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