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