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