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