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