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