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