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