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