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