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