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