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