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