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