Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
user.php
1<?php
2namespace Bitrix\Forum;
3
13
14
15Loc::loadMessages(__FILE__);
16
60class UserTable extends Main\Entity\DataManager
61{
67 public static function getTableName()
68 {
69 return 'b_forum_user';
70 }
71
77 public static function getMap()
78 {
79 return array(
80 'ID' => array(
81 'data_type' => 'integer',
82 'primary' => true,
83 'autocomplete' => true,
84 ),
85 'USER_ID' => array(
86 'data_type' => 'integer',
87 'required' => true
88 ),
89 'USER' => array(
90 'data_type' => 'Bitrix\Main\UserTable',
91 'reference' => array(
92 '=this.USER_ID' => 'ref.ID'
93 )
94 ),
95 'DESCRIPTION' => array(
96 'data_type' => 'string',
97 ),
98 'AVATAR' => array(
99 'data_type' => 'integer'
100 ),
101 'POINTS' => array(
102 'data_type' => 'integer'
103 ),
104 'RANK_ID' => array(
105 'data_type' => 'integer'
106 ),
107 'NUM_POSTS' => array(
108 'data_type' => 'integer'
109 ),
110 'INTERESTS' => array(
111 'data_type' => 'text'
112 ),
113 'LAST_POST' => array(
114 'data_type' => 'integer'
115 ),
116 'SIGNATURE' => array(
117 'data_type' => 'string'
118 ),
119 'IP_ADDRESS' => array(
120 'data_type' => 'string',
121 'size' => 255
122 ),
123 'REAL_IP_ADDRESS' => array(
124 'data_type' => 'string',
125 'size' => 255
126 ),
127 'DATE_REG' => array(
128 'data_type' => 'datetime',
129 'required' => true,
130 'default_value' => function(){return new DateTime();}
131 ),
132 'LAST_VISIT' => array(
133 'data_type' => 'datetime',
134 'required' => true,
135 'default_value' => function(){return new DateTime();}
136 ),
137 'ALLOW_POST' => array(
138 'data_type' => "boolean",
139 'values' => array("N", "Y"),
140 'default_value' => "Y"
141 ),
142 'SHOW_NAME' => array(
143 'data_type' => "boolean",
144 'values' => array("N", "Y"),
145 'default_value' => "Y"
146 ),
147 'HIDE_FROM_ONLINE' => array(
148 'data_type' => "boolean",
149 'values' => array("N", "Y"),
150 'default_value' => "N"
151 ),
152 'SUBSC_GROUP_MESSAGE' => array(
153 'data_type' => "boolean",
154 'values' => array("N", "Y"),
155 'default_value' => "N"
156 ),
157 'SUBSC_GET_MY_MESSAGE' => array(
158 'data_type' => "boolean",
159 'values' => array("N", "Y"),
160 'default_value' => "Y"
161 )
162 );
163 }
164 public static function onBeforeAdd(Event $event)
165 {
166 $result = new Main\ORM\EventResult();
168 $data = $event->getParameter("fields");
169 if ($res = UserTable::getList([
170 "select" => ["ID"],
171 "filter" => ["USER_ID" => $data["USER_ID"]]
172 ])->fetch())
173 {
174 $result->addError(new EntityError("Error: User is already exists.", "event"));
175 return $result;
176 }
177
178 return self::modifyData($event, $result);
179 }
180
181 public static function onBeforeUpdate(Main\ORM\Event $event)
182 {
183 $result = new Main\ORM\EventResult();
184
185 return self::modifyData($event, $result);
186 }
187
188 private static function modifyData(Main\ORM\Event $event, Main\ORM\EventResult $result)
189 {
190 $data = array_merge($event->getParameter("fields"), $result->getModified());
191 $fields = [];
192
193 //region check image
194 if (array_key_exists("AVATAR", $data))
195 {
196 \CFile::ResizeImage($data["AVATAR"], array(
197 "width" => Main\Config\Option::get("forum", "avatar_max_width", 100),
198 "height" => Main\Config\Option::get("forum", "avatar_max_height", 100)));
199 $maxSize = Main\Config\Option::get("forum", "file_max_size", 5242880);
200 if ($str = \CFile::CheckImageFile($data["AVATAR"], $maxSize))
201 {
202 $result->addError(new FieldError(static::getEntity()->getField("AVATAR"), $str));
203 }
204 else
205 {
206 $fields["AVATAR"] = $data["AVATAR"];
207 $fields["AVATAR"]["MODULE_ID"] = "forum";
208 if ($id = $event->getParameter("id"))
209 {
210 $id = is_integer($id) ? $id : $id["ID"];
211 if ($id > 0 && ($res = UserTable::getById($id)->fetch()) && ($res["AVATAR"] > 0))
212 {
213 $fields["AVATAR"]["old_file"] = $res["AVATAR"];
214 }
215 }
216 if (!\CFile::SaveForDB($fields, "AVATAR", "forum/avatar"))
217 {
218 $result->unsetField("AVATAR");
219 }
220 }
221 }
222 //endregion
223 if (!empty($fields))
224 {
225 $result->modifyFields(array_merge($result->getModified(), $fields));
226 }
227 return $result;
228 }
229
230 public static function onBeforeDelete(Main\ORM\Event $event)
231 {
232 $result = new Main\ORM\EventResult();
233 $id = $event->getParameter("id");
234 $id = $id["ID"];
235 if (($events = GetModuleEvents("forum", "onBeforeUserDelete", true)) && !empty($events))
236 {
237 foreach ($events as $ev)
238 {
239 if (ExecuteModuleEventEx($ev, array($id)) === false)
240 {
241 $result->addError(new EntityError("Error: ".serialize($ev), "event"));
242 return $result;
243 }
244 }
245 }
246 if (($user = UserTable::getById($id)->fetch()) && $user["AVATAR"] > 0)
247 {
248 \CFile::Delete($user["AVATAR"]);
249 }
250 return $result;
251 }
252
253 public static function onAfterDelete(Main\ORM\Event $event)
254 {
255 $id = $event->getParameter("id");
256 $id = $id["ID"];
257 foreach(GetModuleEvents("forum", "onAfterUserDelete", true) as $arEvent)
258 {
259 ExecuteModuleEventEx($arEvent, [$id]);
260 }
261 }
262}
263
264class User implements \ArrayAccess {
266 use Internals\EntityBaseMethods;
268 protected $id = 0;
270 protected $data = [];
272 protected $forumUserId = null;
274 protected $locked = false;
276 protected $groups;
277
279 protected $permissions = [];
281 private $editOwn = false;
282
283 protected function __construct($id)
284 {
285 $this->data = [
286 "VISIBLE_NAME"=> "Guest"
287 ];
288 if ($id > 0)
289 {
290 $user = UserTable::getList(array(
291 "select" => array(
292 "*",
293 "ACTIVE" => "USER.ACTIVE",
294 "NAME" => "USER.NAME",
295 "SECOND_NAME" => "USER.SECOND_NAME",
296 "LAST_NAME" => "USER.LAST_NAME",
297 "LOGIN" => "USER.LOGIN"
298 ),
299 "filter" => array("USER_ID" => (int)$id),
300 "limit" => 1,
301 ))->fetch();
302 if ($user)
303 {
304 $this->forumUserId = $user["ID"];
305 $this->id = $user["USER_ID"];
306 $this->locked = ($user["ACTIVE"] !== "Y" || $user["ALLOW_POST"] !== "Y");
307 }
308 elseif ($user = Main\UserTable::getList(array(
309 'select' => array('*'),
310 'filter' => array('ID' => (int)$id),
311 'limit' => 1,
312 ))->fetch())
313 {
314 $this->id = $user["ID"];
315 $this->locked = ($user["ACTIVE"] !== "Y");
316
317 $this->data["ALLOW_POST"] = "Y";
318 $this->data["SHOW_NAME"] = (\COption::GetOptionString("forum", "USER_SHOW_NAME", "Y") == "Y" ? "Y" : "N");
319 }
320 else
321 {
322 throw new Main\ObjectNotFoundException("User was not found.");
323 }
324 $this->data = $user;
325 $this->data["NAME"] = $user["NAME"];
326 $this->data["SECOND_NAME"] = $user["SECOND_NAME"];
327 $this->data["LAST_NAME"] = $user["LAST_NAME"];
328 $this->data["LOGIN"] = $user["LOGIN"];
329 $this->data["ALLOW_POST"] = ($this->data["ALLOW_POST"] === "N" ? "N" : "Y");
330 if ($this->data["SHOW_NAME"] !== "Y" && $this->data["SHOW_NAME"] !== "N")
331 $this->data["SHOW_NAME"] = (\COption::GetOptionString("forum", "USER_SHOW_NAME", "Y") == "Y" ? "Y" : "N");
332 $this->data["VISIBLE_NAME"] = ($this->data["SHOW_NAME"] === "Y" ? \CUser::FormatName(\CSite::getNameFormat(false), $user, true, false) : $this->data["LOGIN"]);
333 $this->editOwn = (\COption::GetOptionString("forum", "USER_EDIT_OWN_POST", "Y") == "Y");
334 }
335
336 }
340 public function getName()
341 {
342 return $this->data["VISIBLE_NAME"];
343 }
344
345 public function setLastVisit()
346 {
347 if ($this->getId() <= 0)
348 {
349 return;
350 }
351
352 $connection = Main\Application::getConnection();
353 $helper = $connection->getSqlHelper();
354 $tableName = UserTable::getTableName();
355 $update = $helper->prepareUpdate($tableName, ['LAST_VISIT' => new Main\DB\SqlExpression($helper->getCurrentDateTimeFunction())]);
356 $where = $helper->prepareAssignment($tableName, 'USER_ID', $this->getId());
357 $sql = 'UPDATE '.$helper->quote($tableName).' SET '.$update[0].' WHERE '.$where;
358 $connection->queryExecute($sql, $update[1]);
359 if ($connection->getAffectedRowsCount() <= 0)
360 {
361 $merge = $helper->prepareMerge(
362 'b_forum_user',
363 array('USER_ID'),
364 array(
365 'SHOW_NAME' => ($this->data['SHOW_NAME'] === 'N' ? 'N' : 'Y'),
366 'ALLOW_POST' => ($this->data['ALLOW_POST'] === 'N' ? 'N' : 'Y'),
367 'USER_ID' => $this->getId(),
368 'DATE_REG' => new Main\DB\SqlExpression($helper->getCurrentDateTimeFunction()),
369 'LAST_VISIT' => new Main\DB\SqlExpression($helper->getCurrentDateTimeFunction())
370 ),
371 array(
372 'LAST_VISIT' => new Main\DB\SqlExpression($helper->getCurrentDateTimeFunction())
373 )
374 );
375 if ($merge[0] != '')
376 {
377 $connection->query($merge[0]);
378 }
379 }
380
381 unset($GLOBALS['FORUM_CACHE']['USER']);
382 unset($GLOBALS['FORUM_CACHE']['USER_ID']);
383 }
384
385 public function setLocation(int $forumId = 0, int $topicId = 0)
386 {
387 global $USER;
388 if (!($USER instanceof \CUser && $this->getId() === $USER->GetID()))
389 {
390 return;
391 }
392
393 $connection = Main\Application::getConnection();
394 $helper = $connection->getSqlHelper();
395
396 $primaryFields = [
397 'USER_ID' => $this->getId(),
398 'PHPSESSID' => $this->getSessId()
399 ];
400 $fields = [
401 'SHOW_NAME' => $this->getName(),
402 'IP_ADDRESS' => Main\Service\GeoIp\Manager::getRealIp(),
403 'LAST_VISIT' => new Main\DB\SqlExpression($helper->getCurrentDateTimeFunction()),
404 'SITE_ID' => SITE_ID,
405 'FORUM_ID' => $forumId,
406 'TOPIC_ID' => $topicId,
407 ];
408
409 if ($this->getId() > 0)
410 {
411 $fields['PHPSESSID'] = $primaryFields['PHPSESSID'];
412 unset($primaryFields['PHPSESSID']);
413 }
414
415 $merge = $helper->prepareMerge(
416 'b_forum_stat',
417 array_keys($primaryFields),
418 $primaryFields + $fields,
419 $fields
420 );
421 if ($merge[0] != '')
422 {
423 $connection->query($merge[0]);
424 }
425 }
426
427 public function isLocked()
428 {
429 return $this->locked;
430 }
431
432 public function isAdmin()
433 {
434 if ($this->isLocked())
435 return false;
436 return self::isUserAdmin($this->getGroups());
437 }
438
439 public function isGuest()
440 {
441 return ($this->getId() <= 0);
442 }
443
444 public function isAuthorized()
445 {
446 return ($this->getId() > 0);
447 }
448
449 public function edit(array $fields)
450 {
451 $result = new Result();
452
453 if (!$this->isAuthorized())
454 {
455 return $result;
456 }
457
458 foreach (GetModuleEvents("forum", "onBeforeUserEdit", true) as $arEvent)
459 {
460 if (ExecuteModuleEventEx($arEvent, [$this->forumUserId, $this->getId(), &$fields]) === false)
461 {
462 $result->addError(new Error("Event error"));
463 return $result;
464 }
465 }
466
467 $result = $this->save($fields);
468
469 if ($result->isSuccess())
470 {
471 foreach(GetModuleEvents("forum", "onAfterUserEdit", true) as $arEvent)
472 {
473 ExecuteModuleEventEx($arEvent, array($this->forumUserId, $this->getId(), $fields));
474 }
475 }
476
477 return $result;
478 }
479
480 public function calculateStatistic()
481 {
482 $result = new Result();
483
484 if (!$this->isAuthorized())
485 {
486 return $result;
487 }
488
489 $fields = [
490 "LAST_POST" => 0,
491 "NUM_POSTS" => 0,
492 "POINTS" => 0
493 ];
494 if ($res = MessageTable::getList([
495 "select" => ["CNT", "LAST_MESSAGE_ID"],
496 "filter" => ["AUTHOR_ID" => $this->getId(), "APPROVED" => "Y"],
497 "runtime" => [
498 new Main\Entity\ExpressionField("CNT", "COUNT(*)"),
499 new Main\Entity\ExpressionField("LAST_MESSAGE_ID", "MAX(%s)", ["ID"])
500 ],
501 ])->fetch())
502 {
503 $fields = [
504 "LAST_POST" => $res["LAST_MESSAGE_ID"],
505 "NUM_POSTS" => $res["CNT"],
506 "POINTS" => \CForumUser::GetUserPoints($this->getId(), ["NUM_POSTS" => $res["CNT"]])
507 ];
508 }
509 return $this->save($fields);
510 }
511
512 public function incrementStatistic(array $message)
513 {
514 if (!$this->isAuthorized() || $message["APPROVED"] != "Y")
515 {
516 return;
517 }
518
519 $this->data["NUM_POSTS"]++;
520 $this->data["POINTS"] = \CForumUser::GetUserPoints($this->getId(), array("INCREMENT" => $this->data["NUM_POSTS"]));
521 $this->data["LAST_POST"] = $message["ID"];
522 $this->save([
523 "NUM_POSTS" => new Main\DB\SqlExpression('?# + 1', "NUM_POSTS"),
524 "POINTS" => $this->data["POINTS"],
525 "LAST_POST" => $message["ID"]
526 ]);
527 }
528
529 public function decrementStatistic($message = null)
530 {
531 if (!$this->isAuthorized() || $message['APPROVED'] != 'Y')
532 {
533 return;
534 }
535
536 $this->data['NUM_POSTS']--;
537 $this->data['POINTS'] = \CForumUser::GetUserPoints($this->getId(), array('INCREMENT' => $this->data['NUM_POSTS']));
538 $fields = [
539 'NUM_POSTS' => new Main\DB\SqlExpression('?# - 1', 'NUM_POSTS'),
540 'POINTS' => $this->data['POINTS'],
541 ];
542 if ($message === null ||
543 $message['ID'] === $this->data['LAST_POST']
544 )
545 {
546 $message = MessageTable::getList([
547 'select' => ['ID'],
548 'filter' => ['AUTHOR_ID' => $this->getId(), 'APPROVED' => 'Y'],
549 'limit' => 1,
550 'order' => ['ID' => 'DESC']
551 ])->fetch();
552 $this->data['LAST_POST'] = $message['ID'];
553 $fields['LAST_POST'] = $message['ID'];
554 }
555 $this->save($fields);
556 }
557
561 public function getUnreadMessageId($topicId = 0): ?int
562 {
563 if ($topicId <= 0)
564 {
565 return null;
566 }
567
568 try
569 {
570 $topic = Topic::getById($topicId);
571 }
572 catch (Main\ObjectNotFoundException $e)
573 {
574 return null;
575 }
576
577 $query = MessageTable::query()
578 ->setSelect(['ID'])
579 ->where('TOPIC_ID', $topic->getId())
580 ->registerRuntimeField('FORCED_INT_ID', new Main\Entity\ExpressionField('FORCED_ID', '%s + ""', ['ID']))
581 ->setOrder(['FORCED_INT_ID' => 'ASC'])
582 ->setLimit(1);
583 if ($this->isAuthorized())
584 {
585 $query
586 ->registerRuntimeField(
587 'USER_TOPIC',
588 new Main\ORM\Fields\Relations\Reference(
589 'USER_TOPIC',
591 [
592 '=this.TOPIC_ID' => 'ref.TOPIC_ID',
593 '=ref.USER_ID' => ['?i', $this->getId()],
594 ],
595 ['join_type' => 'LEFT']
596 )
597 )
598 ->registerRuntimeField(
599 'USER_FORUM',
600 new Main\ORM\Fields\Relations\Reference(
601 'USER_FORUM',
602 UserForumTable::getEntity(),
603 [
604 '=this.FORUM_ID' => 'ref.FORUM_ID',
605 '=ref.USER_ID' => ['?i', $this->getId()]
606 ],
607 ['join_type' => 'LEFT']
608 )
609 )
610 ->registerRuntimeField(
611 'USER_FORUM_0',
612 new Main\ORM\Fields\Relations\Reference(
613 'FUF0',
614 UserForumTable::getEntity(),
615 [
616 '=this.FORUM_ID' => ['?i', 0],
617 '=ref.USER_ID' => ['?i', $this->getId()]
618 ],
619 ['join_type' => 'LEFT']
620 )
621 )
622 ->where(
623 Main\ORM\Query\Query::filter()
624 ->logic('or')
625 ->where(
626 Main\ORM\Query\Query::filter()
627 ->whereNotNull('USER_TOPIC.LAST_VISIT')
628 ->whereColumn('POST_DATE', '>', 'USER_TOPIC.LAST_VISIT')
629 )
630 ->where(
631 Main\ORM\Query\Query::filter()
632 ->whereNull('USER_TOPIC.LAST_VISIT')
633 ->whereColumn('POST_DATE', '>', 'USER_FORUM.LAST_VISIT')
634 )
635 ->where(
636 Main\ORM\Query\Query::filter()
637 ->whereNull('USER_TOPIC.LAST_VISIT')
638 ->whereNull('USER_FORUM.LAST_VISIT')
639 ->whereColumn('POST_DATE', '>', 'USER_FORUM_0.LAST_VISIT')
640 )
641 ->where(
642 Main\ORM\Query\Query::filter()
643 ->whereNull('USER_TOPIC.LAST_VISIT')
644 ->whereNull('USER_FORUM.LAST_VISIT')
645 ->whereNull('USER_FORUM_0.LAST_VISIT')
646 ->whereNotNull('ID')
647 )
648 );
649 }
650 else
651 {
652 $timestamps = $this->getFromSession('GUEST_TID');
653 $lastVisit = max(
654 $this->getFromSession('LAST_VISIT_FORUM_0'),
655 $this->getFromSession('LAST_VISIT_FORUM_'.$topic->getForumId()),
656 is_array($timestamps) && array_key_exists($topic->getId(), $timestamps) ? $timestamps[$topic->getId()] : 0
657 );
658 if ($lastVisit > 0)
659 {
660 $query->where('POST_DATE', '>', DateTime::createFromTimestamp($lastVisit));
661 }
662 else
663 {
664 return null;
665 }
666 }
667 if ($res = $query->fetch())
668 {
669 return $res['ID'];
670 }
671 return null;
672 }
673
678 public function readTopic($topicId = 0): void
679 {
680 if ($topicId <= 0
681 || !($topic = Topic::getById($topicId))
682 || !($topic instanceof Topic)
683 )
684 {
685 return;
686 }
687
688 $topic->incrementViews();
689
690 if ($this->isAuthorized())
691 {
692 $connection = Main\Application::getConnection();
693 $helper = $connection->getSqlHelper();
694
695 $primaryFields = [
696 'USER_ID' => $this->getId(),
697 'TOPIC_ID' => $topic->getId()
698 ];
699
700 $fields = [
701 'FORUM_ID' => $topic->getForumId(),
702 'LAST_VISIT' => new Main\DB\SqlExpression($helper->getCurrentDateTimeFunction())
703 ];
704
705 $result = UserTopicTable::update($primaryFields, $fields);
706 if ($result->getAffectedRowsCount() <= 0)
707 {
708 $merge = $helper->prepareMerge(
709 'b_forum_user_topic',
710 array_keys($primaryFields),
711 $primaryFields + $fields,
712 $fields
713 );
714 if ($merge[0] != '')
715 {
716 $connection->query($merge[0]);
717 }
718 }
719 }
720 else
721 {
722 $timestamp = new DateTime();
723 $this->saveInSession('GUEST_TID', null);
724
725 if (Main\Config\Option::set('forum', 'USE_COOKIE', 'N') == 'Y')
726 {
727 $GLOBALS['APPLICATION']->set_cookie('FORUM_GUEST_TID', '', false, '/', false, false, 'Y', false);
728 }
729 }
730 }
731
732 public function readTopicsOnForum(int $forumId = 0)
733 {
734 if ($this->isAuthorized())
735 {
736 $connection = Main\Application::getConnection();
737 $helper = $connection->getSqlHelper();
738
739 $primaryFields = [
740 'USER_ID' => $this->getId(),
741 'FORUM_ID' => $forumId
742 ];
743
744 $fields = [
745 'LAST_VISIT' => new Main\DB\SqlExpression($helper->getCurrentDateTimeFunction())
746 ];
747
748 $result = Forum\UserForumTable::update($primaryFields, $fields);
749 if ($result->getAffectedRowsCount() <= 0)
750 {
751 $merge = $helper->prepareMerge(
753 array_keys($primaryFields),
754 $primaryFields + $fields,
755 $fields
756 );
757 if ($merge[0] != '')
758 {
759 $connection->query($merge[0]);
760 }
761 }
762
763 if ($forumId > 0)
764 {
765 Forum\UserTopicTable::deleteBatch(['USER_ID' => $this->getId(), 'FORUM_ID' => $forumId]);
766 }
767 else
768 {
769 Forum\UserTopicTable::deleteBatch(['USER_ID' => $this->getId()]);
770 Forum\UserForumTable::deleteBatch(['USER_ID' => $this->getId(), '>FORUM_ID' => 0]);
771 }
772 }
773 else
774 {
775 $timestamp = new DateTime();
776 $topics = $this->saveInSession('GUEST_TID', [$topic->getId() => $timestamp->getTimestamp()]);
777
778 if (Main\Config\Option::set('forum', 'USE_COOKIE', 'N') == 'Y')
779 {
780 foreach ($topics as $topicId => $timestamp)
781 {
782 $topics[$topicId] = implode('-', [$topicId, $timestamp]);
783 }
784 $GLOBALS['APPLICATION']->set_cookie('FORUM_GUEST_TID', implode('/', $topics), false, '/', false, false, 'Y', false);
785 }
786 }
787 }
788
789 private function save(array $fields)
790 {
791 $result = new Result();
792
793 if (!$this->isAuthorized())
794 {
795 return $result;
796 }
797
798 if ($this->forumUserId > 0)
799 {
800 $result = User::update($this->forumUserId, $fields);
801 }
802 else
803 {
804 $fields = ['USER_ID' => $this->getId()] + $fields + $this->data;
805 unset($fields['ID']);
806 $result = User::add($fields);
807 if ($result->isSuccess())
808 {
809 $res = $result->getPrimary();
810 if (is_array($res))
811 {
812 $res = reset($res);
813 }
814 $this->forumUserId = $res;
815 }
816 }
817 return $result;
818 }
819
820 public function getGroups()
821 {
822 if (!$this->groups)
823 {
824 global $USER;
825 $this->groups = [2];
826 if ($this->getId() <= 0 || $this->isLocked())
827 {
828 if (Main\Config\Option::get("main", "new_user_registration", "") == "Y")
829 {
830 $def_group = Main\Config\Option::get("main", "new_user_registration_def_group", "");
831 if($def_group != "" && ($res = explode(",", $def_group)))
832 {
833 $this->groups = array_merge($this->groups, $res);
834 }
835 }
836 }
837 elseif ($USER instanceof \CUser && $this->getId() === $USER->GetID())
838 {
839 $this->groups = $USER->GetUserGroupArray();
840 }
841 else
842 {
843 $dbRes = Main\UserGroupTable::getList(array(
844 "select" => ["GROUP_ID"],
845 "filter" => ["USER_ID" => $this->getId()],
846 "order" => ["GROUP_ID" => "ASC"]
847 ));
848 while ($res = $dbRes->fetch())
849 {
850 $this->groups[] = $res["GROUP_ID"];
851 }
852 }
853 }
854 return $this->groups;
855 }
856
857 public function setPermissionOnForum($forum, $permission)
858 {
859 $forum = Forum\Forum::getInstance($forum);
860 $this->permissions[$forum->getId()] = $permission;
861 return $this;
862 }
863
864 public function getPermissionOnForum($forum)
865 {
866 $forum = Forum\Forum::getInstance($forum);
867 if (!array_key_exists($forum->getId(), $this->permissions))
868 {
869 $this->permissions[$forum->getId()] = $forum->getPermissionForUser($this);
870 }
871 return $this->permissions[$forum->getId()];
872 }
873
874 public function canModerate(Forum\Forum $forum)
875 {
876 return $this->getPermissionOnForum($forum->getId()) >= Permission::CAN_MODERATE;
877 }
878
879 public function canAddTopic(Forum\Forum $forum)
880 {
881 return $this->getPermissionOnForum($forum->getId()) >= Permission::CAN_ADD_TOPIC;
882 }
883
884 public function canAddMessage(Topic $topic)
885 {
886 if ($topic["STATE"] === Topic::STATE_OPENED && $topic["APPROVED"] === Topic::APPROVED_APPROVED)
887 {
889 }
890 return $this->getPermissionOnForum($topic->getForumId()) >= Permission::CAN_EDIT;
891 }
892
893 public function canEditTopic(Topic $topic)
894 {
896 {
897 return true;
898 }
899 if (!$this->isAuthorized())
900 {
901 return false;
902 }
903 if (
904 ($this->getId() == $topic->getAuthorId())
905 &&
906 ($this->editOwn || ($topic["POSTS"] <= 0 && $topic["POSTS_UNAPPROVED"] <= 0))
907 )
908 {
909 return true;
910 }
911 return false;
912 }
913
914 public function canEditMessage(Message $message)
915 {
916 if ($this->getPermissionOnForum($message->getForumId()) >= Permission::CAN_EDIT)
917 {
918 return true;
919 }
920 if (!$this->isAuthorized())
921 {
922 return false;
923 }
924 if ($this->getId() == $message->getAuthorId())
925 {
926 if ($this->editOwn)
927 {
928 return true;
929 }
930 $topic = Topic::getById($message["TOPIC_ID"]);
931 if ($topic["ABS_LAST_MESSAGE_ID"] == $message->getId())
932 {
933 return true;
934 }
935 }
936 return false;
937 }
938
939 public function canDeleteMessage(Message $message)
940 {
941 return $this->canEditMessage($message);
942 }
943
944 public function canEditForum(Forum\Forum $forum)
945 {
946 return $this->getPermissionOnForum($forum->getId()) >= Permission::FULL_ACCESS;
947 }
948
949 public function canDeleteForum(Forum\Forum $forum)
950 {
951 return $this->canEditForum($forum);
952 }
953
954 public function canReadForum(Forum\Forum $forum)
955 {
956 return $this->getPermissionOnForum($forum->getId()) >= Permission::CAN_READ;
957 }
958
959 public function canReadTopic(Topic $topic)
960 {
961 return $this->getPermissionOnForum($topic->getForumId()) >= Permission::CAN_READ;
962 }
963
964 public static function isUserAdmin(array $groups)
965 {
966 global $APPLICATION;
967 return (in_array(1, $groups) || $APPLICATION->GetGroupRight("forum", $groups) >= "W");
968 }
969
970 private function saveInSession(string $name, $value)
971 {
972 if (method_exists(Main\Application::getInstance(), 'getKernelSession'))
973 {
974 $forumSession = Main\Application::getInstance()->getKernelSession()->get('FORUM');
975 }
976 else
977 {
978 $forumSession = $_SESSION['FORUM'];
979 }
980 $forumSession = is_array($forumSession) ? $forumSession : [];
981 if (is_array($value) && array_key_exists($name, $forumSession) && is_array($forumSession[$name]))
982 {
983 $forumSession[$name] = $value + $forumSession[$name];
984 }
985 else
986 {
987 $forumSession[$name] = $value;
988 }
989 if (method_exists(Main\Application::getInstance(), 'getKernelSession'))
990 {
991 Main\Application::getInstance()->getKernelSession()->set('FORUM', $forumSession);
992 }
993 else
994 {
995 $_SESSION['FORUM'] = $forumSession;
996 }
997 return $forumSession[$name];
998 }
999
1000 private function getFromSession(string $name)
1001 {
1002 if (method_exists(Main\Application::getInstance(), 'getKernelSession'))
1003 {
1004 $forumSession = Main\Application::getInstance()->getKernelSession()->get('FORUM');
1005 }
1006 else
1007 {
1008 $forumSession = $_SESSION['FORUM'];
1009 }
1010 if (is_array($forumSession) && array_key_exists($name, $forumSession))
1011 {
1012 return $forumSession[$name];
1013 }
1014 return null;
1015 }
1016
1017 private function getSessId()
1018 {
1019 if (method_exists(Main\Application::getInstance(), 'getKernelSession'))
1020 {
1021 return Main\Application::getInstance()->getKernelSession()->getId();
1022 }
1023 return bitrix_sessid();
1024 }
1025
1026 public static function add(array &$data)
1027 {
1028 $result = new \Bitrix\Main\ORM\Data\AddResult();
1029 if (($events = GetModuleEvents("forum", "onBeforeUserAdd", true)) && !empty($events))
1030 {
1031 global $APPLICATION;
1032 foreach ($events as $ev)
1033 {
1034 $APPLICATION->ResetException();
1035
1036 if (ExecuteModuleEventEx($ev, array(&$data)) === false)
1037 {
1038 $errorMessage = Loc::getMessage("FORUM_EVENT_BEFORE_USER_ADD");
1039 if (($ex = $APPLICATION->GetException()) && ($ex instanceof \CApplicationException))
1040 {
1041 $errorMessage = $ex->getString();
1042 }
1043
1044 $result->addError(new \Bitrix\Main\Error($errorMessage, "onBeforeUserAdd"));
1045 return $result;
1046 }
1047 }
1048 }
1049
1050 $dbResult = UserTable::add($data);
1051
1052 if (!$dbResult->isSuccess())
1053 {
1054 $result->addErrors($dbResult->getErrors());
1055 }
1056 else
1057 {
1058 $id = $dbResult->getId();
1059 $result->setId($id);
1060 foreach (GetModuleEvents("forum", "onAfterUserAdd", true) as $event)
1061 {
1062 ExecuteModuleEventEx($event, [$id, $data]);
1063 }
1064 }
1065
1066 return $result;
1067 }
1068
1069 public static function update(int $id, array &$data)
1070 {
1071 unset($data["USER_ID"]);
1072
1073 $result = new Main\ORM\Data\UpdateResult();
1074 $result->setPrimary(["ID" => $id]);
1075
1076 if (($events = GetModuleEvents("forum", "onBeforeUserUpdate", true)) && !empty($events))
1077 {
1078 global $APPLICATION;
1079 foreach ($events as $ev)
1080 {
1081 $APPLICATION->ResetException();
1082
1083 if (ExecuteModuleEventEx($ev, array($id, &$data)) === false)
1084 {
1085 $errorMessage = Loc::getMessage("FORUM_EVENT_BEFORE_USER_UPDATE_ERROR");
1086 if (($ex = $APPLICATION->GetException()) && ($ex instanceof \CApplicationException))
1087 {
1088 $errorMessage = $ex->getString();
1089 }
1090 $result->addError(new Main\Error($errorMessage, "onBeforeUserUpdate"));
1091 return $result;
1092 }
1093 }
1094 }
1095
1096 $dbResult = UserTable::update($id, $data);
1097
1098 if (!$dbResult->isSuccess())
1099 {
1100 $result->addErrors($dbResult->getErrors());
1101 }
1102 else
1103 {
1104 foreach (GetModuleEvents("forum", "onAfterUserUpdate", true) as $event)
1105 {
1106 ExecuteModuleEventEx($event, [$id, $data]);
1107 }
1108 }
1109 return $result;
1110 }
1111}
const APPROVED_APPROVED
Definition topic.php:275
canReadForum(Forum\Forum $forum)
Definition user.php:954
canDeleteForum(Forum\Forum $forum)
Definition user.php:949
edit(array $fields)
Definition user.php:449
decrementStatistic($message=null)
Definition user.php:529
readTopicsOnForum(int $forumId=0)
Definition user.php:732
incrementStatistic(array $message)
Definition user.php:512
getUnreadMessageId($topicId=0)
Definition user.php:561
setLocation(int $forumId=0, int $topicId=0)
Definition user.php:385
canReadTopic(Topic $topic)
Definition user.php:959
canAddTopic(Forum\Forum $forum)
Definition user.php:879
canEditMessage(Message $message)
Definition user.php:914
canDeleteMessage(Message $message)
Definition user.php:939
canEditForum(Forum\Forum $forum)
Definition user.php:944
readTopic($topicId=0)
Definition user.php:678
static isUserAdmin(array $groups)
Definition user.php:964
setPermissionOnForum($forum, $permission)
Definition user.php:857
canAddMessage(Topic $topic)
Definition user.php:884
static update(int $id, array &$data)
Definition user.php:1069
canEditTopic(Topic $topic)
Definition user.php:893
canModerate(Forum\Forum $forum)
Definition user.php:874
getPermissionOnForum($forum)
Definition user.php:864
static add(array &$data)
Definition user.php:1026
static onAfterDelete(Main\ORM\Event $event)
Definition user.php:253
static onBeforeUpdate(Main\ORM\Event $event)
Definition user.php:181
static onBeforeDelete(Main\ORM\Event $event)
Definition user.php:230
static getTableName()
Definition user.php:67
getParameter($key)
Definition event.php:80
static loadMessages($file)
Definition loc.php:64
static getMessage($code, $replace=null, $language=null)
Definition loc.php:29
static update($primary, array $data)
static createFromTimestamp($timestamp)
Definition datetime.php:246
$GLOBALS['____1444769544']
Definition license.php:1