]> git.mxchange.org Git - friendica.git/blob - src/Model/Item.php
cc42aafc61e83c2fd90ae0e66467e664280abce5
[friendica.git] / src / Model / Item.php
1 <?php
2
3 /**
4  * @file src/Model/Item.php
5  */
6
7 namespace Friendica\Model;
8
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;
26 use dba;
27 use Text_LanguageDetect;
28
29 require_once 'boot.php';
30 require_once 'include/items.php';
31 require_once 'include/text.php';
32 require_once 'include/event.php';
33
34 class Item extends BaseObject
35 {
36         /**
37          * @brief Update existing item entries
38          *
39          * @param array $fields The fields that are to be changed
40          * @param array $condition The condition for finding the item entries
41          *
42          * In the future we may have to change permissions as well.
43          * Then we had to add the user id as third parameter.
44          *
45          * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
46          *
47          * @return integer|boolean number of affected rows - or "false" if there was an error
48          */
49         public static function update(array $fields, array $condition)
50         {
51                 if (empty($condition) || empty($fields)) {
52                         return false;
53                 }
54
55                 $success = dba::update('item', $fields, $condition);
56
57                 if (!$success) {
58                         return false;
59                 }
60
61                 $rows = dba::affected_rows();
62
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                         // We only need to notfiy others when it is an original entry from us
68                         if (!$item['origin']) {
69                                 continue;
70                         }
71
72                         Term::insertFromTagFieldByItemId($item['id']);
73                         Term::insertFromFileFieldByItemId($item['id']);
74                         self::updateThread($item['id']);
75
76                         Worker::add(PRIORITY_HIGH, "Notifier", 'edit_post', $item['id']);
77                 }
78
79                 return $rows;
80         }
81
82         /**
83          * @brief Delete an item and notify others about it - if it was ours
84          *
85          * @param array $condition The condition for finding the item entries
86          * @param integer $priority Priority for the notification
87          */
88         public static function delete($condition, $priority = PRIORITY_HIGH)
89         {
90                 $items = dba::select('item', ['id'], $condition);
91                 while ($item = dba::fetch($items)) {
92                         self::deleteById($item['id'], $priority);
93                 }
94                 dba::close($items);
95         }
96
97         /**
98          * @brief Delete an item and notify others about it - if it was ours
99          *
100          * @param integer $item_id Item ID that should be delete
101          * @param integer $priority Priority for the notification
102          *
103          * @return $boolean success
104          */
105         public static function deleteById($item_id, $priority = PRIORITY_HIGH)
106         {
107                 // locate item to be deleted
108                 $fields = ['id', 'uid', 'parent', 'parent-uri', 'origin', 'deleted',
109                         'file', 'resource-id', 'event-id', 'attach',
110                         'verb', 'object-type', 'object', 'target', 'contact-id'];
111                 $item = dba::selectFirst('item', $fields, ['id' => $item_id]);
112                 if (!DBM::is_result($item)) {
113                         return false;
114                 }
115
116                 if ($item['deleted']) {
117                         return false;
118                 }
119
120                 $parent = dba::selectFirst('item', ['origin'], ['id' => $item['parent']]);
121                 if (!DBM::is_result($parent)) {
122                         $parent = ['origin' => false];
123                 }
124
125                 logger('delete item: ' . $item['id'], LOGGER_DEBUG);
126
127                 // clean up categories and tags so they don't end up as orphans
128
129                 $matches = false;
130                 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
131                 if ($cnt) {
132                         foreach ($matches as $mtch) {
133                                 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],true);
134                         }
135                 }
136
137                 $matches = false;
138
139                 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
140                 if ($cnt) {
141                         foreach ($matches as $mtch) {
142                                 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],false);
143                         }
144                 }
145
146                 /*
147                  * If item is a link to a photo resource, nuke all the associated photos
148                  * (visitors will not have photo resources)
149                  * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
150                  * generate a resource-id and therefore aren't intimately linked to the item.
151                  */
152                 if (strlen($item['resource-id'])) {
153                         dba::delete('photo', ['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
154                 }
155
156                 // If item is a link to an event, delete the event.
157                 if (intval($item['event-id'])) {
158                         event_delete($item['event-id']);
159                 }
160
161                 // If item has attachments, drop them
162                 foreach (explode(", ", $item['attach']) as $attach) {
163                         preg_match("|attach/(\d+)|", $attach, $matches);
164                         dba::delete('attach', ['id' => $matches[1], 'uid' => $item['uid']]);
165                 }
166
167                 // Delete tags that had been attached to other items
168                 self::deleteTagsFromItem($item);
169
170                 // Set the item to "deleted"
171                 dba::update('item', ['deleted' => true, 'title' => '', 'body' => '',
172                                         'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()],
173                                 ['id' => $item['id']]);
174
175                 Term::insertFromTagFieldByItemId($item['id']);
176                 Term::insertFromFileFieldByItemId($item['id']);
177                 self::deleteThread($item['id'], $item['parent-uri']);
178
179                 // If it's the parent of a comment thread, kill all the kids
180                 if ($item['id'] == $item['parent']) {
181                         self::delete(['parent' => $item['parent']], $priority);
182                 }
183
184                 // send the notification upstream/downstream
185                 if ($item['origin'] || $parent['origin']) {
186                         Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", "drop", intval($item['id']));
187                 }
188
189                 return true;
190         }
191
192         private static function deleteTagsFromItem($item)
193         {
194                 if (($item["verb"] != ACTIVITY_TAG) || ($item["object-type"] != ACTIVITY_OBJ_TAGTERM)) {
195                         return;
196                 }
197
198                 $xo = XML::parseString($item["object"], false);
199                 $xt = XML::parseString($item["target"], false);
200
201                 if ($xt->type != ACTIVITY_OBJ_NOTE) {
202                         return;
203                 }
204
205                 $i = dba::selectFirst('item', ['id', 'contact-id', 'tag'], ['uri' => $xt->id, 'uid' => $item['uid']]);
206                 if (!DBM::is_result($i)) {
207                         return;
208                 }
209
210                 // For tags, the owner cannot remove the tag on the author's copy of the post.
211                 $owner_remove = ($item["contact-id"] == $i["contact-id"]);
212                 $author_copy = $item["origin"];
213
214                 if (($owner_remove && $author_copy) || !$owner_remove) {
215                         return;
216                 }
217
218                 $tags = explode(',', $i["tag"]);
219                 $newtags = [];
220                 if (count($tags)) {
221                         foreach ($tags as $tag) {
222                                 if (trim($tag) !== trim($xo->body)) {
223                                        $newtags[] = trim($tag);
224                                 }
225                         }
226                 }
227                 self::update(['tag' => implode(',', $newtags)], ['id' => $i["id"]]);
228         }
229
230         public static function insert($arr, $force_parent = false, $notify = false, $dontcache = false)
231         {
232                 $a = get_app();
233
234                 // If it is a posting where users should get notifications, then define it as wall posting
235                 if ($notify) {
236                         $arr['wall'] = 1;
237                         $arr['type'] = 'wall';
238                         $arr['origin'] = 1;
239                         $arr['network'] = NETWORK_DFRN;
240                         $arr['protocol'] = PROTOCOL_DFRN;
241
242                         // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
243                         // In difference to the call to "self::guidFromUri" several lines below we add the hash of our own host.
244                         // This is done because our host is the original creator of the post.
245                         if (!isset($arr['guid'])) {
246                                 if (isset($arr['plink'])) {
247                                         $arr['guid'] = self::guidFromUri($arr['plink'], $a->get_hostname());
248                                 } elseif (isset($arr['uri'])) {
249                                         $arr['guid'] = self::guidFromUri($arr['uri'], $a->get_hostname());
250                                 }
251                         }
252                 } else {
253                         $arr['network'] = trim(defaults($arr, 'network', NETWORK_PHANTOM));
254                 }
255
256                 if ($notify) {
257                         $guid_prefix = "";
258                 } elseif ((trim($arr['guid']) == "") && (trim($arr['plink']) != "")) {
259                         $arr['guid'] = self::guidFromUri($arr['plink']);
260                 } elseif ((trim($arr['guid']) == "") && (trim($arr['uri']) != "")) {
261                         $arr['guid'] = self::guidFromUri($arr['uri']);
262                 } else {
263                         $parsed = parse_url($arr["author-link"]);
264                         $guid_prefix = hash("crc32", $parsed["host"]);
265                 }
266
267                 $arr['guid'] = notags(trim(defaults($arr, 'guid', get_guid(32, $guid_prefix))));
268                 $arr['uri'] = notags(trim(defaults($arr, 'uri', item_new_uri($a->get_hostname(), $uid, $arr['guid']))));
269
270                 // Store conversation data
271                 $arr = Conversation::insert($arr);
272
273                 /*
274                  * If a Diaspora signature structure was passed in, pull it out of the
275                  * item array and set it aside for later storage.
276                  */
277
278                 $dsprsig = null;
279                 if (x($arr, 'dsprsig')) {
280                         $encoded_signature = $arr['dsprsig'];
281                         $dsprsig = json_decode(base64_decode($arr['dsprsig']));
282                         unset($arr['dsprsig']);
283                 }
284
285                 // Converting the plink
286                 /// @TODO Check if this is really still needed
287                 if ($arr['network'] == NETWORK_OSTATUS) {
288                         if (isset($arr['plink'])) {
289                                 $arr['plink'] = OStatus::convertHref($arr['plink']);
290                         } elseif (isset($arr['uri'])) {
291                                 $arr['plink'] = OStatus::convertHref($arr['uri']);
292                         }
293                 }
294
295                 if (x($arr, 'gravity')) {
296                         $arr['gravity'] = intval($arr['gravity']);
297                 } elseif ($arr['parent-uri'] === $arr['uri']) {
298                         $arr['gravity'] = 0;
299                 } elseif (activity_match($arr['verb'],ACTIVITY_POST)) {
300                         $arr['gravity'] = 6;
301                 } else {
302                         $arr['gravity'] = 6;   // extensible catchall
303                 }
304
305                 $arr['type'] = defaults($arr, 'type', 'remote');
306
307                 $uid = intval($arr['uid']);
308
309                 // check for create date and expire time
310                 $expire_interval = Config::get('system', 'dbclean-expire-days', 0);
311
312                 $user = dba::selectFirst('user', ['expire'], ['uid' => $uid]);
313                 if (DBM::is_result($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
314                         $expire_interval = $user['expire'];
315                 }
316
317                 if (($expire_interval > 0) && !empty($arr['created'])) {
318                         $expire_date = time() - ($expire_interval * 86400);
319                         $created_date = strtotime($arr['created']);
320                         if ($created_date < $expire_date) {
321                                 logger('item-store: item created ('.date('c', $created_date).') before expiration time ('.date('c', $expire_date).'). ignored. ' . print_r($arr,true), LOGGER_DEBUG);
322                                 return 0;
323                         }
324                 }
325
326                 /*
327                  * Do we already have this item?
328                  * We have to check several networks since Friendica posts could be repeated
329                  * via OStatus (maybe Diasporsa as well)
330                  */
331                 if (in_array($arr['network'], [NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS, ""])) {
332                         $r = q("SELECT `id`, `network` FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `network` IN ('%s', '%s', '%s')  LIMIT 1",
333                                         dbesc(trim($arr['uri'])),
334                                         intval($uid),
335                                         dbesc(NETWORK_DIASPORA),
336                                         dbesc(NETWORK_DFRN),
337                                         dbesc(NETWORK_OSTATUS)
338                                 );
339                         if (DBM::is_result($r)) {
340                                 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
341                                 if ($uid != 0) {
342                                         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']);
343                                 }
344
345                                 return $r[0]["id"];
346                         }
347                 }
348
349                 self::addLanguageInPostopts($arr);
350
351                 $arr['wall']          = intval(defaults($arr, 'wall', 0));
352                 $arr['extid']         = trim(defaults($arr, 'extid', ''));
353                 $arr['author-name']   = trim(defaults($arr, 'author-name', ''));
354                 $arr['author-link']   = trim(defaults($arr, 'author-link', ''));
355                 $arr['author-avatar'] = trim(defaults($arr, 'author-avatar', ''));
356                 $arr['owner-name']    = trim(defaults($arr, 'owner-name', ''));
357                 $arr['owner-link']    = trim(defaults($arr, 'owner-link', ''));
358                 $arr['owner-avatar']  = trim(defaults($arr, 'owner-avatar', ''));
359                 $arr['received']      = ((x($arr, 'received') !== false) ? DateTimeFormat::utc($arr['received']) : DateTimeFormat::utcNow());
360                 $arr['created']       = ((x($arr, 'created') !== false) ? DateTimeFormat::utc($arr['created']) : $arr['received']);
361                 $arr['edited']        = ((x($arr, 'edited') !== false) ? DateTimeFormat::utc($arr['edited']) : $arr['created']);
362                 $arr['changed']       = ((x($arr, 'changed') !== false) ? DateTimeFormat::utc($arr['changed']) : $arr['created']);
363                 $arr['commented']     = ((x($arr, 'commented') !== false) ? DateTimeFormat::utc($arr['commented']) : $arr['created']);
364                 $arr['title']         = trim(defaults($arr, 'title', ''));
365                 $arr['location']      = trim(defaults($arr, 'location', ''));
366                 $arr['coord']         = trim(defaults($arr, 'coord', ''));
367                 $arr['visible']       = ((x($arr, 'visible') !== false) ? intval($arr['visible'])         : 1);
368                 $arr['deleted']       = 0;
369                 $arr['parent-uri']    = trim(defaults($arr, 'parent-uri', $arr['uri']));
370                 $arr['verb']          = trim(defaults($arr, 'verb', ''));
371                 $arr['object-type']   = trim(defaults($arr, 'object-type', ''));
372                 $arr['object']        = trim(defaults($arr, 'object', ''));
373                 $arr['target-type']   = trim(defaults($arr, 'target-type', ''));
374                 $arr['target']        = trim(defaults($arr, 'target', ''));
375                 $arr['plink']         = trim(defaults($arr, 'plink', ''));
376                 $arr['allow_cid']     = trim(defaults($arr, 'allow_cid', ''));
377                 $arr['allow_gid']     = trim(defaults($arr, 'allow_gid', ''));
378                 $arr['deny_cid']      = trim(defaults($arr, 'deny_cid', ''));
379                 $arr['deny_gid']      = trim(defaults($arr, 'deny_gid', ''));
380                 $arr['private']       = intval(defaults($arr, 'private', 0));
381                 $arr['bookmark']      = intval(defaults($arr, 'bookmark', 0));
382                 $arr['body']          = trim(defaults($arr, 'body', ''));
383                 $arr['tag']           = trim(defaults($arr, 'tag', ''));
384                 $arr['attach']        = trim(defaults($arr, 'attach', ''));
385                 $arr['app']           = trim(defaults($arr, 'app', ''));
386                 $arr['origin']        = intval(defaults($arr, 'origin', 0));
387                 $arr['postopts']      = trim(defaults($arr, 'postopts', ''));
388                 $arr['resource-id']   = trim(defaults($arr, 'resource-id', ''));
389                 $arr['event-id']      = intval(defaults($arr, 'event-id', 0));
390                 $arr['inform']        = trim(defaults($arr, 'inform', ''));
391                 $arr['file']          = trim(defaults($arr, 'file', ''));
392
393                 // When there is no content then we don't post it
394                 if ($arr['body'].$arr['title'] == '') {
395                         return 0;
396                 }
397
398                 // Items cannot be stored before they happen ...
399                 if ($arr['created'] > DateTimeFormat::utcNow()) {
400                         $arr['created'] = DateTimeFormat::utcNow();
401                 }
402
403                 // We haven't invented time travel by now.
404                 if ($arr['edited'] > DateTimeFormat::utcNow()) {
405                         $arr['edited'] = DateTimeFormat::utcNow();
406                 }
407
408                 if (($arr['author-link'] == "") && ($arr['owner-link'] == "")) {
409                         logger("Both author-link and owner-link are empty. Called by: " . System::callstack(), LOGGER_DEBUG);
410                 }
411
412                 if ($arr['plink'] == "") {
413                         $arr['plink'] = System::baseUrl() . '/display/' . urlencode($arr['guid']);
414                 }
415
416                 if ($arr['network'] == NETWORK_PHANTOM) {
417                         $r = q("SELECT `network` FROM `contact` WHERE `network` IN ('%s', '%s', '%s') AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
418                                 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS),
419                                 dbesc(normalise_link($arr['author-link'])),
420                                 intval($arr['uid'])
421                         );
422
423                         if (!DBM::is_result($r)) {
424                                 $r = q("SELECT `network` FROM `gcontact` WHERE `network` IN ('%s', '%s', '%s') AND `nurl` = '%s' LIMIT 1",
425                                         dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS),
426                                         dbesc(normalise_link($arr['author-link']))
427                                 );
428                         }
429
430                         if (!DBM::is_result($r)) {
431                                 $r = q("SELECT `network` FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
432                                         intval($arr['contact-id']),
433                                         intval($arr['uid'])
434                                 );
435                         }
436
437                         if (DBM::is_result($r)) {
438                                 $arr['network'] = $r[0]["network"];
439                         }
440
441                         // Fallback to friendica (why is it empty in some cases?)
442                         if ($arr['network'] == "") {
443                                 $arr['network'] = NETWORK_DFRN;
444                         }
445
446                         logger("Set network to " . $arr["network"] . " for " . $arr["uri"], LOGGER_DEBUG);
447                 }
448
449                 // The contact-id should be set before "self::insert" was called - but there seems to be some issues
450                 if ($arr["contact-id"] == 0) {
451                         /*
452                          * First we are looking for a suitable contact that matches with the author of the post
453                          * This is done only for comments (See below explanation at "gcontact-id")
454                          */
455                         if ($arr['parent-uri'] != $arr['uri']) {
456                                 $arr["contact-id"] = Contact::getIdForURL($arr['author-link'], $uid);
457                         }
458
459                         // If not present then maybe the owner was found
460                         if ($arr["contact-id"] == 0) {
461                                 $arr["contact-id"] = Contact::getIdForURL($arr['owner-link'], $uid);
462                         }
463
464                         // Still missing? Then use the "self" contact of the current user
465                         if ($arr["contact-id"] == 0) {
466                                 $r = q("SELECT `id` FROM `contact` WHERE `self` AND `uid` = %d", intval($uid));
467
468                                 if (DBM::is_result($r)) {
469                                         $arr["contact-id"] = $r[0]["id"];
470                                 }
471                         }
472
473                         logger("Contact-id was missing for post ".$arr["guid"]." from user id ".$uid." - now set to ".$arr["contact-id"], LOGGER_DEBUG);
474                 }
475
476                 if (!x($arr, "gcontact-id")) {
477                         /*
478                          * The gcontact should mostly behave like the contact. But is is supposed to be global for the system.
479                          * This means that wall posts, repeated posts, etc. should have the gcontact id of the owner.
480                          * On comments the author is the better choice.
481                          */
482                         if ($arr['parent-uri'] === $arr['uri']) {
483                                 $arr["gcontact-id"] = GContact::getId(["url" => $arr['owner-link'], "network" => $arr['network'],
484                                                                          "photo" => $arr['owner-avatar'], "name" => $arr['owner-name']]);
485                         } else {
486                                 $arr["gcontact-id"] = GContact::getId(["url" => $arr['author-link'], "network" => $arr['network'],
487                                                                          "photo" => $arr['author-avatar'], "name" => $arr['author-name']]);
488                         }
489                 }
490
491                 if ($arr["author-id"] == 0) {
492                         $arr["author-id"] = Contact::getIdForURL($arr["author-link"], 0);
493                 }
494
495                 if (Contact::isBlocked($arr["author-id"])) {
496                         logger('Contact '.$arr["author-id"].' is blocked, item '.$arr["uri"].' will not be stored');
497                         return 0;
498                 }
499
500                 if ($arr["owner-id"] == 0) {
501                         $arr["owner-id"] = Contact::getIdForURL($arr["owner-link"], 0);
502                 }
503
504                 if (Contact::isBlocked($arr["owner-id"])) {
505                         logger('Contact '.$arr["owner-id"].' is blocked, item '.$arr["uri"].' will not be stored');
506                         return 0;
507                 }
508
509                 if ($arr['guid'] != "") {
510                         // Checking if there is already an item with the same guid
511                         logger('checking for an item for user '.$arr['uid'].' on network '.$arr['network'].' with the guid '.$arr['guid'], LOGGER_DEBUG);
512                         $r = q("SELECT `guid` FROM `item` WHERE `guid` = '%s' AND `network` = '%s' AND `uid` = '%d' LIMIT 1",
513                                 dbesc($arr['guid']), dbesc($arr['network']), intval($arr['uid']));
514
515                         if (DBM::is_result($r)) {
516                                 logger('found item with guid '.$arr['guid'].' for user '.$arr['uid'].' on network '.$arr['network'], LOGGER_DEBUG);
517                                 return 0;
518                         }
519                 }
520
521                 // Check for hashtags in the body and repair or add hashtag links
522                 self::setHashtags($arr);
523
524                 $arr['thr-parent'] = $arr['parent-uri'];
525
526                 if ($arr['parent-uri'] === $arr['uri']) {
527                         $parent_id = 0;
528                         $parent_deleted = 0;
529                         $allow_cid = $arr['allow_cid'];
530                         $allow_gid = $arr['allow_gid'];
531                         $deny_cid  = $arr['deny_cid'];
532                         $deny_gid  = $arr['deny_gid'];
533                         $notify_type = 'wall-new';
534                 } else {
535
536                         // find the parent and snarf the item id and ACLs
537                         // and anything else we need to inherit
538
539                         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC LIMIT 1",
540                                 dbesc($arr['parent-uri']),
541                                 intval($arr['uid'])
542                         );
543
544                         if (DBM::is_result($r)) {
545
546                                 // is the new message multi-level threaded?
547                                 // even though we don't support it now, preserve the info
548                                 // and re-attach to the conversation parent.
549
550                                 if ($r[0]['uri'] != $r[0]['parent-uri']) {
551                                         $arr['parent-uri'] = $r[0]['parent-uri'];
552                                         $z = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `parent-uri` = '%s' AND `uid` = %d
553                                                 ORDER BY `id` ASC LIMIT 1",
554                                                 dbesc($r[0]['parent-uri']),
555                                                 dbesc($r[0]['parent-uri']),
556                                                 intval($arr['uid'])
557                                         );
558
559                                         if (DBM::is_result($z)) {
560                                                 $r = $z;
561                                         }
562                                 }
563
564                                 $parent_id      = $r[0]['id'];
565                                 $parent_deleted = $r[0]['deleted'];
566                                 $allow_cid      = $r[0]['allow_cid'];
567                                 $allow_gid      = $r[0]['allow_gid'];
568                                 $deny_cid       = $r[0]['deny_cid'];
569                                 $deny_gid       = $r[0]['deny_gid'];
570                                 $arr['wall']    = $r[0]['wall'];
571                                 $notify_type    = 'comment-new';
572
573                                 /*
574                                  * If the parent is private, force privacy for the entire conversation
575                                  * This differs from the above settings as it subtly allows comments from
576                                  * email correspondents to be private even if the overall thread is not.
577                                  */
578                                 if ($r[0]['private']) {
579                                         $arr['private'] = $r[0]['private'];
580                                 }
581
582                                 /*
583                                  * Edge case. We host a public forum that was originally posted to privately.
584                                  * The original author commented, but as this is a comment, the permissions
585                                  * weren't fixed up so it will still show the comment as private unless we fix it here.
586                                  */
587                                 if ((intval($r[0]['forum_mode']) == 1) && $r[0]['private']) {
588                                         $arr['private'] = 0;
589                                 }
590
591                                 // If its a post from myself then tag the thread as "mention"
592                                 logger("Checking if parent ".$parent_id." has to be tagged as mention for user ".$arr['uid'], LOGGER_DEBUG);
593                                 $u = q("SELECT `nickname` FROM `user` WHERE `uid` = %d", intval($arr['uid']));
594                                 if (DBM::is_result($u)) {
595                                         $self = normalise_link(System::baseUrl() . '/profile/' . $u[0]['nickname']);
596                                         logger("'myself' is ".$self." for parent ".$parent_id." checking against ".$arr['author-link']." and ".$arr['owner-link'], LOGGER_DEBUG);
597                                         if ((normalise_link($arr['author-link']) == $self) || (normalise_link($arr['owner-link']) == $self)) {
598                                                 dba::update('thread', ['mention' => true], ['iid' => $parent_id]);
599                                                 logger("tagged thread ".$parent_id." as mention for user ".$self, LOGGER_DEBUG);
600                                         }
601                                 }
602                         } else {
603                                 /*
604                                  * Allow one to see reply tweets from status.net even when
605                                  * we don't have or can't see the original post.
606                                  */
607                                 if ($force_parent) {
608                                         logger('$force_parent=true, reply converted to top-level post.');
609                                         $parent_id = 0;
610                                         $arr['parent-uri'] = $arr['uri'];
611                                         $arr['gravity'] = 0;
612                                 } else {
613                                         logger('item parent '.$arr['parent-uri'].' for '.$arr['uid'].' was not found - ignoring item');
614                                         return 0;
615                                 }
616
617                                 $parent_deleted = 0;
618                         }
619                 }
620
621                 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `network` IN ('%s', '%s') AND `uid` = %d LIMIT 1",
622                         dbesc($arr['uri']),
623                         dbesc($arr['network']),
624                         dbesc(NETWORK_DFRN),
625                         intval($arr['uid'])
626                 );
627                 if (DBM::is_result($r)) {
628                         logger('duplicated item with the same uri found. '.print_r($arr,true));
629                         return 0;
630                 }
631
632                 // On Friendica and Diaspora the GUID is unique
633                 if (in_array($arr['network'], [NETWORK_DFRN, NETWORK_DIASPORA])) {
634                         $r = q("SELECT `id` FROM `item` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
635                                 dbesc($arr['guid']),
636                                 intval($arr['uid'])
637                         );
638                         if (DBM::is_result($r)) {
639                                 logger('duplicated item with the same guid found. '.print_r($arr,true));
640                                 return 0;
641                         }
642                 } else {
643                         // Check for an existing post with the same content. There seems to be a problem with OStatus.
644                         $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['body']),
646                                 dbesc($arr['network']),
647                                 dbesc($arr['created']),
648                                 intval($arr['contact-id']),
649                                 intval($arr['uid'])
650                         );
651                         if (DBM::is_result($r)) {
652                                 logger('duplicated item with the same body found. '.print_r($arr,true));
653                                 return 0;
654                         }
655                 }
656
657                 // Is this item available in the global items (with uid=0)?
658                 if ($arr["uid"] == 0) {
659                         $arr["global"] = true;
660
661                         // Set the global flag on all items if this was a global item entry
662                         dba::update('item', ['global' => true], ['uri' => $arr["uri"]]);
663                 } else {
664                         $isglobal = q("SELECT `global` FROM `item` WHERE `uid` = 0 AND `uri` = '%s'", dbesc($arr["uri"]));
665
666                         $arr["global"] = (DBM::is_result($isglobal) && count($isglobal) > 0);
667                 }
668
669                 // ACL settings
670                 if (strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid)) {
671                         $private = 1;
672                 } else {
673                         $private = $arr['private'];
674                 }
675
676                 $arr["allow_cid"] = $allow_cid;
677                 $arr["allow_gid"] = $allow_gid;
678                 $arr["deny_cid"] = $deny_cid;
679                 $arr["deny_gid"] = $deny_gid;
680                 $arr["private"] = $private;
681                 $arr["deleted"] = $parent_deleted;
682
683                 // Fill the cache field
684                 put_item_in_cache($arr);
685
686                 if ($notify) {
687                         Addon::callHooks('post_local', $arr);
688                 } else {
689                         Addon::callHooks('post_remote', $arr);
690                 }
691
692                 // This array field is used to trigger some automatic reactions
693                 // It is mainly used in the "post_local" hook.
694                 unset($arr['api_source']);
695
696                 if (x($arr, 'cancel')) {
697                         logger('post cancelled by addon.');
698                         return 0;
699                 }
700
701                 /*
702                  * Check for already added items.
703                  * There is a timing issue here that sometimes creates double postings.
704                  * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
705                  */
706                 if ($arr["uid"] == 0) {
707                         $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = 0 LIMIT 1", dbesc(trim($arr['uri'])));
708                         if (DBM::is_result($r)) {
709                                 logger('Global item already stored. URI: '.$arr['uri'].' on network '.$arr['network'], LOGGER_DEBUG);
710                                 return 0;
711                         }
712                 }
713
714                 logger('' . print_r($arr,true), LOGGER_DATA);
715
716                 dba::transaction();
717                 $r = dba::insert('item', $arr);
718
719                 // When the item was successfully stored we fetch the ID of the item.
720                 if (DBM::is_result($r)) {
721                         $current_post = dba::lastInsertId();
722                 } else {
723                         // This can happen - for example - if there are locking timeouts.
724                         dba::rollback();
725
726                         // Store the data into a spool file so that we can try again later.
727
728                         // At first we restore the Diaspora signature that we removed above.
729                         if (isset($encoded_signature)) {
730                                 $arr['dsprsig'] = $encoded_signature;
731                         }
732
733                         // Now we store the data in the spool directory
734                         // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
735                         $file = 'item-'.round(microtime(true) * 10000).'-'.mt_rand().'.msg';
736
737                         $spoolpath = get_spoolpath();
738                         if ($spoolpath != "") {
739                                 $spool = $spoolpath.'/'.$file;
740                                 file_put_contents($spool, json_encode($arr));
741                                 logger("Item wasn't stored - Item was spooled into file ".$file, LOGGER_DEBUG);
742                         }
743                         return 0;
744                 }
745
746                 if ($current_post == 0) {
747                         // This is one of these error messages that never should occur.
748                         logger("couldn't find created item - we better quit now.");
749                         dba::rollback();
750                         return 0;
751                 }
752
753                 // How much entries have we created?
754                 // We wouldn't need this query when we could use an unique index - but MySQL has length problems with them.
755                 $r = q("SELECT COUNT(*) AS `entries` FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `network` = '%s'",
756                         dbesc($arr['uri']),
757                         intval($arr['uid']),
758                         dbesc($arr['network'])
759                 );
760
761                 if (!DBM::is_result($r)) {
762                         // This shouldn't happen, since COUNT always works when the database connection is there.
763                         logger("We couldn't count the stored entries. Very strange ...");
764                         dba::rollback();
765                         return 0;
766                 }
767
768                 if ($r[0]["entries"] > 1) {
769                         // There are duplicates. We delete our just created entry.
770                         logger('Duplicated post occurred. uri = ' . $arr['uri'] . ' uid = ' . $arr['uid']);
771
772                         // Yes, we could do a rollback here - but we are having many users with MyISAM.
773                         dba::delete('item', ['id' => $current_post]);
774                         dba::commit();
775                         return 0;
776                 } elseif ($r[0]["entries"] == 0) {
777                         // This really should never happen since we quit earlier if there were problems.
778                         logger("Something is terribly wrong. We haven't found our created entry.");
779                         dba::rollback();
780                         return 0;
781                 }
782
783                 logger('created item '.$current_post);
784                 self::updateContact($arr);
785
786                 if (!$parent_id || ($arr['parent-uri'] === $arr['uri'])) {
787                         $parent_id = $current_post;
788                 }
789
790                 // Set parent id
791                 dba::update('item', ['parent' => $parent_id], ['id' => $current_post]);
792
793                 $arr['id'] = $current_post;
794                 $arr['parent'] = $parent_id;
795
796                 // update the commented timestamp on the parent
797                 // Only update "commented" if it is really a comment
798                 if (($arr['verb'] == ACTIVITY_POST) || !Config::get("system", "like_no_comment")) {
799                         dba::update('item', ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
800                 } else {
801                         dba::update('item', ['changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
802                 }
803
804                 if ($dsprsig) {
805                         /*
806                          * Friendica servers lower than 3.4.3-2 had double encoded the signature ...
807                          * We can check for this condition when we decode and encode the stuff again.
808                          */
809                         if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) {
810                                 $dsprsig->signature = base64_decode($dsprsig->signature);
811                                 logger("Repaired double encoded signature from handle ".$dsprsig->signer, LOGGER_DEBUG);
812                         }
813
814                         dba::insert('sign', ['iid' => $current_post, 'signed_text' => $dsprsig->signed_text,
815                                                 'signature' => $dsprsig->signature, 'signer' => $dsprsig->signer]);
816                 }
817
818                 $deleted = self::tagDeliver($arr['uid'], $current_post);
819
820                 /*
821                  * current post can be deleted if is for a community page and no mention are
822                  * in it.
823                  */
824                 if (!$deleted && !$dontcache) {
825                         $r = q('SELECT * FROM `item` WHERE `id` = %d', intval($current_post));
826                         if (DBM::is_result($r) && (count($r) == 1)) {
827                                 if ($notify) {
828                                         Addon::callHooks('post_local_end', $r[0]);
829                                 } else {
830                                         Addon::callHooks('post_remote_end', $r[0]);
831                                 }
832                         } else {
833                                 logger('new item not found in DB, id ' . $current_post);
834                         }
835                 }
836
837                 if ($arr['parent-uri'] === $arr['uri']) {
838                         self::addThread($current_post);
839                 } else {
840                         self::updateThread($parent_id);
841                 }
842
843                 dba::commit();
844
845                 /*
846                  * Due to deadlock issues with the "term" table we are doing these steps after the commit.
847                  * This is not perfect - but a workable solution until we found the reason for the problem.
848                  */
849                 Term::insertFromTagFieldByItemId($current_post);
850                 Term::insertFromFileFieldByItemId($current_post);
851
852                 if ($arr['parent-uri'] === $arr['uri']) {
853                         self::addShadow($current_post);
854                 } else {
855                         self::addShadowPost($current_post);
856                 }
857
858                 check_user_notification($current_post);
859
860                 if ($notify) {
861                         Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "Notifier", $notify_type, $current_post);
862                 }
863
864                 return $current_post;
865         }
866
867         /**
868          * @brief Add a shadow entry for a given item id that is a thread starter
869          *
870          * We store every public item entry additionally with the user id "0".
871          * This is used for the community page and for the search.
872          * It is planned that in the future we will store public item entries only once.
873          *
874          * @param integer $itemid Item ID that should be added
875          */
876         public static function addShadow($itemid)
877         {
878                 $fields = ['uid', 'wall', 'private', 'moderated', 'visible', 'contact-id', 'deleted', 'network', 'author-id', 'owner-id'];
879                 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
880                 $item = dba::selectFirst('item', $fields, $condition);
881
882                 if (!DBM::is_result($item)) {
883                         return;
884                 }
885
886                 // is it already a copy?
887                 if (($itemid == 0) || ($item['uid'] == 0)) {
888                         return;
889                 }
890
891                 // Is it a visible public post?
892                 if (!$item["visible"] || $item["deleted"] || $item["moderated"] || $item["private"]) {
893                         return;
894                 }
895
896                 // is it an entry from a connector? Only add an entry for natively connected networks
897                 if (!in_array($item["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""])) {
898                         return;
899                 }
900
901                 // Is the public contact configured as hidden?
902                 if (Contact::isHidden($item["owner-id"]) || Contact::isHidden($item["author-id"])) {
903                         return;
904                 }
905
906                 // Only do these checks if the post isn't a wall post
907                 if (!$item["wall"]) {
908                         // Check, if hide-friends is activated - then don't do a shadow entry
909                         if (dba::exists('profile', ['is-default' => true, 'uid' => $item['uid'], 'hide-friends' => true])) {
910                                 return;
911                         }
912
913                         // Check if the contact is hidden or blocked
914                         if (!dba::exists('contact', ['hidden' => false, 'blocked' => false, 'id' => $item['contact-id']])) {
915                                 return;
916                         }
917                 }
918
919                 // Only add a shadow, if the profile isn't hidden
920                 if (dba::exists('user', ['uid' => $item['uid'], 'hidewall' => true])) {
921                         return;
922                 }
923
924                 $item = dba::selectFirst('item', [], ['id' => $itemid]);
925
926                 if (DBM::is_result($item) && ($item["allow_cid"] == '')  && ($item["allow_gid"] == '') &&
927                         ($item["deny_cid"] == '') && ($item["deny_gid"] == '')) {
928
929                         if (!dba::exists('item', ['uri' => $item['uri'], 'uid' => 0])) {
930                                 // Preparing public shadow (removing user specific data)
931                                 unset($item['id']);
932                                 $item['uid'] = 0;
933                                 $item['origin'] = 0;
934                                 $item['wall'] = 0;
935                                 $item['contact-id'] = Contact::getIdForURL($item['author-link'], 0);
936
937                                 if (in_array($item['type'], ["net-comment", "wall-comment"])) {
938                                         $item['type'] = 'remote-comment';
939                                 } elseif ($item['type'] == 'wall') {
940                                         $item['type'] = 'remote';
941                                 }
942
943                                 $public_shadow = self::insert($item, false, false, true);
944
945                                 logger("Stored public shadow for thread ".$itemid." under id ".$public_shadow, LOGGER_DEBUG);
946                         }
947                 }
948         }
949
950         /**
951          * @brief Add a shadow entry for a given item id that is a comment
952          *
953          * This function does the same like the function above - but for comments
954          *
955          * @param integer $itemid Item ID that should be added
956          */
957         public static function addShadowPost($itemid)
958         {
959                 $item = dba::selectFirst('item', [], ['id' => $itemid]);
960                 if (!DBM::is_result($item)) {
961                         return;
962                 }
963
964                 // Is it a toplevel post?
965                 if ($item['id'] == $item['parent']) {
966                         self::addShadow($itemid);
967                         return;
968                 }
969
970                 // Is this a shadow entry?
971                 if ($item['uid'] == 0)
972                         return;
973
974                 // Is there a shadow parent?
975                 if (!dba::exists('item', ['uri' => $item['parent-uri'], 'uid' => 0])) {
976                         return;
977                 }
978
979                 // Is there already a shadow entry?
980                 if (dba::exists('item', ['uri' => $item['uri'], 'uid' => 0])) {
981                         return;
982                 }
983
984                 // Preparing public shadow (removing user specific data)
985                 unset($item['id']);
986                 $item['uid'] = 0;
987                 $item['origin'] = 0;
988                 $item['wall'] = 0;
989                 $item['contact-id'] = Contact::getIdForURL($item['author-link'], 0);
990
991                 if (in_array($item['type'], ["net-comment", "wall-comment"])) {
992                         $item['type'] = 'remote-comment';
993                 } elseif ($item['type'] == 'wall') {
994                         $item['type'] = 'remote';
995                 }
996
997                 $public_shadow = self::insert($item, false, false, true);
998
999                 logger("Stored public shadow for comment ".$item['uri']." under id ".$public_shadow, LOGGER_DEBUG);
1000         }
1001
1002          /**
1003          * Adds a "lang" specification in a "postopts" element of given $arr,
1004          * if possible and not already present.
1005          * Expects "body" element to exist in $arr.
1006          */
1007         private static function addLanguageInPostopts(&$arr)
1008         {
1009                 if (x($arr, 'postopts')) {
1010                         if (strstr($arr['postopts'], 'lang=')) {
1011                                 // do not override
1012                                 return;
1013                         }
1014                         $postopts = $arr['postopts'];
1015                 } else {
1016                         $postopts = "";
1017                 }
1018
1019                 $naked_body = preg_replace('/\[(.+?)\]/','', $arr['body']);
1020                 $l = new Text_LanguageDetect();
1021                 $lng = $l->detect($naked_body, 3);
1022
1023                 if (sizeof($lng) > 0) {
1024                         if ($postopts != "") {
1025                                 $postopts .= '&'; // arbitrary separator, to be reviewed
1026                         }
1027
1028                         $postopts .= 'lang=';
1029                         $sep = "";
1030
1031                         foreach ($lng as $language => $score) {
1032                                 $postopts .= $sep . $language . ";" . $score;
1033                                 $sep = ':';
1034                         }
1035                         $arr['postopts'] = $postopts;
1036                 }
1037         }
1038
1039         /**
1040          * @brief Creates an unique guid out of a given uri
1041          *
1042          * @param string $uri uri of an item entry
1043          * @param string $host (Optional) hostname for the GUID prefix
1044          * @return string unique guid
1045          */
1046         public static function guidFromUri($uri, $host = "")
1047         {
1048                 // Our regular guid routine is using this kind of prefix as well
1049                 // We have to avoid that different routines could accidentally create the same value
1050                 $parsed = parse_url($uri);
1051
1052                 // When the hostname isn't given, we take it from the uri
1053                 if ($host == "") {
1054                         // Is it in the format data@host.tld?
1055                         if ((count($parsed) == 1) && strstr($uri, '@')) {
1056                                 $mailparts = explode('@', $uri);
1057                                 $host = array_pop($mailparts);
1058                         } else {
1059                                 $host = $parsed["host"];
1060                         }
1061                 }
1062
1063                 // We use a hash of the hostname as prefix for the guid
1064                 $guid_prefix = hash("crc32", $host);
1065
1066                 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
1067                 unset($parsed["scheme"]);
1068
1069                 // Glue it together to be able to make a hash from it
1070                 $host_id = implode("/", $parsed);
1071
1072                 // We could use any hash algorithm since it isn't a security issue
1073                 $host_hash = hash("ripemd128", $host_id);
1074
1075                 return $guid_prefix.$host_hash;
1076         }
1077
1078         /**
1079          * @brief Set "success_update" and "last-item" to the date of the last time we heard from this contact
1080          *
1081          * This can be used to filter for inactive contacts.
1082          * Only do this for public postings to avoid privacy problems, since poco data is public.
1083          * Don't set this value if it isn't from the owner (could be an author that we don't know)
1084          *
1085          * @param array $arr Contains the just posted item record
1086          */
1087         private static function updateContact($arr)
1088         {
1089                 // Unarchive the author
1090                 $contact = dba::selectFirst('contact', [], ['id' => $arr["author-link"]]);
1091                 if ($contact['term-date'] > NULL_DATE) {
1092                          Contact::unmarkForArchival($contact);
1093                 }
1094
1095                 // Unarchive the contact if it is a toplevel posting
1096                 if ($arr["parent-uri"] === $arr["uri"]) {
1097                         $contact = dba::selectFirst('contact', [], ['id' => $arr["contact-id"]]);
1098                         if ($contact['term-date'] > NULL_DATE) {
1099                                  Contact::unmarkForArchival($contact);
1100                         }
1101                 }
1102
1103                 $update = (!$arr['private'] && (($arr["author-link"] === $arr["owner-link"]) || ($arr["parent-uri"] === $arr["uri"])));
1104
1105                 // Is it a forum? Then we don't care about the rules from above
1106                 if (!$update && ($arr["network"] == NETWORK_DFRN) && ($arr["parent-uri"] === $arr["uri"])) {
1107                         $isforum = q("SELECT `forum` FROM `contact` WHERE `id` = %d AND `forum`",
1108                                         intval($arr['contact-id']));
1109                         if (DBM::is_result($isforum)) {
1110                                 $update = true;
1111                         }
1112                 }
1113
1114                 if ($update) {
1115                         dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
1116                                 ['id' => $arr['contact-id']]);
1117                 }
1118                 // Now do the same for the system wide contacts with uid=0
1119                 if (!$arr['private']) {
1120                         dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
1121                                 ['id' => $arr['owner-id']]);
1122
1123                         if ($arr['owner-id'] != $arr['author-id']) {
1124                                 dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
1125                                         ['id' => $arr['author-id']]);
1126                         }
1127                 }
1128         }
1129
1130         private static function setHashtags(&$item)
1131         {
1132
1133                 $tags = get_tags($item["body"]);
1134
1135                 // No hashtags?
1136                 if (!count($tags)) {
1137                         return false;
1138                 }
1139
1140                 // This sorting is important when there are hashtags that are part of other hashtags
1141                 // Otherwise there could be problems with hashtags like #test and #test2
1142                 rsort($tags);
1143
1144                 $URLSearchString = "^\[\]";
1145
1146                 // All hashtags should point to the home server if "local_tags" is activated
1147                 if (Config::get('system', 'local_tags')) {
1148                         $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1149                                         "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["body"]);
1150
1151                         $item["tag"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1152                                         "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["tag"]);
1153                 }
1154
1155                 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
1156                 $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1157                         function ($match) {
1158                                 return ("[url=" . str_replace("#", "&num;", $match[1]) . "]" . str_replace("#", "&num;", $match[2]) . "[/url]");
1159                         }, $item["body"]);
1160
1161                 $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
1162                         function ($match) {
1163                                 return ("[bookmark=" . str_replace("#", "&num;", $match[1]) . "]" . str_replace("#", "&num;", $match[2]) . "[/bookmark]");
1164                         }, $item["body"]);
1165
1166                 $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
1167                         function ($match) {
1168                                 return ("[attachment " . str_replace("#", "&num;", $match[1]) . "]" . $match[2] . "[/attachment]");
1169                         }, $item["body"]);
1170
1171                 // Repair recursive urls
1172                 $item["body"] = preg_replace("/&num;\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1173                                 "&num;$2", $item["body"]);
1174
1175                 foreach ($tags as $tag) {
1176                         if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=')) {
1177                                 continue;
1178                         }
1179
1180                         $basetag = str_replace('_',' ',substr($tag,1));
1181
1182                         $newtag = '#[url=' . System::baseUrl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1183
1184                         $item["body"] = str_replace($tag, $newtag, $item["body"]);
1185
1186                         if (!stristr($item["tag"], "/search?tag=" . $basetag . "]" . $basetag . "[/url]")) {
1187                                 if (strlen($item["tag"])) {
1188                                         $item["tag"] = ','.$item["tag"];
1189                                 }
1190                                 $item["tag"] = $newtag.$item["tag"];
1191                         }
1192                 }
1193
1194                 // Convert back the masked hashtags
1195                 $item["body"] = str_replace("&num;", "#", $item["body"]);
1196         }
1197
1198         public static function getGuidById($id)
1199         {
1200                 $r = q("SELECT `guid` FROM `item` WHERE `id` = %d LIMIT 1", intval($id));
1201                 if (DBM::is_result($r)) {
1202                         return $r[0]["guid"];
1203                 } else {
1204                         return "";
1205                 }
1206         }
1207
1208         public static function getIdAndNickByGuid($guid, $uid = 0)
1209         {
1210                 $nick = "";
1211                 $id = 0;
1212
1213                 if ($uid == 0) {
1214                         $uid == local_user();
1215                 }
1216
1217                 // Does the given user have this item?
1218                 if ($uid) {
1219                         $r = q("SELECT `item`.`id`, `user`.`nickname` FROM `item` INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
1220                                 WHERE `item`.`visible` = 1 AND `item`.`deleted` = 0 AND `item`.`moderated` = 0
1221                                         AND `item`.`guid` = '%s' AND `item`.`uid` = %d", dbesc($guid), intval($uid));
1222                         if (DBM::is_result($r)) {
1223                                 $id = $r[0]["id"];
1224                                 $nick = $r[0]["nickname"];
1225                         }
1226                 }
1227
1228                 // Or is it anywhere on the server?
1229                 if ($nick == "") {
1230                         $r = q("SELECT `item`.`id`, `user`.`nickname` FROM `item` INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
1231                                 WHERE `item`.`visible` = 1 AND `item`.`deleted` = 0 AND `item`.`moderated` = 0
1232                                         AND `item`.`allow_cid` = ''  AND `item`.`allow_gid` = ''
1233                                         AND `item`.`deny_cid`  = '' AND `item`.`deny_gid`  = ''
1234                                         AND `item`.`private` = 0 AND `item`.`wall` = 1
1235                                         AND `item`.`guid` = '%s'", dbesc($guid));
1236                         if (DBM::is_result($r)) {
1237                                 $id = $r[0]["id"];
1238                                 $nick = $r[0]["nickname"];
1239                         }
1240                 }
1241                 return ["nick" => $nick, "id" => $id];
1242         }
1243
1244         /**
1245          * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
1246          * @param int $uid
1247          * @param int $item_id
1248          * @return bool true if item was deleted, else false
1249          */
1250         private static function tagDeliver($uid, $item_id)
1251         {
1252                 $mention = false;
1253
1254                 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
1255                         intval($uid)
1256                 );
1257                 if (!DBM::is_result($u)) {
1258                         return;
1259                 }
1260
1261                 $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
1262                 $prvgroup = (($u[0]['page-flags'] == PAGE_PRVGROUP) ? true : false);
1263
1264                 $i = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1265                         intval($item_id),
1266                         intval($uid)
1267                 );
1268                 if (!DBM::is_result($i)) {
1269                         return;
1270                 }
1271
1272                 $item = $i[0];
1273
1274                 $link = normalise_link(System::baseUrl() . '/profile/' . $u[0]['nickname']);
1275
1276                 /*
1277                  * Diaspora uses their own hardwired link URL in @-tags
1278                  * instead of the one we supply with webfinger
1279                  */
1280                 $dlink = normalise_link(System::baseUrl() . '/u/' . $u[0]['nickname']);
1281
1282                 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
1283                 if ($cnt) {
1284                         foreach ($matches as $mtch) {
1285                                 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
1286                                         $mention = true;
1287                                         logger('mention found: ' . $mtch[2]);
1288                                 }
1289                         }
1290                 }
1291
1292                 if (!$mention) {
1293                         if (($community_page || $prvgroup) &&
1294                                   !$item['wall'] && !$item['origin'] && ($item['id'] == $item['parent'])) {
1295                                 // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
1296                                 // delete it!
1297                                 logger("no-mention top-level post to communuty or private group. delete.");
1298                                 dba::delete('item', ['id' => $item_id]);
1299                                 return true;
1300                         }
1301                         return;
1302                 }
1303
1304                 $arr = ['item' => $item, 'user' => $u[0], 'contact' => $r[0]];
1305
1306                 Addon::callHooks('tagged', $arr);
1307
1308                 if (!$community_page && !$prvgroup) {
1309                         return;
1310                 }
1311
1312                 /*
1313                  * tgroup delivery - setup a second delivery chain
1314                  * prevent delivery looping - only proceed
1315                  * if the message originated elsewhere and is a top-level post
1316                  */
1317                 if ($item['wall'] || $item['origin'] || ($item['id'] != $item['parent'])) {
1318                         return;
1319                 }
1320
1321                 // now change this copy of the post to a forum head message and deliver to all the tgroup members
1322                 $c = q("SELECT `name`, `url`, `thumb` FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1323                         intval($u[0]['uid'])
1324                 );
1325                 if (!DBM::is_result($c)) {
1326                         return;
1327                 }
1328
1329                 // also reset all the privacy bits to the forum default permissions
1330
1331                 $private = ($u[0]['allow_cid'] || $u[0]['allow_gid'] || $u[0]['deny_cid'] || $u[0]['deny_gid']) ? 1 : 0;
1332
1333                 $forum_mode = (($prvgroup) ? 2 : 1);
1334
1335                 q("UPDATE `item` SET `wall` = 1, `origin` = 1, `forum_mode` = %d, `owner-name` = '%s', `owner-link` = '%s', `owner-avatar` = '%s',
1336                         `private` = %d, `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s'  WHERE `id` = %d",
1337                         intval($forum_mode),
1338                         dbesc($c[0]['name']),
1339                         dbesc($c[0]['url']),
1340                         dbesc($c[0]['thumb']),
1341                         intval($private),
1342                         dbesc($u[0]['allow_cid']),
1343                         dbesc($u[0]['allow_gid']),
1344                         dbesc($u[0]['deny_cid']),
1345                         dbesc($u[0]['deny_gid']),
1346                         intval($item_id)
1347                 );
1348                 self::updateThread($item_id);
1349
1350                 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', 'tgroup', $item_id);
1351
1352         }
1353
1354         public static function isRemoteSelf($contact, &$datarray)
1355         {
1356                 $a = get_app();
1357
1358                 if (!$contact['remote_self']) {
1359                         return false;
1360                 }
1361
1362                 // Prevent the forwarding of posts that are forwarded
1363                 if ($datarray["extid"] == NETWORK_DFRN) {
1364                         return false;
1365                 }
1366
1367                 // Prevent to forward already forwarded posts
1368                 if ($datarray["app"] == $a->get_hostname()) {
1369                         return false;
1370                 }
1371
1372                 // Only forward posts
1373                 if ($datarray["verb"] != ACTIVITY_POST) {
1374                         return false;
1375                 }
1376
1377                 if (($contact['network'] != NETWORK_FEED) && $datarray['private']) {
1378                         return false;
1379                 }
1380
1381                 $datarray2 = $datarray;
1382                 logger('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), LOGGER_DEBUG);
1383                 if ($contact['remote_self'] == 2) {
1384                         $r = q("SELECT `id`,`url`,`name`,`thumb` FROM `contact` WHERE `uid` = %d AND `self`",
1385                                 intval($contact['uid']));
1386                         if (DBM::is_result($r)) {
1387                                 $datarray['contact-id'] = $r[0]["id"];
1388
1389                                 $datarray['owner-name'] = $r[0]["name"];
1390                                 $datarray['owner-link'] = $r[0]["url"];
1391                                 $datarray['owner-avatar'] = $r[0]["thumb"];
1392
1393                                 $datarray['author-name']   = $datarray['owner-name'];
1394                                 $datarray['author-link']   = $datarray['owner-link'];
1395                                 $datarray['author-avatar'] = $datarray['owner-avatar'];
1396
1397                                 unset($datarray['created']);
1398                                 unset($datarray['edited']);
1399                         }
1400
1401                         if ($contact['network'] != NETWORK_FEED) {
1402                                 $datarray["guid"] = get_guid(32);
1403                                 unset($datarray["plink"]);
1404                                 $datarray["uri"] = item_new_uri($a->get_hostname(), $contact['uid'], $datarray["guid"]);
1405                                 $datarray["parent-uri"] = $datarray["uri"];
1406                                 $datarray["extid"] = $contact['network'];
1407                                 $urlpart = parse_url($datarray2['author-link']);
1408                                 $datarray["app"] = $urlpart["host"];
1409                         } else {
1410                                 $datarray['private'] = 0;
1411                         }
1412                 }
1413
1414                 if ($contact['network'] != NETWORK_FEED) {
1415                         // Store the original post
1416                         $r = self::insert($datarray2, false, false);
1417                         logger('remote-self post original item - Contact '.$contact['url'].' return '.$r.' Item '.print_r($datarray2, true), LOGGER_DEBUG);
1418                 } else {
1419                         $datarray["app"] = "Feed";
1420                 }
1421
1422                 // Trigger automatic reactions for addons
1423                 $datarray['api_source'] = true;
1424
1425                 // We have to tell the hooks who we are - this really should be improved
1426                 $_SESSION["authenticated"] = true;
1427                 $_SESSION["uid"] = $contact['uid'];
1428
1429                 return true;
1430         }
1431
1432         /**
1433          *
1434          * @param string $s
1435          * @param int    $uid
1436          * @param array  $item
1437          * @param int    $cid
1438          * @return string
1439          */
1440         public static function fixPrivatePhotos($s, $uid, $item = null, $cid = 0)
1441         {
1442                 if (Config::get('system', 'disable_embedded')) {
1443                         return $s;
1444                 }
1445
1446                 logger('check for photos', LOGGER_DEBUG);
1447                 $site = substr(System::baseUrl(), strpos(System::baseUrl(), '://'));
1448
1449                 $orig_body = $s;
1450                 $new_body = '';
1451
1452                 $img_start = strpos($orig_body, '[img');
1453                 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
1454                 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
1455
1456                 while (($img_st_close !== false) && ($img_len !== false)) {
1457                         $img_st_close++; // make it point to AFTER the closing bracket
1458                         $image = substr($orig_body, $img_start + $img_st_close, $img_len);
1459
1460                         logger('found photo ' . $image, LOGGER_DEBUG);
1461
1462                         if (stristr($image, $site . '/photo/')) {
1463                                 // Only embed locally hosted photos
1464                                 $replace = false;
1465                                 $i = basename($image);
1466                                 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
1467                                 $x = strpos($i, '-');
1468
1469                                 if ($x) {
1470                                         $res = substr($i, $x + 1);
1471                                         $i = substr($i, 0, $x);
1472                                         $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
1473                                                 dbesc($i),
1474                                                 intval($res),
1475                                                 intval($uid)
1476                                         );
1477                                         if (DBM::is_result($r)) {
1478                                                 /*
1479                                                  * Check to see if we should replace this photo link with an embedded image
1480                                                  * 1. No need to do so if the photo is public
1481                                                  * 2. If there's a contact-id provided, see if they're in the access list
1482                                                  *    for the photo. If so, embed it.
1483                                                  * 3. Otherwise, if we have an item, see if the item permissions match the photo
1484                                                  *    permissions, regardless of order but first check to see if they're an exact
1485                                                  *    match to save some processing overhead.
1486                                                  */
1487                                                 if (self::hasPermissions($r[0])) {
1488                                                         if ($cid) {
1489                                                                 $recips = self::enumeratePermissions($r[0]);
1490                                                                 if (in_array($cid, $recips)) {
1491                                                                         $replace = true;
1492                                                                 }
1493                                                         } elseif ($item) {
1494                                                                 if (self::samePermissions($item, $r[0])) {
1495                                                                         $replace = true;
1496                                                                 }
1497                                                         }
1498                                                 }
1499                                                 if ($replace) {
1500                                                         $data = $r[0]['data'];
1501                                                         $type = $r[0]['type'];
1502
1503                                                         // If a custom width and height were specified, apply before embedding
1504                                                         if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
1505                                                                 logger('scaling photo', LOGGER_DEBUG);
1506
1507                                                                 $width = intval($match[1]);
1508                                                                 $height = intval($match[2]);
1509
1510                                                                 $Image = new Image($data, $type);
1511                                                                 if ($Image->isValid()) {
1512                                                                         $Image->scaleDown(max($width, $height));
1513                                                                         $data = $Image->asString();
1514                                                                         $type = $Image->getType();
1515                                                                 }
1516                                                         }
1517
1518                                                         logger('replacing photo', LOGGER_DEBUG);
1519                                                         $image = 'data:' . $type . ';base64,' . base64_encode($data);
1520                                                         logger('replaced: ' . $image, LOGGER_DATA);
1521                                                 }
1522                                         }
1523                                 }
1524                         }
1525
1526                         $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
1527                         $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
1528                         if ($orig_body === false) {
1529                                 $orig_body = '';
1530                         }
1531
1532                         $img_start = strpos($orig_body, '[img');
1533                         $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
1534                         $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
1535                 }
1536
1537                 $new_body = $new_body . $orig_body;
1538
1539                 return $new_body;
1540         }
1541
1542         private static function hasPermissions($obj)
1543         {
1544                 return (
1545                         (
1546                                 x($obj, 'allow_cid')
1547                         ) || (
1548                                 x($obj, 'allow_gid')
1549                         ) || (
1550                                 x($obj, 'deny_cid')
1551                         ) || (
1552                                 x($obj, 'deny_gid')
1553                         )
1554                 );
1555         }
1556
1557         private static function samePermissions($obj1, $obj2)
1558         {
1559                 // first part is easy. Check that these are exactly the same.
1560                 if (($obj1['allow_cid'] == $obj2['allow_cid'])
1561                         && ($obj1['allow_gid'] == $obj2['allow_gid'])
1562                         && ($obj1['deny_cid'] == $obj2['deny_cid'])
1563                         && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
1564                         return true;
1565                 }
1566
1567                 // This is harder. Parse all the permissions and compare the resulting set.
1568                 $recipients1 = self::enumeratePermissions($obj1);
1569                 $recipients2 = self::enumeratePermissions($obj2);
1570                 sort($recipients1);
1571                 sort($recipients2);
1572
1573                 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
1574                 return ($recipients1 == $recipients2);
1575         }
1576
1577         // returns an array of contact-ids that are allowed to see this object
1578         private static function enumeratePermissions($obj)
1579         {
1580                 $allow_people = expand_acl($obj['allow_cid']);
1581                 $allow_groups = Group::expand(expand_acl($obj['allow_gid']));
1582                 $deny_people  = expand_acl($obj['deny_cid']);
1583                 $deny_groups  = Group::expand(expand_acl($obj['deny_gid']));
1584                 $recipients   = array_unique(array_merge($allow_people, $allow_groups));
1585                 $deny         = array_unique(array_merge($deny_people, $deny_groups));
1586                 $recipients   = array_diff($recipients, $deny);
1587                 return $recipients;
1588         }
1589
1590         public static function getFeedTags($item)
1591         {
1592                 $ret = [];
1593                 $matches = false;
1594                 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
1595                 if ($cnt) {
1596                         for ($x = 0; $x < $cnt; $x ++) {
1597                                 if ($matches[1][$x]) {
1598                                         $ret[$matches[2][$x]] = ['#', $matches[1][$x], $matches[2][$x]];
1599                                 }
1600                         }
1601                 }
1602                 $matches = false;
1603                 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
1604                 if ($cnt) {
1605                         for ($x = 0; $x < $cnt; $x ++) {
1606                                 if ($matches[1][$x]) {
1607                                         $ret[] = ['@', $matches[1][$x], $matches[2][$x]];
1608                                 }
1609                         }
1610                 }
1611                 return $ret;
1612         }
1613
1614         public static function expire($uid, $days, $network = "", $force = false)
1615         {
1616                 if (!$uid || ($days < 1)) {
1617                         return;
1618                 }
1619
1620                 /*
1621                  * $expire_network_only = save your own wall posts
1622                  * and just expire conversations started by others
1623                  */
1624                 $expire_network_only = PConfig::get($uid,'expire', 'network_only');
1625                 $sql_extra = (intval($expire_network_only) ? " AND wall = 0 " : "");
1626
1627                 if ($network != "") {
1628                         $sql_extra .= sprintf(" AND network = '%s' ", dbesc($network));
1629
1630                         /*
1631                          * There is an index "uid_network_received" but not "uid_network_created"
1632                          * This avoids the creation of another index just for one purpose.
1633                          * And it doesn't really matter wether to look at "received" or "created"
1634                          */
1635                         $range = "AND `received` < UTC_TIMESTAMP() - INTERVAL %d DAY ";
1636                 } else {
1637                         $range = "AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY ";
1638                 }
1639
1640                 $r = q("SELECT `file`, `resource-id`, `starred`, `type`, `id` FROM `item`
1641                         WHERE `uid` = %d $range
1642                         AND `id` = `parent`
1643                         $sql_extra
1644                         AND `deleted` = 0",
1645                         intval($uid),
1646                         intval($days)
1647                 );
1648
1649                 if (!DBM::is_result($r)) {
1650                         return;
1651                 }
1652
1653                 $expire_items = PConfig::get($uid, 'expire', 'items', 1);
1654
1655                 // Forcing expiring of items - but not notes and marked items
1656                 if ($force) {
1657                         $expire_items = true;
1658                 }
1659
1660                 $expire_notes = PConfig::get($uid, 'expire', 'notes', 1);
1661                 $expire_starred = PConfig::get($uid, 'expire', 'starred', 1);
1662                 $expire_photos = PConfig::get($uid, 'expire', 'photos', 0);
1663
1664                 logger('User '.$uid.': expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
1665
1666                 foreach ($r as $item) {
1667
1668                         // don't expire filed items
1669
1670                         if (strpos($item['file'],'[') !== false) {
1671                                 continue;
1672                         }
1673
1674                         // Only expire posts, not photos and photo comments
1675
1676                         if ($expire_photos == 0 && strlen($item['resource-id'])) {
1677                                 continue;
1678                         } elseif ($expire_starred == 0 && intval($item['starred'])) {
1679                                 continue;
1680                         } elseif ($expire_notes == 0 && $item['type'] == 'note') {
1681                                 continue;
1682                         } elseif ($expire_items == 0 && $item['type'] != 'note') {
1683                                 continue;
1684                         }
1685
1686                         self::deleteById($item['id'], PRIORITY_LOW);
1687                 }
1688         }
1689
1690         /// @TODO: This query seems to be really slow
1691         public static function firstPostDate($uid, $wall = false)
1692         {
1693                 $r = q("SELECT `id`, `created` FROM `item`
1694                         WHERE `uid` = %d AND `wall` = %d AND `deleted` = 0 AND `visible` = 1 AND `moderated` = 0
1695                         AND `id` = `parent`
1696                         ORDER BY `created` ASC LIMIT 1",
1697                         intval($uid),
1698                         intval($wall ? 1 : 0)
1699                 );
1700                 if (DBM::is_result($r)) {
1701                         return substr(DateTimeFormat::local($r[0]['created']),0,10);
1702                 }
1703                 return false;
1704         }
1705
1706         /**
1707          * @brief add/remove activity to an item
1708          *
1709          * Toggle activities as like,dislike,attend of an item
1710          *
1711          * @param string $item_id
1712          * @param string $verb
1713          *              Activity verb. One of
1714          *                      like, unlike, dislike, undislike, attendyes, unattendyes,
1715          *                      attendno, unattendno, attendmaybe, unattendmaybe
1716          * @hook 'post_local_end'
1717          *              array $arr
1718          *                      'post_id' => ID of posted item
1719          */
1720         public static function performLike($item_id, $verb)
1721         {
1722                 if (!local_user() && !remote_user()) {
1723                         return false;
1724                 }
1725
1726                 switch ($verb) {
1727                         case 'like':
1728                         case 'unlike':
1729                                 $bodyverb = L10n::t('%1$s likes %2$s\'s %3$s');
1730                                 $activity = ACTIVITY_LIKE;
1731                                 break;
1732                         case 'dislike':
1733                         case 'undislike':
1734                                 $bodyverb = L10n::t('%1$s doesn\'t like %2$s\'s %3$s');
1735                                 $activity = ACTIVITY_DISLIKE;
1736                                 break;
1737                         case 'attendyes':
1738                         case 'unattendyes':
1739                                 $bodyverb = L10n::t('%1$s is attending %2$s\'s %3$s');
1740                                 $activity = ACTIVITY_ATTEND;
1741                                 break;
1742                         case 'attendno':
1743                         case 'unattendno':
1744                                 $bodyverb = L10n::t('%1$s is not attending %2$s\'s %3$s');
1745                                 $activity = ACTIVITY_ATTENDNO;
1746                                 break;
1747                         case 'attendmaybe':
1748                         case 'unattendmaybe':
1749                                 $bodyverb = L10n::t('%1$s may attend %2$s\'s %3$s');
1750                                 $activity = ACTIVITY_ATTENDMAYBE;
1751                                 break;
1752                         default:
1753                                 logger('like: unknown verb ' . $verb . ' for item ' . $item_id);
1754                                 return false;
1755                 }
1756
1757                 // Enable activity toggling instead of on/off
1758                 $event_verb_flag = $activity === ACTIVITY_ATTEND || $activity === ACTIVITY_ATTENDNO || $activity === ACTIVITY_ATTENDMAYBE;
1759
1760                 logger('like: verb ' . $verb . ' item ' . $item_id);
1761
1762                 $item = dba::selectFirst('item', [], ['`id` = ? OR `uri` = ?', $item_id, $item_id]);
1763                 if (!DBM::is_result($item)) {
1764                         logger('like: unknown item ' . $item_id);
1765                         return false;
1766                 }
1767
1768                 $uid = $item['uid'];
1769                 if (($uid == 0) && local_user()) {
1770                         $uid = local_user();
1771                 }
1772
1773                 if (!can_write_wall($uid)) {
1774                         logger('like: unable to write on wall ' . $uid);
1775                         return false;
1776                 }
1777
1778                 // Retrieves the local post owner
1779                 $owner_self_contact = dba::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
1780                 if (!DBM::is_result($owner_self_contact)) {
1781                         logger('like: unknown owner ' . $uid);
1782                         return false;
1783                 }
1784
1785                 // Retrieve the current logged in user's public contact
1786                 $author_id = public_contact();
1787
1788                 $author_contact = dba::selectFirst('contact', [], ['id' => $author_id]);
1789                 if (!DBM::is_result($author_contact)) {
1790                         logger('like: unknown author ' . $author_id);
1791                         return false;
1792                 }
1793
1794                 // Contact-id is the uid-dependant author contact
1795                 if (local_user() == $uid) {
1796                         $item_contact_id = $owner_self_contact['id'];
1797                         $item_contact = $owner_self_contact;
1798                 } else {
1799                         $item_contact_id = Contact::getIdForURL($author_contact['url'], $uid);
1800                         $item_contact = dba::selectFirst('contact', [], ['id' => $item_contact_id]);
1801                         if (!DBM::is_result($item_contact)) {
1802                                 logger('like: unknown item contact ' . $item_contact_id);
1803                                 return false;
1804                         }
1805                 }
1806
1807                 // Look for an existing verb row
1808                 // event participation are essentially radio toggles. If you make a subsequent choice,
1809                 // we need to eradicate your first choice.
1810                 if ($event_verb_flag) {
1811                         $verbs = "'" . dbesc(ACTIVITY_ATTEND) . "', '" . dbesc(ACTIVITY_ATTENDNO) . "', '" . dbesc(ACTIVITY_ATTENDMAYBE) . "'";
1812                 } else {
1813                         $verbs = "'".dbesc($activity)."'";
1814                 }
1815
1816                 $existing_like = q("SELECT `id`, `guid`, `verb` FROM `item`
1817                         WHERE `verb` IN ($verbs)
1818                         AND `deleted` = 0
1819                         AND `author-id` = %d
1820                         AND `uid` = %d
1821                         AND (`parent` = '%s' OR `parent-uri` = '%s' OR `thr-parent` = '%s')
1822                         LIMIT 1",
1823                         intval($author_contact['id']),
1824                         intval($item['uid']),
1825                         dbesc($item_id), dbesc($item_id), dbesc($item['uri'])
1826                 );
1827
1828                 // If it exists, mark it as deleted
1829                 if (DBM::is_result($existing_like)) {
1830                         $like_item = $existing_like[0];
1831
1832                         // Already voted, undo it
1833                         $fields = ['deleted' => true, 'unseen' => true, 'changed' => DateTimeFormat::utcNow()];
1834                         dba::update('item', $fields, ['id' => $like_item['id']]);
1835
1836                         // Clean up the Diaspora signatures for this like
1837                         // Go ahead and do it even if Diaspora support is disabled. We still want to clean up
1838                         // if it had been enabled in the past
1839                         dba::delete('sign', ['iid' => $like_item['id']]);
1840
1841                         $like_item_id = $like_item['id'];
1842                         Worker::add(PRIORITY_HIGH, "Notifier", "like", $like_item_id);
1843
1844                         if (!$event_verb_flag || $like_item['verb'] == $activity) {
1845                                 return true;
1846                         }
1847                 }
1848
1849                 // Verb is "un-something", just trying to delete existing entries
1850                 if (strpos($verb, 'un') === 0) {
1851                         return true;
1852                 }
1853
1854                 // Else or if event verb different from existing row, create a new item row
1855                 $post_type = (($item['resource-id']) ? L10n::t('photo') : L10n::t('status'));
1856                 if ($item['object-type'] === ACTIVITY_OBJ_EVENT) {
1857                         $post_type = L10n::t('event');
1858                 }
1859                 $objtype = $item['resource-id'] ? ACTIVITY_OBJ_IMAGE : ACTIVITY_OBJ_NOTE ;
1860                 $link = xmlify('<link rel="alternate" type="text/html" href="' . System::baseUrl() . '/display/' . $owner_self_contact['nick'] . '/' . $item['id'] . '" />' . "\n") ;
1861                 $body = $item['body'];
1862
1863                 $obj = <<< EOT
1864
1865                 <object>
1866                         <type>$objtype</type>
1867                         <local>1</local>
1868                         <id>{$item['uri']}</id>
1869                         <link>$link</link>
1870                         <title></title>
1871                         <content>$body</content>
1872                 </object>
1873 EOT;
1874
1875                 $ulink = '[url=' . $author_contact['url'] . ']' . $author_contact['name'] . '[/url]';
1876                 $alink = '[url=' . $item['author-link'] . ']' . $item['author-name'] . '[/url]';
1877                 $plink = '[url=' . System::baseUrl() . '/display/' . $owner_self_contact['nick'] . '/' . $item['id'] . ']' . $post_type . '[/url]';
1878
1879                 $new_item = [
1880                         'guid'          => get_guid(32),
1881                         'uri'           => item_new_uri(self::getApp()->get_hostname(), $item['uid']),
1882                         'uid'           => $item['uid'],
1883                         'contact-id'    => $item_contact_id,
1884                         'type'          => 'activity',
1885                         'wall'          => $item['wall'],
1886                         'origin'        => 1,
1887                         'gravity'       => GRAVITY_LIKE,
1888                         'parent'        => $item['id'],
1889                         'parent-uri'    => $item['uri'],
1890                         'thr-parent'    => $item['uri'],
1891                         'owner-id'      => $item['owner-id'],
1892                         'owner-name'    => $item['owner-name'],
1893                         'owner-link'    => $item['owner-link'],
1894                         'owner-avatar'  => $item['owner-avatar'],
1895                         'author-id'     => $author_contact['id'],
1896                         'author-name'   => $author_contact['name'],
1897                         'author-link'   => $author_contact['url'],
1898                         'author-avatar' => $author_contact['thumb'],
1899                         'body'          => sprintf($bodyverb, $ulink, $alink, $plink),
1900                         'verb'          => $activity,
1901                         'object-type'   => $objtype,
1902                         'object'        => $obj,
1903                         'allow_cid'     => $item['allow_cid'],
1904                         'allow_gid'     => $item['allow_gid'],
1905                         'deny_cid'      => $item['deny_cid'],
1906                         'deny_gid'      => $item['deny_gid'],
1907                         'visible'       => 1,
1908                         'unseen'        => 1,
1909                 ];
1910
1911                 $new_item_id = self::insert($new_item);
1912
1913                 // If the parent item isn't visible then set it to visible
1914                 if (!$item['visible']) {
1915                         self::update(['visible' => true], ['id' => $item['id']]);
1916                 }
1917
1918                 // Save the author information for the like in case we need to relay to Diaspora
1919                 Diaspora::storeLikeSignature($item_contact, $new_item_id);
1920
1921                 $new_item['id'] = $new_item_id;
1922
1923                 Addon::callHooks('post_local_end', $new_item);
1924
1925                 Worker::add(PRIORITY_HIGH, "Notifier", "like", $new_item_id);
1926
1927                 return true;
1928         }
1929
1930         private static function addThread($itemid, $onlyshadow = false)
1931         {
1932                 $items = q("SELECT `uid`, `created`, `edited`, `commented`, `received`, `changed`, `wall`, `private`, `pubmail`,
1933                                 `moderated`, `visible`, `spam`, `starred`, `bookmark`, `contact-id`, `gcontact-id`,
1934                                 `deleted`, `origin`, `forum_mode`, `mention`, `network`, `author-id`, `owner-id`
1935                         FROM `item` WHERE `id` = %d AND (`parent` = %d OR `parent` = 0) LIMIT 1", intval($itemid), intval($itemid));
1936
1937                 if (!$items) {
1938                         return;
1939                 }
1940
1941                 $item = $items[0];
1942                 $item['iid'] = $itemid;
1943
1944                 if (!$onlyshadow) {
1945                         $result = dba::insert('thread', $item);
1946
1947                         logger("Add thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
1948                 }
1949         }
1950
1951         private static function updateThread($itemid, $setmention = false)
1952         {
1953                 $items = q("SELECT `uid`, `guid`, `title`, `body`, `created`, `edited`, `commented`, `received`, `changed`, `wall`, `private`, `pubmail`, `moderated`, `visible`, `spam`, `starred`, `bookmark`, `contact-id`, `gcontact-id`,
1954                                 `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));
1955
1956                 if (!DBM::is_result($items)) {
1957                         return;
1958                 }
1959
1960                 $item = $items[0];
1961
1962                 if ($setmention) {
1963                         $item["mention"] = 1;
1964                 }
1965
1966                 $sql = "";
1967
1968                 foreach ($item as $field => $data)
1969                         if (!in_array($field, ["guid", "title", "body", "rendered-html", "rendered-hash"])) {
1970                                 if ($sql != "") {
1971                                         $sql .= ", ";
1972                                 }
1973
1974                                 $sql .= "`".$field."` = '".dbesc($data)."'";
1975                         }
1976
1977                 $result = q("UPDATE `thread` SET ".$sql." WHERE `iid` = %d", intval($itemid));
1978
1979                 logger("Update thread for item ".$itemid." - guid ".$item["guid"]." - ".print_r($result, true)." ".print_r($item, true), LOGGER_DEBUG);
1980
1981                 // Updating a shadow item entry
1982                 $items = dba::selectFirst('item', ['id'], ['guid' => $item['guid'], 'uid' => 0]);
1983
1984                 if (!DBM::is_result($items)) {
1985                         return;
1986                 }
1987
1988                 $result = dba::update(
1989                         'item',
1990                         ['title' => $item['title'], 'body' => $item['body'], 'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']],
1991                         ['id' => $items['id']]
1992                 );
1993
1994                 logger("Updating public shadow for post ".$items["id"]." - guid ".$item["guid"]." Result: ".print_r($result, true), LOGGER_DEBUG);
1995         }
1996
1997         private static function deleteThread($itemid, $itemuri = "")
1998         {
1999                 $item = dba::selectFirst('thread', ['uid'], ['iid' => $itemid]);
2000                 if (!DBM::is_result($item)) {
2001                         logger('No thread found for id '.$itemid, LOGGER_DEBUG);
2002                         return;
2003                 }
2004
2005                 // Using dba::delete at this time could delete the associated item entries
2006                 $result = dba::e("DELETE FROM `thread` WHERE `iid` = ?", $itemid);
2007
2008                 logger("deleteThread: Deleted thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
2009
2010                 if ($itemuri != "") {
2011                         $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND NOT `deleted` AND NOT (`uid` IN (%d, 0))",
2012                                         dbesc($itemuri),
2013                                         intval($item["uid"])
2014                                 );
2015                         if (!DBM::is_result($r)) {
2016                                 dba::delete('item', ['uri' => $itemuri, 'uid' => 0]);
2017                                 logger("deleteThread: Deleted shadow for item ".$itemuri, LOGGER_DEBUG);
2018                         }
2019                 }
2020         }
2021 }