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