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',
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 CONTENT_FIELDLIST = ['title', 'content-warning', 'body', 'location',
62 'coord', 'app', 'rendered-hash', 'rendered-html', 'verb',
63 'object-type', 'object', 'target-type', 'target', 'plink'];
65 // All fields in the item table
66 const ITEM_FIELDLIST = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
67 'contact-id', 'type', 'wall', 'gravity', 'extid', 'icid',
68 'created', 'edited', 'commented', 'received', 'changed', 'verb',
69 'postopts', 'plink', 'resource-id', 'event-id', 'tag', 'attach', 'inform',
70 'file', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
71 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
72 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global', 'network',
73 'title', 'content-warning', 'body', 'location', 'coord', 'app',
74 'rendered-hash', 'rendered-html', 'object-type', 'object', 'target-type', 'target',
75 'author-id', 'author-link', 'author-name', 'author-avatar',
76 'owner-id', 'owner-link', 'owner-name', 'owner-avatar'];
79 * @brief Fetch a single item row
81 * @param mixed $stmt statement object
82 * @return array current row
84 public static function fetch($stmt)
86 $row = dba::fetch($stmt);
88 // Fetch data from the item-content table whenever there is content there
89 foreach (self::CONTENT_FIELDLIST as $field) {
90 if (empty($row[$field]) && !empty($row['item-' . $field])) {
91 $row[$field] = $row['item-' . $field];
93 unset($row['item-' . $field]);
96 // We prefer the data from the user's contact over the public one
97 if (!empty($row['author-link']) && !empty($row['contact-link']) &&
98 ($row['author-link'] == $row['contact-link'])) {
99 if (isset($row['author-avatar']) && !empty($row['contact-avatar'])) {
100 $row['author-avatar'] = $row['contact-avatar'];
102 if (isset($row['author-name']) && !empty($row['contact-name'])) {
103 $row['author-name'] = $row['contact-name'];
107 if (!empty($row['owner-link']) && !empty($row['contact-link']) &&
108 ($row['owner-link'] == $row['contact-link'])) {
109 if (isset($row['owner-avatar']) && !empty($row['contact-avatar'])) {
110 $row['owner-avatar'] = $row['contact-avatar'];
112 if (isset($row['owner-name']) && !empty($row['contact-name'])) {
113 $row['owner-name'] = $row['contact-name'];
117 // We can always comment on posts from these networks
118 if (isset($row['writable']) && !empty($row['network']) &&
119 in_array($row['network'], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS])) {
120 $row['writable'] = true;
127 * @brief Fills an array with data from an item query
129 * @param object $stmt statement object
130 * @return array Data array
132 public static function inArray($stmt, $do_close = true) {
133 if (is_bool($stmt)) {
138 while ($row = self::fetch($stmt)) {
148 * @brief Check if item data exists
150 * @param array $condition array of fields for condition
152 * @return boolean Are there rows for that condition?
154 public static function exists($condition) {
155 $stmt = self::select(['id'], $condition, ['limit' => 1]);
157 if (is_bool($stmt)) {
160 $retval = (dba::num_rows($stmt) > 0);
169 * Retrieve a single record from the item table for a given user and returns it in an associative array
171 * @brief Retrieve a single record from a table
172 * @param integer $uid User ID
173 * @param array $fields
174 * @param array $condition
175 * @param array $params
179 public static function selectFirstForUser($uid, array $selected = [], array $condition = [], $params = [])
181 $params['uid'] = $uid;
183 if (empty($selected)) {
184 $selected = Item::DISPLAY_FIELDLIST;
187 return self::selectFirst($selected, $condition, $params);
191 * @brief Select rows from the item table for a given user
193 * @param integer $uid User ID
194 * @param array $selected Array of selected fields, empty for all
195 * @param array $condition Array of fields for condition
196 * @param array $params Array of several parameters
198 * @return boolean|object
200 public static function selectForUser($uid, array $selected = [], array $condition = [], $params = [])
202 $params['uid'] = $uid;
204 if (empty($selected)) {
205 $selected = Item::DISPLAY_FIELDLIST;
208 return self::select($selected, $condition, $params);
212 * Retrieve a single record from the item table and returns it in an associative array
214 * @brief Retrieve a single record from a table
215 * @param array $fields
216 * @param array $condition
217 * @param array $params
221 public static function selectFirst(array $fields = [], array $condition = [], $params = [])
223 $params['limit'] = 1;
225 $result = self::select($fields, $condition, $params);
227 if (is_bool($result)) {
230 $row = self::fetch($result);
237 * @brief Select rows from the item table
239 * @param array $selected Array of selected fields, empty for all
240 * @param array $condition Array of fields for condition
241 * @param array $params Array of several parameters
243 * @return boolean|object
245 public static function select(array $selected = [], array $condition = [], $params = [])
250 if (isset($params['uid'])) {
251 $uid = $params['uid'];
255 $fields = self::fieldlist($selected);
257 $select_fields = self::constructSelectFields($fields, $selected);
259 $condition_string = dba::buildCondition($condition);
261 $condition_string = self::addTablesToFields($condition_string, $fields);
264 $condition_string = $condition_string . ' AND ' . self::condition(false);
267 $param_string = self::addTablesToFields(dba::buildParameter($params), $fields);
269 $table = "`item` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, false);
271 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
273 return dba::p($sql, $condition);
277 * @brief Select rows from the starting post in the item table
279 * @param integer $uid User ID
280 * @param array $fields Array of selected fields, empty for all
281 * @param array $condition Array of fields for condition
282 * @param array $params Array of several parameters
284 * @return boolean|object
286 public static function selectThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
288 $params['uid'] = $uid;
290 if (empty($selected)) {
291 $selected = Item::DISPLAY_FIELDLIST;
294 return self::selectThread($selected, $condition, $params);
298 * Retrieve a single record from the starting post in the item table and returns it in an associative array
300 * @brief Retrieve a single record from a table
301 * @param integer $uid User ID
302 * @param array $selected
303 * @param array $condition
304 * @param array $params
308 public static function selectFirstThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
310 $params['uid'] = $uid;
312 if (empty($selected)) {
313 $selected = Item::DISPLAY_FIELDLIST;
316 return self::selectFirstThread($selected, $condition, $params);
320 * Retrieve a single record from the starting post in the item table and returns it in an associative array
322 * @brief Retrieve a single record from a table
323 * @param array $fields
324 * @param array $condition
325 * @param array $params
329 public static function selectFirstThread(array $fields = [], array $condition = [], $params = [])
331 $params['limit'] = 1;
332 $result = self::selectThread($fields, $condition, $params);
334 if (is_bool($result)) {
337 $row = self::fetch($result);
344 * @brief Select rows from the starting post in the item table
346 * @param array $selected Array of selected fields, empty for all
347 * @param array $condition Array of fields for condition
348 * @param array $params Array of several parameters
350 * @return boolean|object
352 public static function selectThread(array $selected = [], array $condition = [], $params = [])
357 if (isset($params['uid'])) {
358 $uid = $params['uid'];
362 $fields = self::fieldlist($selected);
364 $threadfields = ['thread' => ['iid', 'uid', 'contact-id', 'owner-id', 'author-id',
365 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private',
366 'pubmail', 'moderated', 'visible', 'starred', 'ignored', 'bookmark',
367 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'network']];
369 $select_fields = self::constructSelectFields($fields, $selected);
371 $condition_string = dba::buildCondition($condition);
373 $condition_string = self::addTablesToFields($condition_string, $threadfields);
374 $condition_string = self::addTablesToFields($condition_string, $fields);
377 $condition_string = $condition_string . ' AND ' . self::condition(true);
380 $param_string = dba::buildParameter($params);
381 $param_string = self::addTablesToFields($param_string, $threadfields);
382 $param_string = self::addTablesToFields($param_string, $fields);
384 $table = "`thread` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, true);
386 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
388 return dba::p($sql, $condition);
392 * @brief Returns a list of fields that are associated with the item table
394 * @return array field list
396 private static function fieldlist($selected)
400 $fields['item'] = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
401 'contact-id', 'owner-id', 'author-id', 'type', 'wall', 'gravity', 'extid',
402 'created', 'edited', 'commented', 'received', 'changed', 'postopts',
403 'resource-id', 'event-id', 'tag', 'attach', 'inform',
404 'file', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
405 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
406 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global',
407 'id' => 'item_id', 'network', 'icid'];
409 $fields['item-content'] = self::CONTENT_FIELDLIST;
411 $fields['author'] = ['url' => 'author-link', 'name' => 'author-name',
412 'thumb' => 'author-avatar', 'nick' => 'author-nick'];
414 $fields['owner'] = ['url' => 'owner-link', 'name' => 'owner-name',
415 'thumb' => 'owner-avatar', 'nick' => 'owner-nick'];
417 $fields['contact'] = ['url' => 'contact-link', 'name' => 'contact-name', 'thumb' => 'contact-avatar',
418 'writable', 'self', 'id' => 'cid', 'alias', 'uid' => 'contact-uid',
419 'photo', 'name-date', 'uri-date', 'avatar-date', 'thumb', 'dfrn-id'];
421 $fields['parent-item'] = ['guid' => 'parent-guid', 'network' => 'parent-network'];
423 $fields['parent-item-author'] = ['url' => 'parent-author-link', 'name' => 'parent-author-name'];
425 $fields['event'] = ['created' => 'event-created', 'edited' => 'event-edited',
426 'start' => 'event-start','finish' => 'event-finish',
427 'summary' => 'event-summary','desc' => 'event-desc',
428 'location' => 'event-location', 'type' => 'event-type',
429 'nofinish' => 'event-nofinish','adjust' => 'event-adjust',
430 'ignore' => 'event-ignore', 'id' => 'event-id'];
432 $fields['sign'] = ['signed_text', 'signature', 'signer'];
438 * @brief Returns SQL condition for the "select" functions
440 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
442 * @return string SQL condition
444 private static function condition($thread_mode)
447 $master_table = "`thread`";
449 $master_table = "`item`";
451 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`) ";
455 * @brief Returns all needed "JOIN" commands for the "select" functions
457 * @param integer $uid User ID
458 * @param string $sql_commands The parts of the built SQL commands in the "select" functions
459 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
461 * @return string The SQL joins for the "select" functions
463 private static function constructJoins($uid, $sql_commands, $thread_mode)
466 $master_table = "`thread`";
467 $master_table_key = "`thread`.`iid`";
468 $joins = "STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid` ";
470 $master_table = "`item`";
471 $master_table_key = "`item`.`id`";
475 $joins .= sprintf("STRAIGHT_JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`
476 AND NOT `contact`.`blocked`
477 AND ((NOT `contact`.`readonly` AND NOT `contact`.`pending` AND (`contact`.`rel` IN (%s, %s)))
478 OR `contact`.`self` OR (`item`.`id` != `item`.`parent`) OR `contact`.`uid` = 0)
479 STRAIGHT_JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id` AND NOT `author`.`blocked`
480 STRAIGHT_JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id` AND NOT `owner`.`blocked`
481 LEFT JOIN `user-item` ON `user-item`.`iid` = $master_table_key AND `user-item`.`uid` = %d",
482 CONTACT_IS_SHARING, CONTACT_IS_FRIEND, intval($uid));
484 if (strpos($sql_commands, "`group_member`.") !== false) {
485 $joins .= " STRAIGHT_JOIN `group_member` ON `group_member`.`contact-id` = $master_table.`contact-id`";
488 if (strpos($sql_commands, "`user`.") !== false) {
489 $joins .= " STRAIGHT_JOIN `user` ON `user`.`uid` = $master_table.`uid`";
492 if (strpos($sql_commands, "`event`.") !== false) {
493 $joins .= " LEFT JOIN `event` ON `event-id` = `event`.`id`";
496 if (strpos($sql_commands, "`sign`.") !== false) {
497 $joins .= " LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`";
500 if (strpos($sql_commands, "`item-content`.") !== false) {
501 $joins .= " LEFT JOIN `item-content` ON `item-content`.`id` = `item`.`icid`";
504 if ((strpos($sql_commands, "`parent-item`.") !== false) || (strpos($sql_commands, "`parent-author`.") !== false)) {
505 $joins .= " STRAIGHT_JOIN `item` AS `parent-item` ON `parent-item`.`id` = `item`.`parent`";
508 if (strpos($sql_commands, "`parent-item-author`.") !== false) {
509 $joins .= " STRAIGHT_JOIN `contact` AS `parent-item-author` ON `parent-item-author`.`id` = `parent-item`.`author-id`";
516 * @brief Add the field list for the "select" functions
518 * @param array $fields The field definition array
519 * @param array $selected The array with the selected fields from the "select" functions
521 * @return string The field list
523 private static function constructSelectFields($fields, $selected)
526 foreach ($fields as $table => $table_fields) {
527 foreach ($table_fields as $field => $select) {
528 if (empty($selected) || in_array($select, $selected)) {
529 if (in_array($select, self::CONTENT_FIELDLIST)) {
530 $selection[] = "`item`.`".$select."` AS `item-" . $select . "`";
532 if (is_int($field)) {
533 $selection[] = "`" . $table . "`.`" . $select . "`";
535 $selection[] = "`" . $table . "`.`" . $field . "` AS `" . $select . "`";
540 return implode(", ", $selection);
544 * @brief add table definition to fields in an SQL query
546 * @param string $query SQL query
547 * @param array $fields The field definition array
549 * @return string the changed SQL query
551 private static function addTablesToFields($query, $fields)
553 foreach ($fields as $table => $table_fields) {
554 foreach ($table_fields as $alias => $field) {
555 if (is_int($alias)) {
556 $replace_field = $field;
558 $replace_field = $alias;
561 $search = "/([^\.])`" . $field . "`/i";
562 $replace = "$1`" . $table . "`.`" . $replace_field . "`";
563 $query = preg_replace($search, $replace, $query);
570 * @brief Update existing item entries
572 * @param array $fields The fields that are to be changed
573 * @param array $condition The condition for finding the item entries
575 * In the future we may have to change permissions as well.
576 * Then we had to add the user id as third parameter.
578 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
580 * @return integer|boolean number of affected rows - or "false" if there was an error
582 public static function update(array $fields, array $condition)
584 if (empty($condition) || empty($fields)) {
588 // To ensure the data integrity we do it in an transaction
591 // We cannot simply expand the condition to check for origin entries
592 // The condition needn't to be a simple array but could be a complex condition.
593 // And we have to execute this query before the update to ensure to fetch the same data.
594 $items = dba::select('item', ['id', 'origin', 'uri', 'plink'], $condition);
596 $content_fields = [];
597 foreach (self::CONTENT_FIELDLIST as $field) {
598 if (isset($fields[$field])) {
599 $content_fields[$field] = $fields[$field];
600 unset($fields[$field]);
604 if (!empty($fields)) {
605 $success = dba::update('item', $fields, $condition);
614 // When there is no content for the "old" item table, this will count the fetched items
615 $rows = dba::affected_rows();
617 while ($item = dba::fetch($items)) {
618 if (!empty($item['plink'])) {
619 $content_fields['plink'] = $item['plink'];
621 self::updateContent($content_fields, ['uri' => $item['uri']]);
622 Term::insertFromTagFieldByItemId($item['id']);
623 Term::insertFromFileFieldByItemId($item['id']);
624 self::updateThread($item['id']);
626 // We only need to notfiy others when it is an original entry from us.
627 // Only call the notifier when the item has some content relevant change.
628 if ($item['origin'] && in_array('edited', array_keys($fields))) {
629 Worker::add(PRIORITY_HIGH, "Notifier", 'edit_post', $item['id']);
639 * @brief Delete an item and notify others about it - if it was ours
641 * @param array $condition The condition for finding the item entries
642 * @param integer $priority Priority for the notification
644 public static function delete($condition, $priority = PRIORITY_HIGH)
646 $items = dba::select('item', ['id'], $condition);
647 while ($item = dba::fetch($items)) {
648 self::deleteById($item['id'], $priority);
654 * @brief Delete an item for an user and notify others about it - if it was ours
656 * @param array $condition The condition for finding the item entries
657 * @param integer $uid User who wants to delete this item
659 public static function deleteForUser($condition, $uid)
665 $items = dba::select('item', ['id', 'uid'], $condition);
666 while ($item = dba::fetch($items)) {
667 // "Deleting" global items just means hiding them
668 if ($item['uid'] == 0) {
669 dba::update('user-item', ['hidden' => true], ['iid' => $item['id'], 'uid' => $uid], true);
670 } elseif ($item['uid'] == $uid) {
671 self::deleteById($item['id'], PRIORITY_HIGH);
673 logger('Wrong ownership. Not deleting item ' . $item['id']);
680 * @brief Delete an item and notify others about it - if it was ours
682 * @param integer $item_id Item ID that should be delete
683 * @param integer $priority Priority for the notification
685 * @return boolean success
687 private static function deleteById($item_id, $priority = PRIORITY_HIGH)
689 // locate item to be deleted
690 $fields = ['id', 'uri', 'uid', 'parent', 'parent-uri', 'origin',
691 'deleted', 'file', 'resource-id', 'event-id', 'attach',
692 'verb', 'object-type', 'object', 'target', 'contact-id'];
693 $item = dba::selectFirst('item', $fields, ['id' => $item_id]);
694 if (!DBM::is_result($item)) {
695 logger('Item with ID ' . $item_id . " hasn't been found.", LOGGER_DEBUG);
699 if ($item['deleted']) {
700 logger('Item with ID ' . $item_id . ' has already been deleted.', LOGGER_DEBUG);
704 $parent = dba::selectFirst('item', ['origin'], ['id' => $item['parent']]);
705 if (!DBM::is_result($parent)) {
706 $parent = ['origin' => false];
709 // clean up categories and tags so they don't end up as orphans
712 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
714 foreach ($matches as $mtch) {
715 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],true);
721 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
723 foreach ($matches as $mtch) {
724 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],false);
729 * If item is a link to a photo resource, nuke all the associated photos
730 * (visitors will not have photo resources)
731 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
732 * generate a resource-id and therefore aren't intimately linked to the item.
734 if (strlen($item['resource-id'])) {
735 dba::delete('photo', ['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
738 // If item is a link to an event, delete the event.
739 if (intval($item['event-id'])) {
740 Event::delete($item['event-id']);
743 // If item has attachments, drop them
744 foreach (explode(", ", $item['attach']) as $attach) {
745 preg_match("|attach/(\d+)|", $attach, $matches);
746 dba::delete('attach', ['id' => $matches[1], 'uid' => $item['uid']]);
749 // Delete tags that had been attached to other items
750 self::deleteTagsFromItem($item);
752 // Set the item to "deleted"
753 // This erasing of item content is superfluous for items with a matching item-content.
754 // But for the next time we will still have old content in the item table.
755 $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow(),
756 'body' => '', 'title' => '', 'content-warning' => '', 'rendered-hash' => '', 'rendered-html' => '',
757 'object' => '', 'target' => '', 'tag' => '', 'postopts' => '', 'attach' => '', 'file' => ''];
758 dba::update('item', $item_fields, ['id' => $item['id']]);
760 Term::insertFromTagFieldByItemId($item['id']);
761 Term::insertFromFileFieldByItemId($item['id']);
762 self::deleteThread($item['id'], $item['parent-uri']);
764 if (!self::exists(["`uri` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri']])) {
765 self::delete(['uri' => $item['uri'], 'uid' => 0, 'deleted' => false], $priority);
768 // If it's the parent of a comment thread, kill all the kids
769 if ($item['id'] == $item['parent']) {
770 self::delete(['parent' => $item['parent'], 'deleted' => false], $priority);
773 // Is it our comment and/or our thread?
774 if ($item['origin'] || $parent['origin']) {
776 // When we delete the original post we will delete all existing copies on the server as well
777 self::delete(['uri' => $item['uri'], 'deleted' => false], $priority);
779 // send the notification upstream/downstream
780 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", "drop", intval($item['id']));
781 } elseif ($item['uid'] != 0) {
783 // When we delete just our local user copy of an item, we have to set a marker to hide it
784 $global_item = dba::selectFirst('item', ['id'], ['uri' => $item['uri'], 'uid' => 0, 'deleted' => false]);
785 if (DBM::is_result($global_item)) {
786 dba::update('user-item', ['hidden' => true], ['iid' => $global_item['id'], 'uid' => $item['uid']], true);
790 logger('Item with ID ' . $item_id . " has been deleted.", LOGGER_DEBUG);
795 private static function deleteTagsFromItem($item)
797 if (($item["verb"] != ACTIVITY_TAG) || ($item["object-type"] != ACTIVITY_OBJ_TAGTERM)) {
801 $xo = XML::parseString($item["object"], false);
802 $xt = XML::parseString($item["target"], false);
804 if ($xt->type != ACTIVITY_OBJ_NOTE) {
808 $i = dba::selectFirst('item', ['id', 'contact-id', 'tag'], ['uri' => $xt->id, 'uid' => $item['uid']]);
809 if (!DBM::is_result($i)) {
813 // For tags, the owner cannot remove the tag on the author's copy of the post.
814 $owner_remove = ($item["contact-id"] == $i["contact-id"]);
815 $author_copy = $item["origin"];
817 if (($owner_remove && $author_copy) || !$owner_remove) {
821 $tags = explode(',', $i["tag"]);
824 foreach ($tags as $tag) {
825 if (trim($tag) !== trim($xo->body)) {
826 $newtags[] = trim($tag);
830 self::update(['tag' => implode(',', $newtags)], ['id' => $i["id"]]);
833 private static function guid($item, $notify)
835 $guid = notags(trim($item['guid']));
842 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
843 // We add the hash of our own host because our host is the original creator of the post.
844 $prefix_host = get_app()->get_hostname();
848 // We are only storing the post so we create a GUID from the original hostname.
849 if (!empty($item['author-link'])) {
850 $parsed = parse_url($item['author-link']);
851 if (!empty($parsed['host'])) {
852 $prefix_host = $parsed['host'];
856 if (empty($prefix_host) && !empty($item['plink'])) {
857 $parsed = parse_url($item['plink']);
858 if (!empty($parsed['host'])) {
859 $prefix_host = $parsed['host'];
863 if (empty($prefix_host) && !empty($item['uri'])) {
864 $parsed = parse_url($item['uri']);
865 if (!empty($parsed['host'])) {
866 $prefix_host = $parsed['host'];
870 // Is it in the format data@host.tld? - Used for mail contacts
871 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
872 $mailparts = explode('@', $item['author-link']);
873 $prefix_host = array_pop($mailparts);
877 if (!empty($item['plink'])) {
878 $guid = self::guidFromUri($item['plink'], $prefix_host);
879 } elseif (!empty($item['uri'])) {
880 $guid = self::guidFromUri($item['uri'], $prefix_host);
882 $guid = get_guid(32, hash('crc32', $prefix_host));
888 private static function contactId($item)
890 $contact_id = (int)$item["contact-id"];
892 if (!empty($contact_id)) {
895 logger('Missing contact-id. Called by: '.System::callstack(), LOGGER_DEBUG);
897 * First we are looking for a suitable contact that matches with the author of the post
898 * This is done only for comments
900 if ($item['parent-uri'] != $item['uri']) {
901 $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
904 // If not present then maybe the owner was found
905 if ($contact_id == 0) {
906 $contact_id = Contact::getIdForURL($item['owner-link'], $item['uid']);
909 // Still missing? Then use the "self" contact of the current user
910 if ($contact_id == 0) {
911 $self = dba::selectFirst('contact', ['id'], ['self' => true, 'uid' => $item['uid']]);
912 if (DBM::is_result($self)) {
913 $contact_id = $self["id"];
916 logger("Contact-id was missing for post ".$item['guid']." from user id ".$item['uid']." - now set to ".$contact_id, LOGGER_DEBUG);
921 public static function insert($item, $force_parent = false, $notify = false, $dontcache = false)
925 // If it is a posting where users should get notifications, then define it as wall posting
928 $item['type'] = 'wall';
930 $item['network'] = NETWORK_DFRN;
931 $item['protocol'] = PROTOCOL_DFRN;
933 if (is_int($notify)) {
936 $priority = PRIORITY_HIGH;
939 $item['network'] = trim(defaults($item, 'network', NETWORK_PHANTOM));
942 $item['guid'] = self::guid($item, $notify);
943 $item['uri'] = notags(trim(defaults($item, 'uri', self::newURI($item['uid'], $item['guid']))));
945 // Store conversation data
946 $item = Conversation::insert($item);
949 * If a Diaspora signature structure was passed in, pull it out of the
950 * item array and set it aside for later storage.
954 if (x($item, 'dsprsig')) {
955 $encoded_signature = $item['dsprsig'];
956 $dsprsig = json_decode(base64_decode($item['dsprsig']));
957 unset($item['dsprsig']);
960 if (!empty($item['diaspora_signed_text'])) {
961 $diaspora_signed_text = $item['diaspora_signed_text'];
962 unset($item['diaspora_signed_text']);
964 $diaspora_signed_text = '';
967 // Converting the plink
968 /// @TODO Check if this is really still needed
969 if ($item['network'] == NETWORK_OSTATUS) {
970 if (isset($item['plink'])) {
971 $item['plink'] = OStatus::convertHref($item['plink']);
972 } elseif (isset($item['uri'])) {
973 $item['plink'] = OStatus::convertHref($item['uri']);
977 if (!empty($item['thr-parent'])) {
978 $item['parent-uri'] = $item['thr-parent'];
981 $item['type'] = defaults($item, 'type', 'remote');
983 if (isset($item['gravity'])) {
984 $item['gravity'] = intval($item['gravity']);
985 } elseif ($item['parent-uri'] === $item['uri']) {
986 $item['gravity'] = GRAVITY_PARENT;
987 } elseif (activity_match($item['verb'], ACTIVITY_POST)) {
988 $item['gravity'] = GRAVITY_COMMENT;
989 } elseif ($item['type'] == 'activity') {
990 $item['gravity'] = GRAVITY_ACTIVITY;
992 $item['gravity'] = GRAVITY_UNKNOWN; // Should not happen
993 logger('Unknown gravity for verb: ' . $item['verb'] . ' - type: ' . $item['type'], LOGGER_DEBUG);
996 $uid = intval($item['uid']);
998 // check for create date and expire time
999 $expire_interval = Config::get('system', 'dbclean-expire-days', 0);
1001 $user = dba::selectFirst('user', ['expire'], ['uid' => $uid]);
1002 if (DBM::is_result($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
1003 $expire_interval = $user['expire'];
1006 if (($expire_interval > 0) && !empty($item['created'])) {
1007 $expire_date = time() - ($expire_interval * 86400);
1008 $created_date = strtotime($item['created']);
1009 if ($created_date < $expire_date) {
1010 logger('item-store: item created ('.date('c', $created_date).') before expiration time ('.date('c', $expire_date).'). ignored. ' . print_r($item,true), LOGGER_DEBUG);
1016 * Do we already have this item?
1017 * We have to check several networks since Friendica posts could be repeated
1018 * via OStatus (maybe Diasporsa as well)
1020 if (in_array($item['network'], [NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS, ""])) {
1021 $condition = ["`uri` = ? AND `uid` = ? AND `network` IN (?, ?, ?)",
1022 trim($item['uri']), $item['uid'],
1023 NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS];
1024 $existing = dba::selectFirst('item', ['id', 'network'], $condition);
1025 if (DBM::is_result($existing)) {
1026 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
1028 logger("Item with uri ".$item['uri']." already existed for user ".$uid." with id ".$existing["id"]." target network ".$existing["network"]." - new network: ".$item['network']);
1031 return $existing["id"];
1035 self::addLanguageInPostopts($item);
1037 $item['wall'] = intval(defaults($item, 'wall', 0));
1038 $item['extid'] = trim(defaults($item, 'extid', ''));
1039 $item['author-name'] = trim(defaults($item, 'author-name', ''));
1040 $item['author-link'] = trim(defaults($item, 'author-link', ''));
1041 $item['author-avatar'] = trim(defaults($item, 'author-avatar', ''));
1042 $item['owner-name'] = trim(defaults($item, 'owner-name', ''));
1043 $item['owner-link'] = trim(defaults($item, 'owner-link', ''));
1044 $item['owner-avatar'] = trim(defaults($item, 'owner-avatar', ''));
1045 $item['received'] = ((x($item, 'received') !== false) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
1046 $item['created'] = ((x($item, 'created') !== false) ? DateTimeFormat::utc($item['created']) : $item['received']);
1047 $item['edited'] = ((x($item, 'edited') !== false) ? DateTimeFormat::utc($item['edited']) : $item['created']);
1048 $item['changed'] = ((x($item, 'changed') !== false) ? DateTimeFormat::utc($item['changed']) : $item['created']);
1049 $item['commented'] = ((x($item, 'commented') !== false) ? DateTimeFormat::utc($item['commented']) : $item['created']);
1050 $item['title'] = trim(defaults($item, 'title', ''));
1051 $item['location'] = trim(defaults($item, 'location', ''));
1052 $item['coord'] = trim(defaults($item, 'coord', ''));
1053 $item['visible'] = ((x($item, 'visible') !== false) ? intval($item['visible']) : 1);
1054 $item['deleted'] = 0;
1055 $item['parent-uri'] = trim(defaults($item, 'parent-uri', $item['uri']));
1056 $item['verb'] = trim(defaults($item, 'verb', ''));
1057 $item['object-type'] = trim(defaults($item, 'object-type', ''));
1058 $item['object'] = trim(defaults($item, 'object', ''));
1059 $item['target-type'] = trim(defaults($item, 'target-type', ''));
1060 $item['target'] = trim(defaults($item, 'target', ''));
1061 $item['plink'] = trim(defaults($item, 'plink', ''));
1062 $item['allow_cid'] = trim(defaults($item, 'allow_cid', ''));
1063 $item['allow_gid'] = trim(defaults($item, 'allow_gid', ''));
1064 $item['deny_cid'] = trim(defaults($item, 'deny_cid', ''));
1065 $item['deny_gid'] = trim(defaults($item, 'deny_gid', ''));
1066 $item['private'] = intval(defaults($item, 'private', 0));
1067 $item['bookmark'] = intval(defaults($item, 'bookmark', 0));
1068 $item['body'] = trim(defaults($item, 'body', ''));
1069 $item['tag'] = trim(defaults($item, 'tag', ''));
1070 $item['attach'] = trim(defaults($item, 'attach', ''));
1071 $item['app'] = trim(defaults($item, 'app', ''));
1072 $item['origin'] = intval(defaults($item, 'origin', 0));
1073 $item['postopts'] = trim(defaults($item, 'postopts', ''));
1074 $item['resource-id'] = trim(defaults($item, 'resource-id', ''));
1075 $item['event-id'] = intval(defaults($item, 'event-id', 0));
1076 $item['inform'] = trim(defaults($item, 'inform', ''));
1077 $item['file'] = trim(defaults($item, 'file', ''));
1079 // When there is no content then we don't post it
1080 if ($item['body'].$item['title'] == '') {
1081 logger('No body, no title.');
1085 // Items cannot be stored before they happen ...
1086 if ($item['created'] > DateTimeFormat::utcNow()) {
1087 $item['created'] = DateTimeFormat::utcNow();
1090 // We haven't invented time travel by now.
1091 if ($item['edited'] > DateTimeFormat::utcNow()) {
1092 $item['edited'] = DateTimeFormat::utcNow();
1095 if (($item['author-link'] == "") && ($item['owner-link'] == "")) {
1096 logger("Both author-link and owner-link are empty. Called by: " . System::callstack(), LOGGER_DEBUG);
1099 $item['plink'] = defaults($item, 'plink', System::baseUrl() . '/display/' . urlencode($item['guid']));
1101 // The contact-id should be set before "self::insert" was called - but there seems to be issues sometimes
1102 $item["contact-id"] = self::contactId($item);
1104 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
1105 'photo' => $item['author-avatar'], 'network' => $item['network']];
1107 $item['author-id'] = defaults($item, 'author-id', Contact::getIdForURL($item["author-link"], 0, false, $default));
1109 if (Contact::isBlocked($item["author-id"])) {
1110 logger('Contact '.$item["author-id"].' is blocked, item '.$item["uri"].' will not be stored');
1114 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
1115 'photo' => $item['owner-avatar'], 'network' => $item['network']];
1117 $item['owner-id'] = defaults($item, 'owner-id', Contact::getIdForURL($item["owner-link"], 0, false, $default));
1119 if (Contact::isBlocked($item["owner-id"])) {
1120 logger('Contact '.$item["owner-id"].' is blocked, item '.$item["uri"].' will not be stored');
1124 // These fields aren't stored anymore in the item table, they are fetched upon request
1125 unset($item['author-link']);
1126 unset($item['author-name']);
1127 unset($item['author-avatar']);
1129 unset($item['owner-link']);
1130 unset($item['owner-name']);
1131 unset($item['owner-avatar']);
1133 if ($item['network'] == NETWORK_PHANTOM) {
1134 logger('Missing network. Called by: '.System::callstack(), LOGGER_DEBUG);
1136 $contact = Contact::getDetailsByURL($item['author-link'], $item['uid']);
1137 if (!empty($contact['network'])) {
1138 $item['network'] = $contact["network"];
1140 $item['network'] = NETWORK_DFRN;
1142 logger("Set network to " . $item["network"] . " for " . $item["uri"], LOGGER_DEBUG);
1145 // Checking if there is already an item with the same guid
1146 logger('Checking for an item for user '.$item['uid'].' on network '.$item['network'].' with the guid '.$item['guid'], LOGGER_DEBUG);
1147 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
1148 if (self::exists($condition)) {
1149 logger('found item with guid '.$item['guid'].' for user '.$item['uid'].' on network '.$item['network'], LOGGER_DEBUG);
1153 // Check for hashtags in the body and repair or add hashtag links
1154 self::setHashtags($item);
1156 $item['thr-parent'] = $item['parent-uri'];
1164 if ($item['parent-uri'] === $item['uri']) {
1166 $parent_deleted = 0;
1167 $allow_cid = $item['allow_cid'];
1168 $allow_gid = $item['allow_gid'];
1169 $deny_cid = $item['deny_cid'];
1170 $deny_gid = $item['deny_gid'];
1171 $notify_type = 'wall-new';
1173 // find the parent and snarf the item id and ACLs
1174 // and anything else we need to inherit
1176 $fields = ['uri', 'parent-uri', 'id', 'deleted',
1177 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
1178 'wall', 'private', 'forum_mode', 'origin'];
1179 $condition = ['uri' => $item['parent-uri'], 'uid' => $item['uid']];
1180 $params = ['order' => ['id' => false]];
1181 $parent = dba::selectFirst('item', $fields, $condition, $params);
1183 if (DBM::is_result($parent)) {
1184 // is the new message multi-level threaded?
1185 // even though we don't support it now, preserve the info
1186 // and re-attach to the conversation parent.
1188 if ($parent['uri'] != $parent['parent-uri']) {
1189 $item['parent-uri'] = $parent['parent-uri'];
1191 $condition = ['uri' => $item['parent-uri'],
1192 'parent-uri' => $item['parent-uri'],
1193 'uid' => $item['uid']];
1194 $params = ['order' => ['id' => false]];
1195 $toplevel_parent = dba::selectFirst('item', $fields, $condition, $params);
1197 if (DBM::is_result($toplevel_parent)) {
1198 $parent = $toplevel_parent;
1202 $parent_id = $parent['id'];
1203 $parent_deleted = $parent['deleted'];
1204 $allow_cid = $parent['allow_cid'];
1205 $allow_gid = $parent['allow_gid'];
1206 $deny_cid = $parent['deny_cid'];
1207 $deny_gid = $parent['deny_gid'];
1208 $item['wall'] = $parent['wall'];
1209 $notify_type = 'comment-new';
1212 * If the parent is private, force privacy for the entire conversation
1213 * This differs from the above settings as it subtly allows comments from
1214 * email correspondents to be private even if the overall thread is not.
1216 if ($parent['private']) {
1217 $item['private'] = $parent['private'];
1221 * Edge case. We host a public forum that was originally posted to privately.
1222 * The original author commented, but as this is a comment, the permissions
1223 * weren't fixed up so it will still show the comment as private unless we fix it here.
1225 if ((intval($parent['forum_mode']) == 1) && $parent['private']) {
1226 $item['private'] = 0;
1229 // If its a post from myself then tag the thread as "mention"
1230 logger("Checking if parent ".$parent_id." has to be tagged as mention for user ".$item['uid'], LOGGER_DEBUG);
1231 $user = dba::selectFirst('user', ['nickname'], ['uid' => $item['uid']]);
1232 if (DBM::is_result($user)) {
1233 $self = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
1234 $self_id = Contact::getIdForURL($self, 0, true);
1235 logger("'myself' is ".$self_id." for parent ".$parent_id." checking against ".$item['author-id']." and ".$item['owner-id'], LOGGER_DEBUG);
1236 if (($item['author-id'] == $self_id) || ($item['owner-id'] == $self_id)) {
1237 dba::update('thread', ['mention' => true], ['iid' => $parent_id]);
1238 logger("tagged thread ".$parent_id." as mention for user ".$self, LOGGER_DEBUG);
1243 * Allow one to see reply tweets from status.net even when
1244 * we don't have or can't see the original post.
1246 if ($force_parent) {
1247 logger('$force_parent=true, reply converted to top-level post.');
1249 $item['parent-uri'] = $item['uri'];
1250 $item['gravity'] = GRAVITY_PARENT;
1252 logger('item parent '.$item['parent-uri'].' for '.$item['uid'].' was not found - ignoring item');
1256 $parent_deleted = 0;
1260 $condition = ["`uri` = ? AND `network` IN (?, ?) AND `uid` = ?",
1261 $item['uri'], $item['network'], NETWORK_DFRN, $item['uid']];
1262 if (self::exists($condition)) {
1263 logger('duplicated item with the same uri found. '.print_r($item,true));
1267 // On Friendica and Diaspora the GUID is unique
1268 if (in_array($item['network'], [NETWORK_DFRN, NETWORK_DIASPORA])) {
1269 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
1270 if (self::exists($condition)) {
1271 logger('duplicated item with the same guid found. '.print_r($item,true));
1275 // Check for an existing post with the same content. There seems to be a problem with OStatus.
1276 $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
1277 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
1278 if (self::exists($condition)) {
1279 logger('duplicated item with the same body found. '.print_r($item,true));
1284 // Is this item available in the global items (with uid=0)?
1285 if ($item["uid"] == 0) {
1286 $item["global"] = true;
1288 // Set the global flag on all items if this was a global item entry
1289 dba::update('item', ['global' => true], ['uri' => $item["uri"]]);
1291 $item["global"] = self::exists(['uid' => 0, 'uri' => $item["uri"]]);
1295 if (strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid)) {
1298 $private = $item['private'];
1301 $item["allow_cid"] = $allow_cid;
1302 $item["allow_gid"] = $allow_gid;
1303 $item["deny_cid"] = $deny_cid;
1304 $item["deny_gid"] = $deny_gid;
1305 $item["private"] = $private;
1306 $item["deleted"] = $parent_deleted;
1308 // Fill the cache field
1309 put_item_in_cache($item);
1312 Addon::callHooks('post_local', $item);
1314 Addon::callHooks('post_remote', $item);
1317 // This array field is used to trigger some automatic reactions
1318 // It is mainly used in the "post_local" hook.
1319 unset($item['api_source']);
1321 if (x($item, 'cancel')) {
1322 logger('post cancelled by addon.');
1327 * Check for already added items.
1328 * There is a timing issue here that sometimes creates double postings.
1329 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
1331 if ($item["uid"] == 0) {
1332 if (self::exists(['uri' => trim($item['uri']), 'uid' => 0])) {
1333 logger('Global item already stored. URI: '.$item['uri'].' on network '.$item['network'], LOGGER_DEBUG);
1338 logger('' . print_r($item,true), LOGGER_DATA);
1340 // We are doing this outside of the transaction to avoid timing problems
1341 self::insertContent($item);
1344 $ret = dba::insert('item', $item);
1346 // When the item was successfully stored we fetch the ID of the item.
1347 if (DBM::is_result($ret)) {
1348 $current_post = dba::lastInsertId();
1350 // This can happen - for example - if there are locking timeouts.
1353 // Store the data into a spool file so that we can try again later.
1355 // At first we restore the Diaspora signature that we removed above.
1356 if (isset($encoded_signature)) {
1357 $item['dsprsig'] = $encoded_signature;
1360 // Now we store the data in the spool directory
1361 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
1362 $file = 'item-'.round(microtime(true) * 10000).'-'.mt_rand().'.msg';
1364 $spoolpath = get_spoolpath();
1365 if ($spoolpath != "") {
1366 $spool = $spoolpath.'/'.$file;
1367 file_put_contents($spool, json_encode($item));
1368 logger("Item wasn't stored - Item was spooled into file ".$file, LOGGER_DEBUG);
1373 if ($current_post == 0) {
1374 // This is one of these error messages that never should occur.
1375 logger("couldn't find created item - we better quit now.");
1380 // How much entries have we created?
1381 // We wouldn't need this query when we could use an unique index - but MySQL has length problems with them.
1382 $entries = dba::count('item', ['uri' => $item['uri'], 'uid' => $item['uid'], 'network' => $item['network']]);
1385 // There are duplicates. We delete our just created entry.
1386 logger('Duplicated post occurred. uri = ' . $item['uri'] . ' uid = ' . $item['uid']);
1388 // Yes, we could do a rollback here - but we are having many users with MyISAM.
1389 dba::delete('item', ['id' => $current_post]);
1392 } elseif ($entries == 0) {
1393 // This really should never happen since we quit earlier if there were problems.
1394 logger("Something is terribly wrong. We haven't found our created entry.");
1399 logger('created item '.$current_post);
1400 self::updateContact($item);
1402 if (!$parent_id || ($item['parent-uri'] === $item['uri'])) {
1403 $parent_id = $current_post;
1407 dba::update('item', ['parent' => $parent_id], ['id' => $current_post]);
1409 $item['id'] = $current_post;
1410 $item['parent'] = $parent_id;
1412 // update the commented timestamp on the parent
1413 // Only update "commented" if it is really a comment
1414 if (($item['gravity'] != GRAVITY_ACTIVITY) || !Config::get("system", "like_no_comment")) {
1415 dba::update('item', ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1417 dba::update('item', ['changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1422 * Friendica servers lower than 3.4.3-2 had double encoded the signature ...
1423 * We can check for this condition when we decode and encode the stuff again.
1425 if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) {
1426 $dsprsig->signature = base64_decode($dsprsig->signature);
1427 logger("Repaired double encoded signature from handle ".$dsprsig->signer, LOGGER_DEBUG);
1430 dba::insert('sign', ['iid' => $current_post, 'signed_text' => $dsprsig->signed_text,
1431 'signature' => $dsprsig->signature, 'signer' => $dsprsig->signer]);
1434 if (!empty($diaspora_signed_text)) {
1435 // Formerly we stored the signed text, the signature and the author in different fields.
1436 // We now store the raw data so that we are more flexible.
1437 dba::insert('sign', ['iid' => $current_post, 'signed_text' => $diaspora_signed_text]);
1440 $deleted = self::tagDeliver($item['uid'], $current_post);
1443 * current post can be deleted if is for a community page and no mention are
1446 if (!$deleted && !$dontcache) {
1447 $posted_item = dba::selectFirst('item', [], ['id' => $current_post]);
1448 if (DBM::is_result($posted_item)) {
1450 Addon::callHooks('post_local_end', $posted_item);
1452 Addon::callHooks('post_remote_end', $posted_item);
1455 logger('new item not found in DB, id ' . $current_post);
1459 if ($item['parent-uri'] === $item['uri']) {
1460 self::addThread($current_post);
1462 self::updateThread($parent_id);
1468 * Due to deadlock issues with the "term" table we are doing these steps after the commit.
1469 * This is not perfect - but a workable solution until we found the reason for the problem.
1471 Term::insertFromTagFieldByItemId($current_post);
1472 Term::insertFromFileFieldByItemId($current_post);
1474 if ($item['parent-uri'] === $item['uri']) {
1475 self::addShadow($current_post);
1477 self::addShadowPost($current_post);
1480 check_user_notification($current_post);
1483 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", $notify_type, $current_post);
1484 } elseif (!empty($parent) && $parent['origin']) {
1485 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "Notifier", "comment-import", $current_post);
1488 return $current_post;
1492 * @brief Insert a new item content entry
1494 * @param array $item The item fields that are to be inserted
1496 private static function insertContent(&$item)
1498 $fields = ['uri' => $item['uri'], 'plink' => $item['plink'],
1499 'uri-plink-hash' => hash('sha1', $item['plink']).hash('sha1', $item['uri'])];
1501 foreach (self::CONTENT_FIELDLIST as $field) {
1502 if (isset($item[$field])) {
1503 $fields[$field] = $item[$field];
1504 unset($item[$field]);
1508 // To avoid timing problems, we are using locks.
1509 $locked = Lock::set('item_insert_content');
1511 logger("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
1514 // Do we already have this content?
1515 $item_content = dba::selectFirst('item-content', ['id'], ['uri' => $item['uri']]);
1516 if (DBM::is_result($item_content)) {
1517 $item['icid'] = $item_content['id'];
1518 logger('Fetched content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
1519 } elseif (dba::insert('item-content', $fields)) {
1520 $item['icid'] = dba::lastInsertId();
1521 logger('Inserted content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
1523 // By setting the ICID value through the worker we should avoid timing problems.
1524 // When the locking works, this shouldn't be needed. But better be prepared.
1525 Worker::add(PRIORITY_HIGH, 'SetItemContentID', $item['uri']);
1526 logger('Could not insert content for URI ' . $item['uri'] . ' - trying asynchronously');
1529 Lock::remove('item_insert_content');
1534 * @brief Set the item content id for a given URI
1536 * @param string $uri The item URI
1538 public static function setICIDforURI($uri)
1540 $item_content = dba::selectFirst('item-content', ['id'], ['uri' => $uri]);
1541 if (DBM::is_result($item_content)) {
1542 dba::update('item', ['icid' => $item_content['id']], ['icid' => 0, 'uri' => $uri]);
1543 logger('Asynchronously set item content id for URI ' . $uri . ' (' . $item_content['id'] . ') - Affected: '. (int)dba::affected_rows());
1545 logger('No item-content found for URI ' . $uri);
1550 * @brief Update existing item content entries
1552 * @param array $item The item fields that are to be changed
1553 * @param array $condition The condition for finding the item content entries
1555 private static function updateContent($item, $condition)
1557 // We have to select only the fields from the "item-content" table
1559 foreach (self::CONTENT_FIELDLIST as $field) {
1560 if (isset($item[$field])) {
1561 $fields[$field] = $item[$field];
1565 if (empty($fields)) {
1569 if (!empty($item['plink'])) {
1570 $fields['uri-plink-hash'] = hash('sha1', $item['plink']) . hash('sha1', $condition['uri']);
1572 // Ensure that we don't delete the plink
1573 unset($fields['plink']);
1576 logger('Update content for URI ' . $condition['uri']);
1578 dba::update('item-content', $fields, $condition, true);
1582 * @brief Distributes public items to the receivers
1584 * @param integer $itemid Item ID that should be added
1585 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
1587 public static function distribute($itemid, $signed_text = '')
1589 $condition = ["`id` IN (SELECT `parent` FROM `item` WHERE `id` = ?)", $itemid];
1590 $parent = dba::selectFirst('item', ['owner-id'], $condition);
1591 if (!DBM::is_result($parent)) {
1595 // Only distribute public items from native networks
1596 $condition = ['id' => $itemid, 'uid' => 0,
1597 'network' => [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""],
1598 'visible' => true, 'deleted' => false, 'moderated' => false, 'private' => false];
1599 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
1600 if (!DBM::is_result($item)) {
1605 unset($item['parent']);
1606 unset($item['mention']);
1607 unset($item['wall']);
1608 unset($item['origin']);
1609 unset($item['starred']);
1613 $condition = ["`nurl` IN (SELECT `nurl` FROM `contact` WHERE `id` = ?) AND `uid` != 0 AND NOT `blocked` AND `rel` IN (?, ?)",
1614 $parent['owner-id'], CONTACT_IS_SHARING, CONTACT_IS_FRIEND];
1615 $contacts = dba::select('contact', ['uid'], $condition);
1616 while ($contact = dba::fetch($contacts)) {
1617 $users[$contact['uid']] = $contact['uid'];
1622 if ($item['uri'] != $item['parent-uri']) {
1623 $parents = dba::select('item', ['uid', 'origin'], ["`uri` = ? AND `uid` != 0", $item['parent-uri']]);
1624 while ($parent = dba::fetch($parents)) {
1625 $users[$parent['uid']] = $parent['uid'];
1626 if ($parent['origin'] && !$item['origin']) {
1627 $origin_uid = $parent['uid'];
1632 foreach ($users as $uid) {
1633 if ($origin_uid == $uid) {
1634 $item['diaspora_signed_text'] = $signed_text;
1636 self::storeForUser($itemid, $item, $uid);
1641 * @brief Store public items for the receivers
1643 * @param integer $itemid Item ID that should be added
1644 * @param array $item The item entry that will be stored
1645 * @param integer $uid The user that will receive the item entry
1647 private static function storeForUser($itemid, $item, $uid)
1649 $item['uid'] = $uid;
1650 $item['origin'] = 0;
1652 if ($item['uri'] == $item['parent-uri']) {
1653 $item['contact-id'] = Contact::getIdForURL($item['owner-link'], $uid);
1655 $item['contact-id'] = Contact::getIdForURL($item['author-link'], $uid);
1658 if (empty($item['contact-id'])) {
1659 $self = dba::selectFirst('contact', ['id'], ['self' => true, 'uid' => $uid]);
1660 if (!DBM::is_result($self)) {
1663 $item['contact-id'] = $self['id'];
1666 if (in_array($item['type'], ["net-comment", "wall-comment"])) {
1667 $item['type'] = 'remote-comment';
1668 } elseif ($item['type'] == 'wall') {
1669 $item['type'] = 'remote';
1672 /// @todo Handling of "event-id"
1675 if ($item['uri'] == $item['parent-uri']) {
1676 $contact = dba::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
1677 if (DBM::is_result($contact)) {
1678 $notify = self::isRemoteSelf($contact, $item);
1682 $distributed = self::insert($item, false, $notify, true);
1684 if (!$distributed) {
1685 logger("Distributed public item " . $itemid . " for user " . $uid . " wasn't stored", LOGGER_DEBUG);
1687 logger("Distributed public item " . $itemid . " for user " . $uid . " with id " . $distributed, LOGGER_DEBUG);
1692 * @brief Add a shadow entry for a given item id that is a thread starter
1694 * We store every public item entry additionally with the user id "0".
1695 * This is used for the community page and for the search.
1696 * It is planned that in the future we will store public item entries only once.
1698 * @param integer $itemid Item ID that should be added
1700 public static function addShadow($itemid)
1702 $fields = ['uid', 'private', 'moderated', 'visible', 'deleted', 'network'];
1703 $condition = ['id' => $itemid, 'parent' => [0, $itemid]];
1704 $item = dba::selectFirst('item', $fields, $condition);
1706 if (!DBM::is_result($item)) {
1710 // is it already a copy?
1711 if (($itemid == 0) || ($item['uid'] == 0)) {
1715 // Is it a visible public post?
1716 if (!$item["visible"] || $item["deleted"] || $item["moderated"] || $item["private"]) {
1720 // is it an entry from a connector? Only add an entry for natively connected networks
1721 if (!in_array($item["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""])) {
1725 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
1727 if (DBM::is_result($item) && ($item["allow_cid"] == '') && ($item["allow_gid"] == '') &&
1728 ($item["deny_cid"] == '') && ($item["deny_gid"] == '')) {
1730 if (!self::exists(['uri' => $item['uri'], 'uid' => 0])) {
1731 // Preparing public shadow (removing user specific data)
1734 unset($item['parent']);
1735 unset($item['wall']);
1736 unset($item['mention']);
1737 unset($item['origin']);
1738 unset($item['starred']);
1739 if ($item['uri'] == $item['parent-uri']) {
1740 $item['contact-id'] = $item['owner-id'];
1742 $item['contact-id'] = $item['author-id'];
1745 if (in_array($item['type'], ["net-comment", "wall-comment"])) {
1746 $item['type'] = 'remote-comment';
1747 } elseif ($item['type'] == 'wall') {
1748 $item['type'] = 'remote';
1751 $public_shadow = self::insert($item, false, false, true);
1753 logger("Stored public shadow for thread ".$itemid." under id ".$public_shadow, LOGGER_DEBUG);
1759 * @brief Add a shadow entry for a given item id that is a comment
1761 * This function does the same like the function above - but for comments
1763 * @param integer $itemid Item ID that should be added
1765 public static function addShadowPost($itemid)
1767 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
1768 if (!DBM::is_result($item)) {
1772 // Is it a toplevel post?
1773 if ($item['id'] == $item['parent']) {
1774 self::addShadow($itemid);
1778 // Is this a shadow entry?
1779 if ($item['uid'] == 0) {
1783 // Is there a shadow parent?
1784 if (!self::exists(['uri' => $item['parent-uri'], 'uid' => 0])) {
1788 // Is there already a shadow entry?
1789 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
1793 // Save "origin" and "parent" state
1794 $origin = $item['origin'];
1795 $parent = $item['parent'];
1797 // Preparing public shadow (removing user specific data)
1800 unset($item['parent']);
1801 unset($item['wall']);
1802 unset($item['mention']);
1803 unset($item['origin']);
1804 unset($item['starred']);
1805 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
1807 if (in_array($item['type'], ["net-comment", "wall-comment"])) {
1808 $item['type'] = 'remote-comment';
1809 } elseif ($item['type'] == 'wall') {
1810 $item['type'] = 'remote';
1813 $public_shadow = self::insert($item, false, false, true);
1815 logger("Stored public shadow for comment ".$item['uri']." under id ".$public_shadow, LOGGER_DEBUG);
1817 // If this was a comment to a Diaspora post we don't get our comment back.
1818 // This means that we have to distribute the comment by ourselves.
1819 if ($origin && self::exists(['id' => $parent, 'network' => NETWORK_DIASPORA])) {
1820 self::distribute($public_shadow);
1825 * Adds a "lang" specification in a "postopts" element of given $arr,
1826 * if possible and not already present.
1827 * Expects "body" element to exist in $arr.
1829 private static function addLanguageInPostopts(&$item)
1833 if (!empty($item['postopts'])) {
1834 if (strstr($item['postopts'], 'lang=')) {
1838 $postopts = $item['postopts'];
1841 $naked_body = Text\BBCode::toPlaintext($item['body'], false);
1843 $languages = (new Text_LanguageDetect())->detect($naked_body, 3);
1845 if (sizeof($languages) > 0) {
1846 if ($postopts != '') {
1847 $postopts .= '&'; // arbitrary separator, to be reviewed
1850 $postopts .= 'lang=';
1853 foreach ($languages as $language => $score) {
1854 $postopts .= $sep . $language . ";" . $score;
1857 $item['postopts'] = $postopts;
1862 * @brief Creates an unique guid out of a given uri
1864 * @param string $uri uri of an item entry
1865 * @param string $host hostname for the GUID prefix
1866 * @return string unique guid
1868 public static function guidFromUri($uri, $host)
1870 // Our regular guid routine is using this kind of prefix as well
1871 // We have to avoid that different routines could accidentally create the same value
1872 $parsed = parse_url($uri);
1874 // We use a hash of the hostname as prefix for the guid
1875 $guid_prefix = hash("crc32", $host);
1877 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
1878 unset($parsed["scheme"]);
1880 // Glue it together to be able to make a hash from it
1881 $host_id = implode("/", $parsed);
1883 // We could use any hash algorithm since it isn't a security issue
1884 $host_hash = hash("ripemd128", $host_id);
1886 return $guid_prefix.$host_hash;
1890 * generate an unique URI
1892 * @param integer $uid User id
1893 * @param string $guid An existing GUID (Otherwise it will be generated)
1897 public static function newURI($uid, $guid = "")
1900 $guid = get_guid(32);
1903 $hostname = self::getApp()->get_hostname();
1905 $user = dba::selectFirst('user', ['nickname'], ['uid' => $uid]);
1907 $uri = "urn:X-dfrn:" . $hostname . ':' . $user['nickname'] . ':' . $guid;
1913 * @brief Set "success_update" and "last-item" to the date of the last time we heard from this contact
1915 * This can be used to filter for inactive contacts.
1916 * Only do this for public postings to avoid privacy problems, since poco data is public.
1917 * Don't set this value if it isn't from the owner (could be an author that we don't know)
1919 * @param array $arr Contains the just posted item record
1921 private static function updateContact($arr)
1923 // Unarchive the author
1924 $contact = dba::selectFirst('contact', [], ['id' => $arr["author-id"]]);
1925 if (DBM::is_result($contact)) {
1926 Contact::unmarkForArchival($contact);
1929 // Unarchive the contact if it's not our own contact
1930 $contact = dba::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
1931 if (DBM::is_result($contact)) {
1932 Contact::unmarkForArchival($contact);
1935 $update = (!$arr['private'] && (($arr["author-link"] === $arr["owner-link"]) || ($arr["parent-uri"] === $arr["uri"])));
1937 // Is it a forum? Then we don't care about the rules from above
1938 if (!$update && ($arr["network"] == NETWORK_DFRN) && ($arr["parent-uri"] === $arr["uri"])) {
1939 if (dba::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
1945 dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
1946 ['id' => $arr['contact-id']]);
1948 // Now do the same for the system wide contacts with uid=0
1949 if (!$arr['private']) {
1950 dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
1951 ['id' => $arr['owner-id']]);
1953 if ($arr['owner-id'] != $arr['author-id']) {
1954 dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
1955 ['id' => $arr['author-id']]);
1960 public static function setHashtags(&$item)
1963 $tags = get_tags($item["body"]);
1966 if (!count($tags)) {
1970 // This sorting is important when there are hashtags that are part of other hashtags
1971 // Otherwise there could be problems with hashtags like #test and #test2
1974 $URLSearchString = "^\[\]";
1976 // All hashtags should point to the home server if "local_tags" is activated
1977 if (Config::get('system', 'local_tags')) {
1978 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1979 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["body"]);
1981 $item["tag"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1982 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["tag"]);
1985 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
1986 $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1988 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
1991 $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
1993 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
1996 $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
1998 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
2001 // Repair recursive urls
2002 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2003 "#$2", $item["body"]);
2005 foreach ($tags as $tag) {
2006 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=')) {
2010 $basetag = str_replace('_',' ',substr($tag,1));
2012 $newtag = '#[url=' . System::baseUrl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
2014 $item["body"] = str_replace($tag, $newtag, $item["body"]);
2016 if (!stristr($item["tag"], "/search?tag=" . $basetag . "]" . $basetag . "[/url]")) {
2017 if (strlen($item["tag"])) {
2018 $item["tag"] = ','.$item["tag"];
2020 $item["tag"] = $newtag.$item["tag"];
2024 // Convert back the masked hashtags
2025 $item["body"] = str_replace("#", "#", $item["body"]);
2028 public static function getGuidById($id)
2030 $item = dba::selectFirst('item', ['guid'], ['id' => $id]);
2031 if (DBM::is_result($item)) {
2032 return $item['guid'];
2038 public static function getIdAndNickByGuid($guid, $uid = 0)
2044 $uid == local_user();
2047 // Does the given user have this item?
2049 $item = dba::fetch_first("SELECT `item`.`id`, `user`.`nickname` FROM `item`
2050 INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
2051 WHERE `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
2052 AND `item`.`guid` = ? AND `item`.`uid` = ?", $guid, $uid);
2053 if (DBM::is_result($item)) {
2055 $nick = $item["nickname"];
2059 // Or is it anywhere on the server?
2061 $item = dba::fetch_first("SELECT `item`.`id`, `user`.`nickname` FROM `item`
2062 INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
2063 WHERE `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
2064 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
2065 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
2066 AND NOT `item`.`private` AND `item`.`wall`
2067 AND `item`.`guid` = ?", $guid);
2068 if (DBM::is_result($item)) {
2070 $nick = $item["nickname"];
2073 return ["nick" => $nick, "id" => $id];
2077 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
2079 * @param int $item_id
2080 * @return bool true if item was deleted, else false
2082 private static function tagDeliver($uid, $item_id)
2086 $user = dba::selectFirst('user', [], ['uid' => $uid]);
2087 if (!DBM::is_result($user)) {
2091 $community_page = (($user['page-flags'] == PAGE_COMMUNITY) ? true : false);
2092 $prvgroup = (($user['page-flags'] == PAGE_PRVGROUP) ? true : false);
2094 $item = dba::selectFirst('item', [], ['id' => $item_id]);
2095 if (!DBM::is_result($item)) {
2099 $link = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
2102 * Diaspora uses their own hardwired link URL in @-tags
2103 * instead of the one we supply with webfinger
2105 $dlink = normalise_link(System::baseUrl() . '/u/' . $user['nickname']);
2107 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
2109 foreach ($matches as $mtch) {
2110 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
2112 logger('mention found: ' . $mtch[2]);
2118 if (($community_page || $prvgroup) &&
2119 !$item['wall'] && !$item['origin'] && ($item['id'] == $item['parent'])) {
2120 // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
2122 logger("no-mention top-level post to community or private group. delete.");
2123 dba::delete('item', ['id' => $item_id]);
2129 $arr = ['item' => $item, 'user' => $user];
2131 Addon::callHooks('tagged', $arr);
2133 if (!$community_page && !$prvgroup) {
2138 * tgroup delivery - setup a second delivery chain
2139 * prevent delivery looping - only proceed
2140 * if the message originated elsewhere and is a top-level post
2142 if ($item['wall'] || $item['origin'] || ($item['id'] != $item['parent'])) {
2146 // now change this copy of the post to a forum head message and deliver to all the tgroup members
2147 $self = dba::selectFirst('contact', ['id', 'name', 'url', 'thumb'], ['uid' => $uid, 'self' => true]);
2148 if (!DBM::is_result($self)) {
2152 $owner_id = Contact::getIdForURL($self['url']);
2154 // also reset all the privacy bits to the forum default permissions
2156 $private = ($user['allow_cid'] || $user['allow_gid'] || $user['deny_cid'] || $user['deny_gid']) ? 1 : 0;
2158 $forum_mode = ($prvgroup ? 2 : 1);
2160 $fields = ['wall' => true, 'origin' => true, 'forum_mode' => $forum_mode, 'contact-id' => $self['id'],
2161 'owner-id' => $owner_id, 'owner-link' => $self['url'], 'private' => $private, 'allow_cid' => $user['allow_cid'],
2162 'allow_gid' => $user['allow_gid'], 'deny_cid' => $user['deny_cid'], 'deny_gid' => $user['deny_gid']];
2163 dba::update('item', $fields, ['id' => $item_id]);
2165 self::updateThread($item_id);
2167 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', 'tgroup', $item_id);
2170 public static function isRemoteSelf($contact, &$datarray)
2174 if (!$contact['remote_self']) {
2178 // Prevent the forwarding of posts that are forwarded
2179 if ($datarray["extid"] == NETWORK_DFRN) {
2180 logger('Already forwarded', LOGGER_DEBUG);
2184 // Prevent to forward already forwarded posts
2185 if ($datarray["app"] == $a->get_hostname()) {
2186 logger('Already forwarded (second test)', LOGGER_DEBUG);
2190 // Only forward posts
2191 if ($datarray["verb"] != ACTIVITY_POST) {
2192 logger('No post', LOGGER_DEBUG);
2196 if (($contact['network'] != NETWORK_FEED) && $datarray['private']) {
2197 logger('Not public', LOGGER_DEBUG);
2201 $datarray2 = $datarray;
2202 logger('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), LOGGER_DEBUG);
2203 if ($contact['remote_self'] == 2) {
2204 $self = dba::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
2205 ['uid' => $contact['uid'], 'self' => true]);
2206 if (DBM::is_result($self)) {
2207 $datarray['contact-id'] = $self["id"];
2209 $datarray['owner-name'] = $self["name"];
2210 $datarray['owner-link'] = $self["url"];
2211 $datarray['owner-avatar'] = $self["thumb"];
2213 $datarray['author-name'] = $datarray['owner-name'];
2214 $datarray['author-link'] = $datarray['owner-link'];
2215 $datarray['author-avatar'] = $datarray['owner-avatar'];
2217 unset($datarray['created']);
2218 unset($datarray['edited']);
2220 unset($datarray['network']);
2221 unset($datarray['owner-id']);
2222 unset($datarray['author-id']);
2225 if ($contact['network'] != NETWORK_FEED) {
2226 $datarray["guid"] = get_guid(32);
2227 unset($datarray["plink"]);
2228 $datarray["uri"] = self::newURI($contact['uid'], $datarray["guid"]);
2229 $datarray["parent-uri"] = $datarray["uri"];
2230 $datarray["thr-parent"] = $datarray["uri"];
2231 $datarray["extid"] = NETWORK_DFRN;
2232 $urlpart = parse_url($datarray2['author-link']);
2233 $datarray["app"] = $urlpart["host"];
2235 $datarray['private'] = 0;
2239 if ($contact['network'] != NETWORK_FEED) {
2240 // Store the original post
2241 $result = self::insert($datarray2, false, false);
2242 logger('remote-self post original item - Contact '.$contact['url'].' return '.$result.' Item '.print_r($datarray2, true), LOGGER_DEBUG);
2244 $datarray["app"] = "Feed";
2248 // Trigger automatic reactions for addons
2249 $datarray['api_source'] = true;
2251 // We have to tell the hooks who we are - this really should be improved
2252 $_SESSION["authenticated"] = true;
2253 $_SESSION["uid"] = $contact['uid'];
2262 * @param array $item
2266 public static function fixPrivatePhotos($s, $uid, $item = null, $cid = 0)
2268 if (Config::get('system', 'disable_embedded')) {
2272 logger('check for photos', LOGGER_DEBUG);
2273 $site = substr(System::baseUrl(), strpos(System::baseUrl(), '://'));
2278 $img_start = strpos($orig_body, '[img');
2279 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2280 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2282 while (($img_st_close !== false) && ($img_len !== false)) {
2283 $img_st_close++; // make it point to AFTER the closing bracket
2284 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2286 logger('found photo ' . $image, LOGGER_DEBUG);
2288 if (stristr($image, $site . '/photo/')) {
2289 // Only embed locally hosted photos
2291 $i = basename($image);
2292 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2293 $x = strpos($i, '-');
2296 $res = substr($i, $x + 1);
2297 $i = substr($i, 0, $x);
2298 $fields = ['data', 'type', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'];
2299 $photo = dba::selectFirst('photo', $fields, ['resource-id' => $i, 'scale' => $res, 'uid' => $uid]);
2300 if (DBM::is_result($photo)) {
2302 * Check to see if we should replace this photo link with an embedded image
2303 * 1. No need to do so if the photo is public
2304 * 2. If there's a contact-id provided, see if they're in the access list
2305 * for the photo. If so, embed it.
2306 * 3. Otherwise, if we have an item, see if the item permissions match the photo
2307 * permissions, regardless of order but first check to see if they're an exact
2308 * match to save some processing overhead.
2310 if (self::hasPermissions($photo)) {
2312 $recips = self::enumeratePermissions($photo);
2313 if (in_array($cid, $recips)) {
2317 if (self::samePermissions($item, $photo)) {
2323 $data = $photo['data'];
2324 $type = $photo['type'];
2326 // If a custom width and height were specified, apply before embedding
2327 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2328 logger('scaling photo', LOGGER_DEBUG);
2330 $width = intval($match[1]);
2331 $height = intval($match[2]);
2333 $Image = new Image($data, $type);
2334 if ($Image->isValid()) {
2335 $Image->scaleDown(max($width, $height));
2336 $data = $Image->asString();
2337 $type = $Image->getType();
2341 logger('replacing photo', LOGGER_DEBUG);
2342 $image = 'data:' . $type . ';base64,' . base64_encode($data);
2343 logger('replaced: ' . $image, LOGGER_DATA);
2349 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2350 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2351 if ($orig_body === false) {
2355 $img_start = strpos($orig_body, '[img');
2356 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2357 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2360 $new_body = $new_body . $orig_body;
2365 private static function hasPermissions($obj)
2369 x($obj, 'allow_cid')
2371 x($obj, 'allow_gid')
2380 private static function samePermissions($obj1, $obj2)
2382 // first part is easy. Check that these are exactly the same.
2383 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2384 && ($obj1['allow_gid'] == $obj2['allow_gid'])
2385 && ($obj1['deny_cid'] == $obj2['deny_cid'])
2386 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
2390 // This is harder. Parse all the permissions and compare the resulting set.
2391 $recipients1 = self::enumeratePermissions($obj1);
2392 $recipients2 = self::enumeratePermissions($obj2);
2396 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2397 return ($recipients1 == $recipients2);
2400 // returns an array of contact-ids that are allowed to see this object
2401 private static function enumeratePermissions($obj)
2403 $allow_people = expand_acl($obj['allow_cid']);
2404 $allow_groups = Group::expand(expand_acl($obj['allow_gid']));
2405 $deny_people = expand_acl($obj['deny_cid']);
2406 $deny_groups = Group::expand(expand_acl($obj['deny_gid']));
2407 $recipients = array_unique(array_merge($allow_people, $allow_groups));
2408 $deny = array_unique(array_merge($deny_people, $deny_groups));
2409 $recipients = array_diff($recipients, $deny);
2413 public static function getFeedTags($item)
2417 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2419 for ($x = 0; $x < $cnt; $x ++) {
2420 if ($matches[1][$x]) {
2421 $ret[$matches[2][$x]] = ['#', $matches[1][$x], $matches[2][$x]];
2426 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2428 for ($x = 0; $x < $cnt; $x ++) {
2429 if ($matches[1][$x]) {
2430 $ret[] = ['@', $matches[1][$x], $matches[2][$x]];
2437 public static function expire($uid, $days, $network = "", $force = false)
2439 if (!$uid || ($days < 1)) {
2444 * $expire_network_only = save your own wall posts
2445 * and just expire conversations started by others
2447 $expire_network_only = PConfig::get($uid,'expire', 'network_only');
2448 $sql_extra = (intval($expire_network_only) ? " AND wall = 0 " : "");
2450 if ($network != "") {
2451 $sql_extra .= sprintf(" AND network = '%s' ", dbesc($network));
2454 * There is an index "uid_network_received" but not "uid_network_created"
2455 * This avoids the creation of another index just for one purpose.
2456 * And it doesn't really matter wether to look at "received" or "created"
2458 $range = "AND `received` < UTC_TIMESTAMP() - INTERVAL %d DAY ";
2460 $range = "AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY ";
2463 $r = q("SELECT `file`, `resource-id`, `starred`, `type`, `id` FROM `item`
2464 WHERE `uid` = %d $range
2472 if (!DBM::is_result($r)) {
2476 $expire_items = PConfig::get($uid, 'expire', 'items', 1);
2478 // Forcing expiring of items - but not notes and marked items
2480 $expire_items = true;
2483 $expire_notes = PConfig::get($uid, 'expire', 'notes', 1);
2484 $expire_starred = PConfig::get($uid, 'expire', 'starred', 1);
2485 $expire_photos = PConfig::get($uid, 'expire', 'photos', 0);
2487 logger('User '.$uid.': expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
2489 foreach ($r as $item) {
2491 // don't expire filed items
2493 if (strpos($item['file'],'[') !== false) {
2497 // Only expire posts, not photos and photo comments
2499 if ($expire_photos == 0 && strlen($item['resource-id'])) {
2501 } elseif ($expire_starred == 0 && intval($item['starred'])) {
2503 } elseif ($expire_notes == 0 && $item['type'] == 'note') {
2505 } elseif ($expire_items == 0 && $item['type'] != 'note') {
2509 self::deleteById($item['id'], PRIORITY_LOW);
2513 public static function firstPostDate($uid, $wall = false)
2515 $condition = ['uid' => $uid, 'wall' => $wall, 'deleted' => false, 'visible' => true, 'moderated' => false];
2516 $params = ['order' => ['created' => false]];
2517 $thread = dba::selectFirst('thread', ['created'], $condition, $params);
2518 if (DBM::is_result($thread)) {
2519 return substr(DateTimeFormat::local($thread['created']), 0, 10);
2525 * @brief add/remove activity to an item
2527 * Toggle activities as like,dislike,attend of an item
2529 * @param string $item_id
2530 * @param string $verb
2531 * Activity verb. One of
2532 * like, unlike, dislike, undislike, attendyes, unattendyes,
2533 * attendno, unattendno, attendmaybe, unattendmaybe
2534 * @hook 'post_local_end'
2536 * 'post_id' => ID of posted item
2538 public static function performLike($item_id, $verb)
2540 if (!local_user() && !remote_user()) {
2547 $bodyverb = L10n::t('%1$s likes %2$s\'s %3$s');
2548 $activity = ACTIVITY_LIKE;
2552 $bodyverb = L10n::t('%1$s doesn\'t like %2$s\'s %3$s');
2553 $activity = ACTIVITY_DISLIKE;
2557 $bodyverb = L10n::t('%1$s is attending %2$s\'s %3$s');
2558 $activity = ACTIVITY_ATTEND;
2562 $bodyverb = L10n::t('%1$s is not attending %2$s\'s %3$s');
2563 $activity = ACTIVITY_ATTENDNO;
2566 case 'unattendmaybe':
2567 $bodyverb = L10n::t('%1$s may attend %2$s\'s %3$s');
2568 $activity = ACTIVITY_ATTENDMAYBE;
2571 logger('like: unknown verb ' . $verb . ' for item ' . $item_id);
2575 // Enable activity toggling instead of on/off
2576 $event_verb_flag = $activity === ACTIVITY_ATTEND || $activity === ACTIVITY_ATTENDNO || $activity === ACTIVITY_ATTENDMAYBE;
2578 logger('like: verb ' . $verb . ' item ' . $item_id);
2580 $item = dba::selectFirst('item', [], ['`id` = ? OR `uri` = ?', $item_id, $item_id]);
2581 if (!DBM::is_result($item)) {
2582 logger('like: unknown item ' . $item_id);
2586 $uid = $item['uid'];
2587 if (($uid == 0) && local_user()) {
2588 $uid = local_user();
2591 if (!can_write_wall($uid)) {
2592 logger('like: unable to write on wall ' . $uid);
2596 // Retrieves the local post owner
2597 $owner_self_contact = dba::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
2598 if (!DBM::is_result($owner_self_contact)) {
2599 logger('like: unknown owner ' . $uid);
2603 // Retrieve the current logged in user's public contact
2604 $author_id = public_contact();
2606 $author_contact = dba::selectFirst('contact', [], ['id' => $author_id]);
2607 if (!DBM::is_result($author_contact)) {
2608 logger('like: unknown author ' . $author_id);
2612 // Contact-id is the uid-dependant author contact
2613 if (local_user() == $uid) {
2614 $item_contact_id = $owner_self_contact['id'];
2615 $item_contact = $owner_self_contact;
2617 $item_contact_id = Contact::getIdForURL($author_contact['url'], $uid, true);
2618 $item_contact = dba::selectFirst('contact', [], ['id' => $item_contact_id]);
2619 if (!DBM::is_result($item_contact)) {
2620 logger('like: unknown item contact ' . $item_contact_id);
2625 // Look for an existing verb row
2626 // event participation are essentially radio toggles. If you make a subsequent choice,
2627 // we need to eradicate your first choice.
2628 if ($event_verb_flag) {
2629 $verbs = [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE];
2634 $base_condition = ['verb' => $verbs, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY,
2635 'author-id' => $author_contact['id'], 'uid' => item['uid']];
2637 $condition = array_merge($base_condition, ['parent' => $item_id]);
2638 $like_item = self::selectFirst(['id', 'guid', 'verb'], $condition);
2640 if (!DBM::is_result($like_item)) {
2641 $condition = array_merge($base_condition, ['parent-uri' => $item_id]);
2642 $like_item = self::selectFirst(['id', 'guid', 'verb'], $condition);
2645 if (!DBM::is_result($like_item)) {
2646 $condition = array_merge($base_condition, ['thr-parent' => $item_id]);
2647 $like_item = self::selectFirst(['id', 'guid', 'verb'], $condition);
2650 // If it exists, mark it as deleted
2651 if (DBM::is_result($like_item)) {
2652 // Already voted, undo it
2653 $fields = ['deleted' => true, 'unseen' => true, 'changed' => DateTimeFormat::utcNow()];
2654 /// @todo Consider using self::update - but before doing so, check the side effects
2655 dba::update('item', $fields, ['id' => $like_item['id']]);
2657 // Clean up the Diaspora signatures for this like
2658 // Go ahead and do it even if Diaspora support is disabled. We still want to clean up
2659 // if it had been enabled in the past
2660 dba::delete('sign', ['iid' => $like_item['id']]);
2662 $like_item_id = $like_item['id'];
2663 Worker::add(PRIORITY_HIGH, "Notifier", "like", $like_item_id);
2665 if (!$event_verb_flag || $like_item['verb'] == $activity) {
2670 // Verb is "un-something", just trying to delete existing entries
2671 if (strpos($verb, 'un') === 0) {
2675 // Else or if event verb different from existing row, create a new item row
2676 $post_type = (($item['resource-id']) ? L10n::t('photo') : L10n::t('status'));
2677 if ($item['object-type'] === ACTIVITY_OBJ_EVENT) {
2678 $post_type = L10n::t('event');
2680 $objtype = $item['resource-id'] ? ACTIVITY_OBJ_IMAGE : ACTIVITY_OBJ_NOTE ;
2681 $link = xmlify('<link rel="alternate" type="text/html" href="' . System::baseUrl() . '/display/' . $owner_self_contact['nick'] . '/' . $item['id'] . '" />' . "\n") ;
2682 $body = $item['body'];
2687 <type>$objtype</type>
2689 <id>{$item['uri']}</id>
2692 <content>$body</content>
2696 $ulink = '[url=' . $author_contact['url'] . ']' . $author_contact['name'] . '[/url]';
2697 $alink = '[url=' . $item['author-link'] . ']' . $item['author-name'] . '[/url]';
2698 $plink = '[url=' . System::baseUrl() . '/display/' . $owner_self_contact['nick'] . '/' . $item['id'] . ']' . $post_type . '[/url]';
2701 'guid' => get_guid(32),
2702 'uri' => self::newURI($item['uid']),
2703 'uid' => $item['uid'],
2704 'contact-id' => $item_contact_id,
2705 'type' => 'activity',
2706 'wall' => $item['wall'],
2708 'gravity' => GRAVITY_ACTIVITY,
2709 'parent' => $item['id'],
2710 'parent-uri' => $item['uri'],
2711 'thr-parent' => $item['uri'],
2712 'owner-id' => $item['owner-id'],
2713 'owner-name' => $item['owner-name'],
2714 'owner-link' => $item['owner-link'],
2715 'owner-avatar' => $item['owner-avatar'],
2716 'author-id' => $author_contact['id'],
2717 'author-name' => $author_contact['name'],
2718 'author-link' => $author_contact['url'],
2719 'author-avatar' => $author_contact['thumb'],
2720 'body' => sprintf($bodyverb, $ulink, $alink, $plink),
2721 'verb' => $activity,
2722 'object-type' => $objtype,
2724 'allow_cid' => $item['allow_cid'],
2725 'allow_gid' => $item['allow_gid'],
2726 'deny_cid' => $item['deny_cid'],
2727 'deny_gid' => $item['deny_gid'],
2732 $new_item_id = self::insert($new_item);
2734 // If the parent item isn't visible then set it to visible
2735 if (!$item['visible']) {
2736 self::update(['visible' => true], ['id' => $item['id']]);
2739 // Save the author information for the like in case we need to relay to Diaspora
2740 Diaspora::storeLikeSignature($item_contact, $new_item_id);
2742 $new_item['id'] = $new_item_id;
2744 Addon::callHooks('post_local_end', $new_item);
2746 Worker::add(PRIORITY_HIGH, "Notifier", "like", $new_item_id);
2751 private static function addThread($itemid, $onlyshadow = false)
2753 $fields = ['uid', 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private', 'pubmail',
2754 'moderated', 'visible', 'starred', 'bookmark', 'contact-id',
2755 'deleted', 'origin', 'forum_mode', 'mention', 'network', 'author-id', 'owner-id'];
2756 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
2757 $item = dba::selectFirst('item', $fields, $condition);
2759 if (!DBM::is_result($item)) {
2763 $item['iid'] = $itemid;
2766 $result = dba::insert('thread', $item);
2768 logger("Add thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
2772 private static function updateThread($itemid, $setmention = false)
2774 $fields = ['uid', 'guid', 'created', 'edited', 'commented', 'received', 'changed',
2775 'wall', 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark', 'contact-id',
2776 'deleted', 'origin', 'forum_mode', 'network', 'author-id', 'owner-id'];
2777 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
2779 $item = dba::selectFirst('item', $fields, $condition);
2780 if (!DBM::is_result($item)) {
2785 $item["mention"] = 1;
2792 foreach ($item as $field => $data) {
2793 if (!in_array($field, ["guid"])) {
2794 $fields[$field] = $data;
2798 $result = dba::update('thread', $fields, ['iid' => $itemid]);
2800 logger("Update thread for item ".$itemid." - guid ".$item["guid"]." - ".(int)$result, LOGGER_DEBUG);
2803 private static function deleteThread($itemid, $itemuri = "")
2805 $item = dba::selectFirst('thread', ['uid'], ['iid' => $itemid]);
2806 if (!DBM::is_result($item)) {
2807 logger('No thread found for id '.$itemid, LOGGER_DEBUG);
2811 // Using dba::delete at this time could delete the associated item entries
2812 $result = dba::e("DELETE FROM `thread` WHERE `iid` = ?", $itemid);
2814 logger("deleteThread: Deleted thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
2816 if ($itemuri != "") {
2817 $condition = ["`uri` = ? AND NOT `deleted` AND NOT (`uid` IN (?, 0))", $itemuri, $item["uid"]];
2818 if (!self::exists($condition)) {
2819 dba::delete('item', ['uri' => $itemuri, 'uid' => 0]);
2820 logger("deleteThread: Deleted shadow for item ".$itemuri, LOGGER_DEBUG);