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