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