Passed
Push — master ( e4e068...422bd9 )
by alexandr
02:42
created

ACP_Feeds_Feed::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 2
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * RooCMS - Open Source Free Content Managment System
4
 * @copyright © 2010-2020 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
 * Load Feed Extends
25
 */
26
require_once _CLASS."/trait_feedExtends.php";
27
28
29
/**
30
 * Class ACP_Feeds_Feed
31
 */
32
class ACP_Feeds_Feed {
33
34
	use FeedExtends;
35
36
	# vars
37
	private $feed     = [];	# structure parametrs
38
	private $userlist = [];
39
40
41
42
	/**
43
	 * Key on "start" (c)
44
	 *
45
	 * @param $structure_data
46
	 */
47
	public function __construct($structure_data=[]) {
48
		$this->feed =& $structure_data;
49
	}
50
51
52
	/**
53
	 * feed view
54
	 */
55
	public function control() {
56
57
		global $db, $parse, $tags, $tpl, $smarty;
58
59
		# order request
60
		$order = $this->feed_order($this->feed['items_sorting']);
61
62
		$smarty->assign("feed", $this->feed);
63
64
65
		# feed items
66
		$taglinks = [];
67
		$feedlist = [];
68
		$q = $db->query("SELECT id, status, group_access, title, date_publications, date_end_publications, date_update, views FROM ".PAGES_FEED_TABLE." WHERE sid='".$this->feed['id']."' ORDER BY ".$order);
69
		while($row = $db->fetch_assoc($q)) {
70
71
			# flag future publications
72
			$row['publication_future'] = ($row['date_publications'] > time()) ? true : false ;
73
74
			# flag show/hide
75
			$row['publication_status'] = "show";
76
77
			if($row['date_end_publications'] != 0) {
78
79
				# hide publications if ending period
80
				if($row['date_end_publications'] < time()) {
81
					$row['publication_status'] = "hide";
82
				}
83
84
				# formated date
85
				$row['date_end_publications'] = $parse->date->unix_to_rus($row['date_end_publications']);
86
			}
87
88
			# formated date
89
			$row['date_publications'] = $parse->date->unix_to_rus($row['date_publications']);
90
			$row['date_update'] = $parse->date->unix_to_rus($row['date_update'], false, true, true);
91
92
			$taglinks[$row['id']] = "feeditemid=".$row['id'];
93
			$feedlist[$row['id']] = $row;
94
		}
95
96
97
		# tags collect
98
		$feedlist = $tags->collect_tags($feedlist, $taglinks);
99
100
		# smarty
101
		$smarty->assign("subfeeds", $this->feed['subfeeds']);
102
		$smarty->assign("feedlist", $feedlist);
103
104
		$content = $tpl->load_template("feeds_control_feed", true);
105
		$smarty->assign("content",  $content);
106
	}
107
108
109
	/**
110
	 * Create new record to feed
111
	 */
112
	public function create_item() {
113
114
		global $db, $users, $logger, $tags, $files, $img, $post, $tpl, $smarty;
115
116
		# insert db
117
		if(isset($post->create_item)) {
118
119
			# Check post data
120
			$this->check_post_data_fields();
121
			$this->control_post_data_date();
122
123
			if(!isset($_SESSION['error'])) {
124
125
				# Check secondary fields
126
				$this->correct_post_fields();
127
128
				# insert
129
				$db->query("INSERT INTO ".PAGES_FEED_TABLE." (title, meta_title, meta_description, meta_keywords,
130
									      brief_item, full_item, author_id,
131
									      date_create, date_update, date_publications, date_end_publications,
132
									      group_access,
133
									      sort, sid)
134
								      VALUES ('".$post->title."', '".$post->meta_title."', '".$post->meta_description."', '".$post->meta_keywords."',
135
									      '".$post->brief_item."', '".$post->full_item."', '".$post->author_id."',
136
									      '".time()."', '".time()."', '".$post->date_publications."', '".$post->date_end_publications."',
137
									      '".$post->gids."',
138
									      '".$post->itemsort."', '".$this->feed['id']."')");
139
140
				# get feed item id
141
				$fiid = $db->insert_id();
142
143
				# save tags
144
				$tags->save_tags($post->tags, "feeditemid=".$fiid);
145
146
147
				# attachment images
148
				$images = $img->upload_image("images", "", array($this->feed['thumb_img_width'], $this->feed['thumb_img_height']));
149
				if($images) {
150
					foreach($images AS $image) {
151
						$img->insert_images($image, "feeditemid=".$fiid, $post->title);
152
					}
153
				}
154
155
				# attachment files
156
				$files->upload("files", "feeditemid=".$fiid);
157
158
				# recount items
159
				$this->count_items($this->feed['id']);
160
161
				# notice
162
				$logger->info("Запись #".$fiid." <".$post->title."> успешно создана.");
163
164
				// TODO: Переделать!
165
				# mailling
166
				if($post->date_publications <= time() && $post->mailing == 1) {
167
					$this->mailing($fiid, $post->title, $post->brief_item);
168
				}
169
			}
170
171
			# go
172
			go(CP."?act=feeds&part=control&page=".$this->feed['id']);
173
		}
174
175
		# userlist
176
		$this->userlist = $users->get_userlist();
177
178
		# grouplist
179
		$groups = $users->get_usergroups();
180
181
		# popular tags
182
		$poptags = $tags->list_tags(true);
183
184
		# show upload files & images form
185
		$tpl->load_image_upload_tpl("imagesupload");
186
		$tpl->load_files_upload_tpl("filesupload");
187
188
		# smarty vars
189
		$smarty->assign("feed",     $this->feed);      # feed data
190
		$smarty->assign("poptags",  $poptags);         # tags
191
		$smarty->assign("userlist", $this->userlist);  # users
192
		$smarty->assign("groups",   $groups);          # groups
193
194
		# tpl
195
		$content = $tpl->load_template("feeds_create_item_feed", true);
196
		$smarty->assign("content",  $content);
197
	}
198
199
200
	/**
201
	 * Edit record from feed
202
	 *
203
	 * @param int $id - record identificator from feed
204
	 */
205
	public function edit_item($id) {
206
207
		global $db, $users, $tags, $files, $img, $tpl, $smarty, $parse;
208
209
		# userlist
210
		$this->userlist = $users->get_userlist();
211
212
		# grouplist
213
		$groups = $users->get_usergroups();
214
215
		# get data
216
		$q = $db->query("SELECT id, sid, status, group_access, sort, title, meta_title, meta_description, meta_keywords, brief_item, full_item, author_id, date_publications, date_end_publications FROM ".PAGES_FEED_TABLE." WHERE id='".$id."'");
217
		$item = $db->fetch_assoc($q);
218
219
		$item['date_publications'] = $parse->date->unix_to_rusint($item['date_publications']);
220
221
		if($item['date_end_publications'] != 0) {
222
			$item['date_end_publications'] = $parse->date->unix_to_rusint($item['date_end_publications']);
223
		}
224
225
		# check access granted for groups
226
		$gids = $users->get_gid_access_granted($item['group_access']);
227
228
		# item tags
229
		$item['tags'] = implode(", ", array_map(array("Tags", "get_tag_title"), $tags->read_tags("feeditemid=".$id)));
230
231
		# popular tags
232
		$poptags = $tags->list_tags(true);
233
234
235
		# download attached images
236
		$attachimg = $img->load_images("feeditemid=".$id);
237
		$smarty->assign("attachimg", $attachimg);
238
239
		# show attached images
240
		$attachedimages = $tpl->load_template("attached_images", true);
241
		$smarty->assign("attachedimages", $attachedimages);
242
243
244
		# download attached files
245
		$attachfile = $files->load_files("feeditemid=".$id);
246
		$smarty->assign("attachfile", $attachfile);
247
248
		# show attached files
249
		$attachedfiles = $tpl->load_template("attached_files", true);
250
		$smarty->assign("attachedfiles", $attachedfiles);
251
252
253
		# show upload files & images form
254
		$tpl->load_image_upload_tpl("imagesupload");
255
		$tpl->load_files_upload_tpl("filesupload");
256
257
258
		# smarty vars
259
		$smarty->assign("item",     $item);            # item data
260
		$smarty->assign("feed",     $this->feed);      # feed data
261
		$smarty->assign("poptags",  $poptags);         # tags
262
		$smarty->assign("userlist", $this->userlist);  # users list
263
		$smarty->assign("gids",     $gids);            # group id access granted
264
		$smarty->assign("groups",   $groups);          # group list
265
266
		# tpl
267
		$content = $tpl->load_template("feeds_edit_item_feed", true);
268
		$smarty->assign("content", $content);
269
	}
270
271
272
	/**
273
	 * Update record
274
	 *
275
	 * @param int $id - record identificator from feed
276
	 */
277
	public function update_item($id) {
278
279
		global $db, $logger, $tags, $files, $img, $post, $get;
280
281
		# Проверяем вводимые поля на ошибки
282
		$this->check_post_data_fields();
283
		$this->control_post_data_date();
284
285
		# update
286
		if(!isset($_SESSION['error'])) {
287
288
                        # Check secondary fields
289
			$this->correct_post_fields();
290
291
			# update
292
		        $db->query("UPDATE ".PAGES_FEED_TABLE."
293
		        		SET
294
		        			status = '".$post->status."',
295
		        			group_access = '".$post->gids."',
296
		        			sort = '".$post->itemsort."',
297
						title = '".$post->title."',
298
						meta_title = '".$post->meta_title."',
299
						meta_description = '".$post->meta_description."',
300
						meta_keywords = '".$post->meta_keywords."',
301
						brief_item = '".$post->brief_item."',
302
						full_item = '".$post->full_item."',
303
						date_publications = '".$post->date_publications."',
304
						date_end_publications = '".$post->date_end_publications."',
305
						date_update = '".time()."',
306
						author_id = '".$post->author_id."'
307
					WHERE
308
						id = '".$id."'");
309
310
			# save tags
311
			$tags->save_tags($post->tags, "feeditemid=".$id);
312
313
			# notice
314
			$logger->info("Запись #".$id." <".$post->title."> успешно отредактирована.");
315
316
			# update images
317
			$img->update_images_info("feeditemid", $id);
318
319
			# attachment images
320
			$images = $img->upload_image("images", "", array($this->feed['thumb_img_width'], $this->feed['thumb_img_height']));
321
			if($images) {
322
				foreach($images AS $image) {
323
					$img->insert_images($image, "feeditemid=".$id, $post->title);
324
				}
325
			}
326
327
			# attachment files
328
			$files->upload("files", "feeditemid=".$id);
329
330
			# go
331
			go(CP."?act=feeds&part=control&page=".$get->_page);
332
		}
333
334
		# back
335
		goback();
336
	}
337
338
339
	/**
340
	 * Migrate record to another feed
341
	 *
342
	 * @param int $id - record identificator from feed
343
	 */
344
	public function migrate_item($id) {
345
346
		global $db, $logger, $tpl, $smarty, $post;
347
348
		# Migrate
349
		if(isset($post->from) && isset($post->to) && $db->check_id($post->from, STRUCTURE_TABLE, "id", "page_type='feed'") && $db->check_id($post->to, STRUCTURE_TABLE, "id", "page_type='feed'")) {
350
351
			$db->query("UPDATE ".PAGES_FEED_TABLE."
352
		        		SET	sid = '".$post->to."',
353
						date_update = '".time()."'
354
					WHERE	id = '".$id."'");
355
356
			# recount items
357
			$this->count_items($post->from);
358
			$this->count_items($post->to);
359
360
361
			# notice
362
			$logger->info("Элемент #".$id." успешно перемещен.");
363
364
			#go
365
			go(CP."?act=feeds&part=control&page=".$post->to);
366
		}
367
368
369
		# get data item from db
370
		$q = $db->query("SELECT id, sid, title FROM ".PAGES_FEED_TABLE." WHERE id='".$id."'");
371
		$data = $db->fetch_assoc($q);
372
373
		# smarty vars
374
		$smarty->assign("item", $data);
375
376
377
		# get data feeds from db
378
		$feeds = [];
379
		$q = $db->query("SELECT id, title, alias FROM ".STRUCTURE_TABLE." WHERE page_type='feed' ORDER BY id ASC");
380
		while($row = $db->fetch_assoc($q)) {
381
			$feeds[$row['id']] = $row;
382
		}
383
384
		# smarty vars
385
		$smarty->assign("feeds", $feeds);
386
387
		# tpl
388
		$content = $tpl->load_template("feeds_migrate_item_feed", true);
389
		$smarty->assign("content", $content);
390
	}
391
392
393
	/**
394
	 * Change status to record feed
395
	 *
396
	 * @param int $id - record id
397
	 * @param int $status - 1=show , 0=hide
398
	 */
399
	public function change_item_status($id, $status = 1) {
400
401
		global $db, $logger;
402
403
		$status = (int) filter_var($status, FILTER_VALIDATE_BOOLEAN);
404
405
		# update data in db
406
		$db->query("UPDATE ".PAGES_FEED_TABLE." SET status='".$status."' WHERE id='".$id."'");
407
408
		# notice
409
		$mstatus = ($status) ? "Видимый" : "Скрытый" ;
410
		$logger->info("Запись #".$id." успешно изменила свой статус на <".$mstatus.">.");
411
412
		# go
413
		goback();
414
	}
415
416
417
	/**
418
	 * Remove record from feed
419
	 *
420
	 * @param int $id - record id
421
	 */
422
	public function delete_item($id) {
423
424
		global $db, $logger, $img, $files, $tags;
425
426
		# get sid
427
		$q = $db->query("SELECT sid FROM ".PAGES_FEED_TABLE." WHERE id='".$id."'");
428
		$row = $db->fetch_assoc($q);
429
430
		# del attached images
431
		$img->remove_images("feeditemid=".$id);
432
433
		# del attached files
434
		$files->remove_files("feeditemid=".$id);
435
436
		# del tags
437
		$tags->save_tags("", "feeditemid=".$id);
438
439
		# delete item
440
		$db->query("DELETE FROM ".PAGES_FEED_TABLE." WHERE id='".$id."'");
441
442
		# recount items
443
		$this->count_items($row['sid']);
444
445
		# notice
446
		$logger->info("Элемент #".$id." успешно удален.");
447
448
		# go
449
		goback();
450
	}
451
452
453
	/**
454
	 * Remove feed
455
	 *
456
	 * @param int $sid - structure element id
457
	 */
458
	public function delete_feed($sid) {
459
460
		global $db, $img, $files, $tags;
461
462
		$cond = "";
463
		$f = $db->query("SELECT id FROM ".PAGES_FEED_TABLE." WHERE sid='".$sid."'");
464
		while($fid = $db->fetch_assoc($f)) {
465
			# del tags
466
			$tags->save_tags("", "feeditemid=".$fid['id']);
467
			# cond
468
			$cond = $db->qcond_or($cond);
469
			$cond .= " attachedto='feeditemid=".$fid['id']."' " ;
470
		}
471
472
		# del attached images
473
		if(trim($cond) != "") {
474
                	$img->remove_images($cond, true);
475
                	$files->remove_files($cond, true);
476
		}
477
478
		$db->query("DELETE FROM ".PAGES_FEED_TABLE." WHERE sid='".$sid."'");
479
	}
480
481
482
	/**
483
	 * Settings feed
484
	 */
485
	public function settings() {
486
487
		global $config, $tpl, $smarty;
488
489
		# Уведомление о глобальном отключении RSS лент
490
		$this->feed['rss_warn'] = (!$config->rss_power) ? true : false ;
491
492
		# глобальное значение количества элементов на страницу
493
		$this->feed['global_items_per_page'] =& $config->feed_items_per_page;
494
495
		# default thumb size
496
		$default_thumb_size = array('width'	=> $config->gd_thumb_image_width,
497
					    'height'	=> $config->gd_thumb_image_height);
498
499
		# smarty vars
500
		$smarty->assign("feed",$this->feed);
501
		$smarty->assign("default_thumb_size", $default_thumb_size);
502
503
		# tpl
504
		$content = $tpl->load_template("feeds_settings_feed", true);
505
		$smarty->assign("content", $content);
506
	}
507
508
509
	/**
510
	 * Settings update to feed
511
	 */
512
	public function update_settings() {
513
514
		global $db, $img, $post, $logger;
515
516
		if(isset($post->update_settings)) {
517
			# update buffer
518
			$update = "";
519
520
			# RSS flag
521
			$rss = 0;
522
			if($post->rss == "1") {
523
				$rss = 1;
524
			}
525
			$update .= " rss='".$rss."', ";
526
527
			# items per page
528
			$items_per_page = 0;
529
			if(round($post->items_per_page) >= 0) {
530
				$items_per_page = round($post->items_per_page);
531
			}
532
			$update .= " items_per_page='".$items_per_page."', " ;
533
534
			# thumbnail check
535
			$img->check_post_thumb_parametrs();
536
537
			# items sorting in feed
538
			$items_sorting = "datepublication";
539
			if(isset($post->items_sorting)) {
540
				switch($post->items_sorting) {
541
					case 'title_asc':
542
						$items_sorting = "title_asc";
543
						break;
544
545
					case 'title_desc':
546
						$items_sorting = "title_desc";
547
						break;
548
549
					case 'manual_sorting':
550
						$items_sorting = "manual_sorting";
551
						break;
552
				}
553
			}
554
			$update .= " items_sorting = '".$items_sorting."', ";
555
556
			# show_child_feeds
557
			$show_child_feeds = "none";
558
			if(isset($post->show_child_feeds)) {
559
				switch($post->show_child_feeds) {
560
					case 'default':
561
						$show_child_feeds = "default";
562
						break;
563
564
					case 'forced':
565
						$show_child_feeds = "forced";
566
						break;
567
				}
568
			}
569
570
571
			# up data to db
572
			$db->query("UPDATE ".STRUCTURE_TABLE."
573
					SET
574
						".$update."
575
						show_child_feeds='".$show_child_feeds."',
576
						thumb_img_width='".$post->thumb_img_width."',
577
						thumb_img_height='".$post->thumb_img_height."',
578
						append_info_before='".$post->append_info_before."',
579
						append_info_after='".$post->append_info_after."',
580
						date_modified='".time()."'
581
					WHERE
582
						id='".$this->feed['id']."'");
583
584
			$logger->info("Настройки ленты #".$this->feed['id']." успешно обновлены.");
585
		}
586
587
		# go
588
		goback();
589
	}
590
591
592
	/**
593
	 * Recount records in feed
594
	 *
595
	 * @param int $sid - feed id
596
	 */
597
	public function count_items($sid) {
598
599
		global $db;
600
601
		# count
602
		$items = $db->count(PAGES_FEED_TABLE, "sid='".$sid."'");
603
604
		# save
605
		$db->query("UPDATE ".STRUCTURE_TABLE." SET items='".$items."' WHERE id='".$sid."'");
606
	}
607
608
609
	/**
610
	 * Check data post
611
	 */
612
	private function check_post_data_fields() {
613
614
		global $post, $logger;
615
616
		# title
617
		if(!isset($post->title)) {
618
			$logger->error("Не заполнен заголовок элемента", false);
619
		}
620
621
		# full desc item
622
		if(!isset($post->full_item)) {
623
			$logger->error("Не заполнен подробный текст элемента", false);
624
		}
625
626
		# status
627
		$post->status = (int) filter_var($post->status, FILTER_VALIDATE_BOOLEAN);
628
	}
629
630
631
	/**
632
	 *  Check dates from data post
633
	 */
634
	private function control_post_data_date() {
635
636
		global $post, $parse;
637
638
		# check isset date publication
639
		if(!isset($post->date_publications)) {
640
			$post->date_publications = date("d.m.Y",time());
641
		}
642
643
		# check isset date end publication
644
		if(!isset($post->date_end_publications)) {
645
			$post->date_end_publications = 0;
646
		}
647
648
		# date publications
649
		$post->date_publications = $parse->date->rusint_to_unix($post->date_publications);
650
651
		# date end publications
652
		if($post->date_end_publications != 0) {
653
			$post->date_end_publications = $parse->date->rusint_to_unix($post->date_end_publications);
654
		}
655
656
		if($post->date_end_publications <= $post->date_publications) {
657
			$post->date_end_publications = 0;
658
		}
659
	}
660
661
662
	/**
663
	 * Check and correct secondary fields
664
	 */
665
	private function correct_post_fields() {
666
667
		global $users, $post;
668
669
		# tags
670
		if(!isset($post->tags)) {
671
			$post->tags = NULL;
672
		}
673
674
		# sort
675
		if(!isset($post->itemsort) || round($post->itemsort) < 0) {
676
			$post->itemsort = 0;
677
		}
678
		else {
679
			$post->itemsort = round($post->itemsort);
680
		}
681
682
		# group ids with access
683
		if(isset($post->gids) && is_array($post->gids)) {
684
			$post->gids = implode(",", $post->gids);
685
		}
686
		else {
687
			$post->gids = 0;
688
		}
689
690
		# userlist
691
		$this->userlist = $users->get_userlist();
692
693
		# author
694
		if(!isset($post->author_id) || !array_key_exists($post->author_id, $this->userlist)) {
695
			$post->author_id = 0;
696
		}
697
	}
698
699
700
	/**
701
	 * Это временная функция
702
	 *
703
	 * @param int    $id
704
	 * @param string $title
705
	 * @param string $subject
706
	 */
707
	private function mailing($id, $title, $subject) {
708
709
		global $parse, $mailer, $logger, $users, $mailer, $site;
710
711
		# get userlist
712
		$userlist = $users->get_userlist(1, 0, 1);
713
714
		# html
715
		$subject = $parse->text->html($subject);
716
		$subject = "<h1>".$title."</h1>
717
				".$subject."
718
				<br /><br /><a href=\"http://".$site['domain']."/index.php?page=".$this->feed['alias']."&id=".$id."\">Читать полностью</a>";
719
720
		# send to email
721
		if(count($userlist) != 0) {
722
			$mailer->spread($userlist, $title, $subject);
723
		}
724
		else {
725
			$logger->error("Сообщение не отправлено! Не обнаружены подписчики подходящие под заданные критерии.", false);
726
		}
727
	}
728
}
729