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