]> git.mxchange.org Git - friendica.git/blob - include/ostatus.php
Merge pull request #3690 from annando/diaspora-like
[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         const OSTATUS_DEFAULT_POLL_INTERVAL = 30; // given in minutes
33         const OSTATUS_DEFAULT_POLL_TIMEFRAME = 1440; // given in minutes
34         const OSTATUS_DEFAULT_POLL_TIMEFRAME_MENTIONS = 14400; // given in minutes
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 detals
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 $contact
261          * @param array $hub Called by reference, returns the fetched hub data
262          */
263         public static function import($xml,$importer,&$contact, &$hub) {
264                 /// @todo this function is too long. It has to be split in many parts
265
266                 logger("Import OStatus message", LOGGER_DEBUG);
267
268                 if ($xml == "") {
269                         return;
270                 }
271                 //$tempfile = tempnam(get_temppath(), "import");
272                 //file_put_contents($tempfile, $xml);
273
274                 $doc = new DOMDocument();
275                 @$doc->loadXML($xml);
276
277                 $xpath = new DomXPath($doc);
278                 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
279                 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
280                 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
281                 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
282                 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
283                 $xpath->registerNamespace('poco', NAMESPACE_POCO);
284                 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
285                 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
286
287                 $gub = "";
288                 $hub_attributes = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0)->attributes;
289                 if (is_object($hub_attributes)) {
290                         foreach ($hub_attributes AS $hub_attribute) {
291                                 if ($hub_attribute->name == "href") {
292                                         $hub = $hub_attribute->textContent;
293                                         logger("Found hub ".$hub, LOGGER_DEBUG);
294                                 }
295                         }
296                 }
297                 $header = array();
298                 $header["uid"] = $importer["uid"];
299                 $header["network"] = NETWORK_OSTATUS;
300                 $header["type"] = "remote";
301                 $header["wall"] = 0;
302                 $header["origin"] = 0;
303                 $header["gravity"] = GRAVITY_PARENT;
304
305                 // it could either be a received post or a post we fetched by ourselves
306                 // depending on that, the first node is different
307                 $first_child = $doc->firstChild->tagName;
308
309                 if ($first_child == "feed") {
310                         $entries = $xpath->query('/atom:feed/atom:entry');
311                         $header["protocol"] = PROTOCOL_OSTATUS_FEED;
312                 } else {
313                         $entries = $xpath->query('/atom:entry');
314                         $header["protocol"] = PROTOCOL_OSTATUS_SALMON;
315                 }
316                 $conversation = "";
317                 $conversationlist = array();
318                 $item_id = 0;
319
320                 // Reverse the order of the entries
321                 $entrylist = array();
322
323                 foreach ($entries AS $entry) {
324                         $entrylist[] = $entry;
325                 }
326                 foreach (array_reverse($entrylist) AS $entry) {
327
328                         $mention = false;
329
330                         // fetch the author
331                         if ($first_child == "feed") {
332                                 $author = self::fetchauthor($xpath, $doc->firstChild, $importer, $contact, false);
333                         } else {
334                                 $author = self::fetchauthor($xpath, $entry, $importer, $contact, false);
335                         }
336                         $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
337                         if ($value != "") {
338                                 $nickname = $value;
339                         } else {
340                                 $nickname = $author["author-name"];
341                         }
342                         $item = array_merge($header, $author);
343
344                         // Now get the item
345                         $item["uri"] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
346
347                         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
348                                 intval($importer["uid"]), dbesc($item["uri"]));
349                         if (dbm::is_result($r)) {
350                                 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already existed under id ".$r[0]["id"], LOGGER_DEBUG);
351                                 continue;
352                         }
353
354                         $item["body"] = html2bbcode($xpath->query('atom:content/text()', $entry)->item(0)->nodeValue);
355                         $item["object-type"] = $xpath->query('activity:object-type/text()', $entry)->item(0)->nodeValue;
356                         $item["verb"] = $xpath->query('activity:verb/text()', $entry)->item(0)->nodeValue;
357
358                         if (($item["object-type"] == ACTIVITY_OBJ_BOOKMARK) || ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
359                                 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
360                                 $item["body"] = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
361                         } elseif ($item["object-type"] == ACTIVITY_OBJ_QUESTION) {
362                                 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
363                         }
364                         $item["source"] = $xml;
365
366                         /// @TODO
367                         /// Delete a message
368                         if ($item["verb"] == "qvitter-delete-notice" || $item["verb"] == ACTIVITY_DELETE) {
369                                 // ignore "Delete" messages (by now)
370                                 logger("Ignore delete message ".print_r($item, true));
371                                 continue;
372                         }
373
374                         if ($item["verb"] == ACTIVITY_JOIN) {
375                                 // ignore "Join" messages
376                                 logger("Ignore join message ".print_r($item, true));
377                                 continue;
378                         }
379
380                         if ($item["verb"] == ACTIVITY_FOLLOW) {
381                                 new_follower($importer, $contact, $item, $nickname);
382                                 continue;
383                         }
384
385                         if ($item["verb"] == NAMESPACE_OSTATUS."/unfollow") {
386                                 lose_follower($importer, $contact, $item, $dummy);
387                                 continue;
388                         }
389
390                         if ($item["verb"] == ACTIVITY_FAVORITE) {
391                                 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
392                                 logger("Favorite ".$orig_uri." ".print_r($item, true));
393
394                                 $item["verb"] = ACTIVITY_LIKE;
395                                 $item["parent-uri"] = $orig_uri;
396                                 $item["gravity"] = GRAVITY_LIKE;
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                         // http://activitystrea.ms/schema/1.0/rsvp-yes
406                         if (!in_array($item["verb"], array(ACTIVITY_POST, ACTIVITY_LIKE, ACTIVITY_SHARE))) {
407                                 logger("Unhandled verb ".$item["verb"]." ".print_r($item, true));
408                         }
409                         $item["created"] = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
410                         $item["edited"] = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
411                         $conversation = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
412                         $item['conversation-uri'] = $conversation;
413
414                         $conv = $xpath->query('ostatus:conversation', $entry);
415                         if (is_object($conv->item(0))) {
416                                 foreach ($conv->item(0)->attributes AS $attributes) {
417                                         if ($attributes->name == "ref") {
418                                                 $item['conversation-uri'] = $attributes->textContent;
419                                         }
420                                         if ($attributes->name == "href") {
421                                                 $item['conversation-href'] = $attributes->textContent;
422                                         }
423                                 }
424                         }
425
426                         $related = "";
427
428                         $inreplyto = $xpath->query('thr:in-reply-to', $entry);
429                         if (is_object($inreplyto->item(0))) {
430                                 foreach ($inreplyto->item(0)->attributes AS $attributes) {
431                                         if ($attributes->name == "ref") {
432                                                 $item["parent-uri"] = $attributes->textContent;
433                                         }
434                                         if ($attributes->name == "href") {
435                                                 $related = $attributes->textContent;
436                                         }
437                                 }
438                         }
439
440                         $georsspoint = $xpath->query('georss:point', $entry);
441                         if ($georsspoint) {
442                                 $item["coord"] = $georsspoint->item(0)->nodeValue;
443                         }
444                         $categories = $xpath->query('atom:category', $entry);
445                         if ($categories) {
446                                 foreach ($categories AS $category) {
447                                         foreach ($category->attributes AS $attributes) {
448                                                 if ($attributes->name == "term") {
449                                                         $term = $attributes->textContent;
450                                                         if (strlen($item["tag"])) {
451                                                                 $item["tag"] .= ',';
452                                                         }
453                                                         $item["tag"] .= "#[url=".System::baseUrl()."/search?tag=".$term."]".$term."[/url]";
454                                                 }
455                                         }
456                                 }
457                         }
458
459                         $self = "";
460
461                         $links = $xpath->query('atom:link', $entry);
462                         if ($links) {
463                                 foreach ($links AS $link) {
464                                         $attribute = self::read_attributes($link);
465
466                                         if (($attribute['rel'] != "") && ($attribute['href'] != "")) {
467                                                 switch ($attribute['rel']) {
468                                                         case "alternate":
469                                                                 $item["plink"] = $attribute['href'];
470                                                                 if (($item["object-type"] == ACTIVITY_OBJ_QUESTION) ||
471                                                                         ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
472                                                                         $item["body"] .= add_page_info($attribute['href']);
473                                                                 }
474                                                                 break;
475                                                         case "ostatus:conversation":
476                                                                 $conversation = $attribute['href'];
477                                                                 $item['conversation-href'] = $conversation;
478                                                                 if (!isset($item['conversation-uri'])) {
479                                                                         $item['conversation-uri'] = $item['conversation-href'];
480                                                                 }
481                                                                 break;
482                                                         case "enclosure":
483                                                                 $filetype = strtolower(substr($attribute['type'], 0, strpos($attribute['type'],'/')));
484                                                                 if ($filetype == 'image') {
485                                                                         $item['body'] .= "\n[img]".$attribute['href'].'[/img]';
486                                                                 } else {
487                                                                         if (strlen($item["attach"])) {
488                                                                                 $item["attach"] .= ',';
489                                                                         }
490                                                                         if (!isset($attribute['length'])) {
491                                                                                 $attribute['length'] = "0";
492                                                                         }
493                                                                         $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.$attribute['title'].'"[/attach]';
494                                                                 }
495                                                                 break;
496                                                         case "related":
497                                                                 if ($item["object-type"] != ACTIVITY_OBJ_BOOKMARK) {
498                                                                         if (!isset($item["parent-uri"])) {
499                                                                                 $item["parent-uri"] = $attribute['href'];
500                                                                         }
501                                                                         if ($related == "") {
502                                                                                 $related = $attribute['href'];
503                                                                         }
504                                                                 } else {
505                                                                         $item["body"] .= add_page_info($attribute['href']);
506                                                                 }
507                                                                 break;
508                                                         case "self":
509                                                                 $self = $attribute['href'];
510                                                                 break;
511                                                         case "mentioned":
512                                                                 // Notification check
513                                                                 if ($importer["nurl"] == normalise_link($attribute['href'])) {
514                                                                         $mention = true;
515                                                                 }
516                                                                 break;
517                                                 }
518                                         }
519                                 }
520                         }
521
522                         // Only add additional data when there is no picture in the post
523                         if (!strstr($item["body"],'[/img]')) {
524                                 $item["body"] = add_page_info_to_body($item["body"]);
525                         }
526
527                         // Mastodon Content Warning
528                         if (($item["verb"] == ACTIVITY_POST) && $xpath->evaluate('boolean(atom:summary)', $entry)) {
529                                 $clear_text = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
530
531                                 $item["body"] = html2bbcode($clear_text) . '[spoiler]' . $item["body"] . '[/spoiler]';
532                         }
533
534                         $local_id = "";
535                         $repeat_of = "";
536
537                         $notice_info = $xpath->query('statusnet:notice_info', $entry);
538                         if ($notice_info && ($notice_info->length > 0)) {
539                                 foreach ($notice_info->item(0)->attributes AS $attributes) {
540                                         if ($attributes->name == "source") {
541                                                 $item["app"] = strip_tags($attributes->textContent);
542                                         }
543                                         if ($attributes->name == "local_id") {
544                                                 $local_id = $attributes->textContent;
545                                         }
546                                         if ($attributes->name == "repeat_of") {
547                                                 $repeat_of = $attributes->textContent;
548                                         }
549                                 }
550                         }
551
552                         // Is it a repeated post?
553                         if (($repeat_of != "") || ($item["verb"] == ACTIVITY_SHARE)) {
554                                 $activityobjects = $xpath->query('activity:object', $entry)->item(0);
555
556                                 if (is_object($activityobjects)) {
557
558                                         $orig_uri = $xpath->query("activity:object/atom:id", $activityobjects)->item(0)->nodeValue;
559                                         if (!isset($orig_uri)) {
560                                                 $orig_uri = $xpath->query('atom:id/text()', $activityobjects)->item(0)->nodeValue;
561                                         }
562                                         $orig_links = $xpath->query("activity:object/atom:link[@rel='alternate']", $activityobjects);
563                                         if ($orig_links && ($orig_links->length > 0)) {
564                                                 foreach ($orig_links->item(0)->attributes AS $attributes) {
565                                                         if ($attributes->name == "href") {
566                                                                 $orig_link = $attributes->textContent;
567                                                         }
568                                                 }
569                                         }
570                                         if (!isset($orig_link)) {
571                                                 $orig_link = $xpath->query("atom:link[@rel='alternate']", $activityobjects)->item(0)->nodeValue;
572                                         }
573                                         if (!isset($orig_link)) {
574                                                 $orig_link =  self::convert_href($orig_uri);
575                                         }
576                                         $orig_body = $xpath->query('activity:object/atom:content/text()', $activityobjects)->item(0)->nodeValue;
577                                         if (!isset($orig_body)) {
578                                                 $orig_body = $xpath->query('atom:content/text()', $activityobjects)->item(0)->nodeValue;
579                                         }
580                                         $orig_created = $xpath->query('atom:published/text()', $activityobjects)->item(0)->nodeValue;
581                                         $orig_edited = $xpath->query('atom:updated/text()', $activityobjects)->item(0)->nodeValue;
582
583                                         $orig_contact = $contact;
584                                         $orig_author = self::fetchauthor($xpath, $activityobjects, $importer, $orig_contact, false);
585
586                                         $item["author-name"] = $orig_author["author-name"];
587                                         $item["author-link"] = $orig_author["author-link"];
588                                         $item["author-avatar"] = $orig_author["author-avatar"];
589
590                                         $item["body"] = add_page_info_to_body(html2bbcode($orig_body));
591                                         $item["created"] = $orig_created;
592                                         $item["edited"] = $orig_edited;
593
594                                         $item["uri"] = $orig_uri;
595
596                                         if (!isset($item["plink"])) {
597                                                 $item["plink"] = $orig_link;
598                                         }
599
600                                         $item["verb"] = $xpath->query('activity:verb/text()', $activityobjects)->item(0)->nodeValue;
601
602                                         $item["object-type"] = $xpath->query('activity:object/activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
603                                         if (!isset($item["object-type"])) {
604                                                 $item["object-type"] = $xpath->query('activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
605                                         }
606
607                                         $enclosures = $xpath->query("atom:link[@rel='alternate']", $activityobjects);
608                                         if ($enclosures) {
609                                                 foreach ($enclosures AS $link) {
610                                                         $attribute = self::read_attributes($link);
611                                                         if ($href != "") {
612                                                                 if (strlen($item["attach"])) {
613                                                                         $item["attach"] .= ',';
614                                                                 }
615                                                                 if (!isset($attribute['length'])) {
616                                                                         $attribute['length'] = "0";
617                                                                 }
618                                                                 $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.$attribute['title'].'"[/attach]';
619                                                         }
620                                                 }
621                                         }
622                                 }
623                         }
624
625                         if (isset($item["parent-uri"])) {
626                                 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
627                                         intval($importer["uid"]), dbesc($item["parent-uri"]));
628
629                                 // Only fetch missing stuff if it is a comment or reshare.
630                                 if (in_array($item["verb"], array(ACTIVITY_POST, ACTIVITY_SHARE)) &&
631                                         !dbm::is_result($r) && ($related != "")) {
632                                         $reply_path = str_replace("/notice/", "/api/statuses/show/", $related).".atom";
633
634                                         if ($reply_path != $related) {
635                                                 logger("Fetching related items for user ".$importer["uid"]." from ".$reply_path, LOGGER_DEBUG);
636                                                 $reply_xml = fetch_url($reply_path);
637
638                                                 $reply_contact = $contact;
639                                                 self::import($reply_xml,$importer,$reply_contact, $reply_hub);
640
641                                                 // After the import try to fetch the parent item again
642                                                 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
643                                                         intval($importer["uid"]), dbesc($item["parent-uri"]));
644                                         }
645                                 }
646                                 if (dbm::is_result($r)) {
647                                         $item["type"] = 'remote-comment';
648                                         $item["gravity"] = GRAVITY_COMMENT;
649                                 }
650                         } else {
651                                 $item["parent-uri"] = $item["uri"];
652                         }
653                         $item_id = self::completion($conversation, $importer["uid"], $item, $self);
654
655                         if (!$item_id) {
656                                 // Store the conversation data. This is normally done in "item_store"
657                                 // but since something went wrong, we want to be sure to save the data.
658                                 store_conversation($item);
659                                 logger("Error storing item", LOGGER_DEBUG);
660                                 continue;
661                         }
662
663                         logger("Item was stored with id ".$item_id, LOGGER_DEBUG);
664                 }
665         }
666
667         /**
668          * @brief Create an url out of an uri
669          *
670          * @param string $href URI in the format "parameter1:parameter1:..."
671          *
672          * @return string URL in the format http(s)://....
673          */
674         public static function convert_href($href) {
675                 $elements = explode(":",$href);
676
677                 if ((count($elements) <= 2) || ($elements[0] != "tag"))
678                         return $href;
679
680                 $server = explode(",", $elements[1]);
681                 $conversation = explode("=", $elements[2]);
682
683                 if ((count($elements) == 4) && ($elements[2] == "post"))
684                         return "http://".$server[0]."/notice/".$elements[3];
685
686                 if ((count($conversation) != 2) || ($conversation[1] =="")) {
687                         return $href;
688                 }
689                 if ($elements[3] == "objectType=thread") {
690                         return "http://".$server[0]."/conversation/".$conversation[1];
691                 } else {
692                         return "http://".$server[0]."/notice/".$conversation[1];
693                 }
694                 return $href;
695         }
696
697         /**
698          * @brief Checks if there are entries in conversations that aren't present on our side
699          *
700          * @param bool $mentions Fetch conversations where we are mentioned
701          * @param bool $override Override the interval setting
702          */
703         public static function check_conversations($mentions = false, $override = false) {
704                 $last = get_config('system','ostatus_last_poll');
705
706                 $poll_interval = intval(get_config('system','ostatus_poll_interval'));
707                 if (!$poll_interval) {
708                         $poll_interval = self::OSTATUS_DEFAULT_POLL_INTERVAL;
709                 }
710
711                 // Don't poll if the interval is set negative
712                 if (($poll_interval < 0) && !$override) {
713                         return;
714                 }
715
716                 if (!$mentions) {
717                         $poll_timeframe = intval(get_config('system','ostatus_poll_timeframe'));
718                         if (!$poll_timeframe) {
719                                 $poll_timeframe = self::OSTATUS_DEFAULT_POLL_TIMEFRAME;
720                         }
721                 } else {
722                         $poll_timeframe = intval(get_config('system','ostatus_poll_timeframe'));
723                         if (!$poll_timeframe) {
724                                 $poll_timeframe = self::OSTATUS_DEFAULT_POLL_TIMEFRAME_MENTIONS;
725                         }
726                 }
727
728
729                 if ($last && !$override) {
730                         $next = $last + ($poll_interval * 60);
731                         if ($next > time()) {
732                                 logger('poll interval not reached');
733                                 return;
734                         }
735                 }
736
737                 logger('cron_start');
738
739                 $start = date("Y-m-d H:i:s", time() - ($poll_timeframe * 60));
740
741                 if ($mentions) {
742                         $conversations = q("SELECT `term`.`oid`, `term`.`url`, `term`.`uid` FROM `term`
743                                                 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `term`.`oid` AND `thread`.`uid` = `term`.`uid`
744                                                 WHERE `term`.`type` = 7 AND `term`.`term` > '%s' AND `thread`.`mention`
745                                                 GROUP BY `term`.`url`, `term`.`uid`, `term`.`oid`, `term`.`term` ORDER BY `term`.`term` DESC", dbesc($start));
746                 } else {
747                         $conversations = q("SELECT `oid`, `url`, `uid` FROM `term`
748                                                 WHERE `type` = 7 AND `term` > '%s'
749                                                 GROUP BY `url`, `uid`, `oid`, `term` ORDER BY `term` DESC", dbesc($start));
750                 }
751
752                 foreach ($conversations AS $conversation) {
753                         self::completion($conversation['url'], $conversation['uid']);
754                 }
755
756                 logger('cron_end');
757
758                 set_config('system','ostatus_last_poll', time());
759         }
760
761         /**
762          * @brief Updates the gcontact table with actor data from the conversation
763          *
764          * @param object $actor The actor object that contains the contact data
765          */
766         private static function conv_fetch_actor($actor) {
767
768                 // We set the generation to "3" since the data here is not as reliable as the data we get on other occasions
769                 $contact = array("network" => NETWORK_OSTATUS, "generation" => 3);
770
771                 if (isset($actor->url))
772                         $contact["url"] = $actor->url;
773
774                 if (isset($actor->displayName))
775                         $contact["name"] = $actor->displayName;
776
777                 if (isset($actor->portablecontacts_net->displayName))
778                         $contact["name"] = $actor->portablecontacts_net->displayName;
779
780                 if (isset($actor->portablecontacts_net->preferredUsername))
781                         $contact["nick"] = $actor->portablecontacts_net->preferredUsername;
782
783                 if (isset($actor->id))
784                         $contact["alias"] = $actor->id;
785
786                 if (isset($actor->summary))
787                         $contact["about"] = $actor->summary;
788
789                 if (isset($actor->portablecontacts_net->note))
790                         $contact["about"] = $actor->portablecontacts_net->note;
791
792                 if (isset($actor->portablecontacts_net->addresses->formatted))
793                         $contact["location"] = $actor->portablecontacts_net->addresses->formatted;
794
795
796                 if (isset($actor->image->url))
797                         $contact["photo"] = $actor->image->url;
798
799                 if (isset($actor->image->width))
800                         $avatarwidth = $actor->image->width;
801
802                 if (is_array($actor->status_net->avatarLinks))
803                         foreach ($actor->status_net->avatarLinks AS $avatar) {
804                                 if ($avatarsize < $avatar->width) {
805                                         $contact["photo"] = $avatar->url;
806                                         $avatarsize = $avatar->width;
807                                 }
808                         }
809
810                 $contact["hide"] = false; // OStatus contacts are never hidden
811                 update_gcontact($contact);
812         }
813
814         /**
815          * @brief Fetches the conversation url for a given item link or conversation id
816          *
817          * @param string $self The link to the posting
818          * @param string $conversation_id The conversation id
819          *
820          * @return string The conversation url
821          */
822         private static function fetch_conversation($self, $conversation_id = "") {
823
824                 if ($conversation_id != "") {
825                         $elements = explode(":", $conversation_id);
826
827                         if ((count($elements) <= 2) || ($elements[0] != "tag"))
828                                 return $conversation_id;
829                 }
830
831                 if ($self == "")
832                         return "";
833
834                 $json = str_replace(".atom", ".json", $self);
835
836                 $raw = fetch_url($json);
837                 if ($raw == "")
838                         return "";
839
840                 $data = json_decode($raw);
841                 if (!is_object($data))
842                         return "";
843
844                 $conversation_id = $data->statusnet_conversation_id;
845
846                 $pos = strpos($self, "/api/statuses/show/");
847                 $base_url = substr($self, 0, $pos);
848
849                 return $base_url."/conversation/".$conversation_id;
850         }
851
852         /**
853          * @brief Fetches a shared object from a given conversation object
854          *
855          * Sometimes GNU Social seems to fail when returning shared objects.
856          * Then they don't contains all needed data.
857          * We then try to find this object in the conversation
858          *
859          * @param string $id Message id
860          * @param object $conversation Conversation object
861          *
862          * @return object The shared object
863          */
864         private static function shared_object($id, $conversation) {
865                 if (!is_array($conversation->items)) {
866                         return false;
867                 }
868                 foreach ($conversation->items AS $single_conv) {
869                         if ($single_conv->id == $id) {
870                                 return $single_conv;
871                         }
872                 }
873                 return false;
874         }
875
876         /**
877          * @brief Fetches actor details of a given actor and user id
878          *
879          * @param string $actor The actor url
880          * @param int $uid The user id
881          * @param int $contact_id The default contact-id
882          *
883          * @return array Array with actor details
884          */
885         private static function get_actor_details($actor, $uid, $contact_id) {
886
887                 $details = array();
888
889                 $contact = q("SELECT `id`, `rel`, `network` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'",
890                                         $uid, normalise_link($actor), NETWORK_STATUSNET);
891
892                 if (!$contact)
893                         $contact = q("SELECT `id`, `rel`, `network` FROM `contact` WHERE `uid` = %d AND `alias` IN ('%s', '%s') AND `network` != '%s'",
894                                         $uid, $actor, normalise_link($actor), NETWORK_STATUSNET);
895
896                 if ($contact) {
897                         logger("Found contact for url ".$actor, LOGGER_DEBUG);
898                         $details["contact_id"] = $contact[0]["id"];
899                         $details["network"] = $contact[0]["network"];
900
901                         $details["not_following"] = !in_array($contact[0]["rel"], array(CONTACT_IS_SHARING, CONTACT_IS_FRIEND));
902                 } else {
903                         logger("No contact found for user ".$uid." and url ".$actor, LOGGER_DEBUG);
904
905                         // Adding a global contact
906                         /// @TODO Use this data for the post
907                         $details["global_contact_id"] = get_contact($actor, 0);
908
909                         logger("Global contact ".$global_contact_id." found for url ".$actor, LOGGER_DEBUG);
910
911                         $details["contact_id"] = $contact_id;
912                         $details["network"] = NETWORK_OSTATUS;
913
914                         $details["not_following"] = true;
915                 }
916
917                 return $details;
918         }
919
920         /**
921          * @brief Stores an item and completes the thread
922          *
923          * @param string $conversation_url The URI of the conversation
924          * @param integer $uid The user id
925          * @param array $item Data of the item that is to be posted
926          *
927          * @return integer The item id of the posted item array
928          */
929         private static function completion($conversation_url, $uid, $item = array(), $self = "") {
930
931                 /// @todo This function is totally ugly and has to be rewritten totally
932
933                 // Import all threads or only threads that were started by our followers?
934                 $all_threads = !get_config('system','ostatus_full_threads');
935
936                 $item_stored = -1;
937
938                 $conversation_url = self::fetch_conversation($self, $conversation_url);
939
940                 // If the thread shouldn't be completed then store the item and go away
941                 // Don't do a completion on liked content
942                 if (((intval(get_config('system','ostatus_poll_interval')) == -2) && (count($item) > 0)) ||
943                         ($item["verb"] == ACTIVITY_LIKE) || ($conversation_url == "")) {
944                         $item_stored = item_store($item, $all_threads);
945                         return $item_stored;
946                 }
947
948                 // Get the parent
949                 $parents = q("SELECT `item`.`id`, `item`.`parent`, `item`.`uri`, `item`.`contact-id`, `item`.`type`,
950                                 `item`.`verb`, `item`.`visible` FROM `term`
951                                 STRAIGHT_JOIN `item` AS `thritem` ON `thritem`.`parent` = `term`.`oid`
952                                 STRAIGHT_JOIN `item` ON `item`.`parent` = `thritem`.`parent`
953                                 WHERE `term`.`uid` = %d AND `term`.`otype` = %d AND `term`.`type` = %d AND `term`.`url` = '%s'",
954                                 intval($uid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION), dbesc($conversation_url));
955                 if ($parents) {
956                         $parent = $parents[0];
957                 } elseif (count($item) > 0) {
958                         $parent = $item;
959                         $parent["type"] = "remote";
960                         $parent["verb"] = ACTIVITY_POST;
961                         $parent["visible"] = 1;
962                 } else {
963                         // Preset the parent
964                         $r = q("SELECT `id` FROM `contact` WHERE `self` AND `uid`=%d", $uid);
965                         if (!dbm::is_result($r)) {
966                                 return -2;
967                         }
968                         $parent = array();
969                         $parent["id"] = 0;
970                         $parent["parent"] = 0;
971                         $parent["uri"] = "";
972                         $parent["contact-id"] = $r[0]["id"];
973                         $parent["type"] = "remote";
974                         $parent["verb"] = ACTIVITY_POST;
975                         $parent["visible"] = 1;
976                 }
977
978                 $conv = str_replace("/conversation/", "/api/statusnet/conversation/", $conversation_url).".as";
979                 $pageno = 1;
980                 $items = array();
981
982                 logger('fetching conversation url '.$conv.' (Self: '.$self.') for user '.$uid);
983
984                 do {
985                         $conv_arr = z_fetch_url($conv."?page=".$pageno);
986
987                         // If it is a non-ssl site and there is an error, then try ssl or vice versa
988                         if (!$conv_arr["success"] && (substr($conv, 0, 7) == "http://")) {
989                                 $conv = str_replace("http://", "https://", $conv);
990                                 $conv_as = fetch_url($conv."?page=".$pageno);
991                         } elseif (!$conv_arr["success"] && (substr($conv, 0, 8) == "https://")) {
992                                 $conv = str_replace("https://", "http://", $conv);
993                                 $conv_as = fetch_url($conv."?page=".$pageno);
994                         } else {
995                                 $conv_as = $conv_arr["body"];
996                         }
997                         $conv_as = str_replace(',"statusnet:notice_info":', ',"statusnet_notice_info":', $conv_as);
998                         $conv_as = json_decode($conv_as);
999
1000                         $no_of_items = sizeof($items);
1001
1002                         if (@is_array($conv_as->items))
1003                                 foreach ($conv_as->items AS $single_item)
1004                                         $items[$single_item->id] = $single_item;
1005
1006                         if ($no_of_items == sizeof($items))
1007                                 break;
1008
1009                         $pageno++;
1010
1011                 } while (true);
1012
1013                 logger('fetching conversation done. Found '.count($items).' items');
1014
1015                 if (!sizeof($items)) {
1016                         if (count($item) > 0) {
1017                                 $item_stored = item_store($item, $all_threads);
1018
1019                                 if ($item_stored) {
1020                                         logger("Conversation ".$conversation_url." couldn't be fetched. Item uri ".$item["uri"]." stored: ".$item_stored, LOGGER_DEBUG);
1021                                         self::store_conversation($item_id, $conversation_url);
1022                                 }
1023
1024                                 return $item_stored;
1025                         } else {
1026                                 return -3;
1027                         }
1028                 }
1029
1030                 $items = array_reverse($items);
1031
1032                 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self`", intval($uid));
1033                 $importer = $r[0];
1034
1035                 $new_parent = true;
1036
1037                 foreach ($items as $single_conv) {
1038
1039                         // Update the gcontact table
1040                         self::conv_fetch_actor($single_conv->actor);
1041
1042                         // Test - remove before flight
1043                         //$tempfile = tempnam(get_temppath(), "conversation");
1044                         //file_put_contents($tempfile, json_encode($single_conv));
1045
1046                         $mention = false;
1047
1048                         if (isset($single_conv->object->id))
1049                                 $single_conv->id = $single_conv->object->id;
1050
1051                         $plink = self::convert_href($single_conv->id);
1052                         if (isset($single_conv->object->url))
1053                                 $plink = self::convert_href($single_conv->object->url);
1054
1055                         if (@!$single_conv->id)
1056                                 continue;
1057
1058                         logger("Got id ".$single_conv->id, LOGGER_DEBUG);
1059
1060                         if ($first_id == "") {
1061                                 $first_id = $single_conv->id;
1062
1063                                 // The first post of the conversation isn't our first post. There are three options:
1064                                 // 1. Our conversation hasn't the "real" thread starter
1065                                 // 2. This first post is a post inside our thread
1066                                 // 3. This first post is a post inside another thread
1067                                 if (($first_id != $parent["uri"]) && ($parent["uri"] != "")) {
1068
1069                                         $new_parent = true;
1070
1071                                         $new_parents = q("SELECT `id`, `parent`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `id` IN
1072                                                                 (SELECT `parent` FROM `item`
1073                                                                         WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s')) LIMIT 1",
1074                                                 intval($uid), dbesc($first_id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
1075                                         if ($new_parents) {
1076                                                 if ($new_parents[0]["parent"] == $parent["parent"]) {
1077                                                         // Option 2: This post is already present inside our thread - but not as thread starter
1078                                                         logger("Option 2: uri present in our thread: ".$first_id, LOGGER_DEBUG);
1079                                                         $first_id = $parent["uri"];
1080                                                 } else {
1081                                                         // Option 3: Not so good. We have mixed parents. We have to see how to clean this up.
1082                                                         // For now just take the new parent.
1083                                                         $parent = $new_parents[0];
1084                                                         $first_id = $parent["uri"];
1085                                                         logger("Option 3: mixed parents for uri ".$first_id, LOGGER_DEBUG);
1086                                                 }
1087                                         } else {
1088                                                 // Option 1: We hadn't got the real thread starter
1089                                                 // We have to clean up our existing messages.
1090                                                 $parent["id"] = 0;
1091                                                 $parent["uri"] = $first_id;
1092                                                 logger("Option 1: we have a new parent: ".$first_id, LOGGER_DEBUG);
1093                                         }
1094                                 } elseif ($parent["uri"] == "") {
1095                                         $parent["id"] = 0;
1096                                         $parent["uri"] = $first_id;
1097                                 }
1098                         }
1099
1100                         $parent_uri = $parent["uri"];
1101
1102                         // "context" only seems to exist on older servers
1103                         if (isset($single_conv->context->inReplyTo->id)) {
1104                                 $parent_exists = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
1105                                                         intval($uid), dbesc($single_conv->context->inReplyTo->id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
1106                                 if ($parent_exists)
1107                                         $parent_uri = $single_conv->context->inReplyTo->id;
1108                         }
1109
1110                         // This is the current way
1111                         if (isset($single_conv->object->inReplyTo->id)) {
1112                                 $parent_exists = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
1113                                                         intval($uid), dbesc($single_conv->object->inReplyTo->id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
1114                                 if ($parent_exists)
1115                                         $parent_uri = $single_conv->object->inReplyTo->id;
1116                         }
1117
1118                         $message_exists = q("SELECT `id`, `parent`, `uri` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
1119                                                         intval($uid), dbesc($single_conv->id),
1120                                                         dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
1121                         if ($message_exists) {
1122                                 logger("Message ".$single_conv->id." already existed on the system", LOGGER_DEBUG);
1123
1124                                 if ($parent["id"] != 0) {
1125                                         $existing_message = $message_exists[0];
1126
1127                                         // We improved the way we fetch OStatus messages, this shouldn't happen very often now
1128                                         /// @TODO We have to change the shadow copies as well. This way here is really ugly.
1129                                         if ($existing_message["parent"] != $parent["id"]) {
1130                                                 logger('updating id '.$existing_message["id"].' with parent '.$existing_message["parent"].' to parent '.$parent["id"].' uri '.$parent["uri"].' thread '.$parent_uri, LOGGER_DEBUG);
1131
1132                                                 // Update the parent id of the selected item
1133                                                 $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s' WHERE `id` = %d",
1134                                                         intval($parent["id"]), dbesc($parent["uri"]), intval($existing_message["id"]));
1135
1136                                                 // Update the parent uri in the thread - but only if it points to itself
1137                                                 $r = q("UPDATE `item` SET `thr-parent` = '%s' WHERE `id` = %d AND `uri` = `thr-parent`",
1138                                                         dbesc($parent_uri), intval($existing_message["id"]));
1139
1140                                                 // try to change all items of the same parent
1141                                                 $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s' WHERE `parent` = %d",
1142                                                         intval($parent["id"]), dbesc($parent["uri"]), intval($existing_message["parent"]));
1143
1144                                                 // Update the parent uri in the thread - but only if it points to itself
1145                                                 $r = q("UPDATE `item` SET `thr-parent` = '%s' WHERE (`parent` = %d) AND (`uri` = `thr-parent`)",
1146                                                         dbesc($parent["uri"]), intval($existing_message["parent"]));
1147
1148                                                 // Now delete the thread
1149                                                 delete_thread($existing_message["parent"]);
1150                                         }
1151                                 }
1152
1153                                 // The item we are having on the system is the one that we wanted to store via the item array
1154                                 if (isset($item["uri"]) && ($item["uri"] == $existing_message["uri"])) {
1155                                         $item = array();
1156                                         $item_stored = 0;
1157                                 }
1158
1159                                 continue;
1160                         }
1161
1162                         if (is_array($single_conv->to))
1163                                 foreach ($single_conv->to AS $to)
1164                                         if ($importer["nurl"] == normalise_link($to->id))
1165                                                 $mention = true;
1166
1167                         $actor = $single_conv->actor->id;
1168                         if (isset($single_conv->actor->url))
1169                                 $actor = $single_conv->actor->url;
1170
1171                         $details = self::get_actor_details($actor, $uid, $parent["contact-id"]);
1172
1173                         // Do we only want to import threads that were started by our contacts?
1174                         if ($details["not_following"] && $new_parent && get_config('system','ostatus_full_threads')) {
1175                                 logger("Don't import uri ".$first_id." because user ".$uid." doesn't follow the person ".$actor, LOGGER_DEBUG);
1176                                 continue;
1177                         }
1178
1179                         /// @TODO One statment is okay (until if () )
1180                         $arr = array();
1181                         $arr["network"] = $details["network"];
1182                         $arr["uri"] = $single_conv->id;
1183                         $arr["plink"] = $plink;
1184                         $arr["uid"] = $uid;
1185                         $arr["contact-id"] = $details["contact_id"];
1186                         $arr["parent-uri"] = $parent_uri;
1187                         $arr["created"] = $single_conv->published;
1188                         $arr["edited"] = $single_conv->published;
1189                         $arr["owner-name"] = $single_conv->actor->displayName;
1190                         if ($arr["owner-name"] == '')
1191                                 $arr["owner-name"] = $single_conv->actor->contact->displayName;
1192                         if ($arr["owner-name"] == '')
1193                                 $arr["owner-name"] = $single_conv->actor->portablecontacts_net->displayName;
1194
1195                         $arr["owner-link"] = $actor;
1196                         $arr["owner-avatar"] = Probe::fixAvatar($single_conv->actor->image->url, $arr["owner-link"]);
1197
1198                         $arr["author-name"] = $arr["owner-name"];
1199                         $arr["author-link"] = $arr["owner-link"];
1200                         $arr["author-avatar"] = $arr["owner-avatar"];
1201                         $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->content));
1202
1203                         if (isset($single_conv->status_net->conversation)) {
1204                                 $arr['conversation-uri'] = $single_conv->status_net->conversation;
1205                         }
1206
1207                         if (isset($single_conv->status_net->notice_info->source)) {
1208                                 $arr["app"] = strip_tags($single_conv->status_net->notice_info->source);
1209                         } elseif (isset($single_conv->statusnet->notice_info->source)) {
1210                                 $arr["app"] = strip_tags($single_conv->statusnet->notice_info->source);
1211                         } elseif (isset($single_conv->statusnet_notice_info->source)) {
1212                                 $arr["app"] = strip_tags($single_conv->statusnet_notice_info->source);
1213                         } elseif (isset($single_conv->provider->displayName)) {
1214                                 $arr["app"] = $single_conv->provider->displayName;
1215                         } else {
1216                                 $arr["app"] = "OStatus";
1217                         }
1218
1219                         $arr["source"] = json_encode($single_conv);
1220                         $arr["protocol"] = PROTOCOL_GS_CONVERSATION;
1221
1222                         $arr["verb"] = $parent["verb"];
1223                         $arr["visible"] = $parent["visible"];
1224                         $arr["location"] = $single_conv->location->displayName;
1225                         $arr["coord"] = trim($single_conv->location->lat." ".$single_conv->location->lon);
1226
1227                         // Is it a reshared item?
1228                         if (isset($single_conv->verb) && ($single_conv->verb == "share") && isset($single_conv->object)) {
1229                                 if (is_array($single_conv->object))
1230                                         $single_conv->object = $single_conv->object[0];
1231
1232                                 // Sometimes GNU Social doesn't returns a complete object
1233                                 if (!isset($single_conv->object->actor->url)) {
1234                                         $object = self::shared_object($single_conv->object->id, $conversation);
1235                                         if (is_object($object)) {
1236                                                 $single_conv->object = $object;
1237                                         }
1238                                 }
1239
1240                                 if (isset($single_conv->object->actor->url)) {
1241                                         logger("Found reshared item ".$single_conv->object->id);
1242
1243                                         // $single_conv->object->context->conversation;
1244
1245                                         if (isset($single_conv->object->object->id)) {
1246                                                 $arr["uri"] = $single_conv->object->object->id;
1247                                         } else {
1248                                                 $arr["uri"] = $single_conv->object->id;
1249                                         }
1250                                         if (isset($single_conv->object->object->url)) {
1251                                                 $plink = self::convert_href($single_conv->object->object->url);
1252                                         } else {
1253                                                 $plink = self::convert_href($single_conv->object->url);
1254                                         }
1255                                         if (isset($single_conv->object->object->content)) {
1256                                                 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->object->content));
1257                                         } else {
1258                                                 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->content));
1259                                         }
1260                                         $arr["plink"] = $plink;
1261
1262                                         $arr["created"] = $single_conv->object->published;
1263                                         $arr["edited"] = $single_conv->object->published;
1264
1265                                         $arr["author-name"] = $single_conv->object->actor->displayName;
1266                                         if ($arr["owner-name"] == '') {
1267                                                 $arr["author-name"] = $single_conv->object->actor->contact->displayName;
1268                                         }
1269                                         $arr["author-link"] = $single_conv->object->actor->url;
1270                                         $arr["author-avatar"] = Probe::fixAvatar($single_conv->object->actor->image->url, $arr["author-link"]);
1271
1272                                         $arr["app"] = $single_conv->object->provider->displayName."#";
1273                                         //$arr["verb"] = $single_conv->object->verb;
1274
1275                                         $arr["location"] = $single_conv->object->location->displayName;
1276                                         $arr["coord"] = trim($single_conv->object->location->lat." ".$single_conv->object->location->lon);
1277                                 }
1278                         }
1279
1280                         if ($arr["location"] == "")
1281                                 unset($arr["location"]);
1282
1283                         if ($arr["coord"] == "")
1284                                 unset($arr["coord"]);
1285
1286                         // Copy fields from given item array
1287                         if (isset($item["uri"]) && (($item["uri"] == $arr["uri"]) || ($item["uri"] ==  $single_conv->id))) {
1288                                 logger('Use stored item array for item with URI '.$item["uri"], LOGGER_DEBUG);
1289                                 $newitem = item_store($item);
1290                                 $item = array();
1291                                 $item_stored = $newitem;
1292                         } else {
1293                                 $newitem = item_store($arr);
1294                         }
1295
1296                         if (!$newitem) {
1297                                 logger("Item wasn't stored ".print_r($arr, true), LOGGER_DEBUG);
1298                                 continue;
1299                         }
1300
1301                         logger('Stored new item '.$plink.' for parent '.$arr["parent-uri"].' under id '.$newitem, LOGGER_DEBUG);
1302
1303                         // Add the conversation entry (but don't fetch the whole conversation)
1304                         self::store_conversation($newitem, $conversation_url);
1305
1306                         // If the newly created item is the top item then change the parent settings of the thread
1307                         // This shouldn't happen anymore. This is supposed to be absolote.
1308                         if ($arr["uri"] == $first_id) {
1309                                 logger('setting new parent to id '.$newitem);
1310                                 $new_parents = q("SELECT `id`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `uid` = %d AND `id` = %d LIMIT 1",
1311                                         intval($uid), intval($newitem));
1312                                 if ($new_parents)
1313                                         $parent = $new_parents[0];
1314                         }
1315                 }
1316
1317                 if (($item_stored < 0) && (count($item) > 0)) {
1318
1319                         if (get_config('system','ostatus_full_threads')) {
1320                                 $details = self::get_actor_details($item["owner-link"], $uid, $item["contact-id"]);
1321                                 if ($details["not_following"]) {
1322                                         logger("Don't import uri ".$item["uri"]." because user ".$uid." doesn't follow the person ".$item["owner-link"], LOGGER_DEBUG);
1323                                         return false;
1324                                 }
1325                         }
1326
1327                         $item_stored = item_store($item, $all_threads);
1328                         if ($item_stored) {
1329                                 logger("Uri ".$item["uri"]." wasn't found in conversation ".$conversation_url, LOGGER_DEBUG);
1330                                 self::store_conversation($item_stored, $conversation_url);
1331                         }
1332                 }
1333
1334                 return $item_stored;
1335         }
1336
1337         /**
1338          * @brief Stores conversation data into the database
1339          *
1340          * @param integer $itemid The id of the item
1341          * @param string $conversation_url The uri of the conversation
1342          */
1343         private static function store_conversation($itemid, $conversation_url) {
1344
1345                 $conversation_url = self::convert_href($conversation_url);
1346
1347                 $messages = q("SELECT `uid`, `parent`, `created`, `received`, `guid` FROM `item` WHERE `id` = %d LIMIT 1", intval($itemid));
1348                 if (!$messages)
1349                         return;
1350                 $message = $messages[0];
1351
1352                 // Store conversation url if not done before
1353                 $conversation = q("SELECT `url` FROM `term` WHERE `uid` = %d AND `oid` = %d AND `otype` = %d AND `type` = %d",
1354                         intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION));
1355
1356                 if (!$conversation) {
1357                         $r = q("INSERT INTO `term` (`uid`, `oid`, `otype`, `type`, `term`, `url`, `created`, `received`, `guid`) VALUES (%d, %d, %d, %d, '%s', '%s', '%s', '%s', '%s')",
1358                                 intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION),
1359                                 dbesc($message["created"]), dbesc($conversation_url), dbesc($message["created"]), dbesc($message["received"]), dbesc($message["guid"]));
1360                         logger('Storing conversation url '.$conversation_url.' for id '.$itemid);
1361                 }
1362         }
1363
1364         /**
1365          * @brief Checks if the current post is a reshare
1366          *
1367          * @param array $item The item array of thw post
1368          *
1369          * @return string The guid if the post is a reshare
1370          */
1371         private static function get_reshared_guid($item) {
1372                 $body = trim($item["body"]);
1373
1374                 // Skip if it isn't a pure repeated messages
1375                 // Does it start with a share?
1376                 if (strpos($body, "[share") > 0)
1377                         return "";
1378
1379                 // Does it end with a share?
1380                 if (strlen($body) > (strrpos($body, "[/share]") + 8))
1381                         return "";
1382
1383                 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
1384                 // Skip if there is no shared message in there
1385                 if ($body == $attributes)
1386                         return false;
1387
1388                 $guid = "";
1389                 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
1390                 if ($matches[1] != "")
1391                         $guid = $matches[1];
1392
1393                 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
1394                 if ($matches[1] != "")
1395                         $guid = $matches[1];
1396
1397                 return $guid;
1398         }
1399
1400         /**
1401          * @brief Cleans the body of a post if it contains picture links
1402          *
1403          * @param string $body The body
1404          *
1405          * @return string The cleaned body
1406          */
1407         private static function format_picture_post($body) {
1408                 $siteinfo = get_attached_data($body);
1409
1410                 if (($siteinfo["type"] == "photo")) {
1411                         if (isset($siteinfo["preview"]))
1412                                 $preview = $siteinfo["preview"];
1413                         else
1414                                 $preview = $siteinfo["image"];
1415
1416                         // Is it a remote picture? Then make a smaller preview here
1417                         $preview = proxy_url($preview, false, PROXY_SIZE_SMALL);
1418
1419                         // Is it a local picture? Then make it smaller here
1420                         $preview = str_replace(array("-0.jpg", "-0.png"), array("-2.jpg", "-2.png"), $preview);
1421                         $preview = str_replace(array("-1.jpg", "-1.png"), array("-2.jpg", "-2.png"), $preview);
1422
1423                         if (isset($siteinfo["url"]))
1424                                 $url = $siteinfo["url"];
1425                         else
1426                                 $url = $siteinfo["image"];
1427
1428                         $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1429                 }
1430
1431                 return $body;
1432         }
1433
1434         /**
1435          * @brief Adds the header elements to the XML document
1436          *
1437          * @param object $doc XML document
1438          * @param array $owner Contact data of the poster
1439          *
1440          * @return object header root element
1441          */
1442         private static function add_header($doc, $owner) {
1443
1444                 $a = get_app();
1445
1446                 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
1447                 $doc->appendChild($root);
1448
1449                 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1450                 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1451                 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1452                 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1453                 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
1454                 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1455                 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1456                 $root->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1457
1458                 $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
1459                 xml::add_element($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1460                 xml::add_element($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]);
1461                 xml::add_element($doc, $root, "title", sprintf("%s timeline", $owner["name"]));
1462                 xml::add_element($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], $a->config["sitename"]));
1463                 xml::add_element($doc, $root, "logo", $owner["photo"]);
1464                 xml::add_element($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
1465
1466                 $author = self::add_author($doc, $owner);
1467                 $root->appendChild($author);
1468
1469                 $attributes = array("href" => $owner["url"], "rel" => "alternate", "type" => "text/html");
1470                 xml::add_element($doc, $root, "link", "", $attributes);
1471
1472                 /// @TODO We have to find out what this is
1473                 /// $attributes = array("href" => System::baseUrl()."/sup",
1474                 ///             "rel" => "http://api.friendfeed.com/2008/03#sup",
1475                 ///             "type" => "application/json");
1476                 /// xml::add_element($doc, $root, "link", "", $attributes);
1477
1478                 self::hublinks($doc, $root, $owner["nick"]);
1479
1480                 $attributes = array("href" => System::baseUrl()."/salmon/".$owner["nick"], "rel" => "salmon");
1481                 xml::add_element($doc, $root, "link", "", $attributes);
1482
1483                 $attributes = array("href" => System::baseUrl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies");
1484                 xml::add_element($doc, $root, "link", "", $attributes);
1485
1486                 $attributes = array("href" => System::baseUrl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention");
1487                 xml::add_element($doc, $root, "link", "", $attributes);
1488
1489                 $attributes = array("href" => System::baseUrl()."/api/statuses/user_timeline/".$owner["nick"].".atom",
1490                                 "rel" => "self", "type" => "application/atom+xml");
1491                 xml::add_element($doc, $root, "link", "", $attributes);
1492
1493                 return $root;
1494         }
1495
1496         /**
1497          * @brief Add the link to the push hubs to the XML document
1498          *
1499          * @param object $doc XML document
1500          * @param object $root XML root element where the hub links are added
1501          */
1502         public static function hublinks($doc, $root, $nick) {
1503                 $h = System::baseUrl() . '/pubsubhubbub/'.$nick;
1504                 xml::add_element($doc, $root, "link", "", array("href" => $h, "rel" => "hub"));
1505         }
1506
1507         /**
1508          * @brief Adds attachement data to the XML document
1509          *
1510          * @param object $doc XML document
1511          * @param object $root XML root element where the hub links are added
1512          * @param array $item Data of the item that is to be posted
1513          */
1514         private static function get_attachment($doc, $root, $item) {
1515                 $o = "";
1516                 $siteinfo = get_attached_data($item["body"]);
1517
1518                 switch ($siteinfo["type"]) {
1519                         case 'photo':
1520                                 $imgdata = get_photo_info($siteinfo["image"]);
1521                                 $attributes = array("rel" => "enclosure",
1522                                                 "href" => $siteinfo["image"],
1523                                                 "type" => $imgdata["mime"],
1524                                                 "length" => intval($imgdata["size"]));
1525                                 xml::add_element($doc, $root, "link", "", $attributes);
1526                                 break;
1527                         case 'video':
1528                                 $attributes = array("rel" => "enclosure",
1529                                                 "href" => $siteinfo["url"],
1530                                                 "type" => "text/html; charset=UTF-8",
1531                                                 "length" => "",
1532                                                 "title" => $siteinfo["title"]);
1533                                 xml::add_element($doc, $root, "link", "", $attributes);
1534                                 break;
1535                         default:
1536                                 break;
1537                 }
1538
1539                 if (!Config::get('system', 'ostatus_not_attach_preview') && ($siteinfo["type"] != "photo") && isset($siteinfo["image"])) {
1540                         $imgdata = get_photo_info($siteinfo["image"]);
1541                         $attributes = array("rel" => "enclosure",
1542                                         "href" => $siteinfo["image"],
1543                                         "type" => $imgdata["mime"],
1544                                         "length" => intval($imgdata["size"]));
1545
1546                         xml::add_element($doc, $root, "link", "", $attributes);
1547                 }
1548
1549                 $arr = explode('[/attach],', $item['attach']);
1550                 if (count($arr)) {
1551                         foreach ($arr as $r) {
1552                                 $matches = false;
1553                                 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1554                                 if ($cnt) {
1555                                         $attributes = array("rel" => "enclosure",
1556                                                         "href" => $matches[1],
1557                                                         "type" => $matches[3]);
1558
1559                                         if (intval($matches[2])) {
1560                                                 $attributes["length"] = intval($matches[2]);
1561                                         }
1562                                         if (trim($matches[4]) != "") {
1563                                                 $attributes["title"] = trim($matches[4]);
1564                                         }
1565                                         xml::add_element($doc, $root, "link", "", $attributes);
1566                                 }
1567                         }
1568                 }
1569         }
1570
1571         /**
1572          * @brief Adds the author element to the XML document
1573          *
1574          * @param object $doc XML document
1575          * @param array $owner Contact data of the poster
1576          *
1577          * @return object author element
1578          */
1579         private static function add_author($doc, $owner) {
1580
1581                 $r = q("SELECT `homepage`, `publish` FROM `profile` WHERE `uid` = %d AND `is-default` LIMIT 1", intval($owner["uid"]));
1582                 if (dbm::is_result($r)) {
1583                         $profile = $r[0];
1584                 }
1585                 $author = $doc->createElement("author");
1586                 xml::add_element($doc, $author, "id", $owner["url"]);
1587                 xml::add_element($doc, $author, "activity:object-type", ACTIVITY_OBJ_PERSON);
1588                 xml::add_element($doc, $author, "uri", $owner["url"]);
1589                 xml::add_element($doc, $author, "name", $owner["nick"]);
1590                 xml::add_element($doc, $author, "email", $owner["addr"]);
1591                 xml::add_element($doc, $author, "summary", bbcode($owner["about"], false, false, 7));
1592
1593                 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $owner["url"]);
1594                 xml::add_element($doc, $author, "link", "", $attributes);
1595
1596                 $attributes = array(
1597                                 "rel" => "avatar",
1598                                 "type" => "image/jpeg", // To-Do?
1599                                 "media:width" => 175,
1600                                 "media:height" => 175,
1601                                 "href" => $owner["photo"]);
1602                 xml::add_element($doc, $author, "link", "", $attributes);
1603
1604                 if (isset($owner["thumb"])) {
1605                         $attributes = array(
1606                                         "rel" => "avatar",
1607                                         "type" => "image/jpeg", // To-Do?
1608                                         "media:width" => 80,
1609                                         "media:height" => 80,
1610                                         "href" => $owner["thumb"]);
1611                         xml::add_element($doc, $author, "link", "", $attributes);
1612                 }
1613
1614                 xml::add_element($doc, $author, "poco:preferredUsername", $owner["nick"]);
1615                 xml::add_element($doc, $author, "poco:displayName", $owner["name"]);
1616                 xml::add_element($doc, $author, "poco:note", bbcode($owner["about"], false, false, 7));
1617
1618                 if (trim($owner["location"]) != "") {
1619                         $element = $doc->createElement("poco:address");
1620                         xml::add_element($doc, $element, "poco:formatted", $owner["location"]);
1621                         $author->appendChild($element);
1622                 }
1623
1624                 if (trim($profile["homepage"]) != "") {
1625                         $urls = $doc->createElement("poco:urls");
1626                         xml::add_element($doc, $urls, "poco:type", "homepage");
1627                         xml::add_element($doc, $urls, "poco:value", $profile["homepage"]);
1628                         xml::add_element($doc, $urls, "poco:primary", "true");
1629                         $author->appendChild($urls);
1630                 }
1631
1632                 if (count($profile)) {
1633                         xml::add_element($doc, $author, "followers", "", array("url" => System::baseUrl()."/viewcontacts/".$owner["nick"]));
1634                         xml::add_element($doc, $author, "statusnet:profile_info", "", array("local_id" => $owner["uid"]));
1635                 }
1636
1637                 if ($profile["publish"]) {
1638                         xml::add_element($doc, $author, "mastodon:scope", "public");
1639                 }
1640                 return $author;
1641         }
1642
1643         /**
1644          * @TODO Picture attachments should look like this:
1645          *      <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1646          *      class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1647          *
1648         */
1649
1650         /**
1651          * @brief Returns the given activity if present - otherwise returns the "post" activity
1652          *
1653          * @param array $item Data of the item that is to be posted
1654          *
1655          * @return string activity
1656          */
1657         private static function construct_verb($item) {
1658                 if ($item['verb'])
1659                         return $item['verb'];
1660                 return ACTIVITY_POST;
1661         }
1662
1663         /**
1664          * @brief Returns the given object type if present - otherwise returns the "note" object type
1665          *
1666          * @param array $item Data of the item that is to be posted
1667          *
1668          * @return string Object type
1669          */
1670         private static function construct_objecttype($item) {
1671                 if (in_array($item['object-type'], array(ACTIVITY_OBJ_NOTE, ACTIVITY_OBJ_COMMENT)))
1672                         return $item['object-type'];
1673                 return ACTIVITY_OBJ_NOTE;
1674         }
1675
1676         /**
1677          * @brief Adds an entry element to the XML document
1678          *
1679          * @param object $doc XML document
1680          * @param array $item Data of the item that is to be posted
1681          * @param array $owner Contact data of the poster
1682          * @param bool $toplevel
1683          *
1684          * @return object Entry element
1685          */
1686         private static function entry($doc, $item, $owner, $toplevel = false) {
1687                 $repeated_guid = self::get_reshared_guid($item);
1688                 if ($repeated_guid != "")
1689                         $xml = self::reshare_entry($doc, $item, $owner, $repeated_guid, $toplevel);
1690
1691                 if ($xml)
1692                         return $xml;
1693
1694                 if ($item["verb"] == ACTIVITY_LIKE) {
1695                         return self::like_entry($doc, $item, $owner, $toplevel);
1696                 } elseif (in_array($item["verb"], array(ACTIVITY_FOLLOW, NAMESPACE_OSTATUS."/unfollow"))) {
1697                         return self::follow_entry($doc, $item, $owner, $toplevel);
1698                 } else {
1699                         return self::note_entry($doc, $item, $owner, $toplevel);
1700                 }
1701         }
1702
1703         /**
1704          * @brief Adds a source entry to the XML document
1705          *
1706          * @param object $doc XML document
1707          * @param array $contact Array of the contact that is added
1708          *
1709          * @return object Source element
1710          */
1711         private static function source_entry($doc, $contact) {
1712                 $source = $doc->createElement("source");
1713                 xml::add_element($doc, $source, "id", $contact["poll"]);
1714                 xml::add_element($doc, $source, "title", $contact["name"]);
1715                 xml::add_element($doc, $source, "link", "", array("rel" => "alternate",
1716                                                                 "type" => "text/html",
1717                                                                 "href" => $contact["alias"]));
1718                 xml::add_element($doc, $source, "link", "", array("rel" => "self",
1719                                                                 "type" => "application/atom+xml",
1720                                                                 "href" => $contact["poll"]));
1721                 xml::add_element($doc, $source, "icon", $contact["photo"]);
1722                 xml::add_element($doc, $source, "updated", datetime_convert("UTC","UTC",$contact["success_update"]."+00:00",ATOM_TIME));
1723
1724                 return $source;
1725         }
1726
1727         /**
1728          * @brief Fetches contact data from the contact or the gcontact table
1729          *
1730          * @param string $url URL of the contact
1731          * @param array $owner Contact data of the poster
1732          *
1733          * @return array Contact array
1734          */
1735         private static function contact_entry($url, $owner) {
1736
1737                 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
1738                         dbesc(normalise_link($url)), intval($owner["uid"]));
1739                 if (dbm::is_result($r)) {
1740                         $contact = $r[0];
1741                         $contact["uid"] = -1;
1742                 }
1743
1744                 if (!dbm::is_result($r)) {
1745                         $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1746                                 dbesc(normalise_link($url)));
1747                         if (dbm::is_result($r)) {
1748                                 $contact = $r[0];
1749                                 $contact["uid"] = -1;
1750                                 $contact["success_update"] = $contact["updated"];
1751                         }
1752                 }
1753
1754                 if (!dbm::is_result($r))
1755                         $contact = owner;
1756
1757                 if (!isset($contact["poll"])) {
1758                         $data = probe_url($url);
1759                         $contact["poll"] = $data["poll"];
1760
1761                         if (!$contact["alias"])
1762                                 $contact["alias"] = $data["alias"];
1763                 }
1764
1765                 if (!isset($contact["alias"]))
1766                         $contact["alias"] = $contact["url"];
1767
1768                 return $contact;
1769         }
1770
1771         /**
1772          * @brief Adds an entry element with reshared content
1773          *
1774          * @param object $doc XML document
1775          * @param array $item Data of the item that is to be posted
1776          * @param array $owner Contact data of the poster
1777          * @param $repeated_guid
1778          * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1779          *
1780          * @return object Entry element
1781          */
1782         private static function reshare_entry($doc, $item, $owner, $repeated_guid, $toplevel) {
1783
1784                 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1785                         logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1786                 }
1787
1788                 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1789
1790                 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' AND NOT `private` AND `network` IN ('%s', '%s', '%s') LIMIT 1",
1791                         intval($owner["uid"]), dbesc($repeated_guid),
1792                         dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS));
1793                 if (dbm::is_result($r)) {
1794                         $repeated_item = $r[0];
1795                 } else {
1796                         return false;
1797                 }
1798                 $contact = self::contact_entry($repeated_item['author-link'], $owner);
1799
1800                 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1801
1802                 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1803
1804                 self::entry_content($doc, $entry, $item, $owner, $title, ACTIVITY_SHARE, false);
1805
1806                 $as_object = $doc->createElement("activity:object");
1807
1808                 xml::add_element($doc, $as_object, "activity:object-type", NAMESPACE_ACTIVITY_SCHEMA."activity");
1809
1810                 self::entry_content($doc, $as_object, $repeated_item, $owner, "", "", false);
1811
1812                 $author = self::add_author($doc, $contact);
1813                 $as_object->appendChild($author);
1814
1815                 $as_object2 = $doc->createElement("activity:object");
1816
1817                 xml::add_element($doc, $as_object2, "activity:object-type", self::construct_objecttype($repeated_item));
1818
1819                 $title = sprintf("New comment by %s", $contact["nick"]);
1820
1821                 self::entry_content($doc, $as_object2, $repeated_item, $owner, $title);
1822
1823                 $as_object->appendChild($as_object2);
1824
1825                 self::entry_footer($doc, $as_object, $item, $owner, false);
1826
1827                 $source = self::source_entry($doc, $contact);
1828
1829                 $as_object->appendChild($source);
1830
1831                 $entry->appendChild($as_object);
1832
1833                 self::entry_footer($doc, $entry, $item, $owner);
1834
1835                 return $entry;
1836         }
1837
1838         /**
1839          * @brief Adds an entry element with a "like"
1840          *
1841          * @param object $doc XML document
1842          * @param array $item Data of the item that is to be posted
1843          * @param array $owner Contact data of the poster
1844          * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1845          *
1846          * @return object Entry element with "like"
1847          */
1848         private static function like_entry($doc, $item, $owner, $toplevel) {
1849
1850                 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1851                         logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1852                 }
1853
1854                 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1855
1856                 $verb = NAMESPACE_ACTIVITY_SCHEMA."favorite";
1857                 self::entry_content($doc, $entry, $item, $owner, "Favorite", $verb, false);
1858
1859                 $as_object = $doc->createElement("activity:object");
1860
1861                 $parent = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d",
1862                         dbesc($item["thr-parent"]), intval($item["uid"]));
1863                 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1864
1865                 xml::add_element($doc, $as_object, "activity:object-type", self::construct_objecttype($parent[0]));
1866
1867                 self::entry_content($doc, $as_object, $parent[0], $owner, "New entry");
1868
1869                 $entry->appendChild($as_object);
1870
1871                 self::entry_footer($doc, $entry, $item, $owner);
1872
1873                 return $entry;
1874         }
1875
1876         /**
1877          * @brief Adds the person object element to the XML document
1878          *
1879          * @param object $doc XML document
1880          * @param array $owner Contact data of the poster
1881          * @param array $contact Contact data of the target
1882          *
1883          * @return object author element
1884          */
1885         private static function add_person_object($doc, $owner, $contact) {
1886
1887                 $object = $doc->createElement("activity:object");
1888                 xml::add_element($doc, $object, "activity:object-type", ACTIVITY_OBJ_PERSON);
1889
1890                 if ($contact['network'] == NETWORK_PHANTOM) {
1891                         xml::add_element($doc, $object, "id", $contact['url']);
1892                         return $object;
1893                 }
1894
1895                 xml::add_element($doc, $object, "id", $contact["alias"]);
1896                 xml::add_element($doc, $object, "title", $contact["nick"]);
1897
1898                 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $contact["url"]);
1899                 xml::add_element($doc, $object, "link", "", $attributes);
1900
1901                 $attributes = array(
1902                                 "rel" => "avatar",
1903                                 "type" => "image/jpeg", // To-Do?
1904                                 "media:width" => 175,
1905                                 "media:height" => 175,
1906                                 "href" => $contact["photo"]);
1907                 xml::add_element($doc, $object, "link", "", $attributes);
1908
1909                 xml::add_element($doc, $object, "poco:preferredUsername", $contact["nick"]);
1910                 xml::add_element($doc, $object, "poco:displayName", $contact["name"]);
1911
1912                 if (trim($contact["location"]) != "") {
1913                         $element = $doc->createElement("poco:address");
1914                         xml::add_element($doc, $element, "poco:formatted", $contact["location"]);
1915                         $object->appendChild($element);
1916                 }
1917
1918                 return $object;
1919         }
1920
1921         /**
1922          * @brief Adds a follow/unfollow entry element
1923          *
1924          * @param object $doc XML document
1925          * @param array $item Data of the follow/unfollow message
1926          * @param array $owner Contact data of the poster
1927          * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1928          *
1929          * @return object Entry element
1930          */
1931         private static function follow_entry($doc, $item, $owner, $toplevel) {
1932
1933                 $item["id"] = $item["parent"] = 0;
1934                 $item["created"] = $item["edited"] = date("c");
1935                 $item["private"] = true;
1936
1937                 $contact = Probe::uri($item['follow']);
1938
1939                 if ($contact['alias'] == '') {
1940                         $contact['alias'] = $contact["url"];
1941                 } else {
1942                         $item['follow'] = $contact['alias'];
1943                 }
1944
1945                 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1946                         intval($owner['uid']), dbesc(normalise_link($contact["url"])));
1947
1948                 if (dbm::is_result($r)) {
1949                         $connect_id = $r[0]['id'];
1950                 } else {
1951                         $connect_id = 0;
1952                 }
1953
1954                 if ($item['verb'] == ACTIVITY_FOLLOW) {
1955                         $message = t('%s is now following %s.');
1956                         $title = t('following');
1957                         $action = "subscription";
1958                 } else {
1959                         $message = t('%s stopped following %s.');
1960                         $title = t('stopped following');
1961                         $action = "unfollow";
1962                 }
1963
1964                 $item["uri"] = $item['parent-uri'] = $item['thr-parent'] =
1965                                 'tag:'.get_app()->get_hostname().
1966                                 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1967                                 ':person:'.$connect_id.':'.$item['created'];
1968
1969                 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1970
1971                 self::entry_header($doc, $entry, $owner, $toplevel);
1972
1973                 self::entry_content($doc, $entry, $item, $owner, $title);
1974
1975                 $object = self::add_person_object($doc, $owner, $contact);
1976                 $entry->appendChild($object);
1977
1978                 self::entry_footer($doc, $entry, $item, $owner);
1979
1980                 return $entry;
1981         }
1982
1983         /**
1984          * @brief Adds a regular entry element
1985          *
1986          * @param object $doc XML document
1987          * @param array $item Data of the item that is to be posted
1988          * @param array $owner Contact data of the poster
1989          * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1990          *
1991          * @return object Entry element
1992          */
1993         private static function note_entry($doc, $item, $owner, $toplevel) {
1994
1995                 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1996                         logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1997                 }
1998
1999                 $title = self::entry_header($doc, $entry, $owner, $toplevel);
2000
2001                 xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
2002
2003                 self::entry_content($doc, $entry, $item, $owner, $title);
2004
2005                 self::entry_footer($doc, $entry, $item, $owner);
2006
2007                 return $entry;
2008         }
2009
2010         /**
2011          * @brief Adds a header element to the XML document
2012          *
2013          * @param object $doc XML document
2014          * @param object $entry The entry element where the elements are added
2015          * @param array $owner Contact data of the poster
2016          * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
2017          *
2018          * @return string The title for the element
2019          */
2020         private static function entry_header($doc, &$entry, $owner, $toplevel) {
2021                 /// @todo Check if this title stuff is really needed (I guess not)
2022                 if (!$toplevel) {
2023                         $entry = $doc->createElement("entry");
2024                         $title = sprintf("New note by %s", $owner["nick"]);
2025                 } else {
2026                         $entry = $doc->createElementNS(NAMESPACE_ATOM1, "entry");
2027
2028                         $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
2029                         $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
2030                         $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
2031                         $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
2032                         $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
2033                         $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
2034                         $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
2035                         $entry->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
2036
2037                         $author = self::add_author($doc, $owner);
2038                         $entry->appendChild($author);
2039
2040                         $title = sprintf("New comment by %s", $owner["nick"]);
2041                 }
2042                 return $title;
2043         }
2044
2045         /**
2046          * @brief Adds elements to the XML document
2047          *
2048          * @param object $doc XML document
2049          * @param object $entry Entry element where the content is added
2050          * @param array $item Data of the item that is to be posted
2051          * @param array $owner Contact data of the poster
2052          * @param string $title Title for the post
2053          * @param string $verb The activity verb
2054          * @param bool $complete Add the "status_net" element?
2055          */
2056         private static function entry_content($doc, $entry, $item, $owner, $title, $verb = "", $complete = true) {
2057
2058                 if ($verb == "")
2059                         $verb = self::construct_verb($item);
2060
2061                 xml::add_element($doc, $entry, "id", $item["uri"]);
2062                 xml::add_element($doc, $entry, "title", $title);
2063
2064                 $body = self::format_picture_post($item['body']);
2065
2066                 if ($item['title'] != "")
2067                         $body = "[b]".$item['title']."[/b]\n\n".$body;
2068
2069                 $body = bbcode($body, false, false, 7);
2070
2071                 xml::add_element($doc, $entry, "content", $body, array("type" => "html"));
2072
2073                 xml::add_element($doc, $entry, "link", "", array("rel" => "alternate", "type" => "text/html",
2074                                                                 "href" => System::baseUrl()."/display/".$item["guid"]));
2075
2076                 if ($complete && ($item["id"] > 0))
2077                         xml::add_element($doc, $entry, "status_net", "", array("notice_id" => $item["id"]));
2078
2079                 xml::add_element($doc, $entry, "activity:verb", $verb);
2080
2081                 xml::add_element($doc, $entry, "published", datetime_convert("UTC","UTC",$item["created"]."+00:00",ATOM_TIME));
2082                 xml::add_element($doc, $entry, "updated", datetime_convert("UTC","UTC",$item["edited"]."+00:00",ATOM_TIME));
2083         }
2084
2085         /**
2086          * @brief Adds the elements at the foot of an entry to the XML document
2087          *
2088          * @param object $doc XML document
2089          * @param object $entry The entry element where the elements are added
2090          * @param array $item Data of the item that is to be posted
2091          * @param array $owner Contact data of the poster
2092          * @param $complete
2093          */
2094         private static function entry_footer($doc, $entry, $item, $owner, $complete = true) {
2095
2096                 $mentioned = array();
2097
2098                 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
2099                         $parent = q("SELECT `guid`, `author-link`, `owner-link` FROM `item` WHERE `id` = %d", intval($item["parent"]));
2100                         $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
2101
2102                         $thrparent = q("SELECT `guid`, `author-link`, `owner-link`, `plink` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
2103                                         intval($owner["uid"]),
2104                                         dbesc($parent_item));
2105                         if ($thrparent) {
2106                                 $mentioned[$thrparent[0]["author-link"]] = $thrparent[0]["author-link"];
2107                                 $mentioned[$thrparent[0]["owner-link"]] = $thrparent[0]["owner-link"];
2108                                 $parent_plink = $thrparent[0]["plink"];
2109                         } else {
2110                                 $mentioned[$parent[0]["author-link"]] = $parent[0]["author-link"];
2111                                 $mentioned[$parent[0]["owner-link"]] = $parent[0]["owner-link"];
2112                                 $parent_plink = System::baseUrl()."/display/".$parent[0]["guid"];
2113                         }
2114
2115                         $attributes = array(
2116                                         "ref" => $parent_item,
2117                                         "href" => $parent_plink);
2118                         xml::add_element($doc, $entry, "thr:in-reply-to", "", $attributes);
2119
2120                         $attributes = array(
2121                                         "rel" => "related",
2122                                         "href" => $parent_plink);
2123                         xml::add_element($doc, $entry, "link", "", $attributes);
2124                 }
2125
2126                 if (intval($item["parent"]) > 0) {
2127                         $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
2128                         $conversation_uri = $conversation_href;
2129
2130                         if (isset($parent_item)) {
2131                                 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $parent_item);
2132                                 if (dbm::is_result($r)) {
2133                                         if ($r['conversation-uri'] != '') {
2134                                                 $conversation_uri = $r['conversation-uri'];
2135                                         }
2136                                         if ($r['conversation-href'] != '') {
2137                                                 $conversation_href = $r['conversation-href'];
2138                                         }
2139                                 }
2140                         }
2141
2142                         xml::add_element($doc, $entry, "link", "", array("rel" => "ostatus:conversation", "href" => $conversation_href));
2143
2144                         $attributes = array(
2145                                         "href" => $conversation_href,
2146                                         "local_id" => $item["parent"],
2147                                         "ref" => $conversation_uri);
2148
2149                         xml::add_element($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
2150                 }
2151
2152                 $tags = item_getfeedtags($item);
2153
2154                 if (count($tags))
2155                         foreach ($tags as $t)
2156                                 if ($t[0] == "@")
2157                                         $mentioned[$t[1]] = $t[1];
2158
2159                 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
2160                 $newmentions = array();
2161                 foreach ($mentioned AS $mention) {
2162                         $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
2163                         $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
2164                 }
2165                 $mentioned = $newmentions;
2166
2167                 foreach ($mentioned AS $mention) {
2168                         $r = q("SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
2169                                 intval($owner["uid"]),
2170                                 dbesc(normalise_link($mention)));
2171                         if ($r[0]["forum"] || $r[0]["prv"])
2172                                 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
2173                                                                                         "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
2174                                                                                         "href" => $mention));
2175                         else
2176                                 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
2177                                                                                         "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
2178                                                                                         "href" => $mention));
2179                 }
2180
2181                 if (!$item["private"]) {
2182                         xml::add_element($doc, $entry, "link", "", array("rel" => "ostatus:attention",
2183                                                                         "href" => "http://activityschema.org/collection/public"));
2184                         xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
2185                                                                         "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
2186                                                                         "href" => "http://activityschema.org/collection/public"));
2187                         xml::add_element($doc, $entry, "mastodon:scope", "public");
2188                 }
2189
2190                 if (count($tags))
2191                         foreach ($tags as $t)
2192                                 if ($t[0] != "@")
2193                                         xml::add_element($doc, $entry, "category", "", array("term" => $t[2]));
2194
2195                 self::get_attachment($doc, $entry, $item);
2196
2197                 if ($complete && ($item["id"] > 0)) {
2198                         $app = $item["app"];
2199                         if ($app == "")
2200                                 $app = "web";
2201
2202                         $attributes = array("local_id" => $item["id"], "source" => $app);
2203
2204                         if (isset($parent["id"]))
2205                                 $attributes["repeat_of"] = $parent["id"];
2206
2207                         if ($item["coord"] != "")
2208                                 xml::add_element($doc, $entry, "georss:point", $item["coord"]);
2209
2210                         xml::add_element($doc, $entry, "statusnet:notice_info", "", $attributes);
2211                 }
2212         }
2213
2214         /**
2215          * @brief Creates the XML feed for a given nickname
2216          *
2217          * @param App $a The application class
2218          * @param string $owner_nick Nickname of the feed owner
2219          * @param string $last_update Date of the last update
2220          * @param integer $max_items Number of maximum items to fetch
2221          *
2222          * @return string XML feed
2223          */
2224         public static function feed(App $a, $owner_nick, &$last_update, $max_items = 300) {
2225                 $stamp = microtime(true);
2226
2227                 $cachekey = "ostatus:feed:".$owner_nick.":".$last_update;
2228
2229                 $previous_created = $last_update;
2230
2231                 $result = Cache::get($cachekey);
2232                 if (!is_null($result)) {
2233                         logger('Feed duration: '.number_format(microtime(true) - $stamp, 3).' - '.$owner_nick.' - '.$previous_created.' (cached)', LOGGER_DEBUG);
2234                         $last_update = $result['last_update'];
2235                         return $result['feed'];
2236                 }
2237
2238                 $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`
2239                                 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
2240                                 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
2241                                 dbesc($owner_nick));
2242                 if (!dbm::is_result($r)) {
2243                         return;
2244                 }
2245
2246                 $owner = $r[0];
2247
2248                 if (!strlen($last_update)) {
2249                         $last_update = 'now -30 days';
2250                 }
2251
2252                 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
2253                 $authorid = get_contact($owner["url"], 0);
2254
2255                 $items = q("SELECT `item`.*, `item`.`id` AS `item_id` FROM `item` USE INDEX (`uid_contactid_created`)
2256                                 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `item`.`parent`
2257                                 WHERE `item`.`uid` = %d AND `item`.`contact-id` = %d AND
2258                                         `item`.`author-id` = %d AND `item`.`created` > '%s' AND
2259                                         NOT `item`.`deleted` AND NOT `item`.`private` AND
2260                                         `thread`.`network` IN ('%s', '%s')
2261                                 ORDER BY `item`.`created` DESC LIMIT %d",
2262                                 intval($owner["uid"]), intval($owner["id"]),
2263                                 intval($authorid), dbesc($check_date),
2264                                 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN), intval($max_items));
2265
2266                 $doc = new DOMDocument('1.0', 'utf-8');
2267                 $doc->formatOutput = true;
2268
2269                 $root = self::add_header($doc, $owner);
2270
2271                 foreach ($items AS $item) {
2272                         if (Config::get('system', 'ostatus_debug')) {
2273                                 $item['body'] .= '🍼';
2274                         }
2275                         $entry = self::entry($doc, $item, $owner);
2276                         $root->appendChild($entry);
2277
2278                         if ($last_update < $item['created']) {
2279                                 $last_update = $item['created'];
2280                         }
2281                 }
2282
2283                 $feeddata = trim($doc->saveXML());
2284
2285                 $msg = array('feed' => $feeddata, 'last_update' => $last_update);
2286                 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
2287
2288                 logger('Feed duration: '.number_format(microtime(true) - $stamp, 3).' - '.$owner_nick.' - '.$previous_created, LOGGER_DEBUG);
2289
2290                 return $feeddata;
2291         }
2292
2293         /**
2294          * @brief Creates the XML for a salmon message
2295          *
2296          * @param array $item Data of the item that is to be posted
2297          * @param array $owner Contact data of the poster
2298          *
2299          * @return string XML for the salmon
2300          */
2301         public static function salmon($item,$owner) {
2302
2303                 $doc = new DOMDocument('1.0', 'utf-8');
2304                 $doc->formatOutput = true;
2305
2306                 if (Config::get('system', 'ostatus_debug')) {
2307                         $item['body'] .= '🐟';
2308                 }
2309
2310                 $entry = self::entry($doc, $item, $owner, true);
2311
2312                 $doc->appendChild($entry);
2313
2314                 return trim($doc->saveXML());
2315         }
2316 }