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