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
37 * @brief Update existing item entries
39 * @param array $fields The fields that are to be changed
40 * @param array $condition The condition for finding the item entries
42 * In the future we may have to change permissions as well.
43 * Then we had to add the user id as third parameter.
45 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
47 * @return integer|boolean number of affected rows - or "false" if there was an error
49 public static function update(array $fields, array $condition)
51 if (empty($condition) || empty($fields)) {
55 // To ensure the data integrity we do it in an transaction
58 // We cannot simply expand the condition to check for origin entries
59 // The condition needn't to be a simple array but could be a complex condition.
60 // And we have to execute this query before the update to ensure to fetch the same data.
61 $items = dba::select('item', ['id', 'origin'], $condition);
63 $success = dba::update('item', $fields, $condition);
71 $rows = dba::affected_rows();
73 while ($item = dba::fetch($items)) {
74 Term::insertFromTagFieldByItemId($item['id']);
75 Term::insertFromFileFieldByItemId($item['id']);
76 self::updateThread($item['id']);
78 // We only need to notfiy others when it is an original entry from us
79 if ($item['origin']) {
80 Worker::add(PRIORITY_HIGH, "Notifier", 'edit_post', $item['id']);
90 * @brief Delete an item and notify others about it - if it was ours
92 * @param array $condition The condition for finding the item entries
93 * @param integer $priority Priority for the notification
95 public static function delete($condition, $priority = PRIORITY_HIGH)
97 $items = dba::select('item', ['id'], $condition);
98 while ($item = dba::fetch($items)) {
99 self::deleteById($item['id'], $priority);
105 * @brief Delete an item and notify others about it - if it was ours
107 * @param integer $item_id Item ID that should be delete
108 * @param integer $priority Priority for the notification
110 * @return boolean success
112 public static function deleteById($item_id, $priority = PRIORITY_HIGH)
114 // locate item to be deleted
115 $fields = ['id', 'uid', 'parent', 'parent-uri', 'origin', 'deleted',
116 'file', 'resource-id', 'event-id', 'attach',
117 'verb', 'object-type', 'object', 'target', 'contact-id'];
118 $item = dba::selectFirst('item', $fields, ['id' => $item_id]);
119 if (!DBM::is_result($item)) {
123 if ($item['deleted']) {
127 $parent = dba::selectFirst('item', ['origin'], ['id' => $item['parent']]);
128 if (!DBM::is_result($parent)) {
129 $parent = ['origin' => false];
132 logger('delete item: ' . $item['id'], LOGGER_DEBUG);
134 // clean up categories and tags so they don't end up as orphans
137 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
139 foreach ($matches as $mtch) {
140 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],true);
146 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
148 foreach ($matches as $mtch) {
149 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],false);
154 * If item is a link to a photo resource, nuke all the associated photos
155 * (visitors will not have photo resources)
156 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
157 * generate a resource-id and therefore aren't intimately linked to the item.
159 if (strlen($item['resource-id'])) {
160 dba::delete('photo', ['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
163 // If item is a link to an event, delete the event.
164 if (intval($item['event-id'])) {
165 Event::delete($item['event-id']);
168 // If item has attachments, drop them
169 foreach (explode(", ", $item['attach']) as $attach) {
170 preg_match("|attach/(\d+)|", $attach, $matches);
171 dba::delete('attach', ['id' => $matches[1], 'uid' => $item['uid']]);
174 // Delete tags that had been attached to other items
175 self::deleteTagsFromItem($item);
177 // Set the item to "deleted"
178 dba::update('item', ['deleted' => true, 'title' => '', 'body' => '',
179 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()],
180 ['id' => $item['id']]);
182 Term::insertFromTagFieldByItemId($item['id']);
183 Term::insertFromFileFieldByItemId($item['id']);
184 self::deleteThread($item['id'], $item['parent-uri']);
186 // If it's the parent of a comment thread, kill all the kids
187 if ($item['id'] == $item['parent']) {
188 self::delete(['parent' => $item['parent']], $priority);
191 // send the notification upstream/downstream
192 if ($item['origin'] || $parent['origin']) {
193 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", "drop", intval($item['id']));
199 private static function deleteTagsFromItem($item)
201 if (($item["verb"] != ACTIVITY_TAG) || ($item["object-type"] != ACTIVITY_OBJ_TAGTERM)) {
205 $xo = XML::parseString($item["object"], false);
206 $xt = XML::parseString($item["target"], false);
208 if ($xt->type != ACTIVITY_OBJ_NOTE) {
212 $i = dba::selectFirst('item', ['id', 'contact-id', 'tag'], ['uri' => $xt->id, 'uid' => $item['uid']]);
213 if (!DBM::is_result($i)) {
217 // For tags, the owner cannot remove the tag on the author's copy of the post.
218 $owner_remove = ($item["contact-id"] == $i["contact-id"]);
219 $author_copy = $item["origin"];
221 if (($owner_remove && $author_copy) || !$owner_remove) {
225 $tags = explode(',', $i["tag"]);
228 foreach ($tags as $tag) {
229 if (trim($tag) !== trim($xo->body)) {
230 $newtags[] = trim($tag);
234 self::update(['tag' => implode(',', $newtags)], ['id' => $i["id"]]);
237 private static function guid($item, $notify)
239 $guid = notags(trim($item['guid']));
246 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
247 // We add the hash of our own host because our host is the original creator of the post.
248 $prefix_host = get_app()->get_hostname();
252 // We are only storing the post so we create a GUID from the original hostname.
253 if (!empty($item['author-link'])) {
254 $parsed = parse_url($item['author-link']);
255 if (!empty($parsed['host'])) {
256 $prefix_host = $parsed['host'];
260 if (empty($prefix_host) && !empty($item['plink'])) {
261 $parsed = parse_url($item['plink']);
262 if (!empty($parsed['host'])) {
263 $prefix_host = $parsed['host'];
267 if (empty($prefix_host) && !empty($item['uri'])) {
268 $parsed = parse_url($item['uri']);
269 if (!empty($parsed['host'])) {
270 $prefix_host = $parsed['host'];
274 // Is it in the format data@host.tld? - Used for mail contacts
275 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
276 $mailparts = explode('@', $item['author-link']);
277 $prefix_host = array_pop($mailparts);
281 if (!empty($item['plink'])) {
282 $guid = self::guidFromUri($item['plink'], $prefix_host);
283 } elseif (!empty($item['uri'])) {
284 $guid = self::guidFromUri($item['uri'], $prefix_host);
286 $guid = get_guid(32, hash('crc32', $prefix_host));
292 private static function contactId($item)
294 $contact_id = (int)$item["contact-id"];
296 if (!empty($contact_id)) {
299 logger('Missing contact-id. Called by: '.System::callstack(), LOGGER_DEBUG);
301 * First we are looking for a suitable contact that matches with the author of the post
302 * This is done only for comments
304 if ($item['parent-uri'] != $item['uri']) {
305 $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
308 // If not present then maybe the owner was found
309 if ($contact_id == 0) {
310 $contact_id = Contact::getIdForURL($item['owner-link'], $item['uid']);
313 // Still missing? Then use the "self" contact of the current user
314 if ($contact_id == 0) {
315 $self = dba::selectFirst('contact', ['id'], ['self' => true, 'uid' => $item['uid']]);
316 if (DBM::is_result($self)) {
317 $contact_id = $self["id"];
320 logger("Contact-id was missing for post ".$item['guid']." from user id ".$item['uid']." - now set to ".$contact_id, LOGGER_DEBUG);
325 public static function insert($item, $force_parent = false, $notify = false, $dontcache = false)
329 // If it is a posting where users should get notifications, then define it as wall posting
332 $item['type'] = 'wall';
334 $item['network'] = NETWORK_DFRN;
335 $item['protocol'] = PROTOCOL_DFRN;
337 $item['network'] = trim(defaults($item, 'network', NETWORK_PHANTOM));
340 $item['guid'] = self::guid($item, $notify);
341 $item['uri'] = notags(trim(defaults($item, 'uri', item_new_uri($a->get_hostname(), $item['uid'], $item['guid']))));
343 // Store conversation data
344 $item = Conversation::insert($item);
347 * If a Diaspora signature structure was passed in, pull it out of the
348 * item array and set it aside for later storage.
352 if (x($item, 'dsprsig')) {
353 $encoded_signature = $item['dsprsig'];
354 $dsprsig = json_decode(base64_decode($item['dsprsig']));
355 unset($item['dsprsig']);
358 if (!empty($item['diaspora_signed_text'])) {
359 $diaspora_signed_text = $item['diaspora_signed_text'];
360 unset($item['diaspora_signed_text']);
362 $diaspora_signed_text = '';
365 // Converting the plink
366 /// @TODO Check if this is really still needed
367 if ($item['network'] == NETWORK_OSTATUS) {
368 if (isset($item['plink'])) {
369 $item['plink'] = OStatus::convertHref($item['plink']);
370 } elseif (isset($item['uri'])) {
371 $item['plink'] = OStatus::convertHref($item['uri']);
375 if (!empty($item['thr-parent'])) {
376 $item['parent-uri'] = $item['thr-parent'];
379 if (x($item, 'gravity')) {
380 $item['gravity'] = intval($item['gravity']);
381 } elseif ($item['parent-uri'] === $item['uri']) {
382 $item['gravity'] = 0;
383 } elseif (activity_match($item['verb'],ACTIVITY_POST)) {
384 $item['gravity'] = 6;
386 $item['gravity'] = 6; // extensible catchall
389 $item['type'] = defaults($item, 'type', 'remote');
391 $uid = intval($item['uid']);
393 // check for create date and expire time
394 $expire_interval = Config::get('system', 'dbclean-expire-days', 0);
396 $user = dba::selectFirst('user', ['expire'], ['uid' => $uid]);
397 if (DBM::is_result($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
398 $expire_interval = $user['expire'];
401 if (($expire_interval > 0) && !empty($item['created'])) {
402 $expire_date = time() - ($expire_interval * 86400);
403 $created_date = strtotime($item['created']);
404 if ($created_date < $expire_date) {
405 logger('item-store: item created ('.date('c', $created_date).') before expiration time ('.date('c', $expire_date).'). ignored. ' . print_r($item,true), LOGGER_DEBUG);
411 * Do we already have this item?
412 * We have to check several networks since Friendica posts could be repeated
413 * via OStatus (maybe Diasporsa as well)
415 if (in_array($item['network'], [NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS, ""])) {
416 $condition = ["`uri` = ? AND `uid` = ? AND `network` IN (?, ?, ?)",
417 trim($item['uri']), $item['uid'],
418 NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS];
419 $existing = dba::selectFirst('item', ['id', 'network'], $condition);
420 if (DBM::is_result($existing)) {
421 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
423 logger("Item with uri ".$item['uri']." already existed for user ".$uid." with id ".$existing["id"]." target network ".$existing["network"]." - new network: ".$item['network']);
426 return $existing["id"];
430 self::addLanguageInPostopts($item);
432 $item['wall'] = intval(defaults($item, 'wall', 0));
433 $item['extid'] = trim(defaults($item, 'extid', ''));
434 $item['author-name'] = trim(defaults($item, 'author-name', ''));
435 $item['author-link'] = trim(defaults($item, 'author-link', ''));
436 $item['author-avatar'] = trim(defaults($item, 'author-avatar', ''));
437 $item['owner-name'] = trim(defaults($item, 'owner-name', ''));
438 $item['owner-link'] = trim(defaults($item, 'owner-link', ''));
439 $item['owner-avatar'] = trim(defaults($item, 'owner-avatar', ''));
440 $item['received'] = ((x($item, 'received') !== false) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
441 $item['created'] = ((x($item, 'created') !== false) ? DateTimeFormat::utc($item['created']) : $item['received']);
442 $item['edited'] = ((x($item, 'edited') !== false) ? DateTimeFormat::utc($item['edited']) : $item['created']);
443 $item['changed'] = ((x($item, 'changed') !== false) ? DateTimeFormat::utc($item['changed']) : $item['created']);
444 $item['commented'] = ((x($item, 'commented') !== false) ? DateTimeFormat::utc($item['commented']) : $item['created']);
445 $item['title'] = trim(defaults($item, 'title', ''));
446 $item['location'] = trim(defaults($item, 'location', ''));
447 $item['coord'] = trim(defaults($item, 'coord', ''));
448 $item['visible'] = ((x($item, 'visible') !== false) ? intval($item['visible']) : 1);
449 $item['deleted'] = 0;
450 $item['parent-uri'] = trim(defaults($item, 'parent-uri', $item['uri']));
451 $item['verb'] = trim(defaults($item, 'verb', ''));
452 $item['object-type'] = trim(defaults($item, 'object-type', ''));
453 $item['object'] = trim(defaults($item, 'object', ''));
454 $item['target-type'] = trim(defaults($item, 'target-type', ''));
455 $item['target'] = trim(defaults($item, 'target', ''));
456 $item['plink'] = trim(defaults($item, 'plink', ''));
457 $item['allow_cid'] = trim(defaults($item, 'allow_cid', ''));
458 $item['allow_gid'] = trim(defaults($item, 'allow_gid', ''));
459 $item['deny_cid'] = trim(defaults($item, 'deny_cid', ''));
460 $item['deny_gid'] = trim(defaults($item, 'deny_gid', ''));
461 $item['private'] = intval(defaults($item, 'private', 0));
462 $item['bookmark'] = intval(defaults($item, 'bookmark', 0));
463 $item['body'] = trim(defaults($item, 'body', ''));
464 $item['tag'] = trim(defaults($item, 'tag', ''));
465 $item['attach'] = trim(defaults($item, 'attach', ''));
466 $item['app'] = trim(defaults($item, 'app', ''));
467 $item['origin'] = intval(defaults($item, 'origin', 0));
468 $item['postopts'] = trim(defaults($item, 'postopts', ''));
469 $item['resource-id'] = trim(defaults($item, 'resource-id', ''));
470 $item['event-id'] = intval(defaults($item, 'event-id', 0));
471 $item['inform'] = trim(defaults($item, 'inform', ''));
472 $item['file'] = trim(defaults($item, 'file', ''));
474 // When there is no content then we don't post it
475 if ($item['body'].$item['title'] == '') {
479 // Items cannot be stored before they happen ...
480 if ($item['created'] > DateTimeFormat::utcNow()) {
481 $item['created'] = DateTimeFormat::utcNow();
484 // We haven't invented time travel by now.
485 if ($item['edited'] > DateTimeFormat::utcNow()) {
486 $item['edited'] = DateTimeFormat::utcNow();
489 if (($item['author-link'] == "") && ($item['owner-link'] == "")) {
490 logger("Both author-link and owner-link are empty. Called by: " . System::callstack(), LOGGER_DEBUG);
493 $item['plink'] = defaults($item, 'plink', System::baseUrl() . '/display/' . urlencode($item['guid']));
495 // The contact-id should be set before "self::insert" was called - but there seems to be issues sometimes
496 $item["contact-id"] = self::contactId($item);
498 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
499 'photo' => $item['author-avatar'], 'network' => $item['network']];
501 $item['author-id'] = defaults($item, 'author-id', Contact::getIdForURL($item["author-link"], 0, false, $default));
503 if (Contact::isBlocked($item["author-id"])) {
504 logger('Contact '.$item["author-id"].' is blocked, item '.$item["uri"].' will not be stored');
508 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
509 'photo' => $item['owner-avatar'], 'network' => $item['network']];
511 $item['owner-id'] = defaults($item, 'owner-id', Contact::getIdForURL($item["owner-link"], 0, false, $default));
513 if (Contact::isBlocked($item["owner-id"])) {
514 logger('Contact '.$item["owner-id"].' is blocked, item '.$item["uri"].' will not be stored');
518 if ($item['network'] == NETWORK_PHANTOM) {
519 logger('Missing network. Called by: '.System::callstack(), LOGGER_DEBUG);
521 $contact = Contact::getDetailsByURL($item['author-link'], $item['uid']);
522 if (!empty($contact['network'])) {
523 $item['network'] = $contact["network"];
525 $item['network'] = NETWORK_DFRN;
527 logger("Set network to " . $item["network"] . " for " . $item["uri"], LOGGER_DEBUG);
530 // Checking if there is already an item with the same guid
531 logger('Checking for an item for user '.$item['uid'].' on network '.$item['network'].' with the guid '.$item['guid'], LOGGER_DEBUG);
532 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
533 if (dba::exists('item', $condition)) {
534 logger('found item with guid '.$item['guid'].' for user '.$item['uid'].' on network '.$item['network'], LOGGER_DEBUG);
538 // Check for hashtags in the body and repair or add hashtag links
539 self::setHashtags($item);
541 $item['thr-parent'] = $item['parent-uri'];
549 if ($item['parent-uri'] === $item['uri']) {
552 $allow_cid = $item['allow_cid'];
553 $allow_gid = $item['allow_gid'];
554 $deny_cid = $item['deny_cid'];
555 $deny_gid = $item['deny_gid'];
556 $notify_type = 'wall-new';
558 // find the parent and snarf the item id and ACLs
559 // and anything else we need to inherit
561 $fields = ['uri', 'parent-uri', 'id', 'deleted',
562 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
563 'wall', 'private', 'forum_mode', 'origin'];
564 $condition = ['uri' => $item['parent-uri'], 'uid' => $item['uid']];
565 $params = ['order' => ['id' => false]];
566 $parent = dba::selectFirst('item', $fields, $condition, $params);
568 if (DBM::is_result($parent)) {
569 // is the new message multi-level threaded?
570 // even though we don't support it now, preserve the info
571 // and re-attach to the conversation parent.
573 if ($parent['uri'] != $parent['parent-uri']) {
574 $item['parent-uri'] = $parent['parent-uri'];
576 $condition = ['uri' => $item['parent-uri'],
577 'parent-uri' => $item['parent-uri'],
578 'uid' => $item['uid']];
579 $params = ['order' => ['id' => false]];
580 $toplevel_parent = dba::selectFirst('item', $fields, $condition, $params);
582 if (DBM::is_result($toplevel_parent)) {
583 $parent = $toplevel_parent;
587 $parent_id = $parent['id'];
588 $parent_deleted = $parent['deleted'];
589 $allow_cid = $parent['allow_cid'];
590 $allow_gid = $parent['allow_gid'];
591 $deny_cid = $parent['deny_cid'];
592 $deny_gid = $parent['deny_gid'];
593 $item['wall'] = $parent['wall'];
594 $notify_type = 'comment-new';
597 * If the parent is private, force privacy for the entire conversation
598 * This differs from the above settings as it subtly allows comments from
599 * email correspondents to be private even if the overall thread is not.
601 if ($parent['private']) {
602 $item['private'] = $parent['private'];
606 * Edge case. We host a public forum that was originally posted to privately.
607 * The original author commented, but as this is a comment, the permissions
608 * weren't fixed up so it will still show the comment as private unless we fix it here.
610 if ((intval($parent['forum_mode']) == 1) && $parent['private']) {
611 $item['private'] = 0;
614 // If its a post from myself then tag the thread as "mention"
615 logger("Checking if parent ".$parent_id." has to be tagged as mention for user ".$item['uid'], LOGGER_DEBUG);
616 $user = dba::selectFirst('user', ['nickname'], ['uid' => $item['uid']]);
617 if (DBM::is_result($user)) {
618 $self = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
619 logger("'myself' is ".$self." for parent ".$parent_id." checking against ".$item['author-link']." and ".$item['owner-link'], LOGGER_DEBUG);
620 if ((normalise_link($item['author-link']) == $self) || (normalise_link($item['owner-link']) == $self)) {
621 dba::update('thread', ['mention' => true], ['iid' => $parent_id]);
622 logger("tagged thread ".$parent_id." as mention for user ".$self, LOGGER_DEBUG);
627 * Allow one to see reply tweets from status.net even when
628 * we don't have or can't see the original post.
631 logger('$force_parent=true, reply converted to top-level post.');
633 $item['parent-uri'] = $item['uri'];
634 $item['gravity'] = 0;
636 logger('item parent '.$item['parent-uri'].' for '.$item['uid'].' was not found - ignoring item');
644 $condition = ["`uri` = ? AND `network` IN (?, ?) AND `uid` = ?",
645 $item['uri'], $item['network'], NETWORK_DFRN, $item['uid']];
646 if (dba::exists('item', $condition)) {
647 logger('duplicated item with the same uri found. '.print_r($item,true));
651 // On Friendica and Diaspora the GUID is unique
652 if (in_array($item['network'], [NETWORK_DFRN, NETWORK_DIASPORA])) {
653 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
654 if (dba::exists('item', $condition)) {
655 logger('duplicated item with the same guid found. '.print_r($item,true));
659 // Check for an existing post with the same content. There seems to be a problem with OStatus.
660 $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
661 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
662 if (dba::exists('item', $condition)) {
663 logger('duplicated item with the same body found. '.print_r($item,true));
668 // Is this item available in the global items (with uid=0)?
669 if ($item["uid"] == 0) {
670 $item["global"] = true;
672 // Set the global flag on all items if this was a global item entry
673 dba::update('item', ['global' => true], ['uri' => $item["uri"]]);
675 $item["global"] = dba::exists('item', ['uid' => 0, 'uri' => $item["uri"]]);
679 if (strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid)) {
682 $private = $item['private'];
685 $item["allow_cid"] = $allow_cid;
686 $item["allow_gid"] = $allow_gid;
687 $item["deny_cid"] = $deny_cid;
688 $item["deny_gid"] = $deny_gid;
689 $item["private"] = $private;
690 $item["deleted"] = $parent_deleted;
692 // Fill the cache field
693 put_item_in_cache($item);
696 Addon::callHooks('post_local', $item);
698 Addon::callHooks('post_remote', $item);
701 // This array field is used to trigger some automatic reactions
702 // It is mainly used in the "post_local" hook.
703 unset($item['api_source']);
705 if (x($item, 'cancel')) {
706 logger('post cancelled by addon.');
711 * Check for already added items.
712 * There is a timing issue here that sometimes creates double postings.
713 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
715 if ($item["uid"] == 0) {
716 if (dba::exists('item', ['uri' => trim($item['uri']), 'uid' => 0])) {
717 logger('Global item already stored. URI: '.$item['uri'].' on network '.$item['network'], LOGGER_DEBUG);
722 logger('' . print_r($item,true), LOGGER_DATA);
725 $ret = dba::insert('item', $item);
727 // When the item was successfully stored we fetch the ID of the item.
728 if (DBM::is_result($ret)) {
729 $current_post = dba::lastInsertId();
731 // This can happen - for example - if there are locking timeouts.
734 // Store the data into a spool file so that we can try again later.
736 // At first we restore the Diaspora signature that we removed above.
737 if (isset($encoded_signature)) {
738 $item['dsprsig'] = $encoded_signature;
741 // Now we store the data in the spool directory
742 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
743 $file = 'item-'.round(microtime(true) * 10000).'-'.mt_rand().'.msg';
745 $spoolpath = get_spoolpath();
746 if ($spoolpath != "") {
747 $spool = $spoolpath.'/'.$file;
748 file_put_contents($spool, json_encode($item));
749 logger("Item wasn't stored - Item was spooled into file ".$file, LOGGER_DEBUG);
754 if ($current_post == 0) {
755 // This is one of these error messages that never should occur.
756 logger("couldn't find created item - we better quit now.");
761 // How much entries have we created?
762 // We wouldn't need this query when we could use an unique index - but MySQL has length problems with them.
763 $entries = dba::count('item', ['uri' => $item['uri'], 'uid' => $item['uid'], 'network' => $item['network']]);
766 // There are duplicates. We delete our just created entry.
767 logger('Duplicated post occurred. uri = ' . $item['uri'] . ' uid = ' . $item['uid']);
769 // Yes, we could do a rollback here - but we are having many users with MyISAM.
770 dba::delete('item', ['id' => $current_post]);
773 } elseif ($entries == 0) {
774 // This really should never happen since we quit earlier if there were problems.
775 logger("Something is terribly wrong. We haven't found our created entry.");
780 logger('created item '.$current_post);
781 self::updateContact($item);
783 if (!$parent_id || ($item['parent-uri'] === $item['uri'])) {
784 $parent_id = $current_post;
788 dba::update('item', ['parent' => $parent_id], ['id' => $current_post]);
790 $item['id'] = $current_post;
791 $item['parent'] = $parent_id;
793 // update the commented timestamp on the parent
794 // Only update "commented" if it is really a comment
795 if (($item['verb'] == ACTIVITY_POST) || !Config::get("system", "like_no_comment")) {
796 dba::update('item', ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
798 dba::update('item', ['changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
803 * Friendica servers lower than 3.4.3-2 had double encoded the signature ...
804 * We can check for this condition when we decode and encode the stuff again.
806 if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) {
807 $dsprsig->signature = base64_decode($dsprsig->signature);
808 logger("Repaired double encoded signature from handle ".$dsprsig->signer, LOGGER_DEBUG);
811 dba::insert('sign', ['iid' => $current_post, 'signed_text' => $dsprsig->signed_text,
812 'signature' => $dsprsig->signature, 'signer' => $dsprsig->signer]);
815 if (!empty($diaspora_signed_text)) {
816 // Formerly we stored the signed text, the signature and the author in different fields.
817 // We now store the raw data so that we are more flexible.
818 dba::insert('sign', ['iid' => $current_post, 'signed_text' => $diaspora_signed_text]);
821 $deleted = self::tagDeliver($item['uid'], $current_post);
824 * current post can be deleted if is for a community page and no mention are
827 if (!$deleted && !$dontcache) {
828 $posted_item = dba::selectFirst('item', [], ['id' => $current_post]);
829 if (DBM::is_result($posted_item)) {
831 Addon::callHooks('post_local_end', $posted_item);
833 Addon::callHooks('post_remote_end', $posted_item);
836 logger('new item not found in DB, id ' . $current_post);
840 if ($item['parent-uri'] === $item['uri']) {
841 self::addThread($current_post);
843 self::updateThread($parent_id);
849 * Due to deadlock issues with the "term" table we are doing these steps after the commit.
850 * This is not perfect - but a workable solution until we found the reason for the problem.
852 Term::insertFromTagFieldByItemId($current_post);
853 Term::insertFromFileFieldByItemId($current_post);
855 if ($item['parent-uri'] === $item['uri']) {
856 self::addShadow($current_post);
858 self::addShadowPost($current_post);
861 check_user_notification($current_post);
864 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "Notifier", $notify_type, $current_post);
865 } elseif (!empty($parent) && $parent['origin']) {
866 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "Notifier", "comment-import", $current_post);
869 return $current_post;
873 * @brief Distributes public items to the receivers
875 * @param integer $itemid Item ID that should be added
876 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
878 public static function distribute($itemid, $signed_text = '')
880 $condition = ["`id` IN (SELECT `parent` FROM `item` WHERE `id` = ?)", $itemid];
881 $parent = dba::selectFirst('item', ['owner-id'], $condition);
882 if (!DBM::is_result($parent)) {
886 // Only distribute public items from native networks
887 $condition = ['id' => $itemid, 'uid' => 0,
888 'network' => [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""],
889 'visible' => true, 'deleted' => false, 'moderated' => false, 'private' => false];
890 $item = dba::selectFirst('item', [], ['id' => $itemid]);
891 if (!DBM::is_result($item)) {
896 unset($item['parent']);
897 unset($item['mention']);
898 unset($item['wall']);
899 unset($item['origin']);
900 unset($item['starred']);
901 unset($item['rendered-hash']);
902 unset($item['rendered-html']);
906 $condition = ["`nurl` IN (SELECT `nurl` FROM `contact` WHERE `id` = ?) AND `uid` != 0 AND NOT `blocked` AND `rel` IN (?, ?)",
907 $parent['owner-id'], CONTACT_IS_SHARING, CONTACT_IS_FRIEND];
908 $contacts = dba::select('contact', ['uid'], $condition);
909 while ($contact = dba::fetch($contacts)) {
910 $users[$contact['uid']] = $contact['uid'];
915 if ($item['uri'] != $item['parent-uri']) {
916 $parents = dba::select('item', ['uid', 'origin'], ["`uri` = ? AND `uid` != 0", $item['parent-uri']]);
917 while ($parent = dba::fetch($parents)) {
918 $users[$parent['uid']] = $parent['uid'];
919 if ($parent['origin'] && !$item['origin']) {
920 $origin_uid = $parent['uid'];
925 foreach ($users as $uid) {
926 if ($origin_uid == $uid) {
927 $item['diaspora_signed_text'] = $signed_text;
929 self::storeForUser($itemid, $item, $uid);
934 * @brief Store public items for the receivers
936 * @param integer $itemid Item ID that should be added
937 * @param array $item The item entry that will be stored
938 * @param integer $uid The user that will receive the item entry
940 private static function storeForUser($itemid, $item, $uid)
945 if ($item['uri'] == $item['parent-uri']) {
946 $item['contact-id'] = Contact::getIdForURL($item['owner-link'], $uid);
948 $item['contact-id'] = Contact::getIdForURL($item['author-link'], $uid);
951 if (empty($item['contact-id'])) {
952 $self = dba::selectFirst('contact', ['id'], ['self' => true, 'uid' => $uid]);
953 if (!DBM::is_result($self)) {
956 $item['contact-id'] = $self['id'];
959 if (in_array($item['type'], ["net-comment", "wall-comment"])) {
960 $item['type'] = 'remote-comment';
961 } elseif ($item['type'] == 'wall') {
962 $item['type'] = 'remote';
965 /// @todo Handling of "event-id"
968 if ($item['uri'] == $item['parent-uri']) {
969 $contact = dba::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
970 if (DBM::is_result($contact)) {
971 $notify = self::isRemoteSelf($contact, $item);
975 $distributed = self::insert($item, false, $notify, true);
978 logger("Distributed public item " . $itemid . " for user " . $uid . " wasn't stored", LOGGER_DEBUG);
980 logger("Distributed public item " . $itemid . " for user " . $uid . " with id " . $distributed, LOGGER_DEBUG);
985 * @brief Add a shadow entry for a given item id that is a thread starter
987 * We store every public item entry additionally with the user id "0".
988 * This is used for the community page and for the search.
989 * It is planned that in the future we will store public item entries only once.
991 * @param integer $itemid Item ID that should be added
993 public static function addShadow($itemid)
995 $fields = ['uid', 'private', 'moderated', 'visible', 'deleted', 'network'];
996 $condition = ['id' => $itemid, 'parent' => [0, $itemid]];
997 $item = dba::selectFirst('item', $fields, $condition);
999 if (!DBM::is_result($item)) {
1003 // is it already a copy?
1004 if (($itemid == 0) || ($item['uid'] == 0)) {
1008 // Is it a visible public post?
1009 if (!$item["visible"] || $item["deleted"] || $item["moderated"] || $item["private"]) {
1013 // is it an entry from a connector? Only add an entry for natively connected networks
1014 if (!in_array($item["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""])) {
1018 $item = dba::selectFirst('item', [], ['id' => $itemid]);
1020 if (DBM::is_result($item) && ($item["allow_cid"] == '') && ($item["allow_gid"] == '') &&
1021 ($item["deny_cid"] == '') && ($item["deny_gid"] == '')) {
1023 if (!dba::exists('item', ['uri' => $item['uri'], 'uid' => 0])) {
1024 // Preparing public shadow (removing user specific data)
1027 unset($item['parent']);
1028 unset($item['wall']);
1029 unset($item['mention']);
1030 unset($item['origin']);
1031 unset($item['starred']);
1032 unset($item['rendered-hash']);
1033 unset($item['rendered-html']);
1034 if ($item['uri'] == $item['parent-uri']) {
1035 $item['contact-id'] = Contact::getIdForURL($item['owner-link']);
1037 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
1040 if (in_array($item['type'], ["net-comment", "wall-comment"])) {
1041 $item['type'] = 'remote-comment';
1042 } elseif ($item['type'] == 'wall') {
1043 $item['type'] = 'remote';
1046 $public_shadow = self::insert($item, false, false, true);
1048 logger("Stored public shadow for thread ".$itemid." under id ".$public_shadow, LOGGER_DEBUG);
1054 * @brief Add a shadow entry for a given item id that is a comment
1056 * This function does the same like the function above - but for comments
1058 * @param integer $itemid Item ID that should be added
1060 public static function addShadowPost($itemid)
1062 $item = dba::selectFirst('item', [], ['id' => $itemid]);
1063 if (!DBM::is_result($item)) {
1067 // Is it a toplevel post?
1068 if ($item['id'] == $item['parent']) {
1069 self::addShadow($itemid);
1073 // Is this a shadow entry?
1074 if ($item['uid'] == 0)
1077 // Is there a shadow parent?
1078 if (!dba::exists('item', ['uri' => $item['parent-uri'], 'uid' => 0])) {
1082 // Is there already a shadow entry?
1083 if (dba::exists('item', ['uri' => $item['uri'], 'uid' => 0])) {
1087 // Save "origin" and "parent" state
1088 $origin = $item['origin'];
1089 $parent = $item['parent'];
1091 // Preparing public shadow (removing user specific data)
1094 unset($item['parent']);
1095 unset($item['wall']);
1096 unset($item['mention']);
1097 unset($item['origin']);
1098 unset($item['starred']);
1099 unset($item['rendered-hash']);
1100 unset($item['rendered-html']);
1101 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
1103 if (in_array($item['type'], ["net-comment", "wall-comment"])) {
1104 $item['type'] = 'remote-comment';
1105 } elseif ($item['type'] == 'wall') {
1106 $item['type'] = 'remote';
1109 $public_shadow = self::insert($item, false, false, true);
1111 logger("Stored public shadow for comment ".$item['uri']." under id ".$public_shadow, LOGGER_DEBUG);
1113 // If this was a comment to a Diaspora post we don't get our comment back.
1114 // This means that we have to distribute the comment by ourselves.
1116 if (dba::exists('item', ['id' => $parent, 'network' => NETWORK_DIASPORA])) {
1117 self::distribute($public_shadow);
1123 * Adds a "lang" specification in a "postopts" element of given $arr,
1124 * if possible and not already present.
1125 * Expects "body" element to exist in $arr.
1127 private static function addLanguageInPostopts(&$item)
1129 if (!empty($item['postopts'])) {
1130 if (strstr($item['postopts'], 'lang=')) {
1134 $postopts = $item['postopts'];
1139 $naked_body = Text\BBCode::toPlaintext($item['body'], false);
1141 $languages = (new Text_LanguageDetect())->detect($naked_body, 3);
1143 if (sizeof($languages) > 0) {
1144 if ($postopts != '') {
1145 $postopts .= '&'; // arbitrary separator, to be reviewed
1148 $postopts .= 'lang=';
1151 foreach ($languages as $language => $score) {
1152 $postopts .= $sep . $language . ";" . $score;
1155 $item['postopts'] = $postopts;
1160 * @brief Creates an unique guid out of a given uri
1162 * @param string $uri uri of an item entry
1163 * @param string $host hostname for the GUID prefix
1164 * @return string unique guid
1166 public static function guidFromUri($uri, $host)
1168 // Our regular guid routine is using this kind of prefix as well
1169 // We have to avoid that different routines could accidentally create the same value
1170 $parsed = parse_url($uri);
1172 // We use a hash of the hostname as prefix for the guid
1173 $guid_prefix = hash("crc32", $host);
1175 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
1176 unset($parsed["scheme"]);
1178 // Glue it together to be able to make a hash from it
1179 $host_id = implode("/", $parsed);
1181 // We could use any hash algorithm since it isn't a security issue
1182 $host_hash = hash("ripemd128", $host_id);
1184 return $guid_prefix.$host_hash;
1188 * @brief Set "success_update" and "last-item" to the date of the last time we heard from this contact
1190 * This can be used to filter for inactive contacts.
1191 * Only do this for public postings to avoid privacy problems, since poco data is public.
1192 * Don't set this value if it isn't from the owner (could be an author that we don't know)
1194 * @param array $arr Contains the just posted item record
1196 private static function updateContact($arr)
1198 // Unarchive the author
1199 $contact = dba::selectFirst('contact', [], ['id' => $arr["author-id"]]);
1200 if (DBM::is_result($contact)) {
1201 Contact::unmarkForArchival($contact);
1204 // Unarchive the contact if it's not our own contact
1205 $contact = dba::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
1206 if (DBM::is_result($contact)) {
1207 Contact::unmarkForArchival($contact);
1210 $update = (!$arr['private'] && (($arr["author-link"] === $arr["owner-link"]) || ($arr["parent-uri"] === $arr["uri"])));
1212 // Is it a forum? Then we don't care about the rules from above
1213 if (!$update && ($arr["network"] == NETWORK_DFRN) && ($arr["parent-uri"] === $arr["uri"])) {
1214 if (dba::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
1220 dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
1221 ['id' => $arr['contact-id']]);
1223 // Now do the same for the system wide contacts with uid=0
1224 if (!$arr['private']) {
1225 dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
1226 ['id' => $arr['owner-id']]);
1228 if ($arr['owner-id'] != $arr['author-id']) {
1229 dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
1230 ['id' => $arr['author-id']]);
1235 private static function setHashtags(&$item)
1238 $tags = get_tags($item["body"]);
1241 if (!count($tags)) {
1245 // This sorting is important when there are hashtags that are part of other hashtags
1246 // Otherwise there could be problems with hashtags like #test and #test2
1249 $URLSearchString = "^\[\]";
1251 // All hashtags should point to the home server if "local_tags" is activated
1252 if (Config::get('system', 'local_tags')) {
1253 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1254 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["body"]);
1256 $item["tag"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1257 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["tag"]);
1260 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
1261 $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1263 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
1266 $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
1268 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
1271 $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
1273 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
1276 // Repair recursive urls
1277 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1278 "#$2", $item["body"]);
1280 foreach ($tags as $tag) {
1281 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=')) {
1285 $basetag = str_replace('_',' ',substr($tag,1));
1287 $newtag = '#[url=' . System::baseUrl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1289 $item["body"] = str_replace($tag, $newtag, $item["body"]);
1291 if (!stristr($item["tag"], "/search?tag=" . $basetag . "]" . $basetag . "[/url]")) {
1292 if (strlen($item["tag"])) {
1293 $item["tag"] = ','.$item["tag"];
1295 $item["tag"] = $newtag.$item["tag"];
1299 // Convert back the masked hashtags
1300 $item["body"] = str_replace("#", "#", $item["body"]);
1303 public static function getGuidById($id)
1305 $item = dba::selectFirst('item', ['guid'], ['id' => $id]);
1306 if (DBM::is_result($item)) {
1307 return $item['guid'];
1313 public static function getIdAndNickByGuid($guid, $uid = 0)
1319 $uid == local_user();
1322 // Does the given user have this item?
1324 $item = dba::fetch_first("SELECT `item`.`id`, `user`.`nickname` FROM `item`
1325 INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
1326 WHERE `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
1327 AND `item`.`guid` = ? AND `item`.`uid` = ?", $guid, $uid);
1328 if (DBM::is_result($item)) {
1330 $nick = $item["nickname"];
1334 // Or is it anywhere on the server?
1336 $item = dba::fetch_first("SELECT `item`.`id`, `user`.`nickname` FROM `item`
1337 INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
1338 WHERE `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
1339 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1340 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1341 AND NOT `item`.`private` AND `item`.`wall`
1342 AND `item`.`guid` = ?", $guid);
1343 if (DBM::is_result($item)) {
1345 $nick = $item["nickname"];
1348 return ["nick" => $nick, "id" => $id];
1352 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
1354 * @param int $item_id
1355 * @return bool true if item was deleted, else false
1357 private static function tagDeliver($uid, $item_id)
1361 $user = dba::selectFirst('user', [], ['uid' => $uid]);
1362 if (!DBM::is_result($user)) {
1366 $community_page = (($user['page-flags'] == PAGE_COMMUNITY) ? true : false);
1367 $prvgroup = (($user['page-flags'] == PAGE_PRVGROUP) ? true : false);
1369 $item = dba::selectFirst('item', [], ['id' => $item_id]);
1370 if (!DBM::is_result($item)) {
1374 $link = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
1377 * Diaspora uses their own hardwired link URL in @-tags
1378 * instead of the one we supply with webfinger
1380 $dlink = normalise_link(System::baseUrl() . '/u/' . $user['nickname']);
1382 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
1384 foreach ($matches as $mtch) {
1385 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
1387 logger('mention found: ' . $mtch[2]);
1393 if (($community_page || $prvgroup) &&
1394 !$item['wall'] && !$item['origin'] && ($item['id'] == $item['parent'])) {
1395 // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
1397 logger("no-mention top-level post to community or private group. delete.");
1398 dba::delete('item', ['id' => $item_id]);
1404 $arr = ['item' => $item, 'user' => $user];
1406 Addon::callHooks('tagged', $arr);
1408 if (!$community_page && !$prvgroup) {
1413 * tgroup delivery - setup a second delivery chain
1414 * prevent delivery looping - only proceed
1415 * if the message originated elsewhere and is a top-level post
1417 if ($item['wall'] || $item['origin'] || ($item['id'] != $item['parent'])) {
1421 // now change this copy of the post to a forum head message and deliver to all the tgroup members
1422 $self = dba::selectFirst('contact', ['id', 'name', 'url', 'thumb'], ['uid' => $uid, 'self' => true]);
1423 if (!DBM::is_result($self)) {
1427 $owner_id = Contact::getIdForURL($self['url']);
1429 // also reset all the privacy bits to the forum default permissions
1431 $private = ($user['allow_cid'] || $user['allow_gid'] || $user['deny_cid'] || $user['deny_gid']) ? 1 : 0;
1433 $forum_mode = ($prvgroup ? 2 : 1);
1435 $fields = ['wall' => true, 'origin' => true, 'forum_mode' => $forum_mode, 'contact-id' => $self['id'],
1436 'owner-id' => $owner_id, 'owner-name' => $self['name'], 'owner-link' => $self['url'],
1437 'owner-avatar' => $self['thumb'], 'private' => $private, 'allow_cid' => $user['allow_cid'],
1438 'allow_gid' => $user['allow_gid'], 'deny_cid' => $user['deny_cid'], 'deny_gid' => $user['deny_gid']];
1439 dba::update('item', $fields, ['id' => $item_id]);
1441 self::updateThread($item_id);
1443 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', 'tgroup', $item_id);
1446 public static function isRemoteSelf($contact, &$datarray)
1450 if (!$contact['remote_self']) {
1454 // Prevent the forwarding of posts that are forwarded
1455 if ($datarray["extid"] == NETWORK_DFRN) {
1456 logger('Already forwarded', LOGGER_DEBUG);
1460 // Prevent to forward already forwarded posts
1461 if ($datarray["app"] == $a->get_hostname()) {
1462 logger('Already forwarded (second test)', LOGGER_DEBUG);
1466 // Only forward posts
1467 if ($datarray["verb"] != ACTIVITY_POST) {
1468 logger('No post', LOGGER_DEBUG);
1472 if (($contact['network'] != NETWORK_FEED) && $datarray['private']) {
1473 logger('Not public', LOGGER_DEBUG);
1477 $datarray2 = $datarray;
1478 logger('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), LOGGER_DEBUG);
1479 if ($contact['remote_self'] == 2) {
1480 $self = dba::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
1481 ['uid' => $contact['uid'], 'self' => true]);
1482 if (DBM::is_result($self)) {
1483 $datarray['contact-id'] = $self["id"];
1485 $datarray['owner-name'] = $self["name"];
1486 $datarray['owner-link'] = $self["url"];
1487 $datarray['owner-avatar'] = $self["thumb"];
1489 $datarray['author-name'] = $datarray['owner-name'];
1490 $datarray['author-link'] = $datarray['owner-link'];
1491 $datarray['author-avatar'] = $datarray['owner-avatar'];
1493 unset($datarray['created']);
1494 unset($datarray['edited']);
1496 unset($datarray['network']);
1497 unset($datarray['owner-id']);
1498 unset($datarray['author-id']);
1501 if ($contact['network'] != NETWORK_FEED) {
1502 $datarray["guid"] = get_guid(32);
1503 unset($datarray["plink"]);
1504 $datarray["uri"] = item_new_uri($a->get_hostname(), $contact['uid'], $datarray["guid"]);
1505 $datarray["parent-uri"] = $datarray["uri"];
1506 $datarray["thr-parent"] = $datarray["uri"];
1507 $datarray["extid"] = NETWORK_DFRN;
1508 $urlpart = parse_url($datarray2['author-link']);
1509 $datarray["app"] = $urlpart["host"];
1511 $datarray['private'] = 0;
1515 if ($contact['network'] != NETWORK_FEED) {
1516 // Store the original post
1517 $result = self::insert($datarray2, false, false);
1518 logger('remote-self post original item - Contact '.$contact['url'].' return '.$result.' Item '.print_r($datarray2, true), LOGGER_DEBUG);
1520 $datarray["app"] = "Feed";
1524 // Trigger automatic reactions for addons
1525 $datarray['api_source'] = true;
1527 // We have to tell the hooks who we are - this really should be improved
1528 $_SESSION["authenticated"] = true;
1529 $_SESSION["uid"] = $contact['uid'];
1538 * @param array $item
1542 public static function fixPrivatePhotos($s, $uid, $item = null, $cid = 0)
1544 if (Config::get('system', 'disable_embedded')) {
1548 logger('check for photos', LOGGER_DEBUG);
1549 $site = substr(System::baseUrl(), strpos(System::baseUrl(), '://'));
1554 $img_start = strpos($orig_body, '[img');
1555 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
1556 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
1558 while (($img_st_close !== false) && ($img_len !== false)) {
1559 $img_st_close++; // make it point to AFTER the closing bracket
1560 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
1562 logger('found photo ' . $image, LOGGER_DEBUG);
1564 if (stristr($image, $site . '/photo/')) {
1565 // Only embed locally hosted photos
1567 $i = basename($image);
1568 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
1569 $x = strpos($i, '-');
1572 $res = substr($i, $x + 1);
1573 $i = substr($i, 0, $x);
1574 $fields = ['data', 'type', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'];
1575 $photo = dba::selectFirst('photo', $fields, ['resource-id' => $i, 'scale' => $res, 'uid' => $uid]);
1576 if (DBM::is_result($photo)) {
1578 * Check to see if we should replace this photo link with an embedded image
1579 * 1. No need to do so if the photo is public
1580 * 2. If there's a contact-id provided, see if they're in the access list
1581 * for the photo. If so, embed it.
1582 * 3. Otherwise, if we have an item, see if the item permissions match the photo
1583 * permissions, regardless of order but first check to see if they're an exact
1584 * match to save some processing overhead.
1586 if (self::hasPermissions($photo)) {
1588 $recips = self::enumeratePermissions($photo);
1589 if (in_array($cid, $recips)) {
1593 if (self::samePermissions($item, $photo)) {
1599 $data = $photo['data'];
1600 $type = $photo['type'];
1602 // If a custom width and height were specified, apply before embedding
1603 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
1604 logger('scaling photo', LOGGER_DEBUG);
1606 $width = intval($match[1]);
1607 $height = intval($match[2]);
1609 $Image = new Image($data, $type);
1610 if ($Image->isValid()) {
1611 $Image->scaleDown(max($width, $height));
1612 $data = $Image->asString();
1613 $type = $Image->getType();
1617 logger('replacing photo', LOGGER_DEBUG);
1618 $image = 'data:' . $type . ';base64,' . base64_encode($data);
1619 logger('replaced: ' . $image, LOGGER_DATA);
1625 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
1626 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
1627 if ($orig_body === false) {
1631 $img_start = strpos($orig_body, '[img');
1632 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
1633 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
1636 $new_body = $new_body . $orig_body;
1641 private static function hasPermissions($obj)
1645 x($obj, 'allow_cid')
1647 x($obj, 'allow_gid')
1656 private static function samePermissions($obj1, $obj2)
1658 // first part is easy. Check that these are exactly the same.
1659 if (($obj1['allow_cid'] == $obj2['allow_cid'])
1660 && ($obj1['allow_gid'] == $obj2['allow_gid'])
1661 && ($obj1['deny_cid'] == $obj2['deny_cid'])
1662 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
1666 // This is harder. Parse all the permissions and compare the resulting set.
1667 $recipients1 = self::enumeratePermissions($obj1);
1668 $recipients2 = self::enumeratePermissions($obj2);
1672 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
1673 return ($recipients1 == $recipients2);
1676 // returns an array of contact-ids that are allowed to see this object
1677 private static function enumeratePermissions($obj)
1679 $allow_people = expand_acl($obj['allow_cid']);
1680 $allow_groups = Group::expand(expand_acl($obj['allow_gid']));
1681 $deny_people = expand_acl($obj['deny_cid']);
1682 $deny_groups = Group::expand(expand_acl($obj['deny_gid']));
1683 $recipients = array_unique(array_merge($allow_people, $allow_groups));
1684 $deny = array_unique(array_merge($deny_people, $deny_groups));
1685 $recipients = array_diff($recipients, $deny);
1689 public static function getFeedTags($item)
1693 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
1695 for ($x = 0; $x < $cnt; $x ++) {
1696 if ($matches[1][$x]) {
1697 $ret[$matches[2][$x]] = ['#', $matches[1][$x], $matches[2][$x]];
1702 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
1704 for ($x = 0; $x < $cnt; $x ++) {
1705 if ($matches[1][$x]) {
1706 $ret[] = ['@', $matches[1][$x], $matches[2][$x]];
1713 public static function expire($uid, $days, $network = "", $force = false)
1715 if (!$uid || ($days < 1)) {
1720 * $expire_network_only = save your own wall posts
1721 * and just expire conversations started by others
1723 $expire_network_only = PConfig::get($uid,'expire', 'network_only');
1724 $sql_extra = (intval($expire_network_only) ? " AND wall = 0 " : "");
1726 if ($network != "") {
1727 $sql_extra .= sprintf(" AND network = '%s' ", dbesc($network));
1730 * There is an index "uid_network_received" but not "uid_network_created"
1731 * This avoids the creation of another index just for one purpose.
1732 * And it doesn't really matter wether to look at "received" or "created"
1734 $range = "AND `received` < UTC_TIMESTAMP() - INTERVAL %d DAY ";
1736 $range = "AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY ";
1739 $r = q("SELECT `file`, `resource-id`, `starred`, `type`, `id` FROM `item`
1740 WHERE `uid` = %d $range
1748 if (!DBM::is_result($r)) {
1752 $expire_items = PConfig::get($uid, 'expire', 'items', 1);
1754 // Forcing expiring of items - but not notes and marked items
1756 $expire_items = true;
1759 $expire_notes = PConfig::get($uid, 'expire', 'notes', 1);
1760 $expire_starred = PConfig::get($uid, 'expire', 'starred', 1);
1761 $expire_photos = PConfig::get($uid, 'expire', 'photos', 0);
1763 logger('User '.$uid.': expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
1765 foreach ($r as $item) {
1767 // don't expire filed items
1769 if (strpos($item['file'],'[') !== false) {
1773 // Only expire posts, not photos and photo comments
1775 if ($expire_photos == 0 && strlen($item['resource-id'])) {
1777 } elseif ($expire_starred == 0 && intval($item['starred'])) {
1779 } elseif ($expire_notes == 0 && $item['type'] == 'note') {
1781 } elseif ($expire_items == 0 && $item['type'] != 'note') {
1785 self::deleteById($item['id'], PRIORITY_LOW);
1789 public static function firstPostDate($uid, $wall = false)
1791 $condition = ['uid' => $uid, 'wall' => $wall, 'deleted' => false, 'visible' => true, 'moderated' => false];
1792 $params = ['order' => ['created' => false]];
1793 $thread = dba::selectFirst('thread', ['created'], $condition, $params);
1794 if (DBM::is_result($thread)) {
1795 return substr(DateTimeFormat::local($thread['created']), 0, 10);
1801 * @brief add/remove activity to an item
1803 * Toggle activities as like,dislike,attend of an item
1805 * @param string $item_id
1806 * @param string $verb
1807 * Activity verb. One of
1808 * like, unlike, dislike, undislike, attendyes, unattendyes,
1809 * attendno, unattendno, attendmaybe, unattendmaybe
1810 * @hook 'post_local_end'
1812 * 'post_id' => ID of posted item
1814 public static function performLike($item_id, $verb)
1816 if (!local_user() && !remote_user()) {
1823 $bodyverb = L10n::t('%1$s likes %2$s\'s %3$s');
1824 $activity = ACTIVITY_LIKE;
1828 $bodyverb = L10n::t('%1$s doesn\'t like %2$s\'s %3$s');
1829 $activity = ACTIVITY_DISLIKE;
1833 $bodyverb = L10n::t('%1$s is attending %2$s\'s %3$s');
1834 $activity = ACTIVITY_ATTEND;
1838 $bodyverb = L10n::t('%1$s is not attending %2$s\'s %3$s');
1839 $activity = ACTIVITY_ATTENDNO;
1842 case 'unattendmaybe':
1843 $bodyverb = L10n::t('%1$s may attend %2$s\'s %3$s');
1844 $activity = ACTIVITY_ATTENDMAYBE;
1847 logger('like: unknown verb ' . $verb . ' for item ' . $item_id);
1851 // Enable activity toggling instead of on/off
1852 $event_verb_flag = $activity === ACTIVITY_ATTEND || $activity === ACTIVITY_ATTENDNO || $activity === ACTIVITY_ATTENDMAYBE;
1854 logger('like: verb ' . $verb . ' item ' . $item_id);
1856 $item = dba::selectFirst('item', [], ['`id` = ? OR `uri` = ?', $item_id, $item_id]);
1857 if (!DBM::is_result($item)) {
1858 logger('like: unknown item ' . $item_id);
1862 $uid = $item['uid'];
1863 if (($uid == 0) && local_user()) {
1864 $uid = local_user();
1867 if (!can_write_wall($uid)) {
1868 logger('like: unable to write on wall ' . $uid);
1872 // Retrieves the local post owner
1873 $owner_self_contact = dba::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
1874 if (!DBM::is_result($owner_self_contact)) {
1875 logger('like: unknown owner ' . $uid);
1879 // Retrieve the current logged in user's public contact
1880 $author_id = public_contact();
1882 $author_contact = dba::selectFirst('contact', [], ['id' => $author_id]);
1883 if (!DBM::is_result($author_contact)) {
1884 logger('like: unknown author ' . $author_id);
1888 // Contact-id is the uid-dependant author contact
1889 if (local_user() == $uid) {
1890 $item_contact_id = $owner_self_contact['id'];
1891 $item_contact = $owner_self_contact;
1893 $item_contact_id = Contact::getIdForURL($author_contact['url'], $uid, true);
1894 $item_contact = dba::selectFirst('contact', [], ['id' => $item_contact_id]);
1895 if (!DBM::is_result($item_contact)) {
1896 logger('like: unknown item contact ' . $item_contact_id);
1901 // Look for an existing verb row
1902 // event participation are essentially radio toggles. If you make a subsequent choice,
1903 // we need to eradicate your first choice.
1904 if ($event_verb_flag) {
1905 $verbs = "'" . dbesc(ACTIVITY_ATTEND) . "', '" . dbesc(ACTIVITY_ATTENDNO) . "', '" . dbesc(ACTIVITY_ATTENDMAYBE) . "'";
1907 $verbs = "'".dbesc($activity)."'";
1910 /// @todo This query is expected to be a performance eater due to the "OR" - it has to be changed totally
1911 $existing_like = q("SELECT `id`, `guid`, `verb` FROM `item`
1912 WHERE `verb` IN ($verbs)
1914 AND `author-id` = %d
1916 AND (`parent` = '%s' OR `parent-uri` = '%s' OR `thr-parent` = '%s')
1918 intval($author_contact['id']),
1919 intval($item['uid']),
1920 dbesc($item_id), dbesc($item_id), dbesc($item['uri'])
1923 // If it exists, mark it as deleted
1924 if (DBM::is_result($existing_like)) {
1925 $like_item = $existing_like[0];
1927 // Already voted, undo it
1928 $fields = ['deleted' => true, 'unseen' => true, 'changed' => DateTimeFormat::utcNow()];
1929 dba::update('item', $fields, ['id' => $like_item['id']]);
1931 // Clean up the Diaspora signatures for this like
1932 // Go ahead and do it even if Diaspora support is disabled. We still want to clean up
1933 // if it had been enabled in the past
1934 dba::delete('sign', ['iid' => $like_item['id']]);
1936 $like_item_id = $like_item['id'];
1937 Worker::add(PRIORITY_HIGH, "Notifier", "like", $like_item_id);
1939 if (!$event_verb_flag || $like_item['verb'] == $activity) {
1944 // Verb is "un-something", just trying to delete existing entries
1945 if (strpos($verb, 'un') === 0) {
1949 // Else or if event verb different from existing row, create a new item row
1950 $post_type = (($item['resource-id']) ? L10n::t('photo') : L10n::t('status'));
1951 if ($item['object-type'] === ACTIVITY_OBJ_EVENT) {
1952 $post_type = L10n::t('event');
1954 $objtype = $item['resource-id'] ? ACTIVITY_OBJ_IMAGE : ACTIVITY_OBJ_NOTE ;
1955 $link = xmlify('<link rel="alternate" type="text/html" href="' . System::baseUrl() . '/display/' . $owner_self_contact['nick'] . '/' . $item['id'] . '" />' . "\n") ;
1956 $body = $item['body'];
1961 <type>$objtype</type>
1963 <id>{$item['uri']}</id>
1966 <content>$body</content>
1970 $ulink = '[url=' . $author_contact['url'] . ']' . $author_contact['name'] . '[/url]';
1971 $alink = '[url=' . $item['author-link'] . ']' . $item['author-name'] . '[/url]';
1972 $plink = '[url=' . System::baseUrl() . '/display/' . $owner_self_contact['nick'] . '/' . $item['id'] . ']' . $post_type . '[/url]';
1975 'guid' => get_guid(32),
1976 'uri' => item_new_uri(self::getApp()->get_hostname(), $item['uid']),
1977 'uid' => $item['uid'],
1978 'contact-id' => $item_contact_id,
1979 'type' => 'activity',
1980 'wall' => $item['wall'],
1982 'gravity' => GRAVITY_LIKE,
1983 'parent' => $item['id'],
1984 'parent-uri' => $item['uri'],
1985 'thr-parent' => $item['uri'],
1986 'owner-id' => $item['owner-id'],
1987 'owner-name' => $item['owner-name'],
1988 'owner-link' => $item['owner-link'],
1989 'owner-avatar' => $item['owner-avatar'],
1990 'author-id' => $author_contact['id'],
1991 'author-name' => $author_contact['name'],
1992 'author-link' => $author_contact['url'],
1993 'author-avatar' => $author_contact['thumb'],
1994 'body' => sprintf($bodyverb, $ulink, $alink, $plink),
1995 'verb' => $activity,
1996 'object-type' => $objtype,
1998 'allow_cid' => $item['allow_cid'],
1999 'allow_gid' => $item['allow_gid'],
2000 'deny_cid' => $item['deny_cid'],
2001 'deny_gid' => $item['deny_gid'],
2006 $new_item_id = self::insert($new_item);
2008 // If the parent item isn't visible then set it to visible
2009 if (!$item['visible']) {
2010 self::update(['visible' => true], ['id' => $item['id']]);
2013 // Save the author information for the like in case we need to relay to Diaspora
2014 Diaspora::storeLikeSignature($item_contact, $new_item_id);
2016 $new_item['id'] = $new_item_id;
2018 Addon::callHooks('post_local_end', $new_item);
2020 Worker::add(PRIORITY_HIGH, "Notifier", "like", $new_item_id);
2025 private static function addThread($itemid, $onlyshadow = false)
2027 $fields = ['uid', 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private', 'pubmail',
2028 'moderated', 'visible', 'spam', 'starred', 'bookmark', 'contact-id',
2029 'deleted', 'origin', 'forum_mode', 'mention', 'network', 'author-id', 'owner-id'];
2030 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
2031 $item = dba::selectFirst('item', $fields, $condition);
2033 if (!DBM::is_result($item)) {
2037 $item['iid'] = $itemid;
2040 $result = dba::insert('thread', $item);
2042 logger("Add thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
2046 private static function updateThread($itemid, $setmention = false)
2048 $fields = ['uid', 'guid', 'title', 'body', 'created', 'edited', 'commented', 'received', 'changed',
2049 'wall', 'private', 'pubmail', 'moderated', 'visible', 'spam', 'starred', 'bookmark', 'contact-id',
2050 'deleted', 'origin', 'forum_mode', 'network', 'author-id', 'owner-id', 'rendered-html', 'rendered-hash'];
2051 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
2053 $item = dba::selectFirst('item', $fields, $condition);
2054 if (!DBM::is_result($item)) {
2059 $item["mention"] = 1;
2066 foreach ($item as $field => $data) {
2067 if (!in_array($field, ["guid", "title", "body", "rendered-html", "rendered-hash"])) {
2068 $fields[$field] = $data;
2072 $result = dba::update('thread', $fields, ['iid' => $itemid]);
2074 logger("Update thread for item ".$itemid." - guid ".$item["guid"]." - ".(int)$result, LOGGER_DEBUG);
2076 // Updating a shadow item entry
2077 $items = dba::selectFirst('item', ['id'], ['guid' => $item['guid'], 'uid' => 0]);
2079 if (!DBM::is_result($items)) {
2083 $fields = ['title' => $item['title'], 'body' => $item['body'],
2084 'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']];
2085 $result = dba::update('item', $fields, ['id' => $items['id']]);
2087 logger("Updating public shadow for post ".$items["id"]." - guid ".$item["guid"]." Result: ".print_r($result, true), LOGGER_DEBUG);
2090 private static function deleteThread($itemid, $itemuri = "")
2092 $item = dba::selectFirst('thread', ['uid'], ['iid' => $itemid]);
2093 if (!DBM::is_result($item)) {
2094 logger('No thread found for id '.$itemid, LOGGER_DEBUG);
2098 // Using dba::delete at this time could delete the associated item entries
2099 $result = dba::e("DELETE FROM `thread` WHERE `iid` = ?", $itemid);
2101 logger("deleteThread: Deleted thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
2103 if ($itemuri != "") {
2104 $condition = ["`uri` = ? AND NOT `deleted` AND NOT (`uid` IN (?, 0))", $itemuri, $item["uid"]];
2105 if (!dba::exists('item', $condition)) {
2106 dba::delete('item', ['uri' => $itemuri, 'uid' => 0]);
2107 logger("deleteThread: Deleted shadow for item ".$itemuri, LOGGER_DEBUG);