GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — develop ( 8f7ff8...eb2efa )
by gyeong-won
12:35
created

fileController::procFileOutput()   D

Complexity

Conditions 17
Paths 152

Size

Total Lines 77
Code Lines 44

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 77
rs 4.8278
cc 17
eloc 44
nc 152
nop 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/* Copyright (C) NAVER <http://www.navercorp.com> */
3
/**
4
 * Controller class of the file module
5
 * @author NAVER ([email protected])
6
 */
7
class fileController extends file
8
{
9
	/**
10
	 * Initialization
11
	 * @return void
12
	 */
13
	function init()
14
	{
15
	}
16
17
	/**
18
	 * Upload attachments in the editor
19
	 *
20
	 * Determine the upload target srl from editor_sequence and uploadTargetSrl variables.
21
	 * Create and return the UploadTargetSrl if not exists so that UI can use the value
22
	 * for sync.
23
	 *
24
	 * @return void
25
	 */
26
	function procFileUpload()
27
	{
28
		Context::setRequestMethod('JSON');
29
		$file_info = $_FILES['Filedata'];
30
31
		// An error appears if not a normally uploaded file
32
		if(!is_uploaded_file($file_info['tmp_name'])) exit();
33
34
		// Basic variables setting
35
		$oFileModel = getModel('file');
0 ignored issues
show
Unused Code introduced by
$oFileModel is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
36
		$editor_sequence = Context::get('editor_sequence');
37
		$upload_target_srl = intval(Context::get('uploadTargetSrl'));
38
		if(!$upload_target_srl) $upload_target_srl = intval(Context::get('upload_target_srl'));
39
		$module_srl = $this->module_srl;
0 ignored issues
show
Bug introduced by
The property module_srl cannot be accessed from this context as it is declared private in class ModuleObject.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
40
		// Exit a session if there is neither upload permission nor information
41
		if(!$_SESSION['upload_info'][$editor_sequence]->enabled) exit();
42
		// Extract from session information if upload_target_srl is not specified
43
		if(!$upload_target_srl) $upload_target_srl = $_SESSION['upload_info'][$editor_sequence]->upload_target_srl;
44
		// Create if upload_target_srl is not defined in the session information
45
		if(!$upload_target_srl) $_SESSION['upload_info'][$editor_sequence]->upload_target_srl = $upload_target_srl = getNextSequence();
46
47
		$output = $this->insertFile($file_info, $module_srl, $upload_target_srl);
48
		Context::setResponseMethod('JSON');
49
		if($output->error != '0') $this->stop($output->message);
50
	}
51
52
	/**
53
	 * Iframe upload attachments
54
	 *
55
	 * @return Object
56
	 */
57
	function procFileIframeUpload()
58
	{
59
		// Basic variables setting
60
		$editor_sequence = Context::get('editor_sequence');
61
		$callback = Context::get('callback');
0 ignored issues
show
Unused Code introduced by
$callback is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
62
		$module_srl = $this->module_srl;
0 ignored issues
show
Bug introduced by
The property module_srl cannot be accessed from this context as it is declared private in class ModuleObject.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
63
		$upload_target_srl = intval(Context::get('uploadTargetSrl'));
64
		if(!$upload_target_srl) $upload_target_srl = intval(Context::get('upload_target_srl'));
65
66
		// Exit a session if there is neither upload permission nor information
67
		if(!$_SESSION['upload_info'][$editor_sequence]->enabled) exit();
68
		// Extract from session information if upload_target_srl is not specified
69
		if(!$upload_target_srl) $upload_target_srl = $_SESSION['upload_info'][$editor_sequence]->upload_target_srl;
70
		// Create if upload_target_srl is not defined in the session information
71
		if(!$upload_target_srl) $_SESSION['upload_info'][$editor_sequence]->upload_target_srl = $upload_target_srl = getNextSequence();
72
		// Delete and then attempt to re-upload if file_srl is requested
73
		$file_srl = Context::get('file_srl');
74
		if($file_srl) $this->deleteFile($file_srl);
75
76
		$file_info = Context::get('Filedata');
77
		// An error appears if not a normally uploaded file
78
		if(is_uploaded_file($file_info['tmp_name'])) {
79
			$output = $this->insertFile($file_info, $module_srl, $upload_target_srl);
0 ignored issues
show
Documentation introduced by
$file_info is of type string, but the function expects a object.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
80
			Context::set('uploaded_fileinfo',$output);
0 ignored issues
show
Documentation introduced by
$output is of type object|null, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
81
		}
82
83
		Context::set('layout','none');
84
85
		$this->setTemplatePath($this->module_path.'tpl');
0 ignored issues
show
Bug introduced by
The property module_path cannot be accessed from this context as it is declared private in class ModuleObject.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
86
		$this->setTemplateFile('iframe');
87
	}
88
89
	/**
90
	 * Image resize
91
	 *
92
	 * @return Object
93
	 */
94
	function procFileImageResize()
95
	{
96
		$file_srl = Context::get('file_srl');
97
		$width = Context::get('width');
98
		$height = Context::get('height');
99
100
		if(!$file_srl || !$width)
101
		{
102
			return new Object(-1,'msg_invalid_request');
103
		}
104
105
		$oFileModel = getModel('file');
106
		$fileInfo = $oFileModel->getFile($file_srl);
107
		if(!$fileInfo || $fileInfo->direct_download != 'Y')
108
		{
109
			return new Object(-1,'msg_invalid_request');
110
		}
111
112
		$source_src = $fileInfo->uploaded_filename;
113
		$output_src = $source_src . '.resized' . strrchr($source_src,'.');
114
115
		if(!$height) $height = $width-1;
116
117
		if(FileHandler::createImageFile($source_src,$output_src,$width,$height,'','ratio'))
118
		{
119
			$output = new stdClass();
120
			$output->info = getimagesize($output_src);
121
			$output->src = $output_src;
122
		}
123
		else
124
		{
125
			return new Object(-1,'msg_invalid_request');
126
		}
127
128
		$this->add('resized_info',$output);
129
	}
130
131
	/**
132
	 * Download Attachment
133
	 *
134
	 * <pre>
135
	 * Receive a request directly
136
	 * file_srl: File sequence
137
	 * sid : value in DB for comparison, No download if not matched
138
	 *
139
	 * This method call trigger 'file.downloadFile'.
140
	 * before, after.
141
	 * Trigger object contains:
142
	 * - download_url
143
	 * - file_srl
144
	 * - upload_target_srl
145
	 * - upload_target_type
146
	 * - sid
147
	 * - module_srl
148
	 * - member_srl
149
	 * - download_count
150
	 * - direct_download
151
	 * - source_filename
152
	 * - uploaded_filename
153
	 * - file_size
154
	 * - comment
155
	 * - isvalid
156
	 * - regdate
157
	 * - ipaddress
158
	 * </pre>
159
	 *
160
	 * return void
161
	 */
162
	function procFileDownload()
163
	{
164
		$oFileModel = getModel('file');
165
166
		if(isset($this->grant->access) && $this->grant->access !== true) return new Object(-1, 'msg_not_permitted');
0 ignored issues
show
Bug introduced by
The property grant does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
167
168
		$file_srl = Context::get('file_srl');
169
		$sid = Context::get('sid');
170
		$logged_info = Context::get('logged_info');
171
		// Get file information from the DB
172
		$columnList = array('file_srl', 'sid', 'isvalid', 'source_filename', 'module_srl', 'uploaded_filename', 'file_size', 'member_srl', 'upload_target_srl', 'upload_target_type');
173
		$file_obj = $oFileModel->getFile($file_srl, $columnList);
174
		// If the requested file information is incorrect, an error that file cannot be found appears
175
		if($file_obj->file_srl!=$file_srl || $file_obj->sid!=$sid) return $this->stop('msg_file_not_found');
176
		// Notify that file download is not allowed when standing-by(Only a top-administrator is permitted)
177
		if($logged_info->is_admin != 'Y' && $file_obj->isvalid!='Y') return $this->stop('msg_not_permitted_download');
178
		// File name
179
		$filename = $file_obj->source_filename;
180
		$file_module_config = $oFileModel->getFileModuleConfig($file_obj->module_srl);
181
		// Not allow the file outlink
182
		if($file_module_config->allow_outlink == 'N')
183
		{
184
			// Handles extension to allow outlink
185 View Code Duplication
			if($file_module_config->allow_outlink_format)
186
			{
187
				$allow_outlink_format_array = array();
0 ignored issues
show
Unused Code introduced by
$allow_outlink_format_array is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
188
				$allow_outlink_format_array = explode(',', $file_module_config->allow_outlink_format);
189
				if(!is_array($allow_outlink_format_array)) $allow_outlink_format_array[0] = $file_module_config->allow_outlink_format;
190
191
				foreach($allow_outlink_format_array as $val)
192
				{
193
					$val = trim($val);
194
					if(preg_match("/\.{$val}$/i", $filename))
195
					{
196
						$file_module_config->allow_outlink = 'Y';
197
						break;
198
					}
199
				}
200
			}
201
			// Sites that outlink is allowed
202
			if($file_module_config->allow_outlink != 'Y')
203
			{
204
				$referer = parse_url($_SERVER["HTTP_REFERER"]);
205
				if($referer['host'] != $_SERVER['HTTP_HOST'])
206
				{
207 View Code Duplication
					if($file_module_config->allow_outlink_site)
208
					{
209
						$allow_outlink_site_array = array();
0 ignored issues
show
Unused Code introduced by
$allow_outlink_site_array is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
210
						$allow_outlink_site_array = explode("\n", $file_module_config->allow_outlink_site);
211
						if(!is_array($allow_outlink_site_array)) $allow_outlink_site_array[0] = $file_module_config->allow_outlink_site;
212
213
						foreach($allow_outlink_site_array as $val)
214
						{
215
							$site = parse_url(trim($val));
216
							if($site['host'] == $referer['host'])
217
							{
218
								$file_module_config->allow_outlink = 'Y';
219
								break;
220
							}
221
						}
222
					}
223
				}
224
				else $file_module_config->allow_outlink = 'Y';
225
			}
226
			if($file_module_config->allow_outlink != 'Y') return $this->stop('msg_not_allowed_outlink');
227
		}
228
229
		// Check if a permission for file download is granted
230
		$downloadGrantCount = 0;
231
		if(is_array($file_module_config->download_grant))
232
		{
233
			foreach($file_module_config->download_grant AS $value)
234
				if($value) $downloadGrantCount++;
235
		}
236
237 View Code Duplication
		if(is_array($file_module_config->download_grant) && $downloadGrantCount>0)
238
		{
239
			if(!Context::get('is_logged')) return $this->stop('msg_not_permitted_download');
240
			$logged_info = Context::get('logged_info');
241
			if($logged_info->is_admin != 'Y')
242
			{
243
				$oModuleModel =& getModel('module');
244
				$columnList = array('module_srl', 'site_srl');
245
				$module_info = $oModuleModel->getModuleInfoByModuleSrl($file_obj->module_srl, $columnList);
246
247
				if(!$oModuleModel->isSiteAdmin($logged_info, $module_info->site_srl))
248
				{
249
					$oMemberModel =& getModel('member');
250
					$member_groups = $oMemberModel->getMemberGroups($logged_info->member_srl, $module_info->site_srl);
251
252
					$is_permitted = false;
253
					for($i=0;$i<count($file_module_config->download_grant);$i++)
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
254
					{
255
						$group_srl = $file_module_config->download_grant[$i];
256
						if($member_groups[$group_srl])
257
						{
258
							$is_permitted = true;
259
							break;
260
						}
261
					}
262
					if(!$is_permitted) return $this->stop('msg_not_permitted_download');
263
				}
264
			}
265
		}
266
		// Call a trigger (before)
267
		$output = ModuleHandler::triggerCall('file.downloadFile', 'before', $file_obj);
268
		if(!$output->toBool()) return $this->stop(($output->message)?$output->message:'msg_not_permitted_download');
269
270
271
		// 다운로드 후 (가상)
272
		// Increase download_count
273
		$args = new stdClass();
274
		$args->file_srl = $file_srl;
275
		executeQuery('file.updateFileDownloadCount', $args);
276
		// Call a trigger (after)
277
		$output = ModuleHandler::triggerCall('file.downloadFile', 'after', $file_obj);
0 ignored issues
show
Unused Code introduced by
$output is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
278
279
		$random = new Password();
280
		$file_key = $_SESSION['__XE_FILE_KEY__'][$file_srl] = $random->createSecureSalt(32, 'hex');
281
		header('Location: '.getNotEncodedUrl('', 'act', 'procFileOutput','file_srl',$file_srl,'file_key',$file_key));
282
		Context::close();
283
		exit();
284
285
	}
286
287
	public function procFileOutput()
288
	{
289
		$oFileModel = getModel('file');
290
		$file_srl = Context::get('file_srl');
291
		$file_key = Context::get('file_key');
292
		if(strstr($_SERVER['HTTP_USER_AGENT'], "Android")) $is_android = true;
293
294
		if($is_android && $_SESSION['__XE_FILE_KEY_AND__'][$file_srl]) $session_key = '__XE_FILE_KEY_AND__';
0 ignored issues
show
Bug introduced by
The variable $is_android does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
295
		else $session_key = '__XE_FILE_KEY__';
296
		$columnList = array('source_filename', 'uploaded_filename', 'file_size');
297
		$file_obj = $oFileModel->getFile($file_srl, $columnList);
298
299
		$uploaded_filename = $file_obj->uploaded_filename;
300
301
		if(!file_exists($uploaded_filename)) return $this->stop('msg_file_not_found');
302
303
		if(!$file_key || $_SESSION[$session_key][$file_srl] != $file_key)
304
		{
305
			unset($_SESSION[$session_key][$file_srl]);
306
			return $this->stop('msg_invalid_request');
307
		}
308
309
		$file_size = $file_obj->file_size;
310
		$filename = $file_obj->source_filename;
311
				if(preg_match('#(?:Chrome|Edge)/(\d+)\.#', $_SERVER['HTTP_USER_AGENT'], $matches) && $matches[1] >= 11)
312
		{
313
			$filename_param = "filename*=UTF-8''" . rawurlencode($filename) . '; filename="' . rawurlencode($filename) . '"';
314
		}
315
		elseif(preg_match('#(?:Firefox|Safari|Trident)/(\d+)\.#', $_SERVER['HTTP_USER_AGENT'], $matches) && $matches[1] >= 6)
316
		{
317
			$filename_param = "filename*=UTF-8''" . rawurlencode($filename) . '; filename="' . rawurlencode($filename) . '"';
318
		}
319
		// Filename encoding for browsers that do not support RFC 5987
320
		elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== FALSE)
321
		{
322
			$filename = rawurlencode($filename);
323
			$filename_param = 'filename="' . preg_replace('/\./', '%2e', $filename, substr_count($filename, '.') - 1) . '"';
324
		}
325
		else
326
		{
327
			$filename_param = 'filename="' . $filename . '"';
328
		}
329
330
		if($is_android)
331
		{
332
			if($_SESSION['__XE_FILE_KEY__'][$file_srl]) $_SESSION['__XE_FILE_KEY_AND__'][$file_srl] = $file_key;
333
		}
334
335
		unset($_SESSION[$session_key][$file_srl]);
336
337
		Context::close();
338
339
		$fp = fopen($uploaded_filename, 'rb');
340
		if(!$fp) return $this->stop('msg_file_not_found');
341
342
		header("Cache-Control: ");
343
		header("Pragma: ");
344
		header("Content-Type: application/octet-stream");
345
		header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
346
347
		header("Content-Length: " .(string)($file_size));
348
		header('Content-Disposition: attachment; ' . $filename_param);
349
		header("Content-Transfer-Encoding: binary\n");
350
351
		// if file size is lager than 10MB, use fread function (#18675748)
352
		if(filesize($uploaded_filename) > 1024 * 1024)
353
		{
354
			while(!feof($fp)) echo fread($fp, 1024);
355
			fclose($fp);
356
		}
357
		else
358
		{
359
			fpassthru($fp);
360
		}
361
362
		exit();
363
	}
364
365
	/**
366
	 * Delete an attachment from the editor
367
	 *
368
	 * @return Object
369
	 */
370
	function procFileDelete()
371
	{
372
		// Basic variable setting(upload_target_srl and module_srl set)
373
		$editor_sequence = Context::get('editor_sequence');
374
		$file_srl = Context::get('file_srl');
375
		$file_srls = Context::get('file_srls');
376
		if($file_srls) $file_srl = $file_srls;
377
		// Exit a session if there is neither upload permission nor information
378
		if(!$_SESSION['upload_info'][$editor_sequence]->enabled) exit();
379
380
		$upload_target_srl = $_SESSION['upload_info'][$editor_sequence]->upload_target_srl;
381
382
		$logged_info = Context::get('logged_info');
383
		$oFileModel = getModel('file');
384
385
		$srls = explode(',',$file_srl);
386
		if(!count($srls)) return;
387
388
		for($i=0;$i<count($srls);$i++)
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
389
		{
390
			$srl = (int)$srls[$i];
391
			if(!$srl) continue;
392
393
			$args = new stdClass;
394
			$args->file_srl = $srl;
395
			$output = executeQuery('file.getFile', $args);
396
			if(!$output->toBool()) continue;
397
398
			$file_info = $output->data;
399
			if(!$file_info) continue;
400
401
			$file_grant = $oFileModel->getFileGrant($file_info, $logged_info);
402
403
			if(!$file_grant->is_deletable) continue;
404
405
			if($upload_target_srl && $file_srl) $output = $this->deleteFile($file_srl);
0 ignored issues
show
Unused Code introduced by
$output is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
406
		}
407
	}
408
409
	/**
410
	 * get file list
411
	 *
412
	 * @return Object
413
	 */
414
	function procFileGetList()
415
	{
416
		if(!Context::get('is_logged')) return new Object(-1,'msg_not_permitted');
417
		$fileSrls = Context::get('file_srls');
418
		if($fileSrls) $fileSrlList = explode(',', $fileSrls);
419
420
		global $lang;
421
		if(count($fileSrlList) > 0)
422
		{
423
			$oFileModel = getModel('file');
424
			$fileList = $oFileModel->getFile($fileSrlList);
0 ignored issues
show
Bug introduced by
The variable $fileSrlList does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
425
			if(!is_array($fileList)) $fileList = array($fileList);
426
427
			if(is_array($fileList))
428
			{
429
				foreach($fileList AS $key=>$value)
430
				{
431
					$value->human_file_size = FileHandler::filesize($value->file_size);
432
					if($value->isvalid=='Y') $value->validName = $lang->is_valid;
433
					else $value->validName = $lang->is_stand_by;
434
				}
435
			}
436
		}
437
		else
438
		{
439
			$fileList = array();
440
			$this->setMessage($lang->no_files);
441
		}
442
443
		$this->add('file_list', $fileList);
444
	}
445
	/**
446
	 * A trigger to return numbers of attachments in the upload_target_srl (document_srl)
447
	 *
448
	 * @param object $obj Trigger object
449
	 * @return Object
450
	 */
451 View Code Duplication
	function triggerCheckAttached(&$obj)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
452
	{
453
		$document_srl = $obj->document_srl;
454
		if(!$document_srl) return new Object();
455
		// Get numbers of attachments
456
		$oFileModel = getModel('file');
457
		$obj->uploaded_count = $oFileModel->getFilesCount($document_srl);
458
459
		return new Object();
460
	}
461
462
	/**
463
	 * A trigger to link the attachment with the upload_target_srl (document_srl)
464
	 *
465
	 * @param object $obj Trigger object
466
	 * @return Object
467
	 */
468
	function triggerAttachFiles(&$obj)
469
	{
470
		$document_srl = $obj->document_srl;
471
		if(!$document_srl) return new Object();
472
473
		$output = $this->setFilesValid($document_srl);
474
		if(!$output->toBool()) return $output;
475
476
		return new Object();
477
	}
478
479
	/**
480
	 * A trigger to delete the attachment in the upload_target_srl (document_srl)
481
	 *
482
	 * @param object $obj Trigger object
483
	 * @return Object
484
	 */
485
	function triggerDeleteAttached(&$obj)
486
	{
487
		$document_srl = $obj->document_srl;
488
		if(!$document_srl) return new Object();
489
490
		$output = $this->deleteFiles($document_srl);
491
		return $output;
492
	}
493
494
	/**
495
	 * A trigger to return numbers of attachments in the upload_target_srl (comment_srl)
496
	 *
497
	 * @param object $obj Trigger object
498
	 * @return Object
499
	 */
500 View Code Duplication
	function triggerCommentCheckAttached(&$obj)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
501
	{
502
		$comment_srl = $obj->comment_srl;
503
		if(!$comment_srl) return new Object();
504
		// Get numbers of attachments
505
		$oFileModel = getModel('file');
506
		$obj->uploaded_count = $oFileModel->getFilesCount($comment_srl);
507
508
		return new Object();
509
	}
510
511
	/**
512
	 * A trigger to link the attachment with the upload_target_srl (comment_srl)
513
	 *
514
	 * @param object $obj Trigger object
515
	 * @return Object
516
	 */
517
	function triggerCommentAttachFiles(&$obj)
518
	{
519
		$comment_srl = $obj->comment_srl;
520
		$uploaded_count = $obj->uploaded_count;
521
		if(!$comment_srl || !$uploaded_count) return new Object();
522
523
		$output = $this->setFilesValid($comment_srl);
524
		if(!$output->toBool()) return $output;
525
526
		return new Object();
527
	}
528
529
	/**
530
	 * A trigger to delete the attachment in the upload_target_srl (comment_srl)
531
	 *
532
	 * @param object $obj Trigger object
533
	 * @return Object
534
	 */
535
	function triggerCommentDeleteAttached(&$obj)
536
	{
537
		$comment_srl = $obj->comment_srl;
538
		if(!$comment_srl) return new Object();
539
540
		if($obj->isMoveToTrash) return new Object();
541
542
		$output = $this->deleteFiles($comment_srl);
543
		return $output;
544
	}
545
546
	/**
547
	 * A trigger to delete all the attachements when deleting the module
548
	 *
549
	 * @param object $obj Trigger object
550
	 * @return Object
551
	 */
552
	function triggerDeleteModuleFiles(&$obj)
553
	{
554
		$module_srl = $obj->module_srl;
555
		if(!$module_srl) return new Object();
556
557
		$oFileController = getAdminController('file');
558
		return $oFileController->deleteModuleFiles($module_srl);
559
	}
560
561
	/**
562
	 * Upload enabled
563
	 *
564
	 * @param int $editor_sequence
565
	 * @param int $upload_target_srl
566
	 * @return void
567
	 */
568
	function setUploadInfo($editor_sequence, $upload_target_srl=0)
569
	{
570
		if(!isset($_SESSION['upload_info'][$editor_sequence]))
571
		{
572
			$_SESSION['upload_info'][$editor_sequence] = new stdClass();
573
		}
574
		$_SESSION['upload_info'][$editor_sequence]->enabled = true;
575
		$_SESSION['upload_info'][$editor_sequence]->upload_target_srl = $upload_target_srl;
576
	}
577
578
	/**
579
	 * Set the attachements of the upload_target_srl to be valid
580
	 * By changing its state to valid when a document is inserted, it prevents from being considered as a unnecessary file
581
	 *
582
	 * @param int $upload_target_srl
583
	 * @return Object
584
	 */
585
	function setFilesValid($upload_target_srl)
586
	{
587
		$args = new stdClass();
588
		$args->upload_target_srl = $upload_target_srl;
589
		return executeQuery('file.updateFileValid', $args);
590
	}
591
592
	/**
593
	 * Add an attachement
594
	 *
595
	 * <pre>
596
	 * This method call trigger 'file.insertFile'.
597
	 *
598
	 * Before trigger object contains:
599
	 * - module_srl
600
	 * - upload_target_srl
601
	 *
602
	 * After trigger object contains:
603
	 * - file_srl
604
	 * - upload_target_srl
605
	 * - module_srl
606
	 * - direct_download
607
	 * - source_filename
608
	 * - uploaded_filename
609
	 * - donwload_count
610
	 * - file_size
611
	 * - comment
612
	 * - member_srl
613
	 * - sid
614
	 * </pre>
615
	 *
616
	 * @param object $file_info PHP file information array
617
	 * @param int $module_srl Sequence of module to upload file
618
	 * @param int $upload_target_srl Sequence of target to upload file
619
	 * @param int $download_count Initial download count
620
	 * @param bool $manual_insert If set true, pass validation check
621
	 * @return Object
622
	 */
623
	function insertFile($file_info, $module_srl, $upload_target_srl, $download_count = 0, $manual_insert = false)
624
	{
625
		// Call a trigger (before)
626
		$trigger_obj = new stdClass;
627
		$trigger_obj->module_srl = $module_srl;
628
		$trigger_obj->upload_target_srl = $upload_target_srl;
629
		$output = ModuleHandler::triggerCall('file.insertFile', 'before', $trigger_obj);
630
		if(!$output->toBool()) return $output;
631
632
		// A workaround for Firefox upload bug
633
		if(preg_match('/^=\?UTF-8\?B\?(.+)\?=$/i', $file_info['name'], $match))
634
		{
635
			$file_info['name'] = base64_decode(strtr($match[1], ':', '/'));
636
		}
637
638
		if(!$manual_insert)
639
		{
640
			// Get the file configurations
641
			$logged_info = Context::get('logged_info');
642
			if($logged_info->is_admin != 'Y')
643
			{
644
				$oFileModel = getModel('file');
645
				$config = $oFileModel->getFileConfig($module_srl);
646
647
				// check file type
648
				if(isset($config->allowed_filetypes) && $config->allowed_filetypes !== '*.*')
649
				{
650
					$filetypes = explode(';', $config->allowed_filetypes);
651
					$ext = array();
652
					foreach($filetypes as $item) {
653
						$item = explode('.', $item);
654
						$ext[] = strtolower($item[1]);
655
					}
656
					$uploaded_ext = explode('.', $file_info['name']);
657
					$uploaded_ext = strtolower(array_pop($uploaded_ext));
658
659
					if(!in_array($uploaded_ext, $ext))
660
					{
661
						return $this->stop('msg_not_allowed_filetype');
662
					}
663
				}
664
665
				$allowed_filesize = $config->allowed_filesize * 1024 * 1024;
666
				$allowed_attach_size = $config->allowed_attach_size * 1024 * 1024;
667
				// An error appears if file size exceeds a limit
668
				if($allowed_filesize < filesize($file_info['tmp_name'])) return new Object(-1, 'msg_exceeds_limit_size');
669
				// Get total file size of all attachements (from DB)
670
				$size_args = new stdClass;
671
				$size_args->upload_target_srl = $upload_target_srl;
672
				$output = executeQuery('file.getAttachedFileSize', $size_args);
673
				$attached_size = (int)$output->data->attached_size + filesize($file_info['tmp_name']);
674
				if($attached_size > $allowed_attach_size) return new Object(-1, 'msg_exceeds_limit_size');
675
			}
676
		}
677
678
		// https://github.com/xpressengine/xe-core/issues/1713
679
		$file_info['name'] = preg_replace('/\.(php|phtm|phar|html?|cgi|pl|exe|jsp|asp|inc)/i', '$0-x',$file_info['name']);
680
		$file_info['name'] = removeHackTag($file_info['name']);
681
		$file_info['name'] = str_replace(array('<','>'),array('%3C','%3E'),$file_info['name']);
682
683
		// Get random number generator
684
		$random = new Password();
685
686
		// Set upload path by checking if the attachement is an image or other kinds of file
687
		if(preg_match("/\.(jpe?g|gif|png|wm[va]|mpe?g|avi|swf|flv|mp[1-4]|as[fx]|wav|midi?|moo?v|qt|r[am]{1,2}|m4v)$/i", $file_info['name']))
688
		{
689
			$path = sprintf("./files/attach/images/%s/%s", $module_srl,getNumberingPath($upload_target_srl,3));
690
691
			// special character to '_'
692
			// change to random file name. because window php bug. window php is not recognize unicode character file name - by cherryfilter
693
			$ext = substr(strrchr($file_info['name'],'.'),1);
694
			//$_filename = preg_replace('/[#$&*?+%"\']/', '_', $file_info['name']);
695
			$_filename = $random->createSecureSalt(32, 'hex').'.'.$ext;
696
			$filename  = $path.$_filename;
697
			$idx = 1;
698 View Code Duplication
			while(file_exists($filename))
699
			{
700
				$filename = $path.preg_replace('/\.([a-z0-9]+)$/i','_'.$idx.'.$1',$_filename);
701
				$idx++;
702
			}
703
			$direct_download = 'Y';
704
		}
705
		else
706
		{
707
			$path = sprintf("./files/attach/binaries/%s/%s", $module_srl, getNumberingPath($upload_target_srl,3));
708
			$filename = $path.$random->createSecureSalt(32, 'hex');
709
			$direct_download = 'N';
710
		}
711
		// Create a directory
712
		if(!FileHandler::makeDir($path)) return new Object(-1,'msg_not_permitted_create');
0 ignored issues
show
Bug Best Practice introduced by
The expression \FileHandler::makeDir($path) of type boolean|null is loosely compared to false; this is ambiguous if the boolean can be false. You might want to explicitly use !== null instead.

If an expression can have both false, and null as possible values. It is generally a good practice to always use strict comparison to clearly distinguish between those two values.

$a = canBeFalseAndNull();

// Instead of
if ( ! $a) { }

// Better use one of the explicit versions:
if ($a !== null) { }
if ($a !== false) { }
if ($a !== null && $a !== false) { }
Loading history...
713
714
		// Check uploaded file
715
		if(!checkUploadedFile($file_info['tmp_name']))  return new Object(-1,'msg_file_upload_error');
716
717
		// Get random number generator
718
		$random = new Password();
719
		
720
		// Move the file
721
		if($manual_insert)
722
		{
723
			@copy($file_info['tmp_name'], $filename);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
724
			if(!file_exists($filename))
725
			{
726
				$filename = $path.$random->createSecureSalt(32, 'hex').'.'.$ext;
0 ignored issues
show
Bug introduced by
The variable $ext does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
727
				@copy($file_info['tmp_name'], $filename);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
728
			}
729
		}
730
		else
731
		{
732
			if(!@move_uploaded_file($file_info['tmp_name'], $filename))
733
			{
734
				$filename = $path.$random->createSecureSalt(32, 'hex').'.'.$ext;
735
				if(!@move_uploaded_file($file_info['tmp_name'], $filename))  return new Object(-1,'msg_file_upload_error');
736
			}
737
		}
738
		// Get member information
739
		$oMemberModel = getModel('member');
740
		$member_srl = $oMemberModel->getLoggedMemberSrl();
741
		// List file information
742
		$args = new stdClass;
743
		$args->file_srl = getNextSequence();
744
		$args->upload_target_srl = $upload_target_srl;
745
		$args->module_srl = $module_srl;
746
		$args->direct_download = $direct_download;
747
		$args->source_filename = $file_info['name'];
748
		$args->uploaded_filename = $filename;
749
		$args->download_count = $download_count;
750
		$args->file_size = @filesize($filename);
751
		$args->comment = NULL;
752
		$args->member_srl = $member_srl;
753
		$args->sid = $random->createSecureSalt(32, 'hex');
754
755
		$output = executeQuery('file.insertFile', $args);
756
		if(!$output->toBool()) return $output;
757
		// Call a trigger (after)
758
		$trigger_output = ModuleHandler::triggerCall('file.insertFile', 'after', $args);
759
		if(!$trigger_output->toBool()) return $trigger_output;
760
761
		$_SESSION['__XE_UPLOADING_FILES_INFO__'][$args->file_srl] = true;
762
763
		$output->add('file_srl', $args->file_srl);
764
		$output->add('file_size', $args->file_size);
765
		$output->add('sid', $args->sid);
766
		$output->add('direct_download', $args->direct_download);
767
		$output->add('source_filename', $args->source_filename);
768
		$output->add('upload_target_srl', $upload_target_srl);
769
		$output->add('uploaded_filename', $args->uploaded_filename);
770
		return $output;
771
	}
772
773
	/**
774
	 * Delete the attachment
775
	 *
776
	 * <pre>
777
	 * This method call trigger 'file.deleteFile'.
778
	 * Before, after trigger object contains:
779
	 * - download_url
780
	 * - file_srl
781
	 * - upload_target_srl
782
	 * - upload_target_type
783
	 * - sid
784
	 * - module_srl
785
	 * - member_srl
786
	 * - download_count
787
	 * - direct_download
788
	 * - source_filename
789
	 * - uploaded_filename
790
	 * - file_size
791
	 * - comment
792
	 * - isvalid
793
	 * - regdate
794
	 * - ipaddress
795
	 * </pre>
796
	 *
797
	 * @param int $file_srl Sequence of file to delete
798
	 * @return Object
799
	 */
800
	function deleteFile($file_srl)
801
	{
802
		if(!$file_srl) return;
803
804
		$srls = (is_array($file_srl)) ? $file_srl : explode(',', $file_srl);
805
		if(!count($srls)) return;
806
807
		$oDocumentController = getController('document');
808
		$documentSrlList = array();
809
810
		foreach($srls as $srl)
811
		{
812
			$srl = (int)$srl;
813
			if(!$srl) 
814
			{
815
				continue;
816
			}
817
818
			$args = new stdClass();
819
			$args->file_srl = $srl;
820
			$output = executeQuery('file.getFile', $args);
821
822
			if(!$output->toBool() || !$output->data) 
823
			{
824
				continue;
825
			}
826
827
			$file_info = $output->data;
828
829
			if($file_info->upload_target_srl)
830
			{
831
				$documentSrlList[] = $file_info->upload_target_srl;
832
			}
833
834
			$source_filename = $output->data->source_filename;
0 ignored issues
show
Unused Code introduced by
$source_filename is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
835
			$uploaded_filename = $output->data->uploaded_filename;
836
837
			// Call a trigger (before)
838
			$trigger_obj = $output->data;
839
			$output = ModuleHandler::triggerCall('file.deleteFile', 'before', $trigger_obj);
840
			if(!$output->toBool()) return $output;
841
842
			// Remove from the DB
843
			$output = executeQuery('file.deleteFile', $args);
844
			if(!$output->toBool()) return $output;
845
846
			// Call a trigger (after)
847
			$trigger_output = ModuleHandler::triggerCall('file.deleteFile', 'after', $trigger_obj);
848
			if(!$trigger_output->toBool()) return $trigger_output;
849
850
			// If successfully deleted, remove the file
851
			FileHandler::removeFile($uploaded_filename);
852
		}
853
854
		$oDocumentController->updateUploaedCount($documentSrlList);
855
856
		return $output;
0 ignored issues
show
Bug introduced by
The variable $output does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
857
	}
858
859
	/**
860
	 * Delete all attachments of a particular document
861
	 *
862
	 * @param int $upload_target_srl Upload target srl to delete files
863
	 * @return Object
864
	 */
865
	function deleteFiles($upload_target_srl)
866
	{
867
		// Get a list of attachements
868
		$oFileModel = getModel('file');
869
		$columnList = array('file_srl', 'uploaded_filename', 'module_srl');
870
		$file_list = $oFileModel->getFiles($upload_target_srl, $columnList);
871
		// Success returned if no attachement exists
872
		if(!is_array($file_list)||!count($file_list)) return new Object();
873
874
		// Delete the file
875
		$path = array();
876
		$file_count = count($file_list);
877 View Code Duplication
		for($i=0;$i<$file_count;$i++)
878
		{
879
			$this->deleteFile($file_list[$i]->file_srl);
880
881
			$uploaded_filename = $file_list[$i]->uploaded_filename;
882
			$path_info = pathinfo($uploaded_filename);
883
			if(!in_array($path_info['dirname'], $path)) $path[] = $path_info['dirname'];
884
		}
885
886
		// Remove from the DB
887
		$args = new stdClass();
888
		$args->upload_target_srl = $upload_target_srl;
889
		$output = executeQuery('file.deleteFiles', $args);
890
		if(!$output->toBool()) return $output;
891
		
892
		// Remove a file directory of the document
893 View Code Duplication
		for($i=0, $c=count($path); $i<$c; $i++)
894
		{
895
			FileHandler::removeBlankDir($path[$i]);
896
		}
897
898
		return $output;
899
	}
900
901
	/**
902
	 * Move an attachement to the other document
903
	 *
904
	 * @param int $source_srl Sequence of target to move
905
	 * @param int $target_module_srl New squence of module
906
	 * @param int $target_srl New sequence of target
907
	 * @return void
908
	 */
909
	function moveFile($source_srl, $target_module_srl, $target_srl)
910
	{
911
		if($source_srl == $target_srl) return;
912
913
		$oFileModel = getModel('file');
914
		$file_list = $oFileModel->getFiles($source_srl);
915
		if(!$file_list) return;
916
917
		$file_count = count($file_list);
918
919
		for($i=0;$i<$file_count;$i++)
920
		{
921
			unset($file_info);
922
			$file_info = $file_list[$i];
923
			$old_file = $file_info->uploaded_filename;
924
			// Determine the file path by checking if the file is an image or other kinds
925
			if(preg_match("/\.(jpg|jpeg|gif|png|wmv|wma|mpg|mpeg|avi|swf|flv|mp1|mp2|mp3|mp4|asf|wav|asx|mid|midi|asf|mov|moov|qt|rm|ram|ra|rmm|m4v)$/i", $file_info->source_filename))
926
			{
927
				$path = sprintf("./files/attach/images/%s/%s/", $target_module_srl,$target_srl);
928
				$new_file = $path.$file_info->source_filename;
929
			}
930
			else
931
			{
932
				$path = sprintf("./files/attach/binaries/%s/%s/", $target_module_srl, $target_srl);
933
				$random = new Password();
934
				$new_file = $path.$random->createSecureSalt(32, 'hex');
935
			}
936
			// Pass if a target document to move is same
937
			if($old_file == $new_file) continue;
938
			// Create a directory
939
			FileHandler::makeDir($path);
940
			// Move the file
941
			FileHandler::rename($old_file, $new_file);
942
			// Update DB information
943
			$args = new stdClass;
944
			$args->file_srl = $file_info->file_srl;
945
			$args->uploaded_filename = $new_file;
946
			$args->module_srl = $file_info->module_srl;
947
			$args->upload_target_srl = $target_srl;
948
			executeQuery('file.updateFile', $args);
949
		}
950
	}
951
952
	public function procFileSetCoverImage()
953
	{
954
		$vars = Context::getRequestVars();
955
		$logged_info = Context::get('logged_info');
956
957
		if(!$vars->editor_sequence) return new Object(-1, 'msg_invalid_request');
958
959
		$upload_target_srl = $_SESSION['upload_info'][$vars->editor_sequence]->upload_target_srl;
960
961
		$oFileModel = getModel('file');
962
		$file_info = $oFileModel->getFile($vars->file_srl);
963
964
		if(!$file_info) return new Object(-1, 'msg_not_founded');
965
966
		if(!$this->manager && !$file_info->member_srl === $logged_info->member_srl) return new Object(-1, 'msg_not_permitted');
0 ignored issues
show
Bug introduced by
The property manager does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
967
968
		$args =  new stdClass();
969
		$args->file_srl = $vars->file_srl;
970
		$args->upload_target_srl = $upload_target_srl;
971
972
		$oDB = &DB::getInstance();
973
		$oDB->begin();
974
975
		$args->cover_image = 'N';
976
		$output = executeQuery('file.updateClearCoverImage', $args);
977
		if(!$output->toBool())
978
		{
979
			$oDB->rollback();
980
			return $output;
981
		}
982
983
		$args->cover_image = 'Y';
984
		$output = executeQuery('file.updateCoverImage', $args);
985
		if(!$output->toBool())
986
		{
987
			$oDB->rollback();
988
			return $output;
989
		}
990
991
		$oDB->commit();
992
993
		// 썸네일 삭제
994
		$thumbnail_path = sprintf('files/thumbnails/%s', getNumberingPath($upload_target_srl, 3));
995
		Filehandler::removeFilesInDir($thumbnail_path);
996
	}
997
998
	/**
999
	 * Find the attachment where a key is upload_target_srl and then return java script code
1000
	 *
1001
	 * @deprecated
1002
	 * @param int $editor_sequence
1003
	 * @param int $upload_target_srl
1004
	 * @return void
1005
	 */
1006
	function printUploadedFileList($editor_sequence, $upload_target_srl)
0 ignored issues
show
Unused Code introduced by
The parameter $editor_sequence is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $upload_target_srl is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
1007
	{
1008
		return;
1009
	}
1010
1011 View Code Duplication
	function triggerCopyModule(&$obj)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1012
	{
1013
		$oModuleModel = getModel('module');
1014
		$fileConfig = $oModuleModel->getModulePartConfig('file', $obj->originModuleSrl);
1015
1016
		$oModuleController = getController('module');
1017
		if(is_array($obj->moduleSrlList))
1018
		{
1019
			foreach($obj->moduleSrlList AS $key=>$moduleSrl)
1020
			{
1021
				$oModuleController->insertModulePartConfig('file', $moduleSrl, $fileConfig);
1022
			}
1023
		}
1024
	}
1025
}
1026
/* End of file file.controller.php */
1027
/* Location: ./modules/file/file.controller.php */
1028
1029