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