3 * @file include/ostatus.php
7 use Friendica\Core\Config;
9 require_once("include/Contact.php");
10 require_once("include/threads.php");
11 require_once("include/html2bbcode.php");
12 require_once("include/bbcode.php");
13 require_once("include/items.php");
14 require_once("mod/share.php");
15 require_once("include/enotify.php");
16 require_once("include/socgraph.php");
17 require_once("include/Photo.php");
18 require_once("include/Scrape.php");
19 require_once("include/follow.php");
20 require_once("include/api.php");
21 require_once("mod/proxy.php");
22 require_once("include/xml.php");
25 * @brief This class contain functions for the OStatus protocol
29 const OSTATUS_DEFAULT_POLL_INTERVAL = 30; // given in minutes
30 const OSTATUS_DEFAULT_POLL_TIMEFRAME = 1440; // given in minutes
31 const OSTATUS_DEFAULT_POLL_TIMEFRAME_MENTIONS = 14400; // given in minutes
34 * @brief Fetches author data
36 * @param object $xpath The xpath object
37 * @param object $context The xml context of the author detals
38 * @param array $importer user record of the importing user
39 * @param array $contact Called by reference, will contain the fetched contact
40 * @param bool $onlyfetch Only fetch the header without updating the contact entries
42 * @return array Array of author related entries for the item
44 private function fetchauthor($xpath, $context, $importer, &$contact, $onlyfetch) {
47 $author["author-link"] = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
48 $author["author-name"] = $xpath->evaluate('atom:author/atom:name/text()', $context)->item(0)->nodeValue;
49 $addr = $xpath->evaluate('atom:author/atom:email/text()', $context)->item(0)->nodeValue;
51 $aliaslink = $author["author-link"];
53 $alternate = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0)->attributes;
54 if (is_object($alternate)) {
55 foreach ($alternate AS $attributes) {
56 if (($attributes->name == "href") AND ($attributes->textContent != "")) {
57 $author["author-link"] = $attributes->textContent;
62 $author["contact-id"] = $contact["id"];
64 if ($author["author-link"] != "") {
65 if ($aliaslink == "") {
66 $aliaslink = $author["author-link"];
69 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` IN ('%s', '%s') AND `network` != '%s'",
70 intval($importer["uid"]), dbesc(normalise_link($author["author-link"])),
71 dbesc(normalise_link($aliaslink)), dbesc(NETWORK_STATUSNET));
72 if (dbm::is_result($r)) {
74 $author["contact-id"] = $r[0]["id"];
75 $author["author-link"] = $r[0]["url"];
77 } elseif ($addr != "") {
79 $contact = dba::fetch_first("SELECT * FROM `contact` WHERE `uid` = ? AND `addr` = ? AND `network` != ?",
80 $importer["uid"], $addr, NETWORK_STATUSNET);
81 if (dbm::is_result($contact)) {
82 $author["contact-id"] = $contact["id"];
83 $author["author-link"] = $contact["url"];
87 $avatarlist = array();
88 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
89 foreach($avatars AS $avatar) {
92 foreach($avatar->attributes AS $attributes) {
93 if ($attributes->name == "href")
94 $href = $attributes->textContent;
95 if ($attributes->name == "width")
96 $width = $attributes->textContent;
98 if (($width > 0) AND ($href != ""))
99 $avatarlist[$width] = $href;
101 if (count($avatarlist) > 0) {
103 $author["author-avatar"] = Probe::fix_avatar(current($avatarlist), $author["author-link"]);
106 $displayname = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
107 if ($displayname != "")
108 $author["author-name"] = $displayname;
110 $author["owner-name"] = $author["author-name"];
111 $author["owner-link"] = $author["author-link"];
112 $author["owner-avatar"] = $author["author-avatar"];
114 // Only update the contacts if it is an OStatus contact
115 if ($r AND !$onlyfetch AND ($contact["network"] == NETWORK_OSTATUS)) {
117 // Update contact data
119 // This query doesn't seem to work
120 // $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
122 // $contact["notify"] = $value;
124 // This query doesn't seem to work as well - I hate these queries
125 // $value = $xpath->query("atom:link[@rel='self' and @type='application/atom+xml']", $context)->item(0)->nodeValue;
127 // $contact["poll"] = $value;
129 $value = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
131 $contact["alias"] = $value;
133 $value = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
135 $contact["name"] = $value;
137 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
139 $contact["nick"] = $value;
141 $value = $xpath->evaluate('atom:author/poco:note/text()', $context)->item(0)->nodeValue;
143 $contact["about"] = html2bbcode($value);
145 $value = $xpath->evaluate('atom:author/poco:address/poco:formatted/text()', $context)->item(0)->nodeValue;
147 $contact["location"] = $value;
149 if (($contact["name"] != $r[0]["name"]) OR ($contact["nick"] != $r[0]["nick"]) OR ($contact["about"] != $r[0]["about"]) OR
150 ($contact["alias"] != $r[0]["alias"]) OR ($contact["location"] != $r[0]["location"])) {
152 logger("Update contact data for contact ".$contact["id"], LOGGER_DEBUG);
154 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `alias` = '%s', `about` = '%s', `location` = '%s', `name-date` = '%s' WHERE `id` = %d",
155 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["alias"]),
156 dbesc($contact["about"]), dbesc($contact["location"]),
157 dbesc(datetime_convert()), intval($contact["id"]));
160 if (isset($author["author-avatar"]) AND ($author["author-avatar"] != $r[0]['avatar'])) {
161 logger("Update profile picture for contact ".$contact["id"], LOGGER_DEBUG);
163 update_contact_avatar($author["author-avatar"], $importer["uid"], $contact["id"]);
166 // Ensure that we are having this contact (with uid=0)
167 $cid = get_contact($author["author-link"], 0);
170 // Update it with the current values
171 q("UPDATE `contact` SET `url` = '%s', `name` = '%s', `nick` = '%s', `alias` = '%s',
172 `about` = '%s', `location` = '%s',
173 `success_update` = '%s', `last-update` = '%s'
175 dbesc($author["author-link"]), dbesc($contact["name"]), dbesc($contact["nick"]),
176 dbesc($contact["alias"]), dbesc($contact["about"]), dbesc($contact["location"]),
177 dbesc(datetime_convert()), dbesc(datetime_convert()), intval($cid));
180 update_contact_avatar($author["author-avatar"], 0, $cid);
183 $contact["generation"] = 2;
184 $contact["hide"] = false; // OStatus contacts are never hidden
185 $contact["photo"] = $author["author-avatar"];
186 $gcid = update_gcontact($contact);
188 link_gcontact($gcid, $contact["uid"], $contact["id"]);
195 * @brief Fetches author data from a given XML string
197 * @param string $xml The XML
198 * @param array $importer user record of the importing user
200 * @return array Array of author related entries for the item
202 public static function salmon_author($xml, $importer) {
207 $doc = new DOMDocument();
208 @$doc->loadXML($xml);
210 $xpath = new DomXPath($doc);
211 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
212 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
213 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
214 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
215 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
216 $xpath->registerNamespace('poco', NAMESPACE_POCO);
217 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
218 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
220 $entries = $xpath->query('/atom:entry');
222 foreach ($entries AS $entry) {
224 $author = self::fetchauthor($xpath, $entry, $importer, $contact, true);
230 * @brief Read attributes from element
232 * @param object $element Element object
234 * @return array attributes
236 private static function read_attributes($element) {
237 $attribute = array();
239 foreach ($element->attributes AS $attributes) {
240 $attribute[$attributes->name] = $attributes->textContent;
247 * @brief Imports an XML string containing OStatus elements
249 * @param string $xml The XML
250 * @param array $importer user record of the importing user
252 * @param array $hub Called by reference, returns the fetched hub data
254 public static function import($xml,$importer,&$contact, &$hub) {
255 /// @todo this function is too long. It has to be split in many parts
257 logger("Import OStatus message", LOGGER_DEBUG);
262 //$tempfile = tempnam(get_temppath(), "import");
263 //file_put_contents($tempfile, $xml);
265 $doc = new DOMDocument();
266 @$doc->loadXML($xml);
268 $xpath = new DomXPath($doc);
269 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
270 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
271 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
272 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
273 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
274 $xpath->registerNamespace('poco', NAMESPACE_POCO);
275 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
276 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
279 $hub_attributes = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0)->attributes;
280 if (is_object($hub_attributes)) {
281 foreach ($hub_attributes AS $hub_attribute) {
282 if ($hub_attribute->name == "href") {
283 $hub = $hub_attribute->textContent;
284 logger("Found hub ".$hub, LOGGER_DEBUG);
289 $header["uid"] = $importer["uid"];
290 $header["network"] = NETWORK_OSTATUS;
291 $header["type"] = "remote";
293 $header["origin"] = 0;
294 $header["gravity"] = GRAVITY_PARENT;
296 // it could either be a received post or a post we fetched by ourselves
297 // depending on that, the first node is different
298 $first_child = $doc->firstChild->tagName;
300 if ($first_child == "feed") {
301 $entries = $xpath->query('/atom:feed/atom:entry');
302 $header["protocol"] = PROTOCOL_OSTATUS_FEED;
304 $entries = $xpath->query('/atom:entry');
305 $header["protocol"] = PROTOCOL_OSTATUS_SALMON;
308 $conversationlist = array();
311 // Reverse the order of the entries
312 $entrylist = array();
314 foreach ($entries AS $entry) {
315 $entrylist[] = $entry;
317 foreach (array_reverse($entrylist) AS $entry) {
322 if ($first_child == "feed") {
323 $author = self::fetchauthor($xpath, $doc->firstChild, $importer, $contact, false);
325 $author = self::fetchauthor($xpath, $entry, $importer, $contact, false);
327 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
331 $nickname = $author["author-name"];
333 $item = array_merge($header, $author);
336 $item["uri"] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
338 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
339 intval($importer["uid"]), dbesc($item["uri"]));
340 if (dbm::is_result($r)) {
341 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already existed under id ".$r[0]["id"], LOGGER_DEBUG);
345 $item["body"] = add_page_info_to_body(html2bbcode($xpath->query('atom:content/text()', $entry)->item(0)->nodeValue));
346 $item["object-type"] = $xpath->query('activity:object-type/text()', $entry)->item(0)->nodeValue;
347 $item["verb"] = $xpath->query('activity:verb/text()', $entry)->item(0)->nodeValue;
349 // Mastodon Content Warning
350 if (($item["verb"] == ACTIVITY_POST) AND $xpath->evaluate('boolean(atom:summary)', $entry)) {
351 $clear_text = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
353 $item["body"] = html2bbcode($clear_text) . '[spoiler]' . $item["body"] . '[/spoiler]';
356 if (($item["object-type"] == ACTIVITY_OBJ_BOOKMARK) OR ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
357 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
358 $item["body"] = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
359 } elseif ($item["object-type"] == ACTIVITY_OBJ_QUESTION) {
360 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
362 $item["source"] = $xml;
366 if ($item["verb"] == "qvitter-delete-notice" || $item["verb"] == ACTIVITY_DELETE) {
367 // ignore "Delete" messages (by now)
368 logger("Ignore delete message ".print_r($item, true));
372 if ($item["verb"] == ACTIVITY_JOIN) {
373 // ignore "Join" messages
374 logger("Ignore join message ".print_r($item, true));
378 if ($item["verb"] == ACTIVITY_FOLLOW) {
379 new_follower($importer, $contact, $item, $nickname);
383 if ($item["verb"] == NAMESPACE_OSTATUS."/unfollow") {
384 lose_follower($importer, $contact, $item, $dummy);
388 if ($item["verb"] == ACTIVITY_FAVORITE) {
389 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
390 logger("Favorite ".$orig_uri." ".print_r($item, true));
392 $item["verb"] = ACTIVITY_LIKE;
393 $item["parent-uri"] = $orig_uri;
394 $item["gravity"] = GRAVITY_LIKE;
397 if ($item["verb"] == NAMESPACE_OSTATUS."/unfavorite") {
398 // Ignore "Unfavorite" message
399 logger("Ignore unfavorite message ".print_r($item, true));
403 // http://activitystrea.ms/schema/1.0/rsvp-yes
404 if (!in_array($item["verb"], array(ACTIVITY_POST, ACTIVITY_LIKE, ACTIVITY_SHARE))) {
405 logger("Unhandled verb ".$item["verb"]." ".print_r($item, true));
407 $item["created"] = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
408 $item["edited"] = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
409 $conversation = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
410 $item['conversation-uri'] = $conversation;
412 $conv = $xpath->query('ostatus:conversation', $entry);
413 if (is_object($conv->item(0))) {
414 foreach ($conv->item(0)->attributes AS $attributes) {
415 if ($attributes->name == "ref") {
416 $item['conversation-uri'] = $attributes->textContent;
418 if ($attributes->name == "href") {
419 $item['conversation-href'] = $attributes->textContent;
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;
432 if ($attributes->name == "href") {
433 $related = $attributes->textContent;
438 $georsspoint = $xpath->query('georss:point', $entry);
440 $item["coord"] = $georsspoint->item(0)->nodeValue;
442 $categories = $xpath->query('atom:category', $entry);
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"])) {
451 $item["tag"] .= "#[url=".App::get_baseurl()."/search?tag=".$term."]".$term."[/url]";
460 $links = $xpath->query('atom:link', $entry);
462 foreach ($links AS $link) {
463 $attribute = self::read_attributes($link);
465 if (($attribute['rel'] != "") AND ($attribute['href'] != "")) {
466 switch ($attribute['rel']) {
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']);
474 case "ostatus:conversation":
475 $conversation = $attribute['href'];
476 $item['conversation-href'] = $conversation;
477 if (!isset($item['conversation-uri'])) {
478 $item['conversation-uri'] = $item['conversation-href'];
482 $enclosure = $attribute['href'];
483 if (strlen($item["attach"])) {
484 $item["attach"] .= ',';
486 if (!isset($attribute['length'])) {
487 $attribute['length'] = "0";
489 $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.$attribute['title'].'"[/attach]';
492 if ($item["object-type"] != ACTIVITY_OBJ_BOOKMARK) {
493 if (!isset($item["parent-uri"])) {
494 $item["parent-uri"] = $attribute['href'];
496 if ($related == "") {
497 $related = $attribute['href'];
500 $item["body"] .= add_page_info($attribute['href']);
504 $self = $attribute['href'];
507 // Notification check
508 if ($importer["nurl"] == normalise_link($attribute['href'])) {
520 $notice_info = $xpath->query('statusnet:notice_info', $entry);
521 if ($notice_info AND ($notice_info->length > 0)) {
522 foreach ($notice_info->item(0)->attributes AS $attributes) {
523 if ($attributes->name == "source") {
524 $item["app"] = strip_tags($attributes->textContent);
526 if ($attributes->name == "local_id") {
527 $local_id = $attributes->textContent;
529 if ($attributes->name == "repeat_of") {
530 $repeat_of = $attributes->textContent;
535 // Is it a repeated post?
536 if (($repeat_of != "") OR ($item["verb"] == ACTIVITY_SHARE)) {
537 $activityobjects = $xpath->query('activity:object', $entry)->item(0);
539 if (is_object($activityobjects)) {
541 $orig_uri = $xpath->query("activity:object/atom:id", $activityobjects)->item(0)->nodeValue;
542 if (!isset($orig_uri)) {
543 $orig_uri = $xpath->query('atom:id/text()', $activityobjects)->item(0)->nodeValue;
545 $orig_links = $xpath->query("activity:object/atom:link[@rel='alternate']", $activityobjects);
546 if ($orig_links AND ($orig_links->length > 0)) {
547 foreach ($orig_links->item(0)->attributes AS $attributes) {
548 if ($attributes->name == "href") {
549 $orig_link = $attributes->textContent;
553 if (!isset($orig_link)) {
554 $orig_link = $xpath->query("atom:link[@rel='alternate']", $activityobjects)->item(0)->nodeValue;
556 if (!isset($orig_link)) {
557 $orig_link = self::convert_href($orig_uri);
559 $orig_body = $xpath->query('activity:object/atom:content/text()', $activityobjects)->item(0)->nodeValue;
560 if (!isset($orig_body)) {
561 $orig_body = $xpath->query('atom:content/text()', $activityobjects)->item(0)->nodeValue;
563 $orig_created = $xpath->query('atom:published/text()', $activityobjects)->item(0)->nodeValue;
564 $orig_edited = $xpath->query('atom:updated/text()', $activityobjects)->item(0)->nodeValue;
566 $orig_contact = $contact;
567 $orig_author = self::fetchauthor($xpath, $activityobjects, $importer, $orig_contact, false);
569 $item["author-name"] = $orig_author["author-name"];
570 $item["author-link"] = $orig_author["author-link"];
571 $item["author-avatar"] = $orig_author["author-avatar"];
573 $item["body"] = add_page_info_to_body(html2bbcode($orig_body));
574 $item["created"] = $orig_created;
575 $item["edited"] = $orig_edited;
577 $item["uri"] = $orig_uri;
579 if (!isset($item["plink"])) {
580 $item["plink"] = $orig_link;
583 $item["verb"] = $xpath->query('activity:verb/text()', $activityobjects)->item(0)->nodeValue;
585 $item["object-type"] = $xpath->query('activity:object/activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
586 if (!isset($item["object-type"])) {
587 $item["object-type"] = $xpath->query('activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
590 $enclosures = $xpath->query("atom:link[@rel='alternate']", $activityobjects);
592 foreach ($enclosures AS $link) {
593 $attribute = self::read_attributes($link);
595 $enclosure = $attribute['href'];
596 if (strlen($item["attach"])) {
597 $item["attach"] .= ',';
599 if (!isset($attribute['length'])) {
600 $attribute['length'] = "0";
602 $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.$attribute['title'].'"[/attach]';
609 //if ($enclosure != "")
610 // $item["body"] .= add_page_info($enclosure);
612 if (isset($item["parent-uri"])) {
613 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
614 intval($importer["uid"]), dbesc($item["parent-uri"]));
616 // Only fetch missing stuff if it is a comment or reshare.
617 if (in_array($item["verb"], array(ACTIVITY_POST, ACTIVITY_SHARE)) AND
618 !dbm::is_result($r) AND ($related != "")) {
619 $reply_path = str_replace("/notice/", "/api/statuses/show/", $related).".atom";
621 if ($reply_path != $related) {
622 logger("Fetching related items for user ".$importer["uid"]." from ".$reply_path, LOGGER_DEBUG);
623 $reply_xml = fetch_url($reply_path);
625 $reply_contact = $contact;
626 self::import($reply_xml,$importer,$reply_contact, $reply_hub);
628 // After the import try to fetch the parent item again
629 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
630 intval($importer["uid"]), dbesc($item["parent-uri"]));
633 if (dbm::is_result($r)) {
634 $item["type"] = 'remote-comment';
635 $item["gravity"] = GRAVITY_COMMENT;
638 $item["parent-uri"] = $item["uri"];
640 $item_id = self::completion($conversation, $importer["uid"], $item, $self);
643 logger("Error storing item", LOGGER_DEBUG);
647 logger("Item was stored with id ".$item_id, LOGGER_DEBUG);
652 * @brief Create an url out of an uri
654 * @param string $href URI in the format "parameter1:parameter1:..."
656 * @return string URL in the format http(s)://....
658 public static function convert_href($href) {
659 $elements = explode(":",$href);
661 if ((count($elements) <= 2) OR ($elements[0] != "tag"))
664 $server = explode(",", $elements[1]);
665 $conversation = explode("=", $elements[2]);
667 if ((count($elements) == 4) AND ($elements[2] == "post"))
668 return "http://".$server[0]."/notice/".$elements[3];
670 if ((count($conversation) != 2) OR ($conversation[1] ==""))
673 if ($elements[3] == "objectType=thread")
674 return "http://".$server[0]."/conversation/".$conversation[1];
676 return "http://".$server[0]."/notice/".$conversation[1];
682 * @brief Checks if there are entries in conversations that aren't present on our side
684 * @param bool $mentions Fetch conversations where we are mentioned
685 * @param bool $override Override the interval setting
687 public static function check_conversations($mentions = false, $override = false) {
688 $last = get_config('system','ostatus_last_poll');
690 $poll_interval = intval(get_config('system','ostatus_poll_interval'));
691 if (!$poll_interval) {
692 $poll_interval = self::OSTATUS_DEFAULT_POLL_INTERVAL;
695 // Don't poll if the interval is set negative
696 if (($poll_interval < 0) AND !$override) {
701 $poll_timeframe = intval(get_config('system','ostatus_poll_timeframe'));
702 if (!$poll_timeframe) {
703 $poll_timeframe = self::OSTATUS_DEFAULT_POLL_TIMEFRAME;
706 $poll_timeframe = intval(get_config('system','ostatus_poll_timeframe'));
707 if (!$poll_timeframe) {
708 $poll_timeframe = self::OSTATUS_DEFAULT_POLL_TIMEFRAME_MENTIONS;
713 if ($last AND !$override) {
714 $next = $last + ($poll_interval * 60);
715 if ($next > time()) {
716 logger('poll interval not reached');
721 logger('cron_start');
723 $start = date("Y-m-d H:i:s", time() - ($poll_timeframe * 60));
726 $conversations = q("SELECT `term`.`oid`, `term`.`url`, `term`.`uid` FROM `term`
727 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `term`.`oid` AND `thread`.`uid` = `term`.`uid`
728 WHERE `term`.`type` = 7 AND `term`.`term` > '%s' AND `thread`.`mention`
729 GROUP BY `term`.`url`, `term`.`uid`, `term`.`oid`, `term`.`term` ORDER BY `term`.`term` DESC", dbesc($start));
731 $conversations = q("SELECT `oid`, `url`, `uid` FROM `term`
732 WHERE `type` = 7 AND `term` > '%s'
733 GROUP BY `url`, `uid`, `oid`, `term` ORDER BY `term` DESC", dbesc($start));
736 foreach ($conversations AS $conversation) {
737 self::completion($conversation['url'], $conversation['uid']);
742 set_config('system','ostatus_last_poll', time());
746 * @brief Updates the gcontact table with actor data from the conversation
748 * @param object $actor The actor object that contains the contact data
750 private function conv_fetch_actor($actor) {
752 // We set the generation to "3" since the data here is not as reliable as the data we get on other occasions
753 $contact = array("network" => NETWORK_OSTATUS, "generation" => 3);
755 if (isset($actor->url))
756 $contact["url"] = $actor->url;
758 if (isset($actor->displayName))
759 $contact["name"] = $actor->displayName;
761 if (isset($actor->portablecontacts_net->displayName))
762 $contact["name"] = $actor->portablecontacts_net->displayName;
764 if (isset($actor->portablecontacts_net->preferredUsername))
765 $contact["nick"] = $actor->portablecontacts_net->preferredUsername;
767 if (isset($actor->id))
768 $contact["alias"] = $actor->id;
770 if (isset($actor->summary))
771 $contact["about"] = $actor->summary;
773 if (isset($actor->portablecontacts_net->note))
774 $contact["about"] = $actor->portablecontacts_net->note;
776 if (isset($actor->portablecontacts_net->addresses->formatted))
777 $contact["location"] = $actor->portablecontacts_net->addresses->formatted;
780 if (isset($actor->image->url))
781 $contact["photo"] = $actor->image->url;
783 if (isset($actor->image->width))
784 $avatarwidth = $actor->image->width;
786 if (is_array($actor->status_net->avatarLinks))
787 foreach ($actor->status_net->avatarLinks AS $avatar) {
788 if ($avatarsize < $avatar->width) {
789 $contact["photo"] = $avatar->url;
790 $avatarsize = $avatar->width;
794 $contact["hide"] = false; // OStatus contacts are never hidden
795 update_gcontact($contact);
799 * @brief Fetches the conversation url for a given item link or conversation id
801 * @param string $self The link to the posting
802 * @param string $conversation_id The conversation id
804 * @return string The conversation url
806 private function fetch_conversation($self, $conversation_id = "") {
808 if ($conversation_id != "") {
809 $elements = explode(":", $conversation_id);
811 if ((count($elements) <= 2) OR ($elements[0] != "tag"))
812 return $conversation_id;
818 $json = str_replace(".atom", ".json", $self);
820 $raw = fetch_url($json);
824 $data = json_decode($raw);
825 if (!is_object($data))
828 $conversation_id = $data->statusnet_conversation_id;
830 $pos = strpos($self, "/api/statuses/show/");
831 $base_url = substr($self, 0, $pos);
833 return $base_url."/conversation/".$conversation_id;
837 * @brief Fetches actor details of a given actor and user id
839 * @param string $actor The actor url
840 * @param int $uid The user id
841 * @param int $contact_id The default contact-id
843 * @return array Array with actor details
845 private function get_actor_details($actor, $uid, $contact_id) {
849 $contact = q("SELECT `id`, `rel`, `network` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'",
850 $uid, normalise_link($actor), NETWORK_STATUSNET);
853 $contact = q("SELECT `id`, `rel`, `network` FROM `contact` WHERE `uid` = %d AND `alias` IN ('%s', '%s') AND `network` != '%s'",
854 $uid, $actor, normalise_link($actor), NETWORK_STATUSNET);
857 logger("Found contact for url ".$actor, LOGGER_DEBUG);
858 $details["contact_id"] = $contact[0]["id"];
859 $details["network"] = $contact[0]["network"];
861 $details["not_following"] = !in_array($contact[0]["rel"], array(CONTACT_IS_SHARING, CONTACT_IS_FRIEND));
863 logger("No contact found for user ".$uid." and url ".$actor, LOGGER_DEBUG);
865 // Adding a global contact
866 /// @TODO Use this data for the post
867 $details["global_contact_id"] = get_contact($actor, 0);
869 logger("Global contact ".$global_contact_id." found for url ".$actor, LOGGER_DEBUG);
871 $details["contact_id"] = $contact_id;
872 $details["network"] = NETWORK_OSTATUS;
874 $details["not_following"] = true;
881 * @brief Stores an item and completes the thread
883 * @param string $conversation_url The URI of the conversation
884 * @param integer $uid The user id
885 * @param array $item Data of the item that is to be posted
887 * @return integer The item id of the posted item array
889 private function completion($conversation_url, $uid, $item = array(), $self = "") {
891 /// @todo This function is totally ugly and has to be rewritten totally
893 // Import all threads or only threads that were started by our followers?
894 $all_threads = !get_config('system','ostatus_full_threads');
898 $conversation_url = self::fetch_conversation($self, $conversation_url);
900 // If the thread shouldn't be completed then store the item and go away
901 // Don't do a completion on liked content
902 if (((intval(get_config('system','ostatus_poll_interval')) == -2) AND (count($item) > 0)) OR
903 ($item["verb"] == ACTIVITY_LIKE) OR ($conversation_url == "")) {
904 $item_stored = item_store($item, $all_threads);
906 } elseif (count($item) > 0) {
907 $item = store_conversation($item);
911 $parents = q("SELECT `item`.`id`, `item`.`parent`, `item`.`uri`, `item`.`contact-id`, `item`.`type`,
912 `item`.`verb`, `item`.`visible` FROM `term`
913 STRAIGHT_JOIN `item` AS `thritem` ON `thritem`.`parent` = `term`.`oid`
914 STRAIGHT_JOIN `item` ON `item`.`parent` = `thritem`.`parent`
915 WHERE `term`.`uid` = %d AND `term`.`otype` = %d AND `term`.`type` = %d AND `term`.`url` = '%s'",
916 intval($uid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION), dbesc($conversation_url));
918 /* 2016-10-23: The old query will be kept until we are sure that the query above is a good and fast replacement
920 $parents = q("SELECT `id`, `parent`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `id` IN
921 (SELECT `parent` FROM `item` WHERE `id` IN
922 (SELECT `oid` FROM `term` WHERE `uid` = %d AND `otype` = %d AND `type` = %d AND `url` = '%s'))",
923 intval($uid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION), dbesc($conversation_url));
926 $parent = $parents[0];
927 elseif (count($item) > 0) {
929 $parent["type"] = "remote";
930 $parent["verb"] = ACTIVITY_POST;
931 $parent["visible"] = 1;
934 $r = q("SELECT `id` FROM `contact` WHERE `self` AND `uid`=%d", $uid);
940 $parent["parent"] = 0;
942 $parent["contact-id"] = $r[0]["id"];
943 $parent["type"] = "remote";
944 $parent["verb"] = ACTIVITY_POST;
945 $parent["visible"] = 1;
948 $conv = str_replace("/conversation/", "/api/statusnet/conversation/", $conversation_url).".as";
952 logger('fetching conversation url '.$conv.' (Self: '.$self.') for user '.$uid);
955 $conv_arr = z_fetch_url($conv."?page=".$pageno);
957 // If it is a non-ssl site and there is an error, then try ssl or vice versa
958 if (!$conv_arr["success"] AND (substr($conv, 0, 7) == "http://")) {
959 $conv = str_replace("http://", "https://", $conv);
960 $conv_as = fetch_url($conv."?page=".$pageno);
961 } elseif (!$conv_arr["success"] AND (substr($conv, 0, 8) == "https://")) {
962 $conv = str_replace("https://", "http://", $conv);
963 $conv_as = fetch_url($conv."?page=".$pageno);
965 $conv_as = $conv_arr["body"];
967 $conv_as = str_replace(',"statusnet:notice_info":', ',"statusnet_notice_info":', $conv_as);
968 $conv_as = json_decode($conv_as);
970 $no_of_items = sizeof($items);
972 if (@is_array($conv_as->items))
973 foreach ($conv_as->items AS $single_item)
974 $items[$single_item->id] = $single_item;
976 if ($no_of_items == sizeof($items))
983 logger('fetching conversation done. Found '.count($items).' items');
985 if (!sizeof($items)) {
986 if (count($item) > 0) {
987 $item_stored = item_store($item, $all_threads);
990 logger("Conversation ".$conversation_url." couldn't be fetched. Item uri ".$item["uri"]." stored: ".$item_stored, LOGGER_DEBUG);
991 self::store_conversation($item_id, $conversation_url);
994 return($item_stored);
999 $items = array_reverse($items);
1001 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self`", intval($uid));
1006 foreach ($items as $single_conv) {
1008 // Update the gcontact table
1009 self::conv_fetch_actor($single_conv->actor);
1011 // Test - remove before flight
1012 //$tempfile = tempnam(get_temppath(), "conversation");
1013 //file_put_contents($tempfile, json_encode($single_conv));
1017 if (isset($single_conv->object->id))
1018 $single_conv->id = $single_conv->object->id;
1020 $plink = self::convert_href($single_conv->id);
1021 if (isset($single_conv->object->url))
1022 $plink = self::convert_href($single_conv->object->url);
1024 if (@!$single_conv->id)
1027 logger("Got id ".$single_conv->id, LOGGER_DEBUG);
1029 if ($first_id == "") {
1030 $first_id = $single_conv->id;
1032 // The first post of the conversation isn't our first post. There are three options:
1033 // 1. Our conversation hasn't the "real" thread starter
1034 // 2. This first post is a post inside our thread
1035 // 3. This first post is a post inside another thread
1036 if (($first_id != $parent["uri"]) AND ($parent["uri"] != "")) {
1040 $new_parents = q("SELECT `id`, `parent`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `id` IN
1041 (SELECT `parent` FROM `item`
1042 WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s')) LIMIT 1",
1043 intval($uid), dbesc($first_id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
1045 if ($new_parents[0]["parent"] == $parent["parent"]) {
1046 // Option 2: This post is already present inside our thread - but not as thread starter
1047 logger("Option 2: uri present in our thread: ".$first_id, LOGGER_DEBUG);
1048 $first_id = $parent["uri"];
1050 // Option 3: Not so good. We have mixed parents. We have to see how to clean this up.
1051 // For now just take the new parent.
1052 $parent = $new_parents[0];
1053 $first_id = $parent["uri"];
1054 logger("Option 3: mixed parents for uri ".$first_id, LOGGER_DEBUG);
1057 // Option 1: We hadn't got the real thread starter
1058 // We have to clean up our existing messages.
1060 $parent["uri"] = $first_id;
1061 logger("Option 1: we have a new parent: ".$first_id, LOGGER_DEBUG);
1063 } elseif ($parent["uri"] == "") {
1065 $parent["uri"] = $first_id;
1069 $parent_uri = $parent["uri"];
1071 // "context" only seems to exist on older servers
1072 if (isset($single_conv->context->inReplyTo->id)) {
1073 $parent_exists = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
1074 intval($uid), dbesc($single_conv->context->inReplyTo->id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
1076 $parent_uri = $single_conv->context->inReplyTo->id;
1079 // This is the current way
1080 if (isset($single_conv->object->inReplyTo->id)) {
1081 $parent_exists = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
1082 intval($uid), dbesc($single_conv->object->inReplyTo->id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
1084 $parent_uri = $single_conv->object->inReplyTo->id;
1087 $message_exists = q("SELECT `id`, `parent`, `uri` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
1088 intval($uid), dbesc($single_conv->id),
1089 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
1090 if ($message_exists) {
1091 logger("Message ".$single_conv->id." already existed on the system", LOGGER_DEBUG);
1093 if ($parent["id"] != 0) {
1094 $existing_message = $message_exists[0];
1096 // We improved the way we fetch OStatus messages, this shouldn't happen very often now
1097 /// @TODO We have to change the shadow copies as well. This way here is really ugly.
1098 if ($existing_message["parent"] != $parent["id"]) {
1099 logger('updating id '.$existing_message["id"].' with parent '.$existing_message["parent"].' to parent '.$parent["id"].' uri '.$parent["uri"].' thread '.$parent_uri, LOGGER_DEBUG);
1101 // Update the parent id of the selected item
1102 $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s' WHERE `id` = %d",
1103 intval($parent["id"]), dbesc($parent["uri"]), intval($existing_message["id"]));
1105 // Update the parent uri in the thread - but only if it points to itself
1106 $r = q("UPDATE `item` SET `thr-parent` = '%s' WHERE `id` = %d AND `uri` = `thr-parent`",
1107 dbesc($parent_uri), intval($existing_message["id"]));
1109 // try to change all items of the same parent
1110 $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s' WHERE `parent` = %d",
1111 intval($parent["id"]), dbesc($parent["uri"]), intval($existing_message["parent"]));
1113 // Update the parent uri in the thread - but only if it points to itself
1114 $r = q("UPDATE `item` SET `thr-parent` = '%s' WHERE (`parent` = %d) AND (`uri` = `thr-parent`)",
1115 dbesc($parent["uri"]), intval($existing_message["parent"]));
1117 // Now delete the thread
1118 delete_thread($existing_message["parent"]);
1122 // The item we are having on the system is the one that we wanted to store via the item array
1123 if (isset($item["uri"]) AND ($item["uri"] == $existing_message["uri"])) {
1131 if (is_array($single_conv->to))
1132 foreach($single_conv->to AS $to)
1133 if ($importer["nurl"] == normalise_link($to->id))
1136 $actor = $single_conv->actor->id;
1137 if (isset($single_conv->actor->url))
1138 $actor = $single_conv->actor->url;
1140 $details = self::get_actor_details($actor, $uid, $parent["contact-id"]);
1142 // Do we only want to import threads that were started by our contacts?
1143 if ($details["not_following"] AND $new_parent AND get_config('system','ostatus_full_threads')) {
1144 logger("Don't import uri ".$first_id." because user ".$uid." doesn't follow the person ".$actor, LOGGER_DEBUG);
1149 $arr["network"] = $details["network"];
1150 $arr["uri"] = $single_conv->id;
1151 $arr["plink"] = $plink;
1153 $arr["contact-id"] = $details["contact_id"];
1154 $arr["parent-uri"] = $parent_uri;
1155 $arr["created"] = $single_conv->published;
1156 $arr["edited"] = $single_conv->published;
1157 $arr["owner-name"] = $single_conv->actor->displayName;
1158 if ($arr["owner-name"] == '')
1159 $arr["owner-name"] = $single_conv->actor->contact->displayName;
1160 if ($arr["owner-name"] == '')
1161 $arr["owner-name"] = $single_conv->actor->portablecontacts_net->displayName;
1163 $arr["owner-link"] = $actor;
1164 $arr["owner-avatar"] = Probe::fix_avatar($single_conv->actor->image->url, $arr["owner-link"]);
1166 $arr["author-name"] = $arr["owner-name"];
1167 $arr["author-link"] = $arr["owner-link"];
1168 $arr["author-avatar"] = $arr["owner-avatar"];
1169 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->content));
1171 if (isset($single_conv->status_net->conversation)) {
1172 $arr['conversation-uri'] = $single_conv->status_net->conversation;
1175 if (isset($single_conv->status_net->notice_info->source))
1176 $arr["app"] = strip_tags($single_conv->status_net->notice_info->source);
1177 elseif (isset($single_conv->statusnet->notice_info->source))
1178 $arr["app"] = strip_tags($single_conv->statusnet->notice_info->source);
1179 elseif (isset($single_conv->statusnet_notice_info->source))
1180 $arr["app"] = strip_tags($single_conv->statusnet_notice_info->source);
1181 elseif (isset($single_conv->provider->displayName))
1182 $arr["app"] = $single_conv->provider->displayName;
1184 $arr["app"] = "OStatus";
1187 $arr["source"] = json_encode($single_conv);
1188 $arr["protocol"] = PROTOCOL_GS_CONVERSATION;
1190 $arr["verb"] = $parent["verb"];
1191 $arr["visible"] = $parent["visible"];
1192 $arr["location"] = $single_conv->location->displayName;
1193 $arr["coord"] = trim($single_conv->location->lat." ".$single_conv->location->lon);
1195 // Is it a reshared item?
1196 if (isset($single_conv->verb) AND ($single_conv->verb == "share") AND isset($single_conv->object)) {
1197 if (is_array($single_conv->object))
1198 $single_conv->object = $single_conv->object[0];
1200 logger("Found reshared item ".$single_conv->object->id);
1202 // $single_conv->object->context->conversation;
1204 if (isset($single_conv->object->object->id))
1205 $arr["uri"] = $single_conv->object->object->id;
1207 $arr["uri"] = $single_conv->object->id;
1209 if (isset($single_conv->object->object->url))
1210 $plink = self::convert_href($single_conv->object->object->url);
1212 $plink = self::convert_href($single_conv->object->url);
1214 if (isset($single_conv->object->object->content))
1215 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->object->content));
1217 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->content));
1219 $arr["plink"] = $plink;
1221 $arr["created"] = $single_conv->object->published;
1222 $arr["edited"] = $single_conv->object->published;
1224 $arr["author-name"] = $single_conv->object->actor->displayName;
1225 if ($arr["owner-name"] == '') {
1226 $arr["author-name"] = $single_conv->object->actor->contact->displayName;
1228 $arr["author-link"] = $single_conv->object->actor->url;
1229 $arr["author-avatar"] = Probe::fix_avatar($single_conv->object->actor->image->url, $arr["author-link"]);
1231 $arr["app"] = $single_conv->object->provider->displayName."#";
1232 //$arr["verb"] = $single_conv->object->verb;
1234 $arr["location"] = $single_conv->object->location->displayName;
1235 $arr["coord"] = trim($single_conv->object->location->lat." ".$single_conv->object->location->lon);
1238 if ($arr["location"] == "")
1239 unset($arr["location"]);
1241 if ($arr["coord"] == "")
1242 unset($arr["coord"]);
1244 // Copy fields from given item array
1245 if (isset($item["uri"]) AND (($item["uri"] == $arr["uri"]) OR ($item["uri"] == $single_conv->id))) {
1246 $copy_fields = array("owner-name", "owner-link", "owner-avatar", "author-name", "author-link", "author-avatar",
1247 "gravity", "body", "object-type", "object", "verb", "created", "edited", "coord", "tag",
1248 "title", "attach", "app", "type", "location", "contact-id", "uri");
1249 foreach ($copy_fields AS $field)
1250 if (isset($item[$field]))
1251 $arr[$field] = $item[$field];
1255 $newitem = item_store($arr);
1257 logger("Item wasn't stored ".print_r($arr, true), LOGGER_DEBUG);
1261 if (isset($item["uri"]) AND ($item["uri"] == $arr["uri"])) {
1263 $item_stored = $newitem;
1266 logger('Stored new item '.$plink.' for parent '.$arr["parent-uri"].' under id '.$newitem, LOGGER_DEBUG);
1268 // Add the conversation entry (but don't fetch the whole conversation)
1269 self::store_conversation($newitem, $conversation_url);
1271 // If the newly created item is the top item then change the parent settings of the thread
1272 // This shouldn't happen anymore. This is supposed to be absolote.
1273 if ($arr["uri"] == $first_id) {
1274 logger('setting new parent to id '.$newitem);
1275 $new_parents = q("SELECT `id`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `uid` = %d AND `id` = %d LIMIT 1",
1276 intval($uid), intval($newitem));
1278 $parent = $new_parents[0];
1282 if (($item_stored < 0) AND (count($item) > 0)) {
1284 if (get_config('system','ostatus_full_threads')) {
1285 $details = self::get_actor_details($item["owner-link"], $uid, $item["contact-id"]);
1286 if ($details["not_following"]) {
1287 logger("Don't import uri ".$item["uri"]." because user ".$uid." doesn't follow the person ".$item["owner-link"], LOGGER_DEBUG);
1292 $item_stored = item_store($item, $all_threads);
1294 logger("Uri ".$item["uri"]." wasn't found in conversation ".$conversation_url, LOGGER_DEBUG);
1295 self::store_conversation($item_stored, $conversation_url);
1299 return($item_stored);
1303 * @brief Stores conversation data into the database
1305 * @param integer $itemid The id of the item
1306 * @param string $conversation_url The uri of the conversation
1308 private function store_conversation($itemid, $conversation_url) {
1310 $conversation_url = self::convert_href($conversation_url);
1312 $messages = q("SELECT `uid`, `parent`, `created`, `received`, `guid` FROM `item` WHERE `id` = %d LIMIT 1", intval($itemid));
1315 $message = $messages[0];
1317 // Store conversation url if not done before
1318 $conversation = q("SELECT `url` FROM `term` WHERE `uid` = %d AND `oid` = %d AND `otype` = %d AND `type` = %d",
1319 intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION));
1321 if (!$conversation) {
1322 $r = q("INSERT INTO `term` (`uid`, `oid`, `otype`, `type`, `term`, `url`, `created`, `received`, `guid`) VALUES (%d, %d, %d, %d, '%s', '%s', '%s', '%s', '%s')",
1323 intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION),
1324 dbesc($message["created"]), dbesc($conversation_url), dbesc($message["created"]), dbesc($message["received"]), dbesc($message["guid"]));
1325 logger('Storing conversation url '.$conversation_url.' for id '.$itemid);
1330 * @brief Checks if the current post is a reshare
1332 * @param array $item The item array of thw post
1334 * @return string The guid if the post is a reshare
1336 private function get_reshared_guid($item) {
1337 $body = trim($item["body"]);
1339 // Skip if it isn't a pure repeated messages
1340 // Does it start with a share?
1341 if (strpos($body, "[share") > 0)
1344 // Does it end with a share?
1345 if (strlen($body) > (strrpos($body, "[/share]") + 8))
1348 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
1349 // Skip if there is no shared message in there
1350 if ($body == $attributes)
1354 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
1355 if ($matches[1] != "")
1356 $guid = $matches[1];
1358 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
1359 if ($matches[1] != "")
1360 $guid = $matches[1];
1366 * @brief Cleans the body of a post if it contains picture links
1368 * @param string $body The body
1370 * @return string The cleaned body
1372 private function format_picture_post($body) {
1373 $siteinfo = get_attached_data($body);
1375 if (($siteinfo["type"] == "photo")) {
1376 if (isset($siteinfo["preview"]))
1377 $preview = $siteinfo["preview"];
1379 $preview = $siteinfo["image"];
1381 // Is it a remote picture? Then make a smaller preview here
1382 $preview = proxy_url($preview, false, PROXY_SIZE_SMALL);
1384 // Is it a local picture? Then make it smaller here
1385 $preview = str_replace(array("-0.jpg", "-0.png"), array("-2.jpg", "-2.png"), $preview);
1386 $preview = str_replace(array("-1.jpg", "-1.png"), array("-2.jpg", "-2.png"), $preview);
1388 if (isset($siteinfo["url"]))
1389 $url = $siteinfo["url"];
1391 $url = $siteinfo["image"];
1393 $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1400 * @brief Adds the header elements to the XML document
1402 * @param object $doc XML document
1403 * @param array $owner Contact data of the poster
1405 * @return object header root element
1407 private function add_header($doc, $owner) {
1411 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
1412 $doc->appendChild($root);
1414 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1415 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1416 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1417 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1418 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
1419 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1420 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1421 $root->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1423 $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
1424 xml::add_element($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1425 xml::add_element($doc, $root, "id", App::get_baseurl()."/profile/".$owner["nick"]);
1426 xml::add_element($doc, $root, "title", sprintf("%s timeline", $owner["name"]));
1427 xml::add_element($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], $a->config["sitename"]));
1428 xml::add_element($doc, $root, "logo", $owner["photo"]);
1429 xml::add_element($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
1431 $author = self::add_author($doc, $owner);
1432 $root->appendChild($author);
1434 $attributes = array("href" => $owner["url"], "rel" => "alternate", "type" => "text/html");
1435 xml::add_element($doc, $root, "link", "", $attributes);
1437 /// @TODO We have to find out what this is
1438 /// $attributes = array("href" => App::get_baseurl()."/sup",
1439 /// "rel" => "http://api.friendfeed.com/2008/03#sup",
1440 /// "type" => "application/json");
1441 /// xml::add_element($doc, $root, "link", "", $attributes);
1443 self::hublinks($doc, $root);
1445 $attributes = array("href" => App::get_baseurl()."/salmon/".$owner["nick"], "rel" => "salmon");
1446 xml::add_element($doc, $root, "link", "", $attributes);
1448 $attributes = array("href" => App::get_baseurl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies");
1449 xml::add_element($doc, $root, "link", "", $attributes);
1451 $attributes = array("href" => App::get_baseurl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention");
1452 xml::add_element($doc, $root, "link", "", $attributes);
1454 $attributes = array("href" => App::get_baseurl()."/api/statuses/user_timeline/".$owner["nick"].".atom",
1455 "rel" => "self", "type" => "application/atom+xml");
1456 xml::add_element($doc, $root, "link", "", $attributes);
1462 * @brief Add the link to the push hubs to the XML document
1464 * @param object $doc XML document
1465 * @param object $root XML root element where the hub links are added
1467 public static function hublinks($doc, $root) {
1468 $hub = get_config('system','huburl');
1472 $hubs = explode(',', $hub);
1474 foreach($hubs as $h) {
1478 if ($h === '[internal]')
1479 $h = App::get_baseurl() . '/pubsubhubbub';
1480 xml::add_element($doc, $root, "link", "", array("href" => $h, "rel" => "hub"));
1487 * @brief Adds attachement data to the XML document
1489 * @param object $doc XML document
1490 * @param object $root XML root element where the hub links are added
1491 * @param array $item Data of the item that is to be posted
1493 private function get_attachment($doc, $root, $item) {
1495 $siteinfo = get_attached_data($item["body"]);
1497 switch ($siteinfo["type"]) {
1499 $imgdata = get_photo_info($siteinfo["image"]);
1500 $attributes = array("rel" => "enclosure",
1501 "href" => $siteinfo["image"],
1502 "type" => $imgdata["mime"],
1503 "length" => intval($imgdata["size"]));
1504 xml::add_element($doc, $root, "link", "", $attributes);
1507 $attributes = array("rel" => "enclosure",
1508 "href" => $siteinfo["url"],
1509 "type" => "text/html; charset=UTF-8",
1511 "title" => $siteinfo["title"]);
1512 xml::add_element($doc, $root, "link", "", $attributes);
1518 if (($siteinfo["type"] != "photo") AND isset($siteinfo["image"])) {
1519 $imgdata = get_photo_info($siteinfo["image"]);
1520 $attributes = array("rel" => "enclosure",
1521 "href" => $siteinfo["image"],
1522 "type" => $imgdata["mime"],
1523 "length" => intval($imgdata["size"]));
1525 xml::add_element($doc, $root, "link", "", $attributes);
1528 $arr = explode('[/attach],', $item['attach']);
1530 foreach ($arr as $r) {
1532 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1534 $attributes = array("rel" => "enclosure",
1535 "href" => $matches[1],
1536 "type" => $matches[3]);
1538 if (intval($matches[2])) {
1539 $attributes["length"] = intval($matches[2]);
1541 if (trim($matches[4]) != "") {
1542 $attributes["title"] = trim($matches[4]);
1544 xml::add_element($doc, $root, "link", "", $attributes);
1551 * @brief Adds the author element to the XML document
1553 * @param object $doc XML document
1554 * @param array $owner Contact data of the poster
1556 * @return object author element
1558 private function add_author($doc, $owner) {
1560 $r = q("SELECT `homepage`, `publish` FROM `profile` WHERE `uid` = %d AND `is-default` LIMIT 1", intval($owner["uid"]));
1564 $author = $doc->createElement("author");
1565 xml::add_element($doc, $author, "id", $owner["url"]);
1566 xml::add_element($doc, $author, "activity:object-type", ACTIVITY_OBJ_PERSON);
1567 xml::add_element($doc, $author, "uri", $owner["url"]);
1568 xml::add_element($doc, $author, "name", $owner["nick"]);
1569 xml::add_element($doc, $author, "email", $owner["addr"]);
1570 xml::add_element($doc, $author, "summary", bbcode($owner["about"], false, false, 7));
1572 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $owner["url"]);
1573 xml::add_element($doc, $author, "link", "", $attributes);
1575 $attributes = array(
1577 "type" => "image/jpeg", // To-Do?
1578 "media:width" => 175,
1579 "media:height" => 175,
1580 "href" => $owner["photo"]);
1581 xml::add_element($doc, $author, "link", "", $attributes);
1583 if (isset($owner["thumb"])) {
1584 $attributes = array(
1586 "type" => "image/jpeg", // To-Do?
1587 "media:width" => 80,
1588 "media:height" => 80,
1589 "href" => $owner["thumb"]);
1590 xml::add_element($doc, $author, "link", "", $attributes);
1593 xml::add_element($doc, $author, "poco:preferredUsername", $owner["nick"]);
1594 xml::add_element($doc, $author, "poco:displayName", $owner["name"]);
1595 xml::add_element($doc, $author, "poco:note", bbcode($owner["about"], false, false, 7));
1597 if (trim($owner["location"]) != "") {
1598 $element = $doc->createElement("poco:address");
1599 xml::add_element($doc, $element, "poco:formatted", $owner["location"]);
1600 $author->appendChild($element);
1603 if (trim($profile["homepage"]) != "") {
1604 $urls = $doc->createElement("poco:urls");
1605 xml::add_element($doc, $urls, "poco:type", "homepage");
1606 xml::add_element($doc, $urls, "poco:value", $profile["homepage"]);
1607 xml::add_element($doc, $urls, "poco:primary", "true");
1608 $author->appendChild($urls);
1611 if (count($profile)) {
1612 xml::add_element($doc, $author, "followers", "", array("url" => App::get_baseurl()."/viewcontacts/".$owner["nick"]));
1613 xml::add_element($doc, $author, "statusnet:profile_info", "", array("local_id" => $owner["uid"]));
1616 if ($profile["publish"]) {
1617 xml::add_element($doc, $author, "mastodon:scope", "public");
1623 * @TODO Picture attachments should look like this:
1624 * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1625 * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1630 * @brief Returns the given activity if present - otherwise returns the "post" activity
1632 * @param array $item Data of the item that is to be posted
1634 * @return string activity
1636 function construct_verb($item) {
1638 return $item['verb'];
1639 return ACTIVITY_POST;
1643 * @brief Returns the given object type if present - otherwise returns the "note" object type
1645 * @param array $item Data of the item that is to be posted
1647 * @return string Object type
1649 function construct_objecttype($item) {
1650 if (in_array($item['object-type'], array(ACTIVITY_OBJ_NOTE, ACTIVITY_OBJ_COMMENT)))
1651 return $item['object-type'];
1652 return ACTIVITY_OBJ_NOTE;
1656 * @brief Adds an entry element to the XML document
1658 * @param object $doc XML document
1659 * @param array $item Data of the item that is to be posted
1660 * @param array $owner Contact data of the poster
1661 * @param bool $toplevel
1663 * @return object Entry element
1665 private function entry($doc, $item, $owner, $toplevel = false) {
1666 $repeated_guid = self::get_reshared_guid($item);
1667 if ($repeated_guid != "")
1668 $xml = self::reshare_entry($doc, $item, $owner, $repeated_guid, $toplevel);
1673 if ($item["verb"] == ACTIVITY_LIKE) {
1674 return self::like_entry($doc, $item, $owner, $toplevel);
1675 } elseif (in_array($item["verb"], array(ACTIVITY_FOLLOW, NAMESPACE_OSTATUS."/unfollow"))) {
1676 return self::follow_entry($doc, $item, $owner, $toplevel);
1678 return self::note_entry($doc, $item, $owner, $toplevel);
1683 * @brief Adds a source entry to the XML document
1685 * @param object $doc XML document
1686 * @param array $contact Array of the contact that is added
1688 * @return object Source element
1690 private function source_entry($doc, $contact) {
1691 $source = $doc->createElement("source");
1692 xml::add_element($doc, $source, "id", $contact["poll"]);
1693 xml::add_element($doc, $source, "title", $contact["name"]);
1694 xml::add_element($doc, $source, "link", "", array("rel" => "alternate",
1695 "type" => "text/html",
1696 "href" => $contact["alias"]));
1697 xml::add_element($doc, $source, "link", "", array("rel" => "self",
1698 "type" => "application/atom+xml",
1699 "href" => $contact["poll"]));
1700 xml::add_element($doc, $source, "icon", $contact["photo"]);
1701 xml::add_element($doc, $source, "updated", datetime_convert("UTC","UTC",$contact["success_update"]."+00:00",ATOM_TIME));
1707 * @brief Fetches contact data from the contact or the gcontact table
1709 * @param string $url URL of the contact
1710 * @param array $owner Contact data of the poster
1712 * @return array Contact array
1714 private function contact_entry($url, $owner) {
1716 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
1717 dbesc(normalise_link($url)), intval($owner["uid"]));
1720 $contact["uid"] = -1;
1724 $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1725 dbesc(normalise_link($url)));
1728 $contact["uid"] = -1;
1729 $contact["success_update"] = $contact["updated"];
1736 if (!isset($contact["poll"])) {
1737 $data = probe_url($url);
1738 $contact["poll"] = $data["poll"];
1740 if (!$contact["alias"])
1741 $contact["alias"] = $data["alias"];
1744 if (!isset($contact["alias"]))
1745 $contact["alias"] = $contact["url"];
1751 * @brief Adds an entry element with reshared content
1753 * @param object $doc XML document
1754 * @param array $item Data of the item that is to be posted
1755 * @param array $owner Contact data of the poster
1756 * @param $repeated_guid
1757 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1759 * @return object Entry element
1761 private function reshare_entry($doc, $item, $owner, $repeated_guid, $toplevel) {
1763 if (($item["id"] != $item["parent"]) AND (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1764 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1767 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1769 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' AND NOT `private` AND `network` IN ('%s', '%s', '%s') LIMIT 1",
1770 intval($owner["uid"]), dbesc($repeated_guid),
1771 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS));
1773 $repeated_item = $r[0];
1777 $contact = self::contact_entry($repeated_item['author-link'], $owner);
1779 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1781 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1783 self::entry_content($doc, $entry, $item, $owner, $title, ACTIVITY_SHARE, false);
1785 $as_object = $doc->createElement("activity:object");
1787 xml::add_element($doc, $as_object, "activity:object-type", NAMESPACE_ACTIVITY_SCHEMA."activity");
1789 self::entry_content($doc, $as_object, $repeated_item, $owner, "", "", false);
1791 $author = self::add_author($doc, $contact);
1792 $as_object->appendChild($author);
1794 $as_object2 = $doc->createElement("activity:object");
1796 xml::add_element($doc, $as_object2, "activity:object-type", self::construct_objecttype($repeated_item));
1798 $title = sprintf("New comment by %s", $contact["nick"]);
1800 self::entry_content($doc, $as_object2, $repeated_item, $owner, $title);
1802 $as_object->appendChild($as_object2);
1804 self::entry_footer($doc, $as_object, $item, $owner, false);
1806 $source = self::source_entry($doc, $contact);
1808 $as_object->appendChild($source);
1810 $entry->appendChild($as_object);
1812 self::entry_footer($doc, $entry, $item, $owner);
1818 * @brief Adds an entry element with a "like"
1820 * @param object $doc XML document
1821 * @param array $item Data of the item that is to be posted
1822 * @param array $owner Contact data of the poster
1823 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1825 * @return object Entry element with "like"
1827 private function like_entry($doc, $item, $owner, $toplevel) {
1829 if (($item["id"] != $item["parent"]) AND (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1830 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1833 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1835 $verb = NAMESPACE_ACTIVITY_SCHEMA."favorite";
1836 self::entry_content($doc, $entry, $item, $owner, "Favorite", $verb, false);
1838 $as_object = $doc->createElement("activity:object");
1840 $parent = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d",
1841 dbesc($item["thr-parent"]), intval($item["uid"]));
1842 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1844 xml::add_element($doc, $as_object, "activity:object-type", self::construct_objecttype($parent[0]));
1846 self::entry_content($doc, $as_object, $parent[0], $owner, "New entry");
1848 $entry->appendChild($as_object);
1850 self::entry_footer($doc, $entry, $item, $owner);
1856 * @brief Adds the person object element to the XML document
1858 * @param object $doc XML document
1859 * @param array $owner Contact data of the poster
1860 * @param array $contact Contact data of the target
1862 * @return object author element
1864 private function add_person_object($doc, $owner, $contact) {
1866 $object = $doc->createElement("activity:object");
1867 xml::add_element($doc, $object, "activity:object-type", ACTIVITY_OBJ_PERSON);
1869 if ($contact['network'] == NETWORK_PHANTOM) {
1870 xml::add_element($doc, $object, "id", $contact['url']);
1874 xml::add_element($doc, $object, "id", $contact["alias"]);
1875 xml::add_element($doc, $object, "title", $contact["nick"]);
1877 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $contact["url"]);
1878 xml::add_element($doc, $object, "link", "", $attributes);
1880 $attributes = array(
1882 "type" => "image/jpeg", // To-Do?
1883 "media:width" => 175,
1884 "media:height" => 175,
1885 "href" => $contact["photo"]);
1886 xml::add_element($doc, $object, "link", "", $attributes);
1888 xml::add_element($doc, $object, "poco:preferredUsername", $contact["nick"]);
1889 xml::add_element($doc, $object, "poco:displayName", $contact["name"]);
1891 if (trim($contact["location"]) != "") {
1892 $element = $doc->createElement("poco:address");
1893 xml::add_element($doc, $element, "poco:formatted", $contact["location"]);
1894 $object->appendChild($element);
1901 * @brief Adds a follow/unfollow entry element
1903 * @param object $doc XML document
1904 * @param array $item Data of the follow/unfollow message
1905 * @param array $owner Contact data of the poster
1906 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1908 * @return object Entry element
1910 private function follow_entry($doc, $item, $owner, $toplevel) {
1912 $item["id"] = $item["parent"] = 0;
1913 $item["created"] = $item["edited"] = date("c");
1914 $item["private"] = true;
1916 $contact = Probe::uri($item['follow']);
1918 if ($contact['alias'] == '') {
1919 $contact['alias'] = $contact["url"];
1921 $item['follow'] = $contact['alias'];
1924 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1925 intval($owner['uid']), dbesc(normalise_link($contact["url"])));
1927 if (dbm::is_result($r)) {
1928 $connect_id = $r[0]['id'];
1933 if ($item['verb'] == ACTIVITY_FOLLOW) {
1934 $message = t('%s is now following %s.');
1935 $title = t('following');
1936 $action = "subscription";
1938 $message = t('%s stopped following %s.');
1939 $title = t('stopped following');
1940 $action = "unfollow";
1943 $item["uri"] = $item['parent-uri'] = $item['thr-parent'] =
1944 'tag:'.get_app()->get_hostname().
1945 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1946 ':person:'.$connect_id.':'.$item['created'];
1948 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1950 self::entry_header($doc, $entry, $owner, $toplevel);
1952 self::entry_content($doc, $entry, $item, $owner, $title);
1954 $object = self::add_person_object($doc, $owner, $contact);
1955 $entry->appendChild($object);
1957 self::entry_footer($doc, $entry, $item, $owner);
1963 * @brief Adds a regular entry element
1965 * @param object $doc XML document
1966 * @param array $item Data of the item that is to be posted
1967 * @param array $owner Contact data of the poster
1968 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1970 * @return object Entry element
1972 private function note_entry($doc, $item, $owner, $toplevel) {
1974 if (($item["id"] != $item["parent"]) AND (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1975 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1978 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1980 xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1982 self::entry_content($doc, $entry, $item, $owner, $title);
1984 self::entry_footer($doc, $entry, $item, $owner);
1990 * @brief Adds a header element to the XML document
1992 * @param object $doc XML document
1993 * @param object $entry The entry element where the elements are added
1994 * @param array $owner Contact data of the poster
1995 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1997 * @return string The title for the element
1999 private function entry_header($doc, &$entry, $owner, $toplevel) {
2000 /// @todo Check if this title stuff is really needed (I guess not)
2002 $entry = $doc->createElement("entry");
2003 $title = sprintf("New note by %s", $owner["nick"]);
2005 $entry = $doc->createElementNS(NAMESPACE_ATOM1, "entry");
2007 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
2008 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
2009 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
2010 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
2011 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
2012 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
2013 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
2014 $entry->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
2016 $author = self::add_author($doc, $owner);
2017 $entry->appendChild($author);
2019 $title = sprintf("New comment by %s", $owner["nick"]);
2025 * @brief Adds elements to the XML document
2027 * @param object $doc XML document
2028 * @param object $entry Entry element where the content is added
2029 * @param array $item Data of the item that is to be posted
2030 * @param array $owner Contact data of the poster
2031 * @param string $title Title for the post
2032 * @param string $verb The activity verb
2033 * @param bool $complete Add the "status_net" element?
2035 private function entry_content($doc, $entry, $item, $owner, $title, $verb = "", $complete = true) {
2038 $verb = self::construct_verb($item);
2040 xml::add_element($doc, $entry, "id", $item["uri"]);
2041 xml::add_element($doc, $entry, "title", $title);
2043 $body = self::format_picture_post($item['body']);
2045 if ($item['title'] != "")
2046 $body = "[b]".$item['title']."[/b]\n\n".$body;
2048 $body = bbcode($body, false, false, 7);
2050 xml::add_element($doc, $entry, "content", $body, array("type" => "html"));
2052 xml::add_element($doc, $entry, "link", "", array("rel" => "alternate", "type" => "text/html",
2053 "href" => App::get_baseurl()."/display/".$item["guid"]));
2055 if ($complete AND ($item["id"] > 0))
2056 xml::add_element($doc, $entry, "status_net", "", array("notice_id" => $item["id"]));
2058 xml::add_element($doc, $entry, "activity:verb", $verb);
2060 xml::add_element($doc, $entry, "published", datetime_convert("UTC","UTC",$item["created"]."+00:00",ATOM_TIME));
2061 xml::add_element($doc, $entry, "updated", datetime_convert("UTC","UTC",$item["edited"]."+00:00",ATOM_TIME));
2065 * @brief Adds the elements at the foot of an entry to the XML document
2067 * @param object $doc XML document
2068 * @param object $entry The entry element where the elements are added
2069 * @param array $item Data of the item that is to be posted
2070 * @param array $owner Contact data of the poster
2073 private function entry_footer($doc, $entry, $item, $owner, $complete = true) {
2075 $mentioned = array();
2077 if (($item['parent'] != $item['id']) OR ($item['parent-uri'] !== $item['uri']) OR (($item['thr-parent'] !== '') AND ($item['thr-parent'] !== $item['uri']))) {
2078 $parent = q("SELECT `guid`, `author-link`, `owner-link` FROM `item` WHERE `id` = %d", intval($item["parent"]));
2079 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
2081 $thrparent = q("SELECT `guid`, `author-link`, `owner-link`, `plink` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
2082 intval($owner["uid"]),
2083 dbesc($parent_item));
2085 $mentioned[$thrparent[0]["author-link"]] = $thrparent[0]["author-link"];
2086 $mentioned[$thrparent[0]["owner-link"]] = $thrparent[0]["owner-link"];
2087 $parent_plink = $thrparent[0]["plink"];
2089 $mentioned[$parent[0]["author-link"]] = $parent[0]["author-link"];
2090 $mentioned[$parent[0]["owner-link"]] = $parent[0]["owner-link"];
2091 $parent_plink = App::get_baseurl()."/display/".$parent[0]["guid"];
2094 $attributes = array(
2095 "ref" => $parent_item,
2096 "href" => $parent_plink);
2097 xml::add_element($doc, $entry, "thr:in-reply-to", "", $attributes);
2099 $attributes = array(
2101 "href" => $parent_plink);
2102 xml::add_element($doc, $entry, "link", "", $attributes);
2105 if (intval($item["parent"]) > 0) {
2106 $conversation_href = App::get_baseurl()."/display/".$owner["nick"]."/".$item["parent"];
2107 $conversation_uri = $conversation_href;
2109 if (isset($parent_item)) {
2110 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $parent_item);
2111 if (dbm::is_result($r)) {
2112 if ($r['conversation-uri'] != '') {
2113 $conversation_uri = $r['conversation-uri'];
2115 if ($r['conversation-href'] != '') {
2116 $conversation_href = $r['conversation-href'];
2121 xml::add_element($doc, $entry, "link", "", array("rel" => "ostatus:conversation", "href" => $conversation_href));
2123 $attributes = array(
2124 "href" => $conversation_href,
2125 "local_id" => $item["parent"],
2126 "ref" => $conversation_uri);
2128 xml::add_element($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
2131 $tags = item_getfeedtags($item);
2134 foreach($tags as $t)
2136 $mentioned[$t[1]] = $t[1];
2138 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
2139 $newmentions = array();
2140 foreach ($mentioned AS $mention) {
2141 $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
2142 $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
2144 $mentioned = $newmentions;
2146 foreach ($mentioned AS $mention) {
2147 $r = q("SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
2148 intval($owner["uid"]),
2149 dbesc(normalise_link($mention)));
2150 if ($r[0]["forum"] OR $r[0]["prv"])
2151 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
2152 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
2153 "href" => $mention));
2155 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
2156 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
2157 "href" => $mention));
2160 if (!$item["private"]) {
2161 xml::add_element($doc, $entry, "link", "", array("rel" => "ostatus:attention",
2162 "href" => "http://activityschema.org/collection/public"));
2163 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
2164 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
2165 "href" => "http://activityschema.org/collection/public"));
2166 xml::add_element($doc, $entry, "mastodon:scope", "public");
2170 foreach($tags as $t)
2172 xml::add_element($doc, $entry, "category", "", array("term" => $t[2]));
2174 self::get_attachment($doc, $entry, $item);
2176 if ($complete AND ($item["id"] > 0)) {
2177 $app = $item["app"];
2181 $attributes = array("local_id" => $item["id"], "source" => $app);
2183 if (isset($parent["id"]))
2184 $attributes["repeat_of"] = $parent["id"];
2186 if ($item["coord"] != "")
2187 xml::add_element($doc, $entry, "georss:point", $item["coord"]);
2189 xml::add_element($doc, $entry, "statusnet:notice_info", "", $attributes);
2194 * @brief Creates the XML feed for a given nickname
2196 * @param App $a The application class
2197 * @param string $owner_nick Nickname of the feed owner
2198 * @param string $last_update Date of the last update
2200 * @return string XML feed
2202 public static function feed(App $a, $owner_nick, $last_update) {
2204 $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`
2205 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
2206 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
2207 dbesc($owner_nick));
2213 if(!strlen($last_update))
2214 $last_update = 'now -30 days';
2216 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
2217 $authorid = get_contact($owner["url"], 0);
2219 $items = q("SELECT `item`.*, `item`.`id` AS `item_id` FROM `item` USE INDEX (`uid_contactid_created`)
2220 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `item`.`parent`
2221 WHERE `item`.`uid` = %d AND `item`.`contact-id` = %d AND
2222 `item`.`author-id` = %d AND `item`.`created` > '%s' AND
2223 NOT `item`.`deleted` AND NOT `item`.`private` AND
2224 `thread`.`network` IN ('%s', '%s')
2225 ORDER BY `item`.`created` DESC LIMIT 300",
2226 intval($owner["uid"]), intval($owner["id"]),
2227 intval($authorid), dbesc($check_date),
2228 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
2230 /* 2016-10-23: The old query will be kept until we are sure that the query above is a good and fast replacement
2232 $items = q("SELECT `item`.*, `item`.`id` AS `item_id` FROM `item`
2233 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `item`.`parent`
2234 LEFT JOIN `item` AS `thritem` ON `thritem`.`uri`=`item`.`thr-parent` AND `thritem`.`uid`=`item`.`uid`
2235 WHERE `item`.`uid` = %d AND `item`.`received` > '%s' AND NOT `item`.`private` AND NOT `item`.`deleted`
2236 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
2237 AND ((`item`.`wall` AND (`item`.`parent` = `item`.`id`))
2238 OR (`item`.`network` = '%s' AND ((`thread`.`network` IN ('%s', '%s')) OR (`thritem`.`network` IN ('%s', '%s')))) AND `thread`.`mention`)
2239 AND ((`item`.`owner-link` IN ('%s', '%s') AND (`item`.`parent` = `item`.`id`))
2240 OR (`item`.`author-link` IN ('%s', '%s')))
2241 ORDER BY `item`.`id` DESC
2243 intval($owner["uid"]), dbesc($check_date), dbesc(NETWORK_DFRN),
2244 //dbesc(NETWORK_OSTATUS), dbesc(NETWORK_OSTATUS),
2245 //dbesc(NETWORK_OSTATUS), dbesc(NETWORK_OSTATUS),
2246 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN),
2247 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN),
2248 dbesc($owner["nurl"]), dbesc(str_replace("http://", "https://", $owner["nurl"])),
2249 dbesc($owner["nurl"]), dbesc(str_replace("http://", "https://", $owner["nurl"]))
2252 $doc = new DOMDocument('1.0', 'utf-8');
2253 $doc->formatOutput = true;
2255 $root = self::add_header($doc, $owner);
2257 foreach ($items AS $item) {
2258 if (Config::get('system', 'ostatus_debug')) {
2259 $item['body'] .= '🍼';
2261 $entry = self::entry($doc, $item, $owner);
2262 $root->appendChild($entry);
2265 return(trim($doc->saveXML()));
2269 * @brief Creates the XML for a salmon message
2271 * @param array $item Data of the item that is to be posted
2272 * @param array $owner Contact data of the poster
2274 * @return string XML for the salmon
2276 public static function salmon($item,$owner) {
2278 $doc = new DOMDocument('1.0', 'utf-8');
2279 $doc->formatOutput = true;
2281 if (Config::get('system', 'ostatus_debug')) {
2282 $item['body'] .= '🐟';
2285 $entry = self::entry($doc, $item, $owner, true);
2287 $doc->appendChild($entry);
2289 return(trim($doc->saveXML()));