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