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 ( 4736fe...9ef204 )
by gyeong-won
13:54
created

fileController::procFileGetList()   D

Complexity

Conditions 10
Paths 12

Size

Total Lines 40
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
eloc 22
nc 12
nop 0
dl 0
loc 40
rs 4.8196
c 0
b 0
f 0

How to fix   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;
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;
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
73
		// Delete and then attempt to re-upload if file_srl is requested
74
		$file_srl = Context::get('file_srl');
75
		if($file_srl)
76
		{
77
			$oFileModel = getModel('file');
78
			$logged_info = Context::get('logged_info');
79
			$file_info = $oFileModel->getFile($file_srl);
80
			$file_grant = $oFileModel->getFileGrant($file_info, $logged_info);
81
			if($file_info->file_srl == $file_srl && $file_grant->is_deletable)
82
			{
83
				$this->deleteFile($file_srl);
84
			}
85
		}
86
87
		$file_info = Context::get('Filedata');
88
		// An error appears if not a normally uploaded file
89
		if(is_uploaded_file($file_info['tmp_name'])) {
90
			$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...
91
			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...
92
		}
93
94
		Context::set('layout','none');
95
96
		$this->setTemplatePath($this->module_path.'tpl');
97
		$this->setTemplateFile('iframe');
98
	}
99
100
	/**
101
	 * Image resize
102
	 *
103
	 * @return Object
104
	 */
105
	function procFileImageResize()
106
	{
107
		$file_srl = Context::get('file_srl');
108
		$width = Context::get('width');
109
		$height = Context::get('height');
110
111
		if(!$file_srl || !$width)
112
		{
113
			return new Object(-1,'msg_invalid_request');
114
		}
115
116
		$oFileModel = getModel('file');
117
		$fileInfo = $oFileModel->getFile($file_srl);
118
		if(!$fileInfo || $fileInfo->direct_download != 'Y')
119
		{
120
			return new Object(-1,'msg_invalid_request');
121
		}
122
123
		$source_src = $fileInfo->uploaded_filename;
124
		$output_src = $source_src . '.resized' . strrchr($source_src,'.');
125
126
		if(!$height) $height = $width-1;
127
128
		if(FileHandler::createImageFile($source_src,$output_src,$width,$height,'','ratio'))
129
		{
130
			$output = new stdClass();
131
			$output->info = getimagesize($output_src);
132
			$output->src = $output_src;
133
		}
134
		else
135
		{
136
			return new Object(-1,'msg_invalid_request');
137
		}
138
139
		$this->add('resized_info',$output);
140
	}
141
142
	/**
143
	 * Download Attachment
144
	 *
145
	 * <pre>
146
	 * Receive a request directly
147
	 * file_srl: File sequence
148
	 * sid : value in DB for comparison, No download if not matched
149
	 *
150
	 * This method call trigger 'file.downloadFile'.
151
	 * before, after.
152
	 * Trigger object contains:
153
	 * - download_url
154
	 * - file_srl
155
	 * - upload_target_srl
156
	 * - upload_target_type
157
	 * - sid
158
	 * - module_srl
159
	 * - member_srl
160
	 * - download_count
161
	 * - direct_download
162
	 * - source_filename
163
	 * - uploaded_filename
164
	 * - file_size
165
	 * - comment
166
	 * - isvalid
167
	 * - regdate
168
	 * - ipaddress
169
	 * </pre>
170
	 *
171
	 * return void
172
	 */
173
	function procFileDownload()
174
	{
175
		$oFileModel = getModel('file');
176
177
		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...
178
179
		$file_srl = Context::get('file_srl');
180
		$sid = Context::get('sid');
181
		$logged_info = Context::get('logged_info');
182
		// Get file information from the DB
183
		$columnList = array('file_srl', 'sid', 'isvalid', 'source_filename', 'module_srl', 'uploaded_filename', 'file_size', 'member_srl', 'upload_target_srl', 'upload_target_type');
184
		$file_obj = $oFileModel->getFile($file_srl, $columnList);
185
		// If the requested file information is incorrect, an error that file cannot be found appears
186
		if($file_obj->file_srl!=$file_srl || $file_obj->sid!=$sid) return $this->stop('msg_file_not_found');
187
		// Notify that file download is not allowed when standing-by(Only a top-administrator is permitted)
188
		if($logged_info->is_admin != 'Y' && $file_obj->isvalid!='Y') return $this->stop('msg_not_permitted_download');
189
		// File name
190
		$filename = $file_obj->source_filename;
191
		$file_module_config = $oFileModel->getFileModuleConfig($file_obj->module_srl);
192
		// Not allow the file outlink
193
		if($file_module_config->allow_outlink == 'N')
194
		{
195
			// Handles extension to allow outlink
196 View Code Duplication
			if($file_module_config->allow_outlink_format)
197
			{
198
				$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...
199
				$allow_outlink_format_array = explode(',', $file_module_config->allow_outlink_format);
200
				if(!is_array($allow_outlink_format_array)) $allow_outlink_format_array[0] = $file_module_config->allow_outlink_format;
201
202
				foreach($allow_outlink_format_array as $val)
203
				{
204
					$val = trim($val);
205
					if(preg_match("/\.{$val}$/i", $filename))
206
					{
207
						$file_module_config->allow_outlink = 'Y';
208
						break;
209
					}
210
				}
211
			}
212
			// Sites that outlink is allowed
213
			if($file_module_config->allow_outlink != 'Y')
214
			{
215
				$referer = parse_url($_SERVER["HTTP_REFERER"]);
216
				if($referer['host'] != $_SERVER['HTTP_HOST'])
217
				{
218 View Code Duplication
					if($file_module_config->allow_outlink_site)
219
					{
220
						$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...
221
						$allow_outlink_site_array = explode("\n", $file_module_config->allow_outlink_site);
222
						if(!is_array($allow_outlink_site_array)) $allow_outlink_site_array[0] = $file_module_config->allow_outlink_site;
223
224
						foreach($allow_outlink_site_array as $val)
225
						{
226
							$site = parse_url(trim($val));
227
							if($site['host'] == $referer['host'])
228
							{
229
								$file_module_config->allow_outlink = 'Y';
230
								break;
231
							}
232
						}
233
					}
234
				}
235
				else $file_module_config->allow_outlink = 'Y';
236
			}
237
			if($file_module_config->allow_outlink != 'Y') return $this->stop('msg_not_allowed_outlink');
238
		}
239
240
		// Check if a permission for file download is granted
241
		$downloadGrantCount = 0;
242
		if(is_array($file_module_config->download_grant))
243
		{
244
			foreach($file_module_config->download_grant AS $value)
245
				if($value) $downloadGrantCount++;
246
		}
247
248 View Code Duplication
		if(is_array($file_module_config->download_grant) && $downloadGrantCount>0)
249
		{
250
			if(!Context::get('is_logged')) return $this->stop('msg_not_permitted_download');
251
			$logged_info = Context::get('logged_info');
252
			if($logged_info->is_admin != 'Y')
253
			{
254
				$oModuleModel =& getModel('module');
255
				$columnList = array('module_srl', 'site_srl');
256
				$module_info = $oModuleModel->getModuleInfoByModuleSrl($file_obj->module_srl, $columnList);
257
258
				if(!$oModuleModel->isSiteAdmin($logged_info, $module_info->site_srl))
259
				{
260
					$oMemberModel =& getModel('member');
261
					$member_groups = $oMemberModel->getMemberGroups($logged_info->member_srl, $module_info->site_srl);
262
263
					$is_permitted = false;
264
					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...
265
					{
266
						$group_srl = $file_module_config->download_grant[$i];
267
						if($member_groups[$group_srl])
268
						{
269
							$is_permitted = true;
270
							break;
271
						}
272
					}
273
					if(!$is_permitted) return $this->stop('msg_not_permitted_download');
274
				}
275
			}
276
		}
277
		// Call a trigger (before)
278
		$output = ModuleHandler::triggerCall('file.downloadFile', 'before', $file_obj);
279
		if(!$output->toBool()) return $this->stop(($output->message)?$output->message:'msg_not_permitted_download');
280
281
282
		// 다운로드 후 (가상)
283
		// Increase download_count
284
		$args = new stdClass();
285
		$args->file_srl = $file_srl;
286
		executeQuery('file.updateFileDownloadCount', $args);
287
		// Call a trigger (after)
288
		$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...
289
290
		$random = new Password();
291
		$file_key = $_SESSION['__XE_FILE_KEY__'][$file_srl] = $random->createSecureSalt(32, 'hex');
292
		header('Location: '.getNotEncodedUrl('', 'act', 'procFileOutput','file_srl',$file_srl,'file_key',$file_key));
293
		Context::close();
294
		exit();
295
296
	}
297
298
	public function procFileOutput()
299
	{
300
		$oFileModel = getModel('file');
301
		$file_srl = Context::get('file_srl');
302
		$file_key = Context::get('file_key');
303
		if(strstr($_SERVER['HTTP_USER_AGENT'], "Android")) $is_android = true;
304
305
		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...
306
		else $session_key = '__XE_FILE_KEY__';
307
		$columnList = array('source_filename', 'uploaded_filename', 'file_size');
308
		$file_obj = $oFileModel->getFile($file_srl, $columnList);
309
310
		$uploaded_filename = $file_obj->uploaded_filename;
311
312
		if(!file_exists($uploaded_filename)) return $this->stop('msg_file_not_found');
313
314
		if(!$file_key || $_SESSION[$session_key][$file_srl] != $file_key)
315
		{
316
			unset($_SESSION[$session_key][$file_srl]);
317
			return $this->stop('msg_invalid_request');
318
		}
319
320
		$file_size = $file_obj->file_size;
321
		$filename = $file_obj->source_filename;
322
		
323
		if(preg_match('#(?:Chrome|Edge)/(\d+)\.#', $_SERVER['HTTP_USER_AGENT'], $matches) && $matches[1] >= 11)
324
		{
325
			if($is_android && preg_match('#\bwv\b|(?:Version|Browser)/\d+#', $_SERVER['HTTP_USER_AGENT']))
326
			{
327
				$filename_param = 'filename="' . $filename . '"';
328
			}
329
			else
330
			{
331
				$filename_param = "filename*=UTF-8''" . rawurlencode($filename) . '; filename="' . rawurlencode($filename) . '"';
332
			}
333
		}
334
		elseif(preg_match('#(?:Firefox|Safari|Trident)/(\d+)\.#', $_SERVER['HTTP_USER_AGENT'], $matches) && $matches[1] >= 6)
335
		{
336
			$filename_param = "filename*=UTF-8''" . rawurlencode($filename) . '; filename="' . rawurlencode($filename) . '"';
337
		}
338
		elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== FALSE)
339
		{
340
			$filename = rawurlencode($filename);
341
			$filename_param = 'filename="' . preg_replace('/\./', '%2e', $filename, substr_count($filename, '.') - 1) . '"';
342
		}
343
		else
344
		{
345
			$filename_param = 'filename="' . $filename . '"';
346
		}
347
348
		if($is_android)
349
		{
350
			if($_SESSION['__XE_FILE_KEY__'][$file_srl]) $_SESSION['__XE_FILE_KEY_AND__'][$file_srl] = $file_key;
351
		}
352
353
		unset($_SESSION[$session_key][$file_srl]);
354
355
		Context::close();
356
357
		$fp = fopen($uploaded_filename, 'rb');
358
		if(!$fp) return $this->stop('msg_file_not_found');
359
360
		header("Cache-Control: ");
361
		header("Pragma: ");
362
		header("Content-Type: application/octet-stream");
363
		header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
364
365
		header("Content-Length: " .(string)($file_size));
366
		header('Content-Disposition: attachment; ' . $filename_param);
367
		header("Content-Transfer-Encoding: binary\n");
368
369
		// if file size is lager than 10MB, use fread function (#18675748)
370
		if(filesize($uploaded_filename) > 1024 * 1024)
371
		{
372
			while(!feof($fp)) echo fread($fp, 1024);
373
			fclose($fp);
374
		}
375
		else
376
		{
377
			fpassthru($fp);
378
		}
379
380
		exit();
381
	}
382
383
	/**
384
	 * Delete an attachment from the editor
385
	 *
386
	 * @return Object
387
	 */
388
	function procFileDelete()
389
	{
390
		// Basic variable setting(upload_target_srl and module_srl set)
391
		$editor_sequence = Context::get('editor_sequence');
392
		$file_srl = Context::get('file_srl');
393
		$file_srls = Context::get('file_srls');
394
		if($file_srls) $file_srl = $file_srls;
395
		// Exit a session if there is neither upload permission nor information
396
		if(!$_SESSION['upload_info'][$editor_sequence]->enabled) exit();
397
398
		$upload_target_srl = $_SESSION['upload_info'][$editor_sequence]->upload_target_srl;
399
400
		$logged_info = Context::get('logged_info');
401
		$oFileModel = getModel('file');
402
403
		$srls = explode(',',$file_srl);
404
		if(!count($srls)) return;
405
406
		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...
407
		{
408
			$srl = (int)$srls[$i];
409
			if(!$srl) continue;
410
411
			$args = new stdClass;
412
			$args->file_srl = $srl;
413
			$output = executeQuery('file.getFile', $args);
414
			if(!$output->toBool()) continue;
415
416
			$file_info = $output->data;
417
			if(!$file_info) continue;
418
419
			$file_grant = $oFileModel->getFileGrant($file_info, $logged_info);
420
421
			if(!$file_grant->is_deletable) continue;
422
423
			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...
424
		}
425
	}
426
427
	/**
428
	 * get file list
429
	 *
430
	 * @return Object
431
	 */
432
	function procFileGetList()
433
	{
434
		if(!Context::get('is_logged')) return new Object(-1,'msg_not_permitted');
435
436
		$oModuleModel = getModel('module');
437
438
		$logged_info = Context::get('logged_info');
439
		if($logged_info->is_admin !== 'Y' && !$oModuleModel->isSiteAdmin($logged_info))
440
		{
441
			return new Object(-1, 'msg_not_permitted');
442
		}
443
444
		$fileSrls = Context::get('file_srls');
445
		if($fileSrls) $fileSrlList = explode(',', $fileSrls);
446
447
		global $lang;
448
		if(count($fileSrlList) > 0)
449
		{
450
			$oFileModel = getModel('file');
451
			$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...
452
			if(!is_array($fileList)) $fileList = array($fileList);
453
454
			if(is_array($fileList))
455
			{
456
				foreach($fileList AS $key=>$value)
457
				{
458
					$value->human_file_size = FileHandler::filesize($value->file_size);
459
					if($value->isvalid=='Y') $value->validName = $lang->is_valid;
460
					else $value->validName = $lang->is_stand_by;
461
				}
462
			}
463
		}
464
		else
465
		{
466
			$fileList = array();
467
			$this->setMessage($lang->no_files);
468
		}
469
470
		$this->add('file_list', $fileList);
471
	}
472
	/**
473
	 * A trigger to return numbers of attachments in the upload_target_srl (document_srl)
474
	 *
475
	 * @param object $obj Trigger object
476
	 * @return Object
477
	 */
478 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...
479
	{
480
		$document_srl = $obj->document_srl;
481
		if(!$document_srl) return new Object();
482
		// Get numbers of attachments
483
		$oFileModel = getModel('file');
484
		$obj->uploaded_count = $oFileModel->getFilesCount($document_srl);
485
486
		return new Object();
487
	}
488
489
	/**
490
	 * A trigger to link the attachment with the upload_target_srl (document_srl)
491
	 *
492
	 * @param object $obj Trigger object
493
	 * @return Object
494
	 */
495
	function triggerAttachFiles(&$obj)
496
	{
497
		$document_srl = $obj->document_srl;
498
		if(!$document_srl) return new Object();
499
500
		$output = $this->setFilesValid($document_srl);
501
		if(!$output->toBool()) return $output;
502
503
		return new Object();
504
	}
505
506
	/**
507
	 * A trigger to delete the attachment in the upload_target_srl (document_srl)
508
	 *
509
	 * @param object $obj Trigger object
510
	 * @return Object
511
	 */
512
	function triggerDeleteAttached(&$obj)
513
	{
514
		$document_srl = $obj->document_srl;
515
		if(!$document_srl) return new Object();
516
517
		$output = $this->deleteFiles($document_srl);
518
		return $output;
519
	}
520
521
	/**
522
	 * A trigger to return numbers of attachments in the upload_target_srl (comment_srl)
523
	 *
524
	 * @param object $obj Trigger object
525
	 * @return Object
526
	 */
527 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...
528
	{
529
		$comment_srl = $obj->comment_srl;
530
		if(!$comment_srl) return new Object();
531
		// Get numbers of attachments
532
		$oFileModel = getModel('file');
533
		$obj->uploaded_count = $oFileModel->getFilesCount($comment_srl);
534
535
		return new Object();
536
	}
537
538
	/**
539
	 * A trigger to link the attachment with the upload_target_srl (comment_srl)
540
	 *
541
	 * @param object $obj Trigger object
542
	 * @return Object
543
	 */
544
	function triggerCommentAttachFiles(&$obj)
545
	{
546
		$comment_srl = $obj->comment_srl;
547
		$uploaded_count = $obj->uploaded_count;
548
		if(!$comment_srl || !$uploaded_count) return new Object();
549
550
		$output = $this->setFilesValid($comment_srl);
551
		if(!$output->toBool()) return $output;
552
553
		return new Object();
554
	}
555
556
	/**
557
	 * A trigger to delete the attachment in the upload_target_srl (comment_srl)
558
	 *
559
	 * @param object $obj Trigger object
560
	 * @return Object
561
	 */
562
	function triggerCommentDeleteAttached(&$obj)
563
	{
564
		$comment_srl = $obj->comment_srl;
565
		if(!$comment_srl) return new Object();
566
567
		if($obj->isMoveToTrash) return new Object();
568
569
		$output = $this->deleteFiles($comment_srl);
570
		return $output;
571
	}
572
573
	/**
574
	 * A trigger to delete all the attachements when deleting the module
575
	 *
576
	 * @param object $obj Trigger object
577
	 * @return Object
578
	 */
579
	function triggerDeleteModuleFiles(&$obj)
580
	{
581
		$module_srl = $obj->module_srl;
582
		if(!$module_srl) return new Object();
583
584
		$oFileController = getAdminController('file');
585
		return $oFileController->deleteModuleFiles($module_srl);
586
	}
587
588
	/**
589
	 * Upload enabled
590
	 *
591
	 * @param int $editor_sequence
592
	 * @param int $upload_target_srl
593
	 * @return void
594
	 */
595
	function setUploadInfo($editor_sequence, $upload_target_srl=0)
596
	{
597
		if(!isset($_SESSION['upload_info'][$editor_sequence]))
598
		{
599
			$_SESSION['upload_info'][$editor_sequence] = new stdClass();
600
		}
601
		$_SESSION['upload_info'][$editor_sequence]->enabled = true;
602
		$_SESSION['upload_info'][$editor_sequence]->upload_target_srl = $upload_target_srl;
603
	}
604
605
	/**
606
	 * Set the attachements of the upload_target_srl to be valid
607
	 * By changing its state to valid when a document is inserted, it prevents from being considered as a unnecessary file
608
	 *
609
	 * @param int $upload_target_srl
610
	 * @return Object
611
	 */
612
	function setFilesValid($upload_target_srl)
613
	{
614
		$args = new stdClass();
615
		$args->upload_target_srl = $upload_target_srl;
616
		return executeQuery('file.updateFileValid', $args);
617
	}
618
619
	/**
620
	 * Add an attachement
621
	 *
622
	 * <pre>
623
	 * This method call trigger 'file.insertFile'.
624
	 *
625
	 * Before trigger object contains:
626
	 * - module_srl
627
	 * - upload_target_srl
628
	 *
629
	 * After trigger object contains:
630
	 * - file_srl
631
	 * - upload_target_srl
632
	 * - module_srl
633
	 * - direct_download
634
	 * - source_filename
635
	 * - uploaded_filename
636
	 * - donwload_count
637
	 * - file_size
638
	 * - comment
639
	 * - member_srl
640
	 * - sid
641
	 * </pre>
642
	 *
643
	 * @param object $file_info PHP file information array
644
	 * @param int $module_srl Sequence of module to upload file
645
	 * @param int $upload_target_srl Sequence of target to upload file
646
	 * @param int $download_count Initial download count
647
	 * @param bool $manual_insert If set true, pass validation check
648
	 * @return Object
649
	 */
650
	function insertFile($file_info, $module_srl, $upload_target_srl, $download_count = 0, $manual_insert = false)
651
	{
652
		// Call a trigger (before)
653
		$trigger_obj = new stdClass;
654
		$trigger_obj->module_srl = $module_srl;
655
		$trigger_obj->upload_target_srl = $upload_target_srl;
656
		$output = ModuleHandler::triggerCall('file.insertFile', 'before', $trigger_obj);
657
		if(!$output->toBool()) return $output;
658
659
		// A workaround for Firefox upload bug
660
		if(preg_match('/^=\?UTF-8\?B\?(.+)\?=$/i', $file_info['name'], $match))
661
		{
662
			$file_info['name'] = base64_decode(strtr($match[1], ':', '/'));
663
		}
664
665
		if(!$manual_insert)
666
		{
667
			// Get the file configurations
668
			$logged_info = Context::get('logged_info');
669
			if($logged_info->is_admin != 'Y')
670
			{
671
				$oFileModel = getModel('file');
672
				$config = $oFileModel->getFileConfig($module_srl);
673
674
				// check file type
675
				if(isset($config->allowed_filetypes) && $config->allowed_filetypes !== '*.*')
676
				{
677
					$filetypes = explode(';', $config->allowed_filetypes);
678
					$ext = array();
679 View Code Duplication
					foreach($filetypes as $item) {
680
						$item = explode('.', $item);
681
						$ext[] = strtolower($item[1]);
682
					}
683
					$uploaded_ext = explode('.', $file_info['name']);
684
					$uploaded_ext = strtolower(array_pop($uploaded_ext));
685
686
					if(!in_array($uploaded_ext, $ext))
687
					{
688
						return $this->stop('msg_not_allowed_filetype');
689
					}
690
				}
691
692
				$allowed_filesize = $config->allowed_filesize * 1024 * 1024;
693
				$allowed_attach_size = $config->allowed_attach_size * 1024 * 1024;
694
				// An error appears if file size exceeds a limit
695
				if($allowed_filesize < filesize($file_info['tmp_name'])) return new Object(-1, 'msg_exceeds_limit_size');
696
				// Get total file size of all attachements (from DB)
697
				$size_args = new stdClass;
698
				$size_args->upload_target_srl = $upload_target_srl;
699
				$output = executeQuery('file.getAttachedFileSize', $size_args);
700
				$attached_size = (int)$output->data->attached_size + filesize($file_info['tmp_name']);
701
				if($attached_size > $allowed_attach_size) return new Object(-1, 'msg_exceeds_limit_size');
702
			}
703
		}
704
705
		// https://github.com/xpressengine/xe-core/issues/1713
706
		$file_info['name'] = preg_replace('/\.(php|phtm|phar|html?|cgi|pl|exe|jsp|asp|inc)/i', '$0-x',$file_info['name']);
707
		$file_info['name'] = removeHackTag($file_info['name']);
708
		$file_info['name'] = str_replace(array('<','>'),array('%3C','%3E'),$file_info['name']);
709
710
		// Get random number generator
711
		$random = new Password();
712
713
		// Set upload path by checking if the attachement is an image or other kinds of file
714
		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']))
715
		{
716
			$path = sprintf("./files/attach/images/%s/%s", $module_srl,getNumberingPath($upload_target_srl,3));
717
718
			// special character to '_'
719
			// change to random file name. because window php bug. window php is not recognize unicode character file name - by cherryfilter
720
			$ext = substr(strrchr($file_info['name'],'.'),1);
721
			//$_filename = preg_replace('/[#$&*?+%"\']/', '_', $file_info['name']);
722
			$_filename = $random->createSecureSalt(32, 'hex').'.'.$ext;
723
			$filename  = $path.$_filename;
724
			$idx = 1;
725 View Code Duplication
			while(file_exists($filename))
726
			{
727
				$filename = $path.preg_replace('/\.([a-z0-9]+)$/i','_'.$idx.'.$1',$_filename);
728
				$idx++;
729
			}
730
			$direct_download = 'Y';
731
		}
732 View Code Duplication
		else
733
		{
734
			$path = sprintf("./files/attach/binaries/%s/%s", $module_srl, getNumberingPath($upload_target_srl,3));
735
			$filename = $path.$random->createSecureSalt(32, 'hex');
736
			$direct_download = 'N';
737
		}
738
		// Create a directory
739
		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...
740
741
		// Check uploaded file
742
		if(!checkUploadedFile($file_info['tmp_name']))  return new Object(-1,'msg_file_upload_error');
743
744
		// Get random number generator
745
		$random = new Password();
746
		
747
		// Move the file
748
		if($manual_insert)
749
		{
750
			@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...
751
			if(!file_exists($filename))
752
			{
753
				$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...
754
				@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...
755
			}
756
		}
757
		else
758
		{
759
			if(!@move_uploaded_file($file_info['tmp_name'], $filename))
760
			{
761
				$filename = $path.$random->createSecureSalt(32, 'hex').'.'.$ext;
762
				if(!@move_uploaded_file($file_info['tmp_name'], $filename))  return new Object(-1,'msg_file_upload_error');
763
			}
764
		}
765
		// Get member information
766
		$oMemberModel = getModel('member');
767
		$member_srl = $oMemberModel->getLoggedMemberSrl();
768
		// List file information
769
		$args = new stdClass;
770
		$args->file_srl = getNextSequence();
771
		$args->upload_target_srl = $upload_target_srl;
772
		$args->module_srl = $module_srl;
773
		$args->direct_download = $direct_download;
774
		$args->source_filename = $file_info['name'];
775
		$args->uploaded_filename = $filename;
776
		$args->download_count = $download_count;
777
		$args->file_size = @filesize($filename);
778
		$args->comment = NULL;
779
		$args->member_srl = $member_srl;
780
		$args->sid = $random->createSecureSalt(32, 'hex');
781
782
		$output = executeQuery('file.insertFile', $args);
783
		if(!$output->toBool()) return $output;
784
		// Call a trigger (after)
785
		$trigger_output = ModuleHandler::triggerCall('file.insertFile', 'after', $args);
786
		if(!$trigger_output->toBool()) return $trigger_output;
787
788
		$_SESSION['__XE_UPLOADING_FILES_INFO__'][$args->file_srl] = true;
789
790
		$output->add('file_srl', $args->file_srl);
791
		$output->add('file_size', $args->file_size);
792
		$output->add('sid', $args->sid);
793
		$output->add('direct_download', $args->direct_download);
794
		$output->add('source_filename', $args->source_filename);
795
		$output->add('upload_target_srl', $upload_target_srl);
796
		$output->add('uploaded_filename', $args->uploaded_filename);
797
		return $output;
798
	}
799
800
	/**
801
	 * Delete the attachment
802
	 *
803
	 * <pre>
804
	 * This method call trigger 'file.deleteFile'.
805
	 * Before, after trigger object contains:
806
	 * - download_url
807
	 * - file_srl
808
	 * - upload_target_srl
809
	 * - upload_target_type
810
	 * - sid
811
	 * - module_srl
812
	 * - member_srl
813
	 * - download_count
814
	 * - direct_download
815
	 * - source_filename
816
	 * - uploaded_filename
817
	 * - file_size
818
	 * - comment
819
	 * - isvalid
820
	 * - regdate
821
	 * - ipaddress
822
	 * </pre>
823
	 *
824
	 * @param int $file_srl Sequence of file to delete
825
	 * @return Object
826
	 */
827
	function deleteFile($file_srl)
828
	{
829
		if(!$file_srl) return;
830
831
		$srls = (is_array($file_srl)) ? $file_srl : explode(',', $file_srl);
832
		if(!count($srls)) return;
833
834
		$oDocumentController = getController('document');
835
		$documentSrlList = array();
836
837
		foreach($srls as $srl)
838
		{
839
			$srl = (int)$srl;
840
			if(!$srl) 
841
			{
842
				continue;
843
			}
844
845
			$args = new stdClass();
846
			$args->file_srl = $srl;
847
			$output = executeQuery('file.getFile', $args);
848
849
			if(!$output->toBool() || !$output->data) 
850
			{
851
				continue;
852
			}
853
854
			$file_info = $output->data;
855
856
			if($file_info->upload_target_srl)
857
			{
858
				$documentSrlList[] = $file_info->upload_target_srl;
859
			}
860
861
			$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...
862
			$uploaded_filename = $output->data->uploaded_filename;
863
864
			// Call a trigger (before)
865
			$trigger_obj = $output->data;
866
			$output = ModuleHandler::triggerCall('file.deleteFile', 'before', $trigger_obj);
867
			if(!$output->toBool()) return $output;
868
869
			// Remove from the DB
870
			$output = executeQuery('file.deleteFile', $args);
871
			if(!$output->toBool()) return $output;
872
873
			// Call a trigger (after)
874
			$trigger_output = ModuleHandler::triggerCall('file.deleteFile', 'after', $trigger_obj);
875
			if(!$trigger_output->toBool()) return $trigger_output;
876
877
			// If successfully deleted, remove the file
878
			FileHandler::removeFile($uploaded_filename);
879
		}
880
881
		$oDocumentController->updateUploaedCount($documentSrlList);
882
883
		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...
884
	}
885
886
	/**
887
	 * Delete all attachments of a particular document
888
	 *
889
	 * @param int $upload_target_srl Upload target srl to delete files
890
	 * @return Object
891
	 */
892
	function deleteFiles($upload_target_srl)
893
	{
894
		// Get a list of attachements
895
		$oFileModel = getModel('file');
896
		$columnList = array('file_srl', 'uploaded_filename', 'module_srl');
897
		$file_list = $oFileModel->getFiles($upload_target_srl, $columnList);
898
		// Success returned if no attachement exists
899
		if(!is_array($file_list)||!count($file_list)) return new Object();
900
901
		// Delete the file
902
		$path = array();
903
		$file_count = count($file_list);
904 View Code Duplication
		for($i=0;$i<$file_count;$i++)
905
		{
906
			$this->deleteFile($file_list[$i]->file_srl);
907
908
			$uploaded_filename = $file_list[$i]->uploaded_filename;
909
			$path_info = pathinfo($uploaded_filename);
910
			if(!in_array($path_info['dirname'], $path)) $path[] = $path_info['dirname'];
911
		}
912
913
		// Remove from the DB
914
		$args = new stdClass();
915
		$args->upload_target_srl = $upload_target_srl;
916
		$output = executeQuery('file.deleteFiles', $args);
917
		if(!$output->toBool()) return $output;
918
		
919
		// Remove a file directory of the document
920 View Code Duplication
		for($i=0, $c=count($path); $i<$c; $i++)
921
		{
922
			FileHandler::removeBlankDir($path[$i]);
923
		}
924
925
		return $output;
926
	}
927
928
	/**
929
	 * Move an attachement to the other document
930
	 *
931
	 * @param int $source_srl Sequence of target to move
932
	 * @param int $target_module_srl New squence of module
933
	 * @param int $target_srl New sequence of target
934
	 * @return void
935
	 */
936
	function moveFile($source_srl, $target_module_srl, $target_srl)
937
	{
938
		if($source_srl == $target_srl) return;
939
940
		$oFileModel = getModel('file');
941
		$file_list = $oFileModel->getFiles($source_srl);
942
		if(!$file_list) return;
943
944
		$file_count = count($file_list);
945
946
		for($i=0;$i<$file_count;$i++)
947
		{
948
			unset($file_info);
949
			$file_info = $file_list[$i];
950
			$old_file = $file_info->uploaded_filename;
951
			// Determine the file path by checking if the file is an image or other kinds
952
			if(preg_match("/\.(asf|asf|asx|avi|flv|gif|jpeg|jpg|m4a|m4v|mid|midi|moov|mov|mp1|mp2|mp3|mp4|mpeg|mpg|ogg|png|qt|ra|ram|rm|rmm|swf|wav|webm|webp|wma|wmv)$/i", $file_info->source_filename))
953
			{
954
				$path = sprintf("./files/attach/images/%s/%s/", $target_module_srl,$target_srl);
955
				$new_file = $path.$file_info->source_filename;
956
			}
957
			else
958
			{
959
				$path = sprintf("./files/attach/binaries/%s/%s/", $target_module_srl, $target_srl);
960
				$random = new Password();
961
				$new_file = $path.$random->createSecureSalt(32, 'hex');
962
			}
963
			// Pass if a target document to move is same
964
			if($old_file == $new_file) continue;
965
			// Create a directory
966
			FileHandler::makeDir($path);
967
			// Move the file
968
			FileHandler::rename($old_file, $new_file);
969
			// Update DB information
970
			$args = new stdClass;
971
			$args->file_srl = $file_info->file_srl;
972
			$args->uploaded_filename = $new_file;
973
			$args->module_srl = $file_info->module_srl;
974
			$args->upload_target_srl = $target_srl;
975
			executeQuery('file.updateFile', $args);
976
		}
977
	}
978
979
	public function procFileSetCoverImage()
980
	{
981
		$vars = Context::getRequestVars();
982
		$logged_info = Context::get('logged_info');
983
984
		if(!$vars->editor_sequence) return new Object(-1, 'msg_invalid_request');
985
986
		$upload_target_srl = $_SESSION['upload_info'][$vars->editor_sequence]->upload_target_srl;
987
988
		$oFileModel = getModel('file');
989
		$file_info = $oFileModel->getFile($vars->file_srl);
990
991
		if(!$file_info) return new Object(-1, 'msg_not_founded');
992
993
		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...
994
995
		$args =  new stdClass();
996
		$args->file_srl = $vars->file_srl;
997
		$args->upload_target_srl = $upload_target_srl;
998
999
		$oDB = &DB::getInstance();
1000
		$oDB->begin();
1001
1002
		$args->cover_image = 'N';
1003
		$output = executeQuery('file.updateClearCoverImage', $args);
1004
		if(!$output->toBool())
1005
		{
1006
			$oDB->rollback();
1007
			return $output;
1008
		}
1009
1010
		$args->cover_image = 'Y';
1011
		$output = executeQuery('file.updateCoverImage', $args);
1012
		if(!$output->toBool())
1013
		{
1014
			$oDB->rollback();
1015
			return $output;
1016
		}
1017
1018
		$oDB->commit();
1019
1020
		// 썸네일 삭제
1021
		$thumbnail_path = sprintf('files/thumbnails/%s', getNumberingPath($upload_target_srl, 3));
1022
		Filehandler::removeFilesInDir($thumbnail_path);
1023
	}
1024
1025
	/**
1026
	 * Find the attachment where a key is upload_target_srl and then return java script code
1027
	 *
1028
	 * @deprecated
1029
	 * @param int $editor_sequence
1030
	 * @param int $upload_target_srl
1031
	 * @return void
1032
	 */
1033
	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...
1034
	{
1035
		return;
1036
	}
1037
1038 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...
1039
	{
1040
		$oModuleModel = getModel('module');
1041
		$fileConfig = $oModuleModel->getModulePartConfig('file', $obj->originModuleSrl);
1042
1043
		$oModuleController = getController('module');
1044
		if(is_array($obj->moduleSrlList))
1045
		{
1046
			foreach($obj->moduleSrlList AS $key=>$moduleSrl)
1047
			{
1048
				$oModuleController->insertModulePartConfig('file', $moduleSrl, $fileConfig);
1049
			}
1050
		}
1051
	}
1052
}
1053
/* End of file file.controller.php */
1054
/* Location: ./modules/file/file.controller.php */
1055
1056