Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
message.php
1<?php
2namespace Bitrix\Forum;
3
21
22Loc::loadMessages(__FILE__);
23
75class MessageTable extends Main\Entity\DataManager
76{
77 const SOURCE_ID_EMAIL = "EMAIL";
78 const SOURCE_ID_WEB = "WEB";
79 const SOURCE_ID_MOBILE = "MOBILE";
80
86 public static function getTableName()
87 {
88 return 'b_forum_message';
89 }
90
91 public static function getUfId()
92 {
93 return 'FORUM_MESSAGE';
94 }
95
96 private static $post_message_hash = [];
97 private static $messageById = [];
98
104 public static function getMap()
105 {
106 return array(
107 (new IntegerField("ID", ["primary" => true, "autocomplete" => true])),
108 (new IntegerField("FORUM_ID", ["required" => true])),
109 (new IntegerField("TOPIC_ID", ["required" => true])),
110 (new BooleanField("USE_SMILES", ["values" => ["N", "Y"], "default_value" => "Y"])),
111 (new BooleanField("NEW_TOPIC", ["values" => ["N", "Y"], "default_value" => "N"])),
112 (new BooleanField("APPROVED", ["values" => ["N", "Y"], "default_value" => "Y"])),
113 (new BooleanField("SOURCE_ID", ["values" => [self::SOURCE_ID_EMAIL, self::SOURCE_ID_WEB, self::SOURCE_ID_MOBILE], "default_value" => self::SOURCE_ID_WEB])),
114 (new DatetimeField("POST_DATE", ["required" => true, "default_value" => function(){ return new DateTime();}])),
115 (new TextField("POST_MESSAGE", ["required" => true])),
116 (new TextField("POST_MESSAGE_HTML")),
117 (new TextField("POST_MESSAGE_FILTER")),
118 (new StringField("POST_MESSAGE_CHECK", ["size" => 32])),
119 (new IntegerField("ATTACH_IMG")),
120 (new StringField("PARAM1", ["size" => 2])),
121 (new IntegerField("PARAM2")),
122
123 (new IntegerField("AUTHOR_ID")),
124 (new StringField("AUTHOR_NAME", ["required" => true, "size" => 255])),
125 (new StringField("AUTHOR_EMAIL", ["size" => 255])),
126 (new StringField("AUTHOR_IP", ["size" => 255])),
127 (new StringField("AUTHOR_REAL_IP", ["size" => 255])),
128 (new IntegerField("GUEST_ID")),
129
130 (new IntegerField("EDITOR_ID")),
131 (new StringField("EDITOR_NAME", ["size" => 255])),
132 (new StringField("EDITOR_EMAIL", ["size" => 255])),
133 (new TextField("EDIT_REASON")),
134 (new DatetimeField("EDIT_DATE")),
135
136 (new StringField("XML_ID", ["size" => 255])),
137
138 (new TextField("HTML")),
139 (new TextField("MAIL_HEADER")),
140 (new IntegerField("SERVICE_TYPE")),
141 (new TextField("SERVICE_DATA")),
142
143 (new Reference("TOPIC", TopicTable::class, Join::on("this.TOPIC_ID", "ref.ID"))),
144 (new Reference("FORUM_USER", UserTable::class, Join::on("this.AUTHOR_ID", "ref.USER_ID"))),
145 (new Reference("FORUM_USER_TOPIC", UserTopicTable::class, Join::on("this.TOPIC_ID", "ref.TOPIC_ID"))),
146 (new Reference("USER", Main\UserTable::class, Join::on("this.AUTHOR_ID", "ref.ID")))
147 );
148 }
149
150 public static function getFilteredFields()
151 {
152 return [
153 "AUTHOR_NAME",
154 "AUTHOR_EMAIL",
155 "EDITOR_NAME",
156 "EDITOR_EMAIL",
157 "EDIT_REASON"
158 ];
159 }
160
161 private static function modifyMessageFields(array &$data)
162 {
163 unset($data["UPLOAD_DIR"]);
164 if (array_key_exists("USE_SMILES", $data))
165 {
166 $data["USE_SMILES"] = $data["USE_SMILES"] === "N" ? "N" : "Y";
167 }
168 if (array_key_exists("NEW_TOPIC", $data))
169 {
170 $data["NEW_TOPIC"] = $data["NEW_TOPIC"] === "Y" ? "Y" : "N";
171 }
172 if (array_key_exists("APPROVED", $data))
173 {
175 }
176 if (array_key_exists("SOURCE_ID", $data))
177 {
178 $data["SOURCE_ID"] = self::filterSourceIdParam($data['SOURCE_ID']);
179 }
180 }
181
182 public static function filterSourceIdParam(string $sourceId): string
183 {
184 if (in_array($sourceId, [self::SOURCE_ID_WEB, self::SOURCE_ID_MOBILE, self::SOURCE_ID_EMAIL], true))
185 {
186 return $sourceId;
187 }
188 return self::SOURCE_ID_WEB;
189 }
190
191 public static function onBeforeAdd(Event $event)
192 {
193 $result = new Main\ORM\EventResult();
195 $data = $event->getParameter("fields");
196 $strUploadDir = array_key_exists("UPLOAD_DIR", $data) ? $data["UPLOAD_DIR"] : "forum";
197 self::modifyMessageFields($data);
198 //region Files
199 if (array_key_exists("ATTACH_IMG", $data) && !empty($data["ATTACH_IMG"]))
200 {
201 if (!array_key_exists("FILES", $data))
202 {
203 $data["FILES"] = [];
204 }
205 $data["FILES"][] = $data["ATTACH_IMG"];
206 unset($data["ATTACH_IMG"]);
207 }
208 if (array_key_exists("FILES", $data))
209 {
210 $data["FILES"] = is_array($data["FILES"]) ? $data["FILES"] : [$data["FILES"]];
211 if (!empty($data["FILES"]))
212 {
213 $res = File::checkFiles(
214 Forum\Forum::getById($data["FORUM_ID"]),
215 $data["FILES"],
216 [
217 "FORUM_ID" => $data["FORUM_ID"],
218 "TOPIC_ID" => ($data["NEW_TOPIC"] === "Y" ? 0 : $data["TOPIC_ID"]),
219 "MESSAGE_ID" => 0,
220 "USER_ID" => $data["AUTHOR_ID"]
221 ]
222 );
223 if (!$res->isSuccess())
224 {
225 $result->setErrors($res->getErrors());
226 }
227 else
228 {
229 /*@var Main\ORM\Objectify\EntityObject $object*/
230 $object = $event->getParameter("object");
231 /*@var Main\Dictionary $object->customData*/
232 $object->sysSetRuntime("FILES", $data["FILES"]);
233 $object->sysSetRuntime("UPLOAD_DIR", $strUploadDir);
234 }
235 }
236 unset($data["FILES"]);
237 }
238 //endregion
239
240 $data["POST_MESSAGE_CHECK"] = md5($data["POST_MESSAGE"] . (array_key_exists("FILES", $data) ? serialize($data["FILES"]) : ""));
241
242 //region Deduplication
243 $forum = Forum\Forum::getById($data["FORUM_ID"]);
244 $deduplication = null;
245 if (array_key_exists("AUX", $data))
246 {
247 if ($data["AUX"] == "Y")
248 {
249 $deduplication = false;
250 }
251 unset($data["AUX"]);
252 }
253 if (array_key_exists("DEDUPLICATION", $data))
254 {
255 $deduplication = $data["DEDUPLICATION"] == "Y";
256 unset($data["DEDUPLICATION"]);
257 }
258 if ($deduplication === null)
259 {
260 $deduplication = $forum["DEDUPLICATION"] === "Y";
261 }
262 if ($deduplication && $data["NEW_TOPIC"] !== "Y")
263 {
264 if (self::getLastMessageHashInTopic($data["TOPIC_ID"]) === $data["POST_MESSAGE_CHECK"])
265 {
266 $result->addError(new EntityError(Loc::getmessage("F_ERR_MESSAGE_ALREADY_EXISTS"), "onBeforeMessageAdd"));
267 return $result;
268 }
269 }
270 //endregion
271
272 $data["POST_MESSAGE"] = Main\Text\Emoji::encode($data["POST_MESSAGE"]);
273
274 //region Filter
275 if (Main\Config\Option::get("forum", "FILTER", "Y") == "Y")
276 {
277 $data["POST_MESSAGE_FILTER"] = \CFilterUnquotableWords::Filter($data["POST_MESSAGE"]);
278 $filteredFields = self::getFilteredFields();
279 $res = [];
280 foreach ($filteredFields as $key)
281 {
282 $res[$key] = array_key_exists($key, $data) ? $data[$key] : "";
283 if (!empty($res[$key]))
284 {
285 $res[$key] = \CFilterUnquotableWords::Filter($res[$key]);
286 if ($res[$key] == '')
287 {
288 $res[$key] = "*";
289 }
290 }
291 }
292 $data["HTML"] = serialize($res);
293 }
294 //endregion
295
296 $fields = $event->getParameter("fields");
297 if ($data != $fields)
298 {
299 foreach ($fields as $key => $val)
300 {
301 if (!array_key_exists($key, $data))
302 {
303 $result->unsetField($key);
304 }
305 else if ($data[$key] == $val)
306 {
307 unset($data[$key]);
308 }
309 }
310 $result->modifyFields($data);
311 }
312 return $result;
313 }
314
319 public static function onAdd(Main\ORM\Event $event)
320 {
321 $result = new Main\ORM\EventResult();
322 if (Main\Config\Option::get("forum", "MESSAGE_HTML", "N") == "Y")
323 {
324 $fields = $event->getParameter("fields");
325 $object = $event->getParameter("object");
326
327 if ($files = $object->sysGetRuntime("FILES"))
328 {
330 $files,
331 [
332 "FORUM_ID" => $fields["FORUM_ID"],
333 "TOPIC_ID" => $fields["TOPIC_ID"],
334 "MESSAGE_ID" => 0,
335 "USER_ID" => $fields["AUTHOR_ID"],
336 ],
337 ($object->sysGetRuntime("UPLOAD_DIR") ?: "forum/upload"));
338 $object->sysSetRuntime("FILES", $files);
339 }
340
341 $parser = new \forumTextParser(LANGUAGE_ID);
342 $allow = \forumTextParser::GetFeatures(\Bitrix\Forum\Forum::getById($fields["FORUM_ID"]));
343 $allow["SMILES"] = ($fields["USE_SMILES"] != "Y" ? "N" : $allow["SMILES"]);
344 $result->modifyFields([
345 "POST_MESSAGE_HTML" => $parser->convert($fields["POST_MESSAGE_FILTER"] ?: $fields["POST_MESSAGE"], $allow, "html", $files)
346 ]);
347 }
348 return $result;
349 }
350
351
356 public static function onAfterAdd(Main\ORM\Event $event)
357 {
358 $object = $event->getParameter("object");
359
360 if ($files = $object->sysGetRuntime("FILES"))
361 {
362 $id = $event->getParameter("id");
363 $id = is_array($id) && array_key_exists("ID", $id) ? $id["ID"] : $id;
364 $fields = $event->getParameter("fields");
366 $files,
367 [
368 "FORUM_ID" => $fields["FORUM_ID"],
369 "TOPIC_ID" => $fields["TOPIC_ID"],
370 "MESSAGE_ID" => $id,
371 "USER_ID" => $fields["AUTHOR_ID"],
372 ],
373 ($object->sysGetRuntime("UPLOAD_DIR") ?: "forum/upload"));
374 }
375 }
376
377 public static function getDataById($id, $ttl = 84600)
378 {
379 if (!array_key_exists($id, self::$messageById))
380 {
381 self::$messageById[$id] = self::getList([
382 "select" => ["*"],
383 "filter" => ["ID" => $id],
384 "cache" => [
385 "ttl" => $ttl
386 ]
387 ])->fetch();
388 }
389 return self::$messageById[$id];
390 }
391
397 public static function onBeforeUpdate(Main\ORM\Event $event)
398 {
399 $result = new Main\ORM\EventResult();
401 $data = $event->getParameter("fields");
402 $id = $event->getParameter("id");
403 $id = $id["ID"];
404 $strUploadDir = array_key_exists("UPLOAD_DIR", $data) ? $data["UPLOAD_DIR"] : "forum";
405 self::modifyMessageFields($data);
406 if (Main\Config\Option::get("forum", "FILTER", "Y") == "Y" &&
407 !empty(array_intersect(self::getFilteredFields(), array_keys($data))))
408 {
409 $forFilter = $data;
410 if (
411 array_intersect(self::getFilteredFields(), array_keys($data)) !== self::getFilteredFields() &&
412 ($message = MessageTable::getDataById($id))
413 )
414 {
415 $forFilter = array_merge($message, $forFilter);
416 }
417 $res = [];
418 foreach (self::getFilteredFields() as $key)
419 {
420 $res[$key] = array_key_exists($key, $forFilter) ? $forFilter[$key] : "";
421 if (!empty($res[$key]))
422 {
423 $res[$key] = \CFilterUnquotableWords::Filter($res[$key]);
424 if ($res[$key] == '' )
425 {
426 $res[$key] = "*";
427 }
428 }
429 }
430 $data["HTML"] = serialize($res);
431 }
432 if (array_key_exists("POST_MESSAGE", $data))
433 {
434 $data["POST_MESSAGE"] = Main\Text\Emoji::encode($data["POST_MESSAGE"]);
435 if (Main\Config\Option::get("forum", "FILTER", "Y") == "Y")
436 {
437 $data["POST_MESSAGE_FILTER"] = \CFilterUnquotableWords::Filter($data["POST_MESSAGE"]);
438 }
439 }
440 unset($data["AUX"]);
441 unset($data["DEDUPLICATION"]);
442
443 //region Files
444 if (array_key_exists("ATTACH_IMG", $data) && !empty($data["ATTACH_IMG"]))
445 {
446 if (!array_key_exists("FILES", $data))
447 {
448 $data["FILES"] = [];
449 }
450 $data["FILES"][] = $data["ATTACH_IMG"];
451 unset($data["ATTACH_IMG"]);
452 }
453 if (array_key_exists("FILES", $data))
454 {
455 $data["FILES"] = is_array($data["FILES"]) ? $data["FILES"] : [$data["FILES"]];
456 if (!empty($data["FILES"]))
457 {
458 $fileFields = $data + MessageTable::getDataById($id);
459 $res = Forum\File::checkFiles(
460 Forum\Forum::getById($fileFields["FORUM_ID"]),
461 $data["FILES"],
462 [
463 "FORUM_ID" => $fileFields["FORUM_ID"],
464 "TOPIC_ID" => $fileFields["TOPIC_ID"],
465 "MESSAGE_ID" => $id,
466 "USER_ID" => $fileFields["AUTHOR_ID"]
467 ]
468 );
469 if (!$res->isSuccess())
470 {
471 $result->setErrors($res->getErrors());
472 }
473 else
474 {
475 /*@var Main\ORM\Objectify\EntityObject $object*/
476 $object = $event->getParameter("object");
477 /*@var Main\Dictionary $object->customData*/
478 $object->sysSetRuntime("FILES", $data["FILES"]);
479 $object->sysSetRuntime("UPLOAD_DIR", $strUploadDir);
480 $object->sysSetRuntime("FILE_FIELDS", $fileFields);
481 }
482 }
483 unset($data["FILES"]);
484 }
485 //endregion
486 $fields = $event->getParameter("fields");
487 if ($data != $fields)
488 {
489 foreach ($fields as $key => $val)
490 {
491 if (!array_key_exists($key, $data))
492 {
493 $result->unsetField($key);
494 }
495 else if ($data[$key] == $val)
496 {
497 unset($data[$key]);
498 }
499 }
500 $result->modifyFields($data);
501 }
502 return $result;
503 }
508 public static function onUpdate(Main\ORM\Event $event)
509 {
510 $id = $event->getParameter("id");
511 $id = $id["ID"];
512 $message = self::getDataById($id);
513
514 $fields = $event->getParameter("fields") + $message;
515 $object = $event->getParameter("object");
516
517 if ($files = $object->sysGetRuntime("FILES"))
518 {
520 $files,
521 [
522 "FORUM_ID" => $fields["FORUM_ID"],
523 "TOPIC_ID" => $fields["TOPIC_ID"],
524 "MESSAGE_ID" => $id,
525 "USER_ID" => $fields["AUTHOR_ID"],
526 ],
527 ($object->sysGetRuntime("UPLOAD_DIR") ?: "forum/upload"));
528 }
529 if (Main\Config\Option::get("forum", "MESSAGE_HTML", "N") == "Y")
530 {
531 $result = new Main\ORM\EventResult();
532 $parser = new \forumTextParser(LANGUAGE_ID);
533 $allow = \forumTextParser::GetFeatures(\Bitrix\Forum\Forum::getById($fields["FORUM_ID"]));
534 $allow["SMILES"] = ($fields["USE_SMILES"] != "Y" ? "N" : $allow["SMILES"]);
535 $result->modifyFields([
536 "POST_MESSAGE_HTML" => $parser->convert($fields["POST_MESSAGE_FILTER"] ?: $fields["POST_MESSAGE"], $allow, "html", $files)
537 ]);
538 return $result;
539 }
540 }
541
546 public static function onAfterUpdate(Main\ORM\Event $event)
547 {
548 $id = $event->getParameter("id");
549 $id = $id["ID"];
550 unset(self::$messageById[$id]);
551 }
559 public static function checkFields(Result $result, $primary, array $data)
560 {
561 parent::checkFields($result, $primary, $data);
562 if ($result->isSuccess())
563 {
564 try
565 {
566 if (array_key_exists("FORUM_ID", $data) && ForumTable::getMainData($data["FORUM_ID"]) === null)
567 {
568 throw new Main\ObjectNotFoundException(Loc::getMessage("F_ERR_INVALID_FORUM_ID"));
569 }
570 if (array_key_exists("TOPIC_ID", $data))
571 {
572 if (!($topic = TopicTable::getById($data["TOPIC_ID"])->fetch()))
573 {
574 throw new Main\ObjectNotFoundException(Loc::getMessage("F_ERR_TOPIC_IS_NOT_EXISTS"));
575 }
576 if ($topic["STATE"] == Topic::STATE_LINK)
577 {
578 throw new Main\ObjectPropertyException(Loc::getMessage("F_ERR_TOPIC_IS_LINK"));
579 }
580 }
581 }
582 catch (\Exception $e)
583 {
584 $result->addError(new Error(
585 $e->getMessage()
586 ));
587 }
588 }
589 }
590
591 private static function getLastMessageHashInTopic(int $topicId): ?string
592 {
593 $res = MessageTable::query()
594 ->setSelect(['ID', 'POST_MESSAGE_CHECK'])
595 ->where('TOPIC_ID', '=', $topicId)
596 ->where('APPROVED', '=', 'Y')
597 ->setOrder(['ID' => 'DESC'])
598 ->setLimit(1)
599 ->exec()
600 ->fetch()
601 ;
602 return $res ? $res['POST_MESSAGE_CHECK'] : null;
603 }
604}
605
607{
608 use Forum\Internals\EntityFabric;
609
610 public const APPROVED_APPROVED = "Y";
611 public const APPROVED_DISAPPROVED = "N";
612
613 protected function init()
614 {
615 if (!($this->data = MessageTable::getById($this->id)->fetch()))
616 {
617 throw new Main\ObjectNotFoundException("Message with id {$this->id} is not found.");
618 }
619 $this->authorId = intval($this->data["AUTHOR_ID"]);
620 }
621
622 public function edit(array $fields)
623 {
624 $result = self::update($this->getId(), $fields);
625
626 if ($result->isSuccess() )
627 {
628 $this->data = MessageTable::getById($result->getId())->fetch();
629
630 Forum\Integration\Search\Message::index(
632 Forum\Topic::getById($this->data["TOPIC_ID"]),
633 $this->data
634 );
635 }
636
637 return $result;
638 }
639
640 public function remove(): Main\ORM\Data\DeleteResult
641 {
642 $result = self::delete($this->getId());
643
644 if ($result->isSuccess())
645 {
646 if ($topic = Forum\Topic::getById($this->data['TOPIC_ID']))
647 {
648 $decrementStatisticResult = $topic->decrementStatistic($this->data);
649 if ($this->data['NEW_TOPIC'] === 'Y' && $decrementStatisticResult->getData())
650 {
651 if (!($newFirstMessage = $decrementStatisticResult->getData()) || empty($newFirstMessage))
652 {
653 $newFirstMessage = MessageTable::getList([
654 'select' => ['*'],
655 'filter' => ['TOPIC_ID' => $this->getId()],
656 'order' => ['ID' => 'ASC'],
657 'limit' => 1
658 ])->fetch();
659 }
660 Forum\Integration\Search\Message::index(
661 Forum\Forum::getById($topic->getForumId()),
662 $topic,
663 $newFirstMessage
664 );
665 }
666 }
667
668 if ($forum = Forum\Forum::getById($this->getForumId()))
669 {
670 $forum->decrementStatistic($this->data);
671 }
672
673 Forum\Integration\Search\Message::deleteIndex($this->data);
674
675 if ($this->data['AUTHOR_ID'] > 0 && ($author = User::getById($this->data['AUTHOR_ID'])))
676 {
677 $author->decrementStatistic($this->data);
678 }
679 }
680
681 return $result;
682 }
683
688 public static function create($parentObject, array $fields)
689 {
690 $topic = Forum\Topic::getInstance($parentObject);
691 $result = self::add($topic, $fields);
692 if (!$result->isSuccess() )
693 {
694 return $result;
695 }
696
697 $message = MessageTable::getDataById($result->getId());
698 $forum = Forum\Forum::getById($topic->getForumId());
699 //region Update statistic & Seacrh
700 User::getById($message["AUTHOR_ID"])->incrementStatistic($message);
701 $topic->incrementStatistic($message);
702 $forum->incrementStatistic($message);
703 Forum\Integration\Search\Message::index($forum, $topic, $message);
704 //endregion
705
706 return $result;
707 }
708
709 public static function update($id, array &$fields)
710 {
711 $result = new Main\ORM\Data\UpdateResult();
712 $result->setPrimary(["ID" => $id]);
713 $data = [];
714 $temporaryFields = ['AUX', 'AUX_DATA'];
715
716 foreach (array_merge([
717 "USE_SMILES",
718 "POST_MESSAGE",
719 "ATTACH_IMG",
720 "FILES",
721 "AUTHOR_NAME",
722 "AUTHOR_EMAIL",
723 "EDITOR_ID",
724 "EDITOR_NAME",
725 "EDITOR_EMAIL",
726 "EDIT_REASON",
727 "EDIT_DATE",
728 'SERVICE_TYPE',
729 'SERVICE_DATA',
730 'SOURCE_ID',
731 'PARAM1',
732 'PARAM2',
733 'XML_ID',
734 ], $temporaryFields) as $field)
735 {
736 if (array_key_exists($field, $fields))
737 {
738 $data[$field] = $fields[$field];
739 }
740 }
741 if (!empty(array_diff_key($fields, $data)))
742 {
743 global $USER_FIELD_MANAGER;
744 $data += array_intersect_key($fields, $USER_FIELD_MANAGER->getUserFields(MessageTable::getUfId()));
745 }
746
747 if (($events = GetModuleEvents("forum", "onBeforeMessageUpdate", true)) && !empty($events))
748 {
749 $strUploadDir = "forum";
750 global $APPLICATION;
751 foreach ($events as $ev)
752 {
753 $APPLICATION->ResetException();
754 if (ExecuteModuleEventEx($ev, array($id, &$data, &$strUploadDir)) === false)
755 {
756 $errorMessage = Loc::getMessage("FORUM_EVENT_BEFOREUPDATE_ERROR");
757 if (($ex = $APPLICATION->GetException()) && ($ex instanceof \CApplicationException))
758 {
759 $errorMessage = $ex->getString();
760 }
761
762 $result->addError(new Main\Error($errorMessage, "onBeforeMessageUpdate"));
763 return $result;
764 }
765 }
766 $data["UPLOAD_DIR"] = $strUploadDir;
767 }
768
769 foreach ($temporaryFields as $field)
770 {
771 unset($data[$field]);
772 }
773
774 if (isset($fields['EDITOR_ID']))
775 {
776 $authContext = new Main\Authentication\Context();
777 $authContext->setUserId($fields['EDITOR_ID']);
778 $data = [
779 'fields' => $data,
780 'auth_context' => $authContext
781 ];
782 }
783
784 $dbResult = MessageTable::update($id, $data);
785
786 if (!$dbResult->isSuccess())
787 {
788 $result->addErrors($dbResult->getErrors());
789 }
790 else
791 {
792 $message = MessageTable::getDataById($id);
793 foreach (GetModuleEvents("forum", "onAfterMessageUpdate", true) as $event)
794 {
795 ExecuteModuleEventEx($event, [$id, $data, $message]);
796 }
797 }
798 return $result;
799 }
804 public static function add(Forum\Topic $topic, array $fields): Main\ORM\Data\AddResult
805 {
806 $data = [
807 "FORUM_ID" => $topic->getForumId(),
808 "TOPIC_ID" => $topic->getId(),
809
810 "USE_SMILES" => $fields["USE_SMILES"],
811 "NEW_TOPIC" => (isset($fields["NEW_TOPIC"]) && $fields["NEW_TOPIC"] === "Y" ? "Y" : "N"),
812 "APPROVED" => $topic["APPROVED"] === Topic::APPROVED_DISAPPROVED || $fields["APPROVED"] === Message::APPROVED_DISAPPROVED ? Message::APPROVED_DISAPPROVED : Message::APPROVED_APPROVED,
813
814 "POST_DATE" => $fields["POST_DATE"] ?: new Main\Type\DateTime(),
815 "POST_MESSAGE" => $fields["POST_MESSAGE"],
816 "ATTACH_IMG" => $fields["ATTACH_IMG"] ?? null,
817 "FILES" => $fields["FILES"] ?? [],
818
819 "AUTHOR_ID" => $fields["AUTHOR_ID"],
820 "AUTHOR_NAME" => $fields["AUTHOR_NAME"],
821 "AUTHOR_EMAIL" => $fields["AUTHOR_EMAIL"],
822 "AUTHOR_IP" => $fields["AUTHOR_IP"] ?? null,
823 "AUTHOR_REAL_IP" => $fields["AUTHOR_REAL_IP"] ?? null,
824 "GUEST_ID" => $fields["GUEST_ID"] ?? null,
825 ];
826
827 if (!empty(array_diff_key($fields, $data)))
828 {
829 global $USER_FIELD_MANAGER;
830 $data += array_intersect_key($fields, $USER_FIELD_MANAGER->getUserFields(MessageTable::getUfId()));
831 }
832
833 $temporaryFields = ['AUX', 'AUX_DATA'];
834 $additionalFields = array_merge(['SERVICE_TYPE', 'SERVICE_DATA', 'SOURCE_ID', 'PARAM1', 'PARAM2', 'XML_ID'], $temporaryFields);
835 foreach ($additionalFields as $key)
836 {
837 if (array_key_exists($key, $fields))
838 {
839 $data[$key] = $fields[$key];
840 }
841 }
842
843 $result = new Main\ORM\Data\AddResult();
844
845 if (($events = GetModuleEvents("forum", "onBeforeMessageAdd", true)) && !empty($events))
846 {
847 $strUploadDir = "forum";
848 global $APPLICATION;
849
850 foreach ($events as $ev)
851 {
852 $APPLICATION->ResetException();
853 if (ExecuteModuleEventEx($ev, array(&$data, &$strUploadDir)) === false)
854 {
855 $errorMessage = Loc::getMessage("FORUM_EVENT_BEFOREADD_ERROR");
856 if (($ex = $APPLICATION->GetException()) && ($ex instanceof \CApplicationException))
857 {
858 $errorMessage = $ex->getString();
859 }
860
861 $result->addError(new Main\Error($errorMessage, "onBeforeMessageAdd"));
862 return $result;
863 }
864 }
865 $data["UPLOAD_DIR"] = $strUploadDir;
866 }
867
868 foreach ($temporaryFields as $field)
869 {
870 unset($data[$field]);
871 }
872
873 $authContext = new Main\Authentication\Context();
874 $authContext->setUserId($fields['AUTHOR_ID']);
875
876 $dbResult = MessageTable::add([
877 "fields" => $data,
878 "auth_context" => $authContext
879 ]);
880
881 if (!$dbResult->isSuccess())
882 {
883 $result->addErrors($dbResult->getErrors());
884 }
885 else
886 {
887 $id = $dbResult->getId();
888 $result->setId($dbResult->getId());
889
890 $message = MessageTable::getDataById($id);
891 $forum = Forum\Forum::getById($topic->getForumId());
892 foreach (GetModuleEvents("forum", "onAfterMessageAdd", true) as $event)
893 {
894 ExecuteModuleEventEx($event, [$id, $message, $topic, $forum, $data]);
895 }
896 }
897 return $result;
898 }
899
900 public static function delete(int $id): Main\ORM\Data\DeleteResult
901 {
902 $result = new Main\ORM\Data\DeleteResult();
903
904 if (!($message = MessageTable::getDataById($id)))
905 {
906 $result->addError(new Main\Error( Loc::getMessage("FORUM_MESSAGE_HAS_NOT_BEEN_FOUND")));
907 return $result;
908 }
909
910 global $APPLICATION, $USER_FIELD_MANAGER;
911 if (($events = GetModuleEvents("forum", "onBeforeMessageDelete", true))
912 && !empty($events))
913 {
914 foreach ($events as $ev)
915 {
916 $APPLICATION->ResetException();
917 if (ExecuteModuleEventEx($ev, [$id, $message]) === false)
918 {
919 $errorMessage = Loc::getMessage("FORUM_EVENT_BEFOREDELETE_ERROR");
920 if (($ex = $APPLICATION->GetException()) && ($ex instanceof \CApplicationException))
921 {
922 $errorMessage = $ex->getString();
923 }
924
925 $result->addError(new Main\Error($errorMessage, "onBeforeMessageDelete"));
926 break;
927 }
928 }
929 }
930
931 if ($result->isSuccess())
932 {
933 if ($message['PARAM1'] == 'VT' && $message['PARAM2'] > 0
934 && IsModuleInstalled('vote') && Main\Loader::includeModule('vote'))
935 {
936 \CVote::Delete($message['PARAM2']);
937 }
938 $USER_FIELD_MANAGER->Delete("FORUM_MESSAGE", $id);
939 FileTable::deleteBatch(['MESSAGE_ID' => $id]);
940 MessageTable::delete($id);
941
942 if (!($nextMessage = MessageTable::getList([
943 'select' => ['ID'],
944 'filter' => [
945 'TOPIC_ID' => $message['TOPIC_ID'],
946 ],
947 'order' => ['ID' => 'ASC'],
948 'limit' => 1
949 ])->fetch()))
950 {
951 Topic::delete($message['TOPIC_ID']);
952 }
953 else if ($message['NEW_TOPIC'] === 'Y')
954 {
955 MessageTable::update($nextMessage['ID'], ['NEW_TOPIC' => 'Y']);
956 }
957 /***************** Event onBeforeMessageAdd ************************/
958 foreach (GetModuleEvents("forum", "onAfterMessageDelete", true) as $event)
959 {
960 ExecuteModuleEventEx($event, [$id, $message]);
961 }
962 /***************** /Event ******************************************/
963 }
964 return $result;
965 }
966}
static checkFiles(Forum $forum, &$files, $params=["TOPIC_ID"=> 0, "MESSAGE_ID"=> 0, "USER_ID"=> 0])
Definition file.php:111
static saveFiles(&$files, $params, $uploadDir="forum/upload")
Definition file.php:197
static deleteBatch(array $filter)
Definition file.php:89
static getMainData(int $forumId, ?string $siteId=null)
Definition forum.php:197
edit(array $fields)
Definition message.php:622
static delete(int $id)
Definition message.php:900
static add(Forum\Topic $topic, array $fields)
Definition message.php:804
static update($id, array &$fields)
Definition message.php:709
static create($parentObject, array $fields)
Definition message.php:688
static onAfterUpdate(Main\ORM\Event $event)
Definition message.php:546
static onAdd(Main\ORM\Event $event)
Definition message.php:319
static filterSourceIdParam(string $sourceId)
Definition message.php:182
static getDataById($id, $ttl=84600)
Definition message.php:377
static checkFields(Result $result, $primary, array $data)
Definition message.php:559
static onUpdate(Main\ORM\Event $event)
Definition message.php:508
static onAfterAdd(Main\ORM\Event $event)
Definition message.php:356
const APPROVED_DISAPPROVED
Definition topic.php:276
static delete(int $id)
Definition topic.php:727
getParameter($key)
Definition event.php:80
static loadMessages($file)
Definition loc.php:64
static getMessage($code, $replace=null, $language=null)
Definition loc.php:29
isSuccess($internalCall=false)
Definition result.php:52
addError(Error $error)
Definition result.php:50