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