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 — master ( 8e2d68...a4d5e8 )
by gyeong-won
14:59 queued 07:34
created

documentController::getXmlTree()   F

Complexity

Conditions 18
Paths 4098

Size

Total Lines 64
Code Lines 42

Duplication

Lines 16
Ratio 25 %

Importance

Changes 0
Metric Value
cc 18
eloc 42
nc 4098
nop 4
dl 16
loc 64
rs 2.8531
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
/* Copyright (C) NAVER <http://www.navercorp.com> */
3
/**
4
 * documentController class
5
 * document the module's controller class
6
 *
7
 * @author NAVER ([email protected])
8
 * @package /modules/document
9
 * @version 0.1
10
 */
11
class documentController extends document
12
{
13
	/**
14
	 * Initialization
15
	 * @return void
16
	 */
17
	function init()
18
	{
19
	}
20
21
	/**
22
	 * Action to handle vote-up of the post (Up)
23
	 * @return BaseObject
24
	 */
25 View Code Duplication
	function procDocumentVoteUp()
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...
26
	{
27
		if(!Context::get('is_logged')) return new BaseObject(-1, 'msg_invalid_request');
28
29
		$document_srl = Context::get('target_srl');
30
		if(!$document_srl) return new BaseObject(-1, 'msg_invalid_request');
31
32
		$oDocumentModel = getModel('document');
33
		$oDocument = $oDocumentModel->getDocument($document_srl, false, false);
34
		$module_srl = $oDocument->get('module_srl');
35
		if(!$module_srl) return new BaseObject(-1, 'msg_invalid_request');
36
37
		$oModuleModel = getModel('module');
38
		$document_config = $oModuleModel->getModulePartConfig('document',$module_srl);
39
		if($document_config->use_vote_up=='N') return new BaseObject(-1, 'msg_invalid_request');
40
41
		$point = 1;
42
		$output = $this->updateVotedCount($document_srl, $point);
43
		$this->add('voted_count', $output->get('voted_count'));
44
		return $output;
45
	}
46
47
	/**
48
	 * insert alias
49
	 * @param int $module_srl
50
	 * @param int $document_srl
51
	 * @param string $alias_title
52
	 * @return object
53
	 */
54
	function insertAlias($module_srl, $document_srl, $alias_title)
55
	{
56
		$args = new stdClass;
57
		$args->alias_srl = getNextSequence();
58
		$args->module_srl = $module_srl;
59
		$args->document_srl = $document_srl;
60
		$args->alias_title = urldecode($alias_title);
61
		$query = "document.insertAlias";
62
		$output = executeQuery($query, $args);
63
		return $output;
64
	}
65
66
	/**
67
	 * Action to handle vote-up of the post (Down)
68
	 * @return BaseObject
69
	 */
70 View Code Duplication
	function procDocumentVoteDown()
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...
71
	{
72
		if(!Context::get('is_logged')) return new BaseObject(-1, 'msg_invalid_request');
73
74
		$document_srl = Context::get('target_srl');
75
		if(!$document_srl) return new BaseObject(-1, 'msg_invalid_request');
76
77
		$oDocumentModel = getModel('document');
78
		$oDocument = $oDocumentModel->getDocument($document_srl, false, false);
79
		$module_srl = $oDocument->get('module_srl');
80
		if(!$module_srl) return new BaseObject(-1, 'msg_invalid_request');
81
82
		$oModuleModel = getModel('module');
83
		$document_config = $oModuleModel->getModulePartConfig('document',$module_srl);
84
		if($document_config->use_vote_down=='N') return new BaseObject(-1, 'msg_invalid_request');
85
86
		$point = -1;
87
		$output = $this->updateVotedCount($document_srl, $point);
88
		$this->add('blamed_count', $output->get('blamed_count'));
89
		return $output;
90
	}
91
92
	/**
93
	 * Action called when the post is reported by other member
94
	 * @return void|BaseObject
95
	 */
96 View Code Duplication
	function procDocumentDeclare()
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...
97
	{
98
		if(!Context::get('is_logged')) return new BaseObject(-1, 'msg_invalid_request');
99
100
		$document_srl = Context::get('target_srl');
101
		if(!$document_srl) return new BaseObject(-1, 'msg_invalid_request');
102
103
		return $this->declaredDocument($document_srl);
104
	}
105
106
	/**
107
	 * Delete alias when module deleted
108
	 * @param int $module_srl
109
	 * @return void
110
	 */
111
	function deleteDocumentAliasByModule($module_srl)
112
	{
113
		$args = new stdClass();
114
		$args->module_srl = $module_srl;
115
		executeQuery("document.deleteAlias", $args);
116
	}
117
118
	/**
119
	 * Delete alias when document deleted
120
	 * @param int $document_srl
121
	 * @return void
122
	 */
123
	function deleteDocumentAliasByDocument($document_srl)
124
	{
125
		$args = new stdClass();
126
		$args->document_srl = $document_srl;
127
		executeQuery("document.deleteAlias", $args);
128
	}
129
130
	/**
131
	 * Delete document history
132
	 * @param int $history_srl
133
	 * @param int $document_srl
134
	 * @param int $module_srl
135
	 * @return void
136
	 */
137
	function deleteDocumentHistory($history_srl, $document_srl, $module_srl)
138
	{
139
		$args = new stdClass();
140
		$args->history_srl = $history_srl;
141
		$args->module_srl = $module_srl;
142
		$args->document_srl = $document_srl;
143
		if(!$args->history_srl && !$args->module_srl && !$args->document_srl) return;
144
		executeQuery("document.deleteHistory", $args);
145
	}
146
147
	/**
148
	 * A trigger to delete all posts together when the module is deleted
149
	 * @param object $obj
150
	 * @return BaseObject
151
	 */
152
	function triggerDeleteModuleDocuments(&$obj)
153
	{
154
		$module_srl = $obj->module_srl;
155
		if(!$module_srl) return new BaseObject();
156
		// Delete the document
157
		$oDocumentAdminController = getAdminController('document');
158
		$output = $oDocumentAdminController->deleteModuleDocument($module_srl);
159
		if(!$output->toBool()) return $output;
160
		// Delete the category
161
		$oDocumentController = getController('document');
162
		$output = $oDocumentController->deleteModuleCategory($module_srl);
163
		if(!$output->toBool()) return $output;
164
		// Delete extra key and variable, because module deleted
165
		$this->deleteDocumentExtraKeys($module_srl);
166
167
		// remove aliases
168
		$this->deleteDocumentAliasByModule($module_srl);
169
170
		// remove histories
171
		$this->deleteDocumentHistory(null, null, $module_srl);
172
173
		return new BaseObject();
174
	}
175
176
	/**
177
	 * Grant a permisstion of the document
178
	 * Available in the current connection with session value
179
	 * @param int $document_srl
180
	 * @return void
181
	 */
182
	function addGrant($document_srl)
183
	{
184
		$_SESSION['own_document'][$document_srl] = true;
185
	}
186
187
	/**
188
	 * Insert the document
189
	 * @param object $obj
190
	 * @param bool $manual_inserted
191
	 * @param bool $isRestore
192
	 * @return object
193
	 */
194
	function insertDocument($obj, $manual_inserted = false, $isRestore = false, $isLatest = true)
195
	{
196
		if(!$manual_inserted && !checkCSRF())
197
		{
198
			return new BaseObject(-1, 'msg_invalid_request');
199
		}
200
201
		// begin transaction
202
		$oDB = &DB::getInstance();
203
		$oDB->begin();
204
		// List variables
205
		if($obj->comment_status) $obj->commentStatus = $obj->comment_status;
206
		if(!$obj->commentStatus) $obj->commentStatus = 'DENY';
207
		if($obj->commentStatus == 'DENY') $this->_checkCommentStatusForOldVersion($obj);
208
		if($obj->allow_trackback!='Y') $obj->allow_trackback = 'N';
209 View Code Duplication
		if($obj->homepage) 
210
		{
211
			$obj->homepage = removeHackTag($obj->homepage);
212
			if(!preg_match('/^[a-z]+:\/\//i',$obj->homepage))
213
			{
214
				$obj->homepage = 'http://'.$obj->homepage;
215
			}
216
		}
217
		
218
		if($obj->notify_message != 'Y') $obj->notify_message = 'N';
219
		if(!$obj->email_address) $obj->email_address = '';
220
		if(!$isRestore) $obj->ipaddress = $_SERVER['REMOTE_ADDR'];
221
222
                // can modify regdate only manager
223
                $grant = Context::get('grant');
224
		if(!$grant->manager)
225
		{
226
			unset($obj->regdate);
227
		}
228
		
229
		// Serialize the $extra_vars, check the extra_vars type, because duplicate serialized avoid
230
		if(!is_string($obj->extra_vars)) $obj->extra_vars = serialize($obj->extra_vars);
231
		// Remove the columns for automatic saving
232
		unset($obj->_saved_doc_srl);
233
		unset($obj->_saved_doc_title);
234
		unset($obj->_saved_doc_content);
235
		unset($obj->_saved_doc_message);
236
		// Call a trigger (before)
237
		$output = ModuleHandler::triggerCall('document.insertDocument', 'before', $obj);
238
		if(!$output->toBool()) return $output;
239
		// Register it if no given document_srl exists
240 View Code Duplication
		if(!$obj->document_srl) $obj->document_srl = getNextSequence();
241
		elseif(!$manual_inserted && !$isRestore && !checkUserSequence($obj->document_srl)) return new BaseObject(-1, 'msg_not_permitted');
242
243
		$oDocumentModel = getModel('document');
244
		// Set to 0 if the category_srl doesn't exist
245
		if($obj->category_srl)
246
		{
247
			$category_list = $oDocumentModel->getCategoryList($obj->module_srl);
248
			if(count($category_list) > 0 && !$category_list[$obj->category_srl]->grant)
249
			{
250
				return new BaseObject(-1, 'msg_not_permitted');
251
			}
252
			if(count($category_list) > 0 && !$category_list[$obj->category_srl]) $obj->category_srl = 0;
253
		}
254
		// Set the read counts and update order.
255
		if(!$obj->readed_count) $obj->readed_count = 0;
256
		if($isLatest) $obj->update_order = $obj->list_order = $obj->document_srl * -1;
257
		else $obj->update_order = $obj->list_order;
258
		// Check the status of password hash for manually inserting. Apply hashing for otherwise.
259
		if($obj->password && !$obj->password_is_hashed)
260
		{
261
			$obj->password = getModel('member')->hashPassword($obj->password);
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class ModuleObject as the method hashPassword() does only exist in the following sub-classes of ModuleObject: memberModel. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
262
		}
263
		// Insert member's information only if the member is logged-in and not manually registered.
264
		$logged_info = Context::get('logged_info');
265
		if(Context::get('is_logged') && !$manual_inserted && !$isRestore)
266
		{
267
			$obj->member_srl = $logged_info->member_srl;
268
269
			// user_id, user_name and nick_name already encoded
270
			$obj->user_id = htmlspecialchars_decode($logged_info->user_id);
271
			$obj->user_name = htmlspecialchars_decode($logged_info->user_name);
272
			$obj->nick_name = htmlspecialchars_decode($logged_info->nick_name);
273
			$obj->email_address = $logged_info->email_address;
274
			$obj->homepage = $logged_info->homepage;
275
		}
276
		// If the tile is empty, extract string from the contents.
277
		$obj->title = htmlspecialchars($obj->title, ENT_COMPAT | ENT_HTML401, 'UTF-8', false);
278
		settype($obj->title, "string");
279 View Code Duplication
		if($obj->title == '') $obj->title = cut_str(trim(strip_tags(nl2br($obj->content))),20,'...');
280
		// If no tile extracted from the contents, leave it untitled.
281
		if($obj->title == '') $obj->title = 'Untitled';
282
		// Remove XE's own tags from the contents.
283
		$obj->content = preg_replace('!<\!--(Before|After)(Document|Comment)\(([0-9]+),([0-9]+)\)-->!is', '', $obj->content);
284 View Code Duplication
		if(Mobile::isFromMobilePhone() && $obj->use_editor != 'Y')
285
		{
286
			if($obj->use_html != 'Y')
287
			{
288
				$obj->content = htmlspecialchars($obj->content, ENT_COMPAT | ENT_HTML401, 'UTF-8', false);
289
			}
290
			$obj->content = nl2br($obj->content);
291
		}
292
		// Remove iframe and script if not a top adminisrator in the session.
293
		if($logged_info->is_admin != 'Y') $obj->content = removeHackTag($obj->content);
294
		// An error appears if both log-in info and user name don't exist.
295
		if(!$logged_info->member_srl && !$obj->nick_name) return new BaseObject(-1,'msg_invalid_request');
296
297
		$obj->lang_code = Context::getLangType();
298
		// Insert data into the DB
299
		if(!$obj->status) $this->_checkDocumentStatusForOldVersion($obj);
300
		$output = executeQuery('document.insertDocument', $obj);
301
		if(!$output->toBool())
302
		{
303
			$oDB->rollback();
304
			return $output;
305
		}
306
		// Insert extra variables if the document successfully inserted.
307
		$extra_keys = $oDocumentModel->getExtraKeys($obj->module_srl);
308 View Code Duplication
		if(count($extra_keys))
309
		{
310
			foreach($extra_keys as $idx => $extra_item)
311
			{
312
				$value = NULL;
313
				if(isset($obj->{'extra_vars'.$idx}))
314
				{
315
					$tmp = $obj->{'extra_vars'.$idx};
316
					if(is_array($tmp))
317
						$value = implode('|@|', $tmp);
318
					else
319
						$value = trim($tmp);
320
				}
321
				else if(isset($obj->{$extra_item->name})) $value = trim($obj->{$extra_item->name});
322
				if($value == NULL) continue;
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $value of type string|null against null; this is ambiguous if the string can be empty. Consider using a strict comparison === instead.
Loading history...
323
324
				$this->insertDocumentExtraVar($obj->module_srl, $obj->document_srl, $idx, $value, $extra_item->eid);
325
			}
326
		}
327
		// Update the category if the category_srl exists.
328
		if($obj->category_srl) $this->updateCategoryCount($obj->module_srl, $obj->category_srl);
329
		// Call a trigger (after)
330 View Code Duplication
		if($output->toBool())
331
		{
332
			$trigger_output = ModuleHandler::triggerCall('document.insertDocument', 'after', $obj);
333
			if(!$trigger_output->toBool())
334
			{
335
				$oDB->rollback();
336
				return $trigger_output;
337
			}
338
		}
339
340
		// commit
341
		$oDB->commit();
342
343
		// return
344
		if(!$manual_inserted)
345
		{
346
			$this->addGrant($obj->document_srl);
347
		}
348
		$output->add('document_srl',$obj->document_srl);
349
		$output->add('category_srl',$obj->category_srl);
350
351
		return $output;
352
	}
353
354
	/**
355
	 * Update the document
356
	 * @param object $source_obj
357
	 * @param object $obj
358
	 * @param bool $manual_updated
359
	 * @return object
360
	 */
361
	function updateDocument($source_obj, $obj, $manual_updated = FALSE)
362
	{
363
		$logged_info = Context::get('logged_info');
364
365
		if(!$manual_updated && !checkCSRF())
366
		{
367
			return new BaseObject(-1, 'msg_invalid_request');
368
		}
369
370
		if(!$source_obj->document_srl || !$obj->document_srl) return new BaseObject(-1,'msg_invalied_request');
371
		if(!$obj->status && $obj->is_secret == 'Y') $obj->status = 'SECRET';
372
		if(!$obj->status) $obj->status = 'PUBLIC';
373
374
		// Call a trigger (before)
375
		$output = ModuleHandler::triggerCall('document.updateDocument', 'before', $obj);
376
		if(!$output->toBool()) return $output;
377
378
		// begin transaction
379
		$oDB = &DB::getInstance();
380
		$oDB->begin();
381
382
		$oModuleModel = getModel('module');
383
		if(!$obj->module_srl) $obj->module_srl = $source_obj->get('module_srl');
384
		$module_srl = $obj->module_srl;
385
		$document_config = $oModuleModel->getModulePartConfig('document', $module_srl);
386
		if(!$document_config)
387
		{
388
			$document_config = new stdClass();
389
		}
390
		if(!isset($document_config->use_history)) $document_config->use_history = 'N';
391
		$bUseHistory = $document_config->use_history == 'Y' || $document_config->use_history == 'Trace';
392
393
		if($bUseHistory)
394
		{
395
			$args = new stdClass;
396
			$args->history_srl = getNextSequence();
397
			$args->document_srl = $obj->document_srl;
398
			$args->module_srl = $module_srl;
399
			if($document_config->use_history == 'Y') $args->content = $source_obj->get('content');
400
			$args->nick_name = $source_obj->get('nick_name');
401
			$args->member_srl = $source_obj->get('member_srl');
402
			$args->regdate = $source_obj->get('last_update');
403
			$args->ipaddress = $source_obj->get('ipaddress');
404
			$output = executeQuery("document.insertHistory", $args);
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...
405
		}
406
		else
407
		{
408
			$obj->ipaddress = $source_obj->get('ipaddress');
409
		}
410
		// List variables
411
		if($obj->comment_status) $obj->commentStatus = $obj->comment_status;
412
		if(!$obj->commentStatus) $obj->commentStatus = 'DENY';
413
		if($obj->commentStatus == 'DENY') $this->_checkCommentStatusForOldVersion($obj);
414
		if($obj->allow_trackback!='Y') $obj->allow_trackback = 'N';
415 View Code Duplication
		if($obj->homepage)
416
		{
417
			$obj->homepage = removeHackTag($obj->homepage);
418
			if(!preg_match('/^[a-z]+:\/\//i',$obj->homepage))
419
			{
420
				$obj->homepage = 'http://'.$obj->homepage;
421
			}
422
		}
423
		
424
		if($obj->notify_message != 'Y') $obj->notify_message = 'N';
425
		
426
		// can modify regdate only manager
427
                $grant = Context::get('grant');
428
		if(!$grant->manager)
429
		{
430
			unset($obj->regdate);
431
		}
432
		
433
		// Serialize the $extra_vars
434
		if(!is_string($obj->extra_vars)) $obj->extra_vars = serialize($obj->extra_vars);
435
		// Remove the columns for automatic saving
436
		unset($obj->_saved_doc_srl);
437
		unset($obj->_saved_doc_title);
438
		unset($obj->_saved_doc_content);
439
		unset($obj->_saved_doc_message);
440
441
		$oDocumentModel = getModel('document');
442
		// Set the category_srl to 0 if the changed category is not exsiting.
443
		if($source_obj->get('category_srl')!=$obj->category_srl)
444
		{
445
			$category_list = $oDocumentModel->getCategoryList($obj->module_srl);
446
			if(!$category_list[$obj->category_srl]) $obj->category_srl = 0;
447
		}
448
		// Change the update order
449
		$obj->update_order = getNextSequence() * -1;
450
		// Hash the password if it exists
451
		if($obj->password)
452
		{
453
			$obj->password = getModel('member')->hashPassword($obj->password);
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class ModuleObject as the method hashPassword() does only exist in the following sub-classes of ModuleObject: memberModel. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
454
		}
455
456
		// If an author is identical to the modifier or history is used, use the logged-in user's information.
457
		if(Context::get('is_logged') && !$manual_updated)
458
		{
459
			if($source_obj->get('member_srl')==$logged_info->member_srl)
460
			{
461
				$obj->member_srl = $logged_info->member_srl;
462
				$obj->user_name = htmlspecialchars_decode($logged_info->user_name);
463
				$obj->nick_name = htmlspecialchars_decode($logged_info->nick_name);
464
				$obj->email_address = $logged_info->email_address;
465
				$obj->homepage = $logged_info->homepage;
466
			}
467
		}
468
469
		// For the document written by logged-in user however no nick_name exists
470 View Code Duplication
		if($source_obj->get('member_srl')&& !$obj->nick_name)
471
		{
472
			$obj->member_srl = $source_obj->get('member_srl');
473
			$obj->user_name = $source_obj->get('user_name');
474
			$obj->nick_name = $source_obj->get('nick_name');
475
			$obj->email_address = $source_obj->get('email_address');
476
			$obj->homepage = $source_obj->get('homepage');
477
		}
478
		// If the tile is empty, extract string from the contents.
479
		$obj->title = htmlspecialchars($obj->title, ENT_COMPAT | ENT_HTML401, 'UTF-8', false);
480
		settype($obj->title, "string");
481 View Code Duplication
		if($obj->title == '') $obj->title = cut_str(strip_tags($obj->content),20,'...');
482
		// If no tile extracted from the contents, leave it untitled.
483
		if($obj->title == '') $obj->title = 'Untitled';
484
		// Remove XE's own tags from the contents.
485
		$obj->content = preg_replace('!<\!--(Before|After)(Document|Comment)\(([0-9]+),([0-9]+)\)-->!is', '', $obj->content);
486 View Code Duplication
		if(Mobile::isFromMobilePhone() && $obj->use_editor != 'Y')
487
		{
488
			if($obj->use_html != 'Y')
489
			{
490
				$obj->content = htmlspecialchars($obj->content, ENT_COMPAT | ENT_HTML401, 'UTF-8', false);
491
			}
492
			$obj->content = nl2br($obj->content);
493
		}
494
		// Change not extra vars but language code of the original document if document's lang_code is different from author's setting.
495
		if($source_obj->get('lang_code') != Context::getLangType())
496
		{
497
			// Change not extra vars but language code of the original document if document's lang_code doesn't exist.
498
			if(!$source_obj->get('lang_code'))
499
			{
500
				$lang_code_args->document_srl = $source_obj->get('document_srl');
0 ignored issues
show
Bug introduced by
The variable $lang_code_args does not exist. Did you forget to declare it?

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

Loading history...
501
				$lang_code_args->lang_code = Context::getLangType();
502
				$output = executeQuery('document.updateDocumentsLangCode', $lang_code_args);
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...
503
			}
504
			else
505
			{
506
				$extra_content = new stdClass;
507
				$extra_content->title = $obj->title;
508
				$extra_content->content = $obj->content;
509
510
				$document_args = new stdClass;
511
				$document_args->document_srl = $source_obj->get('document_srl');
512
				$document_output = executeQuery('document.getDocument', $document_args);
513
				$obj->title = $document_output->data->title;
514
				$obj->content = $document_output->data->content;
515
			}
516
		}
517
		// Remove iframe and script if not a top adminisrator in the session.
518
		if($logged_info->is_admin != 'Y')
519
		{
520
			$obj->content = removeHackTag($obj->content);
521
		}
522
		// if temporary document, regdate is now setting
523
		if($source_obj->get('status') == $this->getConfigStatus('temp')) $obj->regdate = date('YmdHis');
524
525
		// Insert data into the DB
526
		$output = executeQuery('document.updateDocument', $obj);
527
		if(!$output->toBool())
528
		{
529
			$oDB->rollback();
530
			return $output;
531
		}
532
		// Remove all extra variables
533
		if(Context::get('act')!='procFileDelete')
534
		{
535
			$this->deleteDocumentExtraVars($source_obj->get('module_srl'), $obj->document_srl, null, Context::getLangType());
536
			// Insert extra variables if the document successfully inserted.
537
			$extra_keys = $oDocumentModel->getExtraKeys($obj->module_srl);
538 View Code Duplication
			if(count($extra_keys))
539
			{
540
				foreach($extra_keys as $idx => $extra_item)
541
				{
542
					$value = NULL;
543
					if(isset($obj->{'extra_vars'.$idx}))
544
					{
545
						$tmp = $obj->{'extra_vars'.$idx};
546
						if(is_array($tmp))
547
							$value = implode('|@|', $tmp);
548
						else
549
							$value = trim($tmp);
550
					}
551
					else if(isset($obj->{$extra_item->name})) $value = trim($obj->{$extra_item->name});
552
					if($value == NULL) continue;
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $value of type string|null against null; this is ambiguous if the string can be empty. Consider using a strict comparison === instead.
Loading history...
553
					$this->insertDocumentExtraVar($obj->module_srl, $obj->document_srl, $idx, $value, $extra_item->eid);
554
				}
555
			}
556
			// Inert extra vars for multi-language support of title and contents.
557 View Code Duplication
			if($extra_content->title) $this->insertDocumentExtraVar($obj->module_srl, $obj->document_srl, -1, $extra_content->title, 'title_'.Context::getLangType());
0 ignored issues
show
Bug introduced by
The variable $extra_content 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...
558 View Code Duplication
			if($extra_content->content) $this->insertDocumentExtraVar($obj->module_srl, $obj->document_srl, -2, $extra_content->content, 'content_'.Context::getLangType());
559
		}
560
		// Update the category if the category_srl exists.
561
		if($source_obj->get('category_srl') != $obj->category_srl || $source_obj->get('module_srl') == $logged_info->member_srl)
562
		{
563
			if($source_obj->get('category_srl') != $obj->category_srl) $this->updateCategoryCount($obj->module_srl, $source_obj->get('category_srl'));
564
			if($obj->category_srl) $this->updateCategoryCount($obj->module_srl, $obj->category_srl);
565
		}
566
		// Call a trigger (after)
567 View Code Duplication
		if($output->toBool())
568
		{
569
			$trigger_output = ModuleHandler::triggerCall('document.updateDocument', 'after', $obj);
570
			if(!$trigger_output->toBool())
571
			{
572
				$oDB->rollback();
573
				return $trigger_output;
574
			}
575
		}
576
577
		// commit
578
		$oDB->commit();
579
		// Remove the thumbnail file
580
		FileHandler::removeDir(sprintf('files/thumbnails/%s',getNumberingPath($obj->document_srl, 3)));
581
582
		$output->add('document_srl',$obj->document_srl);
583
		//remove from cache
584
		$oCacheHandler = CacheHandler::getInstance('object');
585 View Code Duplication
		if($oCacheHandler->isSupport())
586
		{
587
			//remove document item from cache
588
			$cache_key = 'document_item:'. getNumberingPath($obj->document_srl) . $obj->document_srl;
589
			$oCacheHandler->delete($cache_key);
590
		}
591
592
		return $output;
593
	}
594
595
	/**
596
	 * Deleting Documents
597
	 * @param int $document_srl
598
	 * @param bool $is_admin
599
	 * @param bool $isEmptyTrash
600
	 * @param documentItem $oDocument
601
	 * @return object
602
	 */
603
	function deleteDocument($document_srl, $is_admin = false, $isEmptyTrash = false, $oDocument = null)
604
	{
605
		// Call a trigger (before)
606
		$trigger_obj = new stdClass();
607
		$trigger_obj->document_srl = $document_srl;
608
		$output = ModuleHandler::triggerCall('document.deleteDocument', 'before', $trigger_obj);
609
		if(!$output->toBool()) return $output;
610
611
		// begin transaction
612
		$oDB = &DB::getInstance();
613
		$oDB->begin();
614
615
		if(!$isEmptyTrash)
616
		{
617
			// get model object of the document
618
			$oDocumentModel = getModel('document');
619
			// Check if the documnet exists
620
			$oDocument = $oDocumentModel->getDocument($document_srl, $is_admin);
621
		}
622
		else if($isEmptyTrash && $oDocument == null) return new BaseObject(-1, 'document is not exists');
623
624
		if(!$oDocument->isExists() || $oDocument->document_srl != $document_srl) return new BaseObject(-1, 'msg_invalid_document');
625
		// Check if a permossion is granted
626
		if(!$oDocument->isGranted()) return new BaseObject(-1, 'msg_not_permitted');
627
628
		//if empty trash, document already deleted, therefore document not delete
629
		$args = new stdClass();
630
		$args->document_srl = $document_srl;
631
		if(!$isEmptyTrash)
632
		{
633
			// Delete the document
634
			$output = executeQuery('document.deleteDocument', $args);
635
			if(!$output->toBool())
636
			{
637
				$oDB->rollback();
638
				return $output;
639
			}
640
		}
641
642
		$this->deleteDocumentAliasByDocument($document_srl);
643
644
		$this->deleteDocumentHistory(null, $document_srl, null);
645
		// Update category information if the category_srl exists.
646
		if($oDocument->get('category_srl')) $this->updateCategoryCount($oDocument->get('module_srl'),$oDocument->get('category_srl'));
647
		// Delete a declared list
648
		executeQuery('document.deleteDeclared', $args);
649
		// Delete extra variable
650
		$this->deleteDocumentExtraVars($oDocument->get('module_srl'), $oDocument->document_srl);
651
652
		//this
653
		// Call a trigger (after)
654 View Code Duplication
		if($output->toBool())
655
		{
656
			$trigger_obj = $oDocument->getObjectVars();
657
			$trigger_output = ModuleHandler::triggerCall('document.deleteDocument', 'after', $trigger_obj);
658
			if(!$trigger_output->toBool())
659
			{
660
				$oDB->rollback();
661
				return $trigger_output;
662
			}
663
		}
664
		// declared document, log delete
665
		$this->_deleteDeclaredDocuments($args);
0 ignored issues
show
Documentation introduced by
$args is of type object<stdClass>, 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...
666
		$this->_deleteDocumentReadedLog($args);
0 ignored issues
show
Documentation introduced by
$args is of type object<stdClass>, 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...
667
		$this->_deleteDocumentVotedLog($args);
0 ignored issues
show
Documentation introduced by
$args is of type object<stdClass>, 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...
668
669
		// Remove the thumbnail file
670
		FileHandler::removeDir(sprintf('files/thumbnails/%s',getNumberingPath($document_srl, 3)));
671
672
		// commit
673
		$oDB->commit();
674
675
		//remove from cache
676
		$oCacheHandler = CacheHandler::getInstance('object');
677
		if($oCacheHandler->isSupport())
678
		{
679
			$cache_key = 'document_item:'. getNumberingPath($document_srl) . $document_srl;
680
			$oCacheHandler->delete($cache_key);
681
		}
682
683
		return $output;
684
	}
685
686
	/**
687
	 * Delete declared document, log
688
	 * @param string $documentSrls (ex: 1, 2,56, 88)
689
	 * @return void
690
	 */
691
	function _deleteDeclaredDocuments($documentSrls)
692
	{
693
		executeQuery('document.deleteDeclaredDocuments', $documentSrls);
0 ignored issues
show
Documentation introduced by
$documentSrls is of type string, but the function expects a object|null.

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...
694
		executeQuery('document.deleteDocumentDeclaredLog', $documentSrls);
0 ignored issues
show
Documentation introduced by
$documentSrls is of type string, but the function expects a object|null.

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...
695
	}
696
697
	/**
698
	 * Delete readed log
699
	 * @param string $documentSrls (ex: 1, 2,56, 88)
700
	 * @return void
701
	 */
702
	function _deleteDocumentReadedLog($documentSrls)
703
	{
704
		executeQuery('document.deleteDocumentReadedLog', $documentSrls);
0 ignored issues
show
Documentation introduced by
$documentSrls is of type string, but the function expects a object|null.

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...
705
	}
706
707
	/**
708
	 * Delete voted log
709
	 * @param string $documentSrls (ex: 1, 2,56, 88)
710
	 * @return void
711
	 */
712
	function _deleteDocumentVotedLog($documentSrls)
713
	{
714
		executeQuery('document.deleteDocumentVotedLog', $documentSrls);
0 ignored issues
show
Documentation introduced by
$documentSrls is of type string, but the function expects a object|null.

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...
715
	}
716
717
	/**
718
	 * Move the doc into the trash
719
	 * @param object $obj
720
	 * @return object
721
	 */
722
	function moveDocumentToTrash($obj)
723
	{
724
		$trash_args = new stdClass();
725
		// Get trash_srl if a given trash_srl doesn't exist
726
		if(!$obj->trash_srl) $trash_args->trash_srl = getNextSequence();
727
		else $trash_args->trash_srl = $obj->trash_srl;
728
		// Get its module_srl which the document belongs to
729
		$oDocumentModel = getModel('document');
730
		$oDocument = $oDocumentModel->getDocument($obj->document_srl);
731
732
		$trash_args->module_srl = $oDocument->get('module_srl');
733
		$obj->module_srl = $oDocument->get('module_srl');
734
		// Cannot throw data from the trash to the trash
735
		if($trash_args->module_srl == 0) return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by documentController::moveDocumentToTrash of type object.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
736
		// Data setting
737
		$trash_args->document_srl = $obj->document_srl;
738
		$trash_args->description = $obj->description;
739
		// Insert member's information only if the member is logged-in and not manually registered.
740
		if(Context::get('is_logged')&&!$manual_inserted)
0 ignored issues
show
Bug introduced by
The variable $manual_inserted does not exist. Did you forget to declare it?

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

Loading history...
741
		{
742
			$logged_info = Context::get('logged_info');
743
			$trash_args->member_srl = $logged_info->member_srl;
744
745
			// user_id, user_name and nick_name already encoded
746
			$trash_args->user_id = htmlspecialchars_decode($logged_info->user_id);
747
			$trash_args->user_name = htmlspecialchars_decode($logged_info->user_name);
748
			$trash_args->nick_name = htmlspecialchars_decode($logged_info->nick_name);
749
		}
750
		// Date setting for updating documents
751
		$document_args = new stdClass;
752
		$document_args->module_srl = 0;
753
		$document_args->document_srl = $obj->document_srl;
754
755
		// begin transaction
756
		$oDB = &DB::getInstance();
757
		$oDB->begin();
758
759
		/*$output = executeQuery('document.insertTrash', $trash_args);
760
		  if (!$output->toBool()) {
761
		  $oDB->rollback();
762
		  return $output;
763
		  }*/
764
765
		// new trash module
766
		require_once(_XE_PATH_.'modules/trash/model/TrashVO.php');
767
		$oTrashVO = new TrashVO();
768
		$oTrashVO->setTrashSrl(getNextSequence());
769
		$oTrashVO->setTitle($oDocument->variables['title']);
770
		$oTrashVO->setOriginModule('document');
771
		$oTrashVO->setSerializedObject(serialize($oDocument->variables));
772
		$oTrashVO->setDescription($obj->description);
773
774
		$oTrashAdminController = getAdminController('trash');
775
		$output = $oTrashAdminController->insertTrash($oTrashVO);
776
		if(!$output->toBool())
777
		{
778
			$oDB->rollback();
779
			return $output;
780
		}
781
782
		$output = executeQuery('document.deleteDocument', $trash_args);
783
		if(!$output->toBool())
784
		{
785
			$oDB->rollback();
786
			return $output;
787
		}
788
789
		/*$output = executeQuery('document.updateDocument', $document_args);
790
		  if (!$output->toBool()) {
791
		  $oDB->rollback();
792
		  return $output;
793
		  }*/
794
795
		// update category
796
		if($oDocument->get('category_srl')) $this->updateCategoryCount($oDocument->get('module_srl'),$oDocument->get('category_srl'));
797
798
		// remove thumbnails
799
		FileHandler::removeDir(sprintf('files/thumbnails/%s',getNumberingPath($obj->document_srl, 3)));
800
		// Set the attachment to be invalid state
801 View Code Duplication
		if($oDocument->hasUploadedFiles())
802
		{
803
			$args = new stdClass();
804
			$args->upload_target_srl = $oDocument->document_srl;
805
			$args->isvalid = 'N';
806
			executeQuery('file.updateFileValid', $args);
807
		}
808
		// Call a trigger (after)
809 View Code Duplication
		if($output->toBool())
810
		{
811
			$trigger_output = ModuleHandler::triggerCall('document.moveDocumentToTrash', 'after', $obj);
812
			if(!$trigger_output->toBool())
813
			{
814
				$oDB->rollback();
815
				return $trigger_output;
816
			}
817
		}
818
819
		// commit
820
		$oDB->commit();
821
822
		// Clear cache
823
		$oCacheHandler = CacheHandler::getInstance('object');
824 View Code Duplication
		if($oCacheHandler->isSupport())
825
		{
826
			$cache_key = 'document_item:'. getNumberingPath($oDocument->document_srl) . $oDocument->document_srl;
827
			$oCacheHandler->delete($cache_key);
828
		}
829
830
		return $output;
831
	}
832
833
	/**
834
	 * Update read counts of the document
835
	 * @param documentItem $oDocument
836
	 * @return bool|void
837
	 */
838
	function updateReadedCount(&$oDocument)
839
	{
840
		// Pass if Crawler access
841
		if(isCrawler()) return false;
842
		
843
		$document_srl = $oDocument->document_srl;
844
		$member_srl = $oDocument->get('member_srl');
845
		$logged_info = Context::get('logged_info');
846
847
		// Call a trigger when the read count is updated (before)
848
		$trigger_output = ModuleHandler::triggerCall('document.updateReadedCount', 'before', $oDocument);
849
		if(!$trigger_output->toBool()) return $trigger_output;
850
851
		// Pass if read count is increaded on the session information
852
		if($_SESSION['readed_document'][$document_srl]) return false;
853
854
		// Pass if the author's IP address is as same as visitor's.
855
		if($oDocument->get('ipaddress') == $_SERVER['REMOTE_ADDR'])
856
		{
857
			$_SESSION['readed_document'][$document_srl] = true;
858
			return false;
859
		}
860
		// Pass ater registering sesscion if the author is a member and has same information as the currently logged-in user.
861
		if($member_srl && $logged_info->member_srl == $member_srl)
862
		{
863
			$_SESSION['readed_document'][$document_srl] = true;
864
			return false;
865
		}
866
867
		$oDB = DB::getInstance();
868
		$oDB->begin();
869
870
		// Update read counts
871
		$args = new stdClass;
872
		$args->document_srl = $document_srl;
873
		$output = executeQuery('document.updateReadedCount', $args);
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...
874
875
		// Call a trigger when the read count is updated (after)
876
		$trigger_output = ModuleHandler::triggerCall('document.updateReadedCount', 'after', $oDocument);
877
		if(!$trigger_output->toBool())
878
		{
879
			$oDB->rollback();
880
			return $trigger_output;
881
		}
882
883
		$oDB->commit();
884
885
		$oCacheHandler = CacheHandler::getInstance('object');
886
		if($oCacheHandler->isSupport())
887
		{
888
			//remove document item from cache
889
			$cache_key = 'document_item:'. getNumberingPath($document_srl) . $document_srl;
890
			$oCacheHandler->delete($cache_key);
891
		}
892
893
		// Register session
894
		if(!$_SESSION['banned_document'][$document_srl]) 
895
		{
896
			$_SESSION['readed_document'][$document_srl] = true;
897
		}
898
899
		return TRUE;
900
	}
901
902
	/**
903
	 * Insert extra variables into the document table
904
	 * @param int $module_srl
905
	 * @param int $var_idx
906
	 * @param string $var_name
907
	 * @param string $var_type
908
	 * @param string $var_is_required
909
	 * @param string $var_search
910
	 * @param string $var_default
911
	 * @param string $var_desc
912
	 * @param int $eid
913
	 * @return object
914
	 */
915
	function insertDocumentExtraKey($module_srl, $var_idx, $var_name, $var_type, $var_is_required = 'N', $var_search = 'N', $var_default = '', $var_desc = '', $eid)
916
	{
917
		if(!$module_srl || !$var_idx || !$var_name || !$var_type || !$eid) return new BaseObject(-1,'msg_invalid_request');
918
919
		$obj = new stdClass();
920
		$obj->module_srl = $module_srl;
921
		$obj->var_idx = $var_idx;
922
		$obj->var_name = $var_name;
923
		$obj->var_type = $var_type;
924
		$obj->var_is_required = $var_is_required=='Y'?'Y':'N';
925
		$obj->var_search = $var_search=='Y'?'Y':'N';
926
		$obj->var_default = $var_default;
927
		$obj->var_desc = $var_desc;
928
		$obj->eid = $eid;
929
930
		$output = executeQuery('document.getDocumentExtraKeys', $obj);
931
		if(!$output->data)
932
		{
933
			$output = executeQuery('document.insertDocumentExtraKey', $obj);
934
		}
935
		else
936
		{
937
			$output = executeQuery('document.updateDocumentExtraKey', $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...
938
			// Update the extra var(eid)
939
			$output = executeQuery('document.updateDocumentExtraVar', $obj);
940
		}
941
942
		$oCacheHandler = CacheHandler::getInstance('object', NULL, TRUE);
943
		if($oCacheHandler->isSupport())
944
		{
945
			$object_key = 'module_document_extra_keys:'.$module_srl;
946
			$cache_key = $oCacheHandler->getGroupKey('site_and_module', $object_key);
947
			$oCacheHandler->delete($cache_key);
948
		}
949
950
		return $output;
951
	}
952
953
	/**
954
	 * Remove the extra variables of the documents
955
	 * @param int $module_srl
956
	 * @param int $var_idx
957
	 * @return BaseObject
958
	 */
959
	function deleteDocumentExtraKeys($module_srl, $var_idx = null)
960
	{
961
		if(!$module_srl) return new BaseObject(-1,'msg_invalid_request');
962
		$obj = new stdClass();
963
		$obj->module_srl = $module_srl;
964
		if(!is_null($var_idx)) $obj->var_idx = $var_idx;
965
966
		$oDB = DB::getInstance();
967
		$oDB->begin();
968
969
		$output = $oDB->executeQuery('document.deleteDocumentExtraKeys', $obj);
970
		if(!$output->toBool())
971
		{
972
			$oDB->rollback();
973
			return $output;
974
		}
975
976
		if($var_idx != NULL)
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing $var_idx of type integer|null against null; this is ambiguous if the integer can be zero. Consider using a strict comparison !== instead.
Loading history...
977
		{
978
			$output = $oDB->executeQuery('document.updateDocumentExtraKeyIdxOrder', $obj);
979
			if(!$output->toBool())
980
			{
981
				$oDB->rollback();
982
				return $output;
983
			}
984
		}
985
986
		$output =  executeQuery('document.deleteDocumentExtraVars', $obj);
987
		if(!$output->toBool())
988
		{
989
			$oDB->rollback();
990
			return $output;
991
		}
992
993
		if($var_idx != NULL)
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing $var_idx of type integer|null against null; this is ambiguous if the integer can be zero. Consider using a strict comparison !== instead.
Loading history...
994
		{
995
			$output = $oDB->executeQuery('document.updateDocumentExtraVarIdxOrder', $obj);
996
			if(!$output->toBool())
997
			{
998
				$oDB->rollback();
999
				return $output;
1000
			}
1001
		}
1002
1003
		$oDB->commit();
1004
1005
		$oCacheHandler = CacheHandler::getInstance('object', NULL, TRUE);
1006
		if($oCacheHandler->isSupport())
1007
		{
1008
			$object_key = 'module_document_extra_keys:'.$module_srl;
1009
			$cache_key = $oCacheHandler->getGroupKey('site_and_module', $object_key);
1010
			$oCacheHandler->delete($cache_key);
1011
		}
1012
1013
		return new BaseObject();
1014
	}
1015
1016
	/**
1017
	 * Insert extra vaiable to the documents table
1018
	 * @param int $module_srl
1019
	 * @param int $document_srl
1020
	 * @param int $var_idx
1021
	 * @param mixed $value
1022
	 * @param int $eid
1023
	 * @param string $lang_code
1024
	 * @return BaseObject|void
1025
	 */
1026
	function insertDocumentExtraVar($module_srl, $document_srl, $var_idx, $value, $eid = null, $lang_code = '')
1027
	{
1028
		if(!$module_srl || !$document_srl || !$var_idx || !isset($value)) return new BaseObject(-1,'msg_invalid_request');
1029
		if(!$lang_code) $lang_code = Context::getLangType();
1030
1031
		$obj = new stdClass;
1032
		$obj->module_srl = $module_srl;
1033
		$obj->document_srl = $document_srl;
1034
		$obj->var_idx = $var_idx;
1035
		$obj->value = $value;
1036
		$obj->lang_code = $lang_code;
1037
		$obj->eid = $eid;
1038
1039
		executeQuery('document.insertDocumentExtraVar', $obj);
1040
	}
1041
1042
	/**
1043
	 * Remove values of extra variable from the document
1044
	 * @param int $module_srl
1045
	 * @param int $document_srl
1046
	 * @param int $var_idx
1047
	 * @param string $lang_code
1048
	 * @param int $eid
1049
	 * @return $output
0 ignored issues
show
Documentation introduced by
The doc-type $output could not be parsed: Unknown type name "$output" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
1050
	 */
1051
	function deleteDocumentExtraVars($module_srl, $document_srl = null, $var_idx = null, $lang_code = null, $eid = null)
1052
	{
1053
		$obj = new stdClass();
1054
		$obj->module_srl = $module_srl;
1055
		if(!is_null($document_srl)) $obj->document_srl = $document_srl;
1056
		if(!is_null($var_idx)) $obj->var_idx = $var_idx;
1057
		if(!is_null($lang_code)) $obj->lang_code = $lang_code;
1058
		if(!is_null($eid)) $obj->eid = $eid;
1059
		$output = executeQuery('document.deleteDocumentExtraVars', $obj);
1060
		return $output;
1061
	}
1062
1063
1064
	/**
1065
	 * Increase the number of vote-up of the document
1066
	 * @param int $document_srl
1067
	 * @param int $point
1068
	 * @return BaseObject
1069
	 */
1070
	function updateVotedCount($document_srl, $point = 1)
1071
	{
1072
		if($point > 0) $failed_voted = 'failed_voted';
1073
		else $failed_voted = 'failed_blamed';
1074
		// Return fail if session already has information about votes
1075
		if($_SESSION['voted_document'][$document_srl])
1076
		{
1077
			return new BaseObject(-1, $failed_voted);
1078
		}
1079
		// Get the original document
1080
		$oDocumentModel = getModel('document');
1081
		$oDocument = $oDocumentModel->getDocument($document_srl, false, false);
1082
		// Pass if the author's IP address is as same as visitor's.
1083
		if($oDocument->get('ipaddress') == $_SERVER['REMOTE_ADDR'])
1084
		{
1085
			$_SESSION['voted_document'][$document_srl] = true;
1086
			return new BaseObject(-1, $failed_voted);
1087
		}
1088
1089
		// Create a member model object
1090
		$oMemberModel = getModel('member');
1091
		$member_srl = $oMemberModel->getLoggedMemberSrl();
1092
1093
		// Check if document's author is a member.
1094
		if($oDocument->get('member_srl'))
1095
		{
1096
			// Pass after registering a session if author's information is same as the currently logged-in user's.
1097
			if($member_srl && $member_srl == abs($oDocument->get('member_srl')))
1098
			{
1099
				$_SESSION['voted_document'][$document_srl] = true;
1100
				return new BaseObject(-1, $failed_voted);
1101
			}
1102
		}
1103
1104
		// Use member_srl for logged-in members and IP address for non-members.
1105
		$args = new stdClass;
1106
		if($member_srl)
1107
		{
1108
			$args->member_srl = $member_srl;
1109
		}
1110
		else
1111
		{
1112
			$args->ipaddress = $_SERVER['REMOTE_ADDR'];
1113
		}
1114
		$args->document_srl = $document_srl;
1115
		$output = executeQuery('document.getDocumentVotedLogInfo', $args);
1116
		// Pass after registering a session if log information has vote-up logs
1117
		if($output->data->count)
1118
		{
1119
			$_SESSION['voted_document'][$document_srl] = true;
1120
			return new BaseObject(-1, $failed_voted);
1121
		}
1122
1123
		// begin transaction
1124
		$oDB = DB::getInstance();
1125
		$oDB->begin();
1126
1127
		// Update the voted count
1128 View Code Duplication
		if($point < 0)
1129
		{
1130
			$args->blamed_count = $oDocument->get('blamed_count') + $point;
1131
			$output = executeQuery('document.updateBlamedCount', $args);
1132
		}
1133
		else
1134
		{
1135
			$args->voted_count = $oDocument->get('voted_count') + $point;
1136
			$output = executeQuery('document.updateVotedCount', $args);
1137
		}
1138
		if(!$output->toBool()) return $output;
1139
		// Leave logs
1140
		$args->point = $point;
1141
		$output = executeQuery('document.insertDocumentVotedLog', $args);
1142
		if(!$output->toBool()) return $output;
1143
1144
		$obj = new stdClass;
1145
		$obj->member_srl = $oDocument->get('member_srl');
1146
		$obj->module_srl = $oDocument->get('module_srl');
1147
		$obj->document_srl = $oDocument->get('document_srl');
1148
		$obj->update_target = ($point < 0) ? 'blamed_count' : 'voted_count';
1149
		$obj->point = $point;
1150
		$obj->before_point = ($point < 0) ? $oDocument->get('blamed_count') : $oDocument->get('voted_count');
1151
		$obj->after_point = ($point < 0) ? $args->blamed_count : $args->voted_count;
1152
		$trigger_output = ModuleHandler::triggerCall('document.updateVotedCount', 'after', $obj);
1153
		if(!$trigger_output->toBool())
1154
		{
1155
			$oDB->rollback();
1156
			return $trigger_output;
1157
		}
1158
1159
		$oDB->commit();
1160
1161
		$oCacheHandler = CacheHandler::getInstance('object');
1162
		if($oCacheHandler->isSupport())
1163
		{
1164
			//remove document item from cache
1165
			$cache_key = 'document_item:'. getNumberingPath($document_srl) . $document_srl;
1166
			$oCacheHandler->delete($cache_key);
1167
		}
1168
1169
		// Leave in the session information
1170
		$_SESSION['voted_document'][$document_srl] = true;
1171
1172
		// Return result
1173
		$output = new BaseObject();
1174
		if($point > 0)
1175
		{
1176
			$output->setMessage('success_voted');
1177
			$output->add('voted_count', $obj->after_point);
1178
		}
1179
		else
1180
		{
1181
			$output->setMessage('success_blamed');
1182
			$output->add('blamed_count', $obj->after_point);
1183
		}
1184
		
1185
		return $output;
1186
	}
1187
1188
	/**
1189
	 * Report posts
1190
	 * @param int $document_srl
1191
	 * @return void|BaseObject
1192
	 */
1193
	function declaredDocument($document_srl)
1194
	{
1195
		// Fail if session information already has a reported document
1196
		if($_SESSION['declared_document'][$document_srl]) return new BaseObject(-1, 'failed_declared');
1197
1198
		// Check if previously reported
1199
		$args = new stdClass();
1200
		$args->document_srl = $document_srl;
1201
		$output = executeQuery('document.getDeclaredDocument', $args);
1202
		if(!$output->toBool()) return $output;
1203
1204
		$declared_count = ($output->data->declared_count) ? $output->data->declared_count : 0;
1205
1206
		$trigger_obj = new stdClass();
1207
		$trigger_obj->document_srl = $document_srl;
1208
		$trigger_obj->declared_count = $declared_count;
1209
1210
		// Call a trigger (before)
1211
		$trigger_output = ModuleHandler::triggerCall('document.declaredDocument', 'before', $trigger_obj);
1212
		if(!$trigger_output->toBool())
1213
		{
1214
			return $trigger_output;
1215
		}
1216
1217
		// Get the original document
1218
		$oDocumentModel = getModel('document');
1219
		$oDocument = $oDocumentModel->getDocument($document_srl, false, false);
1220
1221
		// Pass if the author's IP address is as same as visitor's.
1222 View Code Duplication
		if($oDocument->get('ipaddress') == $_SERVER['REMOTE_ADDR']) {
1223
			$_SESSION['declared_document'][$document_srl] = true;
1224
			return new BaseObject(-1, 'failed_declared');
1225
		}
1226
1227
		// Check if document's author is a member.
1228 View Code Duplication
		if($oDocument->get('member_srl'))
1229
		{
1230
			// Create a member model object
1231
			$oMemberModel = getModel('member');
1232
			$member_srl = $oMemberModel->getLoggedMemberSrl();
1233
			// Pass after registering a session if author's information is same as the currently logged-in user's.
1234
			if($member_srl && $member_srl == abs($oDocument->get('member_srl')))
1235
			{
1236
				$_SESSION['declared_document'][$document_srl] = true;
1237
				return new BaseObject(-1, 'failed_declared');
1238
			}
1239
		}
1240
1241
		// Use member_srl for logged-in members and IP address for non-members.
1242
		$args = new stdClass;
1243
		if($member_srl)
1244
		{
1245
			$args->member_srl = $member_srl;
0 ignored issues
show
Bug introduced by
The variable $member_srl 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...
1246
		}
1247
		else
1248
		{
1249
			$args->ipaddress = $_SERVER['REMOTE_ADDR'];
1250
		}
1251
1252
		$args->document_srl = $document_srl;
1253
		$output = executeQuery('document.getDocumentDeclaredLogInfo', $args);
1254
1255
		// Pass after registering a sesson if reported/declared documents are in the logs.
1256
		if($output->data->count)
1257
		{
1258
			$_SESSION['declared_document'][$document_srl] = true;
1259
			return new BaseObject(-1, 'failed_declared');
1260
		}
1261
1262
		// begin transaction
1263
		$oDB = &DB::getInstance();
1264
		$oDB->begin();
1265
1266
		// Add the declared document
1267
		if($declared_count > 0) $output = executeQuery('document.updateDeclaredDocument', $args);
1268
		else $output = executeQuery('document.insertDeclaredDocument', $args);
1269
		if(!$output->toBool()) return $output;
1270
		// Leave logs
1271
		$output = executeQuery('document.insertDocumentDeclaredLog', $args);
1272
		if(!$output->toBool())
1273
		{
1274
			$oDB->rollback();
1275
			return $output;
1276
		}
1277
1278
		$this->add('declared_count', $declared_count+1);
1279
1280
		// Call a trigger (after)
1281
		$trigger_obj->declared_count = $declared_count + 1;
1282
		$trigger_output = ModuleHandler::triggerCall('document.declaredDocument', 'after', $trigger_obj);
1283
		if(!$trigger_output->toBool())
1284
		{
1285
			$oDB->rollback();
1286
			return $trigger_output;
1287
		}
1288
1289
		// commit
1290
		$oDB->commit();
1291
1292
		// Leave in the session information
1293
		$_SESSION['declared_document'][$document_srl] = true;
1294
1295
		$this->setMessage('success_declared');
1296
	}
1297
1298
	/**
1299
	 * Increase the number of comments in the document
1300
	 * Update modified date, modifier, and order with increasing comment count
1301
	 * @param int $document_srl
1302
	 * @param int $comment_count
1303
	 * @param string $last_updater
1304
	 * @param bool $comment_inserted
1305
	 * @return object
1306
	 */
1307
	function updateCommentCount($document_srl, $comment_count, $last_updater, $comment_inserted = false)
1308
	{
1309
		$args = new stdClass();
1310
		$args->document_srl = $document_srl;
1311
		$args->comment_count = $comment_count;
1312
1313
		if($comment_inserted)
1314
		{
1315
			$args->update_order = -1*getNextSequence();
1316
			$args->last_updater = $last_updater;
1317
1318
			$oCacheHandler = CacheHandler::getInstance('object');
1319
			if($oCacheHandler->isSupport())
1320
			{
1321
				//remove document item from cache
1322
				$cache_key = 'document_item:'. getNumberingPath($document_srl) . $document_srl;
1323
				$oCacheHandler->delete($cache_key);
1324
			}
1325
		}
1326
1327
		return executeQuery('document.updateCommentCount', $args);
1328
	}
1329
1330
	/**
1331
	 * Increase trackback count of the document
1332
	 * @param int $document_srl
1333
	 * @param int $trackback_count
1334
	 * @return object
1335
	 */
1336
	function updateTrackbackCount($document_srl, $trackback_count)
1337
	{
1338
		$args = new stdClass;
1339
		$args->document_srl = $document_srl;
1340
		$args->trackback_count = $trackback_count;
1341
1342
		$oCacheHandler = CacheHandler::getInstance('object');
1343
		if($oCacheHandler->isSupport())
1344
		{
1345
			//remove document item from cache
1346
			$cache_key = 'document_item:'. getNumberingPath($document_srl) . $document_srl;
1347
			$oCacheHandler->delete($cache_key);
1348
		}
1349
1350
		return executeQuery('document.updateTrackbackCount', $args);
1351
	}
1352
1353
	/**
1354
	 * Add a category
1355
	 * @param object $obj
1356
	 * @return object
1357
	 */
1358
	function insertCategory($obj)
1359
	{
1360
		// Sort the order to display if a child category is added
1361
		if($obj->parent_srl)
1362
		{
1363
			// Get its parent category
1364
			$oDocumentModel = getModel('document');
1365
			$parent_category = $oDocumentModel->getCategory($obj->parent_srl);
1366
			$obj->list_order = $parent_category->list_order;
1367
			$this->updateCategoryListOrder($parent_category->module_srl, $parent_category->list_order+1);
1368
			if(!$obj->category_srl) $obj->category_srl = getNextSequence();
1369
		}
1370
		else
1371
		{
1372
			$obj->list_order = $obj->category_srl = getNextSequence();
1373
		}
1374
1375
		$output = executeQuery('document.insertCategory', $obj);
1376
		if($output->toBool())
1377
		{
1378
			$output->add('category_srl', $obj->category_srl);
1379
			$this->makeCategoryFile($obj->module_srl);
1380
		}
1381
1382
		return $output;
1383
	}
1384
1385
	/**
1386
	 * Increase list_count from a specific category
1387
	 * @param int $module_srl
1388
	 * @param int $list_order
1389
	 * @return object
1390
	 */
1391
	function updateCategoryListOrder($module_srl, $list_order)
1392
	{
1393
		$args = new stdClass;
1394
		$args->module_srl = $module_srl;
1395
		$args->list_order = $list_order;
1396
		return executeQuery('document.updateCategoryOrder', $args);
1397
	}
1398
1399
	/**
1400
	 * Update document_count in the category.
1401
	 * @param int $module_srl
1402
	 * @param int $category_srl
1403
	 * @param int $document_count
1404
	 * @return object
1405
	 */
1406
	function updateCategoryCount($module_srl, $category_srl, $document_count = 0)
1407
	{
1408
		// Create a document model object
1409
		$oDocumentModel = getModel('document');
1410
		if(!$document_count) $document_count = $oDocumentModel->getCategoryDocumentCount($module_srl,$category_srl);
1411
1412
		$args = new stdClass;
1413
		$args->category_srl = $category_srl;
1414
		$args->document_count = $document_count;
1415
		$output = executeQuery('document.updateCategoryCount', $args);
1416
		if($output->toBool()) $this->makeCategoryFile($module_srl);
1417
1418
		return $output;
1419
	}
1420
1421
	/**
1422
	 * Update category information
1423
	 * @param object $obj
1424
	 * @return object
1425
	 */
1426
	function updateCategory($obj)
1427
	{
1428
		$output = executeQuery('document.updateCategory', $obj);
1429
		if($output->toBool()) $this->makeCategoryFile($obj->module_srl);
1430
		return $output;
1431
	}
1432
1433
	/**
1434
	 * Delete a category
1435
	 * @param int $category_srl
1436
	 * @return object
1437
	 */
1438
	function deleteCategory($category_srl)
1439
	{
1440
		$args = new stdClass();
1441
		$args->category_srl = $category_srl;
1442
		$oDocumentModel = getModel('document');
1443
		$category_info = $oDocumentModel->getCategory($category_srl);
1444
		// Display an error that the category cannot be deleted if it has a child
1445
		$output = executeQuery('document.getChildCategoryCount', $args);
1446
		if(!$output->toBool()) return $output;
1447
		if($output->data->count>0) return new BaseObject(-1, 'msg_cannot_delete_for_child');
1448
		// Delete a category information
1449
		$output = executeQuery('document.deleteCategory', $args);
1450
		if(!$output->toBool()) return $output;
1451
1452
		$this->makeCategoryFile($category_info->module_srl);
1453
		// remvove cache
1454
		$oCacheHandler = CacheHandler::getInstance('object');
1455
		if($oCacheHandler->isSupport())
1456
		{
1457
			$page = 0;
1458
			while(true) {
1459
				$args = new stdClass();
1460
				$args->category_srl = $category_srl;
1461
				$args->list_count = 100;
1462
				$args->page = ++$page;
1463
				$output = executeQuery('document.getDocumentList', $args, array('document_srl'));
1464
1465
				if($output->data == array())
1466
					break;
1467
1468
				foreach($output->data as $val)
1469
				{
1470
					//remove document item from cache
1471
					$cache_key = 'document_item:'. getNumberingPath($val->document_srl) . $val->document_srl;
1472
					$oCacheHandler->delete($cache_key);
1473
				}
1474
			}
1475
		}
1476
1477
		// Update category_srl of the documents in the same category to 0
1478
		$args = new stdClass();
1479
		$args->target_category_srl = 0;
1480
		$args->source_category_srl = $category_srl;
1481
		$output = executeQuery('document.updateDocumentCategory', $args);
1482
1483
		return $output;
1484
	}
1485
1486
	/**
1487
	 * Delete all categories in a module
1488
	 * @param int $module_srl
1489
	 * @return object
1490
	 */
1491
	function deleteModuleCategory($module_srl)
1492
	{
1493
		$args = new stdClass();
1494
		$args->module_srl = $module_srl;
1495
		$output = executeQuery('document.deleteModuleCategory', $args);
1496
		return $output;
1497
	}
1498
1499
	/**
1500
	 * Move the category level to higher
1501
	 * @param int $category_srl
1502
	 * @return BaseObject
1503
	 */
1504
	function moveCategoryUp($category_srl)
1505
	{
1506
		$oDocumentModel = getModel('document');
1507
		// Get information of the selected category
1508
		$args = new stdClass;
1509
		$args->category_srl = $category_srl;
1510
		$output = executeQuery('document.getCategory', $args);
1511
1512
		$category = $output->data;
1513
		$list_order = $category->list_order;
1514
		$module_srl = $category->module_srl;
1515
		// Seek a full list of categories
1516
		$category_list = $oDocumentModel->getCategoryList($module_srl);
1517
		$category_srl_list = array_keys($category_list);
1518
		if(count($category_srl_list)<2) return new BaseObject();
1519
1520
		$prev_category = NULL;
1521
		foreach($category_list as $key => $val)
1522
		{
1523
			if($key==$category_srl) break;
1524
			$prev_category = $val;
1525
		}
1526
		// Return if the previous category doesn't exist
1527
		if(!$prev_category) return new BaseObject(-1,Context::getLang('msg_category_not_moved'));
1528
		// Return if the selected category is the top level
1529
		if($category_srl_list[0]==$category_srl) return new BaseObject(-1,Context::getLang('msg_category_not_moved'));
1530
		// Information of the selected category
1531
		$cur_args = new stdClass;
1532
		$cur_args->category_srl = $category_srl;
1533
		$cur_args->list_order = $prev_category->list_order;
1534
		$cur_args->title = $category->title;
1535
		$this->updateCategory($cur_args);
1536
		// Category information
1537
		$prev_args = new stdClass;
1538
		$prev_args->category_srl = $prev_category->category_srl;
1539
		$prev_args->list_order = $list_order;
1540
		$prev_args->title = $prev_category->title;
1541
		$this->updateCategory($prev_args);
1542
1543
		return new BaseObject();
1544
	}
1545
1546
	/**
1547
	 * Move the category down
1548
	 * @param int $category_srl
1549
	 * @return BaseObject
1550
	 */
1551
	function moveCategoryDown($category_srl)
1552
	{
1553
		$oDocumentModel = getModel('document');
1554
		// Get information of the selected category
1555
		$args = new stdClass;
1556
		$args->category_srl = $category_srl;
1557
		$output = executeQuery('document.getCategory', $args);
1558
1559
		$category = $output->data;
1560
		$list_order = $category->list_order;
1561
		$module_srl = $category->module_srl;
1562
		// Seek a full list of categories
1563
		$category_list = $oDocumentModel->getCategoryList($module_srl);
1564
		$category_srl_list = array_keys($category_list);
1565
		if(count($category_srl_list)<2) return new BaseObject();
1566
1567
		for($i=0;$i<count($category_srl_list);$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...
1568
		{
1569
			if($category_srl_list[$i]==$category_srl) break;
1570
		}
1571
1572
		$next_category_srl = $category_srl_list[$i+1];
1573
		if(!$category_list[$next_category_srl]) return new BaseObject(-1,Context::getLang('msg_category_not_moved'));
1574
		$next_category = $category_list[$next_category_srl];
1575
		// Information of the selected category
1576
		$cur_args = new stdClass;
1577
		$cur_args->category_srl = $category_srl;
1578
		$cur_args->list_order = $next_category->list_order;
1579
		$cur_args->title = $category->title;
1580
		$this->updateCategory($cur_args);
1581
		// Category information
1582
		$next_args = new stdClass;
1583
		$next_args->category_srl = $next_category->category_srl;
1584
		$next_args->list_order = $list_order;
1585
		$next_args->title = $next_category->title;
1586
		$this->updateCategory($next_args);
1587
1588
		return new BaseObject();
1589
	}
1590
1591
	/**
1592
	 * Add javascript codes into the header by checking values of document_extra_keys type, required and others
1593
	 * @param int $module_srl
1594
	 * @return void
1595
	 */
1596
	function addXmlJsFilter($module_srl)
1597
	{
1598
		$oDocumentModel = getModel('document');
1599
		$extra_keys = $oDocumentModel->getExtraKeys($module_srl);
1600
		if(!count($extra_keys)) return;
1601
1602
		$js_code = array();
1603
		$js_code[] = '<script>//<![CDATA[';
1604
		$js_code[] = '(function($){';
1605
		$js_code[] = 'var validator = xe.getApp("validator")[0];';
1606
		$js_code[] = 'if(!validator) return false;';
1607
1608
		$logged_info = Context::get('logged_info');
0 ignored issues
show
Unused Code introduced by
$logged_info 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...
1609
1610
		foreach($extra_keys as $idx => $val)
1611
		{
1612
			$idx = $val->idx;
1613
			if($val->type == 'kr_zip')
1614
			{
1615
				$idx .= '[]';
1616
			}
1617
			$name = str_ireplace(array('<script', '</script'), array('<scr" + "ipt', '</scr" + "ipt'), $val->name);
1618
			$js_code[] = sprintf('validator.cast("ADD_MESSAGE", ["extra_vars%s","%s"]);', $idx, $name);
1619
			if($val->is_required == 'Y') $js_code[] = sprintf('validator.cast("ADD_EXTRA_FIELD", ["extra_vars%s", { required:true }]);', $idx);
1620
		}
1621
1622
		$js_code[] = '})(jQuery);';
1623
		$js_code[] = '//]]></script>';
1624
		$js_code   = implode("\n", $js_code);
1625
1626
		Context::addHtmlHeader($js_code);
1627
	}
1628
1629
	/**
1630
	 * Add a category
1631
	 * @param object $args
1632
	 * @return void
1633
	 */
1634
	function procDocumentInsertCategory($args = null)
1635
	{
1636
		// List variables
1637
		if(!$args) $args = Context::gets('module_srl','category_srl','parent_srl','category_title','category_description','expand','group_srls','category_color','mid');
1638
		$args->title = $args->category_title;
1639
		$args->description = $args->category_description;
1640
		$args->color = $args->category_color;
1641
1642
		if(!$args->module_srl && $args->mid)
1643
		{
1644
			$mid = $args->mid;
0 ignored issues
show
Unused Code introduced by
$mid 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...
1645
			unset($args->mid);
1646
			$args->module_srl = $this->module_srl;
1647
		}
1648
		// Check permissions
1649
		$oModuleModel = getModel('module');
1650
		$columnList = array('module_srl', 'module');
1651
		$module_info = $oModuleModel->getModuleInfoByModuleSrl($args->module_srl, $columnList);
1652
		$grant = $oModuleModel->getGrant($module_info, Context::get('logged_info'));
1653
		if(!$grant->manager) return new BaseObject(-1,'msg_not_permitted');
1654
1655
		if($args->expand !="Y") $args->expand = "N";
1656
		if(!is_array($args->group_srls)) $args->group_srls = str_replace('|@|',',',$args->group_srls);
1657
		else $args->group_srls = implode(',', $args->group_srls);
1658
		$args->parent_srl = (int)$args->parent_srl;
1659
1660
		$oDocumentModel = getModel('document');
1661
1662
		$oDB = &DB::getInstance();
1663
		$oDB->begin();
1664
		// Check if already exists
1665
		if($args->category_srl)
1666
		{
1667
			$category_info = $oDocumentModel->getCategory($args->category_srl);
1668
			if($category_info->category_srl != $args->category_srl) $args->category_srl = null;
1669
		}
1670
		// Update if exists
1671
		if($args->category_srl)
1672
		{
1673
			$output = $this->updateCategory($args);
1674
			if(!$output->toBool())
1675
			{
1676
				$oDB->rollback();
1677
				return $output;
1678
			}
1679
			// Insert if not exist
1680
		}
1681
		else
1682
		{
1683
			$output = $this->insertCategory($args);
1684
			if(!$output->toBool())
1685
			{
1686
				$oDB->rollback();
1687
				return $output;
1688
			}
1689
		}
1690
		// Update the xml file and get its location
1691
		$xml_file = $this->makeCategoryFile($args->module_srl);
1692
1693
		$oDB->commit();
1694
1695
		$this->add('xml_file', $xml_file);
1696
		$this->add('module_srl', $args->module_srl);
1697
		$this->add('category_srl', $args->category_srl);
1698
		$this->add('parent_srl', $args->parent_srl);
1699
1700
		$returnUrl = Context::get('success_return_url') ? Context::get('success_return_url') : Context::get('error_return_url');
1701
		$this->setRedirectUrl($returnUrl);
1702
	}
1703
1704
	/**
1705
	 * Move a category
1706
	 * @return void
1707
	 */
1708
	function procDocumentMoveCategory()
1709
	{
1710
		$source_category_srl = Context::get('source_srl');
1711
		// If parent_srl exists, be the first child
1712
		$parent_category_srl = Context::get('parent_srl');
1713
		// If target_srl exists, be a sibling
1714
		$target_category_srl = Context::get('target_srl');
1715
1716
		$oDocumentModel = getModel('document');
1717
		$source_category = $oDocumentModel->getCategory($source_category_srl);
1718
		// Check permissions
1719
		$oModuleModel = getModel('module');
1720
		$columnList = array('module_srl', 'module');
1721
		$module_info = $oModuleModel->getModuleInfoByModuleSrl($source_category->module_srl, $columnList);
1722
		$grant = $oModuleModel->getGrant($module_info, Context::get('logged_info'));
1723
		if(!$grant->manager) return new BaseObject(-1,'msg_not_permitted');
1724
1725
		// First child of the parent_category_srl
1726
		$source_args = new stdClass;
1727
		if($parent_category_srl > 0 || ($parent_category_srl == 0 && $target_category_srl == 0))
1728
		{
1729
			$parent_category = $oDocumentModel->getCategory($parent_category_srl);
0 ignored issues
show
Unused Code introduced by
$parent_category 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...
1730
1731
			$args = new stdClass;
1732
			$args->module_srl = $source_category->module_srl;
1733
			$args->parent_srl = $parent_category_srl;
1734
			$output = executeQuery('document.getChildCategoryMinListOrder', $args);
1735
1736
			if(!$output->toBool()) return $output;
1737
			$args->list_order = (int)$output->data->list_order;
1738
			if(!$args->list_order) $args->list_order = 0;
1739
			$args->list_order--;
1740
1741
			$source_args->category_srl = $source_category_srl;
1742
			$source_args->parent_srl = $parent_category_srl;
1743
			$source_args->list_order = $args->list_order;
1744
			$output = $this->updateCategory($source_args);
1745
			if(!$output->toBool()) return $output;
1746
			// Sibling of the $target_category_srl
1747
		}
1748
		else if($target_category_srl > 0)
1749
		{
1750
			$target_category = $oDocumentModel->getCategory($target_category_srl);
1751
			// Move all siblings of the $target_category down
1752
			$output = $this->updateCategoryListOrder($target_category->module_srl, $target_category->list_order+1);
1753
			if(!$output->toBool()) return $output;
1754
1755
			$source_args->category_srl = $source_category_srl;
1756
			$source_args->parent_srl = $target_category->parent_srl;
1757
			$source_args->list_order = $target_category->list_order+1;
1758
			$output = $this->updateCategory($source_args);
1759
			if(!$output->toBool()) return $output;
1760
		}
1761
		// Re-generate the xml file
1762
		$xml_file = $this->makeCategoryFile($source_category->module_srl);
1763
		// Variable settings
1764
		$this->add('xml_file', $xml_file);
1765
		$this->add('source_category_srl', $source_category_srl);
1766
	}
1767
1768
	/**
1769
	 * Delete a category
1770
	 * @return void
1771
	 */
1772
	function procDocumentDeleteCategory()
1773
	{
1774
		// List variables
1775
		$args = Context::gets('module_srl','category_srl');
1776
1777
		$oDB = &DB::getInstance();
1778
		$oDB->begin();
1779
		// Check permissions
1780
		$oModuleModel = getModel('module');
1781
		$columnList = array('module_srl', 'module');
1782
		$module_info = $oModuleModel->getModuleInfoByModuleSrl($args->module_srl, $columnList);
1783
		$grant = $oModuleModel->getGrant($module_info, Context::get('logged_info'));
1784
		if(!$grant->manager) return new BaseObject(-1,'msg_not_permitted');
1785
1786
		$oDocumentModel = getModel('document');
1787
		// Get original information
1788
		$category_info = $oDocumentModel->getCategory($args->category_srl);
1789
		if($category_info->parent_srl) $parent_srl = $category_info->parent_srl;
1790
		// Display an error that the category cannot be deleted if it has a child node
1791
		if($oDocumentModel->getCategoryChlidCount($args->category_srl)) return new BaseObject(-1, 'msg_cannot_delete_for_child');
1792
		// Remove from the DB
1793
		$output = $this->deleteCategory($args->category_srl);
1794
		if(!$output->toBool())
1795
		{
1796
			$oDB->rollback();
1797
			return $output;
1798
		}
1799
		// Update the xml file and get its location
1800
		$xml_file = $this->makeCategoryFile($args->module_srl);
1801
1802
		$oDB->commit();
1803
1804
		$this->add('xml_file', $xml_file);
1805
		$this->add('category_srl', $parent_srl);
0 ignored issues
show
Bug introduced by
The variable $parent_srl 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...
1806
		$this->setMessage('success_deleted');
1807
	}
1808
1809
	/**
1810
	 * Xml files updated
1811
	 * Occasionally the xml file is not generated after menu is configued on the admin page \n
1812
	 * The administrator can manually update the file in this case \n
1813
	 * Although the issue is not currently reproduced, it is unnecessay to remove.
1814
	 * @return void
1815
	 */
1816
	function procDocumentMakeXmlFile()
1817
	{
1818
		// Check input values
1819
		$module_srl = Context::get('module_srl');
1820
		// Check permissions
1821
		$oModuleModel = getModel('module');
1822
		$columnList = array('module_srl', 'module');
1823
		$module_info = $oModuleModel->getModuleInfoByModuleSrl($module_srl, $columnList);
1824
		$grant = $oModuleModel->getGrant($module_info, Context::get('logged_info'));
1825
		if(!$grant->manager) return new BaseObject(-1,'msg_not_permitted');
1826
1827
		$xml_file = $this->makeCategoryFile($module_srl);
1828
		// Set return value
1829
		$this->add('xml_file',$xml_file);
1830
	}
1831
1832
	/**
1833
	 * Save the category in a cache file
1834
	 * @param int $module_srl
1835
	 * @return string
1836
	 */
1837
	function makeCategoryFile($module_srl)
1838
	{
1839
		// Return if there is no information you need for creating a cache file
1840
		if(!$module_srl) return false;
1841
		// Get module information (to obtain mid)
1842
		$oModuleModel = getModel('module');
1843
		$columnList = array('module_srl', 'mid', 'site_srl');
1844
		$module_info = $oModuleModel->getModuleInfoByModuleSrl($module_srl, $columnList);
1845
		$mid = $module_info->mid;
1846
1847
		if(!is_dir('./files/cache/document_category')) FileHandler::makeDir('./files/cache/document_category');
1848
		// Cache file's name
1849
		$xml_file = sprintf("./files/cache/document_category/%s.xml.php", $module_srl);
1850
		$php_file = sprintf("./files/cache/document_category/%s.php", $module_srl);
1851
		// Get a category list
1852
		$args = new stdClass();
1853
		$args->module_srl = $module_srl;
1854
		$args->sort_index = 'list_order';
1855
		$output = executeQueryArray('document.getCategoryList', $args);
1856
1857
		$category_list = $output->data;
1858
1859
		if(!is_array($category_list)) $category_list = array($category_list);
1860
1861
		$category_count = count($category_list);
1862
		for($i=0;$i<$category_count;$i++)
1863
		{
1864
			$category_srl = $category_list[$i]->category_srl;
1865
			if(!preg_match('/^[0-9,]+$/', $category_list[$i]->group_srls)) $category_list[$i]->group_srls = '';
1866
			$list[$category_srl] = $category_list[$i];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$list was never initialized. Although not strictly required by PHP, it is generally a good practice to add $list = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
1867
		}
1868
		// Create the xml file without node data if no data is obtained
1869 View Code Duplication
		if(!$list)
0 ignored issues
show
Bug introduced by
The variable $list 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...
Bug Best Practice introduced by
The expression $list of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
1870
		{
1871
			$xml_buff = "<root />";
1872
			FileHandler::writeFile($xml_file, $xml_buff);
1873
			FileHandler::writeFile($php_file, '<?php if(!defined("__XE__")) exit(); ?>');
1874
			return $xml_file;
1875
		}
1876
		// Change to an array if only a single data is obtained
1877
		if(!is_array($list)) $list = array($list);
1878
		// Create a tree for loop
1879
		foreach($list as $category_srl => $node)
1880
		{
1881
			$node->mid = $mid;
1882
			$parent_srl = (int)$node->parent_srl;
1883
			$tree[$parent_srl][$category_srl] = $node;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$tree was never initialized. Although not strictly required by PHP, it is generally a good practice to add $tree = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
1884
		}
1885
		// A common header to set permissions and groups of the cache file
1886
		$header_script =
1887
			'$lang_type = Context::getLangType(); '.
1888
			'$is_logged = Context::get(\'is_logged\'); '.
1889
			'$logged_info = Context::get(\'logged_info\'); '.
1890
			'if($is_logged) {'.
1891
			'if($logged_info->is_admin=="Y") $is_admin = true; '.
1892
			'else $is_admin = false; '.
1893
			'$group_srls = array_keys($logged_info->group_list); '.
1894
			'} else { '.
1895
			'$is_admin = false; '.
1896
			'$group_srsl = array(); '.
1897
			'} '."\n";
1898
1899
		// Create the xml cache file (a separate session is needed for xml cache)
1900
		$xml_header_buff = '';
1901
		$xml_body_buff = $this->getXmlTree($tree[0], $tree, $module_info->site_srl, $xml_header_buff);
0 ignored issues
show
Bug introduced by
The variable $tree 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...
1902
		$xml_buff = sprintf(
1903
			'<?php '.
1904
			'define(\'__XE__\', true); '.
1905
			'require_once(\''.FileHandler::getRealPath('./config/config.inc.php').'\'); '.
1906
			'$oContext = &Context::getInstance(); '.
1907
			'$oContext->init(); '.
1908
			'header("Content-Type: text/xml; charset=UTF-8"); '.
1909
			'header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); '.
1910
			'header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); '.
1911
			'header("Cache-Control: no-store, no-cache, must-revalidate"); '.
1912
			'header("Cache-Control: post-check=0, pre-check=0", false); '.
1913
			'header("Pragma: no-cache"); '.
1914
			'%s'.
1915
			'%s '.
1916
			'$oContext->close();'.
1917
			'?>'.
1918
			'<root>%s</root>',
1919
			$header_script,
1920
			$xml_header_buff,
1921
			$xml_body_buff
1922
		);
1923
		// Create php cache file
1924
		$php_header_buff = '$_titles = array();';
1925
		$php_header_buff .= '$_descriptions = array();';
1926
		$php_output = $this->getPhpCacheCode($tree[0], $tree, $module_info->site_srl, $php_header_buff);
1927
		$php_buff = sprintf(
1928
			'<?php '.
1929
			'if(!defined("__XE__")) exit(); '.
1930
			'%s'.
1931
			'%s'.
1932
			'$menu = new stdClass;'.
1933
			'$menu->list = array(%s); ',
1934
			$header_script,
1935
			$php_header_buff,
1936
			$php_output['buff']
1937
		);
1938
		// Save File
1939
		FileHandler::writeFile($xml_file, $xml_buff);
1940
		FileHandler::writeFile($php_file, $php_buff);
1941
		return $xml_file;
1942
	}
1943
1944
	/**
1945
	 * Create the xml data recursively referring to parent_srl
1946
	 * In the menu xml file, node tag is nested and xml doc enables the admin page to have a menu\n
1947
	 * (tree menu is implemented by reading xml file from the tree_menu.js)
1948
	 * @param array $source_node
1949
	 * @param array $tree
1950
	 * @param int $site_srl
1951
	 * @param string $xml_header_buff
1952
	 * @return string
1953
	 */
1954
	function getXmlTree($source_node, $tree, $site_srl, &$xml_header_buff)
1955
	{
1956
		if(!$source_node) return;
0 ignored issues
show
Bug Best Practice introduced by
The expression $source_node of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
1957
1958
		foreach($source_node as $category_srl => $node)
1959
		{
1960
			$child_buff = "";
1961
			// Get data of the child nodes
1962
			if($category_srl && $tree[$category_srl]) $child_buff = $this->getXmlTree($tree[$category_srl], $tree, $site_srl, $xml_header_buff);
1963
			// List variables
1964
			$expand = ($node->expand) ? $node->expand : 'N';
1965
			$group_srls = ($node->group_srls) ? $node->group_srls : '';
1966
			$mid = ($node->mid) ? $node->mid : '';
1967
			$module_srl = ($node->module_srl) ? $node->parent_srl : '';
1968
			$parent_srl = ($node->parent_srl) ? $node->parent_srl : '';
1969
			$color = ($node->color) ? $node->color : '';
1970
			$description = ($node->description) ? $node->description : '';
1971
			// If node->group_srls value exists
1972
			if($group_srls) $group_check_code = sprintf('($is_admin==true||(is_array($group_srls)&&count(array_intersect($group_srls, array(%s)))))',$group_srls);
1973
			else $group_check_code = "true";
1974
1975
			$title = $node->title;
1976
			$oModuleAdminModel = getAdminModel('module');
1977
1978
			$langs = $oModuleAdminModel->getLangCode($site_srl, $title);
1979 View Code Duplication
			if(count($langs))
1980
			{
1981
				foreach($langs as $key => $val)
1982
				{
1983
					$xml_header_buff .= sprintf('$_titles[%d]["%s"] = %s; ', $category_srl, $key, var_export(str_replace('"','\\"',htmlspecialchars($val, ENT_COMPAT | ENT_HTML401, 'UTF-8', false)), true));
1984
				}
1985
			}
1986
1987
			$langx = $oModuleAdminModel->getLangCode($site_srl, $description);
1988 View Code Duplication
			if(count($langx))
1989
			{
1990
				foreach($langx as $key => $val)
1991
				{
1992
					$xml_header_buff .= sprintf('$_descriptions[%d]["%s"] = %s; ', $category_srl, $key, var_export(str_replace('"','\\"',htmlspecialchars($val, ENT_COMPAT | ENT_HTML401, 'UTF-8', false)), true));
1993
				}
1994
			}
1995
1996
			$attribute = sprintf(
1997
				'mid="%s" module_srl="%d" node_srl="%d" parent_srl="%d" category_srl="%d" text="<?php echo (%s?($_titles[%d][$lang_type]):"")?>" url=%s expand=%s color=%s description="<?php echo (%s?($_descriptions[%d][$lang_type]):"")?>" document_count="%d" ',
1998
				$mid,
1999
				$module_srl,
2000
				$category_srl,
2001
				$parent_srl,
2002
				$category_srl,
2003
				$group_check_code,
2004
				$category_srl,
2005
				var_export(getUrl('','mid',$node->mid,'category',$category_srl), true),
2006
				var_export($expand, true),
2007
				var_export($color, true),
2008
				$group_check_code,
2009
				$category_srl,
2010
				$node->document_count
2011
			);
2012
2013 View Code Duplication
			if($child_buff) $buff .= sprintf('<node %s>%s</node>', $attribute, $child_buff);
0 ignored issues
show
Bug introduced by
The variable $buff 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...
2014
			else $buff .=  sprintf('<node %s />', $attribute);
2015
		}
2016
		return $buff;
2017
	}
2018
2019
	/**
2020
	 * Change sorted nodes in an array to the php code and then return
2021
	 * When using menu on tpl, you can directly xml data. howver you may need javascrips additionally.
2022
	 * Therefore, you can configure the menu info directly from php cache file, not through DB.
2023
	 * You may include the cache in the ModuleHandler::displayContent()
2024
	 * @param array $source_node
2025
	 * @param array $tree
2026
	 * @param int $site_srl
2027
	 * @param string $php_header_buff
2028
	 * @return array
2029
	 */
2030
	function getPhpCacheCode($source_node, $tree, $site_srl, &$php_header_buff)
2031
	{
2032
		$output = array("buff"=>"", "category_srl_list"=>array());
2033
		if(!$source_node) return $output;
0 ignored issues
show
Bug Best Practice introduced by
The expression $source_node of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
2034
2035
		// Set to an arraty for looping and then generate php script codes to be included
2036
		foreach($source_node as $category_srl => $node)
2037
		{
2038
			// Get data from child nodes first if exist.
2039
			if($category_srl && $tree[$category_srl]){
2040
				$child_output = $this->getPhpCacheCode($tree[$category_srl], $tree, $site_srl, $php_header_buff);
2041
			} else {
2042
				$child_output = array("buff"=>"", "category_srl_list"=>array());
2043
			}
2044
2045
			// Set values into category_srl_list arrary if url of the current node is not empty
2046
			$child_output['category_srl_list'][] = $node->category_srl;
2047
			$output['category_srl_list'] = array_merge($output['category_srl_list'], $child_output['category_srl_list']);
2048
2049
			// If node->group_srls value exists
2050
			if($node->group_srls) {
2051
				$group_check_code = sprintf('($is_admin==true||(is_array($group_srls)&&count(array_intersect($group_srls, array(%s)))))',$node->group_srls);
2052
			} else {
2053
				$group_check_code = "true";
2054
			}
2055
2056
			// List variables
2057
			$selected = '"' . implode('","', $child_output['category_srl_list']) . '"';
2058
			$child_buff = $child_output['buff'];
2059
			$expand = $node->expand;
2060
2061
			$title = $node->title;
2062
			$description = $node->description;
2063
			$oModuleAdminModel = getAdminModel('module');
2064
			$langs = $oModuleAdminModel->getLangCode($site_srl, $title);
2065
2066 View Code Duplication
			if(count($langs))
2067
			{
2068
				foreach($langs as $key => $val)
2069
				{
2070
					$val = htmlspecialchars($val, ENT_COMPAT | ENT_HTML401, 'UTF-8', false);
2071
					$php_header_buff .= sprintf(
2072
						'$_titles[%d]["%s"] = %s; ',
2073
						$category_srl,
2074
						$key,
2075
						var_export(str_replace('"','\\"', $val), true)
2076
					);
2077
				}
2078
			}
2079
2080
			$langx = $oModuleAdminModel->getLangCode($site_srl, $description);
2081
2082 View Code Duplication
			if(count($langx))
2083
			{
2084
				foreach($langx as $key => $val)
2085
				{
2086
					$val = htmlspecialchars($val, ENT_COMPAT | ENT_HTML401, 'UTF-8', false);
2087
					$php_header_buff .= sprintf(
2088
						'$_descriptions[%d]["%s"] = %s; ',
2089
						$category_srl,
2090
						$key,
2091
						var_export(str_replace('"','\\"', $val), true)
2092
					);
2093
				}
2094
			}
2095
2096
			// Create attributes(Use the category_srl_list to check whether to belong to the menu's node. It seems to be tricky but fast fast and powerful;)
2097
			$attribute = sprintf(
2098
				'"mid" => "%s", "module_srl" => "%d","node_srl"=>"%d","category_srl"=>"%d","parent_srl"=>"%d","text"=>$_titles[%d][$lang_type],"selected"=>(in_array(Context::get("category"),array(%s))?1:0),"expand"=>%s,"color"=>%s,"description"=>$_descriptions[%d][$lang_type],"list"=>array(%s),"document_count"=>"%d","grant"=>%s?true:false',
2099
				$node->mid,
2100
				$node->module_srl,
2101
				$node->category_srl,
2102
				$node->category_srl,
2103
				$node->parent_srl,
2104
				$node->category_srl,
2105
				$selected,
2106
				var_export($expand, true),
2107
				var_export($node->color, true),
2108
				$node->category_srl,
2109
				$child_buff,
2110
				$node->document_count,
2111
				$group_check_code
2112
			);
2113
2114
			// Generate buff data
2115
			$output['buff'] .=  sprintf('%s=>array(%s),', $node->category_srl, $attribute);
2116
		}
2117
2118
		return $output;
2119
	}
2120
2121
	/**
2122
	 * A method to add a pop-up menu which appears when clicking
2123
	 * @param string $url
2124
	 * @param string $str
2125
	 * @param string $icon
2126
	 * @param string $target
2127
	 * @return void
2128
	 */
2129 View Code Duplication
	function addDocumentPopupMenu($url, $str, $icon = '', $target = 'self')
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...
2130
	{
2131
		$document_popup_menu_list = Context::get('document_popup_menu_list');
2132
		if(!is_array($document_popup_menu_list)) $document_popup_menu_list = array();
2133
2134
		$obj = new stdClass();
2135
		$obj->url = $url;
2136
		$obj->str = $str;
2137
		$obj->icon = $icon;
2138
		$obj->target = $target;
2139
		$document_popup_menu_list[] = $obj;
2140
2141
		Context::set('document_popup_menu_list', $document_popup_menu_list);
2142
	}
2143
2144
	/**
2145
	 * Saved in the session when an administrator selects a post
2146
	 * @return void|BaseObject
2147
	 */
2148
	function procDocumentAddCart()
2149
	{
2150
		if(!Context::get('is_logged')) return new BaseObject(-1, 'msg_not_permitted');
2151
2152
		// Get document_srl
2153
		$srls = explode(',',Context::get('srls'));
2154
		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...
2155
		{
2156
			$srl = trim($srls[$i]);
2157
2158
			if(!$srl) continue;
2159
2160
			$document_srls[] = $srl;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$document_srls was never initialized. Although not strictly required by PHP, it is generally a good practice to add $document_srls = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
2161
		}
2162
		if(!count($document_srls)) return;
0 ignored issues
show
Bug introduced by
The variable $document_srls 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...
2163
2164
		// Get module_srl of the documents
2165
		$args = new stdClass;
2166
		$args->list_count = count($document_srls);
2167
		$args->document_srls = implode(',',$document_srls);
2168
		$args->order_type = 'asc';
2169
		$output = executeQueryArray('document.getDocuments', $args);
2170
		if(!$output->data) return new BaseObject();
2171
2172
		unset($document_srls);
2173
		foreach($output->data as $key => $val)
2174
		{
2175
			$document_srls[$val->module_srl][] = $val->document_srl;
2176
		}
2177
		if(!$document_srls || !count($document_srls)) return new BaseObject();
0 ignored issues
show
Bug Best Practice introduced by
The expression $document_srls of type string[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
2178
2179
		// Check if each of module administrators exists. Top-level administator will have a permission to modify every document of all modules.(Even to modify temporarily saved or trashed documents)
2180
		$oModuleModel = getModel('module');
2181
		$module_srls = array_keys($document_srls);
2182
		for($i=0;$i<count($module_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...
2183
		{
2184
			$module_srl = $module_srls[$i];
2185
			$module_info = $oModuleModel->getModuleInfoByModuleSrl($module_srl);
2186
			$logged_info = Context::get('logged_info');
2187
			if($logged_info->is_admin != 'Y')
2188
			{
2189
				if(!$module_info)
2190
				{
2191
					unset($document_srls[$module_srl]);
2192
					continue;
2193
				}
2194
				$grant = $oModuleModel->getGrant($module_info, $logged_info);
2195
				if(!$grant->manager)
2196
				{
2197
					unset($document_srls[$module_srl]);
2198
					continue;
2199
				}
2200
			}
2201
		}
2202
		if(!count($document_srls)) return new BaseObject();
2203
2204
		foreach($document_srls as $module_srl => $documents)
2205
		{
2206
			$cnt = count($documents);
2207
			for($i=0;$i<$cnt;$i++)
2208
			{
2209
				$document_srl = (int)trim($documents[$i]);
2210
				if(!$document_srls) continue;
0 ignored issues
show
Bug Best Practice introduced by
The expression $document_srls of type string[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
2211
				if($_SESSION['document_management'][$document_srl]) unset($_SESSION['document_management'][$document_srl]);
2212
				else $_SESSION['document_management'][$document_srl] = true;
2213
			}
2214
		}
2215
	}
2216
2217
	/**
2218
	 * Move/ Delete the document in the seession
2219
	 * @return void|BaseObject
2220
	 */
2221
	function procDocumentManageCheckedDocument()
2222
	{
2223
		@set_time_limit(0);
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...
2224
		if(!Context::get('is_logged')) return new BaseObject(-1,'msg_not_permitted');
2225
2226
		if(!checkCSRF())
2227
		{
2228
			return new BaseObject(-1, 'msg_invalid_request');
2229
		}
2230
2231
		$type = Context::get('type');
2232
		$target_module = Context::get('target_module');
2233
		$module_srl = Context::get('module_srl');
2234
		if($target_module && !$module_srl) $module_srl = $target_module;
2235
		$category_srl = Context::get('target_category');
2236
		$message_content = Context::get('message_content');
2237
		if($message_content) $message_content = nl2br($message_content);
2238
2239
		$cart = Context::get('cart');
2240
		if(!is_array($cart)) $document_srl_list = explode('|@|', $cart);
2241
		else $document_srl_list = $cart;
2242
2243
		$document_srl_count = count($document_srl_list);
2244
2245
		$oDocumentModel = getModel('document');
2246
		$document_items = array();
2247
		foreach($document_srl_list as $document_srl)
2248
		{
2249
			$oDocument = $oDocumentModel->getDocument($document_srl);
2250
			$document_items[] = $oDocument;
2251
			if(!$oDocument->isGranted()) return $this->stop('msg_not_permitted');
2252
		}
2253
2254
		// Send a message
2255
		if($message_content)
2256
		{
2257
2258
			$oCommunicationController = getController('communication');
2259
2260
			$logged_info = Context::get('logged_info');
2261
2262
			$title = cut_str($message_content,10,'...');
2263
			$sender_member_srl = $logged_info->member_srl;
2264
2265
			foreach($document_items as $oDocument)
2266
			{
2267
				if(!$oDocument->get('member_srl') || $oDocument->get('member_srl')==$sender_member_srl) continue;
2268
2269
				if($type=='move') $purl = sprintf("<a href=\"%s\" target=\"_blank\">%s</a>", $oDocument->getPermanentUrl(), $oDocument->getPermanentUrl());
2270
				else $purl = "";
2271
				$content = sprintf("<div>%s</div><hr />%s<div style=\"font-weight:bold\">%s</div>%s",$message_content, $purl, $oDocument->getTitleText(), $oDocument->getContent(false, false, false));
2272
2273
				$oCommunicationController->sendMessage($sender_member_srl, $oDocument->get('member_srl'), $title, $content, false);
2274
			}
2275
		}
2276
		// Set a spam-filer not to be filtered to spams
2277
		$oSpamController = getController('spamfilter');
2278
		$oSpamController->setAvoidLog();
2279
2280
		$oDocumentAdminController = getAdminController('document');
2281
		if($type == 'move')
2282
		{
2283
			if(!$module_srl) return new BaseObject(-1, 'fail_to_move');
2284
2285
			$output = $oDocumentAdminController->moveDocumentModule($document_srl_list, $module_srl, $category_srl);
2286
			if(!$output->toBool()) return new BaseObject(-1, 'fail_to_move');
2287
2288
			$msg_code = 'success_moved';
2289
2290
		}
2291
		else if($type == 'copy')
2292
		{
2293
			if(!$module_srl) return new BaseObject(-1, 'fail_to_move');
2294
2295
			$output = $oDocumentAdminController->copyDocumentModule($document_srl_list, $module_srl, $category_srl);
2296
			if(!$output->toBool()) return new BaseObject(-1, 'fail_to_move');
2297
2298
			$msg_code = 'success_copied';
2299
		}
2300
		else if($type =='delete')
2301
		{
2302
			$oDB = &DB::getInstance();
2303
			$oDB->begin();
2304 View Code Duplication
			for($i=0;$i<$document_srl_count;$i++)
2305
			{
2306
				$document_srl = $document_srl_list[$i];
2307
				$output = $this->deleteDocument($document_srl, true);
2308
				if(!$output->toBool()) return new BaseObject(-1, 'fail_to_delete');
2309
			}
2310
			$oDB->commit();
2311
			$msg_code = 'success_deleted';
2312
		}
2313
		else if($type == 'trash')
2314
		{
2315
			$args = new stdClass();
2316
			$args->description = $message_content;
2317
2318
			$oDB = &DB::getInstance();
2319
			$oDB->begin();
2320 View Code Duplication
			for($i=0;$i<$document_srl_count;$i++) {
2321
				$args->document_srl = $document_srl_list[$i];
2322
				$output = $this->moveDocumentToTrash($args);
2323
				if(!$output || !$output->toBool()) return new BaseObject(-1, 'fail_to_trash');
2324
			}
2325
			$oDB->commit();
2326
			$msg_code = 'success_trashed';
2327
		}
2328
		else if($type == 'cancelDeclare')
2329
		{
2330
			$args->document_srl = $document_srl_list;
0 ignored issues
show
Bug introduced by
The variable $args seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
2331
			$output = executeQuery('document.deleteDeclaredDocuments', $args);
0 ignored issues
show
Bug introduced by
The variable $args seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
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...
2332
			$msg_code = 'success_declare_canceled';
2333
		}
2334
2335
		$_SESSION['document_management'] = array();
2336
2337
		$this->setMessage($msg_code);
0 ignored issues
show
Bug introduced by
The variable $msg_code 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...
2338
2339
		$returnUrl = Context::get('success_return_url') ? Context::get('success_return_url') : getNotEncodedUrl('', 'module', 'admin', 'act', 'dispDocumentAdminList');
2340
		$this->setRedirectUrl($returnUrl);
2341
	}
2342
2343
	/**
2344
	 * Insert document module config
2345
	 * @return void
2346
	 */
2347
	function procDocumentInsertModuleConfig()
2348
	{
2349
		$module_srl = Context::get('target_module_srl');
2350 View Code Duplication
		if(preg_match('/^([0-9,]+)$/',$module_srl)) $module_srl = explode(',',$module_srl);
2351
		else $module_srl = array($module_srl);
2352
2353
		$document_config = new stdClass();
2354
		$document_config->use_history = Context::get('use_history');
2355
		if(!$document_config->use_history) $document_config->use_history = 'N';
2356
2357
		$document_config->use_vote_up = Context::get('use_vote_up');
2358
		if(!$document_config->use_vote_up) $document_config->use_vote_up = 'Y';
2359
2360
		$document_config->use_vote_down = Context::get('use_vote_down');
2361
		if(!$document_config->use_vote_down) $document_config->use_vote_down = 'Y';
2362
2363
		$document_config->use_status = Context::get('use_status');
2364
2365
		$oModuleController = getController('module');
2366 View Code Duplication
		for($i=0;$i<count($module_srl);$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...
2367
		{
2368
			$srl = trim($module_srl[$i]);
2369
			if(!$srl) continue;
2370
			$output = $oModuleController->insertModulePartConfig('document',$srl,$document_config);
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...
2371
		}
2372
		$this->setError(-1);
2373
		$this->setMessage('success_updated', 'info');
2374
2375
		$returnUrl = Context::get('success_return_url') ? Context::get('success_return_url') : getNotEncodedUrl('', 'module', 'admin', 'act', 'dispBoardAdminContent');
2376
		$this->setRedirectUrl($returnUrl);
2377
	}
2378
2379
	/**
2380
	 * Document temporary save
2381
	 * @return void|BaseObject
2382
	 */
2383
	function procDocumentTempSave()
2384
	{
2385
		// Check login information
2386
		if(!Context::get('is_logged')) return new BaseObject(-1, 'msg_not_logged');
2387
		$module_info = Context::get('module_info');
2388
		$logged_info = Context::get('logged_info');
0 ignored issues
show
Unused Code introduced by
$logged_info 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...
2389
2390
		// Get form information
2391
		$obj = Context::getRequestVars();
2392
		// Change the target module to log-in information
2393
		$obj->module_srl = $module_info->module_srl;
0 ignored issues
show
Bug introduced by
The property module_srl does not seem to exist in BaseObject.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
2394
		$obj->status = $this->getConfigStatus('temp');
0 ignored issues
show
Bug introduced by
The property status does not seem to exist. Did you mean httpStatusCode?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
2395
		unset($obj->is_notice);
2396
2397
		// Extract from beginning part of contents in the guestbook
2398
		if(!$obj->title)
2399
		{
2400
			$obj->title = cut_str(strip_tags($obj->content), 20, '...');
0 ignored issues
show
Bug introduced by
The property title does not seem to exist in BaseObject.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
Bug introduced by
The property content does not seem to exist in BaseObject.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
2401
		}
2402
2403
		$oDocumentModel = getModel('document');
2404
		$oDocumentController = getController('document');
2405
		// Check if already exist geulinji
2406
		$oDocument = $oDocumentModel->getDocument($obj->document_srl, $this->grant->manager);
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...
Bug introduced by
The property document_srl does not seem to exist in BaseObject.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
2407
2408
		// Update if already exists
2409
		if($oDocument->isExists() && $oDocument->document_srl == $obj->document_srl)
2410
		{
2411
			if($oDocument->get('module_srl') != $obj->module_srl)
2412
			{
2413
				return new BaseObject(-1, 'msg_invalid_request');
2414
			}
2415
			if(!$oDocument->isGranted())
2416
			{
2417
				return new BaseObject(-1, 'msg_invalid_request');
2418
			}
2419
			//if exist document status is already public, use temp status can point problem
2420
			$obj->status = $oDocument->get('status');
0 ignored issues
show
Bug introduced by
The property status does not seem to exist. Did you mean httpStatusCode?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
2421
			$output = $oDocumentController->updateDocument($oDocument, $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...
2422
			$msg_code = 'success_updated';
0 ignored issues
show
Unused Code introduced by
$msg_code 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...
2423
			// Otherwise, get a new
2424
		}
2425
		else
2426
		{
2427
			$output = $oDocumentController->insertDocument($obj);
2428
			$msg_code = 'success_registed';
0 ignored issues
show
Unused Code introduced by
$msg_code 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...
2429
			$obj->document_srl = $output->get('document_srl');
2430
			$oDocument = $oDocumentModel->getDocument($obj->document_srl, $this->grant->manager);
2431
		}
2432
		// Set the attachment to be invalid state
2433 View Code Duplication
		if($oDocument->hasUploadedFiles())
2434
		{
2435
			$args = new stdClass;
2436
			$args->upload_target_srl = $oDocument->document_srl;
2437
			$args->isvalid = 'N';
2438
			executeQuery('file.updateFileValid', $args);
2439
		}
2440
2441
		$this->setMessage('success_saved');
2442
		$this->add('document_srl', $obj->document_srl);
2443
	}
2444
2445
	/**
2446
	 * Return Document List for exec_xml
2447
	 * @return void|BaseObject
2448
	 */
2449
	function procDocumentGetList()
2450
	{
2451
		if(!Context::get('is_logged')) return new BaseObject(-1,'msg_not_permitted');
2452
		$documentSrls = Context::get('document_srls');
2453
		if($documentSrls) $documentSrlList = explode(',', $documentSrls);
2454
2455
		if(count($documentSrlList) > 0)
2456
		{
2457
			$oDocumentModel = getModel('document');
2458
			$columnList = array('document_srl', 'title', 'nick_name', 'status');
2459
			$documentList = $oDocumentModel->getDocuments($documentSrlList, $this->grant->is_admin, false, $columnList);
0 ignored issues
show
Bug introduced by
The variable $documentSrlList 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...
2460
		}
2461
		else
2462
		{
2463
			global $lang;
2464
			$documentList = array();
2465
			$this->setMessage($lang->no_documents);
2466
		}
2467
		$oSecurity = new Security($documentList);
2468
		$oSecurity->encodeHTML('..variables.');
2469
		$this->add('document_list', $documentList);
2470
	}
2471
2472
	/**
2473
	 * For old version, comment allow status check.
2474
	 * @param object $obj
2475
	 * @return void
2476
	 */
2477
	function _checkCommentStatusForOldVersion(&$obj)
2478
	{
2479
		if(!isset($obj->allow_comment)) $obj->allow_comment = 'N';
2480
		if(!isset($obj->lock_comment)) $obj->lock_comment = 'N';
2481
2482
		if($obj->allow_comment == 'Y' && $obj->lock_comment == 'N') $obj->commentStatus = 'ALLOW';
2483
		else $obj->commentStatus = 'DENY';
2484
	}
2485
2486
	/**
2487
	 * For old version, document status check.
2488
	 * @param object $obj
2489
	 * @return void
2490
	 */
2491
	function _checkDocumentStatusForOldVersion(&$obj)
2492
	{
2493
		if(!$obj->status && $obj->is_secret == 'Y') $obj->status = $this->getConfigStatus('secret');
2494
		if(!$obj->status && $obj->is_secret != 'Y') $obj->status = $this->getConfigStatus('public');
2495
	}
2496
2497
	public function updateUploaedCount($documentSrlList)
2498
	{
2499
		$oDocumentModel = getModel('document');
0 ignored issues
show
Unused Code introduced by
$oDocumentModel 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...
2500
		$oFileModel = getModel('file');
2501
2502
		if(is_array($documentSrlList))
2503
		{
2504
			$documentSrlList = array_unique($documentSrlList);
2505
			foreach($documentSrlList AS $key => $documentSrl)
2506
			{
2507
				$fileCount = $oFileModel->getFilesCount($documentSrl);
2508
				$args = new stdClass();
2509
				$args->document_srl = $documentSrl;
2510
				$args->uploaded_count = $fileCount;
2511
				executeQuery('document.updateUploadedCount', $args);
2512
			}
2513
		}
2514
	}
2515
2516
	/**
2517
	 * Copy extra keys when module copied
2518
	 * @param object $obj
2519
	 * @return void
2520
	 */
2521
	function triggerCopyModuleExtraKeys(&$obj)
2522
	{
2523
		$oDocumentModel = getModel('document');
2524
		$documentExtraKeys = $oDocumentModel->getExtraKeys($obj->originModuleSrl);
2525
2526
		if(is_array($documentExtraKeys) && is_array($obj->moduleSrlList))
2527
		{
2528
			$oDocumentController=getController('document');
2529
			foreach($obj->moduleSrlList AS $key=>$value)
2530
			{
2531 View Code Duplication
				foreach($documentExtraKeys AS $extraItem)
2532
				{
2533
					$oDocumentController->insertDocumentExtraKey($value, $extraItem->idx, $extraItem->name, $extraItem->type, $extraItem->is_required , $extraItem->search , $extraItem->default , $extraItem->desc, $extraItem->eid) ;
2534
				}
2535
			}
2536
		}
2537
	}
2538
2539 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...
2540
	{
2541
		$oModuleModel = getModel('module');
2542
		$documentConfig = $oModuleModel->getModulePartConfig('document', $obj->originModuleSrl);
2543
2544
		$oModuleController = getController('module');
2545
		if(is_array($obj->moduleSrlList))
2546
		{
2547
			foreach($obj->moduleSrlList AS $key=>$moduleSrl)
2548
			{
2549
				$oModuleController->insertModulePartConfig('document', $moduleSrl, $documentConfig);
2550
			}
2551
		}
2552
	}
2553
}
2554
/* End of file document.controller.php */
2555
/* Location: ./modules/document/document.controller.php */
2556