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