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 — master (#1842)
by
unknown
14:13 queued 14s
created

fileController   D

Complexity

Total Complexity 170

Size/Duplication

Total Lines 1027
Duplicated Lines 13.05 %

Coupling/Cohesion

Components 3
Dependencies 7
Metric Value
wmc 170
lcom 3
cbo 7
dl 134
loc 1027
rs 4.4346

24 Methods

Rating   Name   Duplication   Size   Complexity  
A init() 0 3 1
F procFileDownload() 61 124 32
C procFileUpload() 0 25 7
C procFileIframeUpload() 0 31 7
C procFileImageResize() 0 36 7
D procFileOutput() 22 85 19
C procFileDelete() 0 38 11
C procFileGetList() 0 31 8
A triggerCheckAttached() 10 10 2
A triggerAttachFiles() 0 10 3
A triggerDeleteAttached() 0 8 2
A triggerCommentCheckAttached() 10 10 2
A triggerCommentAttachFiles() 0 11 4
A triggerCommentDeleteAttached() 0 10 3
A triggerDeleteModuleFiles() 0 8 2
A setUploadInfo() 0 9 2
A setFilesValid() 0 6 1
F insertFile() 5 149 21
C deleteFile() 0 58 12
C deleteFiles() 12 35 7
B moveFile() 0 42 6
C procFileSetCoverImage() 0 45 7
A printUploadedFileList() 0 4 1
A triggerCopyModule() 14 14 3

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like fileController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use fileController, and based on these observations, apply Extract Interface, too.

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