4 * @file src/Model/Item.php
7 namespace Friendica\Model;
9 use Friendica\BaseObject;
10 use Friendica\Core\Addon;
11 use Friendica\Core\Config;
12 use Friendica\Core\L10n;
13 use Friendica\Core\PConfig;
14 use Friendica\Core\System;
15 use Friendica\Core\Worker;
16 use Friendica\Database\DBM;
17 use Friendica\Model\Contact;
18 use Friendica\Model\Conversation;
19 use Friendica\Model\GContact;
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;
27 use Text_LanguageDetect;
29 require_once 'boot.php';
30 require_once 'include/items.php';
31 require_once 'include/text.php';
32 require_once 'include/event.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 $success = dba::update('item', $fields, $condition);
61 $rows = dba::affected_rows();
63 // We cannot simply expand the condition to check for origin entries
64 // The condition needn't to be a simple array but could be a complex condition.
65 $items = dba::select('item', ['id', 'origin'], $condition);
66 while ($item = dba::fetch($items)) {
67 Term::insertFromTagFieldByItemId($item['id']);
68 Term::insertFromFileFieldByItemId($item['id']);
69 self::updateThread($item['id']);
71 // We only need to notfiy others when it is an original entry from us
72 if ($item['origin']) {
73 Worker::add(PRIORITY_HIGH, "Notifier", 'edit_post', $item['id']);
81 * @brief Delete an item and notify others about it - if it was ours
83 * @param array $condition The condition for finding the item entries
84 * @param integer $priority Priority for the notification
86 public static function delete($condition, $priority = PRIORITY_HIGH)
88 $items = dba::select('item', ['id'], $condition);
89 while ($item = dba::fetch($items)) {
90 self::deleteById($item['id'], $priority);
96 * @brief Delete an item and notify others about it - if it was ours
98 * @param integer $item_id Item ID that should be delete
99 * @param integer $priority Priority for the notification
101 * @return $boolean success
103 public static function deleteById($item_id, $priority = PRIORITY_HIGH)
105 // locate item to be deleted
106 $fields = ['id', 'uid', 'parent', 'parent-uri', 'origin', 'deleted',
107 'file', 'resource-id', 'event-id', 'attach',
108 'verb', 'object-type', 'object', 'target', 'contact-id'];
109 $item = dba::selectFirst('item', $fields, ['id' => $item_id]);
110 if (!DBM::is_result($item)) {
114 if ($item['deleted']) {
118 $parent = dba::selectFirst('item', ['origin'], ['id' => $item['parent']]);
119 if (!DBM::is_result($parent)) {
120 $parent = ['origin' => false];
123 logger('delete item: ' . $item['id'], LOGGER_DEBUG);
125 // clean up categories and tags so they don't end up as orphans
128 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
130 foreach ($matches as $mtch) {
131 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],true);
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],false);
145 * If item is a link to a photo resource, nuke all the associated photos
146 * (visitors will not have photo resources)
147 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
148 * generate a resource-id and therefore aren't intimately linked to the item.
150 if (strlen($item['resource-id'])) {
151 dba::delete('photo', ['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
154 // If item is a link to an event, delete the event.
155 if (intval($item['event-id'])) {
156 event_delete($item['event-id']);
159 // If item has attachments, drop them
160 foreach (explode(", ", $item['attach']) as $attach) {
161 preg_match("|attach/(\d+)|", $attach, $matches);
162 dba::delete('attach', ['id' => $matches[1], 'uid' => $item['uid']]);
165 // Delete tags that had been attached to other items
166 self::deleteTagsFromItem($item);
168 // Set the item to "deleted"
169 dba::update('item', ['deleted' => true, 'title' => '', 'body' => '',
170 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()],
171 ['id' => $item['id']]);
173 Term::insertFromTagFieldByItemId($item['id']);
174 Term::insertFromFileFieldByItemId($item['id']);
175 self::deleteThread($item['id'], $item['parent-uri']);
177 // If it's the parent of a comment thread, kill all the kids
178 if ($item['id'] == $item['parent']) {
179 self::delete(['parent' => $item['parent']], $priority);
182 // send the notification upstream/downstream
183 if ($item['origin'] || $parent['origin']) {
184 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", "drop", intval($item['id']));
190 private static function deleteTagsFromItem($item)
192 if (($item["verb"] != ACTIVITY_TAG) || ($item["object-type"] != ACTIVITY_OBJ_TAGTERM)) {
196 $xo = XML::parseString($item["object"], false);
197 $xt = XML::parseString($item["target"], false);
199 if ($xt->type != ACTIVITY_OBJ_NOTE) {
203 $i = dba::selectFirst('item', ['id', 'contact-id', 'tag'], ['uri' => $xt->id, 'uid' => $item['uid']]);
204 if (!DBM::is_result($i)) {
208 // For tags, the owner cannot remove the tag on the author's copy of the post.
209 $owner_remove = ($item["contact-id"] == $i["contact-id"]);
210 $author_copy = $item["origin"];
212 if (($owner_remove && $author_copy) || !$owner_remove) {
216 $tags = explode(',', $i["tag"]);
219 foreach ($tags as $tag) {
220 if (trim($tag) !== trim($xo->body)) {
221 $newtags[] = trim($tag);
225 self::update(['tag' => implode(',', $newtags)], ['id' => $i["id"]]);
228 public static function insert($arr, $force_parent = false, $notify = false, $dontcache = false)
232 // If it is a posting where users should get notifications, then define it as wall posting
235 $arr['type'] = 'wall';
237 $arr['network'] = NETWORK_DFRN;
238 $arr['protocol'] = PROTOCOL_DFRN;
240 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
241 // In difference to the call to "self::guidFromUri" several lines below we add the hash of our own host.
242 // This is done because our host is the original creator of the post.
243 if (!isset($arr['guid'])) {
244 if (isset($arr['plink'])) {
245 $arr['guid'] = self::guidFromUri($arr['plink'], $a->get_hostname());
246 } elseif (isset($arr['uri'])) {
247 $arr['guid'] = self::guidFromUri($arr['uri'], $a->get_hostname());
251 $arr['network'] = trim(defaults($arr, 'network', NETWORK_PHANTOM));
256 } elseif ((trim($arr['guid']) == "") && (trim($arr['plink']) != "")) {
257 $arr['guid'] = self::guidFromUri($arr['plink']);
258 } elseif ((trim($arr['guid']) == "") && (trim($arr['uri']) != "")) {
259 $arr['guid'] = self::guidFromUri($arr['uri']);
261 $parsed = parse_url($arr["author-link"]);
262 $guid_prefix = hash("crc32", $parsed["host"]);
265 $arr['guid'] = notags(trim(defaults($arr, 'guid', get_guid(32, $guid_prefix))));
266 /// @todo Declare $uid variable - Rabuzarus - 2018-02-12.
267 $arr['uri'] = notags(trim(defaults($arr, 'uri', item_new_uri($a->get_hostname(), $uid, $arr['guid']))));
269 // Store conversation data
270 $arr = Conversation::insert($arr);
273 * If a Diaspora signature structure was passed in, pull it out of the
274 * item array and set it aside for later storage.
278 if (x($arr, 'dsprsig')) {
279 $encoded_signature = $arr['dsprsig'];
280 $dsprsig = json_decode(base64_decode($arr['dsprsig']));
281 unset($arr['dsprsig']);
284 // Converting the plink
285 /// @TODO Check if this is really still needed
286 if ($arr['network'] == NETWORK_OSTATUS) {
287 if (isset($arr['plink'])) {
288 $arr['plink'] = OStatus::convertHref($arr['plink']);
289 } elseif (isset($arr['uri'])) {
290 $arr['plink'] = OStatus::convertHref($arr['uri']);
294 if (x($arr, 'gravity')) {
295 $arr['gravity'] = intval($arr['gravity']);
296 } elseif ($arr['parent-uri'] === $arr['uri']) {
298 } elseif (activity_match($arr['verb'],ACTIVITY_POST)) {
301 $arr['gravity'] = 6; // extensible catchall
304 $arr['type'] = defaults($arr, 'type', 'remote');
306 $uid = intval($arr['uid']);
308 // check for create date and expire time
309 $expire_interval = Config::get('system', 'dbclean-expire-days', 0);
311 $user = dba::selectFirst('user', ['expire'], ['uid' => $uid]);
312 if (DBM::is_result($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
313 $expire_interval = $user['expire'];
316 if (($expire_interval > 0) && !empty($arr['created'])) {
317 $expire_date = time() - ($expire_interval * 86400);
318 $created_date = strtotime($arr['created']);
319 if ($created_date < $expire_date) {
320 logger('item-store: item created ('.date('c', $created_date).') before expiration time ('.date('c', $expire_date).'). ignored. ' . print_r($arr,true), LOGGER_DEBUG);
326 * Do we already have this item?
327 * We have to check several networks since Friendica posts could be repeated
328 * via OStatus (maybe Diasporsa as well)
330 if (in_array($arr['network'], [NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS, ""])) {
331 $r = q("SELECT `id`, `network` FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `network` IN ('%s', '%s', '%s') LIMIT 1",
332 dbesc(trim($arr['uri'])),
334 dbesc(NETWORK_DIASPORA),
336 dbesc(NETWORK_OSTATUS)
338 if (DBM::is_result($r)) {
339 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
341 logger("Item with uri ".$arr['uri']." already existed for user ".$uid." with id ".$r[0]["id"]." target network ".$r[0]["network"]." - new network: ".$arr['network']);
348 self::addLanguageInPostopts($arr);
350 $arr['wall'] = intval(defaults($arr, 'wall', 0));
351 $arr['extid'] = trim(defaults($arr, 'extid', ''));
352 $arr['author-name'] = trim(defaults($arr, 'author-name', ''));
353 $arr['author-link'] = trim(defaults($arr, 'author-link', ''));
354 $arr['author-avatar'] = trim(defaults($arr, 'author-avatar', ''));
355 $arr['owner-name'] = trim(defaults($arr, 'owner-name', ''));
356 $arr['owner-link'] = trim(defaults($arr, 'owner-link', ''));
357 $arr['owner-avatar'] = trim(defaults($arr, 'owner-avatar', ''));
358 $arr['received'] = ((x($arr, 'received') !== false) ? DateTimeFormat::utc($arr['received']) : DateTimeFormat::utcNow());
359 $arr['created'] = ((x($arr, 'created') !== false) ? DateTimeFormat::utc($arr['created']) : $arr['received']);
360 $arr['edited'] = ((x($arr, 'edited') !== false) ? DateTimeFormat::utc($arr['edited']) : $arr['created']);
361 $arr['changed'] = ((x($arr, 'changed') !== false) ? DateTimeFormat::utc($arr['changed']) : $arr['created']);
362 $arr['commented'] = ((x($arr, 'commented') !== false) ? DateTimeFormat::utc($arr['commented']) : $arr['created']);
363 $arr['title'] = trim(defaults($arr, 'title', ''));
364 $arr['location'] = trim(defaults($arr, 'location', ''));
365 $arr['coord'] = trim(defaults($arr, 'coord', ''));
366 $arr['visible'] = ((x($arr, 'visible') !== false) ? intval($arr['visible']) : 1);
368 $arr['parent-uri'] = trim(defaults($arr, 'parent-uri', $arr['uri']));
369 $arr['verb'] = trim(defaults($arr, 'verb', ''));
370 $arr['object-type'] = trim(defaults($arr, 'object-type', ''));
371 $arr['object'] = trim(defaults($arr, 'object', ''));
372 $arr['target-type'] = trim(defaults($arr, 'target-type', ''));
373 $arr['target'] = trim(defaults($arr, 'target', ''));
374 $arr['plink'] = trim(defaults($arr, 'plink', ''));
375 $arr['allow_cid'] = trim(defaults($arr, 'allow_cid', ''));
376 $arr['allow_gid'] = trim(defaults($arr, 'allow_gid', ''));
377 $arr['deny_cid'] = trim(defaults($arr, 'deny_cid', ''));
378 $arr['deny_gid'] = trim(defaults($arr, 'deny_gid', ''));
379 $arr['private'] = intval(defaults($arr, 'private', 0));
380 $arr['bookmark'] = intval(defaults($arr, 'bookmark', 0));
381 $arr['body'] = trim(defaults($arr, 'body', ''));
382 $arr['tag'] = trim(defaults($arr, 'tag', ''));
383 $arr['attach'] = trim(defaults($arr, 'attach', ''));
384 $arr['app'] = trim(defaults($arr, 'app', ''));
385 $arr['origin'] = intval(defaults($arr, 'origin', 0));
386 $arr['postopts'] = trim(defaults($arr, 'postopts', ''));
387 $arr['resource-id'] = trim(defaults($arr, 'resource-id', ''));
388 $arr['event-id'] = intval(defaults($arr, 'event-id', 0));
389 $arr['inform'] = trim(defaults($arr, 'inform', ''));
390 $arr['file'] = trim(defaults($arr, 'file', ''));
392 // When there is no content then we don't post it
393 if ($arr['body'].$arr['title'] == '') {
397 // Items cannot be stored before they happen ...
398 if ($arr['created'] > DateTimeFormat::utcNow()) {
399 $arr['created'] = DateTimeFormat::utcNow();
402 // We haven't invented time travel by now.
403 if ($arr['edited'] > DateTimeFormat::utcNow()) {
404 $arr['edited'] = DateTimeFormat::utcNow();
407 if (($arr['author-link'] == "") && ($arr['owner-link'] == "")) {
408 logger("Both author-link and owner-link are empty. Called by: " . System::callstack(), LOGGER_DEBUG);
411 if ($arr['plink'] == "") {
412 $arr['plink'] = System::baseUrl() . '/display/' . urlencode($arr['guid']);
415 if ($arr['network'] == NETWORK_PHANTOM) {
416 $r = q("SELECT `network` FROM `contact` WHERE `network` IN ('%s', '%s', '%s') AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
417 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS),
418 dbesc(normalise_link($arr['author-link'])),
422 if (!DBM::is_result($r)) {
423 $r = q("SELECT `network` FROM `gcontact` WHERE `network` IN ('%s', '%s', '%s') AND `nurl` = '%s' LIMIT 1",
424 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS),
425 dbesc(normalise_link($arr['author-link']))
429 if (!DBM::is_result($r)) {
430 $r = q("SELECT `network` FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
431 intval($arr['contact-id']),
436 if (DBM::is_result($r)) {
437 $arr['network'] = $r[0]["network"];
440 // Fallback to friendica (why is it empty in some cases?)
441 if ($arr['network'] == "") {
442 $arr['network'] = NETWORK_DFRN;
445 logger("Set network to " . $arr["network"] . " for " . $arr["uri"], LOGGER_DEBUG);
448 // The contact-id should be set before "self::insert" was called - but there seems to be some issues
449 if ($arr["contact-id"] == 0) {
451 * First we are looking for a suitable contact that matches with the author of the post
452 * This is done only for comments (See below explanation at "gcontact-id")
454 if ($arr['parent-uri'] != $arr['uri']) {
455 $arr["contact-id"] = Contact::getIdForURL($arr['author-link'], $uid);
458 // If not present then maybe the owner was found
459 if ($arr["contact-id"] == 0) {
460 $arr["contact-id"] = Contact::getIdForURL($arr['owner-link'], $uid);
463 // Still missing? Then use the "self" contact of the current user
464 if ($arr["contact-id"] == 0) {
465 $r = q("SELECT `id` FROM `contact` WHERE `self` AND `uid` = %d", intval($uid));
467 if (DBM::is_result($r)) {
468 $arr["contact-id"] = $r[0]["id"];
472 logger("Contact-id was missing for post ".$arr["guid"]." from user id ".$uid." - now set to ".$arr["contact-id"], LOGGER_DEBUG);
475 if (!x($arr, "gcontact-id")) {
477 * The gcontact should mostly behave like the contact. But is is supposed to be global for the system.
478 * This means that wall posts, repeated posts, etc. should have the gcontact id of the owner.
479 * On comments the author is the better choice.
481 if ($arr['parent-uri'] === $arr['uri']) {
482 $arr["gcontact-id"] = GContact::getId(["url" => $arr['owner-link'], "network" => $arr['network'],
483 "photo" => $arr['owner-avatar'], "name" => $arr['owner-name']]);
485 $arr["gcontact-id"] = GContact::getId(["url" => $arr['author-link'], "network" => $arr['network'],
486 "photo" => $arr['author-avatar'], "name" => $arr['author-name']]);
490 if ($arr["author-id"] == 0) {
491 $arr["author-id"] = Contact::getIdForURL($arr["author-link"], 0);
494 if (Contact::isBlocked($arr["author-id"])) {
495 logger('Contact '.$arr["author-id"].' is blocked, item '.$arr["uri"].' will not be stored');
499 if ($arr["owner-id"] == 0) {
500 $arr["owner-id"] = Contact::getIdForURL($arr["owner-link"], 0);
503 if (Contact::isBlocked($arr["owner-id"])) {
504 logger('Contact '.$arr["owner-id"].' is blocked, item '.$arr["uri"].' will not be stored');
508 if ($arr['guid'] != "") {
509 // Checking if there is already an item with the same guid
510 logger('checking for an item for user '.$arr['uid'].' on network '.$arr['network'].' with the guid '.$arr['guid'], LOGGER_DEBUG);
511 $r = q("SELECT `guid` FROM `item` WHERE `guid` = '%s' AND `network` = '%s' AND `uid` = '%d' LIMIT 1",
512 dbesc($arr['guid']), dbesc($arr['network']), intval($arr['uid']));
514 if (DBM::is_result($r)) {
515 logger('found item with guid '.$arr['guid'].' for user '.$arr['uid'].' on network '.$arr['network'], LOGGER_DEBUG);
520 // Check for hashtags in the body and repair or add hashtag links
521 self::setHashtags($arr);
523 $arr['thr-parent'] = $arr['parent-uri'];
525 if ($arr['parent-uri'] === $arr['uri']) {
528 $allow_cid = $arr['allow_cid'];
529 $allow_gid = $arr['allow_gid'];
530 $deny_cid = $arr['deny_cid'];
531 $deny_gid = $arr['deny_gid'];
532 $notify_type = 'wall-new';
535 // find the parent and snarf the item id and ACLs
536 // and anything else we need to inherit
538 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC LIMIT 1",
539 dbesc($arr['parent-uri']),
543 if (DBM::is_result($r)) {
545 // is the new message multi-level threaded?
546 // even though we don't support it now, preserve the info
547 // and re-attach to the conversation parent.
549 if ($r[0]['uri'] != $r[0]['parent-uri']) {
550 $arr['parent-uri'] = $r[0]['parent-uri'];
551 $z = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `parent-uri` = '%s' AND `uid` = %d
552 ORDER BY `id` ASC LIMIT 1",
553 dbesc($r[0]['parent-uri']),
554 dbesc($r[0]['parent-uri']),
558 if (DBM::is_result($z)) {
563 $parent_id = $r[0]['id'];
564 $parent_deleted = $r[0]['deleted'];
565 $allow_cid = $r[0]['allow_cid'];
566 $allow_gid = $r[0]['allow_gid'];
567 $deny_cid = $r[0]['deny_cid'];
568 $deny_gid = $r[0]['deny_gid'];
569 $arr['wall'] = $r[0]['wall'];
570 $notify_type = 'comment-new';
573 * If the parent is private, force privacy for the entire conversation
574 * This differs from the above settings as it subtly allows comments from
575 * email correspondents to be private even if the overall thread is not.
577 if ($r[0]['private']) {
578 $arr['private'] = $r[0]['private'];
582 * Edge case. We host a public forum that was originally posted to privately.
583 * The original author commented, but as this is a comment, the permissions
584 * weren't fixed up so it will still show the comment as private unless we fix it here.
586 if ((intval($r[0]['forum_mode']) == 1) && $r[0]['private']) {
590 // If its a post from myself then tag the thread as "mention"
591 logger("Checking if parent ".$parent_id." has to be tagged as mention for user ".$arr['uid'], LOGGER_DEBUG);
592 $u = q("SELECT `nickname` FROM `user` WHERE `uid` = %d", intval($arr['uid']));
593 if (DBM::is_result($u)) {
594 $self = normalise_link(System::baseUrl() . '/profile/' . $u[0]['nickname']);
595 logger("'myself' is ".$self." for parent ".$parent_id." checking against ".$arr['author-link']." and ".$arr['owner-link'], LOGGER_DEBUG);
596 if ((normalise_link($arr['author-link']) == $self) || (normalise_link($arr['owner-link']) == $self)) {
597 dba::update('thread', ['mention' => true], ['iid' => $parent_id]);
598 logger("tagged thread ".$parent_id." as mention for user ".$self, LOGGER_DEBUG);
603 * Allow one to see reply tweets from status.net even when
604 * we don't have or can't see the original post.
607 logger('$force_parent=true, reply converted to top-level post.');
609 $arr['parent-uri'] = $arr['uri'];
612 logger('item parent '.$arr['parent-uri'].' for '.$arr['uid'].' was not found - ignoring item');
620 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `network` IN ('%s', '%s') AND `uid` = %d LIMIT 1",
622 dbesc($arr['network']),
626 if (DBM::is_result($r)) {
627 logger('duplicated item with the same uri found. '.print_r($arr,true));
631 // On Friendica and Diaspora the GUID is unique
632 if (in_array($arr['network'], [NETWORK_DFRN, NETWORK_DIASPORA])) {
633 $r = q("SELECT `id` FROM `item` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
637 if (DBM::is_result($r)) {
638 logger('duplicated item with the same guid found. '.print_r($arr,true));
642 // Check for an existing post with the same content. There seems to be a problem with OStatus.
643 $r = q("SELECT `id` FROM `item` WHERE `body` = '%s' AND `network` = '%s' AND `created` = '%s' AND `contact-id` = %d AND `uid` = %d LIMIT 1",
645 dbesc($arr['network']),
646 dbesc($arr['created']),
647 intval($arr['contact-id']),
650 if (DBM::is_result($r)) {
651 logger('duplicated item with the same body found. '.print_r($arr,true));
656 // Is this item available in the global items (with uid=0)?
657 if ($arr["uid"] == 0) {
658 $arr["global"] = true;
660 // Set the global flag on all items if this was a global item entry
661 dba::update('item', ['global' => true], ['uri' => $arr["uri"]]);
663 $isglobal = q("SELECT `global` FROM `item` WHERE `uid` = 0 AND `uri` = '%s'", dbesc($arr["uri"]));
665 $arr["global"] = (DBM::is_result($isglobal) && count($isglobal) > 0);
669 if (strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid)) {
672 $private = $arr['private'];
675 $arr["allow_cid"] = $allow_cid;
676 $arr["allow_gid"] = $allow_gid;
677 $arr["deny_cid"] = $deny_cid;
678 $arr["deny_gid"] = $deny_gid;
679 $arr["private"] = $private;
680 $arr["deleted"] = $parent_deleted;
682 // Fill the cache field
683 put_item_in_cache($arr);
686 Addon::callHooks('post_local', $arr);
688 Addon::callHooks('post_remote', $arr);
691 // This array field is used to trigger some automatic reactions
692 // It is mainly used in the "post_local" hook.
693 unset($arr['api_source']);
695 if (x($arr, 'cancel')) {
696 logger('post cancelled by addon.');
701 * Check for already added items.
702 * There is a timing issue here that sometimes creates double postings.
703 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
705 if ($arr["uid"] == 0) {
706 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = 0 LIMIT 1", dbesc(trim($arr['uri'])));
707 if (DBM::is_result($r)) {
708 logger('Global item already stored. URI: '.$arr['uri'].' on network '.$arr['network'], LOGGER_DEBUG);
713 logger('' . print_r($arr,true), LOGGER_DATA);
716 $r = dba::insert('item', $arr);
718 // When the item was successfully stored we fetch the ID of the item.
719 if (DBM::is_result($r)) {
720 $current_post = dba::lastInsertId();
722 // This can happen - for example - if there are locking timeouts.
725 // Store the data into a spool file so that we can try again later.
727 // At first we restore the Diaspora signature that we removed above.
728 if (isset($encoded_signature)) {
729 $arr['dsprsig'] = $encoded_signature;
732 // Now we store the data in the spool directory
733 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
734 $file = 'item-'.round(microtime(true) * 10000).'-'.mt_rand().'.msg';
736 $spoolpath = get_spoolpath();
737 if ($spoolpath != "") {
738 $spool = $spoolpath.'/'.$file;
739 file_put_contents($spool, json_encode($arr));
740 logger("Item wasn't stored - Item was spooled into file ".$file, LOGGER_DEBUG);
745 if ($current_post == 0) {
746 // This is one of these error messages that never should occur.
747 logger("couldn't find created item - we better quit now.");
752 // How much entries have we created?
753 // We wouldn't need this query when we could use an unique index - but MySQL has length problems with them.
754 $r = q("SELECT COUNT(*) AS `entries` FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `network` = '%s'",
757 dbesc($arr['network'])
760 if (!DBM::is_result($r)) {
761 // This shouldn't happen, since COUNT always works when the database connection is there.
762 logger("We couldn't count the stored entries. Very strange ...");
767 if ($r[0]["entries"] > 1) {
768 // There are duplicates. We delete our just created entry.
769 logger('Duplicated post occurred. uri = ' . $arr['uri'] . ' uid = ' . $arr['uid']);
771 // Yes, we could do a rollback here - but we are having many users with MyISAM.
772 dba::delete('item', ['id' => $current_post]);
775 } elseif ($r[0]["entries"] == 0) {
776 // This really should never happen since we quit earlier if there were problems.
777 logger("Something is terribly wrong. We haven't found our created entry.");
782 logger('created item '.$current_post);
783 self::updateContact($arr);
785 if (!$parent_id || ($arr['parent-uri'] === $arr['uri'])) {
786 $parent_id = $current_post;
790 dba::update('item', ['parent' => $parent_id], ['id' => $current_post]);
792 $arr['id'] = $current_post;
793 $arr['parent'] = $parent_id;
795 // update the commented timestamp on the parent
796 // Only update "commented" if it is really a comment
797 if (($arr['verb'] == ACTIVITY_POST) || !Config::get("system", "like_no_comment")) {
798 dba::update('item', ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
800 dba::update('item', ['changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
805 * Friendica servers lower than 3.4.3-2 had double encoded the signature ...
806 * We can check for this condition when we decode and encode the stuff again.
808 if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) {
809 $dsprsig->signature = base64_decode($dsprsig->signature);
810 logger("Repaired double encoded signature from handle ".$dsprsig->signer, LOGGER_DEBUG);
813 dba::insert('sign', ['iid' => $current_post, 'signed_text' => $dsprsig->signed_text,
814 'signature' => $dsprsig->signature, 'signer' => $dsprsig->signer]);
817 $deleted = self::tagDeliver($arr['uid'], $current_post);
820 * current post can be deleted if is for a community page and no mention are
823 if (!$deleted && !$dontcache) {
824 $r = q('SELECT * FROM `item` WHERE `id` = %d', intval($current_post));
825 if (DBM::is_result($r) && (count($r) == 1)) {
827 Addon::callHooks('post_local_end', $r[0]);
829 Addon::callHooks('post_remote_end', $r[0]);
832 logger('new item not found in DB, id ' . $current_post);
836 if ($arr['parent-uri'] === $arr['uri']) {
837 self::addThread($current_post);
839 self::updateThread($parent_id);
845 * Due to deadlock issues with the "term" table we are doing these steps after the commit.
846 * This is not perfect - but a workable solution until we found the reason for the problem.
848 Term::insertFromTagFieldByItemId($current_post);
849 Term::insertFromFileFieldByItemId($current_post);
851 if ($arr['parent-uri'] === $arr['uri']) {
852 self::addShadow($current_post);
854 self::addShadowPost($current_post);
857 check_user_notification($current_post);
860 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "Notifier", $notify_type, $current_post);
863 return $current_post;
867 * @brief Add a shadow entry for a given item id that is a thread starter
869 * We store every public item entry additionally with the user id "0".
870 * This is used for the community page and for the search.
871 * It is planned that in the future we will store public item entries only once.
873 * @param integer $itemid Item ID that should be added
875 public static function addShadow($itemid)
877 $fields = ['uid', 'wall', 'private', 'moderated', 'visible', 'contact-id', 'deleted', 'network', 'author-id', 'owner-id'];
878 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
879 $item = dba::selectFirst('item', $fields, $condition);
881 if (!DBM::is_result($item)) {
885 // is it already a copy?
886 if (($itemid == 0) || ($item['uid'] == 0)) {
890 // Is it a visible public post?
891 if (!$item["visible"] || $item["deleted"] || $item["moderated"] || $item["private"]) {
895 // is it an entry from a connector? Only add an entry for natively connected networks
896 if (!in_array($item["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""])) {
900 // Only do these checks if the post isn't a wall post
901 if (!$item["wall"]) {
902 // Check, if hide-friends is activated - then don't do a shadow entry
903 if (dba::exists('profile', ['is-default' => true, 'uid' => $item['uid'], 'hide-friends' => true])) {
907 // Check if the contact is hidden or blocked
908 if (!dba::exists('contact', ['hidden' => false, 'blocked' => false, 'id' => $item['contact-id']])) {
913 // Only add a shadow, if the profile isn't hidden
914 if (dba::exists('user', ['uid' => $item['uid'], 'hidewall' => true])) {
918 $item = dba::selectFirst('item', [], ['id' => $itemid]);
920 if (DBM::is_result($item) && ($item["allow_cid"] == '') && ($item["allow_gid"] == '') &&
921 ($item["deny_cid"] == '') && ($item["deny_gid"] == '')) {
923 if (!dba::exists('item', ['uri' => $item['uri'], 'uid' => 0])) {
924 // Preparing public shadow (removing user specific data)
929 $item['contact-id'] = Contact::getIdForURL($item['author-link'], 0);
931 if (in_array($item['type'], ["net-comment", "wall-comment"])) {
932 $item['type'] = 'remote-comment';
933 } elseif ($item['type'] == 'wall') {
934 $item['type'] = 'remote';
937 $public_shadow = self::insert($item, false, false, true);
939 logger("Stored public shadow for thread ".$itemid." under id ".$public_shadow, LOGGER_DEBUG);
945 * @brief Add a shadow entry for a given item id that is a comment
947 * This function does the same like the function above - but for comments
949 * @param integer $itemid Item ID that should be added
951 public static function addShadowPost($itemid)
953 $item = dba::selectFirst('item', [], ['id' => $itemid]);
954 if (!DBM::is_result($item)) {
958 // Is it a toplevel post?
959 if ($item['id'] == $item['parent']) {
960 self::addShadow($itemid);
964 // Is this a shadow entry?
965 if ($item['uid'] == 0)
968 // Is there a shadow parent?
969 if (!dba::exists('item', ['uri' => $item['parent-uri'], 'uid' => 0])) {
973 // Is there already a shadow entry?
974 if (dba::exists('item', ['uri' => $item['uri'], 'uid' => 0])) {
978 // Preparing public shadow (removing user specific data)
983 $item['contact-id'] = Contact::getIdForURL($item['author-link'], 0);
985 if (in_array($item['type'], ["net-comment", "wall-comment"])) {
986 $item['type'] = 'remote-comment';
987 } elseif ($item['type'] == 'wall') {
988 $item['type'] = 'remote';
991 $public_shadow = self::insert($item, false, false, true);
993 logger("Stored public shadow for comment ".$item['uri']." under id ".$public_shadow, LOGGER_DEBUG);
997 * Adds a "lang" specification in a "postopts" element of given $arr,
998 * if possible and not already present.
999 * Expects "body" element to exist in $arr.
1001 private static function addLanguageInPostopts(&$arr)
1003 if (x($arr, 'postopts')) {
1004 if (strstr($arr['postopts'], 'lang=')) {
1008 $postopts = $arr['postopts'];
1013 $naked_body = preg_replace('/\[(.+?)\]/','', $arr['body']);
1014 $l = new Text_LanguageDetect();
1015 $lng = $l->detect($naked_body, 3);
1017 if (sizeof($lng) > 0) {
1018 if ($postopts != "") {
1019 $postopts .= '&'; // arbitrary separator, to be reviewed
1022 $postopts .= 'lang=';
1025 foreach ($lng as $language => $score) {
1026 $postopts .= $sep . $language . ";" . $score;
1029 $arr['postopts'] = $postopts;
1034 * @brief Creates an unique guid out of a given uri
1036 * @param string $uri uri of an item entry
1037 * @param string $host (Optional) hostname for the GUID prefix
1038 * @return string unique guid
1040 public static function guidFromUri($uri, $host = "")
1042 // Our regular guid routine is using this kind of prefix as well
1043 // We have to avoid that different routines could accidentally create the same value
1044 $parsed = parse_url($uri);
1046 // When the hostname isn't given, we take it from the uri
1048 // Is it in the format data@host.tld?
1049 if ((count($parsed) == 1) && strstr($uri, '@')) {
1050 $mailparts = explode('@', $uri);
1051 $host = array_pop($mailparts);
1053 $host = $parsed["host"];
1057 // We use a hash of the hostname as prefix for the guid
1058 $guid_prefix = hash("crc32", $host);
1060 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
1061 unset($parsed["scheme"]);
1063 // Glue it together to be able to make a hash from it
1064 $host_id = implode("/", $parsed);
1066 // We could use any hash algorithm since it isn't a security issue
1067 $host_hash = hash("ripemd128", $host_id);
1069 return $guid_prefix.$host_hash;
1073 * @brief Set "success_update" and "last-item" to the date of the last time we heard from this contact
1075 * This can be used to filter for inactive contacts.
1076 * Only do this for public postings to avoid privacy problems, since poco data is public.
1077 * Don't set this value if it isn't from the owner (could be an author that we don't know)
1079 * @param array $arr Contains the just posted item record
1081 private static function updateContact($arr)
1083 // Unarchive the author
1084 $contact = dba::selectFirst('contact', [], ['id' => $arr["author-link"]]);
1085 if ($contact['term-date'] > NULL_DATE) {
1086 Contact::unmarkForArchival($contact);
1089 // Unarchive the contact if it is a toplevel posting
1090 if ($arr["parent-uri"] === $arr["uri"]) {
1091 $contact = dba::selectFirst('contact', [], ['id' => $arr["contact-id"]]);
1092 if ($contact['term-date'] > NULL_DATE) {
1093 Contact::unmarkForArchival($contact);
1097 $update = (!$arr['private'] && (($arr["author-link"] === $arr["owner-link"]) || ($arr["parent-uri"] === $arr["uri"])));
1099 // Is it a forum? Then we don't care about the rules from above
1100 if (!$update && ($arr["network"] == NETWORK_DFRN) && ($arr["parent-uri"] === $arr["uri"])) {
1101 $isforum = q("SELECT `forum` FROM `contact` WHERE `id` = %d AND `forum`",
1102 intval($arr['contact-id']));
1103 if (DBM::is_result($isforum)) {
1109 dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
1110 ['id' => $arr['contact-id']]);
1112 // Now do the same for the system wide contacts with uid=0
1113 if (!$arr['private']) {
1114 dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
1115 ['id' => $arr['owner-id']]);
1117 if ($arr['owner-id'] != $arr['author-id']) {
1118 dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
1119 ['id' => $arr['author-id']]);
1124 private static function setHashtags(&$item)
1127 $tags = get_tags($item["body"]);
1130 if (!count($tags)) {
1134 // This sorting is important when there are hashtags that are part of other hashtags
1135 // Otherwise there could be problems with hashtags like #test and #test2
1138 $URLSearchString = "^\[\]";
1140 // All hashtags should point to the home server if "local_tags" is activated
1141 if (Config::get('system', 'local_tags')) {
1142 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1143 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["body"]);
1145 $item["tag"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1146 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["tag"]);
1149 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
1150 $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1152 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
1155 $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
1157 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
1160 $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
1162 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
1165 // Repair recursive urls
1166 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1167 "#$2", $item["body"]);
1169 foreach ($tags as $tag) {
1170 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=')) {
1174 $basetag = str_replace('_',' ',substr($tag,1));
1176 $newtag = '#[url=' . System::baseUrl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1178 $item["body"] = str_replace($tag, $newtag, $item["body"]);
1180 if (!stristr($item["tag"], "/search?tag=" . $basetag . "]" . $basetag . "[/url]")) {
1181 if (strlen($item["tag"])) {
1182 $item["tag"] = ','.$item["tag"];
1184 $item["tag"] = $newtag.$item["tag"];
1188 // Convert back the masked hashtags
1189 $item["body"] = str_replace("#", "#", $item["body"]);
1192 public static function getGuidById($id)
1194 $r = q("SELECT `guid` FROM `item` WHERE `id` = %d LIMIT 1", intval($id));
1195 if (DBM::is_result($r)) {
1196 return $r[0]["guid"];
1202 public static function getIdAndNickByGuid($guid, $uid = 0)
1208 $uid == local_user();
1211 // Does the given user have this item?
1213 $r = q("SELECT `item`.`id`, `user`.`nickname` FROM `item` INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
1214 WHERE `item`.`visible` = 1 AND `item`.`deleted` = 0 AND `item`.`moderated` = 0
1215 AND `item`.`guid` = '%s' AND `item`.`uid` = %d", dbesc($guid), intval($uid));
1216 if (DBM::is_result($r)) {
1218 $nick = $r[0]["nickname"];
1222 // Or is it anywhere on the server?
1224 $r = q("SELECT `item`.`id`, `user`.`nickname` FROM `item` INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
1225 WHERE `item`.`visible` = 1 AND `item`.`deleted` = 0 AND `item`.`moderated` = 0
1226 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1227 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1228 AND `item`.`private` = 0 AND `item`.`wall` = 1
1229 AND `item`.`guid` = '%s'", dbesc($guid));
1230 if (DBM::is_result($r)) {
1232 $nick = $r[0]["nickname"];
1235 return ["nick" => $nick, "id" => $id];
1239 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
1241 * @param int $item_id
1242 * @return bool true if item was deleted, else false
1244 private static function tagDeliver($uid, $item_id)
1248 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
1251 if (!DBM::is_result($u)) {
1255 $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
1256 $prvgroup = (($u[0]['page-flags'] == PAGE_PRVGROUP) ? true : false);
1258 $i = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1262 if (!DBM::is_result($i)) {
1268 $link = normalise_link(System::baseUrl() . '/profile/' . $u[0]['nickname']);
1271 * Diaspora uses their own hardwired link URL in @-tags
1272 * instead of the one we supply with webfinger
1274 $dlink = normalise_link(System::baseUrl() . '/u/' . $u[0]['nickname']);
1276 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
1278 foreach ($matches as $mtch) {
1279 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
1281 logger('mention found: ' . $mtch[2]);
1287 if (($community_page || $prvgroup) &&
1288 !$item['wall'] && !$item['origin'] && ($item['id'] == $item['parent'])) {
1289 // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
1291 logger("no-mention top-level post to communuty or private group. delete.");
1292 dba::delete('item', ['id' => $item_id]);
1298 /// @todo Declare $r or lets remove it - Rabuzarus - 2018-02-12.
1299 $arr = ['item' => $item, 'user' => $u[0], 'contact' => $r[0]];
1301 Addon::callHooks('tagged', $arr);
1303 if (!$community_page && !$prvgroup) {
1308 * tgroup delivery - setup a second delivery chain
1309 * prevent delivery looping - only proceed
1310 * if the message originated elsewhere and is a top-level post
1312 if ($item['wall'] || $item['origin'] || ($item['id'] != $item['parent'])) {
1316 // now change this copy of the post to a forum head message and deliver to all the tgroup members
1317 $c = q("SELECT `name`, `url`, `thumb` FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1318 intval($u[0]['uid'])
1320 if (!DBM::is_result($c)) {
1324 // also reset all the privacy bits to the forum default permissions
1326 $private = ($u[0]['allow_cid'] || $u[0]['allow_gid'] || $u[0]['deny_cid'] || $u[0]['deny_gid']) ? 1 : 0;
1328 $forum_mode = (($prvgroup) ? 2 : 1);
1330 q("UPDATE `item` SET `wall` = 1, `origin` = 1, `forum_mode` = %d, `owner-name` = '%s', `owner-link` = '%s', `owner-avatar` = '%s',
1331 `private` = %d, `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s' WHERE `id` = %d",
1332 intval($forum_mode),
1333 dbesc($c[0]['name']),
1334 dbesc($c[0]['url']),
1335 dbesc($c[0]['thumb']),
1337 dbesc($u[0]['allow_cid']),
1338 dbesc($u[0]['allow_gid']),
1339 dbesc($u[0]['deny_cid']),
1340 dbesc($u[0]['deny_gid']),
1343 self::updateThread($item_id);
1345 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', 'tgroup', $item_id);
1349 public static function isRemoteSelf($contact, &$datarray)
1353 if (!$contact['remote_self']) {
1357 // Prevent the forwarding of posts that are forwarded
1358 if ($datarray["extid"] == NETWORK_DFRN) {
1362 // Prevent to forward already forwarded posts
1363 if ($datarray["app"] == $a->get_hostname()) {
1367 // Only forward posts
1368 if ($datarray["verb"] != ACTIVITY_POST) {
1372 if (($contact['network'] != NETWORK_FEED) && $datarray['private']) {
1376 $datarray2 = $datarray;
1377 logger('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), LOGGER_DEBUG);
1378 if ($contact['remote_self'] == 2) {
1379 $r = q("SELECT `id`,`url`,`name`,`thumb` FROM `contact` WHERE `uid` = %d AND `self`",
1380 intval($contact['uid']));
1381 if (DBM::is_result($r)) {
1382 $datarray['contact-id'] = $r[0]["id"];
1384 $datarray['owner-name'] = $r[0]["name"];
1385 $datarray['owner-link'] = $r[0]["url"];
1386 $datarray['owner-avatar'] = $r[0]["thumb"];
1388 $datarray['author-name'] = $datarray['owner-name'];
1389 $datarray['author-link'] = $datarray['owner-link'];
1390 $datarray['author-avatar'] = $datarray['owner-avatar'];
1392 unset($datarray['created']);
1393 unset($datarray['edited']);
1396 if ($contact['network'] != NETWORK_FEED) {
1397 $datarray["guid"] = get_guid(32);
1398 unset($datarray["plink"]);
1399 $datarray["uri"] = item_new_uri($a->get_hostname(), $contact['uid'], $datarray["guid"]);
1400 $datarray["parent-uri"] = $datarray["uri"];
1401 $datarray["extid"] = $contact['network'];
1402 $urlpart = parse_url($datarray2['author-link']);
1403 $datarray["app"] = $urlpart["host"];
1405 $datarray['private'] = 0;
1409 if ($contact['network'] != NETWORK_FEED) {
1410 // Store the original post
1411 $r = self::insert($datarray2, false, false);
1412 logger('remote-self post original item - Contact '.$contact['url'].' return '.$r.' Item '.print_r($datarray2, true), LOGGER_DEBUG);
1414 $datarray["app"] = "Feed";
1417 // Trigger automatic reactions for addons
1418 $datarray['api_source'] = true;
1420 // We have to tell the hooks who we are - this really should be improved
1421 $_SESSION["authenticated"] = true;
1422 $_SESSION["uid"] = $contact['uid'];
1431 * @param array $item
1435 public static function fixPrivatePhotos($s, $uid, $item = null, $cid = 0)
1437 if (Config::get('system', 'disable_embedded')) {
1441 logger('check for photos', LOGGER_DEBUG);
1442 $site = substr(System::baseUrl(), strpos(System::baseUrl(), '://'));
1447 $img_start = strpos($orig_body, '[img');
1448 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
1449 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
1451 while (($img_st_close !== false) && ($img_len !== false)) {
1452 $img_st_close++; // make it point to AFTER the closing bracket
1453 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
1455 logger('found photo ' . $image, LOGGER_DEBUG);
1457 if (stristr($image, $site . '/photo/')) {
1458 // Only embed locally hosted photos
1460 $i = basename($image);
1461 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
1462 $x = strpos($i, '-');
1465 $res = substr($i, $x + 1);
1466 $i = substr($i, 0, $x);
1467 $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
1472 if (DBM::is_result($r)) {
1474 * Check to see if we should replace this photo link with an embedded image
1475 * 1. No need to do so if the photo is public
1476 * 2. If there's a contact-id provided, see if they're in the access list
1477 * for the photo. If so, embed it.
1478 * 3. Otherwise, if we have an item, see if the item permissions match the photo
1479 * permissions, regardless of order but first check to see if they're an exact
1480 * match to save some processing overhead.
1482 if (self::hasPermissions($r[0])) {
1484 $recips = self::enumeratePermissions($r[0]);
1485 if (in_array($cid, $recips)) {
1489 if (self::samePermissions($item, $r[0])) {
1495 $data = $r[0]['data'];
1496 $type = $r[0]['type'];
1498 // If a custom width and height were specified, apply before embedding
1499 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
1500 logger('scaling photo', LOGGER_DEBUG);
1502 $width = intval($match[1]);
1503 $height = intval($match[2]);
1505 $Image = new Image($data, $type);
1506 if ($Image->isValid()) {
1507 $Image->scaleDown(max($width, $height));
1508 $data = $Image->asString();
1509 $type = $Image->getType();
1513 logger('replacing photo', LOGGER_DEBUG);
1514 $image = 'data:' . $type . ';base64,' . base64_encode($data);
1515 logger('replaced: ' . $image, LOGGER_DATA);
1521 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
1522 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
1523 if ($orig_body === false) {
1527 $img_start = strpos($orig_body, '[img');
1528 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
1529 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
1532 $new_body = $new_body . $orig_body;
1537 private static function hasPermissions($obj)
1541 x($obj, 'allow_cid')
1543 x($obj, 'allow_gid')
1552 private static function samePermissions($obj1, $obj2)
1554 // first part is easy. Check that these are exactly the same.
1555 if (($obj1['allow_cid'] == $obj2['allow_cid'])
1556 && ($obj1['allow_gid'] == $obj2['allow_gid'])
1557 && ($obj1['deny_cid'] == $obj2['deny_cid'])
1558 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
1562 // This is harder. Parse all the permissions and compare the resulting set.
1563 $recipients1 = self::enumeratePermissions($obj1);
1564 $recipients2 = self::enumeratePermissions($obj2);
1568 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
1569 return ($recipients1 == $recipients2);
1572 // returns an array of contact-ids that are allowed to see this object
1573 private static function enumeratePermissions($obj)
1575 $allow_people = expand_acl($obj['allow_cid']);
1576 $allow_groups = Group::expand(expand_acl($obj['allow_gid']));
1577 $deny_people = expand_acl($obj['deny_cid']);
1578 $deny_groups = Group::expand(expand_acl($obj['deny_gid']));
1579 $recipients = array_unique(array_merge($allow_people, $allow_groups));
1580 $deny = array_unique(array_merge($deny_people, $deny_groups));
1581 $recipients = array_diff($recipients, $deny);
1585 public static function getFeedTags($item)
1589 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
1591 for ($x = 0; $x < $cnt; $x ++) {
1592 if ($matches[1][$x]) {
1593 $ret[$matches[2][$x]] = ['#', $matches[1][$x], $matches[2][$x]];
1598 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
1600 for ($x = 0; $x < $cnt; $x ++) {
1601 if ($matches[1][$x]) {
1602 $ret[] = ['@', $matches[1][$x], $matches[2][$x]];
1609 public static function expire($uid, $days, $network = "", $force = false)
1611 if (!$uid || ($days < 1)) {
1616 * $expire_network_only = save your own wall posts
1617 * and just expire conversations started by others
1619 $expire_network_only = PConfig::get($uid,'expire', 'network_only');
1620 $sql_extra = (intval($expire_network_only) ? " AND wall = 0 " : "");
1622 if ($network != "") {
1623 $sql_extra .= sprintf(" AND network = '%s' ", dbesc($network));
1626 * There is an index "uid_network_received" but not "uid_network_created"
1627 * This avoids the creation of another index just for one purpose.
1628 * And it doesn't really matter wether to look at "received" or "created"
1630 $range = "AND `received` < UTC_TIMESTAMP() - INTERVAL %d DAY ";
1632 $range = "AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY ";
1635 $r = q("SELECT `file`, `resource-id`, `starred`, `type`, `id` FROM `item`
1636 WHERE `uid` = %d $range
1644 if (!DBM::is_result($r)) {
1648 $expire_items = PConfig::get($uid, 'expire', 'items', 1);
1650 // Forcing expiring of items - but not notes and marked items
1652 $expire_items = true;
1655 $expire_notes = PConfig::get($uid, 'expire', 'notes', 1);
1656 $expire_starred = PConfig::get($uid, 'expire', 'starred', 1);
1657 $expire_photos = PConfig::get($uid, 'expire', 'photos', 0);
1659 logger('User '.$uid.': expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
1661 foreach ($r as $item) {
1663 // don't expire filed items
1665 if (strpos($item['file'],'[') !== false) {
1669 // Only expire posts, not photos and photo comments
1671 if ($expire_photos == 0 && strlen($item['resource-id'])) {
1673 } elseif ($expire_starred == 0 && intval($item['starred'])) {
1675 } elseif ($expire_notes == 0 && $item['type'] == 'note') {
1677 } elseif ($expire_items == 0 && $item['type'] != 'note') {
1681 self::deleteById($item['id'], PRIORITY_LOW);
1685 /// @TODO: This query seems to be really slow
1686 public static function firstPostDate($uid, $wall = false)
1688 $r = q("SELECT `id`, `created` FROM `item`
1689 WHERE `uid` = %d AND `wall` = %d AND `deleted` = 0 AND `visible` = 1 AND `moderated` = 0
1691 ORDER BY `created` ASC LIMIT 1",
1693 intval($wall ? 1 : 0)
1695 if (DBM::is_result($r)) {
1696 return substr(DateTimeFormat::local($r[0]['created']),0,10);
1702 * @brief add/remove activity to an item
1704 * Toggle activities as like,dislike,attend of an item
1706 * @param string $item_id
1707 * @param string $verb
1708 * Activity verb. One of
1709 * like, unlike, dislike, undislike, attendyes, unattendyes,
1710 * attendno, unattendno, attendmaybe, unattendmaybe
1711 * @hook 'post_local_end'
1713 * 'post_id' => ID of posted item
1715 public static function performLike($item_id, $verb)
1717 if (!local_user() && !remote_user()) {
1724 $bodyverb = L10n::t('%1$s likes %2$s\'s %3$s');
1725 $activity = ACTIVITY_LIKE;
1729 $bodyverb = L10n::t('%1$s doesn\'t like %2$s\'s %3$s');
1730 $activity = ACTIVITY_DISLIKE;
1734 $bodyverb = L10n::t('%1$s is attending %2$s\'s %3$s');
1735 $activity = ACTIVITY_ATTEND;
1739 $bodyverb = L10n::t('%1$s is not attending %2$s\'s %3$s');
1740 $activity = ACTIVITY_ATTENDNO;
1743 case 'unattendmaybe':
1744 $bodyverb = L10n::t('%1$s may attend %2$s\'s %3$s');
1745 $activity = ACTIVITY_ATTENDMAYBE;
1748 logger('like: unknown verb ' . $verb . ' for item ' . $item_id);
1752 // Enable activity toggling instead of on/off
1753 $event_verb_flag = $activity === ACTIVITY_ATTEND || $activity === ACTIVITY_ATTENDNO || $activity === ACTIVITY_ATTENDMAYBE;
1755 logger('like: verb ' . $verb . ' item ' . $item_id);
1757 $item = dba::selectFirst('item', [], ['`id` = ? OR `uri` = ?', $item_id, $item_id]);
1758 if (!DBM::is_result($item)) {
1759 logger('like: unknown item ' . $item_id);
1763 $uid = $item['uid'];
1764 if (($uid == 0) && local_user()) {
1765 $uid = local_user();
1768 if (!can_write_wall($uid)) {
1769 logger('like: unable to write on wall ' . $uid);
1773 // Retrieves the local post owner
1774 $owner_self_contact = dba::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
1775 if (!DBM::is_result($owner_self_contact)) {
1776 logger('like: unknown owner ' . $uid);
1780 // Retrieve the current logged in user's public contact
1781 $author_id = public_contact();
1783 $author_contact = dba::selectFirst('contact', [], ['id' => $author_id]);
1784 if (!DBM::is_result($author_contact)) {
1785 logger('like: unknown author ' . $author_id);
1789 // Contact-id is the uid-dependant author contact
1790 if (local_user() == $uid) {
1791 $item_contact_id = $owner_self_contact['id'];
1792 $item_contact = $owner_self_contact;
1794 $item_contact_id = Contact::getIdForURL($author_contact['url'], $uid);
1795 $item_contact = dba::selectFirst('contact', [], ['id' => $item_contact_id]);
1796 if (!DBM::is_result($item_contact)) {
1797 logger('like: unknown item contact ' . $item_contact_id);
1802 // Look for an existing verb row
1803 // event participation are essentially radio toggles. If you make a subsequent choice,
1804 // we need to eradicate your first choice.
1805 if ($event_verb_flag) {
1806 $verbs = "'" . dbesc(ACTIVITY_ATTEND) . "', '" . dbesc(ACTIVITY_ATTENDNO) . "', '" . dbesc(ACTIVITY_ATTENDMAYBE) . "'";
1808 $verbs = "'".dbesc($activity)."'";
1811 $existing_like = q("SELECT `id`, `guid`, `verb` FROM `item`
1812 WHERE `verb` IN ($verbs)
1814 AND `author-id` = %d
1816 AND (`parent` = '%s' OR `parent-uri` = '%s' OR `thr-parent` = '%s')
1818 intval($author_contact['id']),
1819 intval($item['uid']),
1820 dbesc($item_id), dbesc($item_id), dbesc($item['uri'])
1823 // If it exists, mark it as deleted
1824 if (DBM::is_result($existing_like)) {
1825 $like_item = $existing_like[0];
1827 // Already voted, undo it
1828 $fields = ['deleted' => true, 'unseen' => true, 'changed' => DateTimeFormat::utcNow()];
1829 dba::update('item', $fields, ['id' => $like_item['id']]);
1831 // Clean up the Diaspora signatures for this like
1832 // Go ahead and do it even if Diaspora support is disabled. We still want to clean up
1833 // if it had been enabled in the past
1834 dba::delete('sign', ['iid' => $like_item['id']]);
1836 $like_item_id = $like_item['id'];
1837 Worker::add(PRIORITY_HIGH, "Notifier", "like", $like_item_id);
1839 if (!$event_verb_flag || $like_item['verb'] == $activity) {
1844 // Verb is "un-something", just trying to delete existing entries
1845 if (strpos($verb, 'un') === 0) {
1849 // Else or if event verb different from existing row, create a new item row
1850 $post_type = (($item['resource-id']) ? L10n::t('photo') : L10n::t('status'));
1851 if ($item['object-type'] === ACTIVITY_OBJ_EVENT) {
1852 $post_type = L10n::t('event');
1854 $objtype = $item['resource-id'] ? ACTIVITY_OBJ_IMAGE : ACTIVITY_OBJ_NOTE ;
1855 $link = xmlify('<link rel="alternate" type="text/html" href="' . System::baseUrl() . '/display/' . $owner_self_contact['nick'] . '/' . $item['id'] . '" />' . "\n") ;
1856 $body = $item['body'];
1861 <type>$objtype</type>
1863 <id>{$item['uri']}</id>
1866 <content>$body</content>
1870 $ulink = '[url=' . $author_contact['url'] . ']' . $author_contact['name'] . '[/url]';
1871 $alink = '[url=' . $item['author-link'] . ']' . $item['author-name'] . '[/url]';
1872 $plink = '[url=' . System::baseUrl() . '/display/' . $owner_self_contact['nick'] . '/' . $item['id'] . ']' . $post_type . '[/url]';
1875 'guid' => get_guid(32),
1876 'uri' => item_new_uri(self::getApp()->get_hostname(), $item['uid']),
1877 'uid' => $item['uid'],
1878 'contact-id' => $item_contact_id,
1879 'type' => 'activity',
1880 'wall' => $item['wall'],
1882 'gravity' => GRAVITY_LIKE,
1883 'parent' => $item['id'],
1884 'parent-uri' => $item['uri'],
1885 'thr-parent' => $item['uri'],
1886 'owner-id' => $item['owner-id'],
1887 'owner-name' => $item['owner-name'],
1888 'owner-link' => $item['owner-link'],
1889 'owner-avatar' => $item['owner-avatar'],
1890 'author-id' => $author_contact['id'],
1891 'author-name' => $author_contact['name'],
1892 'author-link' => $author_contact['url'],
1893 'author-avatar' => $author_contact['thumb'],
1894 'body' => sprintf($bodyverb, $ulink, $alink, $plink),
1895 'verb' => $activity,
1896 'object-type' => $objtype,
1898 'allow_cid' => $item['allow_cid'],
1899 'allow_gid' => $item['allow_gid'],
1900 'deny_cid' => $item['deny_cid'],
1901 'deny_gid' => $item['deny_gid'],
1906 $new_item_id = self::insert($new_item);
1908 // If the parent item isn't visible then set it to visible
1909 if (!$item['visible']) {
1910 self::update(['visible' => true], ['id' => $item['id']]);
1913 // Save the author information for the like in case we need to relay to Diaspora
1914 Diaspora::storeLikeSignature($item_contact, $new_item_id);
1916 $new_item['id'] = $new_item_id;
1918 Addon::callHooks('post_local_end', $new_item);
1920 Worker::add(PRIORITY_HIGH, "Notifier", "like", $new_item_id);
1925 private static function addThread($itemid, $onlyshadow = false)
1927 $items = q("SELECT `uid`, `created`, `edited`, `commented`, `received`, `changed`, `wall`, `private`, `pubmail`,
1928 `moderated`, `visible`, `spam`, `starred`, `bookmark`, `contact-id`, `gcontact-id`,
1929 `deleted`, `origin`, `forum_mode`, `mention`, `network`, `author-id`, `owner-id`
1930 FROM `item` WHERE `id` = %d AND (`parent` = %d OR `parent` = 0) LIMIT 1", intval($itemid), intval($itemid));
1937 $item['iid'] = $itemid;
1940 $result = dba::insert('thread', $item);
1942 logger("Add thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
1946 private static function updateThread($itemid, $setmention = false)
1948 $items = q("SELECT `uid`, `guid`, `title`, `body`, `created`, `edited`, `commented`, `received`, `changed`, `wall`, `private`, `pubmail`, `moderated`, `visible`, `spam`, `starred`, `bookmark`, `contact-id`, `gcontact-id`,
1949 `deleted`, `origin`, `forum_mode`, `network`, `rendered-html`, `rendered-hash` FROM `item` WHERE `id` = %d AND (`parent` = %d OR `parent` = 0) LIMIT 1", intval($itemid), intval($itemid));
1951 if (!DBM::is_result($items)) {
1958 $item["mention"] = 1;
1963 foreach ($item as $field => $data)
1964 if (!in_array($field, ["guid", "title", "body", "rendered-html", "rendered-hash"])) {
1969 $sql .= "`".$field."` = '".dbesc($data)."'";
1972 $result = q("UPDATE `thread` SET ".$sql." WHERE `iid` = %d", intval($itemid));
1974 logger("Update thread for item ".$itemid." - guid ".$item["guid"]." - ".print_r($result, true)." ".print_r($item, true), LOGGER_DEBUG);
1976 // Updating a shadow item entry
1977 $items = dba::selectFirst('item', ['id'], ['guid' => $item['guid'], 'uid' => 0]);
1979 if (!DBM::is_result($items)) {
1983 $result = dba::update(
1985 ['title' => $item['title'], 'body' => $item['body'], 'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']],
1986 ['id' => $items['id']]
1989 logger("Updating public shadow for post ".$items["id"]." - guid ".$item["guid"]." Result: ".print_r($result, true), LOGGER_DEBUG);
1992 private static function deleteThread($itemid, $itemuri = "")
1994 $item = dba::selectFirst('thread', ['uid'], ['iid' => $itemid]);
1995 if (!DBM::is_result($item)) {
1996 logger('No thread found for id '.$itemid, LOGGER_DEBUG);
2000 // Using dba::delete at this time could delete the associated item entries
2001 $result = dba::e("DELETE FROM `thread` WHERE `iid` = ?", $itemid);
2003 logger("deleteThread: Deleted thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
2005 if ($itemuri != "") {
2006 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND NOT `deleted` AND NOT (`uid` IN (%d, 0))",
2008 intval($item["uid"])
2010 if (!DBM::is_result($r)) {
2011 dba::delete('item', ['uri' => $itemuri, 'uid' => 0]);
2012 logger("deleteThread: Deleted shadow for item ".$itemuri, LOGGER_DEBUG);