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