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