]> git.mxchange.org Git - friendica.git/blob - src/Model/Item.php
New class function to fetch items
[friendica.git] / src / Model / Item.php
1 <?php
2
3 /**
4  * @file src/Model/Item.php
5  */
6
7 namespace Friendica\Model;
8
9 use Friendica\BaseObject;
10 use Friendica\Content\Text;
11 use Friendica\Core\Addon;
12 use Friendica\Core\Config;
13 use Friendica\Core\L10n;
14 use Friendica\Core\PConfig;
15 use Friendica\Core\System;
16 use Friendica\Core\Worker;
17 use Friendica\Database\DBM;
18 use Friendica\Model\Contact;
19 use Friendica\Model\Conversation;
20 use Friendica\Model\Group;
21 use Friendica\Model\Term;
22 use Friendica\Object\Image;
23 use Friendica\Protocol\Diaspora;
24 use Friendica\Protocol\OStatus;
25 use Friendica\Util\DateTimeFormat;
26 use Friendica\Util\XML;
27 use dba;
28 use Text_LanguageDetect;
29
30 require_once 'boot.php';
31 require_once 'include/items.php';
32 require_once 'include/text.php';
33
34 class Item extends BaseObject
35 {
36         public static function select(array $fields = [], array $condition = [], $params = [], $uid = null)
37         {
38                 require_once 'include/conversation.php';
39
40                 $item_fields = ['id', 'guid'];
41
42                 $select_fields = item_fieldlists();
43
44                 $condition_string = dba::buildCondition($condition);
45
46                 foreach ($item_fields as $field) {
47                         $search = [" `" . $field . "`", "(`" . $field . "`"];
48                         $replace = [" `item`.`" . $field . "`", "(`item`.`" . $field . "`"];
49                         $condition_string = str_replace($search, $replace, $condition_string);
50                 }
51
52                 $condition_string = $condition_string . ' AND ' . item_condition();
53
54                 if (!empty($uid)) {
55                         $condition_string .= " AND `item`.`uid` = ?";
56                         $condition['uid'] = $uid;
57                 }
58
59                 $param_string = dba::buildParameter($params);
60
61                 $table = "`item` " . item_joins($uid);
62
63                 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
64 echo $sql;
65                 $result = dba::p($sql, $condition);
66
67                 return dba::inArray($result);
68         }
69
70         /**
71          * @brief Update existing item entries
72          *
73          * @param array $fields The fields that are to be changed
74          * @param array $condition The condition for finding the item entries
75          *
76          * In the future we may have to change permissions as well.
77          * Then we had to add the user id as third parameter.
78          *
79          * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
80          *
81          * @return integer|boolean number of affected rows - or "false" if there was an error
82          */
83         public static function update(array $fields, array $condition)
84         {
85                 if (empty($condition) || empty($fields)) {
86                         return false;
87                 }
88
89                 // To ensure the data integrity we do it in an transaction
90                 dba::transaction();
91
92                 // We cannot simply expand the condition to check for origin entries
93                 // The condition needn't to be a simple array but could be a complex condition.
94                 // And we have to execute this query before the update to ensure to fetch the same data.
95                 $items = dba::select('item', ['id', 'origin'], $condition);
96
97                 $success = dba::update('item', $fields, $condition);
98
99                 if (!$success) {
100                         dba::close($items);
101                         dba::rollback();
102                         return false;
103                 }
104
105                 $rows = dba::affected_rows();
106
107                 while ($item = dba::fetch($items)) {
108                         Term::insertFromTagFieldByItemId($item['id']);
109                         Term::insertFromFileFieldByItemId($item['id']);
110                         self::updateThread($item['id']);
111
112                         // We only need to notfiy others when it is an original entry from us.
113                         // Only call the notifier when the item has some content relevant change.
114                         if ($item['origin'] && in_array('edited', array_keys($fields))) {
115                                 Worker::add(PRIORITY_HIGH, "Notifier", 'edit_post', $item['id']);
116                         }
117                 }
118
119                 dba::close($items);
120                 dba::commit();
121                 return $rows;
122         }
123
124         /**
125          * @brief Delete an item and notify others about it - if it was ours
126          *
127          * @param array $condition The condition for finding the item entries
128          * @param integer $priority Priority for the notification
129          */
130         public static function delete($condition, $priority = PRIORITY_HIGH)
131         {
132                 $items = dba::select('item', ['id'], $condition);
133                 while ($item = dba::fetch($items)) {
134                         self::deleteById($item['id'], $priority);
135                 }
136                 dba::close($items);
137         }
138
139         /**
140          * @brief Delete an item for an user and notify others about it - if it was ours
141          *
142          * @param array $condition The condition for finding the item entries
143          * @param integer $uid User who wants to delete this item
144          */
145         public static function deleteForUser($condition, $uid)
146         {
147                 if ($uid == 0) {
148                         return;
149                 }
150
151                 $items = dba::select('item', ['id', 'uid'], $condition);
152                 while ($item = dba::fetch($items)) {
153                         // "Deleting" global items just means hiding them
154                         if ($item['uid'] == 0) {
155                                 dba::update('user-item', ['hidden' => true], ['iid' => $item['id'], 'uid' => $uid], true);
156                         } elseif ($item['uid'] == $uid) {
157                                 self::deleteById($item['id'], PRIORITY_HIGH);
158                         } else {
159                                 logger('Wrong ownership. Not deleting item ' . $item['id']);
160                         }
161                 }
162                 dba::close($items);
163         }
164
165         /**
166          * @brief Delete an item and notify others about it - if it was ours
167          *
168          * @param integer $item_id Item ID that should be delete
169          * @param integer $priority Priority for the notification
170          *
171          * @return boolean success
172          */
173         private static function deleteById($item_id, $priority = PRIORITY_HIGH)
174         {
175                 // locate item to be deleted
176                 $fields = ['id', 'uri', 'uid', 'parent', 'parent-uri', 'origin',
177                         'deleted', 'file', 'resource-id', 'event-id', 'attach',
178                         'verb', 'object-type', 'object', 'target', 'contact-id'];
179                 $item = dba::selectFirst('item', $fields, ['id' => $item_id]);
180                 if (!DBM::is_result($item)) {
181                         logger('Item with ID ' . $item_id . " hasn't been found.", LOGGER_DEBUG);
182                         return false;
183                 }
184
185                 if ($item['deleted']) {
186                         logger('Item with ID ' . $item_id . ' has already been deleted.', LOGGER_DEBUG);
187                         return false;
188                 }
189
190                 $parent = dba::selectFirst('item', ['origin'], ['id' => $item['parent']]);
191                 if (!DBM::is_result($parent)) {
192                         $parent = ['origin' => false];
193                 }
194
195                 // clean up categories and tags so they don't end up as orphans
196
197                 $matches = false;
198                 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
199                 if ($cnt) {
200                         foreach ($matches as $mtch) {
201                                 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],true);
202                         }
203                 }
204
205                 $matches = false;
206
207                 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
208                 if ($cnt) {
209                         foreach ($matches as $mtch) {
210                                 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],false);
211                         }
212                 }
213
214                 /*
215                  * If item is a link to a photo resource, nuke all the associated photos
216                  * (visitors will not have photo resources)
217                  * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
218                  * generate a resource-id and therefore aren't intimately linked to the item.
219                  */
220                 if (strlen($item['resource-id'])) {
221                         dba::delete('photo', ['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
222                 }
223
224                 // If item is a link to an event, delete the event.
225                 if (intval($item['event-id'])) {
226                         Event::delete($item['event-id']);
227                 }
228
229                 // If item has attachments, drop them
230                 foreach (explode(", ", $item['attach']) as $attach) {
231                         preg_match("|attach/(\d+)|", $attach, $matches);
232                         dba::delete('attach', ['id' => $matches[1], 'uid' => $item['uid']]);
233                 }
234
235                 // Delete tags that had been attached to other items
236                 self::deleteTagsFromItem($item);
237
238                 // Set the item to "deleted"
239                 dba::update('item', ['deleted' => true, 'title' => '', 'body' => '',
240                                         'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()],
241                                 ['id' => $item['id']]);
242
243                 Term::insertFromTagFieldByItemId($item['id']);
244                 Term::insertFromFileFieldByItemId($item['id']);
245                 self::deleteThread($item['id'], $item['parent-uri']);
246
247                 if (!dba::exists('item', ["`uri` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri']])) {
248                         self::delete(['uri' => $item['uri'], 'uid' => 0, 'deleted' => false], $priority);
249                 }
250
251                 // If it's the parent of a comment thread, kill all the kids
252                 if ($item['id'] == $item['parent']) {
253                         self::delete(['parent' => $item['parent'], 'deleted' => false], $priority);
254                 }
255
256                 // Is it our comment and/or our thread?
257                 if ($item['origin'] || $parent['origin']) {
258
259                         // When we delete the original post we will delete all existing copies on the server as well
260                         self::delete(['uri' => $item['uri'], 'deleted' => false], $priority);
261
262                         // send the notification upstream/downstream
263                         Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", "drop", intval($item['id']));
264                 } elseif ($item['uid'] != 0) {
265
266                         // When we delete just our local user copy of an item, we have to set a marker to hide it
267                         $global_item = dba::selectFirst('item', ['id'], ['uri' => $item['uri'], 'uid' => 0, 'deleted' => false]);
268                         if (DBM::is_result($global_item)) {
269                                 dba::update('user-item', ['hidden' => true], ['iid' => $global_item['id'], 'uid' => $item['uid']], true);
270                         }
271                 }
272
273                 logger('Item with ID ' . $item_id . " has been deleted.", LOGGER_DEBUG);
274
275                 return true;
276         }
277
278         private static function deleteTagsFromItem($item)
279         {
280                 if (($item["verb"] != ACTIVITY_TAG) || ($item["object-type"] != ACTIVITY_OBJ_TAGTERM)) {
281                         return;
282                 }
283
284                 $xo = XML::parseString($item["object"], false);
285                 $xt = XML::parseString($item["target"], false);
286
287                 if ($xt->type != ACTIVITY_OBJ_NOTE) {
288                         return;
289                 }
290
291                 $i = dba::selectFirst('item', ['id', 'contact-id', 'tag'], ['uri' => $xt->id, 'uid' => $item['uid']]);
292                 if (!DBM::is_result($i)) {
293                         return;
294                 }
295
296                 // For tags, the owner cannot remove the tag on the author's copy of the post.
297                 $owner_remove = ($item["contact-id"] == $i["contact-id"]);
298                 $author_copy = $item["origin"];
299
300                 if (($owner_remove && $author_copy) || !$owner_remove) {
301                         return;
302                 }
303
304                 $tags = explode(',', $i["tag"]);
305                 $newtags = [];
306                 if (count($tags)) {
307                         foreach ($tags as $tag) {
308                                 if (trim($tag) !== trim($xo->body)) {
309                                        $newtags[] = trim($tag);
310                                 }
311                         }
312                 }
313                 self::update(['tag' => implode(',', $newtags)], ['id' => $i["id"]]);
314         }
315
316         private static function guid($item, $notify)
317         {
318                 $guid = notags(trim($item['guid']));
319
320                 if (!empty($guid)) {
321                         return $guid;
322                 }
323
324                 if ($notify) {
325                         // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
326                         // We add the hash of our own host because our host is the original creator of the post.
327                         $prefix_host = get_app()->get_hostname();
328                 } else {
329                         $prefix_host = '';
330
331                         // We are only storing the post so we create a GUID from the original hostname.
332                         if (!empty($item['author-link'])) {
333                                 $parsed = parse_url($item['author-link']);
334                                 if (!empty($parsed['host'])) {
335                                         $prefix_host = $parsed['host'];
336                                 }
337                         }
338
339                         if (empty($prefix_host) && !empty($item['plink'])) {
340                                 $parsed = parse_url($item['plink']);
341                                 if (!empty($parsed['host'])) {
342                                         $prefix_host = $parsed['host'];
343                                 }
344                         }
345
346                         if (empty($prefix_host) && !empty($item['uri'])) {
347                                 $parsed = parse_url($item['uri']);
348                                 if (!empty($parsed['host'])) {
349                                         $prefix_host = $parsed['host'];
350                                 }
351                         }
352
353                         // Is it in the format data@host.tld? - Used for mail contacts
354                         if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
355                                 $mailparts = explode('@', $item['author-link']);
356                                 $prefix_host = array_pop($mailparts);
357                         }
358                 }
359
360                 if (!empty($item['plink'])) {
361                         $guid = self::guidFromUri($item['plink'], $prefix_host);
362                 } elseif (!empty($item['uri'])) {
363                         $guid = self::guidFromUri($item['uri'], $prefix_host);
364                 } else {
365                         $guid = get_guid(32, hash('crc32', $prefix_host));
366                 }
367
368                 return $guid;
369         }
370
371         private static function contactId($item)
372         {
373                 $contact_id = (int)$item["contact-id"];
374
375                 if (!empty($contact_id)) {
376                         return $contact_id;
377                 }
378                 logger('Missing contact-id. Called by: '.System::callstack(), LOGGER_DEBUG);
379                 /*
380                  * First we are looking for a suitable contact that matches with the author of the post
381                  * This is done only for comments
382                  */
383                 if ($item['parent-uri'] != $item['uri']) {
384                         $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
385                 }
386
387                 // If not present then maybe the owner was found
388                 if ($contact_id == 0) {
389                         $contact_id = Contact::getIdForURL($item['owner-link'], $item['uid']);
390                 }
391
392                 // Still missing? Then use the "self" contact of the current user
393                 if ($contact_id == 0) {
394                         $self = dba::selectFirst('contact', ['id'], ['self' => true, 'uid' => $item['uid']]);
395                         if (DBM::is_result($self)) {
396                                 $contact_id = $self["id"];
397                         }
398                 }
399                 logger("Contact-id was missing for post ".$item['guid']." from user id ".$item['uid']." - now set to ".$contact_id, LOGGER_DEBUG);
400
401                 return $contact_id;
402         }
403
404         public static function insert($item, $force_parent = false, $notify = false, $dontcache = false)
405         {
406                 $a = get_app();
407
408                 // If it is a posting where users should get notifications, then define it as wall posting
409                 if ($notify) {
410                         $item['wall'] = 1;
411                         $item['type'] = 'wall';
412                         $item['origin'] = 1;
413                         $item['network'] = NETWORK_DFRN;
414                         $item['protocol'] = PROTOCOL_DFRN;
415
416                         if (is_int($notify)) {
417                                 $priority = $notify;
418                         } else {
419                                 $priority = PRIORITY_HIGH;
420                         }
421                 } else {
422                         $item['network'] = trim(defaults($item, 'network', NETWORK_PHANTOM));
423                 }
424
425                 $item['guid'] = self::guid($item, $notify);
426                 $item['uri'] = notags(trim(defaults($item, 'uri', item_new_uri($a->get_hostname(), $item['uid'], $item['guid']))));
427
428                 // Store conversation data
429                 $item = Conversation::insert($item);
430
431                 /*
432                  * If a Diaspora signature structure was passed in, pull it out of the
433                  * item array and set it aside for later storage.
434                  */
435
436                 $dsprsig = null;
437                 if (x($item, 'dsprsig')) {
438                         $encoded_signature = $item['dsprsig'];
439                         $dsprsig = json_decode(base64_decode($item['dsprsig']));
440                         unset($item['dsprsig']);
441                 }
442
443                 if (!empty($item['diaspora_signed_text'])) {
444                         $diaspora_signed_text = $item['diaspora_signed_text'];
445                         unset($item['diaspora_signed_text']);
446                 } else {
447                         $diaspora_signed_text = '';
448                 }
449
450                 // Converting the plink
451                 /// @TODO Check if this is really still needed
452                 if ($item['network'] == NETWORK_OSTATUS) {
453                         if (isset($item['plink'])) {
454                                 $item['plink'] = OStatus::convertHref($item['plink']);
455                         } elseif (isset($item['uri'])) {
456                                 $item['plink'] = OStatus::convertHref($item['uri']);
457                         }
458                 }
459
460                 if (!empty($item['thr-parent'])) {
461                         $item['parent-uri'] = $item['thr-parent'];
462                 }
463
464                 if (x($item, 'gravity')) {
465                         $item['gravity'] = intval($item['gravity']);
466                 } elseif ($item['parent-uri'] === $item['uri']) {
467                         $item['gravity'] = 0;
468                 } elseif (activity_match($item['verb'],ACTIVITY_POST)) {
469                         $item['gravity'] = 6;
470                 } else {
471                         $item['gravity'] = 6;   // extensible catchall
472                 }
473
474                 $item['type'] = defaults($item, 'type', 'remote');
475
476                 $uid = intval($item['uid']);
477
478                 // check for create date and expire time
479                 $expire_interval = Config::get('system', 'dbclean-expire-days', 0);
480
481                 $user = dba::selectFirst('user', ['expire'], ['uid' => $uid]);
482                 if (DBM::is_result($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
483                         $expire_interval = $user['expire'];
484                 }
485
486                 if (($expire_interval > 0) && !empty($item['created'])) {
487                         $expire_date = time() - ($expire_interval * 86400);
488                         $created_date = strtotime($item['created']);
489                         if ($created_date < $expire_date) {
490                                 logger('item-store: item created ('.date('c', $created_date).') before expiration time ('.date('c', $expire_date).'). ignored. ' . print_r($item,true), LOGGER_DEBUG);
491                                 return 0;
492                         }
493                 }
494
495                 /*
496                  * Do we already have this item?
497                  * We have to check several networks since Friendica posts could be repeated
498                  * via OStatus (maybe Diasporsa as well)
499                  */
500                 if (in_array($item['network'], [NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS, ""])) {
501                         $condition = ["`uri` = ? AND `uid` = ? AND `network` IN (?, ?, ?)",
502                                 trim($item['uri']), $item['uid'],
503                                 NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS];
504                         $existing = dba::selectFirst('item', ['id', 'network'], $condition);
505                         if (DBM::is_result($existing)) {
506                                 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
507                                 if ($uid != 0) {
508                                         logger("Item with uri ".$item['uri']." already existed for user ".$uid." with id ".$existing["id"]." target network ".$existing["network"]." - new network: ".$item['network']);
509                                 }
510
511                                 return $existing["id"];
512                         }
513                 }
514
515                 self::addLanguageInPostopts($item);
516
517                 $item['wall']          = intval(defaults($item, 'wall', 0));
518                 $item['extid']         = trim(defaults($item, 'extid', ''));
519                 $item['author-name']   = trim(defaults($item, 'author-name', ''));
520                 $item['author-link']   = trim(defaults($item, 'author-link', ''));
521                 $item['author-avatar'] = trim(defaults($item, 'author-avatar', ''));
522                 $item['owner-name']    = trim(defaults($item, 'owner-name', ''));
523                 $item['owner-link']    = trim(defaults($item, 'owner-link', ''));
524                 $item['owner-avatar']  = trim(defaults($item, 'owner-avatar', ''));
525                 $item['received']      = ((x($item, 'received') !== false) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
526                 $item['created']       = ((x($item, 'created') !== false) ? DateTimeFormat::utc($item['created']) : $item['received']);
527                 $item['edited']        = ((x($item, 'edited') !== false) ? DateTimeFormat::utc($item['edited']) : $item['created']);
528                 $item['changed']       = ((x($item, 'changed') !== false) ? DateTimeFormat::utc($item['changed']) : $item['created']);
529                 $item['commented']     = ((x($item, 'commented') !== false) ? DateTimeFormat::utc($item['commented']) : $item['created']);
530                 $item['title']         = trim(defaults($item, 'title', ''));
531                 $item['location']      = trim(defaults($item, 'location', ''));
532                 $item['coord']         = trim(defaults($item, 'coord', ''));
533                 $item['visible']       = ((x($item, 'visible') !== false) ? intval($item['visible'])         : 1);
534                 $item['deleted']       = 0;
535                 $item['parent-uri']    = trim(defaults($item, 'parent-uri', $item['uri']));
536                 $item['verb']          = trim(defaults($item, 'verb', ''));
537                 $item['object-type']   = trim(defaults($item, 'object-type', ''));
538                 $item['object']        = trim(defaults($item, 'object', ''));
539                 $item['target-type']   = trim(defaults($item, 'target-type', ''));
540                 $item['target']        = trim(defaults($item, 'target', ''));
541                 $item['plink']         = trim(defaults($item, 'plink', ''));
542                 $item['allow_cid']     = trim(defaults($item, 'allow_cid', ''));
543                 $item['allow_gid']     = trim(defaults($item, 'allow_gid', ''));
544                 $item['deny_cid']      = trim(defaults($item, 'deny_cid', ''));
545                 $item['deny_gid']      = trim(defaults($item, 'deny_gid', ''));
546                 $item['private']       = intval(defaults($item, 'private', 0));
547                 $item['bookmark']      = intval(defaults($item, 'bookmark', 0));
548                 $item['body']          = trim(defaults($item, 'body', ''));
549                 $item['tag']           = trim(defaults($item, 'tag', ''));
550                 $item['attach']        = trim(defaults($item, 'attach', ''));
551                 $item['app']           = trim(defaults($item, 'app', ''));
552                 $item['origin']        = intval(defaults($item, 'origin', 0));
553                 $item['postopts']      = trim(defaults($item, 'postopts', ''));
554                 $item['resource-id']   = trim(defaults($item, 'resource-id', ''));
555                 $item['event-id']      = intval(defaults($item, 'event-id', 0));
556                 $item['inform']        = trim(defaults($item, 'inform', ''));
557                 $item['file']          = trim(defaults($item, 'file', ''));
558
559                 // When there is no content then we don't post it
560                 if ($item['body'].$item['title'] == '') {
561                         return 0;
562                 }
563
564                 // Items cannot be stored before they happen ...
565                 if ($item['created'] > DateTimeFormat::utcNow()) {
566                         $item['created'] = DateTimeFormat::utcNow();
567                 }
568
569                 // We haven't invented time travel by now.
570                 if ($item['edited'] > DateTimeFormat::utcNow()) {
571                         $item['edited'] = DateTimeFormat::utcNow();
572                 }
573
574                 if (($item['author-link'] == "") && ($item['owner-link'] == "")) {
575                         logger("Both author-link and owner-link are empty. Called by: " . System::callstack(), LOGGER_DEBUG);
576                 }
577
578                 $item['plink'] = defaults($item, 'plink', System::baseUrl() . '/display/' . urlencode($item['guid']));
579
580                 // The contact-id should be set before "self::insert" was called - but there seems to be issues sometimes
581                 $item["contact-id"] = self::contactId($item);
582
583                 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
584                         'photo' => $item['author-avatar'], 'network' => $item['network']];
585
586                 $item['author-id'] = defaults($item, 'author-id', Contact::getIdForURL($item["author-link"], 0, false, $default));
587
588                 if (Contact::isBlocked($item["author-id"])) {
589                         logger('Contact '.$item["author-id"].' is blocked, item '.$item["uri"].' will not be stored');
590                         return 0;
591                 }
592
593                 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
594                         'photo' => $item['owner-avatar'], 'network' => $item['network']];
595
596                 $item['owner-id'] = defaults($item, 'owner-id', Contact::getIdForURL($item["owner-link"], 0, false, $default));
597
598                 if (Contact::isBlocked($item["owner-id"])) {
599                         logger('Contact '.$item["owner-id"].' is blocked, item '.$item["uri"].' will not be stored');
600                         return 0;
601                 }
602
603                 //unset($item['author-link']);
604                 //unset($item['author-name']);
605                 //unset($item['author-avatar']);
606
607                 //unset($item['owner-link']);
608                 unset($item['owner-name']);
609                 unset($item['owner-avatar']);
610
611                 if ($item['network'] == NETWORK_PHANTOM) {
612                         logger('Missing network. Called by: '.System::callstack(), LOGGER_DEBUG);
613
614                         $contact = Contact::getDetailsByURL($item['author-link'], $item['uid']);
615                         if (!empty($contact['network'])) {
616                                 $item['network'] = $contact["network"];
617                         } else {
618                                 $item['network'] = NETWORK_DFRN;
619                         }
620                         logger("Set network to " . $item["network"] . " for " . $item["uri"], LOGGER_DEBUG);
621                 }
622
623                 // Checking if there is already an item with the same guid
624                 logger('Checking for an item for user '.$item['uid'].' on network '.$item['network'].' with the guid '.$item['guid'], LOGGER_DEBUG);
625                 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
626                 if (dba::exists('item', $condition)) {
627                         logger('found item with guid '.$item['guid'].' for user '.$item['uid'].' on network '.$item['network'], LOGGER_DEBUG);
628                         return 0;
629                 }
630
631                 // Check for hashtags in the body and repair or add hashtag links
632                 self::setHashtags($item);
633
634                 $item['thr-parent'] = $item['parent-uri'];
635
636                 $notify_type = '';
637                 $allow_cid = '';
638                 $allow_gid = '';
639                 $deny_cid  = '';
640                 $deny_gid  = '';
641
642                 if ($item['parent-uri'] === $item['uri']) {
643                         $parent_id = 0;
644                         $parent_deleted = 0;
645                         $allow_cid = $item['allow_cid'];
646                         $allow_gid = $item['allow_gid'];
647                         $deny_cid  = $item['deny_cid'];
648                         $deny_gid  = $item['deny_gid'];
649                         $notify_type = 'wall-new';
650                 } else {
651                         // find the parent and snarf the item id and ACLs
652                         // and anything else we need to inherit
653
654                         $fields = ['uri', 'parent-uri', 'id', 'deleted',
655                                 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
656                                 'wall', 'private', 'forum_mode', 'origin'];
657                         $condition = ['uri' => $item['parent-uri'], 'uid' => $item['uid']];
658                         $params = ['order' => ['id' => false]];
659                         $parent = dba::selectFirst('item', $fields, $condition, $params);
660
661                         if (DBM::is_result($parent)) {
662                                 // is the new message multi-level threaded?
663                                 // even though we don't support it now, preserve the info
664                                 // and re-attach to the conversation parent.
665
666                                 if ($parent['uri'] != $parent['parent-uri']) {
667                                         $item['parent-uri'] = $parent['parent-uri'];
668
669                                         $condition = ['uri' => $item['parent-uri'],
670                                                 'parent-uri' => $item['parent-uri'],
671                                                 'uid' => $item['uid']];
672                                         $params = ['order' => ['id' => false]];
673                                         $toplevel_parent = dba::selectFirst('item', $fields, $condition, $params);
674
675                                         if (DBM::is_result($toplevel_parent)) {
676                                                 $parent = $toplevel_parent;
677                                         }
678                                 }
679
680                                 $parent_id      = $parent['id'];
681                                 $parent_deleted = $parent['deleted'];
682                                 $allow_cid      = $parent['allow_cid'];
683                                 $allow_gid      = $parent['allow_gid'];
684                                 $deny_cid       = $parent['deny_cid'];
685                                 $deny_gid       = $parent['deny_gid'];
686                                 $item['wall']    = $parent['wall'];
687                                 $notify_type    = 'comment-new';
688
689                                 /*
690                                  * If the parent is private, force privacy for the entire conversation
691                                  * This differs from the above settings as it subtly allows comments from
692                                  * email correspondents to be private even if the overall thread is not.
693                                  */
694                                 if ($parent['private']) {
695                                         $item['private'] = $parent['private'];
696                                 }
697
698                                 /*
699                                  * Edge case. We host a public forum that was originally posted to privately.
700                                  * The original author commented, but as this is a comment, the permissions
701                                  * weren't fixed up so it will still show the comment as private unless we fix it here.
702                                  */
703                                 if ((intval($parent['forum_mode']) == 1) && $parent['private']) {
704                                         $item['private'] = 0;
705                                 }
706
707                                 // If its a post from myself then tag the thread as "mention"
708                                 logger("Checking if parent ".$parent_id." has to be tagged as mention for user ".$item['uid'], LOGGER_DEBUG);
709                                 $user = dba::selectFirst('user', ['nickname'], ['uid' => $item['uid']]);
710                                 if (DBM::is_result($user)) {
711                                         $self = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
712                                         logger("'myself' is ".$self." for parent ".$parent_id." checking against ".$item['author-link']." and ".$item['owner-link'], LOGGER_DEBUG);
713                                         if ((normalise_link($item['author-link']) == $self) || (normalise_link($item['owner-link']) == $self)) {
714                                                 dba::update('thread', ['mention' => true], ['iid' => $parent_id]);
715                                                 logger("tagged thread ".$parent_id." as mention for user ".$self, LOGGER_DEBUG);
716                                         }
717                                 }
718                         } else {
719                                 /*
720                                  * Allow one to see reply tweets from status.net even when
721                                  * we don't have or can't see the original post.
722                                  */
723                                 if ($force_parent) {
724                                         logger('$force_parent=true, reply converted to top-level post.');
725                                         $parent_id = 0;
726                                         $item['parent-uri'] = $item['uri'];
727                                         $item['gravity'] = 0;
728                                 } else {
729                                         logger('item parent '.$item['parent-uri'].' for '.$item['uid'].' was not found - ignoring item');
730                                         return 0;
731                                 }
732
733                                 $parent_deleted = 0;
734                         }
735                 }
736
737                 $condition = ["`uri` = ? AND `network` IN (?, ?) AND `uid` = ?",
738                         $item['uri'], $item['network'], NETWORK_DFRN, $item['uid']];
739                 if (dba::exists('item', $condition)) {
740                         logger('duplicated item with the same uri found. '.print_r($item,true));
741                         return 0;
742                 }
743
744                 // On Friendica and Diaspora the GUID is unique
745                 if (in_array($item['network'], [NETWORK_DFRN, NETWORK_DIASPORA])) {
746                         $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
747                         if (dba::exists('item', $condition)) {
748                                 logger('duplicated item with the same guid found. '.print_r($item,true));
749                                 return 0;
750                         }
751                 } else {
752                         // Check for an existing post with the same content. There seems to be a problem with OStatus.
753                         $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
754                                         $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
755                         if (dba::exists('item', $condition)) {
756                                 logger('duplicated item with the same body found. '.print_r($item,true));
757                                 return 0;
758                         }
759                 }
760
761                 // Is this item available in the global items (with uid=0)?
762                 if ($item["uid"] == 0) {
763                         $item["global"] = true;
764
765                         // Set the global flag on all items if this was a global item entry
766                         dba::update('item', ['global' => true], ['uri' => $item["uri"]]);
767                 } else {
768                         $item["global"] = dba::exists('item', ['uid' => 0, 'uri' => $item["uri"]]);
769                 }
770
771                 // ACL settings
772                 if (strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid)) {
773                         $private = 1;
774                 } else {
775                         $private = $item['private'];
776                 }
777
778                 $item["allow_cid"] = $allow_cid;
779                 $item["allow_gid"] = $allow_gid;
780                 $item["deny_cid"] = $deny_cid;
781                 $item["deny_gid"] = $deny_gid;
782                 $item["private"] = $private;
783                 $item["deleted"] = $parent_deleted;
784
785                 // Fill the cache field
786                 put_item_in_cache($item);
787
788                 if ($notify) {
789                         Addon::callHooks('post_local', $item);
790                 } else {
791                         Addon::callHooks('post_remote', $item);
792                 }
793
794                 // This array field is used to trigger some automatic reactions
795                 // It is mainly used in the "post_local" hook.
796                 unset($item['api_source']);
797
798                 if (x($item, 'cancel')) {
799                         logger('post cancelled by addon.');
800                         return 0;
801                 }
802
803                 /*
804                  * Check for already added items.
805                  * There is a timing issue here that sometimes creates double postings.
806                  * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
807                  */
808                 if ($item["uid"] == 0) {
809                         if (dba::exists('item', ['uri' => trim($item['uri']), 'uid' => 0])) {
810                                 logger('Global item already stored. URI: '.$item['uri'].' on network '.$item['network'], LOGGER_DEBUG);
811                                 return 0;
812                         }
813                 }
814
815                 logger('' . print_r($item,true), LOGGER_DATA);
816
817                 dba::transaction();
818                 $ret = dba::insert('item', $item);
819
820                 // When the item was successfully stored we fetch the ID of the item.
821                 if (DBM::is_result($ret)) {
822                         $current_post = dba::lastInsertId();
823                 } else {
824                         // This can happen - for example - if there are locking timeouts.
825                         dba::rollback();
826
827                         // Store the data into a spool file so that we can try again later.
828
829                         // At first we restore the Diaspora signature that we removed above.
830                         if (isset($encoded_signature)) {
831                                 $item['dsprsig'] = $encoded_signature;
832                         }
833
834                         // Now we store the data in the spool directory
835                         // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
836                         $file = 'item-'.round(microtime(true) * 10000).'-'.mt_rand().'.msg';
837
838                         $spoolpath = get_spoolpath();
839                         if ($spoolpath != "") {
840                                 $spool = $spoolpath.'/'.$file;
841                                 file_put_contents($spool, json_encode($item));
842                                 logger("Item wasn't stored - Item was spooled into file ".$file, LOGGER_DEBUG);
843                         }
844                         return 0;
845                 }
846
847                 if ($current_post == 0) {
848                         // This is one of these error messages that never should occur.
849                         logger("couldn't find created item - we better quit now.");
850                         dba::rollback();
851                         return 0;
852                 }
853
854                 // How much entries have we created?
855                 // We wouldn't need this query when we could use an unique index - but MySQL has length problems with them.
856                 $entries = dba::count('item', ['uri' => $item['uri'], 'uid' => $item['uid'], 'network' => $item['network']]);
857
858                 if ($entries > 1) {
859                         // There are duplicates. We delete our just created entry.
860                         logger('Duplicated post occurred. uri = ' . $item['uri'] . ' uid = ' . $item['uid']);
861
862                         // Yes, we could do a rollback here - but we are having many users with MyISAM.
863                         dba::delete('item', ['id' => $current_post]);
864                         dba::commit();
865                         return 0;
866                 } elseif ($entries == 0) {
867                         // This really should never happen since we quit earlier if there were problems.
868                         logger("Something is terribly wrong. We haven't found our created entry.");
869                         dba::rollback();
870                         return 0;
871                 }
872
873                 logger('created item '.$current_post);
874                 self::updateContact($item);
875
876                 if (!$parent_id || ($item['parent-uri'] === $item['uri'])) {
877                         $parent_id = $current_post;
878                 }
879
880                 // Set parent id
881                 dba::update('item', ['parent' => $parent_id], ['id' => $current_post]);
882
883                 $item['id'] = $current_post;
884                 $item['parent'] = $parent_id;
885
886                 // update the commented timestamp on the parent
887                 // Only update "commented" if it is really a comment
888                 if (($item['verb'] == ACTIVITY_POST) || !Config::get("system", "like_no_comment")) {
889                         dba::update('item', ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
890                 } else {
891                         dba::update('item', ['changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
892                 }
893
894                 if ($dsprsig) {
895                         /*
896                          * Friendica servers lower than 3.4.3-2 had double encoded the signature ...
897                          * We can check for this condition when we decode and encode the stuff again.
898                          */
899                         if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) {
900                                 $dsprsig->signature = base64_decode($dsprsig->signature);
901                                 logger("Repaired double encoded signature from handle ".$dsprsig->signer, LOGGER_DEBUG);
902                         }
903
904                         dba::insert('sign', ['iid' => $current_post, 'signed_text' => $dsprsig->signed_text,
905                                                 'signature' => $dsprsig->signature, 'signer' => $dsprsig->signer]);
906                 }
907
908                 if (!empty($diaspora_signed_text)) {
909                         // Formerly we stored the signed text, the signature and the author in different fields.
910                         // We now store the raw data so that we are more flexible.
911                         dba::insert('sign', ['iid' => $current_post, 'signed_text' => $diaspora_signed_text]);
912                 }
913
914                 $deleted = self::tagDeliver($item['uid'], $current_post);
915
916                 /*
917                  * current post can be deleted if is for a community page and no mention are
918                  * in it.
919                  */
920                 if (!$deleted && !$dontcache) {
921                         $posted_item = dba::selectFirst('item', [], ['id' => $current_post]);
922                         if (DBM::is_result($posted_item)) {
923                                 if ($notify) {
924                                         Addon::callHooks('post_local_end', $posted_item);
925                                 } else {
926                                         Addon::callHooks('post_remote_end', $posted_item);
927                                 }
928                         } else {
929                                 logger('new item not found in DB, id ' . $current_post);
930                         }
931                 }
932
933                 if ($item['parent-uri'] === $item['uri']) {
934                         self::addThread($current_post);
935                 } else {
936                         self::updateThread($parent_id);
937                 }
938
939                 dba::commit();
940
941                 /*
942                  * Due to deadlock issues with the "term" table we are doing these steps after the commit.
943                  * This is not perfect - but a workable solution until we found the reason for the problem.
944                  */
945                 Term::insertFromTagFieldByItemId($current_post);
946                 Term::insertFromFileFieldByItemId($current_post);
947
948                 if ($item['parent-uri'] === $item['uri']) {
949                         self::addShadow($current_post);
950                 } else {
951                         self::addShadowPost($current_post);
952                 }
953
954                 check_user_notification($current_post);
955
956                 if ($notify) {
957                         Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", $notify_type, $current_post);
958                 } elseif (!empty($parent) && $parent['origin']) {
959                         Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "Notifier", "comment-import", $current_post);
960                 }
961
962                 return $current_post;
963         }
964
965         /**
966          * @brief Distributes public items to the receivers
967          *
968          * @param integer $itemid      Item ID that should be added
969          * @param string  $signed_text Original text (for Diaspora signatures), JSON encoded.
970          */
971         public static function distribute($itemid, $signed_text = '')
972         {
973                 $condition = ["`id` IN (SELECT `parent` FROM `item` WHERE `id` = ?)", $itemid];
974                 $parent = dba::selectFirst('item', ['owner-id'], $condition);
975                 if (!DBM::is_result($parent)) {
976                         return;
977                 }
978
979                 // Only distribute public items from native networks
980                 $condition = ['id' => $itemid, 'uid' => 0,
981                         'network' => [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""],
982                         'visible' => true, 'deleted' => false, 'moderated' => false, 'private' => false];
983                 $item = dba::selectFirst('item', [], ['id' => $itemid]);
984                 if (!DBM::is_result($item)) {
985                         return;
986                 }
987
988                 unset($item['id']);
989                 unset($item['parent']);
990                 unset($item['mention']);
991                 unset($item['wall']);
992                 unset($item['origin']);
993                 unset($item['starred']);
994                 unset($item['rendered-hash']);
995                 unset($item['rendered-html']);
996
997                 $users = [];
998
999                 $condition = ["`nurl` IN (SELECT `nurl` FROM `contact` WHERE `id` = ?) AND `uid` != 0 AND NOT `blocked` AND `rel` IN (?, ?)",
1000                         $parent['owner-id'], CONTACT_IS_SHARING,  CONTACT_IS_FRIEND];
1001                 $contacts = dba::select('contact', ['uid'], $condition);
1002                 while ($contact = dba::fetch($contacts)) {
1003                         $users[$contact['uid']] = $contact['uid'];
1004                 }
1005
1006                 $origin_uid = 0;
1007
1008                 if ($item['uri'] != $item['parent-uri']) {
1009                         $parents = dba::select('item', ['uid', 'origin'], ["`uri` = ? AND `uid` != 0", $item['parent-uri']]);
1010                         while ($parent = dba::fetch($parents)) {
1011                                 $users[$parent['uid']] = $parent['uid'];
1012                                 if ($parent['origin'] && !$item['origin']) {
1013                                         $origin_uid = $parent['uid'];
1014                                 }
1015                         }
1016                 }
1017
1018                 foreach ($users as $uid) {
1019                         if ($origin_uid == $uid) {
1020                                 $item['diaspora_signed_text'] = $signed_text;
1021                         }
1022                         self::storeForUser($itemid, $item, $uid);
1023                 }
1024         }
1025
1026         /**
1027          * @brief Store public items for the receivers
1028          *
1029          * @param integer $itemid Item ID that should be added
1030          * @param array   $item   The item entry that will be stored
1031          * @param integer $uid    The user that will receive the item entry
1032          */
1033         private static function storeForUser($itemid, $item, $uid)
1034         {
1035                 $item['uid'] = $uid;
1036                 $item['origin'] = 0;
1037                 $item['wall'] = 0;
1038                 if ($item['uri'] == $item['parent-uri']) {
1039                         $item['contact-id'] = Contact::getIdForURL($item['owner-link'], $uid);
1040                 } else {
1041                         $item['contact-id'] = Contact::getIdForURL($item['author-link'], $uid);
1042                 }
1043
1044                 if (empty($item['contact-id'])) {
1045                         $self = dba::selectFirst('contact', ['id'], ['self' => true, 'uid' => $uid]);
1046                         if (!DBM::is_result($self)) {
1047                                 return;
1048                         }
1049                         $item['contact-id'] = $self['id'];
1050                 }
1051
1052                 if (in_array($item['type'], ["net-comment", "wall-comment"])) {
1053                         $item['type'] = 'remote-comment';
1054                 } elseif ($item['type'] == 'wall') {
1055                         $item['type'] = 'remote';
1056                 }
1057
1058                 /// @todo Handling of "event-id"
1059
1060                 $notify = false;
1061                 if ($item['uri'] == $item['parent-uri']) {
1062                         $contact = dba::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
1063                         if (DBM::is_result($contact)) {
1064                                 $notify = self::isRemoteSelf($contact, $item);
1065                         }
1066                 }
1067
1068                 $distributed = self::insert($item, false, $notify, true);
1069
1070                 if (!$distributed) {
1071                         logger("Distributed public item " . $itemid . " for user " . $uid . " wasn't stored", LOGGER_DEBUG);
1072                 } else {
1073                         logger("Distributed public item " . $itemid . " for user " . $uid . " with id " . $distributed, LOGGER_DEBUG);
1074                 }
1075         }
1076
1077         /**
1078          * @brief Add a shadow entry for a given item id that is a thread starter
1079          *
1080          * We store every public item entry additionally with the user id "0".
1081          * This is used for the community page and for the search.
1082          * It is planned that in the future we will store public item entries only once.
1083          *
1084          * @param integer $itemid Item ID that should be added
1085          */
1086         public static function addShadow($itemid)
1087         {
1088                 $fields = ['uid', 'private', 'moderated', 'visible', 'deleted', 'network'];
1089                 $condition = ['id' => $itemid, 'parent' => [0, $itemid]];
1090                 $item = dba::selectFirst('item', $fields, $condition);
1091
1092                 if (!DBM::is_result($item)) {
1093                         return;
1094                 }
1095
1096                 // is it already a copy?
1097                 if (($itemid == 0) || ($item['uid'] == 0)) {
1098                         return;
1099                 }
1100
1101                 // Is it a visible public post?
1102                 if (!$item["visible"] || $item["deleted"] || $item["moderated"] || $item["private"]) {
1103                         return;
1104                 }
1105
1106                 // is it an entry from a connector? Only add an entry for natively connected networks
1107                 if (!in_array($item["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""])) {
1108                         return;
1109                 }
1110
1111                 $item = dba::selectFirst('item', [], ['id' => $itemid]);
1112
1113                 if (DBM::is_result($item) && ($item["allow_cid"] == '') && ($item["allow_gid"] == '') &&
1114                         ($item["deny_cid"] == '') && ($item["deny_gid"] == '')) {
1115
1116                         if (!dba::exists('item', ['uri' => $item['uri'], 'uid' => 0])) {
1117                                 // Preparing public shadow (removing user specific data)
1118                                 $item['uid'] = 0;
1119                                 unset($item['id']);
1120                                 unset($item['parent']);
1121                                 unset($item['wall']);
1122                                 unset($item['mention']);
1123                                 unset($item['origin']);
1124                                 unset($item['starred']);
1125                                 unset($item['rendered-hash']);
1126                                 unset($item['rendered-html']);
1127                                 if ($item['uri'] == $item['parent-uri']) {
1128                                         $item['contact-id'] = Contact::getIdForURL($item['owner-link']);
1129                                 } else {
1130                                         $item['contact-id'] = Contact::getIdForURL($item['author-link']);
1131                                 }
1132
1133                                 if (in_array($item['type'], ["net-comment", "wall-comment"])) {
1134                                         $item['type'] = 'remote-comment';
1135                                 } elseif ($item['type'] == 'wall') {
1136                                         $item['type'] = 'remote';
1137                                 }
1138
1139                                 $public_shadow = self::insert($item, false, false, true);
1140
1141                                 logger("Stored public shadow for thread ".$itemid." under id ".$public_shadow, LOGGER_DEBUG);
1142                         }
1143                 }
1144         }
1145
1146         /**
1147          * @brief Add a shadow entry for a given item id that is a comment
1148          *
1149          * This function does the same like the function above - but for comments
1150          *
1151          * @param integer $itemid Item ID that should be added
1152          */
1153         public static function addShadowPost($itemid)
1154         {
1155                 $item = dba::selectFirst('item', [], ['id' => $itemid]);
1156                 if (!DBM::is_result($item)) {
1157                         return;
1158                 }
1159
1160                 // Is it a toplevel post?
1161                 if ($item['id'] == $item['parent']) {
1162                         self::addShadow($itemid);
1163                         return;
1164                 }
1165
1166                 // Is this a shadow entry?
1167                 if ($item['uid'] == 0) {
1168                         return;
1169                 }
1170
1171                 // Is there a shadow parent?
1172                 if (!dba::exists('item', ['uri' => $item['parent-uri'], 'uid' => 0])) {
1173                         return;
1174                 }
1175
1176                 // Is there already a shadow entry?
1177                 if (dba::exists('item', ['uri' => $item['uri'], 'uid' => 0])) {
1178                         return;
1179                 }
1180
1181                 // Save "origin" and "parent" state
1182                 $origin = $item['origin'];
1183                 $parent = $item['parent'];
1184
1185                 // Preparing public shadow (removing user specific data)
1186                 $item['uid'] = 0;
1187                 unset($item['id']);
1188                 unset($item['parent']);
1189                 unset($item['wall']);
1190                 unset($item['mention']);
1191                 unset($item['origin']);
1192                 unset($item['starred']);
1193                 unset($item['rendered-hash']);
1194                 unset($item['rendered-html']);
1195                 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
1196
1197                 if (in_array($item['type'], ["net-comment", "wall-comment"])) {
1198                         $item['type'] = 'remote-comment';
1199                 } elseif ($item['type'] == 'wall') {
1200                         $item['type'] = 'remote';
1201                 }
1202
1203                 $public_shadow = self::insert($item, false, false, true);
1204
1205                 logger("Stored public shadow for comment ".$item['uri']." under id ".$public_shadow, LOGGER_DEBUG);
1206
1207                 // If this was a comment to a Diaspora post we don't get our comment back.
1208                 // This means that we have to distribute the comment by ourselves.
1209                 if ($origin && dba::exists('item', ['id' => $parent, 'network' => NETWORK_DIASPORA])) {
1210                         self::distribute($public_shadow);
1211                 }
1212         }
1213
1214          /**
1215          * Adds a "lang" specification in a "postopts" element of given $arr,
1216          * if possible and not already present.
1217          * Expects "body" element to exist in $arr.
1218          */
1219         private static function addLanguageInPostopts(&$item)
1220         {
1221                 $postopts = "";
1222
1223                 if (!empty($item['postopts'])) {
1224                         if (strstr($item['postopts'], 'lang=')) {
1225                                 // do not override
1226                                 return;
1227                         }
1228                         $postopts = $item['postopts'];
1229                 }
1230
1231                 $naked_body = Text\BBCode::toPlaintext($item['body'], false);
1232
1233                 $languages = (new Text_LanguageDetect())->detect($naked_body, 3);
1234
1235                 if (sizeof($languages) > 0) {
1236                         if ($postopts != '') {
1237                                 $postopts .= '&'; // arbitrary separator, to be reviewed
1238                         }
1239
1240                         $postopts .= 'lang=';
1241                         $sep = "";
1242
1243                         foreach ($languages as $language => $score) {
1244                                 $postopts .= $sep . $language . ";" . $score;
1245                                 $sep = ':';
1246                         }
1247                         $item['postopts'] = $postopts;
1248                 }
1249         }
1250
1251         /**
1252          * @brief Creates an unique guid out of a given uri
1253          *
1254          * @param string $uri uri of an item entry
1255          * @param string $host hostname for the GUID prefix
1256          * @return string unique guid
1257          */
1258         public static function guidFromUri($uri, $host)
1259         {
1260                 // Our regular guid routine is using this kind of prefix as well
1261                 // We have to avoid that different routines could accidentally create the same value
1262                 $parsed = parse_url($uri);
1263
1264                 // We use a hash of the hostname as prefix for the guid
1265                 $guid_prefix = hash("crc32", $host);
1266
1267                 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
1268                 unset($parsed["scheme"]);
1269
1270                 // Glue it together to be able to make a hash from it
1271                 $host_id = implode("/", $parsed);
1272
1273                 // We could use any hash algorithm since it isn't a security issue
1274                 $host_hash = hash("ripemd128", $host_id);
1275
1276                 return $guid_prefix.$host_hash;
1277         }
1278
1279         /**
1280          * @brief Set "success_update" and "last-item" to the date of the last time we heard from this contact
1281          *
1282          * This can be used to filter for inactive contacts.
1283          * Only do this for public postings to avoid privacy problems, since poco data is public.
1284          * Don't set this value if it isn't from the owner (could be an author that we don't know)
1285          *
1286          * @param array $arr Contains the just posted item record
1287          */
1288         private static function updateContact($arr)
1289         {
1290                 // Unarchive the author
1291                 $contact = dba::selectFirst('contact', [], ['id' => $arr["author-id"]]);
1292                 if (DBM::is_result($contact)) {
1293                         Contact::unmarkForArchival($contact);
1294                 }
1295
1296                 // Unarchive the contact if it's not our own contact
1297                 $contact = dba::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
1298                 if (DBM::is_result($contact)) {
1299                         Contact::unmarkForArchival($contact);
1300                 }
1301
1302                 $update = (!$arr['private'] && (($arr["author-link"] === $arr["owner-link"]) || ($arr["parent-uri"] === $arr["uri"])));
1303
1304                 // Is it a forum? Then we don't care about the rules from above
1305                 if (!$update && ($arr["network"] == NETWORK_DFRN) && ($arr["parent-uri"] === $arr["uri"])) {
1306                         if (dba::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
1307                                 $update = true;
1308                         }
1309                 }
1310
1311                 if ($update) {
1312                         dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
1313                                 ['id' => $arr['contact-id']]);
1314                 }
1315                 // Now do the same for the system wide contacts with uid=0
1316                 if (!$arr['private']) {
1317                         dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
1318                                 ['id' => $arr['owner-id']]);
1319
1320                         if ($arr['owner-id'] != $arr['author-id']) {
1321                                 dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
1322                                         ['id' => $arr['author-id']]);
1323                         }
1324                 }
1325         }
1326
1327         public static function setHashtags(&$item)
1328         {
1329
1330                 $tags = get_tags($item["body"]);
1331
1332                 // No hashtags?
1333                 if (!count($tags)) {
1334                         return false;
1335                 }
1336
1337                 // This sorting is important when there are hashtags that are part of other hashtags
1338                 // Otherwise there could be problems with hashtags like #test and #test2
1339                 rsort($tags);
1340
1341                 $URLSearchString = "^\[\]";
1342
1343                 // All hashtags should point to the home server if "local_tags" is activated
1344                 if (Config::get('system', 'local_tags')) {
1345                         $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1346                                         "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["body"]);
1347
1348                         $item["tag"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1349                                         "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["tag"]);
1350                 }
1351
1352                 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
1353                 $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1354                         function ($match) {
1355                                 return ("[url=" . str_replace("#", "&num;", $match[1]) . "]" . str_replace("#", "&num;", $match[2]) . "[/url]");
1356                         }, $item["body"]);
1357
1358                 $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
1359                         function ($match) {
1360                                 return ("[bookmark=" . str_replace("#", "&num;", $match[1]) . "]" . str_replace("#", "&num;", $match[2]) . "[/bookmark]");
1361                         }, $item["body"]);
1362
1363                 $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
1364                         function ($match) {
1365                                 return ("[attachment " . str_replace("#", "&num;", $match[1]) . "]" . $match[2] . "[/attachment]");
1366                         }, $item["body"]);
1367
1368                 // Repair recursive urls
1369                 $item["body"] = preg_replace("/&num;\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1370                                 "&num;$2", $item["body"]);
1371
1372                 foreach ($tags as $tag) {
1373                         if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=')) {
1374                                 continue;
1375                         }
1376
1377                         $basetag = str_replace('_',' ',substr($tag,1));
1378
1379                         $newtag = '#[url=' . System::baseUrl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1380
1381                         $item["body"] = str_replace($tag, $newtag, $item["body"]);
1382
1383                         if (!stristr($item["tag"], "/search?tag=" . $basetag . "]" . $basetag . "[/url]")) {
1384                                 if (strlen($item["tag"])) {
1385                                         $item["tag"] = ','.$item["tag"];
1386                                 }
1387                                 $item["tag"] = $newtag.$item["tag"];
1388                         }
1389                 }
1390
1391                 // Convert back the masked hashtags
1392                 $item["body"] = str_replace("&num;", "#", $item["body"]);
1393         }
1394
1395         public static function getGuidById($id)
1396         {
1397                 $item = dba::selectFirst('item', ['guid'], ['id' => $id]);
1398                 if (DBM::is_result($item)) {
1399                         return $item['guid'];
1400                 } else {
1401                         return '';
1402                 }
1403         }
1404
1405         public static function getIdAndNickByGuid($guid, $uid = 0)
1406         {
1407                 $nick = "";
1408                 $id = 0;
1409
1410                 if ($uid == 0) {
1411                         $uid == local_user();
1412                 }
1413
1414                 // Does the given user have this item?
1415                 if ($uid) {
1416                         $item = dba::fetch_first("SELECT `item`.`id`, `user`.`nickname` FROM `item`
1417                                 INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
1418                                 WHERE `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
1419                                         AND `item`.`guid` = ? AND `item`.`uid` = ?", $guid, $uid);
1420                         if (DBM::is_result($item)) {
1421                                 $id = $item["id"];
1422                                 $nick = $item["nickname"];
1423                         }
1424                 }
1425
1426                 // Or is it anywhere on the server?
1427                 if ($nick == "") {
1428                         $item = dba::fetch_first("SELECT `item`.`id`, `user`.`nickname` FROM `item`
1429                                 INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
1430                                 WHERE `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
1431                                         AND `item`.`allow_cid` = ''  AND `item`.`allow_gid` = ''
1432                                         AND `item`.`deny_cid`  = '' AND `item`.`deny_gid`  = ''
1433                                         AND NOT `item`.`private` AND `item`.`wall`
1434                                         AND `item`.`guid` = ?", $guid);
1435                         if (DBM::is_result($item)) {
1436                                 $id = $item["id"];
1437                                 $nick = $item["nickname"];
1438                         }
1439                 }
1440                 return ["nick" => $nick, "id" => $id];
1441         }
1442
1443         /**
1444          * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
1445          * @param int $uid
1446          * @param int $item_id
1447          * @return bool true if item was deleted, else false
1448          */
1449         private static function tagDeliver($uid, $item_id)
1450         {
1451                 $mention = false;
1452
1453                 $user = dba::selectFirst('user', [], ['uid' => $uid]);
1454                 if (!DBM::is_result($user)) {
1455                         return;
1456                 }
1457
1458                 $community_page = (($user['page-flags'] == PAGE_COMMUNITY) ? true : false);
1459                 $prvgroup = (($user['page-flags'] == PAGE_PRVGROUP) ? true : false);
1460
1461                 $item = dba::selectFirst('item', [], ['id' => $item_id]);
1462                 if (!DBM::is_result($item)) {
1463                         return;
1464                 }
1465
1466                 $link = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
1467
1468                 /*
1469                  * Diaspora uses their own hardwired link URL in @-tags
1470                  * instead of the one we supply with webfinger
1471                  */
1472                 $dlink = normalise_link(System::baseUrl() . '/u/' . $user['nickname']);
1473
1474                 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
1475                 if ($cnt) {
1476                         foreach ($matches as $mtch) {
1477                                 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
1478                                         $mention = true;
1479                                         logger('mention found: ' . $mtch[2]);
1480                                 }
1481                         }
1482                 }
1483
1484                 if (!$mention) {
1485                         if (($community_page || $prvgroup) &&
1486                                   !$item['wall'] && !$item['origin'] && ($item['id'] == $item['parent'])) {
1487                                 // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
1488                                 // delete it!
1489                                 logger("no-mention top-level post to community or private group. delete.");
1490                                 dba::delete('item', ['id' => $item_id]);
1491                                 return true;
1492                         }
1493                         return;
1494                 }
1495
1496                 $arr = ['item' => $item, 'user' => $user];
1497
1498                 Addon::callHooks('tagged', $arr);
1499
1500                 if (!$community_page && !$prvgroup) {
1501                         return;
1502                 }
1503
1504                 /*
1505                  * tgroup delivery - setup a second delivery chain
1506                  * prevent delivery looping - only proceed
1507                  * if the message originated elsewhere and is a top-level post
1508                  */
1509                 if ($item['wall'] || $item['origin'] || ($item['id'] != $item['parent'])) {
1510                         return;
1511                 }
1512
1513                 // now change this copy of the post to a forum head message and deliver to all the tgroup members
1514                 $self = dba::selectFirst('contact', ['id', 'name', 'url', 'thumb'], ['uid' => $uid, 'self' => true]);
1515                 if (!DBM::is_result($self)) {
1516                         return;
1517                 }
1518
1519                 $owner_id = Contact::getIdForURL($self['url']);
1520
1521                 // also reset all the privacy bits to the forum default permissions
1522
1523                 $private = ($user['allow_cid'] || $user['allow_gid'] || $user['deny_cid'] || $user['deny_gid']) ? 1 : 0;
1524
1525                 $forum_mode = ($prvgroup ? 2 : 1);
1526
1527                 $fields = ['wall' => true, 'origin' => true, 'forum_mode' => $forum_mode, 'contact-id' => $self['id'],
1528                         'owner-id' => $owner_id, 'owner-link' => $self['url'], 'private' => $private, 'allow_cid' => $user['allow_cid'],
1529                         'allow_gid' => $user['allow_gid'], 'deny_cid' => $user['deny_cid'], 'deny_gid' => $user['deny_gid']];
1530                 dba::update('item', $fields, ['id' => $item_id]);
1531
1532                 self::updateThread($item_id);
1533
1534                 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', 'tgroup', $item_id);
1535         }
1536
1537         public static function isRemoteSelf($contact, &$datarray)
1538         {
1539                 $a = get_app();
1540
1541                 if (!$contact['remote_self']) {
1542                         return false;
1543                 }
1544
1545                 // Prevent the forwarding of posts that are forwarded
1546                 if ($datarray["extid"] == NETWORK_DFRN) {
1547                         logger('Already forwarded', LOGGER_DEBUG);
1548                         return false;
1549                 }
1550
1551                 // Prevent to forward already forwarded posts
1552                 if ($datarray["app"] == $a->get_hostname()) {
1553                         logger('Already forwarded (second test)', LOGGER_DEBUG);
1554                         return false;
1555                 }
1556
1557                 // Only forward posts
1558                 if ($datarray["verb"] != ACTIVITY_POST) {
1559                         logger('No post', LOGGER_DEBUG);
1560                         return false;
1561                 }
1562
1563                 if (($contact['network'] != NETWORK_FEED) && $datarray['private']) {
1564                         logger('Not public', LOGGER_DEBUG);
1565                         return false;
1566                 }
1567
1568                 $datarray2 = $datarray;
1569                 logger('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), LOGGER_DEBUG);
1570                 if ($contact['remote_self'] == 2) {
1571                         $self = dba::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
1572                                         ['uid' => $contact['uid'], 'self' => true]);
1573                         if (DBM::is_result($self)) {
1574                                 $datarray['contact-id'] = $self["id"];
1575
1576                                 $datarray['owner-name'] = $self["name"];
1577                                 $datarray['owner-link'] = $self["url"];
1578                                 $datarray['owner-avatar'] = $self["thumb"];
1579
1580                                 $datarray['author-name']   = $datarray['owner-name'];
1581                                 $datarray['author-link']   = $datarray['owner-link'];
1582                                 $datarray['author-avatar'] = $datarray['owner-avatar'];
1583
1584                                 unset($datarray['created']);
1585                                 unset($datarray['edited']);
1586
1587                                 unset($datarray['network']);
1588                                 unset($datarray['owner-id']);
1589                                 unset($datarray['author-id']);
1590                         }
1591
1592                         if ($contact['network'] != NETWORK_FEED) {
1593                                 $datarray["guid"] = get_guid(32);
1594                                 unset($datarray["plink"]);
1595                                 $datarray["uri"] = item_new_uri($a->get_hostname(), $contact['uid'], $datarray["guid"]);
1596                                 $datarray["parent-uri"] = $datarray["uri"];
1597                                 $datarray["thr-parent"] = $datarray["uri"];
1598                                 $datarray["extid"] = NETWORK_DFRN;
1599                                 $urlpart = parse_url($datarray2['author-link']);
1600                                 $datarray["app"] = $urlpart["host"];
1601                         } else {
1602                                 $datarray['private'] = 0;
1603                         }
1604                 }
1605
1606                 if ($contact['network'] != NETWORK_FEED) {
1607                         // Store the original post
1608                         $result = self::insert($datarray2, false, false);
1609                         logger('remote-self post original item - Contact '.$contact['url'].' return '.$result.' Item '.print_r($datarray2, true), LOGGER_DEBUG);
1610                 } else {
1611                         $datarray["app"] = "Feed";
1612                         $result = true;
1613                 }
1614
1615                 // Trigger automatic reactions for addons
1616                 $datarray['api_source'] = true;
1617
1618                 // We have to tell the hooks who we are - this really should be improved
1619                 $_SESSION["authenticated"] = true;
1620                 $_SESSION["uid"] = $contact['uid'];
1621
1622                 return $result;
1623         }
1624
1625         /**
1626          *
1627          * @param string $s
1628          * @param int    $uid
1629          * @param array  $item
1630          * @param int    $cid
1631          * @return string
1632          */
1633         public static function fixPrivatePhotos($s, $uid, $item = null, $cid = 0)
1634         {
1635                 if (Config::get('system', 'disable_embedded')) {
1636                         return $s;
1637                 }
1638
1639                 logger('check for photos', LOGGER_DEBUG);
1640                 $site = substr(System::baseUrl(), strpos(System::baseUrl(), '://'));
1641
1642                 $orig_body = $s;
1643                 $new_body = '';
1644
1645                 $img_start = strpos($orig_body, '[img');
1646                 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
1647                 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
1648
1649                 while (($img_st_close !== false) && ($img_len !== false)) {
1650                         $img_st_close++; // make it point to AFTER the closing bracket
1651                         $image = substr($orig_body, $img_start + $img_st_close, $img_len);
1652
1653                         logger('found photo ' . $image, LOGGER_DEBUG);
1654
1655                         if (stristr($image, $site . '/photo/')) {
1656                                 // Only embed locally hosted photos
1657                                 $replace = false;
1658                                 $i = basename($image);
1659                                 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
1660                                 $x = strpos($i, '-');
1661
1662                                 if ($x) {
1663                                         $res = substr($i, $x + 1);
1664                                         $i = substr($i, 0, $x);
1665                                         $fields = ['data', 'type', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'];
1666                                         $photo = dba::selectFirst('photo', $fields, ['resource-id' => $i, 'scale' => $res, 'uid' => $uid]);
1667                                         if (DBM::is_result($photo)) {
1668                                                 /*
1669                                                  * Check to see if we should replace this photo link with an embedded image
1670                                                  * 1. No need to do so if the photo is public
1671                                                  * 2. If there's a contact-id provided, see if they're in the access list
1672                                                  *    for the photo. If so, embed it.
1673                                                  * 3. Otherwise, if we have an item, see if the item permissions match the photo
1674                                                  *    permissions, regardless of order but first check to see if they're an exact
1675                                                  *    match to save some processing overhead.
1676                                                  */
1677                                                 if (self::hasPermissions($photo)) {
1678                                                         if ($cid) {
1679                                                                 $recips = self::enumeratePermissions($photo);
1680                                                                 if (in_array($cid, $recips)) {
1681                                                                         $replace = true;
1682                                                                 }
1683                                                         } elseif ($item) {
1684                                                                 if (self::samePermissions($item, $photo)) {
1685                                                                         $replace = true;
1686                                                                 }
1687                                                         }
1688                                                 }
1689                                                 if ($replace) {
1690                                                         $data = $photo['data'];
1691                                                         $type = $photo['type'];
1692
1693                                                         // If a custom width and height were specified, apply before embedding
1694                                                         if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
1695                                                                 logger('scaling photo', LOGGER_DEBUG);
1696
1697                                                                 $width = intval($match[1]);
1698                                                                 $height = intval($match[2]);
1699
1700                                                                 $Image = new Image($data, $type);
1701                                                                 if ($Image->isValid()) {
1702                                                                         $Image->scaleDown(max($width, $height));
1703                                                                         $data = $Image->asString();
1704                                                                         $type = $Image->getType();
1705                                                                 }
1706                                                         }
1707
1708                                                         logger('replacing photo', LOGGER_DEBUG);
1709                                                         $image = 'data:' . $type . ';base64,' . base64_encode($data);
1710                                                         logger('replaced: ' . $image, LOGGER_DATA);
1711                                                 }
1712                                         }
1713                                 }
1714                         }
1715
1716                         $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
1717                         $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
1718                         if ($orig_body === false) {
1719                                 $orig_body = '';
1720                         }
1721
1722                         $img_start = strpos($orig_body, '[img');
1723                         $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
1724                         $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
1725                 }
1726
1727                 $new_body = $new_body . $orig_body;
1728
1729                 return $new_body;
1730         }
1731
1732         private static function hasPermissions($obj)
1733         {
1734                 return (
1735                         (
1736                                 x($obj, 'allow_cid')
1737                         ) || (
1738                                 x($obj, 'allow_gid')
1739                         ) || (
1740                                 x($obj, 'deny_cid')
1741                         ) || (
1742                                 x($obj, 'deny_gid')
1743                         )
1744                 );
1745         }
1746
1747         private static function samePermissions($obj1, $obj2)
1748         {
1749                 // first part is easy. Check that these are exactly the same.
1750                 if (($obj1['allow_cid'] == $obj2['allow_cid'])
1751                         && ($obj1['allow_gid'] == $obj2['allow_gid'])
1752                         && ($obj1['deny_cid'] == $obj2['deny_cid'])
1753                         && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
1754                         return true;
1755                 }
1756
1757                 // This is harder. Parse all the permissions and compare the resulting set.
1758                 $recipients1 = self::enumeratePermissions($obj1);
1759                 $recipients2 = self::enumeratePermissions($obj2);
1760                 sort($recipients1);
1761                 sort($recipients2);
1762
1763                 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
1764                 return ($recipients1 == $recipients2);
1765         }
1766
1767         // returns an array of contact-ids that are allowed to see this object
1768         private static function enumeratePermissions($obj)
1769         {
1770                 $allow_people = expand_acl($obj['allow_cid']);
1771                 $allow_groups = Group::expand(expand_acl($obj['allow_gid']));
1772                 $deny_people  = expand_acl($obj['deny_cid']);
1773                 $deny_groups  = Group::expand(expand_acl($obj['deny_gid']));
1774                 $recipients   = array_unique(array_merge($allow_people, $allow_groups));
1775                 $deny         = array_unique(array_merge($deny_people, $deny_groups));
1776                 $recipients   = array_diff($recipients, $deny);
1777                 return $recipients;
1778         }
1779
1780         public static function getFeedTags($item)
1781         {
1782                 $ret = [];
1783                 $matches = false;
1784                 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
1785                 if ($cnt) {
1786                         for ($x = 0; $x < $cnt; $x ++) {
1787                                 if ($matches[1][$x]) {
1788                                         $ret[$matches[2][$x]] = ['#', $matches[1][$x], $matches[2][$x]];
1789                                 }
1790                         }
1791                 }
1792                 $matches = false;
1793                 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
1794                 if ($cnt) {
1795                         for ($x = 0; $x < $cnt; $x ++) {
1796                                 if ($matches[1][$x]) {
1797                                         $ret[] = ['@', $matches[1][$x], $matches[2][$x]];
1798                                 }
1799                         }
1800                 }
1801                 return $ret;
1802         }
1803
1804         public static function expire($uid, $days, $network = "", $force = false)
1805         {
1806                 if (!$uid || ($days < 1)) {
1807                         return;
1808                 }
1809
1810                 /*
1811                  * $expire_network_only = save your own wall posts
1812                  * and just expire conversations started by others
1813                  */
1814                 $expire_network_only = PConfig::get($uid,'expire', 'network_only');
1815                 $sql_extra = (intval($expire_network_only) ? " AND wall = 0 " : "");
1816
1817                 if ($network != "") {
1818                         $sql_extra .= sprintf(" AND network = '%s' ", dbesc($network));
1819
1820                         /*
1821                          * There is an index "uid_network_received" but not "uid_network_created"
1822                          * This avoids the creation of another index just for one purpose.
1823                          * And it doesn't really matter wether to look at "received" or "created"
1824                          */
1825                         $range = "AND `received` < UTC_TIMESTAMP() - INTERVAL %d DAY ";
1826                 } else {
1827                         $range = "AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY ";
1828                 }
1829
1830                 $r = q("SELECT `file`, `resource-id`, `starred`, `type`, `id` FROM `item`
1831                         WHERE `uid` = %d $range
1832                         AND `id` = `parent`
1833                         $sql_extra
1834                         AND `deleted` = 0",
1835                         intval($uid),
1836                         intval($days)
1837                 );
1838
1839                 if (!DBM::is_result($r)) {
1840                         return;
1841                 }
1842
1843                 $expire_items = PConfig::get($uid, 'expire', 'items', 1);
1844
1845                 // Forcing expiring of items - but not notes and marked items
1846                 if ($force) {
1847                         $expire_items = true;
1848                 }
1849
1850                 $expire_notes = PConfig::get($uid, 'expire', 'notes', 1);
1851                 $expire_starred = PConfig::get($uid, 'expire', 'starred', 1);
1852                 $expire_photos = PConfig::get($uid, 'expire', 'photos', 0);
1853
1854                 logger('User '.$uid.': expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
1855
1856                 foreach ($r as $item) {
1857
1858                         // don't expire filed items
1859
1860                         if (strpos($item['file'],'[') !== false) {
1861                                 continue;
1862                         }
1863
1864                         // Only expire posts, not photos and photo comments
1865
1866                         if ($expire_photos == 0 && strlen($item['resource-id'])) {
1867                                 continue;
1868                         } elseif ($expire_starred == 0 && intval($item['starred'])) {
1869                                 continue;
1870                         } elseif ($expire_notes == 0 && $item['type'] == 'note') {
1871                                 continue;
1872                         } elseif ($expire_items == 0 && $item['type'] != 'note') {
1873                                 continue;
1874                         }
1875
1876                         self::deleteById($item['id'], PRIORITY_LOW);
1877                 }
1878         }
1879
1880         public static function firstPostDate($uid, $wall = false)
1881         {
1882                 $condition = ['uid' => $uid, 'wall' => $wall, 'deleted' => false, 'visible' => true, 'moderated' => false];
1883                 $params = ['order' => ['created' => false]];
1884                 $thread = dba::selectFirst('thread', ['created'], $condition, $params);
1885                 if (DBM::is_result($thread)) {
1886                         return substr(DateTimeFormat::local($thread['created']), 0, 10);
1887                 }
1888                 return false;
1889         }
1890
1891         /**
1892          * @brief add/remove activity to an item
1893          *
1894          * Toggle activities as like,dislike,attend of an item
1895          *
1896          * @param string $item_id
1897          * @param string $verb
1898          *              Activity verb. One of
1899          *                      like, unlike, dislike, undislike, attendyes, unattendyes,
1900          *                      attendno, unattendno, attendmaybe, unattendmaybe
1901          * @hook 'post_local_end'
1902          *              array $arr
1903          *                      'post_id' => ID of posted item
1904          */
1905         public static function performLike($item_id, $verb)
1906         {
1907                 if (!local_user() && !remote_user()) {
1908                         return false;
1909                 }
1910
1911                 switch ($verb) {
1912                         case 'like':
1913                         case 'unlike':
1914                                 $bodyverb = L10n::t('%1$s likes %2$s\'s %3$s');
1915                                 $activity = ACTIVITY_LIKE;
1916                                 break;
1917                         case 'dislike':
1918                         case 'undislike':
1919                                 $bodyverb = L10n::t('%1$s doesn\'t like %2$s\'s %3$s');
1920                                 $activity = ACTIVITY_DISLIKE;
1921                                 break;
1922                         case 'attendyes':
1923                         case 'unattendyes':
1924                                 $bodyverb = L10n::t('%1$s is attending %2$s\'s %3$s');
1925                                 $activity = ACTIVITY_ATTEND;
1926                                 break;
1927                         case 'attendno':
1928                         case 'unattendno':
1929                                 $bodyverb = L10n::t('%1$s is not attending %2$s\'s %3$s');
1930                                 $activity = ACTIVITY_ATTENDNO;
1931                                 break;
1932                         case 'attendmaybe':
1933                         case 'unattendmaybe':
1934                                 $bodyverb = L10n::t('%1$s may attend %2$s\'s %3$s');
1935                                 $activity = ACTIVITY_ATTENDMAYBE;
1936                                 break;
1937                         default:
1938                                 logger('like: unknown verb ' . $verb . ' for item ' . $item_id);
1939                                 return false;
1940                 }
1941
1942                 // Enable activity toggling instead of on/off
1943                 $event_verb_flag = $activity === ACTIVITY_ATTEND || $activity === ACTIVITY_ATTENDNO || $activity === ACTIVITY_ATTENDMAYBE;
1944
1945                 logger('like: verb ' . $verb . ' item ' . $item_id);
1946
1947                 $item = dba::selectFirst('item', [], ['`id` = ? OR `uri` = ?', $item_id, $item_id]);
1948                 if (!DBM::is_result($item)) {
1949                         logger('like: unknown item ' . $item_id);
1950                         return false;
1951                 }
1952
1953                 $uid = $item['uid'];
1954                 if (($uid == 0) && local_user()) {
1955                         $uid = local_user();
1956                 }
1957
1958                 if (!can_write_wall($uid)) {
1959                         logger('like: unable to write on wall ' . $uid);
1960                         return false;
1961                 }
1962
1963                 // Retrieves the local post owner
1964                 $owner_self_contact = dba::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
1965                 if (!DBM::is_result($owner_self_contact)) {
1966                         logger('like: unknown owner ' . $uid);
1967                         return false;
1968                 }
1969
1970                 // Retrieve the current logged in user's public contact
1971                 $author_id = public_contact();
1972
1973                 $author_contact = dba::selectFirst('contact', [], ['id' => $author_id]);
1974                 if (!DBM::is_result($author_contact)) {
1975                         logger('like: unknown author ' . $author_id);
1976                         return false;
1977                 }
1978
1979                 // Contact-id is the uid-dependant author contact
1980                 if (local_user() == $uid) {
1981                         $item_contact_id = $owner_self_contact['id'];
1982                         $item_contact = $owner_self_contact;
1983                 } else {
1984                         $item_contact_id = Contact::getIdForURL($author_contact['url'], $uid, true);
1985                         $item_contact = dba::selectFirst('contact', [], ['id' => $item_contact_id]);
1986                         if (!DBM::is_result($item_contact)) {
1987                                 logger('like: unknown item contact ' . $item_contact_id);
1988                                 return false;
1989                         }
1990                 }
1991
1992                 // Look for an existing verb row
1993                 // event participation are essentially radio toggles. If you make a subsequent choice,
1994                 // we need to eradicate your first choice.
1995                 if ($event_verb_flag) {
1996                         $verbs = "'" . dbesc(ACTIVITY_ATTEND) . "', '" . dbesc(ACTIVITY_ATTENDNO) . "', '" . dbesc(ACTIVITY_ATTENDMAYBE) . "'";
1997                 } else {
1998                         $verbs = "'".dbesc($activity)."'";
1999                 }
2000
2001                 /// @todo This query is expected to be a performance eater due to the "OR" - it has to be changed totally
2002                 $existing_like = q("SELECT `id`, `guid`, `verb` FROM `item`
2003                         WHERE `verb` IN ($verbs)
2004                         AND `deleted` = 0
2005                         AND `author-id` = %d
2006                         AND `uid` = %d
2007                         AND (`parent` = '%s' OR `parent-uri` = '%s' OR `thr-parent` = '%s')
2008                         LIMIT 1",
2009                         intval($author_contact['id']),
2010                         intval($item['uid']),
2011                         dbesc($item_id), dbesc($item_id), dbesc($item['uri'])
2012                 );
2013
2014                 // If it exists, mark it as deleted
2015                 if (DBM::is_result($existing_like)) {
2016                         $like_item = $existing_like[0];
2017
2018                         // Already voted, undo it
2019                         $fields = ['deleted' => true, 'unseen' => true, 'changed' => DateTimeFormat::utcNow()];
2020                         dba::update('item', $fields, ['id' => $like_item['id']]);
2021
2022                         // Clean up the Diaspora signatures for this like
2023                         // Go ahead and do it even if Diaspora support is disabled. We still want to clean up
2024                         // if it had been enabled in the past
2025                         dba::delete('sign', ['iid' => $like_item['id']]);
2026
2027                         $like_item_id = $like_item['id'];
2028                         Worker::add(PRIORITY_HIGH, "Notifier", "like", $like_item_id);
2029
2030                         if (!$event_verb_flag || $like_item['verb'] == $activity) {
2031                                 return true;
2032                         }
2033                 }
2034
2035                 // Verb is "un-something", just trying to delete existing entries
2036                 if (strpos($verb, 'un') === 0) {
2037                         return true;
2038                 }
2039
2040                 // Else or if event verb different from existing row, create a new item row
2041                 $post_type = (($item['resource-id']) ? L10n::t('photo') : L10n::t('status'));
2042                 if ($item['object-type'] === ACTIVITY_OBJ_EVENT) {
2043                         $post_type = L10n::t('event');
2044                 }
2045                 $objtype = $item['resource-id'] ? ACTIVITY_OBJ_IMAGE : ACTIVITY_OBJ_NOTE ;
2046                 $link = xmlify('<link rel="alternate" type="text/html" href="' . System::baseUrl() . '/display/' . $owner_self_contact['nick'] . '/' . $item['id'] . '" />' . "\n") ;
2047                 $body = $item['body'];
2048
2049                 $obj = <<< EOT
2050
2051                 <object>
2052                         <type>$objtype</type>
2053                         <local>1</local>
2054                         <id>{$item['uri']}</id>
2055                         <link>$link</link>
2056                         <title></title>
2057                         <content>$body</content>
2058                 </object>
2059 EOT;
2060
2061                 $ulink = '[url=' . $author_contact['url'] . ']' . $author_contact['name'] . '[/url]';
2062                 $alink = '[url=' . $item['author-link'] . ']' . $item['author-name'] . '[/url]';
2063                 $plink = '[url=' . System::baseUrl() . '/display/' . $owner_self_contact['nick'] . '/' . $item['id'] . ']' . $post_type . '[/url]';
2064
2065                 $new_item = [
2066                         'guid'          => get_guid(32),
2067                         'uri'           => item_new_uri(self::getApp()->get_hostname(), $item['uid']),
2068                         'uid'           => $item['uid'],
2069                         'contact-id'    => $item_contact_id,
2070                         'type'          => 'activity',
2071                         'wall'          => $item['wall'],
2072                         'origin'        => 1,
2073                         'gravity'       => GRAVITY_LIKE,
2074                         'parent'        => $item['id'],
2075                         'parent-uri'    => $item['uri'],
2076                         'thr-parent'    => $item['uri'],
2077                         'owner-id'      => $item['owner-id'],
2078                         'owner-name'    => $item['owner-name'],
2079                         'owner-link'    => $item['owner-link'],
2080                         'owner-avatar'  => $item['owner-avatar'],
2081                         'author-id'     => $author_contact['id'],
2082                         'author-name'   => $author_contact['name'],
2083                         'author-link'   => $author_contact['url'],
2084                         'author-avatar' => $author_contact['thumb'],
2085                         'body'          => sprintf($bodyverb, $ulink, $alink, $plink),
2086                         'verb'          => $activity,
2087                         'object-type'   => $objtype,
2088                         'object'        => $obj,
2089                         'allow_cid'     => $item['allow_cid'],
2090                         'allow_gid'     => $item['allow_gid'],
2091                         'deny_cid'      => $item['deny_cid'],
2092                         'deny_gid'      => $item['deny_gid'],
2093                         'visible'       => 1,
2094                         'unseen'        => 1,
2095                 ];
2096
2097                 $new_item_id = self::insert($new_item);
2098
2099                 // If the parent item isn't visible then set it to visible
2100                 if (!$item['visible']) {
2101                         self::update(['visible' => true], ['id' => $item['id']]);
2102                 }
2103
2104                 // Save the author information for the like in case we need to relay to Diaspora
2105                 Diaspora::storeLikeSignature($item_contact, $new_item_id);
2106
2107                 $new_item['id'] = $new_item_id;
2108
2109                 Addon::callHooks('post_local_end', $new_item);
2110
2111                 Worker::add(PRIORITY_HIGH, "Notifier", "like", $new_item_id);
2112
2113                 return true;
2114         }
2115
2116         private static function addThread($itemid, $onlyshadow = false)
2117         {
2118                 $fields = ['uid', 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private', 'pubmail',
2119                         'moderated', 'visible', 'starred', 'bookmark', 'contact-id',
2120                         'deleted', 'origin', 'forum_mode', 'mention', 'network', 'author-id', 'owner-id'];
2121                 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
2122                 $item = dba::selectFirst('item', $fields, $condition);
2123
2124                 if (!DBM::is_result($item)) {
2125                         return;
2126                 }
2127
2128                 $item['iid'] = $itemid;
2129
2130                 if (!$onlyshadow) {
2131                         $result = dba::insert('thread', $item);
2132
2133                         logger("Add thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
2134                 }
2135         }
2136
2137         private static function updateThread($itemid, $setmention = false)
2138         {
2139                 $fields = ['uid', 'guid', 'title', 'body', 'created', 'edited', 'commented', 'received', 'changed',
2140                         'wall', 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark', 'contact-id',
2141                         'deleted', 'origin', 'forum_mode', 'network', 'author-id', 'owner-id', 'rendered-html', 'rendered-hash'];
2142                 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
2143
2144                 $item = dba::selectFirst('item', $fields, $condition);
2145                 if (!DBM::is_result($item)) {
2146                         return;
2147                 }
2148
2149                 if ($setmention) {
2150                         $item["mention"] = 1;
2151                 }
2152
2153                 $sql = "";
2154
2155                 $fields = [];
2156
2157                 foreach ($item as $field => $data) {
2158                         if (!in_array($field, ["guid", "title", "body", "rendered-html", "rendered-hash"])) {
2159                                 $fields[$field] = $data;
2160                         }
2161                 }
2162
2163                 $result = dba::update('thread', $fields, ['iid' => $itemid]);
2164
2165                 logger("Update thread for item ".$itemid." - guid ".$item["guid"]." - ".(int)$result, LOGGER_DEBUG);
2166
2167                 // Updating a shadow item entry
2168                 $items = dba::selectFirst('item', ['id'], ['guid' => $item['guid'], 'uid' => 0]);
2169
2170                 if (!DBM::is_result($items)) {
2171                         return;
2172                 }
2173
2174                 $fields = ['title' => $item['title'], 'body' => $item['body'],
2175                         'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']];
2176                 $result = dba::update('item', $fields, ['id' => $items['id']]);
2177
2178                 logger("Updating public shadow for post ".$items["id"]." - guid ".$item["guid"]." Result: ".print_r($result, true), LOGGER_DEBUG);
2179         }
2180
2181         private static function deleteThread($itemid, $itemuri = "")
2182         {
2183                 $item = dba::selectFirst('thread', ['uid'], ['iid' => $itemid]);
2184                 if (!DBM::is_result($item)) {
2185                         logger('No thread found for id '.$itemid, LOGGER_DEBUG);
2186                         return;
2187                 }
2188
2189                 // Using dba::delete at this time could delete the associated item entries
2190                 $result = dba::e("DELETE FROM `thread` WHERE `iid` = ?", $itemid);
2191
2192                 logger("deleteThread: Deleted thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
2193
2194                 if ($itemuri != "") {
2195                         $condition = ["`uri` = ? AND NOT `deleted` AND NOT (`uid` IN (?, 0))", $itemuri, $item["uid"]];
2196                         if (!dba::exists('item', $condition)) {
2197                                 dba::delete('item', ['uri' => $itemuri, 'uid' => 0]);
2198                                 logger("deleteThread: Deleted shadow for item ".$itemuri, LOGGER_DEBUG);
2199                         }
2200                 }
2201         }
2202 }