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