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