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