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