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