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