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