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