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