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