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