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