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