4 * @file src/Model/Item.php
7 namespace Friendica\Model;
9 use Friendica\BaseObject;
10 use Friendica\Content\Text;
11 use Friendica\Core\Addon;
12 use Friendica\Core\Config;
13 use Friendica\Core\L10n;
14 use Friendica\Core\PConfig;
15 use Friendica\Core\System;
16 use Friendica\Core\Worker;
17 use Friendica\Database\DBM;
18 use Friendica\Model\Contact;
19 use Friendica\Model\Conversation;
20 use Friendica\Model\Group;
21 use Friendica\Model\Term;
22 use Friendica\Object\Image;
23 use Friendica\Protocol\Diaspora;
24 use Friendica\Protocol\OStatus;
25 use Friendica\Util\DateTimeFormat;
26 use Friendica\Util\XML;
27 use Friendica\Util\Lock;
29 use Text_LanguageDetect;
31 require_once 'boot.php';
32 require_once 'include/items.php';
33 require_once 'include/text.php';
35 class Item extends BaseObject
37 // Field list that is used to display the items
38 const DISPLAY_FIELDLIST = ['uid', 'id', 'parent', 'uri', 'thr-parent', 'parent-uri', 'guid', 'network',
39 'commented', 'created', 'edited', 'received', 'verb', 'object-type', 'postopts', 'plink',
40 'wall', 'private', 'starred', 'origin', 'title', 'body', 'file', 'attach', 'language',
41 'content-warning', 'location', 'coord', 'app', 'rendered-hash', 'rendered-html', 'object',
42 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'item_id',
43 'author-id', 'author-link', 'author-name', 'author-avatar',
44 'owner-id', 'owner-link', 'owner-name', 'owner-avatar',
45 'contact-id', 'contact-link', 'contact-name', 'contact-avatar',
46 'writable', 'self', 'cid', 'alias',
47 'event-id', 'event-created', 'event-edited', 'event-start', 'event-finish',
48 'event-summary', 'event-desc', 'event-location', 'event-type',
49 'event-nofinish', 'event-adjust', 'event-ignore', 'event-id'];
51 // Field list that is used to deliver items via the protocols
52 const DELIVER_FIELDLIST = ['uid', 'id', 'parent', 'uri', 'thr-parent', 'parent-uri', 'guid',
53 'created', 'edited', 'verb', 'object-type', 'object', 'target',
54 'private', 'title', 'body', 'location', 'coord', 'app',
55 'attach', 'tag', 'bookmark', 'deleted', 'extid',
56 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
57 'author-id', 'author-link', 'owner-link', 'contact-uid',
58 'signed_text', 'signature', 'signer'];
60 // Field list for "item-content" table that is mixed with the item table
61 const MIXED_CONTENT_FIELDLIST = ['title', 'content-warning', 'body', 'location',
62 'coord', 'app', 'rendered-hash', 'rendered-html', 'verb',
63 'object-type', 'object', 'target-type', 'target', 'plink'];
65 // Field list for "item-content" table that is not present in the "item" table
66 const CONTENT_FIELDLIST = ['language'];
68 // All fields in the item table
69 const ITEM_FIELDLIST = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
70 'contact-id', 'type', 'wall', 'gravity', 'extid', 'icid',
71 'created', 'edited', 'commented', 'received', 'changed', 'verb',
72 'postopts', 'plink', 'resource-id', 'event-id', 'tag', 'attach', 'inform',
73 'file', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
74 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
75 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global', 'network',
76 'title', 'content-warning', 'body', 'location', 'coord', 'app',
77 'rendered-hash', 'rendered-html', 'object-type', 'object', 'target-type', 'target',
78 'author-id', 'author-link', 'author-name', 'author-avatar',
79 'owner-id', 'owner-link', 'owner-name', 'owner-avatar'];
82 * @brief Fetch a single item row
84 * @param mixed $stmt statement object
85 * @return array current row
87 public static function fetch($stmt)
89 $row = dba::fetch($stmt);
91 // Fetch data from the item-content table whenever there is content there
92 foreach (self::MIXED_CONTENT_FIELDLIST as $field) {
93 if (empty($row[$field]) && !empty($row['item-' . $field])) {
94 $row[$field] = $row['item-' . $field];
96 unset($row['item-' . $field]);
99 // We prefer the data from the user's contact over the public one
100 if (!empty($row['author-link']) && !empty($row['contact-link']) &&
101 ($row['author-link'] == $row['contact-link'])) {
102 if (isset($row['author-avatar']) && !empty($row['contact-avatar'])) {
103 $row['author-avatar'] = $row['contact-avatar'];
105 if (isset($row['author-name']) && !empty($row['contact-name'])) {
106 $row['author-name'] = $row['contact-name'];
110 if (!empty($row['owner-link']) && !empty($row['contact-link']) &&
111 ($row['owner-link'] == $row['contact-link'])) {
112 if (isset($row['owner-avatar']) && !empty($row['contact-avatar'])) {
113 $row['owner-avatar'] = $row['contact-avatar'];
115 if (isset($row['owner-name']) && !empty($row['contact-name'])) {
116 $row['owner-name'] = $row['contact-name'];
120 // Build the tag string out of the term entries
121 if (isset($row['id']) && array_key_exists('tag', $row)) {
122 $row['tag'] = Term::tagTextFromItemId($row['id']);
125 // We can always comment on posts from these networks
126 if (isset($row['writable']) && !empty($row['network']) &&
127 in_array($row['network'], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS])) {
128 $row['writable'] = true;
135 * @brief Fills an array with data from an item query
137 * @param object $stmt statement object
138 * @return array Data array
140 public static function inArray($stmt, $do_close = true) {
141 if (is_bool($stmt)) {
146 while ($row = self::fetch($stmt)) {
156 * @brief Check if item data exists
158 * @param array $condition array of fields for condition
160 * @return boolean Are there rows for that condition?
162 public static function exists($condition) {
163 $stmt = self::select(['id'], $condition, ['limit' => 1]);
165 if (is_bool($stmt)) {
168 $retval = (dba::num_rows($stmt) > 0);
177 * Retrieve a single record from the item table for a given user and returns it in an associative array
179 * @brief Retrieve a single record from a table
180 * @param integer $uid User ID
181 * @param array $fields
182 * @param array $condition
183 * @param array $params
187 public static function selectFirstForUser($uid, array $selected = [], array $condition = [], $params = [])
189 $params['uid'] = $uid;
191 if (empty($selected)) {
192 $selected = Item::DISPLAY_FIELDLIST;
195 return self::selectFirst($selected, $condition, $params);
199 * @brief Select rows from the item table for a given user
201 * @param integer $uid User ID
202 * @param array $selected Array of selected fields, empty for all
203 * @param array $condition Array of fields for condition
204 * @param array $params Array of several parameters
206 * @return boolean|object
208 public static function selectForUser($uid, array $selected = [], array $condition = [], $params = [])
210 $params['uid'] = $uid;
212 if (empty($selected)) {
213 $selected = Item::DISPLAY_FIELDLIST;
216 return self::select($selected, $condition, $params);
220 * Retrieve a single record from the item table and returns it in an associative array
222 * @brief Retrieve a single record from a table
223 * @param array $fields
224 * @param array $condition
225 * @param array $params
229 public static function selectFirst(array $fields = [], array $condition = [], $params = [])
231 $params['limit'] = 1;
233 $result = self::select($fields, $condition, $params);
235 if (is_bool($result)) {
238 $row = self::fetch($result);
245 * @brief Select rows from the item table
247 * @param array $selected Array of selected fields, empty for all
248 * @param array $condition Array of fields for condition
249 * @param array $params Array of several parameters
251 * @return boolean|object
253 public static function select(array $selected = [], array $condition = [], $params = [])
258 if (isset($params['uid'])) {
259 $uid = $params['uid'];
263 $fields = self::fieldlist($selected);
265 $select_fields = self::constructSelectFields($fields, $selected);
267 $condition_string = dba::buildCondition($condition);
269 $condition_string = self::addTablesToFields($condition_string, $fields);
272 $condition_string = $condition_string . ' AND ' . self::condition(false);
275 $param_string = self::addTablesToFields(dba::buildParameter($params), $fields);
277 $table = "`item` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, false);
279 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
281 return dba::p($sql, $condition);
285 * @brief Select rows from the starting post in the item table
287 * @param integer $uid User ID
288 * @param array $fields Array of selected fields, empty for all
289 * @param array $condition Array of fields for condition
290 * @param array $params Array of several parameters
292 * @return boolean|object
294 public static function selectThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
296 $params['uid'] = $uid;
298 if (empty($selected)) {
299 $selected = Item::DISPLAY_FIELDLIST;
302 return self::selectThread($selected, $condition, $params);
306 * Retrieve a single record from the starting post in the item table and returns it in an associative array
308 * @brief Retrieve a single record from a table
309 * @param integer $uid User ID
310 * @param array $selected
311 * @param array $condition
312 * @param array $params
316 public static function selectFirstThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
318 $params['uid'] = $uid;
320 if (empty($selected)) {
321 $selected = Item::DISPLAY_FIELDLIST;
324 return self::selectFirstThread($selected, $condition, $params);
328 * Retrieve a single record from the starting post in the item table and returns it in an associative array
330 * @brief Retrieve a single record from a table
331 * @param array $fields
332 * @param array $condition
333 * @param array $params
337 public static function selectFirstThread(array $fields = [], array $condition = [], $params = [])
339 $params['limit'] = 1;
340 $result = self::selectThread($fields, $condition, $params);
342 if (is_bool($result)) {
345 $row = self::fetch($result);
352 * @brief Select rows from the starting post in the item table
354 * @param array $selected Array of selected fields, empty for all
355 * @param array $condition Array of fields for condition
356 * @param array $params Array of several parameters
358 * @return boolean|object
360 public static function selectThread(array $selected = [], array $condition = [], $params = [])
365 if (isset($params['uid'])) {
366 $uid = $params['uid'];
370 $fields = self::fieldlist($selected);
372 $threadfields = ['thread' => ['iid', 'uid', 'contact-id', 'owner-id', 'author-id',
373 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private',
374 'pubmail', 'moderated', 'visible', 'starred', 'ignored', 'bookmark',
375 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'network']];
377 $select_fields = self::constructSelectFields($fields, $selected);
379 $condition_string = dba::buildCondition($condition);
381 $condition_string = self::addTablesToFields($condition_string, $threadfields);
382 $condition_string = self::addTablesToFields($condition_string, $fields);
385 $condition_string = $condition_string . ' AND ' . self::condition(true);
388 $param_string = dba::buildParameter($params);
389 $param_string = self::addTablesToFields($param_string, $threadfields);
390 $param_string = self::addTablesToFields($param_string, $fields);
392 $table = "`thread` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, true);
394 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
396 return dba::p($sql, $condition);
400 * @brief Returns a list of fields that are associated with the item table
402 * @return array field list
404 private static function fieldlist($selected)
408 $fields['item'] = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
409 'contact-id', 'owner-id', 'author-id', 'type', 'wall', 'gravity', 'extid',
410 'created', 'edited', 'commented', 'received', 'changed', 'postopts',
411 'resource-id', 'event-id', 'tag', 'attach', 'inform',
412 'file', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
413 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
414 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global',
415 'id' => 'item_id', 'network', 'icid'];
417 $fields['item-content'] = array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST);
419 $fields['author'] = ['url' => 'author-link', 'name' => 'author-name',
420 'thumb' => 'author-avatar', 'nick' => 'author-nick'];
422 $fields['owner'] = ['url' => 'owner-link', 'name' => 'owner-name',
423 'thumb' => 'owner-avatar', 'nick' => 'owner-nick'];
425 $fields['contact'] = ['url' => 'contact-link', 'name' => 'contact-name', 'thumb' => 'contact-avatar',
426 'writable', 'self', 'id' => 'cid', 'alias', 'uid' => 'contact-uid',
427 'photo', 'name-date', 'uri-date', 'avatar-date', 'thumb', 'dfrn-id'];
429 $fields['parent-item'] = ['guid' => 'parent-guid', 'network' => 'parent-network'];
431 $fields['parent-item-author'] = ['url' => 'parent-author-link', 'name' => 'parent-author-name'];
433 $fields['event'] = ['created' => 'event-created', 'edited' => 'event-edited',
434 'start' => 'event-start','finish' => 'event-finish',
435 'summary' => 'event-summary','desc' => 'event-desc',
436 'location' => 'event-location', 'type' => 'event-type',
437 'nofinish' => 'event-nofinish','adjust' => 'event-adjust',
438 'ignore' => 'event-ignore', 'id' => 'event-id'];
440 $fields['sign'] = ['signed_text', 'signature', 'signer'];
446 * @brief Returns SQL condition for the "select" functions
448 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
450 * @return string SQL condition
452 private static function condition($thread_mode)
455 $master_table = "`thread`";
457 $master_table = "`item`";
459 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`) ";
463 * @brief Returns all needed "JOIN" commands for the "select" functions
465 * @param integer $uid User ID
466 * @param string $sql_commands The parts of the built SQL commands in the "select" functions
467 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
469 * @return string The SQL joins for the "select" functions
471 private static function constructJoins($uid, $sql_commands, $thread_mode)
474 $master_table = "`thread`";
475 $master_table_key = "`thread`.`iid`";
476 $joins = "STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid` ";
478 $master_table = "`item`";
479 $master_table_key = "`item`.`id`";
483 $joins .= sprintf("STRAIGHT_JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`
484 AND NOT `contact`.`blocked`
485 AND ((NOT `contact`.`readonly` AND NOT `contact`.`pending` AND (`contact`.`rel` IN (%s, %s)))
486 OR `contact`.`self` OR (`item`.`id` != `item`.`parent`) OR `contact`.`uid` = 0)
487 STRAIGHT_JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id` AND NOT `author`.`blocked`
488 STRAIGHT_JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id` AND NOT `owner`.`blocked`
489 LEFT JOIN `user-item` ON `user-item`.`iid` = $master_table_key AND `user-item`.`uid` = %d",
490 CONTACT_IS_SHARING, CONTACT_IS_FRIEND, intval($uid));
492 if (strpos($sql_commands, "`group_member`.") !== false) {
493 $joins .= " STRAIGHT_JOIN `group_member` ON `group_member`.`contact-id` = $master_table.`contact-id`";
496 if (strpos($sql_commands, "`user`.") !== false) {
497 $joins .= " STRAIGHT_JOIN `user` ON `user`.`uid` = $master_table.`uid`";
500 if (strpos($sql_commands, "`event`.") !== false) {
501 $joins .= " LEFT JOIN `event` ON `event-id` = `event`.`id`";
504 if (strpos($sql_commands, "`sign`.") !== false) {
505 $joins .= " LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`";
508 if (strpos($sql_commands, "`item-content`.") !== false) {
509 $joins .= " LEFT JOIN `item-content` ON `item-content`.`id` = `item`.`icid`";
512 if ((strpos($sql_commands, "`parent-item`.") !== false) || (strpos($sql_commands, "`parent-author`.") !== false)) {
513 $joins .= " STRAIGHT_JOIN `item` AS `parent-item` ON `parent-item`.`id` = `item`.`parent`";
516 if (strpos($sql_commands, "`parent-item-author`.") !== false) {
517 $joins .= " STRAIGHT_JOIN `contact` AS `parent-item-author` ON `parent-item-author`.`id` = `parent-item`.`author-id`";
524 * @brief Add the field list for the "select" functions
526 * @param array $fields The field definition array
527 * @param array $selected The array with the selected fields from the "select" functions
529 * @return string The field list
531 private static function constructSelectFields($fields, $selected)
533 // To be able to fetch the tags we need the item id
534 if (in_array('tag', $selected) && !in_array('id', $selected)) {
539 foreach ($fields as $table => $table_fields) {
540 foreach ($table_fields as $field => $select) {
541 if (empty($selected) || in_array($select, $selected)) {
542 if (in_array($select, self::MIXED_CONTENT_FIELDLIST)) {
543 $selection[] = "`item`.`".$select."` AS `item-" . $select . "`";
545 if (is_int($field)) {
546 $selection[] = "`" . $table . "`.`" . $select . "`";
548 $selection[] = "`" . $table . "`.`" . $field . "` AS `" . $select . "`";
553 return implode(", ", $selection);
557 * @brief add table definition to fields in an SQL query
559 * @param string $query SQL query
560 * @param array $fields The field definition array
562 * @return string the changed SQL query
564 private static function addTablesToFields($query, $fields)
566 foreach ($fields as $table => $table_fields) {
567 foreach ($table_fields as $alias => $field) {
568 if (is_int($alias)) {
569 $replace_field = $field;
571 $replace_field = $alias;
574 $search = "/([^\.])`" . $field . "`/i";
575 $replace = "$1`" . $table . "`.`" . $replace_field . "`";
576 $query = preg_replace($search, $replace, $query);
583 * @brief Update existing item entries
585 * @param array $fields The fields that are to be changed
586 * @param array $condition The condition for finding the item entries
588 * In the future we may have to change permissions as well.
589 * Then we had to add the user id as third parameter.
591 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
593 * @return integer|boolean number of affected rows - or "false" if there was an error
595 public static function update(array $fields, array $condition)
597 if (empty($condition) || empty($fields)) {
601 // To ensure the data integrity we do it in an transaction
604 // We cannot simply expand the condition to check for origin entries
605 // The condition needn't to be a simple array but could be a complex condition.
606 // And we have to execute this query before the update to ensure to fetch the same data.
607 $items = dba::select('item', ['id', 'origin', 'uri', 'plink'], $condition);
609 $content_fields = [];
610 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
611 if (isset($fields[$field])) {
612 $content_fields[$field] = $fields[$field];
613 unset($fields[$field]);
617 if (array_key_exists('tag', $fields)) {
618 $tags = $fields['tag'];
619 unset($fields['tag']);
624 if (!empty($fields)) {
625 $success = dba::update('item', $fields, $condition);
634 // When there is no content for the "old" item table, this will count the fetched items
635 $rows = dba::affected_rows();
637 while ($item = dba::fetch($items)) {
638 if (!empty($item['plink'])) {
639 $content_fields['plink'] = $item['plink'];
641 self::updateContent($content_fields, ['uri' => $item['uri']]);
644 Term::insertFromTagFieldByItemId($item['id'], $tags);
647 if (array_key_exists('file', $fields)) {
648 Term::insertFromFileFieldByItemId($item['id']);
651 self::updateThread($item['id']);
653 // We only need to notfiy others when it is an original entry from us.
654 // Only call the notifier when the item has some content relevant change.
655 if ($item['origin'] && in_array('edited', array_keys($fields))) {
656 Worker::add(PRIORITY_HIGH, "Notifier", 'edit_post', $item['id']);
666 * @brief Delete an item and notify others about it - if it was ours
668 * @param array $condition The condition for finding the item entries
669 * @param integer $priority Priority for the notification
671 public static function delete($condition, $priority = PRIORITY_HIGH)
673 $items = dba::select('item', ['id'], $condition);
674 while ($item = dba::fetch($items)) {
675 self::deleteById($item['id'], $priority);
681 * @brief Delete an item for an user and notify others about it - if it was ours
683 * @param array $condition The condition for finding the item entries
684 * @param integer $uid User who wants to delete this item
686 public static function deleteForUser($condition, $uid)
692 $items = dba::select('item', ['id', 'uid'], $condition);
693 while ($item = dba::fetch($items)) {
694 // "Deleting" global items just means hiding them
695 if ($item['uid'] == 0) {
696 dba::update('user-item', ['hidden' => true], ['iid' => $item['id'], 'uid' => $uid], true);
697 } elseif ($item['uid'] == $uid) {
698 self::deleteById($item['id'], PRIORITY_HIGH);
700 logger('Wrong ownership. Not deleting item ' . $item['id']);
707 * @brief Delete an item and notify others about it - if it was ours
709 * @param integer $item_id Item ID that should be delete
710 * @param integer $priority Priority for the notification
712 * @return boolean success
714 private static function deleteById($item_id, $priority = PRIORITY_HIGH)
716 // locate item to be deleted
717 $fields = ['id', 'uri', 'uid', 'parent', 'parent-uri', 'origin',
718 'deleted', 'file', 'resource-id', 'event-id', 'attach',
719 'verb', 'object-type', 'object', 'target', 'contact-id'];
720 $item = dba::selectFirst('item', $fields, ['id' => $item_id]);
721 if (!DBM::is_result($item)) {
722 logger('Item with ID ' . $item_id . " hasn't been found.", LOGGER_DEBUG);
726 if ($item['deleted']) {
727 logger('Item with ID ' . $item_id . ' has already been deleted.', LOGGER_DEBUG);
731 $parent = dba::selectFirst('item', ['origin'], ['id' => $item['parent']]);
732 if (!DBM::is_result($parent)) {
733 $parent = ['origin' => false];
736 // clean up categories and tags so they don't end up as orphans
739 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
741 foreach ($matches as $mtch) {
742 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],true);
748 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
750 foreach ($matches as $mtch) {
751 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],false);
756 * If item is a link to a photo resource, nuke all the associated photos
757 * (visitors will not have photo resources)
758 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
759 * generate a resource-id and therefore aren't intimately linked to the item.
761 if (strlen($item['resource-id'])) {
762 dba::delete('photo', ['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
765 // If item is a link to an event, delete the event.
766 if (intval($item['event-id'])) {
767 Event::delete($item['event-id']);
770 // If item has attachments, drop them
771 foreach (explode(", ", $item['attach']) as $attach) {
772 preg_match("|attach/(\d+)|", $attach, $matches);
773 dba::delete('attach', ['id' => $matches[1], 'uid' => $item['uid']]);
776 // Delete tags that had been attached to other items
777 self::deleteTagsFromItem($item);
779 // Set the item to "deleted"
780 // This erasing of item content is superfluous for items with a matching item-content.
781 // But for the next time we will still have old content in the item table.
782 $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow(),
783 'body' => '', 'title' => '', 'content-warning' => '', 'rendered-hash' => '', 'rendered-html' => '',
784 'object' => '', 'target' => '', 'tag' => '', 'postopts' => '', 'attach' => '', 'file' => ''];
785 dba::update('item', $item_fields, ['id' => $item['id']]);
787 Term::insertFromTagFieldByItemId($item['id'], '');
788 Term::insertFromFileFieldByItemId($item['id']);
789 self::deleteThread($item['id'], $item['parent-uri']);
791 if (!self::exists(["`uri` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri']])) {
792 self::delete(['uri' => $item['uri'], 'uid' => 0, 'deleted' => false], $priority);
795 // If it's the parent of a comment thread, kill all the kids
796 if ($item['id'] == $item['parent']) {
797 self::delete(['parent' => $item['parent'], 'deleted' => false], $priority);
800 // Is it our comment and/or our thread?
801 if ($item['origin'] || $parent['origin']) {
803 // When we delete the original post we will delete all existing copies on the server as well
804 self::delete(['uri' => $item['uri'], 'deleted' => false], $priority);
806 // send the notification upstream/downstream
807 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", "drop", intval($item['id']));
808 } elseif ($item['uid'] != 0) {
810 // When we delete just our local user copy of an item, we have to set a marker to hide it
811 $global_item = dba::selectFirst('item', ['id'], ['uri' => $item['uri'], 'uid' => 0, 'deleted' => false]);
812 if (DBM::is_result($global_item)) {
813 dba::update('user-item', ['hidden' => true], ['iid' => $global_item['id'], 'uid' => $item['uid']], true);
817 logger('Item with ID ' . $item_id . " has been deleted.", LOGGER_DEBUG);
822 private static function deleteTagsFromItem($item)
824 if (($item["verb"] != ACTIVITY_TAG) || ($item["object-type"] != ACTIVITY_OBJ_TAGTERM)) {
828 $xo = XML::parseString($item["object"], false);
829 $xt = XML::parseString($item["target"], false);
831 if ($xt->type != ACTIVITY_OBJ_NOTE) {
835 $i = dba::selectFirst('item', ['id', 'contact-id', 'tag'], ['uri' => $xt->id, 'uid' => $item['uid']]);
836 if (!DBM::is_result($i)) {
840 // For tags, the owner cannot remove the tag on the author's copy of the post.
841 $owner_remove = ($item["contact-id"] == $i["contact-id"]);
842 $author_copy = $item["origin"];
844 if (($owner_remove && $author_copy) || !$owner_remove) {
848 $tags = explode(',', $i["tag"]);
851 foreach ($tags as $tag) {
852 if (trim($tag) !== trim($xo->body)) {
853 $newtags[] = trim($tag);
857 self::update(['tag' => implode(',', $newtags)], ['id' => $i["id"]]);
860 private static function guid($item, $notify)
862 $guid = notags(trim($item['guid']));
869 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
870 // We add the hash of our own host because our host is the original creator of the post.
871 $prefix_host = get_app()->get_hostname();
875 // We are only storing the post so we create a GUID from the original hostname.
876 if (!empty($item['author-link'])) {
877 $parsed = parse_url($item['author-link']);
878 if (!empty($parsed['host'])) {
879 $prefix_host = $parsed['host'];
883 if (empty($prefix_host) && !empty($item['plink'])) {
884 $parsed = parse_url($item['plink']);
885 if (!empty($parsed['host'])) {
886 $prefix_host = $parsed['host'];
890 if (empty($prefix_host) && !empty($item['uri'])) {
891 $parsed = parse_url($item['uri']);
892 if (!empty($parsed['host'])) {
893 $prefix_host = $parsed['host'];
897 // Is it in the format data@host.tld? - Used for mail contacts
898 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
899 $mailparts = explode('@', $item['author-link']);
900 $prefix_host = array_pop($mailparts);
904 if (!empty($item['plink'])) {
905 $guid = self::guidFromUri($item['plink'], $prefix_host);
906 } elseif (!empty($item['uri'])) {
907 $guid = self::guidFromUri($item['uri'], $prefix_host);
909 $guid = get_guid(32, hash('crc32', $prefix_host));
915 private static function contactId($item)
917 $contact_id = (int)$item["contact-id"];
919 if (!empty($contact_id)) {
922 logger('Missing contact-id. Called by: '.System::callstack(), LOGGER_DEBUG);
924 * First we are looking for a suitable contact that matches with the author of the post
925 * This is done only for comments
927 if ($item['parent-uri'] != $item['uri']) {
928 $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
931 // If not present then maybe the owner was found
932 if ($contact_id == 0) {
933 $contact_id = Contact::getIdForURL($item['owner-link'], $item['uid']);
936 // Still missing? Then use the "self" contact of the current user
937 if ($contact_id == 0) {
938 $self = dba::selectFirst('contact', ['id'], ['self' => true, 'uid' => $item['uid']]);
939 if (DBM::is_result($self)) {
940 $contact_id = $self["id"];
943 logger("Contact-id was missing for post ".$item['guid']." from user id ".$item['uid']." - now set to ".$contact_id, LOGGER_DEBUG);
948 public static function insert($item, $force_parent = false, $notify = false, $dontcache = false)
952 // If it is a posting where users should get notifications, then define it as wall posting
955 $item['type'] = 'wall';
957 $item['network'] = NETWORK_DFRN;
958 $item['protocol'] = PROTOCOL_DFRN;
960 if (is_int($notify)) {
963 $priority = PRIORITY_HIGH;
966 $item['network'] = trim(defaults($item, 'network', NETWORK_PHANTOM));
969 $item['guid'] = self::guid($item, $notify);
970 $item['uri'] = notags(trim(defaults($item, 'uri', self::newURI($item['uid'], $item['guid']))));
972 // Store conversation data
973 $item = Conversation::insert($item);
976 * If a Diaspora signature structure was passed in, pull it out of the
977 * item array and set it aside for later storage.
981 if (x($item, 'dsprsig')) {
982 $encoded_signature = $item['dsprsig'];
983 $dsprsig = json_decode(base64_decode($item['dsprsig']));
984 unset($item['dsprsig']);
987 if (!empty($item['diaspora_signed_text'])) {
988 $diaspora_signed_text = $item['diaspora_signed_text'];
989 unset($item['diaspora_signed_text']);
991 $diaspora_signed_text = '';
994 // Converting the plink
995 /// @TODO Check if this is really still needed
996 if ($item['network'] == NETWORK_OSTATUS) {
997 if (isset($item['plink'])) {
998 $item['plink'] = OStatus::convertHref($item['plink']);
999 } elseif (isset($item['uri'])) {
1000 $item['plink'] = OStatus::convertHref($item['uri']);
1004 if (!empty($item['thr-parent'])) {
1005 $item['parent-uri'] = $item['thr-parent'];
1008 $item['type'] = defaults($item, 'type', 'remote');
1010 if (isset($item['gravity'])) {
1011 $item['gravity'] = intval($item['gravity']);
1012 } elseif ($item['parent-uri'] === $item['uri']) {
1013 $item['gravity'] = GRAVITY_PARENT;
1014 } elseif (activity_match($item['verb'], ACTIVITY_POST)) {
1015 $item['gravity'] = GRAVITY_COMMENT;
1016 } elseif ($item['type'] == 'activity') {
1017 $item['gravity'] = GRAVITY_ACTIVITY;
1019 $item['gravity'] = GRAVITY_UNKNOWN; // Should not happen
1020 logger('Unknown gravity for verb: ' . $item['verb'] . ' - type: ' . $item['type'], LOGGER_DEBUG);
1023 $uid = intval($item['uid']);
1025 // check for create date and expire time
1026 $expire_interval = Config::get('system', 'dbclean-expire-days', 0);
1028 $user = dba::selectFirst('user', ['expire'], ['uid' => $uid]);
1029 if (DBM::is_result($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
1030 $expire_interval = $user['expire'];
1033 if (($expire_interval > 0) && !empty($item['created'])) {
1034 $expire_date = time() - ($expire_interval * 86400);
1035 $created_date = strtotime($item['created']);
1036 if ($created_date < $expire_date) {
1037 logger('item-store: item created ('.date('c', $created_date).') before expiration time ('.date('c', $expire_date).'). ignored. ' . print_r($item,true), LOGGER_DEBUG);
1043 * Do we already have this item?
1044 * We have to check several networks since Friendica posts could be repeated
1045 * via OStatus (maybe Diasporsa as well)
1047 if (in_array($item['network'], [NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS, ""])) {
1048 $condition = ["`uri` = ? AND `uid` = ? AND `network` IN (?, ?, ?)",
1049 trim($item['uri']), $item['uid'],
1050 NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS];
1051 $existing = dba::selectFirst('item', ['id', 'network'], $condition);
1052 if (DBM::is_result($existing)) {
1053 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
1055 logger("Item with uri ".$item['uri']." already existed for user ".$uid." with id ".$existing["id"]." target network ".$existing["network"]." - new network: ".$item['network']);
1058 return $existing["id"];
1062 self::addLanguageToItemArray($item);
1064 $item['wall'] = intval(defaults($item, 'wall', 0));
1065 $item['extid'] = trim(defaults($item, 'extid', ''));
1066 $item['author-name'] = trim(defaults($item, 'author-name', ''));
1067 $item['author-link'] = trim(defaults($item, 'author-link', ''));
1068 $item['author-avatar'] = trim(defaults($item, 'author-avatar', ''));
1069 $item['owner-name'] = trim(defaults($item, 'owner-name', ''));
1070 $item['owner-link'] = trim(defaults($item, 'owner-link', ''));
1071 $item['owner-avatar'] = trim(defaults($item, 'owner-avatar', ''));
1072 $item['received'] = ((x($item, 'received') !== false) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
1073 $item['created'] = ((x($item, 'created') !== false) ? DateTimeFormat::utc($item['created']) : $item['received']);
1074 $item['edited'] = ((x($item, 'edited') !== false) ? DateTimeFormat::utc($item['edited']) : $item['created']);
1075 $item['changed'] = ((x($item, 'changed') !== false) ? DateTimeFormat::utc($item['changed']) : $item['created']);
1076 $item['commented'] = ((x($item, 'commented') !== false) ? DateTimeFormat::utc($item['commented']) : $item['created']);
1077 $item['title'] = trim(defaults($item, 'title', ''));
1078 $item['location'] = trim(defaults($item, 'location', ''));
1079 $item['coord'] = trim(defaults($item, 'coord', ''));
1080 $item['visible'] = ((x($item, 'visible') !== false) ? intval($item['visible']) : 1);
1081 $item['deleted'] = 0;
1082 $item['parent-uri'] = trim(defaults($item, 'parent-uri', $item['uri']));
1083 $item['verb'] = trim(defaults($item, 'verb', ''));
1084 $item['object-type'] = trim(defaults($item, 'object-type', ''));
1085 $item['object'] = trim(defaults($item, 'object', ''));
1086 $item['target-type'] = trim(defaults($item, 'target-type', ''));
1087 $item['target'] = trim(defaults($item, 'target', ''));
1088 $item['plink'] = trim(defaults($item, 'plink', ''));
1089 $item['allow_cid'] = trim(defaults($item, 'allow_cid', ''));
1090 $item['allow_gid'] = trim(defaults($item, 'allow_gid', ''));
1091 $item['deny_cid'] = trim(defaults($item, 'deny_cid', ''));
1092 $item['deny_gid'] = trim(defaults($item, 'deny_gid', ''));
1093 $item['private'] = intval(defaults($item, 'private', 0));
1094 $item['bookmark'] = intval(defaults($item, 'bookmark', 0));
1095 $item['body'] = trim(defaults($item, 'body', ''));
1096 $item['tag'] = trim(defaults($item, 'tag', ''));
1097 $item['attach'] = trim(defaults($item, 'attach', ''));
1098 $item['app'] = trim(defaults($item, 'app', ''));
1099 $item['origin'] = intval(defaults($item, 'origin', 0));
1100 $item['postopts'] = trim(defaults($item, 'postopts', ''));
1101 $item['resource-id'] = trim(defaults($item, 'resource-id', ''));
1102 $item['event-id'] = intval(defaults($item, 'event-id', 0));
1103 $item['inform'] = trim(defaults($item, 'inform', ''));
1104 $item['file'] = trim(defaults($item, 'file', ''));
1106 // When there is no content then we don't post it
1107 if ($item['body'].$item['title'] == '') {
1108 logger('No body, no title.');
1112 // Items cannot be stored before they happen ...
1113 if ($item['created'] > DateTimeFormat::utcNow()) {
1114 $item['created'] = DateTimeFormat::utcNow();
1117 // We haven't invented time travel by now.
1118 if ($item['edited'] > DateTimeFormat::utcNow()) {
1119 $item['edited'] = DateTimeFormat::utcNow();
1122 if (($item['author-link'] == "") && ($item['owner-link'] == "")) {
1123 logger("Both author-link and owner-link are empty. Called by: " . System::callstack(), LOGGER_DEBUG);
1126 $item['plink'] = defaults($item, 'plink', System::baseUrl() . '/display/' . urlencode($item['guid']));
1128 // The contact-id should be set before "self::insert" was called - but there seems to be issues sometimes
1129 $item["contact-id"] = self::contactId($item);
1131 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
1132 'photo' => $item['author-avatar'], 'network' => $item['network']];
1134 $item['author-id'] = defaults($item, 'author-id', Contact::getIdForURL($item["author-link"], 0, false, $default));
1136 if (Contact::isBlocked($item["author-id"])) {
1137 logger('Contact '.$item["author-id"].' is blocked, item '.$item["uri"].' will not be stored');
1141 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
1142 'photo' => $item['owner-avatar'], 'network' => $item['network']];
1144 $item['owner-id'] = defaults($item, 'owner-id', Contact::getIdForURL($item["owner-link"], 0, false, $default));
1146 if (Contact::isBlocked($item["owner-id"])) {
1147 logger('Contact '.$item["owner-id"].' is blocked, item '.$item["uri"].' will not be stored');
1151 // These fields aren't stored anymore in the item table, they are fetched upon request
1152 unset($item['author-link']);
1153 unset($item['author-name']);
1154 unset($item['author-avatar']);
1156 unset($item['owner-link']);
1157 unset($item['owner-name']);
1158 unset($item['owner-avatar']);
1160 if ($item['network'] == NETWORK_PHANTOM) {
1161 logger('Missing network. Called by: '.System::callstack(), LOGGER_DEBUG);
1163 $contact = Contact::getDetailsByURL($item['author-link'], $item['uid']);
1164 if (!empty($contact['network'])) {
1165 $item['network'] = $contact["network"];
1167 $item['network'] = NETWORK_DFRN;
1169 logger("Set network to " . $item["network"] . " for " . $item["uri"], LOGGER_DEBUG);
1172 // Checking if there is already an item with the same guid
1173 logger('Checking for an item for user '.$item['uid'].' on network '.$item['network'].' with the guid '.$item['guid'], LOGGER_DEBUG);
1174 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
1175 if (self::exists($condition)) {
1176 logger('found item with guid '.$item['guid'].' for user '.$item['uid'].' on network '.$item['network'], LOGGER_DEBUG);
1180 // Check for hashtags in the body and repair or add hashtag links
1181 self::setHashtags($item);
1183 $item['thr-parent'] = $item['parent-uri'];
1191 if ($item['parent-uri'] === $item['uri']) {
1193 $parent_deleted = 0;
1194 $allow_cid = $item['allow_cid'];
1195 $allow_gid = $item['allow_gid'];
1196 $deny_cid = $item['deny_cid'];
1197 $deny_gid = $item['deny_gid'];
1198 $notify_type = 'wall-new';
1200 // find the parent and snarf the item id and ACLs
1201 // and anything else we need to inherit
1203 $fields = ['uri', 'parent-uri', 'id', 'deleted',
1204 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
1205 'wall', 'private', 'forum_mode', 'origin'];
1206 $condition = ['uri' => $item['parent-uri'], 'uid' => $item['uid']];
1207 $params = ['order' => ['id' => false]];
1208 $parent = dba::selectFirst('item', $fields, $condition, $params);
1210 if (DBM::is_result($parent)) {
1211 // is the new message multi-level threaded?
1212 // even though we don't support it now, preserve the info
1213 // and re-attach to the conversation parent.
1215 if ($parent['uri'] != $parent['parent-uri']) {
1216 $item['parent-uri'] = $parent['parent-uri'];
1218 $condition = ['uri' => $item['parent-uri'],
1219 'parent-uri' => $item['parent-uri'],
1220 'uid' => $item['uid']];
1221 $params = ['order' => ['id' => false]];
1222 $toplevel_parent = dba::selectFirst('item', $fields, $condition, $params);
1224 if (DBM::is_result($toplevel_parent)) {
1225 $parent = $toplevel_parent;
1229 $parent_id = $parent['id'];
1230 $parent_deleted = $parent['deleted'];
1231 $allow_cid = $parent['allow_cid'];
1232 $allow_gid = $parent['allow_gid'];
1233 $deny_cid = $parent['deny_cid'];
1234 $deny_gid = $parent['deny_gid'];
1235 $item['wall'] = $parent['wall'];
1236 $notify_type = 'comment-new';
1239 * If the parent is private, force privacy for the entire conversation
1240 * This differs from the above settings as it subtly allows comments from
1241 * email correspondents to be private even if the overall thread is not.
1243 if ($parent['private']) {
1244 $item['private'] = $parent['private'];
1248 * Edge case. We host a public forum that was originally posted to privately.
1249 * The original author commented, but as this is a comment, the permissions
1250 * weren't fixed up so it will still show the comment as private unless we fix it here.
1252 if ((intval($parent['forum_mode']) == 1) && $parent['private']) {
1253 $item['private'] = 0;
1256 // If its a post from myself then tag the thread as "mention"
1257 logger("Checking if parent ".$parent_id." has to be tagged as mention for user ".$item['uid'], LOGGER_DEBUG);
1258 $user = dba::selectFirst('user', ['nickname'], ['uid' => $item['uid']]);
1259 if (DBM::is_result($user)) {
1260 $self = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
1261 $self_id = Contact::getIdForURL($self, 0, true);
1262 logger("'myself' is ".$self_id." for parent ".$parent_id." checking against ".$item['author-id']." and ".$item['owner-id'], LOGGER_DEBUG);
1263 if (($item['author-id'] == $self_id) || ($item['owner-id'] == $self_id)) {
1264 dba::update('thread', ['mention' => true], ['iid' => $parent_id]);
1265 logger("tagged thread ".$parent_id." as mention for user ".$self, LOGGER_DEBUG);
1270 * Allow one to see reply tweets from status.net even when
1271 * we don't have or can't see the original post.
1273 if ($force_parent) {
1274 logger('$force_parent=true, reply converted to top-level post.');
1276 $item['parent-uri'] = $item['uri'];
1277 $item['gravity'] = GRAVITY_PARENT;
1279 logger('item parent '.$item['parent-uri'].' for '.$item['uid'].' was not found - ignoring item');
1283 $parent_deleted = 0;
1287 $condition = ["`uri` = ? AND `network` IN (?, ?) AND `uid` = ?",
1288 $item['uri'], $item['network'], NETWORK_DFRN, $item['uid']];
1289 if (self::exists($condition)) {
1290 logger('duplicated item with the same uri found. '.print_r($item,true));
1294 // On Friendica and Diaspora the GUID is unique
1295 if (in_array($item['network'], [NETWORK_DFRN, NETWORK_DIASPORA])) {
1296 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
1297 if (self::exists($condition)) {
1298 logger('duplicated item with the same guid found. '.print_r($item,true));
1302 // Check for an existing post with the same content. There seems to be a problem with OStatus.
1303 $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
1304 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
1305 if (self::exists($condition)) {
1306 logger('duplicated item with the same body found. '.print_r($item,true));
1311 // Is this item available in the global items (with uid=0)?
1312 if ($item["uid"] == 0) {
1313 $item["global"] = true;
1315 // Set the global flag on all items if this was a global item entry
1316 dba::update('item', ['global' => true], ['uri' => $item["uri"]]);
1318 $item["global"] = self::exists(['uid' => 0, 'uri' => $item["uri"]]);
1322 if (strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid)) {
1325 $private = $item['private'];
1328 $item["allow_cid"] = $allow_cid;
1329 $item["allow_gid"] = $allow_gid;
1330 $item["deny_cid"] = $deny_cid;
1331 $item["deny_gid"] = $deny_gid;
1332 $item["private"] = $private;
1333 $item["deleted"] = $parent_deleted;
1335 // Fill the cache field
1336 put_item_in_cache($item);
1339 Addon::callHooks('post_local', $item);
1341 Addon::callHooks('post_remote', $item);
1344 // This array field is used to trigger some automatic reactions
1345 // It is mainly used in the "post_local" hook.
1346 unset($item['api_source']);
1348 if (x($item, 'cancel')) {
1349 logger('post cancelled by addon.');
1354 * Check for already added items.
1355 * There is a timing issue here that sometimes creates double postings.
1356 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
1358 if ($item["uid"] == 0) {
1359 if (self::exists(['uri' => trim($item['uri']), 'uid' => 0])) {
1360 logger('Global item already stored. URI: '.$item['uri'].' on network '.$item['network'], LOGGER_DEBUG);
1365 logger('' . print_r($item,true), LOGGER_DATA);
1367 if (array_key_exists('tag', $item)) {
1368 $tags = $item['tag'];
1369 unset($item['tag']);
1374 // We are doing this outside of the transaction to avoid timing problems
1375 self::insertContent($item);
1378 $ret = dba::insert('item', $item);
1380 // When the item was successfully stored we fetch the ID of the item.
1381 if (DBM::is_result($ret)) {
1382 $current_post = dba::lastInsertId();
1384 // This can happen - for example - if there are locking timeouts.
1387 // Store the data into a spool file so that we can try again later.
1389 // At first we restore the Diaspora signature that we removed above.
1390 if (isset($encoded_signature)) {
1391 $item['dsprsig'] = $encoded_signature;
1394 // Now we store the data in the spool directory
1395 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
1396 $file = 'item-'.round(microtime(true) * 10000).'-'.mt_rand().'.msg';
1398 $spoolpath = get_spoolpath();
1399 if ($spoolpath != "") {
1400 $spool = $spoolpath.'/'.$file;
1401 file_put_contents($spool, json_encode($item));
1402 logger("Item wasn't stored - Item was spooled into file ".$file, LOGGER_DEBUG);
1407 if ($current_post == 0) {
1408 // This is one of these error messages that never should occur.
1409 logger("couldn't find created item - we better quit now.");
1414 // How much entries have we created?
1415 // We wouldn't need this query when we could use an unique index - but MySQL has length problems with them.
1416 $entries = dba::count('item', ['uri' => $item['uri'], 'uid' => $item['uid'], 'network' => $item['network']]);
1419 // There are duplicates. We delete our just created entry.
1420 logger('Duplicated post occurred. uri = ' . $item['uri'] . ' uid = ' . $item['uid']);
1422 // Yes, we could do a rollback here - but we are having many users with MyISAM.
1423 dba::delete('item', ['id' => $current_post]);
1426 } elseif ($entries == 0) {
1427 // This really should never happen since we quit earlier if there were problems.
1428 logger("Something is terribly wrong. We haven't found our created entry.");
1433 logger('created item '.$current_post);
1434 self::updateContact($item);
1436 if (!$parent_id || ($item['parent-uri'] === $item['uri'])) {
1437 $parent_id = $current_post;
1441 dba::update('item', ['parent' => $parent_id], ['id' => $current_post]);
1443 $item['id'] = $current_post;
1444 $item['parent'] = $parent_id;
1446 // update the commented timestamp on the parent
1447 // Only update "commented" if it is really a comment
1448 if (($item['gravity'] != GRAVITY_ACTIVITY) || !Config::get("system", "like_no_comment")) {
1449 dba::update('item', ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1451 dba::update('item', ['changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1456 * Friendica servers lower than 3.4.3-2 had double encoded the signature ...
1457 * We can check for this condition when we decode and encode the stuff again.
1459 if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) {
1460 $dsprsig->signature = base64_decode($dsprsig->signature);
1461 logger("Repaired double encoded signature from handle ".$dsprsig->signer, LOGGER_DEBUG);
1464 dba::insert('sign', ['iid' => $current_post, 'signed_text' => $dsprsig->signed_text,
1465 'signature' => $dsprsig->signature, 'signer' => $dsprsig->signer]);
1468 if (!empty($diaspora_signed_text)) {
1469 // Formerly we stored the signed text, the signature and the author in different fields.
1470 // We now store the raw data so that we are more flexible.
1471 dba::insert('sign', ['iid' => $current_post, 'signed_text' => $diaspora_signed_text]);
1474 $deleted = self::tagDeliver($item['uid'], $current_post);
1477 * current post can be deleted if is for a community page and no mention are
1480 if (!$deleted && !$dontcache) {
1481 $posted_item = dba::selectFirst('item', [], ['id' => $current_post]);
1482 if (DBM::is_result($posted_item)) {
1484 Addon::callHooks('post_local_end', $posted_item);
1486 Addon::callHooks('post_remote_end', $posted_item);
1489 logger('new item not found in DB, id ' . $current_post);
1493 if ($item['parent-uri'] === $item['uri']) {
1494 self::addThread($current_post);
1496 self::updateThread($parent_id);
1502 * Due to deadlock issues with the "term" table we are doing these steps after the commit.
1503 * This is not perfect - but a workable solution until we found the reason for the problem.
1505 if (!empty($tags)) {
1506 Term::insertFromTagFieldByItemId($current_post, $tags);
1509 if (array_key_exists('file', $item)) {
1510 Term::insertFromFileFieldByItemId($current_post);
1513 if ($item['parent-uri'] === $item['uri']) {
1514 self::addShadow($current_post);
1516 self::addShadowPost($current_post);
1519 check_user_notification($current_post);
1522 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", $notify_type, $current_post);
1523 } elseif (!empty($parent) && $parent['origin']) {
1524 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "Notifier", "comment-import", $current_post);
1527 return $current_post;
1531 * @brief Insert a new item content entry
1533 * @param array $item The item fields that are to be inserted
1535 private static function insertContent(&$item)
1537 $fields = ['uri' => $item['uri'], 'plink' => $item['plink'],
1538 'uri-plink-hash' => hash('sha1', $item['plink']).hash('sha1', $item['uri'])];
1540 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1541 if (isset($item[$field])) {
1542 $fields[$field] = $item[$field];
1543 unset($item[$field]);
1547 // To avoid timing problems, we are using locks.
1548 $locked = Lock::set('item_insert_content');
1550 logger("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
1553 // Do we already have this content?
1554 $item_content = dba::selectFirst('item-content', ['id'], ['uri' => $item['uri']]);
1555 if (DBM::is_result($item_content)) {
1556 $item['icid'] = $item_content['id'];
1557 logger('Fetched content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
1558 } elseif (dba::insert('item-content', $fields)) {
1559 $item['icid'] = dba::lastInsertId();
1560 logger('Inserted content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
1562 // By setting the ICID value through the worker we should avoid timing problems.
1563 // When the locking works, this shouldn't be needed. But better be prepared.
1564 Worker::add(PRIORITY_HIGH, 'SetItemContentID', $item['uri']);
1565 logger('Could not insert content for URI ' . $item['uri'] . ' - trying asynchronously');
1568 Lock::remove('item_insert_content');
1573 * @brief Set the item content id for a given URI
1575 * @param string $uri The item URI
1577 public static function setICIDforURI($uri)
1579 $item_content = dba::selectFirst('item-content', ['id'], ['uri' => $uri]);
1580 if (DBM::is_result($item_content)) {
1581 dba::update('item', ['icid' => $item_content['id']], ['icid' => 0, 'uri' => $uri]);
1582 logger('Asynchronously set item content id for URI ' . $uri . ' (' . $item_content['id'] . ') - Affected: '. (int)dba::affected_rows());
1584 logger('No item-content found for URI ' . $uri);
1589 * @brief Update existing item content entries
1591 * @param array $item The item fields that are to be changed
1592 * @param array $condition The condition for finding the item content entries
1594 private static function updateContent($item, $condition)
1596 // We have to select only the fields from the "item-content" table
1598 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1599 if (isset($item[$field])) {
1600 $fields[$field] = $item[$field];
1604 if (empty($fields)) {
1608 if (!empty($item['plink'])) {
1609 $fields['uri-plink-hash'] = hash('sha1', $item['plink']) . hash('sha1', $condition['uri']);
1611 // Ensure that we don't delete the plink
1612 unset($fields['plink']);
1615 logger('Update content for URI ' . $condition['uri']);
1617 dba::update('item-content', $fields, $condition, true);
1621 * @brief Distributes public items to the receivers
1623 * @param integer $itemid Item ID that should be added
1624 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
1626 public static function distribute($itemid, $signed_text = '')
1628 $condition = ["`id` IN (SELECT `parent` FROM `item` WHERE `id` = ?)", $itemid];
1629 $parent = dba::selectFirst('item', ['owner-id'], $condition);
1630 if (!DBM::is_result($parent)) {
1634 // Only distribute public items from native networks
1635 $condition = ['id' => $itemid, 'uid' => 0,
1636 'network' => [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""],
1637 'visible' => true, 'deleted' => false, 'moderated' => false, 'private' => false];
1638 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
1639 if (!DBM::is_result($item)) {
1644 unset($item['parent']);
1645 unset($item['mention']);
1646 unset($item['wall']);
1647 unset($item['origin']);
1648 unset($item['starred']);
1652 $condition = ["`nurl` IN (SELECT `nurl` FROM `contact` WHERE `id` = ?) AND `uid` != 0 AND NOT `blocked` AND `rel` IN (?, ?)",
1653 $parent['owner-id'], CONTACT_IS_SHARING, CONTACT_IS_FRIEND];
1654 $contacts = dba::select('contact', ['uid'], $condition);
1655 while ($contact = dba::fetch($contacts)) {
1656 $users[$contact['uid']] = $contact['uid'];
1661 if ($item['uri'] != $item['parent-uri']) {
1662 $parents = dba::select('item', ['uid', 'origin'], ["`uri` = ? AND `uid` != 0", $item['parent-uri']]);
1663 while ($parent = dba::fetch($parents)) {
1664 $users[$parent['uid']] = $parent['uid'];
1665 if ($parent['origin'] && !$item['origin']) {
1666 $origin_uid = $parent['uid'];
1671 foreach ($users as $uid) {
1672 if ($origin_uid == $uid) {
1673 $item['diaspora_signed_text'] = $signed_text;
1675 self::storeForUser($itemid, $item, $uid);
1680 * @brief Store public items for the receivers
1682 * @param integer $itemid Item ID that should be added
1683 * @param array $item The item entry that will be stored
1684 * @param integer $uid The user that will receive the item entry
1686 private static function storeForUser($itemid, $item, $uid)
1688 $item['uid'] = $uid;
1689 $item['origin'] = 0;
1691 if ($item['uri'] == $item['parent-uri']) {
1692 $item['contact-id'] = Contact::getIdForURL($item['owner-link'], $uid);
1694 $item['contact-id'] = Contact::getIdForURL($item['author-link'], $uid);
1697 if (empty($item['contact-id'])) {
1698 $self = dba::selectFirst('contact', ['id'], ['self' => true, 'uid' => $uid]);
1699 if (!DBM::is_result($self)) {
1702 $item['contact-id'] = $self['id'];
1705 if (in_array($item['type'], ["net-comment", "wall-comment"])) {
1706 $item['type'] = 'remote-comment';
1707 } elseif ($item['type'] == 'wall') {
1708 $item['type'] = 'remote';
1711 /// @todo Handling of "event-id"
1714 if ($item['uri'] == $item['parent-uri']) {
1715 $contact = dba::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
1716 if (DBM::is_result($contact)) {
1717 $notify = self::isRemoteSelf($contact, $item);
1721 $distributed = self::insert($item, false, $notify, true);
1723 if (!$distributed) {
1724 logger("Distributed public item " . $itemid . " for user " . $uid . " wasn't stored", LOGGER_DEBUG);
1726 logger("Distributed public item " . $itemid . " for user " . $uid . " with id " . $distributed, LOGGER_DEBUG);
1731 * @brief Add a shadow entry for a given item id that is a thread starter
1733 * We store every public item entry additionally with the user id "0".
1734 * This is used for the community page and for the search.
1735 * It is planned that in the future we will store public item entries only once.
1737 * @param integer $itemid Item ID that should be added
1739 public static function addShadow($itemid)
1741 $fields = ['uid', 'private', 'moderated', 'visible', 'deleted', 'network'];
1742 $condition = ['id' => $itemid, 'parent' => [0, $itemid]];
1743 $item = dba::selectFirst('item', $fields, $condition);
1745 if (!DBM::is_result($item)) {
1749 // is it already a copy?
1750 if (($itemid == 0) || ($item['uid'] == 0)) {
1754 // Is it a visible public post?
1755 if (!$item["visible"] || $item["deleted"] || $item["moderated"] || $item["private"]) {
1759 // is it an entry from a connector? Only add an entry for natively connected networks
1760 if (!in_array($item["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""])) {
1764 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
1766 if (DBM::is_result($item) && ($item["allow_cid"] == '') && ($item["allow_gid"] == '') &&
1767 ($item["deny_cid"] == '') && ($item["deny_gid"] == '')) {
1769 if (!self::exists(['uri' => $item['uri'], 'uid' => 0])) {
1770 // Preparing public shadow (removing user specific data)
1773 unset($item['parent']);
1774 unset($item['wall']);
1775 unset($item['mention']);
1776 unset($item['origin']);
1777 unset($item['starred']);
1778 if ($item['uri'] == $item['parent-uri']) {
1779 $item['contact-id'] = $item['owner-id'];
1781 $item['contact-id'] = $item['author-id'];
1784 if (in_array($item['type'], ["net-comment", "wall-comment"])) {
1785 $item['type'] = 'remote-comment';
1786 } elseif ($item['type'] == 'wall') {
1787 $item['type'] = 'remote';
1790 $public_shadow = self::insert($item, false, false, true);
1792 logger("Stored public shadow for thread ".$itemid." under id ".$public_shadow, LOGGER_DEBUG);
1798 * @brief Add a shadow entry for a given item id that is a comment
1800 * This function does the same like the function above - but for comments
1802 * @param integer $itemid Item ID that should be added
1804 public static function addShadowPost($itemid)
1806 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
1807 if (!DBM::is_result($item)) {
1811 // Is it a toplevel post?
1812 if ($item['id'] == $item['parent']) {
1813 self::addShadow($itemid);
1817 // Is this a shadow entry?
1818 if ($item['uid'] == 0) {
1822 // Is there a shadow parent?
1823 if (!self::exists(['uri' => $item['parent-uri'], 'uid' => 0])) {
1827 // Is there already a shadow entry?
1828 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
1832 // Save "origin" and "parent" state
1833 $origin = $item['origin'];
1834 $parent = $item['parent'];
1836 // Preparing public shadow (removing user specific data)
1839 unset($item['parent']);
1840 unset($item['wall']);
1841 unset($item['mention']);
1842 unset($item['origin']);
1843 unset($item['starred']);
1844 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
1846 if (in_array($item['type'], ["net-comment", "wall-comment"])) {
1847 $item['type'] = 'remote-comment';
1848 } elseif ($item['type'] == 'wall') {
1849 $item['type'] = 'remote';
1852 $public_shadow = self::insert($item, false, false, true);
1854 logger("Stored public shadow for comment ".$item['uri']." under id ".$public_shadow, LOGGER_DEBUG);
1856 // If this was a comment to a Diaspora post we don't get our comment back.
1857 // This means that we have to distribute the comment by ourselves.
1858 if ($origin && self::exists(['id' => $parent, 'network' => NETWORK_DIASPORA])) {
1859 self::distribute($public_shadow);
1864 * Adds a language specification in a "language" element of given $arr.
1865 * Expects "body" element to exist in $arr.
1867 private static function addLanguageToItemArray(&$item)
1869 $naked_body = Text\BBCode::toPlaintext($item['body'], false);
1871 $ld = new Text_LanguageDetect();
1872 $ld->setNameMode(2);
1873 $languages = $ld->detect($naked_body, 3);
1875 if (is_array($languages)) {
1876 $item['language'] = json_encode($languages);
1881 * @brief Creates an unique guid out of a given uri
1883 * @param string $uri uri of an item entry
1884 * @param string $host hostname for the GUID prefix
1885 * @return string unique guid
1887 public static function guidFromUri($uri, $host)
1889 // Our regular guid routine is using this kind of prefix as well
1890 // We have to avoid that different routines could accidentally create the same value
1891 $parsed = parse_url($uri);
1893 // We use a hash of the hostname as prefix for the guid
1894 $guid_prefix = hash("crc32", $host);
1896 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
1897 unset($parsed["scheme"]);
1899 // Glue it together to be able to make a hash from it
1900 $host_id = implode("/", $parsed);
1902 // We could use any hash algorithm since it isn't a security issue
1903 $host_hash = hash("ripemd128", $host_id);
1905 return $guid_prefix.$host_hash;
1909 * generate an unique URI
1911 * @param integer $uid User id
1912 * @param string $guid An existing GUID (Otherwise it will be generated)
1916 public static function newURI($uid, $guid = "")
1919 $guid = get_guid(32);
1922 $hostname = self::getApp()->get_hostname();
1924 $user = dba::selectFirst('user', ['nickname'], ['uid' => $uid]);
1926 $uri = "urn:X-dfrn:" . $hostname . ':' . $user['nickname'] . ':' . $guid;
1932 * @brief Set "success_update" and "last-item" to the date of the last time we heard from this contact
1934 * This can be used to filter for inactive contacts.
1935 * Only do this for public postings to avoid privacy problems, since poco data is public.
1936 * Don't set this value if it isn't from the owner (could be an author that we don't know)
1938 * @param array $arr Contains the just posted item record
1940 private static function updateContact($arr)
1942 // Unarchive the author
1943 $contact = dba::selectFirst('contact', [], ['id' => $arr["author-id"]]);
1944 if (DBM::is_result($contact)) {
1945 Contact::unmarkForArchival($contact);
1948 // Unarchive the contact if it's not our own contact
1949 $contact = dba::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
1950 if (DBM::is_result($contact)) {
1951 Contact::unmarkForArchival($contact);
1954 $update = (!$arr['private'] && (($arr["author-link"] === $arr["owner-link"]) || ($arr["parent-uri"] === $arr["uri"])));
1956 // Is it a forum? Then we don't care about the rules from above
1957 if (!$update && ($arr["network"] == NETWORK_DFRN) && ($arr["parent-uri"] === $arr["uri"])) {
1958 if (dba::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
1964 dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
1965 ['id' => $arr['contact-id']]);
1967 // Now do the same for the system wide contacts with uid=0
1968 if (!$arr['private']) {
1969 dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
1970 ['id' => $arr['owner-id']]);
1972 if ($arr['owner-id'] != $arr['author-id']) {
1973 dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
1974 ['id' => $arr['author-id']]);
1979 public static function setHashtags(&$item)
1982 $tags = get_tags($item["body"]);
1985 if (!count($tags)) {
1989 // This sorting is important when there are hashtags that are part of other hashtags
1990 // Otherwise there could be problems with hashtags like #test and #test2
1993 $URLSearchString = "^\[\]";
1995 // All hashtags should point to the home server if "local_tags" is activated
1996 if (Config::get('system', 'local_tags')) {
1997 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1998 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["body"]);
2000 $item["tag"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2001 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["tag"]);
2004 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
2005 $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2007 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
2010 $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
2012 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
2015 $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
2017 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
2020 // Repair recursive urls
2021 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2022 "#$2", $item["body"]);
2024 foreach ($tags as $tag) {
2025 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=')) {
2029 $basetag = str_replace('_',' ',substr($tag,1));
2031 $newtag = '#[url=' . System::baseUrl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
2033 $item["body"] = str_replace($tag, $newtag, $item["body"]);
2035 if (!stristr($item["tag"], "/search?tag=" . $basetag . "]" . $basetag . "[/url]")) {
2036 if (strlen($item["tag"])) {
2037 $item["tag"] = ','.$item["tag"];
2039 $item["tag"] = $newtag.$item["tag"];
2043 // Convert back the masked hashtags
2044 $item["body"] = str_replace("#", "#", $item["body"]);
2047 public static function getGuidById($id)
2049 $item = dba::selectFirst('item', ['guid'], ['id' => $id]);
2050 if (DBM::is_result($item)) {
2051 return $item['guid'];
2057 public static function getIdAndNickByGuid($guid, $uid = 0)
2063 $uid == local_user();
2066 // Does the given user have this item?
2068 $item = dba::fetch_first("SELECT `item`.`id`, `user`.`nickname` FROM `item`
2069 INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
2070 WHERE `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
2071 AND `item`.`guid` = ? AND `item`.`uid` = ?", $guid, $uid);
2072 if (DBM::is_result($item)) {
2074 $nick = $item["nickname"];
2078 // Or is it anywhere on the server?
2080 $item = dba::fetch_first("SELECT `item`.`id`, `user`.`nickname` FROM `item`
2081 INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
2082 WHERE `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
2083 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
2084 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
2085 AND NOT `item`.`private` AND `item`.`wall`
2086 AND `item`.`guid` = ?", $guid);
2087 if (DBM::is_result($item)) {
2089 $nick = $item["nickname"];
2092 return ["nick" => $nick, "id" => $id];
2096 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
2098 * @param int $item_id
2099 * @return bool true if item was deleted, else false
2101 private static function tagDeliver($uid, $item_id)
2105 $user = dba::selectFirst('user', [], ['uid' => $uid]);
2106 if (!DBM::is_result($user)) {
2110 $community_page = (($user['page-flags'] == PAGE_COMMUNITY) ? true : false);
2111 $prvgroup = (($user['page-flags'] == PAGE_PRVGROUP) ? true : false);
2113 $item = dba::selectFirst('item', [], ['id' => $item_id]);
2114 if (!DBM::is_result($item)) {
2118 $link = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
2121 * Diaspora uses their own hardwired link URL in @-tags
2122 * instead of the one we supply with webfinger
2124 $dlink = normalise_link(System::baseUrl() . '/u/' . $user['nickname']);
2126 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
2128 foreach ($matches as $mtch) {
2129 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
2131 logger('mention found: ' . $mtch[2]);
2137 if (($community_page || $prvgroup) &&
2138 !$item['wall'] && !$item['origin'] && ($item['id'] == $item['parent'])) {
2139 // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
2141 logger("no-mention top-level post to community or private group. delete.");
2142 dba::delete('item', ['id' => $item_id]);
2148 $arr = ['item' => $item, 'user' => $user];
2150 Addon::callHooks('tagged', $arr);
2152 if (!$community_page && !$prvgroup) {
2157 * tgroup delivery - setup a second delivery chain
2158 * prevent delivery looping - only proceed
2159 * if the message originated elsewhere and is a top-level post
2161 if ($item['wall'] || $item['origin'] || ($item['id'] != $item['parent'])) {
2165 // now change this copy of the post to a forum head message and deliver to all the tgroup members
2166 $self = dba::selectFirst('contact', ['id', 'name', 'url', 'thumb'], ['uid' => $uid, 'self' => true]);
2167 if (!DBM::is_result($self)) {
2171 $owner_id = Contact::getIdForURL($self['url']);
2173 // also reset all the privacy bits to the forum default permissions
2175 $private = ($user['allow_cid'] || $user['allow_gid'] || $user['deny_cid'] || $user['deny_gid']) ? 1 : 0;
2177 $forum_mode = ($prvgroup ? 2 : 1);
2179 $fields = ['wall' => true, 'origin' => true, 'forum_mode' => $forum_mode, 'contact-id' => $self['id'],
2180 'owner-id' => $owner_id, 'owner-link' => $self['url'], 'private' => $private, 'allow_cid' => $user['allow_cid'],
2181 'allow_gid' => $user['allow_gid'], 'deny_cid' => $user['deny_cid'], 'deny_gid' => $user['deny_gid']];
2182 dba::update('item', $fields, ['id' => $item_id]);
2184 self::updateThread($item_id);
2186 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', 'tgroup', $item_id);
2189 public static function isRemoteSelf($contact, &$datarray)
2193 if (!$contact['remote_self']) {
2197 // Prevent the forwarding of posts that are forwarded
2198 if ($datarray["extid"] == NETWORK_DFRN) {
2199 logger('Already forwarded', LOGGER_DEBUG);
2203 // Prevent to forward already forwarded posts
2204 if ($datarray["app"] == $a->get_hostname()) {
2205 logger('Already forwarded (second test)', LOGGER_DEBUG);
2209 // Only forward posts
2210 if ($datarray["verb"] != ACTIVITY_POST) {
2211 logger('No post', LOGGER_DEBUG);
2215 if (($contact['network'] != NETWORK_FEED) && $datarray['private']) {
2216 logger('Not public', LOGGER_DEBUG);
2220 $datarray2 = $datarray;
2221 logger('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), LOGGER_DEBUG);
2222 if ($contact['remote_self'] == 2) {
2223 $self = dba::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
2224 ['uid' => $contact['uid'], 'self' => true]);
2225 if (DBM::is_result($self)) {
2226 $datarray['contact-id'] = $self["id"];
2228 $datarray['owner-name'] = $self["name"];
2229 $datarray['owner-link'] = $self["url"];
2230 $datarray['owner-avatar'] = $self["thumb"];
2232 $datarray['author-name'] = $datarray['owner-name'];
2233 $datarray['author-link'] = $datarray['owner-link'];
2234 $datarray['author-avatar'] = $datarray['owner-avatar'];
2236 unset($datarray['created']);
2237 unset($datarray['edited']);
2239 unset($datarray['network']);
2240 unset($datarray['owner-id']);
2241 unset($datarray['author-id']);
2244 if ($contact['network'] != NETWORK_FEED) {
2245 $datarray["guid"] = get_guid(32);
2246 unset($datarray["plink"]);
2247 $datarray["uri"] = self::newURI($contact['uid'], $datarray["guid"]);
2248 $datarray["parent-uri"] = $datarray["uri"];
2249 $datarray["thr-parent"] = $datarray["uri"];
2250 $datarray["extid"] = NETWORK_DFRN;
2251 $urlpart = parse_url($datarray2['author-link']);
2252 $datarray["app"] = $urlpart["host"];
2254 $datarray['private'] = 0;
2258 if ($contact['network'] != NETWORK_FEED) {
2259 // Store the original post
2260 $result = self::insert($datarray2, false, false);
2261 logger('remote-self post original item - Contact '.$contact['url'].' return '.$result.' Item '.print_r($datarray2, true), LOGGER_DEBUG);
2263 $datarray["app"] = "Feed";
2267 // Trigger automatic reactions for addons
2268 $datarray['api_source'] = true;
2270 // We have to tell the hooks who we are - this really should be improved
2271 $_SESSION["authenticated"] = true;
2272 $_SESSION["uid"] = $contact['uid'];
2281 * @param array $item
2285 public static function fixPrivatePhotos($s, $uid, $item = null, $cid = 0)
2287 if (Config::get('system', 'disable_embedded')) {
2291 logger('check for photos', LOGGER_DEBUG);
2292 $site = substr(System::baseUrl(), strpos(System::baseUrl(), '://'));
2297 $img_start = strpos($orig_body, '[img');
2298 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2299 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2301 while (($img_st_close !== false) && ($img_len !== false)) {
2302 $img_st_close++; // make it point to AFTER the closing bracket
2303 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2305 logger('found photo ' . $image, LOGGER_DEBUG);
2307 if (stristr($image, $site . '/photo/')) {
2308 // Only embed locally hosted photos
2310 $i = basename($image);
2311 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2312 $x = strpos($i, '-');
2315 $res = substr($i, $x + 1);
2316 $i = substr($i, 0, $x);
2317 $fields = ['data', 'type', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'];
2318 $photo = dba::selectFirst('photo', $fields, ['resource-id' => $i, 'scale' => $res, 'uid' => $uid]);
2319 if (DBM::is_result($photo)) {
2321 * Check to see if we should replace this photo link with an embedded image
2322 * 1. No need to do so if the photo is public
2323 * 2. If there's a contact-id provided, see if they're in the access list
2324 * for the photo. If so, embed it.
2325 * 3. Otherwise, if we have an item, see if the item permissions match the photo
2326 * permissions, regardless of order but first check to see if they're an exact
2327 * match to save some processing overhead.
2329 if (self::hasPermissions($photo)) {
2331 $recips = self::enumeratePermissions($photo);
2332 if (in_array($cid, $recips)) {
2336 if (self::samePermissions($item, $photo)) {
2342 $data = $photo['data'];
2343 $type = $photo['type'];
2345 // If a custom width and height were specified, apply before embedding
2346 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2347 logger('scaling photo', LOGGER_DEBUG);
2349 $width = intval($match[1]);
2350 $height = intval($match[2]);
2352 $Image = new Image($data, $type);
2353 if ($Image->isValid()) {
2354 $Image->scaleDown(max($width, $height));
2355 $data = $Image->asString();
2356 $type = $Image->getType();
2360 logger('replacing photo', LOGGER_DEBUG);
2361 $image = 'data:' . $type . ';base64,' . base64_encode($data);
2362 logger('replaced: ' . $image, LOGGER_DATA);
2368 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2369 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2370 if ($orig_body === false) {
2374 $img_start = strpos($orig_body, '[img');
2375 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2376 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2379 $new_body = $new_body . $orig_body;
2384 private static function hasPermissions($obj)
2388 x($obj, 'allow_cid')
2390 x($obj, 'allow_gid')
2399 private static function samePermissions($obj1, $obj2)
2401 // first part is easy. Check that these are exactly the same.
2402 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2403 && ($obj1['allow_gid'] == $obj2['allow_gid'])
2404 && ($obj1['deny_cid'] == $obj2['deny_cid'])
2405 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
2409 // This is harder. Parse all the permissions and compare the resulting set.
2410 $recipients1 = self::enumeratePermissions($obj1);
2411 $recipients2 = self::enumeratePermissions($obj2);
2415 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2416 return ($recipients1 == $recipients2);
2419 // returns an array of contact-ids that are allowed to see this object
2420 private static function enumeratePermissions($obj)
2422 $allow_people = expand_acl($obj['allow_cid']);
2423 $allow_groups = Group::expand(expand_acl($obj['allow_gid']));
2424 $deny_people = expand_acl($obj['deny_cid']);
2425 $deny_groups = Group::expand(expand_acl($obj['deny_gid']));
2426 $recipients = array_unique(array_merge($allow_people, $allow_groups));
2427 $deny = array_unique(array_merge($deny_people, $deny_groups));
2428 $recipients = array_diff($recipients, $deny);
2432 public static function getFeedTags($item)
2436 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2438 for ($x = 0; $x < $cnt; $x ++) {
2439 if ($matches[1][$x]) {
2440 $ret[$matches[2][$x]] = ['#', $matches[1][$x], $matches[2][$x]];
2445 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2447 for ($x = 0; $x < $cnt; $x ++) {
2448 if ($matches[1][$x]) {
2449 $ret[] = ['@', $matches[1][$x], $matches[2][$x]];
2456 public static function expire($uid, $days, $network = "", $force = false)
2458 if (!$uid || ($days < 1)) {
2463 * $expire_network_only = save your own wall posts
2464 * and just expire conversations started by others
2466 $expire_network_only = PConfig::get($uid,'expire', 'network_only');
2467 $sql_extra = (intval($expire_network_only) ? " AND wall = 0 " : "");
2469 if ($network != "") {
2470 $sql_extra .= sprintf(" AND network = '%s' ", dbesc($network));
2473 * There is an index "uid_network_received" but not "uid_network_created"
2474 * This avoids the creation of another index just for one purpose.
2475 * And it doesn't really matter wether to look at "received" or "created"
2477 $range = "AND `received` < UTC_TIMESTAMP() - INTERVAL %d DAY ";
2479 $range = "AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY ";
2482 $r = q("SELECT `file`, `resource-id`, `starred`, `type`, `id` FROM `item`
2483 WHERE `uid` = %d $range
2491 if (!DBM::is_result($r)) {
2495 $expire_items = PConfig::get($uid, 'expire', 'items', 1);
2497 // Forcing expiring of items - but not notes and marked items
2499 $expire_items = true;
2502 $expire_notes = PConfig::get($uid, 'expire', 'notes', 1);
2503 $expire_starred = PConfig::get($uid, 'expire', 'starred', 1);
2504 $expire_photos = PConfig::get($uid, 'expire', 'photos', 0);
2506 logger('User '.$uid.': expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
2508 foreach ($r as $item) {
2510 // don't expire filed items
2512 if (strpos($item['file'],'[') !== false) {
2516 // Only expire posts, not photos and photo comments
2518 if ($expire_photos == 0 && strlen($item['resource-id'])) {
2520 } elseif ($expire_starred == 0 && intval($item['starred'])) {
2522 } elseif ($expire_notes == 0 && $item['type'] == 'note') {
2524 } elseif ($expire_items == 0 && $item['type'] != 'note') {
2528 self::deleteById($item['id'], PRIORITY_LOW);
2532 public static function firstPostDate($uid, $wall = false)
2534 $condition = ['uid' => $uid, 'wall' => $wall, 'deleted' => false, 'visible' => true, 'moderated' => false];
2535 $params = ['order' => ['created' => false]];
2536 $thread = dba::selectFirst('thread', ['created'], $condition, $params);
2537 if (DBM::is_result($thread)) {
2538 return substr(DateTimeFormat::local($thread['created']), 0, 10);
2544 * @brief add/remove activity to an item
2546 * Toggle activities as like,dislike,attend of an item
2548 * @param string $item_id
2549 * @param string $verb
2550 * Activity verb. One of
2551 * like, unlike, dislike, undislike, attendyes, unattendyes,
2552 * attendno, unattendno, attendmaybe, unattendmaybe
2553 * @hook 'post_local_end'
2555 * 'post_id' => ID of posted item
2557 public static function performLike($item_id, $verb)
2559 if (!local_user() && !remote_user()) {
2566 $bodyverb = L10n::t('%1$s likes %2$s\'s %3$s');
2567 $activity = ACTIVITY_LIKE;
2571 $bodyverb = L10n::t('%1$s doesn\'t like %2$s\'s %3$s');
2572 $activity = ACTIVITY_DISLIKE;
2576 $bodyverb = L10n::t('%1$s is attending %2$s\'s %3$s');
2577 $activity = ACTIVITY_ATTEND;
2581 $bodyverb = L10n::t('%1$s is not attending %2$s\'s %3$s');
2582 $activity = ACTIVITY_ATTENDNO;
2585 case 'unattendmaybe':
2586 $bodyverb = L10n::t('%1$s may attend %2$s\'s %3$s');
2587 $activity = ACTIVITY_ATTENDMAYBE;
2590 logger('like: unknown verb ' . $verb . ' for item ' . $item_id);
2594 // Enable activity toggling instead of on/off
2595 $event_verb_flag = $activity === ACTIVITY_ATTEND || $activity === ACTIVITY_ATTENDNO || $activity === ACTIVITY_ATTENDMAYBE;
2597 logger('like: verb ' . $verb . ' item ' . $item_id);
2599 $item = dba::selectFirst('item', [], ['`id` = ? OR `uri` = ?', $item_id, $item_id]);
2600 if (!DBM::is_result($item)) {
2601 logger('like: unknown item ' . $item_id);
2605 $uid = $item['uid'];
2606 if (($uid == 0) && local_user()) {
2607 $uid = local_user();
2610 if (!can_write_wall($uid)) {
2611 logger('like: unable to write on wall ' . $uid);
2615 // Retrieves the local post owner
2616 $owner_self_contact = dba::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
2617 if (!DBM::is_result($owner_self_contact)) {
2618 logger('like: unknown owner ' . $uid);
2622 // Retrieve the current logged in user's public contact
2623 $author_id = public_contact();
2625 $author_contact = dba::selectFirst('contact', [], ['id' => $author_id]);
2626 if (!DBM::is_result($author_contact)) {
2627 logger('like: unknown author ' . $author_id);
2631 // Contact-id is the uid-dependant author contact
2632 if (local_user() == $uid) {
2633 $item_contact_id = $owner_self_contact['id'];
2634 $item_contact = $owner_self_contact;
2636 $item_contact_id = Contact::getIdForURL($author_contact['url'], $uid, true);
2637 $item_contact = dba::selectFirst('contact', [], ['id' => $item_contact_id]);
2638 if (!DBM::is_result($item_contact)) {
2639 logger('like: unknown item contact ' . $item_contact_id);
2644 // Look for an existing verb row
2645 // event participation are essentially radio toggles. If you make a subsequent choice,
2646 // we need to eradicate your first choice.
2647 if ($event_verb_flag) {
2648 $verbs = [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE];
2653 $base_condition = ['verb' => $verbs, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY,
2654 'author-id' => $author_contact['id'], 'uid' => item['uid']];
2656 $condition = array_merge($base_condition, ['parent' => $item_id]);
2657 $like_item = self::selectFirst(['id', 'guid', 'verb'], $condition);
2659 if (!DBM::is_result($like_item)) {
2660 $condition = array_merge($base_condition, ['parent-uri' => $item_id]);
2661 $like_item = self::selectFirst(['id', 'guid', 'verb'], $condition);
2664 if (!DBM::is_result($like_item)) {
2665 $condition = array_merge($base_condition, ['thr-parent' => $item_id]);
2666 $like_item = self::selectFirst(['id', 'guid', 'verb'], $condition);
2669 // If it exists, mark it as deleted
2670 if (DBM::is_result($like_item)) {
2671 // Already voted, undo it
2672 $fields = ['deleted' => true, 'unseen' => true, 'changed' => DateTimeFormat::utcNow()];
2673 /// @todo Consider using self::update - but before doing so, check the side effects
2674 dba::update('item', $fields, ['id' => $like_item['id']]);
2676 // Clean up the Diaspora signatures for this like
2677 // Go ahead and do it even if Diaspora support is disabled. We still want to clean up
2678 // if it had been enabled in the past
2679 dba::delete('sign', ['iid' => $like_item['id']]);
2681 $like_item_id = $like_item['id'];
2682 Worker::add(PRIORITY_HIGH, "Notifier", "like", $like_item_id);
2684 if (!$event_verb_flag || $like_item['verb'] == $activity) {
2689 // Verb is "un-something", just trying to delete existing entries
2690 if (strpos($verb, 'un') === 0) {
2694 // Else or if event verb different from existing row, create a new item row
2695 $post_type = (($item['resource-id']) ? L10n::t('photo') : L10n::t('status'));
2696 if ($item['object-type'] === ACTIVITY_OBJ_EVENT) {
2697 $post_type = L10n::t('event');
2699 $objtype = $item['resource-id'] ? ACTIVITY_OBJ_IMAGE : ACTIVITY_OBJ_NOTE ;
2700 $link = xmlify('<link rel="alternate" type="text/html" href="' . System::baseUrl() . '/display/' . $owner_self_contact['nick'] . '/' . $item['id'] . '" />' . "\n") ;
2701 $body = $item['body'];
2706 <type>$objtype</type>
2708 <id>{$item['uri']}</id>
2711 <content>$body</content>
2715 $ulink = '[url=' . $author_contact['url'] . ']' . $author_contact['name'] . '[/url]';
2716 $alink = '[url=' . $item['author-link'] . ']' . $item['author-name'] . '[/url]';
2717 $plink = '[url=' . System::baseUrl() . '/display/' . $owner_self_contact['nick'] . '/' . $item['id'] . ']' . $post_type . '[/url]';
2720 'guid' => get_guid(32),
2721 'uri' => self::newURI($item['uid']),
2722 'uid' => $item['uid'],
2723 'contact-id' => $item_contact_id,
2724 'type' => 'activity',
2725 'wall' => $item['wall'],
2727 'gravity' => GRAVITY_ACTIVITY,
2728 'parent' => $item['id'],
2729 'parent-uri' => $item['uri'],
2730 'thr-parent' => $item['uri'],
2731 'owner-id' => $item['owner-id'],
2732 'owner-name' => $item['owner-name'],
2733 'owner-link' => $item['owner-link'],
2734 'owner-avatar' => $item['owner-avatar'],
2735 'author-id' => $author_contact['id'],
2736 'author-name' => $author_contact['name'],
2737 'author-link' => $author_contact['url'],
2738 'author-avatar' => $author_contact['thumb'],
2739 'body' => sprintf($bodyverb, $ulink, $alink, $plink),
2740 'verb' => $activity,
2741 'object-type' => $objtype,
2743 'allow_cid' => $item['allow_cid'],
2744 'allow_gid' => $item['allow_gid'],
2745 'deny_cid' => $item['deny_cid'],
2746 'deny_gid' => $item['deny_gid'],
2751 $new_item_id = self::insert($new_item);
2753 // If the parent item isn't visible then set it to visible
2754 if (!$item['visible']) {
2755 self::update(['visible' => true], ['id' => $item['id']]);
2758 // Save the author information for the like in case we need to relay to Diaspora
2759 Diaspora::storeLikeSignature($item_contact, $new_item_id);
2761 $new_item['id'] = $new_item_id;
2763 Addon::callHooks('post_local_end', $new_item);
2765 Worker::add(PRIORITY_HIGH, "Notifier", "like", $new_item_id);
2770 private static function addThread($itemid, $onlyshadow = false)
2772 $fields = ['uid', 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private', 'pubmail',
2773 'moderated', 'visible', 'starred', 'bookmark', 'contact-id',
2774 'deleted', 'origin', 'forum_mode', 'mention', 'network', 'author-id', 'owner-id'];
2775 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
2776 $item = dba::selectFirst('item', $fields, $condition);
2778 if (!DBM::is_result($item)) {
2782 $item['iid'] = $itemid;
2785 $result = dba::insert('thread', $item);
2787 logger("Add thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
2791 private static function updateThread($itemid, $setmention = false)
2793 $fields = ['uid', 'guid', 'created', 'edited', 'commented', 'received', 'changed',
2794 'wall', 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark', 'contact-id',
2795 'deleted', 'origin', 'forum_mode', 'network', 'author-id', 'owner-id'];
2796 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
2798 $item = dba::selectFirst('item', $fields, $condition);
2799 if (!DBM::is_result($item)) {
2804 $item["mention"] = 1;
2811 foreach ($item as $field => $data) {
2812 if (!in_array($field, ["guid"])) {
2813 $fields[$field] = $data;
2817 $result = dba::update('thread', $fields, ['iid' => $itemid]);
2819 logger("Update thread for item ".$itemid." - guid ".$item["guid"]." - ".(int)$result, LOGGER_DEBUG);
2822 private static function deleteThread($itemid, $itemuri = "")
2824 $item = dba::selectFirst('thread', ['uid'], ['iid' => $itemid]);
2825 if (!DBM::is_result($item)) {
2826 logger('No thread found for id '.$itemid, LOGGER_DEBUG);
2830 // Using dba::delete at this time could delete the associated item entries
2831 $result = dba::e("DELETE FROM `thread` WHERE `iid` = ?", $itemid);
2833 logger("deleteThread: Deleted thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
2835 if ($itemuri != "") {
2836 $condition = ["`uri` = ? AND NOT `deleted` AND NOT (`uid` IN (?, 0))", $itemuri, $item["uid"]];
2837 if (!self::exists($condition)) {
2838 dba::delete('item', ['uri' => $itemuri, 'uid' => 0]);
2839 logger("deleteThread: Deleted shadow for item ".$itemuri, LOGGER_DEBUG);