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