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