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\Addon;
13 use Friendica\Core\Config;
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\Object\Image;
30 use Friendica\Protocol\Diaspora;
31 use Friendica\Protocol\OStatus;
32 use Friendica\Util\DateTimeFormat;
33 use Friendica\Util\Map;
34 use Friendica\Util\XML;
35 use Friendica\Util\Security;
36 use Friendica\Util\Strings;
37 use Text_LanguageDetect;
39 require_once 'boot.php';
40 require_once 'include/items.php';
41 require_once 'include/text.php';
43 class Item extends BaseObject
45 // Posting types, inspired by https://www.w3.org/TR/activitystreams-vocabulary/#object-types
52 const PT_DOCUMENT = 19;
54 const PT_PERSONAL_NOTE = 128;
56 // Field list that is used to display the items
57 const DISPLAY_FIELDLIST = ['uid', 'id', 'parent', 'uri', 'thr-parent', 'parent-uri', 'guid', 'network',
58 'commented', 'created', 'edited', 'received', 'verb', 'object-type', 'postopts', 'plink',
59 'wall', 'private', 'starred', 'origin', 'title', 'body', 'file', 'attach', 'language',
60 'content-warning', 'location', 'coord', 'app', 'rendered-hash', 'rendered-html', 'object',
61 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'item_id',
62 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
63 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'owner-network',
64 'contact-id', 'contact-link', 'contact-name', 'contact-avatar',
65 'writable', 'self', 'cid', 'alias',
66 'event-id', 'event-created', 'event-edited', 'event-start', 'event-finish',
67 'event-summary', 'event-desc', 'event-location', 'event-type',
68 'event-nofinish', 'event-adjust', 'event-ignore', 'event-id'];
70 // Field list that is used to deliver items via the protocols
71 const DELIVER_FIELDLIST = ['uid', 'id', 'parent', 'uri', 'thr-parent', 'parent-uri', 'guid',
72 'created', 'edited', 'verb', 'object-type', 'object', 'target',
73 'private', 'title', 'body', 'location', 'coord', 'app',
74 'attach', 'tag', 'deleted', 'extid', 'post-type',
75 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
76 'author-id', 'author-link', 'owner-link', 'contact-uid',
77 'signed_text', 'signature', 'signer', 'network'];
79 // Field list for "item-content" table that is mixed with the item table
80 const MIXED_CONTENT_FIELDLIST = ['title', 'content-warning', 'body', 'location',
81 'coord', 'app', 'rendered-hash', 'rendered-html', 'verb',
82 'object-type', 'object', 'target-type', 'target', 'plink'];
84 // Field list for "item-content" table that is not present in the "item" table
85 const CONTENT_FIELDLIST = ['language'];
87 // Field list for additional delivery data
88 const DELIVERY_DATA_FIELDLIST = ['postopts', 'inform'];
90 // All fields in the item table
91 const ITEM_FIELDLIST = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
92 'contact-id', 'type', 'wall', 'gravity', 'extid', 'icid', 'iaid', 'psid',
93 'created', 'edited', 'commented', 'received', 'changed', 'verb',
94 'postopts', 'plink', 'resource-id', 'event-id', 'tag', 'attach', 'inform',
95 'file', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'post-type',
96 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
97 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global', 'network',
98 'title', 'content-warning', 'body', 'location', 'coord', 'app',
99 'rendered-hash', 'rendered-html', 'object-type', 'object', 'target-type', 'target',
100 'author-id', 'author-link', 'author-name', 'author-avatar',
101 'owner-id', 'owner-link', 'owner-name', 'owner-avatar'];
103 // Never reorder or remove entries from this list. Just add new ones at the end, if needed.
104 // The item-activity table only stores the index and needs this array to know the matching activity.
105 const ACTIVITIES = [ACTIVITY_LIKE, ACTIVITY_DISLIKE, ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE];
107 private static $legacy_mode = null;
109 public static function isLegacyMode()
111 if (is_null(self::$legacy_mode)) {
112 self::$legacy_mode = (Config::get("system", "post_update_version") < 1279);
115 return self::$legacy_mode;
119 * @brief returns an activity index from an activity string
121 * @param string $activity activity string
122 * @return integer Activity index
124 public static function activityToIndex($activity)
126 $index = array_search($activity, self::ACTIVITIES);
128 if (is_bool($index)) {
136 * @brief returns an activity string from an activity index
138 * @param integer $index activity index
139 * @return string Activity string
141 private static function indexToActivity($index)
143 if (is_null($index) || !array_key_exists($index, self::ACTIVITIES)) {
147 return self::ACTIVITIES[$index];
151 * @brief Fetch a single item row
153 * @param mixed $stmt statement object
154 * @return array current row
156 public static function fetch($stmt)
158 $row = DBA::fetch($stmt);
164 // ---------------------- Transform item structure data ----------------------
166 // We prefer the data from the user's contact over the public one
167 if (!empty($row['author-link']) && !empty($row['contact-link']) &&
168 ($row['author-link'] == $row['contact-link'])) {
169 if (isset($row['author-avatar']) && !empty($row['contact-avatar'])) {
170 $row['author-avatar'] = $row['contact-avatar'];
172 if (isset($row['author-name']) && !empty($row['contact-name'])) {
173 $row['author-name'] = $row['contact-name'];
177 if (!empty($row['owner-link']) && !empty($row['contact-link']) &&
178 ($row['owner-link'] == $row['contact-link'])) {
179 if (isset($row['owner-avatar']) && !empty($row['contact-avatar'])) {
180 $row['owner-avatar'] = $row['contact-avatar'];
182 if (isset($row['owner-name']) && !empty($row['contact-name'])) {
183 $row['owner-name'] = $row['contact-name'];
187 // We can always comment on posts from these networks
188 if (array_key_exists('writable', $row) &&
189 in_array($row['internal-network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])) {
190 $row['writable'] = true;
193 // ---------------------- Transform item content data ----------------------
195 // Fetch data from the item-content table whenever there is content there
196 if (self::isLegacyMode()) {
197 $legacy_fields = array_merge(self::DELIVERY_DATA_FIELDLIST, self::MIXED_CONTENT_FIELDLIST);
198 foreach ($legacy_fields as $field) {
199 if (empty($row[$field]) && !empty($row['internal-item-' . $field])) {
200 $row[$field] = $row['internal-item-' . $field];
202 unset($row['internal-item-' . $field]);
206 if (!empty($row['internal-iaid']) && array_key_exists('verb', $row)) {
207 $row['verb'] = self::indexToActivity($row['internal-activity']);
208 if (array_key_exists('title', $row)) {
211 if (array_key_exists('body', $row)) {
212 $row['body'] = $row['verb'];
214 if (array_key_exists('object', $row)) {
217 if (array_key_exists('object-type', $row)) {
218 $row['object-type'] = ACTIVITY_OBJ_NOTE;
220 } elseif (array_key_exists('verb', $row) && in_array($row['verb'], ['', ACTIVITY_POST, ACTIVITY_SHARE])) {
221 // Posts don't have an object or target - but having tags or files.
222 // We safe some performance by building tag and file strings only here.
223 // We remove object and target since they aren't used for this type.
224 if (array_key_exists('object', $row)) {
227 if (array_key_exists('target', $row)) {
232 if (!array_key_exists('verb', $row) || in_array($row['verb'], ['', ACTIVITY_POST, ACTIVITY_SHARE])) {
233 // Build the tag string out of the term entries
234 if (array_key_exists('tag', $row) && empty($row['tag'])) {
235 $row['tag'] = Term::tagTextFromItemId($row['internal-iid']);
238 // Build the file string out of the term entries
239 if (array_key_exists('file', $row) && empty($row['file'])) {
240 $row['file'] = Term::fileTextFromItemId($row['internal-iid']);
244 if (array_key_exists('signed_text', $row) && array_key_exists('interaction', $row) && !is_null($row['interaction'])) {
245 $row['signed_text'] = $row['interaction'];
248 if (array_key_exists('ignored', $row) && array_key_exists('internal-user-ignored', $row) && !is_null($row['internal-user-ignored'])) {
249 $row['ignored'] = $row['internal-user-ignored'];
252 // Remove internal fields
253 unset($row['internal-activity']);
254 unset($row['internal-network']);
255 unset($row['internal-iid']);
256 unset($row['internal-iaid']);
257 unset($row['internal-icid']);
258 unset($row['internal-user-ignored']);
259 unset($row['interaction']);
265 * @brief Fills an array with data from an item query
267 * @param object $stmt statement object
268 * @return array Data array
270 public static function inArray($stmt, $do_close = true) {
271 if (is_bool($stmt)) {
276 while ($row = self::fetch($stmt)) {
286 * @brief Check if item data exists
288 * @param array $condition array of fields for condition
290 * @return boolean Are there rows for that condition?
292 public static function exists($condition) {
293 $stmt = self::select(['id'], $condition, ['limit' => 1]);
295 if (is_bool($stmt)) {
298 $retval = (DBA::numRows($stmt) > 0);
307 * Retrieve a single record from the item table for a given user and returns it in an associative array
309 * @brief Retrieve a single record from a table
310 * @param integer $uid User ID
311 * @param array $fields
312 * @param array $condition
313 * @param array $params
317 public static function selectFirstForUser($uid, array $selected = [], array $condition = [], $params = [])
319 $params['uid'] = $uid;
321 if (empty($selected)) {
322 $selected = Item::DISPLAY_FIELDLIST;
325 return self::selectFirst($selected, $condition, $params);
329 * @brief Select rows from the item table for a given user
331 * @param integer $uid User ID
332 * @param array $selected Array of selected fields, empty for all
333 * @param array $condition Array of fields for condition
334 * @param array $params Array of several parameters
336 * @return boolean|object
338 public static function selectForUser($uid, array $selected = [], array $condition = [], $params = [])
340 $params['uid'] = $uid;
342 if (empty($selected)) {
343 $selected = Item::DISPLAY_FIELDLIST;
346 return self::select($selected, $condition, $params);
350 * Retrieve a single record from the item table and returns it in an associative array
352 * @brief Retrieve a single record from a table
353 * @param array $fields
354 * @param array $condition
355 * @param array $params
359 public static function selectFirst(array $fields = [], array $condition = [], $params = [])
361 $params['limit'] = 1;
363 $result = self::select($fields, $condition, $params);
365 if (is_bool($result)) {
368 $row = self::fetch($result);
375 * @brief Select rows from the item table
377 * @param array $selected Array of selected fields, empty for all
378 * @param array $condition Array of fields for condition
379 * @param array $params Array of several parameters
381 * @return boolean|object
383 public static function select(array $selected = [], array $condition = [], $params = [])
388 if (isset($params['uid'])) {
389 $uid = $params['uid'];
393 $fields = self::fieldlist($usermode);
395 $select_fields = self::constructSelectFields($fields, $selected);
397 $condition_string = DBA::buildCondition($condition);
399 $condition_string = self::addTablesToFields($condition_string, $fields);
402 $condition_string = $condition_string . ' AND ' . self::condition(false);
405 $param_string = self::addTablesToFields(DBA::buildParameter($params), $fields);
407 $table = "`item` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, false, $usermode);
409 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
411 return DBA::p($sql, $condition);
415 * @brief Select rows from the starting post in the item table
417 * @param integer $uid User ID
418 * @param array $fields Array of selected fields, empty for all
419 * @param array $condition Array of fields for condition
420 * @param array $params Array of several parameters
422 * @return boolean|object
424 public static function selectThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
426 $params['uid'] = $uid;
428 if (empty($selected)) {
429 $selected = Item::DISPLAY_FIELDLIST;
432 return self::selectThread($selected, $condition, $params);
436 * Retrieve a single record from the starting post in the item table and returns it in an associative array
438 * @brief Retrieve a single record from a table
439 * @param integer $uid User ID
440 * @param array $selected
441 * @param array $condition
442 * @param array $params
446 public static function selectFirstThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
448 $params['uid'] = $uid;
450 if (empty($selected)) {
451 $selected = Item::DISPLAY_FIELDLIST;
454 return self::selectFirstThread($selected, $condition, $params);
458 * Retrieve a single record from the starting post in the item table and returns it in an associative array
460 * @brief Retrieve a single record from a table
461 * @param array $fields
462 * @param array $condition
463 * @param array $params
467 public static function selectFirstThread(array $fields = [], array $condition = [], $params = [])
469 $params['limit'] = 1;
470 $result = self::selectThread($fields, $condition, $params);
472 if (is_bool($result)) {
475 $row = self::fetch($result);
482 * @brief Select rows from the starting post in the item table
484 * @param array $selected Array of selected fields, empty for all
485 * @param array $condition Array of fields for condition
486 * @param array $params Array of several parameters
488 * @return boolean|object
490 public static function selectThread(array $selected = [], array $condition = [], $params = [])
495 if (isset($params['uid'])) {
496 $uid = $params['uid'];
500 $fields = self::fieldlist($usermode);
502 $fields['thread'] = ['mention', 'ignored', 'iid'];
504 $threadfields = ['thread' => ['iid', 'uid', 'contact-id', 'owner-id', 'author-id',
505 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private',
506 'pubmail', 'moderated', 'visible', 'starred', 'ignored', 'post-type',
507 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'network']];
509 $select_fields = self::constructSelectFields($fields, $selected);
511 $condition_string = DBA::buildCondition($condition);
513 $condition_string = self::addTablesToFields($condition_string, $threadfields);
514 $condition_string = self::addTablesToFields($condition_string, $fields);
517 $condition_string = $condition_string . ' AND ' . self::condition(true);
520 $param_string = DBA::buildParameter($params);
521 $param_string = self::addTablesToFields($param_string, $threadfields);
522 $param_string = self::addTablesToFields($param_string, $fields);
524 $table = "`thread` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, true, $usermode);
526 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
528 return DBA::p($sql, $condition);
532 * @brief Returns a list of fields that are associated with the item table
534 * @return array field list
536 private static function fieldlist($usermode)
540 $fields['item'] = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
541 'contact-id', 'owner-id', 'author-id', 'type', 'wall', 'gravity', 'extid',
542 'created', 'edited', 'commented', 'received', 'changed', 'psid',
543 'resource-id', 'event-id', 'tag', 'attach', 'post-type', 'file',
544 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
545 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global',
546 'id' => 'item_id', 'network', 'icid', 'iaid', 'id' => 'internal-iid',
547 'network' => 'internal-network', 'icid' => 'internal-icid',
548 'iaid' => 'internal-iaid'];
551 $fields['user-item'] = ['ignored' => 'internal-user-ignored'];
554 $fields['item-activity'] = ['activity', 'activity' => 'internal-activity'];
556 $fields['item-content'] = array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST);
558 $fields['item-delivery-data'] = self::DELIVERY_DATA_FIELDLIST;
560 $fields['permissionset'] = ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'];
562 $fields['author'] = ['url' => 'author-link', 'name' => 'author-name',
563 'thumb' => 'author-avatar', 'nick' => 'author-nick', 'network' => 'author-network'];
565 $fields['owner'] = ['url' => 'owner-link', 'name' => 'owner-name',
566 'thumb' => 'owner-avatar', 'nick' => 'owner-nick', 'network' => 'owner-network'];
568 $fields['contact'] = ['url' => 'contact-link', 'name' => 'contact-name', 'thumb' => 'contact-avatar',
569 'writable', 'self', 'id' => 'cid', 'alias', 'uid' => 'contact-uid',
570 'photo', 'name-date', 'uri-date', 'avatar-date', 'thumb', 'dfrn-id'];
572 $fields['parent-item'] = ['guid' => 'parent-guid', 'network' => 'parent-network'];
574 $fields['parent-item-author'] = ['url' => 'parent-author-link', 'name' => 'parent-author-name'];
576 $fields['event'] = ['created' => 'event-created', 'edited' => 'event-edited',
577 'start' => 'event-start','finish' => 'event-finish',
578 'summary' => 'event-summary','desc' => 'event-desc',
579 'location' => 'event-location', 'type' => 'event-type',
580 'nofinish' => 'event-nofinish','adjust' => 'event-adjust',
581 'ignore' => 'event-ignore', 'id' => 'event-id'];
583 $fields['sign'] = ['signed_text', 'signature', 'signer'];
585 $fields['diaspora-interaction'] = ['interaction'];
591 * @brief Returns SQL condition for the "select" functions
593 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
595 * @return string SQL condition
597 private static function condition($thread_mode)
600 $master_table = "`thread`";
602 $master_table = "`item`";
604 return sprintf("$master_table.`visible` AND NOT $master_table.`deleted` AND NOT $master_table.`moderated`
605 AND (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`)
606 AND (`user-author`.`blocked` IS NULL OR NOT `user-author`.`blocked`)
607 AND (`user-author`.`ignored` IS NULL OR NOT `user-author`.`ignored` OR `item`.`gravity` != %d)
608 AND (`user-owner`.`blocked` IS NULL OR NOT `user-owner`.`blocked`)
609 AND (`user-owner`.`ignored` IS NULL OR NOT `user-owner`.`ignored` OR `item`.`gravity` != %d) ",
610 GRAVITY_PARENT, GRAVITY_PARENT);
614 * @brief Returns all needed "JOIN" commands for the "select" functions
616 * @param integer $uid User ID
617 * @param string $sql_commands The parts of the built SQL commands in the "select" functions
618 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
620 * @return string The SQL joins for the "select" functions
622 private static function constructJoins($uid, $sql_commands, $thread_mode, $user_mode)
625 $master_table = "`thread`";
626 $master_table_key = "`thread`.`iid`";
627 $joins = "STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid` ";
629 $master_table = "`item`";
630 $master_table_key = "`item`.`id`";
635 $joins .= sprintf("STRAIGHT_JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`
636 AND NOT `contact`.`blocked`
637 AND ((NOT `contact`.`readonly` AND NOT `contact`.`pending` AND (`contact`.`rel` IN (%s, %s)))
638 OR `contact`.`self` OR `item`.`gravity` != %d OR `contact`.`uid` = 0)
639 STRAIGHT_JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id` AND NOT `author`.`blocked`
640 STRAIGHT_JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id` AND NOT `owner`.`blocked`
641 LEFT JOIN `user-item` ON `user-item`.`iid` = $master_table_key AND `user-item`.`uid` = %d
642 LEFT JOIN `user-contact` AS `user-author` ON `user-author`.`cid` = $master_table.`author-id` AND `user-author`.`uid` = %d
643 LEFT JOIN `user-contact` AS `user-owner` ON `user-owner`.`cid` = $master_table.`owner-id` AND `user-owner`.`uid` = %d",
644 Contact::SHARING, Contact::FRIEND, GRAVITY_PARENT, intval($uid), intval($uid), intval($uid));
646 if (strpos($sql_commands, "`contact`.") !== false) {
647 $joins .= "LEFT JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`";
649 if (strpos($sql_commands, "`author`.") !== false) {
650 $joins .= " LEFT JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id`";
652 if (strpos($sql_commands, "`owner`.") !== false) {
653 $joins .= " LEFT JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id`";
657 if (strpos($sql_commands, "`group_member`.") !== false) {
658 $joins .= " STRAIGHT_JOIN `group_member` ON `group_member`.`contact-id` = $master_table.`contact-id`";
661 if (strpos($sql_commands, "`user`.") !== false) {
662 $joins .= " STRAIGHT_JOIN `user` ON `user`.`uid` = $master_table.`uid`";
665 if (strpos($sql_commands, "`event`.") !== false) {
666 $joins .= " LEFT JOIN `event` ON `event-id` = `event`.`id`";
669 if (strpos($sql_commands, "`sign`.") !== false) {
670 $joins .= " LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`";
673 if (strpos($sql_commands, "`diaspora-interaction`.") !== false) {
674 $joins .= " LEFT JOIN `diaspora-interaction` ON `diaspora-interaction`.`uri-id` = `item`.`uri-id`";
677 if (strpos($sql_commands, "`item-activity`.") !== false) {
678 $joins .= " LEFT JOIN `item-activity` ON `item-activity`.`uri-id` = `item`.`uri-id`";
681 if (strpos($sql_commands, "`item-content`.") !== false) {
682 $joins .= " LEFT JOIN `item-content` ON `item-content`.`uri-id` = `item`.`uri-id`";
685 if (strpos($sql_commands, "`item-delivery-data`.") !== false) {
686 $joins .= " LEFT JOIN `item-delivery-data` ON `item-delivery-data`.`iid` = `item`.`id`";
689 if (strpos($sql_commands, "`permissionset`.") !== false) {
690 $joins .= " LEFT JOIN `permissionset` ON `permissionset`.`id` = `item`.`psid`";
693 if ((strpos($sql_commands, "`parent-item`.") !== false) || (strpos($sql_commands, "`parent-author`.") !== false)) {
694 $joins .= " STRAIGHT_JOIN `item` AS `parent-item` ON `parent-item`.`id` = `item`.`parent`";
697 if (strpos($sql_commands, "`parent-item-author`.") !== false) {
698 $joins .= " STRAIGHT_JOIN `contact` AS `parent-item-author` ON `parent-item-author`.`id` = `parent-item`.`author-id`";
705 * @brief Add the field list for the "select" functions
707 * @param array $fields The field definition array
708 * @param array $selected The array with the selected fields from the "select" functions
710 * @return string The field list
712 private static function constructSelectFields($fields, $selected)
714 if (!empty($selected)) {
715 $selected[] = 'internal-iid';
716 $selected[] = 'internal-iaid';
717 $selected[] = 'internal-icid';
718 $selected[] = 'internal-network';
721 if (in_array('verb', $selected)) {
722 $selected[] = 'internal-activity';
725 if (in_array('ignored', $selected)) {
726 $selected[] = 'internal-user-ignored';
729 if (in_array('signed_text', $selected)) {
730 $selected[] = 'interaction';
734 foreach ($fields as $table => $table_fields) {
735 foreach ($table_fields as $field => $select) {
736 if (empty($selected) || in_array($select, $selected)) {
737 $legacy_fields = array_merge(self::DELIVERY_DATA_FIELDLIST, self::MIXED_CONTENT_FIELDLIST);
738 if (self::isLegacyMode() && in_array($select, $legacy_fields)) {
739 $selection[] = "`item`.`".$select."` AS `internal-item-" . $select . "`";
741 if (is_int($field)) {
742 $selection[] = "`" . $table . "`.`" . $select . "`";
744 $selection[] = "`" . $table . "`.`" . $field . "` AS `" . $select . "`";
749 return implode(", ", $selection);
753 * @brief add table definition to fields in an SQL query
755 * @param string $query SQL query
756 * @param array $fields The field definition array
758 * @return string the changed SQL query
760 private static function addTablesToFields($query, $fields)
762 foreach ($fields as $table => $table_fields) {
763 foreach ($table_fields as $alias => $field) {
764 if (is_int($alias)) {
765 $replace_field = $field;
767 $replace_field = $alias;
770 $search = "/([^\.])`" . $field . "`/i";
771 $replace = "$1`" . $table . "`.`" . $replace_field . "`";
772 $query = preg_replace($search, $replace, $query);
779 * @brief Update existing item entries
781 * @param array $fields The fields that are to be changed
782 * @param array $condition The condition for finding the item entries
784 * In the future we may have to change permissions as well.
785 * Then we had to add the user id as third parameter.
787 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
789 * @return integer|boolean number of affected rows - or "false" if there was an error
791 public static function update(array $fields, array $condition)
793 if (empty($condition) || empty($fields)) {
797 // To ensure the data integrity we do it in an transaction
800 // We cannot simply expand the condition to check for origin entries
801 // The condition needn't to be a simple array but could be a complex condition.
802 // And we have to execute this query before the update to ensure to fetch the same data.
803 $items = DBA::select('item', ['id', 'origin', 'uri', 'uri-id', 'iaid', 'icid', 'tag', 'file'], $condition);
805 $content_fields = [];
806 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
807 if (isset($fields[$field])) {
808 $content_fields[$field] = $fields[$field];
809 if (in_array($field, self::CONTENT_FIELDLIST) || !self::isLegacyMode()) {
810 unset($fields[$field]);
812 $fields[$field] = null;
817 $clear_fields = ['bookmark', 'type', 'author-name', 'author-avatar', 'author-link', 'owner-name', 'owner-avatar', 'owner-link'];
818 foreach ($clear_fields as $field) {
819 if (array_key_exists($field, $fields)) {
820 $fields[$field] = null;
824 if (array_key_exists('tag', $fields)) {
825 $tags = $fields['tag'];
826 $fields['tag'] = null;
831 if (array_key_exists('file', $fields)) {
832 $files = $fields['file'];
833 $fields['file'] = null;
838 $delivery_data = ['postopts' => defaults($fields, 'postopts', ''),
839 'inform' => defaults($fields, 'inform', '')];
841 $fields['postopts'] = null;
842 $fields['inform'] = null;
844 if (!empty($fields)) {
845 $success = DBA::update('item', $fields, $condition);
854 // When there is no content for the "old" item table, this will count the fetched items
855 $rows = DBA::affectedRows();
857 while ($item = DBA::fetch($items)) {
858 if (!empty($item['iaid']) || (!empty($content_fields['verb']) && (self::activityToIndex($content_fields['verb']) >= 0))) {
859 self::updateActivity($content_fields, ['uri-id' => $item['uri-id']]);
861 if (empty($item['iaid'])) {
862 $item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-id' => $item['uri-id']]);
863 if (DBA::isResult($item_activity)) {
864 $item_fields = ['iaid' => $item_activity['id'], 'icid' => null];
865 foreach (self::MIXED_CONTENT_FIELDLIST as $field) {
866 if (self::isLegacyMode()) {
867 $item_fields[$field] = null;
869 unset($item_fields[$field]);
872 DBA::update('item', $item_fields, ['id' => $item['id']]);
874 if (!empty($item['icid']) && !DBA::exists('item', ['icid' => $item['icid']])) {
875 DBA::delete('item-content', ['id' => $item['icid']]);
878 } elseif (!empty($item['icid'])) {
879 DBA::update('item', ['icid' => null], ['id' => $item['id']]);
881 if (!DBA::exists('item', ['icid' => $item['icid']])) {
882 DBA::delete('item-content', ['id' => $item['icid']]);
886 self::updateContent($content_fields, ['uri-id' => $item['uri-id']]);
888 if (empty($item['icid'])) {
889 $item_content = DBA::selectFirst('item-content', [], ['uri-id' => $item['uri-id']]);
890 if (DBA::isResult($item_content)) {
891 $item_fields = ['icid' => $item_content['id']];
892 // Clear all fields in the item table that have a content in the item-content table
893 foreach ($item_content as $field => $content) {
894 if (in_array($field, self::MIXED_CONTENT_FIELDLIST) && !empty($item_content[$field])) {
895 if (self::isLegacyMode()) {
896 $item_fields[$field] = null;
898 unset($item_fields[$field]);
902 DBA::update('item', $item_fields, ['id' => $item['id']]);
907 if (!is_null($tags)) {
908 Term::insertFromTagFieldByItemId($item['id'], $tags);
909 if (!empty($item['tag'])) {
910 DBA::update('item', ['tag' => ''], ['id' => $item['id']]);
914 if (!is_null($files)) {
915 Term::insertFromFileFieldByItemId($item['id'], $files);
916 if (!empty($item['file'])) {
917 DBA::update('item', ['file' => ''], ['id' => $item['id']]);
921 self::updateDeliveryData($item['id'], $delivery_data);
923 self::updateThread($item['id']);
925 // We only need to notfiy others when it is an original entry from us.
926 // Only call the notifier when the item has some content relevant change.
927 if ($item['origin'] && in_array('edited', array_keys($fields))) {
928 Worker::add(PRIORITY_HIGH, "Notifier", 'edit_post', $item['id']);
938 * @brief Delete an item and notify others about it - if it was ours
940 * @param array $condition The condition for finding the item entries
941 * @param integer $priority Priority for the notification
943 public static function delete($condition, $priority = PRIORITY_HIGH)
945 $items = self::select(['id'], $condition);
946 while ($item = self::fetch($items)) {
947 self::deleteById($item['id'], $priority);
953 * @brief Delete an item for an user and notify others about it - if it was ours
955 * @param array $condition The condition for finding the item entries
956 * @param integer $uid User who wants to delete this item
958 public static function deleteForUser($condition, $uid)
964 $items = self::select(['id', 'uid'], $condition);
965 while ($item = self::fetch($items)) {
966 // "Deleting" global items just means hiding them
967 if ($item['uid'] == 0) {
968 DBA::update('user-item', ['hidden' => true], ['iid' => $item['id'], 'uid' => $uid], true);
969 } elseif ($item['uid'] == $uid) {
970 self::deleteById($item['id'], PRIORITY_HIGH);
972 Logger::log('Wrong ownership. Not deleting item ' . $item['id']);
979 * @brief Delete an item and notify others about it - if it was ours
981 * @param integer $item_id Item ID that should be delete
982 * @param integer $priority Priority for the notification
984 * @return boolean success
986 public static function deleteById($item_id, $priority = PRIORITY_HIGH)
988 // locate item to be deleted
989 $fields = ['id', 'uri', 'uid', 'parent', 'parent-uri', 'origin',
990 'deleted', 'file', 'resource-id', 'event-id', 'attach',
991 'verb', 'object-type', 'object', 'target', 'contact-id',
992 'icid', 'iaid', 'psid'];
993 $item = self::selectFirst($fields, ['id' => $item_id]);
994 if (!DBA::isResult($item)) {
995 Logger::log('Item with ID ' . $item_id . " hasn't been found.", Logger::DEBUG);
999 if ($item['deleted']) {
1000 Logger::log('Item with ID ' . $item_id . ' has already been deleted.', Logger::DEBUG);
1004 $parent = self::selectFirst(['origin'], ['id' => $item['parent']]);
1005 if (!DBA::isResult($parent)) {
1006 $parent = ['origin' => false];
1009 // clean up categories and tags so they don't end up as orphans
1012 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
1015 foreach ($matches as $mtch) {
1016 FileTag::unsaveFile($item['uid'], $item['id'], $mtch[1],true);
1022 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
1025 foreach ($matches as $mtch) {
1026 FileTag::unsaveFile($item['uid'], $item['id'], $mtch[1],false);
1031 * If item is a link to a photo resource, nuke all the associated photos
1032 * (visitors will not have photo resources)
1033 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
1034 * generate a resource-id and therefore aren't intimately linked to the item.
1036 if (strlen($item['resource-id'])) {
1037 DBA::delete('photo', ['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
1040 // If item is a link to an event, delete the event.
1041 if (intval($item['event-id'])) {
1042 Event::delete($item['event-id']);
1045 // If item has attachments, drop them
1046 foreach (explode(", ", $item['attach']) as $attach) {
1047 preg_match("|attach/(\d+)|", $attach, $matches);
1048 if (is_array($matches) && count($matches) > 1) {
1049 DBA::delete('attach', ['id' => $matches[1], 'uid' => $item['uid']]);
1053 // Delete tags that had been attached to other items
1054 self::deleteTagsFromItem($item);
1056 // Set the item to "deleted"
1057 $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
1058 DBA::update('item', $item_fields, ['id' => $item['id']]);
1060 Term::insertFromTagFieldByItemId($item['id'], '');
1061 Term::insertFromFileFieldByItemId($item['id'], '');
1062 self::deleteThread($item['id'], $item['parent-uri']);
1064 if (!self::exists(["`uri` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri']])) {
1065 self::delete(['uri' => $item['uri'], 'uid' => 0, 'deleted' => false], $priority);
1068 DBA::delete('item-delivery-data', ['iid' => $item['id']]);
1070 // We don't delete the item-activity here, since we need some of the data for ActivityPub
1072 if (!empty($item['icid']) && !self::exists(['icid' => $item['icid'], 'deleted' => false])) {
1073 DBA::delete('item-content', ['id' => $item['icid']], ['cascade' => false]);
1075 // When the permission set will be used in photo and events as well,
1076 // this query here needs to be extended.
1077 if (!empty($item['psid']) && !self::exists(['psid' => $item['psid'], 'deleted' => false])) {
1078 DBA::delete('permissionset', ['id' => $item['psid']], ['cascade' => false]);
1081 // If it's the parent of a comment thread, kill all the kids
1082 if ($item['id'] == $item['parent']) {
1083 self::delete(['parent' => $item['parent'], 'deleted' => false], $priority);
1086 // Is it our comment and/or our thread?
1087 if ($item['origin'] || $parent['origin']) {
1089 // When we delete the original post we will delete all existing copies on the server as well
1090 self::delete(['uri' => $item['uri'], 'deleted' => false], $priority);
1092 // send the notification upstream/downstream
1093 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", "drop", intval($item['id']));
1094 } elseif ($item['uid'] != 0) {
1096 // When we delete just our local user copy of an item, we have to set a marker to hide it
1097 $global_item = self::selectFirst(['id'], ['uri' => $item['uri'], 'uid' => 0, 'deleted' => false]);
1098 if (DBA::isResult($global_item)) {
1099 DBA::update('user-item', ['hidden' => true], ['iid' => $global_item['id'], 'uid' => $item['uid']], true);
1103 Logger::log('Item with ID ' . $item_id . " has been deleted.", Logger::DEBUG);
1108 private static function deleteTagsFromItem($item)
1110 if (($item["verb"] != ACTIVITY_TAG) || ($item["object-type"] != ACTIVITY_OBJ_TAGTERM)) {
1114 $xo = XML::parseString($item["object"], false);
1115 $xt = XML::parseString($item["target"], false);
1117 if ($xt->type != ACTIVITY_OBJ_NOTE) {
1121 $i = self::selectFirst(['id', 'contact-id', 'tag'], ['uri' => $xt->id, 'uid' => $item['uid']]);
1122 if (!DBA::isResult($i)) {
1126 // For tags, the owner cannot remove the tag on the author's copy of the post.
1127 $owner_remove = ($item["contact-id"] == $i["contact-id"]);
1128 $author_copy = $item["origin"];
1130 if (($owner_remove && $author_copy) || !$owner_remove) {
1134 $tags = explode(',', $i["tag"]);
1137 foreach ($tags as $tag) {
1138 if (trim($tag) !== trim($xo->body)) {
1139 $newtags[] = trim($tag);
1143 self::update(['tag' => implode(',', $newtags)], ['id' => $i["id"]]);
1146 private static function guid($item, $notify)
1148 if (!empty($item['guid'])) {
1149 return Strings::escapeTags(trim($item['guid']));
1153 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
1154 // We add the hash of our own host because our host is the original creator of the post.
1155 $prefix_host = get_app()->getHostName();
1159 // We are only storing the post so we create a GUID from the original hostname.
1160 if (!empty($item['author-link'])) {
1161 $parsed = parse_url($item['author-link']);
1162 if (!empty($parsed['host'])) {
1163 $prefix_host = $parsed['host'];
1167 if (empty($prefix_host) && !empty($item['plink'])) {
1168 $parsed = parse_url($item['plink']);
1169 if (!empty($parsed['host'])) {
1170 $prefix_host = $parsed['host'];
1174 if (empty($prefix_host) && !empty($item['uri'])) {
1175 $parsed = parse_url($item['uri']);
1176 if (!empty($parsed['host'])) {
1177 $prefix_host = $parsed['host'];
1181 // Is it in the format data@host.tld? - Used for mail contacts
1182 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
1183 $mailparts = explode('@', $item['author-link']);
1184 $prefix_host = array_pop($mailparts);
1188 if (!empty($item['plink'])) {
1189 $guid = self::guidFromUri($item['plink'], $prefix_host);
1190 } elseif (!empty($item['uri'])) {
1191 $guid = self::guidFromUri($item['uri'], $prefix_host);
1193 $guid = System::createUUID(hash('crc32', $prefix_host));
1199 private static function contactId($item)
1201 $contact_id = (int)$item["contact-id"];
1203 if (!empty($contact_id)) {
1206 Logger::log('Missing contact-id. Called by: '.System::callstack(), Logger::DEBUG);
1208 * First we are looking for a suitable contact that matches with the author of the post
1209 * This is done only for comments
1211 if ($item['parent-uri'] != $item['uri']) {
1212 $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
1215 // If not present then maybe the owner was found
1216 if ($contact_id == 0) {
1217 $contact_id = Contact::getIdForURL($item['owner-link'], $item['uid']);
1220 // Still missing? Then use the "self" contact of the current user
1221 if ($contact_id == 0) {
1222 $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $item['uid']]);
1223 if (DBA::isResult($self)) {
1224 $contact_id = $self["id"];
1227 Logger::log("Contact-id was missing for post ".$item['guid']." from user id ".$item['uid']." - now set to ".$contact_id, Logger::DEBUG);
1232 // This function will finally cover most of the preparation functionality in mod/item.php
1233 public static function prepare(&$item)
1235 $data = BBCode::getAttachmentData($item['body']);
1236 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $item['body'], $match, PREG_SET_ORDER) || isset($data["type"]))
1237 && ($posttype != Item::PT_PERSONAL_NOTE)) {
1238 $posttype = Item::PT_PAGE;
1239 $objecttype = ACTIVITY_OBJ_BOOKMARK;
1243 public static function insert($item, $force_parent = false, $notify = false, $dontcache = false)
1247 // If it is a posting where users should get notifications, then define it as wall posting
1250 $item['origin'] = 1;
1251 $item['network'] = Protocol::DFRN;
1252 $item['protocol'] = Conversation::PARCEL_DFRN;
1254 if (is_int($notify)) {
1255 $priority = $notify;
1257 $priority = PRIORITY_HIGH;
1260 $item['network'] = trim(defaults($item, 'network', Protocol::PHANTOM));
1263 $item['guid'] = self::guid($item, $notify);
1264 $item['uri'] = Strings::escapeTags(trim(defaults($item, 'uri', self::newURI($item['uid'], $item['guid']))));
1267 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
1269 // Store conversation data
1270 $item = Conversation::insert($item);
1273 * If a Diaspora signature structure was passed in, pull it out of the
1274 * item array and set it aside for later storage.
1278 if (isset($item['dsprsig'])) {
1279 $encoded_signature = $item['dsprsig'];
1280 $dsprsig = json_decode(base64_decode($item['dsprsig']));
1281 unset($item['dsprsig']);
1284 $diaspora_signed_text = '';
1285 if (isset($item['diaspora_signed_text'])) {
1286 $diaspora_signed_text = $item['diaspora_signed_text'];
1287 unset($item['diaspora_signed_text']);
1290 // Converting the plink
1291 /// @TODO Check if this is really still needed
1292 if ($item['network'] == Protocol::OSTATUS) {
1293 if (isset($item['plink'])) {
1294 $item['plink'] = OStatus::convertHref($item['plink']);
1295 } elseif (isset($item['uri'])) {
1296 $item['plink'] = OStatus::convertHref($item['uri']);
1300 if (!empty($item['thr-parent'])) {
1301 $item['parent-uri'] = $item['thr-parent'];
1304 if (isset($item['gravity'])) {
1305 $item['gravity'] = intval($item['gravity']);
1306 } elseif ($item['parent-uri'] === $item['uri']) {
1307 $item['gravity'] = GRAVITY_PARENT;
1308 } elseif (activity_match($item['verb'], ACTIVITY_POST)) {
1309 $item['gravity'] = GRAVITY_COMMENT;
1311 $item['gravity'] = GRAVITY_UNKNOWN; // Should not happen
1312 Logger::log('Unknown gravity for verb: ' . $item['verb'], Logger::DEBUG);
1315 $uid = intval($item['uid']);
1317 // check for create date and expire time
1318 $expire_interval = Config::get('system', 'dbclean-expire-days', 0);
1320 $user = DBA::selectFirst('user', ['expire'], ['uid' => $uid]);
1321 if (DBA::isResult($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
1322 $expire_interval = $user['expire'];
1325 if (($expire_interval > 0) && !empty($item['created'])) {
1326 $expire_date = time() - ($expire_interval * 86400);
1327 $created_date = strtotime($item['created']);
1328 if ($created_date < $expire_date) {
1329 Logger::log('item-store: item created ('.date('c', $created_date).') before expiration time ('.date('c', $expire_date).'). ignored. ' . print_r($item,true), Logger::DEBUG);
1335 * Do we already have this item?
1336 * We have to check several networks since Friendica posts could be repeated
1337 * via OStatus (maybe Diasporsa as well)
1339 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DIASPORA, Protocol::DFRN, Protocol::OSTATUS, ""])) {
1340 $condition = ["`uri` = ? AND `uid` = ? AND `network` IN (?, ?, ?)",
1341 trim($item['uri']), $item['uid'],
1342 Protocol::DIASPORA, Protocol::DFRN, Protocol::OSTATUS];
1343 $existing = self::selectFirst(['id', 'network'], $condition);
1344 if (DBA::isResult($existing)) {
1345 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
1347 Logger::log("Item with uri ".$item['uri']." already existed for user ".$uid." with id ".$existing["id"]." target network ".$existing["network"]." - new network: ".$item['network']);
1350 return $existing["id"];
1354 $item['wall'] = intval(defaults($item, 'wall', 0));
1355 $item['extid'] = trim(defaults($item, 'extid', ''));
1356 $item['author-name'] = trim(defaults($item, 'author-name', ''));
1357 $item['author-link'] = trim(defaults($item, 'author-link', ''));
1358 $item['author-avatar'] = trim(defaults($item, 'author-avatar', ''));
1359 $item['owner-name'] = trim(defaults($item, 'owner-name', ''));
1360 $item['owner-link'] = trim(defaults($item, 'owner-link', ''));
1361 $item['owner-avatar'] = trim(defaults($item, 'owner-avatar', ''));
1362 $item['received'] = (isset($item['received']) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
1363 $item['created'] = (isset($item['created']) ? DateTimeFormat::utc($item['created']) : $item['received']);
1364 $item['edited'] = (isset($item['edited']) ? DateTimeFormat::utc($item['edited']) : $item['created']);
1365 $item['changed'] = (isset($item['changed']) ? DateTimeFormat::utc($item['changed']) : $item['created']);
1366 $item['commented'] = (isset($item['commented']) ? DateTimeFormat::utc($item['commented']) : $item['created']);
1367 $item['title'] = trim(defaults($item, 'title', ''));
1368 $item['location'] = trim(defaults($item, 'location', ''));
1369 $item['coord'] = trim(defaults($item, 'coord', ''));
1370 $item['visible'] = (isset($item['visible']) ? intval($item['visible']) : 1);
1371 $item['deleted'] = 0;
1372 $item['parent-uri'] = trim(defaults($item, 'parent-uri', $item['uri']));
1373 $item['post-type'] = defaults($item, 'post-type', self::PT_ARTICLE);
1374 $item['verb'] = trim(defaults($item, 'verb', ''));
1375 $item['object-type'] = trim(defaults($item, 'object-type', ''));
1376 $item['object'] = trim(defaults($item, 'object', ''));
1377 $item['target-type'] = trim(defaults($item, 'target-type', ''));
1378 $item['target'] = trim(defaults($item, 'target', ''));
1379 $item['plink'] = trim(defaults($item, 'plink', ''));
1380 $item['allow_cid'] = trim(defaults($item, 'allow_cid', ''));
1381 $item['allow_gid'] = trim(defaults($item, 'allow_gid', ''));
1382 $item['deny_cid'] = trim(defaults($item, 'deny_cid', ''));
1383 $item['deny_gid'] = trim(defaults($item, 'deny_gid', ''));
1384 $item['private'] = intval(defaults($item, 'private', 0));
1385 $item['body'] = trim(defaults($item, 'body', ''));
1386 $item['tag'] = trim(defaults($item, 'tag', ''));
1387 $item['attach'] = trim(defaults($item, 'attach', ''));
1388 $item['app'] = trim(defaults($item, 'app', ''));
1389 $item['origin'] = intval(defaults($item, 'origin', 0));
1390 $item['postopts'] = trim(defaults($item, 'postopts', ''));
1391 $item['resource-id'] = trim(defaults($item, 'resource-id', ''));
1392 $item['event-id'] = intval(defaults($item, 'event-id', 0));
1393 $item['inform'] = trim(defaults($item, 'inform', ''));
1394 $item['file'] = trim(defaults($item, 'file', ''));
1396 // When there is no content then we don't post it
1397 if ($item['body'].$item['title'] == '') {
1398 Logger::log('No body, no title.');
1402 self::addLanguageToItemArray($item);
1404 // Items cannot be stored before they happen ...
1405 if ($item['created'] > DateTimeFormat::utcNow()) {
1406 $item['created'] = DateTimeFormat::utcNow();
1409 // We haven't invented time travel by now.
1410 if ($item['edited'] > DateTimeFormat::utcNow()) {
1411 $item['edited'] = DateTimeFormat::utcNow();
1414 $item['plink'] = defaults($item, 'plink', System::baseUrl() . '/display/' . urlencode($item['guid']));
1416 // The contact-id should be set before "self::insert" was called - but there seems to be issues sometimes
1417 $item["contact-id"] = self::contactId($item);
1419 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
1420 'photo' => $item['author-avatar'], 'network' => $item['network']];
1422 $item['author-id'] = defaults($item, 'author-id', Contact::getIdForURL($item["author-link"], 0, false, $default));
1424 if (Contact::isBlocked($item["author-id"])) {
1425 Logger::log('Contact '.$item["author-id"].' is blocked, item '.$item["uri"].' will not be stored');
1429 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
1430 'photo' => $item['owner-avatar'], 'network' => $item['network']];
1432 $item['owner-id'] = defaults($item, 'owner-id', Contact::getIdForURL($item["owner-link"], 0, false, $default));
1434 if (Contact::isBlocked($item["owner-id"])) {
1435 Logger::log('Contact '.$item["owner-id"].' is blocked, item '.$item["uri"].' will not be stored');
1439 if ($item['network'] == Protocol::PHANTOM) {
1440 Logger::log('Missing network. Called by: '.System::callstack(), Logger::DEBUG);
1442 $item['network'] = Protocol::DFRN;
1443 Logger::log("Set network to " . $item["network"] . " for " . $item["uri"], Logger::DEBUG);
1446 // Checking if there is already an item with the same guid
1447 Logger::log('Checking for an item for user '.$item['uid'].' on network '.$item['network'].' with the guid '.$item['guid'], Logger::DEBUG);
1448 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
1449 if (self::exists($condition)) {
1450 Logger::log('found item with guid '.$item['guid'].' for user '.$item['uid'].' on network '.$item['network'], Logger::DEBUG);
1454 // Check for hashtags in the body and repair or add hashtag links
1455 self::setHashtags($item);
1457 $item['thr-parent'] = $item['parent-uri'];
1465 if ($item['parent-uri'] === $item['uri']) {
1467 $parent_deleted = 0;
1468 $allow_cid = $item['allow_cid'];
1469 $allow_gid = $item['allow_gid'];
1470 $deny_cid = $item['deny_cid'];
1471 $deny_gid = $item['deny_gid'];
1472 $notify_type = 'wall-new';
1474 // find the parent and snarf the item id and ACLs
1475 // and anything else we need to inherit
1477 $fields = ['uri', 'parent-uri', 'id', 'deleted',
1478 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
1479 'wall', 'private', 'forum_mode', 'origin'];
1480 $condition = ['uri' => $item['parent-uri'], 'uid' => $item['uid']];
1481 $params = ['order' => ['id' => false]];
1482 $parent = self::selectFirst($fields, $condition, $params);
1484 if (DBA::isResult($parent)) {
1485 // is the new message multi-level threaded?
1486 // even though we don't support it now, preserve the info
1487 // and re-attach to the conversation parent.
1489 if ($parent['uri'] != $parent['parent-uri']) {
1490 $item['parent-uri'] = $parent['parent-uri'];
1492 $condition = ['uri' => $item['parent-uri'],
1493 'parent-uri' => $item['parent-uri'],
1494 'uid' => $item['uid']];
1495 $params = ['order' => ['id' => false]];
1496 $toplevel_parent = self::selectFirst($fields, $condition, $params);
1498 if (DBA::isResult($toplevel_parent)) {
1499 $parent = $toplevel_parent;
1503 $parent_id = $parent['id'];
1504 $parent_deleted = $parent['deleted'];
1505 $allow_cid = $parent['allow_cid'];
1506 $allow_gid = $parent['allow_gid'];
1507 $deny_cid = $parent['deny_cid'];
1508 $deny_gid = $parent['deny_gid'];
1509 $item['wall'] = $parent['wall'];
1510 $notify_type = 'comment-new';
1513 * If the parent is private, force privacy for the entire conversation
1514 * This differs from the above settings as it subtly allows comments from
1515 * email correspondents to be private even if the overall thread is not.
1517 if ($parent['private']) {
1518 $item['private'] = $parent['private'];
1522 * Edge case. We host a public forum that was originally posted to privately.
1523 * The original author commented, but as this is a comment, the permissions
1524 * weren't fixed up so it will still show the comment as private unless we fix it here.
1526 if ((intval($parent['forum_mode']) == 1) && $parent['private']) {
1527 $item['private'] = 0;
1530 // If its a post from myself then tag the thread as "mention"
1531 Logger::log("Checking if parent ".$parent_id." has to be tagged as mention for user ".$item['uid'], Logger::DEBUG);
1532 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $item['uid']]);
1533 if (DBA::isResult($user)) {
1534 $self = Strings::normaliseLink(System::baseUrl() . '/profile/' . $user['nickname']);
1535 $self_id = Contact::getIdForURL($self, 0, true);
1536 Logger::log("'myself' is ".$self_id." for parent ".$parent_id." checking against ".$item['author-id']." and ".$item['owner-id'], Logger::DEBUG);
1537 if (($item['author-id'] == $self_id) || ($item['owner-id'] == $self_id)) {
1538 DBA::update('thread', ['mention' => true], ['iid' => $parent_id]);
1539 Logger::log("tagged thread ".$parent_id." as mention for user ".$self, Logger::DEBUG);
1544 * Allow one to see reply tweets from status.net even when
1545 * we don't have or can't see the original post.
1547 if ($force_parent) {
1548 Logger::log('$force_parent=true, reply converted to top-level post.');
1550 $item['parent-uri'] = $item['uri'];
1551 $item['gravity'] = GRAVITY_PARENT;
1553 Logger::log('item parent '.$item['parent-uri'].' for '.$item['uid'].' was not found - ignoring item');
1557 $parent_deleted = 0;
1561 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
1562 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
1564 $condition = ["`uri` = ? AND `network` IN (?, ?) AND `uid` = ?",
1565 $item['uri'], $item['network'], Protocol::DFRN, $item['uid']];
1566 if (self::exists($condition)) {
1567 Logger::log('duplicated item with the same uri found. '.print_r($item,true));
1571 // On Friendica and Diaspora the GUID is unique
1572 if (in_array($item['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
1573 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
1574 if (self::exists($condition)) {
1575 Logger::log('duplicated item with the same guid found. '.print_r($item,true));
1579 // Check for an existing post with the same content. There seems to be a problem with OStatus.
1580 $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
1581 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
1582 if (self::exists($condition)) {
1583 Logger::log('duplicated item with the same body found. '.print_r($item,true));
1588 // Is this item available in the global items (with uid=0)?
1589 if ($item["uid"] == 0) {
1590 $item["global"] = true;
1592 // Set the global flag on all items if this was a global item entry
1593 self::update(['global' => true], ['uri' => $item["uri"]]);
1595 $item["global"] = self::exists(['uid' => 0, 'uri' => $item["uri"]]);
1599 if (strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid)) {
1602 $private = $item['private'];
1605 $item["allow_cid"] = $allow_cid;
1606 $item["allow_gid"] = $allow_gid;
1607 $item["deny_cid"] = $deny_cid;
1608 $item["deny_gid"] = $deny_gid;
1609 $item["private"] = $private;
1610 $item["deleted"] = $parent_deleted;
1612 // Fill the cache field
1613 self::putInCache($item);
1616 $item['edit'] = false;
1617 $item['parent'] = $parent_id;
1618 Addon::callHooks('post_local', $item);
1619 unset($item['edit']);
1620 unset($item['parent']);
1622 Addon::callHooks('post_remote', $item);
1625 // This array field is used to trigger some automatic reactions
1626 // It is mainly used in the "post_local" hook.
1627 unset($item['api_source']);
1629 if (!empty($item['cancel'])) {
1630 Logger::log('post cancelled by addon.');
1635 * Check for already added items.
1636 * There is a timing issue here that sometimes creates double postings.
1637 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
1639 if ($item["uid"] == 0) {
1640 if (self::exists(['uri' => trim($item['uri']), 'uid' => 0])) {
1641 Logger::log('Global item already stored. URI: '.$item['uri'].' on network '.$item['network'], Logger::DEBUG);
1646 Logger::log('' . print_r($item,true), Logger::DATA);
1648 if (array_key_exists('tag', $item)) {
1649 $tags = $item['tag'];
1650 unset($item['tag']);
1655 if (array_key_exists('file', $item)) {
1656 $files = $item['file'];
1657 unset($item['file']);
1662 // Creates or assigns the permission set
1663 $item['psid'] = PermissionSet::fetchIDForPost($item);
1665 // We are doing this outside of the transaction to avoid timing problems
1666 if (!self::insertActivity($item)) {
1667 self::insertContent($item);
1670 $delivery_data = ['postopts' => defaults($item, 'postopts', ''),
1671 'inform' => defaults($item, 'inform', '')];
1673 unset($item['postopts']);
1674 unset($item['inform']);
1676 // These fields aren't stored anymore in the item table, they are fetched upon request
1677 unset($item['author-link']);
1678 unset($item['author-name']);
1679 unset($item['author-avatar']);
1681 unset($item['owner-link']);
1682 unset($item['owner-name']);
1683 unset($item['owner-avatar']);
1686 $ret = DBA::insert('item', $item);
1688 // When the item was successfully stored we fetch the ID of the item.
1689 if (DBA::isResult($ret)) {
1690 $current_post = DBA::lastInsertId();
1692 // This can happen - for example - if there are locking timeouts.
1695 // Store the data into a spool file so that we can try again later.
1697 // At first we restore the Diaspora signature that we removed above.
1698 if (isset($encoded_signature)) {
1699 $item['dsprsig'] = $encoded_signature;
1702 // Now we store the data in the spool directory
1703 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
1704 $file = 'item-'.round(microtime(true) * 10000).'-'.mt_rand().'.msg';
1706 $spoolpath = get_spoolpath();
1707 if ($spoolpath != "") {
1708 $spool = $spoolpath.'/'.$file;
1710 // Ensure to have the removed data from above again in the item array
1711 $item = array_merge($item, $delivery_data);
1713 file_put_contents($spool, json_encode($item));
1714 Logger::log("Item wasn't stored - Item was spooled into file ".$file, Logger::DEBUG);
1719 if ($current_post == 0) {
1720 // This is one of these error messages that never should occur.
1721 Logger::log("couldn't find created item - we better quit now.");
1726 // How much entries have we created?
1727 // We wouldn't need this query when we could use an unique index - but MySQL has length problems with them.
1728 $entries = DBA::count('item', ['uri' => $item['uri'], 'uid' => $item['uid'], 'network' => $item['network']]);
1731 // There are duplicates. We delete our just created entry.
1732 Logger::log('Duplicated post occurred. uri = ' . $item['uri'] . ' uid = ' . $item['uid']);
1734 // Yes, we could do a rollback here - but we are having many users with MyISAM.
1735 DBA::delete('item', ['id' => $current_post]);
1738 } elseif ($entries == 0) {
1739 // This really should never happen since we quit earlier if there were problems.
1740 Logger::log("Something is terribly wrong. We haven't found our created entry.");
1745 Logger::log('created item '.$current_post);
1746 self::updateContact($item);
1748 if (!$parent_id || ($item['parent-uri'] === $item['uri'])) {
1749 $parent_id = $current_post;
1753 self::update(['parent' => $parent_id], ['id' => $current_post]);
1755 $item['id'] = $current_post;
1756 $item['parent'] = $parent_id;
1758 // update the commented timestamp on the parent
1759 // Only update "commented" if it is really a comment
1760 if (($item['gravity'] != GRAVITY_ACTIVITY) || !Config::get("system", "like_no_comment")) {
1761 self::update(['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1763 self::update(['changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1768 * Friendica servers lower than 3.4.3-2 had double encoded the signature ...
1769 * We can check for this condition when we decode and encode the stuff again.
1771 if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) {
1772 $dsprsig->signature = base64_decode($dsprsig->signature);
1773 Logger::log("Repaired double encoded signature from handle ".$dsprsig->signer, Logger::DEBUG);
1776 if (!empty($dsprsig->signed_text) && empty($dsprsig->signature) && empty($dsprsig->signer)) {
1777 DBA::insert('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $dsprsig->signed_text], true);
1779 // The other fields are used by very old Friendica servers, so we currently store them differently
1780 DBA::insert('sign', ['iid' => $current_post, 'signed_text' => $dsprsig->signed_text,
1781 'signature' => $dsprsig->signature, 'signer' => $dsprsig->signer]);
1785 if (!empty($diaspora_signed_text)) {
1786 DBA::insert('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $diaspora_signed_text], true);
1789 $deleted = self::tagDeliver($item['uid'], $current_post);
1792 * current post can be deleted if is for a community page and no mention are
1795 if (!$deleted && !$dontcache) {
1796 $posted_item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $current_post]);
1797 if (DBA::isResult($posted_item)) {
1799 Addon::callHooks('post_local_end', $posted_item);
1801 Addon::callHooks('post_remote_end', $posted_item);
1804 Logger::log('new item not found in DB, id ' . $current_post);
1808 if ($item['parent-uri'] === $item['uri']) {
1809 self::addThread($current_post);
1811 self::updateThread($parent_id);
1814 $delivery_data['iid'] = $current_post;
1816 self::insertDeliveryData($delivery_data);
1821 * Due to deadlock issues with the "term" table we are doing these steps after the commit.
1822 * This is not perfect - but a workable solution until we found the reason for the problem.
1824 if (!empty($tags)) {
1825 Term::insertFromTagFieldByItemId($current_post, $tags);
1828 if (!empty($files)) {
1829 Term::insertFromFileFieldByItemId($current_post, $files);
1832 if ($item['parent-uri'] === $item['uri']) {
1833 self::addShadow($current_post);
1835 self::addShadowPost($current_post);
1838 check_user_notification($current_post);
1841 Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', $notify_type, $current_post);
1842 } elseif ($item['visible'] && ((!empty($parent) && $parent['origin']) || $item['origin'])) {
1843 if ($item['gravity'] == GRAVITY_ACTIVITY) {
1844 $cmd = $item['origin'] ? 'activity-new' : 'activity-import';
1845 } elseif ($item['gravity'] == GRAVITY_COMMENT) {
1846 $cmd = $item['origin'] ? 'comment-new' : 'comment-import';
1851 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', $cmd, $current_post);
1854 return $current_post;
1858 * @brief Insert a new item delivery data entry
1860 * @param array $item The item fields that are to be inserted
1862 private static function insertDeliveryData($delivery_data)
1864 if (empty($delivery_data['iid']) || (empty($delivery_data['postopts']) && empty($delivery_data['inform']))) {
1868 DBA::insert('item-delivery-data', $delivery_data);
1872 * @brief Update an existing item delivery data entry
1874 * @param integer $id The item id that is to be updated
1875 * @param array $item The item fields that are to be inserted
1877 private static function updateDeliveryData($id, $delivery_data)
1879 if (empty($id) || (empty($delivery_data['postopts']) && empty($delivery_data['inform']))) {
1883 DBA::update('item-delivery-data', $delivery_data, ['iid' => $id], true);
1887 * @brief Insert a new item content entry
1889 * @param array $item The item fields that are to be inserted
1891 private static function insertActivity(&$item)
1893 $activity_index = self::activityToIndex($item['verb']);
1895 if ($activity_index < 0) {
1899 $fields = ['activity' => $activity_index, 'uri-hash' => (string)$item['uri-id'], 'uri-id' => $item['uri-id']];
1901 // We just remove everything that is content
1902 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1903 unset($item[$field]);
1906 // To avoid timing problems, we are using locks.
1907 $locked = Lock::acquire('item_insert_activity');
1909 Logger::log("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
1912 // Do we already have this content?
1913 $item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-id' => $item['uri-id']]);
1914 if (DBA::isResult($item_activity)) {
1915 $item['iaid'] = $item_activity['id'];
1916 Logger::log('Fetched activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
1917 } elseif (DBA::insert('item-activity', $fields)) {
1918 $item['iaid'] = DBA::lastInsertId();
1919 Logger::log('Inserted activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
1921 // This shouldn't happen.
1922 Logger::log('Could not insert activity for URI ' . $item['uri'] . ' - should not happen');
1923 Lock::release('item_insert_activity');
1927 Lock::release('item_insert_activity');
1933 * @brief Insert a new item content entry
1935 * @param array $item The item fields that are to be inserted
1937 private static function insertContent(&$item)
1939 $fields = ['uri-plink-hash' => (string)$item['uri-id'], 'uri-id' => $item['uri-id']];
1941 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1942 if (isset($item[$field])) {
1943 $fields[$field] = $item[$field];
1944 unset($item[$field]);
1948 // To avoid timing problems, we are using locks.
1949 $locked = Lock::acquire('item_insert_content');
1951 Logger::log("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
1954 // Do we already have this content?
1955 $item_content = DBA::selectFirst('item-content', ['id'], ['uri-id' => $item['uri-id']]);
1956 if (DBA::isResult($item_content)) {
1957 $item['icid'] = $item_content['id'];
1958 Logger::log('Fetched content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
1959 } elseif (DBA::insert('item-content', $fields)) {
1960 $item['icid'] = DBA::lastInsertId();
1961 Logger::log('Inserted content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
1963 // This shouldn't happen.
1964 Logger::log('Could not insert content for URI ' . $item['uri'] . ' - should not happen');
1967 Lock::release('item_insert_content');
1972 * @brief Update existing item content entries
1974 * @param array $item The item fields that are to be changed
1975 * @param array $condition The condition for finding the item content entries
1977 private static function updateActivity($item, $condition)
1979 if (empty($item['verb'])) {
1982 $activity_index = self::activityToIndex($item['verb']);
1984 if ($activity_index < 0) {
1988 $fields = ['activity' => $activity_index];
1990 Logger::log('Update activity for ' . json_encode($condition));
1992 DBA::update('item-activity', $fields, $condition, true);
1998 * @brief Update existing item content entries
2000 * @param array $item The item fields that are to be changed
2001 * @param array $condition The condition for finding the item content entries
2003 private static function updateContent($item, $condition)
2005 // We have to select only the fields from the "item-content" table
2007 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
2008 if (isset($item[$field])) {
2009 $fields[$field] = $item[$field];
2013 if (empty($fields)) {
2014 // when there are no fields at all, just use the condition
2015 // This is to ensure that we always store content.
2016 $fields = $condition;
2019 Logger::log('Update content for ' . json_encode($condition));
2021 DBA::update('item-content', $fields, $condition, true);
2025 * @brief Distributes public items to the receivers
2027 * @param integer $itemid Item ID that should be added
2028 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
2030 public static function distribute($itemid, $signed_text = '')
2032 $condition = ["`id` IN (SELECT `parent` FROM `item` WHERE `id` = ?)", $itemid];
2033 $parent = self::selectFirst(['owner-id'], $condition);
2034 if (!DBA::isResult($parent)) {
2038 // Only distribute public items from native networks
2039 $condition = ['id' => $itemid, 'uid' => 0,
2040 'network' => [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""],
2041 'visible' => true, 'deleted' => false, 'moderated' => false, 'private' => false];
2042 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2043 if (!DBA::isResult($item)) {
2047 $origin = $item['origin'];
2050 unset($item['parent']);
2051 unset($item['mention']);
2052 unset($item['wall']);
2053 unset($item['origin']);
2054 unset($item['starred']);
2058 /// @todo add a field "pcid" in the contact table that referrs to the public contact id.
2059 $owner = DBA::selectFirst('contact', ['url', 'nurl', 'alias'], ['id' => $parent['owner-id']]);
2060 if (!DBA::isResult($owner)) {
2064 $condition = ['nurl' => $owner['nurl'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2065 $contacts = DBA::select('contact', ['uid'], $condition);
2066 while ($contact = DBA::fetch($contacts)) {
2067 if ($contact['uid'] == 0) {
2071 $users[$contact['uid']] = $contact['uid'];
2073 DBA::close($contacts);
2075 $condition = ['alias' => $owner['url'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2076 $contacts = DBA::select('contact', ['uid'], $condition);
2077 while ($contact = DBA::fetch($contacts)) {
2078 if ($contact['uid'] == 0) {
2082 $users[$contact['uid']] = $contact['uid'];
2084 DBA::close($contacts);
2086 if (!empty($owner['alias'])) {
2087 $condition = ['url' => $owner['alias'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2088 $contacts = DBA::select('contact', ['uid'], $condition);
2089 while ($contact = DBA::fetch($contacts)) {
2090 if ($contact['uid'] == 0) {
2094 $users[$contact['uid']] = $contact['uid'];
2096 DBA::close($contacts);
2101 if ($item['uri'] != $item['parent-uri']) {
2102 $parents = self::select(['uid', 'origin'], ["`uri` = ? AND `uid` != 0", $item['parent-uri']]);
2103 while ($parent = self::fetch($parents)) {
2104 $users[$parent['uid']] = $parent['uid'];
2105 if ($parent['origin'] && !$origin) {
2106 $origin_uid = $parent['uid'];
2111 foreach ($users as $uid) {
2112 if ($origin_uid == $uid) {
2113 $item['diaspora_signed_text'] = $signed_text;
2115 self::storeForUser($itemid, $item, $uid);
2120 * @brief Store public items for the receivers
2122 * @param integer $itemid Item ID that should be added
2123 * @param array $item The item entry that will be stored
2124 * @param integer $uid The user that will receive the item entry
2126 private static function storeForUser($itemid, $item, $uid)
2128 $item['uid'] = $uid;
2129 $item['origin'] = 0;
2131 if ($item['uri'] == $item['parent-uri']) {
2132 $item['contact-id'] = Contact::getIdForURL($item['owner-link'], $uid);
2134 $item['contact-id'] = Contact::getIdForURL($item['author-link'], $uid);
2137 if (empty($item['contact-id'])) {
2138 $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $uid]);
2139 if (!DBA::isResult($self)) {
2142 $item['contact-id'] = $self['id'];
2145 /// @todo Handling of "event-id"
2148 if ($item['uri'] == $item['parent-uri']) {
2149 $contact = DBA::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
2150 if (DBA::isResult($contact)) {
2151 $notify = self::isRemoteSelf($contact, $item);
2155 $distributed = self::insert($item, false, $notify, true);
2157 if (!$distributed) {
2158 Logger::log("Distributed public item " . $itemid . " for user " . $uid . " wasn't stored", Logger::DEBUG);
2160 Logger::log("Distributed public item " . $itemid . " for user " . $uid . " with id " . $distributed, Logger::DEBUG);
2165 * @brief Add a shadow entry for a given item id that is a thread starter
2167 * We store every public item entry additionally with the user id "0".
2168 * This is used for the community page and for the search.
2169 * It is planned that in the future we will store public item entries only once.
2171 * @param integer $itemid Item ID that should be added
2173 public static function addShadow($itemid)
2175 $fields = ['uid', 'private', 'moderated', 'visible', 'deleted', 'network', 'uri'];
2176 $condition = ['id' => $itemid, 'parent' => [0, $itemid]];
2177 $item = self::selectFirst($fields, $condition);
2179 if (!DBA::isResult($item)) {
2183 // is it already a copy?
2184 if (($itemid == 0) || ($item['uid'] == 0)) {
2188 // Is it a visible public post?
2189 if (!$item["visible"] || $item["deleted"] || $item["moderated"] || $item["private"]) {
2193 // is it an entry from a connector? Only add an entry for natively connected networks
2194 if (!in_array($item["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""])) {
2198 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2202 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2204 if (DBA::isResult($item)) {
2205 // Preparing public shadow (removing user specific data)
2208 unset($item['parent']);
2209 unset($item['wall']);
2210 unset($item['mention']);
2211 unset($item['origin']);
2212 unset($item['starred']);
2213 unset($item['postopts']);
2214 unset($item['inform']);
2215 if ($item['uri'] == $item['parent-uri']) {
2216 $item['contact-id'] = $item['owner-id'];
2218 $item['contact-id'] = $item['author-id'];
2221 $public_shadow = self::insert($item, false, false, true);
2223 Logger::log("Stored public shadow for thread ".$itemid." under id ".$public_shadow, Logger::DEBUG);
2228 * @brief Add a shadow entry for a given item id that is a comment
2230 * This function does the same like the function above - but for comments
2232 * @param integer $itemid Item ID that should be added
2234 public static function addShadowPost($itemid)
2236 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2237 if (!DBA::isResult($item)) {
2241 // Is it a toplevel post?
2242 if ($item['id'] == $item['parent']) {
2243 self::addShadow($itemid);
2247 // Is this a shadow entry?
2248 if ($item['uid'] == 0) {
2252 // Is there a shadow parent?
2253 if (!self::exists(['uri' => $item['parent-uri'], 'uid' => 0])) {
2257 // Is there already a shadow entry?
2258 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2262 // Save "origin" and "parent" state
2263 $origin = $item['origin'];
2264 $parent = $item['parent'];
2266 // Preparing public shadow (removing user specific data)
2269 unset($item['parent']);
2270 unset($item['wall']);
2271 unset($item['mention']);
2272 unset($item['origin']);
2273 unset($item['starred']);
2274 unset($item['postopts']);
2275 unset($item['inform']);
2276 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
2278 $public_shadow = self::insert($item, false, false, true);
2280 Logger::log("Stored public shadow for comment ".$item['uri']." under id ".$public_shadow, Logger::DEBUG);
2282 // If this was a comment to a Diaspora post we don't get our comment back.
2283 // This means that we have to distribute the comment by ourselves.
2284 if ($origin && self::exists(['id' => $parent, 'network' => Protocol::DIASPORA])) {
2285 self::distribute($public_shadow);
2290 * Adds a language specification in a "language" element of given $arr.
2291 * Expects "body" element to exist in $arr.
2293 private static function addLanguageToItemArray(&$item)
2295 $naked_body = BBCode::toPlaintext($item['body'], false);
2297 $ld = new Text_LanguageDetect();
2298 $ld->setNameMode(2);
2299 $languages = $ld->detect($naked_body, 3);
2301 if (is_array($languages)) {
2302 $item['language'] = json_encode($languages);
2307 * @brief Creates an unique guid out of a given uri
2309 * @param string $uri uri of an item entry
2310 * @param string $host hostname for the GUID prefix
2311 * @return string unique guid
2313 public static function guidFromUri($uri, $host)
2315 // Our regular guid routine is using this kind of prefix as well
2316 // We have to avoid that different routines could accidentally create the same value
2317 $parsed = parse_url($uri);
2319 // We use a hash of the hostname as prefix for the guid
2320 $guid_prefix = hash("crc32", $host);
2322 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
2323 unset($parsed["scheme"]);
2325 // Glue it together to be able to make a hash from it
2326 $host_id = implode("/", $parsed);
2328 // We could use any hash algorithm since it isn't a security issue
2329 $host_hash = hash("ripemd128", $host_id);
2331 return $guid_prefix.$host_hash;
2335 * generate an unique URI
2337 * @param integer $uid User id
2338 * @param string $guid An existing GUID (Otherwise it will be generated)
2342 public static function newURI($uid, $guid = "")
2345 $guid = System::createUUID();
2348 return self::getApp()->getBaseURL() . '/objects/' . $guid;
2352 * @brief Set "success_update" and "last-item" to the date of the last time we heard from this contact
2354 * This can be used to filter for inactive contacts.
2355 * Only do this for public postings to avoid privacy problems, since poco data is public.
2356 * Don't set this value if it isn't from the owner (could be an author that we don't know)
2358 * @param array $arr Contains the just posted item record
2360 private static function updateContact($arr)
2362 // Unarchive the author
2363 $contact = DBA::selectFirst('contact', [], ['id' => $arr["author-id"]]);
2364 if (DBA::isResult($contact)) {
2365 Contact::unmarkForArchival($contact);
2368 // Unarchive the contact if it's not our own contact
2369 $contact = DBA::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
2370 if (DBA::isResult($contact)) {
2371 Contact::unmarkForArchival($contact);
2374 $update = (!$arr['private'] && ((defaults($arr, 'author-link', '') === defaults($arr, 'owner-link', '')) || ($arr["parent-uri"] === $arr["uri"])));
2376 // Is it a forum? Then we don't care about the rules from above
2377 if (!$update && ($arr["network"] == Protocol::DFRN) && ($arr["parent-uri"] === $arr["uri"])) {
2378 if (DBA::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
2384 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2385 ['id' => $arr['contact-id']]);
2387 // Now do the same for the system wide contacts with uid=0
2388 if (!$arr['private']) {
2389 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2390 ['id' => $arr['owner-id']]);
2392 if ($arr['owner-id'] != $arr['author-id']) {
2393 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2394 ['id' => $arr['author-id']]);
2399 public static function setHashtags(&$item)
2402 $tags = BBCode::getTags($item["body"]);
2405 if (!count($tags)) {
2409 // This sorting is important when there are hashtags that are part of other hashtags
2410 // Otherwise there could be problems with hashtags like #test and #test2
2413 $URLSearchString = "^\[\]";
2415 // All hashtags should point to the home server if "local_tags" is activated
2416 if (Config::get('system', 'local_tags')) {
2417 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2418 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["body"]);
2420 $item["tag"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2421 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["tag"]);
2424 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
2425 $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2427 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
2430 $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
2432 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
2435 $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
2437 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
2440 // Repair recursive urls
2441 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2442 "#$2", $item["body"]);
2444 foreach ($tags as $tag) {
2445 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=')) {
2449 $basetag = str_replace('_',' ',substr($tag,1));
2451 $newtag = '#[url=' . System::baseUrl() . '/search?tag=' . $basetag . ']' . $basetag . '[/url]';
2453 $item["body"] = str_replace($tag, $newtag, $item["body"]);
2455 if (!stristr($item["tag"], "/search?tag=" . $basetag . "]" . $basetag . "[/url]")) {
2456 if (strlen($item["tag"])) {
2457 $item["tag"] = ',' . $item["tag"];
2459 $item["tag"] = $newtag . $item["tag"];
2463 // Convert back the masked hashtags
2464 $item["body"] = str_replace("#", "#", $item["body"]);
2467 public static function getGuidById($id)
2469 $item = self::selectFirst(['guid'], ['id' => $id]);
2470 if (DBA::isResult($item)) {
2471 return $item['guid'];
2478 * This function is only used for the old Friendica app on Android that doesn't like paths with guid
2479 * @param string $guid item guid
2480 * @param int $uid user id
2481 * @return array with id and nick of the item with the given guid
2483 public static function getIdAndNickByGuid($guid, $uid = 0)
2489 $uid == local_user();
2492 // Does the given user have this item?
2494 $item = self::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
2495 if (DBA::isResult($item)) {
2496 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $uid]);
2497 if (!DBA::isResult($user)) {
2501 $nick = $user['nickname'];
2505 // Or is it anywhere on the server?
2507 $condition = ["`guid` = ? AND `uid` != 0", $guid];
2508 $item = self::selectFirst(['id', 'uid'], $condition);
2509 if (DBA::isResult($item)) {
2510 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $item['uid']]);
2511 if (!DBA::isResult($user)) {
2515 $nick = $user['nickname'];
2518 return ["nick" => $nick, "id" => $id];
2522 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
2524 * @param int $item_id
2525 * @return bool true if item was deleted, else false
2527 private static function tagDeliver($uid, $item_id)
2531 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
2532 if (!DBA::isResult($user)) {
2536 $community_page = (($user['page-flags'] == Contact::PAGE_COMMUNITY) ? true : false);
2537 $prvgroup = (($user['page-flags'] == Contact::PAGE_PRVGROUP) ? true : false);
2539 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2540 if (!DBA::isResult($item)) {
2544 $link = Strings::normaliseLink(System::baseUrl() . '/profile/' . $user['nickname']);
2547 * Diaspora uses their own hardwired link URL in @-tags
2548 * instead of the one we supply with webfinger
2550 $dlink = Strings::normaliseLink(System::baseUrl() . '/u/' . $user['nickname']);
2552 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
2554 foreach ($matches as $mtch) {
2555 if (Strings::compareLink($link, $mtch[1]) || Strings::compareLink($dlink, $mtch[1])) {
2557 Logger::log('mention found: ' . $mtch[2]);
2563 if (($community_page || $prvgroup) &&
2564 !$item['wall'] && !$item['origin'] && ($item['id'] == $item['parent'])) {
2565 // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
2567 Logger::log("no-mention top-level post to community or private group. delete.");
2568 DBA::delete('item', ['id' => $item_id]);
2574 $arr = ['item' => $item, 'user' => $user];
2576 Addon::callHooks('tagged', $arr);
2578 if (!$community_page && !$prvgroup) {
2583 * tgroup delivery - setup a second delivery chain
2584 * prevent delivery looping - only proceed
2585 * if the message originated elsewhere and is a top-level post
2587 if ($item['wall'] || $item['origin'] || ($item['id'] != $item['parent'])) {
2591 // now change this copy of the post to a forum head message and deliver to all the tgroup members
2592 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'], ['uid' => $uid, 'self' => true]);
2593 if (!DBA::isResult($self)) {
2597 $owner_id = Contact::getIdForURL($self['url']);
2599 // also reset all the privacy bits to the forum default permissions
2601 $private = ($user['allow_cid'] || $user['allow_gid'] || $user['deny_cid'] || $user['deny_gid']) ? 1 : 0;
2603 $psid = PermissionSet::fetchIDForPost($user);
2605 $forum_mode = ($prvgroup ? 2 : 1);
2607 $fields = ['wall' => true, 'origin' => true, 'forum_mode' => $forum_mode, 'contact-id' => $self['id'],
2608 'owner-id' => $owner_id, 'private' => $private, 'psid' => $psid];
2609 self::update($fields, ['id' => $item_id]);
2611 self::updateThread($item_id);
2613 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', 'tgroup', $item_id);
2616 public static function isRemoteSelf($contact, &$datarray)
2620 if (!$contact['remote_self']) {
2624 // Prevent the forwarding of posts that are forwarded
2625 if (!empty($datarray["extid"]) && ($datarray["extid"] == Protocol::DFRN)) {
2626 Logger::log('Already forwarded', Logger::DEBUG);
2630 // Prevent to forward already forwarded posts
2631 if ($datarray["app"] == $a->getHostName()) {
2632 Logger::log('Already forwarded (second test)', Logger::DEBUG);
2636 // Only forward posts
2637 if ($datarray["verb"] != ACTIVITY_POST) {
2638 Logger::log('No post', Logger::DEBUG);
2642 if (($contact['network'] != Protocol::FEED) && $datarray['private']) {
2643 Logger::log('Not public', Logger::DEBUG);
2647 $datarray2 = $datarray;
2648 Logger::log('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), Logger::DEBUG);
2649 if ($contact['remote_self'] == 2) {
2650 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
2651 ['uid' => $contact['uid'], 'self' => true]);
2652 if (DBA::isResult($self)) {
2653 $datarray['contact-id'] = $self["id"];
2655 $datarray['owner-name'] = $self["name"];
2656 $datarray['owner-link'] = $self["url"];
2657 $datarray['owner-avatar'] = $self["thumb"];
2659 $datarray['author-name'] = $datarray['owner-name'];
2660 $datarray['author-link'] = $datarray['owner-link'];
2661 $datarray['author-avatar'] = $datarray['owner-avatar'];
2663 unset($datarray['created']);
2664 unset($datarray['edited']);
2666 unset($datarray['network']);
2667 unset($datarray['owner-id']);
2668 unset($datarray['author-id']);
2671 if ($contact['network'] != Protocol::FEED) {
2672 $datarray["guid"] = System::createUUID();
2673 unset($datarray["plink"]);
2674 $datarray["uri"] = self::newURI($contact['uid'], $datarray["guid"]);
2675 $datarray["parent-uri"] = $datarray["uri"];
2676 $datarray["thr-parent"] = $datarray["uri"];
2677 $datarray["extid"] = Protocol::DFRN;
2678 $urlpart = parse_url($datarray2['author-link']);
2679 $datarray["app"] = $urlpart["host"];
2681 $datarray['private'] = 0;
2685 if ($contact['network'] != Protocol::FEED) {
2686 // Store the original post
2687 $result = self::insert($datarray2, false, false);
2688 Logger::log('remote-self post original item - Contact '.$contact['url'].' return '.$result.' Item '.print_r($datarray2, true), Logger::DEBUG);
2690 $datarray["app"] = "Feed";
2694 // Trigger automatic reactions for addons
2695 $datarray['api_source'] = true;
2697 // We have to tell the hooks who we are - this really should be improved
2698 $_SESSION["authenticated"] = true;
2699 $_SESSION["uid"] = $contact['uid'];
2708 * @param array $item
2712 public static function fixPrivatePhotos($s, $uid, $item = null, $cid = 0)
2714 if (Config::get('system', 'disable_embedded')) {
2718 Logger::log('check for photos', Logger::DEBUG);
2719 $site = substr(System::baseUrl(), strpos(System::baseUrl(), '://'));
2724 $img_start = strpos($orig_body, '[img');
2725 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2726 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2728 while (($img_st_close !== false) && ($img_len !== false)) {
2729 $img_st_close++; // make it point to AFTER the closing bracket
2730 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2732 Logger::log('found photo ' . $image, Logger::DEBUG);
2734 if (stristr($image, $site . '/photo/')) {
2735 // Only embed locally hosted photos
2737 $i = basename($image);
2738 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2739 $x = strpos($i, '-');
2742 $res = substr($i, $x + 1);
2743 $i = substr($i, 0, $x);
2744 $fields = ['data', 'type', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'];
2745 $photo = DBA::selectFirst('photo', $fields, ['resource-id' => $i, 'scale' => $res, 'uid' => $uid]);
2746 if (DBA::isResult($photo)) {
2748 * Check to see if we should replace this photo link with an embedded image
2749 * 1. No need to do so if the photo is public
2750 * 2. If there's a contact-id provided, see if they're in the access list
2751 * for the photo. If so, embed it.
2752 * 3. Otherwise, if we have an item, see if the item permissions match the photo
2753 * permissions, regardless of order but first check to see if they're an exact
2754 * match to save some processing overhead.
2756 if (self::hasPermissions($photo)) {
2758 $recips = self::enumeratePermissions($photo);
2759 if (in_array($cid, $recips)) {
2763 if (self::samePermissions($item, $photo)) {
2769 $data = $photo['data'];
2770 $type = $photo['type'];
2772 // If a custom width and height were specified, apply before embedding
2773 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2774 Logger::log('scaling photo', Logger::DEBUG);
2776 $width = intval($match[1]);
2777 $height = intval($match[2]);
2779 $Image = new Image($data, $type);
2780 if ($Image->isValid()) {
2781 $Image->scaleDown(max($width, $height));
2782 $data = $Image->asString();
2783 $type = $Image->getType();
2787 Logger::log('replacing photo', Logger::DEBUG);
2788 $image = 'data:' . $type . ';base64,' . base64_encode($data);
2789 Logger::log('replaced: ' . $image, Logger::DATA);
2795 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2796 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2797 if ($orig_body === false) {
2801 $img_start = strpos($orig_body, '[img');
2802 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2803 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2806 $new_body = $new_body . $orig_body;
2811 private static function hasPermissions($obj)
2813 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2814 !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2817 private static function samePermissions($obj1, $obj2)
2819 // first part is easy. Check that these are exactly the same.
2820 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2821 && ($obj1['allow_gid'] == $obj2['allow_gid'])
2822 && ($obj1['deny_cid'] == $obj2['deny_cid'])
2823 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
2827 // This is harder. Parse all the permissions and compare the resulting set.
2828 $recipients1 = self::enumeratePermissions($obj1);
2829 $recipients2 = self::enumeratePermissions($obj2);
2833 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2834 return ($recipients1 == $recipients2);
2837 // returns an array of contact-ids that are allowed to see this object
2838 public static function enumeratePermissions($obj)
2840 $allow_people = expand_acl($obj['allow_cid']);
2841 $allow_groups = Group::expand(expand_acl($obj['allow_gid']));
2842 $deny_people = expand_acl($obj['deny_cid']);
2843 $deny_groups = Group::expand(expand_acl($obj['deny_gid']));
2844 $recipients = array_unique(array_merge($allow_people, $allow_groups));
2845 $deny = array_unique(array_merge($deny_people, $deny_groups));
2846 $recipients = array_diff($recipients, $deny);
2850 public static function getFeedTags($item)
2854 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2856 for ($x = 0; $x < $cnt; $x ++) {
2857 if ($matches[1][$x]) {
2858 $ret[$matches[2][$x]] = ['#', $matches[1][$x], $matches[2][$x]];
2863 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2865 for ($x = 0; $x < $cnt; $x ++) {
2866 if ($matches[1][$x]) {
2867 $ret[] = ['@', $matches[1][$x], $matches[2][$x]];
2874 public static function expire($uid, $days, $network = "", $force = false)
2876 if (!$uid || ($days < 1)) {
2880 $condition = ["`uid` = ? AND NOT `deleted` AND `id` = `parent` AND `gravity` = ?",
2881 $uid, GRAVITY_PARENT];
2884 * $expire_network_only = save your own wall posts
2885 * and just expire conversations started by others
2887 $expire_network_only = PConfig::get($uid, 'expire', 'network_only', false);
2889 if ($expire_network_only) {
2890 $condition[0] .= " AND NOT `wall`";
2893 if ($network != "") {
2894 $condition[0] .= " AND `network` = ?";
2895 $condition[] = $network;
2898 * There is an index "uid_network_received" but not "uid_network_created"
2899 * This avoids the creation of another index just for one purpose.
2900 * And it doesn't really matter wether to look at "received" or "created"
2902 $condition[0] .= " AND `received` < UTC_TIMESTAMP() - INTERVAL ? DAY";
2903 $condition[] = $days;
2905 $condition[0] .= " AND `created` < UTC_TIMESTAMP() - INTERVAL ? DAY";
2906 $condition[] = $days;
2909 $items = self::select(['file', 'resource-id', 'starred', 'type', 'id', 'post-type'], $condition);
2911 if (!DBA::isResult($items)) {
2915 $expire_items = PConfig::get($uid, 'expire', 'items', true);
2917 // Forcing expiring of items - but not notes and marked items
2919 $expire_items = true;
2922 $expire_notes = PConfig::get($uid, 'expire', 'notes', true);
2923 $expire_starred = PConfig::get($uid, 'expire', 'starred', true);
2924 $expire_photos = PConfig::get($uid, 'expire', 'photos', false);
2928 while ($item = Item::fetch($items)) {
2929 // don't expire filed items
2931 if (strpos($item['file'], '[') !== false) {
2935 // Only expire posts, not photos and photo comments
2937 if (!$expire_photos && strlen($item['resource-id'])) {
2939 } elseif (!$expire_starred && intval($item['starred'])) {
2941 } elseif (!$expire_notes && (($item['type'] == 'note') || ($item['post-type'] == Item::PT_PERSONAL_NOTE))) {
2943 } elseif (!$expire_items && ($item['type'] != 'note') && ($item['post-type'] != Item::PT_PERSONAL_NOTE)) {
2947 self::deleteById($item['id'], PRIORITY_LOW);
2952 Logger::log('User ' . $uid . ": expired $expired items; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
2955 public static function firstPostDate($uid, $wall = false)
2957 $condition = ['uid' => $uid, 'wall' => $wall, 'deleted' => false, 'visible' => true, 'moderated' => false];
2958 $params = ['order' => ['created' => false]];
2959 $thread = DBA::selectFirst('thread', ['created'], $condition, $params);
2960 if (DBA::isResult($thread)) {
2961 return substr(DateTimeFormat::local($thread['created']), 0, 10);
2967 * @brief add/remove activity to an item
2969 * Toggle activities as like,dislike,attend of an item
2971 * @param string $item_id
2972 * @param string $verb
2973 * Activity verb. One of
2974 * like, unlike, dislike, undislike, attendyes, unattendyes,
2975 * attendno, unattendno, attendmaybe, unattendmaybe
2976 * @hook 'post_local_end'
2978 * 'post_id' => ID of posted item
2980 public static function performLike($item_id, $verb)
2982 if (!local_user() && !remote_user()) {
2989 $activity = ACTIVITY_LIKE;
2993 $activity = ACTIVITY_DISLIKE;
2997 $activity = ACTIVITY_ATTEND;
3001 $activity = ACTIVITY_ATTENDNO;
3004 case 'unattendmaybe':
3005 $activity = ACTIVITY_ATTENDMAYBE;
3008 Logger::log('like: unknown verb ' . $verb . ' for item ' . $item_id);
3012 // Enable activity toggling instead of on/off
3013 $event_verb_flag = $activity === ACTIVITY_ATTEND || $activity === ACTIVITY_ATTENDNO || $activity === ACTIVITY_ATTENDMAYBE;
3015 Logger::log('like: verb ' . $verb . ' item ' . $item_id);
3017 $item = self::selectFirst(self::ITEM_FIELDLIST, ['`id` = ? OR `uri` = ?', $item_id, $item_id]);
3018 if (!DBA::isResult($item)) {
3019 Logger::log('like: unknown item ' . $item_id);
3023 $item_uri = $item['uri'];
3025 $uid = $item['uid'];
3026 if (($uid == 0) && local_user()) {
3027 $uid = local_user();
3030 if (!Security::canWriteToUserWall($uid)) {
3031 Logger::log('like: unable to write on wall ' . $uid);
3035 // Retrieves the local post owner
3036 $owner_self_contact = DBA::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
3037 if (!DBA::isResult($owner_self_contact)) {
3038 Logger::log('like: unknown owner ' . $uid);
3042 // Retrieve the current logged in user's public contact
3043 $author_id = public_contact();
3045 $author_contact = DBA::selectFirst('contact', ['url'], ['id' => $author_id]);
3046 if (!DBA::isResult($author_contact)) {
3047 Logger::log('like: unknown author ' . $author_id);
3051 // Contact-id is the uid-dependant author contact
3052 if (local_user() == $uid) {
3053 $item_contact_id = $owner_self_contact['id'];
3054 $item_contact = $owner_self_contact;
3056 $item_contact_id = Contact::getIdForURL($author_contact['url'], $uid, true);
3057 $item_contact = DBA::selectFirst('contact', [], ['id' => $item_contact_id]);
3058 if (!DBA::isResult($item_contact)) {
3059 Logger::log('like: unknown item contact ' . $item_contact_id);
3064 // Look for an existing verb row
3065 // event participation are essentially radio toggles. If you make a subsequent choice,
3066 // we need to eradicate your first choice.
3067 if ($event_verb_flag) {
3068 $verbs = [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE];
3070 // Translate to the index based activity index
3072 foreach ($verbs as $verb) {
3073 $activities[] = self::activityToIndex($verb);
3076 $activities = self::activityToIndex($activity);
3079 $condition = ['activity' => $activities, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY,
3080 'author-id' => $author_id, 'uid' => $item['uid'], 'thr-parent' => $item_uri];
3082 $like_item = self::selectFirst(['id', 'guid', 'verb'], $condition);
3084 // If it exists, mark it as deleted
3085 if (DBA::isResult($like_item)) {
3086 self::deleteById($like_item['id']);
3088 if (!$event_verb_flag || $like_item['verb'] == $activity) {
3093 // Verb is "un-something", just trying to delete existing entries
3094 if (strpos($verb, 'un') === 0) {
3098 $objtype = $item['resource-id'] ? ACTIVITY_OBJ_IMAGE : ACTIVITY_OBJ_NOTE;
3101 'guid' => System::createUUID(),
3102 'uri' => self::newURI($item['uid']),
3103 'uid' => $item['uid'],
3104 'contact-id' => $item_contact_id,
3105 'wall' => $item['wall'],
3107 'network' => Protocol::DFRN,
3108 'gravity' => GRAVITY_ACTIVITY,
3109 'parent' => $item['id'],
3110 'parent-uri' => $item['uri'],
3111 'thr-parent' => $item['uri'],
3112 'owner-id' => $author_id,
3113 'author-id' => $author_id,
3114 'body' => $activity,
3115 'verb' => $activity,
3116 'object-type' => $objtype,
3117 'allow_cid' => $item['allow_cid'],
3118 'allow_gid' => $item['allow_gid'],
3119 'deny_cid' => $item['deny_cid'],
3120 'deny_gid' => $item['deny_gid'],
3125 $signed = Diaspora::createLikeSignature($uid, $new_item);
3126 if (!empty($signed)) {
3127 $new_item['diaspora_signed_text'] = json_encode($signed);
3130 $new_item_id = self::insert($new_item);
3132 // If the parent item isn't visible then set it to visible
3133 if (!$item['visible']) {
3134 self::update(['visible' => true], ['id' => $item['id']]);
3137 $new_item['id'] = $new_item_id;
3139 Addon::callHooks('post_local_end', $new_item);
3144 private static function addThread($itemid, $onlyshadow = false)
3146 $fields = ['uid', 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private', 'pubmail',
3147 'moderated', 'visible', 'starred', 'contact-id', 'post-type',
3148 'deleted', 'origin', 'forum_mode', 'mention', 'network', 'author-id', 'owner-id'];
3149 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
3150 $item = self::selectFirst($fields, $condition);
3152 if (!DBA::isResult($item)) {
3156 $item['iid'] = $itemid;
3159 $result = DBA::insert('thread', $item);
3161 Logger::log("Add thread for item ".$itemid." - ".print_r($result, true), Logger::DEBUG);
3165 private static function updateThread($itemid, $setmention = false)
3167 $fields = ['uid', 'guid', 'created', 'edited', 'commented', 'received', 'changed', 'post-type',
3168 'wall', 'private', 'pubmail', 'moderated', 'visible', 'starred', 'contact-id',
3169 'deleted', 'origin', 'forum_mode', 'network', 'author-id', 'owner-id'];
3170 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
3172 $item = self::selectFirst($fields, $condition);
3173 if (!DBA::isResult($item)) {
3178 $item["mention"] = 1;
3185 foreach ($item as $field => $data) {
3186 if (!in_array($field, ["guid"])) {
3187 $fields[$field] = $data;
3191 $result = DBA::update('thread', $fields, ['iid' => $itemid]);
3193 Logger::log("Update thread for item ".$itemid." - guid ".$item["guid"]." - ".(int)$result, Logger::DEBUG);
3196 private static function deleteThread($itemid, $itemuri = "")
3198 $item = DBA::selectFirst('thread', ['uid'], ['iid' => $itemid]);
3199 if (!DBA::isResult($item)) {
3200 Logger::log('No thread found for id '.$itemid, Logger::DEBUG);
3204 $result = DBA::delete('thread', ['iid' => $itemid], ['cascade' => false]);
3206 Logger::log("deleteThread: Deleted thread for item ".$itemid." - ".print_r($result, true), Logger::DEBUG);
3208 if ($itemuri != "") {
3209 $condition = ["`uri` = ? AND NOT `deleted` AND NOT (`uid` IN (?, 0))", $itemuri, $item["uid"]];
3210 if (!self::exists($condition)) {
3211 DBA::delete('item', ['uri' => $itemuri, 'uid' => 0]);
3212 Logger::log("deleteThread: Deleted shadow for item ".$itemuri, Logger::DEBUG);
3217 public static function getPermissionsSQLByUserId($owner_id, $remote_verified = false, $groups = null)
3219 $local_user = local_user();
3220 $remote_user = remote_user();
3223 * Construct permissions
3225 * default permissions - anonymous user
3227 $sql = " AND NOT `item`.`private`";
3229 // Profile owner - everything is visible
3230 if ($local_user && ($local_user == $owner_id)) {
3232 } elseif ($remote_user) {
3234 * Authenticated visitor. Unless pre-verified,
3235 * check that the contact belongs to this $owner_id
3236 * and load the groups the visitor belongs to.
3237 * If pre-verified, the caller is expected to have already
3238 * done this and passed the groups into this function.
3240 $set = PermissionSet::get($owner_id, $remote_user, $groups);
3243 $sql_set = " OR (`item`.`private` IN (1,2) AND `item`.`wall` AND `item`.`psid` IN (" . implode(',', $set) . "))";
3248 $sql = " AND (NOT `item`.`private`" . $sql_set . ")";
3255 * get translated item type
3257 * @param array $itme
3260 public static function postType($item)
3262 if (!empty($item['event-id'])) {
3263 return L10n::t('event');
3264 } elseif (!empty($item['resource-id'])) {
3265 return L10n::t('photo');
3266 } elseif (!empty($item['verb']) && $item['verb'] !== ACTIVITY_POST) {
3267 return L10n::t('activity');
3268 } elseif ($item['id'] != $item['parent']) {
3269 return L10n::t('comment');
3272 return L10n::t('post');
3276 * Sets the "rendered-html" field of the provided item
3278 * Body is preserved to avoid side-effects as we modify it just-in-time for spoilers and private image links
3280 * @param array $item
3281 * @param bool $update
3283 * @todo Remove reference, simply return "rendered-html" and "rendered-hash"
3285 public static function putInCache(&$item, $update = false)
3287 $body = $item["body"];
3289 $rendered_hash = defaults($item, 'rendered-hash', '');
3290 $rendered_html = defaults($item, 'rendered-html', '');
3292 if ($rendered_hash == ''
3293 || $rendered_html == ""
3294 || $rendered_hash != hash("md5", $item["body"])
3295 || Config::get("system", "ignore_cache")
3297 $a = self::getApp();
3298 redir_private_images($a, $item);
3300 $item["rendered-html"] = prepare_text($item["body"]);
3301 $item["rendered-hash"] = hash("md5", $item["body"]);
3303 $hook_data = ['item' => $item, 'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']];
3304 Addon::callHooks('put_item_in_cache', $hook_data);
3305 $item['rendered-html'] = $hook_data['rendered-html'];
3306 $item['rendered-hash'] = $hook_data['rendered-hash'];
3309 // Force an update if the generated values differ from the existing ones
3310 if ($rendered_hash != $item["rendered-hash"]) {
3314 // Only compare the HTML when we forcefully ignore the cache
3315 if (Config::get("system", "ignore_cache") && ($rendered_html != $item["rendered-html"])) {
3319 if ($update && !empty($item["id"])) {
3322 'rendered-html' => $item["rendered-html"],
3323 'rendered-hash' => $item["rendered-hash"]
3325 ['id' => $item["id"]]
3330 $item["body"] = $body;
3334 * @brief Given an item array, convert the body element from bbcode to html and add smilie icons.
3335 * If attach is true, also add icons for item attachments.
3337 * @param array $item
3338 * @param boolean $attach
3339 * @param boolean $is_preview
3340 * @return string item body html
3341 * @hook prepare_body_init item array before any work
3342 * @hook prepare_body_content_filter ('item'=>item array, 'filter_reasons'=>string array) before first bbcode to html
3343 * @hook prepare_body ('item'=>item array, 'html'=>body string, 'is_preview'=>boolean, 'filter_reasons'=>string array) after first bbcode to html
3344 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
3346 public static function prepareBody(array &$item, $attach = false, $is_preview = false)
3348 $a = self::getApp();
3349 Addon::callHooks('prepare_body_init', $item);
3351 // In order to provide theme developers more possibilities, event items
3352 // are treated differently.
3353 if ($item['object-type'] === ACTIVITY_OBJ_EVENT && isset($item['event-id'])) {
3354 $ev = Event::getItemHTML($item);
3358 $tags = Term::populateTagsFromItem($item);
3360 $item['tags'] = $tags['tags'];
3361 $item['hashtags'] = $tags['hashtags'];
3362 $item['mentions'] = $tags['mentions'];
3364 // Compile eventual content filter reasons
3365 $filter_reasons = [];
3366 if (!$is_preview && public_contact() != $item['author-id']) {
3367 if (!empty($item['content-warning']) && (!local_user() || !PConfig::get(local_user(), 'system', 'disable_cw', false))) {
3368 $filter_reasons[] = L10n::t('Content warning: %s', $item['content-warning']);
3373 'filter_reasons' => $filter_reasons
3375 Addon::callHooks('prepare_body_content_filter', $hook_data);
3376 $filter_reasons = $hook_data['filter_reasons'];
3380 // Update the cached values if there is no "zrl=..." on the links.
3381 $update = (!local_user() && !remote_user() && ($item["uid"] == 0));
3383 // Or update it if the current viewer is the intented viewer.
3384 if (($item["uid"] == local_user()) && ($item["uid"] != 0)) {
3388 self::putInCache($item, $update);
3389 $s = $item["rendered-html"];
3394 'preview' => $is_preview,
3395 'filter_reasons' => $filter_reasons
3397 Addon::callHooks('prepare_body', $hook_data);
3398 $s = $hook_data['html'];
3402 // Replace the blockquotes with quotes that are used in mails.
3403 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
3404 $s = str_replace(['<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'], [$mailquote, $mailquote, $mailquote], $s);
3411 preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\"(?: title=\"(.*?)\")?|', $item['attach'], $matches, PREG_SET_ORDER);
3412 foreach ($matches as $mtch) {
3415 $the_url = Contact::magicLinkById($item['author-id'], $mtch[1]);
3417 if (strpos($mime, 'video') !== false) {
3420 $a->page['htmlhead'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate('videos_head.tpl'), [
3421 '$baseurl' => System::baseUrl(),
3425 $url_parts = explode('/', $the_url);
3426 $id = end($url_parts);
3427 $as .= Renderer::replaceMacros(Renderer::getMarkupTemplate('video_top.tpl'), [
3430 'title' => L10n::t('View Video'),
3437 $filetype = strtolower(substr($mime, 0, strpos($mime, '/')));
3439 $filesubtype = strtolower(substr($mime, strpos($mime, '/') + 1));
3440 $filesubtype = str_replace('.', '-', $filesubtype);
3443 $filesubtype = 'unkn';
3446 $title = Strings::escapeHtml(trim(defaults($mtch, 4, $mtch[1])));
3447 $title .= ' ' . $mtch[2] . ' ' . L10n::t('bytes');
3449 $icon = '<div class="attachtype icon s22 type-' . $filetype . ' subtype-' . $filesubtype . '"></div>';
3450 $as .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" >' . $icon . '</a>';
3454 $s .= '<div class="body-attach">'.$as.'<div class="clear"></div></div>';
3458 if (strpos($s, '<div class="map">') !== false && !empty($item['coord'])) {
3459 $x = Map::byCoordinates(trim($item['coord']));
3461 $s = preg_replace('/\<div class\=\"map\"\>/', '$0' . $x, $s);
3466 // Look for spoiler.
3467 $spoilersearch = '<blockquote class="spoiler">';
3469 // Remove line breaks before the spoiler.
3470 while ((strpos($s, "\n" . $spoilersearch) !== false)) {
3471 $s = str_replace("\n" . $spoilersearch, $spoilersearch, $s);
3473 while ((strpos($s, "<br />" . $spoilersearch) !== false)) {
3474 $s = str_replace("<br />" . $spoilersearch, $spoilersearch, $s);
3477 while ((strpos($s, $spoilersearch) !== false)) {
3478 $pos = strpos($s, $spoilersearch);
3479 $rnd = Strings::getRandomHex(8);
3480 $spoilerreplace = '<br /> <span id="spoiler-wrap-' . $rnd . '" class="spoiler-wrap fakelink" onclick="openClose(\'spoiler-' . $rnd . '\');">' . L10n::t('Click to open/close') . '</span>'.
3481 '<blockquote class="spoiler" id="spoiler-' . $rnd . '" style="display: none;">';
3482 $s = substr($s, 0, $pos) . $spoilerreplace . substr($s, $pos + strlen($spoilersearch));
3485 // Look for quote with author.
3486 $authorsearch = '<blockquote class="author">';
3488 while ((strpos($s, $authorsearch) !== false)) {
3489 $pos = strpos($s, $authorsearch);
3490 $rnd = Strings::getRandomHex(8);
3491 $authorreplace = '<br /> <span id="author-wrap-' . $rnd . '" class="author-wrap fakelink" onclick="openClose(\'author-' . $rnd . '\');">' . L10n::t('Click to open/close') . '</span>'.
3492 '<blockquote class="author" id="author-' . $rnd . '" style="display: block;">';
3493 $s = substr($s, 0, $pos) . $authorreplace . substr($s, $pos + strlen($authorsearch));
3496 // Replace friendica image url size with theme preference.
3497 if (!empty($a->theme_info['item_image_size'])) {
3498 $ps = $a->theme_info['item_image_size'];
3499 $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
3502 $s = HTML::applyContentFilter($s, $filter_reasons);
3504 $hook_data = ['item' => $item, 'html' => $s];
3505 Addon::callHooks('prepare_body_final', $hook_data);
3507 return $hook_data['html'];
3511 * get private link for item
3512 * @param array $item
3513 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
3515 public static function getPlink($item)
3517 $a = self::getApp();
3519 if ($a->user['nickname'] != "") {
3521 'href' => "display/" . $item['guid'],
3522 'orig' => "display/" . $item['guid'],
3523 'title' => L10n::t('View on separate page'),
3524 'orig_title' => L10n::t('view on separate page'),
3527 if (!empty($item['plink'])) {
3528 $ret["href"] = $a->removeBaseURL($item['plink']);
3529 $ret["title"] = L10n::t('link to source');
3532 } elseif (!empty($item['plink']) && ($item['private'] != 1)) {
3534 'href' => $item['plink'],
3535 'orig' => $item['plink'],
3536 'title' => L10n::t('link to source'),