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