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