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