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