1C-Bitrix 25.700.0
Загрузка...
Поиск...
Не найдено
componenthelper.php
См. документацию.
1<?php
2
3namespace Bitrix\Socialnetwork;
4
5use Bitrix\Blog\Item\Post;
6use Bitrix\Crm\Activity\Provider\Tasks\Task;
7use Bitrix\Main\Component\ParameterSigner;
8use Bitrix\Disk\Driver;
9use Bitrix\Main\Loader;
10use Bitrix\Main\ModuleManager;
11use Bitrix\Main;
12use Bitrix\Main\Localization\Loc;
13use Bitrix\Main\Config\Option;
14use Bitrix\Main\EventManager;
15use Bitrix\Main\Security\Sign\BadSignatureException;
16use Bitrix\Main\Update\Stepper;
17use Bitrix\Main\UrlPreview\UrlPreview;
18use Bitrix\Socialnetwork\Item\Log;
19use Bitrix\Main\DB\SqlExpression;
20use Bitrix\Main\Application;
21use Bitrix\Disk\Uf\FileUserType;
22use Bitrix\Disk\AttachedObject;
23use Bitrix\Disk\File;
24use Bitrix\Disk\TypeFile;
25use Bitrix\Socialnetwork\Helper\Mention;
26use Bitrix\Main\Web\Json;
27use Bitrix\Main\ArgumentException;
28
29Loc::loadMessages(__FILE__);
30
32{
33 public const MAIN_SELECTOR_GROUPS_CACHE_TAG = 'sonet_main_selector_groups';
34 protected static $postsCache = [];
35 protected static $commentsCache = [];
36 protected static $commentListsCache = [];
37 protected static $commentCountCache = [];
38 protected static $authorsCache = [];
39 protected static $destinationsCache = [];
40
50 public static function getBlogPostData($postId, $languageId)
51 {
53
54 if (isset(self::$postsCache[$postId]))
55 {
56 $result = self::$postsCache[$postId];
57 }
58 else
59 {
60 if (!Loader::includeModule('blog'))
61 {
62 throw new Main\SystemException("Could not load 'blog' module.");
63 }
64
65 $res = \CBlogPost::getList(
66 [],
67 [
68 "ID" => $postId
69 ],
70 false,
71 false,
72 [ 'ID', 'BLOG_GROUP_ID', 'BLOG_GROUP_SITE_ID', 'BLOG_ID', 'PUBLISH_STATUS', 'TITLE', 'AUTHOR_ID', 'ENABLE_COMMENTS', 'NUM_COMMENTS', 'VIEWS', 'CODE', 'MICRO', 'DETAIL_TEXT', 'DATE_PUBLISH', 'CATEGORY_ID', 'HAS_SOCNET_ALL', 'HAS_TAGS', 'HAS_IMAGES', 'HAS_PROPS', 'HAS_COMMENT_IMAGES' ]
73 );
74
75 if ($result = $res->fetch())
76 {
77 if (!empty($result['DETAIL_TEXT']))
78 {
79 $result['DETAIL_TEXT'] = \Bitrix\Main\Text\Emoji::decode($result['DETAIL_TEXT']);
80 }
81
82 $result["ATTACHMENTS"] = [];
83
84 if($result["HAS_PROPS"] !== "N")
85 {
86 $userFields = $USER_FIELD_MANAGER->getUserFields("BLOG_POST", $postId, $languageId);
87 $postUf = [ 'UF_BLOG_POST_FILE' ];
88 foreach ($userFields as $fieldName => $userField)
89 {
90 if (!in_array($fieldName, $postUf))
91 {
92 unset($userFields[$fieldName]);
93 }
94 }
95
96 if (
97 !empty($userFields["UF_BLOG_POST_FILE"])
98 && !empty($userFields["UF_BLOG_POST_FILE"]["VALUE"])
99 )
100 {
101 $result["ATTACHMENTS"] = self::getAttachmentsData($userFields["UF_BLOG_POST_FILE"]["VALUE"], $result["BLOG_GROUP_SITE_ID"]);
102 }
103 }
104
105 $result["DETAIL_TEXT"] = self::convertDiskFileBBCode(
106 $result["DETAIL_TEXT"],
107 'BLOG_POST',
108 $postId,
109 $result["AUTHOR_ID"],
110 $result["ATTACHMENTS"]
111 );
112
113 $result["DETAIL_TEXT_FORMATTED"] = preg_replace(
114 [
115 '|\[DISK\sFILE\sID=[n]*\d+\]|',
116 '|\[DOCUMENT\sID=[n]*\d+\]|'
117 ],
118 '',
119 $result["DETAIL_TEXT"]
120 );
121
122 $result['DETAIL_TEXT_FORMATTED'] = Mention::clear($result['DETAIL_TEXT_FORMATTED']);
123
124 $p = new \blogTextParser();
125 $p->arUserfields = [];
126
127 $images = [];
128 $allow = [ 'IMAGE' => 'Y' ];
129 $parserParameters = [];
130
131 $result["DETAIL_TEXT_FORMATTED"] = $p->convert($result["DETAIL_TEXT_FORMATTED"], false, $images, $allow, $parserParameters);
132
133 $title = (
134 $result["MICRO"] === "Y"
135 ? \blogTextParser::killAllTags($result["DETAIL_TEXT_FORMATTED"])
136 : htmlspecialcharsEx($result["TITLE"])
137 );
138
139 $title = preg_replace(
140 '|\[MAIL\sDISK\sFILE\sID=[n]*\d+\]|',
141 '',
142 $title
143 );
144
145 $title = str_replace([ "\r\n", "\n", "\r" ], " ", $title);
146 $result["TITLE_FORMATTED"] = \TruncateText($title, 100);
147 $result["DATE_PUBLISH_FORMATTED"] = self::formatDateTimeToGMT($result['DATE_PUBLISH'], $result['AUTHOR_ID']);
148 }
149
150 self::$postsCache[$postId] = $result;
151 }
152
153 return $result;
154 }
155
164 public static function getBlogPostDestinations($postId)
165 {
166 if (isset(self::$destinationsCache[$postId]))
167 {
168 $result = self::$destinationsCache[$postId];
169 }
170 else
171 {
172 $result = [];
173
174 if (!Loader::includeModule('blog'))
175 {
176 throw new Main\SystemException("Could not load 'blog' module.");
177 }
178
179 $sonetPermission = \CBlogPost::getSocnetPermsName($postId);
180 if (!empty($sonetPermission))
181 {
182 foreach ($sonetPermission as $typeCode => $type)
183 {
184 foreach ($type as $destination)
185 {
186 $name = false;
187
188 if ($typeCode === "SG")
189 {
190 if ($sonetGroup = \CSocNetGroup::getByID($destination["ENTITY_ID"]))
191 {
192 $name = $sonetGroup["NAME"];
193 }
194 }
195 elseif ($typeCode === "U")
196 {
197 if(in_array("US" . $destination["ENTITY_ID"], $destination["ENTITY"], true))
198 {
199 $name = "#ALL#";
200 Loader::includeModule('intranet');
201 }
202 else
203 {
204 $name = \CUser::formatName(
205 \CSite::getNameFormat(false),
206 [
207 "NAME" => $destination["~U_NAME"],
208 "LAST_NAME" => $destination["~U_LAST_NAME"],
209 "SECOND_NAME" => $destination["~U_SECOND_NAME"],
210 "LOGIN" => $destination["~U_LOGIN"]
211 ],
212 true
213 );
214 }
215 }
216 elseif ($typeCode === "DR")
217 {
218 $name = $destination["EL_NAME"];
219 }
220
221 if ($name)
222 {
223 $result[] = $name;
224 }
225 }
226 }
227 }
228
229 self::$destinationsCache[$postId] = $result;
230 }
231
232 return $result;
233 }
234
244 public static function getBlogAuthorData($authorId, $params): array
245 {
246 if (isset(self::$authorsCache[$authorId]))
247 {
248 $result = self::$authorsCache[$authorId];
249 }
250 else
251 {
252 if (!Loader::includeModule('blog'))
253 {
254 throw new Main\SystemException("Could not load 'blog' module.");
255 }
256
257 $result = \CBlogUser::getUserInfo(
258 (int)$authorId,
259 '',
260 [
261 "AVATAR_SIZE" => (
262 isset($params["AVATAR_SIZE"])
263 && (int)$params["AVATAR_SIZE"] > 0
264 ? (int)$params["AVATAR_SIZE"]
265 : false
266 ),
267 "AVATAR_SIZE_COMMENT" => (
268 isset($params["AVATAR_SIZE_COMMENT"])
269 && (int)$params["AVATAR_SIZE_COMMENT"] > 0
270 ? (int)$params["AVATAR_SIZE_COMMENT"]
271 : false
272 ),
273 "RESIZE_IMMEDIATE" => "Y"
274 ]
275 );
276
277 $result["NAME_FORMATTED"] = \CUser::formatName(
278 \CSite::getNameFormat(false),
279 [
280 "NAME" => $result["~NAME"],
281 "LAST_NAME" => $result["~LAST_NAME"],
282 "SECOND_NAME" => $result["~SECOND_NAME"],
283 "LOGIN" => $result["~LOGIN"]
284 ],
285 true
286 );
287
288 self::$authorsCache[$authorId] = $result;
289 }
290
291 return $result;
292 }
293
305 public static function getBlogCommentListData($postId, $params, $languageId, &$authorIdList = []): array
306 {
307 if (isset(self::$commentListsCache[$postId]))
308 {
309 $result = self::$commentListsCache[$postId];
310 }
311 else
312 {
313 $result = [];
314
315 if (!Loader::includeModule('blog'))
316 {
317 throw new Main\SystemException("Could not load 'blog' module.");
318 }
319
320 $p = new \blogTextParser();
321
322 $selectedFields = [ 'ID', 'BLOG_GROUP_ID', 'BLOG_GROUP_SITE_ID', 'BLOG_ID', 'POST_ID', 'AUTHOR_ID', 'AUTHOR_NAME', 'AUTHOR_EMAIL', 'POST_TEXT', 'DATE_CREATE', 'PUBLISH_STATUS', 'HAS_PROPS', 'SHARE_DEST' ];
323
324 $connection = Application::getConnection();
325 if ($connection instanceof \Bitrix\Main\DB\MysqlCommonConnection)
326 {
327 $selectedFields[] = "DATE_CREATE_TS";
328 }
329
330 $res = \CBlogComment::getList(
331 [ 'ID' => 'DESC' ],
332 [
333 "PUBLISH_STATUS" => BLOG_PUBLISH_STATUS_PUBLISH,
334 "POST_ID" => $postId
335 ],
336 false,
337 [
338 "nTopCount" => $params["COMMENTS_COUNT"]
339 ],
340 $selectedFields
341 );
342
343 while ($comment = $res->fetch())
344 {
345 self::processCommentData($comment, $languageId, $p, [ "MAIL" => (isset($params["MAIL"]) && $params["MAIL"] === "Y" ? "Y" : "N") ]);
346
347 $result[] = $comment;
348
349 if (!in_array((int)$comment["AUTHOR_ID"], $authorIdList, true))
350 {
351 $authorIdList[] = (int)$comment["AUTHOR_ID"];
352 }
353 }
354
355 if (!empty($result))
356 {
357 $result = array_reverse($result);
358 }
359
360 self::$commentListsCache[$postId] = $result;
361 }
362
363 return $result;
364 }
365
374 public static function getBlogCommentListCount($postId)
375 {
376 if (isset(self::$commentCountCache[$postId]))
377 {
378 $result = self::$commentCountCache[$postId];
379 }
380 else
381 {
382 if (!Loader::includeModule('blog'))
383 {
384 throw new Main\SystemException("Could not load 'blog' module.");
385 }
386
387 $selectedFields = [ 'ID' ];
388
389 $result = \CBlogComment::getList(
390 [ 'ID' => 'DESC' ],
391 [
392 "PUBLISH_STATUS" => BLOG_PUBLISH_STATUS_PUBLISH,
393 "POST_ID" => $postId,
394 ],
395 [], // count only
396 false,
397 $selectedFields
398 );
399
400 self::$commentCountCache[$postId] = $result;
401 }
402
403 return $result;
404 }
405
406
414 public static function getBlogCommentData($commentId, $languageId)
415 {
416 $result = [];
417
418 if (isset(self::$commentsCache[$commentId]))
419 {
420 $result = self::$commentsCache[$commentId];
421 }
422 else
423 {
424 $selectedFields = [ "ID", "BLOG_GROUP_ID", "BLOG_GROUP_SITE_ID", "BLOG_ID", "POST_ID", "AUTHOR_ID", "AUTHOR_NAME", "AUTHOR_EMAIL", "POST_TEXT", "DATE_CREATE", "PUBLISH_STATUS", "HAS_PROPS", "SHARE_DEST" ];
425
426 $connection = Application::getConnection();
427 if ($connection instanceof \Bitrix\Main\DB\MysqlCommonConnection)
428 {
429 $selectedFields[] = "DATE_CREATE_TS";
430 }
431
432 $res = \CBlogComment::getList(
433 [],
434 [
435 "ID" => $commentId
436 ],
437 false,
438 false,
439 $selectedFields
440 );
441
442 if ($comment = $res->fetch())
443 {
444 $p = new \blogTextParser();
445
446 self::processCommentData($comment, $languageId, $p);
447
449 }
450
451 self::$commentsCache[$commentId] = $result;
452 }
453
454 return $result;
455 }
456
464 private static function processCommentData(&$comment, $languageId, $p, $params = []): void
465 {
466 global $USER_FIELD_MANAGER;
467
468 $isMail = (
469 is_array($params)
470 && isset($params["MAIL"])
471 && $params["MAIL"] === 'Y'
472 );
473
474 $comment["ATTACHMENTS"] = $comment["PROPS"] = [];
475
476 if ($commentAuxProvider = \Bitrix\Socialnetwork\CommentAux\Base::findProvider(
477 $comment,
478 [
479 "mobile" => (isset($params["MOBILE"]) && $params["MOBILE"] === "Y"),
480 "mail" => (isset($params["MAIL"]) && $params["MAIL"] === "Y"),
481 "cache" => true
482 ]
483 ))
484 {
485 $comment["POST_TEXT_FORMATTED"] = $commentAuxProvider->getText();
486 $arComment["AUX_TYPE"] = $commentAuxProvider->getType();
487 }
488 else
489 {
490 if($comment["HAS_PROPS"] !== "N")
491 {
492 $userFields = $comment["PROPS"] = $USER_FIELD_MANAGER->getUserFields("BLOG_COMMENT", $comment["ID"], $languageId);
493 $commentUf = [ 'UF_BLOG_COMMENT_FILE' ];
494 foreach ($userFields as $fieldName => $userField)
495 {
496 if (!in_array($fieldName, $commentUf, true))
497 {
498 unset($userFields[$fieldName]);
499 }
500 }
501
502 if (
503 !empty($userFields["UF_BLOG_COMMENT_FILE"])
504 && !empty($userFields["UF_BLOG_COMMENT_FILE"]["VALUE"])
505 )
506 {
507 $comment["ATTACHMENTS"] = self::getAttachmentsData($userFields["UF_BLOG_COMMENT_FILE"]["VALUE"], $comment["BLOG_GROUP_SITE_ID"]);
508 }
509
510 if (
511 $isMail
512 && isset($comment["PROPS"]["UF_BLOG_COMM_URL_PRV"])
513 )
514 {
515 unset($comment["PROPS"]["UF_BLOG_COMM_URL_PRV"]);
516 }
517 }
518
520 $comment["POST_TEXT"],
521 'BLOG_COMMENT',
522 $comment["ID"],
523 $comment["AUTHOR_ID"],
524 $comment["ATTACHMENTS"]
525 );
526
527 $comment["POST_TEXT_FORMATTED"] = preg_replace(
528 [
529 '|\[DISK\sFILE\sID=[n]*\d+\]|',
530 '|\[DOCUMENT\sID=[n]*\d+\]|'
531 ],
532 '',
533 $comment["POST_TEXT"]
534 );
535
536 $comment['POST_TEXT_FORMATTED'] = Mention::clear($comment['POST_TEXT_FORMATTED']);
537
538 if ($p)
539 {
540 $p->arUserfields = [];
541 }
542 $images = [];
543 $allow = [ 'IMAGE' => 'Y' ];
544 $parserParameters = [];
545
546 $comment["POST_TEXT_FORMATTED"] = $p->convert($comment["POST_TEXT_FORMATTED"], false, $images, $allow, $parserParameters);
547 }
548
549 $comment["DATE_CREATE_FORMATTED"] = self::formatDateTimeToGMT($comment['DATE_CREATE'], $comment['AUTHOR_ID']);
550 }
551
563 public static function getReplyToUrl($url, $userId, $entityType, $entityId, $siteId, $backUrl = null)
564 {
565 $result = false;
566
567 $url = (string)$url;
568 $userId = (int)$userId;
569 $entityType = (string)$entityType;
570 $entityId = (int)$entityId;
571 $siteId = (string)$siteId;
572
573 if (
574 $url === ''
575 || $userId <= 0
576 || $entityType === ''
577 || $entityId <= 0
578 || $siteId === ''
579 || !Loader::includeModule('mail')
580 )
581 {
582 return $result;
583 }
584
585 $urlRes = \Bitrix\Mail\User::getReplyTo(
586 $siteId,
587 $userId,
588 $entityType,
589 $entityId,
590 $url,
592 );
593 if (is_array($urlRes))
594 {
595 [ , $backUrl ] = $urlRes;
596
597 if ($backUrl)
598 {
600 }
601 }
602
603 return $result;
604 }
605
614 public static function getAttachmentsData($valueList, $siteId = false): array
615 {
616 $result = [];
617
618 if (!Loader::includeModule('disk'))
619 {
620 return $result;
621 }
622
623 if (
624 !$siteId
625 || (string)$siteId === ''
626 )
627 {
629 }
630
631 foreach ($valueList as $value)
632 {
633 $attachedObject = AttachedObject::loadById($value, [ 'OBJECT' ]);
634 if(
635 !$attachedObject
636 || !$attachedObject->getFile()
637 )
638 {
639 continue;
640 }
641
642 $attachedObjectUrl = \Bitrix\Disk\UrlManager::getUrlUfController('show', [ 'attachedId' => $value ]);
643
644 $result[$value] = [
645 "ID" => $value,
646 "OBJECT_ID" => $attachedObject->getFile()->getId(),
647 "NAME" => $attachedObject->getFile()->getName(),
648 "SIZE" => \CFile::formatSize($attachedObject->getFile()->getSize()),
649 "URL" => $attachedObjectUrl,
650 "IS_IMAGE" => TypeFile::isImage($attachedObject->getFile())
651 ];
652 }
653
654 return $result;
655 }
656
668 public static function getAttachmentUrlList($valueList = [], $entityType = '', $entityId = 0, $authorId = 0, $attachmentList = []): array
669 {
670 $result = [];
671
672 if (
673 empty($valueList)
674 || empty($attachmentList)
675 || (int)$authorId <= 0
676 || (int)$entityId <= 0
677 || !Loader::includeModule('disk')
678 )
679 {
680 return $result;
681 }
682
683 $userFieldManager = Driver::getInstance()->getUserFieldManager();
684 [ $connectorClass, $moduleId ] = $userFieldManager->getConnectorDataByEntityType($entityType);
685
686 foreach($valueList as $value)
687 {
688 $attachedFileId = false;
689 $attachedObject = false;
690
691 [ $type, $realValue ] = FileUserType::detectType($value);
692 if ($type === FileUserType::TYPE_NEW_OBJECT)
693 {
694 $attachedObject = AttachedObject::load([
695 '=ENTITY_TYPE' => $connectorClass,
696 'ENTITY_ID' => $entityId,
697 '=MODULE_ID' => $moduleId,
698 'OBJECT_ID'=> $realValue
699 ], [ 'OBJECT' ]);
700
701 if($attachedObject)
702 {
703 $attachedFileId = $attachedObject->getId();
704 }
705 }
706 else
707 {
708 $attachedFileId = $realValue;
709 }
710
711 if (
712 (int)$attachedFileId > 0
713 && !empty($attachmentList[$attachedFileId])
714 )
715 {
716 if (!$attachmentList[$attachedFileId]["IS_IMAGE"])
717 {
718 $result[$value] = [
719 'TYPE' => 'file',
720 'URL' => $attachmentList[$attachedFileId]["URL"]
721 ];
722 }
723 else
724 {
725 if (!$attachedObject)
726 {
727 $attachedObject = AttachedObject::loadById($attachedFileId, [ 'OBJECT' ]);
728 }
729
730 if ($attachedObject)
731 {
732 $file = $attachedObject->getFile();
733
734 $extLinks = $file->getExternalLinks([
735 'filter' => [
736 'OBJECT_ID' => $file->getId(),
737 'CREATED_BY' => $authorId,
738 'TYPE' => \Bitrix\Disk\Internals\ExternalLinkTable::TYPE_MANUAL,
739 'IS_EXPIRED' => false,
740 ],
741 'limit' => 1,
742 ]);
743
744 if (empty($extLinks))
745 {
746 $externalLink = $file->addExternalLink([
747 'CREATED_BY' => $authorId,
748 'TYPE' => \Bitrix\Disk\Internals\ExternalLinkTable::TYPE_MANUAL,
749 ]);
750 }
751 else
752 {
754 $externalLink = reset($extLinks);
755 }
756
757 if ($externalLink)
758 {
759 $originalFile = $file->getFile();
760
761 $result[$value] = [
762 'TYPE' => 'image',
763 'URL' => Driver::getInstance()->getUrlManager()->getUrlExternalLink(
764 [
765 'hash' => $externalLink->getHash(),
766 'action' => 'showFile'
767 ],
768 true
769 ),
770 'WIDTH' => (int)$originalFile["WIDTH"],
771 'HEIGHT' => (int)$originalFile["HEIGHT"]
772 ];
773 }
774 }
775 }
776 }
777 }
778
779 return $result;
780 }
781
789 public static function convertMailDiskFileBBCode($text = '', $attachmentList = [])
790 {
791 if (preg_match_all('|\[MAIL\sDISK\sFILE\sID=([n]*\d+)\]|', $text, $matches))
792 {
793 foreach($matches[1] as $inlineFileId)
794 {
795 $attachmentId = false;
796 if (mb_strpos($inlineFileId, 'n') === 0)
797 {
798 $found = false;
799 foreach($attachmentList as $attachmentId => $attachment)
800 {
801 if (
802 isset($attachment["OBJECT_ID"])
803 && (int)$attachment["OBJECT_ID"] === (int)mb_substr($inlineFileId, 1)
804 )
805 {
806 $found = true;
807 break;
808 }
809 }
810 if (!$found)
811 {
812 $attachmentId = false;
813 }
814 }
815 else
816 {
817 $attachmentId = $inlineFileId;
818 }
819
820 if ((int)$attachmentId > 0)
821 {
822 $text = preg_replace(
823 '|\[MAIL\sDISK\sFILE\sID='.$inlineFileId.'\]|',
824 '[URL='.$attachmentList[$attachmentId]["URL"].']['.$attachmentList[$attachmentId]["NAME"].'][/URL]',
825 $text
826 );
827 }
828 }
829
830 $p = new \CTextParser();
831 $p->allow = [ 'HTML' => 'Y', 'ANCHOR' => 'Y' ];
832 $text = $p->convertText($text);
833 }
834
835 return $text;
836 }
837
848 public static function convertDiskFileBBCode($text, $entityType, $entityId, $authorId, $attachmentList = [])
849 {
850 $text = trim((string)$text);
851 $authorId = (int)$authorId;
852 $entityType = (string)$entityType;
853 $entityId = (int)$entityId;
854
855 if (
856 $text === ''
857 || empty($attachmentList)
858 || $authorId <= 0
859 || $entityType === ''
860 || $entityId <= 0
861 )
862 {
863 return $text;
864 }
865
866 if (preg_match_all('|\[DISK\sFILE\sID=([n]*\d+)\]|', $text, $matches))
867 {
868 $attachmentUrlList = self::getAttachmentUrlList(
869 $matches[1],
870 $entityType,
871 $entityId,
872 $authorId,
873 $attachmentList
874 );
875
876 foreach($matches[1] as $inlineFileId)
877 {
878 if (!empty($attachmentUrlList[$inlineFileId]))
879 {
880 $needCreatePicture = false;
881 $sizeSource = $sizeDestination = [];
882 \CFile::scaleImage(
883 $attachmentUrlList[$inlineFileId]['WIDTH'], $attachmentUrlList[$inlineFileId]['HEIGHT'],
884 [ 'width' => 400, 'height' => 1000 ], BX_RESIZE_IMAGE_PROPORTIONAL,
885 $needCreatePicture, $sizeSource, $sizeDestination
886 );
887
888 $replacement = (
889 $attachmentUrlList[$inlineFileId]["TYPE"] === 'image'
890 ? '[IMG WIDTH='.(int)$sizeDestination['width'].' HEIGHT='.(int)$sizeDestination['height'].']'.\htmlspecialcharsBack($attachmentUrlList[$inlineFileId]["URL"]).'[/IMG]'
891 : '[MAIL DISK FILE ID='.$inlineFileId.']'
892 );
893 $text = preg_replace(
894 '|\[DISK\sFILE\sID='.$inlineFileId.'\]|',
895 $replacement,
896 $text
897 );
898 }
899 }
900 }
901
902 return $text;
903 }
904
912 public static function hasTextInlineImage(string $text = '', array $ufData = []): bool
913 {
914 $result = false;
915
916 if (
917 preg_match_all("#\\[disk file id=(n?\\d+)\\]#isu", $text, $matches)
918 && Loader::includeModule('disk')
919 )
920 {
921 $userFieldManager = Driver::getInstance()->getUserFieldManager();
922
923 foreach ($matches[1] as $id)
924 {
925 $fileModel = null;
926 [ $type, $realValue ] = FileUserType::detectType($id);
927
928 if ($type === FileUserType::TYPE_NEW_OBJECT)
929 {
930 $fileModel = File::loadById($realValue);
931 if(!$fileModel)
932 {
933 continue;
934 }
935 }
936 else
937 {
938 $attachedModel = $userFieldManager->getAttachedObjectById($realValue);
939 if(!$attachedModel)
940 {
941 continue;
942 }
943
944 $attachedModel->setOperableEntity([
945 'ENTITY_ID' => $ufData['ENTITY_ID'],
946 'ENTITY_VALUE_ID' => $ufData['ENTITY_VALUE_ID']
947 ]);
948 $fileModel = $attachedModel->getFile();
949 }
950
951 if(TypeFile::isImage($fileModel))
952 {
953 $result = true;
954 break;
955 }
956 }
957 }
958
959 return $result;
960 }
961
969 public static function formatDateTimeToGMT($dateTimeSource, $authorId): string
970 {
971 if (empty($dateTimeSource))
972 {
973 return '';
974 }
975
976 $serverTs = \MakeTimeStamp($dateTimeSource) - \CTimeZone::getOffset();
977 $serverGMTOffset = (int)date('Z');
978 $authorOffset = (int)\CTimeZone::getOffset($authorId);
979
980 $authorGMTOffset = $serverGMTOffset + $authorOffset;
981 $authorGMTOffsetFormatted = 'GMT';
982 if ($authorGMTOffset !== 0)
983 {
984 $authorGMTOffsetFormatted .= ($authorGMTOffset >= 0 ? '+' : '-').sprintf('%02d', floor($authorGMTOffset / 3600)).':'.sprintf('%02u', ($authorGMTOffset % 3600) / 60);
985 }
986
987 return \FormatDate(
988 preg_replace('/[\/.,\s:][s]/', '', \Bitrix\Main\Type\Date::convertFormatToPhp(FORMAT_DATETIME)),
989 ($serverTs + $authorOffset)
990 ).' ('.$authorGMTOffsetFormatted.')';
991 }
992
999 public static function getSonetBlogGroupIdList($params): array
1000 {
1001 $result = [];
1002
1003 if (!Loader::includeModule('blog'))
1004 {
1005 throw new Main\SystemException("Could not load 'blog' module.");
1006 }
1007
1008 $cacheTtl = 3153600;
1009 $cacheId = 'blog_group_list_'.md5(serialize($params));
1010 $cacheDir = '/blog/group/';
1011 $cache = new \CPHPCache;
1012
1013 if($cache->initCache($cacheTtl, $cacheId, $cacheDir))
1014 {
1015 $result = $cache->getVars();
1016 }
1017 else
1018 {
1019 $cache->startDataCache();
1020
1021 $ideaBlogGroupIdList = array();
1022 if (ModuleManager::isModuleInstalled("idea"))
1023 {
1024 $res = \CSite::getList("sort", "desc", Array("ACTIVE" => "Y"));
1025 while ($site = $res->fetch())
1026 {
1027 $val = Option::get("idea", "blog_group_id", false, $site["LID"]);
1028 if ($val)
1029 {
1030 $ideaBlogGroupIdList[] = $val;
1031 }
1032 }
1033 }
1034
1035 $filter = array();
1036 if (!empty($params["SITE_ID"]))
1037 {
1038 $filter['SITE_ID'] = $params["SITE_ID"];
1039 }
1040 if (!empty($ideaBlogGroupIdList))
1041 {
1042 $filter['!@ID'] = $ideaBlogGroupIdList;
1043 }
1044
1045 $res = \CBlogGroup::getList(array(), $filter, false, false, array("ID"));
1046 while($blogGroup = $res->fetch())
1047 {
1048 $result[] = $blogGroup["ID"];
1049 }
1050
1051 $cache->endDataCache($result);
1052 }
1053
1054 return $result;
1055 }
1056
1066 public static function createUserBlog($params)
1067 {
1068 $result = false;
1069
1070 if (!Loader::includeModule('blog'))
1071 {
1072 throw new Main\SystemException("Could not load 'blog' module.");
1073 }
1074
1075 if (
1076 !isset($params["BLOG_GROUP_ID"], $params["USER_ID"], $params["SITE_ID"])
1077 || (int)$params["BLOG_GROUP_ID"] <= 0
1078 || (int)$params["USER_ID"] <= 0
1079 || (string)$params["SITE_ID"] === ''
1080 )
1081 {
1082 return false;
1083 }
1084
1085 if (
1086 !isset($params["PATH_TO_BLOG"])
1087 || $params["PATH_TO_BLOG"] == ''
1088 )
1089 {
1090 $params["PATH_TO_BLOG"] = "";
1091 }
1092
1093 $connection = Application::getConnection();
1094 $helper = $connection->getSqlHelper();
1095
1096 $fields = array(
1097 "=DATE_UPDATE" => $helper->getCurrentDateTimeFunction(),
1098 "=DATE_CREATE" => $helper->getCurrentDateTimeFunction(),
1099 "GROUP_ID" => (int)$params["BLOG_GROUP_ID"],
1100 "ACTIVE" => "Y",
1101 "OWNER_ID" => (int)$params["USER_ID"],
1102 "ENABLE_COMMENTS" => "Y",
1103 "ENABLE_IMG_VERIF" => "Y",
1104 "EMAIL_NOTIFY" => "Y",
1105 "ENABLE_RSS" => "Y",
1106 "ALLOW_HTML" => "N",
1107 "ENABLE_TRACKBACK" => "N",
1108 "SEARCH_INDEX" => "Y",
1109 "USE_SOCNET" => "Y",
1110 "PERMS_POST" => Array(
1111 1 => "I",
1112 2 => "I"
1113 ),
1114 "PERMS_COMMENT" => Array(
1115 1 => "P",
1116 2 => "P"
1117 )
1118 );
1119
1121 'order' => array(),
1122 'filter' => array(
1123 "ID" => $params["USER_ID"]
1124 ),
1125 'select' => array("NAME", "LAST_NAME", "LOGIN")
1126 ));
1127
1128 if ($user = $res->fetch())
1129 {
1130 $fields["NAME"] = Loc::getMessage("BLG_NAME")." ".(
1131 $user["NAME"]."".$user["LAST_NAME"] === ''
1132 ? $user["LOGIN"]
1133 : $user["NAME"]." ".$user["LAST_NAME"]
1134 );
1135
1136 $fields["URL"] = str_replace(" ", "_", $user["LOGIN"])."-blog-".$params["SITE_ID"];
1137 $urlCheck = preg_replace("/[^a-zA-Z0-9_-]/i", "", $fields["URL"]);
1138 if ($urlCheck !== $fields["URL"])
1139 {
1140 $fields["URL"] = "u".$params["USER_ID"]."-blog-".$params["SITE_ID"];
1141 }
1142
1143 if(\CBlog::getByUrl($fields["URL"]))
1144 {
1145 $uind = 0;
1146 do
1147 {
1148 $uind++;
1149 $fields["URL"] .= $uind;
1150 }
1151 while (\CBlog::getByUrl($fields["URL"]));
1152 }
1153
1155 $params["PATH_TO_BLOG"],
1156 array(
1157 "blog" => $fields["URL"],
1158 "user_id" => $fields["OWNER_ID"]
1159 )
1160 );
1161
1162 $lock = 'blog_create_lock';
1163 $connection = Application::getConnection();
1164 if (!$connection->lock($lock))
1165 {
1166 return false;
1167 }
1168
1169 if ($blogID = \CBlog::add($fields))
1170 {
1171 BXClearCache(true, "/blog/form/blog/");
1172
1173 $rightsFound = false;
1174
1175 $featureOperationPerms = \CSocNetFeaturesPerms::getOperationPerm(
1177 $fields["OWNER_ID"],
1178 "blog",
1179 "view_post"
1180 );
1181
1182 if ($featureOperationPerms === SONET_RELATIONS_TYPE_ALL)
1183 {
1184 $rightsFound = true;
1185 }
1186
1187 if ($rightsFound)
1188 {
1189 \CBlog::addSocnetRead($blogID);
1190 }
1191
1192 $result = \CBlog::getByID($blogID);
1193 }
1194 }
1195
1196 return $result;
1197 }
1198
1207 public static function getUrlPreviewValue($text, $html = true)
1208 {
1209 static $parser = false;
1210 $value = false;
1211
1212 if (empty($text))
1213 {
1214 return $value;
1215 }
1216
1217 if (!$parser)
1218 {
1219 $parser = new \CTextParser();
1220 }
1221
1222 if ($html)
1223 {
1224 $text = $parser->convertHtmlToBB($text);
1225 }
1226
1227 preg_match_all("/\[url\s*=\s*([^\]]*)\](.+?)\[\/url\]/isu", $text, $res);
1228
1229 if (
1230 !empty($res)
1231 && !empty($res[1])
1232 )
1233 {
1234 $url = $res[1][0];
1235
1236 $metaData = UrlPreview::getMetadataAndHtmlByUrl($url, true, false);
1237 if (
1238 !empty($metaData)
1239 && !empty($metaData["ID"])
1240 && (int)$metaData["ID"] > 0
1241 )
1242 {
1243 $signer = new \Bitrix\Main\Security\Sign\Signer();
1244 $value = $signer->sign($metaData["ID"].'', UrlPreview::SIGN_SALT);
1245 }
1246 }
1247
1248 return $value;
1249 }
1250
1258 public static function getUrlPreviewContent($uf, $params = array())
1259 {
1260 global $APPLICATION;
1261 $res = false;
1262
1263 if ($uf["USER_TYPE"]["USER_TYPE_ID"] !== 'url_preview')
1264 {
1265 return $res;
1266 }
1267
1268 ob_start();
1269
1270 $APPLICATION->includeComponent(
1271 "bitrix:system.field.view",
1272 $uf["USER_TYPE"]["USER_TYPE_ID"],
1273 array(
1274 "LAZYLOAD" => (isset($params["LAZYLOAD"]) && $params["LAZYLOAD"] === "Y" ? "Y" : "N"),
1275 "MOBILE" => (isset($params["MOBILE"]) && $params["MOBILE"] === "Y" ? "Y" : "N"),
1276 "arUserField" => $uf,
1277 "arAddField" => array(
1278 "NAME_TEMPLATE" => ($params["NAME_TEMPLATE"] ?? false),
1279 "PATH_TO_USER" => ($params["PATH_TO_USER"] ?? '')
1280 )
1281 ), null, array("HIDE_ICONS"=>"Y")
1282 );
1283
1284 $res = ob_get_clean();
1285
1286 return $res;
1287 }
1288
1289 public static function getExtranetUserIdList()
1290 {
1291 static $result = false;
1292 global $CACHE_MANAGER;
1293
1294 if ($result === false)
1295 {
1296 $result = array();
1297
1298 if (!ModuleManager::isModuleInstalled('extranet'))
1299 {
1300 return $result;
1301 }
1302
1303 $ttl = (defined("BX_COMP_MANAGED_CACHE") ? 2592000 : 600);
1304 $cacheId = 'sonet_ex_userid';
1305 $cache = new \CPHPCache;
1306 $cacheDir = '/bitrix/sonet/user_ex';
1307
1308 if($cache->initCache($ttl, $cacheId, $cacheDir))
1309 {
1310 $tmpVal = $cache->getVars();
1311 $result = $tmpVal['EX_USER_ID'];
1312 unset($tmpVal);
1313 }
1314 else
1315 {
1316 if (defined("BX_COMP_MANAGED_CACHE"))
1317 {
1318 $CACHE_MANAGER->startTagCache($cacheDir);
1319 }
1320
1321 $filter = array(
1322 'UF_DEPARTMENT_SINGLE' => false
1323 );
1324
1325 $externalAuthIdList = self::checkPredefinedAuthIdList(array('bot', 'email', 'controller', 'sale', 'imconnector'));
1326 if (!empty($externalAuthIdList))
1327 {
1328 $filter['!=EXTERNAL_AUTH_ID'] = $externalAuthIdList;
1329 }
1330
1332 'order' => [],
1333 'filter' => $filter,
1334 'select' => array('ID')
1335 ));
1336
1337 while($user = $res->fetch())
1338 {
1339 $result[] = $user["ID"];
1340 }
1341
1342 $adminList = [];
1343 $res = \Bitrix\Main\UserGroupTable::getList(array(
1344 'order' => [],
1345 'filter' => [
1346 '=GROUP_ID' => 1
1347 ],
1348 'select' => [ 'USER_ID' ]
1349 ));
1350 while($relationFields = $res->fetch())
1351 {
1352 $adminList[] = $relationFields["USER_ID"];
1353 }
1354 $result = array_diff($result, $adminList);
1355
1356 if (defined("BX_COMP_MANAGED_CACHE"))
1357 {
1358 $CACHE_MANAGER->registerTag('sonet_user2group');
1359 $CACHE_MANAGER->registerTag('sonet_extranet_user_list');
1360 $CACHE_MANAGER->endTagCache();
1361 }
1362
1363 if($cache->startDataCache())
1364 {
1365 $cache->endDataCache(array(
1366 'EX_USER_ID' => $result
1367 ));
1368 }
1369 }
1370 }
1371
1372 return $result;
1373 }
1374
1375 public static function getEmailUserIdList()
1376 {
1377 global $CACHE_MANAGER;
1378
1379 $result = array();
1380
1381 if (
1382 !ModuleManager::isModuleInstalled('mail')
1383 || !ModuleManager::isModuleInstalled('intranet')
1384 )
1385 {
1386 return $result;
1387 }
1388
1389 $ttl = (defined("BX_COMP_MANAGED_CACHE") ? 2592000 : 600);
1390 $cacheId = 'sonet_email_userid';
1391 $cache = new \CPHPCache;
1392 $cacheDir = '/bitrix/sonet/user_email';
1393
1394 if($cache->initCache($ttl, $cacheId, $cacheDir))
1395 {
1396 $tmpVal = $cache->getVars();
1397 $result = $tmpVal['EMAIL_USER_ID'];
1398 unset($tmpVal);
1399 }
1400 else
1401 {
1402 if (defined("BX_COMP_MANAGED_CACHE"))
1403 {
1404 $CACHE_MANAGER->startTagCache($cacheDir);
1405 }
1406
1408 'order' => array(),
1409 'filter' => array(
1410 '=EXTERNAL_AUTH_ID' => 'email'
1411 ),
1412 'select' => array('ID')
1413 ));
1414
1415 while($user = $res->fetch())
1416 {
1417 $result[] = $user["ID"];
1418 }
1419
1420 if (defined("BX_COMP_MANAGED_CACHE"))
1421 {
1422 $CACHE_MANAGER->registerTag('USER_CARD');
1423 $CACHE_MANAGER->endTagCache();
1424 }
1425
1426 if($cache->startDataCache())
1427 {
1428 $cache->endDataCache(array(
1429 'EMAIL_USER_ID' => $result
1430 ));
1431 }
1432 }
1433
1434 return $result;
1435 }
1436
1437 public static function getExtranetSonetGroupIdList()
1438 {
1439 $result = array();
1440
1441 $ttl = (defined("BX_COMP_MANAGED_CACHE") ? 2592000 : 600);
1442 $cacheId = 'sonet_ex_groupid';
1443 $cache = new \CPHPCache;
1444 $cacheDir = '/bitrix/sonet/group_ex';
1445
1446 if($cache->initCache($ttl, $cacheId, $cacheDir))
1447 {
1448 $tmpVal = $cache->getVars();
1449 $result = $tmpVal['EX_GROUP_ID'];
1450 unset($tmpVal);
1451 }
1452 elseif (Loader::includeModule('extranet'))
1453 {
1454 global $CACHE_MANAGER;
1455 if (defined("BX_COMP_MANAGED_CACHE"))
1456 {
1457 $CACHE_MANAGER->startTagCache($cacheDir);
1458 }
1459
1460 $res = WorkgroupTable::getList(array(
1461 'order' => array(),
1462 'filter' => array(
1463 "=WorkgroupSite:GROUP.SITE_ID" => \CExtranet::getExtranetSiteID()
1464 ),
1465 'select' => array('ID')
1466 ));
1467
1468 while($sonetGroup = $res->fetch())
1469 {
1470 $result[] = $sonetGroup["ID"];
1471 if (defined("BX_COMP_MANAGED_CACHE"))
1472 {
1473 $CACHE_MANAGER->registerTag('sonet_group_'.$sonetGroup["ID"]);
1474 }
1475 }
1476
1477 if (defined("BX_COMP_MANAGED_CACHE"))
1478 {
1479 $CACHE_MANAGER->registerTag('sonet_group');
1480 $CACHE_MANAGER->endTagCache();
1481 }
1482
1483 if($cache->startDataCache())
1484 {
1485 $cache->endDataCache(array(
1486 'EX_GROUP_ID' => $result
1487 ));
1488 }
1489 }
1490
1491 return $result;
1492 }
1493
1494 public static function hasCommentSource($params): bool
1495 {
1496 $res = false;
1497
1498 if (empty($params["LOG_EVENT_ID"]))
1499 {
1500 return $res;
1501 }
1502
1503 $commentEvent = \CSocNetLogTools::findLogCommentEventByLogEventID($params["LOG_EVENT_ID"]);
1504
1505 if (
1506 isset($commentEvent["DELETE_CALLBACK"])
1507 && $commentEvent["DELETE_CALLBACK"] !== "NO_SOURCE"
1508 )
1509 {
1510 if (
1511 $commentEvent["EVENT_ID"] === "crm_activity_add_comment"
1512 && isset($params["LOG_ENTITY_ID"])
1513 && (int)$params["LOG_ENTITY_ID"] > 0
1514 && Loader::includeModule('crm')
1515 )
1516 {
1517 $result = \CCrmActivity::getList(
1518 array(),
1519 array(
1520 'ID' => (int)$params["LOG_ENTITY_ID"],
1521 'CHECK_PERMISSIONS' => 'N'
1522 )
1523 );
1524
1525 if ($activity = $result->fetch())
1526 {
1527 $res = ((int)$activity['TYPE_ID'] === \CCrmActivityType::Task);
1528 }
1529 }
1530 else
1531 {
1532 $res = true;
1533 }
1534 }
1535
1536 return $res;
1537 }
1538
1539 // only by current userid
1540 public static function processBlogPostShare($fields, $params)
1541 {
1542 $postId = (int)$fields["POST_ID"];
1543 $blogId = (int)$fields["BLOG_ID"];
1544 $siteId = $fields["SITE_ID"];
1545 $sonetRights = $fields["SONET_RIGHTS"];
1546 $newRights = $fields["NEW_RIGHTS"];
1547 $userId = (int)$fields["USER_ID"];
1548
1549 $clearCommentsCache = (!isset($params['CLEAR_COMMENTS_CACHE']) || $params['CLEAR_COMMENTS_CACHE'] !== 'N');
1550
1551 $commentId = false;
1552 $logId = false;
1553
1554 if (
1555 Loader::includeModule('blog')
1556 && \CBlogPost::update($postId, array("SOCNET_RIGHTS" => $sonetRights, "HAS_SOCNET_ALL" => "N"))
1557 )
1558 {
1559 BXClearCache(true, self::getBlogPostCacheDir(array(
1560 'TYPE' => 'post',
1561 'POST_ID' => $postId
1562 )));
1563 BXClearCache(true, self::getBlogPostCacheDir(array(
1564 'TYPE' => 'post_general',
1565 'POST_ID' => $postId
1566 )));
1567 BXClearCache(True, self::getBlogPostCacheDir(array(
1568 'TYPE' => 'posts_popular',
1569 'SITE_ID' => $siteId
1570 )));
1571
1572 $logSiteListNew = array();
1573 $user2NotifyList = array();
1574 $sonetPermissionList = \CBlogPost::getSocnetPermsName($postId);
1575 $extranet = Loader::includeModule("extranet");
1576 $extranetSite = ($extranet ? \CExtranet::getExtranetSiteID() : false);
1577 $tzOffset = \CTimeZone::getOffset();
1578
1579 $res = \CBlogPost::getList(
1580 array(),
1581 array("ID" => $postId),
1582 false,
1583 false,
1584 array("ID", "BLOG_ID", "PUBLISH_STATUS", "TITLE", "AUTHOR_ID", "ENABLE_COMMENTS", "NUM_COMMENTS", "VIEWS", "CODE", "MICRO", "DETAIL_TEXT", "DATE_PUBLISH", "CATEGORY_ID", "HAS_SOCNET_ALL", "HAS_TAGS", "HAS_IMAGES", "HAS_PROPS", "HAS_COMMENT_IMAGES")
1585 );
1586 $post = $res->fetch();
1587 if (!$post)
1588 {
1589 return false;
1590 }
1591
1592 if (!empty($post['DETAIL_TEXT']))
1593 {
1594 $post['DETAIL_TEXT'] = \Bitrix\Main\Text\Emoji::decode($post['DETAIL_TEXT']);
1595 }
1596
1597 $intranetUserIdList = ($extranet ? \CExtranet::getIntranetUsers() : false);
1598 $auxLiveParamList = array();
1599 $sharedToIntranetUser = false;
1600
1601 foreach ($sonetPermissionList as $type => $v)
1602 {
1603 foreach ($v as $vv)
1604 {
1605 if (
1606 $type === "SG"
1607 && in_array($type . $vv["ENTITY_ID"], $newRights, true)
1608 )
1609 {
1610 $renderParts = new Livefeed\RenderParts\SonetGroup();
1611 $renderData = $renderParts->getData($vv["ENTITY_ID"]);
1612
1613 if($sonetGroup = \CSocNetGroup::getByID($vv["ENTITY_ID"]))
1614 {
1615 $res = \CSocNetGroup::getSite($vv["ENTITY_ID"]);
1616 while ($groupSiteList = $res->fetch())
1617 {
1618 $logSiteListNew[] = $groupSiteList["LID"];
1619 }
1620
1621 $auxLiveParamList[] = array(
1622 "ENTITY_TYPE" => 'SG',
1623 "ENTITY_ID" => $renderData['id'],
1624 "NAME" => $renderData['name'],
1625 "LINK" => $renderData['link'],
1626 "VISIBILITY" => ($sonetGroup["VISIBLE"] === "Y" ? "all" : "group_members")
1627 );
1628 }
1629 }
1630 elseif ($type === "U")
1631 {
1632 if (
1633 in_array("US" . $vv["ENTITY_ID"], $vv["ENTITY"], true)
1634 && in_array("UA", $newRights, true)
1635 )
1636 {
1637 $renderParts = new Livefeed\RenderParts\User();
1638 $renderData = $renderParts->getData(0);
1639
1640 $auxLiveParamList[] = array(
1641 "ENTITY_TYPE" => 'UA',
1642 "ENTITY_ID" => 'UA',
1643 "NAME" => $renderData['name'],
1644 "LINK" => $renderData['link'],
1645 "VISIBILITY" => 'all'
1646 );
1647 }
1648 elseif (in_array($type . $vv["ENTITY_ID"], $newRights, true))
1649 {
1650 $renderParts = new Livefeed\RenderParts\User();
1651 $renderData = $renderParts->getData($vv["ENTITY_ID"]);
1652
1653 $user2NotifyList[] = $vv["ENTITY_ID"];
1654
1655 if (
1656 $extranet
1657 && is_array($intranetUserIdList)
1658 && !in_array($vv["ENTITY_ID"], $intranetUserIdList)
1659 )
1660 {
1661 $logSiteListNew[] = $extranetSite;
1662 $visibility = 'extranet';
1663 }
1664 else
1665 {
1666 $sharedToIntranetUser = true;
1667 $visibility = 'intranet';
1668 }
1669
1670 $auxLiveParamList[] = array(
1671 "ENTITY_TYPE" => 'U',
1672 "ENTITY_ID" => $renderData['id'],
1673 "NAME" => $renderData['name'],
1674 "LINK" => $renderData['link'],
1675 "VISIBILITY" => $visibility
1676 );
1677 }
1678 }
1679 elseif (
1680 $type === "DR"
1681 && in_array($type.$vv["ENTITY_ID"], $newRights)
1682 )
1683 {
1684 $renderParts = new Livefeed\RenderParts\Department();
1685 $renderData = $renderParts->getData($vv["ENTITY_ID"]);
1686
1687 $auxLiveParamList[] = array(
1688 "ENTITY_TYPE" => 'DR',
1689 "ENTITY_ID" => $renderData['id'],
1690 "NAME" => $renderData['name'],
1691 "LINK" => $renderData['link'],
1692 "VISIBILITY" => 'intranet'
1693 );
1694 }
1695 }
1696 }
1697
1698 $userIP = \CBlogUser::getUserIP();
1699 $auxText = CommentAux\Share::getPostText();
1700 $mention = (
1701 isset($params["MENTION"])
1702 && $params["MENTION"] === "Y"
1703 );
1704
1705 $commentFields = Array(
1706 "POST_ID" => $postId,
1707 "BLOG_ID" => $blogId,
1708 "POST_TEXT" => $auxText,
1709 "DATE_CREATE" => convertTimeStamp(time() + $tzOffset, "FULL"),
1710 "AUTHOR_IP" => $userIP[0],
1711 "AUTHOR_IP1" => $userIP[1],
1712 "PARENT_ID" => false,
1713 "AUTHOR_ID" => $userId,
1714 "SHARE_DEST" => implode(",", $newRights).($mention ? '|mention' : ''),
1715 );
1716
1717 $userIdSent = [];
1718
1719 if($commentId = \CBlogComment::add($commentFields, false))
1720 {
1721 if ($clearCommentsCache)
1722 {
1723 BXClearCache(true, self::getBlogPostCacheDir(array(
1724 'TYPE' => 'post_comments',
1725 'POST_ID' => $postId
1726 )));
1727 }
1728
1729 if ((int)$post["AUTHOR_ID"] !== $userId)
1730 {
1731 $fieldsIM = array(
1732 "TYPE" => "SHARE",
1733 "TITLE" => htmlspecialcharsback($post["TITLE"]),
1735 htmlspecialcharsBack($params["PATH_TO_POST"]),
1736 array(
1737 "post_id" => $postId,
1738 "user_id" => $post["AUTHOR_ID"]
1739 )
1740 ),
1741 "ID" => $postId,
1742 "FROM_USER_ID" => $userId,
1743 "TO_USER_ID" => array($post["AUTHOR_ID"]),
1744 );
1745 \CBlogPost::notifyIm($fieldsIM);
1746 $userIdSent[] = array_merge($userIdSent, $fieldsIM["TO_USER_ID"]);
1747 }
1748
1749 if(!empty($user2NotifyList))
1750 {
1751 $fieldsIM = array(
1752 "TYPE" => "SHARE2USERS",
1753 "TITLE" => htmlspecialcharsback($post["TITLE"]),
1755 htmlspecialcharsBack($params["PATH_TO_POST"]),
1756 array(
1757 "post_id" => $postId,
1758 "user_id" => $post["AUTHOR_ID"]
1759 )),
1760 "ID" => $postId,
1761 "FROM_USER_ID" => $userId,
1762 "TO_USER_ID" => $user2NotifyList,
1763 );
1764 \CBlogPost::notifyIm($fieldsIM);
1765 $userIdSent[] = array_merge($userIdSent, $fieldsIM["TO_USER_ID"]);
1766
1767 \CBlogPost::notifyMail(array(
1768 "type" => "POST_SHARE",
1769 "siteId" => $siteId,
1770 "userId" => $user2NotifyList,
1771 "authorId" => $userId,
1772 "postId" => $post["ID"],
1774 '/pub/post.php?post_id=#post_id#',
1775 array(
1776 "post_id"=> $post["ID"]
1777 )
1778 )
1779 ));
1780 }
1781 }
1782
1783 $blogPostLivefeedProvider = new \Bitrix\Socialnetwork\Livefeed\BlogPost;
1784
1785 /* update socnet log rights*/
1786 $res = \CSocNetLog::getList(
1787 array("ID" => "DESC"),
1788 array(
1789 "EVENT_ID" => $blogPostLivefeedProvider->getEventId(),
1790 "SOURCE_ID" => $postId
1791 ),
1792 false,
1793 false,
1794 array("ID", "ENTITY_TYPE", "ENTITY_ID", "USER_ID", "EVENT_ID")
1795 );
1796 if ($logEntry = $res->fetch())
1797 {
1798 $logId = $logEntry["ID"];
1799 $logSiteList = array();
1800 $res = \CSocNetLog::getSite($logId);
1801 while ($logSite = $res->fetch())
1802 {
1803 $logSiteList[] = $logSite["LID"];
1804 }
1805 $logSiteListNew = array_unique(array_merge($logSiteListNew, $logSiteList));
1806
1807 if (
1808 $extranet
1809 && $sharedToIntranetUser
1810 && count($logSiteListNew) == 1
1811 && $logSiteListNew[0] == $extranetSite
1812 )
1813 {
1814 $logSiteListNew[] = \CSite::getDefSite();
1815 }
1816
1817 $socnetPerms = self::getBlogPostSocNetPerms(array(
1818 'postId' => $postId,
1819 'authorId' => $post["AUTHOR_ID"]
1820 ));
1821
1822 \CSocNetLogRights::deleteByLogID($logId);
1823 \CSocNetLogRights::add($logId, $socnetPerms, true, false);
1824
1825 foreach($newRights as $GROUP_CODE)
1826 {
1827 if (preg_match('/^U(\d+)$/', $GROUP_CODE, $matches))
1828 {
1830 'logId' => $logId,
1831 'userId' => $matches[1],
1832 'siteId' => $siteId,
1833 'typeList' => array(
1834 'FOLLOW',
1835 'COUNTER_COMMENT_PUSH'
1836 ),
1837 'followDate' => 'CURRENT'
1838 ));
1839 }
1840 }
1841
1842 if (count(array_diff($logSiteListNew, $logSiteList)) > 0)
1843 {
1844 \CSocNetLog::update($logId, array(
1845 "ENTITY_TYPE" => $logEntry["ENTITY_TYPE"], // to use any real field
1846 "SITE_ID" => $logSiteListNew
1847 ));
1848 }
1849
1850 if ($commentId > 0)
1851 {
1852 $connection = Application::getConnection();
1853 $helper = $connection->getSqlHelper();
1854
1855 $logCommentFields = array(
1856 'ENTITY_TYPE' => SONET_ENTITY_USER,
1857 'ENTITY_ID' => $post["AUTHOR_ID"],
1858 'EVENT_ID' => 'blog_comment',
1859 '=LOG_DATE' => $helper->getCurrentDateTimeFunction(),
1860 'LOG_ID' => $logId,
1861 'USER_ID' => $userId,
1862 'MESSAGE' => $auxText,
1863 "TEXT_MESSAGE" => $auxText,
1864 'MODULE_ID' => false,
1865 'SOURCE_ID' => $commentId,
1866 'RATING_TYPE_ID' => 'BLOG_COMMENT',
1867 'RATING_ENTITY_ID' => $commentId
1868 );
1869
1870 \CSocNetLogComments::add($logCommentFields, false, false);
1871 }
1872
1873 \CSocNetLogFollow::deleteByLogID($logId, "Y", true);
1874
1875 /* subscribe share author */
1877 'logId' => $logId,
1878 'userId' => $userId,
1879 'typeList' => [
1880 'FOLLOW',
1881 'COUNTER_COMMENT_PUSH',
1882 ],
1883 'followDate' => 'CURRENT',
1884 ]);
1885 }
1886
1887 /* update socnet groupd activity*/
1888 foreach($newRights as $v)
1889 {
1890 if(mb_substr($v, 0, 2) === "SG")
1891 {
1892 $groupId = (int)mb_substr($v, 2);
1893 if($groupId > 0)
1894 {
1895 \CSocNetGroup::setLastActivity($groupId);
1896 }
1897 }
1898 }
1899
1901 "EMAIL_FROM" => \COption::getOptionString("main","email_from", "nobody@nobody.com"),
1902 "SOCNET_RIGHTS" => $newRights,
1903 "ENTITY_TYPE" => "POST",
1904 "ENTITY_ID" => $post["ID"],
1905 "AUTHOR_ID" => $post["AUTHOR_ID"],
1907 htmlspecialcharsBack($params["PATH_TO_POST"]),
1908 array(
1909 "post_id" => $post["ID"],
1910 "user_id" => $post["AUTHOR_ID"]
1911 )
1912 ),
1913 "EXCLUDE_USERS" => $userIdSent
1914 ));
1915
1916 if (!$mention)
1917 {
1919 "CONTEXT" => "blog_post",
1920 "CODE" => \Bitrix\Main\FinderDestTable::convertRights($newRights)
1921 ));
1922 }
1923
1924 if (\Bitrix\Main\Loader::includeModule('crm'))
1925 {
1926 \CCrmLiveFeedComponent::processCrmBlogPostRights($logId, $logEntry, $post, 'share');
1927 }
1928
1929 if (
1930 (int)$commentId > 0
1931 && (
1932 !isset($params["LIVE"])
1933 || $params["LIVE"] !== "N"
1934 )
1935 )
1936 {
1937 $provider = \Bitrix\Socialnetwork\CommentAux\Base::init(\Bitrix\Socialnetwork\CommentAux\Share::getType(), array(
1938 'liveParamList' => $auxLiveParamList
1939 ));
1940
1942 "PATH_TO_USER" => $params["PATH_TO_USER"],
1943 "PATH_TO_POST" => \CComponentEngine::makePathFromTemplate(
1944 htmlspecialcharsBack($params["PATH_TO_POST"]),
1945 array(
1946 "post_id" => $post["ID"],
1947 "user_id" => $post["AUTHOR_ID"]
1948 )
1949 ),
1950 "LOG_ID" => ($logId ? (int)$logId : 0),
1951 "AUX" => 'share',
1952 "AUX_LIVE_PARAMS" => $provider->getLiveParams(),
1953 "CAN_USER_COMMENT" => (!empty($params["CAN_USER_COMMENT"]) && $params["CAN_USER_COMMENT"] === 'Y' ? 'Y' : 'N')
1954 ));
1955 }
1956 }
1957
1958 return $commentId;
1959 }
1960
1961 public static function getUrlContext(): array
1962 {
1963 $result = [];
1964
1965 if (
1966 isset($_GET["entityType"])
1967 && $_GET["entityType"] <> ''
1968 )
1969 {
1970 $result["ENTITY_TYPE"] = $_GET["entityType"];
1971 }
1972
1973 if (
1974 isset($_GET["entityId"])
1975 && (int)$_GET["entityId"] > 0
1976 )
1977 {
1978 $result["ENTITY_ID"] = (int)$_GET["entityId"];
1979 }
1980
1981 return $result;
1982 }
1983
1984 public static function addContextToUrl($url, $context)
1985 {
1986 $result = $url;
1987
1988 if (
1989 !empty($context)
1990 && !empty($context["ENTITY_TYPE"])
1991 && !empty($context["ENTITY_ID"])
1992 )
1993 {
1994 $result = $url.(mb_strpos($url, '?') === false ? '?' : '&').'entityType='.$context["ENTITY_TYPE"].'&entityId='.$context["ENTITY_ID"];
1995 }
1996
1997 return $result;
1998 }
1999
2000 public static function checkPredefinedAuthIdList($authIdList = array())
2001 {
2002 if (!is_array($authIdList))
2003 {
2004 $authIdList = array($authIdList);
2005 }
2006
2007 foreach($authIdList as $key => $authId)
2008 {
2009 if (
2010 $authId === 'replica'
2011 && !ModuleManager::isModuleInstalled("replica")
2012 )
2013 {
2014 unset($authIdList[$key]);
2015 }
2016
2017 if (
2018 $authId === 'imconnector'
2019 && !ModuleManager::isModuleInstalled("imconnector")
2020 )
2021 {
2022 unset($authIdList[$key]);
2023 }
2024
2025 if (
2026 $authId === 'bot'
2027 && !ModuleManager::isModuleInstalled("im")
2028 )
2029 {
2030 unset($authIdList[$key]);
2031 }
2032
2033 if (
2034 $authId === 'email'
2035 && !ModuleManager::isModuleInstalled("mail")
2036 )
2037 {
2038 unset($authIdList[$key]);
2039 }
2040
2041 if (
2042 in_array($authId, [ 'sale', 'shop' ])
2043 && !ModuleManager::isModuleInstalled("sale")
2044 )
2045 {
2046 unset($authIdList[$key]);
2047 }
2048 }
2049
2050 return $authIdList;
2051 }
2052
2053 public static function setModuleUsed(): void
2054 {
2055 $optionValue = Option::get('socialnetwork', 'is_used', false);
2056
2057 if (!$optionValue)
2058 {
2059 Option::set('socialnetwork', 'is_used', true);
2060 }
2061 }
2062
2063 public static function getModuleUsed(): bool
2064 {
2065 return (bool)Option::get('socialnetwork', 'is_used', false);
2066 }
2067
2068 public static function setComponentOption($list, $params = array()): bool
2069 {
2070 if (!is_array($list))
2071 {
2072 return false;
2073 }
2074
2075 $siteId = (!empty($params["SITE_ID"]) ? $params["SITE_ID"] : SITE_ID);
2076 $sefFolder = (!empty($params["SEF_FOLDER"]) ? $params["SEF_FOLDER"] : false);
2077
2078 foreach ($list as $value)
2079 {
2080 if (
2081 empty($value["OPTION"])
2082 || empty($value["OPTION"]["MODULE_ID"])
2083 || empty($value["OPTION"]["NAME"])
2084 || empty($value["VALUE"])
2085 )
2086 {
2087 continue;
2088 }
2089
2090 $optionValue = Option::get($value["OPTION"]["MODULE_ID"], $value["OPTION"]["NAME"], false, $siteId);
2091
2092 if (
2094 || (
2095 !!($value["CHECK_SEF_FOLDER"] ?? false)
2096 && $sefFolder
2097 && mb_substr($optionValue, 0, mb_strlen($sefFolder)) !== $sefFolder
2098 )
2099 )
2100 {
2101 Option::set($value["OPTION"]["MODULE_ID"], $value["OPTION"]["NAME"], $value["VALUE"], $siteId);
2102 }
2103 }
2104
2105 return true;
2106 }
2107
2108 public static function getSonetGroupAvailable($params = array(), &$limitReached = false)
2109 {
2110 global $USER;
2111
2112 $currentUserId = $USER->getId();
2113 $limit = (isset($params['limit']) && (int)$params['limit'] > 0 ? (int)$params['limit'] : 500);
2114 $useProjects = (!empty($params['useProjects']) && $params['useProjects'] === 'Y' ? 'Y' : 'N');
2115 $siteId = (!empty($params['siteId']) ? $params['siteId'] : SITE_ID);
2116 $landing = (!empty($params['landing']) && $params['landing'] === 'Y' ? 'Y' : '');
2117
2118 $currentCache = \Bitrix\Main\Data\Cache::createInstance();
2119
2120 $cacheTtl = defined("BX_COMP_MANAGED_CACHE") ? 3153600 : 3600*4;
2121 $cacheId = 'dest_group_'.$siteId.'_'.$currentUserId.'_'.$limit.$useProjects.$landing;
2122 $cacheDir = '/sonet/dest_sonet_groups_v2/'.$siteId.'/'.$currentUserId;
2123
2124 if($currentCache->startDataCache($cacheTtl, $cacheId, $cacheDir))
2125 {
2126 global $CACHE_MANAGER;
2127
2128 $limitReached = false;
2129
2130 $filter = [
2131 'features' => array("blog", array("premoderate_post", "moderate_post", "write_post", "full_post")),
2132 'limit' => $limit,
2133 'useProjects' => $useProjects,
2134 'site_id' => $siteId,
2135 ];
2136
2137 if ($landing === 'Y')
2138 {
2139 $filter['landing'] = 'Y';
2140 }
2141
2142 $groupList = \CSocNetLogDestination::getSocnetGroup($filter, $limitReached);
2143
2144 if(defined("BX_COMP_MANAGED_CACHE"))
2145 {
2146 $CACHE_MANAGER->startTagCache($cacheDir);
2147 foreach($groupList as $group)
2148 {
2149 $CACHE_MANAGER->registerTag("sonet_features_G_".$group["entityId"]);
2150 $CACHE_MANAGER->registerTag("sonet_group_".$group["entityId"]);
2151 }
2152 $CACHE_MANAGER->registerTag("sonet_user2group_U".$currentUserId);
2153 $CACHE_MANAGER->registerTag(self::MAIN_SELECTOR_GROUPS_CACHE_TAG);
2154 if ($landing === 'Y')
2155 {
2156 $CACHE_MANAGER->registerTag("sonet_group");
2157 }
2158 $CACHE_MANAGER->endTagCache();
2159 }
2160 $currentCache->endDataCache(array(
2161 'groups' => $groupList,
2162 'limitReached' => $limitReached
2163 ));
2164 }
2165 else
2166 {
2167 $tmp = $currentCache->getVars();
2168 $groupList = $tmp['groups'];
2169 $limitReached = $tmp['limitReached'];
2170 }
2171
2172 if (
2173 !$limitReached
2174 && \CSocNetUser::isCurrentUserModuleAdmin()
2175 )
2176 {
2177 $limitReached = true;
2178 }
2179
2180 return $groupList;
2181 }
2182
2183 public static function canAddComment($logEntry = array(), $commentEvent = array())
2184 {
2185 $canAddComments = false;
2186
2187 global $USER;
2188
2189 if (
2190 !is_array($logEntry)
2191 && (int)$logEntry > 0
2192 )
2193 {
2194 $res = \CSocNetLog::getList(
2195 array(),
2196 array(
2197 "ID" => (int)$logEntry
2198 ),
2199 false,
2200 false,
2201 array("ID", "ENTITY_TYPE", "ENTITY_ID", "EVENT_ID", "USER_ID")
2202 );
2203
2204 if (!($logEntry = $res->fetch()))
2205 {
2206 return $canAddComments;
2207 }
2208 }
2209
2210 if (
2211 !is_array($logEntry)
2212 || empty($logEntry)
2213 || empty($logEntry["EVENT_ID"])
2214 )
2215 {
2216 return $canAddComments;
2217 }
2218
2219 if (
2220 !is_array($commentEvent)
2221 || empty($commentEvent)
2222 )
2223 {
2224 $commentEvent = \CSocNetLogTools::findLogCommentEventByLogEventID($logEntry["EVENT_ID"]);
2225 }
2226
2227 if (is_array($commentEvent))
2228 {
2229 $feature = \CSocNetLogTools::findFeatureByEventID($commentEvent["EVENT_ID"]);
2230
2231 if (
2232 array_key_exists("OPERATION_ADD", $commentEvent)
2233 && $commentEvent["OPERATION_ADD"] === "log_rights"
2234 )
2235 {
2236 $canAddComments = \CSocNetLogRights::checkForUser($logEntry["ID"], $USER->getID());
2237 }
2238 elseif (
2239 $feature
2240 && array_key_exists("OPERATION_ADD", $commentEvent)
2241 && $commentEvent["OPERATION_ADD"] <> ''
2242 )
2243 {
2244 $canAddComments = \CSocNetFeaturesPerms::canPerformOperation(
2245 $USER->getID(),
2246 $logEntry["ENTITY_TYPE"],
2247 $logEntry["ENTITY_ID"],
2248 ($feature === "microblog" ? "blog" : $feature),
2249 $commentEvent["OPERATION_ADD"],
2250 \CSocNetUser::isCurrentUserModuleAdmin()
2251 );
2252 }
2253 else
2254 {
2255 $canAddComments = true;
2256 }
2257 }
2258
2259 return $canAddComments;
2260 }
2261
2262 public static function addLiveComment($comment = [], $logEntry = [], $commentEvent = [], $params = []): array
2263 {
2264 global $USER_FIELD_MANAGER;
2265
2266 $result = [];
2267
2268 if (
2269 !is_array($comment)
2270 || empty($comment)
2271 || !is_array($logEntry)
2272 || empty($logEntry)
2273 || !is_array($commentEvent)
2274 || empty($commentEvent)
2275 )
2276 {
2277 return $result;
2278 }
2279
2280 $aux = !empty($params['AUX']);
2281
2282 if (
2283 !isset($params["ACTION"])
2284 || !in_array($params["ACTION"], array("ADD", "UPDATE"))
2285 )
2286 {
2287 $params["ACTION"] = "ADD";
2288 }
2289
2290 if (
2291 !isset($params["LANGUAGE_ID"])
2292 || empty($params["LANGUAGE_ID"])
2293 )
2294 {
2295 $params["LANGUAGE_ID"] = LANGUAGE_ID;
2296 }
2297
2298 if (
2299 !isset($params["SITE_ID"])
2300 || empty($params["SITE_ID"])
2301 )
2302 {
2303 $params["SITE_ID"] = SITE_ID;
2304 }
2305
2306 if ($params["ACTION"] === "ADD")
2307 {
2308 if (
2309 !empty($commentEvent)
2310 && !empty($commentEvent["METHOD_CANEDIT"])
2311 && !empty($comment["SOURCE_ID"])
2312 && (int)$comment["SOURCE_ID"] > 0
2313 && !empty($logEntry["SOURCE_ID"])
2314 && (int)$logEntry["SOURCE_ID"] > 0
2315 )
2316 {
2317 $canEdit = call_user_func($commentEvent["METHOD_CANEDIT"], array(
2318 "LOG_SOURCE_ID" => $logEntry["SOURCE_ID"],
2319 "COMMENT_SOURCE_ID" => $comment["SOURCE_ID"],
2320 "USER_ID" => $comment["USER_ID"]
2321 ));
2322 }
2323 else
2324 {
2325 $canEdit = !$aux;
2326 }
2327 }
2328
2329 $result["hasEditCallback"] = (
2330 $canEdit
2331 && is_array($commentEvent)
2332 && isset($commentEvent["UPDATE_CALLBACK"])
2333 && (
2334 $commentEvent["UPDATE_CALLBACK"] === "NO_SOURCE"
2335 || is_callable($commentEvent["UPDATE_CALLBACK"])
2336 )
2337 ? "Y"
2338 : "N"
2339 );
2340
2341 $result["hasDeleteCallback"] = (
2342 $canEdit
2343 && is_array($commentEvent)
2344 && isset($commentEvent["DELETE_CALLBACK"])
2345 && (
2346 $commentEvent["DELETE_CALLBACK"] === "NO_SOURCE"
2347 || is_callable($commentEvent["DELETE_CALLBACK"])
2348 )
2349 ? "Y"
2350 : "N"
2351 );
2352
2353 if (
2354 !isset($params["SOURCE_ID"])
2355 || (int)$params["SOURCE_ID"] <= 0
2356 )
2357 {
2358 foreach (EventManager::getInstance()->findEventHandlers('socialnetwork', 'OnAfterSonetLogEntryAddComment') as $handler) // send notification
2359 {
2361 }
2362 }
2363
2364 $result["arComment"] = $comment;
2365 foreach($result["arComment"] as $key => $value)
2366 {
2367 if (mb_strpos($key, "~") === 0)
2368 {
2369 unset($result["arComment"][$key]);
2370 }
2371 }
2372
2373 $result["arComment"]["RATING_USER_HAS_VOTED"] = "N";
2374
2375 $result["sourceID"] = $comment["SOURCE_ID"];
2376 $result["timestamp"] = makeTimeStamp(
2377 array_key_exists("LOG_DATE_FORMAT", $comment)
2378 ? $comment["LOG_DATE_FORMAT"]
2379 : $comment["LOG_DATE"]
2380 );
2381
2382 $comment["UF"] = $USER_FIELD_MANAGER->getUserFields("SONET_COMMENT", $comment["ID"], LANGUAGE_ID);
2383
2384 if (
2385 array_key_exists("UF_SONET_COM_DOC", $comment["UF"])
2386 && array_key_exists("VALUE", $comment["UF"]["UF_SONET_COM_DOC"])
2387 && is_array($comment["UF"]["UF_SONET_COM_DOC"]["VALUE"])
2388 && count($comment["UF"]["UF_SONET_COM_DOC"]["VALUE"]) > 0
2389 && $commentEvent["EVENT_ID"] !== "tasks_comment"
2390 )
2391 {
2392 $logEntryRights = array();
2393 $res = \CSocNetLogRights::getList(array(), array("LOG_ID" => $logEntry["ID"]));
2394 while ($right = $res->fetch())
2395 {
2396 $logEntryRights[] = $right["GROUP_CODE"];
2397 }
2398
2399 \CSocNetLogTools::setUFRights($comment["UF"]["UF_SONET_COM_DOC"]["VALUE"], $logEntryRights);
2400 }
2401
2402 $result['timeFormatted'] = formatDateFromDB(
2403 ($comment['LOG_DATE_FORMAT'] ?? $comment['LOG_DATE']),
2404 self::getTimeFormat($params['TIME_FORMAT'])
2405 );
2406
2407 $authorFields = self::getAuthorData([
2408 'userId' => $comment['USER_ID'],
2409 ]);
2410 $createdBy = self::getCreatedByData([
2411 'userFields' => $authorFields,
2412 'languageId' => $params['LANGUAGE_ID'],
2413 'nameTemplate' => $params['NAME_TEMPLATE'],
2414 'showLogin' => $params['SHOW_LOGIN'],
2415 'pathToUser' => $params['PATH_TO_USER'],
2416 ]);
2417
2418 $commentFormatted = array(
2419 'LOG_DATE' => $comment["LOG_DATE"],
2420 "LOG_DATE_FORMAT" => $comment["LOG_DATE_FORMAT"] ?? null,
2421 "LOG_DATE_DAY" => ConvertTimeStamp(MakeTimeStamp($comment['LOG_DATE']), 'SHORT'),
2422 'LOG_TIME_FORMAT' => $result['timeFormatted'],
2423 "MESSAGE" => $comment["MESSAGE"],
2424 "MESSAGE_FORMAT" => $comment["~MESSAGE"] ?? null,
2425 'CREATED_BY' => $createdBy,
2426 "AVATAR_SRC" => \CSocNetLogTools::formatEvent_CreateAvatar($authorFields, $params, ""),
2427 'USER_ID' => $comment['USER_ID'],
2428 );
2429
2430 if (
2431 array_key_exists("CLASS_FORMAT", $commentEvent)
2432 && array_key_exists("METHOD_FORMAT", $commentEvent)
2433 )
2434 {
2435 $fieldsFormatted = call_user_func(
2436 array($commentEvent["CLASS_FORMAT"], $commentEvent["METHOD_FORMAT"]),
2437 $comment,
2438 $params
2439 );
2440 $commentFormatted["MESSAGE_FORMAT"] = htmlspecialcharsback($fieldsFormatted["EVENT_FORMATTED"]["MESSAGE"]);
2441 }
2442 else
2443 {
2444 $commentFormatted["MESSAGE_FORMAT"] = $comment["MESSAGE"];
2445 }
2446
2447 if (
2448 array_key_exists("CLASS_FORMAT", $commentEvent)
2449 && array_key_exists("METHOD_FORMAT", $commentEvent)
2450 )
2451 {
2452 $fieldsFormatted = call_user_func(
2453 array($commentEvent["CLASS_FORMAT"], $commentEvent["METHOD_FORMAT"]),
2454 $comment,
2455 array_merge(
2456 $params,
2457 array(
2458 "MOBILE" => "Y"
2459 )
2460 )
2461 );
2462 $messageMobile = htmlspecialcharsback($fieldsFormatted["EVENT_FORMATTED"]["MESSAGE"]);
2463 }
2464 else
2465 {
2466 $messageMobile = $comment["MESSAGE"];
2467 }
2468
2469 $result["arCommentFormatted"] = $commentFormatted;
2470
2471 if (
2472 isset($params["PULL"])
2473 && $params["PULL"] === "Y"
2474 )
2475 {
2476 $liveFeedCommentsParams = self::getLFCommentsParams([
2477 'ID' => $logEntry['ID'],
2478 'EVENT_ID' => $logEntry['EVENT_ID'],
2479 'ENTITY_TYPE' => $logEntry['ENTITY_TYPE'],
2480 'ENTITY_ID' => $logEntry['ENTITY_ID'],
2481 'SOURCE_ID' => $logEntry['SOURCE_ID'],
2482 'PARAMS' => $logEntry['PARAMS'] ?? null
2483 ]);
2484
2485 $entityXMLId = $liveFeedCommentsParams['ENTITY_XML_ID'];
2486
2487 $listCommentId = (
2488 !!$comment["SOURCE_ID"]
2489 ? $comment["SOURCE_ID"]
2490 : $comment["ID"]
2491 );
2492
2493 $eventHandlerID = EventManager::getInstance()->addEventHandlerCompatible("main", "system.field.view.file", array("CSocNetLogTools", "logUFfileShow"));
2494 $rights = \CSocNetLogComponent::getCommentRights([
2495 'EVENT_ID' => $logEntry['EVENT_ID'],
2496 'SOURCE_ID' => $logEntry['SOURCE_ID'],
2497 'USER_ID' => $comment['USER_ID']
2498 ]);
2499
2500 $postContentTypeId = '';
2501 $commentContentTypeId = '';
2502
2504 $canGetCommentContent = false;
2505
2506 if (
2507 !empty($postContentId['ENTITY_TYPE'])
2508 && ($postProvider = \Bitrix\Socialnetwork\Livefeed\Provider::getProvider($postContentId['ENTITY_TYPE']))
2509 && ($commentProvider = $postProvider->getCommentProvider())
2510 )
2511 {
2512 $postContentTypeId = $postProvider->getContentTypeId();
2513 $commentProviderClassName = get_class($commentProvider);
2514 $reflectionClass = new \ReflectionClass($commentProviderClassName);
2515
2516 $canGetCommentContent = ($reflectionClass->getMethod('initSourceFields')->class == $commentProviderClassName);
2517 if ($canGetCommentContent)
2518 {
2519 $commentContentTypeId = $commentProvider->getContentTypeId();
2520 }
2521 }
2522
2523 $records = static::getLiveCommentRecords([
2524 'commentId' => $listCommentId,
2525 'ratingTypeId' => $comment['RATING_TYPE_ID'],
2526 'timestamp' => $result['timestamp'],
2527 'author' => [
2528 'ID' => $authorFields['ID'],
2529 'NAME' => $authorFields['NAME'],
2530 'LAST_NAME' => $authorFields['LAST_NAME'],
2531 'SECOND_NAME' => $authorFields['SECOND_NAME'],
2532 'PERSONAL_GENDER' => $authorFields['PERSONAL_GENDER'],
2533 'AVATAR' => $commentFormatted['AVATAR_SRC'],
2534 ],
2535 'uf' => $comment['UF'],
2536 'ufFormatted' => $commentFormatted['UF'] ?? null,
2537 'postMessageTextOriginal' => $comment['~MESSAGE'] ?? null,
2538 'postMessageTextFormatted' => $commentFormatted['MESSAGE_FORMAT'],
2539 'mobileMessage' => $messageMobile,
2540 'aux' => ($params['AUX'] ?? ''),
2541 'auxLiveParams' => ($params['AUX_LIVE_PARAMS'] ?? []),
2542 ]);
2543
2544 $viewUrl = (string)($comment['EVENT']['URL'] ?? '');
2545 if (empty($viewUrl))
2546 {
2547 $pathToLogEntry = (string)($params['PATH_TO_LOG_ENTRY'] ?? '');
2548 if (!empty($pathToLogEntry))
2549 {
2551 $pathToLogEntry,
2552 [
2553 'log_id' => $logEntry['ID']
2554 ]
2555 ) . (mb_strpos($pathToLogEntry, '?') === false ? '?' : '&') . 'commentId=#ID#';
2556 }
2557 }
2558
2559 $rights['COMMENT_RIGHTS_CREATETASK'] = (
2560 $canGetCommentContent
2561 && ModuleManager::isModuleInstalled('tasks')
2562 ? 'Y'
2563 : 'N'
2564 );
2565
2566 $res = static::sendLiveComment([
2567 'ratingTypeId' => $comment['RATING_TYPE_ID'],
2568 'entityXMLId' => $entityXMLId,
2569 'postContentTypeId' => $postContentTypeId,
2570 'commentContentTypeId' => $commentContentTypeId,
2571 'records' => $records,
2572 'rights' => $rights,
2573 'commentId' => $listCommentId,
2574 'action' => ($params['ACTION'] === 'UPDATE' ? 'EDIT' : 'REPLY'),
2575 'urlList' => [
2576 'view' => $viewUrl,
2577 'edit' => "__logEditComment('" . $entityXMLId . "', '#ID#', '" . $logEntry["ID"] . "');",
2578 'delete' => '/bitrix/components/bitrix/socialnetwork.log.entry/ajax.php?lang=' . $params['LANGUAGE_ID'] . '&action=delete_comment&delete_comment_id=#ID#&post_id=' . $logEntry['ID'] . '&site=' . $params['SITE_ID'],
2579 ],
2580 'avatarSize' => $params['AVATAR_SIZE_COMMENT'] ?? null,
2581 'nameTemplate' => $params['NAME_TEMPLATE'],
2582 'dateTimeFormat' => $params['DATE_TIME_FORMAT'] ?? null,
2583 ]);
2584
2585 if ($eventHandlerID > 0)
2586 {
2587 EventManager::getInstance()->removeEventHandler('main', 'system.field.view.file', $eventHandlerID);
2588 }
2589
2590 $result['return_data'] = $res['JSON'];
2591 }
2592
2593 return $result;
2594 }
2595
2596 public static function addLiveSourceComment(array $params = []): void
2597 {
2599
2600 $siteId = (string)($params['siteId'] ?? SITE_ID);
2601 $languageId = (string)($params['siteId'] ?? LANGUAGE_ID);
2602 $entityXmlId = (string)($params['entityXmlId'] ?? '');
2603 $nameTemplate = (string)($params['nameTemplate'] ?? '');
2604 $showLogin = (string)($params['showLogin'] ?? 'N');
2605 $pathToUser = (string)($params['pathToUser'] ?? '');
2606 $avatarSize = (int)($params['avatarSize'] ?? 100);
2607
2608 $postProvider = $params['postProvider'];
2609 $commentProvider = $params['commentProvider'];
2610
2611 if (
2612 !$postProvider
2613 || !$commentProvider
2614 )
2615 {
2616 return;
2617 }
2618
2619 $commentId = $commentProvider->getEntityId();
2620 $ratingTypeId = $commentProvider->getRatingTypeId();
2621 $commentDateTime = $commentProvider->getSourceDateTime();
2622 $commentAuthorId = $commentProvider->getSourceAuthorId();
2623 $commentText = $commentProvider->getSourceDescription();
2624 $userTypeEntityId = $commentProvider->getUserTypeEntityId();
2625 $commentContentTypeId = $commentProvider->getContentTypeId();
2626
2627 $postContentTypeId = $postProvider->getContentTypeId();
2628
2629 $timestamp = ($commentDateTime ? makeTimeStamp($commentDateTime) : 0);
2630
2631 if (!empty($userTypeEntityId))
2632 {
2633 $comment['UF'] = $USER_FIELD_MANAGER->getUserFields($userTypeEntityId, $commentId, $languageId);
2634 }
2635
2636 $timeFormatted = formatDateFromDB($commentDateTime, self::getTimeFormat());
2637
2638 $authorFields = self::getAuthorData([
2639 'userId' => $commentAuthorId,
2640 ]);
2641
2642 $createdBy = self::getCreatedByData([
2643 'userFields' => $authorFields,
2644 'languageId' => $languageId,
2645 'nameTemplate' => $nameTemplate,
2646 'showLogin' => $showLogin,
2647 'pathToUser' => $pathToUser,
2648 ]);
2649
2650 $commentFormatted = [
2651 'LOG_DATE' => $commentDateTime->toString(),
2652 "LOG_DATE_FORMAT" => $comment["LOG_DATE_FORMAT"],
2653 'LOG_DATE_DAY' => convertTimeStamp($timestamp, 'SHORT'),
2654 'LOG_TIME_FORMAT' => $timeFormatted,
2655 'MESSAGE' => $commentText,
2656 'MESSAGE_FORMAT' => $commentText,
2657 'CREATED_BY' => $createdBy,
2658 'AVATAR_SRC' => \CSocNetLogTools::formatEvent_CreateAvatar($authorFields, [
2659 'AVATAR_SIZE' => $avatarSize,
2660 ], ''),
2661 'USER_ID' => $commentAuthorId,
2662 ];
2663
2664 if (
2665 empty($entityXmlId)
2666 && $commentProvider->getContentTypeId() === Livefeed\ForumPost::CONTENT_TYPE_ID
2667 )
2668 {
2669 $feedParams = $commentProvider->getFeedParams();
2670 if (!empty($feedParams['xml_id']))
2671 {
2672 $entityXmlId = $feedParams['xml_id'];
2673 }
2674 }
2675
2676 if (empty($entityXmlId))
2677 {
2678 return;
2679 }
2680
2681 $rights = [
2682 'COMMENT_RIGHTS_EDIT' => 'N',
2683 'COMMENT_RIGHTS_DELETE' => 'N',
2684 'COMMENT_RIGHTS_CREATETASK' => 'N'
2685 ];
2686
2687 $records = static::getLiveCommentRecords([
2688 'commentId' => $commentId,
2689 'ratingTypeId' => $ratingTypeId,
2690 'timestamp' => $timestamp,
2691 'author' => [
2692 'ID' => $authorFields['ID'],
2693 'NAME' => $authorFields['NAME'],
2694 'LAST_NAME' => $authorFields['LAST_NAME'],
2695 'SECOND_NAME' => $authorFields['SECOND_NAME'],
2696 'PERSONAL_GENDER' => $authorFields['PERSONAL_GENDER'],
2697 'AVATAR' => $commentFormatted['AVATAR_SRC'],
2698 ],
2699 'uf' => $comment['UF'],
2700 'ufFormatted' => $commentFormatted['UF'],
2701 'postMessageTextOriginal' => $comment['~MESSAGE'],
2702 'postMessageTextFormatted' => $commentFormatted['MESSAGE_FORMAT'],
2703 'mobileMessage' => $commentText,
2704 'aux' => ($params['aux'] ?? ''),
2705 'auxLiveParams' => ($params['auxLiveParams'] ?? []),
2706 ]);
2707/*
2708 $viewUrl = (string)($comment['EVENT']['URL'] ?? '');
2709 if (empty($viewUrl))
2710 {
2711 $pathToLogEntry = (string)($params['PATH_TO_LOG_ENTRY'] ?? '');
2712 if (!empty($pathToLogEntry))
2713 {
2714 $viewUrl = \CComponentEngine::makePathFromTemplate(
2715 $pathToLogEntry,
2716 [
2717 'log_id' => $logEntry['ID']
2718 ]
2719 ) . (mb_strpos($pathToLogEntry, '?') === false ? '?' : '&') . 'commentId=#ID#';
2720 }
2721 }
2722*/
2723 $res = static::sendLiveComment([
2724 'ratingTypeId' => $ratingTypeId,
2725 'entityXMLId' => $entityXmlId,
2726 'postContentTypeId' => $postContentTypeId,
2727 'commentContentTypeId' => $commentContentTypeId,
2728 'records' => $records,
2729 'rights' => $rights,
2730 'commentId' => $commentId,
2731 'action' => 'REPLY',
2732 'urlList' => [
2733// 'view' => $viewUrl,
2734// 'edit' => "__logEditComment('" . $entityXMLId . "', '#ID#', '" . $logEntry["ID"] . "');",
2735// 'delete' => '/bitrix/components/bitrix/socialnetwork.log.entry/ajax.php?lang=' . $params['LANGUAGE_ID'] . '&action=delete_comment&delete_comment_id=#ID#&post_id=' . $logEntry['ID'] . '&site=' . $params['SITE_ID'],
2736 ],
2737 'avatarSize' => $avatarSize,
2738 'nameTemplate' => $nameTemplate,
2739// 'dateTimeFormat' => $params['DATE_TIME_FORMAT'],
2740 ]);
2741 }
2742
2743 private static function getAuthorData(array $params = []): array
2744 {
2745 $userId = (int)($params['userId'] ?? 0);
2746
2747 if ($userId > 0)
2748 {
2749 $result = [
2750 'ID' => $userId
2751 ];
2753 'filter' => [
2754 'ID' => $userId,
2755 ],
2756 'select' => [ 'ID', 'NAME', 'LAST_NAME', 'SECOND_NAME', 'LOGIN', 'PERSONAL_PHOTO', 'PERSONAL_GENDER' ]
2757 ]);
2758
2759 if ($userFields = $res->fetch())
2760 {
2761 $result = $userFields;
2762 }
2763 }
2764 else
2765 {
2766 $result = [];
2767 }
2768
2769 return $result;
2770 }
2771
2772 private static function getCreatedByData(array $params = []): array
2773 {
2774 $userFields = (array)($params['userFields'] ?? []);
2775 $languageId = ($params['languageId'] ?? null);
2776 $nameTemplate = (string)($params['nameTemplate'] ?? '');
2777 $showLogin = (string)($params['showLogin'] ?? 'N');
2778 $pathToUser = (string)($params['pathToUser'] ?? '');
2779
2780 if (!empty($userFields))
2781 {
2782 $result = [
2783 'FORMATTED' => \CUser::formatName($nameTemplate, $userFields, ($showLogin !== 'N')),
2784 'URL' => \CComponentEngine::makePathFromTemplate(
2785 $pathToUser,
2786 [
2787 'user_id' => $userFields['ID'],
2788 'id' => $userFields['ID'],
2789 ]
2790 )
2791 ];
2792 }
2793 else
2794 {
2795 $result = [
2796 'FORMATTED' => Loc::getMessage('SONET_HELPER_CREATED_BY_ANONYMOUS', false, $languageId)
2797 ];
2798 }
2799
2800 return $result;
2801 }
2802
2803
2804 private static function getTimeFormat($siteTimeFormat = ''): string
2805 {
2806 if (empty($siteTimeFormat))
2807 {
2808 $siteTimeFormat = \CSite::getTimeFormat();
2809 }
2810
2811 return (
2812 mb_stripos($siteTimeFormat, 'a')
2813 || (
2814 $siteTimeFormat === 'FULL'
2815 && (
2816 mb_strpos(FORMAT_DATETIME, 'T') !== false
2817 || mb_strpos(FORMAT_DATETIME, 'TT') !== false
2818 )
2819 )
2820 ? (mb_strpos(FORMAT_DATETIME, 'TT') !== false ? 'H:MI TT' : 'H:MI T')
2821 : 'HH:MI'
2822 );
2823 }
2824
2825 private static function getLiveCommentRecords(array $params = []): array
2826 {
2827 $commentId = (int)($params['commentId'] ?? 0);
2828 $ratingTypeId = (string)($params['ratingTypeId'] ?? '');
2829 $timestamp = (int)($params['timestamp'] ?? 0);
2830 $author = (array)($params['author'] ?? []);
2831 $uf = (array)($params['uf'] ?? []);
2832 $ufFormatted = (string)($params['ufFormatted'] ?? '');
2833 $postMessageTextOriginal = (string)($params['postMessageTextOriginal'] ?? '');
2834 $postMessageTextFormatted = (string)($params['postMessageTextFormatted'] ?? '');
2835 $mobileMessage = (string)($params['mobileMessage'] ?? '');
2836 $aux = (string)($params['aux'] ?? '');
2837 $auxLiveParams = (array)($params['auxLiveParams'] ?? []);
2838
2839 $records = [
2840 $commentId => [
2841 'ID' => $commentId,
2842 'RATING_VOTE_ID' => $ratingTypeId . '_' . $commentId . '-' . (time() + random_int(0, 1000)),
2843 'APPROVED' => 'Y',
2844 'POST_TIMESTAMP' => $timestamp,
2845 'AUTHOR' => $author,
2846 'FILES' => false,
2847 'UF' => $uf,
2848 '~POST_MESSAGE_TEXT' => $postMessageTextOriginal,
2849 'WEB' => [
2850 'CLASSNAME' => '',
2851 'POST_MESSAGE_TEXT' => $postMessageTextFormatted,
2852 'AFTER' => $ufFormatted,
2853 ],
2854 'MOBILE' => [
2855 'CLASSNAME' => '',
2856 'POST_MESSAGE_TEXT' => $mobileMessage
2857 ],
2858 'AUX' => $aux,
2859 'AUX_LIVE_PARAMS' => $auxLiveParams,
2860 ]
2861 ];
2862
2863 if (
2864 !empty($uf)
2865 && !empty($uf['UF_SONET_COM_DOC'])
2866 && !empty($uf['UF_SONET_COM_DOC']['VALUE'])
2867
2868 )
2869 {
2870 $inlineDiskAttachedObjectIdImageList = self::getInlineDiskImages([
2871 'text' => $postMessageTextOriginal,
2872 'commentId' => $commentId,
2873 ]);
2874
2875 if (!empty($inlineDiskAttachedObjectIdImageList))
2876 {
2877 $records[$commentId]['WEB']['UF'] = $records[$commentId]['UF'];
2878 $records[$commentId]['MOBILE']['UF'] = $records[$commentId]['UF'];
2879 $records[$commentId]['MOBILE']['UF']['UF_SONET_COM_DOC']['VALUE'] = array_diff($records[$commentId]['MOBILE']['UF']['UF_SONET_COM_DOC']['VALUE'], $inlineDiskAttachedObjectIdImageList);
2880 }
2881 }
2882
2883 return $records;
2884 }
2885
2886 private static function sendLiveComment(array $params = []): array
2887 {
2888 global $APPLICATION;
2889
2890 $ratingTypeId = (string)($params['ratingTypeId'] ?? '');
2891 $entityXMLId = (string)($params['entityXMLId'] ?? '');
2892 $postContentTypeId = (string)($params['postContentTypeId'] ?? '');
2893 $commentContentTypeId = (string)($params['commentContentTypeId'] ?? '');
2894 $records = (array)($params['records'] ?? []);
2895 $rights = (array)($params['rights'] ?? []);
2896 $commentId = (int)($params['commentId'] ?? 0);
2897 $action = (string)($params['action'] ?? '');
2898 $urlList = (array)($params['urlList'] ?? []);
2899 $avatarSize = (int)($params['avatarSize'] ?? 0);
2900 $nameTemplate = (string)($params['nameTemplate'] ?? '');
2901 $showLogin = (isset($params['showLogin']) && $params['showLogin'] === 'Y' ? 'Y' : 'N');
2902 $dateTimeFormat = (string)($params['dateTimeFormat'] ?? '');
2903
2904 return $APPLICATION->includeComponent(
2905 'bitrix:main.post.list',
2906 '',
2907 [
2908 'TEMPLATE_ID' => '',
2909 'RATING_TYPE_ID' => $ratingTypeId,
2910 'ENTITY_XML_ID' => $entityXMLId,
2911 'POST_CONTENT_TYPE_ID' => $postContentTypeId,
2912 'COMMENT_CONTENT_TYPE_ID' => $commentContentTypeId,
2913 'RECORDS' => $records,
2914 'NAV_STRING' => '',
2915 'NAV_RESULT' => '',
2916 'PREORDER' => "N",
2917 'RIGHTS' => [
2918 'MODERATE' => 'N',
2919 'EDIT' => $rights['COMMENT_RIGHTS_EDIT'],
2920 'DELETE' => $rights['COMMENT_RIGHTS_DELETE'],
2921 'CREATETASK' => $rights['COMMENT_RIGHTS_CREATETASK'],
2922 ],
2923 'VISIBLE_RECORDS_COUNT' => 1,
2924 'ERROR_MESSAGE' => '',
2925 'OK_MESSAGE' => '',
2926 'RESULT' => $commentId,
2927 'PUSH&PULL' => [
2928 'ACTION' => $action,
2929 'ID' => $commentId
2930 ],
2931 'MODE' => 'PULL_MESSAGE',
2932 'VIEW_URL' => ($urlList['view'] ?? ''),
2933 'EDIT_URL' => ($urlList['edit'] ?? ''),
2934 'MODERATE_URL' => '',
2935 'DELETE_URL' => ($urlList['delete'] ?? ''),
2936 'AUTHOR_URL' => '',
2937 'AVATAR_SIZE' => $avatarSize,
2938 'NAME_TEMPLATE' => $nameTemplate,
2939 'SHOW_LOGIN' => $showLogin,
2940 'DATE_TIME_FORMAT' => $dateTimeFormat,
2941 'LAZYLOAD' => 'N',
2942 'NOTIFY_TAG' => '',
2943 'NOTIFY_TEXT' => '',
2944 'SHOW_MINIMIZED' => 'Y',
2945 'SHOW_POST_FORM' => 'Y',
2946 'IMAGE_SIZE' => '',
2947 'mfi' => '',
2948 ],
2949 [],
2950 null
2951 );
2952
2953 }
2954
2955 private static function getInlineDiskImages(array $params = []): array
2956 {
2957 $result = [];
2958
2959 $text = (string)($params['text'] ?? '');
2960 $commentId = (int)($params['commentId'] ?? 0);
2961
2962 if (
2963 $text === ''
2964 || $commentId <= 0
2965 || !ModuleManager::isModuleInstalled('disk')
2966 )
2967 {
2968 return $result;
2969 }
2970
2971 $inlineDiskObjectIdList = [];
2972 $inlineDiskAttachedObjectIdList = [];
2973
2974 // parse inline disk object ids
2975 if (preg_match_all('#\\[disk file id=(n\\d+)\\]#isu', $text, $matches))
2976 {
2977 $inlineDiskObjectIdList = array_map(function($a) { return (int)mb_substr($a, 1); }, $matches[1]);
2978 }
2979
2980 // parse inline disk attached object ids
2981 if (preg_match_all('#\\[disk file id=(\\d+)\\]#isu', $text, $matches))
2982 {
2983 $inlineDiskAttachedObjectIdList = array_map(function($a) { return (int)$a; }, $matches[1]);
2984 }
2985
2986 if (
2987 (
2988 empty($inlineDiskObjectIdList)
2989 && empty($inlineDiskAttachedObjectIdList)
2990 )
2991 || !Loader::includeModule('disk')
2992 )
2993 {
2994 return $result;
2995 }
2996
2997 $filter = [
2998 '=OBJECT.TYPE_FILE' => TypeFile::IMAGE
2999 ];
3000
3001 $subFilter = [];
3002 if (!empty($inlineDiskObjectIdList))
3003 {
3004 $subFilter['@OBJECT_ID'] = $inlineDiskObjectIdList;
3005 }
3006 elseif (!empty($inlineDiskAttachedObjectIdList))
3007 {
3008 $subFilter['@ID'] = $inlineDiskAttachedObjectIdList;
3009 }
3010
3011 if(count($subFilter) > 1)
3012 {
3013 $subFilter['LOGIC'] = 'OR';
3014 $filter[] = $subFilter;
3015 }
3016 else
3017 {
3018 $filter = array_merge($filter, $subFilter);
3019 }
3020
3021 $res = \Bitrix\Disk\Internals\AttachedObjectTable::getList([
3022 'filter' => $filter,
3023 'select' => array('ID', 'ENTITY_ID')
3024 ]);
3025
3026 while ($attachedObjectFields = $res->fetch())
3027 {
3028 if ((int)$attachedObjectFields['ENTITY_ID'] === $commentId)
3029 {
3030 $result[] = (int)$attachedObjectFields['ID'];
3031 }
3032 }
3033
3034 return $result;
3035 }
3036
3037 public static function fillSelectedUsersToInvite($HTTPPost, $componentParams, &$componentResult): void
3038 {
3039 if (
3040 empty($HTTPPost["SPERM"])
3041 || empty($HTTPPost["SPERM"]["UE"])
3042 || !is_array($HTTPPost["SPERM"]["UE"])
3043 )
3044 {
3045 return;
3046 }
3047
3048 $nameFormat = \CSite::getNameFormat(false);
3049 foreach ($HTTPPost["SPERM"]["UE"] as $invitedEmail)
3050 {
3051 $name = (!empty($HTTPPost["INVITED_USER_NAME"][$invitedEmail]) ? $HTTPPost["INVITED_USER_NAME"][$invitedEmail] : '');
3052 $lastName = (!empty($HTTPPost["INVITED_USER_LAST_NAME"][$invitedEmail]) ? $HTTPPost["INVITED_USER_LAST_NAME"][$invitedEmail] : '');
3053
3054 $createCrmContact = (
3055 !empty($HTTPPost["INVITED_USER_CREATE_CRM_CONTACT"][$invitedEmail])
3056 && $HTTPPost["INVITED_USER_CREATE_CRM_CONTACT"][$invitedEmail] === 'Y'
3057 );
3058
3059 $userName = \CUser::formatName(
3060 empty($componentParams["NAME_TEMPLATE"]) ? $nameFormat : $componentParams["NAME_TEMPLATE"],
3061 array(
3062 'NAME' => $name,
3063 'LAST_NAME' => $lastName,
3064 'LOGIN' => $invitedEmail
3065 ),
3066 true,
3067 false
3068 );
3069
3070 $componentResult["PostToShow"]["FEED_DESTINATION"]['USERS'][$invitedEmail] = [
3071 'id' => $invitedEmail,
3072 'email' => $invitedEmail,
3073 'showEmail' => 'Y',
3074 'name' => $userName,
3075 'isEmail' => 'Y',
3076 'isCrmEmail' => ($createCrmContact ? 'Y' : 'N'),
3077 'params' => [
3078 'name' => $name,
3079 'lastName' => $lastName,
3080 'createCrmContact' => $createCrmContact,
3081 ],
3082 ];
3083 $componentResult["PostToShow"]["FEED_DESTINATION"]['SELECTED'][$invitedEmail] = 'users';
3084 }
3085 }
3086
3087 public static function processBlogPostNewMailUser(&$HTTPPost, &$componentResult): void
3088 {
3089 $newName = false;
3090 if (isset($HTTPPost['SONET_PERMS']))
3091 {
3092 $HTTPPost['SPERM'] = $HTTPPost['SONET_PERMS'];
3093 $newName = true;
3094 }
3095
3096 self::processBlogPostNewCrmContact($HTTPPost, $componentResult);
3097
3098 if ($newName)
3099 {
3100 $HTTPPost['SONET_PERMS'] = $HTTPPost['SPERM'];
3101 unset($HTTPPost['SPERM']);
3102 }
3103 }
3104
3105 private static function processUserEmail($params, &$errorText): array
3106 {
3107 $result = [];
3108
3109 if (
3110 !is_array($params)
3111 || empty($params['EMAIL'])
3112 || !check_email($params['EMAIL'])
3113 || !Loader::includeModule('mail')
3114 )
3115 {
3116 return $result;
3117 }
3118
3119 $userEmail = $params['EMAIL'];
3120
3121 if (
3122 empty($userEmail)
3123 || !check_email($userEmail)
3124 )
3125 {
3126 return $result;
3127 }
3128
3129 $res = \CUser::getList(
3130 'ID',
3131 'ASC',
3132 [
3133 '=EMAIL' => $userEmail,
3134 '!EXTERNAL_AUTH_ID' => array_diff(\Bitrix\Main\UserTable::getExternalUserTypes(), [ 'email' ]),
3135 ],
3136 [
3137 'FIELDS' => [ 'ID', 'EXTERNAL_AUTH_ID', 'ACTIVE' ]
3138 ]
3139 );
3140
3141 $userId = false;
3142
3143 while (
3144 ($emailUser = $res->fetch())
3145 && !$userId
3146 )
3147 {
3148 if (
3149 (int)$emailUser["ID"] > 0
3150 && (
3151 $emailUser["ACTIVE"] === "Y"
3152 || $emailUser["EXTERNAL_AUTH_ID"] === "email"
3153 )
3154 )
3155 {
3156 if ($emailUser["ACTIVE"] === "N") // email only
3157 {
3158 $user = new \CUser;
3159 $user->update($emailUser["ID"], [
3160 'ACTIVE' => 'Y'
3161 ]);
3162 }
3163
3164 $userId = $emailUser['ID'];
3165 }
3166 }
3167
3168 if ($userId)
3169 {
3170 $result = [
3171 'U'.$userId
3172 ];
3173 }
3174
3175 if (!$userId)
3176 {
3177 $userFields = array(
3178 'EMAIL' => $userEmail,
3179 'NAME' => ($params["NAME"] ?? ''),
3180 'LAST_NAME' => ($params["LAST_NAME"] ?? '')
3181 );
3182
3183 if (
3184 !empty($params["CRM_ENTITY"])
3185 && Loader::includeModule('crm')
3186 )
3187 {
3188 $userFields['UF'] = [
3189 'UF_USER_CRM_ENTITY' => $params["CRM_ENTITY"],
3190 ];
3191 $res = \CCrmLiveFeedComponent::resolveLFEntityFromUF($params["CRM_ENTITY"]);
3192 if (!empty($res))
3193 {
3194 [ $k, $v ] = $res;
3195 if ($k && $v)
3196 {
3197 $result[] = $k.$v;
3198
3199 if (
3200 $k === \CCrmLiveFeedEntity::Contact
3201 && ($contact = \CCrmContact::getById($v))
3202 && (int)$contact['PHOTO'] > 0
3203 )
3204 {
3205 $userFields['PERSONAL_PHOTO_ID'] = (int)$contact['PHOTO'];
3206 }
3207 }
3208 }
3209 }
3210 elseif (
3211 !empty($params["CREATE_CRM_CONTACT"])
3212 && $params["CREATE_CRM_CONTACT"] === 'Y'
3213 && Loader::includeModule('crm')
3214 && ($contactId = \CCrmLiveFeedComponent::createContact($userFields))
3215 )
3216 {
3217 $userFields['UF'] = [
3218 'UF_USER_CRM_ENTITY' => 'C_'.$contactId
3219 ];
3220 $result[] = "CRMCONTACT".$contactId;
3221 }
3222
3223 // invite extranet user by email
3224 $userId = \Bitrix\Mail\User::create($userFields);
3225
3226 $errorMessage = false;
3227
3228 if (
3229 is_object($userId)
3230 && $userId->LAST_ERROR <> ''
3231 )
3232 {
3233 $errorMessage = $userId->LAST_ERROR;
3234 }
3235
3236 if (
3238 && (int)$userId > 0
3239 )
3240 {
3241 $result[] = "U".$userId;
3242 }
3243 else
3244 {
3245 $errorText = $errorMessage;
3246 }
3247 }
3248
3249 if (
3250 !is_object($userId)
3251 && (int)$userId > 0
3252 )
3253 {
3254 \Bitrix\Main\UI\Selector\Entities::save([
3255 'context' => (isset($params['CONTEXT']) && $params['CONTEXT'] <> '' ? $params['CONTEXT'] : 'BLOG_POST'),
3256 'code' => 'U'.$userId
3257 ]);
3258
3259 if (Loader::includeModule('intranet') && class_exists('\Bitrix\Intranet\Integration\Mail\EmailUser'))
3260 {
3261 \Bitrix\Intranet\Integration\Mail\EmailUser::invite($userId);
3262 }
3263 }
3264
3265 return $result;
3266 }
3267
3268 public static function processBlogPostNewMailUserDestinations(&$destinationList)
3269 {
3270 foreach($destinationList as $key => $code)
3271 {
3272 if (preg_match('/^UE(.+)$/i', $code, $matches))
3273 {
3274
3275 $userEmail = $matches[1];
3276 $errorText = '';
3277
3278 $destRes = self::processUserEmail(array(
3279 'EMAIL' => $userEmail,
3280 'CONTEXT' => 'BLOG_POST'
3281 ), $errorText);
3282
3283 if (
3284 !empty($destRes)
3285 && is_array($destRes)
3286 )
3287 {
3288 unset($destinationList[$key]);
3289 $destinationList = array_merge($destinationList, $destRes);
3290 }
3291 }
3292 }
3293 }
3294
3295 public static function processBlogPostNewCrmContact(&$HTTPPost, &$componentResult)
3296 {
3297 $USent = (
3298 isset($HTTPPost["SPERM"]["U"])
3299 && is_array($HTTPPost["SPERM"]["U"])
3300 && !empty($HTTPPost["SPERM"]["U"])
3301 );
3302
3303 $UESent = (
3304 $componentResult["ALLOW_EMAIL_INVITATION"]
3305 && isset($HTTPPost["SPERM"]["UE"])
3306 && is_array($HTTPPost["SPERM"]["UE"])
3307 && !empty($HTTPPost["SPERM"]["UE"])
3308 );
3309
3310 if (
3311 ($USent || $UESent)
3312 && Loader::includeModule('mail')
3313 )
3314 {
3315 if (
3316 $USent
3317 && Loader::includeModule('crm')
3318 ) // process mail users/contacts
3319 {
3320 $userIdList = array();
3321 foreach ($HTTPPost["SPERM"]["U"] as $code)
3322 {
3323 if (preg_match('/^U(\d+)$/i', $code, $matches))
3324 {
3325 $userIdList[] = (int)$matches[1];
3326 }
3327 }
3328
3329 if (!empty($userIdList))
3330 {
3332 'filter' => array(
3333 'ID' => $userIdList,
3334 '!=UF_USER_CRM_ENTITY' => false
3335 ),
3336 'select' => array('ID', 'UF_USER_CRM_ENTITY')
3337 ));
3338 while ($user = $res->fetch())
3339 {
3340 $livefeedCrmEntity = \CCrmLiveFeedComponent::resolveLFEntityFromUF($user['UF_USER_CRM_ENTITY']);
3341
3342 if (!empty($livefeedCrmEntity))
3343 {
3344 list($k, $v) = $livefeedCrmEntity;
3345 if ($k && $v)
3346 {
3347 if (!isset($HTTPPost["SPERM"][$k]))
3348 {
3349 $HTTPPost["SPERM"][$k] = array();
3350 }
3351 $HTTPPost["SPERM"][$k][] = $k.$v;
3352 }
3353 }
3354 }
3355 }
3356 }
3357
3358 if ($UESent) // process emails
3359 {
3360 foreach ($HTTPPost["SPERM"]["UE"] as $key => $userEmail)
3361 {
3362 if (!check_email($userEmail))
3363 {
3364 continue;
3365 }
3366
3367 $errorText = '';
3368
3369 $destRes = self::processUserEmail([
3370 'EMAIL' => $userEmail,
3371 'NAME' => (
3372 isset($HTTPPost["INVITED_USER_NAME"])
3373 && isset($HTTPPost["INVITED_USER_NAME"][$userEmail])
3374 ? $HTTPPost["INVITED_USER_NAME"][$userEmail]
3375 : ''
3376 ),
3377 'LAST_NAME' => (
3378 isset($HTTPPost["INVITED_USER_LAST_NAME"])
3379 && isset($HTTPPost["INVITED_USER_LAST_NAME"][$userEmail])
3380 ? $HTTPPost["INVITED_USER_LAST_NAME"][$userEmail]
3381 : ''
3382 ),
3383 'CRM_ENTITY' => (
3384 isset($HTTPPost["INVITED_USER_CRM_ENTITY"])
3385 && isset($HTTPPost["INVITED_USER_CRM_ENTITY"][$userEmail])
3386 ? $HTTPPost["INVITED_USER_CRM_ENTITY"][$userEmail]
3387 : ''
3388 ),
3389 "CREATE_CRM_CONTACT" => (
3390 isset($HTTPPost["INVITED_USER_CREATE_CRM_CONTACT"])
3391 && isset($HTTPPost["INVITED_USER_CREATE_CRM_CONTACT"][$userEmail])
3392 ? $HTTPPost["INVITED_USER_CREATE_CRM_CONTACT"][$userEmail]
3393 : 'N'
3394 ),
3395 'CONTEXT' => 'BLOG_POST'
3396 ], $errorText);
3397
3398 foreach($destRes as $code)
3399 {
3400 if (preg_match('/^U(\d+)$/i', $code, $matches))
3401 {
3402 $HTTPPost["SPERM"]["U"][] = $code;
3403 }
3404 elseif (
3405 Loader::includeModule('crm')
3406 && (preg_match('/^CRM(CONTACT|COMPANY|LEAD|DEAL)(\d+)$/i', $code, $matches))
3407 )
3408 {
3409 if (!isset($HTTPPost["SPERM"]["CRM".$matches[1]]))
3410 {
3411 $HTTPPost["SPERM"]["CRM".$matches[1]] = array();
3412 }
3413 $HTTPPost["SPERM"]["CRM".$matches[1]][] = $code;
3414 }
3415 }
3416
3417 if (!empty($errorText))
3418 {
3419 $componentResult["ERROR_MESSAGE"] .= $errorText;
3420 }
3421 }
3422// unset($HTTPPost["SPERM"]["UE"]);
3423 }
3424 }
3425 }
3426
3427 public static function getUserSonetGroupIdList($userId = false, $siteId = false)
3428 {
3429 $result = array();
3430
3431 if ((int)$userId <= 0)
3432 {
3433 global $USER;
3434 $userId = (int)$USER->getId();
3435 }
3436
3437 if (!$siteId)
3438 {
3439 $siteId = SITE_ID;
3440 }
3441
3442 $currentCache = \Bitrix\Main\Data\Cache::createInstance();
3443
3444 $cacheTtl = defined("BX_COMP_MANAGED_CACHE") ? 3153600 : 3600*4;
3445 $cacheId = 'user_group_member'.$siteId.'_'.$userId;
3446 $cacheDir = '/sonet/user_group_member/'.$siteId.'/'.$userId;
3447
3448 if($currentCache->startDataCache($cacheTtl, $cacheId, $cacheDir))
3449 {
3450 global $CACHE_MANAGER;
3451
3452 $res = UserToGroupTable::getList(array(
3453 'filter' => array(
3454 '<=ROLE' => UserToGroupTable::ROLE_USER,
3455 '=USER_ID' => $userId,
3456 '=GROUP.ACTIVE' => 'Y',
3457 '=GROUP.WorkgroupSite:GROUP.SITE_ID' => $siteId
3458 ),
3459 'select' => array('GROUP_ID')
3460 ));
3461
3462 while ($record = $res->fetch())
3463 {
3464 $result[] = $record["GROUP_ID"];
3465 }
3466
3467 if(defined("BX_COMP_MANAGED_CACHE"))
3468 {
3469 $CACHE_MANAGER->startTagCache($cacheDir);
3470 $CACHE_MANAGER->registerTag("sonet_user2group_U".$userId);
3471 $CACHE_MANAGER->endTagCache();
3472 }
3473 $currentCache->endDataCache($result);
3474 }
3475 else
3476 {
3477 $result = $currentCache->getVars();
3478 }
3479
3480 return $result;
3481 }
3482
3483 public static function getAllowToAllDestination($userId = 0)
3484 {
3485 global $USER;
3486
3487 $userId = (int)$userId;
3488 if ($userId <= 0)
3489 {
3490 $userId = (int)$USER->getId();
3491 }
3492
3493 $allowToAll = (Option::get("socialnetwork", "allow_livefeed_toall", "Y") === "Y");
3494
3495 if ($allowToAll)
3496 {
3497 $toAllRightsList = unserialize(Option::get("socialnetwork", "livefeed_toall_rights", 'a:1:{i:0;s:2:"AU";}'), [ 'allowed_classes' => false ]);
3498 if (!$toAllRightsList)
3499 {
3500 $toAllRightsList = array("AU");
3501 }
3502
3503 $userGroupCodeList = array_merge(array("AU"), \CAccess::getUserCodesArray($userId));
3504 if (count(array_intersect($toAllRightsList, $userGroupCodeList)) <= 0)
3505 {
3506 $allowToAll = false;
3507 }
3508 }
3509
3510 return $allowToAll;
3511 }
3512
3513 public static function getLivefeedStepper()
3514 {
3515 $res = array();
3516 if (ModuleManager::isModuleInstalled('blog'))
3517 {
3518 $res["blog"] = array('Bitrix\Blog\Update\LivefeedIndexPost', 'Bitrix\Blog\Update\LivefeedIndexComment');
3519 }
3520 if (ModuleManager::isModuleInstalled('tasks'))
3521 {
3522 $res["tasks"] = array('Bitrix\Tasks\Update\LivefeedIndexTask');
3523 }
3524 if (ModuleManager::isModuleInstalled('calendar'))
3525 {
3526 $res["calendar"] = array('Bitrix\Calendar\Update\LivefeedIndexCalendar');
3527 }
3528 if (ModuleManager::isModuleInstalled('forum'))
3529 {
3530 $res["forum"] = array('Bitrix\Forum\Update\LivefeedIndexMessage', 'Bitrix\Forum\Update\LivefeedIndexComment');
3531 }
3532 if (ModuleManager::isModuleInstalled('xdimport'))
3533 {
3534 $res["xdimport"] = array('Bitrix\XDImport\Update\LivefeedIndexLog', 'Bitrix\XDImport\Update\LivefeedIndexComment');
3535 }
3536 if (ModuleManager::isModuleInstalled('wiki'))
3537 {
3538 $res["wiki"] = array('Bitrix\Wiki\Update\LivefeedIndexLog', 'Bitrix\Wiki\Update\LivefeedIndexComment');
3539 }
3540 if (!empty($res))
3541 {
3542 echo Stepper::getHtml($res, Loc::getMessage(ModuleManager::isModuleInstalled('intranet') ? 'SONET_HELPER_STEPPER_LIVEFEED2': 'SONET_HELPER_STEPPER_LIVEFEED'));
3543 }
3544 }
3545
3546 public static function checkProfileRedirect($userId = 0)
3547 {
3548 $userId = (int)$userId;
3549 if ($userId <= 0)
3550 {
3551 return;
3552 }
3553
3554 $select = array('ID', 'EXTERNAL_AUTH_ID');
3555 if (ModuleManager::isModuleInstalled('crm'))
3556 {
3557 $select[] = 'UF_USER_CRM_ENTITY';
3558 }
3560 'filter' => array(
3561 '=ID' => $userId
3562 ),
3563 'select' => $select
3564 ));
3565
3566 if ($userFields = $res->fetch())
3567 {
3568 $event = new Main\Event(
3569 'socialnetwork',
3570 'onUserProfileRedirectGetUrl',
3571 array(
3572 'userFields' => $userFields
3573 )
3574 );
3575 $event->send();
3576
3577 foreach ($event->getResults() as $eventResult)
3578 {
3579 if ($eventResult->getType() === \Bitrix\Main\EventResult::SUCCESS)
3580 {
3581 $eventParams = $eventResult->getParameters();
3582
3583 if (
3584 is_array($eventParams)
3585 && isset($eventParams['url'])
3586 )
3587 {
3588 LocalRedirect($eventParams['url']);
3589 }
3590 break;
3591 }
3592 }
3593 }
3594 }
3595
3596 // used when video transform
3597 public static function getBlogPostLimitedViewStatus($params = array())
3598 {
3599 $result = false;
3600
3601 $logId = (
3602 is_array($params)
3603 && !empty($params['logId'])
3604 && (int)$params['logId'] > 0
3605 ? (int)$params['logId']
3606 : 0
3607 );
3608
3609 if ($logId <= 0)
3610 {
3611 return $result;
3612 }
3613
3614 if ($logItem = Log::getById($logId))
3615 {
3616 $logItemFields = $logItem->getFields();
3617 if (
3618 isset($logItemFields['TRANSFORM'])
3619 && $logItemFields['TRANSFORM'] === "Y"
3620 )
3621 {
3622 $result = true;
3623 }
3624 }
3625
3626 return $result;
3627 }
3628
3629 public static function setBlogPostLimitedViewStatus($params = array())
3630 {
3631 static $extranetSiteId = null;
3632
3633 $result = false;
3634
3635 $show = (
3636 is_array($params)
3637 && isset($params['show'])
3638 && $params['show'] === true
3639 );
3640
3641 $postId = (
3642 is_array($params)
3643 && !empty($params['postId'])
3644 && (int)$params['postId'] > 0
3645 ? (int)$params['postId']
3646 : 0
3647 );
3648
3649 if (
3650 $postId <= 0
3651 || !Loader::includeModule('blog')
3652 )
3653 {
3654 return $result;
3655 }
3656
3657 if ($show)
3658 {
3659 $liveFeedEntity = Livefeed\Provider::init(array(
3660 'ENTITY_TYPE' => 'BLOG_POST',
3661 'ENTITY_ID' => $postId,
3662 ));
3663
3664 $logId = $liveFeedEntity->getLogId();
3665 if (!self::getBlogPostLimitedViewStatus(array(
3666 'logId' => $logId
3667 )))
3668 {
3669 return $result;
3670 }
3671
3672 $post = Post::getById($postId);
3673 $postFields = $post->getFields();
3674
3675 $socnetPerms = self::getBlogPostSocNetPerms(array(
3676 'postId' => $postId,
3677 'authorId' => $postFields["AUTHOR_ID"]
3678 ));
3679
3680 \CSocNetLogRights::deleteByLogID($logId);
3681 \CSocNetLogRights::add($logId, $socnetPerms, true, false);
3682 LogTable::update($logId, array(
3683 'LOG_UPDATE' => new SqlExpression(Application::getConnection()->getSqlHelper()->getCurrentDateTimeFunction()),
3684 'TRANSFORM' => 'N'
3685 ));
3686
3687 if (\Bitrix\Main\Loader::includeModule('crm'))
3688 {
3689 $logItem = Log::getById($logId);
3690 \CCrmLiveFeedComponent::processCrmBlogPostRights($logId, $logItem->getFields(), $postFields, 'new');
3691 }
3692
3694 'socnetPerms' => $socnetPerms,
3695 'logId' => $logId,
3696 'logEventId' => $liveFeedEntity->getEventId()
3697 ));
3698
3699 $logSiteIdList = array();
3700 $resSite = \CSocNetLog::getSite($logId);
3701 while($logSite = $resSite->fetch())
3702 {
3703 $logSiteIdList[] = $logSite["LID"];
3704 }
3705
3706 if (
3707 $extranetSiteId === null
3708 && Loader::includeModule('extranet')
3709 )
3710 {
3711 $extranetSiteId = \CExtranet::getExtranetSiteID();
3712 }
3713
3714 $siteId = false;
3715 foreach($logSiteIdList as $logSiteId)
3716 {
3717 if ($logSiteId != $extranetSiteId)
3718 {
3719 $siteId = $logSiteId;
3720 break;
3721 }
3722 }
3723
3724 if (!$siteId)
3725 {
3726 $siteId = \CSite::getDefSite();
3727 }
3728
3730 \Bitrix\Socialnetwork\Helper\Path::get('userblogpost_page', $siteId),
3731 array(
3732 "post_id" => $postId,
3733 "user_id" => $postFields["AUTHOR_ID"]
3734 )
3735 );
3736
3737 $notificationParamsList = array(
3738 'post' => array(
3739 'ID' => $postFields["ID"],
3740 'TITLE' => $postFields["TITLE"],
3741 'AUTHOR_ID' => $postFields["AUTHOR_ID"]
3742 ),
3743 'siteId' => $siteId,
3744 'postUrl' => $postUrl,
3745 'socnetRights' => $socnetPerms,
3746 );
3747
3748 $notificationParamsList['mentionList'] = Mention::getUserIds($postFields['DETAIL_TEXT']);
3749
3750 self::notifyBlogPostCreated($notificationParamsList);
3751
3752 if (
3753 !isset($params['notifyAuthor'])
3754 || $params['notifyAuthor']
3755 )
3756 {
3757 self::notifyAuthorOnSetBlogPostLimitedViewStatusShow(array(
3758 'POST_ID' => $postId,
3759 'POST_FIELDS' => $postFields,
3760 'POST_URL' => $postUrl,
3761 'LOG_ID' => $logId,
3762 'SITE_ID' => $siteId
3763 ));
3764 }
3765
3766 BXClearCache(true, self::getBlogPostCacheDir(array(
3767 'TYPE' => 'post',
3768 'POST_ID' => $postId
3769 )));
3770 }
3771
3772 $result = true;
3773
3774 return $result;
3775 }
3776
3777
3778 private static function notifyAuthorOnSetBlogPostLimitedViewStatusShow($params = array())
3779 {
3780 $postId = $params['POST_ID'];
3781 $postFields = $params['POST_FIELDS'];
3782 $postUrl = $params['POST_URL'];
3783 $logId = $params['LOG_ID'];
3784 $siteId = $params['SITE_ID'];
3785
3786
3787 if (Loader::includeModule('im'))
3788 {
3789 $authorPostUrl = $postUrl;
3790 if (ModuleManager::isModuleInstalled("extranet"))
3791 {
3792 $tmp = \CSocNetLogTools::processPath(
3793 array(
3794 "URL" => $authorPostUrl,
3795 ),
3796 $postFields["AUTHOR_ID"],
3797 $siteId
3798 );
3799 $authorPostUrl = $tmp["URLS"]["URL"];
3800
3801 $serverName = (
3802 mb_strpos($authorPostUrl, "http://") === 0
3803 || mb_strpos($authorPostUrl, "https://") === 0
3804 ? ""
3805 : $tmp["SERVER_NAME"]
3806 );
3807 }
3808
3810 "MESSAGE_TYPE" => IM_MESSAGE_SYSTEM,
3811 "TO_USER_ID" => $postFields["AUTHOR_ID"],
3812 "FROM_USER_ID" => $postFields["AUTHOR_ID"],
3813 "NOTIFY_TYPE" => IM_NOTIFY_SYSTEM,
3814 "NOTIFY_ANSWER" => "N",
3815 "NOTIFY_MODULE" => "socialnetwork",
3816 "NOTIFY_EVENT" => "transform",
3817 "NOTIFY_TAG" => "SONET|BLOG_POST_CONVERT|".$postId,
3818 "PARSE_LINK" => "N",
3819 "LOG_ID" => $logId,
3820 "NOTIFY_MESSAGE" => fn (?string $languageId = null) => Loc::getMessage('SONET_HELPER_VIDEO_CONVERSION_COMPLETED', array(
3821 '#POST_TITLE#' => '<a href="'.$authorPostUrl.'" class="bx-notifier-item-action">'.htmlspecialcharsbx($postFields["TITLE"]).'</a>'
3822 ), $languageId),
3823 "NOTIFY_MESSAGE_OUT" => fn (?string $languageId = null) => Loc::getMessage('SONET_HELPER_VIDEO_CONVERSION_COMPLETED', array(
3824 '#POST_TITLE#' => htmlspecialcharsbx($postFields["TITLE"]),
3825 ), $languageId)." ".$serverName.$authorPostUrl,
3826 );
3827
3828 $messageFields['PUSH_MESSAGE'] = Loc::getMessage('SONET_HELPER_VIDEO_CONVERSION_COMPLETED', array(
3829 '#POST_TITLE#' => '<a href="'.$authorPostUrl.'" class="bx-notifier-item-action">'.htmlspecialcharsbx($postFields["TITLE"]).'</a>'
3830 ));
3831 $messageFields['PUSH_PARAMS'] = array(
3832 'ACTION' => 'transform',
3833 'TAG' => $messageFields['NOTIFY_TAG']
3834 );
3835
3836 \CIMNotify::add($messageFields);
3837 }
3838 }
3839
3840 public static function getBlogPostSocNetPerms($params = array())
3841 {
3842 $result = array();
3843
3844 $postId = (
3845 is_array($params)
3846 && !empty($params['postId'])
3847 && (int)$params['postId'] > 0
3848 ? (int)$params['postId']
3849 : 0
3850 );
3851
3852 $authorId = (
3853 is_array($params)
3854 && !empty($params['authorId'])
3855 && (int)$params['authorId'] > 0
3856 ? (int)$params['authorId']
3857 : 0
3858 );
3859
3860 if ($postId <= 0)
3861 {
3862 return $result;
3863 }
3864
3865 if ($authorId <= 0)
3866 {
3867 $blogPostFields = \CBlogPost::getByID($postId);
3868 $authorId = (int)$blogPostFields["AUTHOR_ID"];
3869 }
3870
3871 if ($authorId <= 0)
3872 {
3873 return $result;
3874 }
3875
3876 $result = \CBlogPost::getSocNetPermsCode($postId);
3877
3878 $profileBlogPost = false;
3879 foreach($result as $perm)
3880 {
3881 if (preg_match('/^UP(\d+)$/', $perm, $matches))
3882 {
3883 $profileBlogPost = true;
3884 break;
3885 }
3886 }
3887 if (!$profileBlogPost)
3888 {
3889 if (!in_array("U".$authorId, $result, true))
3890 {
3891 $result[] = "U".$authorId;
3892 }
3893 $result[] = "SA"; // socnet admin
3894
3895 if (
3896 in_array("AU", $result, true)
3897 || in_array("G2", $result, true)
3898 )
3899 {
3900 $socnetPermsAdd = array();
3901
3902 foreach ($result as $perm)
3903 {
3904 if (preg_match('/^SG(\d+)$/', $perm, $matches))
3905 {
3906 if (
3907 !in_array("SG".$matches[1]."_".UserToGroupTable::ROLE_USER, $result, true)
3908 && !in_array("SG".$matches[1]."_".UserToGroupTable::ROLE_MODERATOR, $result, true)
3909 && !in_array("SG".$matches[1]."_".UserToGroupTable::ROLE_OWNER, $result, true)
3910 )
3911 {
3912 $socnetPermsAdd[] = "SG".$matches[1]."_".$result;
3913 }
3914 }
3915 }
3916 if (count($socnetPermsAdd) > 0)
3917 {
3918 $result = array_merge($result, $socnetPermsAdd);
3919 }
3920 }
3921 }
3922
3923 return $result;
3924 }
3925
3926 public static function notifyBlogPostCreated($params = array())
3927 {
3928 if (!Loader::includeModule('blog'))
3929 {
3930 return false;
3931 }
3932
3933 $post = (
3934 !empty($params)
3935 && is_array($params)
3936 && !empty($params['post'])
3937 && is_array($params['post'])
3938 ? $params['post']
3939 : []
3940 );
3941
3942 $siteId = (
3943 !empty($params)
3944 && is_array($params)
3945 && !empty($params['siteId'])
3946 ? $params['siteId']
3947 : \CSite::getDefSite()
3948 );
3949
3950 $postUrl = (
3951 !empty($params)
3952 && is_array($params)
3953 && !empty($params['postUrl'])
3954 ? $params['postUrl']
3955 : ''
3956 );
3957
3958 $socnetRights = (
3959 !empty($params)
3960 && is_array($params)
3961 && !empty($params['socnetRights'])
3962 && is_array($params['socnetRights'])
3963 ? $params['socnetRights']
3964 : []
3965 );
3966
3967 $socnetRightsOld = (
3968 !empty($params)
3969 && is_array($params)
3970 && !empty($params['socnetRightsOld'])
3971 && is_array($params['socnetRightsOld'])
3972 ? $params['socnetRightsOld']
3973 : array(
3974 'U' => [],
3975 'SG' => []
3976 )
3977 );
3978
3979 $mentionListOld = (
3980 !empty($params)
3981 && is_array($params)
3982 && !empty($params['mentionListOld'])
3983 && is_array($params['mentionListOld'])
3984 ? $params['mentionListOld']
3985 : []
3986 );
3987
3988 $mentionList = (
3989 !empty($params)
3990 && is_array($params)
3991 && !empty($params['mentionList'])
3992 && is_array($params['mentionList'])
3993 ? $params['mentionList']
3994 : []
3995 );
3996
3997 $gratData = (
3998 !empty($params)
3999 && is_array($params)
4000 && !empty($params['gratData'])
4001 && is_array($params['gratData'])
4002 ? $params['gratData']
4003 : []
4004 );
4005
4006 $IMNotificationFields = array(
4007 "TYPE" => "POST",
4008 "TITLE" => $post["TITLE"],
4009 "URL" => $postUrl,
4010 "ID" => $post["ID"],
4011 "FROM_USER_ID" => $post["AUTHOR_ID"],
4012 "TO_USER_ID" => array(),
4013 "TO_SOCNET_RIGHTS" => $socnetRights,
4014 "TO_SOCNET_RIGHTS_OLD" => $socnetRightsOld,
4015 "GRAT_DATA" => $gratData
4016 );
4017 if (!empty($mentionListOld))
4018 {
4019 $IMNotificationFields["MENTION_ID_OLD"] = $mentionListOld;
4020 }
4021 if (!empty($mentionList))
4022 {
4023 $IMNotificationFields["MENTION_ID"] = $mentionList;
4024 }
4025
4026 $userIdSentList = \CBlogPost::notifyIm($IMNotificationFields);
4027 if (!$userIdSentList)
4028 {
4029 $userIdSentList = [];
4030 }
4031
4032 $userIdToMailList = [];
4033
4034 if (!empty($socnetRights))
4035 {
4037 "EMAIL_FROM" => Option::get('main', 'email_from', 'nobody@nobody.com'),
4038 "SOCNET_RIGHTS" => $socnetRights,
4039 "SOCNET_RIGHTS_OLD" => $socnetRightsOld,
4040 "ENTITY_TYPE" => "POST",
4041 "ENTITY_ID" => $post["ID"],
4042 "AUTHOR_ID" => $post["AUTHOR_ID"],
4043 "URL" => $postUrl,
4044 'EXCLUDE_USERS' => array_merge([ $post['AUTHOR_ID'] ], $userIdSentList),
4045 ));
4046
4047 foreach ($socnetRights as $right)
4048 {
4049 if (mb_strpos($right, "U") === 0)
4050 {
4051 $rightUserId = (int)mb_substr($right, 1);
4052 if (
4053 $rightUserId > 0
4054 && empty($socnetRightsOld["U"][$rightUserId])
4055 && $rightUserId !== (int)$post["AUTHOR_ID"]
4056 && !in_array($rightUserId, $userIdToMailList, true)
4057 )
4058 {
4059 $userIdToMailList[] = $rightUserId;
4060 }
4061 }
4062 }
4063 }
4064
4065 if (!empty($userIdToMailList))
4066 {
4067 \CBlogPost::notifyMail([
4068 "type" => "POST",
4069 "siteId" => $siteId,
4070 "userId" => $userIdToMailList,
4071 "authorId" => $post["AUTHOR_ID"],
4072 "postId" => $post["ID"],
4074 '/pub/post.php?post_id=#post_id#',
4075 [
4076 "post_id" => $post["ID"],
4077 ]
4078 ),
4079 ]);
4080 }
4081
4082 return true;
4083 }
4084
4085 public static function getUserSEFUrl($params = array())
4086 {
4087 list($siteId, $siteDir) = self::getSiteId($params);
4088
4089 return Option::get('socialnetwork', 'user_page', $siteDir.'company/personal/', $siteId);
4090 }
4091
4092 public static function getWorkgroupSEFUrl($params = []): string
4093 {
4094 list($siteId, $siteDir) = self::getSiteId($params);
4095
4096 return Option::get('socialnetwork', 'workgroups_page', $siteDir.'workgroups/', $siteId);
4097 }
4098
4099 public static function getSpacesSEFUrl($params = []): string
4100 {
4101 list($siteId, $siteDir) = self::getSiteId($params);
4102
4103 return $siteDir . 'spaces/';
4104 }
4105
4106 private static function getSiteId($params = []): array
4107 {
4108 $siteId = (
4109 is_array($params)
4110 && isset($params['siteId'])
4111 ? $params['siteId']
4112 : false
4113 );
4114
4115 $siteDir = SITE_DIR;
4116 if ($siteId)
4117 {
4118 $res = \CSite::getById($siteId);
4119 if ($site = $res->fetch())
4120 {
4121 $siteDir = $site['DIR'];
4122 }
4123 }
4124
4125 return [$siteId, $siteDir];
4126 }
4127
4128 public static function convertBlogPostPermToDestinationList($params, &$resultFields)
4129 {
4130 global $USER;
4131
4132 $result = array();
4133
4134 if (!Loader::includeModule('blog'))
4135 {
4136 return $result;
4137 }
4138
4139 $postId = (
4140 isset($params['POST_ID'])
4141 && (int)$params['POST_ID'] > 0
4142 ? (int)$params['POST_ID']
4143 : false
4144 );
4145
4146 $postFields = array();
4147
4148 if ($postId)
4149 {
4150 $postFields = \Bitrix\Blog\Item\Post::getById($postId)->getFields();
4151 }
4152
4153 $authorId = (
4154 !$postId
4155 && isset($params['AUTHOR_ID'])
4156 && (int)$params['AUTHOR_ID'] > 0
4157 ? (int)$params['AUTHOR_ID']
4158 : $postFields['AUTHOR_ID']
4159 );
4160
4161 $extranetUser = (
4162 $params['IS_EXTRANET_USER'] ?? self::isCurrentUserExtranet([
4163 'siteId' => SITE_ID,
4164 'userId' => $USER->getId(),
4165 ])
4166 );
4167
4168 $siteId = (
4169 !empty($params['SITE_ID'])
4170 ? $params['SITE_ID']
4171 : SITE_ID
4172 );
4173
4174 $socNetPermsListOld = array();
4175
4176 if ($postId > 0)
4177 {
4178 $socNetPermsListOld = \CBlogPost::getSocNetPerms($postId);
4179 }
4180
4181 $authorInDest = (
4182 !empty($postFields)
4183 && !empty($postFields['AUTHOR_ID'])
4184 && !empty($socNetPermsListOld)
4185 && !empty($socNetPermsListOld['U'])
4186 && isset($socNetPermsListOld['U'][$postFields['AUTHOR_ID']])
4187 && in_array('U' . $postFields['AUTHOR_ID'], $socNetPermsListOld['U'][$postFields['AUTHOR_ID']], true)
4188 );
4189
4190 $permList = (
4191 isset($params['PERM'])
4192 && is_array($params['PERM'])
4193 ? $params['PERM']
4194 : array()
4195 );
4196
4197 $allowToAll = self::getAllowToAllDestination();
4198
4199 if(
4200 empty($permList)
4201 && isset($params["IS_REST"])
4202 && $params["IS_REST"]
4203 && $allowToAll
4204 )
4205 {
4206 $permList = array("UA" => array("UA"));
4207 }
4208
4209 foreach ($permList as $v => $k)
4210 {
4211 if (
4212 $v <> ''
4213 && is_array($k)
4214 && !empty($k)
4215 )
4216 {
4217 foreach ($k as $vv)
4218 {
4219 if (
4220 $vv <> ''
4221 && (
4222 empty($postFields['AUTHOR_ID'])
4223 || $vv !== 'U'.$postFields['AUTHOR_ID']
4224 || $authorInDest
4225 )
4226 )
4227 {
4228 $result[] = $vv;
4229 }
4230 }
4231 }
4232 }
4233
4235 'DEST' => $result,
4236 'SITE_ID' => $siteId,
4237 'AUTHOR_ID' => $authorId,
4238 'IS_EXTRANET_USER' => $extranetUser,
4239 'POST_ID' => $postId
4240 ), $resultFields);
4241
4242 return $result;
4243 }
4244
4245 public static function checkBlogPostDestinationList($params, &$resultFields)
4246 {
4247 global $USER;
4248
4249 $destinationList = (
4250 isset($params["DEST"])
4251 && is_array($params["DEST"])
4252 ? $params["DEST"]
4253 : array()
4254 );
4255
4256 $siteId = (
4257 !empty($params['SITE_ID'])
4258 ? $params['SITE_ID']
4259 : SITE_ID
4260 );
4261
4262 $currentUserId = $USER->getId();
4263
4264 if (!$currentUserId)
4265 {
4266 return false;
4267 }
4268
4269 $extranetUser = (
4270 $params['IS_EXTRANET_USER'] ?? self::isCurrentUserExtranet([
4271 'siteId' => SITE_ID,
4272 'userId' => $USER->getId()
4273 ])
4274 );
4275
4276 $postId = (
4277 isset($params['POST_ID'])
4278 && (int)$params['POST_ID'] > 0
4279 ? (int)$params['POST_ID']
4280 : false
4281 );
4282
4283 $postFields = [];
4284 $oldSonetGroupIdList = [];
4285
4286 if ($postId)
4287 {
4288 $socNetPermsListOld = \CBlogPost::getSocNetPerms($postId);
4289 $postFields = \Bitrix\Blog\Item\Post::getById($postId)->getFields();
4290 if (!empty($socNetPermsListOld['SG']))
4291 {
4292 $oldSonetGroupIdList = array_keys($socNetPermsListOld['SG']);
4293 }
4294 }
4295
4296 $userAdmin = \CSocNetUser::isUserModuleAdmin($currentUserId, $siteId);
4297 $allowToAll = self::getAllowToAllDestination();
4298
4299 $newSonetGroupIdList = [];
4300 $newUserIdList = [];
4301
4302 foreach($destinationList as $code)
4303 {
4304 if (preg_match('/^SG(\d+)/i', $code, $matches))
4305 {
4306 $newSonetGroupIdList[] = (int)$matches[1];
4307 }
4308 elseif (preg_match('/^U(\d+)/i', $code, $matches))
4309 {
4310 $newUserIdList[] = (int)$matches[1];
4311 }
4312 }
4313
4314 if (!empty($newSonetGroupIdList))
4315 {
4316 $oneSG = false;
4317 $firstSG = true;
4318
4319 $premoderateSGList = [];
4320 $canPublish = true;
4321
4322 foreach ($newSonetGroupIdList as $groupId)
4323 {
4324 if (
4325 !empty($postFields)
4326 && $postFields["PUBLISH_STATUS"] === BLOG_PUBLISH_STATUS_PUBLISH
4327 && in_array($groupId, $oldSonetGroupIdList)
4328 )
4329 {
4330 continue;
4331 }
4332
4333 $canPublishToGroup = (
4334 $userAdmin
4335 || \CSocNetFeaturesPerms::canPerformOperation($currentUserId, SONET_ENTITY_GROUP, $groupId, 'blog', 'write_post')
4336 || \CSocNetFeaturesPerms::canPerformOperation($currentUserId, SONET_ENTITY_GROUP, $groupId, 'blog', 'full_post')
4337 || \CSocNetFeaturesPerms::canPerformOperation($currentUserId, SONET_ENTITY_GROUP, $groupId, 'blog', 'moderate_post')
4338 );
4339
4340 $canPremoderateToGroup = \CSocNetFeaturesPerms::canPerformOperation($currentUserId, SONET_ENTITY_GROUP, $groupId, 'blog', 'premoderate_post');
4341
4342 if (
4343 !$canPublishToGroup
4344 && $canPremoderateToGroup
4345 )
4346 {
4347 $premoderateSGList[] = $groupId;
4348 }
4349
4350 $canPublish = (
4351 $canPublish
4352 && $canPublishToGroup
4353 );
4354
4355 if($firstSG)
4356 {
4357 $oneSG = true;
4358 $firstSG = false;
4359 }
4360 else
4361 {
4362 $oneSG = false;
4363 }
4364 }
4365
4366 if (!$canPublish)
4367 {
4368 if (!empty($premoderateSGList))
4369 {
4370 if ($oneSG)
4371 {
4372 if ($resultFields['PUBLISH_STATUS'] === BLOG_PUBLISH_STATUS_PUBLISH)
4373 {
4374 if (!$postId) // new post
4375 {
4376 $resultFields['PUBLISH_STATUS'] = BLOG_PUBLISH_STATUS_READY;
4377 }
4378 elseif ($postFields['PUBLISH_STATUS'] !== BLOG_PUBLISH_STATUS_PUBLISH)
4379 {
4380 $resultFields['PUBLISH_STATUS'] = $postFields['PUBLISH_STATUS'];
4381 }
4382 else
4383 {
4384 $resultFields['ERROR_MESSAGE'] = Loc::getMessage('SBPE_EXISTING_POST_PREMODERATION');
4385 $resultFields['ERROR_MESSAGE_PUBLIC'] = $resultFields['ERROR_MESSAGE'];
4386 }
4387 }
4388 }
4389 else
4390 {
4391 $groupNameList = [];
4392 $groupUrl = Option::get('socialnetwork', 'workgroups_page', SITE_DIR.'workgroups/', SITE_ID).'group/#group_id#/';
4393
4394 $res = WorkgroupTable::getList([
4395 'filter' => [
4396 '@ID' => $premoderateSGList
4397 ],
4398 'select' => [ 'ID', 'NAME' ]
4399 ]);
4400 while ($groupFields = $res->fetch())
4401 {
4402 $groupNameList[] = (
4403 isset($params['MOBILE']) && $params['MOBILE'] === 'Y'
4404 ? $groupFields['NAME']
4405 : '<a href="' . \CComponentEngine::makePathFromTemplate($groupUrl, [ 'group_id' => $groupFields['ID'] ]) . '">' . htmlspecialcharsEx($groupFields['NAME']) . '</a>'
4406 );
4407 }
4408
4409 $resultFields['ERROR_MESSAGE'] = Loc::getMessage('SBPE_MULTIPLE_PREMODERATION2', [
4410 '#GROUPS_LIST#' => implode(', ', $groupNameList)
4411 ]);
4412 $resultFields['ERROR_MESSAGE_PUBLIC'] = $resultFields['ERROR_MESSAGE'];
4413 }
4414 }
4415 else
4416 {
4417 $resultFields['ERROR_MESSAGE'] = Loc::getMessage('SONET_HELPER_NO_PERMISSIONS');
4418 }
4419 }
4420 }
4421
4422 if ($extranetUser)
4423 {
4424 $destinationList = array_filter($destinationList, static function ($code) {
4425 return (!preg_match('/^(DR|D)(\d+)$/i', $code, $matches));
4426 });
4427
4428 if (
4429 !empty($newUserIdList)
4430 && Loader::includeModule('extranet')
4431 )
4432 {
4433 $visibleUserIdList = \CExtranet::getMyGroupsUsersSimple(SITE_ID);
4434
4435 if (!empty(array_diff($newUserIdList, $visibleUserIdList)))
4436 {
4437 $resultFields['ERROR_MESSAGE'] = Loc::getMessage('SONET_HELPER_NO_PERMISSIONS');
4438 }
4439 }
4440 }
4441
4442 if (
4443 !$allowToAll
4444 && in_array("UA", $destinationList, true)
4445 )
4446 {
4447 foreach ($destinationList as $key => $value)
4448 {
4449 if ($value === "UA")
4450 {
4451 unset($destinationList[$key]);
4452 break;
4453 }
4454 }
4455 }
4456
4457 if ($extranetUser)
4458 {
4459 if (
4460 empty($destinationList)
4461 || in_array("UA", $destinationList, true)
4462 )
4463 {
4464 $resultFields["ERROR_MESSAGE"] .= Loc::getMessage("BLOG_BPE_EXTRANET_ERROR");
4465 }
4466 }
4467 elseif (empty($destinationList))
4468 {
4469 $resultFields["ERROR_MESSAGE"] .= Loc::getMessage("BLOG_BPE_DESTINATION_EMPTY");
4470 }
4471
4472 return $destinationList;
4473 }
4474
4475 public static function getBlogPostCacheDir($params = array())
4476 {
4477 static $allowedTypes = array(
4478 'post_general',
4479 'post',
4480 'post_urlpreview',
4481 'posts_popular',
4482 'post_comments',
4483 'posts_last',
4484 'posts_last_blog'
4485 );
4486
4487 $result = false;
4488
4489 if (!is_array($params))
4490 {
4491 return $result;
4492 }
4493
4494 $type = ($params['TYPE'] ?? false);
4495
4496 if (
4497 !$type
4498 || !in_array($type, $allowedTypes, true)
4499 )
4500 {
4501 return $result;
4502 }
4503
4504 $postId = (
4505 isset($params['POST_ID'])
4506 && (int)$params['POST_ID'] > 0
4507 ? (int)$params['POST_ID']
4508 : false
4509 );
4510
4511 if (
4512 !$postId
4513 && in_array($type, array('post_general', 'post', 'post_comments', 'post_urlpreview'))
4514 )
4515 {
4516 return $result;
4517 }
4518
4519 $siteId = ($params['SITE_ID'] ?? SITE_ID);
4520
4521 switch($type)
4522 {
4523 case 'post':
4524 $result = "/blog/socnet_post/".(int)($postId / 100)."/".$postId."/";
4525 break;
4526 case 'post_general':
4527 $result = "/blog/socnet_post/gen/".(int)($postId / 100)."/".$postId;
4528 break;
4529 case 'post_urlpreview':
4530 $result = "/blog/socnet_post/urlpreview/".(int)($postId / 100)."/".$postId;
4531 break;
4532 case 'posts_popular':
4533 $result = "/".$siteId."/blog/popular_posts/";
4534 break;
4535 case 'posts_last':
4536 $result = "/".$siteId."/blog/last_messages_list/";
4537 break;
4538 case 'posts_last_blog':
4539 $result = "/".$siteId."/blog/last_messages/";
4540 break;
4541 case 'post_comments':
4542 $result = "/blog/comment/".(int)($postId / 100)."/".$postId."/";
4543 break;
4544 default:
4545 $result = false;
4546 }
4547
4548 return $result;
4549 }
4550
4551 public static function getLivefeedRatingData($params = [])
4552 {
4553 global $USER;
4554
4555 $result = [];
4556
4557 $logIdList = (
4558 !empty($params['logId'])
4559 ? $params['logId']
4560 : []
4561 );
4562
4563 if (!is_array($logIdList))
4564 {
4565 $logIdList = [ $logIdList ];
4566 }
4567
4568 if (empty($logIdList))
4569 {
4570 return $result;
4571 }
4572
4573 $ratingId = \CRatings::getAuthorityRating();
4574 if ((int)$ratingId <= 0)
4575 {
4576 return $result;
4577 }
4578
4579 $result = array_fill_keys($logIdList, []);
4580
4581 $topCount = (
4582 isset($params['topCount'])
4583 ? (int)$params['topCount']
4584 : 0
4585 );
4586
4587 if ($topCount <= 0)
4588 {
4589 $topCount = 2;
4590 }
4591
4592 if ($topCount > 5)
4593 {
4594 $topCount = 5;
4595 }
4596
4597 $avatarSize = (
4598 isset($params['avatarSize'])
4599 ? (int)$params['avatarSize']
4600 : 100
4601 );
4602
4603 $connection = Application::getConnection();
4604
4605 if (ModuleManager::isModuleInstalled('intranet'))
4606 {
4607 $res = $connection->query('
4608 SELECT /*+ NO_DERIVED_CONDITION_PUSHDOWN() */
4609 RS1.ENTITY_ID as USER_ID,
4610 SL.ID as LOG_ID,
4611 MAX(RS1.VOTES) as WEIGHT
4612 FROM
4613 b_rating_subordinate RS1,
4614 b_rating_vote RV1
4615 INNER JOIN b_sonet_log SL
4616 ON SL.RATING_TYPE_ID = RV1.ENTITY_TYPE_ID
4617 AND SL.RATING_ENTITY_ID = RV1.ENTITY_ID
4618 AND SL.ID IN ('.implode(',', $logIdList).')
4619 WHERE
4620 RS1.ENTITY_ID = RV1.USER_ID
4621 AND RS1.RATING_ID = '.(int)$ratingId.'
4622 GROUP BY
4623 SL.ID, RS1.ENTITY_ID
4624 ORDER BY
4625 SL.ID,
4626 WEIGHT DESC
4627 ');
4628 }
4629 else
4630 {
4631 $res = $connection->query('
4632 SELECT /*+ NO_DERIVED_CONDITION_PUSHDOWN() */
4633 RV1.USER_ID as USER_ID,
4634 SL.ID as LOG_ID,
4635 RV1.VALUE as WEIGHT
4636 FROM
4637 b_rating_vote RV1
4638 INNER JOIN b_sonet_log SL
4639 ON SL.RATING_TYPE_ID = RV1.ENTITY_TYPE_ID
4640 AND SL.RATING_ENTITY_ID = RV1.ENTITY_ID
4641 AND SL.ID IN ('.implode(',', $logIdList).')
4642 ORDER BY
4643 SL.ID,
4644 WEIGHT DESC
4645 ');
4646 }
4647
4648 $userWeightData = [];
4649 $logUserData = [];
4650
4651 $currentLogId = 0;
4652 $hasMine = false;
4653 $cnt = 0;
4654
4655 while ($voteFields = $res->fetch())
4656 {
4657 $voteUserId = (int)$voteFields['USER_ID'];
4658 $voteLogId = (int)$voteFields['LOG_ID'];
4659
4660 if (
4661 !$hasMine
4662 && $voteUserId === (int)$USER->getId()
4663 )
4664 {
4665 $hasMine = true;
4666 }
4667
4668 if ($voteLogId !== $currentLogId)
4669 {
4670 $cnt = 0;
4671 $hasMine = false;
4672 $logUserData[$voteLogId] = [];
4673 }
4674
4675 $currentLogId = $voteLogId;
4676
4677 if (in_array($voteUserId, $logUserData[$voteLogId], true))
4678 {
4679 continue;
4680 }
4681
4682 $cnt++;
4683
4684 if ($cnt > ($hasMine ? $topCount+1 : $topCount))
4685 {
4686 continue;
4687 }
4688
4689 $logUserData[$voteLogId][] = $voteUserId;
4690 if (!isset($userWeightData[$voteUserId]))
4691 {
4692 $userWeightData[$voteUserId] = (float)$voteFields['WEIGHT'];
4693 }
4694 }
4695
4696 $userData = [];
4697
4698 if (!empty($userWeightData))
4699 {
4701 'filter' => [
4702 '@ID' => array_keys($userWeightData)
4703 ],
4704 'select' => [ 'ID', 'NAME', 'LAST_NAME', 'SECOND_NAME', 'LOGIN', 'PERSONAL_PHOTO', 'PERSONAL_GENDER' ]
4705 ]);
4706
4707 while ($userFields = $res->fetch())
4708 {
4709 $userData[$userFields["ID"]] = [
4710 'NAME_FORMATTED' => \CUser::formatName(
4711 \CSite::getNameFormat(false),
4712 $userFields,
4713 true
4714 ),
4715 'PERSONAL_PHOTO' => [
4716 'ID' => $userFields['PERSONAL_PHOTO'],
4717 'SRC' => false
4718 ],
4719 'PERSONAL_GENDER' => $userFields['PERSONAL_GENDER']
4720 ];
4721
4722 if ((int)$userFields['PERSONAL_PHOTO'] > 0)
4723 {
4724 $imageFile = \CFile::getFileArray($userFields["PERSONAL_PHOTO"]);
4725 if ($imageFile !== false)
4726 {
4727 $file = \CFile::resizeImageGet(
4728 $imageFile,
4729 [
4730 'width' => $avatarSize,
4731 'height' => $avatarSize,
4732 ],
4734 false
4735 );
4736 $userData[$userFields["ID"]]['PERSONAL_PHOTO']['SRC'] = $file['src'];
4737 }
4738 }
4739 }
4740 }
4741
4742 foreach ($logUserData as $logId => $userIdList)
4743 {
4744 $result[$logId] = [];
4745
4746 foreach ($userIdList as $userId)
4747 {
4748 $result[$logId][] = [
4749 'ID' => $userId,
4750 'NAME_FORMATTED' => $userData[$userId]['NAME_FORMATTED'],
4751 'PERSONAL_PHOTO' => $userData[$userId]['PERSONAL_PHOTO']['ID'],
4752 'PERSONAL_PHOTO_SRC' => $userData[$userId]['PERSONAL_PHOTO']['SRC'],
4753 'PERSONAL_GENDER' => $userData[$userId]['PERSONAL_GENDER'],
4754 'WEIGHT' => $userWeightData[$userId]
4755 ];
4756 }
4757 }
4758
4759 foreach ($result as $logId => $data)
4760 {
4761 usort(
4762 $data,
4763 static function($a, $b)
4764 {
4765 if (
4766 !isset($a['WEIGHT'], $b['WEIGHT'])
4767 || $a['WEIGHT'] === $b['WEIGHT']
4768 )
4769 {
4770 return 0;
4771 }
4772 return ($a['WEIGHT'] > $b['WEIGHT']) ? -1 : 1;
4773 }
4774 );
4775 $result[$logId] = $data;
4776 }
4777
4778 return $result;
4779 }
4780
4781 public static function isCurrentUserExtranet($params = [])
4782 {
4783 static $result = [];
4784
4785 $siteId = (!empty($params['siteId']) ? $params['siteId'] : SITE_ID);
4786
4787 if (!isset($result[$siteId]))
4788 {
4789 $result[$siteId] = (
4790 !\CSocNetUser::isCurrentUserModuleAdmin($siteId, false)
4791 && Loader::includeModule('extranet')
4792 && !\CExtranet::isIntranetUser()
4793 );
4794 }
4795
4796 return $result[$siteId];
4797 }
4798
4799 public static function userLogSubscribe($params = array())
4800 {
4801 static
4802 $logAuthorList = array(),
4803 $logDestUserList = array();
4804
4805 $userId = (isset($params['userId']) ? (int)$params['userId'] : 0);
4806 $logId = (isset($params['logId']) ? (int)$params['logId'] : 0);
4807 $typeList = ($params['typeList'] ?? []);
4808 $siteId = (isset($params['siteId']) ? (int)$params['siteId'] : SITE_ID);
4809 $followByWF = !empty($params['followByWF']);
4810
4811 if (!is_array($typeList))
4812 {
4813 $typeList = array($typeList);
4814 }
4815
4816 if (
4817 $userId <= 0
4818 || $logId <= 0
4819 )
4820 {
4821 return false;
4822 }
4823
4824 $followRes = false;
4825
4826 if (in_array('FOLLOW', $typeList))
4827 {
4828 $followRes = \CSocNetLogFollow::set(
4829 $userId,
4830 "L".$logId,
4831 "Y",
4832 (
4833 !empty($params['followDate'])
4834 ? (
4835 mb_strtoupper($params['followDate']) === 'CURRENT'
4836 ? ConvertTimeStamp(time() + \CTimeZone::getOffset(), "FULL", $siteId)
4837 : $params['followDate']
4838 )
4839 : false
4840 ),
4841 $siteId,
4842 $followByWF
4843 );
4844 }
4845
4846 if (in_array('COUNTER_COMMENT_PUSH', $typeList))
4847 {
4848 if (!isset($logAuthorList[$logId]))
4849 {
4851 'filter' => array(
4852 '=ID' => $logId
4853 ),
4854 'select' => array('USER_ID')
4855 ));
4856 if ($logFields = $res->fetch())
4857 {
4858 $logAuthorList[$logId] = $logFields['USER_ID'];
4859 }
4860 }
4861
4862 if (!isset($logDestUserList[$logId]))
4863 {
4864 $logDestUserList[$logId] = array();
4865 $res = LogRightTable::getList(array(
4866 'filter' => array(
4867 '=LOG_ID' => $logId
4868 ),
4869 'select' => array('GROUP_CODE')
4870 ));
4871 while ($logRightFields = $res->fetch())
4872 {
4873 if (preg_match('/^U(\d+)$/', $logRightFields['GROUP_CODE'], $matches))
4874 {
4875 $logDestUserList[$logId][] = $matches[1];
4876 }
4877 }
4878 }
4879
4880 if (
4881 $userId != $logAuthorList[$logId]
4882 && !in_array($userId, $logDestUserList[$logId])
4883 )
4884 {
4886 'userId' => $userId,
4887 'logId' => $logId,
4889 'ttl' => true
4890 ));
4891 }
4892 }
4893
4894 return (
4895 in_array('FOLLOW', $typeList)
4896 ? $followRes
4897 : true
4898 );
4899 }
4900
4901 public static function getLFCommentsParams($eventFields = array()): array
4902 {
4903 $forumMetaData = \CSocNetLogTools::getForumCommentMetaData($eventFields["EVENT_ID"]);
4904
4905 if (
4906 $forumMetaData
4907 && $eventFields["SOURCE_ID"] > 0
4908 )
4909 {
4910 $result = [
4911 "ENTITY_TYPE" => $forumMetaData[1],
4912 "ENTITY_XML_ID" => $forumMetaData[0]."_".$eventFields["SOURCE_ID"],
4913 "NOTIFY_TAGS" => $forumMetaData[2]
4914 ];
4915
4916 // Calendar events could generate different livefeed entries with same SOURCE_ID
4917 // That's why we should add entry ID to make comment interface work
4918 if (
4919 $eventFields["EVENT_ID"] === 'calendar'
4920 && !empty($eventFields["PARAMS"])
4921 && ($calendarEventParams = unserialize(htmlspecialcharsback($eventFields["PARAMS"]), [ 'allowed_classes' => false ]))
4922 && !empty($calendarEventParams['COMMENT_XML_ID'])
4923 )
4924 {
4925 $result["ENTITY_XML_ID"] = $calendarEventParams['COMMENT_XML_ID'];
4926 }
4927 }
4928 elseif ($eventFields["EVENT_ID"] === 'photo') // photo album
4929 {
4930 $result = array(
4931 "ENTITY_TYPE" => 'PA',
4932 "ENTITY_XML_ID" => 'PHOTO_ALBUM_'.$eventFields["ID"],
4933 "NOTIFY_TAGS" => ''
4934 );
4935 }
4936 else
4937 {
4938 $result = array(
4939 "ENTITY_TYPE" => mb_substr(mb_strtoupper($eventFields["EVENT_ID"])."_".$eventFields["ID"], 0, 2),
4940 "ENTITY_XML_ID" => mb_strtoupper($eventFields["EVENT_ID"])."_".$eventFields["ID"],
4941 "NOTIFY_TAGS" => ""
4942 );
4943 }
4944
4945 if (
4946 mb_strtoupper($eventFields["ENTITY_TYPE"]) === "CRMACTIVITY"
4947 && Loader::includeModule('crm')
4948 && ($activityFields = \CCrmActivity::getById($eventFields["ENTITY_ID"], false))
4949 && (
4950 $activityFields["TYPE_ID"] == \CCrmActivityType::Task
4951 || (
4952 (int)$activityFields['TYPE_ID'] === \CCrmActivityType::Provider
4953 && $activityFields['PROVIDER_ID'] === Task::getId()
4954 )
4955 )
4956 )
4957 {
4958 $result["ENTITY_XML_ID"] = "TASK_".$activityFields["ASSOCIATED_ENTITY_ID"];
4959 }
4960 elseif (
4961 $eventFields["ENTITY_TYPE"] === "WF"
4962 && is_numeric($eventFields["SOURCE_ID"])
4963 && (int)$eventFields["SOURCE_ID"] > 0
4964 && Loader::includeModule('bizproc')
4965 && ($workflowId = \CBPStateService::getWorkflowByIntegerId($eventFields["SOURCE_ID"]))
4966 )
4967 {
4968 $result["ENTITY_XML_ID"] = "WF_".$workflowId;
4969 }
4970
4971 return $result;
4972 }
4973
4974 public static function checkCanCommentInWorkgroup($params)
4975 {
4976 static $canCommentCached = [];
4977
4978 $userId = (isset($params['userId']) ? (int)$params['userId'] : 0);
4979 $workgroupId = (isset($params['workgroupId']) ? (int)$params['workgroupId'] : 0);
4980 if (
4981 $userId <= 0
4982 || $workgroupId <= 0
4983 )
4984 {
4985 return false;
4986 }
4987
4988 $cacheKey = $userId.'_'.$workgroupId;
4989
4990 if (!isset($canCommentCached[$cacheKey]))
4991 {
4992 $canCommentCached[$cacheKey] = (
4993 \CSocNetFeaturesPerms::canPerformOperation($userId, SONET_ENTITY_GROUP, $workgroupId, "blog", "premoderate_comment")
4994 || \CSocNetFeaturesPerms::canPerformOperation($userId, SONET_ENTITY_GROUP, $workgroupId, "blog", "write_comment")
4995 );
4996 }
4997
4998 return $canCommentCached[$cacheKey];
4999 }
5000
5001 public static function checkLivefeedTasksAllowed()
5002 {
5003 return Option::get('socialnetwork', 'livefeed_allow_tasks', true);
5004 }
5005
5006 public static function convertSelectorRequestData(array &$postFields = [], array $params = []): void
5007 {
5008 $perms = (string)($params['perms'] ?? '');
5009 $crm = (bool)($params['crm'] ?? false);
5010
5011 $mapping = [
5012 'DEST_DATA' => 'DEST_CODES',
5013 'GRAT_DEST_DATA' => 'GRAT_DEST_CODES',
5014 ];
5015
5016 foreach ($mapping as $from => $to)
5017 {
5018 if (isset($postFields[$from]))
5019 {
5020 try
5021 {
5022 $entities = Json::decode($postFields[$from]);
5023 }
5024 catch (ArgumentException $e)
5025 {
5026 $entities = [];
5027 }
5028
5029 $postFields[$to] = array_merge(
5030 ($postFields[$to] ?? []),
5031 \Bitrix\Main\UI\EntitySelector\Converter::convertToFinderCodes($entities)
5032 );
5033 }
5034 }
5035
5036 $mapping = [
5037 'DEST_CODES' => 'SPERM',
5038 'GRAT_DEST_CODES' => 'GRAT',
5039 'EVENT_DEST_CODES' => 'EVENT_PERM'
5040 ];
5041
5042 foreach ($mapping as $from => $to)
5043 {
5044 if (isset($postFields[$from]))
5045 {
5046 if (
5047 !isset($postFields[$to])
5048 || !is_array($postFields[$to])
5049 )
5050 {
5051 $postFields[$to] = [];
5052 }
5053
5054 foreach ($postFields[$from] as $destCode)
5055 {
5056 if ($destCode === 'UA')
5057 {
5058 if (empty($postFields[$to]['UA']))
5059 {
5060 $postFields[$to]['UA'] = [];
5061 }
5062 $postFields[$to]['UA'][] = 'UA';
5063 }
5064 elseif (preg_match('/^UE(.+)$/i', $destCode, $matches))
5065 {
5066 if (empty($postFields[$to]['UE']))
5067 {
5068 $postFields[$to]['UE'] = [];
5069 }
5070 $postFields[$to]['UE'][] = $matches[1];
5071 }
5072 elseif (preg_match('/^U(\d+)$/i', $destCode, $matches))
5073 {
5074 if (empty($postFields[$to]['U']))
5075 {
5076 $postFields[$to]['U'] = [];
5077 }
5078 $postFields[$to]['U'][] = 'U' . $matches[1];
5079 }
5080 elseif (
5081 $from === 'DEST_CODES'
5082 && $perms === BLOG_PERMS_FULL
5083 && preg_match('/^UP(\d+)$/i', $destCode, $matches)
5084 && Loader::includeModule('blog')
5085 )
5086 {
5087 if (empty($postFields[$to]['UP']))
5088 {
5089 $postFields[$to]['UP'] = [];
5090 }
5091 $postFields[$to]['UP'][] = 'UP' . $matches[1];
5092 }
5093 elseif (preg_match('/^SG(\d+)$/i', $destCode, $matches))
5094 {
5095 if (empty($postFields[$to]['SG']))
5096 {
5097 $postFields[$to]['SG'] = [];
5098 }
5099 $postFields[$to]['SG'][] = 'SG' . $matches[1];
5100 }
5101 elseif (preg_match('/^DR(\d+)$/i', $destCode, $matches))
5102 {
5103 if (empty($postFields[$to]['DR']))
5104 {
5105 $postFields[$to]['DR'] = [];
5106 }
5107 $postFields[$to]['DR'][] = 'DR' . $matches[1];
5108 }
5109 elseif ($crm && preg_match('/^CRMCONTACT(\d+)$/i', $destCode, $matches))
5110 {
5111 if (empty($postFields[$to]['CRMCONTACT']))
5112 {
5113 $postFields[$to]['CRMCONTACT'] = [];
5114 }
5115 $postFields[$to]['CRMCONTACT'][] = 'CRMCONTACT' . $matches[1];
5116 }
5117 elseif ($crm && preg_match('/^CRMCOMPANY(\d+)$/i', $destCode, $matches))
5118 {
5119 if (empty($postFields[$to]['CRMCOMPANY']))
5120 {
5121 $postFields[$to]['CRMCOMPANY'] = [];
5122 }
5123 $postFields[$to]['CRMCOMPANY'][] = 'CRMCOMPANY' . $matches[1];
5124 }
5125 elseif ($crm && preg_match('/^CRMLEAD(\d+)$/i', $destCode, $matches))
5126 {
5127 if (empty($postFields[$to]['CRMLEAD']))
5128 {
5129 $postFields[$to]['CRMLEAD'] = [];
5130 }
5131 $postFields[$to]['CRMLEAD'][] = 'CRMLEAD' . $matches[1];
5132 }
5133 elseif ($crm && preg_match('/^CRMDEAL(\d+)$/i', $destCode, $matches))
5134 {
5135 if (empty($postFields[$to]['CRMDEAL']))
5136 {
5137 $postFields[$to]['CRMDEAL'] = [];
5138 }
5139 $postFields[$to]['CRMDEAL'][] = 'CRMDEAL' . $matches[1];
5140 }
5141 }
5142
5143 unset($postFields[$from]);
5144 }
5145 }
5146 }
5147
5148 public static function isCurrentPageFirst(array $params = []): bool
5149 {
5150 $result = false;
5151
5152 $componentName = (string)($params['componentName'] ?? '');
5153 $page = (string)($params['page'] ?? '');
5154 $entityId = (int)($params['entityId'] ?? 0);
5155 $firstMenuItemCode = (string)($params['firstMenuItemCode'] ?? '');
5156 $canViewTasks = (bool)($params['canView']['tasks'] ?? false);
5157
5158 if ($entityId <= 0)
5159 {
5160 return $result;
5161 }
5162
5163 if ($componentName === 'bitrix:socialnetwork_group')
5164 {
5165 if ($firstMenuItemCode !== '')
5166 {
5167 return (
5168 mb_strpos($page, $firstMenuItemCode) !== false
5169 || in_array($page, [ 'group', 'group_general', 'group_tasks' ])
5170 );
5171 }
5172
5173 $result = (
5174 (
5175 $page === 'group_tasks'
5176 && \CSocNetFeatures::IsActiveFeature(SONET_ENTITY_GROUP, $entityId, 'tasks')
5177 && $canViewTasks
5178 )
5179 || (
5180 $page === 'group'
5181 || $page === 'group_general'
5182 )
5183 );
5184 }
5185
5186 return $result;
5187 }
5188
5189 public static function getWorkgroupSliderMenuUrlList(array $componentResult = []): array
5190 {
5191 return [
5192 'CARD' => (string)($componentResult['PATH_TO_GROUP_CARD'] ?? ''),
5193 'EDIT' => (string)($componentResult['PATH_TO_GROUP_EDIT'] ?? ''),
5194 'COPY' => (string)($componentResult['PATH_TO_GROUP_COPY'] ?? ''),
5195 'DELETE' => (string)($componentResult['PATH_TO_GROUP_DELETE'] ?? ''),
5196 'LEAVE' => (string)($componentResult['PATH_TO_USER_LEAVE_GROUP'] ?? ''),
5197 'JOIN' => (string)($componentResult['PATH_TO_USER_REQUEST_GROUP'] ?? ''),
5198 'MEMBERS' => (string)($componentResult['PATH_TO_GROUP_USERS'] ?? ''),
5199 'REQUESTS_IN' => (string)($componentResult['PATH_TO_GROUP_REQUESTS'] ?? ''),
5200 'REQUESTS_OUT' => (string)($componentResult['PATH_TO_GROUP_REQUESTS_OUT'] ?? ''),
5201 'FEATURES' => (string)($componentResult['PATH_TO_GROUP_FEATURES'] ?? ''),
5202 ];
5203 }
5204
5205 public static function listWorkgroupSliderMenuSignedParameters(array $componentParameters = []): array
5206 {
5207 return array_filter($componentParameters, static function ($key) {
5208/*
5209 'PATH_TO_USER',
5210 'PATH_TO_GROUP_EDIT',
5211 'PATH_TO_GROUP_INVITE',
5212 'PATH_TO_GROUP_CREATE',
5213 'PATH_TO_GROUP_COPY',
5214 'PATH_TO_GROUP_REQUEST_SEARCH',
5215 'PATH_TO_USER_REQUEST_GROUP',
5216 'PATH_TO_GROUP_REQUESTS',
5217 'PATH_TO_GROUP_REQUESTS_OUT',
5218 'PATH_TO_GROUP_MODS',
5219 'PATH_TO_GROUP_USERS',
5220 'PATH_TO_USER_LEAVE_GROUP',
5221 'PATH_TO_GROUP_DELETE',
5222 'PATH_TO_GROUP_FEATURES',
5223 'PATH_TO_GROUP_BAN',
5224 'PATH_TO_SEARCH',
5225 'PATH_TO_SEARCH_TAG',
5226 'PATH_TO_GROUP_BLOG_POST',
5227 'PATH_TO_GROUP_BLOG',
5228 'PATH_TO_BLOG',
5229 'PATH_TO_POST',
5230 'PATH_TO_POST_EDIT',
5231 'PATH_TO_USER_BLOG_POST_IMPORTANT',
5232 'PATH_TO_GROUP_FORUM',
5233 'PATH_TO_GROUP_FORUM_TOPIC',
5234 'PATH_TO_GROUP_FORUM_MESSAGE',
5235 'PATH_TO_GROUP_SUBSCRIBE',
5236 'PATH_TO_MESSAGE_TO_GROUP',
5237 'PATH_TO_GROUP_TASKS',
5238 'PATH_TO_GROUP_TASKS_TASK',
5239 'PATH_TO_GROUP_TASKS_VIEW',
5240 'PATH_TO_GROUP_CONTENT_SEARCH',
5241 'PATH_TO_MESSAGES_CHAT',
5242 'PATH_TO_VIDEO_CALL',
5243 'PATH_TO_CONPANY_DEPARTMENT',
5244 'PATH_TO_USER_LOG',
5245 'PATH_TO_GROUP_LOG',
5246
5247 'PAGE_VAR',
5248 'USER_VAR',
5249 'GROUP_VAR',
5250 'TASK_VAR',
5251 'TASK_ACTION_VAR',
5252
5253 'SET_NAV_CHAIN',
5254 'USER_ID',
5255 'GROUP_ID',
5256 'ITEMS_COUNT',
5257 'FORUM_ID',
5258 'BLOG_GROUP_ID',
5259 'TASK_FORUM_ID',
5260 'THUMBNAIL_LIST_SIZE',
5261 'DATE_TIME_FORMAT',
5262 'SHOW_YEAR',
5263 'NAME_TEMPLATE',
5264 'SHOW_LOGIN',
5265 'CAN_OWNER_EDIT_DESKTOP',
5266 'CACHE_TYPE',
5267 'CACHE_TIME',
5268 'USE_MAIN_MENU',
5269 'LOG_SUBSCRIBE_ONLY',
5270 'GROUP_PROPERTY',
5271 'GROUP_USE_BAN',
5272 'BLOG_ALLOW_POST_CODE',
5273 'SHOW_RATING',
5274 'LOG_THUMBNAIL_SIZE',
5275 'LOG_COMMENT_THUMBNAIL_SIZE',
5276 'LOG_NEW_TEMPLATE',
5277
5278*/
5279 return (in_array($key, [
5280 'GROUP_ID',
5281 'SET_TITLE',
5282 'PATH_TO_GROUP',
5283 ]));
5284 }, ARRAY_FILTER_USE_KEY);
5285 }
5286
5288 {
5289 return Main\Component\ParameterSigner::signParameters(self::getWorkgroupSliderMenuSignedParametersSalt(), $params);
5290 }
5291
5292
5293 public static function getWorkgroupSliderMenuUnsignedParameters(array $sourceParametersList = [])
5294 {
5295 foreach ($sourceParametersList as $source)
5296 {
5297 if (isset($source['signedParameters']) && is_string($source['signedParameters']))
5298 {
5299 try
5300 {
5301 $componentParameters = ParameterSigner::unsignParameters(
5302 self::getWorkgroupSliderMenuSignedParametersSalt(),
5303 $source['signedParameters']
5304 );
5305 $componentParameters['IFRAME'] = 'Y';
5306 return $componentParameters;
5307 }
5308 catch (BadSignatureException $exception)
5309 {}
5310
5311 return [];
5312 }
5313 }
5314
5315 return [];
5316 }
5317
5318 public static function getWorkgroupSliderMenuSignedParametersSalt(): string
5319 {
5320 return 'bitrix:socialnetwork.group.card.menu';
5321 }
5322
5323 public static function getWorkgroupAvatarToken($fileId = 0): string
5324 {
5325 if ($fileId <= 0)
5326 {
5327 return '';
5328 }
5329
5330 $filePath = \CFile::getPath($fileId);
5331 if ((string)$filePath === '')
5332 {
5333 return '';
5334 }
5335
5336 $signer = new \Bitrix\Main\Security\Sign\Signer;
5337 return $signer->sign(serialize([ $fileId, $filePath ]), 'workgroup_avatar_token');
5338 }
5339
5340 public static function checkEmptyParamInteger(&$params, $paramName, $defaultValue): void
5341 {
5342 $params[$paramName] = (isset($params[$paramName]) && (int)$params[$paramName] > 0 ? (int)$params[$paramName] : $defaultValue);
5343 }
5344
5345 public static function checkEmptyParamString(&$params, $paramName, $defaultValue): void
5346 {
5347 $params[$paramName] = (isset($params[$paramName]) && trim($params[$paramName]) !== '' ? trim($params[$paramName]) : $defaultValue);
5348 }
5349
5351 {
5352 if (ModuleManager::isModuleInstalled('intranet'))
5353 {
5354 $defaultFields = [
5355 'EMAIL',
5356 'PERSONAL_MOBILE',
5357 'WORK_PHONE',
5358 'PERSONAL_ICQ',
5359 'PERSONAL_PHOTO',
5360 'PERSONAL_CITY',
5361 'WORK_COMPANY',
5362 'WORK_POSITION',
5363 ];
5364 $defaultProperties = [
5365 'UF_DEPARTMENT',
5366 'UF_PHONE_INNER',
5367 ];
5368 }
5369 else
5370 {
5371 $defaultFields = [
5372 "PERSONAL_ICQ",
5373 "PERSONAL_BIRTHDAY",
5374 "PERSONAL_PHOTO",
5375 "PERSONAL_CITY",
5376 "WORK_COMPANY",
5377 "WORK_POSITION"
5378 ];
5379 $defaultProperties = [];
5380 }
5381
5382 return [
5383 'SHOW_FIELDS_TOOLTIP' => ($params['SHOW_FIELDS_TOOLTIP'] ?? unserialize(Option::get('socialnetwork', 'tooltip_fields', serialize($defaultFields)), ['allowed_classes' => false])),
5384 'USER_PROPERTY_TOOLTIP' => ($params['USER_PROPERTY_TOOLTIP'] ?? unserialize(Option::get('socialnetwork', 'tooltip_properties', serialize($defaultProperties)), ['allowed_classes' => false])),
5385 ];
5386 }
5387
5388 public static function getWorkgroupPageTitle(array $params = []): string
5389 {
5390 $workgroupName = (string)($params['WORKGROUP_NAME'] ?? '');
5391 $workgroupId = (int)($params['WORKGROUP_ID'] ?? 0);
5392
5393 if (
5394 $workgroupName === ''
5395 && $workgroupId > 0
5396 )
5397 {
5398 $groupFields = \CSocNetGroup::getById($workgroupId, true);
5399 if (!empty($groupFields))
5400 {
5401 $workgroupName = $groupFields['NAME'];
5402 }
5403 }
5404
5405 return Loc::getMessage('SONET_HELPER_PAGE_TITLE_WORKGROUP_TEMPLATE', [
5406 '#WORKGROUP#' => $workgroupName,
5407 '#TITLE#' => ($params['TITLE'] ?? ''),
5408 ]);
5409 }
5410}
$connection
Определения actionsdefinitions.php:38
$type
Определения options.php:106
if($_SERVER $defaultValue['REQUEST_METHOD']==="GET" &&!empty($RestoreDefaults) && $bizprocPerms==="W" &&check_bitrix_sessid())
Определения options.php:32
const BLOG_PUBLISH_STATUS_READY
Определения include.php:46
const BLOG_PERMS_FULL
Определения include.php:10
const BLOG_PUBLISH_STATUS_PUBLISH
Определения include.php:47
$messageFields
Определения callback_ednaru.php:22
if(!Loader::includeModule('messageservice')) $provider
Определения callback_ednaruimhpx.php:21
global $APPLICATION
Определения include.php:80
if(!is_object($USER)||! $USER->IsAuthorized()) $userId
Определения check_mail.php:18
static send($params)
Определения broadcast.php:229
static increment($params=array())
Определения counterpost.php:7
static getById($postId=0, $params=array())
Определения post.php:35
static signParameters($componentName, $parameters)
Определения parametersigner.php:19
Определения event.php:5
static convertRights($rights, $excludeCodes=[])
Определения finderdest.php:171
static merge(array $data)
Определения finderdest.php:99
static getList(array $parameters=array())
Определения datamanager.php:431
static update($primary, array $data)
Определения datamanager.php:1256
static decode($text)
Определения emoji.php:24
static getPostText()
Определения base.php:30
static checkProfileRedirect($userId=0)
Определения componenthelper.php:3546
static getBlogCommentListCount($postId)
Определения componenthelper.php:374
static getSonetGroupAvailable($params=array(), &$limitReached=false)
Определения componenthelper.php:2108
static checkCanCommentInWorkgroup($params)
Определения componenthelper.php:4974
static getWorkgroupSEFUrl($params=[])
Определения componenthelper.php:4092
static getLivefeedRatingData($params=[])
Определения componenthelper.php:4551
static setBlogPostLimitedViewStatus($params=array())
Определения componenthelper.php:3629
static addContextToUrl($url, $context)
Определения componenthelper.php:1984
static getWorkgroupSliderMenuUrlList(array $componentResult=[])
Определения componenthelper.php:5189
static checkEmptyParamString(&$params, $paramName, $defaultValue)
Определения componenthelper.php:5345
static getWorkgroupSliderMenuUnsignedParameters(array $sourceParametersList=[])
Определения componenthelper.php:5293
static convertBlogPostPermToDestinationList($params, &$resultFields)
Определения componenthelper.php:4128
static setComponentOption($list, $params=array())
Определения componenthelper.php:2068
static hasTextInlineImage(string $text='', array $ufData=[])
Определения componenthelper.php:912
static notifyBlogPostCreated($params=array())
Определения componenthelper.php:3926
static getWorkgroupSliderMenuSignedParametersSalt()
Определения componenthelper.php:5318
static getBlogCommentListData($postId, $params, $languageId, &$authorIdList=[])
Определения componenthelper.php:305
static isCurrentUserExtranet($params=[])
Определения componenthelper.php:4781
static getBlogPostCacheDir($params=array())
Определения componenthelper.php:4475
static getAttachmentsData($valueList, $siteId=false)
Определения componenthelper.php:614
static convertSelectorRequestData(array &$postFields=[], array $params=[])
Определения componenthelper.php:5006
static getBlogAuthorData($authorId, $params)
Определения componenthelper.php:244
static checkPredefinedAuthIdList($authIdList=array())
Определения componenthelper.php:2000
static checkBlogPostDestinationList($params, &$resultFields)
Определения componenthelper.php:4245
static getWorkgroupAvatarToken($fileId=0)
Определения componenthelper.php:5323
static addLiveSourceComment(array $params=[])
Определения componenthelper.php:2596
static listWorkgroupSliderMenuSignedParameters(array $componentParameters=[])
Определения componenthelper.php:5205
static checkTooltipComponentParams($params)
Определения componenthelper.php:5350
static getUrlPreviewContent($uf, $params=array())
Определения componenthelper.php:1258
static getAllowToAllDestination($userId=0)
Определения componenthelper.php:3483
static formatDateTimeToGMT($dateTimeSource, $authorId)
Определения componenthelper.php:969
static getSpacesSEFUrl($params=[])
Определения componenthelper.php:4099
static processBlogPostShare($fields, $params)
Определения componenthelper.php:1540
static getUserSonetGroupIdList($userId=false, $siteId=false)
Определения componenthelper.php:3427
static checkEmptyParamInteger(&$params, $paramName, $defaultValue)
Определения componenthelper.php:5340
static getReplyToUrl($url, $userId, $entityType, $entityId, $siteId, $backUrl=null)
Определения componenthelper.php:563
static hasCommentSource($params)
Определения componenthelper.php:1494
static getBlogCommentData($commentId, $languageId)
Определения componenthelper.php:414
static getBlogPostLimitedViewStatus($params=array())
Определения componenthelper.php:3597
static getBlogPostDestinations($postId)
Определения componenthelper.php:164
static getUrlPreviewValue($text, $html=true)
Определения componenthelper.php:1207
static createUserBlog($params)
Определения componenthelper.php:1066
static convertDiskFileBBCode($text, $entityType, $entityId, $authorId, $attachmentList=[])
Определения componenthelper.php:848
static getBlogPostData($postId, $languageId)
Определения componenthelper.php:50
static getUserSEFUrl($params=array())
Определения componenthelper.php:4085
static processBlogPostNewMailUser(&$HTTPPost, &$componentResult)
Определения componenthelper.php:3087
static getExtranetSonetGroupIdList()
Определения componenthelper.php:1437
static addLiveComment($comment=[], $logEntry=[], $commentEvent=[], $params=[])
Определения componenthelper.php:2262
static getWorkgroupSliderMenuSignedParameters(array $params)
Определения componenthelper.php:5287
static canAddComment($logEntry=array(), $commentEvent=array())
Определения componenthelper.php:2183
static userLogSubscribe($params=array())
Определения componenthelper.php:4799
static getSonetBlogGroupIdList($params)
Определения componenthelper.php:999
static fillSelectedUsersToInvite($HTTPPost, $componentParams, &$componentResult)
Определения componenthelper.php:3037
static processBlogPostNewCrmContact(&$HTTPPost, &$componentResult)
Определения componenthelper.php:3295
static isCurrentPageFirst(array $params=[])
Определения componenthelper.php:5148
static getWorkgroupPageTitle(array $params=[])
Определения componenthelper.php:5388
static getLFCommentsParams($eventFields=array())
Определения componenthelper.php:4901
static getBlogPostSocNetPerms($params=array())
Определения componenthelper.php:3840
static processBlogPostNewMailUserDestinations(&$destinationList)
Определения componenthelper.php:3268
static convertMailDiskFileBBCode($text='', $attachmentList=[])
Определения componenthelper.php:789
static init(array $params)
Определения provider.php:279
static getContentId($event=[])
Определения provider.php:958
static set($params=array())
Определения logsubscribe.php:69
static addLiveComment($commentId=0, $arParams=array())
Определения blog_comment.php:910
static getSocNetPerms($ID, $useCache=true)
Определения blog_post.php:1460
static getWorkflowByIntegerId($integerId)
Определения stateservice.php:440
static makePathFromTemplate($template, $arParams=array())
Определения component_engine.php:355
static killAllTags($text)
Определения functions.php:473
global $CACHE_MANAGER
Определения clear_component_cache.php:7
$right
Определения options.php:8
$componentName
Определения component_props2.php:49
if(!is_array($prop["VALUES"])) $tmp
Определения component_props.php:203
$data['IS_AVAILABLE']
Определения .description.php:13
$nameFormat
Определения discount_coupon_list.php:278
</td ></tr ></table ></td ></tr >< tr >< td class="bx-popup-label bx-width30"><?=GetMessage("PAGE_NEW_TAGS")?> array( $site)
Определения file_new.php:804
$res
Определения filter_act.php:7
$perm
Определения options.php:169
global $USER_FIELD_MANAGER
Определения attempt.php:6
$result
Определения get_property_values.php:14
$moduleId
$p
Определения group_list_element_edit.php:23
$componentParams
Определения group_wiki_index.php:20
$activity
Определения options.php:214
if($request->getPost('Update') !==null) elseif( $request->getPost( 'Apply') !==null) elseif($request->getPost('RestoreDefaults') !==null) $backUrl
Определения options.php:66
$select
Определения iblock_catalog_list.php:194
$adminList
Определения iblock_catalog_list.php:44
$filter
Определения iblock_catalog_list.php:54
while($arParentIBlockProperty=$dbParentIBlockProperty->Fetch()) $errorMessage
const IM_MESSAGE_SYSTEM
Определения include.php:21
const IM_NOTIFY_SYSTEM
Определения include.php:38
global $USER
Определения csv_new_run.php:40
$context
Определения csv_new_setup.php:223
if(!is_null($config))($config as $configItem)(! $configItem->isVisible()) $code
Определения options.php:195
const BX_RESIZE_IMAGE_EXACT
Определения constants.php:12
const BX_RESIZE_IMAGE_PROPORTIONAL
Определения constants.php:11
const SITE_DIR(!defined('LANG'))
Определения include.php:72
const FORMAT_DATETIME
Определения include.php:64
$siteId
Определения ajax.php:8
ExecuteModuleEventEx($arEvent, $arParams=[])
Определения tools.php:5214
htmlspecialcharsback($str)
Определения tools.php:2693
htmlspecialcharsEx($str)
Определения tools.php:2685
htmlspecialcharsbx($string, $flags=ENT_COMPAT, $doubleEncode=true)
Определения tools.php:2701
BXClearCache($full=false, $initdir='')
Определения tools.php:5150
check_email($email, $strict=false, $domainCheck=false)
Определения tools.php:4571
MakeTimeStamp($datetime, $format=false)
Определения tools.php:538
LocalRedirect($url, $skip_security_check=false, $status="302 Found")
Определения tools.php:4005
TruncateText($strText, $intLen)
Определения tools.php:2185
$name
Определения menu_edit.php:35
$value
Определения Param.php:39
Определения arrayresult.php:2
Определения collection.php:2
$user
Определения mysql_to_pgsql.php:33
$entityId
Определения payment.php:4
$event
Определения prolog_after.php:141
return false
Определения prolog_main_admin.php:185
if( $daysToExpire >=0 &&$daysToExpire< 60 elseif)( $daysToExpire< 0)
Определения prolog_main_admin.php:393
if(empty($signedUserToken)) $key
Определения quickway.php:257
$text
Определения template_pdf.php:79
$page
Определения order_form.php:33
else $userName
Определения order_form.php:75
</p ></td >< td valign=top style='border-top:none;border-left:none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;padding:0cm 2.0pt 0cm 2.0pt;height:9.0pt'>< p class=Normal align=center style='margin:0cm;margin-bottom:.0001pt;text-align:center;line-height:normal'>< a name=ТекстовоеПоле54 ></a ><?=($taxRate > count( $arTaxList) > 0) ? $taxRate."%"
Определения waybill.php:936
$comment
Определения template.php:15
if($inWords) echo htmlspecialcharsbx(Number2Word_Rus(roundEx($totalVatSum $params['CURRENCY']
Определения template.php:799
else $a
Определения template.php:137
$post
Определения template.php:8
$title
Определения pdf.php:123
$val
Определения options.php:1793
$optionValue
Определения options.php:3512
$matches
Определения index.php:22
const SONET_ENTITY_GROUP
Определения include.php:117
const SONET_ENTITY_USER
Определения include.php:118
const SONET_RELATIONS_TYPE_ALL
Определения include.php:38
const SITE_ID
Определения sonet_set_content_view.php:12
$k
Определения template_pdf.php:567
$action
Определения file_dialog.php:21
$rights
Определения options.php:4
$url
Определения iframe.php:7
$site
Определения yandex_run.php:614
$fields
Определения yandex_run.php:501