4 * @file src/Model/Item.php
7 namespace Friendica\Model;
9 use Friendica\BaseObject;
10 use Friendica\Content\Text\BBCode;
11 use Friendica\Content\Text\HTML;
12 use Friendica\Core\Config;
13 use Friendica\Core\Hook;
14 use Friendica\Core\Lock;
15 use Friendica\Core\Logger;
16 use Friendica\Core\L10n;
17 use Friendica\Core\PConfig;
18 use Friendica\Core\Protocol;
19 use Friendica\Core\Renderer;
20 use Friendica\Core\System;
21 use Friendica\Core\Worker;
22 use Friendica\Database\DBA;
23 use Friendica\Model\Contact;
24 use Friendica\Model\Event;
25 use Friendica\Model\FileTag;
26 use Friendica\Model\PermissionSet;
27 use Friendica\Model\Term;
28 use Friendica\Model\ItemURI;
29 use Friendica\Model\Photo;
30 use Friendica\Model\Attach;
31 use Friendica\Object\Image;
32 use Friendica\Protocol\Diaspora;
33 use Friendica\Protocol\OStatus;
34 use Friendica\Util\DateTimeFormat;
35 use Friendica\Util\Map;
36 use Friendica\Util\XML;
37 use Friendica\Util\Security;
38 use Friendica\Util\Strings;
39 use Text_LanguageDetect;
41 class Item extends BaseObject
43 // Posting types, inspired by https://www.w3.org/TR/activitystreams-vocabulary/#object-types
50 const PT_DOCUMENT = 19;
52 const PT_PERSONAL_NOTE = 128;
54 // Field list that is used to display the items
55 const DISPLAY_FIELDLIST = [
56 'uid', 'id', 'parent', 'uri', 'thr-parent', 'parent-uri', 'guid', 'network',
57 'commented', 'created', 'edited', 'received', 'verb', 'object-type', 'postopts', 'plink',
58 'wall', 'private', 'starred', 'origin', 'title', 'body', 'file', 'attach', 'language',
59 'content-warning', 'location', 'coord', 'app', 'rendered-hash', 'rendered-html', 'object',
60 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'item_id',
61 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
62 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'owner-network',
63 'contact-id', 'contact-link', 'contact-name', 'contact-avatar',
64 'writable', 'self', 'cid', 'alias',
65 'event-id', 'event-created', 'event-edited', 'event-start', 'event-finish',
66 'event-summary', 'event-desc', 'event-location', 'event-type',
67 'event-nofinish', 'event-adjust', 'event-ignore', 'event-id',
68 'delivery_queue_count', 'delivery_queue_done'
71 // Field list that is used to deliver items via the protocols
72 const DELIVER_FIELDLIST = ['uid', 'id', 'parent', 'uri', 'thr-parent', 'parent-uri', 'guid',
73 'created', 'edited', 'verb', 'object-type', 'object', 'target',
74 'private', 'title', 'body', 'location', 'coord', 'app',
75 'attach', 'tag', 'deleted', 'extid', 'post-type',
76 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
77 'author-id', 'author-link', 'owner-link', 'contact-uid',
78 'signed_text', 'signature', 'signer', 'network'];
80 // Field list for "item-content" table that is mixed with the item table
81 const MIXED_CONTENT_FIELDLIST = ['title', 'content-warning', 'body', 'location',
82 'coord', 'app', 'rendered-hash', 'rendered-html', 'verb',
83 'object-type', 'object', 'target-type', 'target', 'plink'];
85 // Field list for "item-content" table that is not present in the "item" table
86 const CONTENT_FIELDLIST = ['language'];
88 // All fields in the item table
89 const ITEM_FIELDLIST = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
90 'contact-id', 'type', 'wall', 'gravity', 'extid', 'icid', 'iaid', 'psid',
91 'created', 'edited', 'commented', 'received', 'changed', 'verb',
92 'postopts', 'plink', 'resource-id', 'event-id', 'tag', 'attach', 'inform',
93 'file', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'post-type',
94 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
95 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global', 'network',
96 'title', 'content-warning', 'body', 'location', 'coord', 'app',
97 'rendered-hash', 'rendered-html', 'object-type', 'object', 'target-type', 'target',
98 'author-id', 'author-link', 'author-name', 'author-avatar',
99 'owner-id', 'owner-link', 'owner-name', 'owner-avatar'];
101 // Never reorder or remove entries from this list. Just add new ones at the end, if needed.
102 // The item-activity table only stores the index and needs this array to know the matching activity.
103 const ACTIVITIES = [ACTIVITY_LIKE, ACTIVITY_DISLIKE, ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE];
105 private static $legacy_mode = null;
107 public static function isLegacyMode()
109 if (is_null(self::$legacy_mode)) {
110 self::$legacy_mode = (Config::get("system", "post_update_version") < 1279);
113 return self::$legacy_mode;
117 * @brief returns an activity index from an activity string
119 * @param string $activity activity string
120 * @return integer Activity index
122 public static function activityToIndex($activity)
124 $index = array_search($activity, self::ACTIVITIES);
126 if (is_bool($index)) {
134 * @brief returns an activity string from an activity index
136 * @param integer $index activity index
137 * @return string Activity string
139 private static function indexToActivity($index)
141 if (is_null($index) || !array_key_exists($index, self::ACTIVITIES)) {
145 return self::ACTIVITIES[$index];
149 * @brief Fetch a single item row
151 * @param mixed $stmt statement object
152 * @return array current row
154 public static function fetch($stmt)
156 $row = DBA::fetch($stmt);
162 // ---------------------- Transform item structure data ----------------------
164 // We prefer the data from the user's contact over the public one
165 if (!empty($row['author-link']) && !empty($row['contact-link']) &&
166 ($row['author-link'] == $row['contact-link'])) {
167 if (isset($row['author-avatar']) && !empty($row['contact-avatar'])) {
168 $row['author-avatar'] = $row['contact-avatar'];
170 if (isset($row['author-name']) && !empty($row['contact-name'])) {
171 $row['author-name'] = $row['contact-name'];
175 if (!empty($row['owner-link']) && !empty($row['contact-link']) &&
176 ($row['owner-link'] == $row['contact-link'])) {
177 if (isset($row['owner-avatar']) && !empty($row['contact-avatar'])) {
178 $row['owner-avatar'] = $row['contact-avatar'];
180 if (isset($row['owner-name']) && !empty($row['contact-name'])) {
181 $row['owner-name'] = $row['contact-name'];
185 // We can always comment on posts from these networks
186 if (array_key_exists('writable', $row) &&
187 in_array($row['internal-network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])) {
188 $row['writable'] = true;
191 // ---------------------- Transform item content data ----------------------
193 // Fetch data from the item-content table whenever there is content there
194 if (self::isLegacyMode()) {
195 $legacy_fields = array_merge(ItemDeliveryData::LEGACY_FIELD_LIST, self::MIXED_CONTENT_FIELDLIST);
196 foreach ($legacy_fields as $field) {
197 if (empty($row[$field]) && !empty($row['internal-item-' . $field])) {
198 $row[$field] = $row['internal-item-' . $field];
200 unset($row['internal-item-' . $field]);
204 if (!empty($row['internal-iaid']) && array_key_exists('verb', $row)) {
205 $row['verb'] = self::indexToActivity($row['internal-activity']);
206 if (array_key_exists('title', $row)) {
209 if (array_key_exists('body', $row)) {
210 $row['body'] = $row['verb'];
212 if (array_key_exists('object', $row)) {
215 if (array_key_exists('object-type', $row)) {
216 $row['object-type'] = ACTIVITY_OBJ_NOTE;
218 } elseif (array_key_exists('verb', $row) && in_array($row['verb'], ['', ACTIVITY_POST, ACTIVITY_SHARE])) {
219 // Posts don't have an object or target - but having tags or files.
220 // We safe some performance by building tag and file strings only here.
221 // We remove object and target since they aren't used for this type.
222 if (array_key_exists('object', $row)) {
225 if (array_key_exists('target', $row)) {
230 if (!array_key_exists('verb', $row) || in_array($row['verb'], ['', ACTIVITY_POST, ACTIVITY_SHARE])) {
231 // Build the tag string out of the term entries
232 if (array_key_exists('tag', $row) && empty($row['tag'])) {
233 $row['tag'] = Term::tagTextFromItemId($row['internal-iid']);
236 // Build the file string out of the term entries
237 if (array_key_exists('file', $row) && empty($row['file'])) {
238 $row['file'] = Term::fileTextFromItemId($row['internal-iid']);
242 if (array_key_exists('signed_text', $row) && array_key_exists('interaction', $row) && !is_null($row['interaction'])) {
243 $row['signed_text'] = $row['interaction'];
246 if (array_key_exists('ignored', $row) && array_key_exists('internal-user-ignored', $row) && !is_null($row['internal-user-ignored'])) {
247 $row['ignored'] = $row['internal-user-ignored'];
250 // Remove internal fields
251 unset($row['internal-activity']);
252 unset($row['internal-network']);
253 unset($row['internal-iid']);
254 unset($row['internal-iaid']);
255 unset($row['internal-icid']);
256 unset($row['internal-user-ignored']);
257 unset($row['interaction']);
263 * @brief Fills an array with data from an item query
265 * @param object $stmt statement object
266 * @return array Data array
268 public static function inArray($stmt, $do_close = true) {
269 if (is_bool($stmt)) {
274 while ($row = self::fetch($stmt)) {
284 * @brief Check if item data exists
286 * @param array $condition array of fields for condition
288 * @return boolean Are there rows for that condition?
290 public static function exists($condition) {
291 $stmt = self::select(['id'], $condition, ['limit' => 1]);
293 if (is_bool($stmt)) {
296 $retval = (DBA::numRows($stmt) > 0);
305 * Retrieve a single record from the item table for a given user and returns it in an associative array
307 * @brief Retrieve a single record from a table
308 * @param integer $uid User ID
309 * @param array $fields
310 * @param array $condition
311 * @param array $params
315 public static function selectFirstForUser($uid, array $selected = [], array $condition = [], $params = [])
317 $params['uid'] = $uid;
319 if (empty($selected)) {
320 $selected = Item::DISPLAY_FIELDLIST;
323 return self::selectFirst($selected, $condition, $params);
327 * @brief Select rows from the item table for a given user
329 * @param integer $uid User ID
330 * @param array $selected Array of selected fields, empty for all
331 * @param array $condition Array of fields for condition
332 * @param array $params Array of several parameters
334 * @return boolean|object
336 public static function selectForUser($uid, array $selected = [], array $condition = [], $params = [])
338 $params['uid'] = $uid;
340 if (empty($selected)) {
341 $selected = Item::DISPLAY_FIELDLIST;
344 return self::select($selected, $condition, $params);
348 * Retrieve a single record from the item table and returns it in an associative array
350 * @brief Retrieve a single record from a table
351 * @param array $fields
352 * @param array $condition
353 * @param array $params
357 public static function selectFirst(array $fields = [], array $condition = [], $params = [])
359 $params['limit'] = 1;
361 $result = self::select($fields, $condition, $params);
363 if (is_bool($result)) {
366 $row = self::fetch($result);
373 * @brief Select rows from the item table
375 * @param array $selected Array of selected fields, empty for all
376 * @param array $condition Array of fields for condition
377 * @param array $params Array of several parameters
379 * @return boolean|object
381 public static function select(array $selected = [], array $condition = [], $params = [])
386 if (isset($params['uid'])) {
387 $uid = $params['uid'];
391 $fields = self::fieldlist($usermode);
393 $select_fields = self::constructSelectFields($fields, $selected);
395 $condition_string = DBA::buildCondition($condition);
397 $condition_string = self::addTablesToFields($condition_string, $fields);
400 $condition_string = $condition_string . ' AND ' . self::condition(false);
403 $param_string = self::addTablesToFields(DBA::buildParameter($params), $fields);
405 $table = "`item` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, false, $usermode);
407 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
409 return DBA::p($sql, $condition);
413 * @brief Select rows from the starting post in the item table
415 * @param integer $uid User ID
416 * @param array $fields Array of selected fields, empty for all
417 * @param array $condition Array of fields for condition
418 * @param array $params Array of several parameters
420 * @return boolean|object
422 public static function selectThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
424 $params['uid'] = $uid;
426 if (empty($selected)) {
427 $selected = Item::DISPLAY_FIELDLIST;
430 return self::selectThread($selected, $condition, $params);
434 * Retrieve a single record from the starting post in the item table and returns it in an associative array
436 * @brief Retrieve a single record from a table
437 * @param integer $uid User ID
438 * @param array $selected
439 * @param array $condition
440 * @param array $params
444 public static function selectFirstThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
446 $params['uid'] = $uid;
448 if (empty($selected)) {
449 $selected = Item::DISPLAY_FIELDLIST;
452 return self::selectFirstThread($selected, $condition, $params);
456 * Retrieve a single record from the starting post in the item table and returns it in an associative array
458 * @brief Retrieve a single record from a table
459 * @param array $fields
460 * @param array $condition
461 * @param array $params
465 public static function selectFirstThread(array $fields = [], array $condition = [], $params = [])
467 $params['limit'] = 1;
468 $result = self::selectThread($fields, $condition, $params);
470 if (is_bool($result)) {
473 $row = self::fetch($result);
480 * @brief Select rows from the starting post in the item table
482 * @param array $selected Array of selected fields, empty for all
483 * @param array $condition Array of fields for condition
484 * @param array $params Array of several parameters
486 * @return boolean|object
488 public static function selectThread(array $selected = [], array $condition = [], $params = [])
493 if (isset($params['uid'])) {
494 $uid = $params['uid'];
498 $fields = self::fieldlist($usermode);
500 $fields['thread'] = ['mention', 'ignored', 'iid'];
502 $threadfields = ['thread' => ['iid', 'uid', 'contact-id', 'owner-id', 'author-id',
503 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private',
504 'pubmail', 'moderated', 'visible', 'starred', 'ignored', 'post-type',
505 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'network']];
507 $select_fields = self::constructSelectFields($fields, $selected);
509 $condition_string = DBA::buildCondition($condition);
511 $condition_string = self::addTablesToFields($condition_string, $threadfields);
512 $condition_string = self::addTablesToFields($condition_string, $fields);
515 $condition_string = $condition_string . ' AND ' . self::condition(true);
518 $param_string = DBA::buildParameter($params);
519 $param_string = self::addTablesToFields($param_string, $threadfields);
520 $param_string = self::addTablesToFields($param_string, $fields);
522 $table = "`thread` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, true, $usermode);
524 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
526 return DBA::p($sql, $condition);
530 * @brief Returns a list of fields that are associated with the item table
532 * @return array field list
534 private static function fieldlist($usermode)
538 $fields['item'] = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
539 'contact-id', 'owner-id', 'author-id', 'type', 'wall', 'gravity', 'extid',
540 'created', 'edited', 'commented', 'received', 'changed', 'psid',
541 'resource-id', 'event-id', 'tag', 'attach', 'post-type', 'file',
542 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
543 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global',
544 'id' => 'item_id', 'network', 'icid', 'iaid', 'id' => 'internal-iid',
545 'network' => 'internal-network', 'icid' => 'internal-icid',
546 'iaid' => 'internal-iaid'];
549 $fields['user-item'] = ['ignored' => 'internal-user-ignored'];
552 $fields['item-activity'] = ['activity', 'activity' => 'internal-activity'];
554 $fields['item-content'] = array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST);
556 $fields['item-delivery-data'] = array_merge(ItemDeliveryData::LEGACY_FIELD_LIST, ItemDeliveryData::FIELD_LIST);
558 $fields['permissionset'] = ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'];
560 $fields['author'] = ['url' => 'author-link', 'name' => 'author-name',
561 'thumb' => 'author-avatar', 'nick' => 'author-nick', 'network' => 'author-network'];
563 $fields['owner'] = ['url' => 'owner-link', 'name' => 'owner-name',
564 'thumb' => 'owner-avatar', 'nick' => 'owner-nick', 'network' => 'owner-network'];
566 $fields['contact'] = ['url' => 'contact-link', 'name' => 'contact-name', 'thumb' => 'contact-avatar',
567 'writable', 'self', 'id' => 'cid', 'alias', 'uid' => 'contact-uid',
568 'photo', 'name-date', 'uri-date', 'avatar-date', 'thumb', 'dfrn-id'];
570 $fields['parent-item'] = ['guid' => 'parent-guid', 'network' => 'parent-network'];
572 $fields['parent-item-author'] = ['url' => 'parent-author-link', 'name' => 'parent-author-name'];
574 $fields['event'] = ['created' => 'event-created', 'edited' => 'event-edited',
575 'start' => 'event-start','finish' => 'event-finish',
576 'summary' => 'event-summary','desc' => 'event-desc',
577 'location' => 'event-location', 'type' => 'event-type',
578 'nofinish' => 'event-nofinish','adjust' => 'event-adjust',
579 'ignore' => 'event-ignore', 'id' => 'event-id'];
581 $fields['sign'] = ['signed_text', 'signature', 'signer'];
583 $fields['diaspora-interaction'] = ['interaction'];
589 * @brief Returns SQL condition for the "select" functions
591 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
593 * @return string SQL condition
595 private static function condition($thread_mode)
598 $master_table = "`thread`";
600 $master_table = "`item`";
602 return sprintf("$master_table.`visible` AND NOT $master_table.`deleted` AND NOT $master_table.`moderated`
603 AND (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`)
604 AND (`user-author`.`blocked` IS NULL OR NOT `user-author`.`blocked`)
605 AND (`user-author`.`ignored` IS NULL OR NOT `user-author`.`ignored` OR `item`.`gravity` != %d)
606 AND (`user-owner`.`blocked` IS NULL OR NOT `user-owner`.`blocked`)
607 AND (`user-owner`.`ignored` IS NULL OR NOT `user-owner`.`ignored` OR `item`.`gravity` != %d) ",
608 GRAVITY_PARENT, GRAVITY_PARENT);
612 * @brief Returns all needed "JOIN" commands for the "select" functions
614 * @param integer $uid User ID
615 * @param string $sql_commands The parts of the built SQL commands in the "select" functions
616 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
618 * @return string The SQL joins for the "select" functions
620 private static function constructJoins($uid, $sql_commands, $thread_mode, $user_mode)
623 $master_table = "`thread`";
624 $master_table_key = "`thread`.`iid`";
625 $joins = "STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid` ";
627 $master_table = "`item`";
628 $master_table_key = "`item`.`id`";
633 $joins .= sprintf("STRAIGHT_JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`
634 AND NOT `contact`.`blocked`
635 AND ((NOT `contact`.`readonly` AND NOT `contact`.`pending` AND (`contact`.`rel` IN (%s, %s)))
636 OR `contact`.`self` OR `item`.`gravity` != %d OR `contact`.`uid` = 0)
637 STRAIGHT_JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id` AND NOT `author`.`blocked`
638 STRAIGHT_JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id` AND NOT `owner`.`blocked`
639 LEFT JOIN `user-item` ON `user-item`.`iid` = $master_table_key AND `user-item`.`uid` = %d
640 LEFT JOIN `user-contact` AS `user-author` ON `user-author`.`cid` = $master_table.`author-id` AND `user-author`.`uid` = %d
641 LEFT JOIN `user-contact` AS `user-owner` ON `user-owner`.`cid` = $master_table.`owner-id` AND `user-owner`.`uid` = %d",
642 Contact::SHARING, Contact::FRIEND, GRAVITY_PARENT, intval($uid), intval($uid), intval($uid));
644 if (strpos($sql_commands, "`contact`.") !== false) {
645 $joins .= "LEFT JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`";
647 if (strpos($sql_commands, "`author`.") !== false) {
648 $joins .= " LEFT JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id`";
650 if (strpos($sql_commands, "`owner`.") !== false) {
651 $joins .= " LEFT JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id`";
655 if (strpos($sql_commands, "`group_member`.") !== false) {
656 $joins .= " STRAIGHT_JOIN `group_member` ON `group_member`.`contact-id` = $master_table.`contact-id`";
659 if (strpos($sql_commands, "`user`.") !== false) {
660 $joins .= " STRAIGHT_JOIN `user` ON `user`.`uid` = $master_table.`uid`";
663 if (strpos($sql_commands, "`event`.") !== false) {
664 $joins .= " LEFT JOIN `event` ON `event-id` = `event`.`id`";
667 if (strpos($sql_commands, "`sign`.") !== false) {
668 $joins .= " LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`";
671 if (strpos($sql_commands, "`diaspora-interaction`.") !== false) {
672 $joins .= " LEFT JOIN `diaspora-interaction` ON `diaspora-interaction`.`uri-id` = `item`.`uri-id`";
675 if (strpos($sql_commands, "`item-activity`.") !== false) {
676 $joins .= " LEFT JOIN `item-activity` ON `item-activity`.`uri-id` = `item`.`uri-id`";
679 if (strpos($sql_commands, "`item-content`.") !== false) {
680 $joins .= " LEFT JOIN `item-content` ON `item-content`.`uri-id` = `item`.`uri-id`";
683 if (strpos($sql_commands, "`item-delivery-data`.") !== false) {
684 $joins .= " LEFT JOIN `item-delivery-data` ON `item-delivery-data`.`iid` = `item`.`id`";
687 if (strpos($sql_commands, "`permissionset`.") !== false) {
688 $joins .= " LEFT JOIN `permissionset` ON `permissionset`.`id` = `item`.`psid`";
691 if ((strpos($sql_commands, "`parent-item`.") !== false) || (strpos($sql_commands, "`parent-author`.") !== false)) {
692 $joins .= " STRAIGHT_JOIN `item` AS `parent-item` ON `parent-item`.`id` = `item`.`parent`";
695 if (strpos($sql_commands, "`parent-item-author`.") !== false) {
696 $joins .= " STRAIGHT_JOIN `contact` AS `parent-item-author` ON `parent-item-author`.`id` = `parent-item`.`author-id`";
703 * @brief Add the field list for the "select" functions
705 * @param array $fields The field definition array
706 * @param array $selected The array with the selected fields from the "select" functions
708 * @return string The field list
710 private static function constructSelectFields($fields, $selected)
712 if (!empty($selected)) {
713 $selected[] = 'internal-iid';
714 $selected[] = 'internal-iaid';
715 $selected[] = 'internal-icid';
716 $selected[] = 'internal-network';
719 if (in_array('verb', $selected)) {
720 $selected[] = 'internal-activity';
723 if (in_array('ignored', $selected)) {
724 $selected[] = 'internal-user-ignored';
727 if (in_array('signed_text', $selected)) {
728 $selected[] = 'interaction';
731 $legacy_fields = array_merge(ItemDeliveryData::LEGACY_FIELD_LIST, self::MIXED_CONTENT_FIELDLIST);
734 foreach ($fields as $table => $table_fields) {
735 foreach ($table_fields as $field => $select) {
736 if (empty($selected) || in_array($select, $selected)) {
737 if (self::isLegacyMode() && in_array($select, $legacy_fields)) {
738 $selection[] = "`item`.`".$select."` AS `internal-item-" . $select . "`";
740 if (is_int($field)) {
741 $selection[] = "`" . $table . "`.`" . $select . "`";
743 $selection[] = "`" . $table . "`.`" . $field . "` AS `" . $select . "`";
748 return implode(", ", $selection);
752 * @brief add table definition to fields in an SQL query
754 * @param string $query SQL query
755 * @param array $fields The field definition array
757 * @return string the changed SQL query
759 private static function addTablesToFields($query, $fields)
761 foreach ($fields as $table => $table_fields) {
762 foreach ($table_fields as $alias => $field) {
763 if (is_int($alias)) {
764 $replace_field = $field;
766 $replace_field = $alias;
769 $search = "/([^\.])`" . $field . "`/i";
770 $replace = "$1`" . $table . "`.`" . $replace_field . "`";
771 $query = preg_replace($search, $replace, $query);
778 * @brief Update existing item entries
780 * @param array $fields The fields that are to be changed
781 * @param array $condition The condition for finding the item entries
783 * In the future we may have to change permissions as well.
784 * Then we had to add the user id as third parameter.
786 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
788 * @return integer|boolean number of affected rows - or "false" if there was an error
790 public static function update(array $fields, array $condition)
792 if (empty($condition) || empty($fields)) {
796 // To ensure the data integrity we do it in an transaction
799 // We cannot simply expand the condition to check for origin entries
800 // The condition needn't to be a simple array but could be a complex condition.
801 // And we have to execute this query before the update to ensure to fetch the same data.
802 $items = DBA::select('item', ['id', 'origin', 'uri', 'uri-id', 'iaid', 'icid', 'tag', 'file'], $condition);
804 $content_fields = [];
805 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
806 if (isset($fields[$field])) {
807 $content_fields[$field] = $fields[$field];
808 if (in_array($field, self::CONTENT_FIELDLIST) || !self::isLegacyMode()) {
809 unset($fields[$field]);
811 $fields[$field] = null;
816 $delivery_data = ItemDeliveryData::extractFields($fields);
818 $clear_fields = ['bookmark', 'type', 'author-name', 'author-avatar', 'author-link', 'owner-name', 'owner-avatar', 'owner-link', 'postopts', 'inform'];
819 foreach ($clear_fields as $field) {
820 if (array_key_exists($field, $fields)) {
821 $fields[$field] = null;
825 if (array_key_exists('tag', $fields)) {
826 $tags = $fields['tag'];
827 $fields['tag'] = null;
832 if (array_key_exists('file', $fields)) {
833 $files = $fields['file'];
834 $fields['file'] = null;
839 if (!empty($fields)) {
840 $success = DBA::update('item', $fields, $condition);
849 // When there is no content for the "old" item table, this will count the fetched items
850 $rows = DBA::affectedRows();
852 while ($item = DBA::fetch($items)) {
853 if (!empty($item['iaid']) || (!empty($content_fields['verb']) && (self::activityToIndex($content_fields['verb']) >= 0))) {
854 self::updateActivity($content_fields, ['uri-id' => $item['uri-id']]);
856 if (empty($item['iaid'])) {
857 $item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-id' => $item['uri-id']]);
858 if (DBA::isResult($item_activity)) {
859 $item_fields = ['iaid' => $item_activity['id'], 'icid' => null];
860 foreach (self::MIXED_CONTENT_FIELDLIST as $field) {
861 if (self::isLegacyMode()) {
862 $item_fields[$field] = null;
864 unset($item_fields[$field]);
867 DBA::update('item', $item_fields, ['id' => $item['id']]);
869 if (!empty($item['icid']) && !DBA::exists('item', ['icid' => $item['icid']])) {
870 DBA::delete('item-content', ['id' => $item['icid']]);
873 } elseif (!empty($item['icid'])) {
874 DBA::update('item', ['icid' => null], ['id' => $item['id']]);
876 if (!DBA::exists('item', ['icid' => $item['icid']])) {
877 DBA::delete('item-content', ['id' => $item['icid']]);
881 self::updateContent($content_fields, ['uri-id' => $item['uri-id']]);
883 if (empty($item['icid'])) {
884 $item_content = DBA::selectFirst('item-content', [], ['uri-id' => $item['uri-id']]);
885 if (DBA::isResult($item_content)) {
886 $item_fields = ['icid' => $item_content['id']];
887 // Clear all fields in the item table that have a content in the item-content table
888 foreach ($item_content as $field => $content) {
889 if (in_array($field, self::MIXED_CONTENT_FIELDLIST) && !empty($item_content[$field])) {
890 if (self::isLegacyMode()) {
891 $item_fields[$field] = null;
893 unset($item_fields[$field]);
897 DBA::update('item', $item_fields, ['id' => $item['id']]);
902 if (!is_null($tags)) {
903 Term::insertFromTagFieldByItemId($item['id'], $tags);
904 if (!empty($item['tag'])) {
905 DBA::update('item', ['tag' => ''], ['id' => $item['id']]);
909 if (!is_null($files)) {
910 Term::insertFromFileFieldByItemId($item['id'], $files);
911 if (!empty($item['file'])) {
912 DBA::update('item', ['file' => ''], ['id' => $item['id']]);
916 ItemDeliveryData::update($item['id'], $delivery_data);
918 self::updateThread($item['id']);
920 // We only need to notfiy others when it is an original entry from us.
921 // Only call the notifier when the item has some content relevant change.
922 if ($item['origin'] && in_array('edited', array_keys($fields))) {
923 Worker::add(PRIORITY_HIGH, "Notifier", 'edit_post', $item['id']);
933 * @brief Delete an item and notify others about it - if it was ours
935 * @param array $condition The condition for finding the item entries
936 * @param integer $priority Priority for the notification
938 public static function delete($condition, $priority = PRIORITY_HIGH)
940 $items = self::select(['id'], $condition);
941 while ($item = self::fetch($items)) {
942 self::deleteById($item['id'], $priority);
948 * @brief Delete an item for an user and notify others about it - if it was ours
950 * @param array $condition The condition for finding the item entries
951 * @param integer $uid User who wants to delete this item
953 public static function deleteForUser($condition, $uid)
959 $items = self::select(['id', 'uid'], $condition);
960 while ($item = self::fetch($items)) {
961 // "Deleting" global items just means hiding them
962 if ($item['uid'] == 0) {
963 DBA::update('user-item', ['hidden' => true], ['iid' => $item['id'], 'uid' => $uid], true);
964 } elseif ($item['uid'] == $uid) {
965 self::deleteById($item['id'], PRIORITY_HIGH);
967 Logger::log('Wrong ownership. Not deleting item ' . $item['id']);
974 * @brief Delete an item and notify others about it - if it was ours
976 * @param integer $item_id Item ID that should be delete
977 * @param integer $priority Priority for the notification
979 * @return boolean success
981 public static function deleteById($item_id, $priority = PRIORITY_HIGH)
983 // locate item to be deleted
984 $fields = ['id', 'uri', 'uid', 'parent', 'parent-uri', 'origin',
985 'deleted', 'file', 'resource-id', 'event-id', 'attach',
986 'verb', 'object-type', 'object', 'target', 'contact-id',
987 'icid', 'iaid', 'psid'];
988 $item = self::selectFirst($fields, ['id' => $item_id]);
989 if (!DBA::isResult($item)) {
990 Logger::log('Item with ID ' . $item_id . " hasn't been found.", Logger::DEBUG);
994 if ($item['deleted']) {
995 Logger::log('Item with ID ' . $item_id . ' has already been deleted.', Logger::DEBUG);
999 $parent = self::selectFirst(['origin'], ['id' => $item['parent']]);
1000 if (!DBA::isResult($parent)) {
1001 $parent = ['origin' => false];
1004 // clean up categories and tags so they don't end up as orphans
1007 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
1010 foreach ($matches as $mtch) {
1011 FileTag::unsaveFile($item['uid'], $item['id'], $mtch[1],true);
1017 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
1020 foreach ($matches as $mtch) {
1021 FileTag::unsaveFile($item['uid'], $item['id'], $mtch[1],false);
1026 * If item is a link to a photo resource, nuke all the associated photos
1027 * (visitors will not have photo resources)
1028 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
1029 * generate a resource-id and therefore aren't intimately linked to the item.
1031 if (strlen($item['resource-id'])) {
1032 Photo::delete(['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
1035 // If item is a link to an event, delete the event.
1036 if (intval($item['event-id'])) {
1037 Event::delete($item['event-id']);
1040 // If item has attachments, drop them
1041 foreach (explode(", ", $item['attach']) as $attach) {
1042 preg_match("|attach/(\d+)|", $attach, $matches);
1043 if (is_array($matches) && count($matches) > 1) {
1044 Attach::delete(['id' => $matches[1], 'uid' => $item['uid']]);
1048 // Delete tags that had been attached to other items
1049 self::deleteTagsFromItem($item);
1051 // Set the item to "deleted"
1052 $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
1053 DBA::update('item', $item_fields, ['id' => $item['id']]);
1055 Term::insertFromTagFieldByItemId($item['id'], '');
1056 Term::insertFromFileFieldByItemId($item['id'], '');
1057 self::deleteThread($item['id'], $item['parent-uri']);
1059 if (!self::exists(["`uri` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri']])) {
1060 self::delete(['uri' => $item['uri'], 'uid' => 0, 'deleted' => false], $priority);
1063 ItemDeliveryData::delete($item['id']);
1065 // We don't delete the item-activity here, since we need some of the data for ActivityPub
1067 if (!empty($item['icid']) && !self::exists(['icid' => $item['icid'], 'deleted' => false])) {
1068 DBA::delete('item-content', ['id' => $item['icid']], ['cascade' => false]);
1070 // When the permission set will be used in photo and events as well,
1071 // this query here needs to be extended.
1072 if (!empty($item['psid']) && !self::exists(['psid' => $item['psid'], 'deleted' => false])) {
1073 DBA::delete('permissionset', ['id' => $item['psid']], ['cascade' => false]);
1076 // If it's the parent of a comment thread, kill all the kids
1077 if ($item['id'] == $item['parent']) {
1078 self::delete(['parent' => $item['parent'], 'deleted' => false], $priority);
1081 // Is it our comment and/or our thread?
1082 if ($item['origin'] || $parent['origin']) {
1084 // When we delete the original post we will delete all existing copies on the server as well
1085 self::delete(['uri' => $item['uri'], 'deleted' => false], $priority);
1087 // send the notification upstream/downstream
1088 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", "drop", intval($item['id']));
1089 } elseif ($item['uid'] != 0) {
1091 // When we delete just our local user copy of an item, we have to set a marker to hide it
1092 $global_item = self::selectFirst(['id'], ['uri' => $item['uri'], 'uid' => 0, 'deleted' => false]);
1093 if (DBA::isResult($global_item)) {
1094 DBA::update('user-item', ['hidden' => true], ['iid' => $global_item['id'], 'uid' => $item['uid']], true);
1098 Logger::log('Item with ID ' . $item_id . " has been deleted.", Logger::DEBUG);
1103 private static function deleteTagsFromItem($item)
1105 if (($item["verb"] != ACTIVITY_TAG) || ($item["object-type"] != ACTIVITY_OBJ_TAGTERM)) {
1109 $xo = XML::parseString($item["object"], false);
1110 $xt = XML::parseString($item["target"], false);
1112 if ($xt->type != ACTIVITY_OBJ_NOTE) {
1116 $i = self::selectFirst(['id', 'contact-id', 'tag'], ['uri' => $xt->id, 'uid' => $item['uid']]);
1117 if (!DBA::isResult($i)) {
1121 // For tags, the owner cannot remove the tag on the author's copy of the post.
1122 $owner_remove = ($item["contact-id"] == $i["contact-id"]);
1123 $author_copy = $item["origin"];
1125 if (($owner_remove && $author_copy) || !$owner_remove) {
1129 $tags = explode(',', $i["tag"]);
1132 foreach ($tags as $tag) {
1133 if (trim($tag) !== trim($xo->body)) {
1134 $newtags[] = trim($tag);
1138 self::update(['tag' => implode(',', $newtags)], ['id' => $i["id"]]);
1141 private static function guid($item, $notify)
1143 if (!empty($item['guid'])) {
1144 return Strings::escapeTags(trim($item['guid']));
1148 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
1149 // We add the hash of our own host because our host is the original creator of the post.
1150 $prefix_host = \get_app()->getHostName();
1154 // We are only storing the post so we create a GUID from the original hostname.
1155 if (!empty($item['author-link'])) {
1156 $parsed = parse_url($item['author-link']);
1157 if (!empty($parsed['host'])) {
1158 $prefix_host = $parsed['host'];
1162 if (empty($prefix_host) && !empty($item['plink'])) {
1163 $parsed = parse_url($item['plink']);
1164 if (!empty($parsed['host'])) {
1165 $prefix_host = $parsed['host'];
1169 if (empty($prefix_host) && !empty($item['uri'])) {
1170 $parsed = parse_url($item['uri']);
1171 if (!empty($parsed['host'])) {
1172 $prefix_host = $parsed['host'];
1176 // Is it in the format data@host.tld? - Used for mail contacts
1177 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
1178 $mailparts = explode('@', $item['author-link']);
1179 $prefix_host = array_pop($mailparts);
1183 if (!empty($item['plink'])) {
1184 $guid = self::guidFromUri($item['plink'], $prefix_host);
1185 } elseif (!empty($item['uri'])) {
1186 $guid = self::guidFromUri($item['uri'], $prefix_host);
1188 $guid = System::createUUID(hash('crc32', $prefix_host));
1194 private static function contactId($item)
1196 $contact_id = (int)$item["contact-id"];
1198 if (!empty($contact_id)) {
1201 Logger::log('Missing contact-id. Called by: '.System::callstack(), Logger::DEBUG);
1203 * First we are looking for a suitable contact that matches with the author of the post
1204 * This is done only for comments
1206 if ($item['parent-uri'] != $item['uri']) {
1207 $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
1210 // If not present then maybe the owner was found
1211 if ($contact_id == 0) {
1212 $contact_id = Contact::getIdForURL($item['owner-link'], $item['uid']);
1215 // Still missing? Then use the "self" contact of the current user
1216 if ($contact_id == 0) {
1217 $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $item['uid']]);
1218 if (DBA::isResult($self)) {
1219 $contact_id = $self["id"];
1222 Logger::log("Contact-id was missing for post ".$item['guid']." from user id ".$item['uid']." - now set to ".$contact_id, Logger::DEBUG);
1227 // This function will finally cover most of the preparation functionality in mod/item.php
1228 public static function prepare(&$item)
1230 $data = BBCode::getAttachmentData($item['body']);
1231 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $item['body'], $match, PREG_SET_ORDER) || isset($data["type"]))
1232 && ($posttype != Item::PT_PERSONAL_NOTE)) {
1233 $posttype = Item::PT_PAGE;
1234 $objecttype = ACTIVITY_OBJ_BOOKMARK;
1238 public static function insert($item, $force_parent = false, $notify = false, $dontcache = false)
1242 // If it is a posting where users should get notifications, then define it as wall posting
1245 $item['origin'] = 1;
1246 $item['network'] = Protocol::DFRN;
1247 $item['protocol'] = Conversation::PARCEL_DFRN;
1249 if (is_int($notify)) {
1250 $priority = $notify;
1252 $priority = PRIORITY_HIGH;
1255 $item['network'] = trim(defaults($item, 'network', Protocol::PHANTOM));
1258 $item['guid'] = self::guid($item, $notify);
1259 $item['uri'] = Strings::escapeTags(trim(defaults($item, 'uri', self::newURI($item['uid'], $item['guid']))));
1262 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
1264 // Store conversation data
1265 $item = Conversation::insert($item);
1268 * If a Diaspora signature structure was passed in, pull it out of the
1269 * item array and set it aside for later storage.
1273 if (isset($item['dsprsig'])) {
1274 $encoded_signature = $item['dsprsig'];
1275 $dsprsig = json_decode(base64_decode($item['dsprsig']));
1276 unset($item['dsprsig']);
1279 $diaspora_signed_text = '';
1280 if (isset($item['diaspora_signed_text'])) {
1281 $diaspora_signed_text = $item['diaspora_signed_text'];
1282 unset($item['diaspora_signed_text']);
1285 // Converting the plink
1286 /// @TODO Check if this is really still needed
1287 if ($item['network'] == Protocol::OSTATUS) {
1288 if (isset($item['plink'])) {
1289 $item['plink'] = OStatus::convertHref($item['plink']);
1290 } elseif (isset($item['uri'])) {
1291 $item['plink'] = OStatus::convertHref($item['uri']);
1295 if (!empty($item['thr-parent'])) {
1296 $item['parent-uri'] = $item['thr-parent'];
1299 if (isset($item['gravity'])) {
1300 $item['gravity'] = intval($item['gravity']);
1301 } elseif ($item['parent-uri'] === $item['uri']) {
1302 $item['gravity'] = GRAVITY_PARENT;
1303 } elseif (activity_match($item['verb'], ACTIVITY_POST)) {
1304 $item['gravity'] = GRAVITY_COMMENT;
1306 $item['gravity'] = GRAVITY_UNKNOWN; // Should not happen
1307 Logger::log('Unknown gravity for verb: ' . $item['verb'], Logger::DEBUG);
1310 $uid = intval($item['uid']);
1312 // check for create date and expire time
1313 $expire_interval = Config::get('system', 'dbclean-expire-days', 0);
1315 $user = DBA::selectFirst('user', ['expire'], ['uid' => $uid]);
1316 if (DBA::isResult($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
1317 $expire_interval = $user['expire'];
1320 if (($expire_interval > 0) && !empty($item['created'])) {
1321 $expire_date = time() - ($expire_interval * 86400);
1322 $created_date = strtotime($item['created']);
1323 if ($created_date < $expire_date) {
1324 Logger::log('item-store: item created ('.date('c', $created_date).') before expiration time ('.date('c', $expire_date).'). ignored. ' . print_r($item,true), Logger::DEBUG);
1330 * Do we already have this item?
1331 * We have to check several networks since Friendica posts could be repeated
1332 * via OStatus (maybe Diasporsa as well)
1334 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DIASPORA, Protocol::DFRN, Protocol::OSTATUS, ""])) {
1335 $condition = ["`uri` = ? AND `uid` = ? AND `network` IN (?, ?, ?)",
1336 trim($item['uri']), $item['uid'],
1337 Protocol::DIASPORA, Protocol::DFRN, Protocol::OSTATUS];
1338 $existing = self::selectFirst(['id', 'network'], $condition);
1339 if (DBA::isResult($existing)) {
1340 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
1342 Logger::log("Item with uri ".$item['uri']." already existed for user ".$uid." with id ".$existing["id"]." target network ".$existing["network"]." - new network: ".$item['network']);
1345 return $existing["id"];
1349 $item['wall'] = intval(defaults($item, 'wall', 0));
1350 $item['extid'] = trim(defaults($item, 'extid', ''));
1351 $item['author-name'] = trim(defaults($item, 'author-name', ''));
1352 $item['author-link'] = trim(defaults($item, 'author-link', ''));
1353 $item['author-avatar'] = trim(defaults($item, 'author-avatar', ''));
1354 $item['owner-name'] = trim(defaults($item, 'owner-name', ''));
1355 $item['owner-link'] = trim(defaults($item, 'owner-link', ''));
1356 $item['owner-avatar'] = trim(defaults($item, 'owner-avatar', ''));
1357 $item['received'] = (isset($item['received']) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
1358 $item['created'] = (isset($item['created']) ? DateTimeFormat::utc($item['created']) : $item['received']);
1359 $item['edited'] = (isset($item['edited']) ? DateTimeFormat::utc($item['edited']) : $item['created']);
1360 $item['changed'] = (isset($item['changed']) ? DateTimeFormat::utc($item['changed']) : $item['created']);
1361 $item['commented'] = (isset($item['commented']) ? DateTimeFormat::utc($item['commented']) : $item['created']);
1362 $item['title'] = trim(defaults($item, 'title', ''));
1363 $item['location'] = trim(defaults($item, 'location', ''));
1364 $item['coord'] = trim(defaults($item, 'coord', ''));
1365 $item['visible'] = (isset($item['visible']) ? intval($item['visible']) : 1);
1366 $item['deleted'] = 0;
1367 $item['parent-uri'] = trim(defaults($item, 'parent-uri', $item['uri']));
1368 $item['post-type'] = defaults($item, 'post-type', self::PT_ARTICLE);
1369 $item['verb'] = trim(defaults($item, 'verb', ''));
1370 $item['object-type'] = trim(defaults($item, 'object-type', ''));
1371 $item['object'] = trim(defaults($item, 'object', ''));
1372 $item['target-type'] = trim(defaults($item, 'target-type', ''));
1373 $item['target'] = trim(defaults($item, 'target', ''));
1374 $item['plink'] = trim(defaults($item, 'plink', ''));
1375 $item['allow_cid'] = trim(defaults($item, 'allow_cid', ''));
1376 $item['allow_gid'] = trim(defaults($item, 'allow_gid', ''));
1377 $item['deny_cid'] = trim(defaults($item, 'deny_cid', ''));
1378 $item['deny_gid'] = trim(defaults($item, 'deny_gid', ''));
1379 $item['private'] = intval(defaults($item, 'private', 0));
1380 $item['body'] = trim(defaults($item, 'body', ''));
1381 $item['tag'] = trim(defaults($item, 'tag', ''));
1382 $item['attach'] = trim(defaults($item, 'attach', ''));
1383 $item['app'] = trim(defaults($item, 'app', ''));
1384 $item['origin'] = intval(defaults($item, 'origin', 0));
1385 $item['postopts'] = trim(defaults($item, 'postopts', ''));
1386 $item['resource-id'] = trim(defaults($item, 'resource-id', ''));
1387 $item['event-id'] = intval(defaults($item, 'event-id', 0));
1388 $item['inform'] = trim(defaults($item, 'inform', ''));
1389 $item['file'] = trim(defaults($item, 'file', ''));
1391 // When there is no content then we don't post it
1392 if ($item['body'].$item['title'] == '') {
1393 Logger::log('No body, no title.');
1397 self::addLanguageToItemArray($item);
1399 // Items cannot be stored before they happen ...
1400 if ($item['created'] > DateTimeFormat::utcNow()) {
1401 $item['created'] = DateTimeFormat::utcNow();
1404 // We haven't invented time travel by now.
1405 if ($item['edited'] > DateTimeFormat::utcNow()) {
1406 $item['edited'] = DateTimeFormat::utcNow();
1409 $item['plink'] = defaults($item, 'plink', System::baseUrl() . '/display/' . urlencode($item['guid']));
1411 // The contact-id should be set before "self::insert" was called - but there seems to be issues sometimes
1412 $item["contact-id"] = self::contactId($item);
1414 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
1415 'photo' => $item['author-avatar'], 'network' => $item['network']];
1417 $item['author-id'] = defaults($item, 'author-id', Contact::getIdForURL($item["author-link"], 0, false, $default));
1419 if (Contact::isBlocked($item["author-id"])) {
1420 Logger::log('Contact '.$item["author-id"].' is blocked, item '.$item["uri"].' will not be stored');
1424 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
1425 'photo' => $item['owner-avatar'], 'network' => $item['network']];
1427 $item['owner-id'] = defaults($item, 'owner-id', Contact::getIdForURL($item["owner-link"], 0, false, $default));
1429 if (Contact::isBlocked($item["owner-id"])) {
1430 Logger::log('Contact '.$item["owner-id"].' is blocked, item '.$item["uri"].' will not be stored');
1434 if ($item['network'] == Protocol::PHANTOM) {
1435 Logger::log('Missing network. Called by: '.System::callstack(), Logger::DEBUG);
1437 $item['network'] = Protocol::DFRN;
1438 Logger::log("Set network to " . $item["network"] . " for " . $item["uri"], Logger::DEBUG);
1441 // Checking if there is already an item with the same guid
1442 Logger::log('Checking for an item for user '.$item['uid'].' on network '.$item['network'].' with the guid '.$item['guid'], Logger::DEBUG);
1443 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
1444 if (self::exists($condition)) {
1445 Logger::log('found item with guid '.$item['guid'].' for user '.$item['uid'].' on network '.$item['network'], Logger::DEBUG);
1449 // Check for hashtags in the body and repair or add hashtag links
1450 self::setHashtags($item);
1452 $item['thr-parent'] = $item['parent-uri'];
1460 if ($item['parent-uri'] === $item['uri']) {
1462 $parent_deleted = 0;
1463 $allow_cid = $item['allow_cid'];
1464 $allow_gid = $item['allow_gid'];
1465 $deny_cid = $item['deny_cid'];
1466 $deny_gid = $item['deny_gid'];
1467 $notify_type = 'wall-new';
1469 // find the parent and snarf the item id and ACLs
1470 // and anything else we need to inherit
1472 $fields = ['uri', 'parent-uri', 'id', 'deleted',
1473 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
1474 'wall', 'private', 'forum_mode', 'origin'];
1475 $condition = ['uri' => $item['parent-uri'], 'uid' => $item['uid']];
1476 $params = ['order' => ['id' => false]];
1477 $parent = self::selectFirst($fields, $condition, $params);
1479 if (DBA::isResult($parent)) {
1480 // is the new message multi-level threaded?
1481 // even though we don't support it now, preserve the info
1482 // and re-attach to the conversation parent.
1484 if ($parent['uri'] != $parent['parent-uri']) {
1485 $item['parent-uri'] = $parent['parent-uri'];
1487 $condition = ['uri' => $item['parent-uri'],
1488 'parent-uri' => $item['parent-uri'],
1489 'uid' => $item['uid']];
1490 $params = ['order' => ['id' => false]];
1491 $toplevel_parent = self::selectFirst($fields, $condition, $params);
1493 if (DBA::isResult($toplevel_parent)) {
1494 $parent = $toplevel_parent;
1498 $parent_id = $parent['id'];
1499 $parent_deleted = $parent['deleted'];
1500 $allow_cid = $parent['allow_cid'];
1501 $allow_gid = $parent['allow_gid'];
1502 $deny_cid = $parent['deny_cid'];
1503 $deny_gid = $parent['deny_gid'];
1504 $item['wall'] = $parent['wall'];
1505 $notify_type = 'comment-new';
1508 * If the parent is private, force privacy for the entire conversation
1509 * This differs from the above settings as it subtly allows comments from
1510 * email correspondents to be private even if the overall thread is not.
1512 if ($parent['private']) {
1513 $item['private'] = $parent['private'];
1517 * Edge case. We host a public forum that was originally posted to privately.
1518 * The original author commented, but as this is a comment, the permissions
1519 * weren't fixed up so it will still show the comment as private unless we fix it here.
1521 if ((intval($parent['forum_mode']) == 1) && $parent['private']) {
1522 $item['private'] = 0;
1525 // If its a post from myself then tag the thread as "mention"
1526 Logger::log("Checking if parent ".$parent_id." has to be tagged as mention for user ".$item['uid'], Logger::DEBUG);
1527 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $item['uid']]);
1528 if (DBA::isResult($user)) {
1529 $self = Strings::normaliseLink(System::baseUrl() . '/profile/' . $user['nickname']);
1530 $self_id = Contact::getIdForURL($self, 0, true);
1531 Logger::log("'myself' is ".$self_id." for parent ".$parent_id." checking against ".$item['author-id']." and ".$item['owner-id'], Logger::DEBUG);
1532 if (($item['author-id'] == $self_id) || ($item['owner-id'] == $self_id)) {
1533 DBA::update('thread', ['mention' => true], ['iid' => $parent_id]);
1534 Logger::log("tagged thread ".$parent_id." as mention for user ".$self, Logger::DEBUG);
1539 * Allow one to see reply tweets from status.net even when
1540 * we don't have or can't see the original post.
1542 if ($force_parent) {
1543 Logger::log('$force_parent=true, reply converted to top-level post.');
1545 $item['parent-uri'] = $item['uri'];
1546 $item['gravity'] = GRAVITY_PARENT;
1548 Logger::log('item parent '.$item['parent-uri'].' for '.$item['uid'].' was not found - ignoring item');
1552 $parent_deleted = 0;
1556 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
1557 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
1559 $condition = ["`uri` = ? AND `network` IN (?, ?) AND `uid` = ?",
1560 $item['uri'], $item['network'], Protocol::DFRN, $item['uid']];
1561 if (self::exists($condition)) {
1562 Logger::log('duplicated item with the same uri found. '.print_r($item,true));
1566 // On Friendica and Diaspora the GUID is unique
1567 if (in_array($item['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
1568 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
1569 if (self::exists($condition)) {
1570 Logger::log('duplicated item with the same guid found. '.print_r($item,true));
1574 // Check for an existing post with the same content. There seems to be a problem with OStatus.
1575 $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
1576 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
1577 if (self::exists($condition)) {
1578 Logger::log('duplicated item with the same body found. '.print_r($item,true));
1583 // Is this item available in the global items (with uid=0)?
1584 if ($item["uid"] == 0) {
1585 $item["global"] = true;
1587 // Set the global flag on all items if this was a global item entry
1588 self::update(['global' => true], ['uri' => $item["uri"]]);
1590 $item["global"] = self::exists(['uid' => 0, 'uri' => $item["uri"]]);
1594 if (strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid)) {
1597 $private = $item['private'];
1600 $item["allow_cid"] = $allow_cid;
1601 $item["allow_gid"] = $allow_gid;
1602 $item["deny_cid"] = $deny_cid;
1603 $item["deny_gid"] = $deny_gid;
1604 $item["private"] = $private;
1605 $item["deleted"] = $parent_deleted;
1607 // Fill the cache field
1608 self::putInCache($item);
1611 $item['edit'] = false;
1612 $item['parent'] = $parent_id;
1613 Hook::callAll('post_local', $item);
1614 unset($item['edit']);
1615 unset($item['parent']);
1617 Hook::callAll('post_remote', $item);
1620 // This array field is used to trigger some automatic reactions
1621 // It is mainly used in the "post_local" hook.
1622 unset($item['api_source']);
1624 if (!empty($item['cancel'])) {
1625 Logger::log('post cancelled by addon.');
1630 * Check for already added items.
1631 * There is a timing issue here that sometimes creates double postings.
1632 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
1634 if ($item["uid"] == 0) {
1635 if (self::exists(['uri' => trim($item['uri']), 'uid' => 0])) {
1636 Logger::log('Global item already stored. URI: '.$item['uri'].' on network '.$item['network'], Logger::DEBUG);
1641 Logger::log('' . print_r($item,true), Logger::DATA);
1643 if (array_key_exists('tag', $item)) {
1644 $tags = $item['tag'];
1645 unset($item['tag']);
1650 if (array_key_exists('file', $item)) {
1651 $files = $item['file'];
1652 unset($item['file']);
1657 // Creates or assigns the permission set
1658 $item['psid'] = PermissionSet::fetchIDForPost($item);
1660 // We are doing this outside of the transaction to avoid timing problems
1661 if (!self::insertActivity($item)) {
1662 self::insertContent($item);
1665 $delivery_data = ItemDeliveryData::extractFields($item);
1667 unset($item['postopts']);
1668 unset($item['inform']);
1670 // These fields aren't stored anymore in the item table, they are fetched upon request
1671 unset($item['author-link']);
1672 unset($item['author-name']);
1673 unset($item['author-avatar']);
1675 unset($item['owner-link']);
1676 unset($item['owner-name']);
1677 unset($item['owner-avatar']);
1680 $ret = DBA::insert('item', $item);
1682 // When the item was successfully stored we fetch the ID of the item.
1683 if (DBA::isResult($ret)) {
1684 $current_post = DBA::lastInsertId();
1686 // This can happen - for example - if there are locking timeouts.
1689 // Store the data into a spool file so that we can try again later.
1691 // At first we restore the Diaspora signature that we removed above.
1692 if (isset($encoded_signature)) {
1693 $item['dsprsig'] = $encoded_signature;
1696 // Now we store the data in the spool directory
1697 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
1698 $file = 'item-'.round(microtime(true) * 10000).'-'.mt_rand().'.msg';
1700 $spoolpath = get_spoolpath();
1701 if ($spoolpath != "") {
1702 $spool = $spoolpath.'/'.$file;
1704 file_put_contents($spool, json_encode($orig_item));
1705 Logger::log("Item wasn't stored - Item was spooled into file ".$file, Logger::DEBUG);
1710 if ($current_post == 0) {
1711 // This is one of these error messages that never should occur.
1712 Logger::log("couldn't find created item - we better quit now.");
1717 // How much entries have we created?
1718 // We wouldn't need this query when we could use an unique index - but MySQL has length problems with them.
1719 $entries = DBA::count('item', ['uri' => $item['uri'], 'uid' => $item['uid'], 'network' => $item['network']]);
1722 // There are duplicates. We delete our just created entry.
1723 Logger::log('Duplicated post occurred. uri = ' . $item['uri'] . ' uid = ' . $item['uid']);
1725 // Yes, we could do a rollback here - but we are having many users with MyISAM.
1726 DBA::delete('item', ['id' => $current_post]);
1729 } elseif ($entries == 0) {
1730 // This really should never happen since we quit earlier if there were problems.
1731 Logger::log("Something is terribly wrong. We haven't found our created entry.");
1736 Logger::log('created item '.$current_post);
1737 self::updateContact($item);
1739 if (!$parent_id || ($item['parent-uri'] === $item['uri'])) {
1740 $parent_id = $current_post;
1744 self::update(['parent' => $parent_id], ['id' => $current_post]);
1746 $item['id'] = $current_post;
1747 $item['parent'] = $parent_id;
1749 // update the commented timestamp on the parent
1750 // Only update "commented" if it is really a comment
1751 if (($item['gravity'] != GRAVITY_ACTIVITY) || !Config::get("system", "like_no_comment")) {
1752 self::update(['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1754 self::update(['changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1759 * Friendica servers lower than 3.4.3-2 had double encoded the signature ...
1760 * We can check for this condition when we decode and encode the stuff again.
1762 if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) {
1763 $dsprsig->signature = base64_decode($dsprsig->signature);
1764 Logger::log("Repaired double encoded signature from handle ".$dsprsig->signer, Logger::DEBUG);
1767 if (!empty($dsprsig->signed_text) && empty($dsprsig->signature) && empty($dsprsig->signer)) {
1768 DBA::insert('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $dsprsig->signed_text], true);
1770 // The other fields are used by very old Friendica servers, so we currently store them differently
1771 DBA::insert('sign', ['iid' => $current_post, 'signed_text' => $dsprsig->signed_text,
1772 'signature' => $dsprsig->signature, 'signer' => $dsprsig->signer]);
1776 if (!empty($diaspora_signed_text)) {
1777 DBA::insert('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $diaspora_signed_text], true);
1780 $deleted = self::tagDeliver($item['uid'], $current_post);
1783 * current post can be deleted if is for a community page and no mention are
1786 if (!$deleted && !$dontcache) {
1787 $posted_item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $current_post]);
1788 if (DBA::isResult($posted_item)) {
1790 Hook::callAll('post_local_end', $posted_item);
1792 Hook::callAll('post_remote_end', $posted_item);
1795 Logger::log('new item not found in DB, id ' . $current_post);
1799 if ($item['parent-uri'] === $item['uri']) {
1800 self::addThread($current_post);
1802 self::updateThread($parent_id);
1805 ItemDeliveryData::insert($current_post, $delivery_data);
1810 * Due to deadlock issues with the "term" table we are doing these steps after the commit.
1811 * This is not perfect - but a workable solution until we found the reason for the problem.
1813 if (!empty($tags)) {
1814 Term::insertFromTagFieldByItemId($current_post, $tags);
1817 if (!empty($files)) {
1818 Term::insertFromFileFieldByItemId($current_post, $files);
1821 if ($item['parent-uri'] === $item['uri']) {
1822 self::addShadow($current_post);
1824 self::addShadowPost($current_post);
1827 check_user_notification($current_post);
1830 Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', $notify_type, $current_post);
1831 } elseif ($item['visible'] && ((!empty($parent) && $parent['origin']) || $item['origin'])) {
1832 if ($item['gravity'] == GRAVITY_ACTIVITY) {
1833 $cmd = $item['origin'] ? 'activity-new' : 'activity-import';
1834 } elseif ($item['gravity'] == GRAVITY_COMMENT) {
1835 $cmd = $item['origin'] ? 'comment-new' : 'comment-import';
1840 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', $cmd, $current_post);
1843 return $current_post;
1847 * @brief Insert a new item content entry
1849 * @param array $item The item fields that are to be inserted
1852 private static function insertActivity(&$item)
1854 $activity_index = self::activityToIndex($item['verb']);
1856 if ($activity_index < 0) {
1860 $fields = ['activity' => $activity_index, 'uri-hash' => (string)$item['uri-id'], 'uri-id' => $item['uri-id']];
1862 // We just remove everything that is content
1863 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1864 unset($item[$field]);
1867 // To avoid timing problems, we are using locks.
1868 $locked = Lock::acquire('item_insert_activity');
1870 Logger::log("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
1873 // Do we already have this content?
1874 $item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-id' => $item['uri-id']]);
1875 if (DBA::isResult($item_activity)) {
1876 $item['iaid'] = $item_activity['id'];
1877 Logger::log('Fetched activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
1878 } elseif (DBA::insert('item-activity', $fields)) {
1879 $item['iaid'] = DBA::lastInsertId();
1880 Logger::log('Inserted activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
1882 // This shouldn't happen.
1883 Logger::log('Could not insert activity for URI ' . $item['uri'] . ' - should not happen');
1884 Lock::release('item_insert_activity');
1888 Lock::release('item_insert_activity');
1894 * @brief Insert a new item content entry
1896 * @param array $item The item fields that are to be inserted
1898 private static function insertContent(&$item)
1900 $fields = ['uri-plink-hash' => (string)$item['uri-id'], 'uri-id' => $item['uri-id']];
1902 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1903 if (isset($item[$field])) {
1904 $fields[$field] = $item[$field];
1905 unset($item[$field]);
1909 // To avoid timing problems, we are using locks.
1910 $locked = Lock::acquire('item_insert_content');
1912 Logger::log("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
1915 // Do we already have this content?
1916 $item_content = DBA::selectFirst('item-content', ['id'], ['uri-id' => $item['uri-id']]);
1917 if (DBA::isResult($item_content)) {
1918 $item['icid'] = $item_content['id'];
1919 Logger::log('Fetched content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
1920 } elseif (DBA::insert('item-content', $fields)) {
1921 $item['icid'] = DBA::lastInsertId();
1922 Logger::log('Inserted content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
1924 // This shouldn't happen.
1925 Logger::log('Could not insert content for URI ' . $item['uri'] . ' - should not happen');
1928 Lock::release('item_insert_content');
1933 * @brief Update existing item content entries
1935 * @param array $item The item fields that are to be changed
1936 * @param array $condition The condition for finding the item content entries
1938 private static function updateActivity($item, $condition)
1940 if (empty($item['verb'])) {
1943 $activity_index = self::activityToIndex($item['verb']);
1945 if ($activity_index < 0) {
1949 $fields = ['activity' => $activity_index];
1951 Logger::log('Update activity for ' . json_encode($condition));
1953 DBA::update('item-activity', $fields, $condition, true);
1959 * @brief Update existing item content entries
1961 * @param array $item The item fields that are to be changed
1962 * @param array $condition The condition for finding the item content entries
1964 private static function updateContent($item, $condition)
1966 // We have to select only the fields from the "item-content" table
1968 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1969 if (isset($item[$field])) {
1970 $fields[$field] = $item[$field];
1974 if (empty($fields)) {
1975 // when there are no fields at all, just use the condition
1976 // This is to ensure that we always store content.
1977 $fields = $condition;
1980 Logger::log('Update content for ' . json_encode($condition));
1982 DBA::update('item-content', $fields, $condition, true);
1986 * @brief Distributes public items to the receivers
1988 * @param integer $itemid Item ID that should be added
1989 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
1991 public static function distribute($itemid, $signed_text = '')
1993 $condition = ["`id` IN (SELECT `parent` FROM `item` WHERE `id` = ?)", $itemid];
1994 $parent = self::selectFirst(['owner-id'], $condition);
1995 if (!DBA::isResult($parent)) {
1999 // Only distribute public items from native networks
2000 $condition = ['id' => $itemid, 'uid' => 0,
2001 'network' => [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""],
2002 'visible' => true, 'deleted' => false, 'moderated' => false, 'private' => false];
2003 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2004 if (!DBA::isResult($item)) {
2008 $origin = $item['origin'];
2011 unset($item['parent']);
2012 unset($item['mention']);
2013 unset($item['wall']);
2014 unset($item['origin']);
2015 unset($item['starred']);
2019 /// @todo add a field "pcid" in the contact table that referrs to the public contact id.
2020 $owner = DBA::selectFirst('contact', ['url', 'nurl', 'alias'], ['id' => $parent['owner-id']]);
2021 if (!DBA::isResult($owner)) {
2025 $condition = ['nurl' => $owner['nurl'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2026 $contacts = DBA::select('contact', ['uid'], $condition);
2027 while ($contact = DBA::fetch($contacts)) {
2028 if ($contact['uid'] == 0) {
2032 $users[$contact['uid']] = $contact['uid'];
2034 DBA::close($contacts);
2036 $condition = ['alias' => $owner['url'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2037 $contacts = DBA::select('contact', ['uid'], $condition);
2038 while ($contact = DBA::fetch($contacts)) {
2039 if ($contact['uid'] == 0) {
2043 $users[$contact['uid']] = $contact['uid'];
2045 DBA::close($contacts);
2047 if (!empty($owner['alias'])) {
2048 $condition = ['url' => $owner['alias'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2049 $contacts = DBA::select('contact', ['uid'], $condition);
2050 while ($contact = DBA::fetch($contacts)) {
2051 if ($contact['uid'] == 0) {
2055 $users[$contact['uid']] = $contact['uid'];
2057 DBA::close($contacts);
2062 if ($item['uri'] != $item['parent-uri']) {
2063 $parents = self::select(['uid', 'origin'], ["`uri` = ? AND `uid` != 0", $item['parent-uri']]);
2064 while ($parent = self::fetch($parents)) {
2065 $users[$parent['uid']] = $parent['uid'];
2066 if ($parent['origin'] && !$origin) {
2067 $origin_uid = $parent['uid'];
2072 foreach ($users as $uid) {
2073 if ($origin_uid == $uid) {
2074 $item['diaspora_signed_text'] = $signed_text;
2076 self::storeForUser($itemid, $item, $uid);
2081 * @brief Store public items for the receivers
2083 * @param integer $itemid Item ID that should be added
2084 * @param array $item The item entry that will be stored
2085 * @param integer $uid The user that will receive the item entry
2087 private static function storeForUser($itemid, $item, $uid)
2089 $item['uid'] = $uid;
2090 $item['origin'] = 0;
2092 if ($item['uri'] == $item['parent-uri']) {
2093 $item['contact-id'] = Contact::getIdForURL($item['owner-link'], $uid);
2095 $item['contact-id'] = Contact::getIdForURL($item['author-link'], $uid);
2098 if (empty($item['contact-id'])) {
2099 $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $uid]);
2100 if (!DBA::isResult($self)) {
2103 $item['contact-id'] = $self['id'];
2106 /// @todo Handling of "event-id"
2109 if ($item['uri'] == $item['parent-uri']) {
2110 $contact = DBA::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
2111 if (DBA::isResult($contact)) {
2112 $notify = self::isRemoteSelf($contact, $item);
2116 $distributed = self::insert($item, false, $notify, true);
2118 if (!$distributed) {
2119 Logger::log("Distributed public item " . $itemid . " for user " . $uid . " wasn't stored", Logger::DEBUG);
2121 Logger::log("Distributed public item " . $itemid . " for user " . $uid . " with id " . $distributed, Logger::DEBUG);
2126 * @brief Add a shadow entry for a given item id that is a thread starter
2128 * We store every public item entry additionally with the user id "0".
2129 * This is used for the community page and for the search.
2130 * It is planned that in the future we will store public item entries only once.
2132 * @param integer $itemid Item ID that should be added
2134 public static function addShadow($itemid)
2136 $fields = ['uid', 'private', 'moderated', 'visible', 'deleted', 'network', 'uri'];
2137 $condition = ['id' => $itemid, 'parent' => [0, $itemid]];
2138 $item = self::selectFirst($fields, $condition);
2140 if (!DBA::isResult($item)) {
2144 // is it already a copy?
2145 if (($itemid == 0) || ($item['uid'] == 0)) {
2149 // Is it a visible public post?
2150 if (!$item["visible"] || $item["deleted"] || $item["moderated"] || $item["private"]) {
2154 // is it an entry from a connector? Only add an entry for natively connected networks
2155 if (!in_array($item["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""])) {
2159 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2163 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2165 if (DBA::isResult($item)) {
2166 // Preparing public shadow (removing user specific data)
2169 unset($item['parent']);
2170 unset($item['wall']);
2171 unset($item['mention']);
2172 unset($item['origin']);
2173 unset($item['starred']);
2174 unset($item['postopts']);
2175 unset($item['inform']);
2176 if ($item['uri'] == $item['parent-uri']) {
2177 $item['contact-id'] = $item['owner-id'];
2179 $item['contact-id'] = $item['author-id'];
2182 $public_shadow = self::insert($item, false, false, true);
2184 Logger::log("Stored public shadow for thread ".$itemid." under id ".$public_shadow, Logger::DEBUG);
2189 * @brief Add a shadow entry for a given item id that is a comment
2191 * This function does the same like the function above - but for comments
2193 * @param integer $itemid Item ID that should be added
2195 public static function addShadowPost($itemid)
2197 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2198 if (!DBA::isResult($item)) {
2202 // Is it a toplevel post?
2203 if ($item['id'] == $item['parent']) {
2204 self::addShadow($itemid);
2208 // Is this a shadow entry?
2209 if ($item['uid'] == 0) {
2213 // Is there a shadow parent?
2214 if (!self::exists(['uri' => $item['parent-uri'], 'uid' => 0])) {
2218 // Is there already a shadow entry?
2219 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2223 // Save "origin" and "parent" state
2224 $origin = $item['origin'];
2225 $parent = $item['parent'];
2227 // Preparing public shadow (removing user specific data)
2230 unset($item['parent']);
2231 unset($item['wall']);
2232 unset($item['mention']);
2233 unset($item['origin']);
2234 unset($item['starred']);
2235 unset($item['postopts']);
2236 unset($item['inform']);
2237 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
2239 $public_shadow = self::insert($item, false, false, true);
2241 Logger::log("Stored public shadow for comment ".$item['uri']." under id ".$public_shadow, Logger::DEBUG);
2243 // If this was a comment to a Diaspora post we don't get our comment back.
2244 // This means that we have to distribute the comment by ourselves.
2245 if ($origin && self::exists(['id' => $parent, 'network' => Protocol::DIASPORA])) {
2246 self::distribute($public_shadow);
2251 * Adds a language specification in a "language" element of given $arr.
2252 * Expects "body" element to exist in $arr.
2254 private static function addLanguageToItemArray(&$item)
2256 $naked_body = BBCode::toPlaintext($item['body'], false);
2258 $ld = new Text_LanguageDetect();
2259 $ld->setNameMode(2);
2260 $languages = $ld->detect($naked_body, 3);
2262 if (is_array($languages)) {
2263 $item['language'] = json_encode($languages);
2268 * @brief Creates an unique guid out of a given uri
2270 * @param string $uri uri of an item entry
2271 * @param string $host hostname for the GUID prefix
2272 * @return string unique guid
2274 public static function guidFromUri($uri, $host)
2276 // Our regular guid routine is using this kind of prefix as well
2277 // We have to avoid that different routines could accidentally create the same value
2278 $parsed = parse_url($uri);
2280 // We use a hash of the hostname as prefix for the guid
2281 $guid_prefix = hash("crc32", $host);
2283 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
2284 unset($parsed["scheme"]);
2286 // Glue it together to be able to make a hash from it
2287 $host_id = implode("/", $parsed);
2289 // We could use any hash algorithm since it isn't a security issue
2290 $host_hash = hash("ripemd128", $host_id);
2292 return $guid_prefix.$host_hash;
2296 * generate an unique URI
2298 * @param integer $uid User id
2299 * @param string $guid An existing GUID (Otherwise it will be generated)
2303 public static function newURI($uid, $guid = "")
2306 $guid = System::createUUID();
2309 return self::getApp()->getBaseURL() . '/objects/' . $guid;
2313 * @brief Set "success_update" and "last-item" to the date of the last time we heard from this contact
2315 * This can be used to filter for inactive contacts.
2316 * Only do this for public postings to avoid privacy problems, since poco data is public.
2317 * Don't set this value if it isn't from the owner (could be an author that we don't know)
2319 * @param array $arr Contains the just posted item record
2321 private static function updateContact($arr)
2323 // Unarchive the author
2324 $contact = DBA::selectFirst('contact', [], ['id' => $arr["author-id"]]);
2325 if (DBA::isResult($contact)) {
2326 Contact::unmarkForArchival($contact);
2329 // Unarchive the contact if it's not our own contact
2330 $contact = DBA::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
2331 if (DBA::isResult($contact)) {
2332 Contact::unmarkForArchival($contact);
2335 $update = (!$arr['private'] && ((defaults($arr, 'author-link', '') === defaults($arr, 'owner-link', '')) || ($arr["parent-uri"] === $arr["uri"])));
2337 // Is it a forum? Then we don't care about the rules from above
2338 if (!$update && in_array($arr["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN]) && ($arr["parent-uri"] === $arr["uri"])) {
2339 if (DBA::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
2345 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2346 ['id' => $arr['contact-id']]);
2348 // Now do the same for the system wide contacts with uid=0
2349 if (!$arr['private']) {
2350 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2351 ['id' => $arr['owner-id']]);
2353 if ($arr['owner-id'] != $arr['author-id']) {
2354 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2355 ['id' => $arr['author-id']]);
2360 public static function setHashtags(&$item)
2363 $tags = BBCode::getTags($item["body"]);
2366 if (!count($tags)) {
2370 // This sorting is important when there are hashtags that are part of other hashtags
2371 // Otherwise there could be problems with hashtags like #test and #test2
2374 $URLSearchString = "^\[\]";
2376 // All hashtags should point to the home server if "local_tags" is activated
2377 if (Config::get('system', 'local_tags')) {
2378 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2379 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["body"]);
2381 $item["tag"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2382 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["tag"]);
2385 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
2386 $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2388 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
2391 $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
2393 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
2396 $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
2398 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
2401 // Repair recursive urls
2402 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2403 "#$2", $item["body"]);
2405 foreach ($tags as $tag) {
2406 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=')) {
2410 $basetag = str_replace('_',' ',substr($tag,1));
2412 $newtag = '#[url=' . System::baseUrl() . '/search?tag=' . $basetag . ']' . $basetag . '[/url]';
2414 $item["body"] = str_replace($tag, $newtag, $item["body"]);
2416 if (!stristr($item["tag"], "/search?tag=" . $basetag . "]" . $basetag . "[/url]")) {
2417 if (strlen($item["tag"])) {
2418 $item["tag"] = ',' . $item["tag"];
2420 $item["tag"] = $newtag . $item["tag"];
2424 // Convert back the masked hashtags
2425 $item["body"] = str_replace("#", "#", $item["body"]);
2428 public static function getGuidById($id)
2430 $item = self::selectFirst(['guid'], ['id' => $id]);
2431 if (DBA::isResult($item)) {
2432 return $item['guid'];
2439 * This function is only used for the old Friendica app on Android that doesn't like paths with guid
2440 * @param string $guid item guid
2441 * @param int $uid user id
2442 * @return array with id and nick of the item with the given guid
2444 public static function getIdAndNickByGuid($guid, $uid = 0)
2450 $uid == local_user();
2453 // Does the given user have this item?
2455 $item = self::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
2456 if (DBA::isResult($item)) {
2457 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $uid]);
2458 if (!DBA::isResult($user)) {
2462 $nick = $user['nickname'];
2466 // Or is it anywhere on the server?
2468 $condition = ["`guid` = ? AND `uid` != 0", $guid];
2469 $item = self::selectFirst(['id', 'uid'], $condition);
2470 if (DBA::isResult($item)) {
2471 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $item['uid']]);
2472 if (!DBA::isResult($user)) {
2476 $nick = $user['nickname'];
2479 return ["nick" => $nick, "id" => $id];
2483 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
2485 * @param int $item_id
2486 * @return bool true if item was deleted, else false
2488 private static function tagDeliver($uid, $item_id)
2492 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
2493 if (!DBA::isResult($user)) {
2497 $community_page = (($user['page-flags'] == Contact::PAGE_COMMUNITY) ? true : false);
2498 $prvgroup = (($user['page-flags'] == Contact::PAGE_PRVGROUP) ? true : false);
2500 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2501 if (!DBA::isResult($item)) {
2505 $link = Strings::normaliseLink(System::baseUrl() . '/profile/' . $user['nickname']);
2508 * Diaspora uses their own hardwired link URL in @-tags
2509 * instead of the one we supply with webfinger
2511 $dlink = Strings::normaliseLink(System::baseUrl() . '/u/' . $user['nickname']);
2513 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
2515 foreach ($matches as $mtch) {
2516 if (Strings::compareLink($link, $mtch[1]) || Strings::compareLink($dlink, $mtch[1])) {
2518 Logger::log('mention found: ' . $mtch[2]);
2524 if (($community_page || $prvgroup) &&
2525 !$item['wall'] && !$item['origin'] && ($item['id'] == $item['parent'])) {
2526 // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
2528 Logger::log("no-mention top-level post to community or private group. delete.");
2529 DBA::delete('item', ['id' => $item_id]);
2535 $arr = ['item' => $item, 'user' => $user];
2537 Hook::callAll('tagged', $arr);
2539 if (!$community_page && !$prvgroup) {
2544 * tgroup delivery - setup a second delivery chain
2545 * prevent delivery looping - only proceed
2546 * if the message originated elsewhere and is a top-level post
2548 if ($item['wall'] || $item['origin'] || ($item['id'] != $item['parent'])) {
2552 // now change this copy of the post to a forum head message and deliver to all the tgroup members
2553 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'], ['uid' => $uid, 'self' => true]);
2554 if (!DBA::isResult($self)) {
2558 $owner_id = Contact::getIdForURL($self['url']);
2560 // also reset all the privacy bits to the forum default permissions
2562 $private = ($user['allow_cid'] || $user['allow_gid'] || $user['deny_cid'] || $user['deny_gid']) ? 1 : 0;
2564 $psid = PermissionSet::fetchIDForPost($user);
2566 $forum_mode = ($prvgroup ? 2 : 1);
2568 $fields = ['wall' => true, 'origin' => true, 'forum_mode' => $forum_mode, 'contact-id' => $self['id'],
2569 'owner-id' => $owner_id, 'private' => $private, 'psid' => $psid];
2570 self::update($fields, ['id' => $item_id]);
2572 self::updateThread($item_id);
2574 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', 'tgroup', $item_id);
2577 public static function isRemoteSelf($contact, &$datarray)
2581 if (!$contact['remote_self']) {
2585 // Prevent the forwarding of posts that are forwarded
2586 if (!empty($datarray["extid"]) && ($datarray["extid"] == Protocol::DFRN)) {
2587 Logger::log('Already forwarded', Logger::DEBUG);
2591 // Prevent to forward already forwarded posts
2592 if ($datarray["app"] == $a->getHostName()) {
2593 Logger::log('Already forwarded (second test)', Logger::DEBUG);
2597 // Only forward posts
2598 if ($datarray["verb"] != ACTIVITY_POST) {
2599 Logger::log('No post', Logger::DEBUG);
2603 if (($contact['network'] != Protocol::FEED) && $datarray['private']) {
2604 Logger::log('Not public', Logger::DEBUG);
2608 $datarray2 = $datarray;
2609 Logger::log('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), Logger::DEBUG);
2610 if ($contact['remote_self'] == 2) {
2611 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
2612 ['uid' => $contact['uid'], 'self' => true]);
2613 if (DBA::isResult($self)) {
2614 $datarray['contact-id'] = $self["id"];
2616 $datarray['owner-name'] = $self["name"];
2617 $datarray['owner-link'] = $self["url"];
2618 $datarray['owner-avatar'] = $self["thumb"];
2620 $datarray['author-name'] = $datarray['owner-name'];
2621 $datarray['author-link'] = $datarray['owner-link'];
2622 $datarray['author-avatar'] = $datarray['owner-avatar'];
2624 unset($datarray['created']);
2625 unset($datarray['edited']);
2627 unset($datarray['network']);
2628 unset($datarray['owner-id']);
2629 unset($datarray['author-id']);
2632 if ($contact['network'] != Protocol::FEED) {
2633 $datarray["guid"] = System::createUUID();
2634 unset($datarray["plink"]);
2635 $datarray["uri"] = self::newURI($contact['uid'], $datarray["guid"]);
2636 $datarray["parent-uri"] = $datarray["uri"];
2637 $datarray["thr-parent"] = $datarray["uri"];
2638 $datarray["extid"] = Protocol::DFRN;
2639 $urlpart = parse_url($datarray2['author-link']);
2640 $datarray["app"] = $urlpart["host"];
2642 $datarray['private'] = 0;
2646 if ($contact['network'] != Protocol::FEED) {
2647 // Store the original post
2648 $result = self::insert($datarray2, false, false);
2649 Logger::log('remote-self post original item - Contact '.$contact['url'].' return '.$result.' Item '.print_r($datarray2, true), Logger::DEBUG);
2651 $datarray["app"] = "Feed";
2655 // Trigger automatic reactions for addons
2656 $datarray['api_source'] = true;
2658 // We have to tell the hooks who we are - this really should be improved
2659 $_SESSION["authenticated"] = true;
2660 $_SESSION["uid"] = $contact['uid'];
2669 * @param array $item
2673 public static function fixPrivatePhotos($s, $uid, $item = null, $cid = 0)
2675 if (Config::get('system', 'disable_embedded')) {
2679 Logger::log('check for photos', Logger::DEBUG);
2680 $site = substr(System::baseUrl(), strpos(System::baseUrl(), '://'));
2685 $img_start = strpos($orig_body, '[img');
2686 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2687 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2689 while (($img_st_close !== false) && ($img_len !== false)) {
2690 $img_st_close++; // make it point to AFTER the closing bracket
2691 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2693 Logger::log('found photo ' . $image, Logger::DEBUG);
2695 if (stristr($image, $site . '/photo/')) {
2696 // Only embed locally hosted photos
2698 $i = basename($image);
2699 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2700 $x = strpos($i, '-');
2703 $res = substr($i, $x + 1);
2704 $i = substr($i, 0, $x);
2705 $photo = Photo::getPhotoForUser($uid, $i, $res);
2706 if (DBA::isResult($photo)) {
2708 * Check to see if we should replace this photo link with an embedded image
2709 * 1. No need to do so if the photo is public
2710 * 2. If there's a contact-id provided, see if they're in the access list
2711 * for the photo. If so, embed it.
2712 * 3. Otherwise, if we have an item, see if the item permissions match the photo
2713 * permissions, regardless of order but first check to see if they're an exact
2714 * match to save some processing overhead.
2716 if (self::hasPermissions($photo)) {
2718 $recips = self::enumeratePermissions($photo);
2719 if (in_array($cid, $recips)) {
2723 if (self::samePermissions($item, $photo)) {
2729 $photo_img = Photo::getImageForPhoto($photo);
2730 // If a custom width and height were specified, apply before embedding
2731 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2732 Logger::log('scaling photo', Logger::DEBUG);
2734 $width = intval($match[1]);
2735 $height = intval($match[2]);
2737 $photo_img->scaleDown(max($width, $height));
2740 $data = $photo_img->asString();
2741 $type = $photo_img->getType();
2743 Logger::log('replacing photo', Logger::DEBUG);
2744 $image = 'data:' . $type . ';base64,' . base64_encode($data);
2745 Logger::log('replaced: ' . $image, Logger::DATA);
2751 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2752 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2753 if ($orig_body === false) {
2757 $img_start = strpos($orig_body, '[img');
2758 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2759 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2762 $new_body = $new_body . $orig_body;
2767 private static function hasPermissions($obj)
2769 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2770 !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2773 private static function samePermissions($obj1, $obj2)
2775 // first part is easy. Check that these are exactly the same.
2776 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2777 && ($obj1['allow_gid'] == $obj2['allow_gid'])
2778 && ($obj1['deny_cid'] == $obj2['deny_cid'])
2779 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
2783 // This is harder. Parse all the permissions and compare the resulting set.
2784 $recipients1 = self::enumeratePermissions($obj1);
2785 $recipients2 = self::enumeratePermissions($obj2);
2789 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2790 return ($recipients1 == $recipients2);
2793 // returns an array of contact-ids that are allowed to see this object
2794 public static function enumeratePermissions($obj)
2796 $allow_people = expand_acl($obj['allow_cid']);
2797 $allow_groups = Group::expand(expand_acl($obj['allow_gid']));
2798 $deny_people = expand_acl($obj['deny_cid']);
2799 $deny_groups = Group::expand(expand_acl($obj['deny_gid']));
2800 $recipients = array_unique(array_merge($allow_people, $allow_groups));
2801 $deny = array_unique(array_merge($deny_people, $deny_groups));
2802 $recipients = array_diff($recipients, $deny);
2806 public static function getFeedTags($item)
2810 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2812 for ($x = 0; $x < $cnt; $x ++) {
2813 if ($matches[1][$x]) {
2814 $ret[$matches[2][$x]] = ['#', $matches[1][$x], $matches[2][$x]];
2819 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2821 for ($x = 0; $x < $cnt; $x ++) {
2822 if ($matches[1][$x]) {
2823 $ret[] = ['@', $matches[1][$x], $matches[2][$x]];
2830 public static function expire($uid, $days, $network = "", $force = false)
2832 if (!$uid || ($days < 1)) {
2836 $condition = ["`uid` = ? AND NOT `deleted` AND `id` = `parent` AND `gravity` = ?",
2837 $uid, GRAVITY_PARENT];
2840 * $expire_network_only = save your own wall posts
2841 * and just expire conversations started by others
2843 $expire_network_only = PConfig::get($uid, 'expire', 'network_only', false);
2845 if ($expire_network_only) {
2846 $condition[0] .= " AND NOT `wall`";
2849 if ($network != "") {
2850 $condition[0] .= " AND `network` = ?";
2851 $condition[] = $network;
2854 * There is an index "uid_network_received" but not "uid_network_created"
2855 * This avoids the creation of another index just for one purpose.
2856 * And it doesn't really matter wether to look at "received" or "created"
2858 $condition[0] .= " AND `received` < UTC_TIMESTAMP() - INTERVAL ? DAY";
2859 $condition[] = $days;
2861 $condition[0] .= " AND `created` < UTC_TIMESTAMP() - INTERVAL ? DAY";
2862 $condition[] = $days;
2865 $items = self::select(['file', 'resource-id', 'starred', 'type', 'id', 'post-type'], $condition);
2867 if (!DBA::isResult($items)) {
2871 $expire_items = PConfig::get($uid, 'expire', 'items', true);
2873 // Forcing expiring of items - but not notes and marked items
2875 $expire_items = true;
2878 $expire_notes = PConfig::get($uid, 'expire', 'notes', true);
2879 $expire_starred = PConfig::get($uid, 'expire', 'starred', true);
2880 $expire_photos = PConfig::get($uid, 'expire', 'photos', false);
2884 while ($item = Item::fetch($items)) {
2885 // don't expire filed items
2887 if (strpos($item['file'], '[') !== false) {
2891 // Only expire posts, not photos and photo comments
2893 if (!$expire_photos && strlen($item['resource-id'])) {
2895 } elseif (!$expire_starred && intval($item['starred'])) {
2897 } elseif (!$expire_notes && (($item['type'] == 'note') || ($item['post-type'] == Item::PT_PERSONAL_NOTE))) {
2899 } elseif (!$expire_items && ($item['type'] != 'note') && ($item['post-type'] != Item::PT_PERSONAL_NOTE)) {
2903 self::deleteById($item['id'], PRIORITY_LOW);
2908 Logger::log('User ' . $uid . ": expired $expired items; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
2911 public static function firstPostDate($uid, $wall = false)
2913 $condition = ['uid' => $uid, 'wall' => $wall, 'deleted' => false, 'visible' => true, 'moderated' => false];
2914 $params = ['order' => ['created' => false]];
2915 $thread = DBA::selectFirst('thread', ['created'], $condition, $params);
2916 if (DBA::isResult($thread)) {
2917 return substr(DateTimeFormat::local($thread['created']), 0, 10);
2923 * @brief add/remove activity to an item
2925 * Toggle activities as like,dislike,attend of an item
2927 * @param string $item_id
2928 * @param string $verb
2929 * Activity verb. One of
2930 * like, unlike, dislike, undislike, attendyes, unattendyes,
2931 * attendno, unattendno, attendmaybe, unattendmaybe
2932 * @hook 'post_local_end'
2934 * 'post_id' => ID of posted item
2936 public static function performLike($item_id, $verb)
2938 if (!local_user() && !remote_user()) {
2945 $activity = ACTIVITY_LIKE;
2949 $activity = ACTIVITY_DISLIKE;
2953 $activity = ACTIVITY_ATTEND;
2957 $activity = ACTIVITY_ATTENDNO;
2960 case 'unattendmaybe':
2961 $activity = ACTIVITY_ATTENDMAYBE;
2964 Logger::log('like: unknown verb ' . $verb . ' for item ' . $item_id);
2968 // Enable activity toggling instead of on/off
2969 $event_verb_flag = $activity === ACTIVITY_ATTEND || $activity === ACTIVITY_ATTENDNO || $activity === ACTIVITY_ATTENDMAYBE;
2971 Logger::log('like: verb ' . $verb . ' item ' . $item_id);
2973 $item = self::selectFirst(self::ITEM_FIELDLIST, ['`id` = ? OR `uri` = ?', $item_id, $item_id]);
2974 if (!DBA::isResult($item)) {
2975 Logger::log('like: unknown item ' . $item_id);
2979 $item_uri = $item['uri'];
2981 $uid = $item['uid'];
2982 if (($uid == 0) && local_user()) {
2983 $uid = local_user();
2986 if (!Security::canWriteToUserWall($uid)) {
2987 Logger::log('like: unable to write on wall ' . $uid);
2991 // Retrieves the local post owner
2992 $owner_self_contact = DBA::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
2993 if (!DBA::isResult($owner_self_contact)) {
2994 Logger::log('like: unknown owner ' . $uid);
2998 // Retrieve the current logged in user's public contact
2999 $author_id = public_contact();
3001 $author_contact = DBA::selectFirst('contact', ['url'], ['id' => $author_id]);
3002 if (!DBA::isResult($author_contact)) {
3003 Logger::log('like: unknown author ' . $author_id);
3007 // Contact-id is the uid-dependant author contact
3008 if (local_user() == $uid) {
3009 $item_contact_id = $owner_self_contact['id'];
3010 $item_contact = $owner_self_contact;
3012 $item_contact_id = Contact::getIdForURL($author_contact['url'], $uid, true);
3013 $item_contact = DBA::selectFirst('contact', [], ['id' => $item_contact_id]);
3014 if (!DBA::isResult($item_contact)) {
3015 Logger::log('like: unknown item contact ' . $item_contact_id);
3020 // Look for an existing verb row
3021 // event participation are essentially radio toggles. If you make a subsequent choice,
3022 // we need to eradicate your first choice.
3023 if ($event_verb_flag) {
3024 $verbs = [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE];
3026 // Translate to the index based activity index
3028 foreach ($verbs as $verb) {
3029 $activities[] = self::activityToIndex($verb);
3032 $activities = self::activityToIndex($activity);
3035 $condition = ['activity' => $activities, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY,
3036 'author-id' => $author_id, 'uid' => $item['uid'], 'thr-parent' => $item_uri];
3038 $like_item = self::selectFirst(['id', 'guid', 'verb'], $condition);
3040 // If it exists, mark it as deleted
3041 if (DBA::isResult($like_item)) {
3042 self::deleteById($like_item['id']);
3044 if (!$event_verb_flag || $like_item['verb'] == $activity) {
3049 // Verb is "un-something", just trying to delete existing entries
3050 if (strpos($verb, 'un') === 0) {
3054 $objtype = $item['resource-id'] ? ACTIVITY_OBJ_IMAGE : ACTIVITY_OBJ_NOTE;
3057 'guid' => System::createUUID(),
3058 'uri' => self::newURI($item['uid']),
3059 'uid' => $item['uid'],
3060 'contact-id' => $item_contact_id,
3061 'wall' => $item['wall'],
3063 'network' => Protocol::DFRN,
3064 'gravity' => GRAVITY_ACTIVITY,
3065 'parent' => $item['id'],
3066 'parent-uri' => $item['uri'],
3067 'thr-parent' => $item['uri'],
3068 'owner-id' => $author_id,
3069 'author-id' => $author_id,
3070 'body' => $activity,
3071 'verb' => $activity,
3072 'object-type' => $objtype,
3073 'allow_cid' => $item['allow_cid'],
3074 'allow_gid' => $item['allow_gid'],
3075 'deny_cid' => $item['deny_cid'],
3076 'deny_gid' => $item['deny_gid'],
3081 $signed = Diaspora::createLikeSignature($uid, $new_item);
3082 if (!empty($signed)) {
3083 $new_item['diaspora_signed_text'] = json_encode($signed);
3086 $new_item_id = self::insert($new_item);
3088 // If the parent item isn't visible then set it to visible
3089 if (!$item['visible']) {
3090 self::update(['visible' => true], ['id' => $item['id']]);
3093 $new_item['id'] = $new_item_id;
3095 Hook::callAll('post_local_end', $new_item);
3100 private static function addThread($itemid, $onlyshadow = false)
3102 $fields = ['uid', 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private', 'pubmail',
3103 'moderated', 'visible', 'starred', 'contact-id', 'post-type',
3104 'deleted', 'origin', 'forum_mode', 'mention', 'network', 'author-id', 'owner-id'];
3105 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
3106 $item = self::selectFirst($fields, $condition);
3108 if (!DBA::isResult($item)) {
3112 $item['iid'] = $itemid;
3115 $result = DBA::insert('thread', $item);
3117 Logger::log("Add thread for item ".$itemid." - ".print_r($result, true), Logger::DEBUG);
3121 private static function updateThread($itemid, $setmention = false)
3123 $fields = ['uid', 'guid', 'created', 'edited', 'commented', 'received', 'changed', 'post-type',
3124 'wall', 'private', 'pubmail', 'moderated', 'visible', 'starred', 'contact-id',
3125 'deleted', 'origin', 'forum_mode', 'network', 'author-id', 'owner-id'];
3126 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
3128 $item = self::selectFirst($fields, $condition);
3129 if (!DBA::isResult($item)) {
3134 $item["mention"] = 1;
3141 foreach ($item as $field => $data) {
3142 if (!in_array($field, ["guid"])) {
3143 $fields[$field] = $data;
3147 $result = DBA::update('thread', $fields, ['iid' => $itemid]);
3149 Logger::log("Update thread for item ".$itemid." - guid ".$item["guid"]." - ".(int)$result, Logger::DEBUG);
3152 private static function deleteThread($itemid, $itemuri = "")
3154 $item = DBA::selectFirst('thread', ['uid'], ['iid' => $itemid]);
3155 if (!DBA::isResult($item)) {
3156 Logger::log('No thread found for id '.$itemid, Logger::DEBUG);
3160 $result = DBA::delete('thread', ['iid' => $itemid], ['cascade' => false]);
3162 Logger::log("deleteThread: Deleted thread for item ".$itemid." - ".print_r($result, true), Logger::DEBUG);
3164 if ($itemuri != "") {
3165 $condition = ["`uri` = ? AND NOT `deleted` AND NOT (`uid` IN (?, 0))", $itemuri, $item["uid"]];
3166 if (!self::exists($condition)) {
3167 DBA::delete('item', ['uri' => $itemuri, 'uid' => 0]);
3168 Logger::log("deleteThread: Deleted shadow for item ".$itemuri, Logger::DEBUG);
3173 public static function getPermissionsSQLByUserId($owner_id, $remote_verified = false, $groups = null, $remote_cid = null)
3175 $local_user = local_user();
3176 $remote_user = remote_user();
3179 * Construct permissions
3181 * default permissions - anonymous user
3183 $sql = " AND NOT `item`.`private`";
3185 // Profile owner - everything is visible
3186 if ($local_user && ($local_user == $owner_id)) {
3188 } elseif ($remote_user) {
3190 * Authenticated visitor. Unless pre-verified,
3191 * check that the contact belongs to this $owner_id
3192 * and load the groups the visitor belongs to.
3193 * If pre-verified, the caller is expected to have already
3194 * done this and passed the groups into this function.
3196 $set = PermissionSet::get($owner_id, $remote_cid, $groups);
3199 $sql_set = " OR (`item`.`private` IN (1,2) AND `item`.`wall` AND `item`.`psid` IN (" . implode(',', $set) . "))";
3204 $sql = " AND (NOT `item`.`private`" . $sql_set . ")";
3211 * get translated item type
3213 * @param array $itme
3216 public static function postType($item)
3218 if (!empty($item['event-id'])) {
3219 return L10n::t('event');
3220 } elseif (!empty($item['resource-id'])) {
3221 return L10n::t('photo');
3222 } elseif (!empty($item['verb']) && $item['verb'] !== ACTIVITY_POST) {
3223 return L10n::t('activity');
3224 } elseif ($item['id'] != $item['parent']) {
3225 return L10n::t('comment');
3228 return L10n::t('post');
3232 * Sets the "rendered-html" field of the provided item
3234 * Body is preserved to avoid side-effects as we modify it just-in-time for spoilers and private image links
3236 * @param array $item
3237 * @param bool $update
3239 * @todo Remove reference, simply return "rendered-html" and "rendered-hash"
3241 public static function putInCache(&$item, $update = false)
3243 $body = $item["body"];
3245 $rendered_hash = defaults($item, 'rendered-hash', '');
3246 $rendered_html = defaults($item, 'rendered-html', '');
3248 if ($rendered_hash == ''
3249 || $rendered_html == ""
3250 || $rendered_hash != hash("md5", $item["body"])
3251 || Config::get("system", "ignore_cache")
3253 $a = self::getApp();
3254 redir_private_images($a, $item);
3256 $item["rendered-html"] = prepare_text($item["body"]);
3257 $item["rendered-hash"] = hash("md5", $item["body"]);
3259 $hook_data = ['item' => $item, 'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']];
3260 Hook::callAll('put_item_in_cache', $hook_data);
3261 $item['rendered-html'] = $hook_data['rendered-html'];
3262 $item['rendered-hash'] = $hook_data['rendered-hash'];
3265 // Force an update if the generated values differ from the existing ones
3266 if ($rendered_hash != $item["rendered-hash"]) {
3270 // Only compare the HTML when we forcefully ignore the cache
3271 if (Config::get("system", "ignore_cache") && ($rendered_html != $item["rendered-html"])) {
3275 if ($update && !empty($item["id"])) {
3278 'rendered-html' => $item["rendered-html"],
3279 'rendered-hash' => $item["rendered-hash"]
3281 ['id' => $item["id"]]
3286 $item["body"] = $body;
3290 * @brief Given an item array, convert the body element from bbcode to html and add smilie icons.
3291 * If attach is true, also add icons for item attachments.
3293 * @param array $item
3294 * @param boolean $attach
3295 * @param boolean $is_preview
3296 * @return string item body html
3297 * @hook prepare_body_init item array before any work
3298 * @hook prepare_body_content_filter ('item'=>item array, 'filter_reasons'=>string array) before first bbcode to html
3299 * @hook prepare_body ('item'=>item array, 'html'=>body string, 'is_preview'=>boolean, 'filter_reasons'=>string array) after first bbcode to html
3300 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
3302 public static function prepareBody(array &$item, $attach = false, $is_preview = false)
3304 $a = self::getApp();
3305 Hook::callAll('prepare_body_init', $item);
3307 // In order to provide theme developers more possibilities, event items
3308 // are treated differently.
3309 if ($item['object-type'] === ACTIVITY_OBJ_EVENT && isset($item['event-id'])) {
3310 $ev = Event::getItemHTML($item);
3314 $tags = Term::populateTagsFromItem($item);
3316 $item['tags'] = $tags['tags'];
3317 $item['hashtags'] = $tags['hashtags'];
3318 $item['mentions'] = $tags['mentions'];
3320 // Compile eventual content filter reasons
3321 $filter_reasons = [];
3322 if (!$is_preview && public_contact() != $item['author-id']) {
3323 if (!empty($item['content-warning']) && (!local_user() || !PConfig::get(local_user(), 'system', 'disable_cw', false))) {
3324 $filter_reasons[] = L10n::t('Content warning: %s', $item['content-warning']);
3329 'filter_reasons' => $filter_reasons
3331 Hook::callAll('prepare_body_content_filter', $hook_data);
3332 $filter_reasons = $hook_data['filter_reasons'];
3336 // Update the cached values if there is no "zrl=..." on the links.
3337 $update = (!local_user() && !remote_user() && ($item["uid"] == 0));
3339 // Or update it if the current viewer is the intented viewer.
3340 if (($item["uid"] == local_user()) && ($item["uid"] != 0)) {
3344 self::putInCache($item, $update);
3345 $s = $item["rendered-html"];
3350 'preview' => $is_preview,
3351 'filter_reasons' => $filter_reasons
3353 Hook::callAll('prepare_body', $hook_data);
3354 $s = $hook_data['html'];
3358 // Replace the blockquotes with quotes that are used in mails.
3359 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
3360 $s = str_replace(['<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'], [$mailquote, $mailquote, $mailquote], $s);
3367 preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\"(?: title=\"(.*?)\")?|', $item['attach'], $matches, PREG_SET_ORDER);
3368 foreach ($matches as $mtch) {
3371 $the_url = Contact::magicLinkById($item['author-id'], $mtch[1]);
3373 if (strpos($mime, 'video') !== false) {
3376 $a->page['htmlhead'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate('videos_head.tpl'), [
3377 '$baseurl' => System::baseUrl(),
3381 $url_parts = explode('/', $the_url);
3382 $id = end($url_parts);
3383 $as .= Renderer::replaceMacros(Renderer::getMarkupTemplate('video_top.tpl'), [
3386 'title' => L10n::t('View Video'),
3393 $filetype = strtolower(substr($mime, 0, strpos($mime, '/')));
3395 $filesubtype = strtolower(substr($mime, strpos($mime, '/') + 1));
3396 $filesubtype = str_replace('.', '-', $filesubtype);
3399 $filesubtype = 'unkn';
3402 $title = Strings::escapeHtml(trim(defaults($mtch, 4, $mtch[1])));
3403 $title .= ' ' . $mtch[2] . ' ' . L10n::t('bytes');
3405 $icon = '<div class="attachtype icon s22 type-' . $filetype . ' subtype-' . $filesubtype . '"></div>';
3406 $as .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" >' . $icon . '</a>';
3410 $s .= '<div class="body-attach">'.$as.'<div class="clear"></div></div>';
3414 if (strpos($s, '<div class="map">') !== false && !empty($item['coord'])) {
3415 $x = Map::byCoordinates(trim($item['coord']));
3417 $s = preg_replace('/\<div class\=\"map\"\>/', '$0' . $x, $s);
3422 // Look for spoiler.
3423 $spoilersearch = '<blockquote class="spoiler">';
3425 // Remove line breaks before the spoiler.
3426 while ((strpos($s, "\n" . $spoilersearch) !== false)) {
3427 $s = str_replace("\n" . $spoilersearch, $spoilersearch, $s);
3429 while ((strpos($s, "<br />" . $spoilersearch) !== false)) {
3430 $s = str_replace("<br />" . $spoilersearch, $spoilersearch, $s);
3433 while ((strpos($s, $spoilersearch) !== false)) {
3434 $pos = strpos($s, $spoilersearch);
3435 $rnd = Strings::getRandomHex(8);
3436 $spoilerreplace = '<br /> <span id="spoiler-wrap-' . $rnd . '" class="spoiler-wrap fakelink" onclick="openClose(\'spoiler-' . $rnd . '\');">' . L10n::t('Click to open/close') . '</span>'.
3437 '<blockquote class="spoiler" id="spoiler-' . $rnd . '" style="display: none;">';
3438 $s = substr($s, 0, $pos) . $spoilerreplace . substr($s, $pos + strlen($spoilersearch));
3441 // Look for quote with author.
3442 $authorsearch = '<blockquote class="author">';
3444 while ((strpos($s, $authorsearch) !== false)) {
3445 $pos = strpos($s, $authorsearch);
3446 $rnd = Strings::getRandomHex(8);
3447 $authorreplace = '<br /> <span id="author-wrap-' . $rnd . '" class="author-wrap fakelink" onclick="openClose(\'author-' . $rnd . '\');">' . L10n::t('Click to open/close') . '</span>'.
3448 '<blockquote class="author" id="author-' . $rnd . '" style="display: block;">';
3449 $s = substr($s, 0, $pos) . $authorreplace . substr($s, $pos + strlen($authorsearch));
3452 // Replace friendica image url size with theme preference.
3453 if (!empty($a->theme_info['item_image_size'])) {
3454 $ps = $a->theme_info['item_image_size'];
3455 $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
3458 $s = HTML::applyContentFilter($s, $filter_reasons);
3460 $hook_data = ['item' => $item, 'html' => $s];
3461 Hook::callAll('prepare_body_final', $hook_data);
3463 return $hook_data['html'];
3467 * get private link for item
3468 * @param array $item
3469 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
3471 public static function getPlink($item)
3473 $a = self::getApp();
3475 if ($a->user['nickname'] != "") {
3477 'href' => "display/" . $item['guid'],
3478 'orig' => "display/" . $item['guid'],
3479 'title' => L10n::t('View on separate page'),
3480 'orig_title' => L10n::t('view on separate page'),
3483 if (!empty($item['plink'])) {
3484 $ret["href"] = $a->removeBaseURL($item['plink']);
3485 $ret["title"] = L10n::t('link to source');
3488 } elseif (!empty($item['plink']) && ($item['private'] != 1)) {
3490 'href' => $item['plink'],
3491 'orig' => $item['plink'],
3492 'title' => L10n::t('link to source'),