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