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 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 // Is it our comment and/or our thread?
192 if ($item['origin'] || $parent['origin']) {
194 // When we delete the original post we will delete all existing copies on the server as well
195 self::delete(['uri' => $item['uri'], 'deleted' => false], $priority);
197 // send the notification upstream/downstream
198 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", "drop", intval($item['id']));
204 private static function deleteTagsFromItem($item)
206 if (($item["verb"] != ACTIVITY_TAG) || ($item["object-type"] != ACTIVITY_OBJ_TAGTERM)) {
210 $xo = XML::parseString($item["object"], false);
211 $xt = XML::parseString($item["target"], false);
213 if ($xt->type != ACTIVITY_OBJ_NOTE) {
217 $i = dba::selectFirst('item', ['id', 'contact-id', 'tag'], ['uri' => $xt->id, 'uid' => $item['uid']]);
218 if (!DBM::is_result($i)) {
222 // For tags, the owner cannot remove the tag on the author's copy of the post.
223 $owner_remove = ($item["contact-id"] == $i["contact-id"]);
224 $author_copy = $item["origin"];
226 if (($owner_remove && $author_copy) || !$owner_remove) {
230 $tags = explode(',', $i["tag"]);
233 foreach ($tags as $tag) {
234 if (trim($tag) !== trim($xo->body)) {
235 $newtags[] = trim($tag);
239 self::update(['tag' => implode(',', $newtags)], ['id' => $i["id"]]);
242 private static function guid($item, $notify)
244 $guid = notags(trim($item['guid']));
251 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
252 // We add the hash of our own host because our host is the original creator of the post.
253 $prefix_host = get_app()->get_hostname();
257 // We are only storing the post so we create a GUID from the original hostname.
258 if (!empty($item['author-link'])) {
259 $parsed = parse_url($item['author-link']);
260 if (!empty($parsed['host'])) {
261 $prefix_host = $parsed['host'];
265 if (empty($prefix_host) && !empty($item['plink'])) {
266 $parsed = parse_url($item['plink']);
267 if (!empty($parsed['host'])) {
268 $prefix_host = $parsed['host'];
272 if (empty($prefix_host) && !empty($item['uri'])) {
273 $parsed = parse_url($item['uri']);
274 if (!empty($parsed['host'])) {
275 $prefix_host = $parsed['host'];
279 // Is it in the format data@host.tld? - Used for mail contacts
280 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
281 $mailparts = explode('@', $item['author-link']);
282 $prefix_host = array_pop($mailparts);
286 if (!empty($item['plink'])) {
287 $guid = self::guidFromUri($item['plink'], $prefix_host);
288 } elseif (!empty($item['uri'])) {
289 $guid = self::guidFromUri($item['uri'], $prefix_host);
291 $guid = get_guid(32, hash('crc32', $prefix_host));
297 private static function contactId($item)
299 $contact_id = (int)$item["contact-id"];
301 if (!empty($contact_id)) {
304 logger('Missing contact-id. Called by: '.System::callstack(), LOGGER_DEBUG);
306 * First we are looking for a suitable contact that matches with the author of the post
307 * This is done only for comments
309 if ($item['parent-uri'] != $item['uri']) {
310 $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
313 // If not present then maybe the owner was found
314 if ($contact_id == 0) {
315 $contact_id = Contact::getIdForURL($item['owner-link'], $item['uid']);
318 // Still missing? Then use the "self" contact of the current user
319 if ($contact_id == 0) {
320 $self = dba::selectFirst('contact', ['id'], ['self' => true, 'uid' => $item['uid']]);
321 if (DBM::is_result($self)) {
322 $contact_id = $self["id"];
325 logger("Contact-id was missing for post ".$item['guid']." from user id ".$item['uid']." - now set to ".$contact_id, LOGGER_DEBUG);
330 public static function insert($item, $force_parent = false, $notify = false, $dontcache = false)
334 // If it is a posting where users should get notifications, then define it as wall posting
337 $item['type'] = 'wall';
339 $item['network'] = NETWORK_DFRN;
340 $item['protocol'] = PROTOCOL_DFRN;
342 $item['network'] = trim(defaults($item, 'network', NETWORK_PHANTOM));
345 $item['guid'] = self::guid($item, $notify);
346 $item['uri'] = notags(trim(defaults($item, 'uri', item_new_uri($a->get_hostname(), $item['uid'], $item['guid']))));
348 // Store conversation data
349 $item = Conversation::insert($item);
352 * If a Diaspora signature structure was passed in, pull it out of the
353 * item array and set it aside for later storage.
357 if (x($item, 'dsprsig')) {
358 $encoded_signature = $item['dsprsig'];
359 $dsprsig = json_decode(base64_decode($item['dsprsig']));
360 unset($item['dsprsig']);
363 if (!empty($item['diaspora_signed_text'])) {
364 $diaspora_signed_text = $item['diaspora_signed_text'];
365 unset($item['diaspora_signed_text']);
367 $diaspora_signed_text = '';
370 // Converting the plink
371 /// @TODO Check if this is really still needed
372 if ($item['network'] == NETWORK_OSTATUS) {
373 if (isset($item['plink'])) {
374 $item['plink'] = OStatus::convertHref($item['plink']);
375 } elseif (isset($item['uri'])) {
376 $item['plink'] = OStatus::convertHref($item['uri']);
380 if (!empty($item['thr-parent'])) {
381 $item['parent-uri'] = $item['thr-parent'];
384 if (x($item, 'gravity')) {
385 $item['gravity'] = intval($item['gravity']);
386 } elseif ($item['parent-uri'] === $item['uri']) {
387 $item['gravity'] = 0;
388 } elseif (activity_match($item['verb'],ACTIVITY_POST)) {
389 $item['gravity'] = 6;
391 $item['gravity'] = 6; // extensible catchall
394 $item['type'] = defaults($item, 'type', 'remote');
396 $uid = intval($item['uid']);
398 // check for create date and expire time
399 $expire_interval = Config::get('system', 'dbclean-expire-days', 0);
401 $user = dba::selectFirst('user', ['expire'], ['uid' => $uid]);
402 if (DBM::is_result($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
403 $expire_interval = $user['expire'];
406 if (($expire_interval > 0) && !empty($item['created'])) {
407 $expire_date = time() - ($expire_interval * 86400);
408 $created_date = strtotime($item['created']);
409 if ($created_date < $expire_date) {
410 logger('item-store: item created ('.date('c', $created_date).') before expiration time ('.date('c', $expire_date).'). ignored. ' . print_r($item,true), LOGGER_DEBUG);
416 * Do we already have this item?
417 * We have to check several networks since Friendica posts could be repeated
418 * via OStatus (maybe Diasporsa as well)
420 if (in_array($item['network'], [NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS, ""])) {
421 $condition = ["`uri` = ? AND `uid` = ? AND `network` IN (?, ?, ?)",
422 trim($item['uri']), $item['uid'],
423 NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS];
424 $existing = dba::selectFirst('item', ['id', 'network'], $condition);
425 if (DBM::is_result($existing)) {
426 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
428 logger("Item with uri ".$item['uri']." already existed for user ".$uid." with id ".$existing["id"]." target network ".$existing["network"]." - new network: ".$item['network']);
431 return $existing["id"];
435 self::addLanguageInPostopts($item);
437 $item['wall'] = intval(defaults($item, 'wall', 0));
438 $item['extid'] = trim(defaults($item, 'extid', ''));
439 $item['author-name'] = trim(defaults($item, 'author-name', ''));
440 $item['author-link'] = trim(defaults($item, 'author-link', ''));
441 $item['author-avatar'] = trim(defaults($item, 'author-avatar', ''));
442 $item['owner-name'] = trim(defaults($item, 'owner-name', ''));
443 $item['owner-link'] = trim(defaults($item, 'owner-link', ''));
444 $item['owner-avatar'] = trim(defaults($item, 'owner-avatar', ''));
445 $item['received'] = ((x($item, 'received') !== false) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
446 $item['created'] = ((x($item, 'created') !== false) ? DateTimeFormat::utc($item['created']) : $item['received']);
447 $item['edited'] = ((x($item, 'edited') !== false) ? DateTimeFormat::utc($item['edited']) : $item['created']);
448 $item['changed'] = ((x($item, 'changed') !== false) ? DateTimeFormat::utc($item['changed']) : $item['created']);
449 $item['commented'] = ((x($item, 'commented') !== false) ? DateTimeFormat::utc($item['commented']) : $item['created']);
450 $item['title'] = trim(defaults($item, 'title', ''));
451 $item['location'] = trim(defaults($item, 'location', ''));
452 $item['coord'] = trim(defaults($item, 'coord', ''));
453 $item['visible'] = ((x($item, 'visible') !== false) ? intval($item['visible']) : 1);
454 $item['deleted'] = 0;
455 $item['parent-uri'] = trim(defaults($item, 'parent-uri', $item['uri']));
456 $item['verb'] = trim(defaults($item, 'verb', ''));
457 $item['object-type'] = trim(defaults($item, 'object-type', ''));
458 $item['object'] = trim(defaults($item, 'object', ''));
459 $item['target-type'] = trim(defaults($item, 'target-type', ''));
460 $item['target'] = trim(defaults($item, 'target', ''));
461 $item['plink'] = trim(defaults($item, 'plink', ''));
462 $item['allow_cid'] = trim(defaults($item, 'allow_cid', ''));
463 $item['allow_gid'] = trim(defaults($item, 'allow_gid', ''));
464 $item['deny_cid'] = trim(defaults($item, 'deny_cid', ''));
465 $item['deny_gid'] = trim(defaults($item, 'deny_gid', ''));
466 $item['private'] = intval(defaults($item, 'private', 0));
467 $item['bookmark'] = intval(defaults($item, 'bookmark', 0));
468 $item['body'] = trim(defaults($item, 'body', ''));
469 $item['tag'] = trim(defaults($item, 'tag', ''));
470 $item['attach'] = trim(defaults($item, 'attach', ''));
471 $item['app'] = trim(defaults($item, 'app', ''));
472 $item['origin'] = intval(defaults($item, 'origin', 0));
473 $item['postopts'] = trim(defaults($item, 'postopts', ''));
474 $item['resource-id'] = trim(defaults($item, 'resource-id', ''));
475 $item['event-id'] = intval(defaults($item, 'event-id', 0));
476 $item['inform'] = trim(defaults($item, 'inform', ''));
477 $item['file'] = trim(defaults($item, 'file', ''));
479 // When there is no content then we don't post it
480 if ($item['body'].$item['title'] == '') {
484 // Items cannot be stored before they happen ...
485 if ($item['created'] > DateTimeFormat::utcNow()) {
486 $item['created'] = DateTimeFormat::utcNow();
489 // We haven't invented time travel by now.
490 if ($item['edited'] > DateTimeFormat::utcNow()) {
491 $item['edited'] = DateTimeFormat::utcNow();
494 if (($item['author-link'] == "") && ($item['owner-link'] == "")) {
495 logger("Both author-link and owner-link are empty. Called by: " . System::callstack(), LOGGER_DEBUG);
498 $item['plink'] = defaults($item, 'plink', System::baseUrl() . '/display/' . urlencode($item['guid']));
500 // The contact-id should be set before "self::insert" was called - but there seems to be issues sometimes
501 $item["contact-id"] = self::contactId($item);
503 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
504 'photo' => $item['author-avatar'], 'network' => $item['network']];
506 $item['author-id'] = defaults($item, 'author-id', Contact::getIdForURL($item["author-link"], 0, false, $default));
508 if (Contact::isBlocked($item["author-id"])) {
509 logger('Contact '.$item["author-id"].' is blocked, item '.$item["uri"].' will not be stored');
513 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
514 'photo' => $item['owner-avatar'], 'network' => $item['network']];
516 $item['owner-id'] = defaults($item, 'owner-id', Contact::getIdForURL($item["owner-link"], 0, false, $default));
518 if (Contact::isBlocked($item["owner-id"])) {
519 logger('Contact '.$item["owner-id"].' is blocked, item '.$item["uri"].' will not be stored');
523 if ($item['network'] == NETWORK_PHANTOM) {
524 logger('Missing network. Called by: '.System::callstack(), LOGGER_DEBUG);
526 $contact = Contact::getDetailsByURL($item['author-link'], $item['uid']);
527 if (!empty($contact['network'])) {
528 $item['network'] = $contact["network"];
530 $item['network'] = NETWORK_DFRN;
532 logger("Set network to " . $item["network"] . " for " . $item["uri"], LOGGER_DEBUG);
535 // Checking if there is already an item with the same guid
536 logger('Checking for an item for user '.$item['uid'].' on network '.$item['network'].' with the guid '.$item['guid'], LOGGER_DEBUG);
537 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
538 if (dba::exists('item', $condition)) {
539 logger('found item with guid '.$item['guid'].' for user '.$item['uid'].' on network '.$item['network'], LOGGER_DEBUG);
543 // Check for hashtags in the body and repair or add hashtag links
544 self::setHashtags($item);
546 $item['thr-parent'] = $item['parent-uri'];
554 if ($item['parent-uri'] === $item['uri']) {
557 $allow_cid = $item['allow_cid'];
558 $allow_gid = $item['allow_gid'];
559 $deny_cid = $item['deny_cid'];
560 $deny_gid = $item['deny_gid'];
561 $notify_type = 'wall-new';
563 // find the parent and snarf the item id and ACLs
564 // and anything else we need to inherit
566 $fields = ['uri', 'parent-uri', 'id', 'deleted',
567 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
568 'wall', 'private', 'forum_mode', 'origin'];
569 $condition = ['uri' => $item['parent-uri'], 'uid' => $item['uid']];
570 $params = ['order' => ['id' => false]];
571 $parent = dba::selectFirst('item', $fields, $condition, $params);
573 if (DBM::is_result($parent)) {
574 // is the new message multi-level threaded?
575 // even though we don't support it now, preserve the info
576 // and re-attach to the conversation parent.
578 if ($parent['uri'] != $parent['parent-uri']) {
579 $item['parent-uri'] = $parent['parent-uri'];
581 $condition = ['uri' => $item['parent-uri'],
582 'parent-uri' => $item['parent-uri'],
583 'uid' => $item['uid']];
584 $params = ['order' => ['id' => false]];
585 $toplevel_parent = dba::selectFirst('item', $fields, $condition, $params);
587 if (DBM::is_result($toplevel_parent)) {
588 $parent = $toplevel_parent;
592 $parent_id = $parent['id'];
593 $parent_deleted = $parent['deleted'];
594 $allow_cid = $parent['allow_cid'];
595 $allow_gid = $parent['allow_gid'];
596 $deny_cid = $parent['deny_cid'];
597 $deny_gid = $parent['deny_gid'];
598 $item['wall'] = $parent['wall'];
599 $notify_type = 'comment-new';
602 * If the parent is private, force privacy for the entire conversation
603 * This differs from the above settings as it subtly allows comments from
604 * email correspondents to be private even if the overall thread is not.
606 if ($parent['private']) {
607 $item['private'] = $parent['private'];
611 * Edge case. We host a public forum that was originally posted to privately.
612 * The original author commented, but as this is a comment, the permissions
613 * weren't fixed up so it will still show the comment as private unless we fix it here.
615 if ((intval($parent['forum_mode']) == 1) && $parent['private']) {
616 $item['private'] = 0;
619 // If its a post from myself then tag the thread as "mention"
620 logger("Checking if parent ".$parent_id." has to be tagged as mention for user ".$item['uid'], LOGGER_DEBUG);
621 $user = dba::selectFirst('user', ['nickname'], ['uid' => $item['uid']]);
622 if (DBM::is_result($user)) {
623 $self = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
624 logger("'myself' is ".$self." for parent ".$parent_id." checking against ".$item['author-link']." and ".$item['owner-link'], LOGGER_DEBUG);
625 if ((normalise_link($item['author-link']) == $self) || (normalise_link($item['owner-link']) == $self)) {
626 dba::update('thread', ['mention' => true], ['iid' => $parent_id]);
627 logger("tagged thread ".$parent_id." as mention for user ".$self, LOGGER_DEBUG);
632 * Allow one to see reply tweets from status.net even when
633 * we don't have or can't see the original post.
636 logger('$force_parent=true, reply converted to top-level post.');
638 $item['parent-uri'] = $item['uri'];
639 $item['gravity'] = 0;
641 logger('item parent '.$item['parent-uri'].' for '.$item['uid'].' was not found - ignoring item');
649 $condition = ["`uri` = ? AND `network` IN (?, ?) AND `uid` = ?",
650 $item['uri'], $item['network'], NETWORK_DFRN, $item['uid']];
651 if (dba::exists('item', $condition)) {
652 logger('duplicated item with the same uri found. '.print_r($item,true));
656 // On Friendica and Diaspora the GUID is unique
657 if (in_array($item['network'], [NETWORK_DFRN, NETWORK_DIASPORA])) {
658 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
659 if (dba::exists('item', $condition)) {
660 logger('duplicated item with the same guid found. '.print_r($item,true));
664 // Check for an existing post with the same content. There seems to be a problem with OStatus.
665 $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
666 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
667 if (dba::exists('item', $condition)) {
668 logger('duplicated item with the same body found. '.print_r($item,true));
673 // Is this item available in the global items (with uid=0)?
674 if ($item["uid"] == 0) {
675 $item["global"] = true;
677 // Set the global flag on all items if this was a global item entry
678 dba::update('item', ['global' => true], ['uri' => $item["uri"]]);
680 $item["global"] = dba::exists('item', ['uid' => 0, 'uri' => $item["uri"]]);
684 if (strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid)) {
687 $private = $item['private'];
690 $item["allow_cid"] = $allow_cid;
691 $item["allow_gid"] = $allow_gid;
692 $item["deny_cid"] = $deny_cid;
693 $item["deny_gid"] = $deny_gid;
694 $item["private"] = $private;
695 $item["deleted"] = $parent_deleted;
697 // Fill the cache field
698 put_item_in_cache($item);
701 Addon::callHooks('post_local', $item);
703 Addon::callHooks('post_remote', $item);
706 // This array field is used to trigger some automatic reactions
707 // It is mainly used in the "post_local" hook.
708 unset($item['api_source']);
710 if (x($item, 'cancel')) {
711 logger('post cancelled by addon.');
716 * Check for already added items.
717 * There is a timing issue here that sometimes creates double postings.
718 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
720 if ($item["uid"] == 0) {
721 if (dba::exists('item', ['uri' => trim($item['uri']), 'uid' => 0])) {
722 logger('Global item already stored. URI: '.$item['uri'].' on network '.$item['network'], LOGGER_DEBUG);
727 logger('' . print_r($item,true), LOGGER_DATA);
730 $ret = dba::insert('item', $item);
732 // When the item was successfully stored we fetch the ID of the item.
733 if (DBM::is_result($ret)) {
734 $current_post = dba::lastInsertId();
736 // This can happen - for example - if there are locking timeouts.
739 // Store the data into a spool file so that we can try again later.
741 // At first we restore the Diaspora signature that we removed above.
742 if (isset($encoded_signature)) {
743 $item['dsprsig'] = $encoded_signature;
746 // Now we store the data in the spool directory
747 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
748 $file = 'item-'.round(microtime(true) * 10000).'-'.mt_rand().'.msg';
750 $spoolpath = get_spoolpath();
751 if ($spoolpath != "") {
752 $spool = $spoolpath.'/'.$file;
753 file_put_contents($spool, json_encode($item));
754 logger("Item wasn't stored - Item was spooled into file ".$file, LOGGER_DEBUG);
759 if ($current_post == 0) {
760 // This is one of these error messages that never should occur.
761 logger("couldn't find created item - we better quit now.");
766 // How much entries have we created?
767 // We wouldn't need this query when we could use an unique index - but MySQL has length problems with them.
768 $entries = dba::count('item', ['uri' => $item['uri'], 'uid' => $item['uid'], 'network' => $item['network']]);
771 // There are duplicates. We delete our just created entry.
772 logger('Duplicated post occurred. uri = ' . $item['uri'] . ' uid = ' . $item['uid']);
774 // Yes, we could do a rollback here - but we are having many users with MyISAM.
775 dba::delete('item', ['id' => $current_post]);
778 } elseif ($entries == 0) {
779 // This really should never happen since we quit earlier if there were problems.
780 logger("Something is terribly wrong. We haven't found our created entry.");
785 logger('created item '.$current_post);
786 self::updateContact($item);
788 if (!$parent_id || ($item['parent-uri'] === $item['uri'])) {
789 $parent_id = $current_post;
793 dba::update('item', ['parent' => $parent_id], ['id' => $current_post]);
795 $item['id'] = $current_post;
796 $item['parent'] = $parent_id;
798 // update the commented timestamp on the parent
799 // Only update "commented" if it is really a comment
800 if (($item['verb'] == ACTIVITY_POST) || !Config::get("system", "like_no_comment")) {
801 dba::update('item', ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
803 dba::update('item', ['changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
808 * Friendica servers lower than 3.4.3-2 had double encoded the signature ...
809 * We can check for this condition when we decode and encode the stuff again.
811 if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) {
812 $dsprsig->signature = base64_decode($dsprsig->signature);
813 logger("Repaired double encoded signature from handle ".$dsprsig->signer, LOGGER_DEBUG);
816 dba::insert('sign', ['iid' => $current_post, 'signed_text' => $dsprsig->signed_text,
817 'signature' => $dsprsig->signature, 'signer' => $dsprsig->signer]);
820 if (!empty($diaspora_signed_text)) {
821 // Formerly we stored the signed text, the signature and the author in different fields.
822 // We now store the raw data so that we are more flexible.
823 dba::insert('sign', ['iid' => $current_post, 'signed_text' => $diaspora_signed_text]);
826 $deleted = self::tagDeliver($item['uid'], $current_post);
829 * current post can be deleted if is for a community page and no mention are
832 if (!$deleted && !$dontcache) {
833 $posted_item = dba::selectFirst('item', [], ['id' => $current_post]);
834 if (DBM::is_result($posted_item)) {
836 Addon::callHooks('post_local_end', $posted_item);
838 Addon::callHooks('post_remote_end', $posted_item);
841 logger('new item not found in DB, id ' . $current_post);
845 if ($item['parent-uri'] === $item['uri']) {
846 self::addThread($current_post);
848 self::updateThread($parent_id);
854 * Due to deadlock issues with the "term" table we are doing these steps after the commit.
855 * This is not perfect - but a workable solution until we found the reason for the problem.
857 Term::insertFromTagFieldByItemId($current_post);
858 Term::insertFromFileFieldByItemId($current_post);
860 if ($item['parent-uri'] === $item['uri']) {
861 self::addShadow($current_post);
863 self::addShadowPost($current_post);
866 check_user_notification($current_post);
869 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "Notifier", $notify_type, $current_post);
870 } elseif (!empty($parent) && $parent['origin']) {
871 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "Notifier", "comment-import", $current_post);
874 return $current_post;
878 * @brief Distributes public items to the receivers
880 * @param integer $itemid Item ID that should be added
881 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
883 public static function distribute($itemid, $signed_text = '')
885 $condition = ["`id` IN (SELECT `parent` FROM `item` WHERE `id` = ?)", $itemid];
886 $parent = dba::selectFirst('item', ['owner-id'], $condition);
887 if (!DBM::is_result($parent)) {
891 // Only distribute public items from native networks
892 $condition = ['id' => $itemid, 'uid' => 0,
893 'network' => [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""],
894 'visible' => true, 'deleted' => false, 'moderated' => false, 'private' => false];
895 $item = dba::selectFirst('item', [], ['id' => $itemid]);
896 if (!DBM::is_result($item)) {
901 unset($item['parent']);
902 unset($item['mention']);
903 unset($item['wall']);
904 unset($item['origin']);
905 unset($item['starred']);
906 unset($item['rendered-hash']);
907 unset($item['rendered-html']);
911 $condition = ["`nurl` IN (SELECT `nurl` FROM `contact` WHERE `id` = ?) AND `uid` != 0 AND NOT `blocked` AND `rel` IN (?, ?)",
912 $parent['owner-id'], CONTACT_IS_SHARING, CONTACT_IS_FRIEND];
913 $contacts = dba::select('contact', ['uid'], $condition);
914 while ($contact = dba::fetch($contacts)) {
915 $users[$contact['uid']] = $contact['uid'];
920 if ($item['uri'] != $item['parent-uri']) {
921 $parents = dba::select('item', ['uid', 'origin'], ["`uri` = ? AND `uid` != 0", $item['parent-uri']]);
922 while ($parent = dba::fetch($parents)) {
923 $users[$parent['uid']] = $parent['uid'];
924 if ($parent['origin'] && !$item['origin']) {
925 $origin_uid = $parent['uid'];
930 foreach ($users as $uid) {
931 if ($origin_uid == $uid) {
932 $item['diaspora_signed_text'] = $signed_text;
934 self::storeForUser($itemid, $item, $uid);
939 * @brief Store public items for the receivers
941 * @param integer $itemid Item ID that should be added
942 * @param array $item The item entry that will be stored
943 * @param integer $uid The user that will receive the item entry
945 private static function storeForUser($itemid, $item, $uid)
950 if ($item['uri'] == $item['parent-uri']) {
951 $item['contact-id'] = Contact::getIdForURL($item['owner-link'], $uid);
953 $item['contact-id'] = Contact::getIdForURL($item['author-link'], $uid);
956 if (empty($item['contact-id'])) {
957 $self = dba::selectFirst('contact', ['id'], ['self' => true, 'uid' => $uid]);
958 if (!DBM::is_result($self)) {
961 $item['contact-id'] = $self['id'];
964 if (in_array($item['type'], ["net-comment", "wall-comment"])) {
965 $item['type'] = 'remote-comment';
966 } elseif ($item['type'] == 'wall') {
967 $item['type'] = 'remote';
970 /// @todo Handling of "event-id"
973 if ($item['uri'] == $item['parent-uri']) {
974 $contact = dba::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
975 if (DBM::is_result($contact)) {
976 $notify = self::isRemoteSelf($contact, $item);
980 $distributed = self::insert($item, false, $notify, true);
983 logger("Distributed public item " . $itemid . " for user " . $uid . " wasn't stored", LOGGER_DEBUG);
985 logger("Distributed public item " . $itemid . " for user " . $uid . " with id " . $distributed, LOGGER_DEBUG);
990 * @brief Add a shadow entry for a given item id that is a thread starter
992 * We store every public item entry additionally with the user id "0".
993 * This is used for the community page and for the search.
994 * It is planned that in the future we will store public item entries only once.
996 * @param integer $itemid Item ID that should be added
998 public static function addShadow($itemid)
1000 $fields = ['uid', 'private', 'moderated', 'visible', 'deleted', 'network'];
1001 $condition = ['id' => $itemid, 'parent' => [0, $itemid]];
1002 $item = dba::selectFirst('item', $fields, $condition);
1004 if (!DBM::is_result($item)) {
1008 // is it already a copy?
1009 if (($itemid == 0) || ($item['uid'] == 0)) {
1013 // Is it a visible public post?
1014 if (!$item["visible"] || $item["deleted"] || $item["moderated"] || $item["private"]) {
1018 // is it an entry from a connector? Only add an entry for natively connected networks
1019 if (!in_array($item["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""])) {
1023 $item = dba::selectFirst('item', [], ['id' => $itemid]);
1025 if (DBM::is_result($item) && ($item["allow_cid"] == '') && ($item["allow_gid"] == '') &&
1026 ($item["deny_cid"] == '') && ($item["deny_gid"] == '')) {
1028 if (!dba::exists('item', ['uri' => $item['uri'], 'uid' => 0])) {
1029 // Preparing public shadow (removing user specific data)
1032 unset($item['parent']);
1033 unset($item['wall']);
1034 unset($item['mention']);
1035 unset($item['origin']);
1036 unset($item['starred']);
1037 unset($item['rendered-hash']);
1038 unset($item['rendered-html']);
1039 if ($item['uri'] == $item['parent-uri']) {
1040 $item['contact-id'] = Contact::getIdForURL($item['owner-link']);
1042 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
1045 if (in_array($item['type'], ["net-comment", "wall-comment"])) {
1046 $item['type'] = 'remote-comment';
1047 } elseif ($item['type'] == 'wall') {
1048 $item['type'] = 'remote';
1051 $public_shadow = self::insert($item, false, false, true);
1053 logger("Stored public shadow for thread ".$itemid." under id ".$public_shadow, LOGGER_DEBUG);
1059 * @brief Add a shadow entry for a given item id that is a comment
1061 * This function does the same like the function above - but for comments
1063 * @param integer $itemid Item ID that should be added
1065 public static function addShadowPost($itemid)
1067 $item = dba::selectFirst('item', [], ['id' => $itemid]);
1068 if (!DBM::is_result($item)) {
1072 // Is it a toplevel post?
1073 if ($item['id'] == $item['parent']) {
1074 self::addShadow($itemid);
1078 // Is this a shadow entry?
1079 if ($item['uid'] == 0)
1082 // Is there a shadow parent?
1083 if (!dba::exists('item', ['uri' => $item['parent-uri'], 'uid' => 0])) {
1087 // Is there already a shadow entry?
1088 if (dba::exists('item', ['uri' => $item['uri'], 'uid' => 0])) {
1092 // Save "origin" and "parent" state
1093 $origin = $item['origin'];
1094 $parent = $item['parent'];
1096 // Preparing public shadow (removing user specific data)
1099 unset($item['parent']);
1100 unset($item['wall']);
1101 unset($item['mention']);
1102 unset($item['origin']);
1103 unset($item['starred']);
1104 unset($item['rendered-hash']);
1105 unset($item['rendered-html']);
1106 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
1108 if (in_array($item['type'], ["net-comment", "wall-comment"])) {
1109 $item['type'] = 'remote-comment';
1110 } elseif ($item['type'] == 'wall') {
1111 $item['type'] = 'remote';
1114 $public_shadow = self::insert($item, false, false, true);
1116 logger("Stored public shadow for comment ".$item['uri']." under id ".$public_shadow, LOGGER_DEBUG);
1118 // If this was a comment to a Diaspora post we don't get our comment back.
1119 // This means that we have to distribute the comment by ourselves.
1121 if (dba::exists('item', ['id' => $parent, 'network' => NETWORK_DIASPORA])) {
1122 self::distribute($public_shadow);
1128 * Adds a "lang" specification in a "postopts" element of given $arr,
1129 * if possible and not already present.
1130 * Expects "body" element to exist in $arr.
1132 private static function addLanguageInPostopts(&$item)
1134 if (!empty($item['postopts'])) {
1135 if (strstr($item['postopts'], 'lang=')) {
1139 $postopts = $item['postopts'];
1144 $naked_body = Text\BBCode::toPlaintext($item['body'], false);
1146 $languages = (new Text_LanguageDetect())->detect($naked_body, 3);
1148 if (sizeof($languages) > 0) {
1149 if ($postopts != '') {
1150 $postopts .= '&'; // arbitrary separator, to be reviewed
1153 $postopts .= 'lang=';
1156 foreach ($languages as $language => $score) {
1157 $postopts .= $sep . $language . ";" . $score;
1160 $item['postopts'] = $postopts;
1165 * @brief Creates an unique guid out of a given uri
1167 * @param string $uri uri of an item entry
1168 * @param string $host hostname for the GUID prefix
1169 * @return string unique guid
1171 public static function guidFromUri($uri, $host)
1173 // Our regular guid routine is using this kind of prefix as well
1174 // We have to avoid that different routines could accidentally create the same value
1175 $parsed = parse_url($uri);
1177 // We use a hash of the hostname as prefix for the guid
1178 $guid_prefix = hash("crc32", $host);
1180 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
1181 unset($parsed["scheme"]);
1183 // Glue it together to be able to make a hash from it
1184 $host_id = implode("/", $parsed);
1186 // We could use any hash algorithm since it isn't a security issue
1187 $host_hash = hash("ripemd128", $host_id);
1189 return $guid_prefix.$host_hash;
1193 * @brief Set "success_update" and "last-item" to the date of the last time we heard from this contact
1195 * This can be used to filter for inactive contacts.
1196 * Only do this for public postings to avoid privacy problems, since poco data is public.
1197 * Don't set this value if it isn't from the owner (could be an author that we don't know)
1199 * @param array $arr Contains the just posted item record
1201 private static function updateContact($arr)
1203 // Unarchive the author
1204 $contact = dba::selectFirst('contact', [], ['id' => $arr["author-id"]]);
1205 if (DBM::is_result($contact)) {
1206 Contact::unmarkForArchival($contact);
1209 // Unarchive the contact if it's not our own contact
1210 $contact = dba::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
1211 if (DBM::is_result($contact)) {
1212 Contact::unmarkForArchival($contact);
1215 $update = (!$arr['private'] && (($arr["author-link"] === $arr["owner-link"]) || ($arr["parent-uri"] === $arr["uri"])));
1217 // Is it a forum? Then we don't care about the rules from above
1218 if (!$update && ($arr["network"] == NETWORK_DFRN) && ($arr["parent-uri"] === $arr["uri"])) {
1219 if (dba::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
1225 dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
1226 ['id' => $arr['contact-id']]);
1228 // Now do the same for the system wide contacts with uid=0
1229 if (!$arr['private']) {
1230 dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
1231 ['id' => $arr['owner-id']]);
1233 if ($arr['owner-id'] != $arr['author-id']) {
1234 dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
1235 ['id' => $arr['author-id']]);
1240 private static function setHashtags(&$item)
1243 $tags = get_tags($item["body"]);
1246 if (!count($tags)) {
1250 // This sorting is important when there are hashtags that are part of other hashtags
1251 // Otherwise there could be problems with hashtags like #test and #test2
1254 $URLSearchString = "^\[\]";
1256 // All hashtags should point to the home server if "local_tags" is activated
1257 if (Config::get('system', 'local_tags')) {
1258 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1259 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["body"]);
1261 $item["tag"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1262 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["tag"]);
1265 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
1266 $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1268 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
1271 $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
1273 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
1276 $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
1278 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
1281 // Repair recursive urls
1282 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1283 "#$2", $item["body"]);
1285 foreach ($tags as $tag) {
1286 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=')) {
1290 $basetag = str_replace('_',' ',substr($tag,1));
1292 $newtag = '#[url=' . System::baseUrl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1294 $item["body"] = str_replace($tag, $newtag, $item["body"]);
1296 if (!stristr($item["tag"], "/search?tag=" . $basetag . "]" . $basetag . "[/url]")) {
1297 if (strlen($item["tag"])) {
1298 $item["tag"] = ','.$item["tag"];
1300 $item["tag"] = $newtag.$item["tag"];
1304 // Convert back the masked hashtags
1305 $item["body"] = str_replace("#", "#", $item["body"]);
1308 public static function getGuidById($id)
1310 $item = dba::selectFirst('item', ['guid'], ['id' => $id]);
1311 if (DBM::is_result($item)) {
1312 return $item['guid'];
1318 public static function getIdAndNickByGuid($guid, $uid = 0)
1324 $uid == local_user();
1327 // Does the given user have this item?
1329 $item = dba::fetch_first("SELECT `item`.`id`, `user`.`nickname` FROM `item`
1330 INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
1331 WHERE `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
1332 AND `item`.`guid` = ? AND `item`.`uid` = ?", $guid, $uid);
1333 if (DBM::is_result($item)) {
1335 $nick = $item["nickname"];
1339 // Or is it anywhere on the server?
1341 $item = dba::fetch_first("SELECT `item`.`id`, `user`.`nickname` FROM `item`
1342 INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
1343 WHERE `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
1344 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1345 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1346 AND NOT `item`.`private` AND `item`.`wall`
1347 AND `item`.`guid` = ?", $guid);
1348 if (DBM::is_result($item)) {
1350 $nick = $item["nickname"];
1353 return ["nick" => $nick, "id" => $id];
1357 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
1359 * @param int $item_id
1360 * @return bool true if item was deleted, else false
1362 private static function tagDeliver($uid, $item_id)
1366 $user = dba::selectFirst('user', [], ['uid' => $uid]);
1367 if (!DBM::is_result($user)) {
1371 $community_page = (($user['page-flags'] == PAGE_COMMUNITY) ? true : false);
1372 $prvgroup = (($user['page-flags'] == PAGE_PRVGROUP) ? true : false);
1374 $item = dba::selectFirst('item', [], ['id' => $item_id]);
1375 if (!DBM::is_result($item)) {
1379 $link = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
1382 * Diaspora uses their own hardwired link URL in @-tags
1383 * instead of the one we supply with webfinger
1385 $dlink = normalise_link(System::baseUrl() . '/u/' . $user['nickname']);
1387 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
1389 foreach ($matches as $mtch) {
1390 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
1392 logger('mention found: ' . $mtch[2]);
1398 if (($community_page || $prvgroup) &&
1399 !$item['wall'] && !$item['origin'] && ($item['id'] == $item['parent'])) {
1400 // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
1402 logger("no-mention top-level post to community or private group. delete.");
1403 dba::delete('item', ['id' => $item_id]);
1409 $arr = ['item' => $item, 'user' => $user];
1411 Addon::callHooks('tagged', $arr);
1413 if (!$community_page && !$prvgroup) {
1418 * tgroup delivery - setup a second delivery chain
1419 * prevent delivery looping - only proceed
1420 * if the message originated elsewhere and is a top-level post
1422 if ($item['wall'] || $item['origin'] || ($item['id'] != $item['parent'])) {
1426 // now change this copy of the post to a forum head message and deliver to all the tgroup members
1427 $self = dba::selectFirst('contact', ['id', 'name', 'url', 'thumb'], ['uid' => $uid, 'self' => true]);
1428 if (!DBM::is_result($self)) {
1432 $owner_id = Contact::getIdForURL($self['url']);
1434 // also reset all the privacy bits to the forum default permissions
1436 $private = ($user['allow_cid'] || $user['allow_gid'] || $user['deny_cid'] || $user['deny_gid']) ? 1 : 0;
1438 $forum_mode = ($prvgroup ? 2 : 1);
1440 $fields = ['wall' => true, 'origin' => true, 'forum_mode' => $forum_mode, 'contact-id' => $self['id'],
1441 'owner-id' => $owner_id, 'owner-name' => $self['name'], 'owner-link' => $self['url'],
1442 'owner-avatar' => $self['thumb'], 'private' => $private, 'allow_cid' => $user['allow_cid'],
1443 'allow_gid' => $user['allow_gid'], 'deny_cid' => $user['deny_cid'], 'deny_gid' => $user['deny_gid']];
1444 dba::update('item', $fields, ['id' => $item_id]);
1446 self::updateThread($item_id);
1448 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', 'tgroup', $item_id);
1451 public static function isRemoteSelf($contact, &$datarray)
1455 if (!$contact['remote_self']) {
1459 // Prevent the forwarding of posts that are forwarded
1460 if ($datarray["extid"] == NETWORK_DFRN) {
1461 logger('Already forwarded', LOGGER_DEBUG);
1465 // Prevent to forward already forwarded posts
1466 if ($datarray["app"] == $a->get_hostname()) {
1467 logger('Already forwarded (second test)', LOGGER_DEBUG);
1471 // Only forward posts
1472 if ($datarray["verb"] != ACTIVITY_POST) {
1473 logger('No post', LOGGER_DEBUG);
1477 if (($contact['network'] != NETWORK_FEED) && $datarray['private']) {
1478 logger('Not public', LOGGER_DEBUG);
1482 $datarray2 = $datarray;
1483 logger('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), LOGGER_DEBUG);
1484 if ($contact['remote_self'] == 2) {
1485 $self = dba::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
1486 ['uid' => $contact['uid'], 'self' => true]);
1487 if (DBM::is_result($self)) {
1488 $datarray['contact-id'] = $self["id"];
1490 $datarray['owner-name'] = $self["name"];
1491 $datarray['owner-link'] = $self["url"];
1492 $datarray['owner-avatar'] = $self["thumb"];
1494 $datarray['author-name'] = $datarray['owner-name'];
1495 $datarray['author-link'] = $datarray['owner-link'];
1496 $datarray['author-avatar'] = $datarray['owner-avatar'];
1498 unset($datarray['created']);
1499 unset($datarray['edited']);
1501 unset($datarray['network']);
1502 unset($datarray['owner-id']);
1503 unset($datarray['author-id']);
1506 if ($contact['network'] != NETWORK_FEED) {
1507 $datarray["guid"] = get_guid(32);
1508 unset($datarray["plink"]);
1509 $datarray["uri"] = item_new_uri($a->get_hostname(), $contact['uid'], $datarray["guid"]);
1510 $datarray["parent-uri"] = $datarray["uri"];
1511 $datarray["thr-parent"] = $datarray["uri"];
1512 $datarray["extid"] = NETWORK_DFRN;
1513 $urlpart = parse_url($datarray2['author-link']);
1514 $datarray["app"] = $urlpart["host"];
1516 $datarray['private'] = 0;
1520 if ($contact['network'] != NETWORK_FEED) {
1521 // Store the original post
1522 $result = self::insert($datarray2, false, false);
1523 logger('remote-self post original item - Contact '.$contact['url'].' return '.$result.' Item '.print_r($datarray2, true), LOGGER_DEBUG);
1525 $datarray["app"] = "Feed";
1529 // Trigger automatic reactions for addons
1530 $datarray['api_source'] = true;
1532 // We have to tell the hooks who we are - this really should be improved
1533 $_SESSION["authenticated"] = true;
1534 $_SESSION["uid"] = $contact['uid'];
1543 * @param array $item
1547 public static function fixPrivatePhotos($s, $uid, $item = null, $cid = 0)
1549 if (Config::get('system', 'disable_embedded')) {
1553 logger('check for photos', LOGGER_DEBUG);
1554 $site = substr(System::baseUrl(), strpos(System::baseUrl(), '://'));
1559 $img_start = strpos($orig_body, '[img');
1560 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
1561 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
1563 while (($img_st_close !== false) && ($img_len !== false)) {
1564 $img_st_close++; // make it point to AFTER the closing bracket
1565 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
1567 logger('found photo ' . $image, LOGGER_DEBUG);
1569 if (stristr($image, $site . '/photo/')) {
1570 // Only embed locally hosted photos
1572 $i = basename($image);
1573 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
1574 $x = strpos($i, '-');
1577 $res = substr($i, $x + 1);
1578 $i = substr($i, 0, $x);
1579 $fields = ['data', 'type', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'];
1580 $photo = dba::selectFirst('photo', $fields, ['resource-id' => $i, 'scale' => $res, 'uid' => $uid]);
1581 if (DBM::is_result($photo)) {
1583 * Check to see if we should replace this photo link with an embedded image
1584 * 1. No need to do so if the photo is public
1585 * 2. If there's a contact-id provided, see if they're in the access list
1586 * for the photo. If so, embed it.
1587 * 3. Otherwise, if we have an item, see if the item permissions match the photo
1588 * permissions, regardless of order but first check to see if they're an exact
1589 * match to save some processing overhead.
1591 if (self::hasPermissions($photo)) {
1593 $recips = self::enumeratePermissions($photo);
1594 if (in_array($cid, $recips)) {
1598 if (self::samePermissions($item, $photo)) {
1604 $data = $photo['data'];
1605 $type = $photo['type'];
1607 // If a custom width and height were specified, apply before embedding
1608 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
1609 logger('scaling photo', LOGGER_DEBUG);
1611 $width = intval($match[1]);
1612 $height = intval($match[2]);
1614 $Image = new Image($data, $type);
1615 if ($Image->isValid()) {
1616 $Image->scaleDown(max($width, $height));
1617 $data = $Image->asString();
1618 $type = $Image->getType();
1622 logger('replacing photo', LOGGER_DEBUG);
1623 $image = 'data:' . $type . ';base64,' . base64_encode($data);
1624 logger('replaced: ' . $image, LOGGER_DATA);
1630 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
1631 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
1632 if ($orig_body === false) {
1636 $img_start = strpos($orig_body, '[img');
1637 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
1638 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
1641 $new_body = $new_body . $orig_body;
1646 private static function hasPermissions($obj)
1650 x($obj, 'allow_cid')
1652 x($obj, 'allow_gid')
1661 private static function samePermissions($obj1, $obj2)
1663 // first part is easy. Check that these are exactly the same.
1664 if (($obj1['allow_cid'] == $obj2['allow_cid'])
1665 && ($obj1['allow_gid'] == $obj2['allow_gid'])
1666 && ($obj1['deny_cid'] == $obj2['deny_cid'])
1667 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
1671 // This is harder. Parse all the permissions and compare the resulting set.
1672 $recipients1 = self::enumeratePermissions($obj1);
1673 $recipients2 = self::enumeratePermissions($obj2);
1677 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
1678 return ($recipients1 == $recipients2);
1681 // returns an array of contact-ids that are allowed to see this object
1682 private static function enumeratePermissions($obj)
1684 $allow_people = expand_acl($obj['allow_cid']);
1685 $allow_groups = Group::expand(expand_acl($obj['allow_gid']));
1686 $deny_people = expand_acl($obj['deny_cid']);
1687 $deny_groups = Group::expand(expand_acl($obj['deny_gid']));
1688 $recipients = array_unique(array_merge($allow_people, $allow_groups));
1689 $deny = array_unique(array_merge($deny_people, $deny_groups));
1690 $recipients = array_diff($recipients, $deny);
1694 public static function getFeedTags($item)
1698 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
1700 for ($x = 0; $x < $cnt; $x ++) {
1701 if ($matches[1][$x]) {
1702 $ret[$matches[2][$x]] = ['#', $matches[1][$x], $matches[2][$x]];
1707 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
1709 for ($x = 0; $x < $cnt; $x ++) {
1710 if ($matches[1][$x]) {
1711 $ret[] = ['@', $matches[1][$x], $matches[2][$x]];
1718 public static function expire($uid, $days, $network = "", $force = false)
1720 if (!$uid || ($days < 1)) {
1725 * $expire_network_only = save your own wall posts
1726 * and just expire conversations started by others
1728 $expire_network_only = PConfig::get($uid,'expire', 'network_only');
1729 $sql_extra = (intval($expire_network_only) ? " AND wall = 0 " : "");
1731 if ($network != "") {
1732 $sql_extra .= sprintf(" AND network = '%s' ", dbesc($network));
1735 * There is an index "uid_network_received" but not "uid_network_created"
1736 * This avoids the creation of another index just for one purpose.
1737 * And it doesn't really matter wether to look at "received" or "created"
1739 $range = "AND `received` < UTC_TIMESTAMP() - INTERVAL %d DAY ";
1741 $range = "AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY ";
1744 $r = q("SELECT `file`, `resource-id`, `starred`, `type`, `id` FROM `item`
1745 WHERE `uid` = %d $range
1753 if (!DBM::is_result($r)) {
1757 $expire_items = PConfig::get($uid, 'expire', 'items', 1);
1759 // Forcing expiring of items - but not notes and marked items
1761 $expire_items = true;
1764 $expire_notes = PConfig::get($uid, 'expire', 'notes', 1);
1765 $expire_starred = PConfig::get($uid, 'expire', 'starred', 1);
1766 $expire_photos = PConfig::get($uid, 'expire', 'photos', 0);
1768 logger('User '.$uid.': expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
1770 foreach ($r as $item) {
1772 // don't expire filed items
1774 if (strpos($item['file'],'[') !== false) {
1778 // Only expire posts, not photos and photo comments
1780 if ($expire_photos == 0 && strlen($item['resource-id'])) {
1782 } elseif ($expire_starred == 0 && intval($item['starred'])) {
1784 } elseif ($expire_notes == 0 && $item['type'] == 'note') {
1786 } elseif ($expire_items == 0 && $item['type'] != 'note') {
1790 self::deleteById($item['id'], PRIORITY_LOW);
1794 public static function firstPostDate($uid, $wall = false)
1796 $condition = ['uid' => $uid, 'wall' => $wall, 'deleted' => false, 'visible' => true, 'moderated' => false];
1797 $params = ['order' => ['created' => false]];
1798 $thread = dba::selectFirst('thread', ['created'], $condition, $params);
1799 if (DBM::is_result($thread)) {
1800 return substr(DateTimeFormat::local($thread['created']), 0, 10);
1806 * @brief add/remove activity to an item
1808 * Toggle activities as like,dislike,attend of an item
1810 * @param string $item_id
1811 * @param string $verb
1812 * Activity verb. One of
1813 * like, unlike, dislike, undislike, attendyes, unattendyes,
1814 * attendno, unattendno, attendmaybe, unattendmaybe
1815 * @hook 'post_local_end'
1817 * 'post_id' => ID of posted item
1819 public static function performLike($item_id, $verb)
1821 if (!local_user() && !remote_user()) {
1828 $bodyverb = L10n::t('%1$s likes %2$s\'s %3$s');
1829 $activity = ACTIVITY_LIKE;
1833 $bodyverb = L10n::t('%1$s doesn\'t like %2$s\'s %3$s');
1834 $activity = ACTIVITY_DISLIKE;
1838 $bodyverb = L10n::t('%1$s is attending %2$s\'s %3$s');
1839 $activity = ACTIVITY_ATTEND;
1843 $bodyverb = L10n::t('%1$s is not attending %2$s\'s %3$s');
1844 $activity = ACTIVITY_ATTENDNO;
1847 case 'unattendmaybe':
1848 $bodyverb = L10n::t('%1$s may attend %2$s\'s %3$s');
1849 $activity = ACTIVITY_ATTENDMAYBE;
1852 logger('like: unknown verb ' . $verb . ' for item ' . $item_id);
1856 // Enable activity toggling instead of on/off
1857 $event_verb_flag = $activity === ACTIVITY_ATTEND || $activity === ACTIVITY_ATTENDNO || $activity === ACTIVITY_ATTENDMAYBE;
1859 logger('like: verb ' . $verb . ' item ' . $item_id);
1861 $item = dba::selectFirst('item', [], ['`id` = ? OR `uri` = ?', $item_id, $item_id]);
1862 if (!DBM::is_result($item)) {
1863 logger('like: unknown item ' . $item_id);
1867 $uid = $item['uid'];
1868 if (($uid == 0) && local_user()) {
1869 $uid = local_user();
1872 if (!can_write_wall($uid)) {
1873 logger('like: unable to write on wall ' . $uid);
1877 // Retrieves the local post owner
1878 $owner_self_contact = dba::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
1879 if (!DBM::is_result($owner_self_contact)) {
1880 logger('like: unknown owner ' . $uid);
1884 // Retrieve the current logged in user's public contact
1885 $author_id = public_contact();
1887 $author_contact = dba::selectFirst('contact', [], ['id' => $author_id]);
1888 if (!DBM::is_result($author_contact)) {
1889 logger('like: unknown author ' . $author_id);
1893 // Contact-id is the uid-dependant author contact
1894 if (local_user() == $uid) {
1895 $item_contact_id = $owner_self_contact['id'];
1896 $item_contact = $owner_self_contact;
1898 $item_contact_id = Contact::getIdForURL($author_contact['url'], $uid, true);
1899 $item_contact = dba::selectFirst('contact', [], ['id' => $item_contact_id]);
1900 if (!DBM::is_result($item_contact)) {
1901 logger('like: unknown item contact ' . $item_contact_id);
1906 // Look for an existing verb row
1907 // event participation are essentially radio toggles. If you make a subsequent choice,
1908 // we need to eradicate your first choice.
1909 if ($event_verb_flag) {
1910 $verbs = "'" . dbesc(ACTIVITY_ATTEND) . "', '" . dbesc(ACTIVITY_ATTENDNO) . "', '" . dbesc(ACTIVITY_ATTENDMAYBE) . "'";
1912 $verbs = "'".dbesc($activity)."'";
1915 /// @todo This query is expected to be a performance eater due to the "OR" - it has to be changed totally
1916 $existing_like = q("SELECT `id`, `guid`, `verb` FROM `item`
1917 WHERE `verb` IN ($verbs)
1919 AND `author-id` = %d
1921 AND (`parent` = '%s' OR `parent-uri` = '%s' OR `thr-parent` = '%s')
1923 intval($author_contact['id']),
1924 intval($item['uid']),
1925 dbesc($item_id), dbesc($item_id), dbesc($item['uri'])
1928 // If it exists, mark it as deleted
1929 if (DBM::is_result($existing_like)) {
1930 $like_item = $existing_like[0];
1932 // Already voted, undo it
1933 $fields = ['deleted' => true, 'unseen' => true, 'changed' => DateTimeFormat::utcNow()];
1934 dba::update('item', $fields, ['id' => $like_item['id']]);
1936 // Clean up the Diaspora signatures for this like
1937 // Go ahead and do it even if Diaspora support is disabled. We still want to clean up
1938 // if it had been enabled in the past
1939 dba::delete('sign', ['iid' => $like_item['id']]);
1941 $like_item_id = $like_item['id'];
1942 Worker::add(PRIORITY_HIGH, "Notifier", "like", $like_item_id);
1944 if (!$event_verb_flag || $like_item['verb'] == $activity) {
1949 // Verb is "un-something", just trying to delete existing entries
1950 if (strpos($verb, 'un') === 0) {
1954 // Else or if event verb different from existing row, create a new item row
1955 $post_type = (($item['resource-id']) ? L10n::t('photo') : L10n::t('status'));
1956 if ($item['object-type'] === ACTIVITY_OBJ_EVENT) {
1957 $post_type = L10n::t('event');
1959 $objtype = $item['resource-id'] ? ACTIVITY_OBJ_IMAGE : ACTIVITY_OBJ_NOTE ;
1960 $link = xmlify('<link rel="alternate" type="text/html" href="' . System::baseUrl() . '/display/' . $owner_self_contact['nick'] . '/' . $item['id'] . '" />' . "\n") ;
1961 $body = $item['body'];
1966 <type>$objtype</type>
1968 <id>{$item['uri']}</id>
1971 <content>$body</content>
1975 $ulink = '[url=' . $author_contact['url'] . ']' . $author_contact['name'] . '[/url]';
1976 $alink = '[url=' . $item['author-link'] . ']' . $item['author-name'] . '[/url]';
1977 $plink = '[url=' . System::baseUrl() . '/display/' . $owner_self_contact['nick'] . '/' . $item['id'] . ']' . $post_type . '[/url]';
1980 'guid' => get_guid(32),
1981 'uri' => item_new_uri(self::getApp()->get_hostname(), $item['uid']),
1982 'uid' => $item['uid'],
1983 'contact-id' => $item_contact_id,
1984 'type' => 'activity',
1985 'wall' => $item['wall'],
1987 'gravity' => GRAVITY_LIKE,
1988 'parent' => $item['id'],
1989 'parent-uri' => $item['uri'],
1990 'thr-parent' => $item['uri'],
1991 'owner-id' => $item['owner-id'],
1992 'owner-name' => $item['owner-name'],
1993 'owner-link' => $item['owner-link'],
1994 'owner-avatar' => $item['owner-avatar'],
1995 'author-id' => $author_contact['id'],
1996 'author-name' => $author_contact['name'],
1997 'author-link' => $author_contact['url'],
1998 'author-avatar' => $author_contact['thumb'],
1999 'body' => sprintf($bodyverb, $ulink, $alink, $plink),
2000 'verb' => $activity,
2001 'object-type' => $objtype,
2003 'allow_cid' => $item['allow_cid'],
2004 'allow_gid' => $item['allow_gid'],
2005 'deny_cid' => $item['deny_cid'],
2006 'deny_gid' => $item['deny_gid'],
2011 $new_item_id = self::insert($new_item);
2013 // If the parent item isn't visible then set it to visible
2014 if (!$item['visible']) {
2015 self::update(['visible' => true], ['id' => $item['id']]);
2018 // Save the author information for the like in case we need to relay to Diaspora
2019 Diaspora::storeLikeSignature($item_contact, $new_item_id);
2021 $new_item['id'] = $new_item_id;
2023 Addon::callHooks('post_local_end', $new_item);
2025 Worker::add(PRIORITY_HIGH, "Notifier", "like", $new_item_id);
2030 private static function addThread($itemid, $onlyshadow = false)
2032 $fields = ['uid', 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private', 'pubmail',
2033 'moderated', 'visible', 'spam', 'starred', 'bookmark', 'contact-id',
2034 'deleted', 'origin', 'forum_mode', 'mention', 'network', 'author-id', 'owner-id'];
2035 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
2036 $item = dba::selectFirst('item', $fields, $condition);
2038 if (!DBM::is_result($item)) {
2042 $item['iid'] = $itemid;
2045 $result = dba::insert('thread', $item);
2047 logger("Add thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
2051 private static function updateThread($itemid, $setmention = false)
2053 $fields = ['uid', 'guid', 'title', 'body', 'created', 'edited', 'commented', 'received', 'changed',
2054 'wall', 'private', 'pubmail', 'moderated', 'visible', 'spam', 'starred', 'bookmark', 'contact-id',
2055 'deleted', 'origin', 'forum_mode', 'network', 'author-id', 'owner-id', 'rendered-html', 'rendered-hash'];
2056 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
2058 $item = dba::selectFirst('item', $fields, $condition);
2059 if (!DBM::is_result($item)) {
2064 $item["mention"] = 1;
2071 foreach ($item as $field => $data) {
2072 if (!in_array($field, ["guid", "title", "body", "rendered-html", "rendered-hash"])) {
2073 $fields[$field] = $data;
2077 $result = dba::update('thread', $fields, ['iid' => $itemid]);
2079 logger("Update thread for item ".$itemid." - guid ".$item["guid"]." - ".(int)$result, LOGGER_DEBUG);
2081 // Updating a shadow item entry
2082 $items = dba::selectFirst('item', ['id'], ['guid' => $item['guid'], 'uid' => 0]);
2084 if (!DBM::is_result($items)) {
2088 $fields = ['title' => $item['title'], 'body' => $item['body'],
2089 'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']];
2090 $result = dba::update('item', $fields, ['id' => $items['id']]);
2092 logger("Updating public shadow for post ".$items["id"]." - guid ".$item["guid"]." Result: ".print_r($result, true), LOGGER_DEBUG);
2095 private static function deleteThread($itemid, $itemuri = "")
2097 $item = dba::selectFirst('thread', ['uid'], ['iid' => $itemid]);
2098 if (!DBM::is_result($item)) {
2099 logger('No thread found for id '.$itemid, LOGGER_DEBUG);
2103 // Using dba::delete at this time could delete the associated item entries
2104 $result = dba::e("DELETE FROM `thread` WHERE `iid` = ?", $itemid);
2106 logger("deleteThread: Deleted thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
2108 if ($itemuri != "") {
2109 $condition = ["`uri` = ? AND NOT `deleted` AND NOT (`uid` IN (?, 0))", $itemuri, $item["uid"]];
2110 if (!dba::exists('item', $condition)) {
2111 dba::delete('item', ['uri' => $itemuri, 'uid' => 0]);
2112 logger("deleteThread: Deleted shadow for item ".$itemuri, LOGGER_DEBUG);