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