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