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