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 // Only call the notifier when the item has some content relevant change.
80 if ($item['origin'] && in_array('edited', array_keys($fields))) {
81 Worker::add(PRIORITY_HIGH, "Notifier", 'edit_post', $item['id']);
91 * @brief Delete an item and notify others about it - if it was ours
93 * @param array $condition The condition for finding the item entries
94 * @param integer $priority Priority for the notification
96 public static function delete($condition, $priority = PRIORITY_HIGH)
98 $items = dba::select('item', ['id'], $condition);
99 while ($item = dba::fetch($items)) {
100 self::deleteById($item['id'], $priority);
106 * @brief Delete an item and notify others about it - if it was ours
108 * @param integer $item_id Item ID that should be delete
109 * @param integer $priority Priority for the notification
111 * @return boolean success
113 public static function deleteById($item_id, $priority = PRIORITY_HIGH)
115 // locate item to be deleted
116 $fields = ['id', 'uri', 'uid', 'parent', 'parent-uri', 'origin',
117 'deleted', 'file', 'resource-id', 'event-id', 'attach',
118 'verb', 'object-type', 'object', 'target', 'contact-id'];
119 $item = dba::selectFirst('item', $fields, ['id' => $item_id]);
120 if (!DBM::is_result($item)) {
121 logger('Item with ID ' . $item_id . " hasn't been found.", LOGGER_DEBUG);
125 if ($item['deleted']) {
126 logger('Item with ID ' . $item_id . ' has already been deleted.', LOGGER_DEBUG);
130 $parent = dba::selectFirst('item', ['origin'], ['id' => $item['parent']]);
131 if (!DBM::is_result($parent)) {
132 $parent = ['origin' => false];
135 // clean up categories and tags so they don't end up as orphans
138 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
140 foreach ($matches as $mtch) {
141 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],true);
147 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
149 foreach ($matches as $mtch) {
150 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],false);
155 * If item is a link to a photo resource, nuke all the associated photos
156 * (visitors will not have photo resources)
157 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
158 * generate a resource-id and therefore aren't intimately linked to the item.
160 if (strlen($item['resource-id'])) {
161 dba::delete('photo', ['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
164 // If item is a link to an event, delete the event.
165 if (intval($item['event-id'])) {
166 Event::delete($item['event-id']);
169 // If item has attachments, drop them
170 foreach (explode(", ", $item['attach']) as $attach) {
171 preg_match("|attach/(\d+)|", $attach, $matches);
172 dba::delete('attach', ['id' => $matches[1], 'uid' => $item['uid']]);
175 // Delete tags that had been attached to other items
176 self::deleteTagsFromItem($item);
178 // Set the item to "deleted"
179 dba::update('item', ['deleted' => true, 'title' => '', 'body' => '',
180 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()],
181 ['id' => $item['id']]);
183 Term::insertFromTagFieldByItemId($item['id']);
184 Term::insertFromFileFieldByItemId($item['id']);
185 self::deleteThread($item['id'], $item['parent-uri']);
187 if (!dba::exists('item', ["`uri` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri']])) {
188 self::delete(['uri' => $item['uri'], 'uid' => 0, 'deleted' => false], $priority);
191 // If it's the parent of a comment thread, kill all the kids
192 if ($item['id'] == $item['parent']) {
193 self::delete(['parent' => $item['parent'], 'deleted' => false], $priority);
196 // Is it our comment and/or our thread?
197 if ($item['origin'] || $parent['origin']) {
199 // When we delete the original post we will delete all existing copies on the server as well
200 self::delete(['uri' => $item['uri'], 'deleted' => false], $priority);
202 // send the notification upstream/downstream
203 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", "drop", intval($item['id']));
206 logger('Item with ID ' . $item_id . " has been deleted.", LOGGER_DEBUG);
211 private static function deleteTagsFromItem($item)
213 if (($item["verb"] != ACTIVITY_TAG) || ($item["object-type"] != ACTIVITY_OBJ_TAGTERM)) {
217 $xo = XML::parseString($item["object"], false);
218 $xt = XML::parseString($item["target"], false);
220 if ($xt->type != ACTIVITY_OBJ_NOTE) {
224 $i = dba::selectFirst('item', ['id', 'contact-id', 'tag'], ['uri' => $xt->id, 'uid' => $item['uid']]);
225 if (!DBM::is_result($i)) {
229 // For tags, the owner cannot remove the tag on the author's copy of the post.
230 $owner_remove = ($item["contact-id"] == $i["contact-id"]);
231 $author_copy = $item["origin"];
233 if (($owner_remove && $author_copy) || !$owner_remove) {
237 $tags = explode(',', $i["tag"]);
240 foreach ($tags as $tag) {
241 if (trim($tag) !== trim($xo->body)) {
242 $newtags[] = trim($tag);
246 self::update(['tag' => implode(',', $newtags)], ['id' => $i["id"]]);
249 private static function guid($item, $notify)
251 $guid = notags(trim($item['guid']));
258 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
259 // We add the hash of our own host because our host is the original creator of the post.
260 $prefix_host = get_app()->get_hostname();
264 // We are only storing the post so we create a GUID from the original hostname.
265 if (!empty($item['author-link'])) {
266 $parsed = parse_url($item['author-link']);
267 if (!empty($parsed['host'])) {
268 $prefix_host = $parsed['host'];
272 if (empty($prefix_host) && !empty($item['plink'])) {
273 $parsed = parse_url($item['plink']);
274 if (!empty($parsed['host'])) {
275 $prefix_host = $parsed['host'];
279 if (empty($prefix_host) && !empty($item['uri'])) {
280 $parsed = parse_url($item['uri']);
281 if (!empty($parsed['host'])) {
282 $prefix_host = $parsed['host'];
286 // Is it in the format data@host.tld? - Used for mail contacts
287 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
288 $mailparts = explode('@', $item['author-link']);
289 $prefix_host = array_pop($mailparts);
293 if (!empty($item['plink'])) {
294 $guid = self::guidFromUri($item['plink'], $prefix_host);
295 } elseif (!empty($item['uri'])) {
296 $guid = self::guidFromUri($item['uri'], $prefix_host);
298 $guid = get_guid(32, hash('crc32', $prefix_host));
304 private static function contactId($item)
306 $contact_id = (int)$item["contact-id"];
308 if (!empty($contact_id)) {
311 logger('Missing contact-id. Called by: '.System::callstack(), LOGGER_DEBUG);
313 * First we are looking for a suitable contact that matches with the author of the post
314 * This is done only for comments
316 if ($item['parent-uri'] != $item['uri']) {
317 $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
320 // If not present then maybe the owner was found
321 if ($contact_id == 0) {
322 $contact_id = Contact::getIdForURL($item['owner-link'], $item['uid']);
325 // Still missing? Then use the "self" contact of the current user
326 if ($contact_id == 0) {
327 $self = dba::selectFirst('contact', ['id'], ['self' => true, 'uid' => $item['uid']]);
328 if (DBM::is_result($self)) {
329 $contact_id = $self["id"];
332 logger("Contact-id was missing for post ".$item['guid']." from user id ".$item['uid']." - now set to ".$contact_id, LOGGER_DEBUG);
337 public static function insert($item, $force_parent = false, $notify = false, $dontcache = false)
341 // If it is a posting where users should get notifications, then define it as wall posting
344 $item['type'] = 'wall';
346 $item['network'] = NETWORK_DFRN;
347 $item['protocol'] = PROTOCOL_DFRN;
349 if (is_int($notify)) {
352 $priority = PRIORITY_HIGH;
355 $item['network'] = trim(defaults($item, 'network', NETWORK_PHANTOM));
358 $item['guid'] = self::guid($item, $notify);
359 $item['uri'] = notags(trim(defaults($item, 'uri', item_new_uri($a->get_hostname(), $item['uid'], $item['guid']))));
361 // Store conversation data
362 $item = Conversation::insert($item);
365 * If a Diaspora signature structure was passed in, pull it out of the
366 * item array and set it aside for later storage.
370 if (x($item, 'dsprsig')) {
371 $encoded_signature = $item['dsprsig'];
372 $dsprsig = json_decode(base64_decode($item['dsprsig']));
373 unset($item['dsprsig']);
376 if (!empty($item['diaspora_signed_text'])) {
377 $diaspora_signed_text = $item['diaspora_signed_text'];
378 unset($item['diaspora_signed_text']);
380 $diaspora_signed_text = '';
383 // Converting the plink
384 /// @TODO Check if this is really still needed
385 if ($item['network'] == NETWORK_OSTATUS) {
386 if (isset($item['plink'])) {
387 $item['plink'] = OStatus::convertHref($item['plink']);
388 } elseif (isset($item['uri'])) {
389 $item['plink'] = OStatus::convertHref($item['uri']);
393 if (!empty($item['thr-parent'])) {
394 $item['parent-uri'] = $item['thr-parent'];
397 if (x($item, 'gravity')) {
398 $item['gravity'] = intval($item['gravity']);
399 } elseif ($item['parent-uri'] === $item['uri']) {
400 $item['gravity'] = 0;
401 } elseif (activity_match($item['verb'],ACTIVITY_POST)) {
402 $item['gravity'] = 6;
404 $item['gravity'] = 6; // extensible catchall
407 $item['type'] = defaults($item, 'type', 'remote');
409 $uid = intval($item['uid']);
411 // check for create date and expire time
412 $expire_interval = Config::get('system', 'dbclean-expire-days', 0);
414 $user = dba::selectFirst('user', ['expire'], ['uid' => $uid]);
415 if (DBM::is_result($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
416 $expire_interval = $user['expire'];
419 if (($expire_interval > 0) && !empty($item['created'])) {
420 $expire_date = time() - ($expire_interval * 86400);
421 $created_date = strtotime($item['created']);
422 if ($created_date < $expire_date) {
423 logger('item-store: item created ('.date('c', $created_date).') before expiration time ('.date('c', $expire_date).'). ignored. ' . print_r($item,true), LOGGER_DEBUG);
429 * Do we already have this item?
430 * We have to check several networks since Friendica posts could be repeated
431 * via OStatus (maybe Diasporsa as well)
433 if (in_array($item['network'], [NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS, ""])) {
434 $condition = ["`uri` = ? AND `uid` = ? AND `network` IN (?, ?, ?)",
435 trim($item['uri']), $item['uid'],
436 NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS];
437 $existing = dba::selectFirst('item', ['id', 'network'], $condition);
438 if (DBM::is_result($existing)) {
439 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
441 logger("Item with uri ".$item['uri']." already existed for user ".$uid." with id ".$existing["id"]." target network ".$existing["network"]." - new network: ".$item['network']);
444 return $existing["id"];
448 self::addLanguageInPostopts($item);
450 $item['wall'] = intval(defaults($item, 'wall', 0));
451 $item['extid'] = trim(defaults($item, 'extid', ''));
452 $item['author-name'] = trim(defaults($item, 'author-name', ''));
453 $item['author-link'] = trim(defaults($item, 'author-link', ''));
454 $item['author-avatar'] = trim(defaults($item, 'author-avatar', ''));
455 $item['owner-name'] = trim(defaults($item, 'owner-name', ''));
456 $item['owner-link'] = trim(defaults($item, 'owner-link', ''));
457 $item['owner-avatar'] = trim(defaults($item, 'owner-avatar', ''));
458 $item['received'] = ((x($item, 'received') !== false) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
459 $item['created'] = ((x($item, 'created') !== false) ? DateTimeFormat::utc($item['created']) : $item['received']);
460 $item['edited'] = ((x($item, 'edited') !== false) ? DateTimeFormat::utc($item['edited']) : $item['created']);
461 $item['changed'] = ((x($item, 'changed') !== false) ? DateTimeFormat::utc($item['changed']) : $item['created']);
462 $item['commented'] = ((x($item, 'commented') !== false) ? DateTimeFormat::utc($item['commented']) : $item['created']);
463 $item['title'] = trim(defaults($item, 'title', ''));
464 $item['location'] = trim(defaults($item, 'location', ''));
465 $item['coord'] = trim(defaults($item, 'coord', ''));
466 $item['visible'] = ((x($item, 'visible') !== false) ? intval($item['visible']) : 1);
467 $item['deleted'] = 0;
468 $item['parent-uri'] = trim(defaults($item, 'parent-uri', $item['uri']));
469 $item['verb'] = trim(defaults($item, 'verb', ''));
470 $item['object-type'] = trim(defaults($item, 'object-type', ''));
471 $item['object'] = trim(defaults($item, 'object', ''));
472 $item['target-type'] = trim(defaults($item, 'target-type', ''));
473 $item['target'] = trim(defaults($item, 'target', ''));
474 $item['plink'] = trim(defaults($item, 'plink', ''));
475 $item['allow_cid'] = trim(defaults($item, 'allow_cid', ''));
476 $item['allow_gid'] = trim(defaults($item, 'allow_gid', ''));
477 $item['deny_cid'] = trim(defaults($item, 'deny_cid', ''));
478 $item['deny_gid'] = trim(defaults($item, 'deny_gid', ''));
479 $item['private'] = intval(defaults($item, 'private', 0));
480 $item['bookmark'] = intval(defaults($item, 'bookmark', 0));
481 $item['body'] = trim(defaults($item, 'body', ''));
482 $item['tag'] = trim(defaults($item, 'tag', ''));
483 $item['attach'] = trim(defaults($item, 'attach', ''));
484 $item['app'] = trim(defaults($item, 'app', ''));
485 $item['origin'] = intval(defaults($item, 'origin', 0));
486 $item['postopts'] = trim(defaults($item, 'postopts', ''));
487 $item['resource-id'] = trim(defaults($item, 'resource-id', ''));
488 $item['event-id'] = intval(defaults($item, 'event-id', 0));
489 $item['inform'] = trim(defaults($item, 'inform', ''));
490 $item['file'] = trim(defaults($item, 'file', ''));
492 // When there is no content then we don't post it
493 if ($item['body'].$item['title'] == '') {
497 // Items cannot be stored before they happen ...
498 if ($item['created'] > DateTimeFormat::utcNow()) {
499 $item['created'] = DateTimeFormat::utcNow();
502 // We haven't invented time travel by now.
503 if ($item['edited'] > DateTimeFormat::utcNow()) {
504 $item['edited'] = DateTimeFormat::utcNow();
507 if (($item['author-link'] == "") && ($item['owner-link'] == "")) {
508 logger("Both author-link and owner-link are empty. Called by: " . System::callstack(), LOGGER_DEBUG);
511 $item['plink'] = defaults($item, 'plink', System::baseUrl() . '/display/' . urlencode($item['guid']));
513 // The contact-id should be set before "self::insert" was called - but there seems to be issues sometimes
514 $item["contact-id"] = self::contactId($item);
516 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
517 'photo' => $item['author-avatar'], 'network' => $item['network']];
519 $item['author-id'] = defaults($item, 'author-id', Contact::getIdForURL($item["author-link"], 0, false, $default));
521 if (Contact::isBlocked($item["author-id"])) {
522 logger('Contact '.$item["author-id"].' is blocked, item '.$item["uri"].' will not be stored');
526 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
527 'photo' => $item['owner-avatar'], 'network' => $item['network']];
529 $item['owner-id'] = defaults($item, 'owner-id', Contact::getIdForURL($item["owner-link"], 0, false, $default));
531 if (Contact::isBlocked($item["owner-id"])) {
532 logger('Contact '.$item["owner-id"].' is blocked, item '.$item["uri"].' will not be stored');
536 if ($item['network'] == NETWORK_PHANTOM) {
537 logger('Missing network. Called by: '.System::callstack(), LOGGER_DEBUG);
539 $contact = Contact::getDetailsByURL($item['author-link'], $item['uid']);
540 if (!empty($contact['network'])) {
541 $item['network'] = $contact["network"];
543 $item['network'] = NETWORK_DFRN;
545 logger("Set network to " . $item["network"] . " for " . $item["uri"], LOGGER_DEBUG);
548 // Checking if there is already an item with the same guid
549 logger('Checking for an item for user '.$item['uid'].' on network '.$item['network'].' with the guid '.$item['guid'], LOGGER_DEBUG);
550 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
551 if (dba::exists('item', $condition)) {
552 logger('found item with guid '.$item['guid'].' for user '.$item['uid'].' on network '.$item['network'], LOGGER_DEBUG);
556 // Check for hashtags in the body and repair or add hashtag links
557 self::setHashtags($item);
559 $item['thr-parent'] = $item['parent-uri'];
567 if ($item['parent-uri'] === $item['uri']) {
570 $allow_cid = $item['allow_cid'];
571 $allow_gid = $item['allow_gid'];
572 $deny_cid = $item['deny_cid'];
573 $deny_gid = $item['deny_gid'];
574 $notify_type = 'wall-new';
576 // find the parent and snarf the item id and ACLs
577 // and anything else we need to inherit
579 $fields = ['uri', 'parent-uri', 'id', 'deleted',
580 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
581 'wall', 'private', 'forum_mode', 'origin'];
582 $condition = ['uri' => $item['parent-uri'], 'uid' => $item['uid']];
583 $params = ['order' => ['id' => false]];
584 $parent = dba::selectFirst('item', $fields, $condition, $params);
586 if (DBM::is_result($parent)) {
587 // is the new message multi-level threaded?
588 // even though we don't support it now, preserve the info
589 // and re-attach to the conversation parent.
591 if ($parent['uri'] != $parent['parent-uri']) {
592 $item['parent-uri'] = $parent['parent-uri'];
594 $condition = ['uri' => $item['parent-uri'],
595 'parent-uri' => $item['parent-uri'],
596 'uid' => $item['uid']];
597 $params = ['order' => ['id' => false]];
598 $toplevel_parent = dba::selectFirst('item', $fields, $condition, $params);
600 if (DBM::is_result($toplevel_parent)) {
601 $parent = $toplevel_parent;
605 $parent_id = $parent['id'];
606 $parent_deleted = $parent['deleted'];
607 $allow_cid = $parent['allow_cid'];
608 $allow_gid = $parent['allow_gid'];
609 $deny_cid = $parent['deny_cid'];
610 $deny_gid = $parent['deny_gid'];
611 $item['wall'] = $parent['wall'];
612 $notify_type = 'comment-new';
615 * If the parent is private, force privacy for the entire conversation
616 * This differs from the above settings as it subtly allows comments from
617 * email correspondents to be private even if the overall thread is not.
619 if ($parent['private']) {
620 $item['private'] = $parent['private'];
624 * Edge case. We host a public forum that was originally posted to privately.
625 * The original author commented, but as this is a comment, the permissions
626 * weren't fixed up so it will still show the comment as private unless we fix it here.
628 if ((intval($parent['forum_mode']) == 1) && $parent['private']) {
629 $item['private'] = 0;
632 // If its a post from myself then tag the thread as "mention"
633 logger("Checking if parent ".$parent_id." has to be tagged as mention for user ".$item['uid'], LOGGER_DEBUG);
634 $user = dba::selectFirst('user', ['nickname'], ['uid' => $item['uid']]);
635 if (DBM::is_result($user)) {
636 $self = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
637 logger("'myself' is ".$self." for parent ".$parent_id." checking against ".$item['author-link']." and ".$item['owner-link'], LOGGER_DEBUG);
638 if ((normalise_link($item['author-link']) == $self) || (normalise_link($item['owner-link']) == $self)) {
639 dba::update('thread', ['mention' => true], ['iid' => $parent_id]);
640 logger("tagged thread ".$parent_id." as mention for user ".$self, LOGGER_DEBUG);
645 * Allow one to see reply tweets from status.net even when
646 * we don't have or can't see the original post.
649 logger('$force_parent=true, reply converted to top-level post.');
651 $item['parent-uri'] = $item['uri'];
652 $item['gravity'] = 0;
654 logger('item parent '.$item['parent-uri'].' for '.$item['uid'].' was not found - ignoring item');
662 $condition = ["`uri` = ? AND `network` IN (?, ?) AND `uid` = ?",
663 $item['uri'], $item['network'], NETWORK_DFRN, $item['uid']];
664 if (dba::exists('item', $condition)) {
665 logger('duplicated item with the same uri found. '.print_r($item,true));
669 // On Friendica and Diaspora the GUID is unique
670 if (in_array($item['network'], [NETWORK_DFRN, NETWORK_DIASPORA])) {
671 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
672 if (dba::exists('item', $condition)) {
673 logger('duplicated item with the same guid found. '.print_r($item,true));
677 // Check for an existing post with the same content. There seems to be a problem with OStatus.
678 $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
679 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
680 if (dba::exists('item', $condition)) {
681 logger('duplicated item with the same body found. '.print_r($item,true));
686 // Is this item available in the global items (with uid=0)?
687 if ($item["uid"] == 0) {
688 $item["global"] = true;
690 // Set the global flag on all items if this was a global item entry
691 dba::update('item', ['global' => true], ['uri' => $item["uri"]]);
693 $item["global"] = dba::exists('item', ['uid' => 0, 'uri' => $item["uri"]]);
697 if (strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid)) {
700 $private = $item['private'];
703 $item["allow_cid"] = $allow_cid;
704 $item["allow_gid"] = $allow_gid;
705 $item["deny_cid"] = $deny_cid;
706 $item["deny_gid"] = $deny_gid;
707 $item["private"] = $private;
708 $item["deleted"] = $parent_deleted;
710 // Fill the cache field
711 put_item_in_cache($item);
714 Addon::callHooks('post_local', $item);
716 Addon::callHooks('post_remote', $item);
719 // This array field is used to trigger some automatic reactions
720 // It is mainly used in the "post_local" hook.
721 unset($item['api_source']);
723 if (x($item, 'cancel')) {
724 logger('post cancelled by addon.');
729 * Check for already added items.
730 * There is a timing issue here that sometimes creates double postings.
731 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
733 if ($item["uid"] == 0) {
734 if (dba::exists('item', ['uri' => trim($item['uri']), 'uid' => 0])) {
735 logger('Global item already stored. URI: '.$item['uri'].' on network '.$item['network'], LOGGER_DEBUG);
740 logger('' . print_r($item,true), LOGGER_DATA);
743 $ret = dba::insert('item', $item);
745 // When the item was successfully stored we fetch the ID of the item.
746 if (DBM::is_result($ret)) {
747 $current_post = dba::lastInsertId();
749 // This can happen - for example - if there are locking timeouts.
752 // Store the data into a spool file so that we can try again later.
754 // At first we restore the Diaspora signature that we removed above.
755 if (isset($encoded_signature)) {
756 $item['dsprsig'] = $encoded_signature;
759 // Now we store the data in the spool directory
760 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
761 $file = 'item-'.round(microtime(true) * 10000).'-'.mt_rand().'.msg';
763 $spoolpath = get_spoolpath();
764 if ($spoolpath != "") {
765 $spool = $spoolpath.'/'.$file;
766 file_put_contents($spool, json_encode($item));
767 logger("Item wasn't stored - Item was spooled into file ".$file, LOGGER_DEBUG);
772 if ($current_post == 0) {
773 // This is one of these error messages that never should occur.
774 logger("couldn't find created item - we better quit now.");
779 // How much entries have we created?
780 // We wouldn't need this query when we could use an unique index - but MySQL has length problems with them.
781 $entries = dba::count('item', ['uri' => $item['uri'], 'uid' => $item['uid'], 'network' => $item['network']]);
784 // There are duplicates. We delete our just created entry.
785 logger('Duplicated post occurred. uri = ' . $item['uri'] . ' uid = ' . $item['uid']);
787 // Yes, we could do a rollback here - but we are having many users with MyISAM.
788 dba::delete('item', ['id' => $current_post]);
791 } elseif ($entries == 0) {
792 // This really should never happen since we quit earlier if there were problems.
793 logger("Something is terribly wrong. We haven't found our created entry.");
798 logger('created item '.$current_post);
799 self::updateContact($item);
801 if (!$parent_id || ($item['parent-uri'] === $item['uri'])) {
802 $parent_id = $current_post;
806 dba::update('item', ['parent' => $parent_id], ['id' => $current_post]);
808 $item['id'] = $current_post;
809 $item['parent'] = $parent_id;
811 // update the commented timestamp on the parent
812 // Only update "commented" if it is really a comment
813 if (($item['verb'] == ACTIVITY_POST) || !Config::get("system", "like_no_comment")) {
814 dba::update('item', ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
816 dba::update('item', ['changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
821 * Friendica servers lower than 3.4.3-2 had double encoded the signature ...
822 * We can check for this condition when we decode and encode the stuff again.
824 if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) {
825 $dsprsig->signature = base64_decode($dsprsig->signature);
826 logger("Repaired double encoded signature from handle ".$dsprsig->signer, LOGGER_DEBUG);
829 dba::insert('sign', ['iid' => $current_post, 'signed_text' => $dsprsig->signed_text,
830 'signature' => $dsprsig->signature, 'signer' => $dsprsig->signer]);
833 if (!empty($diaspora_signed_text)) {
834 // Formerly we stored the signed text, the signature and the author in different fields.
835 // We now store the raw data so that we are more flexible.
836 dba::insert('sign', ['iid' => $current_post, 'signed_text' => $diaspora_signed_text]);
839 $deleted = self::tagDeliver($item['uid'], $current_post);
842 * current post can be deleted if is for a community page and no mention are
845 if (!$deleted && !$dontcache) {
846 $posted_item = dba::selectFirst('item', [], ['id' => $current_post]);
847 if (DBM::is_result($posted_item)) {
849 Addon::callHooks('post_local_end', $posted_item);
851 Addon::callHooks('post_remote_end', $posted_item);
854 logger('new item not found in DB, id ' . $current_post);
858 if ($item['parent-uri'] === $item['uri']) {
859 self::addThread($current_post);
861 self::updateThread($parent_id);
867 * Due to deadlock issues with the "term" table we are doing these steps after the commit.
868 * This is not perfect - but a workable solution until we found the reason for the problem.
870 Term::insertFromTagFieldByItemId($current_post);
871 Term::insertFromFileFieldByItemId($current_post);
873 if ($item['parent-uri'] === $item['uri']) {
874 self::addShadow($current_post);
876 self::addShadowPost($current_post);
879 check_user_notification($current_post);
882 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", $notify_type, $current_post);
883 } elseif (!empty($parent) && $parent['origin']) {
884 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "Notifier", "comment-import", $current_post);
887 return $current_post;
891 * @brief Distributes public items to the receivers
893 * @param integer $itemid Item ID that should be added
894 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
896 public static function distribute($itemid, $signed_text = '')
898 $condition = ["`id` IN (SELECT `parent` FROM `item` WHERE `id` = ?)", $itemid];
899 $parent = dba::selectFirst('item', ['owner-id'], $condition);
900 if (!DBM::is_result($parent)) {
904 // Only distribute public items from native networks
905 $condition = ['id' => $itemid, 'uid' => 0,
906 'network' => [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""],
907 'visible' => true, 'deleted' => false, 'moderated' => false, 'private' => false];
908 $item = dba::selectFirst('item', [], ['id' => $itemid]);
909 if (!DBM::is_result($item)) {
914 unset($item['parent']);
915 unset($item['mention']);
916 unset($item['wall']);
917 unset($item['origin']);
918 unset($item['starred']);
919 unset($item['rendered-hash']);
920 unset($item['rendered-html']);
924 $condition = ["`nurl` IN (SELECT `nurl` FROM `contact` WHERE `id` = ?) AND `uid` != 0 AND NOT `blocked` AND `rel` IN (?, ?)",
925 $parent['owner-id'], CONTACT_IS_SHARING, CONTACT_IS_FRIEND];
926 $contacts = dba::select('contact', ['uid'], $condition);
927 while ($contact = dba::fetch($contacts)) {
928 $users[$contact['uid']] = $contact['uid'];
933 if ($item['uri'] != $item['parent-uri']) {
934 $parents = dba::select('item', ['uid', 'origin'], ["`uri` = ? AND `uid` != 0", $item['parent-uri']]);
935 while ($parent = dba::fetch($parents)) {
936 $users[$parent['uid']] = $parent['uid'];
937 if ($parent['origin'] && !$item['origin']) {
938 $origin_uid = $parent['uid'];
943 foreach ($users as $uid) {
944 if ($origin_uid == $uid) {
945 $item['diaspora_signed_text'] = $signed_text;
947 self::storeForUser($itemid, $item, $uid);
952 * @brief Store public items for the receivers
954 * @param integer $itemid Item ID that should be added
955 * @param array $item The item entry that will be stored
956 * @param integer $uid The user that will receive the item entry
958 private static function storeForUser($itemid, $item, $uid)
963 if ($item['uri'] == $item['parent-uri']) {
964 $item['contact-id'] = Contact::getIdForURL($item['owner-link'], $uid);
966 $item['contact-id'] = Contact::getIdForURL($item['author-link'], $uid);
969 if (empty($item['contact-id'])) {
970 $self = dba::selectFirst('contact', ['id'], ['self' => true, 'uid' => $uid]);
971 if (!DBM::is_result($self)) {
974 $item['contact-id'] = $self['id'];
977 if (in_array($item['type'], ["net-comment", "wall-comment"])) {
978 $item['type'] = 'remote-comment';
979 } elseif ($item['type'] == 'wall') {
980 $item['type'] = 'remote';
983 /// @todo Handling of "event-id"
986 if ($item['uri'] == $item['parent-uri']) {
987 $contact = dba::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
988 if (DBM::is_result($contact)) {
989 $notify = self::isRemoteSelf($contact, $item);
993 $distributed = self::insert($item, false, $notify, true);
996 logger("Distributed public item " . $itemid . " for user " . $uid . " wasn't stored", LOGGER_DEBUG);
998 logger("Distributed public item " . $itemid . " for user " . $uid . " with id " . $distributed, LOGGER_DEBUG);
1003 * @brief Add a shadow entry for a given item id that is a thread starter
1005 * We store every public item entry additionally with the user id "0".
1006 * This is used for the community page and for the search.
1007 * It is planned that in the future we will store public item entries only once.
1009 * @param integer $itemid Item ID that should be added
1011 public static function addShadow($itemid)
1013 $fields = ['uid', 'private', 'moderated', 'visible', 'deleted', 'network'];
1014 $condition = ['id' => $itemid, 'parent' => [0, $itemid]];
1015 $item = dba::selectFirst('item', $fields, $condition);
1017 if (!DBM::is_result($item)) {
1021 // is it already a copy?
1022 if (($itemid == 0) || ($item['uid'] == 0)) {
1026 // Is it a visible public post?
1027 if (!$item["visible"] || $item["deleted"] || $item["moderated"] || $item["private"]) {
1031 // is it an entry from a connector? Only add an entry for natively connected networks
1032 if (!in_array($item["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""])) {
1036 $item = dba::selectFirst('item', [], ['id' => $itemid]);
1038 if (DBM::is_result($item) && ($item["allow_cid"] == '') && ($item["allow_gid"] == '') &&
1039 ($item["deny_cid"] == '') && ($item["deny_gid"] == '')) {
1041 if (!dba::exists('item', ['uri' => $item['uri'], 'uid' => 0])) {
1042 // Preparing public shadow (removing user specific data)
1045 unset($item['parent']);
1046 unset($item['wall']);
1047 unset($item['mention']);
1048 unset($item['origin']);
1049 unset($item['starred']);
1050 unset($item['rendered-hash']);
1051 unset($item['rendered-html']);
1052 if ($item['uri'] == $item['parent-uri']) {
1053 $item['contact-id'] = Contact::getIdForURL($item['owner-link']);
1055 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
1058 if (in_array($item['type'], ["net-comment", "wall-comment"])) {
1059 $item['type'] = 'remote-comment';
1060 } elseif ($item['type'] == 'wall') {
1061 $item['type'] = 'remote';
1064 $public_shadow = self::insert($item, false, false, true);
1066 logger("Stored public shadow for thread ".$itemid." under id ".$public_shadow, LOGGER_DEBUG);
1072 * @brief Add a shadow entry for a given item id that is a comment
1074 * This function does the same like the function above - but for comments
1076 * @param integer $itemid Item ID that should be added
1078 public static function addShadowPost($itemid)
1080 $item = dba::selectFirst('item', [], ['id' => $itemid]);
1081 if (!DBM::is_result($item)) {
1085 // Is it a toplevel post?
1086 if ($item['id'] == $item['parent']) {
1087 self::addShadow($itemid);
1091 // Is this a shadow entry?
1092 if ($item['uid'] == 0)
1095 // Is there a shadow parent?
1096 if (!dba::exists('item', ['uri' => $item['parent-uri'], 'uid' => 0])) {
1100 // Is there already a shadow entry?
1101 if (dba::exists('item', ['uri' => $item['uri'], 'uid' => 0])) {
1105 // Save "origin" and "parent" state
1106 $origin = $item['origin'];
1107 $parent = $item['parent'];
1109 // Preparing public shadow (removing user specific data)
1112 unset($item['parent']);
1113 unset($item['wall']);
1114 unset($item['mention']);
1115 unset($item['origin']);
1116 unset($item['starred']);
1117 unset($item['rendered-hash']);
1118 unset($item['rendered-html']);
1119 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
1121 if (in_array($item['type'], ["net-comment", "wall-comment"])) {
1122 $item['type'] = 'remote-comment';
1123 } elseif ($item['type'] == 'wall') {
1124 $item['type'] = 'remote';
1127 $public_shadow = self::insert($item, false, false, true);
1129 logger("Stored public shadow for comment ".$item['uri']." under id ".$public_shadow, LOGGER_DEBUG);
1131 // If this was a comment to a Diaspora post we don't get our comment back.
1132 // This means that we have to distribute the comment by ourselves.
1134 if (dba::exists('item', ['id' => $parent, 'network' => NETWORK_DIASPORA])) {
1135 self::distribute($public_shadow);
1141 * Adds a "lang" specification in a "postopts" element of given $arr,
1142 * if possible and not already present.
1143 * Expects "body" element to exist in $arr.
1145 private static function addLanguageInPostopts(&$item)
1147 if (!empty($item['postopts'])) {
1148 if (strstr($item['postopts'], 'lang=')) {
1152 $postopts = $item['postopts'];
1157 $naked_body = Text\BBCode::toPlaintext($item['body'], false);
1159 $languages = (new Text_LanguageDetect())->detect($naked_body, 3);
1161 if (sizeof($languages) > 0) {
1162 if ($postopts != '') {
1163 $postopts .= '&'; // arbitrary separator, to be reviewed
1166 $postopts .= 'lang=';
1169 foreach ($languages as $language => $score) {
1170 $postopts .= $sep . $language . ";" . $score;
1173 $item['postopts'] = $postopts;
1178 * @brief Creates an unique guid out of a given uri
1180 * @param string $uri uri of an item entry
1181 * @param string $host hostname for the GUID prefix
1182 * @return string unique guid
1184 public static function guidFromUri($uri, $host)
1186 // Our regular guid routine is using this kind of prefix as well
1187 // We have to avoid that different routines could accidentally create the same value
1188 $parsed = parse_url($uri);
1190 // We use a hash of the hostname as prefix for the guid
1191 $guid_prefix = hash("crc32", $host);
1193 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
1194 unset($parsed["scheme"]);
1196 // Glue it together to be able to make a hash from it
1197 $host_id = implode("/", $parsed);
1199 // We could use any hash algorithm since it isn't a security issue
1200 $host_hash = hash("ripemd128", $host_id);
1202 return $guid_prefix.$host_hash;
1206 * @brief Set "success_update" and "last-item" to the date of the last time we heard from this contact
1208 * This can be used to filter for inactive contacts.
1209 * Only do this for public postings to avoid privacy problems, since poco data is public.
1210 * Don't set this value if it isn't from the owner (could be an author that we don't know)
1212 * @param array $arr Contains the just posted item record
1214 private static function updateContact($arr)
1216 // Unarchive the author
1217 $contact = dba::selectFirst('contact', [], ['id' => $arr["author-id"]]);
1218 if (DBM::is_result($contact)) {
1219 Contact::unmarkForArchival($contact);
1222 // Unarchive the contact if it's not our own contact
1223 $contact = dba::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
1224 if (DBM::is_result($contact)) {
1225 Contact::unmarkForArchival($contact);
1228 $update = (!$arr['private'] && (($arr["author-link"] === $arr["owner-link"]) || ($arr["parent-uri"] === $arr["uri"])));
1230 // Is it a forum? Then we don't care about the rules from above
1231 if (!$update && ($arr["network"] == NETWORK_DFRN) && ($arr["parent-uri"] === $arr["uri"])) {
1232 if (dba::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
1238 dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
1239 ['id' => $arr['contact-id']]);
1241 // Now do the same for the system wide contacts with uid=0
1242 if (!$arr['private']) {
1243 dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
1244 ['id' => $arr['owner-id']]);
1246 if ($arr['owner-id'] != $arr['author-id']) {
1247 dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
1248 ['id' => $arr['author-id']]);
1253 public static function setHashtags(&$item)
1256 $tags = get_tags($item["body"]);
1259 if (!count($tags)) {
1263 // This sorting is important when there are hashtags that are part of other hashtags
1264 // Otherwise there could be problems with hashtags like #test and #test2
1267 $URLSearchString = "^\[\]";
1269 // All hashtags should point to the home server if "local_tags" is activated
1270 if (Config::get('system', 'local_tags')) {
1271 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1272 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["body"]);
1274 $item["tag"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1275 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["tag"]);
1278 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
1279 $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1281 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
1284 $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
1286 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
1289 $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
1291 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
1294 // Repair recursive urls
1295 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1296 "#$2", $item["body"]);
1298 foreach ($tags as $tag) {
1299 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=')) {
1303 $basetag = str_replace('_',' ',substr($tag,1));
1305 $newtag = '#[url=' . System::baseUrl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1307 $item["body"] = str_replace($tag, $newtag, $item["body"]);
1309 if (!stristr($item["tag"], "/search?tag=" . $basetag . "]" . $basetag . "[/url]")) {
1310 if (strlen($item["tag"])) {
1311 $item["tag"] = ','.$item["tag"];
1313 $item["tag"] = $newtag.$item["tag"];
1317 // Convert back the masked hashtags
1318 $item["body"] = str_replace("#", "#", $item["body"]);
1321 public static function getGuidById($id)
1323 $item = dba::selectFirst('item', ['guid'], ['id' => $id]);
1324 if (DBM::is_result($item)) {
1325 return $item['guid'];
1331 public static function getIdAndNickByGuid($guid, $uid = 0)
1337 $uid == local_user();
1340 // Does the given user have this item?
1342 $item = dba::fetch_first("SELECT `item`.`id`, `user`.`nickname` FROM `item`
1343 INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
1344 WHERE `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
1345 AND `item`.`guid` = ? AND `item`.`uid` = ?", $guid, $uid);
1346 if (DBM::is_result($item)) {
1348 $nick = $item["nickname"];
1352 // Or is it anywhere on the server?
1354 $item = dba::fetch_first("SELECT `item`.`id`, `user`.`nickname` FROM `item`
1355 INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
1356 WHERE `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
1357 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1358 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1359 AND NOT `item`.`private` AND `item`.`wall`
1360 AND `item`.`guid` = ?", $guid);
1361 if (DBM::is_result($item)) {
1363 $nick = $item["nickname"];
1366 return ["nick" => $nick, "id" => $id];
1370 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
1372 * @param int $item_id
1373 * @return bool true if item was deleted, else false
1375 private static function tagDeliver($uid, $item_id)
1379 $user = dba::selectFirst('user', [], ['uid' => $uid]);
1380 if (!DBM::is_result($user)) {
1384 $community_page = (($user['page-flags'] == PAGE_COMMUNITY) ? true : false);
1385 $prvgroup = (($user['page-flags'] == PAGE_PRVGROUP) ? true : false);
1387 $item = dba::selectFirst('item', [], ['id' => $item_id]);
1388 if (!DBM::is_result($item)) {
1392 $link = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
1395 * Diaspora uses their own hardwired link URL in @-tags
1396 * instead of the one we supply with webfinger
1398 $dlink = normalise_link(System::baseUrl() . '/u/' . $user['nickname']);
1400 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
1402 foreach ($matches as $mtch) {
1403 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
1405 logger('mention found: ' . $mtch[2]);
1411 if (($community_page || $prvgroup) &&
1412 !$item['wall'] && !$item['origin'] && ($item['id'] == $item['parent'])) {
1413 // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
1415 logger("no-mention top-level post to community or private group. delete.");
1416 dba::delete('item', ['id' => $item_id]);
1422 $arr = ['item' => $item, 'user' => $user];
1424 Addon::callHooks('tagged', $arr);
1426 if (!$community_page && !$prvgroup) {
1431 * tgroup delivery - setup a second delivery chain
1432 * prevent delivery looping - only proceed
1433 * if the message originated elsewhere and is a top-level post
1435 if ($item['wall'] || $item['origin'] || ($item['id'] != $item['parent'])) {
1439 // now change this copy of the post to a forum head message and deliver to all the tgroup members
1440 $self = dba::selectFirst('contact', ['id', 'name', 'url', 'thumb'], ['uid' => $uid, 'self' => true]);
1441 if (!DBM::is_result($self)) {
1445 $owner_id = Contact::getIdForURL($self['url']);
1447 // also reset all the privacy bits to the forum default permissions
1449 $private = ($user['allow_cid'] || $user['allow_gid'] || $user['deny_cid'] || $user['deny_gid']) ? 1 : 0;
1451 $forum_mode = ($prvgroup ? 2 : 1);
1453 $fields = ['wall' => true, 'origin' => true, 'forum_mode' => $forum_mode, 'contact-id' => $self['id'],
1454 'owner-id' => $owner_id, 'owner-name' => $self['name'], 'owner-link' => $self['url'],
1455 'owner-avatar' => $self['thumb'], 'private' => $private, 'allow_cid' => $user['allow_cid'],
1456 'allow_gid' => $user['allow_gid'], 'deny_cid' => $user['deny_cid'], 'deny_gid' => $user['deny_gid']];
1457 dba::update('item', $fields, ['id' => $item_id]);
1459 self::updateThread($item_id);
1461 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', 'tgroup', $item_id);
1464 public static function isRemoteSelf($contact, &$datarray)
1468 if (!$contact['remote_self']) {
1472 // Prevent the forwarding of posts that are forwarded
1473 if ($datarray["extid"] == NETWORK_DFRN) {
1474 logger('Already forwarded', LOGGER_DEBUG);
1478 // Prevent to forward already forwarded posts
1479 if ($datarray["app"] == $a->get_hostname()) {
1480 logger('Already forwarded (second test)', LOGGER_DEBUG);
1484 // Only forward posts
1485 if ($datarray["verb"] != ACTIVITY_POST) {
1486 logger('No post', LOGGER_DEBUG);
1490 if (($contact['network'] != NETWORK_FEED) && $datarray['private']) {
1491 logger('Not public', LOGGER_DEBUG);
1495 $datarray2 = $datarray;
1496 logger('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), LOGGER_DEBUG);
1497 if ($contact['remote_self'] == 2) {
1498 $self = dba::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
1499 ['uid' => $contact['uid'], 'self' => true]);
1500 if (DBM::is_result($self)) {
1501 $datarray['contact-id'] = $self["id"];
1503 $datarray['owner-name'] = $self["name"];
1504 $datarray['owner-link'] = $self["url"];
1505 $datarray['owner-avatar'] = $self["thumb"];
1507 $datarray['author-name'] = $datarray['owner-name'];
1508 $datarray['author-link'] = $datarray['owner-link'];
1509 $datarray['author-avatar'] = $datarray['owner-avatar'];
1511 unset($datarray['created']);
1512 unset($datarray['edited']);
1514 unset($datarray['network']);
1515 unset($datarray['owner-id']);
1516 unset($datarray['author-id']);
1519 if ($contact['network'] != NETWORK_FEED) {
1520 $datarray["guid"] = get_guid(32);
1521 unset($datarray["plink"]);
1522 $datarray["uri"] = item_new_uri($a->get_hostname(), $contact['uid'], $datarray["guid"]);
1523 $datarray["parent-uri"] = $datarray["uri"];
1524 $datarray["thr-parent"] = $datarray["uri"];
1525 $datarray["extid"] = NETWORK_DFRN;
1526 $urlpart = parse_url($datarray2['author-link']);
1527 $datarray["app"] = $urlpart["host"];
1529 $datarray['private'] = 0;
1533 if ($contact['network'] != NETWORK_FEED) {
1534 // Store the original post
1535 $result = self::insert($datarray2, false, false);
1536 logger('remote-self post original item - Contact '.$contact['url'].' return '.$result.' Item '.print_r($datarray2, true), LOGGER_DEBUG);
1538 $datarray["app"] = "Feed";
1542 // Trigger automatic reactions for addons
1543 $datarray['api_source'] = true;
1545 // We have to tell the hooks who we are - this really should be improved
1546 $_SESSION["authenticated"] = true;
1547 $_SESSION["uid"] = $contact['uid'];
1556 * @param array $item
1560 public static function fixPrivatePhotos($s, $uid, $item = null, $cid = 0)
1562 if (Config::get('system', 'disable_embedded')) {
1566 logger('check for photos', LOGGER_DEBUG);
1567 $site = substr(System::baseUrl(), strpos(System::baseUrl(), '://'));
1572 $img_start = strpos($orig_body, '[img');
1573 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
1574 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
1576 while (($img_st_close !== false) && ($img_len !== false)) {
1577 $img_st_close++; // make it point to AFTER the closing bracket
1578 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
1580 logger('found photo ' . $image, LOGGER_DEBUG);
1582 if (stristr($image, $site . '/photo/')) {
1583 // Only embed locally hosted photos
1585 $i = basename($image);
1586 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
1587 $x = strpos($i, '-');
1590 $res = substr($i, $x + 1);
1591 $i = substr($i, 0, $x);
1592 $fields = ['data', 'type', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'];
1593 $photo = dba::selectFirst('photo', $fields, ['resource-id' => $i, 'scale' => $res, 'uid' => $uid]);
1594 if (DBM::is_result($photo)) {
1596 * Check to see if we should replace this photo link with an embedded image
1597 * 1. No need to do so if the photo is public
1598 * 2. If there's a contact-id provided, see if they're in the access list
1599 * for the photo. If so, embed it.
1600 * 3. Otherwise, if we have an item, see if the item permissions match the photo
1601 * permissions, regardless of order but first check to see if they're an exact
1602 * match to save some processing overhead.
1604 if (self::hasPermissions($photo)) {
1606 $recips = self::enumeratePermissions($photo);
1607 if (in_array($cid, $recips)) {
1611 if (self::samePermissions($item, $photo)) {
1617 $data = $photo['data'];
1618 $type = $photo['type'];
1620 // If a custom width and height were specified, apply before embedding
1621 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
1622 logger('scaling photo', LOGGER_DEBUG);
1624 $width = intval($match[1]);
1625 $height = intval($match[2]);
1627 $Image = new Image($data, $type);
1628 if ($Image->isValid()) {
1629 $Image->scaleDown(max($width, $height));
1630 $data = $Image->asString();
1631 $type = $Image->getType();
1635 logger('replacing photo', LOGGER_DEBUG);
1636 $image = 'data:' . $type . ';base64,' . base64_encode($data);
1637 logger('replaced: ' . $image, LOGGER_DATA);
1643 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
1644 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
1645 if ($orig_body === false) {
1649 $img_start = strpos($orig_body, '[img');
1650 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
1651 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
1654 $new_body = $new_body . $orig_body;
1659 private static function hasPermissions($obj)
1663 x($obj, 'allow_cid')
1665 x($obj, 'allow_gid')
1674 private static function samePermissions($obj1, $obj2)
1676 // first part is easy. Check that these are exactly the same.
1677 if (($obj1['allow_cid'] == $obj2['allow_cid'])
1678 && ($obj1['allow_gid'] == $obj2['allow_gid'])
1679 && ($obj1['deny_cid'] == $obj2['deny_cid'])
1680 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
1684 // This is harder. Parse all the permissions and compare the resulting set.
1685 $recipients1 = self::enumeratePermissions($obj1);
1686 $recipients2 = self::enumeratePermissions($obj2);
1690 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
1691 return ($recipients1 == $recipients2);
1694 // returns an array of contact-ids that are allowed to see this object
1695 private static function enumeratePermissions($obj)
1697 $allow_people = expand_acl($obj['allow_cid']);
1698 $allow_groups = Group::expand(expand_acl($obj['allow_gid']));
1699 $deny_people = expand_acl($obj['deny_cid']);
1700 $deny_groups = Group::expand(expand_acl($obj['deny_gid']));
1701 $recipients = array_unique(array_merge($allow_people, $allow_groups));
1702 $deny = array_unique(array_merge($deny_people, $deny_groups));
1703 $recipients = array_diff($recipients, $deny);
1707 public static function getFeedTags($item)
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[2][$x]] = ['#', $matches[1][$x], $matches[2][$x]];
1720 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
1722 for ($x = 0; $x < $cnt; $x ++) {
1723 if ($matches[1][$x]) {
1724 $ret[] = ['@', $matches[1][$x], $matches[2][$x]];
1731 public static function expire($uid, $days, $network = "", $force = false)
1733 if (!$uid || ($days < 1)) {
1738 * $expire_network_only = save your own wall posts
1739 * and just expire conversations started by others
1741 $expire_network_only = PConfig::get($uid,'expire', 'network_only');
1742 $sql_extra = (intval($expire_network_only) ? " AND wall = 0 " : "");
1744 if ($network != "") {
1745 $sql_extra .= sprintf(" AND network = '%s' ", dbesc($network));
1748 * There is an index "uid_network_received" but not "uid_network_created"
1749 * This avoids the creation of another index just for one purpose.
1750 * And it doesn't really matter wether to look at "received" or "created"
1752 $range = "AND `received` < UTC_TIMESTAMP() - INTERVAL %d DAY ";
1754 $range = "AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY ";
1757 $r = q("SELECT `file`, `resource-id`, `starred`, `type`, `id` FROM `item`
1758 WHERE `uid` = %d $range
1766 if (!DBM::is_result($r)) {
1770 $expire_items = PConfig::get($uid, 'expire', 'items', 1);
1772 // Forcing expiring of items - but not notes and marked items
1774 $expire_items = true;
1777 $expire_notes = PConfig::get($uid, 'expire', 'notes', 1);
1778 $expire_starred = PConfig::get($uid, 'expire', 'starred', 1);
1779 $expire_photos = PConfig::get($uid, 'expire', 'photos', 0);
1781 logger('User '.$uid.': expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
1783 foreach ($r as $item) {
1785 // don't expire filed items
1787 if (strpos($item['file'],'[') !== false) {
1791 // Only expire posts, not photos and photo comments
1793 if ($expire_photos == 0 && strlen($item['resource-id'])) {
1795 } elseif ($expire_starred == 0 && intval($item['starred'])) {
1797 } elseif ($expire_notes == 0 && $item['type'] == 'note') {
1799 } elseif ($expire_items == 0 && $item['type'] != 'note') {
1803 self::deleteById($item['id'], PRIORITY_LOW);
1807 public static function firstPostDate($uid, $wall = false)
1809 $condition = ['uid' => $uid, 'wall' => $wall, 'deleted' => false, 'visible' => true, 'moderated' => false];
1810 $params = ['order' => ['created' => false]];
1811 $thread = dba::selectFirst('thread', ['created'], $condition, $params);
1812 if (DBM::is_result($thread)) {
1813 return substr(DateTimeFormat::local($thread['created']), 0, 10);
1819 * @brief add/remove activity to an item
1821 * Toggle activities as like,dislike,attend of an item
1823 * @param string $item_id
1824 * @param string $verb
1825 * Activity verb. One of
1826 * like, unlike, dislike, undislike, attendyes, unattendyes,
1827 * attendno, unattendno, attendmaybe, unattendmaybe
1828 * @hook 'post_local_end'
1830 * 'post_id' => ID of posted item
1832 public static function performLike($item_id, $verb)
1834 if (!local_user() && !remote_user()) {
1841 $bodyverb = L10n::t('%1$s likes %2$s\'s %3$s');
1842 $activity = ACTIVITY_LIKE;
1846 $bodyverb = L10n::t('%1$s doesn\'t like %2$s\'s %3$s');
1847 $activity = ACTIVITY_DISLIKE;
1851 $bodyverb = L10n::t('%1$s is attending %2$s\'s %3$s');
1852 $activity = ACTIVITY_ATTEND;
1856 $bodyverb = L10n::t('%1$s is not attending %2$s\'s %3$s');
1857 $activity = ACTIVITY_ATTENDNO;
1860 case 'unattendmaybe':
1861 $bodyverb = L10n::t('%1$s may attend %2$s\'s %3$s');
1862 $activity = ACTIVITY_ATTENDMAYBE;
1865 logger('like: unknown verb ' . $verb . ' for item ' . $item_id);
1869 // Enable activity toggling instead of on/off
1870 $event_verb_flag = $activity === ACTIVITY_ATTEND || $activity === ACTIVITY_ATTENDNO || $activity === ACTIVITY_ATTENDMAYBE;
1872 logger('like: verb ' . $verb . ' item ' . $item_id);
1874 $item = dba::selectFirst('item', [], ['`id` = ? OR `uri` = ?', $item_id, $item_id]);
1875 if (!DBM::is_result($item)) {
1876 logger('like: unknown item ' . $item_id);
1880 $uid = $item['uid'];
1881 if (($uid == 0) && local_user()) {
1882 $uid = local_user();
1885 if (!can_write_wall($uid)) {
1886 logger('like: unable to write on wall ' . $uid);
1890 // Retrieves the local post owner
1891 $owner_self_contact = dba::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
1892 if (!DBM::is_result($owner_self_contact)) {
1893 logger('like: unknown owner ' . $uid);
1897 // Retrieve the current logged in user's public contact
1898 $author_id = public_contact();
1900 $author_contact = dba::selectFirst('contact', [], ['id' => $author_id]);
1901 if (!DBM::is_result($author_contact)) {
1902 logger('like: unknown author ' . $author_id);
1906 // Contact-id is the uid-dependant author contact
1907 if (local_user() == $uid) {
1908 $item_contact_id = $owner_self_contact['id'];
1909 $item_contact = $owner_self_contact;
1911 $item_contact_id = Contact::getIdForURL($author_contact['url'], $uid, true);
1912 $item_contact = dba::selectFirst('contact', [], ['id' => $item_contact_id]);
1913 if (!DBM::is_result($item_contact)) {
1914 logger('like: unknown item contact ' . $item_contact_id);
1919 // Look for an existing verb row
1920 // event participation are essentially radio toggles. If you make a subsequent choice,
1921 // we need to eradicate your first choice.
1922 if ($event_verb_flag) {
1923 $verbs = "'" . dbesc(ACTIVITY_ATTEND) . "', '" . dbesc(ACTIVITY_ATTENDNO) . "', '" . dbesc(ACTIVITY_ATTENDMAYBE) . "'";
1925 $verbs = "'".dbesc($activity)."'";
1928 /// @todo This query is expected to be a performance eater due to the "OR" - it has to be changed totally
1929 $existing_like = q("SELECT `id`, `guid`, `verb` FROM `item`
1930 WHERE `verb` IN ($verbs)
1932 AND `author-id` = %d
1934 AND (`parent` = '%s' OR `parent-uri` = '%s' OR `thr-parent` = '%s')
1936 intval($author_contact['id']),
1937 intval($item['uid']),
1938 dbesc($item_id), dbesc($item_id), dbesc($item['uri'])
1941 // If it exists, mark it as deleted
1942 if (DBM::is_result($existing_like)) {
1943 $like_item = $existing_like[0];
1945 // Already voted, undo it
1946 $fields = ['deleted' => true, 'unseen' => true, 'changed' => DateTimeFormat::utcNow()];
1947 dba::update('item', $fields, ['id' => $like_item['id']]);
1949 // Clean up the Diaspora signatures for this like
1950 // Go ahead and do it even if Diaspora support is disabled. We still want to clean up
1951 // if it had been enabled in the past
1952 dba::delete('sign', ['iid' => $like_item['id']]);
1954 $like_item_id = $like_item['id'];
1955 Worker::add(PRIORITY_HIGH, "Notifier", "like", $like_item_id);
1957 if (!$event_verb_flag || $like_item['verb'] == $activity) {
1962 // Verb is "un-something", just trying to delete existing entries
1963 if (strpos($verb, 'un') === 0) {
1967 // Else or if event verb different from existing row, create a new item row
1968 $post_type = (($item['resource-id']) ? L10n::t('photo') : L10n::t('status'));
1969 if ($item['object-type'] === ACTIVITY_OBJ_EVENT) {
1970 $post_type = L10n::t('event');
1972 $objtype = $item['resource-id'] ? ACTIVITY_OBJ_IMAGE : ACTIVITY_OBJ_NOTE ;
1973 $link = xmlify('<link rel="alternate" type="text/html" href="' . System::baseUrl() . '/display/' . $owner_self_contact['nick'] . '/' . $item['id'] . '" />' . "\n") ;
1974 $body = $item['body'];
1979 <type>$objtype</type>
1981 <id>{$item['uri']}</id>
1984 <content>$body</content>
1988 $ulink = '[url=' . $author_contact['url'] . ']' . $author_contact['name'] . '[/url]';
1989 $alink = '[url=' . $item['author-link'] . ']' . $item['author-name'] . '[/url]';
1990 $plink = '[url=' . System::baseUrl() . '/display/' . $owner_self_contact['nick'] . '/' . $item['id'] . ']' . $post_type . '[/url]';
1993 'guid' => get_guid(32),
1994 'uri' => item_new_uri(self::getApp()->get_hostname(), $item['uid']),
1995 'uid' => $item['uid'],
1996 'contact-id' => $item_contact_id,
1997 'type' => 'activity',
1998 'wall' => $item['wall'],
2000 'gravity' => GRAVITY_LIKE,
2001 'parent' => $item['id'],
2002 'parent-uri' => $item['uri'],
2003 'thr-parent' => $item['uri'],
2004 'owner-id' => $item['owner-id'],
2005 'owner-name' => $item['owner-name'],
2006 'owner-link' => $item['owner-link'],
2007 'owner-avatar' => $item['owner-avatar'],
2008 'author-id' => $author_contact['id'],
2009 'author-name' => $author_contact['name'],
2010 'author-link' => $author_contact['url'],
2011 'author-avatar' => $author_contact['thumb'],
2012 'body' => sprintf($bodyverb, $ulink, $alink, $plink),
2013 'verb' => $activity,
2014 'object-type' => $objtype,
2016 'allow_cid' => $item['allow_cid'],
2017 'allow_gid' => $item['allow_gid'],
2018 'deny_cid' => $item['deny_cid'],
2019 'deny_gid' => $item['deny_gid'],
2024 $new_item_id = self::insert($new_item);
2026 // If the parent item isn't visible then set it to visible
2027 if (!$item['visible']) {
2028 self::update(['visible' => true], ['id' => $item['id']]);
2031 // Save the author information for the like in case we need to relay to Diaspora
2032 Diaspora::storeLikeSignature($item_contact, $new_item_id);
2034 $new_item['id'] = $new_item_id;
2036 Addon::callHooks('post_local_end', $new_item);
2038 Worker::add(PRIORITY_HIGH, "Notifier", "like", $new_item_id);
2043 private static function addThread($itemid, $onlyshadow = false)
2045 $fields = ['uid', 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private', 'pubmail',
2046 'moderated', 'visible', 'spam', 'starred', 'bookmark', 'contact-id',
2047 'deleted', 'origin', 'forum_mode', 'mention', 'network', 'author-id', 'owner-id'];
2048 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
2049 $item = dba::selectFirst('item', $fields, $condition);
2051 if (!DBM::is_result($item)) {
2055 $item['iid'] = $itemid;
2058 $result = dba::insert('thread', $item);
2060 logger("Add thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
2064 private static function updateThread($itemid, $setmention = false)
2066 $fields = ['uid', 'guid', 'title', 'body', 'created', 'edited', 'commented', 'received', 'changed',
2067 'wall', 'private', 'pubmail', 'moderated', 'visible', 'spam', 'starred', 'bookmark', 'contact-id',
2068 'deleted', 'origin', 'forum_mode', 'network', 'author-id', 'owner-id', 'rendered-html', 'rendered-hash'];
2069 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
2071 $item = dba::selectFirst('item', $fields, $condition);
2072 if (!DBM::is_result($item)) {
2077 $item["mention"] = 1;
2084 foreach ($item as $field => $data) {
2085 if (!in_array($field, ["guid", "title", "body", "rendered-html", "rendered-hash"])) {
2086 $fields[$field] = $data;
2090 $result = dba::update('thread', $fields, ['iid' => $itemid]);
2092 logger("Update thread for item ".$itemid." - guid ".$item["guid"]." - ".(int)$result, LOGGER_DEBUG);
2094 // Updating a shadow item entry
2095 $items = dba::selectFirst('item', ['id'], ['guid' => $item['guid'], 'uid' => 0]);
2097 if (!DBM::is_result($items)) {
2101 $fields = ['title' => $item['title'], 'body' => $item['body'],
2102 'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']];
2103 $result = dba::update('item', $fields, ['id' => $items['id']]);
2105 logger("Updating public shadow for post ".$items["id"]." - guid ".$item["guid"]." Result: ".print_r($result, true), LOGGER_DEBUG);
2108 private static function deleteThread($itemid, $itemuri = "")
2110 $item = dba::selectFirst('thread', ['uid'], ['iid' => $itemid]);
2111 if (!DBM::is_result($item)) {
2112 logger('No thread found for id '.$itemid, LOGGER_DEBUG);
2116 // Using dba::delete at this time could delete the associated item entries
2117 $result = dba::e("DELETE FROM `thread` WHERE `iid` = ?", $itemid);
2119 logger("deleteThread: Deleted thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
2121 if ($itemuri != "") {
2122 $condition = ["`uri` = ? AND NOT `deleted` AND NOT (`uid` IN (?, 0))", $itemuri, $item["uid"]];
2123 if (!dba::exists('item', $condition)) {
2124 dba::delete('item', ['uri' => $itemuri, 'uid' => 0]);
2125 logger("deleteThread: Deleted shadow for item ".$itemuri, LOGGER_DEBUG);