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