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;
28 use Text_LanguageDetect;
30 require_once 'boot.php';
31 require_once 'include/items.php';
32 require_once 'include/text.php';
34 class Item extends BaseObject
36 // Field list that is used to display the items
37 const DISPLAY_FIELDLIST = ['uid', 'id', 'parent', 'uri', 'thr-parent', 'parent-uri', 'guid',
38 'commented', 'created', 'edited', 'received', 'verb', 'object-type', 'postopts', 'plink',
39 'wall', 'private', 'starred', 'origin', 'title', 'body', 'file', 'attach',
40 'content-warning', 'location', 'coord', 'app', 'rendered-hash', 'rendered-html', 'object',
41 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'item_id', 'item_network',
42 'author-id', 'author-link', 'author-name', 'author-avatar',
43 'owner-id', 'owner-link', 'owner-name', 'owner-avatar',
44 'contact-id', 'contact-link', 'contact-name', 'contact-avatar',
45 'network', 'url', 'name', 'writable', 'self', 'cid', 'alias',
46 'event-id', 'event-created', 'event-edited', 'event-start', 'event-finish',
47 'event-summary', 'event-desc', 'event-location', 'event-type',
48 'event-nofinish', 'event-adjust', 'event-ignore', 'event-id'];
50 // Field list that is used to deliver items via the protocols
51 const DELIVER_FIELDLIST = ['uid', 'id', 'parent', 'uri', 'thr-parent', 'parent-uri', 'guid',
52 'created', 'edited', 'verb', 'object-type', 'object', 'target',
53 'private', 'title', 'body', 'location', 'coord', 'app',
54 'attach', 'tag', 'bookmark', 'deleted', 'extid',
55 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
56 'author-id', 'author-link', 'owner-link', 'contact-uid',
57 'signed_text', 'signature', 'signer'];
60 * Retrieve a single record from the item table for a given user and returns it in an associative array
62 * @brief Retrieve a single record from a table
63 * @param integer $uid User ID
64 * @param array $fields
65 * @param array $condition
66 * @param array $params
70 public static function selectFirstForUser($uid, array $selected = [], array $condition = [], $params = [])
72 $params['uid'] = $uid;
74 if (empty($selected)) {
75 $selected = Item::DISPLAY_FIELDLIST;
78 return self::selectFirst($selected, $condition, $params);
82 * @brief Select rows from the item table for a given user
84 * @param integer $uid User ID
85 * @param array $selected Array of selected fields, empty for all
86 * @param array $condition Array of fields for condition
87 * @param array $params Array of several parameters
89 * @return boolean|object
91 public static function selectForUser($uid, array $selected = [], array $condition = [], $params = [])
93 $params['uid'] = $uid;
95 if (empty($selected)) {
96 $selected = Item::DISPLAY_FIELDLIST;
99 return self::select($selected, $condition, $params);
103 * Retrieve a single record from the item table and returns it in an associative array
105 * @brief Retrieve a single record from a table
106 * @param array $fields
107 * @param array $condition
108 * @param array $params
112 public static function selectFirst(array $fields = [], array $condition = [], $params = [])
114 $params['limit'] = 1;
116 $result = self::select($fields, $condition, $params);
118 if (is_bool($result)) {
121 $row = dba::fetch($result);
128 * @brief Select rows from the item table
130 * @param array $selected Array of selected fields, empty for all
131 * @param array $condition Array of fields for condition
132 * @param array $params Array of several parameters
134 * @return boolean|object
136 public static function select(array $selected = [], array $condition = [], $params = [])
141 if (isset($params['uid'])) {
142 $uid = $params['uid'];
146 $fields = self::fieldlist($selected);
148 $select_fields = self::constructSelectFields($fields, $selected);
150 $condition_string = dba::buildCondition($condition);
152 $condition_string = self::addTablesToFields($condition_string, $fields);
155 $condition_string = $condition_string . ' AND ' . self::condition(false);
158 $param_string = self::addTablesToFields(dba::buildParameter($params), $fields);
160 $table = "`item` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, false);
162 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
164 return dba::p($sql, $condition);
168 * Retrieve a single record from the starting post in the item table and returns it in an associative array
170 * @brief Retrieve a single record from a table
171 * @param integer $uid User ID
172 * @param array $fields
173 * @param array $condition
174 * @param array $params
178 public static function selectFirstThreadForUser($uid, array $fields = [], array $condition = [], $params = [])
180 $params['limit'] = 1;
181 $result = self::selectThreadForUser($uid, $fields, $condition, $params);
183 if (is_bool($result)) {
186 $row = dba::fetch($result);
193 * @brief Select rows from the starting post in the item table
195 * @param integer $uid User ID
196 * @param array $fields Array of selected fields, empty for all
197 * @param array $condition Array of fields for condition
198 * @param array $params Array of several parameters
200 * @return boolean|object
202 public static function selectThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
204 if (empty($selected)) {
205 $selected = Item::DISPLAY_FIELDLIST;
208 $fields = self::fieldlist($selected);
210 $threadfields = ['thread' => ['iid', 'uid', 'contact-id', 'owner-id', 'author-id',
211 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private',
212 'pubmail', 'moderated', 'visible', 'starred', 'ignored', 'bookmark',
213 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'network']];
215 $select_fields = self::constructSelectFields($fields, $selected);
217 $condition_string = dba::buildCondition($condition);
219 $condition_string = self::addTablesToFields($condition_string, $threadfields);
220 $condition_string = self::addTablesToFields($condition_string, $fields);
222 $condition_string = $condition_string . ' AND ' . self::condition(true);
224 $param_string = dba::buildParameter($params);
225 $param_string = self::addTablesToFields($param_string, $threadfields);
226 $param_string = self::addTablesToFields($param_string, $fields);
228 $table = "`thread` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, true);
230 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
232 return dba::p($sql, $condition);
236 * @brief Returns a list of fields that are associated with the item table
238 * @return array field list
240 private static function fieldlist($selected)
244 $fields['item'] = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
245 'contact-id', 'owner-id', 'author-id', 'type', 'wall', 'gravity', 'extid',
246 'created', 'edited', 'commented', 'received', 'changed',
247 'title', 'body', 'app', 'verb', 'object-type', 'object', 'target-type', 'target',
248 'postopts', 'plink', 'resource-id', 'event-id', 'tag', 'attach', 'inform',
249 'file', 'location', 'coord', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
250 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
251 'unseen', 'deleted', 'origin', 'forum_mode', 'mention',
252 'rendered-hash', 'rendered-html', 'global', 'shadow', 'content-warning',
253 'id' => 'item_id', 'network' => 'item_network'];
255 $fields['author'] = ['url' => 'author-link', 'name' => 'author-name', 'thumb' => 'author-avatar'];
257 $fields['owner'] = ['url' => 'owner-link', 'name' => 'owner-name', 'thumb' => 'owner-avatar'];
259 $fields['contact'] = ['url' => 'contact-link', 'name' => 'contact-name', 'thumb' => 'contact-avatar',
260 'network', 'url', 'name', 'writable', 'self', 'id' => 'cid', 'alias', 'uid' => 'contact-uid',
261 'photo', 'name-date', 'uri-date', 'avatar-date', 'thumb', 'dfrn-id'];
263 $fields['parent-item'] = ['guid' => 'parent-guid'];
265 $fields['parent-item-author'] = ['url' => 'parent-author-link', 'name' => 'parent-author-name'];
267 $fields['event'] = ['created' => 'event-created', 'edited' => 'event-edited',
268 'start' => 'event-start','finish' => 'event-finish',
269 'summary' => 'event-summary','desc' => 'event-desc',
270 'location' => 'event-location', 'type' => 'event-type',
271 'nofinish' => 'event-nofinish','adjust' => 'event-adjust',
272 'ignore' => 'event-ignore', 'id' => 'event-id'];
274 $fields['sign'] = ['signed_text', 'signature', 'signer'];
280 * @brief Returns SQL condition for the "select" functions
282 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
284 * @return string SQL condition
286 private static function condition($thread_mode)
289 $master_table = "`thread`";
291 $master_table = "`item`";
293 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`) ";
297 * @brief Returns all needed "JOIN" commands for the "select" functions
299 * @param integer $uid User ID
300 * @param string $sql_commands The parts of the built SQL commands in the "select" functions
301 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
303 * @return string The SQL joins for the "select" functions
305 private static function constructJoins($uid, $sql_commands, $thread_mode)
308 $master_table = "`thread`";
309 $master_table_key = "`thread`.`iid`";
310 $joins = "STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid` ";
312 $master_table = "`item`";
313 $master_table_key = "`item`.`id`";
317 $joins .= sprintf("STRAIGHT_JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`
318 AND NOT `contact`.`blocked`
319 AND ((NOT `contact`.`readonly` AND NOT `contact`.`pending` AND (`contact`.`rel` IN (%s, %s)))
320 OR `contact`.`self` OR (`item`.`id` != `item`.`parent`) OR `contact`.`uid` = 0)
321 STRAIGHT_JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id` AND NOT `author`.`blocked`
322 STRAIGHT_JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id` AND NOT `owner`.`blocked`
323 LEFT JOIN `user-item` ON `user-item`.`iid` = $master_table_key AND `user-item`.`uid` = %d",
324 CONTACT_IS_SHARING, CONTACT_IS_FRIEND, intval($uid));
326 if (strpos($sql_commands, "`group_member`.") !== false) {
327 $joins .= " STRAIGHT_JOIN `group_member` ON `group_member`.`contact-id` = $master_table.`contact-id`";
330 if (strpos($sql_commands, "`user`.") !== false) {
331 $joins .= " STRAIGHT_JOIN `user` ON `user`.`uid` = $master_table.`uid`";
334 if (strpos($sql_commands, "`event`.") !== false) {
335 $joins .= " LEFT JOIN `event` ON `event-id` = `event`.`id`";
338 if (strpos($sql_commands, "`sign`.") !== false) {
339 $joins .= " LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`";
342 if ((strpos($sql_commands, "`parent-item`.") !== false) || (strpos($sql_commands, "`parent-author`.") !== false)) {
343 $joins .= " STRAIGHT_JOIN `item` AS `parent-item` ON `parent-item`.`id` = `item`.`parent`";
346 if (strpos($sql_commands, "`parent-item-author`.") !== false) {
347 $joins .= " STRAIGHT_JOIN `contact` AS `parent-item-author` ON `parent-item-author`.`id` = `parent-item`.`author-id`";
354 * @brief Add the field list for the "select" functions
356 * @param array $fields The field definition array
357 * @param array $selected The array with the selected fields from the "select" functions
359 * @return string The field list
361 private static function constructSelectFields($fields, $selected)
364 foreach ($fields as $table => $table_fields) {
365 foreach ($table_fields as $field => $select) {
366 if (empty($selected) || in_array($select, $selected)) {
367 if (is_int($field)) {
368 $selection[] = "`" . $table . "`.`".$select."`";
370 $selection[] = "`" . $table . "`.`" . $field . "` AS `".$select ."`";
375 return implode(", ", $selection);
379 * @brief add table definition to fields in an SQL query
381 * @param string $query SQL query
382 * @param array $fields The field definition array
384 * @return string the changed SQL query
386 private static function addTablesToFields($query, $fields)
388 foreach ($fields as $table => $table_fields) {
389 foreach ($table_fields as $alias => $field) {
390 if (is_int($alias)) {
391 $replace_field = $field;
393 $replace_field = $alias;
396 $search = "/([^\.])`" . $field . "`/i";
397 $replace = "$1`" . $table . "`.`" . $replace_field . "`";
398 $query = preg_replace($search, $replace, $query);
405 * @brief Update existing item entries
407 * @param array $fields The fields that are to be changed
408 * @param array $condition The condition for finding the item entries
410 * In the future we may have to change permissions as well.
411 * Then we had to add the user id as third parameter.
413 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
415 * @return integer|boolean number of affected rows - or "false" if there was an error
417 public static function update(array $fields, array $condition)
419 if (empty($condition) || empty($fields)) {
423 // To ensure the data integrity we do it in an transaction
426 // We cannot simply expand the condition to check for origin entries
427 // The condition needn't to be a simple array but could be a complex condition.
428 // And we have to execute this query before the update to ensure to fetch the same data.
429 $items = dba::select('item', ['id', 'origin'], $condition);
431 $success = dba::update('item', $fields, $condition);
439 $rows = dba::affected_rows();
441 while ($item = dba::fetch($items)) {
442 Term::insertFromTagFieldByItemId($item['id']);
443 Term::insertFromFileFieldByItemId($item['id']);
444 self::updateThread($item['id']);
446 // We only need to notfiy others when it is an original entry from us.
447 // Only call the notifier when the item has some content relevant change.
448 if ($item['origin'] && in_array('edited', array_keys($fields))) {
449 Worker::add(PRIORITY_HIGH, "Notifier", 'edit_post', $item['id']);
459 * @brief Delete an item and notify others about it - if it was ours
461 * @param array $condition The condition for finding the item entries
462 * @param integer $priority Priority for the notification
464 public static function delete($condition, $priority = PRIORITY_HIGH)
466 $items = dba::select('item', ['id'], $condition);
467 while ($item = dba::fetch($items)) {
468 self::deleteById($item['id'], $priority);
474 * @brief Delete an item for an user and notify others about it - if it was ours
476 * @param array $condition The condition for finding the item entries
477 * @param integer $uid User who wants to delete this item
479 public static function deleteForUser($condition, $uid)
485 $items = dba::select('item', ['id', 'uid'], $condition);
486 while ($item = dba::fetch($items)) {
487 // "Deleting" global items just means hiding them
488 if ($item['uid'] == 0) {
489 dba::update('user-item', ['hidden' => true], ['iid' => $item['id'], 'uid' => $uid], true);
490 } elseif ($item['uid'] == $uid) {
491 self::deleteById($item['id'], PRIORITY_HIGH);
493 logger('Wrong ownership. Not deleting item ' . $item['id']);
500 * @brief Delete an item and notify others about it - if it was ours
502 * @param integer $item_id Item ID that should be delete
503 * @param integer $priority Priority for the notification
505 * @return boolean success
507 private static function deleteById($item_id, $priority = PRIORITY_HIGH)
509 // locate item to be deleted
510 $fields = ['id', 'uri', 'uid', 'parent', 'parent-uri', 'origin',
511 'deleted', 'file', 'resource-id', 'event-id', 'attach',
512 'verb', 'object-type', 'object', 'target', 'contact-id'];
513 $item = dba::selectFirst('item', $fields, ['id' => $item_id]);
514 if (!DBM::is_result($item)) {
515 logger('Item with ID ' . $item_id . " hasn't been found.", LOGGER_DEBUG);
519 if ($item['deleted']) {
520 logger('Item with ID ' . $item_id . ' has already been deleted.', LOGGER_DEBUG);
524 $parent = dba::selectFirst('item', ['origin'], ['id' => $item['parent']]);
525 if (!DBM::is_result($parent)) {
526 $parent = ['origin' => false];
529 // clean up categories and tags so they don't end up as orphans
532 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
534 foreach ($matches as $mtch) {
535 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],true);
541 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
543 foreach ($matches as $mtch) {
544 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],false);
549 * If item is a link to a photo resource, nuke all the associated photos
550 * (visitors will not have photo resources)
551 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
552 * generate a resource-id and therefore aren't intimately linked to the item.
554 if (strlen($item['resource-id'])) {
555 dba::delete('photo', ['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
558 // If item is a link to an event, delete the event.
559 if (intval($item['event-id'])) {
560 Event::delete($item['event-id']);
563 // If item has attachments, drop them
564 foreach (explode(", ", $item['attach']) as $attach) {
565 preg_match("|attach/(\d+)|", $attach, $matches);
566 dba::delete('attach', ['id' => $matches[1], 'uid' => $item['uid']]);
569 // Delete tags that had been attached to other items
570 self::deleteTagsFromItem($item);
572 // Set the item to "deleted"
573 dba::update('item', ['deleted' => true, 'title' => '', 'body' => '',
574 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()],
575 ['id' => $item['id']]);
577 Term::insertFromTagFieldByItemId($item['id']);
578 Term::insertFromFileFieldByItemId($item['id']);
579 self::deleteThread($item['id'], $item['parent-uri']);
581 if (!dba::exists('item', ["`uri` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri']])) {
582 self::delete(['uri' => $item['uri'], 'uid' => 0, 'deleted' => false], $priority);
585 // If it's the parent of a comment thread, kill all the kids
586 if ($item['id'] == $item['parent']) {
587 self::delete(['parent' => $item['parent'], 'deleted' => false], $priority);
590 // Is it our comment and/or our thread?
591 if ($item['origin'] || $parent['origin']) {
593 // When we delete the original post we will delete all existing copies on the server as well
594 self::delete(['uri' => $item['uri'], 'deleted' => false], $priority);
596 // send the notification upstream/downstream
597 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", "drop", intval($item['id']));
598 } elseif ($item['uid'] != 0) {
600 // When we delete just our local user copy of an item, we have to set a marker to hide it
601 $global_item = dba::selectFirst('item', ['id'], ['uri' => $item['uri'], 'uid' => 0, 'deleted' => false]);
602 if (DBM::is_result($global_item)) {
603 dba::update('user-item', ['hidden' => true], ['iid' => $global_item['id'], 'uid' => $item['uid']], true);
607 logger('Item with ID ' . $item_id . " has been deleted.", LOGGER_DEBUG);
612 private static function deleteTagsFromItem($item)
614 if (($item["verb"] != ACTIVITY_TAG) || ($item["object-type"] != ACTIVITY_OBJ_TAGTERM)) {
618 $xo = XML::parseString($item["object"], false);
619 $xt = XML::parseString($item["target"], false);
621 if ($xt->type != ACTIVITY_OBJ_NOTE) {
625 $i = dba::selectFirst('item', ['id', 'contact-id', 'tag'], ['uri' => $xt->id, 'uid' => $item['uid']]);
626 if (!DBM::is_result($i)) {
630 // For tags, the owner cannot remove the tag on the author's copy of the post.
631 $owner_remove = ($item["contact-id"] == $i["contact-id"]);
632 $author_copy = $item["origin"];
634 if (($owner_remove && $author_copy) || !$owner_remove) {
638 $tags = explode(',', $i["tag"]);
641 foreach ($tags as $tag) {
642 if (trim($tag) !== trim($xo->body)) {
643 $newtags[] = trim($tag);
647 self::update(['tag' => implode(',', $newtags)], ['id' => $i["id"]]);
650 private static function guid($item, $notify)
652 $guid = notags(trim($item['guid']));
659 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
660 // We add the hash of our own host because our host is the original creator of the post.
661 $prefix_host = get_app()->get_hostname();
665 // We are only storing the post so we create a GUID from the original hostname.
666 if (!empty($item['author-link'])) {
667 $parsed = parse_url($item['author-link']);
668 if (!empty($parsed['host'])) {
669 $prefix_host = $parsed['host'];
673 if (empty($prefix_host) && !empty($item['plink'])) {
674 $parsed = parse_url($item['plink']);
675 if (!empty($parsed['host'])) {
676 $prefix_host = $parsed['host'];
680 if (empty($prefix_host) && !empty($item['uri'])) {
681 $parsed = parse_url($item['uri']);
682 if (!empty($parsed['host'])) {
683 $prefix_host = $parsed['host'];
687 // Is it in the format data@host.tld? - Used for mail contacts
688 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
689 $mailparts = explode('@', $item['author-link']);
690 $prefix_host = array_pop($mailparts);
694 if (!empty($item['plink'])) {
695 $guid = self::guidFromUri($item['plink'], $prefix_host);
696 } elseif (!empty($item['uri'])) {
697 $guid = self::guidFromUri($item['uri'], $prefix_host);
699 $guid = get_guid(32, hash('crc32', $prefix_host));
705 private static function contactId($item)
707 $contact_id = (int)$item["contact-id"];
709 if (!empty($contact_id)) {
712 logger('Missing contact-id. Called by: '.System::callstack(), LOGGER_DEBUG);
714 * First we are looking for a suitable contact that matches with the author of the post
715 * This is done only for comments
717 if ($item['parent-uri'] != $item['uri']) {
718 $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
721 // If not present then maybe the owner was found
722 if ($contact_id == 0) {
723 $contact_id = Contact::getIdForURL($item['owner-link'], $item['uid']);
726 // Still missing? Then use the "self" contact of the current user
727 if ($contact_id == 0) {
728 $self = dba::selectFirst('contact', ['id'], ['self' => true, 'uid' => $item['uid']]);
729 if (DBM::is_result($self)) {
730 $contact_id = $self["id"];
733 logger("Contact-id was missing for post ".$item['guid']." from user id ".$item['uid']." - now set to ".$contact_id, LOGGER_DEBUG);
738 public static function insert($item, $force_parent = false, $notify = false, $dontcache = false)
742 // If it is a posting where users should get notifications, then define it as wall posting
745 $item['type'] = 'wall';
747 $item['network'] = NETWORK_DFRN;
748 $item['protocol'] = PROTOCOL_DFRN;
750 if (is_int($notify)) {
753 $priority = PRIORITY_HIGH;
756 $item['network'] = trim(defaults($item, 'network', NETWORK_PHANTOM));
759 $item['guid'] = self::guid($item, $notify);
760 $item['uri'] = notags(trim(defaults($item, 'uri', self::newURI($item['uid'], $item['guid']))));
762 // Store conversation data
763 $item = Conversation::insert($item);
766 * If a Diaspora signature structure was passed in, pull it out of the
767 * item array and set it aside for later storage.
771 if (x($item, 'dsprsig')) {
772 $encoded_signature = $item['dsprsig'];
773 $dsprsig = json_decode(base64_decode($item['dsprsig']));
774 unset($item['dsprsig']);
777 if (!empty($item['diaspora_signed_text'])) {
778 $diaspora_signed_text = $item['diaspora_signed_text'];
779 unset($item['diaspora_signed_text']);
781 $diaspora_signed_text = '';
784 // Converting the plink
785 /// @TODO Check if this is really still needed
786 if ($item['network'] == NETWORK_OSTATUS) {
787 if (isset($item['plink'])) {
788 $item['plink'] = OStatus::convertHref($item['plink']);
789 } elseif (isset($item['uri'])) {
790 $item['plink'] = OStatus::convertHref($item['uri']);
794 if (!empty($item['thr-parent'])) {
795 $item['parent-uri'] = $item['thr-parent'];
798 if (x($item, 'gravity')) {
799 $item['gravity'] = intval($item['gravity']);
800 } elseif ($item['parent-uri'] === $item['uri']) {
801 $item['gravity'] = 0;
802 } elseif (activity_match($item['verb'],ACTIVITY_POST)) {
803 $item['gravity'] = 6;
805 $item['gravity'] = 6; // extensible catchall
808 $item['type'] = defaults($item, 'type', 'remote');
810 $uid = intval($item['uid']);
812 // check for create date and expire time
813 $expire_interval = Config::get('system', 'dbclean-expire-days', 0);
815 $user = dba::selectFirst('user', ['expire'], ['uid' => $uid]);
816 if (DBM::is_result($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
817 $expire_interval = $user['expire'];
820 if (($expire_interval > 0) && !empty($item['created'])) {
821 $expire_date = time() - ($expire_interval * 86400);
822 $created_date = strtotime($item['created']);
823 if ($created_date < $expire_date) {
824 logger('item-store: item created ('.date('c', $created_date).') before expiration time ('.date('c', $expire_date).'). ignored. ' . print_r($item,true), LOGGER_DEBUG);
830 * Do we already have this item?
831 * We have to check several networks since Friendica posts could be repeated
832 * via OStatus (maybe Diasporsa as well)
834 if (in_array($item['network'], [NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS, ""])) {
835 $condition = ["`uri` = ? AND `uid` = ? AND `network` IN (?, ?, ?)",
836 trim($item['uri']), $item['uid'],
837 NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS];
838 $existing = dba::selectFirst('item', ['id', 'network'], $condition);
839 if (DBM::is_result($existing)) {
840 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
842 logger("Item with uri ".$item['uri']." already existed for user ".$uid." with id ".$existing["id"]." target network ".$existing["network"]." - new network: ".$item['network']);
845 return $existing["id"];
849 self::addLanguageInPostopts($item);
851 $item['wall'] = intval(defaults($item, 'wall', 0));
852 $item['extid'] = trim(defaults($item, 'extid', ''));
853 $item['author-name'] = trim(defaults($item, 'author-name', ''));
854 $item['author-link'] = trim(defaults($item, 'author-link', ''));
855 $item['author-avatar'] = trim(defaults($item, 'author-avatar', ''));
856 $item['owner-name'] = trim(defaults($item, 'owner-name', ''));
857 $item['owner-link'] = trim(defaults($item, 'owner-link', ''));
858 $item['owner-avatar'] = trim(defaults($item, 'owner-avatar', ''));
859 $item['received'] = ((x($item, 'received') !== false) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
860 $item['created'] = ((x($item, 'created') !== false) ? DateTimeFormat::utc($item['created']) : $item['received']);
861 $item['edited'] = ((x($item, 'edited') !== false) ? DateTimeFormat::utc($item['edited']) : $item['created']);
862 $item['changed'] = ((x($item, 'changed') !== false) ? DateTimeFormat::utc($item['changed']) : $item['created']);
863 $item['commented'] = ((x($item, 'commented') !== false) ? DateTimeFormat::utc($item['commented']) : $item['created']);
864 $item['title'] = trim(defaults($item, 'title', ''));
865 $item['location'] = trim(defaults($item, 'location', ''));
866 $item['coord'] = trim(defaults($item, 'coord', ''));
867 $item['visible'] = ((x($item, 'visible') !== false) ? intval($item['visible']) : 1);
868 $item['deleted'] = 0;
869 $item['parent-uri'] = trim(defaults($item, 'parent-uri', $item['uri']));
870 $item['verb'] = trim(defaults($item, 'verb', ''));
871 $item['object-type'] = trim(defaults($item, 'object-type', ''));
872 $item['object'] = trim(defaults($item, 'object', ''));
873 $item['target-type'] = trim(defaults($item, 'target-type', ''));
874 $item['target'] = trim(defaults($item, 'target', ''));
875 $item['plink'] = trim(defaults($item, 'plink', ''));
876 $item['allow_cid'] = trim(defaults($item, 'allow_cid', ''));
877 $item['allow_gid'] = trim(defaults($item, 'allow_gid', ''));
878 $item['deny_cid'] = trim(defaults($item, 'deny_cid', ''));
879 $item['deny_gid'] = trim(defaults($item, 'deny_gid', ''));
880 $item['private'] = intval(defaults($item, 'private', 0));
881 $item['bookmark'] = intval(defaults($item, 'bookmark', 0));
882 $item['body'] = trim(defaults($item, 'body', ''));
883 $item['tag'] = trim(defaults($item, 'tag', ''));
884 $item['attach'] = trim(defaults($item, 'attach', ''));
885 $item['app'] = trim(defaults($item, 'app', ''));
886 $item['origin'] = intval(defaults($item, 'origin', 0));
887 $item['postopts'] = trim(defaults($item, 'postopts', ''));
888 $item['resource-id'] = trim(defaults($item, 'resource-id', ''));
889 $item['event-id'] = intval(defaults($item, 'event-id', 0));
890 $item['inform'] = trim(defaults($item, 'inform', ''));
891 $item['file'] = trim(defaults($item, 'file', ''));
893 // When there is no content then we don't post it
894 if ($item['body'].$item['title'] == '') {
898 // Items cannot be stored before they happen ...
899 if ($item['created'] > DateTimeFormat::utcNow()) {
900 $item['created'] = DateTimeFormat::utcNow();
903 // We haven't invented time travel by now.
904 if ($item['edited'] > DateTimeFormat::utcNow()) {
905 $item['edited'] = DateTimeFormat::utcNow();
908 if (($item['author-link'] == "") && ($item['owner-link'] == "")) {
909 logger("Both author-link and owner-link are empty. Called by: " . System::callstack(), LOGGER_DEBUG);
912 $item['plink'] = defaults($item, 'plink', System::baseUrl() . '/display/' . urlencode($item['guid']));
914 // The contact-id should be set before "self::insert" was called - but there seems to be issues sometimes
915 $item["contact-id"] = self::contactId($item);
917 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
918 'photo' => $item['author-avatar'], 'network' => $item['network']];
920 $item['author-id'] = defaults($item, 'author-id', Contact::getIdForURL($item["author-link"], 0, false, $default));
922 if (Contact::isBlocked($item["author-id"])) {
923 logger('Contact '.$item["author-id"].' is blocked, item '.$item["uri"].' will not be stored');
927 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
928 'photo' => $item['owner-avatar'], 'network' => $item['network']];
930 $item['owner-id'] = defaults($item, 'owner-id', Contact::getIdForURL($item["owner-link"], 0, false, $default));
932 if (Contact::isBlocked($item["owner-id"])) {
933 logger('Contact '.$item["owner-id"].' is blocked, item '.$item["uri"].' will not be stored');
937 //unset($item['author-link']);
938 unset($item['author-name']);
939 unset($item['author-avatar']);
941 //unset($item['owner-link']);
942 unset($item['owner-name']);
943 unset($item['owner-avatar']);
945 if ($item['network'] == NETWORK_PHANTOM) {
946 logger('Missing network. Called by: '.System::callstack(), LOGGER_DEBUG);
948 $contact = Contact::getDetailsByURL($item['author-link'], $item['uid']);
949 if (!empty($contact['network'])) {
950 $item['network'] = $contact["network"];
952 $item['network'] = NETWORK_DFRN;
954 logger("Set network to " . $item["network"] . " for " . $item["uri"], LOGGER_DEBUG);
957 // Checking if there is already an item with the same guid
958 logger('Checking for an item for user '.$item['uid'].' on network '.$item['network'].' with the guid '.$item['guid'], LOGGER_DEBUG);
959 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
960 if (dba::exists('item', $condition)) {
961 logger('found item with guid '.$item['guid'].' for user '.$item['uid'].' on network '.$item['network'], LOGGER_DEBUG);
965 // Check for hashtags in the body and repair or add hashtag links
966 self::setHashtags($item);
968 $item['thr-parent'] = $item['parent-uri'];
976 if ($item['parent-uri'] === $item['uri']) {
979 $allow_cid = $item['allow_cid'];
980 $allow_gid = $item['allow_gid'];
981 $deny_cid = $item['deny_cid'];
982 $deny_gid = $item['deny_gid'];
983 $notify_type = 'wall-new';
985 // find the parent and snarf the item id and ACLs
986 // and anything else we need to inherit
988 $fields = ['uri', 'parent-uri', 'id', 'deleted',
989 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
990 'wall', 'private', 'forum_mode', 'origin'];
991 $condition = ['uri' => $item['parent-uri'], 'uid' => $item['uid']];
992 $params = ['order' => ['id' => false]];
993 $parent = dba::selectFirst('item', $fields, $condition, $params);
995 if (DBM::is_result($parent)) {
996 // is the new message multi-level threaded?
997 // even though we don't support it now, preserve the info
998 // and re-attach to the conversation parent.
1000 if ($parent['uri'] != $parent['parent-uri']) {
1001 $item['parent-uri'] = $parent['parent-uri'];
1003 $condition = ['uri' => $item['parent-uri'],
1004 'parent-uri' => $item['parent-uri'],
1005 'uid' => $item['uid']];
1006 $params = ['order' => ['id' => false]];
1007 $toplevel_parent = dba::selectFirst('item', $fields, $condition, $params);
1009 if (DBM::is_result($toplevel_parent)) {
1010 $parent = $toplevel_parent;
1014 $parent_id = $parent['id'];
1015 $parent_deleted = $parent['deleted'];
1016 $allow_cid = $parent['allow_cid'];
1017 $allow_gid = $parent['allow_gid'];
1018 $deny_cid = $parent['deny_cid'];
1019 $deny_gid = $parent['deny_gid'];
1020 $item['wall'] = $parent['wall'];
1021 $notify_type = 'comment-new';
1024 * If the parent is private, force privacy for the entire conversation
1025 * This differs from the above settings as it subtly allows comments from
1026 * email correspondents to be private even if the overall thread is not.
1028 if ($parent['private']) {
1029 $item['private'] = $parent['private'];
1033 * Edge case. We host a public forum that was originally posted to privately.
1034 * The original author commented, but as this is a comment, the permissions
1035 * weren't fixed up so it will still show the comment as private unless we fix it here.
1037 if ((intval($parent['forum_mode']) == 1) && $parent['private']) {
1038 $item['private'] = 0;
1041 // If its a post from myself then tag the thread as "mention"
1042 logger("Checking if parent ".$parent_id." has to be tagged as mention for user ".$item['uid'], LOGGER_DEBUG);
1043 $user = dba::selectFirst('user', ['nickname'], ['uid' => $item['uid']]);
1044 if (DBM::is_result($user)) {
1045 $self = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
1046 logger("'myself' is ".$self." for parent ".$parent_id." checking against ".$item['author-link']." and ".$item['owner-link'], LOGGER_DEBUG);
1047 if ((normalise_link($item['author-link']) == $self) || (normalise_link($item['owner-link']) == $self)) {
1048 dba::update('thread', ['mention' => true], ['iid' => $parent_id]);
1049 logger("tagged thread ".$parent_id." as mention for user ".$self, LOGGER_DEBUG);
1054 * Allow one to see reply tweets from status.net even when
1055 * we don't have or can't see the original post.
1057 if ($force_parent) {
1058 logger('$force_parent=true, reply converted to top-level post.');
1060 $item['parent-uri'] = $item['uri'];
1061 $item['gravity'] = 0;
1063 logger('item parent '.$item['parent-uri'].' for '.$item['uid'].' was not found - ignoring item');
1067 $parent_deleted = 0;
1071 $condition = ["`uri` = ? AND `network` IN (?, ?) AND `uid` = ?",
1072 $item['uri'], $item['network'], NETWORK_DFRN, $item['uid']];
1073 if (dba::exists('item', $condition)) {
1074 logger('duplicated item with the same uri found. '.print_r($item,true));
1078 // On Friendica and Diaspora the GUID is unique
1079 if (in_array($item['network'], [NETWORK_DFRN, NETWORK_DIASPORA])) {
1080 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
1081 if (dba::exists('item', $condition)) {
1082 logger('duplicated item with the same guid found. '.print_r($item,true));
1086 // Check for an existing post with the same content. There seems to be a problem with OStatus.
1087 $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
1088 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
1089 if (dba::exists('item', $condition)) {
1090 logger('duplicated item with the same body found. '.print_r($item,true));
1095 // Is this item available in the global items (with uid=0)?
1096 if ($item["uid"] == 0) {
1097 $item["global"] = true;
1099 // Set the global flag on all items if this was a global item entry
1100 dba::update('item', ['global' => true], ['uri' => $item["uri"]]);
1102 $item["global"] = dba::exists('item', ['uid' => 0, 'uri' => $item["uri"]]);
1106 if (strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid)) {
1109 $private = $item['private'];
1112 $item["allow_cid"] = $allow_cid;
1113 $item["allow_gid"] = $allow_gid;
1114 $item["deny_cid"] = $deny_cid;
1115 $item["deny_gid"] = $deny_gid;
1116 $item["private"] = $private;
1117 $item["deleted"] = $parent_deleted;
1119 // Fill the cache field
1120 put_item_in_cache($item);
1123 Addon::callHooks('post_local', $item);
1125 Addon::callHooks('post_remote', $item);
1128 // This array field is used to trigger some automatic reactions
1129 // It is mainly used in the "post_local" hook.
1130 unset($item['api_source']);
1132 if (x($item, 'cancel')) {
1133 logger('post cancelled by addon.');
1138 * Check for already added items.
1139 * There is a timing issue here that sometimes creates double postings.
1140 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
1142 if ($item["uid"] == 0) {
1143 if (dba::exists('item', ['uri' => trim($item['uri']), 'uid' => 0])) {
1144 logger('Global item already stored. URI: '.$item['uri'].' on network '.$item['network'], LOGGER_DEBUG);
1149 logger('' . print_r($item,true), LOGGER_DATA);
1152 $ret = dba::insert('item', $item);
1154 // When the item was successfully stored we fetch the ID of the item.
1155 if (DBM::is_result($ret)) {
1156 $current_post = dba::lastInsertId();
1158 // This can happen - for example - if there are locking timeouts.
1161 // Store the data into a spool file so that we can try again later.
1163 // At first we restore the Diaspora signature that we removed above.
1164 if (isset($encoded_signature)) {
1165 $item['dsprsig'] = $encoded_signature;
1168 // Now we store the data in the spool directory
1169 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
1170 $file = 'item-'.round(microtime(true) * 10000).'-'.mt_rand().'.msg';
1172 $spoolpath = get_spoolpath();
1173 if ($spoolpath != "") {
1174 $spool = $spoolpath.'/'.$file;
1175 file_put_contents($spool, json_encode($item));
1176 logger("Item wasn't stored - Item was spooled into file ".$file, LOGGER_DEBUG);
1181 if ($current_post == 0) {
1182 // This is one of these error messages that never should occur.
1183 logger("couldn't find created item - we better quit now.");
1188 // How much entries have we created?
1189 // We wouldn't need this query when we could use an unique index - but MySQL has length problems with them.
1190 $entries = dba::count('item', ['uri' => $item['uri'], 'uid' => $item['uid'], 'network' => $item['network']]);
1193 // There are duplicates. We delete our just created entry.
1194 logger('Duplicated post occurred. uri = ' . $item['uri'] . ' uid = ' . $item['uid']);
1196 // Yes, we could do a rollback here - but we are having many users with MyISAM.
1197 dba::delete('item', ['id' => $current_post]);
1200 } elseif ($entries == 0) {
1201 // This really should never happen since we quit earlier if there were problems.
1202 logger("Something is terribly wrong. We haven't found our created entry.");
1207 logger('created item '.$current_post);
1208 self::updateContact($item);
1210 if (!$parent_id || ($item['parent-uri'] === $item['uri'])) {
1211 $parent_id = $current_post;
1215 dba::update('item', ['parent' => $parent_id], ['id' => $current_post]);
1217 $item['id'] = $current_post;
1218 $item['parent'] = $parent_id;
1220 // update the commented timestamp on the parent
1221 // Only update "commented" if it is really a comment
1222 if (($item['verb'] == ACTIVITY_POST) || !Config::get("system", "like_no_comment")) {
1223 dba::update('item', ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1225 dba::update('item', ['changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1230 * Friendica servers lower than 3.4.3-2 had double encoded the signature ...
1231 * We can check for this condition when we decode and encode the stuff again.
1233 if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) {
1234 $dsprsig->signature = base64_decode($dsprsig->signature);
1235 logger("Repaired double encoded signature from handle ".$dsprsig->signer, LOGGER_DEBUG);
1238 dba::insert('sign', ['iid' => $current_post, 'signed_text' => $dsprsig->signed_text,
1239 'signature' => $dsprsig->signature, 'signer' => $dsprsig->signer]);
1242 if (!empty($diaspora_signed_text)) {
1243 // Formerly we stored the signed text, the signature and the author in different fields.
1244 // We now store the raw data so that we are more flexible.
1245 dba::insert('sign', ['iid' => $current_post, 'signed_text' => $diaspora_signed_text]);
1248 $deleted = self::tagDeliver($item['uid'], $current_post);
1251 * current post can be deleted if is for a community page and no mention are
1254 if (!$deleted && !$dontcache) {
1255 $posted_item = dba::selectFirst('item', [], ['id' => $current_post]);
1256 if (DBM::is_result($posted_item)) {
1258 Addon::callHooks('post_local_end', $posted_item);
1260 Addon::callHooks('post_remote_end', $posted_item);
1263 logger('new item not found in DB, id ' . $current_post);
1267 if ($item['parent-uri'] === $item['uri']) {
1268 self::addThread($current_post);
1270 self::updateThread($parent_id);
1276 * Due to deadlock issues with the "term" table we are doing these steps after the commit.
1277 * This is not perfect - but a workable solution until we found the reason for the problem.
1279 Term::insertFromTagFieldByItemId($current_post);
1280 Term::insertFromFileFieldByItemId($current_post);
1282 if ($item['parent-uri'] === $item['uri']) {
1283 self::addShadow($current_post);
1285 self::addShadowPost($current_post);
1288 check_user_notification($current_post);
1291 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", $notify_type, $current_post);
1292 } elseif (!empty($parent) && $parent['origin']) {
1293 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "Notifier", "comment-import", $current_post);
1296 return $current_post;
1300 * @brief Distributes public items to the receivers
1302 * @param integer $itemid Item ID that should be added
1303 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
1305 public static function distribute($itemid, $signed_text = '')
1307 $condition = ["`id` IN (SELECT `parent` FROM `item` WHERE `id` = ?)", $itemid];
1308 $parent = dba::selectFirst('item', ['owner-id'], $condition);
1309 if (!DBM::is_result($parent)) {
1313 // Only distribute public items from native networks
1314 $condition = ['id' => $itemid, 'uid' => 0,
1315 'network' => [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""],
1316 'visible' => true, 'deleted' => false, 'moderated' => false, 'private' => false];
1317 $item = dba::selectFirst('item', [], ['id' => $itemid]);
1318 if (!DBM::is_result($item)) {
1323 unset($item['parent']);
1324 unset($item['mention']);
1325 unset($item['wall']);
1326 unset($item['origin']);
1327 unset($item['starred']);
1328 unset($item['rendered-hash']);
1329 unset($item['rendered-html']);
1333 $condition = ["`nurl` IN (SELECT `nurl` FROM `contact` WHERE `id` = ?) AND `uid` != 0 AND NOT `blocked` AND `rel` IN (?, ?)",
1334 $parent['owner-id'], CONTACT_IS_SHARING, CONTACT_IS_FRIEND];
1335 $contacts = dba::select('contact', ['uid'], $condition);
1336 while ($contact = dba::fetch($contacts)) {
1337 $users[$contact['uid']] = $contact['uid'];
1342 if ($item['uri'] != $item['parent-uri']) {
1343 $parents = dba::select('item', ['uid', 'origin'], ["`uri` = ? AND `uid` != 0", $item['parent-uri']]);
1344 while ($parent = dba::fetch($parents)) {
1345 $users[$parent['uid']] = $parent['uid'];
1346 if ($parent['origin'] && !$item['origin']) {
1347 $origin_uid = $parent['uid'];
1352 foreach ($users as $uid) {
1353 if ($origin_uid == $uid) {
1354 $item['diaspora_signed_text'] = $signed_text;
1356 self::storeForUser($itemid, $item, $uid);
1361 * @brief Store public items for the receivers
1363 * @param integer $itemid Item ID that should be added
1364 * @param array $item The item entry that will be stored
1365 * @param integer $uid The user that will receive the item entry
1367 private static function storeForUser($itemid, $item, $uid)
1369 $item['uid'] = $uid;
1370 $item['origin'] = 0;
1372 if ($item['uri'] == $item['parent-uri']) {
1373 $item['contact-id'] = Contact::getIdForURL($item['owner-link'], $uid);
1375 $item['contact-id'] = Contact::getIdForURL($item['author-link'], $uid);
1378 if (empty($item['contact-id'])) {
1379 $self = dba::selectFirst('contact', ['id'], ['self' => true, 'uid' => $uid]);
1380 if (!DBM::is_result($self)) {
1383 $item['contact-id'] = $self['id'];
1386 if (in_array($item['type'], ["net-comment", "wall-comment"])) {
1387 $item['type'] = 'remote-comment';
1388 } elseif ($item['type'] == 'wall') {
1389 $item['type'] = 'remote';
1392 /// @todo Handling of "event-id"
1395 if ($item['uri'] == $item['parent-uri']) {
1396 $contact = dba::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
1397 if (DBM::is_result($contact)) {
1398 $notify = self::isRemoteSelf($contact, $item);
1402 $distributed = self::insert($item, false, $notify, true);
1404 if (!$distributed) {
1405 logger("Distributed public item " . $itemid . " for user " . $uid . " wasn't stored", LOGGER_DEBUG);
1407 logger("Distributed public item " . $itemid . " for user " . $uid . " with id " . $distributed, LOGGER_DEBUG);
1412 * @brief Add a shadow entry for a given item id that is a thread starter
1414 * We store every public item entry additionally with the user id "0".
1415 * This is used for the community page and for the search.
1416 * It is planned that in the future we will store public item entries only once.
1418 * @param integer $itemid Item ID that should be added
1420 public static function addShadow($itemid)
1422 $fields = ['uid', 'private', 'moderated', 'visible', 'deleted', 'network'];
1423 $condition = ['id' => $itemid, 'parent' => [0, $itemid]];
1424 $item = dba::selectFirst('item', $fields, $condition);
1426 if (!DBM::is_result($item)) {
1430 // is it already a copy?
1431 if (($itemid == 0) || ($item['uid'] == 0)) {
1435 // Is it a visible public post?
1436 if (!$item["visible"] || $item["deleted"] || $item["moderated"] || $item["private"]) {
1440 // is it an entry from a connector? Only add an entry for natively connected networks
1441 if (!in_array($item["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""])) {
1445 $item = dba::selectFirst('item', [], ['id' => $itemid]);
1447 if (DBM::is_result($item) && ($item["allow_cid"] == '') && ($item["allow_gid"] == '') &&
1448 ($item["deny_cid"] == '') && ($item["deny_gid"] == '')) {
1450 if (!dba::exists('item', ['uri' => $item['uri'], 'uid' => 0])) {
1451 // Preparing public shadow (removing user specific data)
1454 unset($item['parent']);
1455 unset($item['wall']);
1456 unset($item['mention']);
1457 unset($item['origin']);
1458 unset($item['starred']);
1459 unset($item['rendered-hash']);
1460 unset($item['rendered-html']);
1461 if ($item['uri'] == $item['parent-uri']) {
1462 $item['contact-id'] = Contact::getIdForURL($item['owner-link']);
1464 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
1467 if (in_array($item['type'], ["net-comment", "wall-comment"])) {
1468 $item['type'] = 'remote-comment';
1469 } elseif ($item['type'] == 'wall') {
1470 $item['type'] = 'remote';
1473 $public_shadow = self::insert($item, false, false, true);
1475 logger("Stored public shadow for thread ".$itemid." under id ".$public_shadow, LOGGER_DEBUG);
1481 * @brief Add a shadow entry for a given item id that is a comment
1483 * This function does the same like the function above - but for comments
1485 * @param integer $itemid Item ID that should be added
1487 public static function addShadowPost($itemid)
1489 $item = dba::selectFirst('item', [], ['id' => $itemid]);
1490 if (!DBM::is_result($item)) {
1494 // Is it a toplevel post?
1495 if ($item['id'] == $item['parent']) {
1496 self::addShadow($itemid);
1500 // Is this a shadow entry?
1501 if ($item['uid'] == 0) {
1505 // Is there a shadow parent?
1506 if (!dba::exists('item', ['uri' => $item['parent-uri'], 'uid' => 0])) {
1510 // Is there already a shadow entry?
1511 if (dba::exists('item', ['uri' => $item['uri'], 'uid' => 0])) {
1515 // Save "origin" and "parent" state
1516 $origin = $item['origin'];
1517 $parent = $item['parent'];
1519 // Preparing public shadow (removing user specific data)
1522 unset($item['parent']);
1523 unset($item['wall']);
1524 unset($item['mention']);
1525 unset($item['origin']);
1526 unset($item['starred']);
1527 unset($item['rendered-hash']);
1528 unset($item['rendered-html']);
1529 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
1531 if (in_array($item['type'], ["net-comment", "wall-comment"])) {
1532 $item['type'] = 'remote-comment';
1533 } elseif ($item['type'] == 'wall') {
1534 $item['type'] = 'remote';
1537 $public_shadow = self::insert($item, false, false, true);
1539 logger("Stored public shadow for comment ".$item['uri']." under id ".$public_shadow, LOGGER_DEBUG);
1541 // If this was a comment to a Diaspora post we don't get our comment back.
1542 // This means that we have to distribute the comment by ourselves.
1543 if ($origin && dba::exists('item', ['id' => $parent, 'network' => NETWORK_DIASPORA])) {
1544 self::distribute($public_shadow);
1549 * Adds a "lang" specification in a "postopts" element of given $arr,
1550 * if possible and not already present.
1551 * Expects "body" element to exist in $arr.
1553 private static function addLanguageInPostopts(&$item)
1557 if (!empty($item['postopts'])) {
1558 if (strstr($item['postopts'], 'lang=')) {
1562 $postopts = $item['postopts'];
1565 $naked_body = Text\BBCode::toPlaintext($item['body'], false);
1567 $languages = (new Text_LanguageDetect())->detect($naked_body, 3);
1569 if (sizeof($languages) > 0) {
1570 if ($postopts != '') {
1571 $postopts .= '&'; // arbitrary separator, to be reviewed
1574 $postopts .= 'lang=';
1577 foreach ($languages as $language => $score) {
1578 $postopts .= $sep . $language . ";" . $score;
1581 $item['postopts'] = $postopts;
1586 * @brief Creates an unique guid out of a given uri
1588 * @param string $uri uri of an item entry
1589 * @param string $host hostname for the GUID prefix
1590 * @return string unique guid
1592 public static function guidFromUri($uri, $host)
1594 // Our regular guid routine is using this kind of prefix as well
1595 // We have to avoid that different routines could accidentally create the same value
1596 $parsed = parse_url($uri);
1598 // We use a hash of the hostname as prefix for the guid
1599 $guid_prefix = hash("crc32", $host);
1601 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
1602 unset($parsed["scheme"]);
1604 // Glue it together to be able to make a hash from it
1605 $host_id = implode("/", $parsed);
1607 // We could use any hash algorithm since it isn't a security issue
1608 $host_hash = hash("ripemd128", $host_id);
1610 return $guid_prefix.$host_hash;
1614 * generate an unique URI
1616 * @param integer $uid User id
1617 * @param string $guid An existing GUID (Otherwise it will be generated)
1621 public static function newURI($uid, $guid = "")
1624 $guid = get_guid(32);
1627 $hostname = self::getApp()->get_hostname();
1629 $user = dba::selectFirst('user', ['nickname'], ['uid' => $uid]);
1631 $uri = "urn:X-dfrn:" . $hostname . ':' . $user['nickname'] . ':' . $guid;
1637 * @brief Set "success_update" and "last-item" to the date of the last time we heard from this contact
1639 * This can be used to filter for inactive contacts.
1640 * Only do this for public postings to avoid privacy problems, since poco data is public.
1641 * Don't set this value if it isn't from the owner (could be an author that we don't know)
1643 * @param array $arr Contains the just posted item record
1645 private static function updateContact($arr)
1647 // Unarchive the author
1648 $contact = dba::selectFirst('contact', [], ['id' => $arr["author-id"]]);
1649 if (DBM::is_result($contact)) {
1650 Contact::unmarkForArchival($contact);
1653 // Unarchive the contact if it's not our own contact
1654 $contact = dba::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
1655 if (DBM::is_result($contact)) {
1656 Contact::unmarkForArchival($contact);
1659 $update = (!$arr['private'] && (($arr["author-link"] === $arr["owner-link"]) || ($arr["parent-uri"] === $arr["uri"])));
1661 // Is it a forum? Then we don't care about the rules from above
1662 if (!$update && ($arr["network"] == NETWORK_DFRN) && ($arr["parent-uri"] === $arr["uri"])) {
1663 if (dba::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
1669 dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
1670 ['id' => $arr['contact-id']]);
1672 // Now do the same for the system wide contacts with uid=0
1673 if (!$arr['private']) {
1674 dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
1675 ['id' => $arr['owner-id']]);
1677 if ($arr['owner-id'] != $arr['author-id']) {
1678 dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
1679 ['id' => $arr['author-id']]);
1684 public static function setHashtags(&$item)
1687 $tags = get_tags($item["body"]);
1690 if (!count($tags)) {
1694 // This sorting is important when there are hashtags that are part of other hashtags
1695 // Otherwise there could be problems with hashtags like #test and #test2
1698 $URLSearchString = "^\[\]";
1700 // All hashtags should point to the home server if "local_tags" is activated
1701 if (Config::get('system', 'local_tags')) {
1702 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1703 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["body"]);
1705 $item["tag"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1706 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["tag"]);
1709 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
1710 $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1712 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
1715 $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
1717 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
1720 $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
1722 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
1725 // Repair recursive urls
1726 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1727 "#$2", $item["body"]);
1729 foreach ($tags as $tag) {
1730 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=')) {
1734 $basetag = str_replace('_',' ',substr($tag,1));
1736 $newtag = '#[url=' . System::baseUrl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1738 $item["body"] = str_replace($tag, $newtag, $item["body"]);
1740 if (!stristr($item["tag"], "/search?tag=" . $basetag . "]" . $basetag . "[/url]")) {
1741 if (strlen($item["tag"])) {
1742 $item["tag"] = ','.$item["tag"];
1744 $item["tag"] = $newtag.$item["tag"];
1748 // Convert back the masked hashtags
1749 $item["body"] = str_replace("#", "#", $item["body"]);
1752 public static function getGuidById($id)
1754 $item = dba::selectFirst('item', ['guid'], ['id' => $id]);
1755 if (DBM::is_result($item)) {
1756 return $item['guid'];
1762 public static function getIdAndNickByGuid($guid, $uid = 0)
1768 $uid == local_user();
1771 // Does the given user have this item?
1773 $item = dba::fetch_first("SELECT `item`.`id`, `user`.`nickname` FROM `item`
1774 INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
1775 WHERE `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
1776 AND `item`.`guid` = ? AND `item`.`uid` = ?", $guid, $uid);
1777 if (DBM::is_result($item)) {
1779 $nick = $item["nickname"];
1783 // Or is it anywhere on the server?
1785 $item = dba::fetch_first("SELECT `item`.`id`, `user`.`nickname` FROM `item`
1786 INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
1787 WHERE `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
1788 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1789 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1790 AND NOT `item`.`private` AND `item`.`wall`
1791 AND `item`.`guid` = ?", $guid);
1792 if (DBM::is_result($item)) {
1794 $nick = $item["nickname"];
1797 return ["nick" => $nick, "id" => $id];
1801 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
1803 * @param int $item_id
1804 * @return bool true if item was deleted, else false
1806 private static function tagDeliver($uid, $item_id)
1810 $user = dba::selectFirst('user', [], ['uid' => $uid]);
1811 if (!DBM::is_result($user)) {
1815 $community_page = (($user['page-flags'] == PAGE_COMMUNITY) ? true : false);
1816 $prvgroup = (($user['page-flags'] == PAGE_PRVGROUP) ? true : false);
1818 $item = dba::selectFirst('item', [], ['id' => $item_id]);
1819 if (!DBM::is_result($item)) {
1823 $link = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
1826 * Diaspora uses their own hardwired link URL in @-tags
1827 * instead of the one we supply with webfinger
1829 $dlink = normalise_link(System::baseUrl() . '/u/' . $user['nickname']);
1831 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
1833 foreach ($matches as $mtch) {
1834 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
1836 logger('mention found: ' . $mtch[2]);
1842 if (($community_page || $prvgroup) &&
1843 !$item['wall'] && !$item['origin'] && ($item['id'] == $item['parent'])) {
1844 // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
1846 logger("no-mention top-level post to community or private group. delete.");
1847 dba::delete('item', ['id' => $item_id]);
1853 $arr = ['item' => $item, 'user' => $user];
1855 Addon::callHooks('tagged', $arr);
1857 if (!$community_page && !$prvgroup) {
1862 * tgroup delivery - setup a second delivery chain
1863 * prevent delivery looping - only proceed
1864 * if the message originated elsewhere and is a top-level post
1866 if ($item['wall'] || $item['origin'] || ($item['id'] != $item['parent'])) {
1870 // now change this copy of the post to a forum head message and deliver to all the tgroup members
1871 $self = dba::selectFirst('contact', ['id', 'name', 'url', 'thumb'], ['uid' => $uid, 'self' => true]);
1872 if (!DBM::is_result($self)) {
1876 $owner_id = Contact::getIdForURL($self['url']);
1878 // also reset all the privacy bits to the forum default permissions
1880 $private = ($user['allow_cid'] || $user['allow_gid'] || $user['deny_cid'] || $user['deny_gid']) ? 1 : 0;
1882 $forum_mode = ($prvgroup ? 2 : 1);
1884 $fields = ['wall' => true, 'origin' => true, 'forum_mode' => $forum_mode, 'contact-id' => $self['id'],
1885 'owner-id' => $owner_id, 'owner-link' => $self['url'], 'private' => $private, 'allow_cid' => $user['allow_cid'],
1886 'allow_gid' => $user['allow_gid'], 'deny_cid' => $user['deny_cid'], 'deny_gid' => $user['deny_gid']];
1887 dba::update('item', $fields, ['id' => $item_id]);
1889 self::updateThread($item_id);
1891 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', 'tgroup', $item_id);
1894 public static function isRemoteSelf($contact, &$datarray)
1898 if (!$contact['remote_self']) {
1902 // Prevent the forwarding of posts that are forwarded
1903 if ($datarray["extid"] == NETWORK_DFRN) {
1904 logger('Already forwarded', LOGGER_DEBUG);
1908 // Prevent to forward already forwarded posts
1909 if ($datarray["app"] == $a->get_hostname()) {
1910 logger('Already forwarded (second test)', LOGGER_DEBUG);
1914 // Only forward posts
1915 if ($datarray["verb"] != ACTIVITY_POST) {
1916 logger('No post', LOGGER_DEBUG);
1920 if (($contact['network'] != NETWORK_FEED) && $datarray['private']) {
1921 logger('Not public', LOGGER_DEBUG);
1925 $datarray2 = $datarray;
1926 logger('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), LOGGER_DEBUG);
1927 if ($contact['remote_self'] == 2) {
1928 $self = dba::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
1929 ['uid' => $contact['uid'], 'self' => true]);
1930 if (DBM::is_result($self)) {
1931 $datarray['contact-id'] = $self["id"];
1933 $datarray['owner-name'] = $self["name"];
1934 $datarray['owner-link'] = $self["url"];
1935 $datarray['owner-avatar'] = $self["thumb"];
1937 $datarray['author-name'] = $datarray['owner-name'];
1938 $datarray['author-link'] = $datarray['owner-link'];
1939 $datarray['author-avatar'] = $datarray['owner-avatar'];
1941 unset($datarray['created']);
1942 unset($datarray['edited']);
1944 unset($datarray['network']);
1945 unset($datarray['owner-id']);
1946 unset($datarray['author-id']);
1949 if ($contact['network'] != NETWORK_FEED) {
1950 $datarray["guid"] = get_guid(32);
1951 unset($datarray["plink"]);
1952 $datarray["uri"] = self::newURI($contact['uid'], $datarray["guid"]);
1953 $datarray["parent-uri"] = $datarray["uri"];
1954 $datarray["thr-parent"] = $datarray["uri"];
1955 $datarray["extid"] = NETWORK_DFRN;
1956 $urlpart = parse_url($datarray2['author-link']);
1957 $datarray["app"] = $urlpart["host"];
1959 $datarray['private'] = 0;
1963 if ($contact['network'] != NETWORK_FEED) {
1964 // Store the original post
1965 $result = self::insert($datarray2, false, false);
1966 logger('remote-self post original item - Contact '.$contact['url'].' return '.$result.' Item '.print_r($datarray2, true), LOGGER_DEBUG);
1968 $datarray["app"] = "Feed";
1972 // Trigger automatic reactions for addons
1973 $datarray['api_source'] = true;
1975 // We have to tell the hooks who we are - this really should be improved
1976 $_SESSION["authenticated"] = true;
1977 $_SESSION["uid"] = $contact['uid'];
1986 * @param array $item
1990 public static function fixPrivatePhotos($s, $uid, $item = null, $cid = 0)
1992 if (Config::get('system', 'disable_embedded')) {
1996 logger('check for photos', LOGGER_DEBUG);
1997 $site = substr(System::baseUrl(), strpos(System::baseUrl(), '://'));
2002 $img_start = strpos($orig_body, '[img');
2003 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2004 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2006 while (($img_st_close !== false) && ($img_len !== false)) {
2007 $img_st_close++; // make it point to AFTER the closing bracket
2008 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2010 logger('found photo ' . $image, LOGGER_DEBUG);
2012 if (stristr($image, $site . '/photo/')) {
2013 // Only embed locally hosted photos
2015 $i = basename($image);
2016 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2017 $x = strpos($i, '-');
2020 $res = substr($i, $x + 1);
2021 $i = substr($i, 0, $x);
2022 $fields = ['data', 'type', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'];
2023 $photo = dba::selectFirst('photo', $fields, ['resource-id' => $i, 'scale' => $res, 'uid' => $uid]);
2024 if (DBM::is_result($photo)) {
2026 * Check to see if we should replace this photo link with an embedded image
2027 * 1. No need to do so if the photo is public
2028 * 2. If there's a contact-id provided, see if they're in the access list
2029 * for the photo. If so, embed it.
2030 * 3. Otherwise, if we have an item, see if the item permissions match the photo
2031 * permissions, regardless of order but first check to see if they're an exact
2032 * match to save some processing overhead.
2034 if (self::hasPermissions($photo)) {
2036 $recips = self::enumeratePermissions($photo);
2037 if (in_array($cid, $recips)) {
2041 if (self::samePermissions($item, $photo)) {
2047 $data = $photo['data'];
2048 $type = $photo['type'];
2050 // If a custom width and height were specified, apply before embedding
2051 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2052 logger('scaling photo', LOGGER_DEBUG);
2054 $width = intval($match[1]);
2055 $height = intval($match[2]);
2057 $Image = new Image($data, $type);
2058 if ($Image->isValid()) {
2059 $Image->scaleDown(max($width, $height));
2060 $data = $Image->asString();
2061 $type = $Image->getType();
2065 logger('replacing photo', LOGGER_DEBUG);
2066 $image = 'data:' . $type . ';base64,' . base64_encode($data);
2067 logger('replaced: ' . $image, LOGGER_DATA);
2073 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2074 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2075 if ($orig_body === false) {
2079 $img_start = strpos($orig_body, '[img');
2080 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2081 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2084 $new_body = $new_body . $orig_body;
2089 private static function hasPermissions($obj)
2093 x($obj, 'allow_cid')
2095 x($obj, 'allow_gid')
2104 private static function samePermissions($obj1, $obj2)
2106 // first part is easy. Check that these are exactly the same.
2107 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2108 && ($obj1['allow_gid'] == $obj2['allow_gid'])
2109 && ($obj1['deny_cid'] == $obj2['deny_cid'])
2110 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
2114 // This is harder. Parse all the permissions and compare the resulting set.
2115 $recipients1 = self::enumeratePermissions($obj1);
2116 $recipients2 = self::enumeratePermissions($obj2);
2120 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2121 return ($recipients1 == $recipients2);
2124 // returns an array of contact-ids that are allowed to see this object
2125 private static function enumeratePermissions($obj)
2127 $allow_people = expand_acl($obj['allow_cid']);
2128 $allow_groups = Group::expand(expand_acl($obj['allow_gid']));
2129 $deny_people = expand_acl($obj['deny_cid']);
2130 $deny_groups = Group::expand(expand_acl($obj['deny_gid']));
2131 $recipients = array_unique(array_merge($allow_people, $allow_groups));
2132 $deny = array_unique(array_merge($deny_people, $deny_groups));
2133 $recipients = array_diff($recipients, $deny);
2137 public static function getFeedTags($item)
2141 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2143 for ($x = 0; $x < $cnt; $x ++) {
2144 if ($matches[1][$x]) {
2145 $ret[$matches[2][$x]] = ['#', $matches[1][$x], $matches[2][$x]];
2150 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2152 for ($x = 0; $x < $cnt; $x ++) {
2153 if ($matches[1][$x]) {
2154 $ret[] = ['@', $matches[1][$x], $matches[2][$x]];
2161 public static function expire($uid, $days, $network = "", $force = false)
2163 if (!$uid || ($days < 1)) {
2168 * $expire_network_only = save your own wall posts
2169 * and just expire conversations started by others
2171 $expire_network_only = PConfig::get($uid,'expire', 'network_only');
2172 $sql_extra = (intval($expire_network_only) ? " AND wall = 0 " : "");
2174 if ($network != "") {
2175 $sql_extra .= sprintf(" AND network = '%s' ", dbesc($network));
2178 * There is an index "uid_network_received" but not "uid_network_created"
2179 * This avoids the creation of another index just for one purpose.
2180 * And it doesn't really matter wether to look at "received" or "created"
2182 $range = "AND `received` < UTC_TIMESTAMP() - INTERVAL %d DAY ";
2184 $range = "AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY ";
2187 $r = q("SELECT `file`, `resource-id`, `starred`, `type`, `id` FROM `item`
2188 WHERE `uid` = %d $range
2196 if (!DBM::is_result($r)) {
2200 $expire_items = PConfig::get($uid, 'expire', 'items', 1);
2202 // Forcing expiring of items - but not notes and marked items
2204 $expire_items = true;
2207 $expire_notes = PConfig::get($uid, 'expire', 'notes', 1);
2208 $expire_starred = PConfig::get($uid, 'expire', 'starred', 1);
2209 $expire_photos = PConfig::get($uid, 'expire', 'photos', 0);
2211 logger('User '.$uid.': expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
2213 foreach ($r as $item) {
2215 // don't expire filed items
2217 if (strpos($item['file'],'[') !== false) {
2221 // Only expire posts, not photos and photo comments
2223 if ($expire_photos == 0 && strlen($item['resource-id'])) {
2225 } elseif ($expire_starred == 0 && intval($item['starred'])) {
2227 } elseif ($expire_notes == 0 && $item['type'] == 'note') {
2229 } elseif ($expire_items == 0 && $item['type'] != 'note') {
2233 self::deleteById($item['id'], PRIORITY_LOW);
2237 public static function firstPostDate($uid, $wall = false)
2239 $condition = ['uid' => $uid, 'wall' => $wall, 'deleted' => false, 'visible' => true, 'moderated' => false];
2240 $params = ['order' => ['created' => false]];
2241 $thread = dba::selectFirst('thread', ['created'], $condition, $params);
2242 if (DBM::is_result($thread)) {
2243 return substr(DateTimeFormat::local($thread['created']), 0, 10);
2249 * @brief add/remove activity to an item
2251 * Toggle activities as like,dislike,attend of an item
2253 * @param string $item_id
2254 * @param string $verb
2255 * Activity verb. One of
2256 * like, unlike, dislike, undislike, attendyes, unattendyes,
2257 * attendno, unattendno, attendmaybe, unattendmaybe
2258 * @hook 'post_local_end'
2260 * 'post_id' => ID of posted item
2262 public static function performLike($item_id, $verb)
2264 if (!local_user() && !remote_user()) {
2271 $bodyverb = L10n::t('%1$s likes %2$s\'s %3$s');
2272 $activity = ACTIVITY_LIKE;
2276 $bodyverb = L10n::t('%1$s doesn\'t like %2$s\'s %3$s');
2277 $activity = ACTIVITY_DISLIKE;
2281 $bodyverb = L10n::t('%1$s is attending %2$s\'s %3$s');
2282 $activity = ACTIVITY_ATTEND;
2286 $bodyverb = L10n::t('%1$s is not attending %2$s\'s %3$s');
2287 $activity = ACTIVITY_ATTENDNO;
2290 case 'unattendmaybe':
2291 $bodyverb = L10n::t('%1$s may attend %2$s\'s %3$s');
2292 $activity = ACTIVITY_ATTENDMAYBE;
2295 logger('like: unknown verb ' . $verb . ' for item ' . $item_id);
2299 // Enable activity toggling instead of on/off
2300 $event_verb_flag = $activity === ACTIVITY_ATTEND || $activity === ACTIVITY_ATTENDNO || $activity === ACTIVITY_ATTENDMAYBE;
2302 logger('like: verb ' . $verb . ' item ' . $item_id);
2304 $item = dba::selectFirst('item', [], ['`id` = ? OR `uri` = ?', $item_id, $item_id]);
2305 if (!DBM::is_result($item)) {
2306 logger('like: unknown item ' . $item_id);
2310 $uid = $item['uid'];
2311 if (($uid == 0) && local_user()) {
2312 $uid = local_user();
2315 if (!can_write_wall($uid)) {
2316 logger('like: unable to write on wall ' . $uid);
2320 // Retrieves the local post owner
2321 $owner_self_contact = dba::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
2322 if (!DBM::is_result($owner_self_contact)) {
2323 logger('like: unknown owner ' . $uid);
2327 // Retrieve the current logged in user's public contact
2328 $author_id = public_contact();
2330 $author_contact = dba::selectFirst('contact', [], ['id' => $author_id]);
2331 if (!DBM::is_result($author_contact)) {
2332 logger('like: unknown author ' . $author_id);
2336 // Contact-id is the uid-dependant author contact
2337 if (local_user() == $uid) {
2338 $item_contact_id = $owner_self_contact['id'];
2339 $item_contact = $owner_self_contact;
2341 $item_contact_id = Contact::getIdForURL($author_contact['url'], $uid, true);
2342 $item_contact = dba::selectFirst('contact', [], ['id' => $item_contact_id]);
2343 if (!DBM::is_result($item_contact)) {
2344 logger('like: unknown item contact ' . $item_contact_id);
2349 // Look for an existing verb row
2350 // event participation are essentially radio toggles. If you make a subsequent choice,
2351 // we need to eradicate your first choice.
2352 if ($event_verb_flag) {
2353 $verbs = "'" . dbesc(ACTIVITY_ATTEND) . "', '" . dbesc(ACTIVITY_ATTENDNO) . "', '" . dbesc(ACTIVITY_ATTENDMAYBE) . "'";
2355 $verbs = "'".dbesc($activity)."'";
2358 /// @todo This query is expected to be a performance eater due to the "OR" - it has to be changed totally
2359 $existing_like = q("SELECT `id`, `guid`, `verb` FROM `item`
2360 WHERE `verb` IN ($verbs)
2362 AND `author-id` = %d
2364 AND (`parent` = '%s' OR `parent-uri` = '%s' OR `thr-parent` = '%s')
2366 intval($author_contact['id']),
2367 intval($item['uid']),
2368 dbesc($item_id), dbesc($item_id), dbesc($item['uri'])
2371 // If it exists, mark it as deleted
2372 if (DBM::is_result($existing_like)) {
2373 $like_item = $existing_like[0];
2375 // Already voted, undo it
2376 $fields = ['deleted' => true, 'unseen' => true, 'changed' => DateTimeFormat::utcNow()];
2377 dba::update('item', $fields, ['id' => $like_item['id']]);
2379 // Clean up the Diaspora signatures for this like
2380 // Go ahead and do it even if Diaspora support is disabled. We still want to clean up
2381 // if it had been enabled in the past
2382 dba::delete('sign', ['iid' => $like_item['id']]);
2384 $like_item_id = $like_item['id'];
2385 Worker::add(PRIORITY_HIGH, "Notifier", "like", $like_item_id);
2387 if (!$event_verb_flag || $like_item['verb'] == $activity) {
2392 // Verb is "un-something", just trying to delete existing entries
2393 if (strpos($verb, 'un') === 0) {
2397 // Else or if event verb different from existing row, create a new item row
2398 $post_type = (($item['resource-id']) ? L10n::t('photo') : L10n::t('status'));
2399 if ($item['object-type'] === ACTIVITY_OBJ_EVENT) {
2400 $post_type = L10n::t('event');
2402 $objtype = $item['resource-id'] ? ACTIVITY_OBJ_IMAGE : ACTIVITY_OBJ_NOTE ;
2403 $link = xmlify('<link rel="alternate" type="text/html" href="' . System::baseUrl() . '/display/' . $owner_self_contact['nick'] . '/' . $item['id'] . '" />' . "\n") ;
2404 $body = $item['body'];
2409 <type>$objtype</type>
2411 <id>{$item['uri']}</id>
2414 <content>$body</content>
2418 $ulink = '[url=' . $author_contact['url'] . ']' . $author_contact['name'] . '[/url]';
2419 $alink = '[url=' . $item['author-link'] . ']' . $item['author-name'] . '[/url]';
2420 $plink = '[url=' . System::baseUrl() . '/display/' . $owner_self_contact['nick'] . '/' . $item['id'] . ']' . $post_type . '[/url]';
2423 'guid' => get_guid(32),
2424 'uri' => self::newURI($item['uid']),
2425 'uid' => $item['uid'],
2426 'contact-id' => $item_contact_id,
2427 'type' => 'activity',
2428 'wall' => $item['wall'],
2430 'gravity' => GRAVITY_LIKE,
2431 'parent' => $item['id'],
2432 'parent-uri' => $item['uri'],
2433 'thr-parent' => $item['uri'],
2434 'owner-id' => $item['owner-id'],
2435 'owner-name' => $item['owner-name'],
2436 'owner-link' => $item['owner-link'],
2437 'owner-avatar' => $item['owner-avatar'],
2438 'author-id' => $author_contact['id'],
2439 'author-name' => $author_contact['name'],
2440 'author-link' => $author_contact['url'],
2441 'author-avatar' => $author_contact['thumb'],
2442 'body' => sprintf($bodyverb, $ulink, $alink, $plink),
2443 'verb' => $activity,
2444 'object-type' => $objtype,
2446 'allow_cid' => $item['allow_cid'],
2447 'allow_gid' => $item['allow_gid'],
2448 'deny_cid' => $item['deny_cid'],
2449 'deny_gid' => $item['deny_gid'],
2454 $new_item_id = self::insert($new_item);
2456 // If the parent item isn't visible then set it to visible
2457 if (!$item['visible']) {
2458 self::update(['visible' => true], ['id' => $item['id']]);
2461 // Save the author information for the like in case we need to relay to Diaspora
2462 Diaspora::storeLikeSignature($item_contact, $new_item_id);
2464 $new_item['id'] = $new_item_id;
2466 Addon::callHooks('post_local_end', $new_item);
2468 Worker::add(PRIORITY_HIGH, "Notifier", "like", $new_item_id);
2473 private static function addThread($itemid, $onlyshadow = false)
2475 $fields = ['uid', 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private', 'pubmail',
2476 'moderated', 'visible', 'starred', 'bookmark', 'contact-id',
2477 'deleted', 'origin', 'forum_mode', 'mention', 'network', 'author-id', 'owner-id'];
2478 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
2479 $item = dba::selectFirst('item', $fields, $condition);
2481 if (!DBM::is_result($item)) {
2485 $item['iid'] = $itemid;
2488 $result = dba::insert('thread', $item);
2490 logger("Add thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
2494 private static function updateThread($itemid, $setmention = false)
2496 $fields = ['uid', 'guid', 'title', 'body', 'created', 'edited', 'commented', 'received', 'changed',
2497 'wall', 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark', 'contact-id',
2498 'deleted', 'origin', 'forum_mode', 'network', 'author-id', 'owner-id', 'rendered-html', 'rendered-hash'];
2499 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
2501 $item = dba::selectFirst('item', $fields, $condition);
2502 if (!DBM::is_result($item)) {
2507 $item["mention"] = 1;
2514 foreach ($item as $field => $data) {
2515 if (!in_array($field, ["guid", "title", "body", "rendered-html", "rendered-hash"])) {
2516 $fields[$field] = $data;
2520 $result = dba::update('thread', $fields, ['iid' => $itemid]);
2522 logger("Update thread for item ".$itemid." - guid ".$item["guid"]." - ".(int)$result, LOGGER_DEBUG);
2524 // Updating a shadow item entry
2525 $items = dba::selectFirst('item', ['id'], ['guid' => $item['guid'], 'uid' => 0]);
2527 if (!DBM::is_result($items)) {
2531 $fields = ['title' => $item['title'], 'body' => $item['body'],
2532 'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']];
2533 $result = dba::update('item', $fields, ['id' => $items['id']]);
2535 logger("Updating public shadow for post ".$items["id"]." - guid ".$item["guid"]." Result: ".print_r($result, true), LOGGER_DEBUG);
2538 private static function deleteThread($itemid, $itemuri = "")
2540 $item = dba::selectFirst('thread', ['uid'], ['iid' => $itemid]);
2541 if (!DBM::is_result($item)) {
2542 logger('No thread found for id '.$itemid, LOGGER_DEBUG);
2546 // Using dba::delete at this time could delete the associated item entries
2547 $result = dba::e("DELETE FROM `thread` WHERE `iid` = ?", $itemid);
2549 logger("deleteThread: Deleted thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
2551 if ($itemuri != "") {
2552 $condition = ["`uri` = ? AND NOT `deleted` AND NOT (`uid` IN (?, 0))", $itemuri, $item["uid"]];
2553 if (!dba::exists('item', $condition)) {
2554 dba::delete('item', ['uri' => $itemuri, 'uid' => 0]);
2555 logger("deleteThread: Deleted shadow for item ".$itemuri, LOGGER_DEBUG);