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
Pull Request — develop (#1852)
by
unknown
34:15 queued 17:46
created

fileController::procFileOutput()   D

Complexity

Conditions 20
Paths 176

Size

Total Lines 93
Code Lines 55

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 93
rs 4.4507
cc 20
eloc 55
nc 176
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(strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== FALSE || (strpos($_SERVER['HTTP_USER_AGENT'], 'Windows') !== FALSE && strpos($_SERVER['HTTP_USER_AGENT'], 'Trident') !== FALSE && strpos($_SERVER['HTTP_USER_AGENT'], 'rv:') !== FALSE))
312
		{
313
			$filename = rawurlencode($filename);
314
			$filename = preg_replace('/\./', '%2e', $filename, substr_count($filename, '.') - 1);
315
		}
316
317
		if($is_android)
318
		{
319
			if($_SESSION['__XE_FILE_KEY__'][$file_srl]) $_SESSION['__XE_FILE_KEY_AND__'][$file_srl] = $file_key;
320
		}
321
322
		unset($_SESSION[$session_key][$file_srl]);
323
324
		Context::close();
325
326
		$fp = fopen($uploaded_filename, 'rb');
327
		if(!$fp) return $this->stop('msg_file_not_found');
328
329
		header("Cache-Control: ");
330
		header("Pragma: ");
331
		header("Content-Type: application/octet-stream");
332
		header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
333
334
		header('Content-Disposition: attachment; filename="'.$filename.'"');
335
		header("Content-Transfer-Encoding: binary\n");
336
		
337
		if(isset($_SERVER['HTTP_RANGE']))
338
		{
339
			$ranges = array_map('intval', explode('-', substr($_SERVER['HTTP_RANGE'], 6)));
340
341
			if(!$ranges[1])
342
			{
343
				$ranges[1] = $size - 1;
0 ignored issues
show
Bug introduced by
The variable $size does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
344
			}
345
346
			header('HTTP/1.1 206 Partial Content');
347
			header('Accept-Ranges: bytes');
348
			header('Content-Length: ' . ($ranges[1] - $ranges[0]+1));
349
350
			header(sprintf('Content-Range: bytes %d-%d/%d', $ranges[0], $ranges[1], $size));
351
			$chunkSize = 8192;
352
353
			fseek($fp, $ranges[0]);
354
			while(true) {
355
				if(ftell($fp) >= $ranges[1]) {
356
					break;
357
				}
358
				echo fread($fp, $chunkSize);
359
				@ob_flush();
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...
360
				flush();
361
			}
362
		}
363
		else
364
		{
365
			header("Content-Length: " .(string)($file_size));
366
			// if file size is lager than 10MB, use fread function (#18675748)
367
			if($file_size > 1024 * 1024)
368
			{
369
				while(!feof($fp)) echo fread($fp, 1024);
370
				fclose($fp);
371
			}
372
			else
373
			{
374
				fpassthru($fp);
375
			}
376
		}
377
378
		exit();
379
	}
380
381
	/**
382
	 * Delete an attachment from the editor
383
	 *
384
	 * @return Object
385
	 */
386
	function procFileDelete()
387
	{
388
		// Basic variable setting(upload_target_srl and module_srl set)
389
		$editor_sequence = Context::get('editor_sequence');
390
		$file_srl = Context::get('file_srl');
391
		$file_srls = Context::get('file_srls');
392
		if($file_srls) $file_srl = $file_srls;
393
		// Exit a session if there is neither upload permission nor information
394
		if(!$_SESSION['upload_info'][$editor_sequence]->enabled) exit();
395
396
		$upload_target_srl = $_SESSION['upload_info'][$editor_sequence]->upload_target_srl;
397
398
		$logged_info = Context::get('logged_info');
399
		$oFileModel = getModel('file');
400
401
		$srls = explode(',',$file_srl);
402
		if(!count($srls)) return;
403
404
		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...
405
		{
406
			$srl = (int)$srls[$i];
407
			if(!$srl) continue;
408
409
			$args = new stdClass;
410
			$args->file_srl = $srl;
411
			$output = executeQuery('file.getFile', $args);
412
			if(!$output->toBool()) continue;
413
414
			$file_info = $output->data;
415
			if(!$file_info) continue;
416
417
			$file_grant = $oFileModel->getFileGrant($file_info, $logged_info);
418
419
			if(!$file_grant->is_deletable) continue;
420
421
			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...
422
		}
423
	}
424
425
	/**
426
	 * get file list
427
	 *
428
	 * @return Object
429
	 */
430
	function procFileGetList()
431
	{
432
		if(!Context::get('is_logged')) return new Object(-1,'msg_not_permitted');
433
		$fileSrls = Context::get('file_srls');
434
		if($fileSrls) $fileSrlList = explode(',', $fileSrls);
435
436
		global $lang;
437
		if(count($fileSrlList) > 0)
438
		{
439
			$oFileModel = getModel('file');
440
			$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...
441
			if(!is_array($fileList)) $fileList = array($fileList);
442
443
			if(is_array($fileList))
444
			{
445
				foreach($fileList AS $key=>$value)
446
				{
447
					$value->human_file_size = FileHandler::filesize($value->file_size);
448
					if($value->isvalid=='Y') $value->validName = $lang->is_valid;
449
					else $value->validName = $lang->is_stand_by;
450
				}
451
			}
452
		}
453
		else
454
		{
455
			$fileList = array();
456
			$this->setMessage($lang->no_files);
457
		}
458
459
		$this->add('file_list', $fileList);
460
	}
461
	/**
462
	 * A trigger to return numbers of attachments in the upload_target_srl (document_srl)
463
	 *
464
	 * @param object $obj Trigger object
465
	 * @return Object
466
	 */
467 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...
468
	{
469
		$document_srl = $obj->document_srl;
470
		if(!$document_srl) return new Object();
471
		// Get numbers of attachments
472
		$oFileModel = getModel('file');
473
		$obj->uploaded_count = $oFileModel->getFilesCount($document_srl);
474
475
		return new Object();
476
	}
477
478
	/**
479
	 * A trigger to link the attachment with the upload_target_srl (document_srl)
480
	 *
481
	 * @param object $obj Trigger object
482
	 * @return Object
483
	 */
484
	function triggerAttachFiles(&$obj)
485
	{
486
		$document_srl = $obj->document_srl;
487
		if(!$document_srl) return new Object();
488
489
		$output = $this->setFilesValid($document_srl);
490
		if(!$output->toBool()) return $output;
491
492
		return new Object();
493
	}
494
495
	/**
496
	 * A trigger to delete the attachment in the upload_target_srl (document_srl)
497
	 *
498
	 * @param object $obj Trigger object
499
	 * @return Object
500
	 */
501
	function triggerDeleteAttached(&$obj)
502
	{
503
		$document_srl = $obj->document_srl;
504
		if(!$document_srl) return new Object();
505
506
		$output = $this->deleteFiles($document_srl);
507
		return $output;
508
	}
509
510
	/**
511
	 * A trigger to return numbers of attachments in the upload_target_srl (comment_srl)
512
	 *
513
	 * @param object $obj Trigger object
514
	 * @return Object
515
	 */
516 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...
517
	{
518
		$comment_srl = $obj->comment_srl;
519
		if(!$comment_srl) return new Object();
520
		// Get numbers of attachments
521
		$oFileModel = getModel('file');
522
		$obj->uploaded_count = $oFileModel->getFilesCount($comment_srl);
523
524
		return new Object();
525
	}
526
527
	/**
528
	 * A trigger to link the attachment with the upload_target_srl (comment_srl)
529
	 *
530
	 * @param object $obj Trigger object
531
	 * @return Object
532
	 */
533
	function triggerCommentAttachFiles(&$obj)
534
	{
535
		$comment_srl = $obj->comment_srl;
536
		$uploaded_count = $obj->uploaded_count;
537
		if(!$comment_srl || !$uploaded_count) return new Object();
538
539
		$output = $this->setFilesValid($comment_srl);
540
		if(!$output->toBool()) return $output;
541
542
		return new Object();
543
	}
544
545
	/**
546
	 * A trigger to delete the attachment in the upload_target_srl (comment_srl)
547
	 *
548
	 * @param object $obj Trigger object
549
	 * @return Object
550
	 */
551
	function triggerCommentDeleteAttached(&$obj)
552
	{
553
		$comment_srl = $obj->comment_srl;
554
		if(!$comment_srl) return new Object();
555
556
		if($obj->isMoveToTrash) return new Object();
557
558
		$output = $this->deleteFiles($comment_srl);
559
		return $output;
560
	}
561
562
	/**
563
	 * A trigger to delete all the attachements when deleting the module
564
	 *
565
	 * @param object $obj Trigger object
566
	 * @return Object
567
	 */
568
	function triggerDeleteModuleFiles(&$obj)
569
	{
570
		$module_srl = $obj->module_srl;
571
		if(!$module_srl) return new Object();
572
573
		$oFileController = getAdminController('file');
574
		return $oFileController->deleteModuleFiles($module_srl);
575
	}
576
577
	/**
578
	 * Upload enabled
579
	 *
580
	 * @param int $editor_sequence
581
	 * @param int $upload_target_srl
582
	 * @return void
583
	 */
584
	function setUploadInfo($editor_sequence, $upload_target_srl=0)
585
	{
586
		if(!isset($_SESSION['upload_info'][$editor_sequence]))
587
		{
588
			$_SESSION['upload_info'][$editor_sequence] = new stdClass();
589
		}
590
		$_SESSION['upload_info'][$editor_sequence]->enabled = true;
591
		$_SESSION['upload_info'][$editor_sequence]->upload_target_srl = $upload_target_srl;
592
	}
593
594
	/**
595
	 * Set the attachements of the upload_target_srl to be valid
596
	 * By changing its state to valid when a document is inserted, it prevents from being considered as a unnecessary file
597
	 *
598
	 * @param int $upload_target_srl
599
	 * @return Object
600
	 */
601
	function setFilesValid($upload_target_srl)
602
	{
603
		$args = new stdClass();
604
		$args->upload_target_srl = $upload_target_srl;
605
		return executeQuery('file.updateFileValid', $args);
606
	}
607
608
	/**
609
	 * Add an attachement
610
	 *
611
	 * <pre>
612
	 * This method call trigger 'file.insertFile'.
613
	 *
614
	 * Before trigger object contains:
615
	 * - module_srl
616
	 * - upload_target_srl
617
	 *
618
	 * After trigger object contains:
619
	 * - file_srl
620
	 * - upload_target_srl
621
	 * - module_srl
622
	 * - direct_download
623
	 * - source_filename
624
	 * - uploaded_filename
625
	 * - donwload_count
626
	 * - file_size
627
	 * - comment
628
	 * - member_srl
629
	 * - sid
630
	 * </pre>
631
	 *
632
	 * @param object $file_info PHP file information array
633
	 * @param int $module_srl Sequence of module to upload file
634
	 * @param int $upload_target_srl Sequence of target to upload file
635
	 * @param int $download_count Initial download count
636
	 * @param bool $manual_insert If set true, pass validation check
637
	 * @return Object
638
	 */
639
	function insertFile($file_info, $module_srl, $upload_target_srl, $download_count = 0, $manual_insert = false)
640
	{
641
		// Call a trigger (before)
642
		$trigger_obj = new stdClass;
643
		$trigger_obj->module_srl = $module_srl;
644
		$trigger_obj->upload_target_srl = $upload_target_srl;
645
		$output = ModuleHandler::triggerCall('file.insertFile', 'before', $trigger_obj);
646
		if(!$output->toBool()) return $output;
647
648
		// A workaround for Firefox upload bug
649
		if(preg_match('/^=\?UTF-8\?B\?(.+)\?=$/i', $file_info['name'], $match))
650
		{
651
			$file_info['name'] = base64_decode(strtr($match[1], ':', '/'));
652
		}
653
654
		if(!$manual_insert)
655
		{
656
			// Get the file configurations
657
			$logged_info = Context::get('logged_info');
658
			if($logged_info->is_admin != 'Y')
659
			{
660
				$oFileModel = getModel('file');
661
				$config = $oFileModel->getFileConfig($module_srl);
662
663
				// check file type
664
				if(isset($config->allowed_filetypes) && $config->allowed_filetypes !== '*.*')
665
				{
666
					$filetypes = explode(';', $config->allowed_filetypes);
667
					$ext = array();
668
					foreach($filetypes as $item) {
669
						$item = explode('.', $item);
670
						$ext[] = strtolower($item[1]);
671
					}
672
					$uploaded_ext = explode('.', $file_info['name']);
673
					$uploaded_ext = strtolower(array_pop($uploaded_ext));
674
675
					if(!in_array($uploaded_ext, $ext))
676
					{
677
						return $this->stop('msg_not_allowed_filetype');
678
					}
679
				}
680
681
				$allowed_filesize = $config->allowed_filesize * 1024 * 1024;
682
				$allowed_attach_size = $config->allowed_attach_size * 1024 * 1024;
683
				// An error appears if file size exceeds a limit
684
				if($allowed_filesize < filesize($file_info['tmp_name'])) return new Object(-1, 'msg_exceeds_limit_size');
685
				// Get total file size of all attachements (from DB)
686
				$size_args = new stdClass;
687
				$size_args->upload_target_srl = $upload_target_srl;
688
				$output = executeQuery('file.getAttachedFileSize', $size_args);
689
				$attached_size = (int)$output->data->attached_size + filesize($file_info['tmp_name']);
690
				if($attached_size > $allowed_attach_size) return new Object(-1, 'msg_exceeds_limit_size');
691
			}
692
		}
693
694
		// https://github.com/xpressengine/xe-core/issues/1713
695
		$file_info['name'] = preg_replace('/\.(php|phtm|phar|html?|cgi|pl|exe|jsp|asp|inc)/i', '$0-x',$file_info['name']);
696
		$file_info['name'] = removeHackTag($file_info['name']);
697
		$file_info['name'] = str_replace(array('<','>'),array('%3C','%3E'),$file_info['name']);
698
699
		// Get random number generator
700
		$random = new Password();
701
702
		// Set upload path by checking if the attachement is an image or other kinds of file
703
		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']))
704
		{
705
			$path = sprintf("./files/attach/images/%s/%s", $module_srl,getNumberingPath($upload_target_srl,3));
706
707
			// special character to '_'
708
			// change to random file name. because window php bug. window php is not recognize unicode character file name - by cherryfilter
709
			$ext = substr(strrchr($file_info['name'],'.'),1);
710
			//$_filename = preg_replace('/[#$&*?+%"\']/', '_', $file_info['name']);
711
			$_filename = $random->createSecureSalt(32, 'hex').'.'.$ext;
712
			$filename  = $path.$_filename;
713
			$idx = 1;
714 View Code Duplication
			while(file_exists($filename))
715
			{
716
				$filename = $path.preg_replace('/\.([a-z0-9]+)$/i','_'.$idx.'.$1',$_filename);
717
				$idx++;
718
			}
719
			$direct_download = 'Y';
720
		}
721
		else
722
		{
723
			$path = sprintf("./files/attach/binaries/%s/%s", $module_srl, getNumberingPath($upload_target_srl,3));
724
			$filename = $path.$random->createSecureSalt(32, 'hex');
725
			$direct_download = 'N';
726
		}
727
		// Create a directory
728
		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...
729
730
		// Check uploaded file
731
		if(!checkUploadedFile($file_info['tmp_name']))  return new Object(-1,'msg_file_upload_error');
732
733
		// Get random number generator
734
		$random = new Password();
735
		
736
		// Move the file
737
		if($manual_insert)
738
		{
739
			@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...
740
			if(!file_exists($filename))
741
			{
742
				$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...
743
				@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...
744
			}
745
		}
746
		else
747
		{
748
			if(!@move_uploaded_file($file_info['tmp_name'], $filename))
749
			{
750
				$filename = $path.$random->createSecureSalt(32, 'hex').'.'.$ext;
751
				if(!@move_uploaded_file($file_info['tmp_name'], $filename))  return new Object(-1,'msg_file_upload_error');
752
			}
753
		}
754
		// Get member information
755
		$oMemberModel = getModel('member');
756
		$member_srl = $oMemberModel->getLoggedMemberSrl();
757
		// List file information
758
		$args = new stdClass;
759
		$args->file_srl = getNextSequence();
760
		$args->upload_target_srl = $upload_target_srl;
761
		$args->module_srl = $module_srl;
762
		$args->direct_download = $direct_download;
763
		$args->source_filename = $file_info['name'];
764
		$args->uploaded_filename = $filename;
765
		$args->download_count = $download_count;
766
		$args->file_size = @filesize($filename);
767
		$args->comment = NULL;
768
		$args->member_srl = $member_srl;
769
		$args->sid = $random->createSecureSalt(32, 'hex');
770
771
		$output = executeQuery('file.insertFile', $args);
772
		if(!$output->toBool()) return $output;
773
		// Call a trigger (after)
774
		$trigger_output = ModuleHandler::triggerCall('file.insertFile', 'after', $args);
775
		if(!$trigger_output->toBool()) return $trigger_output;
776
777
		$_SESSION['__XE_UPLOADING_FILES_INFO__'][$args->file_srl] = true;
778
779
		$output->add('file_srl', $args->file_srl);
780
		$output->add('file_size', $args->file_size);
781
		$output->add('sid', $args->sid);
782
		$output->add('direct_download', $args->direct_download);
783
		$output->add('source_filename', $args->source_filename);
784
		$output->add('upload_target_srl', $upload_target_srl);
785
		$output->add('uploaded_filename', $args->uploaded_filename);
786
		return $output;
787
	}
788
789
	/**
790
	 * Delete the attachment
791
	 *
792
	 * <pre>
793
	 * This method call trigger 'file.deleteFile'.
794
	 * Before, after trigger object contains:
795
	 * - download_url
796
	 * - file_srl
797
	 * - upload_target_srl
798
	 * - upload_target_type
799
	 * - sid
800
	 * - module_srl
801
	 * - member_srl
802
	 * - download_count
803
	 * - direct_download
804
	 * - source_filename
805
	 * - uploaded_filename
806
	 * - file_size
807
	 * - comment
808
	 * - isvalid
809
	 * - regdate
810
	 * - ipaddress
811
	 * </pre>
812
	 *
813
	 * @param int $file_srl Sequence of file to delete
814
	 * @return Object
815
	 */
816
	function deleteFile($file_srl)
817
	{
818
		if(!$file_srl) return;
819
820
		$srls = (is_array($file_srl)) ? $file_srl : explode(',', $file_srl);
821
		if(!count($srls)) return;
822
823
		$oDocumentController = getController('document');
824
		$documentSrlList = array();
825
826
		foreach($srls as $srl)
827
		{
828
			$srl = (int)$srl;
829
			if(!$srl) 
830
			{
831
				continue;
832
			}
833
834
			$args = new stdClass();
835
			$args->file_srl = $srl;
836
			$output = executeQuery('file.getFile', $args);
837
838
			if(!$output->toBool() || !$output->data) 
839
			{
840
				continue;
841
			}
842
843
			$file_info = $output->data;
844
845
			if($file_info->upload_target_srl)
846
			{
847
				$documentSrlList[] = $file_info->upload_target_srl;
848
			}
849
850
			$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...
851
			$uploaded_filename = $output->data->uploaded_filename;
852
853
			// Call a trigger (before)
854
			$trigger_obj = $output->data;
855
			$output = ModuleHandler::triggerCall('file.deleteFile', 'before', $trigger_obj);
856
			if(!$output->toBool()) return $output;
857
858
			// Remove from the DB
859
			$output = executeQuery('file.deleteFile', $args);
860
			if(!$output->toBool()) return $output;
861
862
			// Call a trigger (after)
863
			$trigger_output = ModuleHandler::triggerCall('file.deleteFile', 'after', $trigger_obj);
864
			if(!$trigger_output->toBool()) return $trigger_output;
865
866
			// If successfully deleted, remove the file
867
			FileHandler::removeFile($uploaded_filename);
868
		}
869
870
		$oDocumentController->updateUploaedCount($documentSrlList);
871
872
		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...
873
	}
874
875
	/**
876
	 * Delete all attachments of a particular document
877
	 *
878
	 * @param int $upload_target_srl Upload target srl to delete files
879
	 * @return Object
880
	 */
881
	function deleteFiles($upload_target_srl)
882
	{
883
		// Get a list of attachements
884
		$oFileModel = getModel('file');
885
		$columnList = array('file_srl', 'uploaded_filename', 'module_srl');
886
		$file_list = $oFileModel->getFiles($upload_target_srl, $columnList);
887
		// Success returned if no attachement exists
888
		if(!is_array($file_list)||!count($file_list)) return new Object();
889
890
		// Delete the file
891
		$path = array();
892
		$file_count = count($file_list);
893 View Code Duplication
		for($i=0;$i<$file_count;$i++)
894
		{
895
			$this->deleteFile($file_list[$i]->file_srl);
896
897
			$uploaded_filename = $file_list[$i]->uploaded_filename;
898
			$path_info = pathinfo($uploaded_filename);
899
			if(!in_array($path_info['dirname'], $path)) $path[] = $path_info['dirname'];
900
		}
901
902
		// Remove from the DB
903
		$args = new stdClass();
904
		$args->upload_target_srl = $upload_target_srl;
905
		$output = executeQuery('file.deleteFiles', $args);
906
		if(!$output->toBool()) return $output;
907
		
908
		// Remove a file directory of the document
909 View Code Duplication
		for($i=0, $c=count($path); $i<$c; $i++)
910
		{
911
			FileHandler::removeBlankDir($path[$i]);
912
		}
913
914
		return $output;
915
	}
916
917
	/**
918
	 * Move an attachement to the other document
919
	 *
920
	 * @param int $source_srl Sequence of target to move
921
	 * @param int $target_module_srl New squence of module
922
	 * @param int $target_srl New sequence of target
923
	 * @return void
924
	 */
925
	function moveFile($source_srl, $target_module_srl, $target_srl)
926
	{
927
		if($source_srl == $target_srl) return;
928
929
		$oFileModel = getModel('file');
930
		$file_list = $oFileModel->getFiles($source_srl);
931
		if(!$file_list) return;
932
933
		$file_count = count($file_list);
934
935
		for($i=0;$i<$file_count;$i++)
936
		{
937
			unset($file_info);
938
			$file_info = $file_list[$i];
939
			$old_file = $file_info->uploaded_filename;
940
			// Determine the file path by checking if the file is an image or other kinds
941
			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))
942
			{
943
				$path = sprintf("./files/attach/images/%s/%s/", $target_module_srl,$target_srl);
944
				$new_file = $path.$file_info->source_filename;
945
			}
946
			else
947
			{
948
				$path = sprintf("./files/attach/binaries/%s/%s/", $target_module_srl, $target_srl);
949
				$random = new Password();
950
				$new_file = $path.$random->createSecureSalt(32, 'hex');
951
			}
952
			// Pass if a target document to move is same
953
			if($old_file == $new_file) continue;
954
			// Create a directory
955
			FileHandler::makeDir($path);
956
			// Move the file
957
			FileHandler::rename($old_file, $new_file);
958
			// Update DB information
959
			$args = new stdClass;
960
			$args->file_srl = $file_info->file_srl;
961
			$args->uploaded_filename = $new_file;
962
			$args->module_srl = $file_info->module_srl;
963
			$args->upload_target_srl = $target_srl;
964
			executeQuery('file.updateFile', $args);
965
		}
966
	}
967
968
	public function procFileSetCoverImage()
969
	{
970
		$vars = Context::getRequestVars();
971
		$logged_info = Context::get('logged_info');
972
973
		if(!$vars->editor_sequence) return new Object(-1, 'msg_invalid_request');
974
975
		$upload_target_srl = $_SESSION['upload_info'][$vars->editor_sequence]->upload_target_srl;
976
977
		$oFileModel = getModel('file');
978
		$file_info = $oFileModel->getFile($vars->file_srl);
979
980
		if(!$file_info) return new Object(-1, 'msg_not_founded');
981
982
		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...
983
984
		$args =  new stdClass();
985
		$args->file_srl = $vars->file_srl;
986
		$args->upload_target_srl = $upload_target_srl;
987
988
		$oDB = &DB::getInstance();
989
		$oDB->begin();
990
991
		$args->cover_image = 'N';
992
		$output = executeQuery('file.updateClearCoverImage', $args);
993
		if(!$output->toBool())
994
		{
995
			$oDB->rollback();
996
			return $output;
997
		}
998
999
		$args->cover_image = 'Y';
1000
		$output = executeQuery('file.updateCoverImage', $args);
1001
		if(!$output->toBool())
1002
		{
1003
			$oDB->rollback();
1004
			return $output;
1005
		}
1006
1007
		$oDB->commit();
1008
1009
		// 썸네일 삭제
1010
		$thumbnail_path = sprintf('files/thumbnails/%s', getNumberingPath($upload_target_srl, 3));
1011
		Filehandler::removeFilesInDir($thumbnail_path);
1012
	}
1013
1014
	/**
1015
	 * Find the attachment where a key is upload_target_srl and then return java script code
1016
	 *
1017
	 * @deprecated
1018
	 * @param int $editor_sequence
1019
	 * @param int $upload_target_srl
1020
	 * @return void
1021
	 */
1022
	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...
1023
	{
1024
		return;
1025
	}
1026
1027 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...
1028
	{
1029
		$oModuleModel = getModel('module');
1030
		$fileConfig = $oModuleModel->getModulePartConfig('file', $obj->originModuleSrl);
1031
1032
		$oModuleController = getController('module');
1033
		if(is_array($obj->moduleSrlList))
1034
		{
1035
			foreach($obj->moduleSrlList AS $key=>$moduleSrl)
1036
			{
1037
				$oModuleController->insertModulePartConfig('file', $moduleSrl, $fileConfig);
1038
			}
1039
		}
1040
	}
1041
}
1042
/* End of file file.controller.php */
1043
/* Location: ./modules/file/file.controller.php */
1044
1045