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