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