]> git.mxchange.org Git - friendica.git/blob - src/Model/Item.php
6c071bfc7fb7e1adec24c92a2f893dda94e0bea0
[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\Content\Text\BBCode;
11 use Friendica\Content\Text\HTML;
12 use Friendica\Core\Config;
13 use Friendica\Core\Hook;
14 use Friendica\Core\Lock;
15 use Friendica\Core\Logger;
16 use Friendica\Core\L10n;
17 use Friendica\Core\PConfig;
18 use Friendica\Core\Protocol;
19 use Friendica\Core\Renderer;
20 use Friendica\Core\System;
21 use Friendica\Core\Worker;
22 use Friendica\Database\DBA;
23 use Friendica\Model\Contact;
24 use Friendica\Model\Event;
25 use Friendica\Model\FileTag;
26 use Friendica\Model\PermissionSet;
27 use Friendica\Model\Term;
28 use Friendica\Model\ItemURI;
29 use Friendica\Model\Photo;
30 use Friendica\Model\Attach;
31 use Friendica\Object\Image;
32 use Friendica\Protocol\Diaspora;
33 use Friendica\Protocol\OStatus;
34 use Friendica\Util\DateTimeFormat;
35 use Friendica\Util\Map;
36 use Friendica\Util\XML;
37 use Friendica\Util\Security;
38 use Friendica\Util\Strings;
39 use Text_LanguageDetect;
40
41 class Item extends BaseObject
42 {
43         // Posting types, inspired by https://www.w3.org/TR/activitystreams-vocabulary/#object-types
44         const PT_ARTICLE = 0;
45         const PT_NOTE = 1;
46         const PT_PAGE = 2;
47         const PT_IMAGE = 16;
48         const PT_AUDIO = 17;
49         const PT_VIDEO = 18;
50         const PT_DOCUMENT = 19;
51         const PT_EVENT = 32;
52         const PT_PERSONAL_NOTE = 128;
53
54         // Field list that is used to display the items
55         const DISPLAY_FIELDLIST = [
56                 'uid', 'id', 'parent', 'uri', 'thr-parent', 'parent-uri', 'guid', 'network',
57                 'commented', 'created', 'edited', 'received', 'verb', 'object-type', 'postopts', 'plink',
58                 'wall', 'private', 'starred', 'origin', 'title', 'body', 'file', 'attach', 'language',
59                 'content-warning', 'location', 'coord', 'app', 'rendered-hash', 'rendered-html', 'object',
60                 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'item_id',
61                 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
62                 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'owner-network',
63                 'contact-id', 'contact-link', 'contact-name', 'contact-avatar',
64                 'writable', 'self', 'cid', 'alias',
65                 'event-id', 'event-created', 'event-edited', 'event-start', 'event-finish',
66                 'event-summary', 'event-desc', 'event-location', 'event-type',
67                 'event-nofinish', 'event-adjust', 'event-ignore', 'event-id',
68                 'delivery_queue_count', 'delivery_queue_done'
69         ];
70
71         // Field list that is used to deliver items via the protocols
72         const DELIVER_FIELDLIST = ['uid', 'id', 'parent', 'uri', 'thr-parent', 'parent-uri', 'guid',
73                         'created', 'edited', 'verb', 'object-type', 'object', 'target',
74                         'private', 'title', 'body', 'location', 'coord', 'app',
75                         'attach', 'tag', 'deleted', 'extid', 'post-type',
76                         'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
77                         'author-id', 'author-link', 'owner-link', 'contact-uid',
78                         'signed_text', 'signature', 'signer', 'network'];
79
80         // Field list for "item-content" table that is mixed with the item table
81         const MIXED_CONTENT_FIELDLIST = ['title', 'content-warning', 'body', 'location',
82                         'coord', 'app', 'rendered-hash', 'rendered-html', 'verb',
83                         'object-type', 'object', 'target-type', 'target', 'plink'];
84
85         // Field list for "item-content" table that is not present in the "item" table
86         const CONTENT_FIELDLIST = ['language'];
87
88         // All fields in the item table
89         const ITEM_FIELDLIST = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
90                         'contact-id', 'type', 'wall', 'gravity', 'extid', 'icid', 'iaid', 'psid',
91                         'created', 'edited', 'commented', 'received', 'changed', 'verb',
92                         'postopts', 'plink', 'resource-id', 'event-id', 'tag', 'attach', 'inform',
93                         'file', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'post-type',
94                         'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
95                         'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global', 'network',
96                         'title', 'content-warning', 'body', 'location', 'coord', 'app',
97                         'rendered-hash', 'rendered-html', 'object-type', 'object', 'target-type', 'target',
98                         'author-id', 'author-link', 'author-name', 'author-avatar',
99                         'owner-id', 'owner-link', 'owner-name', 'owner-avatar'];
100
101         // Never reorder or remove entries from this list. Just add new ones at the end, if needed.
102         // The item-activity table only stores the index and needs this array to know the matching activity.
103         const ACTIVITIES = [ACTIVITY_LIKE, ACTIVITY_DISLIKE, ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE];
104
105         private static $legacy_mode = null;
106
107         public static function isLegacyMode()
108         {
109                 if (is_null(self::$legacy_mode)) {
110                         self::$legacy_mode = (Config::get("system", "post_update_version") < 1279);
111                 }
112
113                 return self::$legacy_mode;
114         }
115
116         /**
117          * @brief returns an activity index from an activity string
118          *
119          * @param string $activity activity string
120          * @return integer Activity index
121          */
122         public static function activityToIndex($activity)
123         {
124                 $index = array_search($activity, self::ACTIVITIES);
125
126                 if (is_bool($index)) {
127                         $index = -1;
128                 }
129
130                 return $index;
131         }
132
133         /**
134          * @brief returns an activity string from an activity index
135          *
136          * @param integer $index activity index
137          * @return string Activity string
138          */
139         private static function indexToActivity($index)
140         {
141                 if (is_null($index) || !array_key_exists($index, self::ACTIVITIES)) {
142                         return '';
143                 }
144
145                 return self::ACTIVITIES[$index];
146         }
147
148         /**
149          * @brief Fetch a single item row
150          *
151          * @param mixed $stmt statement object
152          * @return array current row
153          */
154         public static function fetch($stmt)
155         {
156                 $row = DBA::fetch($stmt);
157
158                 if (is_bool($row)) {
159                         return $row;
160                 }
161
162                 // ---------------------- Transform item structure data ----------------------
163
164                 // We prefer the data from the user's contact over the public one
165                 if (!empty($row['author-link']) && !empty($row['contact-link']) &&
166                         ($row['author-link'] == $row['contact-link'])) {
167                         if (isset($row['author-avatar']) && !empty($row['contact-avatar'])) {
168                                 $row['author-avatar'] = $row['contact-avatar'];
169                         }
170                         if (isset($row['author-name']) && !empty($row['contact-name'])) {
171                                 $row['author-name'] = $row['contact-name'];
172                         }
173                 }
174
175                 if (!empty($row['owner-link']) && !empty($row['contact-link']) &&
176                         ($row['owner-link'] == $row['contact-link'])) {
177                         if (isset($row['owner-avatar']) && !empty($row['contact-avatar'])) {
178                                 $row['owner-avatar'] = $row['contact-avatar'];
179                         }
180                         if (isset($row['owner-name']) && !empty($row['contact-name'])) {
181                                 $row['owner-name'] = $row['contact-name'];
182                         }
183                 }
184
185                 // We can always comment on posts from these networks
186                 if (array_key_exists('writable', $row) &&
187                         in_array($row['internal-network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])) {
188                         $row['writable'] = true;
189                 }
190
191                 // ---------------------- Transform item content data ----------------------
192
193                 // Fetch data from the item-content table whenever there is content there
194                 if (self::isLegacyMode()) {
195                         $legacy_fields = array_merge(ItemDeliveryData::LEGACY_FIELD_LIST, self::MIXED_CONTENT_FIELDLIST);
196                         foreach ($legacy_fields as $field) {
197                                 if (empty($row[$field]) && !empty($row['internal-item-' . $field])) {
198                                         $row[$field] = $row['internal-item-' . $field];
199                                 }
200                                 unset($row['internal-item-' . $field]);
201                         }
202                 }
203
204                 if (!empty($row['internal-iaid']) && array_key_exists('verb', $row)) {
205                         $row['verb'] = self::indexToActivity($row['internal-activity']);
206                         if (array_key_exists('title', $row)) {
207                                 $row['title'] = '';
208                         }
209                         if (array_key_exists('body', $row)) {
210                                 $row['body'] = $row['verb'];
211                         }
212                         if (array_key_exists('object', $row)) {
213                                 $row['object'] = '';
214                         }
215                         if (array_key_exists('object-type', $row)) {
216                                 $row['object-type'] = ACTIVITY_OBJ_NOTE;
217                         }
218                 } elseif (array_key_exists('verb', $row) && in_array($row['verb'], ['', ACTIVITY_POST, ACTIVITY_SHARE])) {
219                         // Posts don't have an object or target - but having tags or files.
220                         // We safe some performance by building tag and file strings only here.
221                         // We remove object and target since they aren't used for this type.
222                         if (array_key_exists('object', $row)) {
223                                 $row['object'] = '';
224                         }
225                         if (array_key_exists('target', $row)) {
226                                 $row['target'] = '';
227                         }
228                 }
229
230                 if (!array_key_exists('verb', $row) || in_array($row['verb'], ['', ACTIVITY_POST, ACTIVITY_SHARE])) {
231                         // Build the tag string out of the term entries
232                         if (array_key_exists('tag', $row) && empty($row['tag'])) {
233                                 $row['tag'] = Term::tagTextFromItemId($row['internal-iid']);
234                         }
235
236                         // Build the file string out of the term entries
237                         if (array_key_exists('file', $row) && empty($row['file'])) {
238                                 $row['file'] = Term::fileTextFromItemId($row['internal-iid']);
239                         }
240                 }
241
242                 if (array_key_exists('signed_text', $row) && array_key_exists('interaction', $row) && !is_null($row['interaction'])) {
243                         $row['signed_text'] = $row['interaction'];
244                 }
245
246                 if (array_key_exists('ignored', $row) && array_key_exists('internal-user-ignored', $row) && !is_null($row['internal-user-ignored'])) {
247                         $row['ignored'] = $row['internal-user-ignored'];
248                 }
249
250                 // Remove internal fields
251                 unset($row['internal-activity']);
252                 unset($row['internal-network']);
253                 unset($row['internal-iid']);
254                 unset($row['internal-iaid']);
255                 unset($row['internal-icid']);
256                 unset($row['internal-user-ignored']);
257                 unset($row['interaction']);
258
259                 return $row;
260         }
261
262         /**
263          * @brief Fills an array with data from an item query
264          *
265          * @param object $stmt statement object
266          * @param bool   $do_close
267          * @return array Data array
268          */
269         public static function inArray($stmt, $do_close = true) {
270                 if (is_bool($stmt)) {
271                         return $stmt;
272                 }
273
274                 $data = [];
275                 while ($row = self::fetch($stmt)) {
276                         $data[] = $row;
277                 }
278                 if ($do_close) {
279                         DBA::close($stmt);
280                 }
281                 return $data;
282         }
283
284         /**
285          * @brief Check if item data exists
286          *
287          * @param array $condition array of fields for condition
288          *
289          * @return boolean Are there rows for that condition?
290          * @throws \Exception
291          */
292         public static function exists($condition) {
293                 $stmt = self::select(['id'], $condition, ['limit' => 1]);
294
295                 if (is_bool($stmt)) {
296                         $retval = $stmt;
297                 } else {
298                         $retval = (DBA::numRows($stmt) > 0);
299                 }
300
301                 DBA::close($stmt);
302
303                 return $retval;
304         }
305
306         /**
307          * Retrieve a single record from the item table for a given user and returns it in an associative array
308          *
309          * @brief Retrieve a single record from a table
310          * @param integer $uid User ID
311          * @param array   $selected
312          * @param array   $condition
313          * @param array   $params
314          * @return bool|array
315          * @throws \Exception
316          * @see   DBA::select
317          */
318         public static function selectFirstForUser($uid, array $selected = [], array $condition = [], $params = [])
319         {
320                 $params['uid'] = $uid;
321
322                 if (empty($selected)) {
323                         $selected = Item::DISPLAY_FIELDLIST;
324                 }
325
326                 return self::selectFirst($selected, $condition, $params);
327         }
328
329         /**
330          * @brief Select rows from the item table for a given user
331          *
332          * @param integer $uid       User ID
333          * @param array   $selected  Array of selected fields, empty for all
334          * @param array   $condition Array of fields for condition
335          * @param array   $params    Array of several parameters
336          *
337          * @return boolean|object
338          * @throws \Exception
339          */
340         public static function selectForUser($uid, array $selected = [], array $condition = [], $params = [])
341         {
342                 $params['uid'] = $uid;
343
344                 if (empty($selected)) {
345                         $selected = Item::DISPLAY_FIELDLIST;
346                 }
347
348                 return self::select($selected, $condition, $params);
349         }
350
351         /**
352          * Retrieve a single record from the item table and returns it in an associative array
353          *
354          * @brief Retrieve a single record from a table
355          * @param array $fields
356          * @param array $condition
357          * @param array $params
358          * @return bool|array
359          * @throws \Exception
360          * @see   DBA::select
361          */
362         public static function selectFirst(array $fields = [], array $condition = [], $params = [])
363         {
364                 $params['limit'] = 1;
365
366                 $result = self::select($fields, $condition, $params);
367
368                 if (is_bool($result)) {
369                         return $result;
370                 } else {
371                         $row = self::fetch($result);
372                         DBA::close($result);
373                         return $row;
374                 }
375         }
376
377         /**
378          * @brief Select rows from the item table
379          *
380          * @param array $selected  Array of selected fields, empty for all
381          * @param array $condition Array of fields for condition
382          * @param array $params    Array of several parameters
383          *
384          * @return boolean|object
385          * @throws \Exception
386          */
387         public static function select(array $selected = [], array $condition = [], $params = [])
388         {
389                 $uid = 0;
390                 $usermode = false;
391
392                 if (isset($params['uid'])) {
393                         $uid = $params['uid'];
394                         $usermode = true;
395                 }
396
397                 $fields = self::fieldlist($usermode);
398
399                 $select_fields = self::constructSelectFields($fields, $selected);
400
401                 $condition_string = DBA::buildCondition($condition);
402
403                 $condition_string = self::addTablesToFields($condition_string, $fields);
404
405                 if ($usermode) {
406                         $condition_string = $condition_string . ' AND ' . self::condition(false);
407                 }
408
409                 $param_string = self::addTablesToFields(DBA::buildParameter($params), $fields);
410
411                 $table = "`item` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, false, $usermode);
412
413                 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
414
415                 return DBA::p($sql, $condition);
416         }
417
418         /**
419          * @brief Select rows from the starting post in the item table
420          *
421          * @param integer $uid       User ID
422          * @param array   $selected
423          * @param array   $condition Array of fields for condition
424          * @param array   $params    Array of several parameters
425          *
426          * @return boolean|object
427          * @throws \Exception
428          */
429         public static function selectThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
430         {
431                 $params['uid'] = $uid;
432
433                 if (empty($selected)) {
434                         $selected = Item::DISPLAY_FIELDLIST;
435                 }
436
437                 return self::selectThread($selected, $condition, $params);
438         }
439
440         /**
441          * Retrieve a single record from the starting post in the item table and returns it in an associative array
442          *
443          * @brief Retrieve a single record from a table
444          * @param integer $uid User ID
445          * @param array   $selected
446          * @param array   $condition
447          * @param array   $params
448          * @return bool|array
449          * @throws \Exception
450          * @see   DBA::select
451          */
452         public static function selectFirstThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
453         {
454                 $params['uid'] = $uid;
455
456                 if (empty($selected)) {
457                         $selected = Item::DISPLAY_FIELDLIST;
458                 }
459
460                 return self::selectFirstThread($selected, $condition, $params);
461         }
462
463         /**
464          * Retrieve a single record from the starting post in the item table and returns it in an associative array
465          *
466          * @brief Retrieve a single record from a table
467          * @param array $fields
468          * @param array $condition
469          * @param array $params
470          * @return bool|array
471          * @throws \Exception
472          * @see   DBA::select
473          */
474         public static function selectFirstThread(array $fields = [], array $condition = [], $params = [])
475         {
476                 $params['limit'] = 1;
477                 $result = self::selectThread($fields, $condition, $params);
478
479                 if (is_bool($result)) {
480                         return $result;
481                 } else {
482                         $row = self::fetch($result);
483                         DBA::close($result);
484                         return $row;
485                 }
486         }
487
488         /**
489          * @brief Select rows from the starting post in the item table
490          *
491          * @param array $selected  Array of selected fields, empty for all
492          * @param array $condition Array of fields for condition
493          * @param array $params    Array of several parameters
494          *
495          * @return boolean|object
496          * @throws \Exception
497          */
498         public static function selectThread(array $selected = [], array $condition = [], $params = [])
499         {
500                 $uid = 0;
501                 $usermode = false;
502
503                 if (isset($params['uid'])) {
504                         $uid = $params['uid'];
505                         $usermode = true;
506                 }
507
508                 $fields = self::fieldlist($usermode);
509
510                 $fields['thread'] = ['mention', 'ignored', 'iid'];
511
512                 $threadfields = ['thread' => ['iid', 'uid', 'contact-id', 'owner-id', 'author-id',
513                         'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private',
514                         'pubmail', 'moderated', 'visible', 'starred', 'ignored', 'post-type',
515                         'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'network']];
516
517                 $select_fields = self::constructSelectFields($fields, $selected);
518
519                 $condition_string = DBA::buildCondition($condition);
520
521                 $condition_string = self::addTablesToFields($condition_string, $threadfields);
522                 $condition_string = self::addTablesToFields($condition_string, $fields);
523
524                 if ($usermode) {
525                         $condition_string = $condition_string . ' AND ' . self::condition(true);
526                 }
527
528                 $param_string = DBA::buildParameter($params);
529                 $param_string = self::addTablesToFields($param_string, $threadfields);
530                 $param_string = self::addTablesToFields($param_string, $fields);
531
532                 $table = "`thread` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, true, $usermode);
533
534                 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
535
536                 return DBA::p($sql, $condition);
537         }
538
539         /**
540          * @brief Returns a list of fields that are associated with the item table
541          *
542          * @param $usermode
543          * @return array field list
544          */
545         private static function fieldlist($usermode)
546         {
547                 $fields = [];
548
549                 $fields['item'] = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
550                         'contact-id', 'owner-id', 'author-id', 'type', 'wall', 'gravity', 'extid',
551                         'created', 'edited', 'commented', 'received', 'changed', 'psid',
552                         'resource-id', 'event-id', 'tag', 'attach', 'post-type', 'file',
553                         'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
554                         'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global',
555                         'id' => 'item_id', 'network', 'icid', 'iaid', 'id' => 'internal-iid',
556                         'network' => 'internal-network', 'icid' => 'internal-icid',
557                         'iaid' => 'internal-iaid'];
558
559                 if ($usermode) {
560                         $fields['user-item'] = ['ignored' => 'internal-user-ignored'];
561                 }
562
563                 $fields['item-activity'] = ['activity', 'activity' => 'internal-activity'];
564
565                 $fields['item-content'] = array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST);
566
567                 $fields['item-delivery-data'] = array_merge(ItemDeliveryData::LEGACY_FIELD_LIST, ItemDeliveryData::FIELD_LIST);
568
569                 $fields['permissionset'] = ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'];
570
571                 $fields['author'] = ['url' => 'author-link', 'name' => 'author-name',
572                         'thumb' => 'author-avatar', 'nick' => 'author-nick', 'network' => 'author-network'];
573
574                 $fields['owner'] = ['url' => 'owner-link', 'name' => 'owner-name',
575                         'thumb' => 'owner-avatar', 'nick' => 'owner-nick', 'network' => 'owner-network'];
576
577                 $fields['contact'] = ['url' => 'contact-link', 'name' => 'contact-name', 'thumb' => 'contact-avatar',
578                         'writable', 'self', 'id' => 'cid', 'alias', 'uid' => 'contact-uid',
579                         'photo', 'name-date', 'uri-date', 'avatar-date', 'thumb', 'dfrn-id'];
580
581                 $fields['parent-item'] = ['guid' => 'parent-guid', 'network' => 'parent-network'];
582
583                 $fields['parent-item-author'] = ['url' => 'parent-author-link', 'name' => 'parent-author-name'];
584
585                 $fields['event'] = ['created' => 'event-created', 'edited' => 'event-edited',
586                         'start' => 'event-start','finish' => 'event-finish',
587                         'summary' => 'event-summary','desc' => 'event-desc',
588                         'location' => 'event-location', 'type' => 'event-type',
589                         'nofinish' => 'event-nofinish','adjust' => 'event-adjust',
590                         'ignore' => 'event-ignore', 'id' => 'event-id'];
591
592                 $fields['sign'] = ['signed_text', 'signature', 'signer'];
593
594                 $fields['diaspora-interaction'] = ['interaction'];
595
596                 return $fields;
597         }
598
599         /**
600          * @brief Returns SQL condition for the "select" functions
601          *
602          * @param boolean $thread_mode Called for the items (false) or for the threads (true)
603          *
604          * @return string SQL condition
605          */
606         private static function condition($thread_mode)
607         {
608                 if ($thread_mode) {
609                         $master_table = "`thread`";
610                 } else {
611                         $master_table = "`item`";
612                 }
613                 return sprintf("$master_table.`visible` AND NOT $master_table.`deleted` AND NOT $master_table.`moderated`
614                         AND (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`)
615                         AND (`user-author`.`blocked` IS NULL OR NOT `user-author`.`blocked`)
616                         AND (`user-author`.`ignored` IS NULL OR NOT `user-author`.`ignored` OR `item`.`gravity` != %d)
617                         AND (`user-owner`.`blocked` IS NULL OR NOT `user-owner`.`blocked`)
618                         AND (`user-owner`.`ignored` IS NULL OR NOT `user-owner`.`ignored` OR `item`.`gravity` != %d) ",
619                         GRAVITY_PARENT, GRAVITY_PARENT);
620         }
621
622         /**
623          * @brief Returns all needed "JOIN" commands for the "select" functions
624          *
625          * @param integer $uid          User ID
626          * @param string  $sql_commands The parts of the built SQL commands in the "select" functions
627          * @param boolean $thread_mode  Called for the items (false) or for the threads (true)
628          *
629          * @param         $user_mode
630          * @return string The SQL joins for the "select" functions
631          */
632         private static function constructJoins($uid, $sql_commands, $thread_mode, $user_mode)
633         {
634                 if ($thread_mode) {
635                         $master_table = "`thread`";
636                         $master_table_key = "`thread`.`iid`";
637                         $joins = "STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid` ";
638                 } else {
639                         $master_table = "`item`";
640                         $master_table_key = "`item`.`id`";
641                         $joins = '';
642                 }
643
644                 if ($user_mode) {
645                         $joins .= sprintf("STRAIGHT_JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`
646                                 AND NOT `contact`.`blocked`
647                                 AND ((NOT `contact`.`readonly` AND NOT `contact`.`pending` AND (`contact`.`rel` IN (%s, %s)))
648                                 OR `contact`.`self` OR `item`.`gravity` != %d OR `contact`.`uid` = 0)
649                                 STRAIGHT_JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id` AND NOT `author`.`blocked`
650                                 STRAIGHT_JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id` AND NOT `owner`.`blocked`
651                                 LEFT JOIN `user-item` ON `user-item`.`iid` = $master_table_key AND `user-item`.`uid` = %d
652                                 LEFT JOIN `user-contact` AS `user-author` ON `user-author`.`cid` = $master_table.`author-id` AND `user-author`.`uid` = %d
653                                 LEFT JOIN `user-contact` AS `user-owner` ON `user-owner`.`cid` = $master_table.`owner-id` AND `user-owner`.`uid` = %d",
654                                 Contact::SHARING, Contact::FRIEND, GRAVITY_PARENT, intval($uid), intval($uid), intval($uid));
655                 } else {
656                         if (strpos($sql_commands, "`contact`.") !== false) {
657                                 $joins .= "LEFT JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`";
658                         }
659                         if (strpos($sql_commands, "`author`.") !== false) {
660                                 $joins .= " LEFT JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id`";
661                         }
662                         if (strpos($sql_commands, "`owner`.") !== false) {
663                                 $joins .= " LEFT JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id`";
664                         }
665                 }
666
667                 if (strpos($sql_commands, "`group_member`.") !== false) {
668                         $joins .= " STRAIGHT_JOIN `group_member` ON `group_member`.`contact-id` = $master_table.`contact-id`";
669                 }
670
671                 if (strpos($sql_commands, "`user`.") !== false) {
672                         $joins .= " STRAIGHT_JOIN `user` ON `user`.`uid` = $master_table.`uid`";
673                 }
674
675                 if (strpos($sql_commands, "`event`.") !== false) {
676                         $joins .= " LEFT JOIN `event` ON `event-id` = `event`.`id`";
677                 }
678
679                 if (strpos($sql_commands, "`sign`.") !== false) {
680                         $joins .= " LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`";
681                 }
682
683                 if (strpos($sql_commands, "`diaspora-interaction`.") !== false) {
684                         $joins .= " LEFT JOIN `diaspora-interaction` ON `diaspora-interaction`.`uri-id` = `item`.`uri-id`";
685                 }
686
687                 if (strpos($sql_commands, "`item-activity`.") !== false) {
688                         $joins .= " LEFT JOIN `item-activity` ON `item-activity`.`uri-id` = `item`.`uri-id`";
689                 }
690
691                 if (strpos($sql_commands, "`item-content`.") !== false) {
692                         $joins .= " LEFT JOIN `item-content` ON `item-content`.`uri-id` = `item`.`uri-id`";
693                 }
694
695                 if (strpos($sql_commands, "`item-delivery-data`.") !== false) {
696                         $joins .= " LEFT JOIN `item-delivery-data` ON `item-delivery-data`.`iid` = `item`.`id`";
697                 }
698
699                 if (strpos($sql_commands, "`permissionset`.") !== false) {
700                         $joins .= " LEFT JOIN `permissionset` ON `permissionset`.`id` = `item`.`psid`";
701                 }
702
703                 if ((strpos($sql_commands, "`parent-item`.") !== false) || (strpos($sql_commands, "`parent-author`.") !== false)) {
704                         $joins .= " STRAIGHT_JOIN `item` AS `parent-item` ON `parent-item`.`id` = `item`.`parent`";
705                 }
706
707                 if (strpos($sql_commands, "`parent-item-author`.") !== false) {
708                         $joins .= " STRAIGHT_JOIN `contact` AS `parent-item-author` ON `parent-item-author`.`id` = `parent-item`.`author-id`";
709                 }
710
711                 return $joins;
712         }
713
714         /**
715          * @brief Add the field list for the "select" functions
716          *
717          * @param array $fields The field definition array
718          * @param array $selected The array with the selected fields from the "select" functions
719          *
720          * @return string The field list
721          */
722         private static function constructSelectFields($fields, $selected)
723         {
724                 if (!empty($selected)) {
725                         $selected[] = 'internal-iid';
726                         $selected[] = 'internal-iaid';
727                         $selected[] = 'internal-icid';
728                         $selected[] = 'internal-network';
729                 }
730
731                 if (in_array('verb', $selected)) {
732                         $selected[] = 'internal-activity';
733                 }
734
735                 if (in_array('ignored', $selected)) {
736                         $selected[] = 'internal-user-ignored';
737                 }
738
739                 if (in_array('signed_text', $selected)) {
740                         $selected[] = 'interaction';
741                 }
742
743                 $legacy_fields = array_merge(ItemDeliveryData::LEGACY_FIELD_LIST, self::MIXED_CONTENT_FIELDLIST);
744
745                 $selection = [];
746                 foreach ($fields as $table => $table_fields) {
747                         foreach ($table_fields as $field => $select) {
748                                 if (empty($selected) || in_array($select, $selected)) {
749                                         if (self::isLegacyMode() && in_array($select, $legacy_fields)) {
750                                                 $selection[] = "`item`.`".$select."` AS `internal-item-" . $select . "`";
751                                         }
752                                         if (is_int($field)) {
753                                                 $selection[] = "`" . $table . "`.`" . $select . "`";
754                                         } else {
755                                                 $selection[] = "`" . $table . "`.`" . $field . "` AS `" . $select . "`";
756                                         }
757                                 }
758                         }
759                 }
760                 return implode(", ", $selection);
761         }
762
763         /**
764          * @brief add table definition to fields in an SQL query
765          *
766          * @param string $query SQL query
767          * @param array $fields The field definition array
768          *
769          * @return string the changed SQL query
770          */
771         private static function addTablesToFields($query, $fields)
772         {
773                 foreach ($fields as $table => $table_fields) {
774                         foreach ($table_fields as $alias => $field) {
775                                 if (is_int($alias)) {
776                                         $replace_field = $field;
777                                 } else {
778                                         $replace_field = $alias;
779                                 }
780
781                                 $search = "/([^\.])`" . $field . "`/i";
782                                 $replace = "$1`" . $table . "`.`" . $replace_field . "`";
783                                 $query = preg_replace($search, $replace, $query);
784                         }
785                 }
786                 return $query;
787         }
788
789         /**
790          * @brief Update existing item entries
791          *
792          * @param array $fields    The fields that are to be changed
793          * @param array $condition The condition for finding the item entries
794          *
795          * In the future we may have to change permissions as well.
796          * Then we had to add the user id as third parameter.
797          *
798          * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
799          *
800          * @return integer|boolean number of affected rows - or "false" if there was an error
801          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
802          */
803         public static function update(array $fields, array $condition)
804         {
805                 if (empty($condition) || empty($fields)) {
806                         return false;
807                 }
808
809                 // To ensure the data integrity we do it in an transaction
810                 DBA::transaction();
811
812                 // We cannot simply expand the condition to check for origin entries
813                 // The condition needn't to be a simple array but could be a complex condition.
814                 // And we have to execute this query before the update to ensure to fetch the same data.
815                 $items = DBA::select('item', ['id', 'origin', 'uri', 'uri-id', 'iaid', 'icid', 'tag', 'file'], $condition);
816
817                 $content_fields = [];
818                 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
819                         if (isset($fields[$field])) {
820                                 $content_fields[$field] = $fields[$field];
821                                 if (in_array($field, self::CONTENT_FIELDLIST) || !self::isLegacyMode()) {
822                                         unset($fields[$field]);
823                                 } else {
824                                         $fields[$field] = null;
825                                 }
826                         }
827                 }
828
829                 $delivery_data = ItemDeliveryData::extractFields($fields);
830
831                 $clear_fields = ['bookmark', 'type', 'author-name', 'author-avatar', 'author-link', 'owner-name', 'owner-avatar', 'owner-link', 'postopts', 'inform'];
832                 foreach ($clear_fields as $field) {
833                         if (array_key_exists($field, $fields)) {
834                                 $fields[$field] = null;
835                         }
836                 }
837
838                 if (array_key_exists('tag', $fields)) {
839                         $tags = $fields['tag'];
840                         $fields['tag'] = null;
841                 } else {
842                         $tags = null;
843                 }
844
845                 if (array_key_exists('file', $fields)) {
846                         $files = $fields['file'];
847                         $fields['file'] = null;
848                 } else {
849                         $files = null;
850                 }
851
852                 if (!empty($fields)) {
853                         $success = DBA::update('item', $fields, $condition);
854
855                         if (!$success) {
856                                 DBA::close($items);
857                                 DBA::rollback();
858                                 return false;
859                         }
860                 }
861
862                 // When there is no content for the "old" item table, this will count the fetched items
863                 $rows = DBA::affectedRows();
864
865                 while ($item = DBA::fetch($items)) {
866                         if (!empty($item['iaid']) || (!empty($content_fields['verb']) && (self::activityToIndex($content_fields['verb']) >= 0))) {
867                                 self::updateActivity($content_fields, ['uri-id' => $item['uri-id']]);
868
869                                 if (empty($item['iaid'])) {
870                                         $item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-id' => $item['uri-id']]);
871                                         if (DBA::isResult($item_activity)) {
872                                                 $item_fields = ['iaid' => $item_activity['id'], 'icid' => null];
873                                                 foreach (self::MIXED_CONTENT_FIELDLIST as $field) {
874                                                         if (self::isLegacyMode()) {
875                                                                 $item_fields[$field] = null;
876                                                         } else {
877                                                                 unset($item_fields[$field]);
878                                                         }
879                                                 }
880                                                 DBA::update('item', $item_fields, ['id' => $item['id']]);
881
882                                                 if (!empty($item['icid']) && !DBA::exists('item', ['icid' => $item['icid']])) {
883                                                         DBA::delete('item-content', ['id' => $item['icid']]);
884                                                 }
885                                         }
886                                 } elseif (!empty($item['icid'])) {
887                                         DBA::update('item', ['icid' => null], ['id' => $item['id']]);
888
889                                         if (!DBA::exists('item', ['icid' => $item['icid']])) {
890                                                 DBA::delete('item-content', ['id' => $item['icid']]);
891                                         }
892                                 }
893                         } else {
894                                 self::updateContent($content_fields, ['uri-id' => $item['uri-id']]);
895
896                                 if (empty($item['icid'])) {
897                                         $item_content = DBA::selectFirst('item-content', [], ['uri-id' => $item['uri-id']]);
898                                         if (DBA::isResult($item_content)) {
899                                                 $item_fields = ['icid' => $item_content['id']];
900                                                 // Clear all fields in the item table that have a content in the item-content table
901                                                 foreach ($item_content as $field => $content) {
902                                                         if (in_array($field, self::MIXED_CONTENT_FIELDLIST) && !empty($item_content[$field])) {
903                                                                 if (self::isLegacyMode()) {
904                                                                         $item_fields[$field] = null;
905                                                                 } else {
906                                                                         unset($item_fields[$field]);
907                                                                 }
908                                                         }
909                                                 }
910                                                 DBA::update('item', $item_fields, ['id' => $item['id']]);
911                                         }
912                                 }
913                         }
914
915                         if (!is_null($tags)) {
916                                 Term::insertFromTagFieldByItemId($item['id'], $tags);
917                                 if (!empty($item['tag'])) {
918                                         DBA::update('item', ['tag' => ''], ['id' => $item['id']]);
919                                 }
920                         }
921
922                         if (!is_null($files)) {
923                                 Term::insertFromFileFieldByItemId($item['id'], $files);
924                                 if (!empty($item['file'])) {
925                                         DBA::update('item', ['file' => ''], ['id' => $item['id']]);
926                                 }
927                         }
928
929                         ItemDeliveryData::update($item['id'], $delivery_data);
930
931                         self::updateThread($item['id']);
932
933                         // We only need to notfiy others when it is an original entry from us.
934                         // Only call the notifier when the item has some content relevant change.
935                         if ($item['origin'] && in_array('edited', array_keys($fields))) {
936                                 Worker::add(PRIORITY_HIGH, "Notifier", 'edit_post', $item['id']);
937                         }
938                 }
939
940                 DBA::close($items);
941                 DBA::commit();
942                 return $rows;
943         }
944
945         /**
946          * @brief Delete an item and notify others about it - if it was ours
947          *
948          * @param array   $condition The condition for finding the item entries
949          * @param integer $priority  Priority for the notification
950          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
951          */
952         public static function delete($condition, $priority = PRIORITY_HIGH)
953         {
954                 $items = self::select(['id'], $condition);
955                 while ($item = self::fetch($items)) {
956                         self::deleteById($item['id'], $priority);
957                 }
958                 DBA::close($items);
959         }
960
961         /**
962          * @brief Delete an item for an user and notify others about it - if it was ours
963          *
964          * @param array   $condition The condition for finding the item entries
965          * @param integer $uid       User who wants to delete this item
966          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
967          */
968         public static function deleteForUser($condition, $uid)
969         {
970                 if ($uid == 0) {
971                         return;
972                 }
973
974                 $items = self::select(['id', 'uid'], $condition);
975                 while ($item = self::fetch($items)) {
976                         // "Deleting" global items just means hiding them
977                         if ($item['uid'] == 0) {
978                                 DBA::update('user-item', ['hidden' => true], ['iid' => $item['id'], 'uid' => $uid], true);
979                         } elseif ($item['uid'] == $uid) {
980                                 self::deleteById($item['id'], PRIORITY_HIGH);
981                         } else {
982                                 Logger::log('Wrong ownership. Not deleting item ' . $item['id']);
983                         }
984                 }
985                 DBA::close($items);
986         }
987
988         /**
989          * @brief Delete an item and notify others about it - if it was ours
990          *
991          * @param integer $item_id  Item ID that should be delete
992          * @param integer $priority Priority for the notification
993          *
994          * @return boolean success
995          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
996          */
997         public static function deleteById($item_id, $priority = PRIORITY_HIGH)
998         {
999                 // locate item to be deleted
1000                 $fields = ['id', 'uri', 'uid', 'parent', 'parent-uri', 'origin',
1001                         'deleted', 'file', 'resource-id', 'event-id', 'attach',
1002                         'verb', 'object-type', 'object', 'target', 'contact-id',
1003                         'icid', 'iaid', 'psid'];
1004                 $item = self::selectFirst($fields, ['id' => $item_id]);
1005                 if (!DBA::isResult($item)) {
1006                         Logger::log('Item with ID ' . $item_id . " hasn't been found.", Logger::DEBUG);
1007                         return false;
1008                 }
1009
1010                 if ($item['deleted']) {
1011                         Logger::log('Item with ID ' . $item_id . ' has already been deleted.', Logger::DEBUG);
1012                         return false;
1013                 }
1014
1015                 $parent = self::selectFirst(['origin'], ['id' => $item['parent']]);
1016                 if (!DBA::isResult($parent)) {
1017                         $parent = ['origin' => false];
1018                 }
1019
1020                 // clean up categories and tags so they don't end up as orphans
1021
1022                 $matches = false;
1023                 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
1024
1025                 if ($cnt) {
1026                         foreach ($matches as $mtch) {
1027                                 FileTag::unsaveFile($item['uid'], $item['id'], $mtch[1],true);
1028                         }
1029                 }
1030
1031                 $matches = false;
1032
1033                 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
1034
1035                 if ($cnt) {
1036                         foreach ($matches as $mtch) {
1037                                 FileTag::unsaveFile($item['uid'], $item['id'], $mtch[1],false);
1038                         }
1039                 }
1040
1041                 /*
1042                  * If item is a link to a photo resource, nuke all the associated photos
1043                  * (visitors will not have photo resources)
1044                  * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
1045                  * generate a resource-id and therefore aren't intimately linked to the item.
1046                  */
1047                 /// @TODO: this should first check if photo is used elsewhere
1048                 if (strlen($item['resource-id'])) {
1049                         Photo::delete(['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
1050                 }
1051
1052                 // If item is a link to an event, delete the event.
1053                 if (intval($item['event-id'])) {
1054                         Event::delete($item['event-id']);
1055                 }
1056
1057                 // If item has attachments, drop them
1058                 /// @TODO: this should first check if attachment is used elsewhere
1059                 foreach (explode(",", $item['attach']) as $attach) {
1060                         preg_match("|attach/(\d+)|", $attach, $matches);
1061                         if (is_array($matches) && count($matches) > 1) {
1062                                 Attach::delete(['id' => $matches[1], 'uid' => $item['uid']]);
1063                         }
1064                 }
1065
1066                 // Delete tags that had been attached to other items
1067                 self::deleteTagsFromItem($item);
1068
1069                 // Set the item to "deleted"
1070                 $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
1071                 DBA::update('item', $item_fields, ['id' => $item['id']]);
1072
1073                 Term::insertFromTagFieldByItemId($item['id'], '');
1074                 Term::insertFromFileFieldByItemId($item['id'], '');
1075                 self::deleteThread($item['id'], $item['parent-uri']);
1076
1077                 if (!self::exists(["`uri` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri']])) {
1078                         self::delete(['uri' => $item['uri'], 'uid' => 0, 'deleted' => false], $priority);
1079                 }
1080
1081                 ItemDeliveryData::delete($item['id']);
1082
1083                 // We don't delete the item-activity here, since we need some of the data for ActivityPub
1084
1085                 if (!empty($item['icid']) && !self::exists(['icid' => $item['icid'], 'deleted' => false])) {
1086                         DBA::delete('item-content', ['id' => $item['icid']], ['cascade' => false]);
1087                 }
1088                 // When the permission set will be used in photo and events as well,
1089                 // this query here needs to be extended.
1090                 if (!empty($item['psid']) && !self::exists(['psid' => $item['psid'], 'deleted' => false])) {
1091                         DBA::delete('permissionset', ['id' => $item['psid']], ['cascade' => false]);
1092                 }
1093
1094                 // If it's the parent of a comment thread, kill all the kids
1095                 if ($item['id'] == $item['parent']) {
1096                         self::delete(['parent' => $item['parent'], 'deleted' => false], $priority);
1097                 }
1098
1099                 // Is it our comment and/or our thread?
1100                 if ($item['origin'] || $parent['origin']) {
1101
1102                         // When we delete the original post we will delete all existing copies on the server as well
1103                         self::delete(['uri' => $item['uri'], 'deleted' => false], $priority);
1104
1105                         // send the notification upstream/downstream
1106                         Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", "drop", intval($item['id']));
1107                 } elseif ($item['uid'] != 0) {
1108
1109                         // When we delete just our local user copy of an item, we have to set a marker to hide it
1110                         $global_item = self::selectFirst(['id'], ['uri' => $item['uri'], 'uid' => 0, 'deleted' => false]);
1111                         if (DBA::isResult($global_item)) {
1112                                 DBA::update('user-item', ['hidden' => true], ['iid' => $global_item['id'], 'uid' => $item['uid']], true);
1113                         }
1114                 }
1115
1116                 Logger::log('Item with ID ' . $item_id . " has been deleted.", Logger::DEBUG);
1117
1118                 return true;
1119         }
1120
1121         private static function deleteTagsFromItem($item)
1122         {
1123                 if (($item["verb"] != ACTIVITY_TAG) || ($item["object-type"] != ACTIVITY_OBJ_TAGTERM)) {
1124                         return;
1125                 }
1126
1127                 $xo = XML::parseString($item["object"], false);
1128                 $xt = XML::parseString($item["target"], false);
1129
1130                 if ($xt->type != ACTIVITY_OBJ_NOTE) {
1131                         return;
1132                 }
1133
1134                 $i = self::selectFirst(['id', 'contact-id', 'tag'], ['uri' => $xt->id, 'uid' => $item['uid']]);
1135                 if (!DBA::isResult($i)) {
1136                         return;
1137                 }
1138
1139                 // For tags, the owner cannot remove the tag on the author's copy of the post.
1140                 $owner_remove = ($item["contact-id"] == $i["contact-id"]);
1141                 $author_copy = $item["origin"];
1142
1143                 if (($owner_remove && $author_copy) || !$owner_remove) {
1144                         return;
1145                 }
1146
1147                 $tags = explode(',', $i["tag"]);
1148                 $newtags = [];
1149                 if (count($tags)) {
1150                         foreach ($tags as $tag) {
1151                                 if (trim($tag) !== trim($xo->body)) {
1152                                        $newtags[] = trim($tag);
1153                                 }
1154                         }
1155                 }
1156                 self::update(['tag' => implode(',', $newtags)], ['id' => $i["id"]]);
1157         }
1158
1159         private static function guid($item, $notify)
1160         {
1161                 if (!empty($item['guid'])) {
1162                         return Strings::escapeTags(trim($item['guid']));
1163                 }
1164
1165                 if ($notify) {
1166                         // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
1167                         // We add the hash of our own host because our host is the original creator of the post.
1168                         $prefix_host = \get_app()->getHostName();
1169                 } else {
1170                         $prefix_host = '';
1171
1172                         // We are only storing the post so we create a GUID from the original hostname.
1173                         if (!empty($item['author-link'])) {
1174                                 $parsed = parse_url($item['author-link']);
1175                                 if (!empty($parsed['host'])) {
1176                                         $prefix_host = $parsed['host'];
1177                                 }
1178                         }
1179
1180                         if (empty($prefix_host) && !empty($item['plink'])) {
1181                                 $parsed = parse_url($item['plink']);
1182                                 if (!empty($parsed['host'])) {
1183                                         $prefix_host = $parsed['host'];
1184                                 }
1185                         }
1186
1187                         if (empty($prefix_host) && !empty($item['uri'])) {
1188                                 $parsed = parse_url($item['uri']);
1189                                 if (!empty($parsed['host'])) {
1190                                         $prefix_host = $parsed['host'];
1191                                 }
1192                         }
1193
1194                         // Is it in the format data@host.tld? - Used for mail contacts
1195                         if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
1196                                 $mailparts = explode('@', $item['author-link']);
1197                                 $prefix_host = array_pop($mailparts);
1198                         }
1199                 }
1200
1201                 if (!empty($item['plink'])) {
1202                         $guid = self::guidFromUri($item['plink'], $prefix_host);
1203                 } elseif (!empty($item['uri'])) {
1204                         $guid = self::guidFromUri($item['uri'], $prefix_host);
1205                 } else {
1206                         $guid = System::createUUID(hash('crc32', $prefix_host));
1207                 }
1208
1209                 return $guid;
1210         }
1211
1212         private static function contactId($item)
1213         {
1214                 $contact_id = (int)$item["contact-id"];
1215
1216                 if (!empty($contact_id)) {
1217                         return $contact_id;
1218                 }
1219                 Logger::log('Missing contact-id. Called by: '.System::callstack(), Logger::DEBUG);
1220                 /*
1221                  * First we are looking for a suitable contact that matches with the author of the post
1222                  * This is done only for comments
1223                  */
1224                 if ($item['parent-uri'] != $item['uri']) {
1225                         $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
1226                 }
1227
1228                 // If not present then maybe the owner was found
1229                 if ($contact_id == 0) {
1230                         $contact_id = Contact::getIdForURL($item['owner-link'], $item['uid']);
1231                 }
1232
1233                 // Still missing? Then use the "self" contact of the current user
1234                 if ($contact_id == 0) {
1235                         $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $item['uid']]);
1236                         if (DBA::isResult($self)) {
1237                                 $contact_id = $self["id"];
1238                         }
1239                 }
1240                 Logger::log("Contact-id was missing for post ".$item['guid']." from user id ".$item['uid']." - now set to ".$contact_id, Logger::DEBUG);
1241
1242                 return $contact_id;
1243         }
1244
1245         // This function will finally cover most of the preparation functionality in mod/item.php
1246         public static function prepare(&$item)
1247         {
1248                 $data = BBCode::getAttachmentData($item['body']);
1249                 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $item['body'], $match, PREG_SET_ORDER) || isset($data["type"]))
1250                         && ($posttype != Item::PT_PERSONAL_NOTE)) {
1251                         $posttype = Item::PT_PAGE;
1252                         $objecttype = ACTIVITY_OBJ_BOOKMARK;
1253                 }
1254         }
1255
1256         public static function insert($item, $force_parent = false, $notify = false, $dontcache = false)
1257         {
1258                 $orig_item = $item;
1259
1260                 // If it is a posting where users should get notifications, then define it as wall posting
1261                 if ($notify) {
1262                         $item['wall'] = 1;
1263                         $item['origin'] = 1;
1264                         $item['network'] = Protocol::DFRN;
1265                         $item['protocol'] = Conversation::PARCEL_DFRN;
1266
1267                         if (is_int($notify)) {
1268                                 $priority = $notify;
1269                         } else {
1270                                 $priority = PRIORITY_HIGH;
1271                         }
1272                 } else {
1273                         $item['network'] = trim(defaults($item, 'network', Protocol::PHANTOM));
1274                 }
1275
1276                 $item['guid'] = self::guid($item, $notify);
1277                 $item['uri'] = Strings::escapeTags(trim(defaults($item, 'uri', self::newURI($item['uid'], $item['guid']))));
1278
1279                 // Store URI data
1280                 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
1281
1282                 // Store conversation data
1283                 $item = Conversation::insert($item);
1284
1285                 /*
1286                  * If a Diaspora signature structure was passed in, pull it out of the
1287                  * item array and set it aside for later storage.
1288                  */
1289
1290                 $dsprsig = null;
1291                 if (isset($item['dsprsig'])) {
1292                         $encoded_signature = $item['dsprsig'];
1293                         $dsprsig = json_decode(base64_decode($item['dsprsig']));
1294                         unset($item['dsprsig']);
1295                 }
1296
1297                 $diaspora_signed_text = '';
1298                 if (isset($item['diaspora_signed_text'])) {
1299                         $diaspora_signed_text = $item['diaspora_signed_text'];
1300                         unset($item['diaspora_signed_text']);
1301                 }
1302
1303                 // Converting the plink
1304                 /// @TODO Check if this is really still needed
1305                 if ($item['network'] == Protocol::OSTATUS) {
1306                         if (isset($item['plink'])) {
1307                                 $item['plink'] = OStatus::convertHref($item['plink']);
1308                         } elseif (isset($item['uri'])) {
1309                                 $item['plink'] = OStatus::convertHref($item['uri']);
1310                         }
1311                 }
1312
1313                 if (!empty($item['thr-parent'])) {
1314                         $item['parent-uri'] = $item['thr-parent'];
1315                 }
1316
1317                 if (isset($item['gravity'])) {
1318                         $item['gravity'] = intval($item['gravity']);
1319                 } elseif ($item['parent-uri'] === $item['uri']) {
1320                         $item['gravity'] = GRAVITY_PARENT;
1321                 } elseif (activity_match($item['verb'], ACTIVITY_POST)) {
1322                         $item['gravity'] = GRAVITY_COMMENT;
1323                 } else {
1324                         $item['gravity'] = GRAVITY_UNKNOWN;   // Should not happen
1325                         Logger::log('Unknown gravity for verb: ' . $item['verb'], Logger::DEBUG);
1326                 }
1327
1328                 $uid = intval($item['uid']);
1329
1330                 // check for create date and expire time
1331                 $expire_interval = Config::get('system', 'dbclean-expire-days', 0);
1332
1333                 $user = DBA::selectFirst('user', ['expire'], ['uid' => $uid]);
1334                 if (DBA::isResult($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
1335                         $expire_interval = $user['expire'];
1336                 }
1337
1338                 if (($expire_interval > 0) && !empty($item['created'])) {
1339                         $expire_date = time() - ($expire_interval * 86400);
1340                         $created_date = strtotime($item['created']);
1341                         if ($created_date < $expire_date) {
1342                                 Logger::log('item-store: item created ('.date('c', $created_date).') before expiration time ('.date('c', $expire_date).'). ignored. ' . print_r($item,true), Logger::DEBUG);
1343                                 return 0;
1344                         }
1345                 }
1346
1347                 /*
1348                  * Do we already have this item?
1349                  * We have to check several networks since Friendica posts could be repeated
1350                  * via OStatus (maybe Diasporsa as well)
1351                  */
1352                 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DIASPORA, Protocol::DFRN, Protocol::OSTATUS, ""])) {
1353                         $condition = ["`uri` = ? AND `uid` = ? AND `network` IN (?, ?, ?)",
1354                                 trim($item['uri']), $item['uid'],
1355                                 Protocol::DIASPORA, Protocol::DFRN, Protocol::OSTATUS];
1356                         $existing = self::selectFirst(['id', 'network'], $condition);
1357                         if (DBA::isResult($existing)) {
1358                                 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
1359                                 if ($uid != 0) {
1360                                         Logger::log("Item with uri ".$item['uri']." already existed for user ".$uid." with id ".$existing["id"]." target network ".$existing["network"]." - new network: ".$item['network']);
1361                                 }
1362
1363                                 return $existing["id"];
1364                         }
1365                 }
1366
1367                 $item['wall']          = intval(defaults($item, 'wall', 0));
1368                 $item['extid']         = trim(defaults($item, 'extid', ''));
1369                 $item['author-name']   = trim(defaults($item, 'author-name', ''));
1370                 $item['author-link']   = trim(defaults($item, 'author-link', ''));
1371                 $item['author-avatar'] = trim(defaults($item, 'author-avatar', ''));
1372                 $item['owner-name']    = trim(defaults($item, 'owner-name', ''));
1373                 $item['owner-link']    = trim(defaults($item, 'owner-link', ''));
1374                 $item['owner-avatar']  = trim(defaults($item, 'owner-avatar', ''));
1375                 $item['received']      = (isset($item['received'])  ? DateTimeFormat::utc($item['received'])  : DateTimeFormat::utcNow());
1376                 $item['created']       = (isset($item['created'])   ? DateTimeFormat::utc($item['created'])   : $item['received']);
1377                 $item['edited']        = (isset($item['edited'])    ? DateTimeFormat::utc($item['edited'])    : $item['created']);
1378                 $item['changed']       = (isset($item['changed'])   ? DateTimeFormat::utc($item['changed'])   : $item['created']);
1379                 $item['commented']     = (isset($item['commented']) ? DateTimeFormat::utc($item['commented']) : $item['created']);
1380                 $item['title']         = trim(defaults($item, 'title', ''));
1381                 $item['location']      = trim(defaults($item, 'location', ''));
1382                 $item['coord']         = trim(defaults($item, 'coord', ''));
1383                 $item['visible']       = (isset($item['visible']) ? intval($item['visible']) : 1);
1384                 $item['deleted']       = 0;
1385                 $item['parent-uri']    = trim(defaults($item, 'parent-uri', $item['uri']));
1386                 $item['post-type']     = defaults($item, 'post-type', self::PT_ARTICLE);
1387                 $item['verb']          = trim(defaults($item, 'verb', ''));
1388                 $item['object-type']   = trim(defaults($item, 'object-type', ''));
1389                 $item['object']        = trim(defaults($item, 'object', ''));
1390                 $item['target-type']   = trim(defaults($item, 'target-type', ''));
1391                 $item['target']        = trim(defaults($item, 'target', ''));
1392                 $item['plink']         = trim(defaults($item, 'plink', ''));
1393                 $item['allow_cid']     = trim(defaults($item, 'allow_cid', ''));
1394                 $item['allow_gid']     = trim(defaults($item, 'allow_gid', ''));
1395                 $item['deny_cid']      = trim(defaults($item, 'deny_cid', ''));
1396                 $item['deny_gid']      = trim(defaults($item, 'deny_gid', ''));
1397                 $item['private']       = intval(defaults($item, 'private', 0));
1398                 $item['body']          = trim(defaults($item, 'body', ''));
1399                 $item['tag']           = trim(defaults($item, 'tag', ''));
1400                 $item['attach']        = trim(defaults($item, 'attach', ''));
1401                 $item['app']           = trim(defaults($item, 'app', ''));
1402                 $item['origin']        = intval(defaults($item, 'origin', 0));
1403                 $item['postopts']      = trim(defaults($item, 'postopts', ''));
1404                 $item['resource-id']   = trim(defaults($item, 'resource-id', ''));
1405                 $item['event-id']      = intval(defaults($item, 'event-id', 0));
1406                 $item['inform']        = trim(defaults($item, 'inform', ''));
1407                 $item['file']          = trim(defaults($item, 'file', ''));
1408
1409                 // When there is no content then we don't post it
1410                 if ($item['body'].$item['title'] == '') {
1411                         Logger::log('No body, no title.');
1412                         return 0;
1413                 }
1414
1415                 self::addLanguageToItemArray($item);
1416
1417                 // Items cannot be stored before they happen ...
1418                 if ($item['created'] > DateTimeFormat::utcNow()) {
1419                         $item['created'] = DateTimeFormat::utcNow();
1420                 }
1421
1422                 // We haven't invented time travel by now.
1423                 if ($item['edited'] > DateTimeFormat::utcNow()) {
1424                         $item['edited'] = DateTimeFormat::utcNow();
1425                 }
1426
1427                 $item['plink'] = defaults($item, 'plink', System::baseUrl() . '/display/' . urlencode($item['guid']));
1428
1429                 // The contact-id should be set before "self::insert" was called - but there seems to be issues sometimes
1430                 $item["contact-id"] = self::contactId($item);
1431
1432                 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
1433                         'photo' => $item['author-avatar'], 'network' => $item['network']];
1434
1435                 $item['author-id'] = defaults($item, 'author-id', Contact::getIdForURL($item["author-link"], 0, false, $default));
1436
1437                 if (Contact::isBlocked($item["author-id"])) {
1438                         Logger::log('Contact '.$item["author-id"].' is blocked, item '.$item["uri"].' will not be stored');
1439                         return 0;
1440                 }
1441
1442                 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
1443                         'photo' => $item['owner-avatar'], 'network' => $item['network']];
1444
1445                 $item['owner-id'] = defaults($item, 'owner-id', Contact::getIdForURL($item["owner-link"], 0, false, $default));
1446
1447                 if (Contact::isBlocked($item["owner-id"])) {
1448                         Logger::log('Contact '.$item["owner-id"].' is blocked, item '.$item["uri"].' will not be stored');
1449                         return 0;
1450                 }
1451
1452                 if ($item['network'] == Protocol::PHANTOM) {
1453                         Logger::log('Missing network. Called by: '.System::callstack(), Logger::DEBUG);
1454
1455                         $item['network'] = Protocol::DFRN;
1456                         Logger::log("Set network to " . $item["network"] . " for " . $item["uri"], Logger::DEBUG);
1457                 }
1458
1459                 // Checking if there is already an item with the same guid
1460                 Logger::log('Checking for an item for user '.$item['uid'].' on network '.$item['network'].' with the guid '.$item['guid'], Logger::DEBUG);
1461                 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
1462                 if (self::exists($condition)) {
1463                         Logger::log('found item with guid '.$item['guid'].' for user '.$item['uid'].' on network '.$item['network'], Logger::DEBUG);
1464                         return 0;
1465                 }
1466
1467                 // Check for hashtags in the body and repair or add hashtag links
1468                 self::setHashtags($item);
1469
1470                 $item['thr-parent'] = $item['parent-uri'];
1471
1472                 $notify_type = '';
1473                 $allow_cid = '';
1474                 $allow_gid = '';
1475                 $deny_cid  = '';
1476                 $deny_gid  = '';
1477
1478                 if ($item['parent-uri'] === $item['uri']) {
1479                         $parent_id = 0;
1480                         $parent_deleted = 0;
1481                         $allow_cid = $item['allow_cid'];
1482                         $allow_gid = $item['allow_gid'];
1483                         $deny_cid  = $item['deny_cid'];
1484                         $deny_gid  = $item['deny_gid'];
1485                         $notify_type = 'wall-new';
1486                 } else {
1487                         // find the parent and snarf the item id and ACLs
1488                         // and anything else we need to inherit
1489
1490                         $fields = ['uri', 'parent-uri', 'id', 'deleted',
1491                                 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
1492                                 'wall', 'private', 'forum_mode', 'origin'];
1493                         $condition = ['uri' => $item['parent-uri'], 'uid' => $item['uid']];
1494                         $params = ['order' => ['id' => false]];
1495                         $parent = self::selectFirst($fields, $condition, $params);
1496
1497                         if (DBA::isResult($parent)) {
1498                                 // is the new message multi-level threaded?
1499                                 // even though we don't support it now, preserve the info
1500                                 // and re-attach to the conversation parent.
1501
1502                                 if ($parent['uri'] != $parent['parent-uri']) {
1503                                         $item['parent-uri'] = $parent['parent-uri'];
1504
1505                                         $condition = ['uri' => $item['parent-uri'],
1506                                                 'parent-uri' => $item['parent-uri'],
1507                                                 'uid' => $item['uid']];
1508                                         $params = ['order' => ['id' => false]];
1509                                         $toplevel_parent = self::selectFirst($fields, $condition, $params);
1510
1511                                         if (DBA::isResult($toplevel_parent)) {
1512                                                 $parent = $toplevel_parent;
1513                                         }
1514                                 }
1515
1516                                 $parent_id      = $parent['id'];
1517                                 $parent_deleted = $parent['deleted'];
1518                                 $allow_cid      = $parent['allow_cid'];
1519                                 $allow_gid      = $parent['allow_gid'];
1520                                 $deny_cid       = $parent['deny_cid'];
1521                                 $deny_gid       = $parent['deny_gid'];
1522                                 $item['wall']    = $parent['wall'];
1523                                 $notify_type    = 'comment-new';
1524
1525                                 /*
1526                                  * If the parent is private, force privacy for the entire conversation
1527                                  * This differs from the above settings as it subtly allows comments from
1528                                  * email correspondents to be private even if the overall thread is not.
1529                                  */
1530                                 if ($parent['private']) {
1531                                         $item['private'] = $parent['private'];
1532                                 }
1533
1534                                 /*
1535                                  * Edge case. We host a public forum that was originally posted to privately.
1536                                  * The original author commented, but as this is a comment, the permissions
1537                                  * weren't fixed up so it will still show the comment as private unless we fix it here.
1538                                  */
1539                                 if ((intval($parent['forum_mode']) == 1) && $parent['private']) {
1540                                         $item['private'] = 0;
1541                                 }
1542
1543                                 // If its a post from myself then tag the thread as "mention"
1544                                 Logger::log("Checking if parent ".$parent_id." has to be tagged as mention for user ".$item['uid'], Logger::DEBUG);
1545                                 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $item['uid']]);
1546                                 if (DBA::isResult($user)) {
1547                                         $self = Strings::normaliseLink(System::baseUrl() . '/profile/' . $user['nickname']);
1548                                         $self_id = Contact::getIdForURL($self, 0, true);
1549                                         Logger::log("'myself' is ".$self_id." for parent ".$parent_id." checking against ".$item['author-id']." and ".$item['owner-id'], Logger::DEBUG);
1550                                         if (($item['author-id'] == $self_id) || ($item['owner-id'] == $self_id)) {
1551                                                 DBA::update('thread', ['mention' => true], ['iid' => $parent_id]);
1552                                                 Logger::log("tagged thread ".$parent_id." as mention for user ".$self, Logger::DEBUG);
1553                                         }
1554                                 }
1555                         } else {
1556                                 /*
1557                                  * Allow one to see reply tweets from status.net even when
1558                                  * we don't have or can't see the original post.
1559                                  */
1560                                 if ($force_parent) {
1561                                         Logger::log('$force_parent=true, reply converted to top-level post.');
1562                                         $parent_id = 0;
1563                                         $item['parent-uri'] = $item['uri'];
1564                                         $item['gravity'] = GRAVITY_PARENT;
1565                                 } else {
1566                                         Logger::log('item parent '.$item['parent-uri'].' for '.$item['uid'].' was not found - ignoring item');
1567                                         return 0;
1568                                 }
1569
1570                                 $parent_deleted = 0;
1571                         }
1572                 }
1573
1574                 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
1575                 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
1576
1577                 $condition = ["`uri` = ? AND `network` IN (?, ?) AND `uid` = ?",
1578                         $item['uri'], $item['network'], Protocol::DFRN, $item['uid']];
1579                 if (self::exists($condition)) {
1580                         Logger::log('duplicated item with the same uri found. '.print_r($item,true));
1581                         return 0;
1582                 }
1583
1584                 // On Friendica and Diaspora the GUID is unique
1585                 if (in_array($item['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
1586                         $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
1587                         if (self::exists($condition)) {
1588                                 Logger::log('duplicated item with the same guid found. '.print_r($item,true));
1589                                 return 0;
1590                         }
1591                 } else {
1592                         // Check for an existing post with the same content. There seems to be a problem with OStatus.
1593                         $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
1594                                         $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
1595                         if (self::exists($condition)) {
1596                                 Logger::log('duplicated item with the same body found. '.print_r($item,true));
1597                                 return 0;
1598                         }
1599                 }
1600
1601                 // Is this item available in the global items (with uid=0)?
1602                 if ($item["uid"] == 0) {
1603                         $item["global"] = true;
1604
1605                         // Set the global flag on all items if this was a global item entry
1606                         self::update(['global' => true], ['uri' => $item["uri"]]);
1607                 } else {
1608                         $item["global"] = self::exists(['uid' => 0, 'uri' => $item["uri"]]);
1609                 }
1610
1611                 // ACL settings
1612                 if (strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid)) {
1613                         $private = 1;
1614                 } else {
1615                         $private = $item['private'];
1616                 }
1617
1618                 $item["allow_cid"] = $allow_cid;
1619                 $item["allow_gid"] = $allow_gid;
1620                 $item["deny_cid"] = $deny_cid;
1621                 $item["deny_gid"] = $deny_gid;
1622                 $item["private"] = $private;
1623                 $item["deleted"] = $parent_deleted;
1624
1625                 // Fill the cache field
1626                 self::putInCache($item);
1627
1628                 if ($notify) {
1629                         $item['edit'] = false;
1630                         $item['parent'] = $parent_id;
1631                         Hook::callAll('post_local', $item);
1632                         unset($item['edit']);
1633                         unset($item['parent']);
1634                 } else {
1635                         Hook::callAll('post_remote', $item);
1636                 }
1637
1638                 // This array field is used to trigger some automatic reactions
1639                 // It is mainly used in the "post_local" hook.
1640                 unset($item['api_source']);
1641
1642                 if (!empty($item['cancel'])) {
1643                         Logger::log('post cancelled by addon.');
1644                         return 0;
1645                 }
1646
1647                 /*
1648                  * Check for already added items.
1649                  * There is a timing issue here that sometimes creates double postings.
1650                  * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
1651                  */
1652                 if ($item["uid"] == 0) {
1653                         if (self::exists(['uri' => trim($item['uri']), 'uid' => 0])) {
1654                                 Logger::log('Global item already stored. URI: '.$item['uri'].' on network '.$item['network'], Logger::DEBUG);
1655                                 return 0;
1656                         }
1657                 }
1658
1659                 Logger::log('' . print_r($item,true), Logger::DATA);
1660
1661                 if (array_key_exists('tag', $item)) {
1662                         $tags = $item['tag'];
1663                         unset($item['tag']);
1664                 } else {
1665                         $tags = '';
1666                 }
1667
1668                 if (array_key_exists('file', $item)) {
1669                         $files = $item['file'];
1670                         unset($item['file']);
1671                 } else {
1672                         $files = '';
1673                 }
1674
1675                 // Creates or assigns the permission set
1676                 $item['psid'] = PermissionSet::fetchIDForPost($item);
1677
1678                 // We are doing this outside of the transaction to avoid timing problems
1679                 if (!self::insertActivity($item)) {
1680                         self::insertContent($item);
1681                 }
1682
1683                 $delivery_data = ItemDeliveryData::extractFields($item);
1684
1685                 unset($item['postopts']);
1686                 unset($item['inform']);
1687
1688                 // These fields aren't stored anymore in the item table, they are fetched upon request
1689                 unset($item['author-link']);
1690                 unset($item['author-name']);
1691                 unset($item['author-avatar']);
1692
1693                 unset($item['owner-link']);
1694                 unset($item['owner-name']);
1695                 unset($item['owner-avatar']);
1696
1697                 DBA::transaction();
1698                 $ret = DBA::insert('item', $item);
1699
1700                 // When the item was successfully stored we fetch the ID of the item.
1701                 if (DBA::isResult($ret)) {
1702                         $current_post = DBA::lastInsertId();
1703                 } else {
1704                         // This can happen - for example - if there are locking timeouts.
1705                         DBA::rollback();
1706
1707                         // Store the data into a spool file so that we can try again later.
1708
1709                         // At first we restore the Diaspora signature that we removed above.
1710                         if (isset($encoded_signature)) {
1711                                 $item['dsprsig'] = $encoded_signature;
1712                         }
1713
1714                         // Now we store the data in the spool directory
1715                         // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
1716                         $file = 'item-'.round(microtime(true) * 10000).'-'.mt_rand().'.msg';
1717
1718                         $spoolpath = get_spoolpath();
1719                         if ($spoolpath != "") {
1720                                 $spool = $spoolpath.'/'.$file;
1721
1722                                 file_put_contents($spool, json_encode($orig_item));
1723                                 Logger::log("Item wasn't stored - Item was spooled into file ".$file, Logger::DEBUG);
1724                         }
1725                         return 0;
1726                 }
1727
1728                 if ($current_post == 0) {
1729                         // This is one of these error messages that never should occur.
1730                         Logger::log("couldn't find created item - we better quit now.");
1731                         DBA::rollback();
1732                         return 0;
1733                 }
1734
1735                 // How much entries have we created?
1736                 // We wouldn't need this query when we could use an unique index - but MySQL has length problems with them.
1737                 $entries = DBA::count('item', ['uri' => $item['uri'], 'uid' => $item['uid'], 'network' => $item['network']]);
1738
1739                 if ($entries > 1) {
1740                         // There are duplicates. We delete our just created entry.
1741                         Logger::log('Duplicated post occurred. uri = ' . $item['uri'] . ' uid = ' . $item['uid']);
1742
1743                         // Yes, we could do a rollback here - but we are having many users with MyISAM.
1744                         DBA::delete('item', ['id' => $current_post]);
1745                         DBA::commit();
1746                         return 0;
1747                 } elseif ($entries == 0) {
1748                         // This really should never happen since we quit earlier if there were problems.
1749                         Logger::log("Something is terribly wrong. We haven't found our created entry.");
1750                         DBA::rollback();
1751                         return 0;
1752                 }
1753
1754                 Logger::log('created item '.$current_post);
1755                 self::updateContact($item);
1756
1757                 if (!$parent_id || ($item['parent-uri'] === $item['uri'])) {
1758                         $parent_id = $current_post;
1759                 }
1760
1761                 // Set parent id
1762                 self::update(['parent' => $parent_id], ['id' => $current_post]);
1763
1764                 $item['id'] = $current_post;
1765                 $item['parent'] = $parent_id;
1766
1767                 // update the commented timestamp on the parent
1768                 // Only update "commented" if it is really a comment
1769                 if (($item['gravity'] != GRAVITY_ACTIVITY) || !Config::get("system", "like_no_comment")) {
1770                         self::update(['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1771                 } else {
1772                         self::update(['changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1773                 }
1774
1775                 if ($dsprsig) {
1776                         /*
1777                          * Friendica servers lower than 3.4.3-2 had double encoded the signature ...
1778                          * We can check for this condition when we decode and encode the stuff again.
1779                          */
1780                         if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) {
1781                                 $dsprsig->signature = base64_decode($dsprsig->signature);
1782                                 Logger::log("Repaired double encoded signature from handle ".$dsprsig->signer, Logger::DEBUG);
1783                         }
1784
1785                         if (!empty($dsprsig->signed_text) && empty($dsprsig->signature) && empty($dsprsig->signer)) {
1786                                 DBA::insert('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $dsprsig->signed_text], true);
1787                         } else {
1788                                 // The other fields are used by very old Friendica servers, so we currently store them differently
1789                                 DBA::insert('sign', ['iid' => $current_post, 'signed_text' => $dsprsig->signed_text,
1790                                         'signature' => $dsprsig->signature, 'signer' => $dsprsig->signer]);
1791                         }
1792                 }
1793
1794                 if (!empty($diaspora_signed_text)) {
1795                         DBA::insert('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $diaspora_signed_text], true);
1796                 }
1797
1798                 $deleted = self::tagDeliver($item['uid'], $current_post);
1799
1800                 /*
1801                  * current post can be deleted if is for a community page and no mention are
1802                  * in it.
1803                  */
1804                 if (!$deleted && !$dontcache) {
1805                         $posted_item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $current_post]);
1806                         if (DBA::isResult($posted_item)) {
1807                                 if ($notify) {
1808                                         Hook::callAll('post_local_end', $posted_item);
1809                                 } else {
1810                                         Hook::callAll('post_remote_end', $posted_item);
1811                                 }
1812                         } else {
1813                                 Logger::log('new item not found in DB, id ' . $current_post);
1814                         }
1815                 }
1816
1817                 if ($item['parent-uri'] === $item['uri']) {
1818                         self::addThread($current_post);
1819                 } else {
1820                         self::updateThread($parent_id);
1821                 }
1822
1823                 ItemDeliveryData::insert($current_post, $delivery_data);
1824
1825                 DBA::commit();
1826
1827                 /*
1828                  * Due to deadlock issues with the "term" table we are doing these steps after the commit.
1829                  * This is not perfect - but a workable solution until we found the reason for the problem.
1830                  */
1831                 if (!empty($tags)) {
1832                         Term::insertFromTagFieldByItemId($current_post, $tags);
1833                 }
1834
1835                 if (!empty($files)) {
1836                         Term::insertFromFileFieldByItemId($current_post, $files);
1837                 }
1838
1839                 if ($item['parent-uri'] === $item['uri']) {
1840                         self::addShadow($current_post);
1841                 } else {
1842                         self::addShadowPost($current_post);
1843                 }
1844
1845                 check_user_notification($current_post);
1846
1847                 if ($notify) {
1848                         Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', $notify_type, $current_post);
1849                 } elseif ($item['visible'] && ((!empty($parent) && $parent['origin']) || $item['origin'])) {
1850                         if ($item['gravity'] == GRAVITY_ACTIVITY) {
1851                                 $cmd = $item['origin'] ? 'activity-new' : 'activity-import';
1852                         } elseif ($item['gravity'] == GRAVITY_COMMENT) {
1853                                 $cmd = $item['origin'] ? 'comment-new' : 'comment-import';
1854                         } else {
1855                                 $cmd = 'wall-new';
1856                         }
1857
1858                         Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', $cmd, $current_post);
1859                 }
1860
1861                 return $current_post;
1862         }
1863
1864         /**
1865          * @brief Insert a new item content entry
1866          *
1867          * @param array $item The item fields that are to be inserted
1868          * @return bool
1869          * @throws \Exception
1870          */
1871         private static function insertActivity(&$item)
1872         {
1873                 $activity_index = self::activityToIndex($item['verb']);
1874
1875                 if ($activity_index < 0) {
1876                         return false;
1877                 }
1878
1879                 $fields = ['activity' => $activity_index, 'uri-hash' => (string)$item['uri-id'], 'uri-id' => $item['uri-id']];
1880
1881                 // We just remove everything that is content
1882                 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1883                         unset($item[$field]);
1884                 }
1885
1886                 // To avoid timing problems, we are using locks.
1887                 $locked = Lock::acquire('item_insert_activity');
1888                 if (!$locked) {
1889                         Logger::log("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
1890                 }
1891
1892                 // Do we already have this content?
1893                 $item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-id' => $item['uri-id']]);
1894                 if (DBA::isResult($item_activity)) {
1895                         $item['iaid'] = $item_activity['id'];
1896                         Logger::log('Fetched activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
1897                 } elseif (DBA::insert('item-activity', $fields)) {
1898                         $item['iaid'] = DBA::lastInsertId();
1899                         Logger::log('Inserted activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
1900                 } else {
1901                         // This shouldn't happen.
1902                         Logger::log('Could not insert activity for URI ' . $item['uri'] . ' - should not happen');
1903                         Lock::release('item_insert_activity');
1904                         return false;
1905                 }
1906                 if ($locked) {
1907                         Lock::release('item_insert_activity');
1908                 }
1909                 return true;
1910         }
1911
1912         /**
1913          * @brief Insert a new item content entry
1914          *
1915          * @param array $item The item fields that are to be inserted
1916          * @throws \Exception
1917          */
1918         private static function insertContent(&$item)
1919         {
1920                 $fields = ['uri-plink-hash' => (string)$item['uri-id'], 'uri-id' => $item['uri-id']];
1921
1922                 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1923                         if (isset($item[$field])) {
1924                                 $fields[$field] = $item[$field];
1925                                 unset($item[$field]);
1926                         }
1927                 }
1928
1929                 // To avoid timing problems, we are using locks.
1930                 $locked = Lock::acquire('item_insert_content');
1931                 if (!$locked) {
1932                         Logger::log("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
1933                 }
1934
1935                 // Do we already have this content?
1936                 $item_content = DBA::selectFirst('item-content', ['id'], ['uri-id' => $item['uri-id']]);
1937                 if (DBA::isResult($item_content)) {
1938                         $item['icid'] = $item_content['id'];
1939                         Logger::log('Fetched content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
1940                 } elseif (DBA::insert('item-content', $fields)) {
1941                         $item['icid'] = DBA::lastInsertId();
1942                         Logger::log('Inserted content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
1943                 } else {
1944                         // This shouldn't happen.
1945                         Logger::log('Could not insert content for URI ' . $item['uri'] . ' - should not happen');
1946                 }
1947                 if ($locked) {
1948                         Lock::release('item_insert_content');
1949                 }
1950         }
1951
1952         /**
1953          * @brief Update existing item content entries
1954          *
1955          * @param array $item      The item fields that are to be changed
1956          * @param array $condition The condition for finding the item content entries
1957          * @return bool
1958          * @throws \Exception
1959          */
1960         private static function updateActivity($item, $condition)
1961         {
1962                 if (empty($item['verb'])) {
1963                         return false;
1964                 }
1965                 $activity_index = self::activityToIndex($item['verb']);
1966
1967                 if ($activity_index < 0) {
1968                         return false;
1969                 }
1970
1971                 $fields = ['activity' => $activity_index];
1972
1973                 Logger::log('Update activity for ' . json_encode($condition));
1974
1975                 DBA::update('item-activity', $fields, $condition, true);
1976
1977                 return true;
1978         }
1979
1980         /**
1981          * @brief Update existing item content entries
1982          *
1983          * @param array $item      The item fields that are to be changed
1984          * @param array $condition The condition for finding the item content entries
1985          * @throws \Exception
1986          */
1987         private static function updateContent($item, $condition)
1988         {
1989                 // We have to select only the fields from the "item-content" table
1990                 $fields = [];
1991                 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1992                         if (isset($item[$field])) {
1993                                 $fields[$field] = $item[$field];
1994                         }
1995                 }
1996
1997                 if (empty($fields)) {
1998                         // when there are no fields at all, just use the condition
1999                         // This is to ensure that we always store content.
2000                         $fields = $condition;
2001                 }
2002
2003                 Logger::log('Update content for ' . json_encode($condition));
2004
2005                 DBA::update('item-content', $fields, $condition, true);
2006         }
2007
2008         /**
2009          * @brief Distributes public items to the receivers
2010          *
2011          * @param integer $itemid      Item ID that should be added
2012          * @param string  $signed_text Original text (for Diaspora signatures), JSON encoded.
2013          * @throws \Exception
2014          */
2015         public static function distribute($itemid, $signed_text = '')
2016         {
2017                 $condition = ["`id` IN (SELECT `parent` FROM `item` WHERE `id` = ?)", $itemid];
2018                 $parent = self::selectFirst(['owner-id'], $condition);
2019                 if (!DBA::isResult($parent)) {
2020                         return;
2021                 }
2022
2023                 // Only distribute public items from native networks
2024                 $condition = ['id' => $itemid, 'uid' => 0,
2025                         'network' => [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""],
2026                         'visible' => true, 'deleted' => false, 'moderated' => false, 'private' => false];
2027                 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2028                 if (!DBA::isResult($item)) {
2029                         return;
2030                 }
2031
2032                 $origin = $item['origin'];
2033
2034                 unset($item['id']);
2035                 unset($item['parent']);
2036                 unset($item['mention']);
2037                 unset($item['wall']);
2038                 unset($item['origin']);
2039                 unset($item['starred']);
2040
2041                 $users = [];
2042
2043                 /// @todo add a field "pcid" in the contact table that referrs to the public contact id.
2044                 $owner = DBA::selectFirst('contact', ['url', 'nurl', 'alias'], ['id' => $parent['owner-id']]);
2045                 if (!DBA::isResult($owner)) {
2046                         return;
2047                 }
2048
2049                 $condition = ['nurl' => $owner['nurl'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2050                 $contacts = DBA::select('contact', ['uid'], $condition);
2051                 while ($contact = DBA::fetch($contacts)) {
2052                         if ($contact['uid'] == 0) {
2053                                 continue;
2054                         }
2055
2056                         $users[$contact['uid']] = $contact['uid'];
2057                 }
2058                 DBA::close($contacts);
2059
2060                 $condition = ['alias' => $owner['url'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2061                 $contacts = DBA::select('contact', ['uid'], $condition);
2062                 while ($contact = DBA::fetch($contacts)) {
2063                         if ($contact['uid'] == 0) {
2064                                 continue;
2065                         }
2066
2067                         $users[$contact['uid']] = $contact['uid'];
2068                 }
2069                 DBA::close($contacts);
2070
2071                 if (!empty($owner['alias'])) {
2072                         $condition = ['url' => $owner['alias'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2073                         $contacts = DBA::select('contact', ['uid'], $condition);
2074                         while ($contact = DBA::fetch($contacts)) {
2075                                 if ($contact['uid'] == 0) {
2076                                         continue;
2077                                 }
2078
2079                                 $users[$contact['uid']] = $contact['uid'];
2080                         }
2081                         DBA::close($contacts);
2082                 }
2083
2084                 $origin_uid = 0;
2085
2086                 if ($item['uri'] != $item['parent-uri']) {
2087                         $parents = self::select(['uid', 'origin'], ["`uri` = ? AND `uid` != 0", $item['parent-uri']]);
2088                         while ($parent = self::fetch($parents)) {
2089                                 $users[$parent['uid']] = $parent['uid'];
2090                                 if ($parent['origin'] && !$origin) {
2091                                         $origin_uid = $parent['uid'];
2092                                 }
2093                         }
2094                 }
2095
2096                 foreach ($users as $uid) {
2097                         if ($origin_uid == $uid) {
2098                                 $item['diaspora_signed_text'] = $signed_text;
2099                         }
2100                         self::storeForUser($itemid, $item, $uid);
2101                 }
2102         }
2103
2104         /**
2105          * @brief Store public items for the receivers
2106          *
2107          * @param integer $itemid Item ID that should be added
2108          * @param array   $item   The item entry that will be stored
2109          * @param integer $uid    The user that will receive the item entry
2110          * @throws \Exception
2111          */
2112         private static function storeForUser($itemid, $item, $uid)
2113         {
2114                 $item['uid'] = $uid;
2115                 $item['origin'] = 0;
2116                 $item['wall'] = 0;
2117                 if ($item['uri'] == $item['parent-uri']) {
2118                         $item['contact-id'] = Contact::getIdForURL($item['owner-link'], $uid);
2119                 } else {
2120                         $item['contact-id'] = Contact::getIdForURL($item['author-link'], $uid);
2121                 }
2122
2123                 if (empty($item['contact-id'])) {
2124                         $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $uid]);
2125                         if (!DBA::isResult($self)) {
2126                                 return;
2127                         }
2128                         $item['contact-id'] = $self['id'];
2129                 }
2130
2131                 /// @todo Handling of "event-id"
2132
2133                 $notify = false;
2134                 if ($item['uri'] == $item['parent-uri']) {
2135                         $contact = DBA::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
2136                         if (DBA::isResult($contact)) {
2137                                 $notify = self::isRemoteSelf($contact, $item);
2138                         }
2139                 }
2140
2141                 $distributed = self::insert($item, false, $notify, true);
2142
2143                 if (!$distributed) {
2144                         Logger::log("Distributed public item " . $itemid . " for user " . $uid . " wasn't stored", Logger::DEBUG);
2145                 } else {
2146                         Logger::log("Distributed public item " . $itemid . " for user " . $uid . " with id " . $distributed, Logger::DEBUG);
2147                 }
2148         }
2149
2150         /**
2151          * @brief Add a shadow entry for a given item id that is a thread starter
2152          *
2153          * We store every public item entry additionally with the user id "0".
2154          * This is used for the community page and for the search.
2155          * It is planned that in the future we will store public item entries only once.
2156          *
2157          * @param integer $itemid Item ID that should be added
2158          * @throws \Exception
2159          */
2160         public static function addShadow($itemid)
2161         {
2162                 $fields = ['uid', 'private', 'moderated', 'visible', 'deleted', 'network', 'uri'];
2163                 $condition = ['id' => $itemid, 'parent' => [0, $itemid]];
2164                 $item = self::selectFirst($fields, $condition);
2165
2166                 if (!DBA::isResult($item)) {
2167                         return;
2168                 }
2169
2170                 // is it already a copy?
2171                 if (($itemid == 0) || ($item['uid'] == 0)) {
2172                         return;
2173                 }
2174
2175                 // Is it a visible public post?
2176                 if (!$item["visible"] || $item["deleted"] || $item["moderated"] || $item["private"]) {
2177                         return;
2178                 }
2179
2180                 // is it an entry from a connector? Only add an entry for natively connected networks
2181                 if (!in_array($item["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""])) {
2182                         return;
2183                 }
2184
2185                 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2186                         return;
2187                 }
2188
2189                 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2190
2191                 if (DBA::isResult($item)) {
2192                         // Preparing public shadow (removing user specific data)
2193                         $item['uid'] = 0;
2194                         unset($item['id']);
2195                         unset($item['parent']);
2196                         unset($item['wall']);
2197                         unset($item['mention']);
2198                         unset($item['origin']);
2199                         unset($item['starred']);
2200                         unset($item['postopts']);
2201                         unset($item['inform']);
2202                         if ($item['uri'] == $item['parent-uri']) {
2203                                 $item['contact-id'] = $item['owner-id'];
2204                         } else {
2205                                 $item['contact-id'] = $item['author-id'];
2206                         }
2207
2208                         $public_shadow = self::insert($item, false, false, true);
2209
2210                         Logger::log("Stored public shadow for thread ".$itemid." under id ".$public_shadow, Logger::DEBUG);
2211                 }
2212         }
2213
2214         /**
2215          * @brief Add a shadow entry for a given item id that is a comment
2216          *
2217          * This function does the same like the function above - but for comments
2218          *
2219          * @param integer $itemid Item ID that should be added
2220          * @throws \Exception
2221          */
2222         public static function addShadowPost($itemid)
2223         {
2224                 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2225                 if (!DBA::isResult($item)) {
2226                         return;
2227                 }
2228
2229                 // Is it a toplevel post?
2230                 if ($item['id'] == $item['parent']) {
2231                         self::addShadow($itemid);
2232                         return;
2233                 }
2234
2235                 // Is this a shadow entry?
2236                 if ($item['uid'] == 0) {
2237                         return;
2238                 }
2239
2240                 // Is there a shadow parent?
2241                 if (!self::exists(['uri' => $item['parent-uri'], 'uid' => 0])) {
2242                         return;
2243                 }
2244
2245                 // Is there already a shadow entry?
2246                 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2247                         return;
2248                 }
2249
2250                 // Save "origin" and "parent" state
2251                 $origin = $item['origin'];
2252                 $parent = $item['parent'];
2253
2254                 // Preparing public shadow (removing user specific data)
2255                 $item['uid'] = 0;
2256                 unset($item['id']);
2257                 unset($item['parent']);
2258                 unset($item['wall']);
2259                 unset($item['mention']);
2260                 unset($item['origin']);
2261                 unset($item['starred']);
2262                 unset($item['postopts']);
2263                 unset($item['inform']);
2264                 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
2265
2266                 $public_shadow = self::insert($item, false, false, true);
2267
2268                 Logger::log("Stored public shadow for comment ".$item['uri']." under id ".$public_shadow, Logger::DEBUG);
2269
2270                 // If this was a comment to a Diaspora post we don't get our comment back.
2271                 // This means that we have to distribute the comment by ourselves.
2272                 if ($origin && self::exists(['id' => $parent, 'network' => Protocol::DIASPORA])) {
2273                         self::distribute($public_shadow);
2274                 }
2275         }
2276
2277         /**
2278          * Adds a language specification in a "language" element of given $arr.
2279          * Expects "body" element to exist in $arr.
2280          *
2281          * @param $item
2282          * @throws \Text_LanguageDetect_Exception
2283          */
2284         private static function addLanguageToItemArray(&$item)
2285         {
2286                 $naked_body = BBCode::toPlaintext($item['body'], false);
2287
2288                 $ld = new Text_LanguageDetect();
2289                 $ld->setNameMode(2);
2290                 $languages = $ld->detect($naked_body, 3);
2291
2292                 if (is_array($languages)) {
2293                         $item['language'] = json_encode($languages);
2294                 }
2295         }
2296
2297         /**
2298          * @brief Creates an unique guid out of a given uri
2299          *
2300          * @param string $uri uri of an item entry
2301          * @param string $host hostname for the GUID prefix
2302          * @return string unique guid
2303          */
2304         public static function guidFromUri($uri, $host)
2305         {
2306                 // Our regular guid routine is using this kind of prefix as well
2307                 // We have to avoid that different routines could accidentally create the same value
2308                 $parsed = parse_url($uri);
2309
2310                 // We use a hash of the hostname as prefix for the guid
2311                 $guid_prefix = hash("crc32", $host);
2312
2313                 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
2314                 unset($parsed["scheme"]);
2315
2316                 // Glue it together to be able to make a hash from it
2317                 $host_id = implode("/", $parsed);
2318
2319                 // We could use any hash algorithm since it isn't a security issue
2320                 $host_hash = hash("ripemd128", $host_id);
2321
2322                 return $guid_prefix.$host_hash;
2323         }
2324
2325         /**
2326          * generate an unique URI
2327          *
2328          * @param integer $uid  User id
2329          * @param string  $guid An existing GUID (Otherwise it will be generated)
2330          *
2331          * @return string
2332          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2333          */
2334         public static function newURI($uid, $guid = "")
2335         {
2336                 if ($guid == "") {
2337                         $guid = System::createUUID();
2338                 }
2339
2340                 return self::getApp()->getBaseURL() . '/objects/' . $guid;
2341         }
2342
2343         /**
2344          * @brief Set "success_update" and "last-item" to the date of the last time we heard from this contact
2345          *
2346          * This can be used to filter for inactive contacts.
2347          * Only do this for public postings to avoid privacy problems, since poco data is public.
2348          * Don't set this value if it isn't from the owner (could be an author that we don't know)
2349          *
2350          * @param array $arr Contains the just posted item record
2351          * @throws \Exception
2352          */
2353         private static function updateContact($arr)
2354         {
2355                 // Unarchive the author
2356                 $contact = DBA::selectFirst('contact', [], ['id' => $arr["author-id"]]);
2357                 if (DBA::isResult($contact)) {
2358                         Contact::unmarkForArchival($contact);
2359                 }
2360
2361                 // Unarchive the contact if it's not our own contact
2362                 $contact = DBA::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
2363                 if (DBA::isResult($contact)) {
2364                         Contact::unmarkForArchival($contact);
2365                 }
2366
2367                 $update = (!$arr['private'] && ((defaults($arr, 'author-link', '') === defaults($arr, 'owner-link', '')) || ($arr["parent-uri"] === $arr["uri"])));
2368
2369                 // Is it a forum? Then we don't care about the rules from above
2370                 if (!$update && in_array($arr["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN]) && ($arr["parent-uri"] === $arr["uri"])) {
2371                         if (DBA::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
2372                                 $update = true;
2373                         }
2374                 }
2375
2376                 if ($update) {
2377                         DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2378                                 ['id' => $arr['contact-id']]);
2379                 }
2380                 // Now do the same for the system wide contacts with uid=0
2381                 if (!$arr['private']) {
2382                         DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2383                                 ['id' => $arr['owner-id']]);
2384
2385                         if ($arr['owner-id'] != $arr['author-id']) {
2386                                 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2387                                         ['id' => $arr['author-id']]);
2388                         }
2389                 }
2390         }
2391
2392         public static function setHashtags(&$item)
2393         {
2394
2395                 $tags = BBCode::getTags($item["body"]);
2396
2397                 // No hashtags?
2398                 if (!count($tags)) {
2399                         return false;
2400                 }
2401
2402                 // This sorting is important when there are hashtags that are part of other hashtags
2403                 // Otherwise there could be problems with hashtags like #test and #test2
2404                 rsort($tags);
2405
2406                 $URLSearchString = "^\[\]";
2407
2408                 // All hashtags should point to the home server if "local_tags" is activated
2409                 if (Config::get('system', 'local_tags')) {
2410                         $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2411                                         "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["body"]);
2412
2413                         $item["tag"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2414                                         "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["tag"]);
2415                 }
2416
2417                 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
2418                 $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2419                         function ($match) {
2420                                 return ("[url=" . str_replace("#", "&num;", $match[1]) . "]" . str_replace("#", "&num;", $match[2]) . "[/url]");
2421                         }, $item["body"]);
2422
2423                 $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
2424                         function ($match) {
2425                                 return ("[bookmark=" . str_replace("#", "&num;", $match[1]) . "]" . str_replace("#", "&num;", $match[2]) . "[/bookmark]");
2426                         }, $item["body"]);
2427
2428                 $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
2429                         function ($match) {
2430                                 return ("[attachment " . str_replace("#", "&num;", $match[1]) . "]" . $match[2] . "[/attachment]");
2431                         }, $item["body"]);
2432
2433                 // Repair recursive urls
2434                 $item["body"] = preg_replace("/&num;\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2435                                 "&num;$2", $item["body"]);
2436
2437                 foreach ($tags as $tag) {
2438                         if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=')) {
2439                                 continue;
2440                         }
2441
2442                         $basetag = str_replace('_',' ',substr($tag,1));
2443
2444                         $newtag = '#[url=' . System::baseUrl() . '/search?tag=' . $basetag . ']' . $basetag . '[/url]';
2445
2446                         $item["body"] = str_replace($tag, $newtag, $item["body"]);
2447
2448                         if (!stristr($item["tag"], "/search?tag=" . $basetag . "]" . $basetag . "[/url]")) {
2449                                 if (strlen($item["tag"])) {
2450                                         $item["tag"] = ',' . $item["tag"];
2451                                 }
2452                                 $item["tag"] = $newtag . $item["tag"];
2453                         }
2454                 }
2455
2456                 // Convert back the masked hashtags
2457                 $item["body"] = str_replace("&num;", "#", $item["body"]);
2458         }
2459
2460         public static function getGuidById($id)
2461         {
2462                 $item = self::selectFirst(['guid'], ['id' => $id]);
2463                 if (DBA::isResult($item)) {
2464                         return $item['guid'];
2465                 } else {
2466                         return '';
2467                 }
2468         }
2469
2470         /**
2471          * This function is only used for the old Friendica app on Android that doesn't like paths with guid
2472          *
2473          * @param string $guid item guid
2474          * @param int    $uid  user id
2475          * @return array with id and nick of the item with the given guid
2476          * @throws \Exception
2477          */
2478         public static function getIdAndNickByGuid($guid, $uid = 0)
2479         {
2480                 $nick = "";
2481                 $id = 0;
2482
2483                 if ($uid == 0) {
2484                         $uid == local_user();
2485                 }
2486
2487                 // Does the given user have this item?
2488                 if ($uid) {
2489                         $item = self::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
2490                         if (DBA::isResult($item)) {
2491                                 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $uid]);
2492                                 if (!DBA::isResult($user)) {
2493                                         return;
2494                                 }
2495                                 $id = $item['id'];
2496                                 $nick = $user['nickname'];
2497                         }
2498                 }
2499
2500                 // Or is it anywhere on the server?
2501                 if ($nick == "") {
2502                         $condition = ["`guid` = ? AND `uid` != 0", $guid];
2503                         $item = self::selectFirst(['id', 'uid'], $condition);
2504                         if (DBA::isResult($item)) {
2505                                 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $item['uid']]);
2506                                 if (!DBA::isResult($user)) {
2507                                         return;
2508                                 }
2509                                 $id = $item['id'];
2510                                 $nick = $user['nickname'];
2511                         }
2512                 }
2513                 return ["nick" => $nick, "id" => $id];
2514         }
2515
2516         /**
2517          * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
2518          *
2519          * @param int $uid
2520          * @param int $item_id
2521          * @return void true if item was deleted, else false
2522          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2523          * @throws \ImagickException
2524          */
2525         private static function tagDeliver($uid, $item_id)
2526         {
2527                 $mention = false;
2528
2529                 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
2530                 if (!DBA::isResult($user)) {
2531                         return;
2532                 }
2533
2534                 $community_page = (($user['page-flags'] == Contact::PAGE_COMMUNITY) ? true : false);
2535                 $prvgroup = (($user['page-flags'] == Contact::PAGE_PRVGROUP) ? true : false);
2536
2537                 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2538                 if (!DBA::isResult($item)) {
2539                         return;
2540                 }
2541
2542                 $link = Strings::normaliseLink(System::baseUrl() . '/profile/' . $user['nickname']);
2543
2544                 /*
2545                  * Diaspora uses their own hardwired link URL in @-tags
2546                  * instead of the one we supply with webfinger
2547                  */
2548                 $dlink = Strings::normaliseLink(System::baseUrl() . '/u/' . $user['nickname']);
2549
2550                 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
2551                 if ($cnt) {
2552                         foreach ($matches as $mtch) {
2553                                 if (Strings::compareLink($link, $mtch[1]) || Strings::compareLink($dlink, $mtch[1])) {
2554                                         $mention = true;
2555                                         Logger::log('mention found: ' . $mtch[2]);
2556                                 }
2557                         }
2558                 }
2559
2560                 if (!$mention) {
2561                         if (($community_page || $prvgroup) &&
2562                                   !$item['wall'] && !$item['origin'] && ($item['id'] == $item['parent'])) {
2563                                 // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
2564                                 // delete it!
2565                                 Logger::log("no-mention top-level post to community or private group. delete.");
2566                                 DBA::delete('item', ['id' => $item_id]);
2567                                 return true;
2568                         }
2569                         return;
2570                 }
2571
2572                 $arr = ['item' => $item, 'user' => $user];
2573
2574                 Hook::callAll('tagged', $arr);
2575
2576                 if (!$community_page && !$prvgroup) {
2577                         return;
2578                 }
2579
2580                 /*
2581                  * tgroup delivery - setup a second delivery chain
2582                  * prevent delivery looping - only proceed
2583                  * if the message originated elsewhere and is a top-level post
2584                  */
2585                 if ($item['wall'] || $item['origin'] || ($item['id'] != $item['parent'])) {
2586                         return;
2587                 }
2588
2589                 // now change this copy of the post to a forum head message and deliver to all the tgroup members
2590                 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'], ['uid' => $uid, 'self' => true]);
2591                 if (!DBA::isResult($self)) {
2592                         return;
2593                 }
2594
2595                 $owner_id = Contact::getIdForURL($self['url']);
2596
2597                 // also reset all the privacy bits to the forum default permissions
2598
2599                 $private = ($user['allow_cid'] || $user['allow_gid'] || $user['deny_cid'] || $user['deny_gid']) ? 1 : 0;
2600
2601                 $psid = PermissionSet::fetchIDForPost($user);
2602
2603                 $forum_mode = ($prvgroup ? 2 : 1);
2604
2605                 $fields = ['wall' => true, 'origin' => true, 'forum_mode' => $forum_mode, 'contact-id' => $self['id'],
2606                         'owner-id' => $owner_id, 'private' => $private, 'psid' => $psid];
2607                 self::update($fields, ['id' => $item_id]);
2608
2609                 self::updateThread($item_id);
2610
2611                 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', 'tgroup', $item_id);
2612         }
2613
2614         public static function isRemoteSelf($contact, &$datarray)
2615         {
2616                 $a = \get_app();
2617
2618                 if (!$contact['remote_self']) {
2619                         return false;
2620                 }
2621
2622                 // Prevent the forwarding of posts that are forwarded
2623                 if (!empty($datarray["extid"]) && ($datarray["extid"] == Protocol::DFRN)) {
2624                         Logger::log('Already forwarded', Logger::DEBUG);
2625                         return false;
2626                 }
2627
2628                 // Prevent to forward already forwarded posts
2629                 if ($datarray["app"] == $a->getHostName()) {
2630                         Logger::log('Already forwarded (second test)', Logger::DEBUG);
2631                         return false;
2632                 }
2633
2634                 // Only forward posts
2635                 if ($datarray["verb"] != ACTIVITY_POST) {
2636                         Logger::log('No post', Logger::DEBUG);
2637                         return false;
2638                 }
2639
2640                 if (($contact['network'] != Protocol::FEED) && $datarray['private']) {
2641                         Logger::log('Not public', Logger::DEBUG);
2642                         return false;
2643                 }
2644
2645                 $datarray2 = $datarray;
2646                 Logger::log('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), Logger::DEBUG);
2647                 if ($contact['remote_self'] == 2) {
2648                         $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
2649                                         ['uid' => $contact['uid'], 'self' => true]);
2650                         if (DBA::isResult($self)) {
2651                                 $datarray['contact-id'] = $self["id"];
2652
2653                                 $datarray['owner-name'] = $self["name"];
2654                                 $datarray['owner-link'] = $self["url"];
2655                                 $datarray['owner-avatar'] = $self["thumb"];
2656
2657                                 $datarray['author-name']   = $datarray['owner-name'];
2658                                 $datarray['author-link']   = $datarray['owner-link'];
2659                                 $datarray['author-avatar'] = $datarray['owner-avatar'];
2660
2661                                 unset($datarray['created']);
2662                                 unset($datarray['edited']);
2663
2664                                 unset($datarray['network']);
2665                                 unset($datarray['owner-id']);
2666                                 unset($datarray['author-id']);
2667                         }
2668
2669                         if ($contact['network'] != Protocol::FEED) {
2670                                 $datarray["guid"] = System::createUUID();
2671                                 unset($datarray["plink"]);
2672                                 $datarray["uri"] = self::newURI($contact['uid'], $datarray["guid"]);
2673                                 $datarray["parent-uri"] = $datarray["uri"];
2674                                 $datarray["thr-parent"] = $datarray["uri"];
2675                                 $datarray["extid"] = Protocol::DFRN;
2676                                 $urlpart = parse_url($datarray2['author-link']);
2677                                 $datarray["app"] = $urlpart["host"];
2678                         } else {
2679                                 $datarray['private'] = 0;
2680                         }
2681                 }
2682
2683                 if ($contact['network'] != Protocol::FEED) {
2684                         // Store the original post
2685                         $result = self::insert($datarray2, false, false);
2686                         Logger::log('remote-self post original item - Contact '.$contact['url'].' return '.$result.' Item '.print_r($datarray2, true), Logger::DEBUG);
2687                 } else {
2688                         $datarray["app"] = "Feed";
2689                         $result = true;
2690                 }
2691
2692                 // Trigger automatic reactions for addons
2693                 $datarray['api_source'] = true;
2694
2695                 // We have to tell the hooks who we are - this really should be improved
2696                 $_SESSION["authenticated"] = true;
2697                 $_SESSION["uid"] = $contact['uid'];
2698
2699                 return $result;
2700         }
2701
2702         /**
2703          *
2704          * @param string $s
2705          * @param int    $uid
2706          * @param array  $item
2707          * @param int    $cid
2708          * @return string
2709          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2710          * @throws \ImagickException
2711          */
2712         public static function fixPrivatePhotos($s, $uid, $item = null, $cid = 0)
2713         {
2714                 if (Config::get('system', 'disable_embedded')) {
2715                         return $s;
2716                 }
2717
2718                 Logger::log('check for photos', Logger::DEBUG);
2719                 $site = substr(System::baseUrl(), strpos(System::baseUrl(), '://'));
2720
2721                 $orig_body = $s;
2722                 $new_body = '';
2723
2724                 $img_start = strpos($orig_body, '[img');
2725                 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2726                 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2727
2728                 while (($img_st_close !== false) && ($img_len !== false)) {
2729                         $img_st_close++; // make it point to AFTER the closing bracket
2730                         $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2731
2732                         Logger::log('found photo ' . $image, Logger::DEBUG);
2733
2734                         if (stristr($image, $site . '/photo/')) {
2735                                 // Only embed locally hosted photos
2736                                 $replace = false;
2737                                 $i = basename($image);
2738                                 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2739                                 $x = strpos($i, '-');
2740
2741                                 if ($x) {
2742                                         $res = substr($i, $x + 1);
2743                                         $i = substr($i, 0, $x);
2744                                         $photo = Photo::getPhotoForUser($uid, $i, $res);
2745                                         if (DBA::isResult($photo)) {
2746                                                 /*
2747                                                  * Check to see if we should replace this photo link with an embedded image
2748                                                  * 1. No need to do so if the photo is public
2749                                                  * 2. If there's a contact-id provided, see if they're in the access list
2750                                                  *    for the photo. If so, embed it.
2751                                                  * 3. Otherwise, if we have an item, see if the item permissions match the photo
2752                                                  *    permissions, regardless of order but first check to see if they're an exact
2753                                                  *    match to save some processing overhead.
2754                                                  */
2755                                                 if (self::hasPermissions($photo)) {
2756                                                         if ($cid) {
2757                                                                 $recips = self::enumeratePermissions($photo);
2758                                                                 if (in_array($cid, $recips)) {
2759                                                                         $replace = true;
2760                                                                 }
2761                                                         } elseif ($item) {
2762                                                                 if (self::samePermissions($item, $photo)) {
2763                                                                         $replace = true;
2764                                                                 }
2765                                                         }
2766                                                 }
2767                                                 if ($replace) {
2768                                                         $photo_img = Photo::getImageForPhoto($photo);
2769                                                         // If a custom width and height were specified, apply before embedding
2770                                                         if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2771                                                                 Logger::log('scaling photo', Logger::DEBUG);
2772
2773                                                                 $width = intval($match[1]);
2774                                                                 $height = intval($match[2]);
2775
2776                                                                 $photo_img->scaleDown(max($width, $height));
2777                                                         }
2778
2779                                                         $data = $photo_img->asString();
2780                                                         $type = $photo_img->getType();
2781
2782                                                         Logger::log('replacing photo', Logger::DEBUG);
2783                                                         $image = 'data:' . $type . ';base64,' . base64_encode($data);
2784                                                         Logger::log('replaced: ' . $image, Logger::DATA);
2785                                                 }
2786                                         }
2787                                 }
2788                         }
2789
2790                         $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2791                         $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2792                         if ($orig_body === false) {
2793                                 $orig_body = '';
2794                         }
2795
2796                         $img_start = strpos($orig_body, '[img');
2797                         $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2798                         $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2799                 }
2800
2801                 $new_body = $new_body . $orig_body;
2802
2803                 return $new_body;
2804         }
2805
2806         private static function hasPermissions($obj)
2807         {
2808                 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2809                         !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2810         }
2811
2812         private static function samePermissions($obj1, $obj2)
2813         {
2814                 // first part is easy. Check that these are exactly the same.
2815                 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2816                         && ($obj1['allow_gid'] == $obj2['allow_gid'])
2817                         && ($obj1['deny_cid'] == $obj2['deny_cid'])
2818                         && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
2819                         return true;
2820                 }
2821
2822                 // This is harder. Parse all the permissions and compare the resulting set.
2823                 $recipients1 = self::enumeratePermissions($obj1);
2824                 $recipients2 = self::enumeratePermissions($obj2);
2825                 sort($recipients1);
2826                 sort($recipients2);
2827
2828                 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2829                 return ($recipients1 == $recipients2);
2830         }
2831
2832         // returns an array of contact-ids that are allowed to see this object
2833         public static function enumeratePermissions($obj)
2834         {
2835                 $allow_people = expand_acl($obj['allow_cid']);
2836                 $allow_groups = Group::expand(expand_acl($obj['allow_gid']));
2837                 $deny_people  = expand_acl($obj['deny_cid']);
2838                 $deny_groups  = Group::expand(expand_acl($obj['deny_gid']));
2839                 $recipients   = array_unique(array_merge($allow_people, $allow_groups));
2840                 $deny         = array_unique(array_merge($deny_people, $deny_groups));
2841                 $recipients   = array_diff($recipients, $deny);
2842                 return $recipients;
2843         }
2844
2845         public static function getFeedTags($item)
2846         {
2847                 $ret = [];
2848                 $matches = false;
2849                 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2850                 if ($cnt) {
2851                         for ($x = 0; $x < $cnt; $x ++) {
2852                                 if ($matches[1][$x]) {
2853                                         $ret[$matches[2][$x]] = ['#', $matches[1][$x], $matches[2][$x]];
2854                                 }
2855                         }
2856                 }
2857                 $matches = false;
2858                 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2859                 if ($cnt) {
2860                         for ($x = 0; $x < $cnt; $x ++) {
2861                                 if ($matches[1][$x]) {
2862                                         $ret[] = ['@', $matches[1][$x], $matches[2][$x]];
2863                                 }
2864                         }
2865                 }
2866                 return $ret;
2867         }
2868
2869         public static function expire($uid, $days, $network = "", $force = false)
2870         {
2871                 if (!$uid || ($days < 1)) {
2872                         return;
2873                 }
2874
2875                 $condition = ["`uid` = ? AND NOT `deleted` AND `id` = `parent` AND `gravity` = ?",
2876                         $uid, GRAVITY_PARENT];
2877
2878                 /*
2879                  * $expire_network_only = save your own wall posts
2880                  * and just expire conversations started by others
2881                  */
2882                 $expire_network_only = PConfig::get($uid, 'expire', 'network_only', false);
2883
2884                 if ($expire_network_only) {
2885                         $condition[0] .= " AND NOT `wall`";
2886                 }
2887
2888                 if ($network != "") {
2889                         $condition[0] .= " AND `network` = ?";
2890                         $condition[] = $network;
2891
2892                         /*
2893                          * There is an index "uid_network_received" but not "uid_network_created"
2894                          * This avoids the creation of another index just for one purpose.
2895                          * And it doesn't really matter wether to look at "received" or "created"
2896                          */
2897                         $condition[0] .= " AND `received` < UTC_TIMESTAMP() - INTERVAL ? DAY";
2898                         $condition[] = $days;
2899                 } else {
2900                         $condition[0] .= " AND `created` < UTC_TIMESTAMP() - INTERVAL ? DAY";
2901                         $condition[] = $days;
2902                 }
2903
2904                 $items = self::select(['file', 'resource-id', 'starred', 'type', 'id', 'post-type'], $condition);
2905
2906                 if (!DBA::isResult($items)) {
2907                         return;
2908                 }
2909
2910                 $expire_items = PConfig::get($uid, 'expire', 'items', true);
2911
2912                 // Forcing expiring of items - but not notes and marked items
2913                 if ($force) {
2914                         $expire_items = true;
2915                 }
2916
2917                 $expire_notes = PConfig::get($uid, 'expire', 'notes', true);
2918                 $expire_starred = PConfig::get($uid, 'expire', 'starred', true);
2919                 $expire_photos = PConfig::get($uid, 'expire', 'photos', false);
2920
2921                 $expired = 0;
2922
2923                 while ($item = Item::fetch($items)) {
2924                         // don't expire filed items
2925
2926                         if (strpos($item['file'], '[') !== false) {
2927                                 continue;
2928                         }
2929
2930                         // Only expire posts, not photos and photo comments
2931
2932                         if (!$expire_photos && strlen($item['resource-id'])) {
2933                                 continue;
2934                         } elseif (!$expire_starred && intval($item['starred'])) {
2935                                 continue;
2936                         } elseif (!$expire_notes && (($item['type'] == 'note') || ($item['post-type'] == Item::PT_PERSONAL_NOTE))) {
2937                                 continue;
2938                         } elseif (!$expire_items && ($item['type'] != 'note') && ($item['post-type'] != Item::PT_PERSONAL_NOTE)) {
2939                                 continue;
2940                         }
2941
2942                         self::deleteById($item['id'], PRIORITY_LOW);
2943
2944                         ++$expired;
2945                 }
2946                 DBA::close($items);
2947                 Logger::log('User ' . $uid . ": expired $expired items; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
2948         }
2949
2950         public static function firstPostDate($uid, $wall = false)
2951         {
2952                 $condition = ['uid' => $uid, 'wall' => $wall, 'deleted' => false, 'visible' => true, 'moderated' => false];
2953                 $params = ['order' => ['created' => false]];
2954                 $thread = DBA::selectFirst('thread', ['created'], $condition, $params);
2955                 if (DBA::isResult($thread)) {
2956                         return substr(DateTimeFormat::local($thread['created']), 0, 10);
2957                 }
2958                 return false;
2959         }
2960
2961         /**
2962          * @brief add/remove activity to an item
2963          *
2964          * Toggle activities as like,dislike,attend of an item
2965          *
2966          * @param string $item_id
2967          * @param string $verb
2968          *            Activity verb. One of
2969          *            like, unlike, dislike, undislike, attendyes, unattendyes,
2970          *            attendno, unattendno, attendmaybe, unattendmaybe
2971          * @return bool
2972          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2973          * @throws \ImagickException
2974          * @hook  'post_local_end'
2975          *            array $arr
2976          *            'post_id' => ID of posted item
2977          */
2978         public static function performLike($item_id, $verb)
2979         {
2980                 if (!local_user() && !remote_user()) {
2981                         return false;
2982                 }
2983
2984                 switch ($verb) {
2985                         case 'like':
2986                         case 'unlike':
2987                                 $activity = ACTIVITY_LIKE;
2988                                 break;
2989                         case 'dislike':
2990                         case 'undislike':
2991                                 $activity = ACTIVITY_DISLIKE;
2992                                 break;
2993                         case 'attendyes':
2994                         case 'unattendyes':
2995                                 $activity = ACTIVITY_ATTEND;
2996                                 break;
2997                         case 'attendno':
2998                         case 'unattendno':
2999                                 $activity = ACTIVITY_ATTENDNO;
3000                                 break;
3001                         case 'attendmaybe':
3002                         case 'unattendmaybe':
3003                                 $activity = ACTIVITY_ATTENDMAYBE;
3004                                 break;
3005                         default:
3006                                 Logger::log('like: unknown verb ' . $verb . ' for item ' . $item_id);
3007                                 return false;
3008                 }
3009
3010                 // Enable activity toggling instead of on/off
3011                 $event_verb_flag = $activity === ACTIVITY_ATTEND || $activity === ACTIVITY_ATTENDNO || $activity === ACTIVITY_ATTENDMAYBE;
3012
3013                 Logger::log('like: verb ' . $verb . ' item ' . $item_id);
3014
3015                 $item = self::selectFirst(self::ITEM_FIELDLIST, ['`id` = ? OR `uri` = ?', $item_id, $item_id]);
3016                 if (!DBA::isResult($item)) {
3017                         Logger::log('like: unknown item ' . $item_id);
3018                         return false;
3019                 }
3020
3021                 $item_uri = $item['uri'];
3022
3023                 $uid = $item['uid'];
3024                 if (($uid == 0) && local_user()) {
3025                         $uid = local_user();
3026                 }
3027
3028                 if (!Security::canWriteToUserWall($uid)) {
3029                         Logger::log('like: unable to write on wall ' . $uid);
3030                         return false;
3031                 }
3032
3033                 // Retrieves the local post owner
3034                 $owner_self_contact = DBA::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
3035                 if (!DBA::isResult($owner_self_contact)) {
3036                         Logger::log('like: unknown owner ' . $uid);
3037                         return false;
3038                 }
3039
3040                 // Retrieve the current logged in user's public contact
3041                 $author_id = public_contact();
3042
3043                 $author_contact = DBA::selectFirst('contact', ['url'], ['id' => $author_id]);
3044                 if (!DBA::isResult($author_contact)) {
3045                         Logger::log('like: unknown author ' . $author_id);
3046                         return false;
3047                 }
3048
3049                 // Contact-id is the uid-dependant author contact
3050                 if (local_user() == $uid) {
3051                         $item_contact_id = $owner_self_contact['id'];
3052                         $item_contact = $owner_self_contact;
3053                 } else {
3054                         $item_contact_id = Contact::getIdForURL($author_contact['url'], $uid, true);
3055                         $item_contact = DBA::selectFirst('contact', [], ['id' => $item_contact_id]);
3056                         if (!DBA::isResult($item_contact)) {
3057                                 Logger::log('like: unknown item contact ' . $item_contact_id);
3058                                 return false;
3059                         }
3060                 }
3061
3062                 // Look for an existing verb row
3063                 // event participation are essentially radio toggles. If you make a subsequent choice,
3064                 // we need to eradicate your first choice.
3065                 if ($event_verb_flag) {
3066                         $verbs = [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE];
3067
3068                         // Translate to the index based activity index
3069                         $activities = [];
3070                         foreach ($verbs as $verb) {
3071                                 $activities[] = self::activityToIndex($verb);
3072                         }
3073                 } else {
3074                         $activities = self::activityToIndex($activity);
3075                 }
3076
3077                 $condition = ['activity' => $activities, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY,
3078                         'author-id' => $author_id, 'uid' => $item['uid'], 'thr-parent' => $item_uri];
3079
3080                 $like_item = self::selectFirst(['id', 'guid', 'verb'], $condition);
3081
3082                 // If it exists, mark it as deleted
3083                 if (DBA::isResult($like_item)) {
3084                         self::deleteById($like_item['id']);
3085
3086                         if (!$event_verb_flag || $like_item['verb'] == $activity) {
3087                                 return true;
3088                         }
3089                 }
3090
3091                 // Verb is "un-something", just trying to delete existing entries
3092                 if (strpos($verb, 'un') === 0) {
3093                         return true;
3094                 }
3095
3096                 $objtype = $item['resource-id'] ? ACTIVITY_OBJ_IMAGE : ACTIVITY_OBJ_NOTE;
3097
3098                 $new_item = [
3099                         'guid'          => System::createUUID(),
3100                         'uri'           => self::newURI($item['uid']),
3101                         'uid'           => $item['uid'],
3102                         'contact-id'    => $item_contact_id,
3103                         'wall'          => $item['wall'],
3104                         'origin'        => 1,
3105                         'network'       => Protocol::DFRN,
3106                         'gravity'       => GRAVITY_ACTIVITY,
3107                         'parent'        => $item['id'],
3108                         'parent-uri'    => $item['uri'],
3109                         'thr-parent'    => $item['uri'],
3110                         'owner-id'      => $author_id,
3111                         'author-id'     => $author_id,
3112                         'body'          => $activity,
3113                         'verb'          => $activity,
3114                         'object-type'   => $objtype,
3115                         'allow_cid'     => $item['allow_cid'],
3116                         'allow_gid'     => $item['allow_gid'],
3117                         'deny_cid'      => $item['deny_cid'],
3118                         'deny_gid'      => $item['deny_gid'],
3119                         'visible'       => 1,
3120                         'unseen'        => 1,
3121                 ];
3122
3123                 $signed = Diaspora::createLikeSignature($uid, $new_item);
3124                 if (!empty($signed)) {
3125                         $new_item['diaspora_signed_text'] = json_encode($signed);
3126                 }
3127
3128                 $new_item_id = self::insert($new_item);
3129
3130                 // If the parent item isn't visible then set it to visible
3131                 if (!$item['visible']) {
3132                         self::update(['visible' => true], ['id' => $item['id']]);
3133                 }
3134
3135                 $new_item['id'] = $new_item_id;
3136
3137                 Hook::callAll('post_local_end', $new_item);
3138
3139                 return true;
3140         }
3141
3142         private static function addThread($itemid, $onlyshadow = false)
3143         {
3144                 $fields = ['uid', 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private', 'pubmail',
3145                         'moderated', 'visible', 'starred', 'contact-id', 'post-type',
3146                         'deleted', 'origin', 'forum_mode', 'mention', 'network', 'author-id', 'owner-id'];
3147                 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
3148                 $item = self::selectFirst($fields, $condition);
3149
3150                 if (!DBA::isResult($item)) {
3151                         return;
3152                 }
3153
3154                 $item['iid'] = $itemid;
3155
3156                 if (!$onlyshadow) {
3157                         $result = DBA::insert('thread', $item);
3158
3159                         Logger::log("Add thread for item ".$itemid." - ".print_r($result, true), Logger::DEBUG);
3160                 }
3161         }
3162
3163         private static function updateThread($itemid, $setmention = false)
3164         {
3165                 $fields = ['uid', 'guid', 'created', 'edited', 'commented', 'received', 'changed', 'post-type',
3166                         'wall', 'private', 'pubmail', 'moderated', 'visible', 'starred', 'contact-id',
3167                         'deleted', 'origin', 'forum_mode', 'network', 'author-id', 'owner-id'];
3168                 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
3169
3170                 $item = self::selectFirst($fields, $condition);
3171                 if (!DBA::isResult($item)) {
3172                         return;
3173                 }
3174
3175                 if ($setmention) {
3176                         $item["mention"] = 1;
3177                 }
3178
3179                 $sql = "";
3180
3181                 $fields = [];
3182
3183                 foreach ($item as $field => $data) {
3184                         if (!in_array($field, ["guid"])) {
3185                                 $fields[$field] = $data;
3186                         }
3187                 }
3188
3189                 $result = DBA::update('thread', $fields, ['iid' => $itemid]);
3190
3191                 Logger::log("Update thread for item ".$itemid." - guid ".$item["guid"]." - ".(int)$result, Logger::DEBUG);
3192         }
3193
3194         private static function deleteThread($itemid, $itemuri = "")
3195         {
3196                 $item = DBA::selectFirst('thread', ['uid'], ['iid' => $itemid]);
3197                 if (!DBA::isResult($item)) {
3198                         Logger::log('No thread found for id '.$itemid, Logger::DEBUG);
3199                         return;
3200                 }
3201
3202                 $result = DBA::delete('thread', ['iid' => $itemid], ['cascade' => false]);
3203
3204                 Logger::log("deleteThread: Deleted thread for item ".$itemid." - ".print_r($result, true), Logger::DEBUG);
3205
3206                 if ($itemuri != "") {
3207                         $condition = ["`uri` = ? AND NOT `deleted` AND NOT (`uid` IN (?, 0))", $itemuri, $item["uid"]];
3208                         if (!self::exists($condition)) {
3209                                 DBA::delete('item', ['uri' => $itemuri, 'uid' => 0]);
3210                                 Logger::log("deleteThread: Deleted shadow for item ".$itemuri, Logger::DEBUG);
3211                         }
3212                 }
3213         }
3214
3215         public static function getPermissionsSQLByUserId($owner_id, $remote_verified = false, $groups = null, $remote_cid = null)
3216         {
3217                 $local_user = local_user();
3218                 $remote_user = remote_user();
3219
3220                 /*
3221                  * Construct permissions
3222                  *
3223                  * default permissions - anonymous user
3224                  */
3225                 $sql = " AND NOT `item`.`private`";
3226
3227                 // Profile owner - everything is visible
3228                 if ($local_user && ($local_user == $owner_id)) {
3229                         $sql = '';
3230                 } elseif ($remote_user) {
3231                         /*
3232                          * Authenticated visitor. Unless pre-verified,
3233                          * check that the contact belongs to this $owner_id
3234                          * and load the groups the visitor belongs to.
3235                          * If pre-verified, the caller is expected to have already
3236                          * done this and passed the groups into this function.
3237                          */
3238                         $set = PermissionSet::get($owner_id, $remote_cid, $groups);
3239
3240                         if (!empty($set)) {
3241                                 $sql_set = " OR (`item`.`private` IN (1,2) AND `item`.`wall` AND `item`.`psid` IN (" . implode(',', $set) . "))";
3242                         } else {
3243                                 $sql_set = '';
3244                         }
3245
3246                         $sql = " AND (NOT `item`.`private`" . $sql_set . ")";
3247                 }
3248
3249                 return $sql;
3250         }
3251
3252         /**
3253          * get translated item type
3254          *
3255          * @param $item
3256          * @return string
3257          */
3258         public static function postType($item)
3259         {
3260                 if (!empty($item['event-id'])) {
3261                         return L10n::t('event');
3262                 } elseif (!empty($item['resource-id'])) {
3263                         return L10n::t('photo');
3264                 } elseif (!empty($item['verb']) && $item['verb'] !== ACTIVITY_POST) {
3265                         return L10n::t('activity');
3266                 } elseif ($item['id'] != $item['parent']) {
3267                         return L10n::t('comment');
3268                 }
3269
3270                 return L10n::t('post');
3271         }
3272
3273         /**
3274          * Sets the "rendered-html" field of the provided item
3275          *
3276          * Body is preserved to avoid side-effects as we modify it just-in-time for spoilers and private image links
3277          *
3278          * @param array $item
3279          * @param bool  $update
3280          *
3281          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3282          * @todo Remove reference, simply return "rendered-html" and "rendered-hash"
3283          */
3284         public static function putInCache(&$item, $update = false)
3285         {
3286                 $body = $item["body"];
3287
3288                 $rendered_hash = defaults($item, 'rendered-hash', '');
3289                 $rendered_html = defaults($item, 'rendered-html', '');
3290
3291                 if ($rendered_hash == ''
3292                         || $rendered_html == ""
3293                         || $rendered_hash != hash("md5", $item["body"])
3294                         || Config::get("system", "ignore_cache")
3295                 ) {
3296                         $a = self::getApp();
3297                         redir_private_images($a, $item);
3298
3299                         $item["rendered-html"] = prepare_text($item["body"]);
3300                         $item["rendered-hash"] = hash("md5", $item["body"]);
3301
3302                         $hook_data = ['item' => $item, 'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']];
3303                         Hook::callAll('put_item_in_cache', $hook_data);
3304                         $item['rendered-html'] = $hook_data['rendered-html'];
3305                         $item['rendered-hash'] = $hook_data['rendered-hash'];
3306                         unset($hook_data);
3307
3308                         // Force an update if the generated values differ from the existing ones
3309                         if ($rendered_hash != $item["rendered-hash"]) {
3310                                 $update = true;
3311                         }
3312
3313                         // Only compare the HTML when we forcefully ignore the cache
3314                         if (Config::get("system", "ignore_cache") && ($rendered_html != $item["rendered-html"])) {
3315                                 $update = true;
3316                         }
3317
3318                         if ($update && !empty($item["id"])) {
3319                                 self::update(
3320                                         [
3321                                                 'rendered-html' => $item["rendered-html"],
3322                                                 'rendered-hash' => $item["rendered-hash"]
3323                                         ],
3324                                         ['id' => $item["id"]]
3325                                 );
3326                         }
3327                 }
3328
3329                 $item["body"] = $body;
3330         }
3331
3332         /**
3333          * @brief Given an item array, convert the body element from bbcode to html and add smilie icons.
3334          * If attach is true, also add icons for item attachments.
3335          *
3336          * @param array   $item
3337          * @param boolean $attach
3338          * @param boolean $is_preview
3339          * @return string item body html
3340          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3341          * @throws \ImagickException
3342          * @hook  prepare_body_init item array before any work
3343          * @hook  prepare_body_content_filter ('item'=>item array, 'filter_reasons'=>string array) before first bbcode to html
3344          * @hook  prepare_body ('item'=>item array, 'html'=>body string, 'is_preview'=>boolean, 'filter_reasons'=>string array) after first bbcode to html
3345          * @hook  prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
3346          */
3347         public static function prepareBody(array &$item, $attach = false, $is_preview = false)
3348         {
3349                 $a = self::getApp();
3350                 Hook::callAll('prepare_body_init', $item);
3351
3352                 // In order to provide theme developers more possibilities, event items
3353                 // are treated differently.
3354                 if ($item['object-type'] === ACTIVITY_OBJ_EVENT && isset($item['event-id'])) {
3355                         $ev = Event::getItemHTML($item);
3356                         return $ev;
3357                 }
3358
3359                 $tags = Term::populateTagsFromItem($item);
3360
3361                 $item['tags'] = $tags['tags'];
3362                 $item['hashtags'] = $tags['hashtags'];
3363                 $item['mentions'] = $tags['mentions'];
3364
3365                 // Compile eventual content filter reasons
3366                 $filter_reasons = [];
3367                 if (!$is_preview && public_contact() != $item['author-id']) {
3368                         if (!empty($item['content-warning']) && (!local_user() || !PConfig::get(local_user(), 'system', 'disable_cw', false))) {
3369                                 $filter_reasons[] = L10n::t('Content warning: %s', $item['content-warning']);
3370                         }
3371
3372                         $hook_data = [
3373                                 'item' => $item,
3374                                 'filter_reasons' => $filter_reasons
3375                         ];
3376                         Hook::callAll('prepare_body_content_filter', $hook_data);
3377                         $filter_reasons = $hook_data['filter_reasons'];
3378                         unset($hook_data);
3379                 }
3380
3381                 // Update the cached values if there is no "zrl=..." on the links.
3382                 $update = (!local_user() && !remote_user() && ($item["uid"] == 0));
3383
3384                 // Or update it if the current viewer is the intented viewer.
3385                 if (($item["uid"] == local_user()) && ($item["uid"] != 0)) {
3386                         $update = true;
3387                 }
3388
3389                 self::putInCache($item, $update);
3390                 $s = $item["rendered-html"];
3391
3392                 $hook_data = [
3393                         'item' => $item,
3394                         'html' => $s,
3395                         'preview' => $is_preview,
3396                         'filter_reasons' => $filter_reasons
3397                 ];
3398                 Hook::callAll('prepare_body', $hook_data);
3399                 $s = $hook_data['html'];
3400                 unset($hook_data);
3401
3402                 if (!$attach) {
3403                         // Replace the blockquotes with quotes that are used in mails.
3404                         $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
3405                         $s = str_replace(['<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'], [$mailquote, $mailquote, $mailquote], $s);
3406                         return $s;
3407                 }
3408
3409                 $as = '';
3410                 $vhead = false;
3411                 $matches = [];
3412                 preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\"(?: title=\"(.*?)\")?|', $item['attach'], $matches, PREG_SET_ORDER);
3413                 foreach ($matches as $mtch) {
3414                         $mime = $mtch[3];
3415
3416                         $the_url = Contact::magicLinkById($item['author-id'], $mtch[1]);
3417
3418                         if (strpos($mime, 'video') !== false) {
3419                                 if (!$vhead) {
3420                                         $vhead = true;
3421                                         $a->page['htmlhead'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate('videos_head.tpl'), [
3422                                                 '$baseurl' => System::baseUrl(),
3423                                         ]);
3424                                 }
3425
3426                                 $url_parts = explode('/', $the_url);
3427                                 $id = end($url_parts);
3428                                 $as .= Renderer::replaceMacros(Renderer::getMarkupTemplate('video_top.tpl'), [
3429                                         '$video' => [
3430                                                 'id'     => $id,
3431                                                 'title'  => L10n::t('View Video'),
3432                                                 'src'    => $the_url,
3433                                                 'mime'   => $mime,
3434                                         ],
3435                                 ]);
3436                         }
3437
3438                         $filetype = strtolower(substr($mime, 0, strpos($mime, '/')));
3439                         if ($filetype) {
3440                                 $filesubtype = strtolower(substr($mime, strpos($mime, '/') + 1));
3441                                 $filesubtype = str_replace('.', '-', $filesubtype);
3442                         } else {
3443                                 $filetype = 'unkn';
3444                                 $filesubtype = 'unkn';
3445                         }
3446
3447                         $title = Strings::escapeHtml(trim(defaults($mtch, 4, $mtch[1])));
3448                         $title .= ' ' . $mtch[2] . ' ' . L10n::t('bytes');
3449
3450                         $icon = '<div class="attachtype icon s22 type-' . $filetype . ' subtype-' . $filesubtype . '"></div>';
3451                         $as .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" >' . $icon . '</a>';
3452                 }
3453
3454                 if ($as != '') {
3455                         $s .= '<div class="body-attach">'.$as.'<div class="clear"></div></div>';
3456                 }
3457
3458                 // Map.
3459                 if (strpos($s, '<div class="map">') !== false && !empty($item['coord'])) {
3460                         $x = Map::byCoordinates(trim($item['coord']));
3461                         if ($x) {
3462                                 $s = preg_replace('/\<div class\=\"map\"\>/', '$0' . $x, $s);
3463                         }
3464                 }
3465
3466
3467                 // Look for spoiler.
3468                 $spoilersearch = '<blockquote class="spoiler">';
3469
3470                 // Remove line breaks before the spoiler.
3471                 while ((strpos($s, "\n" . $spoilersearch) !== false)) {
3472                         $s = str_replace("\n" . $spoilersearch, $spoilersearch, $s);
3473                 }
3474                 while ((strpos($s, "<br />" . $spoilersearch) !== false)) {
3475                         $s = str_replace("<br />" . $spoilersearch, $spoilersearch, $s);
3476                 }
3477
3478                 while ((strpos($s, $spoilersearch) !== false)) {
3479                         $pos = strpos($s, $spoilersearch);
3480                         $rnd = Strings::getRandomHex(8);
3481                         $spoilerreplace = '<br /> <span id="spoiler-wrap-' . $rnd . '" class="spoiler-wrap fakelink" onclick="openClose(\'spoiler-' . $rnd . '\');">' . L10n::t('Click to open/close') . '</span>'.
3482                                                 '<blockquote class="spoiler" id="spoiler-' . $rnd . '" style="display: none;">';
3483                         $s = substr($s, 0, $pos) . $spoilerreplace . substr($s, $pos + strlen($spoilersearch));
3484                 }
3485
3486                 // Look for quote with author.
3487                 $authorsearch = '<blockquote class="author">';
3488
3489                 while ((strpos($s, $authorsearch) !== false)) {
3490                         $pos = strpos($s, $authorsearch);
3491                         $rnd = Strings::getRandomHex(8);
3492                         $authorreplace = '<br /> <span id="author-wrap-' . $rnd . '" class="author-wrap fakelink" onclick="openClose(\'author-' . $rnd . '\');">' . L10n::t('Click to open/close') . '</span>'.
3493                                                 '<blockquote class="author" id="author-' . $rnd . '" style="display: block;">';
3494                         $s = substr($s, 0, $pos) . $authorreplace . substr($s, $pos + strlen($authorsearch));
3495                 }
3496
3497                 // Replace friendica image url size with theme preference.
3498                 if (!empty($a->theme_info['item_image_size'])) {
3499                         $ps = $a->theme_info['item_image_size'];
3500                         $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
3501                 }
3502
3503                 $s = HTML::applyContentFilter($s, $filter_reasons);
3504
3505                 $hook_data = ['item' => $item, 'html' => $s];
3506                 Hook::callAll('prepare_body_final', $hook_data);
3507
3508                 return $hook_data['html'];
3509         }
3510
3511         /**
3512          * get private link for item
3513          *
3514          * @param array $item
3515          * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
3516          * @throws \Exception
3517          */
3518         public static function getPlink($item)
3519         {
3520                 $a = self::getApp();
3521
3522                 if ($a->user['nickname'] != "") {
3523                         $ret = [
3524                                 'href' => "display/" . $item['guid'],
3525                                 'orig' => "display/" . $item['guid'],
3526                                 'title' => L10n::t('View on separate page'),
3527                                 'orig_title' => L10n::t('view on separate page'),
3528                         ];
3529
3530                         if (!empty($item['plink'])) {
3531                                 $ret["href"] = $a->removeBaseURL($item['plink']);
3532                                 $ret["title"] = L10n::t('link to source');
3533                         }
3534
3535                 } elseif (!empty($item['plink']) && ($item['private'] != 1)) {
3536                         $ret = [
3537                                 'href' => $item['plink'],
3538                                 'orig' => $item['plink'],
3539                                 'title' => L10n::t('link to source'),
3540                         ];
3541                 } else {
3542                         $ret = [];
3543                 }
3544
3545                 return $ret;
3546         }
3547 }