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