]> git.mxchange.org Git - friendica.git/blob - src/Protocol/OStatus.php
Merge pull request #8888 from annando/rename-keywordlist
[friendica.git] / src / Protocol / OStatus.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Protocol;
23
24 use DOMDocument;
25 use DOMXPath;
26 use Friendica\Content\PageInfo;
27 use Friendica\Content\Text\BBCode;
28 use Friendica\Content\Text\HTML;
29 use Friendica\Core\Cache\Duration;
30 use Friendica\Core\Logger;
31 use Friendica\Core\Protocol;
32 use Friendica\Database\DBA;
33 use Friendica\DI;
34 use Friendica\Model\APContact;
35 use Friendica\Model\Contact;
36 use Friendica\Model\Conversation;
37 use Friendica\Model\GContact;
38 use Friendica\Model\Item;
39 use Friendica\Model\ItemURI;
40 use Friendica\Model\Tag;
41 use Friendica\Model\User;
42 use Friendica\Network\Probe;
43 use Friendica\Util\DateTimeFormat;
44 use Friendica\Util\Images;
45 use Friendica\Util\Network;
46 use Friendica\Util\Proxy as ProxyUtils;
47 use Friendica\Util\Strings;
48 use Friendica\Util\XML;
49
50 require_once 'mod/share.php';
51 require_once 'include/api.php';
52
53 /**
54  * This class contain functions for the OStatus protocol
55  */
56 class OStatus
57 {
58         private static $itemlist;
59         private static $conv_list = [];
60
61         /**
62          * Fetches author data
63          *
64          * @param DOMXPath $xpath     The xpath object
65          * @param object   $context   The xml context of the author details
66          * @param array    $importer  user record of the importing user
67          * @param array    $contact   Called by reference, will contain the fetched contact
68          * @param bool     $onlyfetch Only fetch the header without updating the contact entries
69          *
70          * @return array Array of author related entries for the item
71          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
72          * @throws \ImagickException
73          */
74         private static function fetchAuthor(DOMXPath $xpath, $context, array $importer, array &$contact = null, $onlyfetch)
75         {
76                 $author = [];
77                 $author["author-link"] = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()', $context);
78                 $author["author-name"] = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $context);
79                 $addr = XML::getFirstNodeValue($xpath, 'atom:author/atom:email/text()', $context);
80
81                 $aliaslink = $author["author-link"];
82
83                 $alternate_item = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0);
84                 if (is_object($alternate_item)) {
85                         foreach ($alternate_item->attributes as $attributes) {
86                                 if (($attributes->name == "href") && ($attributes->textContent != "")) {
87                                         $author["author-link"] = $attributes->textContent;
88                                 }
89                         }
90                 }
91                 $author["author-id"] = Contact::getIdForURL($author["author-link"]);
92
93                 $author['contact-id'] = ($contact['id'] ?? 0) ?: $author['author-id'];
94
95                 $contact = [];
96
97 /*
98                 This here would be better, but we would get problems with contacts from the statusnet addon
99                 This is kept here as a reminder for the future
100
101                 $cid = Contact::getIdForURL($author["author-link"], $importer["uid"]);
102                 if ($cid) {
103                         $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
104                 }
105 */
106                 if ($aliaslink != '') {
107                         $condition = ["`uid` = ? AND `alias` = ? AND `network` != ? AND `rel` IN (?, ?)",
108                                         $importer["uid"], $aliaslink, Protocol::STATUSNET,
109                                         Contact::SHARING, Contact::FRIEND];
110                         $contact = DBA::selectFirst('contact', [], $condition);
111                 }
112
113                 if (!DBA::isResult($contact) && $author["author-link"] != '') {
114                         if ($aliaslink == "") {
115                                 $aliaslink = $author["author-link"];
116                         }
117
118                         $condition = ["`uid` = ? AND `nurl` IN (?, ?) AND `network` != ? AND `rel` IN (?, ?)",
119                                         $importer["uid"], Strings::normaliseLink($author["author-link"]), Strings::normaliseLink($aliaslink),
120                                         Protocol::STATUSNET, Contact::SHARING, Contact::FRIEND];
121                         $contact = DBA::selectFirst('contact', [], $condition);
122                 }
123
124                 if (!DBA::isResult($contact) && ($addr != '')) {
125                         $condition = ["`uid` = ? AND `addr` = ? AND `network` != ? AND `rel` IN (?, ?)",
126                                         $importer["uid"], $addr, Protocol::STATUSNET,
127                                         Contact::SHARING, Contact::FRIEND];
128                         $contact = DBA::selectFirst('contact', [], $condition);
129                 }
130
131                 if (DBA::isResult($contact)) {
132                         if ($contact['blocked']) {
133                                 $contact['id'] = -1;
134                         } elseif (!empty(APContact::getByURL($contact['url'], false))) {
135                                 ActivityPub\Receiver::switchContact($contact['id'], $importer['uid'], $contact['url']);
136                         }
137                         $author["contact-id"] = $contact["id"];
138                 }
139
140                 $avatarlist = [];
141                 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
142                 foreach ($avatars as $avatar) {
143                         $href = "";
144                         $width = 0;
145                         foreach ($avatar->attributes as $attributes) {
146                                 if ($attributes->name == "href") {
147                                         $href = $attributes->textContent;
148                                 }
149                                 if ($attributes->name == "width") {
150                                         $width = $attributes->textContent;
151                                 }
152                         }
153                         if ($href != "") {
154                                 $avatarlist[$width] = $href;
155                         }
156                 }
157                 if (count($avatarlist) > 0) {
158                         krsort($avatarlist);
159                         $author["author-avatar"] = Probe::fixAvatar(current($avatarlist), $author["author-link"]);
160                 }
161
162                 $displayname = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()', $context);
163                 if ($displayname != "") {
164                         $author["author-name"] = $displayname;
165                 }
166
167                 $author["owner-id"] = $author["author-id"];
168
169                 // Only update the contacts if it is an OStatus contact
170                 if (DBA::isResult($contact) && ($contact['id'] > 0) && !$onlyfetch && ($contact["network"] == Protocol::OSTATUS)) {
171
172                         // Update contact data
173                         $current = $contact;
174                         unset($current['name-date']);
175
176                         // This query doesn't seem to work
177                         // $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
178                         // if ($value != "")
179                         //      $contact["notify"] = $value;
180
181                         // This query doesn't seem to work as well - I hate these queries
182                         // $value = $xpath->query("atom:link[@rel='self' and @type='application/atom+xml']", $context)->item(0)->nodeValue;
183                         // if ($value != "")
184                         //      $contact["poll"] = $value;
185
186                         $contact['url'] = $author["author-link"];
187                         $contact['nurl'] = Strings::normaliseLink($contact['url']);
188
189                         $value = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()', $context);
190                         if ($value != "") {
191                                 $contact["alias"] = $value;
192                         }
193
194                         $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()', $context);
195                         if ($value != "") {
196                                 $contact["name"] = $value;
197                         }
198
199                         $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()', $context);
200                         if ($value != "") {
201                                 $contact["nick"] = $value;
202                         }
203
204                         $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:note/text()', $context);
205                         if ($value != "") {
206                                 $contact["about"] = HTML::toBBCode($value);
207                         }
208
209                         $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:address/poco:formatted/text()', $context);
210                         if ($value != "") {
211                                 $contact["location"] = $value;
212                         }
213
214                         $contact['name-date'] = DateTimeFormat::utcNow();
215
216                         DBA::update('contact', $contact, ['id' => $contact["id"]], $current);
217
218                         if (!empty($author["author-avatar"]) && ($author["author-avatar"] != $current['avatar'])) {
219                                 Logger::log("Update profile picture for contact ".$contact["id"], Logger::DEBUG);
220                                 Contact::updateAvatar($author["author-avatar"], $importer["uid"], $contact["id"]);
221                         }
222
223                         // Ensure that we are having this contact (with uid=0)
224                         $cid = Contact::getIdForURL($aliaslink, 0, false);
225
226                         if ($cid) {
227                                 $fields = ['url', 'nurl', 'name', 'nick', 'alias', 'about', 'location'];
228                                 $old_contact = DBA::selectFirst('contact', $fields, ['id' => $cid]);
229
230                                 // Update it with the current values
231                                 $fields = ['url' => $author["author-link"], 'name' => $contact["name"],
232                                                 'nurl' => Strings::normaliseLink($author["author-link"]),
233                                                 'nick' => $contact["nick"], 'alias' => $contact["alias"],
234                                                 'about' => $contact["about"], 'location' => $contact["location"],
235                                                 'success_update' => DateTimeFormat::utcNow(), 'last-update' => DateTimeFormat::utcNow()];
236
237                                 DBA::update('contact', $fields, ['id' => $cid], $old_contact);
238
239                                 // Update the avatar
240                                 if (!empty($author["author-avatar"])) {
241                                         Contact::updateAvatar($author["author-avatar"], 0, $cid);
242                                 }
243                         }
244
245                         $contact["generation"] = 2;
246                         $contact["hide"] = false; // OStatus contacts are never hidden
247                         if (!empty($author["author-avatar"])) {
248                                 $contact["photo"] = $author["author-avatar"];
249                         }
250                         $gcid = GContact::update($contact);
251
252                         GContact::link($gcid, $contact["uid"], $contact["id"]);
253                 } elseif (empty($contact["network"]) || ($contact["network"] != Protocol::DFRN)) {
254                         $contact = [];
255                 }
256
257                 return $author;
258         }
259
260         /**
261          * Fetches author data from a given XML string
262          *
263          * @param string $xml      The XML
264          * @param array  $importer user record of the importing user
265          *
266          * @return array Array of author related entries for the item
267          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
268          * @throws \ImagickException
269          */
270         public static function salmonAuthor($xml, array $importer)
271         {
272                 if ($xml == "") {
273                         return;
274                 }
275
276                 $doc = new DOMDocument();
277                 @$doc->loadXML($xml);
278
279                 $xpath = new DOMXPath($doc);
280                 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
281                 $xpath->registerNamespace('thr', ActivityNamespace::THREAD);
282                 $xpath->registerNamespace('georss', ActivityNamespace::GEORSS);
283                 $xpath->registerNamespace('activity', ActivityNamespace::ACTIVITY);
284                 $xpath->registerNamespace('media', ActivityNamespace::MEDIA);
285                 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
286                 $xpath->registerNamespace('ostatus', ActivityNamespace::OSTATUS);
287                 $xpath->registerNamespace('statusnet', ActivityNamespace::STATUSNET);
288
289                 $contact = ["id" => 0];
290
291                 // Fetch the first author
292                 $authordata = $xpath->query('//author')->item(0);
293                 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, true);
294                 return $author;
295         }
296
297         /**
298          * Read attributes from element
299          *
300          * @param object $element Element object
301          *
302          * @return array attributes
303          */
304         private static function readAttributes($element)
305         {
306                 $attribute = [];
307
308                 foreach ($element->attributes as $attributes) {
309                         $attribute[$attributes->name] = $attributes->textContent;
310                 }
311
312                 return $attribute;
313         }
314
315         /**
316          * Imports an XML string containing OStatus elements
317          *
318          * @param string $xml      The XML
319          * @param array  $importer user record of the importing user
320          * @param array  $contact  contact
321          * @param string $hub      Called by reference, returns the fetched hub data
322          * @return void
323          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
324          * @throws \ImagickException
325          */
326         public static function import($xml, array $importer, array &$contact, &$hub)
327         {
328                 self::process($xml, $importer, $contact, $hub);
329         }
330
331         /**
332          * Internal feed processing
333          *
334          * @param string  $xml        The XML
335          * @param array   $importer   user record of the importing user
336          * @param array   $contact    contact
337          * @param string  $hub        Called by reference, returns the fetched hub data
338          * @param boolean $stored     Is the post fresh imported or from the database?
339          * @param boolean $initialize Is it the leading post so that data has to be initialized?
340          *
341          * @return boolean Could the XML be processed?
342          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
343          * @throws \ImagickException
344          */
345         private static function process($xml, array $importer, array &$contact = null, &$hub, $stored = false, $initialize = true)
346         {
347                 if ($initialize) {
348                         self::$itemlist = [];
349                         self::$conv_list = [];
350                 }
351
352                 Logger::log('Import OStatus message for user ' . $importer['uid'], Logger::DEBUG);
353
354                 if ($xml == "") {
355                         return false;
356                 }
357                 $doc = new DOMDocument();
358                 @$doc->loadXML($xml);
359
360                 $xpath = new DOMXPath($doc);
361                 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
362                 $xpath->registerNamespace('thr', ActivityNamespace::THREAD);
363                 $xpath->registerNamespace('georss', ActivityNamespace::GEORSS);
364                 $xpath->registerNamespace('activity', ActivityNamespace::ACTIVITY);
365                 $xpath->registerNamespace('media', ActivityNamespace::MEDIA);
366                 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
367                 $xpath->registerNamespace('ostatus', ActivityNamespace::OSTATUS);
368                 $xpath->registerNamespace('statusnet', ActivityNamespace::STATUSNET);
369
370                 $hub = "";
371                 $hub_items = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0);
372                 if (is_object($hub_items)) {
373                         $hub_attributes = $hub_items->attributes;
374                         if (is_object($hub_attributes)) {
375                                 foreach ($hub_attributes as $hub_attribute) {
376                                         if ($hub_attribute->name == "href") {
377                                                 $hub = $hub_attribute->textContent;
378                                                 Logger::log("Found hub ".$hub, Logger::DEBUG);
379                                         }
380                                 }
381                         }
382                 }
383
384                 $header = [];
385                 $header["uid"] = $importer["uid"];
386                 $header["network"] = Protocol::OSTATUS;
387                 $header["wall"] = 0;
388                 $header["origin"] = 0;
389                 $header["gravity"] = GRAVITY_COMMENT;
390
391                 if (!is_object($doc->firstChild) || empty($doc->firstChild->tagName)) {
392                         return false;
393                 }
394
395                 $first_child = $doc->firstChild->tagName;
396
397                 if ($first_child == "feed") {
398                         $entries = $xpath->query('/atom:feed/atom:entry');
399                 } else {
400                         $entries = $xpath->query('/atom:entry');
401                 }
402
403                 if ($entries->length == 1) {
404                         // We reformat the XML to make it better readable
405                         $doc2 = new DOMDocument();
406                         $doc2->loadXML($xml);
407                         $doc2->preserveWhiteSpace = false;
408                         $doc2->formatOutput = true;
409                         $xml2 = $doc2->saveXML();
410
411                         $header["protocol"] = Conversation::PARCEL_SALMON;
412                         $header["source"] = $xml2;
413                 } elseif (!$initialize) {
414                         return false;
415                 }
416
417                 // Fetch the first author
418                 $authordata = $xpath->query('//author')->item(0);
419                 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, $stored);
420
421                 // Reverse the order of the entries
422                 $entrylist = [];
423
424                 foreach ($entries as $entry) {
425                         $entrylist[] = $entry;
426                 }
427
428                 foreach (array_reverse($entrylist) as $entry) {
429                         // fetch the author
430                         $authorelement = $xpath->query('/atom:entry/atom:author', $entry);
431
432                         if ($authorelement->length == 0) {
433                                 $authorelement = $xpath->query('atom:author', $entry);
434                         }
435
436                         if ($authorelement->length > 0) {
437                                 $author = self::fetchAuthor($xpath, $entry, $importer, $contact, $stored);
438                         }
439
440                         $item = array_merge($header, $author);
441
442                         $item["uri"] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
443                         $item['uri-id'] = ItemURI::insert(['uri' => $item['uri']]);
444
445                         $item["verb"] = XML::getFirstNodeValue($xpath, 'activity:verb/text()', $entry);
446
447                         // Delete a message
448                         if (in_array($item["verb"], ['qvitter-delete-notice', Activity::DELETE, 'delete'])) {
449                                 self::deleteNotice($item);
450                                 continue;
451                         }
452
453                         if (in_array($item["verb"], [Activity::O_UNFAVOURITE, Activity::UNFAVORITE])) {
454                                 // Ignore "Unfavorite" message
455                                 Logger::log("Ignore unfavorite message ".print_r($item, true), Logger::DEBUG);
456                                 continue;
457                         }
458
459                         // Deletions come with the same uri, so we check for duplicates after processing deletions
460                         if (Item::exists(['uid' => $importer["uid"], 'uri' => $item["uri"]])) {
461                                 Logger::log('Post with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', Logger::DEBUG);
462                                 continue;
463                         } else {
464                                 Logger::log('Processing post with URI '.$item["uri"].' for user '.$importer["uid"].'.', Logger::DEBUG);
465                         }
466
467                         if ($item["verb"] == Activity::JOIN) {
468                                 // ignore "Join" messages
469                                 Logger::log("Ignore join message ".print_r($item, true), Logger::DEBUG);
470                                 continue;
471                         }
472
473                         if ($item["verb"] == "http://mastodon.social/schema/1.0/block") {
474                                 // ignore mastodon "block" messages
475                                 Logger::log("Ignore block message ".print_r($item, true), Logger::DEBUG);
476                                 continue;
477                         }
478
479                         if ($item["verb"] == Activity::FOLLOW) {
480                                 Contact::addRelationship($importer, $contact, $item);
481                                 continue;
482                         }
483
484                         if ($item["verb"] == Activity::O_UNFOLLOW) {
485                                 $dummy = null;
486                                 Contact::removeFollower($importer, $contact, $item, $dummy);
487                                 continue;
488                         }
489
490                         if ($item["verb"] == Activity::FAVORITE) {
491                                 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
492                                 Logger::log("Favorite ".$orig_uri." ".print_r($item, true));
493
494                                 $item["verb"] = Activity::LIKE;
495                                 $item["parent-uri"] = $orig_uri;
496                                 $item["gravity"] = GRAVITY_ACTIVITY;
497                                 $item["object-type"] = Activity\ObjectType::NOTE;
498                         }
499
500                         // http://activitystrea.ms/schema/1.0/rsvp-yes
501                         if (!in_array($item["verb"], [Activity::POST, Activity::LIKE, Activity::SHARE])) {
502                                 Logger::log("Unhandled verb ".$item["verb"]." ".print_r($item, true), Logger::DEBUG);
503                         }
504
505                         self::processPost($xpath, $entry, $item, $importer);
506
507                         if ($initialize && (count(self::$itemlist) > 0)) {
508                                 if (self::$itemlist[0]['uri'] == self::$itemlist[0]['parent-uri']) {
509                                         // We will import it everytime, when it is started by our contacts
510                                         $valid = Contact::isSharingByURL(self::$itemlist[0]['author-link'], self::$itemlist[0]['uid']);
511
512                                         if (!$valid) {
513                                                 // If not, then it depends on this setting
514                                                 $valid = ((self::$itemlist[0]['uid'] == 0) || !DI::pConfig()->get(self::$itemlist[0]['uid'], 'system', 'accept_only_sharer', false));
515                                                 if ($valid) {
516                                                         Logger::log("Item with uri ".self::$itemlist[0]['uri']." will be imported due to the system settings.", Logger::DEBUG);
517                                                 }
518                                         } else {
519                                                 Logger::log("Item with uri ".self::$itemlist[0]['uri']." belongs to a contact (".self::$itemlist[0]['contact-id']."). It will be imported.", Logger::DEBUG);
520                                         }
521                                         if ($valid) {
522                                                 // Never post a thread when the only interaction by our contact was a like
523                                                 $valid = false;
524                                                 $verbs = [Activity::POST, Activity::SHARE];
525                                                 foreach (self::$itemlist as $item) {
526                                                         if (in_array($item['verb'], $verbs) && Contact::isSharingByURL($item['author-link'], $item['uid'])) {
527                                                                 $valid = true;
528                                                         }
529                                                 }
530                                                 if ($valid) {
531                                                         Logger::log("Item with uri ".self::$itemlist[0]['uri']." will be imported since the thread contains posts or shares.", Logger::DEBUG);
532                                                 }
533                                         }
534                                 } else {
535                                         // But we will only import complete threads
536                                         $valid = Item::exists(['uid' => $importer["uid"], 'uri' => self::$itemlist[0]['parent-uri']]);
537                                         if ($valid) {
538                                                 Logger::log("Item with uri ".self::$itemlist[0]["uri"]." belongs to parent ".self::$itemlist[0]['parent-uri']." of user ".$importer["uid"].". It will be imported.", Logger::DEBUG);
539                                         }
540                                 }
541
542                                 if ($valid) {
543                                         $default_contact = 0;
544                                         for ($key = count(self::$itemlist) - 1; $key >= 0; $key--) {
545                                                 if (empty(self::$itemlist[$key]['contact-id'])) {
546                                                         self::$itemlist[$key]['contact-id'] = $default_contact;
547                                                 } else {
548                                                         $default_contact = $item['contact-id'];
549                                                 }
550                                         }
551                                         foreach (self::$itemlist as $item) {
552                                                 $found = Item::exists(['uid' => $importer["uid"], 'uri' => $item["uri"]]);
553                                                 if ($found) {
554                                                         Logger::log("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already exists.", Logger::DEBUG);
555                                                 } elseif ($item['contact-id'] < 0) {
556                                                         Logger::log("Item with uri ".$item["uri"]." is from a blocked contact.", Logger::DEBUG);
557                                                 } else {
558                                                         // We are having duplicated entries. Hopefully this solves it.
559                                                         if (DI::lock()->acquire('ostatus_process_item_insert')) {
560                                                                 $ret = Item::insert($item);
561                                                                 DI::lock()->release('ostatus_process_item_insert');
562                                                                 Logger::log("Item with uri ".$item["uri"]." for user ".$importer["uid"].' stored. Return value: '.$ret);
563                                                         } else {
564                                                                 $ret = Item::insert($item);
565                                                                 Logger::log("We couldn't lock - but tried to store the item anyway. Return value is ".$ret);
566                                                         }
567                                                 }
568                                         }
569                                 }
570                                 self::$itemlist = [];
571                         }
572                         Logger::log('Processing done for post with URI '.$item["uri"].' for user '.$importer["uid"].'.', Logger::DEBUG);
573                 }
574                 return true;
575         }
576
577         /**
578          * Removes notice item from database
579          *
580          * @param array $item item
581          * @return void
582          * @throws \Exception
583          */
584         private static function deleteNotice(array $item)
585         {
586                 $condition = ['uid' => $item['uid'], 'author-id' => $item['author-id'], 'uri' => $item['uri']];
587                 if (!Item::exists($condition)) {
588                         Logger::log('Item from '.$item['author-link'].' with uri '.$item['uri'].' for user '.$item['uid']." wasn't found. We don't delete it.");
589                         return;
590                 }
591
592                 Item::markForDeletion($condition);
593
594                 Logger::log('Deleted item with uri '.$item['uri'].' for user '.$item['uid']);
595         }
596
597         /**
598          * Processes the XML for a post
599          *
600          * @param DOMXPath $xpath    The xpath object
601          * @param object   $entry    The xml entry that is processed
602          * @param array    $item     The item array
603          * @param array    $importer user record of the importing user
604          * @return void
605          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
606          * @throws \ImagickException
607          */
608         private static function processPost(DOMXPath $xpath, $entry, array &$item, array $importer)
609         {
610                 $item["body"] = HTML::toBBCode(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
611                 $item["object-type"] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $entry);
612                 if (($item["object-type"] == Activity\ObjectType::BOOKMARK) || ($item["object-type"] == Activity\ObjectType::EVENT)) {
613                         $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
614                         $item["body"] = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry);
615                 } elseif ($item["object-type"] == Activity\ObjectType::QUESTION) {
616                         $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
617                 }
618
619                 $item["created"] = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
620                 $item["edited"] = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
621                 $item['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
622
623                 $conv = $xpath->query('ostatus:conversation', $entry);
624                 if (is_object($conv->item(0))) {
625                         foreach ($conv->item(0)->attributes as $attributes) {
626                                 if ($attributes->name == "ref") {
627                                         $item['conversation-uri'] = $attributes->textContent;
628                                 }
629                                 if ($attributes->name == "href") {
630                                         $item['conversation-href'] = $attributes->textContent;
631                                 }
632                         }
633                 }
634
635                 $related = "";
636
637                 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
638                 if (is_object($inreplyto->item(0))) {
639                         foreach ($inreplyto->item(0)->attributes as $attributes) {
640                                 if ($attributes->name == "ref") {
641                                         $item["parent-uri"] = $attributes->textContent;
642                                 }
643                                 if ($attributes->name == "href") {
644                                         $related = $attributes->textContent;
645                                 }
646                         }
647                 }
648
649                 $georsspoint = $xpath->query('georss:point', $entry);
650                 if (!empty($georsspoint) && ($georsspoint->length > 0)) {
651                         $item["coord"] = $georsspoint->item(0)->nodeValue;
652                 }
653
654                 $categories = $xpath->query('atom:category', $entry);
655                 if ($categories) {
656                         foreach ($categories as $category) {
657                                 foreach ($category->attributes as $attributes) {
658                                         if ($attributes->name == 'term') {
659                                                 // Store the hashtag
660                                                 Tag::store($item['uri-id'], Tag::HASHTAG, $attributes->textContent);
661                                         }
662                                 }
663                         }
664                 }
665
666                 $self = '';
667                 $add_body = '';
668
669                 $links = $xpath->query('atom:link', $entry);
670                 if ($links) {
671                         $link_data = self::processLinks($links, $item);
672                         $self = $link_data['self'];
673                         $add_body = $link_data['add_body'];
674                 }
675
676                 $repeat_of = "";
677
678                 $notice_info = $xpath->query('statusnet:notice_info', $entry);
679                 if ($notice_info && ($notice_info->length > 0)) {
680                         foreach ($notice_info->item(0)->attributes as $attributes) {
681                                 if ($attributes->name == "source") {
682                                         $item["app"] = strip_tags($attributes->textContent);
683                                 }
684                                 if ($attributes->name == "repeat_of") {
685                                         $repeat_of = $attributes->textContent;
686                                 }
687                         }
688                 }
689                 // Is it a repeated post?
690                 if (($repeat_of != "") || ($item["verb"] == Activity::SHARE)) {
691                         $link_data = self::processRepeatedItem($xpath, $entry, $item, $importer);
692                         if (!empty($link_data['add_body'])) {
693                                 $add_body .= $link_data['add_body'];
694                         }
695                 }
696
697                 $item["body"] .= $add_body;
698
699                 // Only add additional data when there is no picture in the post
700                 if (!strstr($item["body"], '[/img]')) {
701                         $item["body"] = PageInfo::appendToBody($item["body"]);
702                 }
703
704                 Tag::storeFromBody($item['uri-id'], $item['body']);
705
706                 // Mastodon Content Warning
707                 if (($item["verb"] == Activity::POST) && $xpath->evaluate('boolean(atom:summary)', $entry)) {
708                         $clear_text = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry);
709                         if (!empty($clear_text)) {
710                                 $item['content-warning'] = HTML::toBBCode($clear_text);
711                         }
712                 }
713
714                 if (($self != '') && empty($item['protocol'])) {
715                         self::fetchSelf($self, $item);
716                 }
717
718                 if (!empty($item["conversation-href"])) {
719                         self::fetchConversation($item['conversation-href'], $item['conversation-uri']);
720                 }
721
722                 if (isset($item["parent-uri"])) {
723                         if (!Item::exists(['uid' => $importer["uid"], 'uri' => $item['parent-uri']])) {
724                                 if ($related != '') {
725                                         self::fetchRelated($related, $item["parent-uri"], $importer);
726                                 }
727                         } else {
728                                 Logger::log('Reply with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', Logger::DEBUG);
729                         }
730                 } else {
731                         $item["parent-uri"] = $item["uri"];
732                         $item["gravity"] = GRAVITY_PARENT;
733                 }
734
735                 if (($item['author-link'] != '') && !empty($item['protocol'])) {
736                         $item = Conversation::insert($item);
737                 }
738
739                 self::$itemlist[] = $item;
740         }
741
742         /**
743          * Fetch the conversation for posts
744          *
745          * @param string $conversation     The link to the conversation
746          * @param string $conversation_uri The conversation in "uri" format
747          * @return void
748          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
749          */
750         private static function fetchConversation($conversation, $conversation_uri)
751         {
752                 // Ensure that we only store a conversation once in a process
753                 if (isset(self::$conv_list[$conversation])) {
754                         return;
755                 }
756
757                 self::$conv_list[$conversation] = true;
758
759                 $curlResult = Network::curl($conversation, false, ['accept_content' => 'application/atom+xml, text/html']);
760
761                 if (!$curlResult->isSuccess()) {
762                         return;
763                 }
764
765                 $xml = '';
766
767                 if (stristr($curlResult->getHeader(), 'Content-Type: application/atom+xml')) {
768                         $xml = $curlResult->getBody();
769                 }
770
771                 if ($xml == '') {
772                         $doc = new DOMDocument();
773                         if (!@$doc->loadHTML($curlResult->getBody())) {
774                                 return;
775                         }
776                         $xpath = new DOMXPath($doc);
777
778                         $links = $xpath->query('//link');
779                         if ($links) {
780                                 $file = '';
781                                 foreach ($links as $link) {
782                                         $attribute = self::readAttributes($link);
783                                         if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
784                                                 $file = $attribute['href'];
785                                         }
786                                 }
787                                 if ($file != '') {
788                                         $conversation_atom = Network::curl($attribute['href']);
789
790                                         if ($conversation_atom->isSuccess()) {
791                                                 $xml = $conversation_atom->getBody();
792                                         }
793                                 }
794                         }
795                 }
796
797                 if ($xml == '') {
798                         return;
799                 }
800
801                 self::storeConversation($xml, $conversation, $conversation_uri);
802         }
803
804         /**
805          * Store a feed in several conversation entries
806          *
807          * @param string $xml              The feed
808          * @param string $conversation     conversation
809          * @param string $conversation_uri conversation uri
810          * @return void
811          * @throws \Exception
812          */
813         private static function storeConversation($xml, $conversation = '', $conversation_uri = '')
814         {
815                 $doc = new DOMDocument();
816                 @$doc->loadXML($xml);
817
818                 $xpath = new DOMXPath($doc);
819                 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
820                 $xpath->registerNamespace('thr', ActivityNamespace::THREAD);
821                 $xpath->registerNamespace('ostatus', ActivityNamespace::OSTATUS);
822
823                 $entries = $xpath->query('/atom:feed/atom:entry');
824
825                 // Now store the entries
826                 foreach ($entries as $entry) {
827                         $doc2 = new DOMDocument();
828                         $doc2->preserveWhiteSpace = false;
829                         $doc2->formatOutput = true;
830
831                         $conv_data = [];
832
833                         $conv_data['protocol'] = Conversation::PARCEL_SPLIT_CONVERSATION;
834                         $conv_data['network'] = Protocol::OSTATUS;
835                         $conv_data['uri'] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
836
837                         $inreplyto = $xpath->query('thr:in-reply-to', $entry);
838                         if (is_object($inreplyto->item(0))) {
839                                 foreach ($inreplyto->item(0)->attributes as $attributes) {
840                                         if ($attributes->name == "ref") {
841                                                 $conv_data['reply-to-uri'] = $attributes->textContent;
842                                         }
843                                 }
844                         }
845
846                         $conv_data['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
847
848                         $conv = $xpath->query('ostatus:conversation', $entry);
849                         if (is_object($conv->item(0))) {
850                                 foreach ($conv->item(0)->attributes as $attributes) {
851                                         if ($attributes->name == "ref") {
852                                                 $conv_data['conversation-uri'] = $attributes->textContent;
853                                         }
854                                         if ($attributes->name == "href") {
855                                                 $conv_data['conversation-href'] = $attributes->textContent;
856                                         }
857                                 }
858                         }
859
860                         if ($conversation != '') {
861                                 $conv_data['conversation-uri'] = $conversation;
862                         }
863
864                         if ($conversation_uri != '') {
865                                 $conv_data['conversation-uri'] = $conversation_uri;
866                         }
867
868                         $entry = $doc2->importNode($entry, true);
869
870                         $doc2->appendChild($entry);
871
872                         $conv_data['source'] = $doc2->saveXML();
873
874                         $condition = ['item-uri' => $conv_data['uri'],'protocol' => Conversation::PARCEL_FEED];
875                         if (DBA::exists('conversation', $condition)) {
876                                 Logger::log('Delete deprecated entry for URI '.$conv_data['uri'], Logger::DEBUG);
877                                 DBA::delete('conversation', ['item-uri' => $conv_data['uri']]);
878                         }
879
880                         Logger::log('Store conversation data for uri '.$conv_data['uri'], Logger::DEBUG);
881                         Conversation::insert($conv_data);
882                 }
883         }
884
885         /**
886          * Fetch the own post so that it can be stored later
887          *
888          * We want to store the original data for later processing.
889          * This function is meant for cases where we process a feed with multiple entries.
890          * In that case we need to fetch the single posts here.
891          *
892          * @param string $self The link to the self item
893          * @param array  $item The item array
894          * @return void
895          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
896          */
897         private static function fetchSelf($self, array &$item)
898         {
899                 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $self, Conversation::PARCEL_DFRN, Conversation::PARCEL_SALMON];
900                 if (DBA::exists('conversation', $condition)) {
901                         Logger::log('Conversation '.$item['uri'].' is already stored.', Logger::DEBUG);
902                         return;
903                 }
904
905                 $curlResult = Network::curl($self);
906
907                 if (!$curlResult->isSuccess()) {
908                         return;
909                 }
910
911                 // We reformat the XML to make it better readable
912                 $doc = new DOMDocument();
913                 $doc->loadXML($curlResult->getBody());
914                 $doc->preserveWhiteSpace = false;
915                 $doc->formatOutput = true;
916                 $xml = $doc->saveXML();
917
918                 $item["protocol"] = Conversation::PARCEL_SALMON;
919                 $item["source"] = $xml;
920
921                 Logger::log('Conversation '.$item['uri'].' is now fetched.', Logger::DEBUG);
922         }
923
924         /**
925          * Fetch related posts and processes them
926          *
927          * @param string $related     The link to the related item
928          * @param string $related_uri The related item in "uri" format
929          * @param array  $importer    user record of the importing user
930          * @return void
931          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
932          * @throws \ImagickException
933          */
934         private static function fetchRelated($related, $related_uri, $importer)
935         {
936                 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $related_uri, Conversation::PARCEL_DFRN, Conversation::PARCEL_SALMON];
937                 $conversation = DBA::selectFirst('conversation', ['source', 'protocol'], $condition);
938                 if (DBA::isResult($conversation)) {
939                         $stored = true;
940                         $xml = $conversation['source'];
941                         if (self::process($xml, $importer, $contact, $hub, $stored, false)) {
942                                 Logger::log('Got valid cached XML for URI '.$related_uri, Logger::DEBUG);
943                                 return;
944                         }
945                         if ($conversation['protocol'] == Conversation::PARCEL_SALMON) {
946                                 Logger::log('Delete invalid cached XML for URI '.$related_uri, Logger::DEBUG);
947                                 DBA::delete('conversation', ['item-uri' => $related_uri]);
948                         }
949                 }
950
951                 $stored = false;
952                 $curlResult = Network::curl($related, false, ['accept_content' => 'application/atom+xml, text/html']);
953
954                 if (!$curlResult->isSuccess()) {
955                         return;
956                 }
957
958                 $xml = '';
959
960                 if (stristr($curlResult->getHeader(), 'Content-Type: application/atom+xml')) {
961                         Logger::log('Directly fetched XML for URI ' . $related_uri, Logger::DEBUG);
962                         $xml = $curlResult->getBody();
963                 }
964
965                 if ($xml == '') {
966                         $doc = new DOMDocument();
967                         if (!@$doc->loadHTML($curlResult->getBody())) {
968                                 return;
969                         }
970                         $xpath = new DOMXPath($doc);
971
972                         $atom_file = '';
973
974                         $links = $xpath->query('//link');
975                         if ($links) {
976                                 foreach ($links as $link) {
977                                         $attribute = self::readAttributes($link);
978                                         if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
979                                                 $atom_file = $attribute['href'];
980                                         }
981                                 }
982                                 if ($atom_file != '') {
983                                         $curlResult = Network::curl($atom_file);
984
985                                         if ($curlResult->isSuccess()) {
986                                                 Logger::log('Fetched XML for URI ' . $related_uri, Logger::DEBUG);
987                                                 $xml = $curlResult->getBody();
988                                         }
989                                 }
990                         }
991                 }
992
993                 // Workaround for older GNU Social servers
994                 if (($xml == '') && strstr($related, '/notice/')) {
995                         $curlResult = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related).'.atom');
996
997                         if ($curlResult->isSuccess()) {
998                                 Logger::log('GNU Social workaround to fetch XML for URI ' . $related_uri, Logger::DEBUG);
999                                 $xml = $curlResult->getBody();
1000                         }
1001                 }
1002
1003                 // Even more worse workaround for GNU Social ;-)
1004                 if ($xml == '') {
1005                         $related_guess = self::convertHref($related_uri);
1006                         $curlResult = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related_guess).'.atom');
1007
1008                         if ($curlResult->isSuccess()) {
1009                                 Logger::log('GNU Social workaround 2 to fetch XML for URI ' . $related_uri, Logger::DEBUG);
1010                                 $xml = $curlResult->getBody();
1011                         }
1012                 }
1013
1014                 // Finally we take the data that we fetched from "ostatus:conversation"
1015                 if ($xml == '') {
1016                         $condition = ['item-uri' => $related_uri, 'protocol' => Conversation::PARCEL_SPLIT_CONVERSATION];
1017                         $conversation = DBA::selectFirst('conversation', ['source'], $condition);
1018                         if (DBA::isResult($conversation)) {
1019                                 $stored = true;
1020                                 Logger::log('Got cached XML from conversation for URI '.$related_uri, Logger::DEBUG);
1021                                 $xml = $conversation['source'];
1022                         }
1023                 }
1024
1025                 if ($xml != '') {
1026                         self::process($xml, $importer, $contact, $hub, $stored, false);
1027                 } else {
1028                         Logger::log("XML couldn't be fetched for URI: ".$related_uri." - href: ".$related, Logger::DEBUG);
1029                 }
1030                 return;
1031         }
1032
1033         /**
1034          * Processes the XML for a repeated post
1035          *
1036          * @param DOMXPath $xpath    The xpath object
1037          * @param object   $entry    The xml entry that is processed
1038          * @param array    $item     The item array
1039          * @param array    $importer user record of the importing user
1040          *
1041          * @return array with data from links
1042          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1043          * @throws \ImagickException
1044          */
1045         private static function processRepeatedItem(DOMXPath $xpath, $entry, array &$item, array $importer)
1046         {
1047                 $activityobject = $xpath->query('activity:object', $entry)->item(0);
1048
1049                 if (!is_object($activityobject)) {
1050                         return [];
1051                 }
1052
1053                 $link_data = [];
1054
1055                 $orig_uri = XML::getFirstNodeValue($xpath, 'atom:id/text()', $activityobject);
1056
1057                 $links = $xpath->query("atom:link", $activityobject);
1058                 if ($links) {
1059                         $link_data = self::processLinks($links, $item);
1060                 }
1061
1062                 $orig_body = XML::getFirstNodeValue($xpath, 'atom:content/text()', $activityobject);
1063                 $orig_created = XML::getFirstNodeValue($xpath, 'atom:published/text()', $activityobject);
1064                 $orig_edited = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $activityobject);
1065
1066                 $orig_author = self::fetchAuthor($xpath, $activityobject, $importer, $dummy, false);
1067
1068                 $item["author-name"] = $orig_author["author-name"];
1069                 $item["author-link"] = $orig_author["author-link"];
1070                 $item["author-id"] = $orig_author["author-id"];
1071
1072                 $item["body"] = HTML::toBBCode($orig_body);
1073                 $item["created"] = $orig_created;
1074                 $item["edited"] = $orig_edited;
1075
1076                 $item["uri"] = $orig_uri;
1077
1078                 $item["verb"] = XML::getFirstNodeValue($xpath, 'activity:verb/text()', $activityobject);
1079
1080                 $item["object-type"] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $activityobject);
1081
1082                 // Mastodon Content Warning
1083                 if (($item["verb"] == Activity::POST) && $xpath->evaluate('boolean(atom:summary)', $activityobject)) {
1084                         $clear_text = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $activityobject);
1085                         if (!empty($clear_text)) {
1086                                 $item['content-warning'] = HTML::toBBCode($clear_text);
1087                         }
1088                 }
1089
1090                 $inreplyto = $xpath->query('thr:in-reply-to', $activityobject);
1091                 if (is_object($inreplyto->item(0))) {
1092                         foreach ($inreplyto->item(0)->attributes as $attributes) {
1093                                 if ($attributes->name == "ref") {
1094                                         $item["parent-uri"] = $attributes->textContent;
1095                                 }
1096                         }
1097                 }
1098
1099                 return $link_data;
1100         }
1101
1102         /**
1103          * Processes links in the XML
1104          *
1105          * @param object $links The xml data that contain links
1106          * @param array  $item  The item array
1107          *
1108          * @return array with data from the links
1109          */
1110         private static function processLinks($links, array &$item)
1111         {
1112                 $link_data = ['add_body' => '', 'self' => ''];
1113
1114                 foreach ($links as $link) {
1115                         $attribute = self::readAttributes($link);
1116
1117                         if (!empty($attribute['rel']) && !empty($attribute['href'])) {
1118                                 switch ($attribute['rel']) {
1119                                         case "alternate":
1120                                                 $item["plink"] = $attribute['href'];
1121                                                 if (($item["object-type"] == Activity\ObjectType::QUESTION)
1122                                                         || ($item["object-type"] == Activity\ObjectType::EVENT)
1123                                                 ) {
1124                                                         $item["body"] .= "\n" . PageInfo::getFooterFromUrl($attribute['href']);
1125                                                 }
1126                                                 break;
1127                                         case "ostatus:conversation":
1128                                                 $link_data['conversation'] = $attribute['href'];
1129                                                 $item['conversation-href'] = $link_data['conversation'];
1130                                                 if (!isset($item['conversation-uri'])) {
1131                                                         $item['conversation-uri'] = $item['conversation-href'];
1132                                                 }
1133                                                 break;
1134                                         case "enclosure":
1135                                                 $filetype = strtolower(substr($attribute['type'], 0, strpos($attribute['type'], '/')));
1136                                                 if ($filetype == 'image') {
1137                                                         $link_data['add_body'] .= "\n[img]".$attribute['href'].'[/img]';
1138                                                 } else {
1139                                                         if (!empty($item["attach"])) {
1140                                                                 $item["attach"] .= ',';
1141                                                         } else {
1142                                                                 $item["attach"] = '';
1143                                                         }
1144                                                         if (!isset($attribute['length'])) {
1145                                                                 $attribute['length'] = "0";
1146                                                         }
1147                                                         $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.($attribute['title'] ?? '') .'"[/attach]';
1148                                                 }
1149                                                 break;
1150                                         case "related":
1151                                                 if ($item["object-type"] != Activity\ObjectType::BOOKMARK) {
1152                                                         if (!isset($item["parent-uri"])) {
1153                                                                 $item["parent-uri"] = $attribute['href'];
1154                                                         }
1155                                                         $link_data['related'] = $attribute['href'];
1156                                                 } else {
1157                                                         $item["body"] .= "\n" . PageInfo::getFooterFromUrl($attribute['href']);
1158                                                 }
1159                                                 break;
1160                                         case "self":
1161                                                 if (empty($item["plink"])) {
1162                                                         $item["plink"] = $attribute['href'];
1163                                                 }
1164                                                 $link_data['self'] = $attribute['href'];
1165                                                 break;
1166                                 }
1167                         }
1168                 }
1169                 return $link_data;
1170         }
1171
1172         /**
1173          * Create an url out of an uri
1174          *
1175          * @param string $href URI in the format "parameter1:parameter1:..."
1176          *
1177          * @return string URL in the format http(s)://....
1178          */
1179         private static function convertHref($href)
1180         {
1181                 $elements = explode(":", $href);
1182
1183                 if ((count($elements) <= 2) || ($elements[0] != "tag")) {
1184                         return $href;
1185                 }
1186
1187                 $server = explode(",", $elements[1]);
1188                 $conversation = explode("=", $elements[2]);
1189
1190                 if ((count($elements) == 4) && ($elements[2] == "post")) {
1191                         return "http://".$server[0]."/notice/".$elements[3];
1192                 }
1193
1194                 if ((count($conversation) != 2) || ($conversation[1] =="")) {
1195                         return $href;
1196                 }
1197                 if ($elements[3] == "objectType=thread") {
1198                         return "http://".$server[0]."/conversation/".$conversation[1];
1199                 } else {
1200                         return "http://".$server[0]."/notice/".$conversation[1];
1201                 }
1202         }
1203
1204         /**
1205          * Checks if the current post is a reshare
1206          *
1207          * @param array $item The item array of thw post
1208          *
1209          * @return string The guid if the post is a reshare
1210          */
1211         private static function getResharedGuid(array $item)
1212         {
1213                 $reshared = Item::getShareArray($item);
1214                 if (empty($reshared['guid']) || !empty($reshared['comment'])) {
1215                         return '';
1216                 }
1217
1218                 return $reshared['guid'];
1219         }
1220
1221         /**
1222          * Cleans the body of a post if it contains picture links
1223          *
1224          * @param string $body The body
1225          *
1226          * @return string The cleaned body
1227          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1228          */
1229         private static function formatPicturePost($body)
1230         {
1231                 $siteinfo = BBCode::getAttachedData($body);
1232
1233                 if (($siteinfo["type"] == "photo") && (!empty($siteinfo["preview"]) || !empty($siteinfo["image"]))) {
1234                         if (isset($siteinfo["preview"])) {
1235                                 $preview = $siteinfo["preview"];
1236                         } else {
1237                                 $preview = $siteinfo["image"];
1238                         }
1239
1240                         // Is it a remote picture? Then make a smaller preview here
1241                         $preview = ProxyUtils::proxifyUrl($preview, false, ProxyUtils::SIZE_SMALL);
1242
1243                         // Is it a local picture? Then make it smaller here
1244                         $preview = str_replace(["-0.jpg", "-0.png"], ["-2.jpg", "-2.png"], $preview);
1245                         $preview = str_replace(["-1.jpg", "-1.png"], ["-2.jpg", "-2.png"], $preview);
1246
1247                         if (isset($siteinfo["url"])) {
1248                                 $url = $siteinfo["url"];
1249                         } else {
1250                                 $url = $siteinfo["image"];
1251                         }
1252
1253                         $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1254                 }
1255
1256                 return $body;
1257         }
1258
1259         /**
1260          * Adds the header elements to the XML document
1261          *
1262          * @param DOMDocument $doc       XML document
1263          * @param array       $owner     Contact data of the poster
1264          * @param string      $filter    The related feed filter (activity, posts or comments)
1265          * @param bool        $feed_mode Behave like a regular feed for users if true
1266          *
1267          * @return object header root element
1268          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1269          */
1270         private static function addHeader(DOMDocument $doc, array $owner, $filter, $feed_mode = false)
1271         {
1272                 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
1273                 $doc->appendChild($root);
1274
1275                 if (!$feed_mode) {
1276                         $root->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
1277                         $root->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
1278                         $root->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
1279                         $root->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
1280                         $root->setAttribute("xmlns:poco", ActivityNamespace::POCO);
1281                         $root->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
1282                         $root->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
1283                         $root->setAttribute("xmlns:mastodon", ActivityNamespace::MASTODON);
1284                 }
1285
1286                 $title = '';
1287                 $selfUri = '/feed/' . $owner["nick"] . '/';
1288                 switch ($filter) {
1289                         case 'activity':
1290                                 $title = DI::l10n()->t('%s\'s timeline', $owner['name']);
1291                                 $selfUri .= $filter;
1292                                 break;
1293                         case 'posts':
1294                                 $title = DI::l10n()->t('%s\'s posts', $owner['name']);
1295                                 break;
1296                         case 'comments':
1297                                 $title = DI::l10n()->t('%s\'s comments', $owner['name']);
1298                                 $selfUri .= $filter;
1299                                 break;
1300                 }
1301
1302                 if (!$feed_mode) {
1303                         $selfUri = "/dfrn_poll/" . $owner["nick"];
1304                 }
1305
1306                 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION . "-" . DB_UPDATE_VERSION];
1307                 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1308                 XML::addElement($doc, $root, "id", DI::baseUrl() . "/profile/" . $owner["nick"]);
1309                 XML::addElement($doc, $root, "title", $title);
1310                 XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], DI::config()->get('config', 'sitename')));
1311                 XML::addElement($doc, $root, "logo", $owner["photo"]);
1312                 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
1313
1314                 $author = self::addAuthor($doc, $owner, true, $feed_mode);
1315                 $root->appendChild($author);
1316
1317                 $attributes = ["href" => $owner["url"], "rel" => "alternate", "type" => "text/html"];
1318                 XML::addElement($doc, $root, "link", "", $attributes);
1319
1320                 /// @TODO We have to find out what this is
1321                 /// $attributes = array("href" => DI::baseUrl()."/sup",
1322                 ///             "rel" => "http://api.friendfeed.com/2008/03#sup",
1323                 ///             "type" => "application/json");
1324                 /// XML::addElement($doc, $root, "link", "", $attributes);
1325
1326                 self::hublinks($doc, $root, $owner["nick"]);
1327
1328                 if (!$feed_mode) {
1329                         $attributes = ["href" => DI::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "salmon"];
1330                         XML::addElement($doc, $root, "link", "", $attributes);
1331
1332                         $attributes = ["href" => DI::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies"];
1333                         XML::addElement($doc, $root, "link", "", $attributes);
1334
1335                         $attributes = ["href" => DI::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention"];
1336                         XML::addElement($doc, $root, "link", "", $attributes);
1337                 }
1338
1339                 $attributes = ["href" => DI::baseUrl() . $selfUri, "rel" => "self", "type" => "application/atom+xml"];
1340                 XML::addElement($doc, $root, "link", "", $attributes);
1341
1342                 if ($owner['account-type'] == Contact::TYPE_COMMUNITY) {
1343                         $condition = ['uid' => $owner['uid'], 'self' => false, 'pending' => false,
1344                                         'archive' => false, 'hidden' => false, 'blocked' => false];
1345                         $members = DBA::count('contact', $condition);
1346                         XML::addElement($doc, $root, "statusnet:group_info", "", ["member_count" => $members]);
1347                 }
1348
1349                 return $root;
1350         }
1351
1352         /**
1353          * Add the link to the push hubs to the XML document
1354          *
1355          * @param DOMDocument $doc  XML document
1356          * @param object      $root XML root element where the hub links are added
1357          * @param object      $nick nick
1358          * @return void
1359          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1360          */
1361         public static function hublinks(DOMDocument $doc, $root, $nick)
1362         {
1363                 $h = DI::baseUrl() . '/pubsubhubbub/'.$nick;
1364                 XML::addElement($doc, $root, "link", "", ["href" => $h, "rel" => "hub"]);
1365         }
1366
1367         /**
1368          * Adds attachment data to the XML document
1369          *
1370          * @param DOMDocument $doc  XML document
1371          * @param object      $root XML root element where the hub links are added
1372          * @param array       $item Data of the item that is to be posted
1373          * @return void
1374          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1375          */
1376         private static function getAttachment(DOMDocument $doc, $root, $item)
1377         {
1378                 $siteinfo = BBCode::getAttachedData($item["body"]);
1379
1380                 switch ($siteinfo["type"]) {
1381                         case 'photo':
1382                                 if (!empty($siteinfo["image"])) {
1383                                         $imgdata = Images::getInfoFromURLCached($siteinfo["image"]);
1384                                         if ($imgdata) {
1385                                                 $attributes = ["rel" => "enclosure",
1386                                                                 "href" => $siteinfo["image"],
1387                                                                 "type" => $imgdata["mime"],
1388                                                                 "length" => intval($imgdata["size"])];
1389                                                 XML::addElement($doc, $root, "link", "", $attributes);
1390                                         }
1391                                 }
1392                                 break;
1393                         case 'video':
1394                                 $attributes = ["rel" => "enclosure",
1395                                                 "href" => $siteinfo["url"],
1396                                                 "type" => "text/html; charset=UTF-8",
1397                                                 "length" => "0",
1398                                                 "title" => ($siteinfo["title"] ?? '') ?: $siteinfo["url"],
1399                                 ];
1400                                 XML::addElement($doc, $root, "link", "", $attributes);
1401                                 break;
1402                         default:
1403                                 break;
1404                 }
1405
1406                 if (!DI::config()->get('system', 'ostatus_not_attach_preview') && ($siteinfo["type"] != "photo") && isset($siteinfo["image"])) {
1407                         $imgdata = Images::getInfoFromURLCached($siteinfo["image"]);
1408                         if ($imgdata) {
1409                                 $attributes = ["rel" => "enclosure",
1410                                                 "href" => $siteinfo["image"],
1411                                                 "type" => $imgdata["mime"],
1412                                                 "length" => intval($imgdata["size"])];
1413
1414                                 XML::addElement($doc, $root, "link", "", $attributes);
1415                         }
1416                 }
1417
1418                 $arr = explode('[/attach],', $item['attach']);
1419                 if (count($arr)) {
1420                         foreach ($arr as $r) {
1421                                 $matches = false;
1422                                 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1423                                 if ($cnt) {
1424                                         $attributes = ["rel" => "enclosure",
1425                                                         "href" => $matches[1],
1426                                                         "type" => $matches[3]];
1427
1428                                         if (intval($matches[2])) {
1429                                                 $attributes["length"] = intval($matches[2]);
1430                                         }
1431                                         if (trim($matches[4]) != "") {
1432                                                 $attributes["title"] = trim($matches[4]);
1433                                         }
1434                                         XML::addElement($doc, $root, "link", "", $attributes);
1435                                 }
1436                         }
1437                 }
1438         }
1439
1440         /**
1441          * Adds the author element to the XML document
1442          *
1443          * @param DOMDocument $doc          XML document
1444          * @param array       $owner        Contact data of the poster
1445          * @param bool        $show_profile Whether to show profile
1446          * @param bool        $feed_mode Behave like a regular feed for users if true
1447          *
1448          * @return \DOMElement author element
1449          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1450          */
1451         private static function addAuthor(DOMDocument $doc, array $owner, $show_profile = true, $feed_mode = false)
1452         {
1453                 $profile = DBA::selectFirst('profile', ['homepage', 'publish'], ['uid' => $owner['uid']]);
1454                 $author = $doc->createElement("author");
1455                 if (!$feed_mode) {
1456                         XML::addElement($doc, $author, "id", $owner["url"]);
1457                         if ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
1458                                 XML::addElement($doc, $author, "activity:object-type", Activity\ObjectType::GROUP);
1459                         } else {
1460                                 XML::addElement($doc, $author, "activity:object-type", Activity\ObjectType::PERSON);
1461                         }
1462                 }
1463                 XML::addElement($doc, $author, "uri", $owner["url"]);
1464                 XML::addElement($doc, $author, "name", $owner["nick"]);
1465                 XML::addElement($doc, $author, "email", $owner["addr"]);
1466                 if ($show_profile && !$feed_mode) {
1467                         XML::addElement($doc, $author, "summary", BBCode::convert($owner["about"], false, BBCode::OSTATUS));
1468                 }
1469
1470                 if (!$feed_mode) {
1471                         $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $owner["url"]];
1472                         XML::addElement($doc, $author, "link", "", $attributes);
1473
1474                         $attributes = [
1475                                         "rel" => "avatar",
1476                                         "type" => "image/jpeg", // To-Do?
1477                                         "media:width" => 300,
1478                                         "media:height" => 300,
1479                                         "href" => $owner["photo"]];
1480                         XML::addElement($doc, $author, "link", "", $attributes);
1481
1482                         if (isset($owner["thumb"])) {
1483                                 $attributes = [
1484                                                 "rel" => "avatar",
1485                                                 "type" => "image/jpeg", // To-Do?
1486                                                 "media:width" => 80,
1487                                                 "media:height" => 80,
1488                                                 "href" => $owner["thumb"]];
1489                                 XML::addElement($doc, $author, "link", "", $attributes);
1490                         }
1491
1492                         XML::addElement($doc, $author, "poco:preferredUsername", $owner["nick"]);
1493                         XML::addElement($doc, $author, "poco:displayName", $owner["name"]);
1494                         if ($show_profile) {
1495                                 XML::addElement($doc, $author, "poco:note", BBCode::convert($owner["about"], false, BBCode::OSTATUS));
1496
1497                                 if (trim($owner["location"]) != "") {
1498                                         $element = $doc->createElement("poco:address");
1499                                         XML::addElement($doc, $element, "poco:formatted", $owner["location"]);
1500                                         $author->appendChild($element);
1501                                 }
1502                         }
1503
1504                         if (DBA::isResult($profile) && !$show_profile) {
1505                                 if (trim($profile["homepage"]) != "") {
1506                                         $urls = $doc->createElement("poco:urls");
1507                                         XML::addElement($doc, $urls, "poco:type", "homepage");
1508                                         XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
1509                                         XML::addElement($doc, $urls, "poco:primary", "true");
1510                                         $author->appendChild($urls);
1511                                 }
1512
1513                                 XML::addElement($doc, $author, "followers", "", ["url" => DI::baseUrl() . "/profile/" . $owner["nick"] . "/contacts/followers"]);
1514                                 XML::addElement($doc, $author, "statusnet:profile_info", "", ["local_id" => $owner["uid"]]);
1515
1516                                 if ($profile["publish"]) {
1517                                         XML::addElement($doc, $author, "mastodon:scope", "public");
1518                                 }
1519                         }
1520                 }
1521
1522                 return $author;
1523         }
1524
1525         /**
1526          * @TODO Picture attachments should look like this:
1527          *      <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1528          *      class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1529          */
1530
1531         /**
1532          * Returns the given activity if present - otherwise returns the "post" activity
1533          *
1534          * @param array $item Data of the item that is to be posted
1535          *
1536          * @return string activity
1537          */
1538         private static function constructVerb(array $item)
1539         {
1540                 if (!empty($item['verb'])) {
1541                         return $item['verb'];
1542                 }
1543
1544                 return Activity::POST;
1545         }
1546
1547         /**
1548          * Returns the given object type if present - otherwise returns the "note" object type
1549          *
1550          * @param array $item Data of the item that is to be posted
1551          *
1552          * @return string Object type
1553          */
1554         private static function constructObjecttype(array $item)
1555         {
1556                 if (!empty($item['object-type']) && in_array($item['object-type'], [Activity\ObjectType::NOTE, Activity\ObjectType::COMMENT])) {
1557                         return $item['object-type'];
1558                 }
1559
1560                 return Activity\ObjectType::NOTE;
1561         }
1562
1563         /**
1564          * Adds an entry element to the XML document
1565          *
1566          * @param DOMDocument $doc       XML document
1567          * @param array       $item      Data of the item that is to be posted
1568          * @param array       $owner     Contact data of the poster
1569          * @param bool        $toplevel  optional default false
1570          * @param bool        $feed_mode Behave like a regular feed for users if true
1571          *
1572          * @return \DOMElement Entry element
1573          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1574          * @throws \ImagickException
1575          */
1576         private static function entry(DOMDocument $doc, array $item, array $owner, $toplevel = false, $feed_mode = false)
1577         {
1578                 $xml = null;
1579
1580                 $repeated_guid = self::getResharedGuid($item);
1581                 if ($repeated_guid != "") {
1582                         $xml = self::reshareEntry($doc, $item, $owner, $repeated_guid, $toplevel, $feed_mode);
1583                 }
1584
1585                 if ($xml) {
1586                         return $xml;
1587                 }
1588
1589                 if ($item["verb"] == Activity::LIKE) {
1590                         return self::likeEntry($doc, $item, $owner, $toplevel);
1591                 } elseif (in_array($item["verb"], [Activity::FOLLOW, Activity::O_UNFOLLOW])) {
1592                         return self::followEntry($doc, $item, $owner, $toplevel);
1593                 } else {
1594                         return self::noteEntry($doc, $item, $owner, $toplevel, $feed_mode);
1595                 }
1596         }
1597
1598         /**
1599          * Adds a source entry to the XML document
1600          *
1601          * @param DOMDocument $doc     XML document
1602          * @param array       $contact Array of the contact that is added
1603          *
1604          * @return \DOMElement Source element
1605          * @throws \Exception
1606          */
1607         private static function sourceEntry(DOMDocument $doc, array $contact)
1608         {
1609                 $source = $doc->createElement("source");
1610                 XML::addElement($doc, $source, "id", $contact["poll"]);
1611                 XML::addElement($doc, $source, "title", $contact["name"]);
1612                 XML::addElement($doc, $source, "link", "", ["rel" => "alternate", "type" => "text/html", "href" => $contact["alias"]]);
1613                 XML::addElement($doc, $source, "link", "", ["rel" => "self", "type" => "application/atom+xml", "href" => $contact["poll"]]);
1614                 XML::addElement($doc, $source, "icon", $contact["photo"]);
1615                 XML::addElement($doc, $source, "updated", DateTimeFormat::utc($contact["success_update"]."+00:00", DateTimeFormat::ATOM));
1616
1617                 return $source;
1618         }
1619
1620         /**
1621          * Fetches contact data from the contact or the gcontact table
1622          *
1623          * @param string $url   URL of the contact
1624          * @param array  $owner Contact data of the poster
1625          *
1626          * @return array Contact array
1627          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1628          * @throws \ImagickException
1629          */
1630         private static function contactEntry($url, array $owner)
1631         {
1632                 $r = q(
1633                         "SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
1634                         DBA::escape(Strings::normaliseLink($url)),
1635                         intval($owner["uid"])
1636                 );
1637                 if (DBA::isResult($r)) {
1638                         $contact = $r[0];
1639                         $contact["uid"] = -1;
1640                 }
1641
1642                 if (!DBA::isResult($r)) {
1643                         $gcontact = DBA::selectFirst('gcontact', [], ['nurl' => Strings::normaliseLink($url)]);
1644                         if (DBA::isResult($r)) {
1645                                 $contact = $gcontact;
1646                                 $contact["uid"] = -1;
1647                                 $contact["success_update"] = $contact["updated"];
1648                         }
1649                 }
1650
1651                 if (!DBA::isResult($r)) {
1652                         $contact = $owner;
1653                 }
1654
1655                 if (!isset($contact["poll"])) {
1656                         $data = Probe::uri($url);
1657                         $contact["poll"] = $data["poll"];
1658
1659                         if (!$contact["alias"]) {
1660                                 $contact["alias"] = $data["alias"];
1661                         }
1662                 }
1663
1664                 if (!isset($contact["alias"])) {
1665                         $contact["alias"] = $contact["url"];
1666                 }
1667
1668                 $contact['account-type'] = $owner['account-type'];
1669
1670                 return $contact;
1671         }
1672
1673         /**
1674          * Adds an entry element with reshared content
1675          *
1676          * @param DOMDocument $doc           XML document
1677          * @param array       $item          Data of the item that is to be posted
1678          * @param array       $owner         Contact data of the poster
1679          * @param string      $repeated_guid guid
1680          * @param bool        $toplevel      Is it for en entry element (false) or a feed entry (true)?
1681          * @param bool        $feed_mode Behave like a regular feed for users if true
1682          *
1683          * @return bool Entry element
1684          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1685          * @throws \ImagickException
1686          */
1687         private static function reshareEntry(DOMDocument $doc, array $item, array $owner, $repeated_guid, $toplevel, $feed_mode = false)
1688         {
1689                 if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1690                         Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
1691                 }
1692
1693                 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1694
1695                 $condition = ['uid' => $owner["uid"], 'guid' => $repeated_guid, 'private' => [Item::PUBLIC, Item::UNLISTED],
1696                         'network' => [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS]];
1697                 $repeated_item = Item::selectFirst([], $condition);
1698                 if (!DBA::isResult($repeated_item)) {
1699                         return false;
1700                 }
1701
1702                 $contact = self::contactEntry($repeated_item['author-link'], $owner);
1703
1704                 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1705
1706                 self::entryContent($doc, $entry, $item, $owner, $title, Activity::SHARE, false, $feed_mode);
1707
1708                 if (!$feed_mode) {
1709                         $as_object = $doc->createElement("activity:object");
1710
1711                         XML::addElement($doc, $as_object, "activity:object-type", ActivityNamespace::ACTIVITY_SCHEMA . "activity");
1712
1713                         self::entryContent($doc, $as_object, $repeated_item, $owner, "", "", false);
1714
1715                         $author = self::addAuthor($doc, $contact, false);
1716                         $as_object->appendChild($author);
1717
1718                         $as_object2 = $doc->createElement("activity:object");
1719
1720                         XML::addElement($doc, $as_object2, "activity:object-type", self::constructObjecttype($repeated_item));
1721
1722                         $title = sprintf("New comment by %s", $contact["nick"]);
1723
1724                         self::entryContent($doc, $as_object2, $repeated_item, $owner, $title);
1725
1726                         $as_object->appendChild($as_object2);
1727
1728                         self::entryFooter($doc, $as_object, $item, $owner, false);
1729
1730                         $source = self::sourceEntry($doc, $contact);
1731
1732                         $as_object->appendChild($source);
1733
1734                         $entry->appendChild($as_object);
1735                 }
1736
1737                 self::entryFooter($doc, $entry, $item, $owner, true, $feed_mode);
1738
1739                 return $entry;
1740         }
1741
1742         /**
1743          * Adds an entry element with a "like"
1744          *
1745          * @param DOMDocument $doc      XML document
1746          * @param array       $item     Data of the item that is to be posted
1747          * @param array       $owner    Contact data of the poster
1748          * @param bool        $toplevel Is it for en entry element (false) or a feed entry (true)?
1749          *
1750          * @return \DOMElement Entry element with "like"
1751          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1752          * @throws \ImagickException
1753          */
1754         private static function likeEntry(DOMDocument $doc, array $item, array $owner, $toplevel)
1755         {
1756                 if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1757                         Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
1758                 }
1759
1760                 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1761
1762                 $verb = ActivityNamespace::ACTIVITY_SCHEMA . "favorite";
1763                 self::entryContent($doc, $entry, $item, $owner, "Favorite", $verb, false);
1764
1765                 $parent = Item::selectFirst([], ['uri' => $item["thr-parent"], 'uid' => $item["uid"]]);
1766                 if (DBA::isResult($parent)) {
1767                         $as_object = $doc->createElement("activity:object");
1768
1769                         XML::addElement($doc, $as_object, "activity:object-type", self::constructObjecttype($parent));
1770
1771                         self::entryContent($doc, $as_object, $parent, $owner, "New entry");
1772
1773                         $entry->appendChild($as_object);
1774                 }
1775
1776                 self::entryFooter($doc, $entry, $item, $owner);
1777
1778                 return $entry;
1779         }
1780
1781         /**
1782          * Adds the person object element to the XML document
1783          *
1784          * @param DOMDocument $doc     XML document
1785          * @param array       $owner   Contact data of the poster
1786          * @param array       $contact Contact data of the target
1787          *
1788          * @return object author element
1789          */
1790         private static function addPersonObject(DOMDocument $doc, array $owner, array $contact)
1791         {
1792                 $object = $doc->createElement("activity:object");
1793                 XML::addElement($doc, $object, "activity:object-type", Activity\ObjectType::PERSON);
1794
1795                 if ($contact['network'] == Protocol::PHANTOM) {
1796                         XML::addElement($doc, $object, "id", $contact['url']);
1797                         return $object;
1798                 }
1799
1800                 XML::addElement($doc, $object, "id", $contact["alias"]);
1801                 XML::addElement($doc, $object, "title", $contact["nick"]);
1802
1803                 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $contact["url"]];
1804                 XML::addElement($doc, $object, "link", "", $attributes);
1805
1806                 $attributes = [
1807                                 "rel" => "avatar",
1808                                 "type" => "image/jpeg", // To-Do?
1809                                 "media:width" => 300,
1810                                 "media:height" => 300,
1811                                 "href" => $contact["photo"]];
1812                 XML::addElement($doc, $object, "link", "", $attributes);
1813
1814                 XML::addElement($doc, $object, "poco:preferredUsername", $contact["nick"]);
1815                 XML::addElement($doc, $object, "poco:displayName", $contact["name"]);
1816
1817                 if (trim($contact["location"]) != "") {
1818                         $element = $doc->createElement("poco:address");
1819                         XML::addElement($doc, $element, "poco:formatted", $contact["location"]);
1820                         $object->appendChild($element);
1821                 }
1822
1823                 return $object;
1824         }
1825
1826         /**
1827          * Adds a follow/unfollow entry element
1828          *
1829          * @param DOMDocument $doc      XML document
1830          * @param array       $item     Data of the follow/unfollow message
1831          * @param array       $owner    Contact data of the poster
1832          * @param bool        $toplevel Is it for en entry element (false) or a feed entry (true)?
1833          *
1834          * @return \DOMElement Entry element
1835          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1836          * @throws \ImagickException
1837          */
1838         private static function followEntry(DOMDocument $doc, array $item, array $owner, $toplevel)
1839         {
1840                 $item["id"] = $item['parent'] = 0;
1841                 $item["created"] = $item["edited"] = date("c");
1842                 $item["private"] = Item::PRIVATE;
1843
1844                 $contact = Probe::uri($item['follow']);
1845                 $item['follow'] = $contact['url'];
1846
1847                 if ($contact['alias']) {
1848                         $item['follow'] = $contact['alias'];
1849                 } else {
1850                         $contact['alias'] = $contact['url'];
1851                 }
1852
1853                 $condition = ['uid' => $owner['uid'], 'nurl' => Strings::normaliseLink($contact["url"])];
1854                 $user_contact = DBA::selectFirst('contact', ['id'], $condition);
1855
1856                 if (DBA::isResult($user_contact)) {
1857                         $connect_id = $user_contact['id'];
1858                 } else {
1859                         $connect_id = 0;
1860                 }
1861
1862                 if ($item['verb'] == Activity::FOLLOW) {
1863                         $message = DI::l10n()->t('%s is now following %s.');
1864                         $title = DI::l10n()->t('following');
1865                         $action = "subscription";
1866                 } else {
1867                         $message = DI::l10n()->t('%s stopped following %s.');
1868                         $title = DI::l10n()->t('stopped following');
1869                         $action = "unfollow";
1870                 }
1871
1872                 $item["uri"] = $item['parent-uri'] = $item['thr-parent']
1873                                 = 'tag:' . DI::baseUrl()->getHostname().
1874                                 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1875                                 ':person:'.$connect_id.':'.$item['created'];
1876
1877                 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1878
1879                 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1880
1881                 self::entryContent($doc, $entry, $item, $owner, $title);
1882
1883                 $object = self::addPersonObject($doc, $owner, $contact);
1884                 $entry->appendChild($object);
1885
1886                 self::entryFooter($doc, $entry, $item, $owner);
1887
1888                 return $entry;
1889         }
1890
1891         /**
1892          * Adds a regular entry element
1893          *
1894          * @param DOMDocument $doc       XML document
1895          * @param array       $item      Data of the item that is to be posted
1896          * @param array       $owner     Contact data of the poster
1897          * @param bool        $toplevel  Is it for en entry element (false) or a feed entry (true)?
1898          * @param bool        $feed_mode Behave like a regular feed for users if true
1899          *
1900          * @return \DOMElement Entry element
1901          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1902          * @throws \ImagickException
1903          */
1904         private static function noteEntry(DOMDocument $doc, array $item, array $owner, $toplevel, $feed_mode)
1905         {
1906                 if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1907                         Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
1908                 }
1909
1910                 if (!$toplevel) {
1911                         if (!empty($item['title'])) {
1912                                 $title = BBCode::convert($item['title'], false, BBCode::OSTATUS);
1913                         } else {
1914                                 $title = sprintf("New note by %s", $owner["nick"]);
1915                         }
1916                 } else {
1917                         $title = sprintf("New comment by %s", $owner["nick"]);
1918                 }
1919
1920                 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1921
1922                 if (!$feed_mode) {
1923                         XML::addElement($doc, $entry, "activity:object-type", Activity\ObjectType::NOTE);
1924                 }
1925
1926                 self::entryContent($doc, $entry, $item, $owner, $title, '', true, $feed_mode);
1927
1928                 self::entryFooter($doc, $entry, $item, $owner, !$feed_mode, $feed_mode);
1929
1930                 return $entry;
1931         }
1932
1933         /**
1934          * Adds a header element to the XML document
1935          *
1936          * @param DOMDocument $doc      XML document
1937          * @param array       $owner    Contact data of the poster
1938          * @param array       $item
1939          * @param bool        $toplevel Is it for en entry element (false) or a feed entry (true)?
1940          *
1941          * @return \DOMElement The entry element where the elements are added
1942          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1943          * @throws \ImagickException
1944          */
1945         private static function entryHeader(DOMDocument $doc, array $owner, array $item, $toplevel)
1946         {
1947                 if (!$toplevel) {
1948                         $entry = $doc->createElement("entry");
1949
1950                         if ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
1951                                 $contact = self::contactEntry($item['author-link'], $owner);
1952                                 $author = self::addAuthor($doc, $contact, false);
1953                                 $entry->appendChild($author);
1954                         }
1955                 } else {
1956                         $entry = $doc->createElementNS(ActivityNamespace::ATOM1, "entry");
1957
1958                         $entry->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
1959                         $entry->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
1960                         $entry->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
1961                         $entry->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
1962                         $entry->setAttribute("xmlns:poco", ActivityNamespace::POCO);
1963                         $entry->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
1964                         $entry->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
1965                         $entry->setAttribute("xmlns:mastodon", ActivityNamespace::MASTODON);
1966
1967                         $author = self::addAuthor($doc, $owner);
1968                         $entry->appendChild($author);
1969                 }
1970
1971                 return $entry;
1972         }
1973
1974         /**
1975          * Adds elements to the XML document
1976          *
1977          * @param DOMDocument $doc       XML document
1978          * @param \DOMElement $entry     Entry element where the content is added
1979          * @param array       $item      Data of the item that is to be posted
1980          * @param array       $owner     Contact data of the poster
1981          * @param string      $title     Title for the post
1982          * @param string      $verb      The activity verb
1983          * @param bool        $complete  Add the "status_net" element?
1984          * @param bool        $feed_mode Behave like a regular feed for users if true
1985          * @return void
1986          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1987          */
1988         private static function entryContent(DOMDocument $doc, \DOMElement $entry, array $item, array $owner, $title, $verb = "", $complete = true, $feed_mode = false)
1989         {
1990                 if ($verb == "") {
1991                         $verb = self::constructVerb($item);
1992                 }
1993
1994                 XML::addElement($doc, $entry, "id", $item["uri"]);
1995                 XML::addElement($doc, $entry, "title", html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
1996
1997                 $body = self::formatPicturePost($item['body']);
1998
1999                 if (!empty($item['title']) && !$feed_mode) {
2000                         $body = "[b]".$item['title']."[/b]\n\n".$body;
2001                 }
2002
2003                 $body = BBCode::convert($body, false, BBCode::OSTATUS);
2004
2005                 XML::addElement($doc, $entry, "content", $body, ["type" => "html"]);
2006
2007                 XML::addElement($doc, $entry, "link", "", ["rel" => "alternate", "type" => "text/html",
2008                                                                 "href" => DI::baseUrl()."/display/".$item["guid"]]
2009                 );
2010
2011                 if (!$feed_mode && $complete && ($item["id"] > 0)) {
2012                         XML::addElement($doc, $entry, "status_net", "", ["notice_id" => $item["id"]]);
2013                 }
2014
2015                 if (!$feed_mode) {
2016                         XML::addElement($doc, $entry, "activity:verb", $verb);
2017                 }
2018
2019                 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM));
2020                 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM));
2021         }
2022
2023         /**
2024          * Adds the elements at the foot of an entry to the XML document
2025          *
2026          * @param DOMDocument $doc       XML document
2027          * @param object      $entry     The entry element where the elements are added
2028          * @param array       $item      Data of the item that is to be posted
2029          * @param array       $owner     Contact data of the poster
2030          * @param bool        $complete  default true
2031          * @param bool        $feed_mode Behave like a regular feed for users if true
2032          * @return void
2033          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2034          */
2035         private static function entryFooter(DOMDocument $doc, $entry, array $item, array $owner, $complete = true, $feed_mode = false)
2036         {
2037                 $mentioned = [];
2038
2039                 if ($item['gravity'] != GRAVITY_PARENT) {
2040                         $parent = Item::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item['parent']]);
2041                         $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
2042
2043                         $thrparent = Item::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner["uid"], 'uri' => $parent_item]);
2044
2045                         if (DBA::isResult($thrparent)) {
2046                                 $mentioned[$thrparent["author-link"]] = $thrparent["author-link"];
2047                                 $mentioned[$thrparent["owner-link"]] = $thrparent["owner-link"];
2048                                 $parent_plink = $thrparent["plink"];
2049                         } else {
2050                                 $mentioned[$parent["author-link"]] = $parent["author-link"];
2051                                 $mentioned[$parent["owner-link"]] = $parent["owner-link"];
2052                                 $parent_plink = DI::baseUrl()."/display/".$parent["guid"];
2053                         }
2054
2055                         $attributes = [
2056                                         "ref" => $parent_item,
2057                                         "href" => $parent_plink];
2058                         XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
2059
2060                         $attributes = [
2061                                         "rel" => "related",
2062                                         "href" => $parent_plink];
2063                         XML::addElement($doc, $entry, "link", "", $attributes);
2064                 }
2065
2066                 if (!$feed_mode && (intval($item['parent']) > 0)) {
2067                         $conversation_href = $conversation_uri = str_replace('/objects/', '/context/', $item['parent-uri']);
2068
2069                         if (isset($parent_item)) {
2070                                 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $parent_item]);
2071                                 if (DBA::isResult($conversation)) {
2072                                         if ($conversation['conversation-uri'] != '') {
2073                                                 $conversation_uri = $conversation['conversation-uri'];
2074                                         }
2075                                         if ($conversation['conversation-href'] != '') {
2076                                                 $conversation_href = $conversation['conversation-href'];
2077                                         }
2078                                 }
2079                         }
2080
2081                         if (!$feed_mode) {
2082                                 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:conversation", "href" => $conversation_href]);
2083
2084                                 $attributes = [
2085                                                 "href" => $conversation_href,
2086                                                 "local_id" => $item['parent'],
2087                                                 "ref" => $conversation_uri];
2088
2089                                 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
2090                         }
2091                 }
2092
2093                 // uri-id isn't present for follow entry pseudo-items
2094                 $tags = Tag::getByURIId($item['uri-id'] ?? 0);
2095                 foreach ($tags as $tag) {
2096                         $mentioned[$tag['url']] = $tag['url'];
2097                 }
2098
2099                 if (!$feed_mode) {
2100                         // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
2101                         $newmentions = [];
2102                         foreach ($mentioned as $mention) {
2103                                 $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
2104                                 $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
2105                         }
2106                         $mentioned = $newmentions;
2107
2108                         foreach ($mentioned as $mention) {
2109                                 $contact = Contact::getByURL($mention, ['contact-type']);
2110                                 if (!empty($contact) && ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
2111                                         XML::addElement($doc, $entry, "link", "",
2112                                                 [
2113                                                         "rel" => "mentioned",
2114                                                         "ostatus:object-type" => Activity\ObjectType::GROUP,
2115                                                         "href" => $mention]
2116                                         );
2117                                 } else {
2118                                         XML::addElement($doc, $entry, "link", "",
2119                                                 [
2120                                                         "rel" => "mentioned",
2121                                                         "ostatus:object-type" => Activity\ObjectType::PERSON,
2122                                                         "href" => $mention]
2123                                         );
2124                                 }
2125                         }
2126
2127                         if ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
2128                                 XML::addElement($doc, $entry, "link", "", [
2129                                         "rel" => "mentioned",
2130                                         "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/group",
2131                                         "href" => $owner['url']
2132                                 ]);
2133                         }
2134
2135                         if ($item['private'] != Item::PRIVATE) {
2136                                 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:attention",
2137                                                                                 "href" => "http://activityschema.org/collection/public"]);
2138                                 XML::addElement($doc, $entry, "link", "", ["rel" => "mentioned",
2139                                                                                 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
2140                                                                                 "href" => "http://activityschema.org/collection/public"]);
2141                                 XML::addElement($doc, $entry, "mastodon:scope", "public");
2142                         }
2143                 }
2144
2145                 foreach ($tags as $tag) {
2146                         if ($tag['type'] == Tag::HASHTAG) {
2147                                 XML::addElement($doc, $entry, "category", "", ["term" => $tag['name']]);
2148                         }
2149                 }
2150
2151                 self::getAttachment($doc, $entry, $item);
2152
2153                 if (!$feed_mode && $complete && ($item["id"] > 0)) {
2154                         $app = $item["app"];
2155                         if ($app == "") {
2156                                 $app = "web";
2157                         }
2158
2159                         $attributes = ["local_id" => $item["id"], "source" => $app];
2160
2161                         if (isset($parent["id"])) {
2162                                 $attributes["repeat_of"] = $parent["id"];
2163                         }
2164
2165                         if ($item["coord"] != "") {
2166                                 XML::addElement($doc, $entry, "georss:point", $item["coord"]);
2167                         }
2168
2169                         XML::addElement($doc, $entry, "statusnet:notice_info", "", $attributes);
2170                 }
2171         }
2172
2173         /**
2174          * Creates the XML feed for a given nickname
2175          *
2176          * Supported filters:
2177          * - activity (default): all the public posts
2178          * - posts: all the public top-level posts
2179          * - comments: all the public replies
2180          *
2181          * Updates the provided last_update parameter if the result comes from the
2182          * cache or it is empty
2183          *
2184          * @param string  $owner_nick  Nickname of the feed owner
2185          * @param string  $last_update Date of the last update
2186          * @param integer $max_items   Number of maximum items to fetch
2187          * @param string  $filter      Feed items filter (activity, posts or comments)
2188          * @param boolean $nocache     Wether to bypass caching
2189          * @param boolean $feed_mode   Behave like a regular feed for users if true
2190          *
2191          * @return string XML feed
2192          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2193          * @throws \ImagickException
2194          */
2195         public static function feed($owner_nick, &$last_update, $max_items = 300, $filter = 'activity', $nocache = false, $feed_mode = false)
2196         {
2197                 $stamp = microtime(true);
2198
2199                 $owner = User::getOwnerDataByNick($owner_nick);
2200                 if (!$owner) {
2201                         return;
2202                 }
2203
2204                 $cachekey = "ostatus:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
2205
2206                 $previous_created = $last_update;
2207
2208                 // Don't cache when the last item was posted less then 15 minutes ago (Cache duration)
2209                 if ((time() - strtotime($owner['last-item'])) < 15*60) {
2210                         $result = DI::cache()->get($cachekey);
2211                         if (!$nocache && !is_null($result)) {
2212                                 Logger::log('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created . ' (cached)', Logger::DEBUG);
2213                                 $last_update = $result['last_update'];
2214                                 return $result['feed'];
2215                         }
2216                 }
2217
2218                 if (!strlen($last_update)) {
2219                         $last_update = 'now -30 days';
2220                 }
2221
2222                 $check_date = $feed_mode ? '' : DateTimeFormat::utc($last_update);
2223                 $authorid = Contact::getIdForURL($owner["url"], 0, false);
2224
2225                 $condition = ["`uid` = ? AND `received` > ? AND NOT `deleted`
2226                         AND `private` != ? AND `visible` AND `wall` AND `parent-network` IN (?, ?)",
2227                         $owner["uid"], $check_date, Item::PRIVATE, Protocol::OSTATUS, Protocol::DFRN];
2228
2229                 if ($filter === 'comments') {
2230                         $condition[0] .= " AND `object-type` = ? ";
2231                         $condition[] = Activity\ObjectType::COMMENT;
2232                 }
2233
2234                 if ($owner['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
2235                         $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
2236                         $condition[] = $owner["id"];
2237                         $condition[] = $authorid;
2238                 }
2239
2240                 $params = ['order' => ['received' => true], 'limit' => $max_items];
2241
2242                 if ($filter === 'posts') {
2243                         $ret = Item::selectThread([], $condition, $params);
2244                 } else {
2245                         $ret = Item::select([], $condition, $params);
2246                 }
2247
2248                 $items = Item::inArray($ret);
2249
2250                 $doc = new DOMDocument('1.0', 'utf-8');
2251                 $doc->formatOutput = true;
2252
2253                 $root = self::addHeader($doc, $owner, $filter, $feed_mode);
2254
2255                 foreach ($items as $item) {
2256                         if (DI::config()->get('system', 'ostatus_debug')) {
2257                                 $item['body'] .= '🍼';
2258                         }
2259
2260                         if (in_array($item["verb"], [Activity::FOLLOW, Activity::O_UNFOLLOW, Activity::LIKE])) {
2261                                 continue;
2262                         }
2263
2264                         $entry = self::entry($doc, $item, $owner, false, $feed_mode);
2265                         $root->appendChild($entry);
2266
2267                         if ($last_update < $item['created']) {
2268                                 $last_update = $item['created'];
2269                         }
2270                 }
2271
2272                 $feeddata = trim($doc->saveXML());
2273
2274                 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
2275                 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
2276
2277                 Logger::log('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created, Logger::DEBUG);
2278
2279                 return $feeddata;
2280         }
2281
2282         /**
2283          * Creates the XML for a salmon message
2284          *
2285          * @param array $item  Data of the item that is to be posted
2286          * @param array $owner Contact data of the poster
2287          *
2288          * @return string XML for the salmon
2289          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2290          * @throws \ImagickException
2291          */
2292         public static function salmon(array $item, array $owner)
2293         {
2294                 $doc = new DOMDocument('1.0', 'utf-8');
2295                 $doc->formatOutput = true;
2296
2297                 if (DI::config()->get('system', 'ostatus_debug')) {
2298                         $item['body'] .= '🐟';
2299                 }
2300
2301                 $entry = self::entry($doc, $item, $owner, true);
2302
2303                 $doc->appendChild($entry);
2304
2305                 return trim($doc->saveXML());
2306         }
2307
2308         /**
2309          * Checks if the given contact url does support OStatus
2310          *
2311          * @param string  $url    profile url
2312          * @param boolean $update Update the profile
2313          * @return boolean
2314          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2315          * @throws \ImagickException
2316          */
2317         public static function isSupportedByContactUrl($url, $update = false)
2318         {
2319                 $probe = Probe::uri($url, Protocol::OSTATUS, 0, !$update);
2320                 return $probe['network'] == Protocol::OSTATUS;
2321         }
2322 }