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