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