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