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 public static function selectFirst($uid, array $fields = [], array $condition = [], $params = [])
39 $result = self::select($uid, $fields, $condition, $params);
41 if (is_bool($result)) {
44 $row = dba::fetch($result);
50 public static function select($uid, array $selected = [], array $condition = [], $params = [])
52 $fields = self::fieldlist();
54 $select_fields = self::constructSelectFields($fields, $selected);
56 $condition_string = dba::buildCondition($condition);
58 $condition_string = self::addTablesToFields($condition_string, $fields);
60 $condition_string = $condition_string . ' AND ' . self::condition();
62 $param_string = self::addTablesToFields(dba::buildParameter($params), $fields);
64 $table = "`item` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, false);
66 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
68 return dba::p($sql, $condition);
71 public static function selectFirstThread($uid, array $fields = [], array $condition = [], $params = [])
74 $result = self::selectThread($uid, $fields, $condition, $params);
76 if (is_bool($result)) {
79 $row = dba::fetch($result);
85 public static function selectThread($uid, array $selected = [], array $condition = [], $params = [])
87 $fields = self::fieldlist();
89 $threadfields = ['thread' => ['iid', 'uid', 'contact-id', 'owner-id', 'author-id',
90 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private',
91 'pubmail', 'moderated', 'visible', 'starred', 'ignored', 'bookmark',
92 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'network']];
94 $select_fields = self::constructSelectFields($fields, $selected);
96 $condition_string = dba::buildCondition($condition);
98 $condition_string = self::addTablesToFields($condition_string, $threadfields);
99 $condition_string = self::addTablesToFields($condition_string, $fields);
101 $condition_string = $condition_string . ' AND ' . self::condition();
103 $param_string = dba::buildParameter($params);
104 $param_string = self::addTablesToFields($param_string, $threadfields);
105 $param_string = self::addTablesToFields($param_string, $fields);
107 $table = "`thread` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, true);
109 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
111 return dba::p($sql, $condition);
114 private static function fieldlist()
116 $item_fields = ['author-id', 'owner-id', 'contact-id', 'uid', 'id', 'parent',
117 'uri', 'thr-parent', 'parent-uri', 'content-warning',
118 'commented', 'created', 'edited', 'received', 'verb', 'object-type', 'postopts', 'plink',
119 'guid', 'wall', 'private', 'starred', 'origin', 'title', 'body', 'file', 'event-id',
120 'location', 'coord', 'app', 'attach', 'rendered-hash', 'rendered-html', 'object',
121 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
122 'id' => 'item_id', 'network' => 'item_network'];
124 $author_fields = ['url' => 'author-link', 'name' => 'author-name', 'thumb' => 'author-avatar'];
125 $owner_fields = ['url' => 'owner-link', 'name' => 'owner-name', 'thumb' => 'owner-avatar'];
126 $contact_fields = ['url' => 'contact-link', 'name' => 'contact-name', 'thumb' => 'contact-avatar',
127 'network', 'url', 'name', 'writable', 'self', 'id' => 'cid', 'alias'];
129 $event_fields = ['created' => 'event-created', 'edited' => 'event-edited',
130 'start' => 'event-start','finish' => 'event-finish',
131 'summary' => 'event-summary','desc' => 'event-desc',
132 'location' => 'event-location', 'type' => 'event-type',
133 'nofinish' => 'event-nofinish','adjust' => 'event-adjust',
134 'ignore' => 'event-ignore', 'id' => 'event-id'];
136 return ['item' => $item_fields, 'author' => $author_fields, 'owner' => $owner_fields,
137 'contact' => $contact_fields, 'event' => $event_fields];
140 private static function condition()
142 return "`item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated` AND (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`) ";
145 private static function constructJoins($uid, $sql_commands, $thread_mode)
148 $master_table = "`thread`";
149 $master_table_key = "`thread`.`iid`";
150 $joins = "STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid` ";
152 $master_table = "`item`";
153 $master_table_key = "`item`.`id`";
157 $joins .= sprintf("STRAIGHT_JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`
158 AND NOT `contact`.`blocked`
159 AND ((NOT `contact`.`readonly` AND NOT `contact`.`pending` AND (`contact`.`rel` IN (%s, %s)))
160 OR `contact`.`self` OR (`item`.`id` != `item`.`parent`) OR `contact`.`uid` = 0)
161 STRAIGHT_JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id` AND NOT `author`.`blocked`
162 STRAIGHT_JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id` AND NOT `owner`.`blocked`
163 LEFT JOIN `user-item` ON `user-item`.`iid` = $master_table_key AND `user-item`.`uid` = %d",
164 CONTACT_IS_SHARING, CONTACT_IS_FRIEND, intval($uid));
166 if (strpos($sql_commands, "`group_member`.") !== false) {
167 $joins .= " STRAIGHT_JOIN `group_member` ON `group_member`.`contact-id` = $master_table.`contact-id`";
170 if (strpos($sql_commands, "`user`.") !== false) {
171 $joins .= " STRAIGHT_JOIN `user` ON `user`.`uid` = $master_table.`uid`";
174 if (strpos($sql_commands, "`event`.") !== false) {
175 $joins .= " LEFT JOIN `event` ON `event-id` = `event`.`id`";
181 private static function constructSelectFields($fields, $selected)
184 foreach ($fields as $table => $table_fields) {
185 foreach ($table_fields as $field => $select) {
186 if (empty($selected) || in_array($select, $selected)) {
187 if (is_int($field)) {
188 $selection[] = "`" . $table . "`.`".$select."`";
190 $selection[] = "`" . $table . "`.`" . $field . "` AS `".$select ."`";
195 return implode(", ", $selection);
198 private static function addTablesToFields($query, $fields)
200 foreach ($fields as $table => $table_fields) {
201 foreach ($table_fields as $alias => $field) {
202 if (is_int($alias)) {
203 $replace_field = $field;
205 $replace_field = $alias;
208 $search = "/([^\.])`" . $field . "`/i";
209 $replace = "$1`" . $table . "`.`" . $replace_field . "`";
210 $query = preg_replace($search, $replace, $query);
217 * @brief Update existing item entries
219 * @param array $fields The fields that are to be changed
220 * @param array $condition The condition for finding the item entries
222 * In the future we may have to change permissions as well.
223 * Then we had to add the user id as third parameter.
225 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
227 * @return integer|boolean number of affected rows - or "false" if there was an error
229 public static function update(array $fields, array $condition)
231 if (empty($condition) || empty($fields)) {
235 // To ensure the data integrity we do it in an transaction
238 // We cannot simply expand the condition to check for origin entries
239 // The condition needn't to be a simple array but could be a complex condition.
240 // And we have to execute this query before the update to ensure to fetch the same data.
241 $items = dba::select('item', ['id', 'origin'], $condition);
243 $success = dba::update('item', $fields, $condition);
251 $rows = dba::affected_rows();
253 while ($item = dba::fetch($items)) {
254 Term::insertFromTagFieldByItemId($item['id']);
255 Term::insertFromFileFieldByItemId($item['id']);
256 self::updateThread($item['id']);
258 // We only need to notfiy others when it is an original entry from us.
259 // Only call the notifier when the item has some content relevant change.
260 if ($item['origin'] && in_array('edited', array_keys($fields))) {
261 Worker::add(PRIORITY_HIGH, "Notifier", 'edit_post', $item['id']);
271 * @brief Delete an item and notify others about it - if it was ours
273 * @param array $condition The condition for finding the item entries
274 * @param integer $priority Priority for the notification
276 public static function delete($condition, $priority = PRIORITY_HIGH)
278 $items = dba::select('item', ['id'], $condition);
279 while ($item = dba::fetch($items)) {
280 self::deleteById($item['id'], $priority);
286 * @brief Delete an item for an user and notify others about it - if it was ours
288 * @param array $condition The condition for finding the item entries
289 * @param integer $uid User who wants to delete this item
291 public static function deleteForUser($condition, $uid)
297 $items = dba::select('item', ['id', 'uid'], $condition);
298 while ($item = dba::fetch($items)) {
299 // "Deleting" global items just means hiding them
300 if ($item['uid'] == 0) {
301 dba::update('user-item', ['hidden' => true], ['iid' => $item['id'], 'uid' => $uid], true);
302 } elseif ($item['uid'] == $uid) {
303 self::deleteById($item['id'], PRIORITY_HIGH);
305 logger('Wrong ownership. Not deleting item ' . $item['id']);
312 * @brief Delete an item and notify others about it - if it was ours
314 * @param integer $item_id Item ID that should be delete
315 * @param integer $priority Priority for the notification
317 * @return boolean success
319 private static function deleteById($item_id, $priority = PRIORITY_HIGH)
321 // locate item to be deleted
322 $fields = ['id', 'uri', 'uid', 'parent', 'parent-uri', 'origin',
323 'deleted', 'file', 'resource-id', 'event-id', 'attach',
324 'verb', 'object-type', 'object', 'target', 'contact-id'];
325 $item = dba::selectFirst('item', $fields, ['id' => $item_id]);
326 if (!DBM::is_result($item)) {
327 logger('Item with ID ' . $item_id . " hasn't been found.", LOGGER_DEBUG);
331 if ($item['deleted']) {
332 logger('Item with ID ' . $item_id . ' has already been deleted.', LOGGER_DEBUG);
336 $parent = dba::selectFirst('item', ['origin'], ['id' => $item['parent']]);
337 if (!DBM::is_result($parent)) {
338 $parent = ['origin' => false];
341 // clean up categories and tags so they don't end up as orphans
344 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
346 foreach ($matches as $mtch) {
347 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],true);
353 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
355 foreach ($matches as $mtch) {
356 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],false);
361 * If item is a link to a photo resource, nuke all the associated photos
362 * (visitors will not have photo resources)
363 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
364 * generate a resource-id and therefore aren't intimately linked to the item.
366 if (strlen($item['resource-id'])) {
367 dba::delete('photo', ['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
370 // If item is a link to an event, delete the event.
371 if (intval($item['event-id'])) {
372 Event::delete($item['event-id']);
375 // If item has attachments, drop them
376 foreach (explode(", ", $item['attach']) as $attach) {
377 preg_match("|attach/(\d+)|", $attach, $matches);
378 dba::delete('attach', ['id' => $matches[1], 'uid' => $item['uid']]);
381 // Delete tags that had been attached to other items
382 self::deleteTagsFromItem($item);
384 // Set the item to "deleted"
385 dba::update('item', ['deleted' => true, 'title' => '', 'body' => '',
386 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()],
387 ['id' => $item['id']]);
389 Term::insertFromTagFieldByItemId($item['id']);
390 Term::insertFromFileFieldByItemId($item['id']);
391 self::deleteThread($item['id'], $item['parent-uri']);
393 if (!dba::exists('item', ["`uri` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri']])) {
394 self::delete(['uri' => $item['uri'], 'uid' => 0, 'deleted' => false], $priority);
397 // If it's the parent of a comment thread, kill all the kids
398 if ($item['id'] == $item['parent']) {
399 self::delete(['parent' => $item['parent'], 'deleted' => false], $priority);
402 // Is it our comment and/or our thread?
403 if ($item['origin'] || $parent['origin']) {
405 // When we delete the original post we will delete all existing copies on the server as well
406 self::delete(['uri' => $item['uri'], 'deleted' => false], $priority);
408 // send the notification upstream/downstream
409 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", "drop", intval($item['id']));
410 } elseif ($item['uid'] != 0) {
412 // When we delete just our local user copy of an item, we have to set a marker to hide it
413 $global_item = dba::selectFirst('item', ['id'], ['uri' => $item['uri'], 'uid' => 0, 'deleted' => false]);
414 if (DBM::is_result($global_item)) {
415 dba::update('user-item', ['hidden' => true], ['iid' => $global_item['id'], 'uid' => $item['uid']], true);
419 logger('Item with ID ' . $item_id . " has been deleted.", LOGGER_DEBUG);
424 private static function deleteTagsFromItem($item)
426 if (($item["verb"] != ACTIVITY_TAG) || ($item["object-type"] != ACTIVITY_OBJ_TAGTERM)) {
430 $xo = XML::parseString($item["object"], false);
431 $xt = XML::parseString($item["target"], false);
433 if ($xt->type != ACTIVITY_OBJ_NOTE) {
437 $i = dba::selectFirst('item', ['id', 'contact-id', 'tag'], ['uri' => $xt->id, 'uid' => $item['uid']]);
438 if (!DBM::is_result($i)) {
442 // For tags, the owner cannot remove the tag on the author's copy of the post.
443 $owner_remove = ($item["contact-id"] == $i["contact-id"]);
444 $author_copy = $item["origin"];
446 if (($owner_remove && $author_copy) || !$owner_remove) {
450 $tags = explode(',', $i["tag"]);
453 foreach ($tags as $tag) {
454 if (trim($tag) !== trim($xo->body)) {
455 $newtags[] = trim($tag);
459 self::update(['tag' => implode(',', $newtags)], ['id' => $i["id"]]);
462 private static function guid($item, $notify)
464 $guid = notags(trim($item['guid']));
471 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
472 // We add the hash of our own host because our host is the original creator of the post.
473 $prefix_host = get_app()->get_hostname();
477 // We are only storing the post so we create a GUID from the original hostname.
478 if (!empty($item['author-link'])) {
479 $parsed = parse_url($item['author-link']);
480 if (!empty($parsed['host'])) {
481 $prefix_host = $parsed['host'];
485 if (empty($prefix_host) && !empty($item['plink'])) {
486 $parsed = parse_url($item['plink']);
487 if (!empty($parsed['host'])) {
488 $prefix_host = $parsed['host'];
492 if (empty($prefix_host) && !empty($item['uri'])) {
493 $parsed = parse_url($item['uri']);
494 if (!empty($parsed['host'])) {
495 $prefix_host = $parsed['host'];
499 // Is it in the format data@host.tld? - Used for mail contacts
500 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
501 $mailparts = explode('@', $item['author-link']);
502 $prefix_host = array_pop($mailparts);
506 if (!empty($item['plink'])) {
507 $guid = self::guidFromUri($item['plink'], $prefix_host);
508 } elseif (!empty($item['uri'])) {
509 $guid = self::guidFromUri($item['uri'], $prefix_host);
511 $guid = get_guid(32, hash('crc32', $prefix_host));
517 private static function contactId($item)
519 $contact_id = (int)$item["contact-id"];
521 if (!empty($contact_id)) {
524 logger('Missing contact-id. Called by: '.System::callstack(), LOGGER_DEBUG);
526 * First we are looking for a suitable contact that matches with the author of the post
527 * This is done only for comments
529 if ($item['parent-uri'] != $item['uri']) {
530 $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
533 // If not present then maybe the owner was found
534 if ($contact_id == 0) {
535 $contact_id = Contact::getIdForURL($item['owner-link'], $item['uid']);
538 // Still missing? Then use the "self" contact of the current user
539 if ($contact_id == 0) {
540 $self = dba::selectFirst('contact', ['id'], ['self' => true, 'uid' => $item['uid']]);
541 if (DBM::is_result($self)) {
542 $contact_id = $self["id"];
545 logger("Contact-id was missing for post ".$item['guid']." from user id ".$item['uid']." - now set to ".$contact_id, LOGGER_DEBUG);
550 public static function insert($item, $force_parent = false, $notify = false, $dontcache = false)
554 // If it is a posting where users should get notifications, then define it as wall posting
557 $item['type'] = 'wall';
559 $item['network'] = NETWORK_DFRN;
560 $item['protocol'] = PROTOCOL_DFRN;
562 if (is_int($notify)) {
565 $priority = PRIORITY_HIGH;
568 $item['network'] = trim(defaults($item, 'network', NETWORK_PHANTOM));
571 $item['guid'] = self::guid($item, $notify);
572 $item['uri'] = notags(trim(defaults($item, 'uri', item_new_uri($a->get_hostname(), $item['uid'], $item['guid']))));
574 // Store conversation data
575 $item = Conversation::insert($item);
578 * If a Diaspora signature structure was passed in, pull it out of the
579 * item array and set it aside for later storage.
583 if (x($item, 'dsprsig')) {
584 $encoded_signature = $item['dsprsig'];
585 $dsprsig = json_decode(base64_decode($item['dsprsig']));
586 unset($item['dsprsig']);
589 if (!empty($item['diaspora_signed_text'])) {
590 $diaspora_signed_text = $item['diaspora_signed_text'];
591 unset($item['diaspora_signed_text']);
593 $diaspora_signed_text = '';
596 // Converting the plink
597 /// @TODO Check if this is really still needed
598 if ($item['network'] == NETWORK_OSTATUS) {
599 if (isset($item['plink'])) {
600 $item['plink'] = OStatus::convertHref($item['plink']);
601 } elseif (isset($item['uri'])) {
602 $item['plink'] = OStatus::convertHref($item['uri']);
606 if (!empty($item['thr-parent'])) {
607 $item['parent-uri'] = $item['thr-parent'];
610 if (x($item, 'gravity')) {
611 $item['gravity'] = intval($item['gravity']);
612 } elseif ($item['parent-uri'] === $item['uri']) {
613 $item['gravity'] = 0;
614 } elseif (activity_match($item['verb'],ACTIVITY_POST)) {
615 $item['gravity'] = 6;
617 $item['gravity'] = 6; // extensible catchall
620 $item['type'] = defaults($item, 'type', 'remote');
622 $uid = intval($item['uid']);
624 // check for create date and expire time
625 $expire_interval = Config::get('system', 'dbclean-expire-days', 0);
627 $user = dba::selectFirst('user', ['expire'], ['uid' => $uid]);
628 if (DBM::is_result($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
629 $expire_interval = $user['expire'];
632 if (($expire_interval > 0) && !empty($item['created'])) {
633 $expire_date = time() - ($expire_interval * 86400);
634 $created_date = strtotime($item['created']);
635 if ($created_date < $expire_date) {
636 logger('item-store: item created ('.date('c', $created_date).') before expiration time ('.date('c', $expire_date).'). ignored. ' . print_r($item,true), LOGGER_DEBUG);
642 * Do we already have this item?
643 * We have to check several networks since Friendica posts could be repeated
644 * via OStatus (maybe Diasporsa as well)
646 if (in_array($item['network'], [NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS, ""])) {
647 $condition = ["`uri` = ? AND `uid` = ? AND `network` IN (?, ?, ?)",
648 trim($item['uri']), $item['uid'],
649 NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS];
650 $existing = dba::selectFirst('item', ['id', 'network'], $condition);
651 if (DBM::is_result($existing)) {
652 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
654 logger("Item with uri ".$item['uri']." already existed for user ".$uid." with id ".$existing["id"]." target network ".$existing["network"]." - new network: ".$item['network']);
657 return $existing["id"];
661 self::addLanguageInPostopts($item);
663 $item['wall'] = intval(defaults($item, 'wall', 0));
664 $item['extid'] = trim(defaults($item, 'extid', ''));
665 $item['author-name'] = trim(defaults($item, 'author-name', ''));
666 $item['author-link'] = trim(defaults($item, 'author-link', ''));
667 $item['author-avatar'] = trim(defaults($item, 'author-avatar', ''));
668 $item['owner-name'] = trim(defaults($item, 'owner-name', ''));
669 $item['owner-link'] = trim(defaults($item, 'owner-link', ''));
670 $item['owner-avatar'] = trim(defaults($item, 'owner-avatar', ''));
671 $item['received'] = ((x($item, 'received') !== false) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
672 $item['created'] = ((x($item, 'created') !== false) ? DateTimeFormat::utc($item['created']) : $item['received']);
673 $item['edited'] = ((x($item, 'edited') !== false) ? DateTimeFormat::utc($item['edited']) : $item['created']);
674 $item['changed'] = ((x($item, 'changed') !== false) ? DateTimeFormat::utc($item['changed']) : $item['created']);
675 $item['commented'] = ((x($item, 'commented') !== false) ? DateTimeFormat::utc($item['commented']) : $item['created']);
676 $item['title'] = trim(defaults($item, 'title', ''));
677 $item['location'] = trim(defaults($item, 'location', ''));
678 $item['coord'] = trim(defaults($item, 'coord', ''));
679 $item['visible'] = ((x($item, 'visible') !== false) ? intval($item['visible']) : 1);
680 $item['deleted'] = 0;
681 $item['parent-uri'] = trim(defaults($item, 'parent-uri', $item['uri']));
682 $item['verb'] = trim(defaults($item, 'verb', ''));
683 $item['object-type'] = trim(defaults($item, 'object-type', ''));
684 $item['object'] = trim(defaults($item, 'object', ''));
685 $item['target-type'] = trim(defaults($item, 'target-type', ''));
686 $item['target'] = trim(defaults($item, 'target', ''));
687 $item['plink'] = trim(defaults($item, 'plink', ''));
688 $item['allow_cid'] = trim(defaults($item, 'allow_cid', ''));
689 $item['allow_gid'] = trim(defaults($item, 'allow_gid', ''));
690 $item['deny_cid'] = trim(defaults($item, 'deny_cid', ''));
691 $item['deny_gid'] = trim(defaults($item, 'deny_gid', ''));
692 $item['private'] = intval(defaults($item, 'private', 0));
693 $item['bookmark'] = intval(defaults($item, 'bookmark', 0));
694 $item['body'] = trim(defaults($item, 'body', ''));
695 $item['tag'] = trim(defaults($item, 'tag', ''));
696 $item['attach'] = trim(defaults($item, 'attach', ''));
697 $item['app'] = trim(defaults($item, 'app', ''));
698 $item['origin'] = intval(defaults($item, 'origin', 0));
699 $item['postopts'] = trim(defaults($item, 'postopts', ''));
700 $item['resource-id'] = trim(defaults($item, 'resource-id', ''));
701 $item['event-id'] = intval(defaults($item, 'event-id', 0));
702 $item['inform'] = trim(defaults($item, 'inform', ''));
703 $item['file'] = trim(defaults($item, 'file', ''));
705 // When there is no content then we don't post it
706 if ($item['body'].$item['title'] == '') {
710 // Items cannot be stored before they happen ...
711 if ($item['created'] > DateTimeFormat::utcNow()) {
712 $item['created'] = DateTimeFormat::utcNow();
715 // We haven't invented time travel by now.
716 if ($item['edited'] > DateTimeFormat::utcNow()) {
717 $item['edited'] = DateTimeFormat::utcNow();
720 if (($item['author-link'] == "") && ($item['owner-link'] == "")) {
721 logger("Both author-link and owner-link are empty. Called by: " . System::callstack(), LOGGER_DEBUG);
724 $item['plink'] = defaults($item, 'plink', System::baseUrl() . '/display/' . urlencode($item['guid']));
726 // The contact-id should be set before "self::insert" was called - but there seems to be issues sometimes
727 $item["contact-id"] = self::contactId($item);
729 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
730 'photo' => $item['author-avatar'], 'network' => $item['network']];
732 $item['author-id'] = defaults($item, 'author-id', Contact::getIdForURL($item["author-link"], 0, false, $default));
734 if (Contact::isBlocked($item["author-id"])) {
735 logger('Contact '.$item["author-id"].' is blocked, item '.$item["uri"].' will not be stored');
739 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
740 'photo' => $item['owner-avatar'], 'network' => $item['network']];
742 $item['owner-id'] = defaults($item, 'owner-id', Contact::getIdForURL($item["owner-link"], 0, false, $default));
744 if (Contact::isBlocked($item["owner-id"])) {
745 logger('Contact '.$item["owner-id"].' is blocked, item '.$item["uri"].' will not be stored');
749 //unset($item['author-link']);
750 //unset($item['author-name']);
751 //unset($item['author-avatar']);
753 //unset($item['owner-link']);
754 unset($item['owner-name']);
755 unset($item['owner-avatar']);
757 if ($item['network'] == NETWORK_PHANTOM) {
758 logger('Missing network. Called by: '.System::callstack(), LOGGER_DEBUG);
760 $contact = Contact::getDetailsByURL($item['author-link'], $item['uid']);
761 if (!empty($contact['network'])) {
762 $item['network'] = $contact["network"];
764 $item['network'] = NETWORK_DFRN;
766 logger("Set network to " . $item["network"] . " for " . $item["uri"], LOGGER_DEBUG);
769 // Checking if there is already an item with the same guid
770 logger('Checking for an item for user '.$item['uid'].' on network '.$item['network'].' with the guid '.$item['guid'], LOGGER_DEBUG);
771 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
772 if (dba::exists('item', $condition)) {
773 logger('found item with guid '.$item['guid'].' for user '.$item['uid'].' on network '.$item['network'], LOGGER_DEBUG);
777 // Check for hashtags in the body and repair or add hashtag links
778 self::setHashtags($item);
780 $item['thr-parent'] = $item['parent-uri'];
788 if ($item['parent-uri'] === $item['uri']) {
791 $allow_cid = $item['allow_cid'];
792 $allow_gid = $item['allow_gid'];
793 $deny_cid = $item['deny_cid'];
794 $deny_gid = $item['deny_gid'];
795 $notify_type = 'wall-new';
797 // find the parent and snarf the item id and ACLs
798 // and anything else we need to inherit
800 $fields = ['uri', 'parent-uri', 'id', 'deleted',
801 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
802 'wall', 'private', 'forum_mode', 'origin'];
803 $condition = ['uri' => $item['parent-uri'], 'uid' => $item['uid']];
804 $params = ['order' => ['id' => false]];
805 $parent = dba::selectFirst('item', $fields, $condition, $params);
807 if (DBM::is_result($parent)) {
808 // is the new message multi-level threaded?
809 // even though we don't support it now, preserve the info
810 // and re-attach to the conversation parent.
812 if ($parent['uri'] != $parent['parent-uri']) {
813 $item['parent-uri'] = $parent['parent-uri'];
815 $condition = ['uri' => $item['parent-uri'],
816 'parent-uri' => $item['parent-uri'],
817 'uid' => $item['uid']];
818 $params = ['order' => ['id' => false]];
819 $toplevel_parent = dba::selectFirst('item', $fields, $condition, $params);
821 if (DBM::is_result($toplevel_parent)) {
822 $parent = $toplevel_parent;
826 $parent_id = $parent['id'];
827 $parent_deleted = $parent['deleted'];
828 $allow_cid = $parent['allow_cid'];
829 $allow_gid = $parent['allow_gid'];
830 $deny_cid = $parent['deny_cid'];
831 $deny_gid = $parent['deny_gid'];
832 $item['wall'] = $parent['wall'];
833 $notify_type = 'comment-new';
836 * If the parent is private, force privacy for the entire conversation
837 * This differs from the above settings as it subtly allows comments from
838 * email correspondents to be private even if the overall thread is not.
840 if ($parent['private']) {
841 $item['private'] = $parent['private'];
845 * Edge case. We host a public forum that was originally posted to privately.
846 * The original author commented, but as this is a comment, the permissions
847 * weren't fixed up so it will still show the comment as private unless we fix it here.
849 if ((intval($parent['forum_mode']) == 1) && $parent['private']) {
850 $item['private'] = 0;
853 // If its a post from myself then tag the thread as "mention"
854 logger("Checking if parent ".$parent_id." has to be tagged as mention for user ".$item['uid'], LOGGER_DEBUG);
855 $user = dba::selectFirst('user', ['nickname'], ['uid' => $item['uid']]);
856 if (DBM::is_result($user)) {
857 $self = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
858 logger("'myself' is ".$self." for parent ".$parent_id." checking against ".$item['author-link']." and ".$item['owner-link'], LOGGER_DEBUG);
859 if ((normalise_link($item['author-link']) == $self) || (normalise_link($item['owner-link']) == $self)) {
860 dba::update('thread', ['mention' => true], ['iid' => $parent_id]);
861 logger("tagged thread ".$parent_id." as mention for user ".$self, LOGGER_DEBUG);
866 * Allow one to see reply tweets from status.net even when
867 * we don't have or can't see the original post.
870 logger('$force_parent=true, reply converted to top-level post.');
872 $item['parent-uri'] = $item['uri'];
873 $item['gravity'] = 0;
875 logger('item parent '.$item['parent-uri'].' for '.$item['uid'].' was not found - ignoring item');
883 $condition = ["`uri` = ? AND `network` IN (?, ?) AND `uid` = ?",
884 $item['uri'], $item['network'], NETWORK_DFRN, $item['uid']];
885 if (dba::exists('item', $condition)) {
886 logger('duplicated item with the same uri found. '.print_r($item,true));
890 // On Friendica and Diaspora the GUID is unique
891 if (in_array($item['network'], [NETWORK_DFRN, NETWORK_DIASPORA])) {
892 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
893 if (dba::exists('item', $condition)) {
894 logger('duplicated item with the same guid found. '.print_r($item,true));
898 // Check for an existing post with the same content. There seems to be a problem with OStatus.
899 $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
900 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
901 if (dba::exists('item', $condition)) {
902 logger('duplicated item with the same body found. '.print_r($item,true));
907 // Is this item available in the global items (with uid=0)?
908 if ($item["uid"] == 0) {
909 $item["global"] = true;
911 // Set the global flag on all items if this was a global item entry
912 dba::update('item', ['global' => true], ['uri' => $item["uri"]]);
914 $item["global"] = dba::exists('item', ['uid' => 0, 'uri' => $item["uri"]]);
918 if (strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid)) {
921 $private = $item['private'];
924 $item["allow_cid"] = $allow_cid;
925 $item["allow_gid"] = $allow_gid;
926 $item["deny_cid"] = $deny_cid;
927 $item["deny_gid"] = $deny_gid;
928 $item["private"] = $private;
929 $item["deleted"] = $parent_deleted;
931 // Fill the cache field
932 put_item_in_cache($item);
935 Addon::callHooks('post_local', $item);
937 Addon::callHooks('post_remote', $item);
940 // This array field is used to trigger some automatic reactions
941 // It is mainly used in the "post_local" hook.
942 unset($item['api_source']);
944 if (x($item, 'cancel')) {
945 logger('post cancelled by addon.');
950 * Check for already added items.
951 * There is a timing issue here that sometimes creates double postings.
952 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
954 if ($item["uid"] == 0) {
955 if (dba::exists('item', ['uri' => trim($item['uri']), 'uid' => 0])) {
956 logger('Global item already stored. URI: '.$item['uri'].' on network '.$item['network'], LOGGER_DEBUG);
961 logger('' . print_r($item,true), LOGGER_DATA);
964 $ret = dba::insert('item', $item);
966 // When the item was successfully stored we fetch the ID of the item.
967 if (DBM::is_result($ret)) {
968 $current_post = dba::lastInsertId();
970 // This can happen - for example - if there are locking timeouts.
973 // Store the data into a spool file so that we can try again later.
975 // At first we restore the Diaspora signature that we removed above.
976 if (isset($encoded_signature)) {
977 $item['dsprsig'] = $encoded_signature;
980 // Now we store the data in the spool directory
981 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
982 $file = 'item-'.round(microtime(true) * 10000).'-'.mt_rand().'.msg';
984 $spoolpath = get_spoolpath();
985 if ($spoolpath != "") {
986 $spool = $spoolpath.'/'.$file;
987 file_put_contents($spool, json_encode($item));
988 logger("Item wasn't stored - Item was spooled into file ".$file, LOGGER_DEBUG);
993 if ($current_post == 0) {
994 // This is one of these error messages that never should occur.
995 logger("couldn't find created item - we better quit now.");
1000 // How much entries have we created?
1001 // We wouldn't need this query when we could use an unique index - but MySQL has length problems with them.
1002 $entries = dba::count('item', ['uri' => $item['uri'], 'uid' => $item['uid'], 'network' => $item['network']]);
1005 // There are duplicates. We delete our just created entry.
1006 logger('Duplicated post occurred. uri = ' . $item['uri'] . ' uid = ' . $item['uid']);
1008 // Yes, we could do a rollback here - but we are having many users with MyISAM.
1009 dba::delete('item', ['id' => $current_post]);
1012 } elseif ($entries == 0) {
1013 // This really should never happen since we quit earlier if there were problems.
1014 logger("Something is terribly wrong. We haven't found our created entry.");
1019 logger('created item '.$current_post);
1020 self::updateContact($item);
1022 if (!$parent_id || ($item['parent-uri'] === $item['uri'])) {
1023 $parent_id = $current_post;
1027 dba::update('item', ['parent' => $parent_id], ['id' => $current_post]);
1029 $item['id'] = $current_post;
1030 $item['parent'] = $parent_id;
1032 // update the commented timestamp on the parent
1033 // Only update "commented" if it is really a comment
1034 if (($item['verb'] == ACTIVITY_POST) || !Config::get("system", "like_no_comment")) {
1035 dba::update('item', ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1037 dba::update('item', ['changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1042 * Friendica servers lower than 3.4.3-2 had double encoded the signature ...
1043 * We can check for this condition when we decode and encode the stuff again.
1045 if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) {
1046 $dsprsig->signature = base64_decode($dsprsig->signature);
1047 logger("Repaired double encoded signature from handle ".$dsprsig->signer, LOGGER_DEBUG);
1050 dba::insert('sign', ['iid' => $current_post, 'signed_text' => $dsprsig->signed_text,
1051 'signature' => $dsprsig->signature, 'signer' => $dsprsig->signer]);
1054 if (!empty($diaspora_signed_text)) {
1055 // Formerly we stored the signed text, the signature and the author in different fields.
1056 // We now store the raw data so that we are more flexible.
1057 dba::insert('sign', ['iid' => $current_post, 'signed_text' => $diaspora_signed_text]);
1060 $deleted = self::tagDeliver($item['uid'], $current_post);
1063 * current post can be deleted if is for a community page and no mention are
1066 if (!$deleted && !$dontcache) {
1067 $posted_item = dba::selectFirst('item', [], ['id' => $current_post]);
1068 if (DBM::is_result($posted_item)) {
1070 Addon::callHooks('post_local_end', $posted_item);
1072 Addon::callHooks('post_remote_end', $posted_item);
1075 logger('new item not found in DB, id ' . $current_post);
1079 if ($item['parent-uri'] === $item['uri']) {
1080 self::addThread($current_post);
1082 self::updateThread($parent_id);
1088 * Due to deadlock issues with the "term" table we are doing these steps after the commit.
1089 * This is not perfect - but a workable solution until we found the reason for the problem.
1091 Term::insertFromTagFieldByItemId($current_post);
1092 Term::insertFromFileFieldByItemId($current_post);
1094 if ($item['parent-uri'] === $item['uri']) {
1095 self::addShadow($current_post);
1097 self::addShadowPost($current_post);
1100 check_user_notification($current_post);
1103 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", $notify_type, $current_post);
1104 } elseif (!empty($parent) && $parent['origin']) {
1105 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "Notifier", "comment-import", $current_post);
1108 return $current_post;
1112 * @brief Distributes public items to the receivers
1114 * @param integer $itemid Item ID that should be added
1115 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
1117 public static function distribute($itemid, $signed_text = '')
1119 $condition = ["`id` IN (SELECT `parent` FROM `item` WHERE `id` = ?)", $itemid];
1120 $parent = dba::selectFirst('item', ['owner-id'], $condition);
1121 if (!DBM::is_result($parent)) {
1125 // Only distribute public items from native networks
1126 $condition = ['id' => $itemid, 'uid' => 0,
1127 'network' => [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""],
1128 'visible' => true, 'deleted' => false, 'moderated' => false, 'private' => false];
1129 $item = dba::selectFirst('item', [], ['id' => $itemid]);
1130 if (!DBM::is_result($item)) {
1135 unset($item['parent']);
1136 unset($item['mention']);
1137 unset($item['wall']);
1138 unset($item['origin']);
1139 unset($item['starred']);
1140 unset($item['rendered-hash']);
1141 unset($item['rendered-html']);
1145 $condition = ["`nurl` IN (SELECT `nurl` FROM `contact` WHERE `id` = ?) AND `uid` != 0 AND NOT `blocked` AND `rel` IN (?, ?)",
1146 $parent['owner-id'], CONTACT_IS_SHARING, CONTACT_IS_FRIEND];
1147 $contacts = dba::select('contact', ['uid'], $condition);
1148 while ($contact = dba::fetch($contacts)) {
1149 $users[$contact['uid']] = $contact['uid'];
1154 if ($item['uri'] != $item['parent-uri']) {
1155 $parents = dba::select('item', ['uid', 'origin'], ["`uri` = ? AND `uid` != 0", $item['parent-uri']]);
1156 while ($parent = dba::fetch($parents)) {
1157 $users[$parent['uid']] = $parent['uid'];
1158 if ($parent['origin'] && !$item['origin']) {
1159 $origin_uid = $parent['uid'];
1164 foreach ($users as $uid) {
1165 if ($origin_uid == $uid) {
1166 $item['diaspora_signed_text'] = $signed_text;
1168 self::storeForUser($itemid, $item, $uid);
1173 * @brief Store public items for the receivers
1175 * @param integer $itemid Item ID that should be added
1176 * @param array $item The item entry that will be stored
1177 * @param integer $uid The user that will receive the item entry
1179 private static function storeForUser($itemid, $item, $uid)
1181 $item['uid'] = $uid;
1182 $item['origin'] = 0;
1184 if ($item['uri'] == $item['parent-uri']) {
1185 $item['contact-id'] = Contact::getIdForURL($item['owner-link'], $uid);
1187 $item['contact-id'] = Contact::getIdForURL($item['author-link'], $uid);
1190 if (empty($item['contact-id'])) {
1191 $self = dba::selectFirst('contact', ['id'], ['self' => true, 'uid' => $uid]);
1192 if (!DBM::is_result($self)) {
1195 $item['contact-id'] = $self['id'];
1198 if (in_array($item['type'], ["net-comment", "wall-comment"])) {
1199 $item['type'] = 'remote-comment';
1200 } elseif ($item['type'] == 'wall') {
1201 $item['type'] = 'remote';
1204 /// @todo Handling of "event-id"
1207 if ($item['uri'] == $item['parent-uri']) {
1208 $contact = dba::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
1209 if (DBM::is_result($contact)) {
1210 $notify = self::isRemoteSelf($contact, $item);
1214 $distributed = self::insert($item, false, $notify, true);
1216 if (!$distributed) {
1217 logger("Distributed public item " . $itemid . " for user " . $uid . " wasn't stored", LOGGER_DEBUG);
1219 logger("Distributed public item " . $itemid . " for user " . $uid . " with id " . $distributed, LOGGER_DEBUG);
1224 * @brief Add a shadow entry for a given item id that is a thread starter
1226 * We store every public item entry additionally with the user id "0".
1227 * This is used for the community page and for the search.
1228 * It is planned that in the future we will store public item entries only once.
1230 * @param integer $itemid Item ID that should be added
1232 public static function addShadow($itemid)
1234 $fields = ['uid', 'private', 'moderated', 'visible', 'deleted', 'network'];
1235 $condition = ['id' => $itemid, 'parent' => [0, $itemid]];
1236 $item = dba::selectFirst('item', $fields, $condition);
1238 if (!DBM::is_result($item)) {
1242 // is it already a copy?
1243 if (($itemid == 0) || ($item['uid'] == 0)) {
1247 // Is it a visible public post?
1248 if (!$item["visible"] || $item["deleted"] || $item["moderated"] || $item["private"]) {
1252 // is it an entry from a connector? Only add an entry for natively connected networks
1253 if (!in_array($item["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""])) {
1257 $item = dba::selectFirst('item', [], ['id' => $itemid]);
1259 if (DBM::is_result($item) && ($item["allow_cid"] == '') && ($item["allow_gid"] == '') &&
1260 ($item["deny_cid"] == '') && ($item["deny_gid"] == '')) {
1262 if (!dba::exists('item', ['uri' => $item['uri'], 'uid' => 0])) {
1263 // Preparing public shadow (removing user specific data)
1266 unset($item['parent']);
1267 unset($item['wall']);
1268 unset($item['mention']);
1269 unset($item['origin']);
1270 unset($item['starred']);
1271 unset($item['rendered-hash']);
1272 unset($item['rendered-html']);
1273 if ($item['uri'] == $item['parent-uri']) {
1274 $item['contact-id'] = Contact::getIdForURL($item['owner-link']);
1276 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
1279 if (in_array($item['type'], ["net-comment", "wall-comment"])) {
1280 $item['type'] = 'remote-comment';
1281 } elseif ($item['type'] == 'wall') {
1282 $item['type'] = 'remote';
1285 $public_shadow = self::insert($item, false, false, true);
1287 logger("Stored public shadow for thread ".$itemid." under id ".$public_shadow, LOGGER_DEBUG);
1293 * @brief Add a shadow entry for a given item id that is a comment
1295 * This function does the same like the function above - but for comments
1297 * @param integer $itemid Item ID that should be added
1299 public static function addShadowPost($itemid)
1301 $item = dba::selectFirst('item', [], ['id' => $itemid]);
1302 if (!DBM::is_result($item)) {
1306 // Is it a toplevel post?
1307 if ($item['id'] == $item['parent']) {
1308 self::addShadow($itemid);
1312 // Is this a shadow entry?
1313 if ($item['uid'] == 0) {
1317 // Is there a shadow parent?
1318 if (!dba::exists('item', ['uri' => $item['parent-uri'], 'uid' => 0])) {
1322 // Is there already a shadow entry?
1323 if (dba::exists('item', ['uri' => $item['uri'], 'uid' => 0])) {
1327 // Save "origin" and "parent" state
1328 $origin = $item['origin'];
1329 $parent = $item['parent'];
1331 // Preparing public shadow (removing user specific data)
1334 unset($item['parent']);
1335 unset($item['wall']);
1336 unset($item['mention']);
1337 unset($item['origin']);
1338 unset($item['starred']);
1339 unset($item['rendered-hash']);
1340 unset($item['rendered-html']);
1341 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
1343 if (in_array($item['type'], ["net-comment", "wall-comment"])) {
1344 $item['type'] = 'remote-comment';
1345 } elseif ($item['type'] == 'wall') {
1346 $item['type'] = 'remote';
1349 $public_shadow = self::insert($item, false, false, true);
1351 logger("Stored public shadow for comment ".$item['uri']." under id ".$public_shadow, LOGGER_DEBUG);
1353 // If this was a comment to a Diaspora post we don't get our comment back.
1354 // This means that we have to distribute the comment by ourselves.
1355 if ($origin && dba::exists('item', ['id' => $parent, 'network' => NETWORK_DIASPORA])) {
1356 self::distribute($public_shadow);
1361 * Adds a "lang" specification in a "postopts" element of given $arr,
1362 * if possible and not already present.
1363 * Expects "body" element to exist in $arr.
1365 private static function addLanguageInPostopts(&$item)
1369 if (!empty($item['postopts'])) {
1370 if (strstr($item['postopts'], 'lang=')) {
1374 $postopts = $item['postopts'];
1377 $naked_body = Text\BBCode::toPlaintext($item['body'], false);
1379 $languages = (new Text_LanguageDetect())->detect($naked_body, 3);
1381 if (sizeof($languages) > 0) {
1382 if ($postopts != '') {
1383 $postopts .= '&'; // arbitrary separator, to be reviewed
1386 $postopts .= 'lang=';
1389 foreach ($languages as $language => $score) {
1390 $postopts .= $sep . $language . ";" . $score;
1393 $item['postopts'] = $postopts;
1398 * @brief Creates an unique guid out of a given uri
1400 * @param string $uri uri of an item entry
1401 * @param string $host hostname for the GUID prefix
1402 * @return string unique guid
1404 public static function guidFromUri($uri, $host)
1406 // Our regular guid routine is using this kind of prefix as well
1407 // We have to avoid that different routines could accidentally create the same value
1408 $parsed = parse_url($uri);
1410 // We use a hash of the hostname as prefix for the guid
1411 $guid_prefix = hash("crc32", $host);
1413 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
1414 unset($parsed["scheme"]);
1416 // Glue it together to be able to make a hash from it
1417 $host_id = implode("/", $parsed);
1419 // We could use any hash algorithm since it isn't a security issue
1420 $host_hash = hash("ripemd128", $host_id);
1422 return $guid_prefix.$host_hash;
1426 * @brief Set "success_update" and "last-item" to the date of the last time we heard from this contact
1428 * This can be used to filter for inactive contacts.
1429 * Only do this for public postings to avoid privacy problems, since poco data is public.
1430 * Don't set this value if it isn't from the owner (could be an author that we don't know)
1432 * @param array $arr Contains the just posted item record
1434 private static function updateContact($arr)
1436 // Unarchive the author
1437 $contact = dba::selectFirst('contact', [], ['id' => $arr["author-id"]]);
1438 if (DBM::is_result($contact)) {
1439 Contact::unmarkForArchival($contact);
1442 // Unarchive the contact if it's not our own contact
1443 $contact = dba::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
1444 if (DBM::is_result($contact)) {
1445 Contact::unmarkForArchival($contact);
1448 $update = (!$arr['private'] && (($arr["author-link"] === $arr["owner-link"]) || ($arr["parent-uri"] === $arr["uri"])));
1450 // Is it a forum? Then we don't care about the rules from above
1451 if (!$update && ($arr["network"] == NETWORK_DFRN) && ($arr["parent-uri"] === $arr["uri"])) {
1452 if (dba::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
1458 dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
1459 ['id' => $arr['contact-id']]);
1461 // Now do the same for the system wide contacts with uid=0
1462 if (!$arr['private']) {
1463 dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
1464 ['id' => $arr['owner-id']]);
1466 if ($arr['owner-id'] != $arr['author-id']) {
1467 dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
1468 ['id' => $arr['author-id']]);
1473 public static function setHashtags(&$item)
1476 $tags = get_tags($item["body"]);
1479 if (!count($tags)) {
1483 // This sorting is important when there are hashtags that are part of other hashtags
1484 // Otherwise there could be problems with hashtags like #test and #test2
1487 $URLSearchString = "^\[\]";
1489 // All hashtags should point to the home server if "local_tags" is activated
1490 if (Config::get('system', 'local_tags')) {
1491 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1492 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["body"]);
1494 $item["tag"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1495 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["tag"]);
1498 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
1499 $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1501 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
1504 $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
1506 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
1509 $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
1511 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
1514 // Repair recursive urls
1515 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1516 "#$2", $item["body"]);
1518 foreach ($tags as $tag) {
1519 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=')) {
1523 $basetag = str_replace('_',' ',substr($tag,1));
1525 $newtag = '#[url=' . System::baseUrl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1527 $item["body"] = str_replace($tag, $newtag, $item["body"]);
1529 if (!stristr($item["tag"], "/search?tag=" . $basetag . "]" . $basetag . "[/url]")) {
1530 if (strlen($item["tag"])) {
1531 $item["tag"] = ','.$item["tag"];
1533 $item["tag"] = $newtag.$item["tag"];
1537 // Convert back the masked hashtags
1538 $item["body"] = str_replace("#", "#", $item["body"]);
1541 public static function getGuidById($id)
1543 $item = dba::selectFirst('item', ['guid'], ['id' => $id]);
1544 if (DBM::is_result($item)) {
1545 return $item['guid'];
1551 public static function getIdAndNickByGuid($guid, $uid = 0)
1557 $uid == local_user();
1560 // Does the given user have this item?
1562 $item = dba::fetch_first("SELECT `item`.`id`, `user`.`nickname` FROM `item`
1563 INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
1564 WHERE `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
1565 AND `item`.`guid` = ? AND `item`.`uid` = ?", $guid, $uid);
1566 if (DBM::is_result($item)) {
1568 $nick = $item["nickname"];
1572 // Or is it anywhere on the server?
1574 $item = dba::fetch_first("SELECT `item`.`id`, `user`.`nickname` FROM `item`
1575 INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
1576 WHERE `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
1577 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1578 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1579 AND NOT `item`.`private` AND `item`.`wall`
1580 AND `item`.`guid` = ?", $guid);
1581 if (DBM::is_result($item)) {
1583 $nick = $item["nickname"];
1586 return ["nick" => $nick, "id" => $id];
1590 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
1592 * @param int $item_id
1593 * @return bool true if item was deleted, else false
1595 private static function tagDeliver($uid, $item_id)
1599 $user = dba::selectFirst('user', [], ['uid' => $uid]);
1600 if (!DBM::is_result($user)) {
1604 $community_page = (($user['page-flags'] == PAGE_COMMUNITY) ? true : false);
1605 $prvgroup = (($user['page-flags'] == PAGE_PRVGROUP) ? true : false);
1607 $item = dba::selectFirst('item', [], ['id' => $item_id]);
1608 if (!DBM::is_result($item)) {
1612 $link = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
1615 * Diaspora uses their own hardwired link URL in @-tags
1616 * instead of the one we supply with webfinger
1618 $dlink = normalise_link(System::baseUrl() . '/u/' . $user['nickname']);
1620 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
1622 foreach ($matches as $mtch) {
1623 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
1625 logger('mention found: ' . $mtch[2]);
1631 if (($community_page || $prvgroup) &&
1632 !$item['wall'] && !$item['origin'] && ($item['id'] == $item['parent'])) {
1633 // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
1635 logger("no-mention top-level post to community or private group. delete.");
1636 dba::delete('item', ['id' => $item_id]);
1642 $arr = ['item' => $item, 'user' => $user];
1644 Addon::callHooks('tagged', $arr);
1646 if (!$community_page && !$prvgroup) {
1651 * tgroup delivery - setup a second delivery chain
1652 * prevent delivery looping - only proceed
1653 * if the message originated elsewhere and is a top-level post
1655 if ($item['wall'] || $item['origin'] || ($item['id'] != $item['parent'])) {
1659 // now change this copy of the post to a forum head message and deliver to all the tgroup members
1660 $self = dba::selectFirst('contact', ['id', 'name', 'url', 'thumb'], ['uid' => $uid, 'self' => true]);
1661 if (!DBM::is_result($self)) {
1665 $owner_id = Contact::getIdForURL($self['url']);
1667 // also reset all the privacy bits to the forum default permissions
1669 $private = ($user['allow_cid'] || $user['allow_gid'] || $user['deny_cid'] || $user['deny_gid']) ? 1 : 0;
1671 $forum_mode = ($prvgroup ? 2 : 1);
1673 $fields = ['wall' => true, 'origin' => true, 'forum_mode' => $forum_mode, 'contact-id' => $self['id'],
1674 'owner-id' => $owner_id, 'owner-link' => $self['url'], 'private' => $private, 'allow_cid' => $user['allow_cid'],
1675 'allow_gid' => $user['allow_gid'], 'deny_cid' => $user['deny_cid'], 'deny_gid' => $user['deny_gid']];
1676 dba::update('item', $fields, ['id' => $item_id]);
1678 self::updateThread($item_id);
1680 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', 'tgroup', $item_id);
1683 public static function isRemoteSelf($contact, &$datarray)
1687 if (!$contact['remote_self']) {
1691 // Prevent the forwarding of posts that are forwarded
1692 if ($datarray["extid"] == NETWORK_DFRN) {
1693 logger('Already forwarded', LOGGER_DEBUG);
1697 // Prevent to forward already forwarded posts
1698 if ($datarray["app"] == $a->get_hostname()) {
1699 logger('Already forwarded (second test)', LOGGER_DEBUG);
1703 // Only forward posts
1704 if ($datarray["verb"] != ACTIVITY_POST) {
1705 logger('No post', LOGGER_DEBUG);
1709 if (($contact['network'] != NETWORK_FEED) && $datarray['private']) {
1710 logger('Not public', LOGGER_DEBUG);
1714 $datarray2 = $datarray;
1715 logger('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), LOGGER_DEBUG);
1716 if ($contact['remote_self'] == 2) {
1717 $self = dba::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
1718 ['uid' => $contact['uid'], 'self' => true]);
1719 if (DBM::is_result($self)) {
1720 $datarray['contact-id'] = $self["id"];
1722 $datarray['owner-name'] = $self["name"];
1723 $datarray['owner-link'] = $self["url"];
1724 $datarray['owner-avatar'] = $self["thumb"];
1726 $datarray['author-name'] = $datarray['owner-name'];
1727 $datarray['author-link'] = $datarray['owner-link'];
1728 $datarray['author-avatar'] = $datarray['owner-avatar'];
1730 unset($datarray['created']);
1731 unset($datarray['edited']);
1733 unset($datarray['network']);
1734 unset($datarray['owner-id']);
1735 unset($datarray['author-id']);
1738 if ($contact['network'] != NETWORK_FEED) {
1739 $datarray["guid"] = get_guid(32);
1740 unset($datarray["plink"]);
1741 $datarray["uri"] = item_new_uri($a->get_hostname(), $contact['uid'], $datarray["guid"]);
1742 $datarray["parent-uri"] = $datarray["uri"];
1743 $datarray["thr-parent"] = $datarray["uri"];
1744 $datarray["extid"] = NETWORK_DFRN;
1745 $urlpart = parse_url($datarray2['author-link']);
1746 $datarray["app"] = $urlpart["host"];
1748 $datarray['private'] = 0;
1752 if ($contact['network'] != NETWORK_FEED) {
1753 // Store the original post
1754 $result = self::insert($datarray2, false, false);
1755 logger('remote-self post original item - Contact '.$contact['url'].' return '.$result.' Item '.print_r($datarray2, true), LOGGER_DEBUG);
1757 $datarray["app"] = "Feed";
1761 // Trigger automatic reactions for addons
1762 $datarray['api_source'] = true;
1764 // We have to tell the hooks who we are - this really should be improved
1765 $_SESSION["authenticated"] = true;
1766 $_SESSION["uid"] = $contact['uid'];
1775 * @param array $item
1779 public static function fixPrivatePhotos($s, $uid, $item = null, $cid = 0)
1781 if (Config::get('system', 'disable_embedded')) {
1785 logger('check for photos', LOGGER_DEBUG);
1786 $site = substr(System::baseUrl(), strpos(System::baseUrl(), '://'));
1791 $img_start = strpos($orig_body, '[img');
1792 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
1793 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
1795 while (($img_st_close !== false) && ($img_len !== false)) {
1796 $img_st_close++; // make it point to AFTER the closing bracket
1797 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
1799 logger('found photo ' . $image, LOGGER_DEBUG);
1801 if (stristr($image, $site . '/photo/')) {
1802 // Only embed locally hosted photos
1804 $i = basename($image);
1805 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
1806 $x = strpos($i, '-');
1809 $res = substr($i, $x + 1);
1810 $i = substr($i, 0, $x);
1811 $fields = ['data', 'type', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'];
1812 $photo = dba::selectFirst('photo', $fields, ['resource-id' => $i, 'scale' => $res, 'uid' => $uid]);
1813 if (DBM::is_result($photo)) {
1815 * Check to see if we should replace this photo link with an embedded image
1816 * 1. No need to do so if the photo is public
1817 * 2. If there's a contact-id provided, see if they're in the access list
1818 * for the photo. If so, embed it.
1819 * 3. Otherwise, if we have an item, see if the item permissions match the photo
1820 * permissions, regardless of order but first check to see if they're an exact
1821 * match to save some processing overhead.
1823 if (self::hasPermissions($photo)) {
1825 $recips = self::enumeratePermissions($photo);
1826 if (in_array($cid, $recips)) {
1830 if (self::samePermissions($item, $photo)) {
1836 $data = $photo['data'];
1837 $type = $photo['type'];
1839 // If a custom width and height were specified, apply before embedding
1840 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
1841 logger('scaling photo', LOGGER_DEBUG);
1843 $width = intval($match[1]);
1844 $height = intval($match[2]);
1846 $Image = new Image($data, $type);
1847 if ($Image->isValid()) {
1848 $Image->scaleDown(max($width, $height));
1849 $data = $Image->asString();
1850 $type = $Image->getType();
1854 logger('replacing photo', LOGGER_DEBUG);
1855 $image = 'data:' . $type . ';base64,' . base64_encode($data);
1856 logger('replaced: ' . $image, LOGGER_DATA);
1862 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
1863 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
1864 if ($orig_body === false) {
1868 $img_start = strpos($orig_body, '[img');
1869 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
1870 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
1873 $new_body = $new_body . $orig_body;
1878 private static function hasPermissions($obj)
1882 x($obj, 'allow_cid')
1884 x($obj, 'allow_gid')
1893 private static function samePermissions($obj1, $obj2)
1895 // first part is easy. Check that these are exactly the same.
1896 if (($obj1['allow_cid'] == $obj2['allow_cid'])
1897 && ($obj1['allow_gid'] == $obj2['allow_gid'])
1898 && ($obj1['deny_cid'] == $obj2['deny_cid'])
1899 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
1903 // This is harder. Parse all the permissions and compare the resulting set.
1904 $recipients1 = self::enumeratePermissions($obj1);
1905 $recipients2 = self::enumeratePermissions($obj2);
1909 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
1910 return ($recipients1 == $recipients2);
1913 // returns an array of contact-ids that are allowed to see this object
1914 private static function enumeratePermissions($obj)
1916 $allow_people = expand_acl($obj['allow_cid']);
1917 $allow_groups = Group::expand(expand_acl($obj['allow_gid']));
1918 $deny_people = expand_acl($obj['deny_cid']);
1919 $deny_groups = Group::expand(expand_acl($obj['deny_gid']));
1920 $recipients = array_unique(array_merge($allow_people, $allow_groups));
1921 $deny = array_unique(array_merge($deny_people, $deny_groups));
1922 $recipients = array_diff($recipients, $deny);
1926 public static function getFeedTags($item)
1930 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
1932 for ($x = 0; $x < $cnt; $x ++) {
1933 if ($matches[1][$x]) {
1934 $ret[$matches[2][$x]] = ['#', $matches[1][$x], $matches[2][$x]];
1939 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
1941 for ($x = 0; $x < $cnt; $x ++) {
1942 if ($matches[1][$x]) {
1943 $ret[] = ['@', $matches[1][$x], $matches[2][$x]];
1950 public static function expire($uid, $days, $network = "", $force = false)
1952 if (!$uid || ($days < 1)) {
1957 * $expire_network_only = save your own wall posts
1958 * and just expire conversations started by others
1960 $expire_network_only = PConfig::get($uid,'expire', 'network_only');
1961 $sql_extra = (intval($expire_network_only) ? " AND wall = 0 " : "");
1963 if ($network != "") {
1964 $sql_extra .= sprintf(" AND network = '%s' ", dbesc($network));
1967 * There is an index "uid_network_received" but not "uid_network_created"
1968 * This avoids the creation of another index just for one purpose.
1969 * And it doesn't really matter wether to look at "received" or "created"
1971 $range = "AND `received` < UTC_TIMESTAMP() - INTERVAL %d DAY ";
1973 $range = "AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY ";
1976 $r = q("SELECT `file`, `resource-id`, `starred`, `type`, `id` FROM `item`
1977 WHERE `uid` = %d $range
1985 if (!DBM::is_result($r)) {
1989 $expire_items = PConfig::get($uid, 'expire', 'items', 1);
1991 // Forcing expiring of items - but not notes and marked items
1993 $expire_items = true;
1996 $expire_notes = PConfig::get($uid, 'expire', 'notes', 1);
1997 $expire_starred = PConfig::get($uid, 'expire', 'starred', 1);
1998 $expire_photos = PConfig::get($uid, 'expire', 'photos', 0);
2000 logger('User '.$uid.': expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
2002 foreach ($r as $item) {
2004 // don't expire filed items
2006 if (strpos($item['file'],'[') !== false) {
2010 // Only expire posts, not photos and photo comments
2012 if ($expire_photos == 0 && strlen($item['resource-id'])) {
2014 } elseif ($expire_starred == 0 && intval($item['starred'])) {
2016 } elseif ($expire_notes == 0 && $item['type'] == 'note') {
2018 } elseif ($expire_items == 0 && $item['type'] != 'note') {
2022 self::deleteById($item['id'], PRIORITY_LOW);
2026 public static function firstPostDate($uid, $wall = false)
2028 $condition = ['uid' => $uid, 'wall' => $wall, 'deleted' => false, 'visible' => true, 'moderated' => false];
2029 $params = ['order' => ['created' => false]];
2030 $thread = dba::selectFirst('thread', ['created'], $condition, $params);
2031 if (DBM::is_result($thread)) {
2032 return substr(DateTimeFormat::local($thread['created']), 0, 10);
2038 * @brief add/remove activity to an item
2040 * Toggle activities as like,dislike,attend of an item
2042 * @param string $item_id
2043 * @param string $verb
2044 * Activity verb. One of
2045 * like, unlike, dislike, undislike, attendyes, unattendyes,
2046 * attendno, unattendno, attendmaybe, unattendmaybe
2047 * @hook 'post_local_end'
2049 * 'post_id' => ID of posted item
2051 public static function performLike($item_id, $verb)
2053 if (!local_user() && !remote_user()) {
2060 $bodyverb = L10n::t('%1$s likes %2$s\'s %3$s');
2061 $activity = ACTIVITY_LIKE;
2065 $bodyverb = L10n::t('%1$s doesn\'t like %2$s\'s %3$s');
2066 $activity = ACTIVITY_DISLIKE;
2070 $bodyverb = L10n::t('%1$s is attending %2$s\'s %3$s');
2071 $activity = ACTIVITY_ATTEND;
2075 $bodyverb = L10n::t('%1$s is not attending %2$s\'s %3$s');
2076 $activity = ACTIVITY_ATTENDNO;
2079 case 'unattendmaybe':
2080 $bodyverb = L10n::t('%1$s may attend %2$s\'s %3$s');
2081 $activity = ACTIVITY_ATTENDMAYBE;
2084 logger('like: unknown verb ' . $verb . ' for item ' . $item_id);
2088 // Enable activity toggling instead of on/off
2089 $event_verb_flag = $activity === ACTIVITY_ATTEND || $activity === ACTIVITY_ATTENDNO || $activity === ACTIVITY_ATTENDMAYBE;
2091 logger('like: verb ' . $verb . ' item ' . $item_id);
2093 $item = dba::selectFirst('item', [], ['`id` = ? OR `uri` = ?', $item_id, $item_id]);
2094 if (!DBM::is_result($item)) {
2095 logger('like: unknown item ' . $item_id);
2099 $uid = $item['uid'];
2100 if (($uid == 0) && local_user()) {
2101 $uid = local_user();
2104 if (!can_write_wall($uid)) {
2105 logger('like: unable to write on wall ' . $uid);
2109 // Retrieves the local post owner
2110 $owner_self_contact = dba::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
2111 if (!DBM::is_result($owner_self_contact)) {
2112 logger('like: unknown owner ' . $uid);
2116 // Retrieve the current logged in user's public contact
2117 $author_id = public_contact();
2119 $author_contact = dba::selectFirst('contact', [], ['id' => $author_id]);
2120 if (!DBM::is_result($author_contact)) {
2121 logger('like: unknown author ' . $author_id);
2125 // Contact-id is the uid-dependant author contact
2126 if (local_user() == $uid) {
2127 $item_contact_id = $owner_self_contact['id'];
2128 $item_contact = $owner_self_contact;
2130 $item_contact_id = Contact::getIdForURL($author_contact['url'], $uid, true);
2131 $item_contact = dba::selectFirst('contact', [], ['id' => $item_contact_id]);
2132 if (!DBM::is_result($item_contact)) {
2133 logger('like: unknown item contact ' . $item_contact_id);
2138 // Look for an existing verb row
2139 // event participation are essentially radio toggles. If you make a subsequent choice,
2140 // we need to eradicate your first choice.
2141 if ($event_verb_flag) {
2142 $verbs = "'" . dbesc(ACTIVITY_ATTEND) . "', '" . dbesc(ACTIVITY_ATTENDNO) . "', '" . dbesc(ACTIVITY_ATTENDMAYBE) . "'";
2144 $verbs = "'".dbesc($activity)."'";
2147 /// @todo This query is expected to be a performance eater due to the "OR" - it has to be changed totally
2148 $existing_like = q("SELECT `id`, `guid`, `verb` FROM `item`
2149 WHERE `verb` IN ($verbs)
2151 AND `author-id` = %d
2153 AND (`parent` = '%s' OR `parent-uri` = '%s' OR `thr-parent` = '%s')
2155 intval($author_contact['id']),
2156 intval($item['uid']),
2157 dbesc($item_id), dbesc($item_id), dbesc($item['uri'])
2160 // If it exists, mark it as deleted
2161 if (DBM::is_result($existing_like)) {
2162 $like_item = $existing_like[0];
2164 // Already voted, undo it
2165 $fields = ['deleted' => true, 'unseen' => true, 'changed' => DateTimeFormat::utcNow()];
2166 dba::update('item', $fields, ['id' => $like_item['id']]);
2168 // Clean up the Diaspora signatures for this like
2169 // Go ahead and do it even if Diaspora support is disabled. We still want to clean up
2170 // if it had been enabled in the past
2171 dba::delete('sign', ['iid' => $like_item['id']]);
2173 $like_item_id = $like_item['id'];
2174 Worker::add(PRIORITY_HIGH, "Notifier", "like", $like_item_id);
2176 if (!$event_verb_flag || $like_item['verb'] == $activity) {
2181 // Verb is "un-something", just trying to delete existing entries
2182 if (strpos($verb, 'un') === 0) {
2186 // Else or if event verb different from existing row, create a new item row
2187 $post_type = (($item['resource-id']) ? L10n::t('photo') : L10n::t('status'));
2188 if ($item['object-type'] === ACTIVITY_OBJ_EVENT) {
2189 $post_type = L10n::t('event');
2191 $objtype = $item['resource-id'] ? ACTIVITY_OBJ_IMAGE : ACTIVITY_OBJ_NOTE ;
2192 $link = xmlify('<link rel="alternate" type="text/html" href="' . System::baseUrl() . '/display/' . $owner_self_contact['nick'] . '/' . $item['id'] . '" />' . "\n") ;
2193 $body = $item['body'];
2198 <type>$objtype</type>
2200 <id>{$item['uri']}</id>
2203 <content>$body</content>
2207 $ulink = '[url=' . $author_contact['url'] . ']' . $author_contact['name'] . '[/url]';
2208 $alink = '[url=' . $item['author-link'] . ']' . $item['author-name'] . '[/url]';
2209 $plink = '[url=' . System::baseUrl() . '/display/' . $owner_self_contact['nick'] . '/' . $item['id'] . ']' . $post_type . '[/url]';
2212 'guid' => get_guid(32),
2213 'uri' => item_new_uri(self::getApp()->get_hostname(), $item['uid']),
2214 'uid' => $item['uid'],
2215 'contact-id' => $item_contact_id,
2216 'type' => 'activity',
2217 'wall' => $item['wall'],
2219 'gravity' => GRAVITY_LIKE,
2220 'parent' => $item['id'],
2221 'parent-uri' => $item['uri'],
2222 'thr-parent' => $item['uri'],
2223 'owner-id' => $item['owner-id'],
2224 'owner-name' => $item['owner-name'],
2225 'owner-link' => $item['owner-link'],
2226 'owner-avatar' => $item['owner-avatar'],
2227 'author-id' => $author_contact['id'],
2228 'author-name' => $author_contact['name'],
2229 'author-link' => $author_contact['url'],
2230 'author-avatar' => $author_contact['thumb'],
2231 'body' => sprintf($bodyverb, $ulink, $alink, $plink),
2232 'verb' => $activity,
2233 'object-type' => $objtype,
2235 'allow_cid' => $item['allow_cid'],
2236 'allow_gid' => $item['allow_gid'],
2237 'deny_cid' => $item['deny_cid'],
2238 'deny_gid' => $item['deny_gid'],
2243 $new_item_id = self::insert($new_item);
2245 // If the parent item isn't visible then set it to visible
2246 if (!$item['visible']) {
2247 self::update(['visible' => true], ['id' => $item['id']]);
2250 // Save the author information for the like in case we need to relay to Diaspora
2251 Diaspora::storeLikeSignature($item_contact, $new_item_id);
2253 $new_item['id'] = $new_item_id;
2255 Addon::callHooks('post_local_end', $new_item);
2257 Worker::add(PRIORITY_HIGH, "Notifier", "like", $new_item_id);
2262 private static function addThread($itemid, $onlyshadow = false)
2264 $fields = ['uid', 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private', 'pubmail',
2265 'moderated', 'visible', 'starred', 'bookmark', 'contact-id',
2266 'deleted', 'origin', 'forum_mode', 'mention', 'network', 'author-id', 'owner-id'];
2267 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
2268 $item = dba::selectFirst('item', $fields, $condition);
2270 if (!DBM::is_result($item)) {
2274 $item['iid'] = $itemid;
2277 $result = dba::insert('thread', $item);
2279 logger("Add thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
2283 private static function updateThread($itemid, $setmention = false)
2285 $fields = ['uid', 'guid', 'title', 'body', 'created', 'edited', 'commented', 'received', 'changed',
2286 'wall', 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark', 'contact-id',
2287 'deleted', 'origin', 'forum_mode', 'network', 'author-id', 'owner-id', 'rendered-html', 'rendered-hash'];
2288 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
2290 $item = dba::selectFirst('item', $fields, $condition);
2291 if (!DBM::is_result($item)) {
2296 $item["mention"] = 1;
2303 foreach ($item as $field => $data) {
2304 if (!in_array($field, ["guid", "title", "body", "rendered-html", "rendered-hash"])) {
2305 $fields[$field] = $data;
2309 $result = dba::update('thread', $fields, ['iid' => $itemid]);
2311 logger("Update thread for item ".$itemid." - guid ".$item["guid"]." - ".(int)$result, LOGGER_DEBUG);
2313 // Updating a shadow item entry
2314 $items = dba::selectFirst('item', ['id'], ['guid' => $item['guid'], 'uid' => 0]);
2316 if (!DBM::is_result($items)) {
2320 $fields = ['title' => $item['title'], 'body' => $item['body'],
2321 'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']];
2322 $result = dba::update('item', $fields, ['id' => $items['id']]);
2324 logger("Updating public shadow for post ".$items["id"]." - guid ".$item["guid"]." Result: ".print_r($result, true), LOGGER_DEBUG);
2327 private static function deleteThread($itemid, $itemuri = "")
2329 $item = dba::selectFirst('thread', ['uid'], ['iid' => $itemid]);
2330 if (!DBM::is_result($item)) {
2331 logger('No thread found for id '.$itemid, LOGGER_DEBUG);
2335 // Using dba::delete at this time could delete the associated item entries
2336 $result = dba::e("DELETE FROM `thread` WHERE `iid` = ?", $itemid);
2338 logger("deleteThread: Deleted thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
2340 if ($itemuri != "") {
2341 $condition = ["`uri` = ? AND NOT `deleted` AND NOT (`uid` IN (?, 0))", $itemuri, $item["uid"]];
2342 if (!dba::exists('item', $condition)) {
2343 dba::delete('item', ['uri' => $itemuri, 'uid' => 0]);
2344 logger("deleteThread: Deleted shadow for item ".$itemuri, LOGGER_DEBUG);