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