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