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