4 * @file src/Model/Item.php
7 namespace Friendica\Model;
10 use Friendica\BaseObject;
11 use Friendica\Content\Text;
12 use Friendica\Core\Addon;
13 use Friendica\Core\Config;
14 use Friendica\Core\L10n;
15 use Friendica\Core\Lock;
16 use Friendica\Core\PConfig;
17 use Friendica\Core\System;
18 use Friendica\Core\Worker;
19 use Friendica\Database\DBM;
20 use Friendica\Object\Image;
21 use Friendica\Protocol\Diaspora;
22 use Friendica\Protocol\OStatus;
23 use Friendica\Util\DateTimeFormat;
24 use Friendica\Util\XML;
25 use Text_LanguageDetect;
27 require_once 'boot.php';
28 require_once 'include/items.php';
29 require_once 'include/text.php';
31 class Item extends BaseObject
33 // Field list that is used to display the items
34 const DISPLAY_FIELDLIST = ['uid', 'id', 'parent', 'uri', 'thr-parent', 'parent-uri', 'guid', 'network',
35 'commented', 'created', 'edited', 'received', 'verb', 'object-type', 'postopts', 'plink',
36 'wall', 'private', 'starred', 'origin', 'title', 'body', 'file', 'attach', 'language',
37 'content-warning', 'location', 'coord', 'app', 'rendered-hash', 'rendered-html', 'object',
38 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'item_id',
39 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
40 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'owner-network',
41 'contact-id', 'contact-link', 'contact-name', 'contact-avatar',
42 'writable', 'self', 'cid', 'alias',
43 'event-id', 'event-created', 'event-edited', 'event-start', 'event-finish',
44 'event-summary', 'event-desc', 'event-location', 'event-type',
45 'event-nofinish', 'event-adjust', 'event-ignore', 'event-id'];
47 // Field list that is used to deliver items via the protocols
48 const DELIVER_FIELDLIST = ['uid', 'id', 'parent', 'uri', 'thr-parent', 'parent-uri', 'guid',
49 'created', 'edited', 'verb', 'object-type', 'object', 'target',
50 'private', 'title', 'body', 'location', 'coord', 'app',
51 'attach', 'tag', 'bookmark', 'deleted', 'extid',
52 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
53 'author-id', 'author-link', 'owner-link', 'contact-uid',
54 'signed_text', 'signature', 'signer'];
56 // Field list for "item-content" table that is mixed with the item table
57 const MIXED_CONTENT_FIELDLIST = ['title', 'content-warning', 'body', 'location',
58 'coord', 'app', 'rendered-hash', 'rendered-html', 'verb',
59 'object-type', 'object', 'target-type', 'target', 'plink'];
61 // Field list for "item-content" table that is not present in the "item" table
62 const CONTENT_FIELDLIST = ['language'];
64 // All fields in the item table
65 const ITEM_FIELDLIST = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
66 'contact-id', 'type', 'wall', 'gravity', 'extid', 'icid',
67 'created', 'edited', 'commented', 'received', 'changed', 'verb',
68 'postopts', 'plink', 'resource-id', 'event-id', 'tag', 'attach', 'inform',
69 'file', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
70 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
71 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global', 'network',
72 'title', 'content-warning', 'body', 'location', 'coord', 'app',
73 'rendered-hash', 'rendered-html', 'object-type', 'object', 'target-type', 'target',
74 'author-id', 'author-link', 'author-name', 'author-avatar',
75 'owner-id', 'owner-link', 'owner-name', 'owner-avatar'];
78 * @brief Fetch a single item row
80 * @param mixed $stmt statement object
81 * @return array current row
83 public static function fetch($stmt)
85 $row = dba::fetch($stmt);
87 // Fetch data from the item-content table whenever there is content there
88 foreach (self::MIXED_CONTENT_FIELDLIST as $field) {
89 if (empty($row[$field]) && !empty($row['item-' . $field])) {
90 $row[$field] = $row['item-' . $field];
92 unset($row['item-' . $field]);
95 // We prefer the data from the user's contact over the public one
96 if (!empty($row['author-link']) && !empty($row['contact-link']) &&
97 ($row['author-link'] == $row['contact-link'])) {
98 if (isset($row['author-avatar']) && !empty($row['contact-avatar'])) {
99 $row['author-avatar'] = $row['contact-avatar'];
101 if (isset($row['author-name']) && !empty($row['contact-name'])) {
102 $row['author-name'] = $row['contact-name'];
106 if (!empty($row['owner-link']) && !empty($row['contact-link']) &&
107 ($row['owner-link'] == $row['contact-link'])) {
108 if (isset($row['owner-avatar']) && !empty($row['contact-avatar'])) {
109 $row['owner-avatar'] = $row['contact-avatar'];
111 if (isset($row['owner-name']) && !empty($row['contact-name'])) {
112 $row['owner-name'] = $row['contact-name'];
116 // Build the tag string out of the term entries
117 if (isset($row['id']) && array_key_exists('tag', $row)) {
118 $row['tag'] = Term::tagTextFromItemId($row['id']);
121 // Build the file string out of the term entries
122 if (isset($row['id']) && array_key_exists('file', $row)) {
123 $row['file'] = Term::fileTextFromItemId($row['id']);
126 // We can always comment on posts from these networks
127 if (isset($row['writable']) && !empty($row['network']) &&
128 in_array($row['network'], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS])) {
129 $row['writable'] = true;
136 * @brief Fills an array with data from an item query
138 * @param object $stmt statement object
139 * @return array Data array
141 public static function inArray($stmt, $do_close = true) {
142 if (is_bool($stmt)) {
147 while ($row = self::fetch($stmt)) {
157 * @brief Check if item data exists
159 * @param array $condition array of fields for condition
161 * @return boolean Are there rows for that condition?
163 public static function exists($condition) {
164 $stmt = self::select(['id'], $condition, ['limit' => 1]);
166 if (is_bool($stmt)) {
169 $retval = (dba::num_rows($stmt) > 0);
178 * Retrieve a single record from the item table for a given user and returns it in an associative array
180 * @brief Retrieve a single record from a table
181 * @param integer $uid User ID
182 * @param array $fields
183 * @param array $condition
184 * @param array $params
188 public static function selectFirstForUser($uid, array $selected = [], array $condition = [], $params = [])
190 $params['uid'] = $uid;
192 if (empty($selected)) {
193 $selected = Item::DISPLAY_FIELDLIST;
196 return self::selectFirst($selected, $condition, $params);
200 * @brief Select rows from the item table for a given user
202 * @param integer $uid User ID
203 * @param array $selected Array of selected fields, empty for all
204 * @param array $condition Array of fields for condition
205 * @param array $params Array of several parameters
207 * @return boolean|object
209 public static function selectForUser($uid, array $selected = [], array $condition = [], $params = [])
211 $params['uid'] = $uid;
213 if (empty($selected)) {
214 $selected = Item::DISPLAY_FIELDLIST;
217 return self::select($selected, $condition, $params);
221 * Retrieve a single record from the item table and returns it in an associative array
223 * @brief Retrieve a single record from a table
224 * @param array $fields
225 * @param array $condition
226 * @param array $params
230 public static function selectFirst(array $fields = [], array $condition = [], $params = [])
232 $params['limit'] = 1;
234 $result = self::select($fields, $condition, $params);
236 if (is_bool($result)) {
239 $row = self::fetch($result);
246 * @brief Select rows from the item table
248 * @param array $selected Array of selected fields, empty for all
249 * @param array $condition Array of fields for condition
250 * @param array $params Array of several parameters
252 * @return boolean|object
254 public static function select(array $selected = [], array $condition = [], $params = [])
259 if (isset($params['uid'])) {
260 $uid = $params['uid'];
264 $fields = self::fieldlist($selected);
266 $select_fields = self::constructSelectFields($fields, $selected);
268 $condition_string = dba::buildCondition($condition);
270 $condition_string = self::addTablesToFields($condition_string, $fields);
273 $condition_string = $condition_string . ' AND ' . self::condition(false);
276 $param_string = self::addTablesToFields(dba::buildParameter($params), $fields);
278 $table = "`item` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, false, $usermode);
280 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
282 return dba::p($sql, $condition);
286 * @brief Select rows from the starting post in the item table
288 * @param integer $uid User ID
289 * @param array $fields Array of selected fields, empty for all
290 * @param array $condition Array of fields for condition
291 * @param array $params Array of several parameters
293 * @return boolean|object
295 public static function selectThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
297 $params['uid'] = $uid;
299 if (empty($selected)) {
300 $selected = Item::DISPLAY_FIELDLIST;
303 return self::selectThread($selected, $condition, $params);
307 * Retrieve a single record from the starting post in the item table and returns it in an associative array
309 * @brief Retrieve a single record from a table
310 * @param integer $uid User ID
311 * @param array $selected
312 * @param array $condition
313 * @param array $params
317 public static function selectFirstThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
319 $params['uid'] = $uid;
321 if (empty($selected)) {
322 $selected = Item::DISPLAY_FIELDLIST;
325 return self::selectFirstThread($selected, $condition, $params);
329 * Retrieve a single record from the starting post in 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 selectFirstThread(array $fields = [], array $condition = [], $params = [])
340 $params['limit'] = 1;
341 $result = self::selectThread($fields, $condition, $params);
343 if (is_bool($result)) {
346 $row = self::fetch($result);
353 * @brief Select rows from the starting post in the item table
355 * @param array $selected Array of selected fields, empty for all
356 * @param array $condition Array of fields for condition
357 * @param array $params Array of several parameters
359 * @return boolean|object
361 public static function selectThread(array $selected = [], array $condition = [], $params = [])
366 if (isset($params['uid'])) {
367 $uid = $params['uid'];
371 $fields = self::fieldlist($selected);
373 $threadfields = ['thread' => ['iid', 'uid', 'contact-id', 'owner-id', 'author-id',
374 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private',
375 'pubmail', 'moderated', 'visible', 'starred', 'ignored', 'bookmark',
376 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'network']];
378 $select_fields = self::constructSelectFields($fields, $selected);
380 $condition_string = dba::buildCondition($condition);
382 $condition_string = self::addTablesToFields($condition_string, $threadfields);
383 $condition_string = self::addTablesToFields($condition_string, $fields);
386 $condition_string = $condition_string . ' AND ' . self::condition(true);
389 $param_string = dba::buildParameter($params);
390 $param_string = self::addTablesToFields($param_string, $threadfields);
391 $param_string = self::addTablesToFields($param_string, $fields);
393 $table = "`thread` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, true, $usermode);
395 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
397 return dba::p($sql, $condition);
401 * @brief Returns a list of fields that are associated with the item table
403 * @return array field list
405 private static function fieldlist($selected)
409 $fields['item'] = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
410 'contact-id', 'owner-id', 'author-id', 'type', 'wall', 'gravity', 'extid',
411 'created', 'edited', 'commented', 'received', 'changed', 'postopts',
412 'resource-id', 'event-id', 'tag', 'attach', 'inform',
413 'file', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
414 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
415 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global',
416 'id' => 'item_id', 'network', 'icid'];
418 $fields['item-content'] = array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST);
420 $fields['author'] = ['url' => 'author-link', 'name' => 'author-name',
421 'thumb' => 'author-avatar', 'nick' => 'author-nick', 'network' => 'author-network'];
423 $fields['owner'] = ['url' => 'owner-link', 'name' => 'owner-name',
424 'thumb' => 'owner-avatar', 'nick' => 'owner-nick', 'network' => 'owner-network'];
426 $fields['contact'] = ['url' => 'contact-link', 'name' => 'contact-name', 'thumb' => 'contact-avatar',
427 'writable', 'self', 'id' => 'cid', 'alias', 'uid' => 'contact-uid',
428 'photo', 'name-date', 'uri-date', 'avatar-date', 'thumb', 'dfrn-id'];
430 $fields['parent-item'] = ['guid' => 'parent-guid', 'network' => 'parent-network'];
432 $fields['parent-item-author'] = ['url' => 'parent-author-link', 'name' => 'parent-author-name'];
434 $fields['event'] = ['created' => 'event-created', 'edited' => 'event-edited',
435 'start' => 'event-start','finish' => 'event-finish',
436 'summary' => 'event-summary','desc' => 'event-desc',
437 'location' => 'event-location', 'type' => 'event-type',
438 'nofinish' => 'event-nofinish','adjust' => 'event-adjust',
439 'ignore' => 'event-ignore', 'id' => 'event-id'];
441 $fields['sign'] = ['signed_text', 'signature', 'signer'];
447 * @brief Returns SQL condition for the "select" functions
449 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
451 * @return string SQL condition
453 private static function condition($thread_mode)
456 $master_table = "`thread`";
458 $master_table = "`item`";
460 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`) ";
464 * @brief Returns all needed "JOIN" commands for the "select" functions
466 * @param integer $uid User ID
467 * @param string $sql_commands The parts of the built SQL commands in the "select" functions
468 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
470 * @return string The SQL joins for the "select" functions
472 private static function constructJoins($uid, $sql_commands, $thread_mode, $user_mode)
475 $master_table = "`thread`";
476 $master_table_key = "`thread`.`iid`";
477 $joins = "STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid` ";
479 $master_table = "`item`";
480 $master_table_key = "`item`.`id`";
485 $joins .= sprintf("STRAIGHT_JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`
486 AND NOT `contact`.`blocked`
487 AND ((NOT `contact`.`readonly` AND NOT `contact`.`pending` AND (`contact`.`rel` IN (%s, %s)))
488 OR `contact`.`self` OR (`item`.`id` != `item`.`parent`) OR `contact`.`uid` = 0)
489 STRAIGHT_JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id` AND NOT `author`.`blocked`
490 STRAIGHT_JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id` AND NOT `owner`.`blocked`
491 LEFT JOIN `user-item` ON `user-item`.`iid` = $master_table_key AND `user-item`.`uid` = %d",
492 CONTACT_IS_SHARING, CONTACT_IS_FRIEND, intval($uid));
494 if (strpos($sql_commands, "`contact`.") !== false) {
495 $joins .= "STRAIGHT_JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`";
497 if (strpos($sql_commands, "`author`.") !== false) {
498 $joins .= " STRAIGHT_JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id`";
500 if (strpos($sql_commands, "`owner`.") !== false) {
501 $joins .= " STRAIGHT_JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id`";
505 if (strpos($sql_commands, "`group_member`.") !== false) {
506 $joins .= " STRAIGHT_JOIN `group_member` ON `group_member`.`contact-id` = $master_table.`contact-id`";
509 if (strpos($sql_commands, "`user`.") !== false) {
510 $joins .= " STRAIGHT_JOIN `user` ON `user`.`uid` = $master_table.`uid`";
513 if (strpos($sql_commands, "`event`.") !== false) {
514 $joins .= " LEFT JOIN `event` ON `event-id` = `event`.`id`";
517 if (strpos($sql_commands, "`sign`.") !== false) {
518 $joins .= " LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`";
521 if (strpos($sql_commands, "`item-content`.") !== false) {
522 $joins .= " LEFT JOIN `item-content` ON `item-content`.`id` = `item`.`icid`";
525 if ((strpos($sql_commands, "`parent-item`.") !== false) || (strpos($sql_commands, "`parent-author`.") !== false)) {
526 $joins .= " STRAIGHT_JOIN `item` AS `parent-item` ON `parent-item`.`id` = `item`.`parent`";
529 if (strpos($sql_commands, "`parent-item-author`.") !== false) {
530 $joins .= " STRAIGHT_JOIN `contact` AS `parent-item-author` ON `parent-item-author`.`id` = `parent-item`.`author-id`";
537 * @brief Add the field list for the "select" functions
539 * @param array $fields The field definition array
540 * @param array $selected The array with the selected fields from the "select" functions
542 * @return string The field list
544 private static function constructSelectFields($fields, $selected)
546 // To be able to fetch the tags we need the item id
547 if (in_array('tag', $selected) && !in_array('id', $selected)) {
551 // To be able to fetch the files we need the item id
552 if (in_array('file', $selected) && !in_array('id', $selected)) {
557 foreach ($fields as $table => $table_fields) {
558 foreach ($table_fields as $field => $select) {
559 if (empty($selected) || in_array($select, $selected)) {
560 if (in_array($select, self::MIXED_CONTENT_FIELDLIST)) {
561 $selection[] = "`item`.`".$select."` AS `item-" . $select . "`";
563 if (is_int($field)) {
564 $selection[] = "`" . $table . "`.`" . $select . "`";
566 $selection[] = "`" . $table . "`.`" . $field . "` AS `" . $select . "`";
571 return implode(", ", $selection);
575 * @brief add table definition to fields in an SQL query
577 * @param string $query SQL query
578 * @param array $fields The field definition array
580 * @return string the changed SQL query
582 private static function addTablesToFields($query, $fields)
584 foreach ($fields as $table => $table_fields) {
585 foreach ($table_fields as $alias => $field) {
586 if (is_int($alias)) {
587 $replace_field = $field;
589 $replace_field = $alias;
592 $search = "/([^\.])`" . $field . "`/i";
593 $replace = "$1`" . $table . "`.`" . $replace_field . "`";
594 $query = preg_replace($search, $replace, $query);
601 * @brief Update existing item entries
603 * @param array $fields The fields that are to be changed
604 * @param array $condition The condition for finding the item entries
606 * In the future we may have to change permissions as well.
607 * Then we had to add the user id as third parameter.
609 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
611 * @return integer|boolean number of affected rows - or "false" if there was an error
613 public static function update(array $fields, array $condition)
615 if (empty($condition) || empty($fields)) {
619 // To ensure the data integrity we do it in an transaction
622 // We cannot simply expand the condition to check for origin entries
623 // The condition needn't to be a simple array but could be a complex condition.
624 // And we have to execute this query before the update to ensure to fetch the same data.
625 $items = dba::select('item', ['id', 'origin', 'uri', 'plink', 'icid'], $condition);
627 $content_fields = [];
628 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
629 if (isset($fields[$field])) {
630 $content_fields[$field] = $fields[$field];
631 unset($fields[$field]);
635 if (array_key_exists('tag', $fields)) {
636 $tags = $fields['tag'];
637 unset($fields['tag']);
642 if (array_key_exists('file', $fields)) {
643 $files = $fields['file'];
644 unset($fields['file']);
649 if (!empty($fields)) {
650 $success = dba::update('item', $fields, $condition);
659 // When there is no content for the "old" item table, this will count the fetched items
660 $rows = dba::affected_rows();
662 while ($item = dba::fetch($items)) {
663 if (!empty($item['plink'])) {
664 $content_fields['plink'] = $item['plink'];
666 self::updateContent($content_fields, ['uri' => $item['uri']]);
668 if (empty($item['icid'])) {
669 $item_content = dba::selectFirst('item-content', [], ['uri' => $item['uri']]);
670 if (DBM::is_result($item_content)) {
671 $item_fields = ['icid' => $item_content['id']];
672 // Clear all fields in the item table that have a content in the item-content table
673 foreach ($item_content as $field => $content) {
674 if (in_array($field, self::MIXED_CONTENT_FIELDLIST) && !empty($item_content[$field])) {
675 $item_fields[$field] = '';
678 dba::update('item', $item_fields, ['id' => $item['id']]);
683 Term::insertFromTagFieldByItemId($item['id'], $tags);
686 if (!empty($files)) {
687 Term::insertFromFileFieldByItemId($item['id'], $files);
690 self::updateThread($item['id']);
692 // We only need to notfiy others when it is an original entry from us.
693 // Only call the notifier when the item has some content relevant change.
694 if ($item['origin'] && in_array('edited', array_keys($fields))) {
695 Worker::add(PRIORITY_HIGH, "Notifier", 'edit_post', $item['id']);
705 * @brief Delete an item and notify others about it - if it was ours
707 * @param array $condition The condition for finding the item entries
708 * @param integer $priority Priority for the notification
710 public static function delete($condition, $priority = PRIORITY_HIGH)
712 $items = dba::select('item', ['id'], $condition);
713 while ($item = dba::fetch($items)) {
714 self::deleteById($item['id'], $priority);
720 * @brief Delete an item for an user and notify others about it - if it was ours
722 * @param array $condition The condition for finding the item entries
723 * @param integer $uid User who wants to delete this item
725 public static function deleteForUser($condition, $uid)
731 $items = dba::select('item', ['id', 'uid'], $condition);
732 while ($item = dba::fetch($items)) {
733 // "Deleting" global items just means hiding them
734 if ($item['uid'] == 0) {
735 dba::update('user-item', ['hidden' => true], ['iid' => $item['id'], 'uid' => $uid], true);
736 } elseif ($item['uid'] == $uid) {
737 self::deleteById($item['id'], PRIORITY_HIGH);
739 logger('Wrong ownership. Not deleting item ' . $item['id']);
746 * @brief Delete an item and notify others about it - if it was ours
748 * @param integer $item_id Item ID that should be delete
749 * @param integer $priority Priority for the notification
751 * @return boolean success
753 private static function deleteById($item_id, $priority = PRIORITY_HIGH)
755 // locate item to be deleted
756 $fields = ['id', 'uri', 'uid', 'parent', 'parent-uri', 'origin',
757 'deleted', 'file', 'resource-id', 'event-id', 'attach',
758 'verb', 'object-type', 'object', 'target', 'contact-id'];
759 $item = self::selectFirst($fields, ['id' => $item_id]);
760 if (!DBM::is_result($item)) {
761 logger('Item with ID ' . $item_id . " hasn't been found.", LOGGER_DEBUG);
765 if ($item['deleted']) {
766 logger('Item with ID ' . $item_id . ' has already been deleted.', LOGGER_DEBUG);
770 $parent = self::selectFirst(['origin'], ['id' => $item['parent']]);
771 if (!DBM::is_result($parent)) {
772 $parent = ['origin' => false];
775 // clean up categories and tags so they don't end up as orphans
778 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
780 foreach ($matches as $mtch) {
781 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],true);
787 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
789 foreach ($matches as $mtch) {
790 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],false);
795 * If item is a link to a photo resource, nuke all the associated photos
796 * (visitors will not have photo resources)
797 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
798 * generate a resource-id and therefore aren't intimately linked to the item.
800 if (strlen($item['resource-id'])) {
801 dba::delete('photo', ['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
804 // If item is a link to an event, delete the event.
805 if (intval($item['event-id'])) {
806 Event::delete($item['event-id']);
809 // If item has attachments, drop them
810 foreach (explode(", ", $item['attach']) as $attach) {
811 preg_match("|attach/(\d+)|", $attach, $matches);
812 if (is_array($matches) && count($matches) > 1) {
813 dba::delete('attach', ['id' => $matches[1], 'uid' => $item['uid']]);
817 // Delete tags that had been attached to other items
818 self::deleteTagsFromItem($item);
820 // Set the item to "deleted"
821 // This erasing of item content is superfluous for items with a matching item-content.
822 // But for the next time we will still have old content in the item table.
823 $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow(),
824 'body' => '', 'title' => '', 'content-warning' => '', 'rendered-hash' => '', 'rendered-html' => '',
825 'object' => '', 'target' => '', 'tag' => '', 'postopts' => '', 'attach' => '', 'file' => ''];
826 dba::update('item', $item_fields, ['id' => $item['id']]);
828 Term::insertFromTagFieldByItemId($item['id'], '');
829 Term::insertFromFileFieldByItemId($item['id'], '');
830 self::deleteThread($item['id'], $item['parent-uri']);
832 if (!self::exists(["`uri` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri']])) {
833 self::delete(['uri' => $item['uri'], 'uid' => 0, 'deleted' => false], $priority);
836 // If it's the parent of a comment thread, kill all the kids
837 if ($item['id'] == $item['parent']) {
838 self::delete(['parent' => $item['parent'], 'deleted' => false], $priority);
841 // Is it our comment and/or our thread?
842 if ($item['origin'] || $parent['origin']) {
844 // When we delete the original post we will delete all existing copies on the server as well
845 self::delete(['uri' => $item['uri'], 'deleted' => false], $priority);
847 // send the notification upstream/downstream
848 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", "drop", intval($item['id']));
849 } elseif ($item['uid'] != 0) {
851 // When we delete just our local user copy of an item, we have to set a marker to hide it
852 $global_item = self::selectFirst(['id'], ['uri' => $item['uri'], 'uid' => 0, 'deleted' => false]);
853 if (DBM::is_result($global_item)) {
854 dba::update('user-item', ['hidden' => true], ['iid' => $global_item['id'], 'uid' => $item['uid']], true);
858 logger('Item with ID ' . $item_id . " has been deleted.", LOGGER_DEBUG);
863 private static function deleteTagsFromItem($item)
865 if (($item["verb"] != ACTIVITY_TAG) || ($item["object-type"] != ACTIVITY_OBJ_TAGTERM)) {
869 $xo = XML::parseString($item["object"], false);
870 $xt = XML::parseString($item["target"], false);
872 if ($xt->type != ACTIVITY_OBJ_NOTE) {
876 $i = self::selectFirst(['id', 'contact-id', 'tag'], ['uri' => $xt->id, 'uid' => $item['uid']]);
877 if (!DBM::is_result($i)) {
881 // For tags, the owner cannot remove the tag on the author's copy of the post.
882 $owner_remove = ($item["contact-id"] == $i["contact-id"]);
883 $author_copy = $item["origin"];
885 if (($owner_remove && $author_copy) || !$owner_remove) {
889 $tags = explode(',', $i["tag"]);
892 foreach ($tags as $tag) {
893 if (trim($tag) !== trim($xo->body)) {
894 $newtags[] = trim($tag);
898 self::update(['tag' => implode(',', $newtags)], ['id' => $i["id"]]);
901 private static function guid($item, $notify)
903 $guid = notags(trim($item['guid']));
910 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
911 // We add the hash of our own host because our host is the original creator of the post.
912 $prefix_host = get_app()->get_hostname();
916 // We are only storing the post so we create a GUID from the original hostname.
917 if (!empty($item['author-link'])) {
918 $parsed = parse_url($item['author-link']);
919 if (!empty($parsed['host'])) {
920 $prefix_host = $parsed['host'];
924 if (empty($prefix_host) && !empty($item['plink'])) {
925 $parsed = parse_url($item['plink']);
926 if (!empty($parsed['host'])) {
927 $prefix_host = $parsed['host'];
931 if (empty($prefix_host) && !empty($item['uri'])) {
932 $parsed = parse_url($item['uri']);
933 if (!empty($parsed['host'])) {
934 $prefix_host = $parsed['host'];
938 // Is it in the format data@host.tld? - Used for mail contacts
939 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
940 $mailparts = explode('@', $item['author-link']);
941 $prefix_host = array_pop($mailparts);
945 if (!empty($item['plink'])) {
946 $guid = self::guidFromUri($item['plink'], $prefix_host);
947 } elseif (!empty($item['uri'])) {
948 $guid = self::guidFromUri($item['uri'], $prefix_host);
950 $guid = get_guid(32, hash('crc32', $prefix_host));
956 private static function contactId($item)
958 $contact_id = (int)$item["contact-id"];
960 if (!empty($contact_id)) {
963 logger('Missing contact-id. Called by: '.System::callstack(), LOGGER_DEBUG);
965 * First we are looking for a suitable contact that matches with the author of the post
966 * This is done only for comments
968 if ($item['parent-uri'] != $item['uri']) {
969 $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
972 // If not present then maybe the owner was found
973 if ($contact_id == 0) {
974 $contact_id = Contact::getIdForURL($item['owner-link'], $item['uid']);
977 // Still missing? Then use the "self" contact of the current user
978 if ($contact_id == 0) {
979 $self = dba::selectFirst('contact', ['id'], ['self' => true, 'uid' => $item['uid']]);
980 if (DBM::is_result($self)) {
981 $contact_id = $self["id"];
984 logger("Contact-id was missing for post ".$item['guid']." from user id ".$item['uid']." - now set to ".$contact_id, LOGGER_DEBUG);
989 public static function insert($item, $force_parent = false, $notify = false, $dontcache = false)
993 // If it is a posting where users should get notifications, then define it as wall posting
996 $item['type'] = 'wall';
998 $item['network'] = NETWORK_DFRN;
999 $item['protocol'] = PROTOCOL_DFRN;
1001 if (is_int($notify)) {
1002 $priority = $notify;
1004 $priority = PRIORITY_HIGH;
1007 $item['network'] = trim(defaults($item, 'network', NETWORK_PHANTOM));
1010 $item['guid'] = self::guid($item, $notify);
1011 $item['uri'] = notags(trim(defaults($item, 'uri', self::newURI($item['uid'], $item['guid']))));
1013 // Store conversation data
1014 $item = Conversation::insert($item);
1017 * If a Diaspora signature structure was passed in, pull it out of the
1018 * item array and set it aside for later storage.
1022 if (x($item, 'dsprsig')) {
1023 $encoded_signature = $item['dsprsig'];
1024 $dsprsig = json_decode(base64_decode($item['dsprsig']));
1025 unset($item['dsprsig']);
1028 if (!empty($item['diaspora_signed_text'])) {
1029 $diaspora_signed_text = $item['diaspora_signed_text'];
1030 unset($item['diaspora_signed_text']);
1032 $diaspora_signed_text = '';
1035 // Converting the plink
1036 /// @TODO Check if this is really still needed
1037 if ($item['network'] == NETWORK_OSTATUS) {
1038 if (isset($item['plink'])) {
1039 $item['plink'] = OStatus::convertHref($item['plink']);
1040 } elseif (isset($item['uri'])) {
1041 $item['plink'] = OStatus::convertHref($item['uri']);
1045 if (!empty($item['thr-parent'])) {
1046 $item['parent-uri'] = $item['thr-parent'];
1049 $item['type'] = defaults($item, 'type', 'remote');
1051 if (isset($item['gravity'])) {
1052 $item['gravity'] = intval($item['gravity']);
1053 } elseif ($item['parent-uri'] === $item['uri']) {
1054 $item['gravity'] = GRAVITY_PARENT;
1055 } elseif (activity_match($item['verb'], ACTIVITY_POST)) {
1056 $item['gravity'] = GRAVITY_COMMENT;
1057 } elseif ($item['type'] == 'activity') {
1058 $item['gravity'] = GRAVITY_ACTIVITY;
1060 $item['gravity'] = GRAVITY_UNKNOWN; // Should not happen
1061 logger('Unknown gravity for verb: ' . $item['verb'] . ' - type: ' . $item['type'], LOGGER_DEBUG);
1064 $uid = intval($item['uid']);
1066 // check for create date and expire time
1067 $expire_interval = Config::get('system', 'dbclean-expire-days', 0);
1069 $user = dba::selectFirst('user', ['expire'], ['uid' => $uid]);
1070 if (DBM::is_result($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
1071 $expire_interval = $user['expire'];
1074 if (($expire_interval > 0) && !empty($item['created'])) {
1075 $expire_date = time() - ($expire_interval * 86400);
1076 $created_date = strtotime($item['created']);
1077 if ($created_date < $expire_date) {
1078 logger('item-store: item created ('.date('c', $created_date).') before expiration time ('.date('c', $expire_date).'). ignored. ' . print_r($item,true), LOGGER_DEBUG);
1084 * Do we already have this item?
1085 * We have to check several networks since Friendica posts could be repeated
1086 * via OStatus (maybe Diasporsa as well)
1088 if (in_array($item['network'], [NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS, ""])) {
1089 $condition = ["`uri` = ? AND `uid` = ? AND `network` IN (?, ?, ?)",
1090 trim($item['uri']), $item['uid'],
1091 NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS];
1092 $existing = self::selectFirst(['id', 'network'], $condition);
1093 if (DBM::is_result($existing)) {
1094 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
1096 logger("Item with uri ".$item['uri']." already existed for user ".$uid." with id ".$existing["id"]." target network ".$existing["network"]." - new network: ".$item['network']);
1099 return $existing["id"];
1103 self::addLanguageToItemArray($item);
1105 $item['wall'] = intval(defaults($item, 'wall', 0));
1106 $item['extid'] = trim(defaults($item, 'extid', ''));
1107 $item['author-name'] = trim(defaults($item, 'author-name', ''));
1108 $item['author-link'] = trim(defaults($item, 'author-link', ''));
1109 $item['author-avatar'] = trim(defaults($item, 'author-avatar', ''));
1110 $item['owner-name'] = trim(defaults($item, 'owner-name', ''));
1111 $item['owner-link'] = trim(defaults($item, 'owner-link', ''));
1112 $item['owner-avatar'] = trim(defaults($item, 'owner-avatar', ''));
1113 $item['received'] = ((x($item, 'received') !== false) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
1114 $item['created'] = ((x($item, 'created') !== false) ? DateTimeFormat::utc($item['created']) : $item['received']);
1115 $item['edited'] = ((x($item, 'edited') !== false) ? DateTimeFormat::utc($item['edited']) : $item['created']);
1116 $item['changed'] = ((x($item, 'changed') !== false) ? DateTimeFormat::utc($item['changed']) : $item['created']);
1117 $item['commented'] = ((x($item, 'commented') !== false) ? DateTimeFormat::utc($item['commented']) : $item['created']);
1118 $item['title'] = trim(defaults($item, 'title', ''));
1119 $item['location'] = trim(defaults($item, 'location', ''));
1120 $item['coord'] = trim(defaults($item, 'coord', ''));
1121 $item['visible'] = ((x($item, 'visible') !== false) ? intval($item['visible']) : 1);
1122 $item['deleted'] = 0;
1123 $item['parent-uri'] = trim(defaults($item, 'parent-uri', $item['uri']));
1124 $item['verb'] = trim(defaults($item, 'verb', ''));
1125 $item['object-type'] = trim(defaults($item, 'object-type', ''));
1126 $item['object'] = trim(defaults($item, 'object', ''));
1127 $item['target-type'] = trim(defaults($item, 'target-type', ''));
1128 $item['target'] = trim(defaults($item, 'target', ''));
1129 $item['plink'] = trim(defaults($item, 'plink', ''));
1130 $item['allow_cid'] = trim(defaults($item, 'allow_cid', ''));
1131 $item['allow_gid'] = trim(defaults($item, 'allow_gid', ''));
1132 $item['deny_cid'] = trim(defaults($item, 'deny_cid', ''));
1133 $item['deny_gid'] = trim(defaults($item, 'deny_gid', ''));
1134 $item['private'] = intval(defaults($item, 'private', 0));
1135 $item['bookmark'] = intval(defaults($item, 'bookmark', 0));
1136 $item['body'] = trim(defaults($item, 'body', ''));
1137 $item['tag'] = trim(defaults($item, 'tag', ''));
1138 $item['attach'] = trim(defaults($item, 'attach', ''));
1139 $item['app'] = trim(defaults($item, 'app', ''));
1140 $item['origin'] = intval(defaults($item, 'origin', 0));
1141 $item['postopts'] = trim(defaults($item, 'postopts', ''));
1142 $item['resource-id'] = trim(defaults($item, 'resource-id', ''));
1143 $item['event-id'] = intval(defaults($item, 'event-id', 0));
1144 $item['inform'] = trim(defaults($item, 'inform', ''));
1145 $item['file'] = trim(defaults($item, 'file', ''));
1147 // When there is no content then we don't post it
1148 if ($item['body'].$item['title'] == '') {
1149 logger('No body, no title.');
1153 // Items cannot be stored before they happen ...
1154 if ($item['created'] > DateTimeFormat::utcNow()) {
1155 $item['created'] = DateTimeFormat::utcNow();
1158 // We haven't invented time travel by now.
1159 if ($item['edited'] > DateTimeFormat::utcNow()) {
1160 $item['edited'] = DateTimeFormat::utcNow();
1163 if (($item['author-link'] == "") && ($item['owner-link'] == "")) {
1164 logger("Both author-link and owner-link are empty. Called by: " . System::callstack(), LOGGER_DEBUG);
1167 $item['plink'] = defaults($item, 'plink', System::baseUrl() . '/display/' . urlencode($item['guid']));
1169 // The contact-id should be set before "self::insert" was called - but there seems to be issues sometimes
1170 $item["contact-id"] = self::contactId($item);
1172 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
1173 'photo' => $item['author-avatar'], 'network' => $item['network']];
1175 $item['author-id'] = defaults($item, 'author-id', Contact::getIdForURL($item["author-link"], 0, false, $default));
1177 if (Contact::isBlocked($item["author-id"])) {
1178 logger('Contact '.$item["author-id"].' is blocked, item '.$item["uri"].' will not be stored');
1182 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
1183 'photo' => $item['owner-avatar'], 'network' => $item['network']];
1185 $item['owner-id'] = defaults($item, 'owner-id', Contact::getIdForURL($item["owner-link"], 0, false, $default));
1187 if (Contact::isBlocked($item["owner-id"])) {
1188 logger('Contact '.$item["owner-id"].' is blocked, item '.$item["uri"].' will not be stored');
1192 // These fields aren't stored anymore in the item table, they are fetched upon request
1193 unset($item['author-link']);
1194 unset($item['author-name']);
1195 unset($item['author-avatar']);
1197 unset($item['owner-link']);
1198 unset($item['owner-name']);
1199 unset($item['owner-avatar']);
1201 if ($item['network'] == NETWORK_PHANTOM) {
1202 logger('Missing network. Called by: '.System::callstack(), LOGGER_DEBUG);
1204 $contact = Contact::getDetailsByURL($item['author-link'], $item['uid']);
1205 if (!empty($contact['network'])) {
1206 $item['network'] = $contact["network"];
1208 $item['network'] = NETWORK_DFRN;
1210 logger("Set network to " . $item["network"] . " for " . $item["uri"], LOGGER_DEBUG);
1213 // Checking if there is already an item with the same guid
1214 logger('Checking for an item for user '.$item['uid'].' on network '.$item['network'].' with the guid '.$item['guid'], LOGGER_DEBUG);
1215 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
1216 if (self::exists($condition)) {
1217 logger('found item with guid '.$item['guid'].' for user '.$item['uid'].' on network '.$item['network'], LOGGER_DEBUG);
1221 // Check for hashtags in the body and repair or add hashtag links
1222 self::setHashtags($item);
1224 $item['thr-parent'] = $item['parent-uri'];
1232 if ($item['parent-uri'] === $item['uri']) {
1234 $parent_deleted = 0;
1235 $allow_cid = $item['allow_cid'];
1236 $allow_gid = $item['allow_gid'];
1237 $deny_cid = $item['deny_cid'];
1238 $deny_gid = $item['deny_gid'];
1239 $notify_type = 'wall-new';
1241 // find the parent and snarf the item id and ACLs
1242 // and anything else we need to inherit
1244 $fields = ['uri', 'parent-uri', 'id', 'deleted',
1245 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
1246 'wall', 'private', 'forum_mode', 'origin'];
1247 $condition = ['uri' => $item['parent-uri'], 'uid' => $item['uid']];
1248 $params = ['order' => ['id' => false]];
1249 $parent = self::selectFirst($fields, $condition, $params);
1251 if (DBM::is_result($parent)) {
1252 // is the new message multi-level threaded?
1253 // even though we don't support it now, preserve the info
1254 // and re-attach to the conversation parent.
1256 if ($parent['uri'] != $parent['parent-uri']) {
1257 $item['parent-uri'] = $parent['parent-uri'];
1259 $condition = ['uri' => $item['parent-uri'],
1260 'parent-uri' => $item['parent-uri'],
1261 'uid' => $item['uid']];
1262 $params = ['order' => ['id' => false]];
1263 $toplevel_parent = self::selectFirst($fields, $condition, $params);
1265 if (DBM::is_result($toplevel_parent)) {
1266 $parent = $toplevel_parent;
1270 $parent_id = $parent['id'];
1271 $parent_deleted = $parent['deleted'];
1272 $allow_cid = $parent['allow_cid'];
1273 $allow_gid = $parent['allow_gid'];
1274 $deny_cid = $parent['deny_cid'];
1275 $deny_gid = $parent['deny_gid'];
1276 $item['wall'] = $parent['wall'];
1277 $notify_type = 'comment-new';
1280 * If the parent is private, force privacy for the entire conversation
1281 * This differs from the above settings as it subtly allows comments from
1282 * email correspondents to be private even if the overall thread is not.
1284 if ($parent['private']) {
1285 $item['private'] = $parent['private'];
1289 * Edge case. We host a public forum that was originally posted to privately.
1290 * The original author commented, but as this is a comment, the permissions
1291 * weren't fixed up so it will still show the comment as private unless we fix it here.
1293 if ((intval($parent['forum_mode']) == 1) && $parent['private']) {
1294 $item['private'] = 0;
1297 // If its a post from myself then tag the thread as "mention"
1298 logger("Checking if parent ".$parent_id." has to be tagged as mention for user ".$item['uid'], LOGGER_DEBUG);
1299 $user = dba::selectFirst('user', ['nickname'], ['uid' => $item['uid']]);
1300 if (DBM::is_result($user)) {
1301 $self = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
1302 $self_id = Contact::getIdForURL($self, 0, true);
1303 logger("'myself' is ".$self_id." for parent ".$parent_id." checking against ".$item['author-id']." and ".$item['owner-id'], LOGGER_DEBUG);
1304 if (($item['author-id'] == $self_id) || ($item['owner-id'] == $self_id)) {
1305 dba::update('thread', ['mention' => true], ['iid' => $parent_id]);
1306 logger("tagged thread ".$parent_id." as mention for user ".$self, LOGGER_DEBUG);
1311 * Allow one to see reply tweets from status.net even when
1312 * we don't have or can't see the original post.
1314 if ($force_parent) {
1315 logger('$force_parent=true, reply converted to top-level post.');
1317 $item['parent-uri'] = $item['uri'];
1318 $item['gravity'] = GRAVITY_PARENT;
1320 logger('item parent '.$item['parent-uri'].' for '.$item['uid'].' was not found - ignoring item');
1324 $parent_deleted = 0;
1328 $condition = ["`uri` = ? AND `network` IN (?, ?) AND `uid` = ?",
1329 $item['uri'], $item['network'], NETWORK_DFRN, $item['uid']];
1330 if (self::exists($condition)) {
1331 logger('duplicated item with the same uri found. '.print_r($item,true));
1335 // On Friendica and Diaspora the GUID is unique
1336 if (in_array($item['network'], [NETWORK_DFRN, NETWORK_DIASPORA])) {
1337 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
1338 if (self::exists($condition)) {
1339 logger('duplicated item with the same guid found. '.print_r($item,true));
1343 // Check for an existing post with the same content. There seems to be a problem with OStatus.
1344 $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
1345 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
1346 if (self::exists($condition)) {
1347 logger('duplicated item with the same body found. '.print_r($item,true));
1352 // Is this item available in the global items (with uid=0)?
1353 if ($item["uid"] == 0) {
1354 $item["global"] = true;
1356 // Set the global flag on all items if this was a global item entry
1357 dba::update('item', ['global' => true], ['uri' => $item["uri"]]);
1359 $item["global"] = self::exists(['uid' => 0, 'uri' => $item["uri"]]);
1363 if (strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid)) {
1366 $private = $item['private'];
1369 $item["allow_cid"] = $allow_cid;
1370 $item["allow_gid"] = $allow_gid;
1371 $item["deny_cid"] = $deny_cid;
1372 $item["deny_gid"] = $deny_gid;
1373 $item["private"] = $private;
1374 $item["deleted"] = $parent_deleted;
1376 // Fill the cache field
1377 put_item_in_cache($item);
1380 Addon::callHooks('post_local', $item);
1382 Addon::callHooks('post_remote', $item);
1385 // This array field is used to trigger some automatic reactions
1386 // It is mainly used in the "post_local" hook.
1387 unset($item['api_source']);
1389 if (x($item, 'cancel')) {
1390 logger('post cancelled by addon.');
1395 * Check for already added items.
1396 * There is a timing issue here that sometimes creates double postings.
1397 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
1399 if ($item["uid"] == 0) {
1400 if (self::exists(['uri' => trim($item['uri']), 'uid' => 0])) {
1401 logger('Global item already stored. URI: '.$item['uri'].' on network '.$item['network'], LOGGER_DEBUG);
1406 logger('' . print_r($item,true), LOGGER_DATA);
1408 if (array_key_exists('tag', $item)) {
1409 $tags = $item['tag'];
1410 unset($item['tag']);
1415 if (array_key_exists('file', $item)) {
1416 $files = $item['file'];
1417 unset($item['file']);
1422 // We are doing this outside of the transaction to avoid timing problems
1423 self::insertContent($item);
1426 $ret = dba::insert('item', $item);
1428 // When the item was successfully stored we fetch the ID of the item.
1429 if (DBM::is_result($ret)) {
1430 $current_post = dba::lastInsertId();
1432 // This can happen - for example - if there are locking timeouts.
1435 // Store the data into a spool file so that we can try again later.
1437 // At first we restore the Diaspora signature that we removed above.
1438 if (isset($encoded_signature)) {
1439 $item['dsprsig'] = $encoded_signature;
1442 // Now we store the data in the spool directory
1443 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
1444 $file = 'item-'.round(microtime(true) * 10000).'-'.mt_rand().'.msg';
1446 $spoolpath = get_spoolpath();
1447 if ($spoolpath != "") {
1448 $spool = $spoolpath.'/'.$file;
1449 file_put_contents($spool, json_encode($item));
1450 logger("Item wasn't stored - Item was spooled into file ".$file, LOGGER_DEBUG);
1455 if ($current_post == 0) {
1456 // This is one of these error messages that never should occur.
1457 logger("couldn't find created item - we better quit now.");
1462 // How much entries have we created?
1463 // We wouldn't need this query when we could use an unique index - but MySQL has length problems with them.
1464 $entries = dba::count('item', ['uri' => $item['uri'], 'uid' => $item['uid'], 'network' => $item['network']]);
1467 // There are duplicates. We delete our just created entry.
1468 logger('Duplicated post occurred. uri = ' . $item['uri'] . ' uid = ' . $item['uid']);
1470 // Yes, we could do a rollback here - but we are having many users with MyISAM.
1471 dba::delete('item', ['id' => $current_post]);
1474 } elseif ($entries == 0) {
1475 // This really should never happen since we quit earlier if there were problems.
1476 logger("Something is terribly wrong. We haven't found our created entry.");
1481 logger('created item '.$current_post);
1482 self::updateContact($item);
1484 if (!$parent_id || ($item['parent-uri'] === $item['uri'])) {
1485 $parent_id = $current_post;
1489 dba::update('item', ['parent' => $parent_id], ['id' => $current_post]);
1491 $item['id'] = $current_post;
1492 $item['parent'] = $parent_id;
1494 // update the commented timestamp on the parent
1495 // Only update "commented" if it is really a comment
1496 if (($item['gravity'] != GRAVITY_ACTIVITY) || !Config::get("system", "like_no_comment")) {
1497 dba::update('item', ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1499 dba::update('item', ['changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1504 * Friendica servers lower than 3.4.3-2 had double encoded the signature ...
1505 * We can check for this condition when we decode and encode the stuff again.
1507 if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) {
1508 $dsprsig->signature = base64_decode($dsprsig->signature);
1509 logger("Repaired double encoded signature from handle ".$dsprsig->signer, LOGGER_DEBUG);
1512 dba::insert('sign', ['iid' => $current_post, 'signed_text' => $dsprsig->signed_text,
1513 'signature' => $dsprsig->signature, 'signer' => $dsprsig->signer]);
1516 if (!empty($diaspora_signed_text)) {
1517 // Formerly we stored the signed text, the signature and the author in different fields.
1518 // We now store the raw data so that we are more flexible.
1519 dba::insert('sign', ['iid' => $current_post, 'signed_text' => $diaspora_signed_text]);
1522 $deleted = self::tagDeliver($item['uid'], $current_post);
1525 * current post can be deleted if is for a community page and no mention are
1528 if (!$deleted && !$dontcache) {
1529 $posted_item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $current_post]);
1530 if (DBM::is_result($posted_item)) {
1532 Addon::callHooks('post_local_end', $posted_item);
1534 Addon::callHooks('post_remote_end', $posted_item);
1537 logger('new item not found in DB, id ' . $current_post);
1541 if ($item['parent-uri'] === $item['uri']) {
1542 self::addThread($current_post);
1544 self::updateThread($parent_id);
1550 * Due to deadlock issues with the "term" table we are doing these steps after the commit.
1551 * This is not perfect - but a workable solution until we found the reason for the problem.
1553 if (!empty($tags)) {
1554 Term::insertFromTagFieldByItemId($current_post, $tags);
1557 if (!empty($files)) {
1558 Term::insertFromFileFieldByItemId($current_post, $files);
1561 if ($item['parent-uri'] === $item['uri']) {
1562 self::addShadow($current_post);
1564 self::addShadowPost($current_post);
1567 check_user_notification($current_post);
1570 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", $notify_type, $current_post);
1571 } elseif (!empty($parent) && $parent['origin']) {
1572 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "Notifier", "comment-import", $current_post);
1575 return $current_post;
1579 * @brief Insert a new item content entry
1581 * @param array $item The item fields that are to be inserted
1583 private static function insertContent(&$item)
1585 $fields = ['uri' => $item['uri'], 'plink' => $item['plink'],
1586 'uri-plink-hash' => hash('sha1', $item['plink']).hash('sha1', $item['uri'])];
1588 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1589 if (isset($item[$field])) {
1590 $fields[$field] = $item[$field];
1591 unset($item[$field]);
1595 // To avoid timing problems, we are using locks.
1596 $locked = Lock::acquire('item_insert_content');
1598 logger("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
1601 // Do we already have this content?
1602 $item_content = dba::selectFirst('item-content', ['id'], ['uri' => $item['uri']]);
1603 if (DBM::is_result($item_content)) {
1604 $item['icid'] = $item_content['id'];
1605 logger('Fetched content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
1606 } elseif (dba::insert('item-content', $fields)) {
1607 $item['icid'] = dba::lastInsertId();
1608 logger('Inserted content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
1610 // By setting the ICID value through the worker we should avoid timing problems.
1611 // When the locking works, this shouldn't be needed. But better be prepared.
1612 Worker::add(PRIORITY_HIGH, 'SetItemContentID', $item['uri']);
1613 logger('Could not insert content for URI ' . $item['uri'] . ' - trying asynchronously');
1616 Lock::release('item_insert_content');
1621 * @brief Set the item content id for a given URI
1623 * @param string $uri The item URI
1625 public static function setICIDforURI($uri)
1627 $item_content = dba::selectFirst('item-content', ['id'], ['uri' => $uri]);
1628 if (DBM::is_result($item_content)) {
1629 dba::update('item', ['icid' => $item_content['id']], ['icid' => 0, 'uri' => $uri]);
1630 logger('Asynchronously set item content id for URI ' . $uri . ' (' . $item_content['id'] . ') - Affected: '. (int)dba::affected_rows());
1632 logger('No item-content found for URI ' . $uri);
1637 * @brief Update existing item content entries
1639 * @param array $item The item fields that are to be changed
1640 * @param array $condition The condition for finding the item content entries
1642 private static function updateContent($item, $condition)
1644 // We have to select only the fields from the "item-content" table
1646 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1647 if (isset($item[$field])) {
1648 $fields[$field] = $item[$field];
1652 if (empty($fields)) {
1656 if (!empty($item['plink'])) {
1657 $fields['uri-plink-hash'] = hash('sha1', $item['plink']) . hash('sha1', $condition['uri']);
1659 // Ensure that we don't delete the plink
1660 unset($fields['plink']);
1663 logger('Update content for URI ' . $condition['uri']);
1665 dba::update('item-content', $fields, $condition, true);
1669 * @brief Distributes public items to the receivers
1671 * @param integer $itemid Item ID that should be added
1672 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
1674 public static function distribute($itemid, $signed_text = '')
1676 $condition = ["`id` IN (SELECT `parent` FROM `item` WHERE `id` = ?)", $itemid];
1677 $parent = self::selectFirst(['owner-id'], $condition);
1678 if (!DBM::is_result($parent)) {
1682 // Only distribute public items from native networks
1683 $condition = ['id' => $itemid, 'uid' => 0,
1684 'network' => [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""],
1685 'visible' => true, 'deleted' => false, 'moderated' => false, 'private' => false];
1686 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
1687 if (!DBM::is_result($item)) {
1692 unset($item['parent']);
1693 unset($item['mention']);
1694 unset($item['wall']);
1695 unset($item['origin']);
1696 unset($item['starred']);
1700 $condition = ["`nurl` IN (SELECT `nurl` FROM `contact` WHERE `id` = ?) AND `uid` != 0 AND NOT `blocked` AND `rel` IN (?, ?)",
1701 $parent['owner-id'], CONTACT_IS_SHARING, CONTACT_IS_FRIEND];
1702 $contacts = dba::select('contact', ['uid'], $condition);
1703 while ($contact = dba::fetch($contacts)) {
1704 $users[$contact['uid']] = $contact['uid'];
1709 if ($item['uri'] != $item['parent-uri']) {
1710 $parents = self::select(['uid', 'origin'], ["`uri` = ? AND `uid` != 0", $item['parent-uri']]);
1711 while ($parent = dba::fetch($parents)) {
1712 $users[$parent['uid']] = $parent['uid'];
1713 if ($parent['origin'] && !$item['origin']) {
1714 $origin_uid = $parent['uid'];
1719 foreach ($users as $uid) {
1720 if ($origin_uid == $uid) {
1721 $item['diaspora_signed_text'] = $signed_text;
1723 self::storeForUser($itemid, $item, $uid);
1728 * @brief Store public items for the receivers
1730 * @param integer $itemid Item ID that should be added
1731 * @param array $item The item entry that will be stored
1732 * @param integer $uid The user that will receive the item entry
1734 private static function storeForUser($itemid, $item, $uid)
1736 $item['uid'] = $uid;
1737 $item['origin'] = 0;
1739 if ($item['uri'] == $item['parent-uri']) {
1740 $item['contact-id'] = Contact::getIdForURL($item['owner-link'], $uid);
1742 $item['contact-id'] = Contact::getIdForURL($item['author-link'], $uid);
1745 if (empty($item['contact-id'])) {
1746 $self = dba::selectFirst('contact', ['id'], ['self' => true, 'uid' => $uid]);
1747 if (!DBM::is_result($self)) {
1750 $item['contact-id'] = $self['id'];
1753 if (in_array($item['type'], ["net-comment", "wall-comment"])) {
1754 $item['type'] = 'remote-comment';
1755 } elseif ($item['type'] == 'wall') {
1756 $item['type'] = 'remote';
1759 /// @todo Handling of "event-id"
1762 if ($item['uri'] == $item['parent-uri']) {
1763 $contact = dba::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
1764 if (DBM::is_result($contact)) {
1765 $notify = self::isRemoteSelf($contact, $item);
1769 $distributed = self::insert($item, false, $notify, true);
1771 if (!$distributed) {
1772 logger("Distributed public item " . $itemid . " for user " . $uid . " wasn't stored", LOGGER_DEBUG);
1774 logger("Distributed public item " . $itemid . " for user " . $uid . " with id " . $distributed, LOGGER_DEBUG);
1779 * @brief Add a shadow entry for a given item id that is a thread starter
1781 * We store every public item entry additionally with the user id "0".
1782 * This is used for the community page and for the search.
1783 * It is planned that in the future we will store public item entries only once.
1785 * @param integer $itemid Item ID that should be added
1787 public static function addShadow($itemid)
1789 $fields = ['uid', 'private', 'moderated', 'visible', 'deleted', 'network', 'uri'];
1790 $condition = ['id' => $itemid, 'parent' => [0, $itemid]];
1791 $item = self::selectFirst($fields, $condition);
1793 if (!DBM::is_result($item)) {
1797 // is it already a copy?
1798 if (($itemid == 0) || ($item['uid'] == 0)) {
1802 // Is it a visible public post?
1803 if (!$item["visible"] || $item["deleted"] || $item["moderated"] || $item["private"]) {
1807 // is it an entry from a connector? Only add an entry for natively connected networks
1808 if (!in_array($item["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""])) {
1812 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
1816 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
1818 if (DBM::is_result($item)) {
1819 // Preparing public shadow (removing user specific data)
1822 unset($item['parent']);
1823 unset($item['wall']);
1824 unset($item['mention']);
1825 unset($item['origin']);
1826 unset($item['starred']);
1827 if ($item['uri'] == $item['parent-uri']) {
1828 $item['contact-id'] = $item['owner-id'];
1830 $item['contact-id'] = $item['author-id'];
1833 if (in_array($item['type'], ["net-comment", "wall-comment"])) {
1834 $item['type'] = 'remote-comment';
1835 } elseif ($item['type'] == 'wall') {
1836 $item['type'] = 'remote';
1839 $public_shadow = self::insert($item, false, false, true);
1841 logger("Stored public shadow for thread ".$itemid." under id ".$public_shadow, LOGGER_DEBUG);
1846 * @brief Add a shadow entry for a given item id that is a comment
1848 * This function does the same like the function above - but for comments
1850 * @param integer $itemid Item ID that should be added
1852 public static function addShadowPost($itemid)
1854 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
1855 if (!DBM::is_result($item)) {
1859 // Is it a toplevel post?
1860 if ($item['id'] == $item['parent']) {
1861 self::addShadow($itemid);
1865 // Is this a shadow entry?
1866 if ($item['uid'] == 0) {
1870 // Is there a shadow parent?
1871 if (!self::exists(['uri' => $item['parent-uri'], 'uid' => 0])) {
1875 // Is there already a shadow entry?
1876 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
1880 // Save "origin" and "parent" state
1881 $origin = $item['origin'];
1882 $parent = $item['parent'];
1884 // Preparing public shadow (removing user specific data)
1887 unset($item['parent']);
1888 unset($item['wall']);
1889 unset($item['mention']);
1890 unset($item['origin']);
1891 unset($item['starred']);
1892 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
1894 if (in_array($item['type'], ["net-comment", "wall-comment"])) {
1895 $item['type'] = 'remote-comment';
1896 } elseif ($item['type'] == 'wall') {
1897 $item['type'] = 'remote';
1900 $public_shadow = self::insert($item, false, false, true);
1902 logger("Stored public shadow for comment ".$item['uri']." under id ".$public_shadow, LOGGER_DEBUG);
1904 // If this was a comment to a Diaspora post we don't get our comment back.
1905 // This means that we have to distribute the comment by ourselves.
1906 if ($origin && self::exists(['id' => $parent, 'network' => NETWORK_DIASPORA])) {
1907 self::distribute($public_shadow);
1912 * Adds a language specification in a "language" element of given $arr.
1913 * Expects "body" element to exist in $arr.
1915 private static function addLanguageToItemArray(&$item)
1917 $naked_body = Text\BBCode::toPlaintext($item['body'], false);
1919 $ld = new Text_LanguageDetect();
1920 $ld->setNameMode(2);
1921 $languages = $ld->detect($naked_body, 3);
1923 if (is_array($languages)) {
1924 $item['language'] = json_encode($languages);
1929 * @brief Creates an unique guid out of a given uri
1931 * @param string $uri uri of an item entry
1932 * @param string $host hostname for the GUID prefix
1933 * @return string unique guid
1935 public static function guidFromUri($uri, $host)
1937 // Our regular guid routine is using this kind of prefix as well
1938 // We have to avoid that different routines could accidentally create the same value
1939 $parsed = parse_url($uri);
1941 // We use a hash of the hostname as prefix for the guid
1942 $guid_prefix = hash("crc32", $host);
1944 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
1945 unset($parsed["scheme"]);
1947 // Glue it together to be able to make a hash from it
1948 $host_id = implode("/", $parsed);
1950 // We could use any hash algorithm since it isn't a security issue
1951 $host_hash = hash("ripemd128", $host_id);
1953 return $guid_prefix.$host_hash;
1957 * generate an unique URI
1959 * @param integer $uid User id
1960 * @param string $guid An existing GUID (Otherwise it will be generated)
1964 public static function newURI($uid, $guid = "")
1967 $guid = get_guid(32);
1970 $hostname = self::getApp()->get_hostname();
1972 $user = dba::selectFirst('user', ['nickname'], ['uid' => $uid]);
1974 $uri = "urn:X-dfrn:" . $hostname . ':' . $user['nickname'] . ':' . $guid;
1980 * @brief Set "success_update" and "last-item" to the date of the last time we heard from this contact
1982 * This can be used to filter for inactive contacts.
1983 * Only do this for public postings to avoid privacy problems, since poco data is public.
1984 * Don't set this value if it isn't from the owner (could be an author that we don't know)
1986 * @param array $arr Contains the just posted item record
1988 private static function updateContact($arr)
1990 // Unarchive the author
1991 $contact = dba::selectFirst('contact', [], ['id' => $arr["author-id"]]);
1992 if (DBM::is_result($contact)) {
1993 Contact::unmarkForArchival($contact);
1996 // Unarchive the contact if it's not our own contact
1997 $contact = dba::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
1998 if (DBM::is_result($contact)) {
1999 Contact::unmarkForArchival($contact);
2002 $update = (!$arr['private'] && ((defaults($arr, 'author-link', '') === defaults($arr, 'owner-link', '')) || ($arr["parent-uri"] === $arr["uri"])));
2004 // Is it a forum? Then we don't care about the rules from above
2005 if (!$update && ($arr["network"] == NETWORK_DFRN) && ($arr["parent-uri"] === $arr["uri"])) {
2006 if (dba::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
2012 dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2013 ['id' => $arr['contact-id']]);
2015 // Now do the same for the system wide contacts with uid=0
2016 if (!$arr['private']) {
2017 dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2018 ['id' => $arr['owner-id']]);
2020 if ($arr['owner-id'] != $arr['author-id']) {
2021 dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2022 ['id' => $arr['author-id']]);
2027 public static function setHashtags(&$item)
2030 $tags = get_tags($item["body"]);
2033 if (!count($tags)) {
2037 // This sorting is important when there are hashtags that are part of other hashtags
2038 // Otherwise there could be problems with hashtags like #test and #test2
2041 $URLSearchString = "^\[\]";
2043 // All hashtags should point to the home server if "local_tags" is activated
2044 if (Config::get('system', 'local_tags')) {
2045 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2046 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["body"]);
2048 $item["tag"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2049 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["tag"]);
2052 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
2053 $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2055 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
2058 $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
2060 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
2063 $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
2065 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
2068 // Repair recursive urls
2069 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2070 "#$2", $item["body"]);
2072 foreach ($tags as $tag) {
2073 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=')) {
2077 $basetag = str_replace('_',' ',substr($tag,1));
2079 $newtag = '#[url=' . System::baseUrl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
2081 $item["body"] = str_replace($tag, $newtag, $item["body"]);
2083 if (!stristr($item["tag"], "/search?tag=" . $basetag . "]" . $basetag . "[/url]")) {
2084 if (strlen($item["tag"])) {
2085 $item["tag"] = ','.$item["tag"];
2087 $item["tag"] = $newtag.$item["tag"];
2091 // Convert back the masked hashtags
2092 $item["body"] = str_replace("#", "#", $item["body"]);
2095 public static function getGuidById($id)
2097 $item = self::selectFirst(['guid'], ['id' => $id]);
2098 if (DBM::is_result($item)) {
2099 return $item['guid'];
2105 public static function getIdAndNickByGuid($guid, $uid = 0)
2111 $uid == local_user();
2114 // Does the given user have this item?
2116 $item = dba::fetch_first("SELECT `item`.`id`, `user`.`nickname` FROM `item`
2117 INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
2118 WHERE `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
2119 AND `item`.`guid` = ? AND `item`.`uid` = ?", $guid, $uid);
2120 if (DBM::is_result($item)) {
2122 $nick = $item["nickname"];
2126 // Or is it anywhere on the server?
2128 $item = dba::fetch_first("SELECT `item`.`id`, `user`.`nickname` FROM `item`
2129 INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
2130 WHERE `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
2131 AND NOT `item`.`private` AND `item`.`wall`
2132 AND `item`.`guid` = ?", $guid);
2133 if (DBM::is_result($item)) {
2135 $nick = $item["nickname"];
2138 return ["nick" => $nick, "id" => $id];
2142 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
2144 * @param int $item_id
2145 * @return bool true if item was deleted, else false
2147 private static function tagDeliver($uid, $item_id)
2151 $user = dba::selectFirst('user', [], ['uid' => $uid]);
2152 if (!DBM::is_result($user)) {
2156 $community_page = (($user['page-flags'] == PAGE_COMMUNITY) ? true : false);
2157 $prvgroup = (($user['page-flags'] == PAGE_PRVGROUP) ? true : false);
2159 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2160 if (!DBM::is_result($item)) {
2164 $link = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
2167 * Diaspora uses their own hardwired link URL in @-tags
2168 * instead of the one we supply with webfinger
2170 $dlink = normalise_link(System::baseUrl() . '/u/' . $user['nickname']);
2172 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
2174 foreach ($matches as $mtch) {
2175 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
2177 logger('mention found: ' . $mtch[2]);
2183 if (($community_page || $prvgroup) &&
2184 !$item['wall'] && !$item['origin'] && ($item['id'] == $item['parent'])) {
2185 // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
2187 logger("no-mention top-level post to community or private group. delete.");
2188 dba::delete('item', ['id' => $item_id]);
2194 $arr = ['item' => $item, 'user' => $user];
2196 Addon::callHooks('tagged', $arr);
2198 if (!$community_page && !$prvgroup) {
2203 * tgroup delivery - setup a second delivery chain
2204 * prevent delivery looping - only proceed
2205 * if the message originated elsewhere and is a top-level post
2207 if ($item['wall'] || $item['origin'] || ($item['id'] != $item['parent'])) {
2211 // now change this copy of the post to a forum head message and deliver to all the tgroup members
2212 $self = dba::selectFirst('contact', ['id', 'name', 'url', 'thumb'], ['uid' => $uid, 'self' => true]);
2213 if (!DBM::is_result($self)) {
2217 $owner_id = Contact::getIdForURL($self['url']);
2219 // also reset all the privacy bits to the forum default permissions
2221 $private = ($user['allow_cid'] || $user['allow_gid'] || $user['deny_cid'] || $user['deny_gid']) ? 1 : 0;
2223 $forum_mode = ($prvgroup ? 2 : 1);
2225 $fields = ['wall' => true, 'origin' => true, 'forum_mode' => $forum_mode, 'contact-id' => $self['id'],
2226 'owner-id' => $owner_id, 'owner-link' => $self['url'], 'private' => $private, 'allow_cid' => $user['allow_cid'],
2227 'allow_gid' => $user['allow_gid'], 'deny_cid' => $user['deny_cid'], 'deny_gid' => $user['deny_gid']];
2228 dba::update('item', $fields, ['id' => $item_id]);
2230 self::updateThread($item_id);
2232 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', 'tgroup', $item_id);
2235 public static function isRemoteSelf($contact, &$datarray)
2239 if (!$contact['remote_self']) {
2243 // Prevent the forwarding of posts that are forwarded
2244 if ($datarray["extid"] == NETWORK_DFRN) {
2245 logger('Already forwarded', LOGGER_DEBUG);
2249 // Prevent to forward already forwarded posts
2250 if ($datarray["app"] == $a->get_hostname()) {
2251 logger('Already forwarded (second test)', LOGGER_DEBUG);
2255 // Only forward posts
2256 if ($datarray["verb"] != ACTIVITY_POST) {
2257 logger('No post', LOGGER_DEBUG);
2261 if (($contact['network'] != NETWORK_FEED) && $datarray['private']) {
2262 logger('Not public', LOGGER_DEBUG);
2266 $datarray2 = $datarray;
2267 logger('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), LOGGER_DEBUG);
2268 if ($contact['remote_self'] == 2) {
2269 $self = dba::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
2270 ['uid' => $contact['uid'], 'self' => true]);
2271 if (DBM::is_result($self)) {
2272 $datarray['contact-id'] = $self["id"];
2274 $datarray['owner-name'] = $self["name"];
2275 $datarray['owner-link'] = $self["url"];
2276 $datarray['owner-avatar'] = $self["thumb"];
2278 $datarray['author-name'] = $datarray['owner-name'];
2279 $datarray['author-link'] = $datarray['owner-link'];
2280 $datarray['author-avatar'] = $datarray['owner-avatar'];
2282 unset($datarray['created']);
2283 unset($datarray['edited']);
2285 unset($datarray['network']);
2286 unset($datarray['owner-id']);
2287 unset($datarray['author-id']);
2290 if ($contact['network'] != NETWORK_FEED) {
2291 $datarray["guid"] = get_guid(32);
2292 unset($datarray["plink"]);
2293 $datarray["uri"] = self::newURI($contact['uid'], $datarray["guid"]);
2294 $datarray["parent-uri"] = $datarray["uri"];
2295 $datarray["thr-parent"] = $datarray["uri"];
2296 $datarray["extid"] = NETWORK_DFRN;
2297 $urlpart = parse_url($datarray2['author-link']);
2298 $datarray["app"] = $urlpart["host"];
2300 $datarray['private'] = 0;
2304 if ($contact['network'] != NETWORK_FEED) {
2305 // Store the original post
2306 $result = self::insert($datarray2, false, false);
2307 logger('remote-self post original item - Contact '.$contact['url'].' return '.$result.' Item '.print_r($datarray2, true), LOGGER_DEBUG);
2309 $datarray["app"] = "Feed";
2313 // Trigger automatic reactions for addons
2314 $datarray['api_source'] = true;
2316 // We have to tell the hooks who we are - this really should be improved
2317 $_SESSION["authenticated"] = true;
2318 $_SESSION["uid"] = $contact['uid'];
2327 * @param array $item
2331 public static function fixPrivatePhotos($s, $uid, $item = null, $cid = 0)
2333 if (Config::get('system', 'disable_embedded')) {
2337 logger('check for photos', LOGGER_DEBUG);
2338 $site = substr(System::baseUrl(), strpos(System::baseUrl(), '://'));
2343 $img_start = strpos($orig_body, '[img');
2344 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2345 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2347 while (($img_st_close !== false) && ($img_len !== false)) {
2348 $img_st_close++; // make it point to AFTER the closing bracket
2349 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2351 logger('found photo ' . $image, LOGGER_DEBUG);
2353 if (stristr($image, $site . '/photo/')) {
2354 // Only embed locally hosted photos
2356 $i = basename($image);
2357 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2358 $x = strpos($i, '-');
2361 $res = substr($i, $x + 1);
2362 $i = substr($i, 0, $x);
2363 $fields = ['data', 'type', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'];
2364 $photo = dba::selectFirst('photo', $fields, ['resource-id' => $i, 'scale' => $res, 'uid' => $uid]);
2365 if (DBM::is_result($photo)) {
2367 * Check to see if we should replace this photo link with an embedded image
2368 * 1. No need to do so if the photo is public
2369 * 2. If there's a contact-id provided, see if they're in the access list
2370 * for the photo. If so, embed it.
2371 * 3. Otherwise, if we have an item, see if the item permissions match the photo
2372 * permissions, regardless of order but first check to see if they're an exact
2373 * match to save some processing overhead.
2375 if (self::hasPermissions($photo)) {
2377 $recips = self::enumeratePermissions($photo);
2378 if (in_array($cid, $recips)) {
2382 if (self::samePermissions($item, $photo)) {
2388 $data = $photo['data'];
2389 $type = $photo['type'];
2391 // If a custom width and height were specified, apply before embedding
2392 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2393 logger('scaling photo', LOGGER_DEBUG);
2395 $width = intval($match[1]);
2396 $height = intval($match[2]);
2398 $Image = new Image($data, $type);
2399 if ($Image->isValid()) {
2400 $Image->scaleDown(max($width, $height));
2401 $data = $Image->asString();
2402 $type = $Image->getType();
2406 logger('replacing photo', LOGGER_DEBUG);
2407 $image = 'data:' . $type . ';base64,' . base64_encode($data);
2408 logger('replaced: ' . $image, LOGGER_DATA);
2414 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2415 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2416 if ($orig_body === false) {
2420 $img_start = strpos($orig_body, '[img');
2421 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2422 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2425 $new_body = $new_body . $orig_body;
2430 private static function hasPermissions($obj)
2432 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2433 !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2436 private static function samePermissions($obj1, $obj2)
2438 // first part is easy. Check that these are exactly the same.
2439 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2440 && ($obj1['allow_gid'] == $obj2['allow_gid'])
2441 && ($obj1['deny_cid'] == $obj2['deny_cid'])
2442 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
2446 // This is harder. Parse all the permissions and compare the resulting set.
2447 $recipients1 = self::enumeratePermissions($obj1);
2448 $recipients2 = self::enumeratePermissions($obj2);
2452 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2453 return ($recipients1 == $recipients2);
2456 // returns an array of contact-ids that are allowed to see this object
2457 private static function enumeratePermissions($obj)
2459 $allow_people = expand_acl($obj['allow_cid']);
2460 $allow_groups = Group::expand(expand_acl($obj['allow_gid']));
2461 $deny_people = expand_acl($obj['deny_cid']);
2462 $deny_groups = Group::expand(expand_acl($obj['deny_gid']));
2463 $recipients = array_unique(array_merge($allow_people, $allow_groups));
2464 $deny = array_unique(array_merge($deny_people, $deny_groups));
2465 $recipients = array_diff($recipients, $deny);
2469 public static function getFeedTags($item)
2473 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2475 for ($x = 0; $x < $cnt; $x ++) {
2476 if ($matches[1][$x]) {
2477 $ret[$matches[2][$x]] = ['#', $matches[1][$x], $matches[2][$x]];
2482 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2484 for ($x = 0; $x < $cnt; $x ++) {
2485 if ($matches[1][$x]) {
2486 $ret[] = ['@', $matches[1][$x], $matches[2][$x]];
2493 public static function expire($uid, $days, $network = "", $force = false)
2495 if (!$uid || ($days < 1)) {
2499 $condition = ["`uid` = ? AND NOT `deleted` AND `id` = `parent` AND `gravity` = ?",
2500 $uid, GRAVITY_PARENT];
2503 * $expire_network_only = save your own wall posts
2504 * and just expire conversations started by others
2506 $expire_network_only = PConfig::get($uid, 'expire', 'network_only', false);
2508 if ($expire_network_only) {
2509 $condition[0] .= " AND NOT `wall`";
2512 if ($network != "") {
2513 $condition[0] .= " AND `network` = ?";
2514 $condition[] = $network;
2517 * There is an index "uid_network_received" but not "uid_network_created"
2518 * This avoids the creation of another index just for one purpose.
2519 * And it doesn't really matter wether to look at "received" or "created"
2521 $condition[0] .= " AND `received` < UTC_TIMESTAMP() - INTERVAL ? DAY";
2522 $condition[] = $days;
2524 $condition[0] .= " AND `created` < UTC_TIMESTAMP() - INTERVAL ? DAY";
2525 $condition[] = $days;
2528 $items = self::select(['file', 'resource-id', 'starred', 'type', 'id'], $condition);
2530 if (!DBM::is_result($items)) {
2534 $expire_items = PConfig::get($uid, 'expire', 'items', true);
2536 // Forcing expiring of items - but not notes and marked items
2538 $expire_items = true;
2541 $expire_notes = PConfig::get($uid, 'expire', 'notes', true);
2542 $expire_starred = PConfig::get($uid, 'expire', 'starred', true);
2543 $expire_photos = PConfig::get($uid, 'expire', 'photos', false);
2547 while ($item = Item::fetch($items)) {
2548 // don't expire filed items
2550 if (strpos($item['file'], '[') !== false) {
2554 // Only expire posts, not photos and photo comments
2556 if (!$expire_photos && strlen($item['resource-id'])) {
2558 } elseif (!$expire_starred && intval($item['starred'])) {
2560 } elseif (!$expire_notes && $item['type'] == 'note') {
2562 } elseif (!$expire_items && $item['type'] != 'note') {
2566 self::deleteById($item['id'], PRIORITY_LOW);
2571 logger('User ' . $uid . ": expired $expired items; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
2574 public static function firstPostDate($uid, $wall = false)
2576 $condition = ['uid' => $uid, 'wall' => $wall, 'deleted' => false, 'visible' => true, 'moderated' => false];
2577 $params = ['order' => ['created' => false]];
2578 $thread = dba::selectFirst('thread', ['created'], $condition, $params);
2579 if (DBM::is_result($thread)) {
2580 return substr(DateTimeFormat::local($thread['created']), 0, 10);
2586 * @brief add/remove activity to an item
2588 * Toggle activities as like,dislike,attend of an item
2590 * @param string $item_id
2591 * @param string $verb
2592 * Activity verb. One of
2593 * like, unlike, dislike, undislike, attendyes, unattendyes,
2594 * attendno, unattendno, attendmaybe, unattendmaybe
2595 * @hook 'post_local_end'
2597 * 'post_id' => ID of posted item
2599 public static function performLike($item_id, $verb)
2601 if (!local_user() && !remote_user()) {
2608 $bodyverb = L10n::t('%1$s likes %2$s\'s %3$s');
2609 $activity = ACTIVITY_LIKE;
2613 $bodyverb = L10n::t('%1$s doesn\'t like %2$s\'s %3$s');
2614 $activity = ACTIVITY_DISLIKE;
2618 $bodyverb = L10n::t('%1$s is attending %2$s\'s %3$s');
2619 $activity = ACTIVITY_ATTEND;
2623 $bodyverb = L10n::t('%1$s is not attending %2$s\'s %3$s');
2624 $activity = ACTIVITY_ATTENDNO;
2627 case 'unattendmaybe':
2628 $bodyverb = L10n::t('%1$s may attend %2$s\'s %3$s');
2629 $activity = ACTIVITY_ATTENDMAYBE;
2632 logger('like: unknown verb ' . $verb . ' for item ' . $item_id);
2636 // Enable activity toggling instead of on/off
2637 $event_verb_flag = $activity === ACTIVITY_ATTEND || $activity === ACTIVITY_ATTENDNO || $activity === ACTIVITY_ATTENDMAYBE;
2639 logger('like: verb ' . $verb . ' item ' . $item_id);
2641 $item = self::selectFirst(self::ITEM_FIELDLIST, ['`id` = ? OR `uri` = ?', $item_id, $item_id]);
2642 if (!DBM::is_result($item)) {
2643 logger('like: unknown item ' . $item_id);
2647 $uid = $item['uid'];
2648 if (($uid == 0) && local_user()) {
2649 $uid = local_user();
2652 if (!can_write_wall($uid)) {
2653 logger('like: unable to write on wall ' . $uid);
2657 // Retrieves the local post owner
2658 $owner_self_contact = dba::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
2659 if (!DBM::is_result($owner_self_contact)) {
2660 logger('like: unknown owner ' . $uid);
2664 // Retrieve the current logged in user's public contact
2665 $author_id = public_contact();
2667 $author_contact = dba::selectFirst('contact', [], ['id' => $author_id]);
2668 if (!DBM::is_result($author_contact)) {
2669 logger('like: unknown author ' . $author_id);
2673 // Contact-id is the uid-dependant author contact
2674 if (local_user() == $uid) {
2675 $item_contact_id = $owner_self_contact['id'];
2676 $item_contact = $owner_self_contact;
2678 $item_contact_id = Contact::getIdForURL($author_contact['url'], $uid, true);
2679 $item_contact = dba::selectFirst('contact', [], ['id' => $item_contact_id]);
2680 if (!DBM::is_result($item_contact)) {
2681 logger('like: unknown item contact ' . $item_contact_id);
2686 // Look for an existing verb row
2687 // event participation are essentially radio toggles. If you make a subsequent choice,
2688 // we need to eradicate your first choice.
2689 if ($event_verb_flag) {
2690 $verbs = [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE];
2695 $base_condition = ['verb' => $verbs, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY,
2696 'author-id' => $author_contact['id'], 'uid' => $item['uid']];
2698 $condition = array_merge($base_condition, ['parent' => $item_id]);
2699 $like_item = self::selectFirst(['id', 'guid', 'verb'], $condition);
2701 if (!DBM::is_result($like_item)) {
2702 $condition = array_merge($base_condition, ['parent-uri' => $item_id]);
2703 $like_item = self::selectFirst(['id', 'guid', 'verb'], $condition);
2706 if (!DBM::is_result($like_item)) {
2707 $condition = array_merge($base_condition, ['thr-parent' => $item_id]);
2708 $like_item = self::selectFirst(['id', 'guid', 'verb'], $condition);
2711 // If it exists, mark it as deleted
2712 if (DBM::is_result($like_item)) {
2713 // Already voted, undo it
2714 $fields = ['deleted' => true, 'unseen' => true, 'changed' => DateTimeFormat::utcNow()];
2715 /// @todo Consider using self::update - but before doing so, check the side effects
2716 dba::update('item', $fields, ['id' => $like_item['id']]);
2718 // Clean up the Diaspora signatures for this like
2719 // Go ahead and do it even if Diaspora support is disabled. We still want to clean up
2720 // if it had been enabled in the past
2721 dba::delete('sign', ['iid' => $like_item['id']]);
2723 $like_item_id = $like_item['id'];
2724 Worker::add(PRIORITY_HIGH, "Notifier", "like", $like_item_id);
2726 if (!$event_verb_flag || $like_item['verb'] == $activity) {
2731 // Verb is "un-something", just trying to delete existing entries
2732 if (strpos($verb, 'un') === 0) {
2736 // Else or if event verb different from existing row, create a new item row
2737 $post_type = (($item['resource-id']) ? L10n::t('photo') : L10n::t('status'));
2738 if ($item['object-type'] === ACTIVITY_OBJ_EVENT) {
2739 $post_type = L10n::t('event');
2741 $objtype = $item['resource-id'] ? ACTIVITY_OBJ_IMAGE : ACTIVITY_OBJ_NOTE ;
2742 $link = xmlify('<link rel="alternate" type="text/html" href="' . System::baseUrl() . '/display/' . $owner_self_contact['nick'] . '/' . $item['id'] . '" />' . "\n") ;
2743 $body = $item['body'];
2748 <type>$objtype</type>
2750 <id>{$item['uri']}</id>
2753 <content>$body</content>
2757 $ulink = '[url=' . $author_contact['url'] . ']' . $author_contact['name'] . '[/url]';
2758 $alink = '[url=' . $item['author-link'] . ']' . $item['author-name'] . '[/url]';
2759 $plink = '[url=' . System::baseUrl() . '/display/' . $owner_self_contact['nick'] . '/' . $item['id'] . ']' . $post_type . '[/url]';
2762 'guid' => get_guid(32),
2763 'uri' => self::newURI($item['uid']),
2764 'uid' => $item['uid'],
2765 'contact-id' => $item_contact_id,
2766 'type' => 'activity',
2767 'wall' => $item['wall'],
2769 'gravity' => GRAVITY_ACTIVITY,
2770 'parent' => $item['id'],
2771 'parent-uri' => $item['uri'],
2772 'thr-parent' => $item['uri'],
2773 'owner-id' => $item['owner-id'],
2774 'owner-name' => $item['owner-name'],
2775 'owner-link' => $item['owner-link'],
2776 'owner-avatar' => $item['owner-avatar'],
2777 'author-id' => $author_contact['id'],
2778 'author-name' => $author_contact['name'],
2779 'author-link' => $author_contact['url'],
2780 'author-avatar' => $author_contact['thumb'],
2781 'body' => sprintf($bodyverb, $ulink, $alink, $plink),
2782 'verb' => $activity,
2783 'object-type' => $objtype,
2785 'allow_cid' => $item['allow_cid'],
2786 'allow_gid' => $item['allow_gid'],
2787 'deny_cid' => $item['deny_cid'],
2788 'deny_gid' => $item['deny_gid'],
2793 $new_item_id = self::insert($new_item);
2795 // If the parent item isn't visible then set it to visible
2796 if (!$item['visible']) {
2797 self::update(['visible' => true], ['id' => $item['id']]);
2800 // Save the author information for the like in case we need to relay to Diaspora
2801 Diaspora::storeLikeSignature($item_contact, $new_item_id);
2803 $new_item['id'] = $new_item_id;
2805 Addon::callHooks('post_local_end', $new_item);
2807 Worker::add(PRIORITY_HIGH, "Notifier", "like", $new_item_id);
2812 private static function addThread($itemid, $onlyshadow = false)
2814 $fields = ['uid', 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private', 'pubmail',
2815 'moderated', 'visible', 'starred', 'bookmark', 'contact-id',
2816 'deleted', 'origin', 'forum_mode', 'mention', 'network', 'author-id', 'owner-id'];
2817 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
2818 $item = self::selectFirst($fields, $condition);
2820 if (!DBM::is_result($item)) {
2824 $item['iid'] = $itemid;
2827 $result = dba::insert('thread', $item);
2829 logger("Add thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
2833 private static function updateThread($itemid, $setmention = false)
2835 $fields = ['uid', 'guid', 'created', 'edited', 'commented', 'received', 'changed',
2836 'wall', 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark', 'contact-id',
2837 'deleted', 'origin', 'forum_mode', 'network', 'author-id', 'owner-id'];
2838 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
2840 $item = self::selectFirst($fields, $condition);
2841 if (!DBM::is_result($item)) {
2846 $item["mention"] = 1;
2853 foreach ($item as $field => $data) {
2854 if (!in_array($field, ["guid"])) {
2855 $fields[$field] = $data;
2859 $result = dba::update('thread', $fields, ['iid' => $itemid]);
2861 logger("Update thread for item ".$itemid." - guid ".$item["guid"]." - ".(int)$result, LOGGER_DEBUG);
2864 private static function deleteThread($itemid, $itemuri = "")
2866 $item = dba::selectFirst('thread', ['uid'], ['iid' => $itemid]);
2867 if (!DBM::is_result($item)) {
2868 logger('No thread found for id '.$itemid, LOGGER_DEBUG);
2872 // Using dba::delete at this time could delete the associated item entries
2873 $result = dba::e("DELETE FROM `thread` WHERE `iid` = ?", $itemid);
2875 logger("deleteThread: Deleted thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
2877 if ($itemuri != "") {
2878 $condition = ["`uri` = ? AND NOT `deleted` AND NOT (`uid` IN (?, 0))", $itemuri, $item["uid"]];
2879 if (!self::exists($condition)) {
2880 dba::delete('item', ['uri' => $itemuri, 'uid' => 0]);
2881 logger("deleteThread: Deleted shadow for item ".$itemuri, LOGGER_DEBUG);