3 * @file include/ostatus.php
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");
22 * @brief This class contain functions for the OStatus protocol
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
31 * @brief Fetches author data
33 * @param object $xpath The xpath object
34 * @param object $context The xml context of the author detals
35 * @param array $importer user record of the importing user
36 * @param array $contact Called by reference, will contain the fetched contact
37 * @param bool $onlyfetch Only fetch the header without updating the contact entries
39 * @return array Array of author related entries for the item
41 private function fetchauthor($xpath, $context, $importer, &$contact, $onlyfetch) {
44 $author["author-link"] = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
45 $author["author-name"] = $xpath->evaluate('atom:author/atom:name/text()', $context)->item(0)->nodeValue;
47 $aliaslink = $author["author-link"];
49 $alternate = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0)->attributes;
50 if (is_object($alternate))
51 foreach($alternate AS $attributes)
52 if ($attributes->name == "href")
53 $author["author-link"] = $attributes->textContent;
55 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` IN ('%s', '%s') AND `network` != '%s'",
56 intval($importer["uid"]), dbesc(normalise_link($author["author-link"])),
57 dbesc(normalise_link($aliaslink)), dbesc(NETWORK_STATUSNET));
60 $author["contact-id"] = $r[0]["id"];
62 $author["contact-id"] = $contact["id"];
64 $avatarlist = array();
65 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
66 foreach($avatars AS $avatar) {
69 foreach($avatar->attributes AS $attributes) {
70 if ($attributes->name == "href")
71 $href = $attributes->textContent;
72 if ($attributes->name == "width")
73 $width = $attributes->textContent;
75 if (($width > 0) AND ($href != ""))
76 $avatarlist[$width] = $href;
78 if (count($avatarlist) > 0) {
80 $author["author-avatar"] = current($avatarlist);
83 $displayname = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
84 if ($displayname != "")
85 $author["author-name"] = $displayname;
87 $author["owner-name"] = $author["author-name"];
88 $author["owner-link"] = $author["author-link"];
89 $author["owner-avatar"] = $author["author-avatar"];
91 // Only update the contacts if it is an OStatus contact
92 if ($r AND !$onlyfetch AND ($contact["network"] == NETWORK_OSTATUS)) {
94 // Update contact data
96 // This query doesn't seem to work
97 // $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
99 // $contact["notify"] = $value;
101 // This query doesn't seem to work as well - I hate these queries
102 // $value = $xpath->query("atom:link[@rel='self' and @type='application/atom+xml']", $context)->item(0)->nodeValue;
104 // $contact["poll"] = $value;
106 $value = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
108 $contact["alias"] = $value;
111 $value = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
113 $contact["name"] = $value;
116 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
118 $contact["nick"] = $value;
121 $value = $xpath->evaluate('atom:author/poco:note/text()', $context)->item(0)->nodeValue;
123 $contact["about"] = html2bbcode($value);
126 $value = $xpath->evaluate('atom:author/poco:address/poco:formatted/text()', $context)->item(0)->nodeValue;
128 $contact["location"] = $value;
131 if (($contact["name"] != $r[0]["name"]) OR ($contact["nick"] != $r[0]["nick"]) OR ($contact["about"] != $r[0]["about"]) OR
132 ($contact["alias"] != $r[0]["alias"]) OR ($contact["location"] != $r[0]["location"])) {
134 logger("Update contact data for contact ".$contact["id"], LOGGER_DEBUG);
136 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `alias` = '%s', `about` = '%s', `location` = '%s', `name-date` = '%s' WHERE `id` = %d",
137 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["alias"]),
138 dbesc($contact["about"]), dbesc($contact["location"]),
139 dbesc(datetime_convert()), intval($contact["id"]));
141 poco_check($contact["url"], $contact["name"], $contact["network"], $author["author-avatar"], $contact["about"], $contact["location"],
142 "", "", "", datetime_convert(), 2, $contact["id"], $contact["uid"]);
145 if (isset($author["author-avatar"]) AND ($author["author-avatar"] != $r[0]['avatar'])) {
146 logger("Update profile picture for contact ".$contact["id"], LOGGER_DEBUG);
148 update_contact_avatar($author["author-avatar"], $importer["uid"], $contact["id"]);
151 // Ensure that we are having this contact (with uid=0)
152 $cid = get_contact($author["author-link"], 0);
155 // Update it with the current values
156 q("UPDATE `contact` SET `url` = '%s', `name` = '%s', `nick` = '%s', `alias` = '%s',
157 `about` = '%s', `location` = '%s',
158 `success_update` = '%s', `last-update` = '%s'
160 dbesc($author["author-link"]), dbesc($contact["name"]), dbesc($contact["nick"]),
161 dbesc($contact["alias"]), dbesc($contact["about"]), dbesc($contact["location"]),
162 dbesc(datetime_convert()), dbesc(datetime_convert()), intval($cid));
165 update_contact_avatar($author["author-avatar"], 0, $cid);
168 $contact["generation"] = 2;
169 $contact["hide"] = false; // OStatus contacts are never hidden
170 $contact["photo"] = $author["author-avatar"];
171 update_gcontact($contact);
178 * @brief Fetches author data from a given XML string
180 * @param string $xml The XML
181 * @param array $importer user record of the importing user
183 * @return array Array of author related entries for the item
185 public static function salmon_author($xml, $importer) {
191 $doc = new DOMDocument();
192 @$doc->loadXML($xml);
194 $xpath = new DomXPath($doc);
195 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
196 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
197 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
198 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
199 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
200 $xpath->registerNamespace('poco', NAMESPACE_POCO);
201 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
202 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
204 $entries = $xpath->query('/atom:entry');
206 foreach ($entries AS $entry) {
208 $author = self::fetchauthor($xpath, $entry, $importer, $contact, true);
214 * @brief Imports an XML string containing OStatus elements
216 * @param string $xml The XML
217 * @param array $importer user record of the importing user
219 * @param array $hub Called by reference, returns the fetched hub data
221 public static function import($xml,$importer,&$contact, &$hub) {
222 /// @todo this function is too long. It has to be split in many parts
224 logger("Import OStatus message", LOGGER_DEBUG);
230 //$tempfile = tempnam(get_temppath(), "import");
231 //file_put_contents($tempfile, $xml);
233 $doc = new DOMDocument();
234 @$doc->loadXML($xml);
236 $xpath = new DomXPath($doc);
237 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
238 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
239 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
240 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
241 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
242 $xpath->registerNamespace('poco', NAMESPACE_POCO);
243 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
244 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
247 $hub_attributes = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0)->attributes;
248 if (is_object($hub_attributes)) {
249 foreach($hub_attributes AS $hub_attribute) {
250 if ($hub_attribute->name == "href") {
251 $hub = $hub_attribute->textContent;
252 logger("Found hub ".$hub, LOGGER_DEBUG);
258 $header["uid"] = $importer["uid"];
259 $header["network"] = NETWORK_OSTATUS;
260 $header["type"] = "remote";
262 $header["origin"] = 0;
263 $header["gravity"] = GRAVITY_PARENT;
265 // it could either be a received post or a post we fetched by ourselves
266 // depending on that, the first node is different
267 $first_child = $doc->firstChild->tagName;
269 if ($first_child == "feed") {
270 $entries = $xpath->query('/atom:feed/atom:entry');
272 $entries = $xpath->query('/atom:entry');
276 $conversationlist = array();
279 // Reverse the order of the entries
280 $entrylist = array();
282 foreach ($entries AS $entry)
283 $entrylist[] = $entry;
285 foreach (array_reverse($entrylist) AS $entry) {
290 if ($first_child == "feed") {
291 $author = self::fetchauthor($xpath, $doc->firstChild, $importer, $contact, false);
293 $author = self::fetchauthor($xpath, $entry, $importer, $contact, false);
296 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
300 $nickname = $author["author-name"];
303 $item = array_merge($header, $author);
306 $item["uri"] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
308 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
309 intval($importer["uid"]), dbesc($item["uri"]));
310 if (dbm::is_result($r)) {
311 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already existed under id ".$r[0]["id"], LOGGER_DEBUG);
315 $item["body"] = add_page_info_to_body(html2bbcode($xpath->query('atom:content/text()', $entry)->item(0)->nodeValue));
316 $item["object-type"] = $xpath->query('activity:object-type/text()', $entry)->item(0)->nodeValue;
318 if (($item["object-type"] == ACTIVITY_OBJ_BOOKMARK) OR ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
319 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
320 $item["body"] = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
321 } elseif ($item["object-type"] == ACTIVITY_OBJ_QUESTION) {
322 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
325 $item["object"] = $xml;
326 $item["verb"] = $xpath->query('activity:verb/text()', $entry)->item(0)->nodeValue;
330 if ($item["verb"] == "qvitter-delete-notice") {
331 // ignore "Delete" messages (by now)
332 logger("Ignore delete message ".print_r($item, true));
336 if ($item["verb"] == ACTIVITY_JOIN) {
337 // ignore "Join" messages
338 logger("Ignore join message ".print_r($item, true));
342 if ($item["verb"] == ACTIVITY_FOLLOW) {
343 new_follower($importer, $contact, $item, $nickname);
347 if ($item["verb"] == NAMESPACE_OSTATUS."/unfollow") {
348 lose_follower($importer, $contact, $item, $dummy);
352 if ($item["verb"] == ACTIVITY_FAVORITE) {
353 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
354 logger("Favorite ".$orig_uri." ".print_r($item, true));
356 $item["verb"] = ACTIVITY_LIKE;
357 $item["parent-uri"] = $orig_uri;
358 $item["gravity"] = GRAVITY_LIKE;
361 if ($item["verb"] == NAMESPACE_OSTATUS."/unfavorite") {
362 // Ignore "Unfavorite" message
363 logger("Ignore unfavorite message ".print_r($item, true));
367 // http://activitystrea.ms/schema/1.0/rsvp-yes
368 if (!in_array($item["verb"], array(ACTIVITY_POST, ACTIVITY_LIKE, ACTIVITY_SHARE))) {
369 logger("Unhandled verb ".$item["verb"]." ".print_r($item, true));
372 $item["created"] = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
373 $item["edited"] = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
374 $conversation = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
378 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
379 if (is_object($inreplyto->item(0))) {
380 foreach($inreplyto->item(0)->attributes AS $attributes) {
381 if ($attributes->name == "ref") {
382 $item["parent-uri"] = $attributes->textContent;
384 if ($attributes->name == "href") {
385 $related = $attributes->textContent;
390 $georsspoint = $xpath->query('georss:point', $entry);
392 $item["coord"] = $georsspoint->item(0)->nodeValue;
394 $categories = $xpath->query('atom:category', $entry);
396 foreach ($categories AS $category) {
397 foreach($category->attributes AS $attributes)
398 if ($attributes->name == "term") {
399 $term = $attributes->textContent;
400 if(strlen($item["tag"]))
402 $item["tag"] .= "#[url=".App::get_baseurl()."/search?tag=".$term."]".$term."[/url]";
410 $links = $xpath->query('atom:link', $entry);
417 foreach ($links AS $link) {
418 foreach($link->attributes AS $attributes) {
419 if ($attributes->name == "href")
420 $href = $attributes->textContent;
421 if ($attributes->name == "rel")
422 $rel = $attributes->textContent;
423 if ($attributes->name == "type")
424 $type = $attributes->textContent;
425 if ($attributes->name == "length")
426 $length = $attributes->textContent;
427 if ($attributes->name == "title")
428 $title = $attributes->textContent;
430 if (($rel != "") AND ($href != "")) {
433 $item["plink"] = $href;
434 if (($item["object-type"] == ACTIVITY_OBJ_QUESTION) OR
435 ($item["object-type"] == ACTIVITY_OBJ_EVENT))
436 $item["body"] .= add_page_info($href);
438 case "ostatus:conversation":
439 $conversation = $href;
443 if(strlen($item["attach"]))
444 $item["attach"] .= ',';
446 $item["attach"] .= '[attach]href="'.$href.'" length="'.$length.'" type="'.$type.'" title="'.$title.'"[/attach]';
449 if ($item["object-type"] != ACTIVITY_OBJ_BOOKMARK) {
450 if (!isset($item["parent-uri"]))
451 $item["parent-uri"] = $href;
456 $item["body"] .= add_page_info($href);
462 // Notification check
463 if ($importer["nurl"] == normalise_link($href))
474 $notice_info = $xpath->query('statusnet:notice_info', $entry);
475 if ($notice_info AND ($notice_info->length > 0)) {
476 foreach($notice_info->item(0)->attributes AS $attributes) {
477 if ($attributes->name == "source") {
478 $item["app"] = strip_tags($attributes->textContent);
480 if ($attributes->name == "local_id") {
481 $local_id = $attributes->textContent;
483 if ($attributes->name == "repeat_of") {
484 $repeat_of = $attributes->textContent;
489 // Is it a repeated post?
490 if (($repeat_of != "") OR ($item["verb"] == ACTIVITY_SHARE)) {
491 $activityobjects = $xpath->query('activity:object', $entry)->item(0);
493 if (is_object($activityobjects)) {
495 $orig_uri = $xpath->query("activity:object/atom:id", $activityobjects)->item(0)->nodeValue;
496 if (!isset($orig_uri)) {
497 $orig_uri = $xpath->query('atom:id/text()', $activityobjects)->item(0)->nodeValue;
500 $orig_links = $xpath->query("activity:object/atom:link[@rel='alternate']", $activityobjects);
501 if ($orig_links AND ($orig_links->length > 0)) {
502 foreach ($orig_links->item(0)->attributes AS $attributes) {
503 if ($attributes->name == "href") {
504 $orig_link = $attributes->textContent;
509 if (!isset($orig_link)) {
510 $orig_link = $xpath->query("atom:link[@rel='alternate']", $activityobjects)->item(0)->nodeValue;
513 if (!isset($orig_link)) {
514 $orig_link = self::convert_href($orig_uri);
517 $orig_body = $xpath->query('activity:object/atom:content/text()', $activityobjects)->item(0)->nodeValue;
519 if (!isset($orig_body)) {
520 $orig_body = $xpath->query('atom:content/text()', $activityobjects)->item(0)->nodeValue;
523 $orig_created = $xpath->query('atom:published/text()', $activityobjects)->item(0)->nodeValue;
524 $orig_edited = $xpath->query('atom:updated/text()', $activityobjects)->item(0)->nodeValue;
526 $orig_contact = $contact;
527 $orig_author = self::fetchauthor($xpath, $activityobjects, $importer, $orig_contact, false);
529 $item["author-name"] = $orig_author["author-name"];
530 $item["author-link"] = $orig_author["author-link"];
531 $item["author-avatar"] = $orig_author["author-avatar"];
532 $item["body"] = add_page_info_to_body(html2bbcode($orig_body));
533 $item["created"] = $orig_created;
534 $item["edited"] = $orig_edited;
536 $item["uri"] = $orig_uri;
537 $item["plink"] = $orig_link;
539 $item["verb"] = $xpath->query('activity:verb/text()', $activityobjects)->item(0)->nodeValue;
541 $item["object-type"] = $xpath->query('activity:object/activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
543 if (!isset($item["object-type"])) {
544 $item["object-type"] = $xpath->query('activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
549 //if ($enclosure != "")
550 // $item["body"] .= add_page_info($enclosure);
552 if (isset($item["parent-uri"])) {
553 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
554 intval($importer["uid"]), dbesc($item["parent-uri"]));
556 // Only fetch missing stuff if it is a comment or reshare.
557 if (in_array($item["verb"], array(ACTIVITY_POST, ACTIVITY_SHARE)) AND
558 !dbm::is_result($r) AND ($related != "")) {
559 $reply_path = str_replace("/notice/", "/api/statuses/show/", $related).".atom";
561 if ($reply_path != $related) {
562 logger("Fetching related items for user ".$importer["uid"]." from ".$reply_path, LOGGER_DEBUG);
563 $reply_xml = fetch_url($reply_path);
565 $reply_contact = $contact;
566 self::import($reply_xml,$importer,$reply_contact, $reply_hub);
568 // After the import try to fetch the parent item again
569 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
570 intval($importer["uid"]), dbesc($item["parent-uri"]));
574 if (dbm::is_result($r)) {
575 $item["type"] = 'remote-comment';
576 $item["gravity"] = GRAVITY_COMMENT;
579 $item["parent-uri"] = $item["uri"];
582 $item_id = self::completion($conversation, $importer["uid"], $item, $self);
585 logger("Error storing item", LOGGER_DEBUG);
589 logger("Item was stored with id ".$item_id, LOGGER_DEBUG);
594 * @brief Create an url out of an uri
596 * @param string $href URI in the format "parameter1:parameter1:..."
598 * @return string URL in the format http(s)://....
600 public static function convert_href($href) {
601 $elements = explode(":",$href);
603 if ((count($elements) <= 2) OR ($elements[0] != "tag"))
606 $server = explode(",", $elements[1]);
607 $conversation = explode("=", $elements[2]);
609 if ((count($elements) == 4) AND ($elements[2] == "post"))
610 return "http://".$server[0]."/notice/".$elements[3];
612 if ((count($conversation) != 2) OR ($conversation[1] ==""))
615 if ($elements[3] == "objectType=thread")
616 return "http://".$server[0]."/conversation/".$conversation[1];
618 return "http://".$server[0]."/notice/".$conversation[1];
624 * @brief Checks if there are entries in conversations that aren't present on our side
626 * @param bool $mentions Fetch conversations where we are mentioned
627 * @param bool $override Override the interval setting
629 public static function check_conversations($mentions = false, $override = false) {
630 $last = get_config('system','ostatus_last_poll');
632 $poll_interval = intval(get_config('system','ostatus_poll_interval'));
633 if (!$poll_interval) {
634 $poll_interval = self::OSTATUS_DEFAULT_POLL_INTERVAL;
637 // Don't poll if the interval is set negative
638 if (($poll_interval < 0) AND !$override) {
643 $poll_timeframe = intval(get_config('system','ostatus_poll_timeframe'));
644 if (!$poll_timeframe) {
645 $poll_timeframe = self::OSTATUS_DEFAULT_POLL_TIMEFRAME;
648 $poll_timeframe = intval(get_config('system','ostatus_poll_timeframe'));
649 if (!$poll_timeframe) {
650 $poll_timeframe = self::OSTATUS_DEFAULT_POLL_TIMEFRAME_MENTIONS;
655 if ($last AND !$override) {
656 $next = $last + ($poll_interval * 60);
657 if ($next > time()) {
658 logger('poll interval not reached');
663 logger('cron_start');
665 $start = date("Y-m-d H:i:s", time() - ($poll_timeframe * 60));
668 $conversations = q("SELECT `term`.`oid`, `term`.`url`, `term`.`uid` FROM `term`
669 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `term`.`oid` AND `thread`.`uid` = `term`.`uid`
670 WHERE `term`.`type` = 7 AND `term`.`term` > '%s' AND `thread`.`mention`
671 GROUP BY `term`.`url`, `term`.`uid` ORDER BY `term`.`term` DESC", dbesc($start));
673 $conversations = q("SELECT `oid`, `url`, `uid` FROM `term`
674 WHERE `type` = 7 AND `term` > '%s'
675 GROUP BY `url`, `uid` ORDER BY `term` DESC", dbesc($start));
678 foreach ($conversations AS $conversation) {
679 self::completion($conversation['url'], $conversation['uid']);
684 set_config('system','ostatus_last_poll', time());
688 * @brief Updates the gcontact table with actor data from the conversation
690 * @param object $actor The actor object that contains the contact data
692 private function conv_fetch_actor($actor) {
694 // We set the generation to "3" since the data here is not as reliable as the data we get on other occasions
695 $contact = array("network" => NETWORK_OSTATUS, "generation" => 3);
697 if (isset($actor->url))
698 $contact["url"] = $actor->url;
700 if (isset($actor->displayName))
701 $contact["name"] = $actor->displayName;
703 if (isset($actor->portablecontacts_net->displayName))
704 $contact["name"] = $actor->portablecontacts_net->displayName;
706 if (isset($actor->portablecontacts_net->preferredUsername))
707 $contact["nick"] = $actor->portablecontacts_net->preferredUsername;
709 if (isset($actor->id))
710 $contact["alias"] = $actor->id;
712 if (isset($actor->summary))
713 $contact["about"] = $actor->summary;
715 if (isset($actor->portablecontacts_net->note))
716 $contact["about"] = $actor->portablecontacts_net->note;
718 if (isset($actor->portablecontacts_net->addresses->formatted))
719 $contact["location"] = $actor->portablecontacts_net->addresses->formatted;
722 if (isset($actor->image->url))
723 $contact["photo"] = $actor->image->url;
725 if (isset($actor->image->width))
726 $avatarwidth = $actor->image->width;
728 if (is_array($actor->status_net->avatarLinks))
729 foreach ($actor->status_net->avatarLinks AS $avatar) {
730 if ($avatarsize < $avatar->width) {
731 $contact["photo"] = $avatar->url;
732 $avatarsize = $avatar->width;
736 $contact["hide"] = false; // OStatus contacts are never hidden
737 update_gcontact($contact);
741 * @brief Fetches the conversation url for a given item link or conversation id
743 * @param string $self The link to the posting
744 * @param string $conversation_id The conversation id
746 * @return string The conversation url
748 private function fetch_conversation($self, $conversation_id = "") {
750 if ($conversation_id != "") {
751 $elements = explode(":", $conversation_id);
753 if ((count($elements) <= 2) OR ($elements[0] != "tag"))
754 return $conversation_id;
760 $json = str_replace(".atom", ".json", $self);
762 $raw = fetch_url($json);
766 $data = json_decode($raw);
767 if (!is_object($data))
770 $conversation_id = $data->statusnet_conversation_id;
772 $pos = strpos($self, "/api/statuses/show/");
773 $base_url = substr($self, 0, $pos);
775 return $base_url."/conversation/".$conversation_id;
779 * @brief Fetches actor details of a given actor and user id
781 * @param string $actor The actor url
782 * @param int $uid The user id
783 * @param int $contact_id The default contact-id
785 * @return array Array with actor details
787 private function get_actor_details($actor, $uid, $contact_id) {
791 $contact = q("SELECT `id`, `rel`, `network` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'",
792 $uid, normalise_link($actor), NETWORK_STATUSNET);
795 $contact = q("SELECT `id`, `rel`, `network` FROM `contact` WHERE `uid` = %d AND `alias` IN ('%s', '%s') AND `network` != '%s'",
796 $uid, $actor, normalise_link($actor), NETWORK_STATUSNET);
799 logger("Found contact for url ".$actor, LOGGER_DEBUG);
800 $details["contact_id"] = $contact[0]["id"];
801 $details["network"] = $contact[0]["network"];
803 $details["not_following"] = !in_array($contact[0]["rel"], array(CONTACT_IS_SHARING, CONTACT_IS_FRIEND));
805 logger("No contact found for user ".$uid." and url ".$actor, LOGGER_DEBUG);
807 // Adding a global contact
808 /// @TODO Use this data for the post
809 $details["global_contact_id"] = get_contact($actor, 0);
811 logger("Global contact ".$global_contact_id." found for url ".$actor, LOGGER_DEBUG);
813 $details["contact_id"] = $contact_id;
814 $details["network"] = NETWORK_OSTATUS;
816 $details["not_following"] = true;
823 * @brief Stores an item and completes the thread
825 * @param string $conversation_url The URI of the conversation
826 * @param integer $uid The user id
827 * @param array $item Data of the item that is to be posted
829 * @return integer The item id of the posted item array
831 private function completion($conversation_url, $uid, $item = array(), $self = "") {
833 /// @todo This function is totally ugly and has to be rewritten totally
837 $conversation_url = self::fetch_conversation($self, $conversation_url);
839 // If the thread shouldn't be completed then store the item and go away
840 // Don't do a completion on liked content
841 if (((intval(get_config('system','ostatus_poll_interval')) == -2) AND (count($item) > 0)) OR
842 ($item["verb"] == ACTIVITY_LIKE) OR ($conversation_url == "")) {
843 $item_stored = item_store($item, true);
844 return($item_stored);
848 $parents = q("SELECT `item`.`id`, `item`.`parent`, `item`.`uri`, `item`.`contact-id`, `item`.`type`,
849 `item`.`verb`, `item`.`visible` FROM `term`
850 STRAIGHT_JOIN `item` AS `thritem` ON `thritem`.`parent` = `term`.`oid`
851 STRAIGHT_JOIN `item` ON `item`.`parent` = `thritem`.`parent`
852 WHERE `term`.`uid` = %d AND `term`.`otype` = %d AND `term`.`type` = %d AND `term`.`url` = '%s'",
853 intval($uid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION), dbesc($conversation_url));
855 /* 2016-10-23: The old query will be kept until we are sure that the query above is a good and fast replacement
857 $parents = q("SELECT `id`, `parent`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `id` IN
858 (SELECT `parent` FROM `item` WHERE `id` IN
859 (SELECT `oid` FROM `term` WHERE `uid` = %d AND `otype` = %d AND `type` = %d AND `url` = '%s'))",
860 intval($uid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION), dbesc($conversation_url));
863 $parent = $parents[0];
864 elseif (count($item) > 0) {
866 $parent["type"] = "remote";
867 $parent["verb"] = ACTIVITY_POST;
868 $parent["visible"] = 1;
871 $r = q("SELECT `id` FROM `contact` WHERE `self` AND `uid`=%d", $uid);
877 $parent["parent"] = 0;
879 $parent["contact-id"] = $r[0]["id"];
880 $parent["type"] = "remote";
881 $parent["verb"] = ACTIVITY_POST;
882 $parent["visible"] = 1;
885 $conv = str_replace("/conversation/", "/api/statusnet/conversation/", $conversation_url).".as";
889 logger('fetching conversation url '.$conv.' (Self: '.$self.') for user '.$uid);
892 $conv_arr = z_fetch_url($conv."?page=".$pageno);
894 // If it is a non-ssl site and there is an error, then try ssl or vice versa
895 if (!$conv_arr["success"] AND (substr($conv, 0, 7) == "http://")) {
896 $conv = str_replace("http://", "https://", $conv);
897 $conv_as = fetch_url($conv."?page=".$pageno);
898 } elseif (!$conv_arr["success"] AND (substr($conv, 0, 8) == "https://")) {
899 $conv = str_replace("https://", "http://", $conv);
900 $conv_as = fetch_url($conv."?page=".$pageno);
902 $conv_as = $conv_arr["body"];
904 $conv_as = str_replace(',"statusnet:notice_info":', ',"statusnet_notice_info":', $conv_as);
905 $conv_as = json_decode($conv_as);
907 $no_of_items = sizeof($items);
909 if (@is_array($conv_as->items))
910 foreach ($conv_as->items AS $single_item)
911 $items[$single_item->id] = $single_item;
913 if ($no_of_items == sizeof($items))
920 logger('fetching conversation done. Found '.count($items).' items');
922 if (!sizeof($items)) {
923 if (count($item) > 0) {
924 $item_stored = item_store($item, true);
927 logger("Conversation ".$conversation_url." couldn't be fetched. Item uri ".$item["uri"]." stored: ".$item_stored, LOGGER_DEBUG);
928 self::store_conversation($item_id, $conversation_url);
931 return($item_stored);
936 $items = array_reverse($items);
938 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self`", intval($uid));
943 foreach ($items as $single_conv) {
945 // Update the gcontact table
946 self::conv_fetch_actor($single_conv->actor);
948 // Test - remove before flight
949 //$tempfile = tempnam(get_temppath(), "conversation");
950 //file_put_contents($tempfile, json_encode($single_conv));
954 if (isset($single_conv->object->id))
955 $single_conv->id = $single_conv->object->id;
957 $plink = self::convert_href($single_conv->id);
958 if (isset($single_conv->object->url))
959 $plink = self::convert_href($single_conv->object->url);
961 if (@!$single_conv->id)
964 logger("Got id ".$single_conv->id, LOGGER_DEBUG);
966 if ($first_id == "") {
967 $first_id = $single_conv->id;
969 // The first post of the conversation isn't our first post. There are three options:
970 // 1. Our conversation hasn't the "real" thread starter
971 // 2. This first post is a post inside our thread
972 // 3. This first post is a post inside another thread
973 if (($first_id != $parent["uri"]) AND ($parent["uri"] != "")) {
977 $new_parents = q("SELECT `id`, `parent`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `id` IN
978 (SELECT `parent` FROM `item`
979 WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s')) LIMIT 1",
980 intval($uid), dbesc($first_id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
982 if ($new_parents[0]["parent"] == $parent["parent"]) {
983 // Option 2: This post is already present inside our thread - but not as thread starter
984 logger("Option 2: uri present in our thread: ".$first_id, LOGGER_DEBUG);
985 $first_id = $parent["uri"];
987 // Option 3: Not so good. We have mixed parents. We have to see how to clean this up.
988 // For now just take the new parent.
989 $parent = $new_parents[0];
990 $first_id = $parent["uri"];
991 logger("Option 3: mixed parents for uri ".$first_id, LOGGER_DEBUG);
994 // Option 1: We hadn't got the real thread starter
995 // We have to clean up our existing messages.
997 $parent["uri"] = $first_id;
998 logger("Option 1: we have a new parent: ".$first_id, LOGGER_DEBUG);
1000 } elseif ($parent["uri"] == "") {
1002 $parent["uri"] = $first_id;
1006 $parent_uri = $parent["uri"];
1008 // "context" only seems to exist on older servers
1009 if (isset($single_conv->context->inReplyTo->id)) {
1010 $parent_exists = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
1011 intval($uid), dbesc($single_conv->context->inReplyTo->id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
1013 $parent_uri = $single_conv->context->inReplyTo->id;
1016 // This is the current way
1017 if (isset($single_conv->object->inReplyTo->id)) {
1018 $parent_exists = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
1019 intval($uid), dbesc($single_conv->object->inReplyTo->id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
1021 $parent_uri = $single_conv->object->inReplyTo->id;
1024 $message_exists = q("SELECT `id`, `parent`, `uri` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
1025 intval($uid), dbesc($single_conv->id),
1026 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
1027 if ($message_exists) {
1028 logger("Message ".$single_conv->id." already existed on the system", LOGGER_DEBUG);
1030 if ($parent["id"] != 0) {
1031 $existing_message = $message_exists[0];
1033 // We improved the way we fetch OStatus messages, this shouldn't happen very often now
1034 /// @TODO We have to change the shadow copies as well. This way here is really ugly.
1035 if ($existing_message["parent"] != $parent["id"]) {
1036 logger('updating id '.$existing_message["id"].' with parent '.$existing_message["parent"].' to parent '.$parent["id"].' uri '.$parent["uri"].' thread '.$parent_uri, LOGGER_DEBUG);
1038 // Update the parent id of the selected item
1039 $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s' WHERE `id` = %d",
1040 intval($parent["id"]), dbesc($parent["uri"]), intval($existing_message["id"]));
1042 // Update the parent uri in the thread - but only if it points to itself
1043 $r = q("UPDATE `item` SET `thr-parent` = '%s' WHERE `id` = %d AND `uri` = `thr-parent`",
1044 dbesc($parent_uri), intval($existing_message["id"]));
1046 // try to change all items of the same parent
1047 $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s' WHERE `parent` = %d",
1048 intval($parent["id"]), dbesc($parent["uri"]), intval($existing_message["parent"]));
1050 // Update the parent uri in the thread - but only if it points to itself
1051 $r = q("UPDATE `item` SET `thr-parent` = '%s' WHERE (`parent` = %d) AND (`uri` = `thr-parent`)",
1052 dbesc($parent["uri"]), intval($existing_message["parent"]));
1054 // Now delete the thread
1055 delete_thread($existing_message["parent"]);
1059 // The item we are having on the system is the one that we wanted to store via the item array
1060 if (isset($item["uri"]) AND ($item["uri"] == $existing_message["uri"])) {
1068 if (is_array($single_conv->to))
1069 foreach($single_conv->to AS $to)
1070 if ($importer["nurl"] == normalise_link($to->id))
1073 $actor = $single_conv->actor->id;
1074 if (isset($single_conv->actor->url))
1075 $actor = $single_conv->actor->url;
1077 $details = self::get_actor_details($actor, $uid, $parent["contact-id"]);
1079 // Do we only want to import threads that were started by our contacts?
1080 if ($details["not_following"] AND $new_parent AND get_config('system','ostatus_full_threads')) {
1081 logger("Don't import uri ".$first_id." because user ".$uid." doesn't follow the person ".$actor, LOGGER_DEBUG);
1086 $arr["network"] = $details["network"];
1087 $arr["uri"] = $single_conv->id;
1088 $arr["plink"] = $plink;
1090 $arr["contact-id"] = $details["contact_id"];
1091 $arr["parent-uri"] = $parent_uri;
1092 $arr["created"] = $single_conv->published;
1093 $arr["edited"] = $single_conv->published;
1094 $arr["owner-name"] = $single_conv->actor->displayName;
1095 if ($arr["owner-name"] == '')
1096 $arr["owner-name"] = $single_conv->actor->contact->displayName;
1097 if ($arr["owner-name"] == '')
1098 $arr["owner-name"] = $single_conv->actor->portablecontacts_net->displayName;
1100 $arr["owner-link"] = $actor;
1101 $arr["owner-avatar"] = $single_conv->actor->image->url;
1102 $arr["author-name"] = $arr["owner-name"];
1103 $arr["author-link"] = $actor;
1104 $arr["author-avatar"] = $single_conv->actor->image->url;
1105 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->content));
1107 if (isset($single_conv->status_net->notice_info->source))
1108 $arr["app"] = strip_tags($single_conv->status_net->notice_info->source);
1109 elseif (isset($single_conv->statusnet->notice_info->source))
1110 $arr["app"] = strip_tags($single_conv->statusnet->notice_info->source);
1111 elseif (isset($single_conv->statusnet_notice_info->source))
1112 $arr["app"] = strip_tags($single_conv->statusnet_notice_info->source);
1113 elseif (isset($single_conv->provider->displayName))
1114 $arr["app"] = $single_conv->provider->displayName;
1116 $arr["app"] = "OStatus";
1119 $arr["object"] = json_encode($single_conv);
1120 $arr["verb"] = $parent["verb"];
1121 $arr["visible"] = $parent["visible"];
1122 $arr["location"] = $single_conv->location->displayName;
1123 $arr["coord"] = trim($single_conv->location->lat." ".$single_conv->location->lon);
1125 // Is it a reshared item?
1126 if (isset($single_conv->verb) AND ($single_conv->verb == "share") AND isset($single_conv->object)) {
1127 if (is_array($single_conv->object))
1128 $single_conv->object = $single_conv->object[0];
1130 logger("Found reshared item ".$single_conv->object->id);
1132 // $single_conv->object->context->conversation;
1134 if (isset($single_conv->object->object->id))
1135 $arr["uri"] = $single_conv->object->object->id;
1137 $arr["uri"] = $single_conv->object->id;
1139 if (isset($single_conv->object->object->url))
1140 $plink = self::convert_href($single_conv->object->object->url);
1142 $plink = self::convert_href($single_conv->object->url);
1144 if (isset($single_conv->object->object->content))
1145 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->object->content));
1147 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->content));
1149 $arr["plink"] = $plink;
1151 $arr["created"] = $single_conv->object->published;
1152 $arr["edited"] = $single_conv->object->published;
1154 $arr["author-name"] = $single_conv->object->actor->displayName;
1155 if ($arr["owner-name"] == '')
1156 $arr["author-name"] = $single_conv->object->actor->contact->displayName;
1158 $arr["author-link"] = $single_conv->object->actor->url;
1159 $arr["author-avatar"] = $single_conv->object->actor->image->url;
1161 $arr["app"] = $single_conv->object->provider->displayName."#";
1162 //$arr["verb"] = $single_conv->object->verb;
1164 $arr["location"] = $single_conv->object->location->displayName;
1165 $arr["coord"] = trim($single_conv->object->location->lat." ".$single_conv->object->location->lon);
1168 if ($arr["location"] == "")
1169 unset($arr["location"]);
1171 if ($arr["coord"] == "")
1172 unset($arr["coord"]);
1174 // Copy fields from given item array
1175 if (isset($item["uri"]) AND (($item["uri"] == $arr["uri"]) OR ($item["uri"] == $single_conv->id))) {
1176 $copy_fields = array("owner-name", "owner-link", "owner-avatar", "author-name", "author-link", "author-avatar",
1177 "gravity", "body", "object-type", "object", "verb", "created", "edited", "coord", "tag",
1178 "title", "attach", "app", "type", "location", "contact-id", "uri");
1179 foreach ($copy_fields AS $field)
1180 if (isset($item[$field]))
1181 $arr[$field] = $item[$field];
1185 $newitem = item_store($arr);
1187 logger("Item wasn't stored ".print_r($arr, true), LOGGER_DEBUG);
1191 if (isset($item["uri"]) AND ($item["uri"] == $arr["uri"])) {
1193 $item_stored = $newitem;
1196 logger('Stored new item '.$plink.' for parent '.$arr["parent-uri"].' under id '.$newitem, LOGGER_DEBUG);
1198 // Add the conversation entry (but don't fetch the whole conversation)
1199 self::store_conversation($newitem, $conversation_url);
1201 // If the newly created item is the top item then change the parent settings of the thread
1202 // This shouldn't happen anymore. This is supposed to be absolote.
1203 if ($arr["uri"] == $first_id) {
1204 logger('setting new parent to id '.$newitem);
1205 $new_parents = q("SELECT `id`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `uid` = %d AND `id` = %d LIMIT 1",
1206 intval($uid), intval($newitem));
1208 $parent = $new_parents[0];
1212 if (($item_stored < 0) AND (count($item) > 0)) {
1214 if (get_config('system','ostatus_full_threads')) {
1215 $details = self::get_actor_details($item["owner-link"], $uid, $item["contact-id"]);
1216 if ($details["not_following"]) {
1217 logger("Don't import uri ".$item["uri"]." because user ".$uid." doesn't follow the person ".$item["owner-link"], LOGGER_DEBUG);
1222 $item_stored = item_store($item, true);
1224 logger("Uri ".$item["uri"]." wasn't found in conversation ".$conversation_url, LOGGER_DEBUG);
1225 self::store_conversation($item_stored, $conversation_url);
1229 return($item_stored);
1233 * @brief Stores conversation data into the database
1235 * @param integer $itemid The id of the item
1236 * @param string $conversation_url The uri of the conversation
1238 private function store_conversation($itemid, $conversation_url) {
1240 $conversation_url = self::convert_href($conversation_url);
1242 $messages = q("SELECT `uid`, `parent`, `created`, `received`, `guid` FROM `item` WHERE `id` = %d LIMIT 1", intval($itemid));
1245 $message = $messages[0];
1247 // Store conversation url if not done before
1248 $conversation = q("SELECT `url` FROM `term` WHERE `uid` = %d AND `oid` = %d AND `otype` = %d AND `type` = %d",
1249 intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION));
1251 if (!$conversation) {
1252 $r = q("INSERT INTO `term` (`uid`, `oid`, `otype`, `type`, `term`, `url`, `created`, `received`, `guid`) VALUES (%d, %d, %d, %d, '%s', '%s', '%s', '%s', '%s')",
1253 intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION),
1254 dbesc($message["created"]), dbesc($conversation_url), dbesc($message["created"]), dbesc($message["received"]), dbesc($message["guid"]));
1255 logger('Storing conversation url '.$conversation_url.' for id '.$itemid);
1260 * @brief Checks if the current post is a reshare
1262 * @param array $item The item array of thw post
1264 * @return string The guid if the post is a reshare
1266 private function get_reshared_guid($item) {
1267 $body = trim($item["body"]);
1269 // Skip if it isn't a pure repeated messages
1270 // Does it start with a share?
1271 if (strpos($body, "[share") > 0)
1274 // Does it end with a share?
1275 if (strlen($body) > (strrpos($body, "[/share]") + 8))
1278 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
1279 // Skip if there is no shared message in there
1280 if ($body == $attributes)
1284 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
1285 if ($matches[1] != "")
1286 $guid = $matches[1];
1288 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
1289 if ($matches[1] != "")
1290 $guid = $matches[1];
1296 * @brief Cleans the body of a post if it contains picture links
1298 * @param string $body The body
1300 * @return string The cleaned body
1302 private function format_picture_post($body) {
1303 $siteinfo = get_attached_data($body);
1305 if (($siteinfo["type"] == "photo")) {
1306 if (isset($siteinfo["preview"]))
1307 $preview = $siteinfo["preview"];
1309 $preview = $siteinfo["image"];
1311 // Is it a remote picture? Then make a smaller preview here
1312 $preview = proxy_url($preview, false, PROXY_SIZE_SMALL);
1314 // Is it a local picture? Then make it smaller here
1315 $preview = str_replace(array("-0.jpg", "-0.png"), array("-2.jpg", "-2.png"), $preview);
1316 $preview = str_replace(array("-1.jpg", "-1.png"), array("-2.jpg", "-2.png"), $preview);
1318 if (isset($siteinfo["url"]))
1319 $url = $siteinfo["url"];
1321 $url = $siteinfo["image"];
1323 $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1330 * @brief Adds the header elements to the XML document
1332 * @param object $doc XML document
1333 * @param array $owner Contact data of the poster
1335 * @return object header root element
1337 private function add_header($doc, $owner) {
1341 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
1342 $doc->appendChild($root);
1344 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1345 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1346 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1347 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1348 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
1349 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1350 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1352 $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
1353 xml::add_element($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1354 xml::add_element($doc, $root, "id", App::get_baseurl()."/profile/".$owner["nick"]);
1355 xml::add_element($doc, $root, "title", sprintf("%s timeline", $owner["name"]));
1356 xml::add_element($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], $a->config["sitename"]));
1357 xml::add_element($doc, $root, "logo", $owner["photo"]);
1358 xml::add_element($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
1360 $author = self::add_author($doc, $owner);
1361 $root->appendChild($author);
1363 $attributes = array("href" => $owner["url"], "rel" => "alternate", "type" => "text/html");
1364 xml::add_element($doc, $root, "link", "", $attributes);
1366 /// @TODO We have to find out what this is
1367 /// $attributes = array("href" => App::get_baseurl()."/sup",
1368 /// "rel" => "http://api.friendfeed.com/2008/03#sup",
1369 /// "type" => "application/json");
1370 /// xml::add_element($doc, $root, "link", "", $attributes);
1372 self::hublinks($doc, $root);
1374 $attributes = array("href" => App::get_baseurl()."/salmon/".$owner["nick"], "rel" => "salmon");
1375 xml::add_element($doc, $root, "link", "", $attributes);
1377 $attributes = array("href" => App::get_baseurl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies");
1378 xml::add_element($doc, $root, "link", "", $attributes);
1380 $attributes = array("href" => App::get_baseurl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention");
1381 xml::add_element($doc, $root, "link", "", $attributes);
1383 $attributes = array("href" => App::get_baseurl()."/api/statuses/user_timeline/".$owner["nick"].".atom",
1384 "rel" => "self", "type" => "application/atom+xml");
1385 xml::add_element($doc, $root, "link", "", $attributes);
1391 * @brief Add the link to the push hubs to the XML document
1393 * @param object $doc XML document
1394 * @param object $root XML root element where the hub links are added
1396 public static function hublinks($doc, $root) {
1397 $hub = get_config('system','huburl');
1401 $hubs = explode(',', $hub);
1403 foreach($hubs as $h) {
1407 if ($h === '[internal]')
1408 $h = App::get_baseurl() . '/pubsubhubbub';
1409 xml::add_element($doc, $root, "link", "", array("href" => $h, "rel" => "hub"));
1416 * @brief Adds attachement data to the XML document
1418 * @param object $doc XML document
1419 * @param object $root XML root element where the hub links are added
1420 * @param array $item Data of the item that is to be posted
1422 private function get_attachment($doc, $root, $item) {
1424 $siteinfo = get_attached_data($item["body"]);
1426 switch($siteinfo["type"]) {
1428 $attributes = array("rel" => "enclosure",
1429 "href" => $siteinfo["url"],
1430 "type" => "text/html; charset=UTF-8",
1432 "title" => $siteinfo["title"]);
1433 xml::add_element($doc, $root, "link", "", $attributes);
1436 $imgdata = get_photo_info($siteinfo["image"]);
1437 $attributes = array("rel" => "enclosure",
1438 "href" => $siteinfo["image"],
1439 "type" => $imgdata["mime"],
1440 "length" => intval($imgdata["size"]));
1441 xml::add_element($doc, $root, "link", "", $attributes);
1444 $attributes = array("rel" => "enclosure",
1445 "href" => $siteinfo["url"],
1446 "type" => "text/html; charset=UTF-8",
1448 "title" => $siteinfo["title"]);
1449 xml::add_element($doc, $root, "link", "", $attributes);
1455 if (($siteinfo["type"] != "photo") AND isset($siteinfo["image"])) {
1456 $photodata = get_photo_info($siteinfo["image"]);
1458 $attributes = array("rel" => "preview", "href" => $siteinfo["image"], "media:width" => $photodata[0], "media:height" => $photodata[1]);
1459 xml::add_element($doc, $root, "link", "", $attributes);
1463 $arr = explode('[/attach],',$item['attach']);
1465 foreach($arr as $r) {
1467 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r,$matches);
1469 $attributes = array("rel" => "enclosure",
1470 "href" => $matches[1],
1471 "type" => $matches[3]);
1473 if(intval($matches[2]))
1474 $attributes["length"] = intval($matches[2]);
1476 if(trim($matches[4]) != "")
1477 $attributes["title"] = trim($matches[4]);
1479 xml::add_element($doc, $root, "link", "", $attributes);
1486 * @brief Adds the author element to the XML document
1488 * @param object $doc XML document
1489 * @param array $owner Contact data of the poster
1491 * @return object author element
1493 private function add_author($doc, $owner) {
1495 $r = q("SELECT `homepage` FROM `profile` WHERE `uid` = %d AND `is-default` LIMIT 1", intval($owner["uid"]));
1499 $author = $doc->createElement("author");
1500 xml::add_element($doc, $author, "activity:object-type", ACTIVITY_OBJ_PERSON);
1501 xml::add_element($doc, $author, "uri", $owner["url"]);
1502 xml::add_element($doc, $author, "name", $owner["name"]);
1503 xml::add_element($doc, $author, "summary", bbcode($owner["about"], false, false, 7));
1505 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $owner["url"]);
1506 xml::add_element($doc, $author, "link", "", $attributes);
1508 $attributes = array(
1510 "type" => "image/jpeg", // To-Do?
1511 "media:width" => 175,
1512 "media:height" => 175,
1513 "href" => $owner["photo"]);
1514 xml::add_element($doc, $author, "link", "", $attributes);
1516 if (isset($owner["thumb"])) {
1517 $attributes = array(
1519 "type" => "image/jpeg", // To-Do?
1520 "media:width" => 80,
1521 "media:height" => 80,
1522 "href" => $owner["thumb"]);
1523 xml::add_element($doc, $author, "link", "", $attributes);
1526 xml::add_element($doc, $author, "poco:preferredUsername", $owner["nick"]);
1527 xml::add_element($doc, $author, "poco:displayName", $owner["name"]);
1528 xml::add_element($doc, $author, "poco:note", bbcode($owner["about"], false, false, 7));
1530 if (trim($owner["location"]) != "") {
1531 $element = $doc->createElement("poco:address");
1532 xml::add_element($doc, $element, "poco:formatted", $owner["location"]);
1533 $author->appendChild($element);
1536 if (trim($profile["homepage"]) != "") {
1537 $urls = $doc->createElement("poco:urls");
1538 xml::add_element($doc, $urls, "poco:type", "homepage");
1539 xml::add_element($doc, $urls, "poco:value", $profile["homepage"]);
1540 xml::add_element($doc, $urls, "poco:primary", "true");
1541 $author->appendChild($urls);
1544 if (count($profile)) {
1545 xml::add_element($doc, $author, "followers", "", array("url" => App::get_baseurl()."/viewcontacts/".$owner["nick"]));
1546 xml::add_element($doc, $author, "statusnet:profile_info", "", array("local_id" => $owner["uid"]));
1553 * @TODO Picture attachments should look like this:
1554 * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1555 * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1560 * @brief Returns the given activity if present - otherwise returns the "post" activity
1562 * @param array $item Data of the item that is to be posted
1564 * @return string activity
1566 function construct_verb($item) {
1568 return $item['verb'];
1569 return ACTIVITY_POST;
1573 * @brief Returns the given object type if present - otherwise returns the "note" object type
1575 * @param array $item Data of the item that is to be posted
1577 * @return string Object type
1579 function construct_objecttype($item) {
1580 if (in_array($item['object-type'], array(ACTIVITY_OBJ_NOTE, ACTIVITY_OBJ_COMMENT)))
1581 return $item['object-type'];
1582 return ACTIVITY_OBJ_NOTE;
1586 * @brief Adds an entry element to the XML document
1588 * @param object $doc XML document
1589 * @param array $item Data of the item that is to be posted
1590 * @param array $owner Contact data of the poster
1591 * @param bool $toplevel
1593 * @return object Entry element
1595 private function entry($doc, $item, $owner, $toplevel = false) {
1596 $repeated_guid = self::get_reshared_guid($item);
1597 if ($repeated_guid != "")
1598 $xml = self::reshare_entry($doc, $item, $owner, $repeated_guid, $toplevel);
1603 if ($item["verb"] == ACTIVITY_LIKE) {
1604 return self::like_entry($doc, $item, $owner, $toplevel);
1605 } elseif (in_array($item["verb"], array(ACTIVITY_FOLLOW, NAMESPACE_OSTATUS."/unfollow"))) {
1606 return self::follow_entry($doc, $item, $owner, $toplevel);
1608 return self::note_entry($doc, $item, $owner, $toplevel);
1613 * @brief Adds a source entry to the XML document
1615 * @param object $doc XML document
1616 * @param array $contact Array of the contact that is added
1618 * @return object Source element
1620 private function source_entry($doc, $contact) {
1621 $source = $doc->createElement("source");
1622 xml::add_element($doc, $source, "id", $contact["poll"]);
1623 xml::add_element($doc, $source, "title", $contact["name"]);
1624 xml::add_element($doc, $source, "link", "", array("rel" => "alternate",
1625 "type" => "text/html",
1626 "href" => $contact["alias"]));
1627 xml::add_element($doc, $source, "link", "", array("rel" => "self",
1628 "type" => "application/atom+xml",
1629 "href" => $contact["poll"]));
1630 xml::add_element($doc, $source, "icon", $contact["photo"]);
1631 xml::add_element($doc, $source, "updated", datetime_convert("UTC","UTC",$contact["success_update"]."+00:00",ATOM_TIME));
1637 * @brief Fetches contact data from the contact or the gcontact table
1639 * @param string $url URL of the contact
1640 * @param array $owner Contact data of the poster
1642 * @return array Contact array
1644 private function contact_entry($url, $owner) {
1646 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
1647 dbesc(normalise_link($url)), intval($owner["uid"]));
1650 $contact["uid"] = -1;
1654 $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1655 dbesc(normalise_link($url)));
1658 $contact["uid"] = -1;
1659 $contact["success_update"] = $contact["updated"];
1666 if (!isset($contact["poll"])) {
1667 $data = probe_url($url);
1668 $contact["poll"] = $data["poll"];
1670 if (!$contact["alias"])
1671 $contact["alias"] = $data["alias"];
1674 if (!isset($contact["alias"]))
1675 $contact["alias"] = $contact["url"];
1681 * @brief Adds an entry element with reshared content
1683 * @param object $doc XML document
1684 * @param array $item Data of the item that is to be posted
1685 * @param array $owner Contact data of the poster
1686 * @param $repeated_guid
1687 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1689 * @return object Entry element
1691 private function reshare_entry($doc, $item, $owner, $repeated_guid, $toplevel) {
1693 if (($item["id"] != $item["parent"]) AND (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1694 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1697 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1699 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' AND NOT `private` AND `network` IN ('%s', '%s', '%s') LIMIT 1",
1700 intval($owner["uid"]), dbesc($repeated_guid),
1701 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS));
1703 $repeated_item = $r[0];
1707 $contact = self::contact_entry($repeated_item['author-link'], $owner);
1709 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1711 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1713 self::entry_content($doc, $entry, $item, $owner, $title, ACTIVITY_SHARE, false);
1715 $as_object = $doc->createElement("activity:object");
1717 xml::add_element($doc, $as_object, "activity:object-type", NAMESPACE_ACTIVITY_SCHEMA."activity");
1719 self::entry_content($doc, $as_object, $repeated_item, $owner, "", "", false);
1721 $author = self::add_author($doc, $contact);
1722 $as_object->appendChild($author);
1724 $as_object2 = $doc->createElement("activity:object");
1726 xml::add_element($doc, $as_object2, "activity:object-type", self::construct_objecttype($repeated_item));
1728 $title = sprintf("New comment by %s", $contact["nick"]);
1730 self::entry_content($doc, $as_object2, $repeated_item, $owner, $title);
1732 $as_object->appendChild($as_object2);
1734 self::entry_footer($doc, $as_object, $item, $owner, false);
1736 $source = self::source_entry($doc, $contact);
1738 $as_object->appendChild($source);
1740 $entry->appendChild($as_object);
1742 self::entry_footer($doc, $entry, $item, $owner);
1748 * @brief Adds an entry element with a "like"
1750 * @param object $doc XML document
1751 * @param array $item Data of the item that is to be posted
1752 * @param array $owner Contact data of the poster
1753 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1755 * @return object Entry element with "like"
1757 private function like_entry($doc, $item, $owner, $toplevel) {
1759 if (($item["id"] != $item["parent"]) AND (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1760 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1763 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1765 $verb = NAMESPACE_ACTIVITY_SCHEMA."favorite";
1766 self::entry_content($doc, $entry, $item, $owner, "Favorite", $verb, false);
1768 $as_object = $doc->createElement("activity:object");
1770 $parent = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d",
1771 dbesc($item["thr-parent"]), intval($item["uid"]));
1772 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1774 xml::add_element($doc, $as_object, "activity:object-type", self::construct_objecttype($parent[0]));
1776 self::entry_content($doc, $as_object, $parent[0], $owner, "New entry");
1778 $entry->appendChild($as_object);
1780 self::entry_footer($doc, $entry, $item, $owner);
1786 * @brief Adds the person object element to the XML document
1788 * @param object $doc XML document
1789 * @param array $owner Contact data of the poster
1790 * @param array $contact Contact data of the target
1792 * @return object author element
1794 private function add_person_object($doc, $owner, $contact) {
1796 $object = $doc->createElement("activity:object");
1797 xml::add_element($doc, $object, "activity:object-type", ACTIVITY_OBJ_PERSON);
1799 if ($contact['network'] == NETWORK_PHANTOM) {
1800 xml::add_element($doc, $object, "id", $contact['url']);
1804 xml::add_element($doc, $object, "id", $contact["alias"]);
1805 xml::add_element($doc, $object, "title", $contact["nick"]);
1807 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $contact["url"]);
1808 xml::add_element($doc, $object, "link", "", $attributes);
1810 $attributes = array(
1812 "type" => "image/jpeg", // To-Do?
1813 "media:width" => 175,
1814 "media:height" => 175,
1815 "href" => $contact["photo"]);
1816 xml::add_element($doc, $object, "link", "", $attributes);
1818 xml::add_element($doc, $object, "poco:preferredUsername", $contact["nick"]);
1819 xml::add_element($doc, $object, "poco:displayName", $contact["name"]);
1821 if (trim($contact["location"]) != "") {
1822 $element = $doc->createElement("poco:address");
1823 xml::add_element($doc, $element, "poco:formatted", $contact["location"]);
1824 $object->appendChild($element);
1831 * @brief Adds a follow/unfollow entry element
1833 * @param object $doc XML document
1834 * @param array $item Data of the follow/unfollow message
1835 * @param array $owner Contact data of the poster
1836 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1838 * @return object Entry element
1840 private function follow_entry($doc, $item, $owner, $toplevel) {
1842 $item["id"] = $item["parent"] = 0;
1843 $item["created"] = $item["edited"] = date("c");
1844 $item["private"] = true;
1846 $contact = Probe::uri($item['follow']);
1848 if ($contact['alias'] == '') {
1849 $contact['alias'] = $contact["url"];
1851 $item['follow'] = $contact['alias'];
1854 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1855 intval($owner['uid']), dbesc(normalise_link($contact["url"])));
1857 if (dbm::is_result($r)) {
1858 $connect_id = $r[0]['id'];
1863 if ($item['verb'] == ACTIVITY_FOLLOW) {
1864 $message = t('%s is now following %s.');
1865 $title = t('following');
1866 $action = "subscription";
1868 $message = t('%s stopped following %s.');
1869 $title = t('stopped following');
1870 $action = "unfollow";
1873 $item["uri"] = $item['parent-uri'] = $item['thr-parent'] =
1874 'tag:'.get_app()->get_hostname().
1875 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1876 ':person:'.$connect_id.':'.$item['created'];
1878 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1880 self::entry_header($doc, $entry, $owner, $toplevel);
1882 self::entry_content($doc, $entry, $item, $owner, $title);
1884 $object = self::add_person_object($doc, $owner, $contact);
1885 $entry->appendChild($object);
1887 self::entry_footer($doc, $entry, $item, $owner);
1893 * @brief Adds a regular entry element
1895 * @param object $doc XML document
1896 * @param array $item Data of the item that is to be posted
1897 * @param array $owner Contact data of the poster
1898 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1900 * @return object Entry element
1902 private function note_entry($doc, $item, $owner, $toplevel) {
1904 if (($item["id"] != $item["parent"]) AND (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1905 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1908 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1910 xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1912 self::entry_content($doc, $entry, $item, $owner, $title);
1914 self::entry_footer($doc, $entry, $item, $owner);
1920 * @brief Adds a header element to the XML document
1922 * @param object $doc XML document
1923 * @param object $entry The entry element where the elements are added
1924 * @param array $owner Contact data of the poster
1925 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1927 * @return string The title for the element
1929 private function entry_header($doc, &$entry, $owner, $toplevel) {
1930 /// @todo Check if this title stuff is really needed (I guess not)
1932 $entry = $doc->createElement("entry");
1933 $title = sprintf("New note by %s", $owner["nick"]);
1935 $entry = $doc->createElementNS(NAMESPACE_ATOM1, "entry");
1937 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1938 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1939 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1940 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1941 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
1942 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1943 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1945 $author = self::add_author($doc, $owner);
1946 $entry->appendChild($author);
1948 $title = sprintf("New comment by %s", $owner["nick"]);
1954 * @brief Adds elements to the XML document
1956 * @param object $doc XML document
1957 * @param object $entry Entry element where the content is added
1958 * @param array $item Data of the item that is to be posted
1959 * @param array $owner Contact data of the poster
1960 * @param string $title Title for the post
1961 * @param string $verb The activity verb
1962 * @param bool $complete Add the "status_net" element?
1964 private function entry_content($doc, $entry, $item, $owner, $title, $verb = "", $complete = true) {
1967 $verb = self::construct_verb($item);
1969 xml::add_element($doc, $entry, "id", $item["uri"]);
1970 xml::add_element($doc, $entry, "title", $title);
1972 $body = self::format_picture_post($item['body']);
1974 if ($item['title'] != "")
1975 $body = "[b]".$item['title']."[/b]\n\n".$body;
1977 $body = bbcode($body, false, false, 7);
1979 xml::add_element($doc, $entry, "content", $body, array("type" => "html"));
1981 xml::add_element($doc, $entry, "link", "", array("rel" => "alternate", "type" => "text/html",
1982 "href" => App::get_baseurl()."/display/".$item["guid"]));
1984 if ($complete AND ($item["id"] > 0))
1985 xml::add_element($doc, $entry, "status_net", "", array("notice_id" => $item["id"]));
1987 xml::add_element($doc, $entry, "activity:verb", $verb);
1989 xml::add_element($doc, $entry, "published", datetime_convert("UTC","UTC",$item["created"]."+00:00",ATOM_TIME));
1990 xml::add_element($doc, $entry, "updated", datetime_convert("UTC","UTC",$item["edited"]."+00:00",ATOM_TIME));
1994 * @brief Adds the elements at the foot of an entry to the XML document
1996 * @param object $doc XML document
1997 * @param object $entry The entry element where the elements are added
1998 * @param array $item Data of the item that is to be posted
1999 * @param array $owner Contact data of the poster
2002 private function entry_footer($doc, $entry, $item, $owner, $complete = true) {
2004 $mentioned = array();
2006 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
2007 $parent = q("SELECT `guid`, `author-link`, `owner-link` FROM `item` WHERE `id` = %d", intval($item["parent"]));
2008 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
2010 $attributes = array(
2011 "ref" => $parent_item,
2012 "type" => "text/html",
2013 "href" => App::get_baseurl()."/display/".$parent[0]["guid"]);
2014 xml::add_element($doc, $entry, "thr:in-reply-to", "", $attributes);
2016 $attributes = array(
2018 "href" => App::get_baseurl()."/display/".$parent[0]["guid"]);
2019 xml::add_element($doc, $entry, "link", "", $attributes);
2021 $mentioned[$parent[0]["author-link"]] = $parent[0]["author-link"];
2022 $mentioned[$parent[0]["owner-link"]] = $parent[0]["owner-link"];
2024 $thrparent = q("SELECT `guid`, `author-link`, `owner-link` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
2025 intval($owner["uid"]),
2026 dbesc($parent_item));
2028 $mentioned[$thrparent[0]["author-link"]] = $thrparent[0]["author-link"];
2029 $mentioned[$thrparent[0]["owner-link"]] = $thrparent[0]["owner-link"];
2033 if (intval($item["parent"]) > 0) {
2034 $conversation = App::get_baseurl()."/display/".$owner["nick"]."/".$item["parent"];
2035 xml::add_element($doc, $entry, "link", "", array("rel" => "ostatus:conversation", "href" => $conversation));
2036 xml::add_element($doc, $entry, "ostatus:conversation", $conversation);
2039 $tags = item_getfeedtags($item);
2042 foreach($tags as $t)
2044 $mentioned[$t[1]] = $t[1];
2046 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
2047 $newmentions = array();
2048 foreach ($mentioned AS $mention) {
2049 $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
2050 $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
2052 $mentioned = $newmentions;
2054 foreach ($mentioned AS $mention) {
2055 $r = q("SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
2056 intval($owner["uid"]),
2057 dbesc(normalise_link($mention)));
2058 if ($r[0]["forum"] OR $r[0]["prv"])
2059 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
2060 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
2061 "href" => $mention));
2063 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
2064 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
2065 "href" => $mention));
2068 if (!$item["private"]) {
2069 xml::add_element($doc, $entry, "link", "", array("rel" => "ostatus:attention",
2070 "href" => "http://activityschema.org/collection/public"));
2071 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
2072 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
2073 "href" => "http://activityschema.org/collection/public"));
2077 foreach($tags as $t)
2079 xml::add_element($doc, $entry, "category", "", array("term" => $t[2]));
2081 self::get_attachment($doc, $entry, $item);
2083 if ($complete AND ($item["id"] > 0)) {
2084 $app = $item["app"];
2088 $attributes = array("local_id" => $item["id"], "source" => $app);
2090 if (isset($parent["id"]))
2091 $attributes["repeat_of"] = $parent["id"];
2093 if ($item["coord"] != "")
2094 xml::add_element($doc, $entry, "georss:point", $item["coord"]);
2096 xml::add_element($doc, $entry, "statusnet:notice_info", "", $attributes);
2101 * @brief Creates the XML feed for a given nickname
2103 * @param app $a The application class
2104 * @param string $owner_nick Nickname of the feed owner
2105 * @param string $last_update Date of the last update
2107 * @return string XML feed
2109 public static function feed(App $a, $owner_nick, $last_update) {
2111 $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`
2112 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
2113 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
2114 dbesc($owner_nick));
2120 if(!strlen($last_update))
2121 $last_update = 'now -30 days';
2123 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
2124 $authorid = get_contact($owner["url"], 0);
2126 $items = q("SELECT `item`.*, `item`.`id` AS `item_id` FROM `item` USE INDEX (`uid_contactid_created`)
2127 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `item`.`parent`
2128 WHERE `item`.`uid` = %d AND `item`.`contact-id` = %d AND
2129 `item`.`author-id` = %d AND `item`.`created` > '%s' AND
2130 NOT `item`.`deleted` AND NOT `item`.`private` AND
2131 `thread`.`network` IN ('%s', '%s')
2132 ORDER BY `item`.`created` DESC LIMIT 300",
2133 intval($owner["uid"]), intval($owner["id"]),
2134 intval($authorid), dbesc($check_date),
2135 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
2137 /* 2016-10-23: The old query will be kept until we are sure that the query above is a good and fast replacement
2139 $items = q("SELECT `item`.*, `item`.`id` AS `item_id` FROM `item`
2140 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `item`.`parent`
2141 LEFT JOIN `item` AS `thritem` ON `thritem`.`uri`=`item`.`thr-parent` AND `thritem`.`uid`=`item`.`uid`
2142 WHERE `item`.`uid` = %d AND `item`.`received` > '%s' AND NOT `item`.`private` AND NOT `item`.`deleted`
2143 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
2144 AND ((`item`.`wall` AND (`item`.`parent` = `item`.`id`))
2145 OR (`item`.`network` = '%s' AND ((`thread`.`network` IN ('%s', '%s')) OR (`thritem`.`network` IN ('%s', '%s')))) AND `thread`.`mention`)
2146 AND ((`item`.`owner-link` IN ('%s', '%s') AND (`item`.`parent` = `item`.`id`))
2147 OR (`item`.`author-link` IN ('%s', '%s')))
2148 ORDER BY `item`.`id` DESC
2150 intval($owner["uid"]), dbesc($check_date), dbesc(NETWORK_DFRN),
2151 //dbesc(NETWORK_OSTATUS), dbesc(NETWORK_OSTATUS),
2152 //dbesc(NETWORK_OSTATUS), dbesc(NETWORK_OSTATUS),
2153 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN),
2154 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN),
2155 dbesc($owner["nurl"]), dbesc(str_replace("http://", "https://", $owner["nurl"])),
2156 dbesc($owner["nurl"]), dbesc(str_replace("http://", "https://", $owner["nurl"]))
2159 $doc = new DOMDocument('1.0', 'utf-8');
2160 $doc->formatOutput = true;
2162 $root = self::add_header($doc, $owner);
2164 foreach ($items AS $item) {
2165 $entry = self::entry($doc, $item, $owner);
2166 $root->appendChild($entry);
2169 return(trim($doc->saveXML()));
2173 * @brief Creates the XML for a salmon message
2175 * @param array $item Data of the item that is to be posted
2176 * @param array $owner Contact data of the poster
2178 * @return string XML for the salmon
2180 public static function salmon($item,$owner) {
2182 $doc = new DOMDocument('1.0', 'utf-8');
2183 $doc->formatOutput = true;
2185 $entry = self::entry($doc, $item, $owner, true);
2187 $doc->appendChild($entry);
2189 return(trim($doc->saveXML()));