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