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