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