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