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