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