Passed
Push — master ( 53f74f...bb09c2 )
by alexandr
03:03
created

ACP_Structure::delete_unit()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 52
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 31
nc 6
nop 1
dl 0
loc 52
rs 8.8017
c 0
b 0
f 0

How to fix   Long Method   

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
/**
3
 * RooCMS - Open Source Free Content Managment System
4
 * @copyright © 2010-2021 alexandr Belov aka alex Roosso. All rights reserved.
5
 * @author    alex Roosso <[email protected]>
6
 * @link      http://www.roocms.com
7
 * @license   http://www.gnu.org/licenses/gpl-3.0.html
8
 *
9
 * You should have received a copy of the GNU General Public License v3
10
 * along with this program.  If not, see http://www.gnu.org/licenses/
11
 */
12
13
14
//#########################################################
15
// Anti Hack
16
//---------------------------------------------------------
17
if(!defined('RooCMS') || !defined('ACP')) {
18
	die('Access Denied');
19
}
20
//#########################################################
21
22
23
/**
24
 * Class ACP_STRUCTURE
25
 */
26
class ACP_Structure {
27
28
	# vars
29
	private	$engine;
30
	private $unit;
31
32
	private $sid = 0;
33
34
35
36
	/**
37
	 * Lets mortal kombat begin
38
	 */
39
	public function __construct() {
40
41
		require_once _CLASS."/class_structure.php";
42
		$this->engine = new Structure(false);
43
44
		# initialise
45
		$this->init();
46
	}
47
48
49
	/**
50
	 * initialisation action
51
	 */
52
	private function init() {
53
54
		global $roocms, $config, $db, $users, $tpl, $smarty, $get, $post;
55
56
		# read site tree
57
		$smarty->assign('tree', $this->engine->sitetree);
58
59
		# Check enabled page type
60
		$content_types = [];
61
		foreach($this->engine->content_types AS $key=>$value) {
62
			$content_types[$key] = $value['title'];
63
		}
64
		$smarty->assign('content_types', $content_types);
65
66
67
		# default thumb size
68
		$default_thumb_size = array('width'  => $config->gd_thumb_image_width,
69
					    'height' => $config->gd_thumb_image_height);
70
		$smarty->assign("default_thumb_size", $default_thumb_size);
71
72
73
		# Check id
74
		if(isset($get->_id) && $db->check_id($get->_id, STRUCTURE_TABLE)) {
75
			$this->sid = $get->_id;
76
		}
77
78
79
		# action
80
		switch($roocms->part) {
81
			# create
82
			case 'create':
83
				if(isset($post->create_unit)) {
84
					$this->create_unit();
85
				}
86
				else {
87
					# list groups
88
					$groups = $users->get_usergroups();
89
90
					# tpl
91
					$smarty->assign("groups", $groups);
92
					$content = $tpl->load_template("structure_create", true);
93
				}
94
				break;
95
96
			# edit and update
97
			case 'edit':
98
				if(isset($post->update_unit)) {
99
					$this->update_unit($this->sid);
100
				}
101
102
				$content = $this->edit_unit($this->sid);
103
				break;
104
105
			# delete
106
			case 'delete':
107
				$this->delete_unit($this->sid);
108
				break;
109
110
			default:
111
				$content = $tpl->load_template("structure_tree", true);
112
				break;
113
		}
114
115
		# tpl
116
		$smarty->assign('content', $content);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $content does not seem to be defined for all execution paths leading up to this point.
Loading history...
117
		$tpl->load_template("structure");
118
	}
119
120
121
	/**
122
	 * Create new structure unit
123
	 */
124
	private function create_unit() {
125
126
		global $db, $logger, $post;
127
128
		# check unit parametrs
129
		$this->check_unit_parametrs();
130
131
132
		if(!isset($_SESSION['error'])) {
133
134
			# check parent type
135
			$q = $db->query("SELECT page_type FROM ".STRUCTURE_TABLE." WHERE id='".$post->parent_id."'");
136
			$d = $db->fetch_assoc($q);
137
138
			# not add another page type to feed
139
			if($d['page_type'] == "feed" && $post->page_type != "feed") {
140
				$logger->error("Вы не можете установить для ленты в качестве дочерней страницы другой структурный элемент, кроме ленты.");
141
				goback();
142
			}
143
144
			# insert structure int data
145
			$db->query("INSERT INTO ".STRUCTURE_TABLE."    (alias, title, parent_id, nav, group_access, page_type, meta_title, meta_description, meta_keywords, noindex, sort, date_create, date_modified, thumb_img_width, thumb_img_height)
146
								VALUES ('".$post->alias."', '".$post->title."', '".$post->parent_id."', '".$post->nav."', '".$post->gids."', '".$post->page_type."', '".$post->meta_title."', '".$post->meta_description."', '".$post->meta_keywords."', '".$post->noindex."', '".$post->sort."', '".time()."', '".time()."', '".$post->thumb_img_width."', '".$post->thumb_img_height."')");
147
			$sid = $db->insert_id();
148
149
			# create body unit for html & php pages
150
			switch($post->page_type) {
151
				case 'html':
152
					$db->query("INSERT INTO ".PAGES_HTML_TABLE." (sid, date_modified) VALUE ('".$sid."', '".time()."')");
153
					break;
154
155
				case 'story':
156
					$db->query("INSERT INTO ".PAGES_STORY_TABLE." (sid, date_modified) VALUE ('".$sid."', '".time()."')");
157
					break;
158
159
				case 'php':
160
					$db->query("INSERT INTO ".PAGES_PHP_TABLE." (sid, date_modified) VALUE ('".$sid."', '".time()."')");
161
					break;
162
163
				case 'feed':
164
					$db->query("UPDATE ".STRUCTURE_TABLE." SET rss='1' WHERE sid='".$sid."'");
165
					break;
166
			}
167
168
			# recount childs
169
			$this->count_childs($post->parent_id);
170
171
			# notice
172
			$logger->info("Элемент структуры #".$sid." успешно добавлена.");
173
174
			# go
175
			if(isset($post->create_unit['ae'])) {
176
				go(CP."?act=structure");
177
			}
178
179
			if($post->page_type == "feed") {
180
				go(CP."?act=feeds&part=control&page=".$sid);
181
			}
182
183
			go(CP."?act=pages&part=edit&page=".$sid);
184
		}
185
186
		# goback
187
		goback();
188
	}
189
190
191
	/**
192
	 * Edit structure unit
193
	 *
194
	 * @param mixed $sid - Structure id
195
	 *
196
	 * @return string
197
	 */
198
	private function edit_unit($sid) {
199
200
		global $db, $users, $smarty, $tpl;
201
202
		$q = $db->query("SELECT id, parent_id, nav, group_access, alias, title, meta_title, meta_description, meta_keywords, noindex, sort, page_type, thumb_img_width, thumb_img_height FROM ".STRUCTURE_TABLE." WHERE id='".$sid."'");
203
		$data = $db->fetch_assoc($q);
204
205
		# check access granted for groups
206
		$gids = $users->get_gid_access_granted($data['group_access']);
207
208
		# list groups
209
		$groups = $users->get_usergroups();
210
211
		# tpl
212
		$smarty->assign("gids",   $gids);
213
		$smarty->assign("groups", $groups);
214
		$smarty->assign("data",   $data);
215
216
		return $tpl->load_template("structure_edit", true);
217
	}
218
219
220
	/**
221
	 * Update structure unit
222
	 *
223
	 * @param mixed $sid - structure id
224
	 */
225
	private function update_unit($sid) {
226
227
		global $db, $logger, $post;
228
229
		# dont change parent, alias and nav flag for main page
230
		If($sid == 1) {
231
			$post->parent_id = 0;
232
			$post->alias     = "index";
233
			$post->nav       = 1;
234
		}
235
236
		# check unit parametrs
237
		$this->check_unit_parametrs();
238
239
240
		if(!isset($_SESSION['error'])) {
241
242
			# if set new parent
243
			if($post->parent_id != $post->now_parent_id) {
244
245
				# Check that we are not trying to be a parent for ourselves
246
				if($post->parent_id == $sid) {
247
					$post->parent_id = $post->now_parent_id;
248
					$logger->error("Не удалось изменить иерархию! Вы не можете назначить страницу подчиненной самой себе!");
249
				}
250
				# ... and check that new parent is not a child
251
				else {
252
					$childs = $this->engine->load_tree($sid);
253
254
					foreach((array)$childs AS $v) {
255
						if($post->parent_id == $v['id']) {
256
							$post->parent_id = $post->now_parent_id;
257
							$logger->error("Не удалось изменить иерархию! Вы не можете поместить страницу в подчинение странице собственного нижнего уровня!");
258
						}
259
					}
260
				}
261
			}
262
263
			# get parent type
264
			$q = $db->query("SELECT page_type FROM ".STRUCTURE_TABLE." WHERE id='".$post->parent_id."'");
265
			$d = $db->fetch_assoc($q);
266
267
			# get page type
268
			$q = $db->query("SELECT page_type FROM ".STRUCTURE_TABLE." WHERE id='".$sid."'");
269
			$n = $db->fetch_assoc($q);
270
271
			# not add another page type to feed
272
			if($d['page_type'] == "feed" && $n['page_type'] != "feed") {
273
				$logger->error("Вы не можете установить для ленты в качестве дочерней страницы другой структурный элемент, кроме ленты.");
274
				$post->parent_id = $post->now_parent_id;
275
			}
276
277
			# DB
278
			$db->query("UPDATE ".STRUCTURE_TABLE."
279
					SET
280
						alias='".$post->alias."',
281
						title='".$post->title."',
282
						parent_id='".$post->parent_id."',
283
						nav='".$post->nav."',
284
						group_access='".$post->gids."',
285
						meta_title='".$post->meta_title."',
286
						meta_description='".$post->meta_description."',
287
						meta_keywords='".$post->meta_keywords."',
288
						noindex='".$post->noindex."',
289
						sort='".$post->sort."',
290
						date_modified='".time()."',
291
						thumb_img_width='".$post->thumb_img_width."',
292
						thumb_img_height='".$post->thumb_img_height."'
293
					WHERE
294
						id='".$sid."'");
295
296
			# if set new parent
297
			if($post->parent_id != $post->now_parent_id) {
298
				# recount childs
299
				$this->count_childs($post->parent_id);
300
				$this->count_childs($post->now_parent_id);
301
			}
302
303
			# notice
304
			$logger->info("Страница #".$sid." успешно обновлена.");
305
306
			# go
307
			if(isset($post->update_unit['ae'])) {
308
				go(CP."?act=structure");
309
			}
310
311
			go(CP."?act=structure&part=edit&id=".$sid);
312
		}
313
314
		# goback
315
		goback();
316
	}
317
318
319
	/**
320
	 * Remove structure unit
321
	 *
322
	 * @param mixed $sid - structure id
323
	 */
324
	private function delete_unit($sid) {
325
326
		global $db, $logger;
327
328
		$q = $db->query("SELECT childs, parent_id, page_type FROM ".STRUCTURE_TABLE." WHERE id='".$sid."'");
329
		$c = $db->fetch_assoc($q);
330
331
		if($c['childs'] == 0) {
332
333
			switch($c['page_type']) {
334
335
				case 'html': # del content html
336
					require_once _ROOCMS."/acp/pages_html.php";
337
					$this->unit = new ACP_Pages_HTML;
338
					$this->unit->delete($sid);
339
					break;
340
341
				case 'story': # del content story
342
					require_once _ROOCMS."/acp/pages_story.php";
343
					$this->unit = new ACP_Pages_Story;
344
					$this->unit->delete($sid);
345
					break;
346
347
				case 'php': # del content php
348
					require_once _ROOCMS."/acp/pages_php.php";
349
					$this->unit = new ACP_Pages_PHP;
350
					$this->unit->delete($sid);
351
					break;
352
353
				case 'feed': # del content feed
354
					require_once _ROOCMS."/acp/feeds_feed.php";
355
					$this->unit = new ACP_Feeds_Feed();
356
					$this->unit->delete_feed($sid);
357
					break;
358
			}
359
360
361
			# structure unit
362
			$db->query("DELETE FROM ".STRUCTURE_TABLE." WHERE id='".$sid."'");
363
364
			# notice
365
			$logger->info("Страница #".$sid." успешно удалена");
366
367
			# recount parent childs
368
			$this->count_childs($c['parent_id']);
369
		}
370
		else {
371
			$logger->error("Невозможно удалить страницу, по причине имеющихся у страницы дочерних связей. Сначала перенесите или удалите дочерние страницы.");
372
		}
373
374
		# go
375
		goback();
376
	}
377
378
379
	/**
380
	 * Check alias name on unique
381
	 *
382
	 * @param string $name    - uname
383
	 * @param string $without - exclude uname
384
	 *
385
	 * @return bool
386
	 */
387
	private function check_unique_alias(string $name, $without="") {
388
389
		global $db;
390
391
		$res = false;
392
393
		if(trim($without) != trim($name)) {
394
395
			$without = trim($without);
396
			$w = "alias!='".$without."'";
397
398
			if(!$db->check_id($name, STRUCTURE_TABLE, "alias", $w)) {
399
				$res = true;
400
			}
401
		}
402
		else {
403
			$res = true;
404
		}
405
406
		return $res;
407
	}
408
409
410
	/**
411
	 * Check nav bool for use
412
	 */
413
	private function check_nav() {
414
415
		global $post, $logger;
416
417
		if(isset($this->engine->sitetree[$post->parent_id]['nav']) && $this->engine->sitetree[$post->parent_id]['nav'] == 0) {
418
			$post->nav = 0;
419
			$logger->info("Прежде чем включить в навигацию эту страницу сайта, вы должны включить в навигацию родительскую", false);
420
		}
421
	}
422
423
424
	/**
425
	 * Alias handler
426
	 */
427
	private function handler_alias() {
428
429
		global $parse, $post;
430
431
		if(trim($post->alias) == "") {
432
			$post->alias = $post->title;
433
		}
434
435
		# clear alias from trash symbols
436
		$post->alias = str_ireplace(array(' ','-','='), '_', $post->alias);
437
438
		# correct alias
439
		$post->alias = $parse->text->correct_aliases($post->alias);
440
	}
441
442
443
	/**
444
	 * Check unit data
445
	 */
446
	private function check_unit_parametrs() {
447
448
		global $logger, $post, $img;
449
450
		# title
451
		if(!isset($post->title)) {
452
			$logger->error("Не указано название страницы.");
453
		}
454
455
		# alias
456
		$this->handler_alias();
457
		if(!isset($post->old_alias)) {
458
			$post->old_alias = "";
459
		}
460
		if(!$this->check_unique_alias($post->alias, $post->old_alias)) {
461
			$logger->error("Алиас страницы не уникален.");
462
		}
463
464
		# group access
465
		if(isset($post->gids) && is_array($post->gids)) {
466
			$post->gids = implode(",", $post->gids);
467
		}
468
		else {
469
			$post->gids = 0;
470
		}
471
472
		# sort
473
		$post->sort = round($post->sort);
474
475
		# nav
476
		$this->check_nav();
477
478
		# thumbnail check
479
		$img->check_post_thumb_parametrs();
480
	}
481
482
483
	/**
484
	 * Recount subparts
485
	 *
486
	 * @param int $sid - structure id
487
	 */
488
	private function count_childs(int $sid) {
489
490
		global $db;
491
492
		$c = $db->count(STRUCTURE_TABLE, "parent_id='".$sid."'");
493
494
		$db->query("UPDATE ".STRUCTURE_TABLE." SET childs='".$c."' WHERE id='".$sid."'");
495
	}
496
}
497
498
/**
499
 * Init Class
500
 */
501
$acp_structure = new ACP_Structure;
502