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', 'uri', 'uid', 'parent', 'parent-uri', 'origin',
116 'deleted', '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 (!dba::exists('item', ["`uri` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri']])) {
187 self::delete(['uri' => $item['uri'], 'uid' => 0, 'deleted' => false], $priority);
190 // If it's the parent of a comment thread, kill all the kids
191 if ($item['id'] == $item['parent']) {
192 self::delete(['parent' => $item['parent']], $priority);
195 // Is it our comment and/or our thread?
196 if ($item['origin'] || $parent['origin']) {
198 // When we delete the original post we will delete all existing copies on the server as well
199 self::delete(['uri' => $item['uri'], 'deleted' => false], $priority);
201 // send the notification upstream/downstream
202 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", "drop", intval($item['id']));
208 private static function deleteTagsFromItem($item)
210 if (($item["verb"] != ACTIVITY_TAG) || ($item["object-type"] != ACTIVITY_OBJ_TAGTERM)) {
214 $xo = XML::parseString($item["object"], false);
215 $xt = XML::parseString($item["target"], false);
217 if ($xt->type != ACTIVITY_OBJ_NOTE) {
221 $i = dba::selectFirst('item', ['id', 'contact-id', 'tag'], ['uri' => $xt->id, 'uid' => $item['uid']]);
222 if (!DBM::is_result($i)) {
226 // For tags, the owner cannot remove the tag on the author's copy of the post.
227 $owner_remove = ($item["contact-id"] == $i["contact-id"]);
228 $author_copy = $item["origin"];
230 if (($owner_remove && $author_copy) || !$owner_remove) {
234 $tags = explode(',', $i["tag"]);
237 foreach ($tags as $tag) {
238 if (trim($tag) !== trim($xo->body)) {
239 $newtags[] = trim($tag);
243 self::update(['tag' => implode(',', $newtags)], ['id' => $i["id"]]);
246 private static function guid($item, $notify)
248 $guid = notags(trim($item['guid']));
255 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
256 // We add the hash of our own host because our host is the original creator of the post.
257 $prefix_host = get_app()->get_hostname();
261 // We are only storing the post so we create a GUID from the original hostname.
262 if (!empty($item['author-link'])) {
263 $parsed = parse_url($item['author-link']);
264 if (!empty($parsed['host'])) {
265 $prefix_host = $parsed['host'];
269 if (empty($prefix_host) && !empty($item['plink'])) {
270 $parsed = parse_url($item['plink']);
271 if (!empty($parsed['host'])) {
272 $prefix_host = $parsed['host'];
276 if (empty($prefix_host) && !empty($item['uri'])) {
277 $parsed = parse_url($item['uri']);
278 if (!empty($parsed['host'])) {
279 $prefix_host = $parsed['host'];
283 // Is it in the format data@host.tld? - Used for mail contacts
284 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
285 $mailparts = explode('@', $item['author-link']);
286 $prefix_host = array_pop($mailparts);
290 if (!empty($item['plink'])) {
291 $guid = self::guidFromUri($item['plink'], $prefix_host);
292 } elseif (!empty($item['uri'])) {
293 $guid = self::guidFromUri($item['uri'], $prefix_host);
295 $guid = get_guid(32, hash('crc32', $prefix_host));
301 private static function contactId($item)
303 $contact_id = (int)$item["contact-id"];
305 if (!empty($contact_id)) {
308 logger('Missing contact-id. Called by: '.System::callstack(), LOGGER_DEBUG);
310 * First we are looking for a suitable contact that matches with the author of the post
311 * This is done only for comments
313 if ($item['parent-uri'] != $item['uri']) {
314 $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
317 // If not present then maybe the owner was found
318 if ($contact_id == 0) {
319 $contact_id = Contact::getIdForURL($item['owner-link'], $item['uid']);
322 // Still missing? Then use the "self" contact of the current user
323 if ($contact_id == 0) {
324 $self = dba::selectFirst('contact', ['id'], ['self' => true, 'uid' => $item['uid']]);
325 if (DBM::is_result($self)) {
326 $contact_id = $self["id"];
329 logger("Contact-id was missing for post ".$item['guid']." from user id ".$item['uid']." - now set to ".$contact_id, LOGGER_DEBUG);
334 public static function insert($item, $force_parent = false, $notify = false, $dontcache = false)
338 // If it is a posting where users should get notifications, then define it as wall posting
341 $item['type'] = 'wall';
343 $item['network'] = NETWORK_DFRN;
344 $item['protocol'] = PROTOCOL_DFRN;
346 $item['network'] = trim(defaults($item, 'network', NETWORK_PHANTOM));
349 $item['guid'] = self::guid($item, $notify);
350 $item['uri'] = notags(trim(defaults($item, 'uri', item_new_uri($a->get_hostname(), $item['uid'], $item['guid']))));
352 // Store conversation data
353 $item = Conversation::insert($item);
356 * If a Diaspora signature structure was passed in, pull it out of the
357 * item array and set it aside for later storage.
361 if (x($item, 'dsprsig')) {
362 $encoded_signature = $item['dsprsig'];
363 $dsprsig = json_decode(base64_decode($item['dsprsig']));
364 unset($item['dsprsig']);
367 if (!empty($item['diaspora_signed_text'])) {
368 $diaspora_signed_text = $item['diaspora_signed_text'];
369 unset($item['diaspora_signed_text']);
371 $diaspora_signed_text = '';
374 // Converting the plink
375 /// @TODO Check if this is really still needed
376 if ($item['network'] == NETWORK_OSTATUS) {
377 if (isset($item['plink'])) {
378 $item['plink'] = OStatus::convertHref($item['plink']);
379 } elseif (isset($item['uri'])) {
380 $item['plink'] = OStatus::convertHref($item['uri']);
384 if (!empty($item['thr-parent'])) {
385 $item['parent-uri'] = $item['thr-parent'];
388 if (x($item, 'gravity')) {
389 $item['gravity'] = intval($item['gravity']);
390 } elseif ($item['parent-uri'] === $item['uri']) {
391 $item['gravity'] = 0;
392 } elseif (activity_match($item['verb'],ACTIVITY_POST)) {
393 $item['gravity'] = 6;
395 $item['gravity'] = 6; // extensible catchall
398 $item['type'] = defaults($item, 'type', 'remote');
400 $uid = intval($item['uid']);
402 // check for create date and expire time
403 $expire_interval = Config::get('system', 'dbclean-expire-days', 0);
405 $user = dba::selectFirst('user', ['expire'], ['uid' => $uid]);
406 if (DBM::is_result($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
407 $expire_interval = $user['expire'];
410 if (($expire_interval > 0) && !empty($item['created'])) {
411 $expire_date = time() - ($expire_interval * 86400);
412 $created_date = strtotime($item['created']);
413 if ($created_date < $expire_date) {
414 logger('item-store: item created ('.date('c', $created_date).') before expiration time ('.date('c', $expire_date).'). ignored. ' . print_r($item,true), LOGGER_DEBUG);
420 * Do we already have this item?
421 * We have to check several networks since Friendica posts could be repeated
422 * via OStatus (maybe Diasporsa as well)
424 if (in_array($item['network'], [NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS, ""])) {
425 $condition = ["`uri` = ? AND `uid` = ? AND `network` IN (?, ?, ?)",
426 trim($item['uri']), $item['uid'],
427 NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS];
428 $existing = dba::selectFirst('item', ['id', 'network'], $condition);
429 if (DBM::is_result($existing)) {
430 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
432 logger("Item with uri ".$item['uri']." already existed for user ".$uid." with id ".$existing["id"]." target network ".$existing["network"]." - new network: ".$item['network']);
435 return $existing["id"];
439 self::addLanguageInPostopts($item);
441 $item['wall'] = intval(defaults($item, 'wall', 0));
442 $item['extid'] = trim(defaults($item, 'extid', ''));
443 $item['author-name'] = trim(defaults($item, 'author-name', ''));
444 $item['author-link'] = trim(defaults($item, 'author-link', ''));
445 $item['author-avatar'] = trim(defaults($item, 'author-avatar', ''));
446 $item['owner-name'] = trim(defaults($item, 'owner-name', ''));
447 $item['owner-link'] = trim(defaults($item, 'owner-link', ''));
448 $item['owner-avatar'] = trim(defaults($item, 'owner-avatar', ''));
449 $item['received'] = ((x($item, 'received') !== false) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
450 $item['created'] = ((x($item, 'created') !== false) ? DateTimeFormat::utc($item['created']) : $item['received']);
451 $item['edited'] = ((x($item, 'edited') !== false) ? DateTimeFormat::utc($item['edited']) : $item['created']);
452 $item['changed'] = ((x($item, 'changed') !== false) ? DateTimeFormat::utc($item['changed']) : $item['created']);
453 $item['commented'] = ((x($item, 'commented') !== false) ? DateTimeFormat::utc($item['commented']) : $item['created']);
454 $item['title'] = trim(defaults($item, 'title', ''));
455 $item['location'] = trim(defaults($item, 'location', ''));
456 $item['coord'] = trim(defaults($item, 'coord', ''));
457 $item['visible'] = ((x($item, 'visible') !== false) ? intval($item['visible']) : 1);
458 $item['deleted'] = 0;
459 $item['parent-uri'] = trim(defaults($item, 'parent-uri', $item['uri']));
460 $item['verb'] = trim(defaults($item, 'verb', ''));
461 $item['object-type'] = trim(defaults($item, 'object-type', ''));
462 $item['object'] = trim(defaults($item, 'object', ''));
463 $item['target-type'] = trim(defaults($item, 'target-type', ''));
464 $item['target'] = trim(defaults($item, 'target', ''));
465 $item['plink'] = trim(defaults($item, 'plink', ''));
466 $item['allow_cid'] = trim(defaults($item, 'allow_cid', ''));
467 $item['allow_gid'] = trim(defaults($item, 'allow_gid', ''));
468 $item['deny_cid'] = trim(defaults($item, 'deny_cid', ''));
469 $item['deny_gid'] = trim(defaults($item, 'deny_gid', ''));
470 $item['private'] = intval(defaults($item, 'private', 0));
471 $item['bookmark'] = intval(defaults($item, 'bookmark', 0));
472 $item['body'] = trim(defaults($item, 'body', ''));
473 $item['tag'] = trim(defaults($item, 'tag', ''));
474 $item['attach'] = trim(defaults($item, 'attach', ''));
475 $item['app'] = trim(defaults($item, 'app', ''));
476 $item['origin'] = intval(defaults($item, 'origin', 0));
477 $item['postopts'] = trim(defaults($item, 'postopts', ''));
478 $item['resource-id'] = trim(defaults($item, 'resource-id', ''));
479 $item['event-id'] = intval(defaults($item, 'event-id', 0));
480 $item['inform'] = trim(defaults($item, 'inform', ''));
481 $item['file'] = trim(defaults($item, 'file', ''));
483 // When there is no content then we don't post it
484 if ($item['body'].$item['title'] == '') {
488 // Items cannot be stored before they happen ...
489 if ($item['created'] > DateTimeFormat::utcNow()) {
490 $item['created'] = DateTimeFormat::utcNow();
493 // We haven't invented time travel by now.
494 if ($item['edited'] > DateTimeFormat::utcNow()) {
495 $item['edited'] = DateTimeFormat::utcNow();
498 if (($item['author-link'] == "") && ($item['owner-link'] == "")) {
499 logger("Both author-link and owner-link are empty. Called by: " . System::callstack(), LOGGER_DEBUG);
502 $item['plink'] = defaults($item, 'plink', System::baseUrl() . '/display/' . urlencode($item['guid']));
504 // The contact-id should be set before "self::insert" was called - but there seems to be issues sometimes
505 $item["contact-id"] = self::contactId($item);
507 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
508 'photo' => $item['author-avatar'], 'network' => $item['network']];
510 $item['author-id'] = defaults($item, 'author-id', Contact::getIdForURL($item["author-link"], 0, false, $default));
512 if (Contact::isBlocked($item["author-id"])) {
513 logger('Contact '.$item["author-id"].' is blocked, item '.$item["uri"].' will not be stored');
517 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
518 'photo' => $item['owner-avatar'], 'network' => $item['network']];
520 $item['owner-id'] = defaults($item, 'owner-id', Contact::getIdForURL($item["owner-link"], 0, false, $default));
522 if (Contact::isBlocked($item["owner-id"])) {
523 logger('Contact '.$item["owner-id"].' is blocked, item '.$item["uri"].' will not be stored');
527 if ($item['network'] == NETWORK_PHANTOM) {
528 logger('Missing network. Called by: '.System::callstack(), LOGGER_DEBUG);
530 $contact = Contact::getDetailsByURL($item['author-link'], $item['uid']);
531 if (!empty($contact['network'])) {
532 $item['network'] = $contact["network"];
534 $item['network'] = NETWORK_DFRN;
536 logger("Set network to " . $item["network"] . " for " . $item["uri"], LOGGER_DEBUG);
539 // Checking if there is already an item with the same guid
540 logger('Checking for an item for user '.$item['uid'].' on network '.$item['network'].' with the guid '.$item['guid'], LOGGER_DEBUG);
541 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
542 if (dba::exists('item', $condition)) {
543 logger('found item with guid '.$item['guid'].' for user '.$item['uid'].' on network '.$item['network'], LOGGER_DEBUG);
547 // Check for hashtags in the body and repair or add hashtag links
548 self::setHashtags($item);
550 $item['thr-parent'] = $item['parent-uri'];
558 if ($item['parent-uri'] === $item['uri']) {
561 $allow_cid = $item['allow_cid'];
562 $allow_gid = $item['allow_gid'];
563 $deny_cid = $item['deny_cid'];
564 $deny_gid = $item['deny_gid'];
565 $notify_type = 'wall-new';
567 // find the parent and snarf the item id and ACLs
568 // and anything else we need to inherit
570 $fields = ['uri', 'parent-uri', 'id', 'deleted',
571 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
572 'wall', 'private', 'forum_mode', 'origin'];
573 $condition = ['uri' => $item['parent-uri'], 'uid' => $item['uid']];
574 $params = ['order' => ['id' => false]];
575 $parent = dba::selectFirst('item', $fields, $condition, $params);
577 if (DBM::is_result($parent)) {
578 // is the new message multi-level threaded?
579 // even though we don't support it now, preserve the info
580 // and re-attach to the conversation parent.
582 if ($parent['uri'] != $parent['parent-uri']) {
583 $item['parent-uri'] = $parent['parent-uri'];
585 $condition = ['uri' => $item['parent-uri'],
586 'parent-uri' => $item['parent-uri'],
587 'uid' => $item['uid']];
588 $params = ['order' => ['id' => false]];
589 $toplevel_parent = dba::selectFirst('item', $fields, $condition, $params);
591 if (DBM::is_result($toplevel_parent)) {
592 $parent = $toplevel_parent;
596 $parent_id = $parent['id'];
597 $parent_deleted = $parent['deleted'];
598 $allow_cid = $parent['allow_cid'];
599 $allow_gid = $parent['allow_gid'];
600 $deny_cid = $parent['deny_cid'];
601 $deny_gid = $parent['deny_gid'];
602 $item['wall'] = $parent['wall'];
603 $notify_type = 'comment-new';
606 * If the parent is private, force privacy for the entire conversation
607 * This differs from the above settings as it subtly allows comments from
608 * email correspondents to be private even if the overall thread is not.
610 if ($parent['private']) {
611 $item['private'] = $parent['private'];
615 * Edge case. We host a public forum that was originally posted to privately.
616 * The original author commented, but as this is a comment, the permissions
617 * weren't fixed up so it will still show the comment as private unless we fix it here.
619 if ((intval($parent['forum_mode']) == 1) && $parent['private']) {
620 $item['private'] = 0;
623 // If its a post from myself then tag the thread as "mention"
624 logger("Checking if parent ".$parent_id." has to be tagged as mention for user ".$item['uid'], LOGGER_DEBUG);
625 $user = dba::selectFirst('user', ['nickname'], ['uid' => $item['uid']]);
626 if (DBM::is_result($user)) {
627 $self = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
628 logger("'myself' is ".$self." for parent ".$parent_id." checking against ".$item['author-link']." and ".$item['owner-link'], LOGGER_DEBUG);
629 if ((normalise_link($item['author-link']) == $self) || (normalise_link($item['owner-link']) == $self)) {
630 dba::update('thread', ['mention' => true], ['iid' => $parent_id]);
631 logger("tagged thread ".$parent_id." as mention for user ".$self, LOGGER_DEBUG);
636 * Allow one to see reply tweets from status.net even when
637 * we don't have or can't see the original post.
640 logger('$force_parent=true, reply converted to top-level post.');
642 $item['parent-uri'] = $item['uri'];
643 $item['gravity'] = 0;
645 logger('item parent '.$item['parent-uri'].' for '.$item['uid'].' was not found - ignoring item');
653 $condition = ["`uri` = ? AND `network` IN (?, ?) AND `uid` = ?",
654 $item['uri'], $item['network'], NETWORK_DFRN, $item['uid']];
655 if (dba::exists('item', $condition)) {
656 logger('duplicated item with the same uri found. '.print_r($item,true));
660 // On Friendica and Diaspora the GUID is unique
661 if (in_array($item['network'], [NETWORK_DFRN, NETWORK_DIASPORA])) {
662 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
663 if (dba::exists('item', $condition)) {
664 logger('duplicated item with the same guid found. '.print_r($item,true));
668 // Check for an existing post with the same content. There seems to be a problem with OStatus.
669 $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
670 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
671 if (dba::exists('item', $condition)) {
672 logger('duplicated item with the same body found. '.print_r($item,true));
677 // Is this item available in the global items (with uid=0)?
678 if ($item["uid"] == 0) {
679 $item["global"] = true;
681 // Set the global flag on all items if this was a global item entry
682 dba::update('item', ['global' => true], ['uri' => $item["uri"]]);
684 $item["global"] = dba::exists('item', ['uid' => 0, 'uri' => $item["uri"]]);
688 if (strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid)) {
691 $private = $item['private'];
694 $item["allow_cid"] = $allow_cid;
695 $item["allow_gid"] = $allow_gid;
696 $item["deny_cid"] = $deny_cid;
697 $item["deny_gid"] = $deny_gid;
698 $item["private"] = $private;
699 $item["deleted"] = $parent_deleted;
701 // Fill the cache field
702 put_item_in_cache($item);
705 Addon::callHooks('post_local', $item);
707 Addon::callHooks('post_remote', $item);
710 // This array field is used to trigger some automatic reactions
711 // It is mainly used in the "post_local" hook.
712 unset($item['api_source']);
714 if (x($item, 'cancel')) {
715 logger('post cancelled by addon.');
720 * Check for already added items.
721 * There is a timing issue here that sometimes creates double postings.
722 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
724 if ($item["uid"] == 0) {
725 if (dba::exists('item', ['uri' => trim($item['uri']), 'uid' => 0])) {
726 logger('Global item already stored. URI: '.$item['uri'].' on network '.$item['network'], LOGGER_DEBUG);
731 logger('' . print_r($item,true), LOGGER_DATA);
734 $ret = dba::insert('item', $item);
736 // When the item was successfully stored we fetch the ID of the item.
737 if (DBM::is_result($ret)) {
738 $current_post = dba::lastInsertId();
740 // This can happen - for example - if there are locking timeouts.
743 // Store the data into a spool file so that we can try again later.
745 // At first we restore the Diaspora signature that we removed above.
746 if (isset($encoded_signature)) {
747 $item['dsprsig'] = $encoded_signature;
750 // Now we store the data in the spool directory
751 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
752 $file = 'item-'.round(microtime(true) * 10000).'-'.mt_rand().'.msg';
754 $spoolpath = get_spoolpath();
755 if ($spoolpath != "") {
756 $spool = $spoolpath.'/'.$file;
757 file_put_contents($spool, json_encode($item));
758 logger("Item wasn't stored - Item was spooled into file ".$file, LOGGER_DEBUG);
763 if ($current_post == 0) {
764 // This is one of these error messages that never should occur.
765 logger("couldn't find created item - we better quit now.");
770 // How much entries have we created?
771 // We wouldn't need this query when we could use an unique index - but MySQL has length problems with them.
772 $entries = dba::count('item', ['uri' => $item['uri'], 'uid' => $item['uid'], 'network' => $item['network']]);
775 // There are duplicates. We delete our just created entry.
776 logger('Duplicated post occurred. uri = ' . $item['uri'] . ' uid = ' . $item['uid']);
778 // Yes, we could do a rollback here - but we are having many users with MyISAM.
779 dba::delete('item', ['id' => $current_post]);
782 } elseif ($entries == 0) {
783 // This really should never happen since we quit earlier if there were problems.
784 logger("Something is terribly wrong. We haven't found our created entry.");
789 logger('created item '.$current_post);
790 self::updateContact($item);
792 if (!$parent_id || ($item['parent-uri'] === $item['uri'])) {
793 $parent_id = $current_post;
797 dba::update('item', ['parent' => $parent_id], ['id' => $current_post]);
799 $item['id'] = $current_post;
800 $item['parent'] = $parent_id;
802 // update the commented timestamp on the parent
803 // Only update "commented" if it is really a comment
804 if (($item['verb'] == ACTIVITY_POST) || !Config::get("system", "like_no_comment")) {
805 dba::update('item', ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
807 dba::update('item', ['changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
812 * Friendica servers lower than 3.4.3-2 had double encoded the signature ...
813 * We can check for this condition when we decode and encode the stuff again.
815 if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) {
816 $dsprsig->signature = base64_decode($dsprsig->signature);
817 logger("Repaired double encoded signature from handle ".$dsprsig->signer, LOGGER_DEBUG);
820 dba::insert('sign', ['iid' => $current_post, 'signed_text' => $dsprsig->signed_text,
821 'signature' => $dsprsig->signature, 'signer' => $dsprsig->signer]);
824 if (!empty($diaspora_signed_text)) {
825 // Formerly we stored the signed text, the signature and the author in different fields.
826 // We now store the raw data so that we are more flexible.
827 dba::insert('sign', ['iid' => $current_post, 'signed_text' => $diaspora_signed_text]);
830 $deleted = self::tagDeliver($item['uid'], $current_post);
833 * current post can be deleted if is for a community page and no mention are
836 if (!$deleted && !$dontcache) {
837 $posted_item = dba::selectFirst('item', [], ['id' => $current_post]);
838 if (DBM::is_result($posted_item)) {
840 Addon::callHooks('post_local_end', $posted_item);
842 Addon::callHooks('post_remote_end', $posted_item);
845 logger('new item not found in DB, id ' . $current_post);
849 if ($item['parent-uri'] === $item['uri']) {
850 self::addThread($current_post);
852 self::updateThread($parent_id);
858 * Due to deadlock issues with the "term" table we are doing these steps after the commit.
859 * This is not perfect - but a workable solution until we found the reason for the problem.
861 Term::insertFromTagFieldByItemId($current_post);
862 Term::insertFromFileFieldByItemId($current_post);
864 if ($item['parent-uri'] === $item['uri']) {
865 self::addShadow($current_post);
867 self::addShadowPost($current_post);
870 check_user_notification($current_post);
873 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "Notifier", $notify_type, $current_post);
874 } elseif (!empty($parent) && $parent['origin']) {
875 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "Notifier", "comment-import", $current_post);
878 return $current_post;
882 * @brief Distributes public items to the receivers
884 * @param integer $itemid Item ID that should be added
885 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
887 public static function distribute($itemid, $signed_text = '')
889 $condition = ["`id` IN (SELECT `parent` FROM `item` WHERE `id` = ?)", $itemid];
890 $parent = dba::selectFirst('item', ['owner-id'], $condition);
891 if (!DBM::is_result($parent)) {
895 // Only distribute public items from native networks
896 $condition = ['id' => $itemid, 'uid' => 0,
897 'network' => [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""],
898 'visible' => true, 'deleted' => false, 'moderated' => false, 'private' => false];
899 $item = dba::selectFirst('item', [], ['id' => $itemid]);
900 if (!DBM::is_result($item)) {
905 unset($item['parent']);
906 unset($item['mention']);
907 unset($item['wall']);
908 unset($item['origin']);
909 unset($item['starred']);
910 unset($item['rendered-hash']);
911 unset($item['rendered-html']);
915 $condition = ["`nurl` IN (SELECT `nurl` FROM `contact` WHERE `id` = ?) AND `uid` != 0 AND NOT `blocked` AND `rel` IN (?, ?)",
916 $parent['owner-id'], CONTACT_IS_SHARING, CONTACT_IS_FRIEND];
917 $contacts = dba::select('contact', ['uid'], $condition);
918 while ($contact = dba::fetch($contacts)) {
919 $users[$contact['uid']] = $contact['uid'];
924 if ($item['uri'] != $item['parent-uri']) {
925 $parents = dba::select('item', ['uid', 'origin'], ["`uri` = ? AND `uid` != 0", $item['parent-uri']]);
926 while ($parent = dba::fetch($parents)) {
927 $users[$parent['uid']] = $parent['uid'];
928 if ($parent['origin'] && !$item['origin']) {
929 $origin_uid = $parent['uid'];
934 foreach ($users as $uid) {
935 if ($origin_uid == $uid) {
936 $item['diaspora_signed_text'] = $signed_text;
938 self::storeForUser($itemid, $item, $uid);
943 * @brief Store public items for the receivers
945 * @param integer $itemid Item ID that should be added
946 * @param array $item The item entry that will be stored
947 * @param integer $uid The user that will receive the item entry
949 private static function storeForUser($itemid, $item, $uid)
954 if ($item['uri'] == $item['parent-uri']) {
955 $item['contact-id'] = Contact::getIdForURL($item['owner-link'], $uid);
957 $item['contact-id'] = Contact::getIdForURL($item['author-link'], $uid);
960 if (empty($item['contact-id'])) {
961 $self = dba::selectFirst('contact', ['id'], ['self' => true, 'uid' => $uid]);
962 if (!DBM::is_result($self)) {
965 $item['contact-id'] = $self['id'];
968 if (in_array($item['type'], ["net-comment", "wall-comment"])) {
969 $item['type'] = 'remote-comment';
970 } elseif ($item['type'] == 'wall') {
971 $item['type'] = 'remote';
974 /// @todo Handling of "event-id"
977 if ($item['uri'] == $item['parent-uri']) {
978 $contact = dba::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
979 if (DBM::is_result($contact)) {
980 $notify = self::isRemoteSelf($contact, $item);
984 $distributed = self::insert($item, false, $notify, true);
987 logger("Distributed public item " . $itemid . " for user " . $uid . " wasn't stored", LOGGER_DEBUG);
989 logger("Distributed public item " . $itemid . " for user " . $uid . " with id " . $distributed, LOGGER_DEBUG);
994 * @brief Add a shadow entry for a given item id that is a thread starter
996 * We store every public item entry additionally with the user id "0".
997 * This is used for the community page and for the search.
998 * It is planned that in the future we will store public item entries only once.
1000 * @param integer $itemid Item ID that should be added
1002 public static function addShadow($itemid)
1004 $fields = ['uid', 'private', 'moderated', 'visible', 'deleted', 'network'];
1005 $condition = ['id' => $itemid, 'parent' => [0, $itemid]];
1006 $item = dba::selectFirst('item', $fields, $condition);
1008 if (!DBM::is_result($item)) {
1012 // is it already a copy?
1013 if (($itemid == 0) || ($item['uid'] == 0)) {
1017 // Is it a visible public post?
1018 if (!$item["visible"] || $item["deleted"] || $item["moderated"] || $item["private"]) {
1022 // is it an entry from a connector? Only add an entry for natively connected networks
1023 if (!in_array($item["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""])) {
1027 $item = dba::selectFirst('item', [], ['id' => $itemid]);
1029 if (DBM::is_result($item) && ($item["allow_cid"] == '') && ($item["allow_gid"] == '') &&
1030 ($item["deny_cid"] == '') && ($item["deny_gid"] == '')) {
1032 if (!dba::exists('item', ['uri' => $item['uri'], 'uid' => 0])) {
1033 // Preparing public shadow (removing user specific data)
1036 unset($item['parent']);
1037 unset($item['wall']);
1038 unset($item['mention']);
1039 unset($item['origin']);
1040 unset($item['starred']);
1041 unset($item['rendered-hash']);
1042 unset($item['rendered-html']);
1043 if ($item['uri'] == $item['parent-uri']) {
1044 $item['contact-id'] = Contact::getIdForURL($item['owner-link']);
1046 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
1049 if (in_array($item['type'], ["net-comment", "wall-comment"])) {
1050 $item['type'] = 'remote-comment';
1051 } elseif ($item['type'] == 'wall') {
1052 $item['type'] = 'remote';
1055 $public_shadow = self::insert($item, false, false, true);
1057 logger("Stored public shadow for thread ".$itemid." under id ".$public_shadow, LOGGER_DEBUG);
1063 * @brief Add a shadow entry for a given item id that is a comment
1065 * This function does the same like the function above - but for comments
1067 * @param integer $itemid Item ID that should be added
1069 public static function addShadowPost($itemid)
1071 $item = dba::selectFirst('item', [], ['id' => $itemid]);
1072 if (!DBM::is_result($item)) {
1076 // Is it a toplevel post?
1077 if ($item['id'] == $item['parent']) {
1078 self::addShadow($itemid);
1082 // Is this a shadow entry?
1083 if ($item['uid'] == 0)
1086 // Is there a shadow parent?
1087 if (!dba::exists('item', ['uri' => $item['parent-uri'], 'uid' => 0])) {
1091 // Is there already a shadow entry?
1092 if (dba::exists('item', ['uri' => $item['uri'], 'uid' => 0])) {
1096 // Save "origin" and "parent" state
1097 $origin = $item['origin'];
1098 $parent = $item['parent'];
1100 // Preparing public shadow (removing user specific data)
1103 unset($item['parent']);
1104 unset($item['wall']);
1105 unset($item['mention']);
1106 unset($item['origin']);
1107 unset($item['starred']);
1108 unset($item['rendered-hash']);
1109 unset($item['rendered-html']);
1110 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
1112 if (in_array($item['type'], ["net-comment", "wall-comment"])) {
1113 $item['type'] = 'remote-comment';
1114 } elseif ($item['type'] == 'wall') {
1115 $item['type'] = 'remote';
1118 $public_shadow = self::insert($item, false, false, true);
1120 logger("Stored public shadow for comment ".$item['uri']." under id ".$public_shadow, LOGGER_DEBUG);
1122 // If this was a comment to a Diaspora post we don't get our comment back.
1123 // This means that we have to distribute the comment by ourselves.
1125 if (dba::exists('item', ['id' => $parent, 'network' => NETWORK_DIASPORA])) {
1126 self::distribute($public_shadow);
1132 * Adds a "lang" specification in a "postopts" element of given $arr,
1133 * if possible and not already present.
1134 * Expects "body" element to exist in $arr.
1136 private static function addLanguageInPostopts(&$item)
1138 if (!empty($item['postopts'])) {
1139 if (strstr($item['postopts'], 'lang=')) {
1143 $postopts = $item['postopts'];
1148 $naked_body = Text\BBCode::toPlaintext($item['body'], false);
1150 $languages = (new Text_LanguageDetect())->detect($naked_body, 3);
1152 if (sizeof($languages) > 0) {
1153 if ($postopts != '') {
1154 $postopts .= '&'; // arbitrary separator, to be reviewed
1157 $postopts .= 'lang=';
1160 foreach ($languages as $language => $score) {
1161 $postopts .= $sep . $language . ";" . $score;
1164 $item['postopts'] = $postopts;
1169 * @brief Creates an unique guid out of a given uri
1171 * @param string $uri uri of an item entry
1172 * @param string $host hostname for the GUID prefix
1173 * @return string unique guid
1175 public static function guidFromUri($uri, $host)
1177 // Our regular guid routine is using this kind of prefix as well
1178 // We have to avoid that different routines could accidentally create the same value
1179 $parsed = parse_url($uri);
1181 // We use a hash of the hostname as prefix for the guid
1182 $guid_prefix = hash("crc32", $host);
1184 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
1185 unset($parsed["scheme"]);
1187 // Glue it together to be able to make a hash from it
1188 $host_id = implode("/", $parsed);
1190 // We could use any hash algorithm since it isn't a security issue
1191 $host_hash = hash("ripemd128", $host_id);
1193 return $guid_prefix.$host_hash;
1197 * @brief Set "success_update" and "last-item" to the date of the last time we heard from this contact
1199 * This can be used to filter for inactive contacts.
1200 * Only do this for public postings to avoid privacy problems, since poco data is public.
1201 * Don't set this value if it isn't from the owner (could be an author that we don't know)
1203 * @param array $arr Contains the just posted item record
1205 private static function updateContact($arr)
1207 // Unarchive the author
1208 $contact = dba::selectFirst('contact', [], ['id' => $arr["author-id"]]);
1209 if (DBM::is_result($contact)) {
1210 Contact::unmarkForArchival($contact);
1213 // Unarchive the contact if it's not our own contact
1214 $contact = dba::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
1215 if (DBM::is_result($contact)) {
1216 Contact::unmarkForArchival($contact);
1219 $update = (!$arr['private'] && (($arr["author-link"] === $arr["owner-link"]) || ($arr["parent-uri"] === $arr["uri"])));
1221 // Is it a forum? Then we don't care about the rules from above
1222 if (!$update && ($arr["network"] == NETWORK_DFRN) && ($arr["parent-uri"] === $arr["uri"])) {
1223 if (dba::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
1229 dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
1230 ['id' => $arr['contact-id']]);
1232 // Now do the same for the system wide contacts with uid=0
1233 if (!$arr['private']) {
1234 dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
1235 ['id' => $arr['owner-id']]);
1237 if ($arr['owner-id'] != $arr['author-id']) {
1238 dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
1239 ['id' => $arr['author-id']]);
1244 private static function setHashtags(&$item)
1247 $tags = get_tags($item["body"]);
1250 if (!count($tags)) {
1254 // This sorting is important when there are hashtags that are part of other hashtags
1255 // Otherwise there could be problems with hashtags like #test and #test2
1258 $URLSearchString = "^\[\]";
1260 // All hashtags should point to the home server if "local_tags" is activated
1261 if (Config::get('system', 'local_tags')) {
1262 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1263 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["body"]);
1265 $item["tag"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1266 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["tag"]);
1269 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
1270 $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1272 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
1275 $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
1277 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
1280 $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
1282 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
1285 // Repair recursive urls
1286 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1287 "#$2", $item["body"]);
1289 foreach ($tags as $tag) {
1290 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=')) {
1294 $basetag = str_replace('_',' ',substr($tag,1));
1296 $newtag = '#[url=' . System::baseUrl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1298 $item["body"] = str_replace($tag, $newtag, $item["body"]);
1300 if (!stristr($item["tag"], "/search?tag=" . $basetag . "]" . $basetag . "[/url]")) {
1301 if (strlen($item["tag"])) {
1302 $item["tag"] = ','.$item["tag"];
1304 $item["tag"] = $newtag.$item["tag"];
1308 // Convert back the masked hashtags
1309 $item["body"] = str_replace("#", "#", $item["body"]);
1312 public static function getGuidById($id)
1314 $item = dba::selectFirst('item', ['guid'], ['id' => $id]);
1315 if (DBM::is_result($item)) {
1316 return $item['guid'];
1322 public static function getIdAndNickByGuid($guid, $uid = 0)
1328 $uid == local_user();
1331 // Does the given user have this item?
1333 $item = dba::fetch_first("SELECT `item`.`id`, `user`.`nickname` FROM `item`
1334 INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
1335 WHERE `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
1336 AND `item`.`guid` = ? AND `item`.`uid` = ?", $guid, $uid);
1337 if (DBM::is_result($item)) {
1339 $nick = $item["nickname"];
1343 // Or is it anywhere on the server?
1345 $item = dba::fetch_first("SELECT `item`.`id`, `user`.`nickname` FROM `item`
1346 INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
1347 WHERE `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
1348 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1349 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1350 AND NOT `item`.`private` AND `item`.`wall`
1351 AND `item`.`guid` = ?", $guid);
1352 if (DBM::is_result($item)) {
1354 $nick = $item["nickname"];
1357 return ["nick" => $nick, "id" => $id];
1361 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
1363 * @param int $item_id
1364 * @return bool true if item was deleted, else false
1366 private static function tagDeliver($uid, $item_id)
1370 $user = dba::selectFirst('user', [], ['uid' => $uid]);
1371 if (!DBM::is_result($user)) {
1375 $community_page = (($user['page-flags'] == PAGE_COMMUNITY) ? true : false);
1376 $prvgroup = (($user['page-flags'] == PAGE_PRVGROUP) ? true : false);
1378 $item = dba::selectFirst('item', [], ['id' => $item_id]);
1379 if (!DBM::is_result($item)) {
1383 $link = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
1386 * Diaspora uses their own hardwired link URL in @-tags
1387 * instead of the one we supply with webfinger
1389 $dlink = normalise_link(System::baseUrl() . '/u/' . $user['nickname']);
1391 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
1393 foreach ($matches as $mtch) {
1394 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
1396 logger('mention found: ' . $mtch[2]);
1402 if (($community_page || $prvgroup) &&
1403 !$item['wall'] && !$item['origin'] && ($item['id'] == $item['parent'])) {
1404 // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
1406 logger("no-mention top-level post to community or private group. delete.");
1407 dba::delete('item', ['id' => $item_id]);
1413 $arr = ['item' => $item, 'user' => $user];
1415 Addon::callHooks('tagged', $arr);
1417 if (!$community_page && !$prvgroup) {
1422 * tgroup delivery - setup a second delivery chain
1423 * prevent delivery looping - only proceed
1424 * if the message originated elsewhere and is a top-level post
1426 if ($item['wall'] || $item['origin'] || ($item['id'] != $item['parent'])) {
1430 // now change this copy of the post to a forum head message and deliver to all the tgroup members
1431 $self = dba::selectFirst('contact', ['id', 'name', 'url', 'thumb'], ['uid' => $uid, 'self' => true]);
1432 if (!DBM::is_result($self)) {
1436 $owner_id = Contact::getIdForURL($self['url']);
1438 // also reset all the privacy bits to the forum default permissions
1440 $private = ($user['allow_cid'] || $user['allow_gid'] || $user['deny_cid'] || $user['deny_gid']) ? 1 : 0;
1442 $forum_mode = ($prvgroup ? 2 : 1);
1444 $fields = ['wall' => true, 'origin' => true, 'forum_mode' => $forum_mode, 'contact-id' => $self['id'],
1445 'owner-id' => $owner_id, 'owner-name' => $self['name'], 'owner-link' => $self['url'],
1446 'owner-avatar' => $self['thumb'], 'private' => $private, 'allow_cid' => $user['allow_cid'],
1447 'allow_gid' => $user['allow_gid'], 'deny_cid' => $user['deny_cid'], 'deny_gid' => $user['deny_gid']];
1448 dba::update('item', $fields, ['id' => $item_id]);
1450 self::updateThread($item_id);
1452 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', 'tgroup', $item_id);
1455 public static function isRemoteSelf($contact, &$datarray)
1459 if (!$contact['remote_self']) {
1463 // Prevent the forwarding of posts that are forwarded
1464 if ($datarray["extid"] == NETWORK_DFRN) {
1465 logger('Already forwarded', LOGGER_DEBUG);
1469 // Prevent to forward already forwarded posts
1470 if ($datarray["app"] == $a->get_hostname()) {
1471 logger('Already forwarded (second test)', LOGGER_DEBUG);
1475 // Only forward posts
1476 if ($datarray["verb"] != ACTIVITY_POST) {
1477 logger('No post', LOGGER_DEBUG);
1481 if (($contact['network'] != NETWORK_FEED) && $datarray['private']) {
1482 logger('Not public', LOGGER_DEBUG);
1486 $datarray2 = $datarray;
1487 logger('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), LOGGER_DEBUG);
1488 if ($contact['remote_self'] == 2) {
1489 $self = dba::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
1490 ['uid' => $contact['uid'], 'self' => true]);
1491 if (DBM::is_result($self)) {
1492 $datarray['contact-id'] = $self["id"];
1494 $datarray['owner-name'] = $self["name"];
1495 $datarray['owner-link'] = $self["url"];
1496 $datarray['owner-avatar'] = $self["thumb"];
1498 $datarray['author-name'] = $datarray['owner-name'];
1499 $datarray['author-link'] = $datarray['owner-link'];
1500 $datarray['author-avatar'] = $datarray['owner-avatar'];
1502 unset($datarray['created']);
1503 unset($datarray['edited']);
1505 unset($datarray['network']);
1506 unset($datarray['owner-id']);
1507 unset($datarray['author-id']);
1510 if ($contact['network'] != NETWORK_FEED) {
1511 $datarray["guid"] = get_guid(32);
1512 unset($datarray["plink"]);
1513 $datarray["uri"] = item_new_uri($a->get_hostname(), $contact['uid'], $datarray["guid"]);
1514 $datarray["parent-uri"] = $datarray["uri"];
1515 $datarray["thr-parent"] = $datarray["uri"];
1516 $datarray["extid"] = NETWORK_DFRN;
1517 $urlpart = parse_url($datarray2['author-link']);
1518 $datarray["app"] = $urlpart["host"];
1520 $datarray['private'] = 0;
1524 if ($contact['network'] != NETWORK_FEED) {
1525 // Store the original post
1526 $result = self::insert($datarray2, false, false);
1527 logger('remote-self post original item - Contact '.$contact['url'].' return '.$result.' Item '.print_r($datarray2, true), LOGGER_DEBUG);
1529 $datarray["app"] = "Feed";
1533 // Trigger automatic reactions for addons
1534 $datarray['api_source'] = true;
1536 // We have to tell the hooks who we are - this really should be improved
1537 $_SESSION["authenticated"] = true;
1538 $_SESSION["uid"] = $contact['uid'];
1547 * @param array $item
1551 public static function fixPrivatePhotos($s, $uid, $item = null, $cid = 0)
1553 if (Config::get('system', 'disable_embedded')) {
1557 logger('check for photos', LOGGER_DEBUG);
1558 $site = substr(System::baseUrl(), strpos(System::baseUrl(), '://'));
1563 $img_start = strpos($orig_body, '[img');
1564 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
1565 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
1567 while (($img_st_close !== false) && ($img_len !== false)) {
1568 $img_st_close++; // make it point to AFTER the closing bracket
1569 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
1571 logger('found photo ' . $image, LOGGER_DEBUG);
1573 if (stristr($image, $site . '/photo/')) {
1574 // Only embed locally hosted photos
1576 $i = basename($image);
1577 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
1578 $x = strpos($i, '-');
1581 $res = substr($i, $x + 1);
1582 $i = substr($i, 0, $x);
1583 $fields = ['data', 'type', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'];
1584 $photo = dba::selectFirst('photo', $fields, ['resource-id' => $i, 'scale' => $res, 'uid' => $uid]);
1585 if (DBM::is_result($photo)) {
1587 * Check to see if we should replace this photo link with an embedded image
1588 * 1. No need to do so if the photo is public
1589 * 2. If there's a contact-id provided, see if they're in the access list
1590 * for the photo. If so, embed it.
1591 * 3. Otherwise, if we have an item, see if the item permissions match the photo
1592 * permissions, regardless of order but first check to see if they're an exact
1593 * match to save some processing overhead.
1595 if (self::hasPermissions($photo)) {
1597 $recips = self::enumeratePermissions($photo);
1598 if (in_array($cid, $recips)) {
1602 if (self::samePermissions($item, $photo)) {
1608 $data = $photo['data'];
1609 $type = $photo['type'];
1611 // If a custom width and height were specified, apply before embedding
1612 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
1613 logger('scaling photo', LOGGER_DEBUG);
1615 $width = intval($match[1]);
1616 $height = intval($match[2]);
1618 $Image = new Image($data, $type);
1619 if ($Image->isValid()) {
1620 $Image->scaleDown(max($width, $height));
1621 $data = $Image->asString();
1622 $type = $Image->getType();
1626 logger('replacing photo', LOGGER_DEBUG);
1627 $image = 'data:' . $type . ';base64,' . base64_encode($data);
1628 logger('replaced: ' . $image, LOGGER_DATA);
1634 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
1635 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
1636 if ($orig_body === false) {
1640 $img_start = strpos($orig_body, '[img');
1641 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
1642 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
1645 $new_body = $new_body . $orig_body;
1650 private static function hasPermissions($obj)
1654 x($obj, 'allow_cid')
1656 x($obj, 'allow_gid')
1665 private static function samePermissions($obj1, $obj2)
1667 // first part is easy. Check that these are exactly the same.
1668 if (($obj1['allow_cid'] == $obj2['allow_cid'])
1669 && ($obj1['allow_gid'] == $obj2['allow_gid'])
1670 && ($obj1['deny_cid'] == $obj2['deny_cid'])
1671 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
1675 // This is harder. Parse all the permissions and compare the resulting set.
1676 $recipients1 = self::enumeratePermissions($obj1);
1677 $recipients2 = self::enumeratePermissions($obj2);
1681 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
1682 return ($recipients1 == $recipients2);
1685 // returns an array of contact-ids that are allowed to see this object
1686 private static function enumeratePermissions($obj)
1688 $allow_people = expand_acl($obj['allow_cid']);
1689 $allow_groups = Group::expand(expand_acl($obj['allow_gid']));
1690 $deny_people = expand_acl($obj['deny_cid']);
1691 $deny_groups = Group::expand(expand_acl($obj['deny_gid']));
1692 $recipients = array_unique(array_merge($allow_people, $allow_groups));
1693 $deny = array_unique(array_merge($deny_people, $deny_groups));
1694 $recipients = array_diff($recipients, $deny);
1698 public static function getFeedTags($item)
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[2][$x]] = ['#', $matches[1][$x], $matches[2][$x]];
1711 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
1713 for ($x = 0; $x < $cnt; $x ++) {
1714 if ($matches[1][$x]) {
1715 $ret[] = ['@', $matches[1][$x], $matches[2][$x]];
1722 public static function expire($uid, $days, $network = "", $force = false)
1724 if (!$uid || ($days < 1)) {
1729 * $expire_network_only = save your own wall posts
1730 * and just expire conversations started by others
1732 $expire_network_only = PConfig::get($uid,'expire', 'network_only');
1733 $sql_extra = (intval($expire_network_only) ? " AND wall = 0 " : "");
1735 if ($network != "") {
1736 $sql_extra .= sprintf(" AND network = '%s' ", dbesc($network));
1739 * There is an index "uid_network_received" but not "uid_network_created"
1740 * This avoids the creation of another index just for one purpose.
1741 * And it doesn't really matter wether to look at "received" or "created"
1743 $range = "AND `received` < UTC_TIMESTAMP() - INTERVAL %d DAY ";
1745 $range = "AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY ";
1748 $r = q("SELECT `file`, `resource-id`, `starred`, `type`, `id` FROM `item`
1749 WHERE `uid` = %d $range
1757 if (!DBM::is_result($r)) {
1761 $expire_items = PConfig::get($uid, 'expire', 'items', 1);
1763 // Forcing expiring of items - but not notes and marked items
1765 $expire_items = true;
1768 $expire_notes = PConfig::get($uid, 'expire', 'notes', 1);
1769 $expire_starred = PConfig::get($uid, 'expire', 'starred', 1);
1770 $expire_photos = PConfig::get($uid, 'expire', 'photos', 0);
1772 logger('User '.$uid.': expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
1774 foreach ($r as $item) {
1776 // don't expire filed items
1778 if (strpos($item['file'],'[') !== false) {
1782 // Only expire posts, not photos and photo comments
1784 if ($expire_photos == 0 && strlen($item['resource-id'])) {
1786 } elseif ($expire_starred == 0 && intval($item['starred'])) {
1788 } elseif ($expire_notes == 0 && $item['type'] == 'note') {
1790 } elseif ($expire_items == 0 && $item['type'] != 'note') {
1794 self::deleteById($item['id'], PRIORITY_LOW);
1798 public static function firstPostDate($uid, $wall = false)
1800 $condition = ['uid' => $uid, 'wall' => $wall, 'deleted' => false, 'visible' => true, 'moderated' => false];
1801 $params = ['order' => ['created' => false]];
1802 $thread = dba::selectFirst('thread', ['created'], $condition, $params);
1803 if (DBM::is_result($thread)) {
1804 return substr(DateTimeFormat::local($thread['created']), 0, 10);
1810 * @brief add/remove activity to an item
1812 * Toggle activities as like,dislike,attend of an item
1814 * @param string $item_id
1815 * @param string $verb
1816 * Activity verb. One of
1817 * like, unlike, dislike, undislike, attendyes, unattendyes,
1818 * attendno, unattendno, attendmaybe, unattendmaybe
1819 * @hook 'post_local_end'
1821 * 'post_id' => ID of posted item
1823 public static function performLike($item_id, $verb)
1825 if (!local_user() && !remote_user()) {
1832 $bodyverb = L10n::t('%1$s likes %2$s\'s %3$s');
1833 $activity = ACTIVITY_LIKE;
1837 $bodyverb = L10n::t('%1$s doesn\'t like %2$s\'s %3$s');
1838 $activity = ACTIVITY_DISLIKE;
1842 $bodyverb = L10n::t('%1$s is attending %2$s\'s %3$s');
1843 $activity = ACTIVITY_ATTEND;
1847 $bodyverb = L10n::t('%1$s is not attending %2$s\'s %3$s');
1848 $activity = ACTIVITY_ATTENDNO;
1851 case 'unattendmaybe':
1852 $bodyverb = L10n::t('%1$s may attend %2$s\'s %3$s');
1853 $activity = ACTIVITY_ATTENDMAYBE;
1856 logger('like: unknown verb ' . $verb . ' for item ' . $item_id);
1860 // Enable activity toggling instead of on/off
1861 $event_verb_flag = $activity === ACTIVITY_ATTEND || $activity === ACTIVITY_ATTENDNO || $activity === ACTIVITY_ATTENDMAYBE;
1863 logger('like: verb ' . $verb . ' item ' . $item_id);
1865 $item = dba::selectFirst('item', [], ['`id` = ? OR `uri` = ?', $item_id, $item_id]);
1866 if (!DBM::is_result($item)) {
1867 logger('like: unknown item ' . $item_id);
1871 $uid = $item['uid'];
1872 if (($uid == 0) && local_user()) {
1873 $uid = local_user();
1876 if (!can_write_wall($uid)) {
1877 logger('like: unable to write on wall ' . $uid);
1881 // Retrieves the local post owner
1882 $owner_self_contact = dba::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
1883 if (!DBM::is_result($owner_self_contact)) {
1884 logger('like: unknown owner ' . $uid);
1888 // Retrieve the current logged in user's public contact
1889 $author_id = public_contact();
1891 $author_contact = dba::selectFirst('contact', [], ['id' => $author_id]);
1892 if (!DBM::is_result($author_contact)) {
1893 logger('like: unknown author ' . $author_id);
1897 // Contact-id is the uid-dependant author contact
1898 if (local_user() == $uid) {
1899 $item_contact_id = $owner_self_contact['id'];
1900 $item_contact = $owner_self_contact;
1902 $item_contact_id = Contact::getIdForURL($author_contact['url'], $uid, true);
1903 $item_contact = dba::selectFirst('contact', [], ['id' => $item_contact_id]);
1904 if (!DBM::is_result($item_contact)) {
1905 logger('like: unknown item contact ' . $item_contact_id);
1910 // Look for an existing verb row
1911 // event participation are essentially radio toggles. If you make a subsequent choice,
1912 // we need to eradicate your first choice.
1913 if ($event_verb_flag) {
1914 $verbs = "'" . dbesc(ACTIVITY_ATTEND) . "', '" . dbesc(ACTIVITY_ATTENDNO) . "', '" . dbesc(ACTIVITY_ATTENDMAYBE) . "'";
1916 $verbs = "'".dbesc($activity)."'";
1919 /// @todo This query is expected to be a performance eater due to the "OR" - it has to be changed totally
1920 $existing_like = q("SELECT `id`, `guid`, `verb` FROM `item`
1921 WHERE `verb` IN ($verbs)
1923 AND `author-id` = %d
1925 AND (`parent` = '%s' OR `parent-uri` = '%s' OR `thr-parent` = '%s')
1927 intval($author_contact['id']),
1928 intval($item['uid']),
1929 dbesc($item_id), dbesc($item_id), dbesc($item['uri'])
1932 // If it exists, mark it as deleted
1933 if (DBM::is_result($existing_like)) {
1934 $like_item = $existing_like[0];
1936 // Already voted, undo it
1937 $fields = ['deleted' => true, 'unseen' => true, 'changed' => DateTimeFormat::utcNow()];
1938 dba::update('item', $fields, ['id' => $like_item['id']]);
1940 // Clean up the Diaspora signatures for this like
1941 // Go ahead and do it even if Diaspora support is disabled. We still want to clean up
1942 // if it had been enabled in the past
1943 dba::delete('sign', ['iid' => $like_item['id']]);
1945 $like_item_id = $like_item['id'];
1946 Worker::add(PRIORITY_HIGH, "Notifier", "like", $like_item_id);
1948 if (!$event_verb_flag || $like_item['verb'] == $activity) {
1953 // Verb is "un-something", just trying to delete existing entries
1954 if (strpos($verb, 'un') === 0) {
1958 // Else or if event verb different from existing row, create a new item row
1959 $post_type = (($item['resource-id']) ? L10n::t('photo') : L10n::t('status'));
1960 if ($item['object-type'] === ACTIVITY_OBJ_EVENT) {
1961 $post_type = L10n::t('event');
1963 $objtype = $item['resource-id'] ? ACTIVITY_OBJ_IMAGE : ACTIVITY_OBJ_NOTE ;
1964 $link = xmlify('<link rel="alternate" type="text/html" href="' . System::baseUrl() . '/display/' . $owner_self_contact['nick'] . '/' . $item['id'] . '" />' . "\n") ;
1965 $body = $item['body'];
1970 <type>$objtype</type>
1972 <id>{$item['uri']}</id>
1975 <content>$body</content>
1979 $ulink = '[url=' . $author_contact['url'] . ']' . $author_contact['name'] . '[/url]';
1980 $alink = '[url=' . $item['author-link'] . ']' . $item['author-name'] . '[/url]';
1981 $plink = '[url=' . System::baseUrl() . '/display/' . $owner_self_contact['nick'] . '/' . $item['id'] . ']' . $post_type . '[/url]';
1984 'guid' => get_guid(32),
1985 'uri' => item_new_uri(self::getApp()->get_hostname(), $item['uid']),
1986 'uid' => $item['uid'],
1987 'contact-id' => $item_contact_id,
1988 'type' => 'activity',
1989 'wall' => $item['wall'],
1991 'gravity' => GRAVITY_LIKE,
1992 'parent' => $item['id'],
1993 'parent-uri' => $item['uri'],
1994 'thr-parent' => $item['uri'],
1995 'owner-id' => $item['owner-id'],
1996 'owner-name' => $item['owner-name'],
1997 'owner-link' => $item['owner-link'],
1998 'owner-avatar' => $item['owner-avatar'],
1999 'author-id' => $author_contact['id'],
2000 'author-name' => $author_contact['name'],
2001 'author-link' => $author_contact['url'],
2002 'author-avatar' => $author_contact['thumb'],
2003 'body' => sprintf($bodyverb, $ulink, $alink, $plink),
2004 'verb' => $activity,
2005 'object-type' => $objtype,
2007 'allow_cid' => $item['allow_cid'],
2008 'allow_gid' => $item['allow_gid'],
2009 'deny_cid' => $item['deny_cid'],
2010 'deny_gid' => $item['deny_gid'],
2015 $new_item_id = self::insert($new_item);
2017 // If the parent item isn't visible then set it to visible
2018 if (!$item['visible']) {
2019 self::update(['visible' => true], ['id' => $item['id']]);
2022 // Save the author information for the like in case we need to relay to Diaspora
2023 Diaspora::storeLikeSignature($item_contact, $new_item_id);
2025 $new_item['id'] = $new_item_id;
2027 Addon::callHooks('post_local_end', $new_item);
2029 Worker::add(PRIORITY_HIGH, "Notifier", "like", $new_item_id);
2034 private static function addThread($itemid, $onlyshadow = false)
2036 $fields = ['uid', 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private', 'pubmail',
2037 'moderated', 'visible', 'spam', 'starred', 'bookmark', 'contact-id',
2038 'deleted', 'origin', 'forum_mode', 'mention', 'network', 'author-id', 'owner-id'];
2039 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
2040 $item = dba::selectFirst('item', $fields, $condition);
2042 if (!DBM::is_result($item)) {
2046 $item['iid'] = $itemid;
2049 $result = dba::insert('thread', $item);
2051 logger("Add thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
2055 private static function updateThread($itemid, $setmention = false)
2057 $fields = ['uid', 'guid', 'title', 'body', 'created', 'edited', 'commented', 'received', 'changed',
2058 'wall', 'private', 'pubmail', 'moderated', 'visible', 'spam', 'starred', 'bookmark', 'contact-id',
2059 'deleted', 'origin', 'forum_mode', 'network', 'author-id', 'owner-id', 'rendered-html', 'rendered-hash'];
2060 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
2062 $item = dba::selectFirst('item', $fields, $condition);
2063 if (!DBM::is_result($item)) {
2068 $item["mention"] = 1;
2075 foreach ($item as $field => $data) {
2076 if (!in_array($field, ["guid", "title", "body", "rendered-html", "rendered-hash"])) {
2077 $fields[$field] = $data;
2081 $result = dba::update('thread', $fields, ['iid' => $itemid]);
2083 logger("Update thread for item ".$itemid." - guid ".$item["guid"]." - ".(int)$result, LOGGER_DEBUG);
2085 // Updating a shadow item entry
2086 $items = dba::selectFirst('item', ['id'], ['guid' => $item['guid'], 'uid' => 0]);
2088 if (!DBM::is_result($items)) {
2092 $fields = ['title' => $item['title'], 'body' => $item['body'],
2093 'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']];
2094 $result = dba::update('item', $fields, ['id' => $items['id']]);
2096 logger("Updating public shadow for post ".$items["id"]." - guid ".$item["guid"]." Result: ".print_r($result, true), LOGGER_DEBUG);
2099 private static function deleteThread($itemid, $itemuri = "")
2101 $item = dba::selectFirst('thread', ['uid'], ['iid' => $itemid]);
2102 if (!DBM::is_result($item)) {
2103 logger('No thread found for id '.$itemid, LOGGER_DEBUG);
2107 // Using dba::delete at this time could delete the associated item entries
2108 $result = dba::e("DELETE FROM `thread` WHERE `iid` = ?", $itemid);
2110 logger("deleteThread: Deleted thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
2112 if ($itemuri != "") {
2113 $condition = ["`uri` = ? AND NOT `deleted` AND NOT (`uid` IN (?, 0))", $itemuri, $item["uid"]];
2114 if (!dba::exists('item', $condition)) {
2115 dba::delete('item', ['uri' => $itemuri, 'uid' => 0]);
2116 logger("deleteThread: Deleted shadow for item ".$itemuri, LOGGER_DEBUG);