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