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