4 * @file src/Model/Item.php
7 namespace Friendica\Model;
9 use Friendica\BaseObject;
10 use Friendica\Content\Text\BBCode;
11 use Friendica\Core\Addon;
12 use Friendica\Core\Config;
13 use Friendica\Core\Lock;
14 use Friendica\Core\PConfig;
15 use Friendica\Core\System;
16 use Friendica\Core\Worker;
17 use Friendica\Database\DBA;
18 use Friendica\Model\Contact;
19 use Friendica\Model\PermissionSet;
20 use Friendica\Model\ItemURI;
21 use Friendica\Object\Image;
22 use Friendica\Protocol\Diaspora;
23 use Friendica\Protocol\OStatus;
24 use Friendica\Util\DateTimeFormat;
25 use Friendica\Util\XML;
26 use Text_LanguageDetect;
28 require_once 'boot.php';
29 require_once 'include/items.php';
30 require_once 'include/text.php';
32 class Item extends BaseObject
34 // Posting types, inspired by https://www.w3.org/TR/activitystreams-vocabulary/#object-types
41 const PT_DOCUMENT = 19;
43 const PT_PERSONAL_NOTE = 128;
45 // Field list that is used to display the items
46 const DISPLAY_FIELDLIST = ['uid', 'id', 'parent', 'uri', 'thr-parent', 'parent-uri', 'guid', 'network',
47 'commented', 'created', 'edited', 'received', 'verb', 'object-type', 'postopts', 'plink',
48 'wall', 'private', 'starred', 'origin', 'title', 'body', 'file', 'attach', 'language',
49 'content-warning', 'location', 'coord', 'app', 'rendered-hash', 'rendered-html', 'object',
50 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'item_id',
51 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
52 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'owner-network',
53 'contact-id', 'contact-link', 'contact-name', 'contact-avatar',
54 'writable', 'self', 'cid', 'alias',
55 'event-id', 'event-created', 'event-edited', 'event-start', 'event-finish',
56 'event-summary', 'event-desc', 'event-location', 'event-type',
57 'event-nofinish', 'event-adjust', 'event-ignore', 'event-id'];
59 // Field list that is used to deliver items via the protocols
60 const DELIVER_FIELDLIST = ['uid', 'id', 'parent', 'uri', 'thr-parent', 'parent-uri', 'guid',
61 'created', 'edited', 'verb', 'object-type', 'object', 'target',
62 'private', 'title', 'body', 'location', 'coord', 'app',
63 'attach', 'tag', 'deleted', 'extid', 'post-type',
64 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
65 'author-id', 'author-link', 'owner-link', 'contact-uid',
66 'signed_text', 'signature', 'signer', 'network'];
68 // Field list for "item-content" table that is mixed with the item table
69 const MIXED_CONTENT_FIELDLIST = ['title', 'content-warning', 'body', 'location',
70 'coord', 'app', 'rendered-hash', 'rendered-html', 'verb',
71 'object-type', 'object', 'target-type', 'target', 'plink'];
73 // Field list for "item-content" table that is not present in the "item" table
74 const CONTENT_FIELDLIST = ['language'];
76 // Field list for additional delivery data
77 const DELIVERY_DATA_FIELDLIST = ['postopts', 'inform'];
79 // All fields in the item table
80 const ITEM_FIELDLIST = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
81 'contact-id', 'type', 'wall', 'gravity', 'extid', 'icid', 'iaid', 'psid',
82 'created', 'edited', 'commented', 'received', 'changed', 'verb',
83 'postopts', 'plink', 'resource-id', 'event-id', 'tag', 'attach', 'inform',
84 'file', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'post-type',
85 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
86 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global', 'network',
87 'title', 'content-warning', 'body', 'location', 'coord', 'app',
88 'rendered-hash', 'rendered-html', 'object-type', 'object', 'target-type', 'target',
89 'author-id', 'author-link', 'author-name', 'author-avatar',
90 'owner-id', 'owner-link', 'owner-name', 'owner-avatar'];
92 // Never reorder or remove entries from this list. Just add new ones at the end, if needed.
93 // The item-activity table only stores the index and needs this array to know the matching activity.
94 const ACTIVITIES = [ACTIVITY_LIKE, ACTIVITY_DISLIKE, ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE];
96 private static $legacy_mode = null;
98 public static function isLegacyMode()
100 if (is_null(self::$legacy_mode)) {
101 self::$legacy_mode = (Config::get("system", "post_update_version") < 1279);
104 return self::$legacy_mode;
108 * @brief returns an activity index from an activity string
110 * @param string $activity activity string
111 * @return integer Activity index
113 private static function activityToIndex($activity)
115 $index = array_search($activity, self::ACTIVITIES);
117 if (is_bool($index)) {
125 * @brief returns an activity string from an activity index
127 * @param integer $index activity index
128 * @return string Activity string
130 private static function indexToActivity($index)
132 if (is_null($index) || !array_key_exists($index, self::ACTIVITIES)) {
136 return self::ACTIVITIES[$index];
140 * @brief Fetch a single item row
142 * @param mixed $stmt statement object
143 * @return array current row
145 public static function fetch($stmt)
147 $row = DBA::fetch($stmt);
153 // ---------------------- Transform item structure data ----------------------
155 // We prefer the data from the user's contact over the public one
156 if (!empty($row['author-link']) && !empty($row['contact-link']) &&
157 ($row['author-link'] == $row['contact-link'])) {
158 if (isset($row['author-avatar']) && !empty($row['contact-avatar'])) {
159 $row['author-avatar'] = $row['contact-avatar'];
161 if (isset($row['author-name']) && !empty($row['contact-name'])) {
162 $row['author-name'] = $row['contact-name'];
166 if (!empty($row['owner-link']) && !empty($row['contact-link']) &&
167 ($row['owner-link'] == $row['contact-link'])) {
168 if (isset($row['owner-avatar']) && !empty($row['contact-avatar'])) {
169 $row['owner-avatar'] = $row['contact-avatar'];
171 if (isset($row['owner-name']) && !empty($row['contact-name'])) {
172 $row['owner-name'] = $row['contact-name'];
176 // We can always comment on posts from these networks
177 if (array_key_exists('writable', $row) &&
178 in_array($row['internal-network'], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS])) {
179 $row['writable'] = true;
182 // ---------------------- Transform item content data ----------------------
184 // Fetch data from the item-content table whenever there is content there
185 if (self::isLegacyMode()) {
186 $legacy_fields = array_merge(self::DELIVERY_DATA_FIELDLIST, self::MIXED_CONTENT_FIELDLIST);
187 foreach ($legacy_fields as $field) {
188 if (empty($row[$field]) && !empty($row['internal-item-' . $field])) {
189 $row[$field] = $row['internal-item-' . $field];
191 unset($row['internal-item-' . $field]);
195 if (!empty($row['internal-iaid']) && array_key_exists('verb', $row)) {
196 $row['verb'] = self::indexToActivity($row['internal-activity']);
197 if (array_key_exists('title', $row)) {
200 if (array_key_exists('body', $row)) {
201 $row['body'] = $row['verb'];
203 if (array_key_exists('object', $row)) {
206 if (array_key_exists('object-type', $row)) {
207 $row['object-type'] = ACTIVITY_OBJ_NOTE;
209 } elseif (array_key_exists('verb', $row) && in_array($row['verb'], ['', ACTIVITY_POST, ACTIVITY_SHARE])) {
210 // Posts don't have an object or target - but having tags or files.
211 // We safe some performance by building tag and file strings only here.
212 // We remove object and target since they aren't used for this type.
213 if (array_key_exists('object', $row)) {
216 if (array_key_exists('target', $row)) {
221 if (!array_key_exists('verb', $row) || in_array($row['verb'], ['', ACTIVITY_POST, ACTIVITY_SHARE])) {
222 // Build the tag string out of the term entries
223 if (array_key_exists('tag', $row) && empty($row['tag'])) {
224 $row['tag'] = Term::tagTextFromItemId($row['internal-iid']);
227 // Build the file string out of the term entries
228 if (array_key_exists('file', $row) && empty($row['file'])) {
229 $row['file'] = Term::fileTextFromItemId($row['internal-iid']);
233 // Remove internal fields
234 unset($row['internal-activity']);
235 unset($row['internal-network']);
236 unset($row['internal-iid']);
237 unset($row['internal-iaid']);
238 unset($row['internal-icid']);
244 * @brief Fills an array with data from an item query
246 * @param object $stmt statement object
247 * @return array Data array
249 public static function inArray($stmt, $do_close = true) {
250 if (is_bool($stmt)) {
255 while ($row = self::fetch($stmt)) {
265 * @brief Check if item data exists
267 * @param array $condition array of fields for condition
269 * @return boolean Are there rows for that condition?
271 public static function exists($condition) {
272 $stmt = self::select(['id'], $condition, ['limit' => 1]);
274 if (is_bool($stmt)) {
277 $retval = (DBA::numRows($stmt) > 0);
286 * Retrieve a single record from the item table for a given user and returns it in an associative array
288 * @brief Retrieve a single record from a table
289 * @param integer $uid User ID
290 * @param array $fields
291 * @param array $condition
292 * @param array $params
296 public static function selectFirstForUser($uid, array $selected = [], array $condition = [], $params = [])
298 $params['uid'] = $uid;
300 if (empty($selected)) {
301 $selected = Item::DISPLAY_FIELDLIST;
304 return self::selectFirst($selected, $condition, $params);
308 * @brief Select rows from the item table for a given user
310 * @param integer $uid User ID
311 * @param array $selected Array of selected fields, empty for all
312 * @param array $condition Array of fields for condition
313 * @param array $params Array of several parameters
315 * @return boolean|object
317 public static function selectForUser($uid, array $selected = [], array $condition = [], $params = [])
319 $params['uid'] = $uid;
321 if (empty($selected)) {
322 $selected = Item::DISPLAY_FIELDLIST;
325 return self::select($selected, $condition, $params);
329 * Retrieve a single record from the item table and returns it in an associative array
331 * @brief Retrieve a single record from a table
332 * @param array $fields
333 * @param array $condition
334 * @param array $params
338 public static function selectFirst(array $fields = [], array $condition = [], $params = [])
340 $params['limit'] = 1;
342 $result = self::select($fields, $condition, $params);
344 if (is_bool($result)) {
347 $row = self::fetch($result);
354 * @brief Select rows from the item table
356 * @param array $selected Array of selected fields, empty for all
357 * @param array $condition Array of fields for condition
358 * @param array $params Array of several parameters
360 * @return boolean|object
362 public static function select(array $selected = [], array $condition = [], $params = [])
367 if (isset($params['uid'])) {
368 $uid = $params['uid'];
372 $fields = self::fieldlist($selected);
374 $select_fields = self::constructSelectFields($fields, $selected);
376 $condition_string = DBA::buildCondition($condition);
378 $condition_string = self::addTablesToFields($condition_string, $fields);
381 $condition_string = $condition_string . ' AND ' . self::condition(false);
384 $param_string = self::addTablesToFields(DBA::buildParameter($params), $fields);
386 $table = "`item` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, false, $usermode);
388 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
390 return DBA::p($sql, $condition);
394 * @brief Select rows from the starting post in the item table
396 * @param integer $uid User ID
397 * @param array $fields Array of selected fields, empty for all
398 * @param array $condition Array of fields for condition
399 * @param array $params Array of several parameters
401 * @return boolean|object
403 public static function selectThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
405 $params['uid'] = $uid;
407 if (empty($selected)) {
408 $selected = Item::DISPLAY_FIELDLIST;
411 return self::selectThread($selected, $condition, $params);
415 * Retrieve a single record from the starting post in the item table and returns it in an associative array
417 * @brief Retrieve a single record from a table
418 * @param integer $uid User ID
419 * @param array $selected
420 * @param array $condition
421 * @param array $params
425 public static function selectFirstThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
427 $params['uid'] = $uid;
429 if (empty($selected)) {
430 $selected = Item::DISPLAY_FIELDLIST;
433 return self::selectFirstThread($selected, $condition, $params);
437 * Retrieve a single record from the starting post in the item table and returns it in an associative array
439 * @brief Retrieve a single record from a table
440 * @param array $fields
441 * @param array $condition
442 * @param array $params
446 public static function selectFirstThread(array $fields = [], array $condition = [], $params = [])
448 $params['limit'] = 1;
449 $result = self::selectThread($fields, $condition, $params);
451 if (is_bool($result)) {
454 $row = self::fetch($result);
461 * @brief Select rows from the starting post in the item table
463 * @param array $selected Array of selected fields, empty for all
464 * @param array $condition Array of fields for condition
465 * @param array $params Array of several parameters
467 * @return boolean|object
469 public static function selectThread(array $selected = [], array $condition = [], $params = [])
474 if (isset($params['uid'])) {
475 $uid = $params['uid'];
479 $fields = self::fieldlist($selected);
481 $threadfields = ['thread' => ['iid', 'uid', 'contact-id', 'owner-id', 'author-id',
482 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private',
483 'pubmail', 'moderated', 'visible', 'starred', 'ignored', 'post-type',
484 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'network']];
486 $select_fields = self::constructSelectFields($fields, $selected);
488 $condition_string = DBA::buildCondition($condition);
490 $condition_string = self::addTablesToFields($condition_string, $threadfields);
491 $condition_string = self::addTablesToFields($condition_string, $fields);
494 $condition_string = $condition_string . ' AND ' . self::condition(true);
497 $param_string = DBA::buildParameter($params);
498 $param_string = self::addTablesToFields($param_string, $threadfields);
499 $param_string = self::addTablesToFields($param_string, $fields);
501 $table = "`thread` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, true, $usermode);
503 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
505 return DBA::p($sql, $condition);
509 * @brief Returns a list of fields that are associated with the item table
511 * @return array field list
513 private static function fieldlist($selected)
517 $fields['item'] = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
518 'contact-id', 'owner-id', 'author-id', 'type', 'wall', 'gravity', 'extid',
519 'created', 'edited', 'commented', 'received', 'changed', 'psid',
520 'resource-id', 'event-id', 'tag', 'attach', 'post-type', 'file',
521 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
522 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global',
523 'id' => 'item_id', 'network', 'icid', 'iaid', 'id' => 'internal-iid',
524 'network' => 'internal-network', 'icid' => 'internal-icid',
525 'iaid' => 'internal-iaid'];
527 $fields['item-activity'] = ['activity', 'activity' => 'internal-activity'];
529 $fields['item-content'] = array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST);
531 $fields['item-delivery-data'] = self::DELIVERY_DATA_FIELDLIST;
533 $fields['permissionset'] = ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'];
535 $fields['author'] = ['url' => 'author-link', 'name' => 'author-name',
536 'thumb' => 'author-avatar', 'nick' => 'author-nick', 'network' => 'author-network'];
538 $fields['owner'] = ['url' => 'owner-link', 'name' => 'owner-name',
539 'thumb' => 'owner-avatar', 'nick' => 'owner-nick', 'network' => 'owner-network'];
541 $fields['contact'] = ['url' => 'contact-link', 'name' => 'contact-name', 'thumb' => 'contact-avatar',
542 'writable', 'self', 'id' => 'cid', 'alias', 'uid' => 'contact-uid',
543 'photo', 'name-date', 'uri-date', 'avatar-date', 'thumb', 'dfrn-id'];
545 $fields['parent-item'] = ['guid' => 'parent-guid', 'network' => 'parent-network'];
547 $fields['parent-item-author'] = ['url' => 'parent-author-link', 'name' => 'parent-author-name'];
549 $fields['event'] = ['created' => 'event-created', 'edited' => 'event-edited',
550 'start' => 'event-start','finish' => 'event-finish',
551 'summary' => 'event-summary','desc' => 'event-desc',
552 'location' => 'event-location', 'type' => 'event-type',
553 'nofinish' => 'event-nofinish','adjust' => 'event-adjust',
554 'ignore' => 'event-ignore', 'id' => 'event-id'];
556 $fields['sign'] = ['signed_text', 'signature', 'signer'];
562 * @brief Returns SQL condition for the "select" functions
564 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
566 * @return string SQL condition
568 private static function condition($thread_mode)
571 $master_table = "`thread`";
573 $master_table = "`item`";
575 return "$master_table.`visible` AND NOT $master_table.`deleted` AND NOT $master_table.`moderated` AND (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`) ";
579 * @brief Returns all needed "JOIN" commands for the "select" functions
581 * @param integer $uid User ID
582 * @param string $sql_commands The parts of the built SQL commands in the "select" functions
583 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
585 * @return string The SQL joins for the "select" functions
587 private static function constructJoins($uid, $sql_commands, $thread_mode, $user_mode)
590 $master_table = "`thread`";
591 $master_table_key = "`thread`.`iid`";
592 $joins = "STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid` ";
594 $master_table = "`item`";
595 $master_table_key = "`item`.`id`";
600 $joins .= sprintf("STRAIGHT_JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`
601 AND NOT `contact`.`blocked`
602 AND ((NOT `contact`.`readonly` AND NOT `contact`.`pending` AND (`contact`.`rel` IN (%s, %s)))
603 OR `contact`.`self` OR `item`.`gravity` != %d OR `contact`.`uid` = 0)
604 STRAIGHT_JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id` AND NOT `author`.`blocked`
605 STRAIGHT_JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id` AND NOT `owner`.`blocked`
606 LEFT JOIN `user-item` ON `user-item`.`iid` = $master_table_key AND `user-item`.`uid` = %d",
607 Contact::SHARING, Contact::FRIEND, GRAVITY_PARENT, intval($uid));
609 if (strpos($sql_commands, "`contact`.") !== false) {
610 $joins .= "LEFT JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`";
612 if (strpos($sql_commands, "`author`.") !== false) {
613 $joins .= " LEFT JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id`";
615 if (strpos($sql_commands, "`owner`.") !== false) {
616 $joins .= " LEFT JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id`";
620 if (strpos($sql_commands, "`group_member`.") !== false) {
621 $joins .= " STRAIGHT_JOIN `group_member` ON `group_member`.`contact-id` = $master_table.`contact-id`";
624 if (strpos($sql_commands, "`user`.") !== false) {
625 $joins .= " STRAIGHT_JOIN `user` ON `user`.`uid` = $master_table.`uid`";
628 if (strpos($sql_commands, "`event`.") !== false) {
629 $joins .= " LEFT JOIN `event` ON `event-id` = `event`.`id`";
632 if (strpos($sql_commands, "`sign`.") !== false) {
633 $joins .= " LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`";
636 if (strpos($sql_commands, "`item-activity`.") !== false) {
637 $joins .= " LEFT JOIN `item-activity` ON `item-activity`.`id` = `item`.`iaid`";
640 if (strpos($sql_commands, "`item-content`.") !== false) {
641 $joins .= " LEFT JOIN `item-content` ON `item-content`.`id` = `item`.`icid`";
644 if (strpos($sql_commands, "`item-delivery-data`.") !== false) {
645 $joins .= " LEFT JOIN `item-delivery-data` ON `item-delivery-data`.`iid` = `item`.`id`";
648 if (strpos($sql_commands, "`permissionset`.") !== false) {
649 $joins .= " LEFT JOIN `permissionset` ON `permissionset`.`id` = `item`.`psid`";
652 if ((strpos($sql_commands, "`parent-item`.") !== false) || (strpos($sql_commands, "`parent-author`.") !== false)) {
653 $joins .= " STRAIGHT_JOIN `item` AS `parent-item` ON `parent-item`.`id` = `item`.`parent`";
656 if (strpos($sql_commands, "`parent-item-author`.") !== false) {
657 $joins .= " STRAIGHT_JOIN `contact` AS `parent-item-author` ON `parent-item-author`.`id` = `parent-item`.`author-id`";
664 * @brief Add the field list for the "select" functions
666 * @param array $fields The field definition array
667 * @param array $selected The array with the selected fields from the "select" functions
669 * @return string The field list
671 private static function constructSelectFields($fields, $selected)
673 if (!empty($selected)) {
674 $selected[] = 'internal-iid';
675 $selected[] = 'internal-iaid';
676 $selected[] = 'internal-icid';
677 $selected[] = 'internal-network';
680 if (in_array('verb', $selected)) {
681 $selected[] = 'internal-activity';
685 foreach ($fields as $table => $table_fields) {
686 foreach ($table_fields as $field => $select) {
687 if (empty($selected) || in_array($select, $selected)) {
688 $legacy_fields = array_merge(self::DELIVERY_DATA_FIELDLIST, self::MIXED_CONTENT_FIELDLIST);
689 if (self::isLegacyMode() && in_array($select, $legacy_fields)) {
690 $selection[] = "`item`.`".$select."` AS `internal-item-" . $select . "`";
692 if (is_int($field)) {
693 $selection[] = "`" . $table . "`.`" . $select . "`";
695 $selection[] = "`" . $table . "`.`" . $field . "` AS `" . $select . "`";
700 return implode(", ", $selection);
704 * @brief add table definition to fields in an SQL query
706 * @param string $query SQL query
707 * @param array $fields The field definition array
709 * @return string the changed SQL query
711 private static function addTablesToFields($query, $fields)
713 foreach ($fields as $table => $table_fields) {
714 foreach ($table_fields as $alias => $field) {
715 if (is_int($alias)) {
716 $replace_field = $field;
718 $replace_field = $alias;
721 $search = "/([^\.])`" . $field . "`/i";
722 $replace = "$1`" . $table . "`.`" . $replace_field . "`";
723 $query = preg_replace($search, $replace, $query);
730 * @brief Generate a server unique item hash for linking between the item tables
732 * @param string $uri Item URI
733 * @param date $created Item creation date
735 * @return string the item hash
737 private static function itemHash($uri, $created)
739 return round(strtotime($created) / 100) . hash('ripemd128', $uri);
743 * @brief Update existing item entries
745 * @param array $fields The fields that are to be changed
746 * @param array $condition The condition for finding the item entries
748 * In the future we may have to change permissions as well.
749 * Then we had to add the user id as third parameter.
751 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
753 * @return integer|boolean number of affected rows - or "false" if there was an error
755 public static function update(array $fields, array $condition)
757 if (empty($condition) || empty($fields)) {
761 // To ensure the data integrity we do it in an transaction
764 // We cannot simply expand the condition to check for origin entries
765 // The condition needn't to be a simple array but could be a complex condition.
766 // And we have to execute this query before the update to ensure to fetch the same data.
767 $items = DBA::select('item', ['id', 'origin', 'uri', 'created', 'uri-hash', 'iaid', 'icid', 'tag', 'file'], $condition);
769 $content_fields = [];
770 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
771 if (isset($fields[$field])) {
772 $content_fields[$field] = $fields[$field];
773 if (in_array($field, self::CONTENT_FIELDLIST) || !self::isLegacyMode()) {
774 unset($fields[$field]);
776 $fields[$field] = null;
781 $clear_fields = ['bookmark', 'type', 'author-name', 'author-avatar', 'author-link', 'owner-name', 'owner-avatar', 'owner-link'];
782 foreach ($clear_fields as $field) {
783 if (array_key_exists($field, $fields)) {
784 $fields[$field] = null;
788 if (array_key_exists('tag', $fields)) {
789 $tags = $fields['tag'];
790 $fields['tag'] = null;
795 if (array_key_exists('file', $fields)) {
796 $files = $fields['file'];
797 $fields['file'] = null;
802 $delivery_data = ['postopts' => defaults($fields, 'postopts', ''),
803 'inform' => defaults($fields, 'inform', '')];
805 $fields['postopts'] = null;
806 $fields['inform'] = null;
808 if (!empty($fields)) {
809 $success = DBA::update('item', $fields, $condition);
818 // When there is no content for the "old" item table, this will count the fetched items
819 $rows = DBA::affectedRows();
821 while ($item = DBA::fetch($items)) {
823 // This part here can safely be removed when the legacy fields in the item had been removed
824 if (empty($item['uri-hash']) && !empty($item['uri']) && !empty($item['created'])) {
826 // Fetch the uri-hash from an existing item entry if there is one
827 $item_condition = ["`uri` = ? AND `uri-hash` != ''", $item['uri']];
828 $existing = DBA::selectfirst('item', ['uri-hash'], $item_condition);
829 if (DBA::isResult($existing)) {
830 $item['uri-hash'] = $existing['uri-hash'];
832 $item['uri-hash'] = self::itemHash($item['uri'], $item['created']);
835 DBA::update('item', ['uri-hash' => $item['uri-hash']], ['id' => $item['id']]);
836 DBA::update('item-activity', ['uri-hash' => $item['uri-hash']], ["`uri` = ? AND `uri-hash` = ''", $item['uri']]);
837 DBA::update('item-content', ['uri-plink-hash' => $item['uri-hash']], ["`uri` = ? AND `uri-plink-hash` = ''", $item['uri']]);
840 if (!empty($item['iaid']) || (!empty($content_fields['verb']) && (self::activityToIndex($content_fields['verb']) >= 0))) {
841 if (!empty($item['iaid'])) {
842 $update_condition = ['id' => $item['iaid']];
844 $update_condition = ['uri-hash' => $item['uri-hash']];
846 self::updateActivity($content_fields, $update_condition);
848 if (empty($item['iaid'])) {
849 $item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-hash' => $item['uri-hash']]);
850 if (DBA::isResult($item_activity)) {
851 $item_fields = ['iaid' => $item_activity['id'], 'icid' => null];
852 foreach (self::MIXED_CONTENT_FIELDLIST as $field) {
853 if (self::isLegacyMode()) {
854 $item_fields[$field] = null;
856 unset($item_fields[$field]);
859 DBA::update('item', $item_fields, ['id' => $item['id']]);
861 if (!empty($item['icid']) && !DBA::exists('item', ['icid' => $item['icid']])) {
862 DBA::delete('item-content', ['id' => $item['icid']]);
865 } elseif (!empty($item['icid'])) {
866 DBA::update('item', ['icid' => null], ['id' => $item['id']]);
868 if (!DBA::exists('item', ['icid' => $item['icid']])) {
869 DBA::delete('item-content', ['id' => $item['icid']]);
873 if (!empty($item['icid'])) {
874 $update_condition = ['id' => $item['icid']];
876 $update_condition = ['uri-plink-hash' => $item['uri-hash']];
878 self::updateContent($content_fields, $update_condition);
880 if (empty($item['icid'])) {
881 $item_content = DBA::selectFirst('item-content', [], ['uri-plink-hash' => $item['uri-hash']]);
882 if (DBA::isResult($item_content)) {
883 $item_fields = ['icid' => $item_content['id']];
884 // Clear all fields in the item table that have a content in the item-content table
885 foreach ($item_content as $field => $content) {
886 if (in_array($field, self::MIXED_CONTENT_FIELDLIST) && !empty($item_content[$field])) {
887 if (self::isLegacyMode()) {
888 $item_fields[$field] = null;
890 unset($item_fields[$field]);
894 DBA::update('item', $item_fields, ['id' => $item['id']]);
900 Term::insertFromTagFieldByItemId($item['id'], $tags);
901 if (!empty($item['tag'])) {
902 DBA::update('item', ['tag' => ''], ['id' => $item['id']]);
906 if (!empty($files)) {
907 Term::insertFromFileFieldByItemId($item['id'], $files);
908 if (!empty($item['file'])) {
909 DBA::update('item', ['file' => ''], ['id' => $item['id']]);
913 self::updateDeliveryData($item['id'], $delivery_data);
915 self::updateThread($item['id']);
917 // We only need to notfiy others when it is an original entry from us.
918 // Only call the notifier when the item has some content relevant change.
919 if ($item['origin'] && in_array('edited', array_keys($fields))) {
920 Worker::add(PRIORITY_HIGH, "Notifier", 'edit_post', $item['id']);
930 * @brief Delete an item and notify others about it - if it was ours
932 * @param array $condition The condition for finding the item entries
933 * @param integer $priority Priority for the notification
935 public static function delete($condition, $priority = PRIORITY_HIGH)
937 $items = DBA::select('item', ['id'], $condition);
938 while ($item = DBA::fetch($items)) {
939 self::deleteById($item['id'], $priority);
945 * @brief Delete an item for an user and notify others about it - if it was ours
947 * @param array $condition The condition for finding the item entries
948 * @param integer $uid User who wants to delete this item
950 public static function deleteForUser($condition, $uid)
956 $items = DBA::select('item', ['id', 'uid'], $condition);
957 while ($item = DBA::fetch($items)) {
958 // "Deleting" global items just means hiding them
959 if ($item['uid'] == 0) {
960 DBA::update('user-item', ['hidden' => true], ['iid' => $item['id'], 'uid' => $uid], true);
961 } elseif ($item['uid'] == $uid) {
962 self::deleteById($item['id'], PRIORITY_HIGH);
964 logger('Wrong ownership. Not deleting item ' . $item['id']);
971 * @brief Delete an item and notify others about it - if it was ours
973 * @param integer $item_id Item ID that should be delete
974 * @param integer $priority Priority for the notification
976 * @return boolean success
978 private static function deleteById($item_id, $priority = PRIORITY_HIGH)
980 // locate item to be deleted
981 $fields = ['id', 'uri', 'uid', 'parent', 'parent-uri', 'origin',
982 'deleted', 'file', 'resource-id', 'event-id', 'attach',
983 'verb', 'object-type', 'object', 'target', 'contact-id',
984 'icid', 'iaid', 'psid'];
985 $item = self::selectFirst($fields, ['id' => $item_id]);
986 if (!DBA::isResult($item)) {
987 logger('Item with ID ' . $item_id . " hasn't been found.", LOGGER_DEBUG);
991 if ($item['deleted']) {
992 logger('Item with ID ' . $item_id . ' has already been deleted.', LOGGER_DEBUG);
996 $parent = self::selectFirst(['origin'], ['id' => $item['parent']]);
997 if (!DBA::isResult($parent)) {
998 $parent = ['origin' => false];
1001 // clean up categories and tags so they don't end up as orphans
1004 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
1006 foreach ($matches as $mtch) {
1007 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],true);
1013 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
1015 foreach ($matches as $mtch) {
1016 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],false);
1021 * If item is a link to a photo resource, nuke all the associated photos
1022 * (visitors will not have photo resources)
1023 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
1024 * generate a resource-id and therefore aren't intimately linked to the item.
1026 if (strlen($item['resource-id'])) {
1027 DBA::delete('photo', ['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
1030 // If item is a link to an event, delete the event.
1031 if (intval($item['event-id'])) {
1032 Event::delete($item['event-id']);
1035 // If item has attachments, drop them
1036 foreach (explode(", ", $item['attach']) as $attach) {
1037 preg_match("|attach/(\d+)|", $attach, $matches);
1038 if (is_array($matches) && count($matches) > 1) {
1039 DBA::delete('attach', ['id' => $matches[1], 'uid' => $item['uid']]);
1043 // Delete tags that had been attached to other items
1044 self::deleteTagsFromItem($item);
1046 // Set the item to "deleted"
1047 $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
1048 DBA::update('item', $item_fields, ['id' => $item['id']]);
1050 Term::insertFromTagFieldByItemId($item['id'], '');
1051 Term::insertFromFileFieldByItemId($item['id'], '');
1052 self::deleteThread($item['id'], $item['parent-uri']);
1054 if (!self::exists(["`uri` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri']])) {
1055 self::delete(['uri' => $item['uri'], 'uid' => 0, 'deleted' => false], $priority);
1058 DBA::delete('item-delivery-data', ['iid' => $item['id']]);
1060 if (!empty($item['iaid']) && !DBA::exists('item', ['iaid' => $item['iaid'], 'deleted' => false])) {
1061 DBA::delete('item-activity', ['id' => $item['iaid']], ['cascade' => false]);
1063 if (!empty($item['icid']) && !DBA::exists('item', ['icid' => $item['icid'], 'deleted' => false])) {
1064 DBA::delete('item-content', ['id' => $item['icid']], ['cascade' => false]);
1066 // When the permission set will be used in photo and events as well,
1067 // this query here needs to be extended.
1068 if (!empty($item['psid']) && !DBA::exists('item', ['psid' => $item['psid'], 'deleted' => false])) {
1069 DBA::delete('permissionset', ['id' => $item['psid']], ['cascade' => false]);
1072 // If it's the parent of a comment thread, kill all the kids
1073 if ($item['id'] == $item['parent']) {
1074 self::delete(['parent' => $item['parent'], 'deleted' => false], $priority);
1077 // Is it our comment and/or our thread?
1078 if ($item['origin'] || $parent['origin']) {
1080 // When we delete the original post we will delete all existing copies on the server as well
1081 self::delete(['uri' => $item['uri'], 'deleted' => false], $priority);
1083 // send the notification upstream/downstream
1084 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", "drop", intval($item['id']));
1085 } elseif ($item['uid'] != 0) {
1087 // When we delete just our local user copy of an item, we have to set a marker to hide it
1088 $global_item = self::selectFirst(['id'], ['uri' => $item['uri'], 'uid' => 0, 'deleted' => false]);
1089 if (DBA::isResult($global_item)) {
1090 DBA::update('user-item', ['hidden' => true], ['iid' => $global_item['id'], 'uid' => $item['uid']], true);
1094 logger('Item with ID ' . $item_id . " has been deleted.", LOGGER_DEBUG);
1099 private static function deleteTagsFromItem($item)
1101 if (($item["verb"] != ACTIVITY_TAG) || ($item["object-type"] != ACTIVITY_OBJ_TAGTERM)) {
1105 $xo = XML::parseString($item["object"], false);
1106 $xt = XML::parseString($item["target"], false);
1108 if ($xt->type != ACTIVITY_OBJ_NOTE) {
1112 $i = self::selectFirst(['id', 'contact-id', 'tag'], ['uri' => $xt->id, 'uid' => $item['uid']]);
1113 if (!DBA::isResult($i)) {
1117 // For tags, the owner cannot remove the tag on the author's copy of the post.
1118 $owner_remove = ($item["contact-id"] == $i["contact-id"]);
1119 $author_copy = $item["origin"];
1121 if (($owner_remove && $author_copy) || !$owner_remove) {
1125 $tags = explode(',', $i["tag"]);
1128 foreach ($tags as $tag) {
1129 if (trim($tag) !== trim($xo->body)) {
1130 $newtags[] = trim($tag);
1134 self::update(['tag' => implode(',', $newtags)], ['id' => $i["id"]]);
1137 private static function guid($item, $notify)
1139 if (!empty($item['guid'])) {
1140 return notags(trim($item['guid']));
1144 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
1145 // We add the hash of our own host because our host is the original creator of the post.
1146 $prefix_host = get_app()->get_hostname();
1150 // We are only storing the post so we create a GUID from the original hostname.
1151 if (!empty($item['author-link'])) {
1152 $parsed = parse_url($item['author-link']);
1153 if (!empty($parsed['host'])) {
1154 $prefix_host = $parsed['host'];
1158 if (empty($prefix_host) && !empty($item['plink'])) {
1159 $parsed = parse_url($item['plink']);
1160 if (!empty($parsed['host'])) {
1161 $prefix_host = $parsed['host'];
1165 if (empty($prefix_host) && !empty($item['uri'])) {
1166 $parsed = parse_url($item['uri']);
1167 if (!empty($parsed['host'])) {
1168 $prefix_host = $parsed['host'];
1172 // Is it in the format data@host.tld? - Used for mail contacts
1173 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
1174 $mailparts = explode('@', $item['author-link']);
1175 $prefix_host = array_pop($mailparts);
1179 if (!empty($item['plink'])) {
1180 $guid = self::guidFromUri($item['plink'], $prefix_host);
1181 } elseif (!empty($item['uri'])) {
1182 $guid = self::guidFromUri($item['uri'], $prefix_host);
1184 $guid = System::createGUID(32, hash('crc32', $prefix_host));
1190 private static function contactId($item)
1192 $contact_id = (int)$item["contact-id"];
1194 if (!empty($contact_id)) {
1197 logger('Missing contact-id. Called by: '.System::callstack(), LOGGER_DEBUG);
1199 * First we are looking for a suitable contact that matches with the author of the post
1200 * This is done only for comments
1202 if ($item['parent-uri'] != $item['uri']) {
1203 $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
1206 // If not present then maybe the owner was found
1207 if ($contact_id == 0) {
1208 $contact_id = Contact::getIdForURL($item['owner-link'], $item['uid']);
1211 // Still missing? Then use the "self" contact of the current user
1212 if ($contact_id == 0) {
1213 $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $item['uid']]);
1214 if (DBA::isResult($self)) {
1215 $contact_id = $self["id"];
1218 logger("Contact-id was missing for post ".$item['guid']." from user id ".$item['uid']." - now set to ".$contact_id, LOGGER_DEBUG);
1223 // This function will finally cover most of the preparation functionality in mod/item.php
1224 public static function prepare(&$item)
1226 $data = BBCode::getAttachmentData($item['body']);
1227 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $item['body'], $match, PREG_SET_ORDER) || isset($data["type"]))
1228 && ($posttype != Item::PT_PERSONAL_NOTE)) {
1229 $posttype = Item::PT_PAGE;
1230 $objecttype = ACTIVITY_OBJ_BOOKMARK;
1234 public static function insert($item, $force_parent = false, $notify = false, $dontcache = false)
1238 // If it is a posting where users should get notifications, then define it as wall posting
1241 $item['origin'] = 1;
1242 $item['network'] = NETWORK_DFRN;
1243 $item['protocol'] = PROTOCOL_DFRN;
1245 if (is_int($notify)) {
1246 $priority = $notify;
1248 $priority = PRIORITY_HIGH;
1251 $item['network'] = trim(defaults($item, 'network', NETWORK_PHANTOM));
1254 $item['guid'] = self::guid($item, $notify);
1255 $item['uri'] = notags(trim(defaults($item, 'uri', self::newURI($item['uid'], $item['guid']))));
1258 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
1260 // Store conversation data
1261 $item = Conversation::insert($item);
1264 * If a Diaspora signature structure was passed in, pull it out of the
1265 * item array and set it aside for later storage.
1269 if (x($item, 'dsprsig')) {
1270 $encoded_signature = $item['dsprsig'];
1271 $dsprsig = json_decode(base64_decode($item['dsprsig']));
1272 unset($item['dsprsig']);
1275 if (!empty($item['diaspora_signed_text'])) {
1276 $diaspora_signed_text = $item['diaspora_signed_text'];
1277 unset($item['diaspora_signed_text']);
1279 $diaspora_signed_text = '';
1282 // Converting the plink
1283 /// @TODO Check if this is really still needed
1284 if ($item['network'] == NETWORK_OSTATUS) {
1285 if (isset($item['plink'])) {
1286 $item['plink'] = OStatus::convertHref($item['plink']);
1287 } elseif (isset($item['uri'])) {
1288 $item['plink'] = OStatus::convertHref($item['uri']);
1292 if (!empty($item['thr-parent'])) {
1293 $item['parent-uri'] = $item['thr-parent'];
1296 if (isset($item['gravity'])) {
1297 $item['gravity'] = intval($item['gravity']);
1298 } elseif ($item['parent-uri'] === $item['uri']) {
1299 $item['gravity'] = GRAVITY_PARENT;
1300 } elseif (activity_match($item['verb'], ACTIVITY_POST)) {
1301 $item['gravity'] = GRAVITY_COMMENT;
1303 $item['gravity'] = GRAVITY_UNKNOWN; // Should not happen
1304 logger('Unknown gravity for verb: ' . $item['verb'], LOGGER_DEBUG);
1307 $uid = intval($item['uid']);
1309 // check for create date and expire time
1310 $expire_interval = Config::get('system', 'dbclean-expire-days', 0);
1312 $user = DBA::selectFirst('user', ['expire'], ['uid' => $uid]);
1313 if (DBA::isResult($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
1314 $expire_interval = $user['expire'];
1317 if (($expire_interval > 0) && !empty($item['created'])) {
1318 $expire_date = time() - ($expire_interval * 86400);
1319 $created_date = strtotime($item['created']);
1320 if ($created_date < $expire_date) {
1321 logger('item-store: item created ('.date('c', $created_date).') before expiration time ('.date('c', $expire_date).'). ignored. ' . print_r($item,true), LOGGER_DEBUG);
1327 * Do we already have this item?
1328 * We have to check several networks since Friendica posts could be repeated
1329 * via OStatus (maybe Diasporsa as well)
1331 if (in_array($item['network'], [NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS, ""])) {
1332 $condition = ["`uri` = ? AND `uid` = ? AND `network` IN (?, ?, ?)",
1333 trim($item['uri']), $item['uid'],
1334 NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS];
1335 $existing = self::selectFirst(['id', 'network'], $condition);
1336 if (DBA::isResult($existing)) {
1337 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
1339 logger("Item with uri ".$item['uri']." already existed for user ".$uid." with id ".$existing["id"]." target network ".$existing["network"]." - new network: ".$item['network']);
1342 return $existing["id"];
1346 // Ensure to always have the same creation date.
1347 $existing = DBA::selectfirst('item', ['created', 'uri-hash'], ['uri' => $item['uri']]);
1348 if (DBA::isResult($existing)) {
1349 $item['created'] = $existing['created'];
1350 $item['uri-hash'] = $existing['uri-hash'];
1353 $item['wall'] = intval(defaults($item, 'wall', 0));
1354 $item['extid'] = trim(defaults($item, 'extid', ''));
1355 $item['author-name'] = trim(defaults($item, 'author-name', ''));
1356 $item['author-link'] = trim(defaults($item, 'author-link', ''));
1357 $item['author-avatar'] = trim(defaults($item, 'author-avatar', ''));
1358 $item['owner-name'] = trim(defaults($item, 'owner-name', ''));
1359 $item['owner-link'] = trim(defaults($item, 'owner-link', ''));
1360 $item['owner-avatar'] = trim(defaults($item, 'owner-avatar', ''));
1361 $item['received'] = ((x($item, 'received') !== false) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
1362 $item['created'] = ((x($item, 'created') !== false) ? DateTimeFormat::utc($item['created']) : $item['received']);
1363 $item['edited'] = ((x($item, 'edited') !== false) ? DateTimeFormat::utc($item['edited']) : $item['created']);
1364 $item['changed'] = ((x($item, 'changed') !== false) ? DateTimeFormat::utc($item['changed']) : $item['created']);
1365 $item['commented'] = ((x($item, 'commented') !== false) ? DateTimeFormat::utc($item['commented']) : $item['created']);
1366 $item['title'] = trim(defaults($item, 'title', ''));
1367 $item['location'] = trim(defaults($item, 'location', ''));
1368 $item['coord'] = trim(defaults($item, 'coord', ''));
1369 $item['visible'] = ((x($item, 'visible') !== false) ? intval($item['visible']) : 1);
1370 $item['deleted'] = 0;
1371 $item['parent-uri'] = trim(defaults($item, 'parent-uri', $item['uri']));
1372 $item['post-type'] = defaults($item, 'post-type', self::PT_ARTICLE);
1373 $item['verb'] = trim(defaults($item, 'verb', ''));
1374 $item['object-type'] = trim(defaults($item, 'object-type', ''));
1375 $item['object'] = trim(defaults($item, 'object', ''));
1376 $item['target-type'] = trim(defaults($item, 'target-type', ''));
1377 $item['target'] = trim(defaults($item, 'target', ''));
1378 $item['plink'] = trim(defaults($item, 'plink', ''));
1379 $item['allow_cid'] = trim(defaults($item, 'allow_cid', ''));
1380 $item['allow_gid'] = trim(defaults($item, 'allow_gid', ''));
1381 $item['deny_cid'] = trim(defaults($item, 'deny_cid', ''));
1382 $item['deny_gid'] = trim(defaults($item, 'deny_gid', ''));
1383 $item['private'] = intval(defaults($item, 'private', 0));
1384 $item['body'] = trim(defaults($item, 'body', ''));
1385 $item['tag'] = trim(defaults($item, 'tag', ''));
1386 $item['attach'] = trim(defaults($item, 'attach', ''));
1387 $item['app'] = trim(defaults($item, 'app', ''));
1388 $item['origin'] = intval(defaults($item, 'origin', 0));
1389 $item['postopts'] = trim(defaults($item, 'postopts', ''));
1390 $item['resource-id'] = trim(defaults($item, 'resource-id', ''));
1391 $item['event-id'] = intval(defaults($item, 'event-id', 0));
1392 $item['inform'] = trim(defaults($item, 'inform', ''));
1393 $item['file'] = trim(defaults($item, 'file', ''));
1395 // Unique identifier to be linked against item-activities and item-content
1396 $item['uri-hash'] = defaults($item, 'uri-hash', self::itemHash($item['uri'], $item['created']));
1398 // When there is no content then we don't post it
1399 if ($item['body'].$item['title'] == '') {
1400 logger('No body, no title.');
1404 self::addLanguageToItemArray($item);
1406 // Items cannot be stored before they happen ...
1407 if ($item['created'] > DateTimeFormat::utcNow()) {
1408 $item['created'] = DateTimeFormat::utcNow();
1411 // We haven't invented time travel by now.
1412 if ($item['edited'] > DateTimeFormat::utcNow()) {
1413 $item['edited'] = DateTimeFormat::utcNow();
1416 $item['plink'] = defaults($item, 'plink', System::baseUrl() . '/display/' . urlencode($item['guid']));
1418 // The contact-id should be set before "self::insert" was called - but there seems to be issues sometimes
1419 $item["contact-id"] = self::contactId($item);
1421 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
1422 'photo' => $item['author-avatar'], 'network' => $item['network']];
1424 $item['author-id'] = defaults($item, 'author-id', Contact::getIdForURL($item["author-link"], 0, false, $default));
1426 if (Contact::isBlocked($item["author-id"])) {
1427 logger('Contact '.$item["author-id"].' is blocked, item '.$item["uri"].' will not be stored');
1431 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
1432 'photo' => $item['owner-avatar'], 'network' => $item['network']];
1434 $item['owner-id'] = defaults($item, 'owner-id', Contact::getIdForURL($item["owner-link"], 0, false, $default));
1436 if (Contact::isBlocked($item["owner-id"])) {
1437 logger('Contact '.$item["owner-id"].' is blocked, item '.$item["uri"].' will not be stored');
1441 // These fields aren't stored anymore in the item table, they are fetched upon request
1442 unset($item['author-link']);
1443 unset($item['author-name']);
1444 unset($item['author-avatar']);
1446 unset($item['owner-link']);
1447 unset($item['owner-name']);
1448 unset($item['owner-avatar']);
1450 if ($item['network'] == NETWORK_PHANTOM) {
1451 logger('Missing network. Called by: '.System::callstack(), LOGGER_DEBUG);
1453 $item['network'] = NETWORK_DFRN;
1454 logger("Set network to " . $item["network"] . " for " . $item["uri"], LOGGER_DEBUG);
1457 // Checking if there is already an item with the same guid
1458 logger('Checking for an item for user '.$item['uid'].' on network '.$item['network'].' with the guid '.$item['guid'], LOGGER_DEBUG);
1459 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
1460 if (self::exists($condition)) {
1461 logger('found item with guid '.$item['guid'].' for user '.$item['uid'].' on network '.$item['network'], LOGGER_DEBUG);
1465 // Check for hashtags in the body and repair or add hashtag links
1466 self::setHashtags($item);
1468 $item['thr-parent'] = $item['parent-uri'];
1476 if ($item['parent-uri'] === $item['uri']) {
1478 $parent_deleted = 0;
1479 $allow_cid = $item['allow_cid'];
1480 $allow_gid = $item['allow_gid'];
1481 $deny_cid = $item['deny_cid'];
1482 $deny_gid = $item['deny_gid'];
1483 $notify_type = 'wall-new';
1485 // find the parent and snarf the item id and ACLs
1486 // and anything else we need to inherit
1488 $fields = ['uri', 'parent-uri', 'id', 'deleted',
1489 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
1490 'wall', 'private', 'forum_mode', 'origin'];
1491 $condition = ['uri' => $item['parent-uri'], 'uid' => $item['uid']];
1492 $params = ['order' => ['id' => false]];
1493 $parent = self::selectFirst($fields, $condition, $params);
1495 if (DBA::isResult($parent)) {
1496 // is the new message multi-level threaded?
1497 // even though we don't support it now, preserve the info
1498 // and re-attach to the conversation parent.
1500 if ($parent['uri'] != $parent['parent-uri']) {
1501 $item['parent-uri'] = $parent['parent-uri'];
1503 $condition = ['uri' => $item['parent-uri'],
1504 'parent-uri' => $item['parent-uri'],
1505 'uid' => $item['uid']];
1506 $params = ['order' => ['id' => false]];
1507 $toplevel_parent = self::selectFirst($fields, $condition, $params);
1509 if (DBA::isResult($toplevel_parent)) {
1510 $parent = $toplevel_parent;
1514 $parent_id = $parent['id'];
1515 $parent_deleted = $parent['deleted'];
1516 $allow_cid = $parent['allow_cid'];
1517 $allow_gid = $parent['allow_gid'];
1518 $deny_cid = $parent['deny_cid'];
1519 $deny_gid = $parent['deny_gid'];
1520 $item['wall'] = $parent['wall'];
1521 $notify_type = 'comment-new';
1524 * If the parent is private, force privacy for the entire conversation
1525 * This differs from the above settings as it subtly allows comments from
1526 * email correspondents to be private even if the overall thread is not.
1528 if ($parent['private']) {
1529 $item['private'] = $parent['private'];
1533 * Edge case. We host a public forum that was originally posted to privately.
1534 * The original author commented, but as this is a comment, the permissions
1535 * weren't fixed up so it will still show the comment as private unless we fix it here.
1537 if ((intval($parent['forum_mode']) == 1) && $parent['private']) {
1538 $item['private'] = 0;
1541 // If its a post from myself then tag the thread as "mention"
1542 logger("Checking if parent ".$parent_id." has to be tagged as mention for user ".$item['uid'], LOGGER_DEBUG);
1543 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $item['uid']]);
1544 if (DBA::isResult($user)) {
1545 $self = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
1546 $self_id = Contact::getIdForURL($self, 0, true);
1547 logger("'myself' is ".$self_id." for parent ".$parent_id." checking against ".$item['author-id']." and ".$item['owner-id'], LOGGER_DEBUG);
1548 if (($item['author-id'] == $self_id) || ($item['owner-id'] == $self_id)) {
1549 DBA::update('thread', ['mention' => true], ['iid' => $parent_id]);
1550 logger("tagged thread ".$parent_id." as mention for user ".$self, LOGGER_DEBUG);
1555 * Allow one to see reply tweets from status.net even when
1556 * we don't have or can't see the original post.
1558 if ($force_parent) {
1559 logger('$force_parent=true, reply converted to top-level post.');
1561 $item['parent-uri'] = $item['uri'];
1562 $item['gravity'] = GRAVITY_PARENT;
1564 logger('item parent '.$item['parent-uri'].' for '.$item['uid'].' was not found - ignoring item');
1568 $parent_deleted = 0;
1572 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
1573 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
1575 $condition = ["`uri` = ? AND `network` IN (?, ?) AND `uid` = ?",
1576 $item['uri'], $item['network'], NETWORK_DFRN, $item['uid']];
1577 if (self::exists($condition)) {
1578 logger('duplicated item with the same uri found. '.print_r($item,true));
1582 // On Friendica and Diaspora the GUID is unique
1583 if (in_array($item['network'], [NETWORK_DFRN, NETWORK_DIASPORA])) {
1584 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
1585 if (self::exists($condition)) {
1586 logger('duplicated item with the same guid found. '.print_r($item,true));
1590 // Check for an existing post with the same content. There seems to be a problem with OStatus.
1591 $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
1592 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
1593 if (self::exists($condition)) {
1594 logger('duplicated item with the same body found. '.print_r($item,true));
1599 // Is this item available in the global items (with uid=0)?
1600 if ($item["uid"] == 0) {
1601 $item["global"] = true;
1603 // Set the global flag on all items if this was a global item entry
1604 DBA::update('item', ['global' => true], ['uri' => $item["uri"]]);
1606 $item["global"] = self::exists(['uid' => 0, 'uri' => $item["uri"]]);
1610 if (strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid)) {
1613 $private = $item['private'];
1616 $item["allow_cid"] = $allow_cid;
1617 $item["allow_gid"] = $allow_gid;
1618 $item["deny_cid"] = $deny_cid;
1619 $item["deny_gid"] = $deny_gid;
1620 $item["private"] = $private;
1621 $item["deleted"] = $parent_deleted;
1623 // Fill the cache field
1624 put_item_in_cache($item);
1627 $item['edit'] = false;
1628 $item['parent'] = $parent_id;
1629 Addon::callHooks('post_local', $item);
1630 unset($item['edit']);
1631 unset($item['parent']);
1633 Addon::callHooks('post_remote', $item);
1636 // This array field is used to trigger some automatic reactions
1637 // It is mainly used in the "post_local" hook.
1638 unset($item['api_source']);
1640 if (x($item, 'cancel')) {
1641 logger('post cancelled by addon.');
1646 * Check for already added items.
1647 * There is a timing issue here that sometimes creates double postings.
1648 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
1650 if ($item["uid"] == 0) {
1651 if (self::exists(['uri' => trim($item['uri']), 'uid' => 0])) {
1652 logger('Global item already stored. URI: '.$item['uri'].' on network '.$item['network'], LOGGER_DEBUG);
1657 logger('' . print_r($item,true), LOGGER_DATA);
1659 if (array_key_exists('tag', $item)) {
1660 $tags = $item['tag'];
1661 unset($item['tag']);
1666 if (array_key_exists('file', $item)) {
1667 $files = $item['file'];
1668 unset($item['file']);
1673 // Creates or assigns the permission set
1674 $item['psid'] = PermissionSet::fetchIDForPost($item);
1676 // We are doing this outside of the transaction to avoid timing problems
1677 if (!self::insertActivity($item)) {
1678 self::insertContent($item);
1681 $delivery_data = ['postopts' => defaults($item, 'postopts', ''),
1682 'inform' => defaults($item, 'inform', '')];
1684 unset($item['postopts']);
1685 unset($item['inform']);
1688 $ret = DBA::insert('item', $item);
1690 // When the item was successfully stored we fetch the ID of the item.
1691 if (DBA::isResult($ret)) {
1692 $current_post = DBA::lastInsertId();
1694 // This can happen - for example - if there are locking timeouts.
1697 // Store the data into a spool file so that we can try again later.
1699 // At first we restore the Diaspora signature that we removed above.
1700 if (isset($encoded_signature)) {
1701 $item['dsprsig'] = $encoded_signature;
1704 // Now we store the data in the spool directory
1705 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
1706 $file = 'item-'.round(microtime(true) * 10000).'-'.mt_rand().'.msg';
1708 $spoolpath = get_spoolpath();
1709 if ($spoolpath != "") {
1710 $spool = $spoolpath.'/'.$file;
1712 // Ensure to have the removed data from above again in the item array
1713 $item = array_merge($item, $delivery_data);
1715 file_put_contents($spool, json_encode($item));
1716 logger("Item wasn't stored - Item was spooled into file ".$file, LOGGER_DEBUG);
1721 if ($current_post == 0) {
1722 // This is one of these error messages that never should occur.
1723 logger("couldn't find created item - we better quit now.");
1728 // How much entries have we created?
1729 // We wouldn't need this query when we could use an unique index - but MySQL has length problems with them.
1730 $entries = DBA::count('item', ['uri' => $item['uri'], 'uid' => $item['uid'], 'network' => $item['network']]);
1733 // There are duplicates. We delete our just created entry.
1734 logger('Duplicated post occurred. uri = ' . $item['uri'] . ' uid = ' . $item['uid']);
1736 // Yes, we could do a rollback here - but we are having many users with MyISAM.
1737 DBA::delete('item', ['id' => $current_post]);
1740 } elseif ($entries == 0) {
1741 // This really should never happen since we quit earlier if there were problems.
1742 logger("Something is terribly wrong. We haven't found our created entry.");
1747 logger('created item '.$current_post);
1748 self::updateContact($item);
1750 if (!$parent_id || ($item['parent-uri'] === $item['uri'])) {
1751 $parent_id = $current_post;
1755 DBA::update('item', ['parent' => $parent_id], ['id' => $current_post]);
1757 $item['id'] = $current_post;
1758 $item['parent'] = $parent_id;
1760 // update the commented timestamp on the parent
1761 // Only update "commented" if it is really a comment
1762 if (($item['gravity'] != GRAVITY_ACTIVITY) || !Config::get("system", "like_no_comment")) {
1763 DBA::update('item', ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1765 DBA::update('item', ['changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1770 * Friendica servers lower than 3.4.3-2 had double encoded the signature ...
1771 * We can check for this condition when we decode and encode the stuff again.
1773 if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) {
1774 $dsprsig->signature = base64_decode($dsprsig->signature);
1775 logger("Repaired double encoded signature from handle ".$dsprsig->signer, LOGGER_DEBUG);
1778 DBA::insert('sign', ['iid' => $current_post, 'signed_text' => $dsprsig->signed_text,
1779 'signature' => $dsprsig->signature, 'signer' => $dsprsig->signer]);
1782 if (!empty($diaspora_signed_text)) {
1783 // Formerly we stored the signed text, the signature and the author in different fields.
1784 // We now store the raw data so that we are more flexible.
1785 DBA::insert('sign', ['iid' => $current_post, 'signed_text' => $diaspora_signed_text]);
1788 $deleted = self::tagDeliver($item['uid'], $current_post);
1791 * current post can be deleted if is for a community page and no mention are
1794 if (!$deleted && !$dontcache) {
1795 $posted_item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $current_post]);
1796 if (DBA::isResult($posted_item)) {
1798 Addon::callHooks('post_local_end', $posted_item);
1800 Addon::callHooks('post_remote_end', $posted_item);
1803 logger('new item not found in DB, id ' . $current_post);
1807 if ($item['parent-uri'] === $item['uri']) {
1808 self::addThread($current_post);
1810 self::updateThread($parent_id);
1813 $delivery_data['iid'] = $current_post;
1815 self::insertDeliveryData($delivery_data);
1820 * Due to deadlock issues with the "term" table we are doing these steps after the commit.
1821 * This is not perfect - but a workable solution until we found the reason for the problem.
1823 if (!empty($tags)) {
1824 Term::insertFromTagFieldByItemId($current_post, $tags);
1827 if (!empty($files)) {
1828 Term::insertFromFileFieldByItemId($current_post, $files);
1831 if ($item['parent-uri'] === $item['uri']) {
1832 self::addShadow($current_post);
1834 self::addShadowPost($current_post);
1837 check_user_notification($current_post);
1840 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", $notify_type, $current_post);
1841 } elseif (!empty($parent) && $parent['origin']) {
1842 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "Notifier", "comment-import", $current_post);
1845 return $current_post;
1849 * @brief Insert a new item delivery data entry
1851 * @param array $item The item fields that are to be inserted
1853 private static function insertDeliveryData($delivery_data)
1855 if (empty($delivery_data['iid']) || (empty($delivery_data['postopts']) && empty($delivery_data['inform']))) {
1859 DBA::insert('item-delivery-data', $delivery_data);
1863 * @brief Update an existing item delivery data entry
1865 * @param integer $id The item id that is to be updated
1866 * @param array $item The item fields that are to be inserted
1868 private static function updateDeliveryData($id, $delivery_data)
1870 if (empty($id) || (empty($delivery_data['postopts']) && empty($delivery_data['inform']))) {
1874 DBA::update('item-delivery-data', $delivery_data, ['iid' => $id], true);
1878 * @brief Insert a new item content entry
1880 * @param array $item The item fields that are to be inserted
1882 private static function insertActivity(&$item)
1884 $activity_index = self::activityToIndex($item['verb']);
1886 if ($activity_index < 0) {
1890 $fields = ['uri' => $item['uri'], 'activity' => $activity_index,
1891 'uri-hash' => $item['uri-hash']];
1893 // We just remove everything that is content
1894 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1895 unset($item[$field]);
1898 // To avoid timing problems, we are using locks.
1899 $locked = Lock::acquire('item_insert_activity');
1901 logger("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
1904 // Do we already have this content?
1905 $item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-hash' => $item['uri-hash']]);
1906 if (DBA::isResult($item_activity)) {
1907 $item['iaid'] = $item_activity['id'];
1908 logger('Fetched activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
1909 } elseif (DBA::insert('item-activity', $fields)) {
1910 $item['iaid'] = DBA::lastInsertId();
1911 logger('Inserted activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
1913 // This shouldn't happen.
1914 logger('Could not insert activity for URI ' . $item['uri'] . ' - should not happen');
1918 Lock::release('item_insert_activity');
1924 * @brief Insert a new item content entry
1926 * @param array $item The item fields that are to be inserted
1928 private static function insertContent(&$item)
1930 $fields = ['uri' => $item['uri'], 'uri-plink-hash' => $item['uri-hash']];
1932 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1933 if (isset($item[$field])) {
1934 $fields[$field] = $item[$field];
1935 unset($item[$field]);
1939 // To avoid timing problems, we are using locks.
1940 $locked = Lock::acquire('item_insert_content');
1942 logger("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
1945 // Do we already have this content?
1946 $item_content = DBA::selectFirst('item-content', ['id'], ['uri-plink-hash' => $item['uri-hash']]);
1947 if (DBA::isResult($item_content)) {
1948 $item['icid'] = $item_content['id'];
1949 logger('Fetched content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
1950 } elseif (DBA::insert('item-content', $fields)) {
1951 $item['icid'] = DBA::lastInsertId();
1952 logger('Inserted content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
1954 // This shouldn't happen.
1955 logger('Could not insert content for URI ' . $item['uri'] . ' - should not happen');
1958 Lock::release('item_insert_content');
1963 * @brief Update existing item content entries
1965 * @param array $item The item fields that are to be changed
1966 * @param array $condition The condition for finding the item content entries
1968 private static function updateActivity($item, $condition)
1970 if (empty($item['verb'])) {
1973 $activity_index = self::activityToIndex($item['verb']);
1975 if ($activity_index < 0) {
1979 $fields = ['activity' => $activity_index];
1981 logger('Update activity for ' . json_encode($condition));
1983 DBA::update('item-activity', $fields, $condition, true);
1989 * @brief Update existing item content entries
1991 * @param array $item The item fields that are to be changed
1992 * @param array $condition The condition for finding the item content entries
1994 private static function updateContent($item, $condition)
1996 // We have to select only the fields from the "item-content" table
1998 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1999 if (isset($item[$field])) {
2000 $fields[$field] = $item[$field];
2004 if (empty($fields)) {
2005 // when there are no fields at all, just use the condition
2006 // This is to ensure that we always store content.
2007 $fields = $condition;
2010 logger('Update content for ' . json_encode($condition));
2012 DBA::update('item-content', $fields, $condition, true);
2016 * @brief Distributes public items to the receivers
2018 * @param integer $itemid Item ID that should be added
2019 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
2021 public static function distribute($itemid, $signed_text = '')
2023 $condition = ["`id` IN (SELECT `parent` FROM `item` WHERE `id` = ?)", $itemid];
2024 $parent = self::selectFirst(['owner-id'], $condition);
2025 if (!DBA::isResult($parent)) {
2029 // Only distribute public items from native networks
2030 $condition = ['id' => $itemid, 'uid' => 0,
2031 'network' => [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""],
2032 'visible' => true, 'deleted' => false, 'moderated' => false, 'private' => false];
2033 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2034 if (!DBA::isResult($item)) {
2038 $origin = $item['origin'];
2041 unset($item['parent']);
2042 unset($item['mention']);
2043 unset($item['wall']);
2044 unset($item['origin']);
2045 unset($item['starred']);
2049 $condition = ["`nurl` IN (SELECT `nurl` FROM `contact` WHERE `id` = ?) AND `uid` != 0 AND NOT `blocked` AND `rel` IN (?, ?)",
2050 $parent['owner-id'], Contact::SHARING, Contact::FRIEND];
2052 $contacts = DBA::select('contact', ['uid'], $condition);
2054 while ($contact = DBA::fetch($contacts)) {
2055 $users[$contact['uid']] = $contact['uid'];
2060 if ($item['uri'] != $item['parent-uri']) {
2061 $parents = self::select(['uid', 'origin'], ["`uri` = ? AND `uid` != 0", $item['parent-uri']]);
2062 while ($parent = DBA::fetch($parents)) {
2063 $users[$parent['uid']] = $parent['uid'];
2064 if ($parent['origin'] && !$origin) {
2065 $origin_uid = $parent['uid'];
2070 foreach ($users as $uid) {
2071 if ($origin_uid == $uid) {
2072 $item['diaspora_signed_text'] = $signed_text;
2074 self::storeForUser($itemid, $item, $uid);
2079 * @brief Store public items for the receivers
2081 * @param integer $itemid Item ID that should be added
2082 * @param array $item The item entry that will be stored
2083 * @param integer $uid The user that will receive the item entry
2085 private static function storeForUser($itemid, $item, $uid)
2087 $item['uid'] = $uid;
2088 $item['origin'] = 0;
2090 if ($item['uri'] == $item['parent-uri']) {
2091 $item['contact-id'] = Contact::getIdForURL($item['owner-link'], $uid);
2093 $item['contact-id'] = Contact::getIdForURL($item['author-link'], $uid);
2096 if (empty($item['contact-id'])) {
2097 $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $uid]);
2098 if (!DBA::isResult($self)) {
2101 $item['contact-id'] = $self['id'];
2104 /// @todo Handling of "event-id"
2107 if ($item['uri'] == $item['parent-uri']) {
2108 $contact = DBA::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
2109 if (DBA::isResult($contact)) {
2110 $notify = self::isRemoteSelf($contact, $item);
2114 $distributed = self::insert($item, false, $notify, true);
2116 if (!$distributed) {
2117 logger("Distributed public item " . $itemid . " for user " . $uid . " wasn't stored", LOGGER_DEBUG);
2119 logger("Distributed public item " . $itemid . " for user " . $uid . " with id " . $distributed, LOGGER_DEBUG);
2124 * @brief Add a shadow entry for a given item id that is a thread starter
2126 * We store every public item entry additionally with the user id "0".
2127 * This is used for the community page and for the search.
2128 * It is planned that in the future we will store public item entries only once.
2130 * @param integer $itemid Item ID that should be added
2132 public static function addShadow($itemid)
2134 $fields = ['uid', 'private', 'moderated', 'visible', 'deleted', 'network', 'uri'];
2135 $condition = ['id' => $itemid, 'parent' => [0, $itemid]];
2136 $item = self::selectFirst($fields, $condition);
2138 if (!DBA::isResult($item)) {
2142 // is it already a copy?
2143 if (($itemid == 0) || ($item['uid'] == 0)) {
2147 // Is it a visible public post?
2148 if (!$item["visible"] || $item["deleted"] || $item["moderated"] || $item["private"]) {
2152 // is it an entry from a connector? Only add an entry for natively connected networks
2153 if (!in_array($item["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""])) {
2157 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2161 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2163 if (DBA::isResult($item)) {
2164 // Preparing public shadow (removing user specific data)
2167 unset($item['parent']);
2168 unset($item['wall']);
2169 unset($item['mention']);
2170 unset($item['origin']);
2171 unset($item['starred']);
2172 unset($item['postopts']);
2173 unset($item['inform']);
2174 if ($item['uri'] == $item['parent-uri']) {
2175 $item['contact-id'] = $item['owner-id'];
2177 $item['contact-id'] = $item['author-id'];
2180 $public_shadow = self::insert($item, false, false, true);
2182 logger("Stored public shadow for thread ".$itemid." under id ".$public_shadow, LOGGER_DEBUG);
2187 * @brief Add a shadow entry for a given item id that is a comment
2189 * This function does the same like the function above - but for comments
2191 * @param integer $itemid Item ID that should be added
2193 public static function addShadowPost($itemid)
2195 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2196 if (!DBA::isResult($item)) {
2200 // Is it a toplevel post?
2201 if ($item['id'] == $item['parent']) {
2202 self::addShadow($itemid);
2206 // Is this a shadow entry?
2207 if ($item['uid'] == 0) {
2211 // Is there a shadow parent?
2212 if (!self::exists(['uri' => $item['parent-uri'], 'uid' => 0])) {
2216 // Is there already a shadow entry?
2217 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2221 // Save "origin" and "parent" state
2222 $origin = $item['origin'];
2223 $parent = $item['parent'];
2225 // Preparing public shadow (removing user specific data)
2228 unset($item['parent']);
2229 unset($item['wall']);
2230 unset($item['mention']);
2231 unset($item['origin']);
2232 unset($item['starred']);
2233 unset($item['postopts']);
2234 unset($item['inform']);
2235 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
2237 $public_shadow = self::insert($item, false, false, true);
2239 logger("Stored public shadow for comment ".$item['uri']." under id ".$public_shadow, LOGGER_DEBUG);
2241 // If this was a comment to a Diaspora post we don't get our comment back.
2242 // This means that we have to distribute the comment by ourselves.
2243 if ($origin && self::exists(['id' => $parent, 'network' => NETWORK_DIASPORA])) {
2244 self::distribute($public_shadow);
2249 * Adds a language specification in a "language" element of given $arr.
2250 * Expects "body" element to exist in $arr.
2252 private static function addLanguageToItemArray(&$item)
2254 $naked_body = BBCode::toPlaintext($item['body'], false);
2256 $ld = new Text_LanguageDetect();
2257 $ld->setNameMode(2);
2258 $languages = $ld->detect($naked_body, 3);
2260 if (is_array($languages)) {
2261 $item['language'] = json_encode($languages);
2266 * @brief Creates an unique guid out of a given uri
2268 * @param string $uri uri of an item entry
2269 * @param string $host hostname for the GUID prefix
2270 * @return string unique guid
2272 public static function guidFromUri($uri, $host)
2274 // Our regular guid routine is using this kind of prefix as well
2275 // We have to avoid that different routines could accidentally create the same value
2276 $parsed = parse_url($uri);
2278 // We use a hash of the hostname as prefix for the guid
2279 $guid_prefix = hash("crc32", $host);
2281 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
2282 unset($parsed["scheme"]);
2284 // Glue it together to be able to make a hash from it
2285 $host_id = implode("/", $parsed);
2287 // We could use any hash algorithm since it isn't a security issue
2288 $host_hash = hash("ripemd128", $host_id);
2290 return $guid_prefix.$host_hash;
2294 * generate an unique URI
2296 * @param integer $uid User id
2297 * @param string $guid An existing GUID (Otherwise it will be generated)
2301 public static function newURI($uid, $guid = "")
2304 $guid = System::createGUID(32);
2307 $hostname = self::getApp()->get_hostname();
2309 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $uid]);
2311 $uri = "urn:X-dfrn:" . $hostname . ':' . $user['nickname'] . ':' . $guid;
2317 * @brief Set "success_update" and "last-item" to the date of the last time we heard from this contact
2319 * This can be used to filter for inactive contacts.
2320 * Only do this for public postings to avoid privacy problems, since poco data is public.
2321 * Don't set this value if it isn't from the owner (could be an author that we don't know)
2323 * @param array $arr Contains the just posted item record
2325 private static function updateContact($arr)
2327 // Unarchive the author
2328 $contact = DBA::selectFirst('contact', [], ['id' => $arr["author-id"]]);
2329 if (DBA::isResult($contact)) {
2330 Contact::unmarkForArchival($contact);
2333 // Unarchive the contact if it's not our own contact
2334 $contact = DBA::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
2335 if (DBA::isResult($contact)) {
2336 Contact::unmarkForArchival($contact);
2339 $update = (!$arr['private'] && ((defaults($arr, 'author-link', '') === defaults($arr, 'owner-link', '')) || ($arr["parent-uri"] === $arr["uri"])));
2341 // Is it a forum? Then we don't care about the rules from above
2342 if (!$update && ($arr["network"] == NETWORK_DFRN) && ($arr["parent-uri"] === $arr["uri"])) {
2343 if (DBA::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
2349 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2350 ['id' => $arr['contact-id']]);
2352 // Now do the same for the system wide contacts with uid=0
2353 if (!$arr['private']) {
2354 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2355 ['id' => $arr['owner-id']]);
2357 if ($arr['owner-id'] != $arr['author-id']) {
2358 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2359 ['id' => $arr['author-id']]);
2364 public static function setHashtags(&$item)
2367 $tags = get_tags($item["body"]);
2370 if (!count($tags)) {
2374 // This sorting is important when there are hashtags that are part of other hashtags
2375 // Otherwise there could be problems with hashtags like #test and #test2
2378 $URLSearchString = "^\[\]";
2380 // All hashtags should point to the home server if "local_tags" is activated
2381 if (Config::get('system', 'local_tags')) {
2382 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2383 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["body"]);
2385 $item["tag"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2386 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["tag"]);
2389 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
2390 $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2392 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
2395 $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
2397 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
2400 $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
2402 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
2405 // Repair recursive urls
2406 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2407 "#$2", $item["body"]);
2409 foreach ($tags as $tag) {
2410 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=')) {
2414 $basetag = str_replace('_',' ',substr($tag,1));
2416 $newtag = '#[url=' . System::baseUrl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
2418 $item["body"] = str_replace($tag, $newtag, $item["body"]);
2420 if (!stristr($item["tag"], "/search?tag=" . $basetag . "]" . $basetag . "[/url]")) {
2421 if (strlen($item["tag"])) {
2422 $item["tag"] = ','.$item["tag"];
2424 $item["tag"] = $newtag.$item["tag"];
2428 // Convert back the masked hashtags
2429 $item["body"] = str_replace("#", "#", $item["body"]);
2432 public static function getGuidById($id)
2434 $item = self::selectFirst(['guid'], ['id' => $id]);
2435 if (DBA::isResult($item)) {
2436 return $item['guid'];
2442 public static function getIdAndNickByGuid($guid, $uid = 0)
2448 $uid == local_user();
2451 // Does the given user have this item?
2453 $item = DBA::fetchFirst("SELECT `item`.`id`, `user`.`nickname` FROM `item`
2454 INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
2455 WHERE `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
2456 AND `item`.`guid` = ? AND `item`.`uid` = ?", $guid, $uid);
2457 if (DBA::isResult($item)) {
2459 $nick = $item["nickname"];
2463 // Or is it anywhere on the server?
2465 $item = DBA::fetchFirst("SELECT `item`.`id`, `user`.`nickname` FROM `item`
2466 INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
2467 WHERE `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
2468 AND NOT `item`.`private` AND `item`.`wall`
2469 AND `item`.`guid` = ?", $guid);
2470 if (DBA::isResult($item)) {
2472 $nick = $item["nickname"];
2475 return ["nick" => $nick, "id" => $id];
2479 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
2481 * @param int $item_id
2482 * @return bool true if item was deleted, else false
2484 private static function tagDeliver($uid, $item_id)
2488 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
2489 if (!DBA::isResult($user)) {
2493 $community_page = (($user['page-flags'] == Contact::PAGE_COMMUNITY) ? true : false);
2494 $prvgroup = (($user['page-flags'] == Contact::PAGE_PRVGROUP) ? true : false);
2496 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2497 if (!DBA::isResult($item)) {
2501 $link = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
2504 * Diaspora uses their own hardwired link URL in @-tags
2505 * instead of the one we supply with webfinger
2507 $dlink = normalise_link(System::baseUrl() . '/u/' . $user['nickname']);
2509 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
2511 foreach ($matches as $mtch) {
2512 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
2514 logger('mention found: ' . $mtch[2]);
2520 if (($community_page || $prvgroup) &&
2521 !$item['wall'] && !$item['origin'] && ($item['id'] == $item['parent'])) {
2522 // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
2524 logger("no-mention top-level post to community or private group. delete.");
2525 DBA::delete('item', ['id' => $item_id]);
2531 $arr = ['item' => $item, 'user' => $user];
2533 Addon::callHooks('tagged', $arr);
2535 if (!$community_page && !$prvgroup) {
2540 * tgroup delivery - setup a second delivery chain
2541 * prevent delivery looping - only proceed
2542 * if the message originated elsewhere and is a top-level post
2544 if ($item['wall'] || $item['origin'] || ($item['id'] != $item['parent'])) {
2548 // now change this copy of the post to a forum head message and deliver to all the tgroup members
2549 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'], ['uid' => $uid, 'self' => true]);
2550 if (!DBA::isResult($self)) {
2554 $owner_id = Contact::getIdForURL($self['url']);
2556 // also reset all the privacy bits to the forum default permissions
2558 $private = ($user['allow_cid'] || $user['allow_gid'] || $user['deny_cid'] || $user['deny_gid']) ? 1 : 0;
2560 $forum_mode = ($prvgroup ? 2 : 1);
2562 $fields = ['wall' => true, 'origin' => true, 'forum_mode' => $forum_mode, 'contact-id' => $self['id'],
2563 'owner-id' => $owner_id, 'owner-link' => $self['url'], 'private' => $private, 'allow_cid' => $user['allow_cid'],
2564 'allow_gid' => $user['allow_gid'], 'deny_cid' => $user['deny_cid'], 'deny_gid' => $user['deny_gid']];
2565 DBA::update('item', $fields, ['id' => $item_id]);
2567 self::updateThread($item_id);
2569 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', 'tgroup', $item_id);
2572 public static function isRemoteSelf($contact, &$datarray)
2576 if (!$contact['remote_self']) {
2580 // Prevent the forwarding of posts that are forwarded
2581 if (!empty($datarray["extid"]) && ($datarray["extid"] == NETWORK_DFRN)) {
2582 logger('Already forwarded', LOGGER_DEBUG);
2586 // Prevent to forward already forwarded posts
2587 if ($datarray["app"] == $a->get_hostname()) {
2588 logger('Already forwarded (second test)', LOGGER_DEBUG);
2592 // Only forward posts
2593 if ($datarray["verb"] != ACTIVITY_POST) {
2594 logger('No post', LOGGER_DEBUG);
2598 if (($contact['network'] != NETWORK_FEED) && $datarray['private']) {
2599 logger('Not public', LOGGER_DEBUG);
2603 $datarray2 = $datarray;
2604 logger('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), LOGGER_DEBUG);
2605 if ($contact['remote_self'] == 2) {
2606 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
2607 ['uid' => $contact['uid'], 'self' => true]);
2608 if (DBA::isResult($self)) {
2609 $datarray['contact-id'] = $self["id"];
2611 $datarray['owner-name'] = $self["name"];
2612 $datarray['owner-link'] = $self["url"];
2613 $datarray['owner-avatar'] = $self["thumb"];
2615 $datarray['author-name'] = $datarray['owner-name'];
2616 $datarray['author-link'] = $datarray['owner-link'];
2617 $datarray['author-avatar'] = $datarray['owner-avatar'];
2619 unset($datarray['created']);
2620 unset($datarray['edited']);
2622 unset($datarray['network']);
2623 unset($datarray['owner-id']);
2624 unset($datarray['author-id']);
2627 if ($contact['network'] != NETWORK_FEED) {
2628 $datarray["guid"] = System::createGUID(32);
2629 unset($datarray["plink"]);
2630 $datarray["uri"] = self::newURI($contact['uid'], $datarray["guid"]);
2631 $datarray["parent-uri"] = $datarray["uri"];
2632 $datarray["thr-parent"] = $datarray["uri"];
2633 $datarray["extid"] = NETWORK_DFRN;
2634 $urlpart = parse_url($datarray2['author-link']);
2635 $datarray["app"] = $urlpart["host"];
2637 $datarray['private'] = 0;
2641 if ($contact['network'] != NETWORK_FEED) {
2642 // Store the original post
2643 $result = self::insert($datarray2, false, false);
2644 logger('remote-self post original item - Contact '.$contact['url'].' return '.$result.' Item '.print_r($datarray2, true), LOGGER_DEBUG);
2646 $datarray["app"] = "Feed";
2650 // Trigger automatic reactions for addons
2651 $datarray['api_source'] = true;
2653 // We have to tell the hooks who we are - this really should be improved
2654 $_SESSION["authenticated"] = true;
2655 $_SESSION["uid"] = $contact['uid'];
2664 * @param array $item
2668 public static function fixPrivatePhotos($s, $uid, $item = null, $cid = 0)
2670 if (Config::get('system', 'disable_embedded')) {
2674 logger('check for photos', LOGGER_DEBUG);
2675 $site = substr(System::baseUrl(), strpos(System::baseUrl(), '://'));
2680 $img_start = strpos($orig_body, '[img');
2681 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2682 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2684 while (($img_st_close !== false) && ($img_len !== false)) {
2685 $img_st_close++; // make it point to AFTER the closing bracket
2686 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2688 logger('found photo ' . $image, LOGGER_DEBUG);
2690 if (stristr($image, $site . '/photo/')) {
2691 // Only embed locally hosted photos
2693 $i = basename($image);
2694 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2695 $x = strpos($i, '-');
2698 $res = substr($i, $x + 1);
2699 $i = substr($i, 0, $x);
2700 $fields = ['data', 'type', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'];
2701 $photo = DBA::selectFirst('photo', $fields, ['resource-id' => $i, 'scale' => $res, 'uid' => $uid]);
2702 if (DBA::isResult($photo)) {
2704 * Check to see if we should replace this photo link with an embedded image
2705 * 1. No need to do so if the photo is public
2706 * 2. If there's a contact-id provided, see if they're in the access list
2707 * for the photo. If so, embed it.
2708 * 3. Otherwise, if we have an item, see if the item permissions match the photo
2709 * permissions, regardless of order but first check to see if they're an exact
2710 * match to save some processing overhead.
2712 if (self::hasPermissions($photo)) {
2714 $recips = self::enumeratePermissions($photo);
2715 if (in_array($cid, $recips)) {
2719 if (self::samePermissions($item, $photo)) {
2725 $data = $photo['data'];
2726 $type = $photo['type'];
2728 // If a custom width and height were specified, apply before embedding
2729 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2730 logger('scaling photo', LOGGER_DEBUG);
2732 $width = intval($match[1]);
2733 $height = intval($match[2]);
2735 $Image = new Image($data, $type);
2736 if ($Image->isValid()) {
2737 $Image->scaleDown(max($width, $height));
2738 $data = $Image->asString();
2739 $type = $Image->getType();
2743 logger('replacing photo', LOGGER_DEBUG);
2744 $image = 'data:' . $type . ';base64,' . base64_encode($data);
2745 logger('replaced: ' . $image, LOGGER_DATA);
2751 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2752 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2753 if ($orig_body === false) {
2757 $img_start = strpos($orig_body, '[img');
2758 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2759 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2762 $new_body = $new_body . $orig_body;
2767 private static function hasPermissions($obj)
2769 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2770 !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2773 private static function samePermissions($obj1, $obj2)
2775 // first part is easy. Check that these are exactly the same.
2776 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2777 && ($obj1['allow_gid'] == $obj2['allow_gid'])
2778 && ($obj1['deny_cid'] == $obj2['deny_cid'])
2779 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
2783 // This is harder. Parse all the permissions and compare the resulting set.
2784 $recipients1 = self::enumeratePermissions($obj1);
2785 $recipients2 = self::enumeratePermissions($obj2);
2789 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2790 return ($recipients1 == $recipients2);
2793 // returns an array of contact-ids that are allowed to see this object
2794 private static function enumeratePermissions($obj)
2796 $allow_people = expand_acl($obj['allow_cid']);
2797 $allow_groups = Group::expand(expand_acl($obj['allow_gid']));
2798 $deny_people = expand_acl($obj['deny_cid']);
2799 $deny_groups = Group::expand(expand_acl($obj['deny_gid']));
2800 $recipients = array_unique(array_merge($allow_people, $allow_groups));
2801 $deny = array_unique(array_merge($deny_people, $deny_groups));
2802 $recipients = array_diff($recipients, $deny);
2806 public static function getFeedTags($item)
2810 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2812 for ($x = 0; $x < $cnt; $x ++) {
2813 if ($matches[1][$x]) {
2814 $ret[$matches[2][$x]] = ['#', $matches[1][$x], $matches[2][$x]];
2819 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2821 for ($x = 0; $x < $cnt; $x ++) {
2822 if ($matches[1][$x]) {
2823 $ret[] = ['@', $matches[1][$x], $matches[2][$x]];
2830 public static function expire($uid, $days, $network = "", $force = false)
2832 if (!$uid || ($days < 1)) {
2836 $condition = ["`uid` = ? AND NOT `deleted` AND `id` = `parent` AND `gravity` = ?",
2837 $uid, GRAVITY_PARENT];
2840 * $expire_network_only = save your own wall posts
2841 * and just expire conversations started by others
2843 $expire_network_only = PConfig::get($uid, 'expire', 'network_only', false);
2845 if ($expire_network_only) {
2846 $condition[0] .= " AND NOT `wall`";
2849 if ($network != "") {
2850 $condition[0] .= " AND `network` = ?";
2851 $condition[] = $network;
2854 * There is an index "uid_network_received" but not "uid_network_created"
2855 * This avoids the creation of another index just for one purpose.
2856 * And it doesn't really matter wether to look at "received" or "created"
2858 $condition[0] .= " AND `received` < UTC_TIMESTAMP() - INTERVAL ? DAY";
2859 $condition[] = $days;
2861 $condition[0] .= " AND `created` < UTC_TIMESTAMP() - INTERVAL ? DAY";
2862 $condition[] = $days;
2865 $items = self::select(['file', 'resource-id', 'starred', 'type', 'id', 'post-type'], $condition);
2867 if (!DBA::isResult($items)) {
2871 $expire_items = PConfig::get($uid, 'expire', 'items', true);
2873 // Forcing expiring of items - but not notes and marked items
2875 $expire_items = true;
2878 $expire_notes = PConfig::get($uid, 'expire', 'notes', true);
2879 $expire_starred = PConfig::get($uid, 'expire', 'starred', true);
2880 $expire_photos = PConfig::get($uid, 'expire', 'photos', false);
2884 while ($item = Item::fetch($items)) {
2885 // don't expire filed items
2887 if (strpos($item['file'], '[') !== false) {
2891 // Only expire posts, not photos and photo comments
2893 if (!$expire_photos && strlen($item['resource-id'])) {
2895 } elseif (!$expire_starred && intval($item['starred'])) {
2897 } elseif (!$expire_notes && (($item['type'] == 'note') || ($item['post-type'] == Item::PT_PERSONAL_NOTE))) {
2899 } elseif (!$expire_items && ($item['type'] != 'note') && ($item['post-type'] != Item::PT_PERSONAL_NOTE)) {
2903 self::deleteById($item['id'], PRIORITY_LOW);
2908 logger('User ' . $uid . ": expired $expired items; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
2911 public static function firstPostDate($uid, $wall = false)
2913 $condition = ['uid' => $uid, 'wall' => $wall, 'deleted' => false, 'visible' => true, 'moderated' => false];
2914 $params = ['order' => ['created' => false]];
2915 $thread = DBA::selectFirst('thread', ['created'], $condition, $params);
2916 if (DBA::isResult($thread)) {
2917 return substr(DateTimeFormat::local($thread['created']), 0, 10);
2923 * @brief add/remove activity to an item
2925 * Toggle activities as like,dislike,attend of an item
2927 * @param string $item_id
2928 * @param string $verb
2929 * Activity verb. One of
2930 * like, unlike, dislike, undislike, attendyes, unattendyes,
2931 * attendno, unattendno, attendmaybe, unattendmaybe
2932 * @hook 'post_local_end'
2934 * 'post_id' => ID of posted item
2936 public static function performLike($item_id, $verb)
2938 if (!local_user() && !remote_user()) {
2945 $activity = ACTIVITY_LIKE;
2949 $activity = ACTIVITY_DISLIKE;
2953 $activity = ACTIVITY_ATTEND;
2957 $activity = ACTIVITY_ATTENDNO;
2960 case 'unattendmaybe':
2961 $activity = ACTIVITY_ATTENDMAYBE;
2964 logger('like: unknown verb ' . $verb . ' for item ' . $item_id);
2968 // Enable activity toggling instead of on/off
2969 $event_verb_flag = $activity === ACTIVITY_ATTEND || $activity === ACTIVITY_ATTENDNO || $activity === ACTIVITY_ATTENDMAYBE;
2971 logger('like: verb ' . $verb . ' item ' . $item_id);
2973 $item = self::selectFirst(self::ITEM_FIELDLIST, ['`id` = ? OR `uri` = ?', $item_id, $item_id]);
2974 if (!DBA::isResult($item)) {
2975 logger('like: unknown item ' . $item_id);
2979 $item_uri = $item['uri'];
2981 $uid = $item['uid'];
2982 if (($uid == 0) && local_user()) {
2983 $uid = local_user();
2986 if (!can_write_wall($uid)) {
2987 logger('like: unable to write on wall ' . $uid);
2991 // Retrieves the local post owner
2992 $owner_self_contact = DBA::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
2993 if (!DBA::isResult($owner_self_contact)) {
2994 logger('like: unknown owner ' . $uid);
2998 // Retrieve the current logged in user's public contact
2999 $author_id = public_contact();
3001 $author_contact = DBA::selectFirst('contact', ['url'], ['id' => $author_id]);
3002 if (!DBA::isResult($author_contact)) {
3003 logger('like: unknown author ' . $author_id);
3007 // Contact-id is the uid-dependant author contact
3008 if (local_user() == $uid) {
3009 $item_contact_id = $owner_self_contact['id'];
3010 $item_contact = $owner_self_contact;
3012 $item_contact_id = Contact::getIdForURL($author_contact['url'], $uid, true);
3013 $item_contact = DBA::selectFirst('contact', [], ['id' => $item_contact_id]);
3014 if (!DBA::isResult($item_contact)) {
3015 logger('like: unknown item contact ' . $item_contact_id);
3020 // Look for an existing verb row
3021 // event participation are essentially radio toggles. If you make a subsequent choice,
3022 // we need to eradicate your first choice.
3023 if ($event_verb_flag) {
3024 $verbs = [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE];
3026 // Translate to the index based activity index
3028 foreach ($verbs as $verb) {
3029 $activities[] = self::activityToIndex($verb);
3032 $activities = self::activityToIndex($activity);
3035 $condition = ['activity' => $activities, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY,
3036 'author-id' => $author_id, 'uid' => $item['uid'], 'thr-parent' => $item_uri];
3038 $like_item = self::selectFirst(['id', 'guid', 'verb'], $condition);
3040 // If it exists, mark it as deleted
3041 if (DBA::isResult($like_item)) {
3042 self::deleteById($like_item['id']);
3044 if (!$event_verb_flag || $like_item['verb'] == $activity) {
3049 // Verb is "un-something", just trying to delete existing entries
3050 if (strpos($verb, 'un') === 0) {
3054 $objtype = $item['resource-id'] ? ACTIVITY_OBJ_IMAGE : ACTIVITY_OBJ_NOTE ;
3057 'guid' => System::createGUID(32),
3058 'uri' => self::newURI($item['uid']),
3059 'uid' => $item['uid'],
3060 'contact-id' => $item_contact_id,
3061 'wall' => $item['wall'],
3063 'network' => NETWORK_DFRN,
3064 'gravity' => GRAVITY_ACTIVITY,
3065 'parent' => $item['id'],
3066 'parent-uri' => $item['uri'],
3067 'thr-parent' => $item['uri'],
3068 'owner-id' => $item['owner-id'],
3069 'author-id' => $author_id,
3070 'body' => $activity,
3071 'verb' => $activity,
3072 'object-type' => $objtype,
3073 'allow_cid' => $item['allow_cid'],
3074 'allow_gid' => $item['allow_gid'],
3075 'deny_cid' => $item['deny_cid'],
3076 'deny_gid' => $item['deny_gid'],
3081 $new_item_id = self::insert($new_item);
3083 // If the parent item isn't visible then set it to visible
3084 if (!$item['visible']) {
3085 self::update(['visible' => true], ['id' => $item['id']]);
3088 // Save the author information for the like in case we need to relay to Diaspora
3089 Diaspora::storeLikeSignature($item_contact, $new_item_id);
3091 $new_item['id'] = $new_item_id;
3093 Addon::callHooks('post_local_end', $new_item);
3095 Worker::add(PRIORITY_HIGH, "Notifier", "like", $new_item_id);
3100 private static function addThread($itemid, $onlyshadow = false)
3102 $fields = ['uid', 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private', 'pubmail',
3103 'moderated', 'visible', 'starred', 'contact-id', 'post-type',
3104 'deleted', 'origin', 'forum_mode', 'mention', 'network', 'author-id', 'owner-id'];
3105 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
3106 $item = self::selectFirst($fields, $condition);
3108 if (!DBA::isResult($item)) {
3112 $item['iid'] = $itemid;
3115 $result = DBA::insert('thread', $item);
3117 logger("Add thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
3121 private static function updateThread($itemid, $setmention = false)
3123 $fields = ['uid', 'guid', 'created', 'edited', 'commented', 'received', 'changed', 'post-type',
3124 'wall', 'private', 'pubmail', 'moderated', 'visible', 'starred', 'contact-id',
3125 'deleted', 'origin', 'forum_mode', 'network', 'author-id', 'owner-id'];
3126 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
3128 $item = self::selectFirst($fields, $condition);
3129 if (!DBA::isResult($item)) {
3134 $item["mention"] = 1;
3141 foreach ($item as $field => $data) {
3142 if (!in_array($field, ["guid"])) {
3143 $fields[$field] = $data;
3147 $result = DBA::update('thread', $fields, ['iid' => $itemid]);
3149 logger("Update thread for item ".$itemid." - guid ".$item["guid"]." - ".(int)$result, LOGGER_DEBUG);
3152 private static function deleteThread($itemid, $itemuri = "")
3154 $item = DBA::selectFirst('thread', ['uid'], ['iid' => $itemid]);
3155 if (!DBA::isResult($item)) {
3156 logger('No thread found for id '.$itemid, LOGGER_DEBUG);
3160 // Using dba::delete at this time could delete the associated item entries
3161 $result = DBA::e("DELETE FROM `thread` WHERE `iid` = ?", $itemid);
3163 logger("deleteThread: Deleted thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
3165 if ($itemuri != "") {
3166 $condition = ["`uri` = ? AND NOT `deleted` AND NOT (`uid` IN (?, 0))", $itemuri, $item["uid"]];
3167 if (!self::exists($condition)) {
3168 DBA::delete('item', ['uri' => $itemuri, 'uid' => 0]);
3169 logger("deleteThread: Deleted shadow for item ".$itemuri, LOGGER_DEBUG);