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