3 * @file include/ostatus.php
6 use \Friendica\Core\Config;
8 require_once("include/Contact.php");
9 require_once("include/threads.php");
10 require_once("include/html2bbcode.php");
11 require_once("include/bbcode.php");
12 require_once("include/items.php");
13 require_once("mod/share.php");
14 require_once("include/enotify.php");
15 require_once("include/socgraph.php");
16 require_once("include/Photo.php");
17 require_once("include/Scrape.php");
18 require_once("include/follow.php");
19 require_once("include/api.php");
20 require_once("mod/proxy.php");
21 require_once("include/xml.php");
24 * @brief This class contain functions for the OStatus protocol
28 const OSTATUS_DEFAULT_POLL_INTERVAL = 30; // given in minutes
29 const OSTATUS_DEFAULT_POLL_TIMEFRAME = 1440; // given in minutes
30 const OSTATUS_DEFAULT_POLL_TIMEFRAME_MENTIONS = 14400; // given in minutes
33 * @brief Fetches author data
35 * @param object $xpath The xpath object
36 * @param object $context The xml context of the author detals
37 * @param array $importer user record of the importing user
38 * @param array $contact Called by reference, will contain the fetched contact
39 * @param bool $onlyfetch Only fetch the header without updating the contact entries
41 * @return array Array of author related entries for the item
43 private function fetchauthor($xpath, $context, $importer, &$contact, $onlyfetch) {
46 $author["author-link"] = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
47 $author["author-name"] = $xpath->evaluate('atom:author/atom:name/text()', $context)->item(0)->nodeValue;
48 $addr = $xpath->evaluate('atom:author/atom:email/text()', $context)->item(0)->nodeValue;
50 $aliaslink = $author["author-link"];
52 $alternate = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0)->attributes;
53 if (is_object($alternate)) {
54 foreach ($alternate AS $attributes) {
55 if (($attributes->name == "href") AND ($attributes->textContent != "")) {
56 $author["author-link"] = $attributes->textContent;
61 $author["contact-id"] = $contact["id"];
63 if ($author["author-link"] != "") {
64 if ($aliaslink == "") {
65 $aliaslink = $author["author-link"];
68 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` IN ('%s', '%s') AND `network` != '%s'",
69 intval($importer["uid"]), dbesc(normalise_link($author["author-link"])),
70 dbesc(normalise_link($aliaslink)), dbesc(NETWORK_STATUSNET));
71 if (dbm::is_result($r)) {
73 $author["contact-id"] = $r[0]["id"];
74 $author["author-link"] = $r[0]["url"];
76 } elseif ($addr != "") {
78 $contact = dba::fetch_first("SELECT * FROM `contact` WHERE `uid` = ? AND `addr` = ? AND `network` != ?",
79 $importer["uid"], $addr, NETWORK_STATUSNET);
80 if (dbm::is_result($contact)) {
81 $author["contact-id"] = $contact["id"];
82 $author["author-link"] = $contact["url"];
86 $avatarlist = array();
87 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
88 foreach($avatars AS $avatar) {
91 foreach($avatar->attributes AS $attributes) {
92 if ($attributes->name == "href")
93 $href = $attributes->textContent;
94 if ($attributes->name == "width")
95 $width = $attributes->textContent;
97 if (($width > 0) AND ($href != ""))
98 $avatarlist[$width] = $href;
100 if (count($avatarlist) > 0) {
102 $author["author-avatar"] = Probe::fix_avatar(current($avatarlist), $author["author-link"]);
105 $displayname = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
106 if ($displayname != "")
107 $author["author-name"] = $displayname;
109 $author["owner-name"] = $author["author-name"];
110 $author["owner-link"] = $author["author-link"];
111 $author["owner-avatar"] = $author["author-avatar"];
113 // Only update the contacts if it is an OStatus contact
114 if ($r AND !$onlyfetch AND ($contact["network"] == NETWORK_OSTATUS)) {
116 // Update contact data
118 // This query doesn't seem to work
119 // $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
121 // $contact["notify"] = $value;
123 // This query doesn't seem to work as well - I hate these queries
124 // $value = $xpath->query("atom:link[@rel='self' and @type='application/atom+xml']", $context)->item(0)->nodeValue;
126 // $contact["poll"] = $value;
128 $value = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
130 $contact["alias"] = $value;
132 $value = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
134 $contact["name"] = $value;
136 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
138 $contact["nick"] = $value;
140 $value = $xpath->evaluate('atom:author/poco:note/text()', $context)->item(0)->nodeValue;
142 $contact["about"] = html2bbcode($value);
144 $value = $xpath->evaluate('atom:author/poco:address/poco:formatted/text()', $context)->item(0)->nodeValue;
146 $contact["location"] = $value;
148 if (($contact["name"] != $r[0]["name"]) OR ($contact["nick"] != $r[0]["nick"]) OR ($contact["about"] != $r[0]["about"]) OR
149 ($contact["alias"] != $r[0]["alias"]) OR ($contact["location"] != $r[0]["location"])) {
151 logger("Update contact data for contact ".$contact["id"], LOGGER_DEBUG);
153 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `alias` = '%s', `about` = '%s', `location` = '%s', `name-date` = '%s' WHERE `id` = %d",
154 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["alias"]),
155 dbesc($contact["about"]), dbesc($contact["location"]),
156 dbesc(datetime_convert()), intval($contact["id"]));
159 if (isset($author["author-avatar"]) AND ($author["author-avatar"] != $r[0]['avatar'])) {
160 logger("Update profile picture for contact ".$contact["id"], LOGGER_DEBUG);
162 update_contact_avatar($author["author-avatar"], $importer["uid"], $contact["id"]);
165 // Ensure that we are having this contact (with uid=0)
166 $cid = get_contact($author["author-link"], 0);
169 // Update it with the current values
170 q("UPDATE `contact` SET `url` = '%s', `name` = '%s', `nick` = '%s', `alias` = '%s',
171 `about` = '%s', `location` = '%s',
172 `success_update` = '%s', `last-update` = '%s'
174 dbesc($author["author-link"]), dbesc($contact["name"]), dbesc($contact["nick"]),
175 dbesc($contact["alias"]), dbesc($contact["about"]), dbesc($contact["location"]),
176 dbesc(datetime_convert()), dbesc(datetime_convert()), intval($cid));
179 update_contact_avatar($author["author-avatar"], 0, $cid);
182 $contact["generation"] = 2;
183 $contact["hide"] = false; // OStatus contacts are never hidden
184 $contact["photo"] = $author["author-avatar"];
185 $gcid = update_gcontact($contact);
187 link_gcontact($gcid, $contact["uid"], $contact["id"]);
194 * @brief Fetches author data from a given XML string
196 * @param string $xml The XML
197 * @param array $importer user record of the importing user
199 * @return array Array of author related entries for the item
201 public static function salmon_author($xml, $importer) {
206 $doc = new DOMDocument();
207 @$doc->loadXML($xml);
209 $xpath = new DomXPath($doc);
210 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
211 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
212 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
213 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
214 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
215 $xpath->registerNamespace('poco', NAMESPACE_POCO);
216 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
217 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
219 $entries = $xpath->query('/atom:entry');
221 foreach ($entries AS $entry) {
223 $author = self::fetchauthor($xpath, $entry, $importer, $contact, true);
229 * @brief Read attributes from element
231 * @param object $element Element object
233 * @return array attributes
235 private static function read_attributes($element) {
236 $attribute = array();
238 foreach ($element->attributes AS $attributes) {
239 $attribute[$attributes->name] = $attributes->textContent;
246 * @brief Imports an XML string containing OStatus elements
248 * @param string $xml The XML
249 * @param array $importer user record of the importing user
251 * @param array $hub Called by reference, returns the fetched hub data
253 public static function import($xml,$importer,&$contact, &$hub) {
254 /// @todo this function is too long. It has to be split in many parts
256 logger("Import OStatus message", LOGGER_DEBUG);
261 //$tempfile = tempnam(get_temppath(), "import");
262 //file_put_contents($tempfile, $xml);
264 $doc = new DOMDocument();
265 @$doc->loadXML($xml);
267 $xpath = new DomXPath($doc);
268 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
269 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
270 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
271 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
272 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
273 $xpath->registerNamespace('poco', NAMESPACE_POCO);
274 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
275 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
278 $hub_attributes = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0)->attributes;
279 if (is_object($hub_attributes)) {
280 foreach ($hub_attributes AS $hub_attribute) {
281 if ($hub_attribute->name == "href") {
282 $hub = $hub_attribute->textContent;
283 logger("Found hub ".$hub, LOGGER_DEBUG);
288 $header["uid"] = $importer["uid"];
289 $header["network"] = NETWORK_OSTATUS;
290 $header["type"] = "remote";
292 $header["origin"] = 0;
293 $header["gravity"] = GRAVITY_PARENT;
295 // it could either be a received post or a post we fetched by ourselves
296 // depending on that, the first node is different
297 $first_child = $doc->firstChild->tagName;
299 if ($first_child == "feed") {
300 $entries = $xpath->query('/atom:feed/atom:entry');
301 $header["protocol"] = PROTOCOL_OSTATUS_FEED;
303 $entries = $xpath->query('/atom:entry');
304 $header["protocol"] = PROTOCOL_OSTATUS_SALMON;
307 $conversationlist = array();
310 // Reverse the order of the entries
311 $entrylist = array();
313 foreach ($entries AS $entry) {
314 $entrylist[] = $entry;
316 foreach (array_reverse($entrylist) AS $entry) {
321 if ($first_child == "feed") {
322 $author = self::fetchauthor($xpath, $doc->firstChild, $importer, $contact, false);
324 $author = self::fetchauthor($xpath, $entry, $importer, $contact, false);
326 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
330 $nickname = $author["author-name"];
332 $item = array_merge($header, $author);
335 $item["uri"] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
337 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
338 intval($importer["uid"]), dbesc($item["uri"]));
339 if (dbm::is_result($r)) {
340 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already existed under id ".$r[0]["id"], LOGGER_DEBUG);
344 $item["body"] = add_page_info_to_body(html2bbcode($xpath->query('atom:content/text()', $entry)->item(0)->nodeValue));
345 $item["object-type"] = $xpath->query('activity:object-type/text()', $entry)->item(0)->nodeValue;
346 $item["verb"] = $xpath->query('activity:verb/text()', $entry)->item(0)->nodeValue;
348 // Mastodon Content Warning
349 if (($item["verb"] == ACTIVITY_POST) AND $xpath->evaluate('boolean(atom:summary)', $entry)) {
350 $clear_text = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
352 $item["body"] = html2bbcode($clear_text) . '[spoiler]' . $item["body"] . '[/spoiler]';
355 if (($item["object-type"] == ACTIVITY_OBJ_BOOKMARK) OR ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
356 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
357 $item["body"] = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
358 } elseif ($item["object-type"] == ACTIVITY_OBJ_QUESTION) {
359 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
361 $item["source"] = $xml;
365 if ($item["verb"] == "qvitter-delete-notice" || $item["verb"] == ACTIVITY_DELETE) {
366 // ignore "Delete" messages (by now)
367 logger("Ignore delete message ".print_r($item, true));
371 if ($item["verb"] == ACTIVITY_JOIN) {
372 // ignore "Join" messages
373 logger("Ignore join message ".print_r($item, true));
377 if ($item["verb"] == ACTIVITY_FOLLOW) {
378 new_follower($importer, $contact, $item, $nickname);
382 if ($item["verb"] == NAMESPACE_OSTATUS."/unfollow") {
383 lose_follower($importer, $contact, $item, $dummy);
387 if ($item["verb"] == ACTIVITY_FAVORITE) {
388 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
389 logger("Favorite ".$orig_uri." ".print_r($item, true));
391 $item["verb"] = ACTIVITY_LIKE;
392 $item["parent-uri"] = $orig_uri;
393 $item["gravity"] = GRAVITY_LIKE;
396 if ($item["verb"] == NAMESPACE_OSTATUS."/unfavorite") {
397 // Ignore "Unfavorite" message
398 logger("Ignore unfavorite message ".print_r($item, true));
402 // http://activitystrea.ms/schema/1.0/rsvp-yes
403 if (!in_array($item["verb"], array(ACTIVITY_POST, ACTIVITY_LIKE, ACTIVITY_SHARE))) {
404 logger("Unhandled verb ".$item["verb"]." ".print_r($item, true));
406 $item["created"] = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
407 $item["edited"] = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
408 $conversation = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
409 $item['conversation-uri'] = $conversation;
411 $conv = $xpath->query('ostatus:conversation', $entry);
412 if (is_object($conv->item(0))) {
413 foreach ($conv->item(0)->attributes AS $attributes) {
414 if ($attributes->name == "ref") {
415 $item['conversation-uri'] = $attributes->textContent;
417 if ($attributes->name == "href") {
418 $item['conversation-href'] = $attributes->textContent;
425 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
426 if (is_object($inreplyto->item(0))) {
427 foreach ($inreplyto->item(0)->attributes AS $attributes) {
428 if ($attributes->name == "ref") {
429 $item["parent-uri"] = $attributes->textContent;
431 if ($attributes->name == "href") {
432 $related = $attributes->textContent;
437 $georsspoint = $xpath->query('georss:point', $entry);
439 $item["coord"] = $georsspoint->item(0)->nodeValue;
441 $categories = $xpath->query('atom:category', $entry);
443 foreach ($categories AS $category) {
444 foreach ($category->attributes AS $attributes) {
445 if ($attributes->name == "term") {
446 $term = $attributes->textContent;
447 if(strlen($item["tag"])) {
450 $item["tag"] .= "#[url=".App::get_baseurl()."/search?tag=".$term."]".$term."[/url]";
459 $links = $xpath->query('atom:link', $entry);
461 foreach ($links AS $link) {
462 $attribute = self::read_attributes($link);
464 if (($attribute['rel'] != "") AND ($attribute['href'] != "")) {
465 switch ($attribute['rel']) {
467 $item["plink"] = $attribute['href'];
468 if (($item["object-type"] == ACTIVITY_OBJ_QUESTION) OR
469 ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
470 $item["body"] .= add_page_info($attribute['href']);
473 case "ostatus:conversation":
474 $conversation = $attribute['href'];
475 $item['conversation-href'] = $conversation;
476 if (!isset($item['conversation-uri'])) {
477 $item['conversation-uri'] = $item['conversation-href'];
481 $enclosure = $attribute['href'];
482 if (strlen($item["attach"])) {
483 $item["attach"] .= ',';
485 if (!isset($attribute['length'])) {
486 $attribute['length'] = "0";
488 $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.$attribute['title'].'"[/attach]';
491 if ($item["object-type"] != ACTIVITY_OBJ_BOOKMARK) {
492 if (!isset($item["parent-uri"])) {
493 $item["parent-uri"] = $attribute['href'];
495 if ($related == "") {
496 $related = $attribute['href'];
499 $item["body"] .= add_page_info($attribute['href']);
503 $self = $attribute['href'];
506 // Notification check
507 if ($importer["nurl"] == normalise_link($attribute['href'])) {
519 $notice_info = $xpath->query('statusnet:notice_info', $entry);
520 if ($notice_info AND ($notice_info->length > 0)) {
521 foreach ($notice_info->item(0)->attributes AS $attributes) {
522 if ($attributes->name == "source") {
523 $item["app"] = strip_tags($attributes->textContent);
525 if ($attributes->name == "local_id") {
526 $local_id = $attributes->textContent;
528 if ($attributes->name == "repeat_of") {
529 $repeat_of = $attributes->textContent;
534 // Is it a repeated post?
535 if (($repeat_of != "") OR ($item["verb"] == ACTIVITY_SHARE)) {
536 $activityobjects = $xpath->query('activity:object', $entry)->item(0);
538 if (is_object($activityobjects)) {
540 $orig_uri = $xpath->query("activity:object/atom:id", $activityobjects)->item(0)->nodeValue;
541 if (!isset($orig_uri)) {
542 $orig_uri = $xpath->query('atom:id/text()', $activityobjects)->item(0)->nodeValue;
544 $orig_links = $xpath->query("activity:object/atom:link[@rel='alternate']", $activityobjects);
545 if ($orig_links AND ($orig_links->length > 0)) {
546 foreach ($orig_links->item(0)->attributes AS $attributes) {
547 if ($attributes->name == "href") {
548 $orig_link = $attributes->textContent;
552 if (!isset($orig_link)) {
553 $orig_link = $xpath->query("atom:link[@rel='alternate']", $activityobjects)->item(0)->nodeValue;
555 if (!isset($orig_link)) {
556 $orig_link = self::convert_href($orig_uri);
558 $orig_body = $xpath->query('activity:object/atom:content/text()', $activityobjects)->item(0)->nodeValue;
559 if (!isset($orig_body)) {
560 $orig_body = $xpath->query('atom:content/text()', $activityobjects)->item(0)->nodeValue;
562 $orig_created = $xpath->query('atom:published/text()', $activityobjects)->item(0)->nodeValue;
563 $orig_edited = $xpath->query('atom:updated/text()', $activityobjects)->item(0)->nodeValue;
565 $orig_contact = $contact;
566 $orig_author = self::fetchauthor($xpath, $activityobjects, $importer, $orig_contact, false);
568 $item["author-name"] = $orig_author["author-name"];
569 $item["author-link"] = $orig_author["author-link"];
570 $item["author-avatar"] = $orig_author["author-avatar"];
572 $item["body"] = add_page_info_to_body(html2bbcode($orig_body));
573 $item["created"] = $orig_created;
574 $item["edited"] = $orig_edited;
576 $item["uri"] = $orig_uri;
578 if (!isset($item["plink"])) {
579 $item["plink"] = $orig_link;
582 $item["verb"] = $xpath->query('activity:verb/text()', $activityobjects)->item(0)->nodeValue;
584 $item["object-type"] = $xpath->query('activity:object/activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
585 if (!isset($item["object-type"])) {
586 $item["object-type"] = $xpath->query('activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
589 $enclosures = $xpath->query("atom:link[@rel='alternate']", $activityobjects);
591 foreach ($enclosures AS $link) {
592 $attribute = self::read_attributes($link);
594 $enclosure = $attribute['href'];
595 if (strlen($item["attach"])) {
596 $item["attach"] .= ',';
598 if (!isset($attribute['length'])) {
599 $attribute['length'] = "0";
601 $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.$attribute['title'].'"[/attach]';
608 //if ($enclosure != "")
609 // $item["body"] .= add_page_info($enclosure);
611 if (isset($item["parent-uri"])) {
612 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
613 intval($importer["uid"]), dbesc($item["parent-uri"]));
615 // Only fetch missing stuff if it is a comment or reshare.
616 if (in_array($item["verb"], array(ACTIVITY_POST, ACTIVITY_SHARE)) AND
617 !dbm::is_result($r) AND ($related != "")) {
618 $reply_path = str_replace("/notice/", "/api/statuses/show/", $related).".atom";
620 if ($reply_path != $related) {
621 logger("Fetching related items for user ".$importer["uid"]." from ".$reply_path, LOGGER_DEBUG);
622 $reply_xml = fetch_url($reply_path);
624 $reply_contact = $contact;
625 self::import($reply_xml,$importer,$reply_contact, $reply_hub);
627 // After the import try to fetch the parent item again
628 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
629 intval($importer["uid"]), dbesc($item["parent-uri"]));
632 if (dbm::is_result($r)) {
633 $item["type"] = 'remote-comment';
634 $item["gravity"] = GRAVITY_COMMENT;
637 $item["parent-uri"] = $item["uri"];
639 $item_id = self::completion($conversation, $importer["uid"], $item, $self);
642 logger("Error storing item", LOGGER_DEBUG);
646 logger("Item was stored with id ".$item_id, LOGGER_DEBUG);
651 * @brief Create an url out of an uri
653 * @param string $href URI in the format "parameter1:parameter1:..."
655 * @return string URL in the format http(s)://....
657 public static function convert_href($href) {
658 $elements = explode(":",$href);
660 if ((count($elements) <= 2) OR ($elements[0] != "tag"))
663 $server = explode(",", $elements[1]);
664 $conversation = explode("=", $elements[2]);
666 if ((count($elements) == 4) AND ($elements[2] == "post"))
667 return "http://".$server[0]."/notice/".$elements[3];
669 if ((count($conversation) != 2) OR ($conversation[1] ==""))
672 if ($elements[3] == "objectType=thread")
673 return "http://".$server[0]."/conversation/".$conversation[1];
675 return "http://".$server[0]."/notice/".$conversation[1];
681 * @brief Checks if there are entries in conversations that aren't present on our side
683 * @param bool $mentions Fetch conversations where we are mentioned
684 * @param bool $override Override the interval setting
686 public static function check_conversations($mentions = false, $override = false) {
687 $last = get_config('system','ostatus_last_poll');
689 $poll_interval = intval(get_config('system','ostatus_poll_interval'));
690 if (!$poll_interval) {
691 $poll_interval = self::OSTATUS_DEFAULT_POLL_INTERVAL;
694 // Don't poll if the interval is set negative
695 if (($poll_interval < 0) AND !$override) {
700 $poll_timeframe = intval(get_config('system','ostatus_poll_timeframe'));
701 if (!$poll_timeframe) {
702 $poll_timeframe = self::OSTATUS_DEFAULT_POLL_TIMEFRAME;
705 $poll_timeframe = intval(get_config('system','ostatus_poll_timeframe'));
706 if (!$poll_timeframe) {
707 $poll_timeframe = self::OSTATUS_DEFAULT_POLL_TIMEFRAME_MENTIONS;
712 if ($last AND !$override) {
713 $next = $last + ($poll_interval * 60);
714 if ($next > time()) {
715 logger('poll interval not reached');
720 logger('cron_start');
722 $start = date("Y-m-d H:i:s", time() - ($poll_timeframe * 60));
725 $conversations = q("SELECT `term`.`oid`, `term`.`url`, `term`.`uid` FROM `term`
726 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `term`.`oid` AND `thread`.`uid` = `term`.`uid`
727 WHERE `term`.`type` = 7 AND `term`.`term` > '%s' AND `thread`.`mention`
728 GROUP BY `term`.`url`, `term`.`uid`, `term`.`oid`, `term`.`term` ORDER BY `term`.`term` DESC", dbesc($start));
730 $conversations = q("SELECT `oid`, `url`, `uid` FROM `term`
731 WHERE `type` = 7 AND `term` > '%s'
732 GROUP BY `url`, `uid`, `oid`, `term` ORDER BY `term` DESC", dbesc($start));
735 foreach ($conversations AS $conversation) {
736 self::completion($conversation['url'], $conversation['uid']);
741 set_config('system','ostatus_last_poll', time());
745 * @brief Updates the gcontact table with actor data from the conversation
747 * @param object $actor The actor object that contains the contact data
749 private function conv_fetch_actor($actor) {
751 // We set the generation to "3" since the data here is not as reliable as the data we get on other occasions
752 $contact = array("network" => NETWORK_OSTATUS, "generation" => 3);
754 if (isset($actor->url))
755 $contact["url"] = $actor->url;
757 if (isset($actor->displayName))
758 $contact["name"] = $actor->displayName;
760 if (isset($actor->portablecontacts_net->displayName))
761 $contact["name"] = $actor->portablecontacts_net->displayName;
763 if (isset($actor->portablecontacts_net->preferredUsername))
764 $contact["nick"] = $actor->portablecontacts_net->preferredUsername;
766 if (isset($actor->id))
767 $contact["alias"] = $actor->id;
769 if (isset($actor->summary))
770 $contact["about"] = $actor->summary;
772 if (isset($actor->portablecontacts_net->note))
773 $contact["about"] = $actor->portablecontacts_net->note;
775 if (isset($actor->portablecontacts_net->addresses->formatted))
776 $contact["location"] = $actor->portablecontacts_net->addresses->formatted;
779 if (isset($actor->image->url))
780 $contact["photo"] = $actor->image->url;
782 if (isset($actor->image->width))
783 $avatarwidth = $actor->image->width;
785 if (is_array($actor->status_net->avatarLinks))
786 foreach ($actor->status_net->avatarLinks AS $avatar) {
787 if ($avatarsize < $avatar->width) {
788 $contact["photo"] = $avatar->url;
789 $avatarsize = $avatar->width;
793 $contact["hide"] = false; // OStatus contacts are never hidden
794 update_gcontact($contact);
798 * @brief Fetches the conversation url for a given item link or conversation id
800 * @param string $self The link to the posting
801 * @param string $conversation_id The conversation id
803 * @return string The conversation url
805 private function fetch_conversation($self, $conversation_id = "") {
807 if ($conversation_id != "") {
808 $elements = explode(":", $conversation_id);
810 if ((count($elements) <= 2) OR ($elements[0] != "tag"))
811 return $conversation_id;
817 $json = str_replace(".atom", ".json", $self);
819 $raw = fetch_url($json);
823 $data = json_decode($raw);
824 if (!is_object($data))
827 $conversation_id = $data->statusnet_conversation_id;
829 $pos = strpos($self, "/api/statuses/show/");
830 $base_url = substr($self, 0, $pos);
832 return $base_url."/conversation/".$conversation_id;
836 * @brief Fetches actor details of a given actor and user id
838 * @param string $actor The actor url
839 * @param int $uid The user id
840 * @param int $contact_id The default contact-id
842 * @return array Array with actor details
844 private function get_actor_details($actor, $uid, $contact_id) {
848 $contact = q("SELECT `id`, `rel`, `network` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'",
849 $uid, normalise_link($actor), NETWORK_STATUSNET);
852 $contact = q("SELECT `id`, `rel`, `network` FROM `contact` WHERE `uid` = %d AND `alias` IN ('%s', '%s') AND `network` != '%s'",
853 $uid, $actor, normalise_link($actor), NETWORK_STATUSNET);
856 logger("Found contact for url ".$actor, LOGGER_DEBUG);
857 $details["contact_id"] = $contact[0]["id"];
858 $details["network"] = $contact[0]["network"];
860 $details["not_following"] = !in_array($contact[0]["rel"], array(CONTACT_IS_SHARING, CONTACT_IS_FRIEND));
862 logger("No contact found for user ".$uid." and url ".$actor, LOGGER_DEBUG);
864 // Adding a global contact
865 /// @TODO Use this data for the post
866 $details["global_contact_id"] = get_contact($actor, 0);
868 logger("Global contact ".$global_contact_id." found for url ".$actor, LOGGER_DEBUG);
870 $details["contact_id"] = $contact_id;
871 $details["network"] = NETWORK_OSTATUS;
873 $details["not_following"] = true;
880 * @brief Stores an item and completes the thread
882 * @param string $conversation_url The URI of the conversation
883 * @param integer $uid The user id
884 * @param array $item Data of the item that is to be posted
886 * @return integer The item id of the posted item array
888 private function completion($conversation_url, $uid, $item = array(), $self = "") {
890 /// @todo This function is totally ugly and has to be rewritten totally
892 // Import all threads or only threads that were started by our followers?
893 $all_threads = !get_config('system','ostatus_full_threads');
897 $conversation_url = self::fetch_conversation($self, $conversation_url);
899 // If the thread shouldn't be completed then store the item and go away
900 // Don't do a completion on liked content
901 if (((intval(get_config('system','ostatus_poll_interval')) == -2) AND (count($item) > 0)) OR
902 ($item["verb"] == ACTIVITY_LIKE) OR ($conversation_url == "")) {
903 $item_stored = item_store($item, $all_threads);
905 } elseif (count($item) > 0) {
906 $item = store_conversation($item);
910 $parents = q("SELECT `item`.`id`, `item`.`parent`, `item`.`uri`, `item`.`contact-id`, `item`.`type`,
911 `item`.`verb`, `item`.`visible` FROM `term`
912 STRAIGHT_JOIN `item` AS `thritem` ON `thritem`.`parent` = `term`.`oid`
913 STRAIGHT_JOIN `item` ON `item`.`parent` = `thritem`.`parent`
914 WHERE `term`.`uid` = %d AND `term`.`otype` = %d AND `term`.`type` = %d AND `term`.`url` = '%s'",
915 intval($uid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION), dbesc($conversation_url));
917 /* 2016-10-23: The old query will be kept until we are sure that the query above is a good and fast replacement
919 $parents = q("SELECT `id`, `parent`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `id` IN
920 (SELECT `parent` FROM `item` WHERE `id` IN
921 (SELECT `oid` FROM `term` WHERE `uid` = %d AND `otype` = %d AND `type` = %d AND `url` = '%s'))",
922 intval($uid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION), dbesc($conversation_url));
925 $parent = $parents[0];
926 elseif (count($item) > 0) {
928 $parent["type"] = "remote";
929 $parent["verb"] = ACTIVITY_POST;
930 $parent["visible"] = 1;
933 $r = q("SELECT `id` FROM `contact` WHERE `self` AND `uid`=%d", $uid);
939 $parent["parent"] = 0;
941 $parent["contact-id"] = $r[0]["id"];
942 $parent["type"] = "remote";
943 $parent["verb"] = ACTIVITY_POST;
944 $parent["visible"] = 1;
947 $conv = str_replace("/conversation/", "/api/statusnet/conversation/", $conversation_url).".as";
951 logger('fetching conversation url '.$conv.' (Self: '.$self.') for user '.$uid);
954 $conv_arr = z_fetch_url($conv."?page=".$pageno);
956 // If it is a non-ssl site and there is an error, then try ssl or vice versa
957 if (!$conv_arr["success"] AND (substr($conv, 0, 7) == "http://")) {
958 $conv = str_replace("http://", "https://", $conv);
959 $conv_as = fetch_url($conv."?page=".$pageno);
960 } elseif (!$conv_arr["success"] AND (substr($conv, 0, 8) == "https://")) {
961 $conv = str_replace("https://", "http://", $conv);
962 $conv_as = fetch_url($conv."?page=".$pageno);
964 $conv_as = $conv_arr["body"];
966 $conv_as = str_replace(',"statusnet:notice_info":', ',"statusnet_notice_info":', $conv_as);
967 $conv_as = json_decode($conv_as);
969 $no_of_items = sizeof($items);
971 if (@is_array($conv_as->items))
972 foreach ($conv_as->items AS $single_item)
973 $items[$single_item->id] = $single_item;
975 if ($no_of_items == sizeof($items))
982 logger('fetching conversation done. Found '.count($items).' items');
984 if (!sizeof($items)) {
985 if (count($item) > 0) {
986 $item_stored = item_store($item, $all_threads);
989 logger("Conversation ".$conversation_url." couldn't be fetched. Item uri ".$item["uri"]." stored: ".$item_stored, LOGGER_DEBUG);
990 self::store_conversation($item_id, $conversation_url);
993 return($item_stored);
998 $items = array_reverse($items);
1000 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self`", intval($uid));
1005 foreach ($items as $single_conv) {
1007 // Update the gcontact table
1008 self::conv_fetch_actor($single_conv->actor);
1010 // Test - remove before flight
1011 //$tempfile = tempnam(get_temppath(), "conversation");
1012 //file_put_contents($tempfile, json_encode($single_conv));
1016 if (isset($single_conv->object->id))
1017 $single_conv->id = $single_conv->object->id;
1019 $plink = self::convert_href($single_conv->id);
1020 if (isset($single_conv->object->url))
1021 $plink = self::convert_href($single_conv->object->url);
1023 if (@!$single_conv->id)
1026 logger("Got id ".$single_conv->id, LOGGER_DEBUG);
1028 if ($first_id == "") {
1029 $first_id = $single_conv->id;
1031 // The first post of the conversation isn't our first post. There are three options:
1032 // 1. Our conversation hasn't the "real" thread starter
1033 // 2. This first post is a post inside our thread
1034 // 3. This first post is a post inside another thread
1035 if (($first_id != $parent["uri"]) AND ($parent["uri"] != "")) {
1039 $new_parents = q("SELECT `id`, `parent`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `id` IN
1040 (SELECT `parent` FROM `item`
1041 WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s')) LIMIT 1",
1042 intval($uid), dbesc($first_id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
1044 if ($new_parents[0]["parent"] == $parent["parent"]) {
1045 // Option 2: This post is already present inside our thread - but not as thread starter
1046 logger("Option 2: uri present in our thread: ".$first_id, LOGGER_DEBUG);
1047 $first_id = $parent["uri"];
1049 // Option 3: Not so good. We have mixed parents. We have to see how to clean this up.
1050 // For now just take the new parent.
1051 $parent = $new_parents[0];
1052 $first_id = $parent["uri"];
1053 logger("Option 3: mixed parents for uri ".$first_id, LOGGER_DEBUG);
1056 // Option 1: We hadn't got the real thread starter
1057 // We have to clean up our existing messages.
1059 $parent["uri"] = $first_id;
1060 logger("Option 1: we have a new parent: ".$first_id, LOGGER_DEBUG);
1062 } elseif ($parent["uri"] == "") {
1064 $parent["uri"] = $first_id;
1068 $parent_uri = $parent["uri"];
1070 // "context" only seems to exist on older servers
1071 if (isset($single_conv->context->inReplyTo->id)) {
1072 $parent_exists = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
1073 intval($uid), dbesc($single_conv->context->inReplyTo->id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
1075 $parent_uri = $single_conv->context->inReplyTo->id;
1078 // This is the current way
1079 if (isset($single_conv->object->inReplyTo->id)) {
1080 $parent_exists = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
1081 intval($uid), dbesc($single_conv->object->inReplyTo->id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
1083 $parent_uri = $single_conv->object->inReplyTo->id;
1086 $message_exists = q("SELECT `id`, `parent`, `uri` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
1087 intval($uid), dbesc($single_conv->id),
1088 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
1089 if ($message_exists) {
1090 logger("Message ".$single_conv->id." already existed on the system", LOGGER_DEBUG);
1092 if ($parent["id"] != 0) {
1093 $existing_message = $message_exists[0];
1095 // We improved the way we fetch OStatus messages, this shouldn't happen very often now
1096 /// @TODO We have to change the shadow copies as well. This way here is really ugly.
1097 if ($existing_message["parent"] != $parent["id"]) {
1098 logger('updating id '.$existing_message["id"].' with parent '.$existing_message["parent"].' to parent '.$parent["id"].' uri '.$parent["uri"].' thread '.$parent_uri, LOGGER_DEBUG);
1100 // Update the parent id of the selected item
1101 $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s' WHERE `id` = %d",
1102 intval($parent["id"]), dbesc($parent["uri"]), intval($existing_message["id"]));
1104 // Update the parent uri in the thread - but only if it points to itself
1105 $r = q("UPDATE `item` SET `thr-parent` = '%s' WHERE `id` = %d AND `uri` = `thr-parent`",
1106 dbesc($parent_uri), intval($existing_message["id"]));
1108 // try to change all items of the same parent
1109 $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s' WHERE `parent` = %d",
1110 intval($parent["id"]), dbesc($parent["uri"]), intval($existing_message["parent"]));
1112 // Update the parent uri in the thread - but only if it points to itself
1113 $r = q("UPDATE `item` SET `thr-parent` = '%s' WHERE (`parent` = %d) AND (`uri` = `thr-parent`)",
1114 dbesc($parent["uri"]), intval($existing_message["parent"]));
1116 // Now delete the thread
1117 delete_thread($existing_message["parent"]);
1121 // The item we are having on the system is the one that we wanted to store via the item array
1122 if (isset($item["uri"]) AND ($item["uri"] == $existing_message["uri"])) {
1130 if (is_array($single_conv->to))
1131 foreach($single_conv->to AS $to)
1132 if ($importer["nurl"] == normalise_link($to->id))
1135 $actor = $single_conv->actor->id;
1136 if (isset($single_conv->actor->url))
1137 $actor = $single_conv->actor->url;
1139 $details = self::get_actor_details($actor, $uid, $parent["contact-id"]);
1141 // Do we only want to import threads that were started by our contacts?
1142 if ($details["not_following"] AND $new_parent AND get_config('system','ostatus_full_threads')) {
1143 logger("Don't import uri ".$first_id." because user ".$uid." doesn't follow the person ".$actor, LOGGER_DEBUG);
1148 $arr["network"] = $details["network"];
1149 $arr["uri"] = $single_conv->id;
1150 $arr["plink"] = $plink;
1152 $arr["contact-id"] = $details["contact_id"];
1153 $arr["parent-uri"] = $parent_uri;
1154 $arr["created"] = $single_conv->published;
1155 $arr["edited"] = $single_conv->published;
1156 $arr["owner-name"] = $single_conv->actor->displayName;
1157 if ($arr["owner-name"] == '')
1158 $arr["owner-name"] = $single_conv->actor->contact->displayName;
1159 if ($arr["owner-name"] == '')
1160 $arr["owner-name"] = $single_conv->actor->portablecontacts_net->displayName;
1162 $arr["owner-link"] = $actor;
1163 $arr["owner-avatar"] = Probe::fix_avatar($single_conv->actor->image->url, $arr["owner-link"]);
1165 $arr["author-name"] = $arr["owner-name"];
1166 $arr["author-link"] = $arr["owner-link"];
1167 $arr["author-avatar"] = $arr["owner-avatar"];
1168 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->content));
1170 if (isset($single_conv->status_net->conversation)) {
1171 $arr['conversation-uri'] = $single_conv->status_net->conversation;
1174 if (isset($single_conv->status_net->notice_info->source))
1175 $arr["app"] = strip_tags($single_conv->status_net->notice_info->source);
1176 elseif (isset($single_conv->statusnet->notice_info->source))
1177 $arr["app"] = strip_tags($single_conv->statusnet->notice_info->source);
1178 elseif (isset($single_conv->statusnet_notice_info->source))
1179 $arr["app"] = strip_tags($single_conv->statusnet_notice_info->source);
1180 elseif (isset($single_conv->provider->displayName))
1181 $arr["app"] = $single_conv->provider->displayName;
1183 $arr["app"] = "OStatus";
1186 $arr["source"] = json_encode($single_conv);
1187 $arr["protocol"] = PROTOCOL_GS_CONVERSATION;
1189 $arr["verb"] = $parent["verb"];
1190 $arr["visible"] = $parent["visible"];
1191 $arr["location"] = $single_conv->location->displayName;
1192 $arr["coord"] = trim($single_conv->location->lat." ".$single_conv->location->lon);
1194 // Is it a reshared item?
1195 if (isset($single_conv->verb) AND ($single_conv->verb == "share") AND isset($single_conv->object)) {
1196 if (is_array($single_conv->object))
1197 $single_conv->object = $single_conv->object[0];
1199 logger("Found reshared item ".$single_conv->object->id);
1201 // $single_conv->object->context->conversation;
1203 if (isset($single_conv->object->object->id))
1204 $arr["uri"] = $single_conv->object->object->id;
1206 $arr["uri"] = $single_conv->object->id;
1208 if (isset($single_conv->object->object->url))
1209 $plink = self::convert_href($single_conv->object->object->url);
1211 $plink = self::convert_href($single_conv->object->url);
1213 if (isset($single_conv->object->object->content))
1214 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->object->content));
1216 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->content));
1218 $arr["plink"] = $plink;
1220 $arr["created"] = $single_conv->object->published;
1221 $arr["edited"] = $single_conv->object->published;
1223 $arr["author-name"] = $single_conv->object->actor->displayName;
1224 if ($arr["owner-name"] == '') {
1225 $arr["author-name"] = $single_conv->object->actor->contact->displayName;
1227 $arr["author-link"] = $single_conv->object->actor->url;
1228 $arr["author-avatar"] = Probe::fix_avatar($single_conv->object->actor->image->url, $arr["author-link"]);
1230 $arr["app"] = $single_conv->object->provider->displayName."#";
1231 //$arr["verb"] = $single_conv->object->verb;
1233 $arr["location"] = $single_conv->object->location->displayName;
1234 $arr["coord"] = trim($single_conv->object->location->lat." ".$single_conv->object->location->lon);
1237 if ($arr["location"] == "")
1238 unset($arr["location"]);
1240 if ($arr["coord"] == "")
1241 unset($arr["coord"]);
1243 // Copy fields from given item array
1244 if (isset($item["uri"]) AND (($item["uri"] == $arr["uri"]) OR ($item["uri"] == $single_conv->id))) {
1245 $copy_fields = array("owner-name", "owner-link", "owner-avatar", "author-name", "author-link", "author-avatar",
1246 "gravity", "body", "object-type", "object", "verb", "created", "edited", "coord", "tag",
1247 "title", "attach", "app", "type", "location", "contact-id", "uri");
1248 foreach ($copy_fields AS $field)
1249 if (isset($item[$field]))
1250 $arr[$field] = $item[$field];
1254 $newitem = item_store($arr);
1256 logger("Item wasn't stored ".print_r($arr, true), LOGGER_DEBUG);
1260 if (isset($item["uri"]) AND ($item["uri"] == $arr["uri"])) {
1262 $item_stored = $newitem;
1265 logger('Stored new item '.$plink.' for parent '.$arr["parent-uri"].' under id '.$newitem, LOGGER_DEBUG);
1267 // Add the conversation entry (but don't fetch the whole conversation)
1268 self::store_conversation($newitem, $conversation_url);
1270 // If the newly created item is the top item then change the parent settings of the thread
1271 // This shouldn't happen anymore. This is supposed to be absolote.
1272 if ($arr["uri"] == $first_id) {
1273 logger('setting new parent to id '.$newitem);
1274 $new_parents = q("SELECT `id`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `uid` = %d AND `id` = %d LIMIT 1",
1275 intval($uid), intval($newitem));
1277 $parent = $new_parents[0];
1281 if (($item_stored < 0) AND (count($item) > 0)) {
1283 if (get_config('system','ostatus_full_threads')) {
1284 $details = self::get_actor_details($item["owner-link"], $uid, $item["contact-id"]);
1285 if ($details["not_following"]) {
1286 logger("Don't import uri ".$item["uri"]." because user ".$uid." doesn't follow the person ".$item["owner-link"], LOGGER_DEBUG);
1291 $item_stored = item_store($item, $all_threads);
1293 logger("Uri ".$item["uri"]." wasn't found in conversation ".$conversation_url, LOGGER_DEBUG);
1294 self::store_conversation($item_stored, $conversation_url);
1298 return($item_stored);
1302 * @brief Stores conversation data into the database
1304 * @param integer $itemid The id of the item
1305 * @param string $conversation_url The uri of the conversation
1307 private function store_conversation($itemid, $conversation_url) {
1309 $conversation_url = self::convert_href($conversation_url);
1311 $messages = q("SELECT `uid`, `parent`, `created`, `received`, `guid` FROM `item` WHERE `id` = %d LIMIT 1", intval($itemid));
1314 $message = $messages[0];
1316 // Store conversation url if not done before
1317 $conversation = q("SELECT `url` FROM `term` WHERE `uid` = %d AND `oid` = %d AND `otype` = %d AND `type` = %d",
1318 intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION));
1320 if (!$conversation) {
1321 $r = q("INSERT INTO `term` (`uid`, `oid`, `otype`, `type`, `term`, `url`, `created`, `received`, `guid`) VALUES (%d, %d, %d, %d, '%s', '%s', '%s', '%s', '%s')",
1322 intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION),
1323 dbesc($message["created"]), dbesc($conversation_url), dbesc($message["created"]), dbesc($message["received"]), dbesc($message["guid"]));
1324 logger('Storing conversation url '.$conversation_url.' for id '.$itemid);
1329 * @brief Checks if the current post is a reshare
1331 * @param array $item The item array of thw post
1333 * @return string The guid if the post is a reshare
1335 private function get_reshared_guid($item) {
1336 $body = trim($item["body"]);
1338 // Skip if it isn't a pure repeated messages
1339 // Does it start with a share?
1340 if (strpos($body, "[share") > 0)
1343 // Does it end with a share?
1344 if (strlen($body) > (strrpos($body, "[/share]") + 8))
1347 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
1348 // Skip if there is no shared message in there
1349 if ($body == $attributes)
1353 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
1354 if ($matches[1] != "")
1355 $guid = $matches[1];
1357 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
1358 if ($matches[1] != "")
1359 $guid = $matches[1];
1365 * @brief Cleans the body of a post if it contains picture links
1367 * @param string $body The body
1369 * @return string The cleaned body
1371 private function format_picture_post($body) {
1372 $siteinfo = get_attached_data($body);
1374 if (($siteinfo["type"] == "photo")) {
1375 if (isset($siteinfo["preview"]))
1376 $preview = $siteinfo["preview"];
1378 $preview = $siteinfo["image"];
1380 // Is it a remote picture? Then make a smaller preview here
1381 $preview = proxy_url($preview, false, PROXY_SIZE_SMALL);
1383 // Is it a local picture? Then make it smaller here
1384 $preview = str_replace(array("-0.jpg", "-0.png"), array("-2.jpg", "-2.png"), $preview);
1385 $preview = str_replace(array("-1.jpg", "-1.png"), array("-2.jpg", "-2.png"), $preview);
1387 if (isset($siteinfo["url"]))
1388 $url = $siteinfo["url"];
1390 $url = $siteinfo["image"];
1392 $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1399 * @brief Adds the header elements to the XML document
1401 * @param object $doc XML document
1402 * @param array $owner Contact data of the poster
1404 * @return object header root element
1406 private function add_header($doc, $owner) {
1410 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
1411 $doc->appendChild($root);
1413 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1414 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1415 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1416 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1417 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
1418 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1419 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1420 $root->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1422 $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
1423 xml::add_element($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1424 xml::add_element($doc, $root, "id", App::get_baseurl()."/profile/".$owner["nick"]);
1425 xml::add_element($doc, $root, "title", sprintf("%s timeline", $owner["name"]));
1426 xml::add_element($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], $a->config["sitename"]));
1427 xml::add_element($doc, $root, "logo", $owner["photo"]);
1428 xml::add_element($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
1430 $author = self::add_author($doc, $owner);
1431 $root->appendChild($author);
1433 $attributes = array("href" => $owner["url"], "rel" => "alternate", "type" => "text/html");
1434 xml::add_element($doc, $root, "link", "", $attributes);
1436 /// @TODO We have to find out what this is
1437 /// $attributes = array("href" => App::get_baseurl()."/sup",
1438 /// "rel" => "http://api.friendfeed.com/2008/03#sup",
1439 /// "type" => "application/json");
1440 /// xml::add_element($doc, $root, "link", "", $attributes);
1442 self::hublinks($doc, $root);
1444 $attributes = array("href" => App::get_baseurl()."/salmon/".$owner["nick"], "rel" => "salmon");
1445 xml::add_element($doc, $root, "link", "", $attributes);
1447 $attributes = array("href" => App::get_baseurl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies");
1448 xml::add_element($doc, $root, "link", "", $attributes);
1450 $attributes = array("href" => App::get_baseurl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention");
1451 xml::add_element($doc, $root, "link", "", $attributes);
1453 $attributes = array("href" => App::get_baseurl()."/api/statuses/user_timeline/".$owner["nick"].".atom",
1454 "rel" => "self", "type" => "application/atom+xml");
1455 xml::add_element($doc, $root, "link", "", $attributes);
1461 * @brief Add the link to the push hubs to the XML document
1463 * @param object $doc XML document
1464 * @param object $root XML root element where the hub links are added
1466 public static function hublinks($doc, $root) {
1467 $hub = get_config('system','huburl');
1471 $hubs = explode(',', $hub);
1473 foreach($hubs as $h) {
1477 if ($h === '[internal]')
1478 $h = App::get_baseurl() . '/pubsubhubbub';
1479 xml::add_element($doc, $root, "link", "", array("href" => $h, "rel" => "hub"));
1486 * @brief Adds attachement data to the XML document
1488 * @param object $doc XML document
1489 * @param object $root XML root element where the hub links are added
1490 * @param array $item Data of the item that is to be posted
1492 private function get_attachment($doc, $root, $item) {
1494 $siteinfo = get_attached_data($item["body"]);
1496 switch ($siteinfo["type"]) {
1498 $imgdata = get_photo_info($siteinfo["image"]);
1499 $attributes = array("rel" => "enclosure",
1500 "href" => $siteinfo["image"],
1501 "type" => $imgdata["mime"],
1502 "length" => intval($imgdata["size"]));
1503 xml::add_element($doc, $root, "link", "", $attributes);
1506 $attributes = array("rel" => "enclosure",
1507 "href" => $siteinfo["url"],
1508 "type" => "text/html; charset=UTF-8",
1510 "title" => $siteinfo["title"]);
1511 xml::add_element($doc, $root, "link", "", $attributes);
1517 if (($siteinfo["type"] != "photo") AND isset($siteinfo["image"])) {
1518 $imgdata = get_photo_info($siteinfo["image"]);
1519 $attributes = array("rel" => "enclosure",
1520 "href" => $siteinfo["image"],
1521 "type" => $imgdata["mime"],
1522 "length" => intval($imgdata["size"]));
1524 xml::add_element($doc, $root, "link", "", $attributes);
1527 $arr = explode('[/attach],', $item['attach']);
1529 foreach ($arr as $r) {
1531 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1533 $attributes = array("rel" => "enclosure",
1534 "href" => $matches[1],
1535 "type" => $matches[3]);
1537 if (intval($matches[2])) {
1538 $attributes["length"] = intval($matches[2]);
1540 if (trim($matches[4]) != "") {
1541 $attributes["title"] = trim($matches[4]);
1543 xml::add_element($doc, $root, "link", "", $attributes);
1550 * @brief Adds the author element to the XML document
1552 * @param object $doc XML document
1553 * @param array $owner Contact data of the poster
1555 * @return object author element
1557 private function add_author($doc, $owner) {
1559 $r = q("SELECT `homepage`, `publish` FROM `profile` WHERE `uid` = %d AND `is-default` LIMIT 1", intval($owner["uid"]));
1563 $author = $doc->createElement("author");
1564 xml::add_element($doc, $author, "id", $owner["url"]);
1565 xml::add_element($doc, $author, "activity:object-type", ACTIVITY_OBJ_PERSON);
1566 xml::add_element($doc, $author, "uri", $owner["url"]);
1567 xml::add_element($doc, $author, "name", $owner["nick"]);
1568 xml::add_element($doc, $author, "email", $owner["addr"]);
1569 xml::add_element($doc, $author, "summary", bbcode($owner["about"], false, false, 7));
1571 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $owner["url"]);
1572 xml::add_element($doc, $author, "link", "", $attributes);
1574 $attributes = array(
1576 "type" => "image/jpeg", // To-Do?
1577 "media:width" => 175,
1578 "media:height" => 175,
1579 "href" => $owner["photo"]);
1580 xml::add_element($doc, $author, "link", "", $attributes);
1582 if (isset($owner["thumb"])) {
1583 $attributes = array(
1585 "type" => "image/jpeg", // To-Do?
1586 "media:width" => 80,
1587 "media:height" => 80,
1588 "href" => $owner["thumb"]);
1589 xml::add_element($doc, $author, "link", "", $attributes);
1592 xml::add_element($doc, $author, "poco:preferredUsername", $owner["nick"]);
1593 xml::add_element($doc, $author, "poco:displayName", $owner["name"]);
1594 xml::add_element($doc, $author, "poco:note", bbcode($owner["about"], false, false, 7));
1596 if (trim($owner["location"]) != "") {
1597 $element = $doc->createElement("poco:address");
1598 xml::add_element($doc, $element, "poco:formatted", $owner["location"]);
1599 $author->appendChild($element);
1602 if (trim($profile["homepage"]) != "") {
1603 $urls = $doc->createElement("poco:urls");
1604 xml::add_element($doc, $urls, "poco:type", "homepage");
1605 xml::add_element($doc, $urls, "poco:value", $profile["homepage"]);
1606 xml::add_element($doc, $urls, "poco:primary", "true");
1607 $author->appendChild($urls);
1610 if (count($profile)) {
1611 xml::add_element($doc, $author, "followers", "", array("url" => App::get_baseurl()."/viewcontacts/".$owner["nick"]));
1612 xml::add_element($doc, $author, "statusnet:profile_info", "", array("local_id" => $owner["uid"]));
1615 if ($profile["publish"]) {
1616 xml::add_element($doc, $author, "mastodon:scope", "public");
1622 * @TODO Picture attachments should look like this:
1623 * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1624 * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1629 * @brief Returns the given activity if present - otherwise returns the "post" activity
1631 * @param array $item Data of the item that is to be posted
1633 * @return string activity
1635 function construct_verb($item) {
1637 return $item['verb'];
1638 return ACTIVITY_POST;
1642 * @brief Returns the given object type if present - otherwise returns the "note" object type
1644 * @param array $item Data of the item that is to be posted
1646 * @return string Object type
1648 function construct_objecttype($item) {
1649 if (in_array($item['object-type'], array(ACTIVITY_OBJ_NOTE, ACTIVITY_OBJ_COMMENT)))
1650 return $item['object-type'];
1651 return ACTIVITY_OBJ_NOTE;
1655 * @brief Adds an entry element to the XML document
1657 * @param object $doc XML document
1658 * @param array $item Data of the item that is to be posted
1659 * @param array $owner Contact data of the poster
1660 * @param bool $toplevel
1662 * @return object Entry element
1664 private function entry($doc, $item, $owner, $toplevel = false) {
1665 $repeated_guid = self::get_reshared_guid($item);
1666 if ($repeated_guid != "")
1667 $xml = self::reshare_entry($doc, $item, $owner, $repeated_guid, $toplevel);
1672 if ($item["verb"] == ACTIVITY_LIKE) {
1673 return self::like_entry($doc, $item, $owner, $toplevel);
1674 } elseif (in_array($item["verb"], array(ACTIVITY_FOLLOW, NAMESPACE_OSTATUS."/unfollow"))) {
1675 return self::follow_entry($doc, $item, $owner, $toplevel);
1677 return self::note_entry($doc, $item, $owner, $toplevel);
1682 * @brief Adds a source entry to the XML document
1684 * @param object $doc XML document
1685 * @param array $contact Array of the contact that is added
1687 * @return object Source element
1689 private function source_entry($doc, $contact) {
1690 $source = $doc->createElement("source");
1691 xml::add_element($doc, $source, "id", $contact["poll"]);
1692 xml::add_element($doc, $source, "title", $contact["name"]);
1693 xml::add_element($doc, $source, "link", "", array("rel" => "alternate",
1694 "type" => "text/html",
1695 "href" => $contact["alias"]));
1696 xml::add_element($doc, $source, "link", "", array("rel" => "self",
1697 "type" => "application/atom+xml",
1698 "href" => $contact["poll"]));
1699 xml::add_element($doc, $source, "icon", $contact["photo"]);
1700 xml::add_element($doc, $source, "updated", datetime_convert("UTC","UTC",$contact["success_update"]."+00:00",ATOM_TIME));
1706 * @brief Fetches contact data from the contact or the gcontact table
1708 * @param string $url URL of the contact
1709 * @param array $owner Contact data of the poster
1711 * @return array Contact array
1713 private function contact_entry($url, $owner) {
1715 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
1716 dbesc(normalise_link($url)), intval($owner["uid"]));
1719 $contact["uid"] = -1;
1723 $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1724 dbesc(normalise_link($url)));
1727 $contact["uid"] = -1;
1728 $contact["success_update"] = $contact["updated"];
1735 if (!isset($contact["poll"])) {
1736 $data = probe_url($url);
1737 $contact["poll"] = $data["poll"];
1739 if (!$contact["alias"])
1740 $contact["alias"] = $data["alias"];
1743 if (!isset($contact["alias"]))
1744 $contact["alias"] = $contact["url"];
1750 * @brief Adds an entry element with reshared content
1752 * @param object $doc XML document
1753 * @param array $item Data of the item that is to be posted
1754 * @param array $owner Contact data of the poster
1755 * @param $repeated_guid
1756 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1758 * @return object Entry element
1760 private function reshare_entry($doc, $item, $owner, $repeated_guid, $toplevel) {
1762 if (($item["id"] != $item["parent"]) AND (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1763 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1766 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1768 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' AND NOT `private` AND `network` IN ('%s', '%s', '%s') LIMIT 1",
1769 intval($owner["uid"]), dbesc($repeated_guid),
1770 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS));
1772 $repeated_item = $r[0];
1776 $contact = self::contact_entry($repeated_item['author-link'], $owner);
1778 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1780 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1782 self::entry_content($doc, $entry, $item, $owner, $title, ACTIVITY_SHARE, false);
1784 $as_object = $doc->createElement("activity:object");
1786 xml::add_element($doc, $as_object, "activity:object-type", NAMESPACE_ACTIVITY_SCHEMA."activity");
1788 self::entry_content($doc, $as_object, $repeated_item, $owner, "", "", false);
1790 $author = self::add_author($doc, $contact);
1791 $as_object->appendChild($author);
1793 $as_object2 = $doc->createElement("activity:object");
1795 xml::add_element($doc, $as_object2, "activity:object-type", self::construct_objecttype($repeated_item));
1797 $title = sprintf("New comment by %s", $contact["nick"]);
1799 self::entry_content($doc, $as_object2, $repeated_item, $owner, $title);
1801 $as_object->appendChild($as_object2);
1803 self::entry_footer($doc, $as_object, $item, $owner, false);
1805 $source = self::source_entry($doc, $contact);
1807 $as_object->appendChild($source);
1809 $entry->appendChild($as_object);
1811 self::entry_footer($doc, $entry, $item, $owner);
1817 * @brief Adds an entry element with a "like"
1819 * @param object $doc XML document
1820 * @param array $item Data of the item that is to be posted
1821 * @param array $owner Contact data of the poster
1822 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1824 * @return object Entry element with "like"
1826 private function like_entry($doc, $item, $owner, $toplevel) {
1828 if (($item["id"] != $item["parent"]) AND (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1829 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1832 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1834 $verb = NAMESPACE_ACTIVITY_SCHEMA."favorite";
1835 self::entry_content($doc, $entry, $item, $owner, "Favorite", $verb, false);
1837 $as_object = $doc->createElement("activity:object");
1839 $parent = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d",
1840 dbesc($item["thr-parent"]), intval($item["uid"]));
1841 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1843 xml::add_element($doc, $as_object, "activity:object-type", self::construct_objecttype($parent[0]));
1845 self::entry_content($doc, $as_object, $parent[0], $owner, "New entry");
1847 $entry->appendChild($as_object);
1849 self::entry_footer($doc, $entry, $item, $owner);
1855 * @brief Adds the person object element to the XML document
1857 * @param object $doc XML document
1858 * @param array $owner Contact data of the poster
1859 * @param array $contact Contact data of the target
1861 * @return object author element
1863 private function add_person_object($doc, $owner, $contact) {
1865 $object = $doc->createElement("activity:object");
1866 xml::add_element($doc, $object, "activity:object-type", ACTIVITY_OBJ_PERSON);
1868 if ($contact['network'] == NETWORK_PHANTOM) {
1869 xml::add_element($doc, $object, "id", $contact['url']);
1873 xml::add_element($doc, $object, "id", $contact["alias"]);
1874 xml::add_element($doc, $object, "title", $contact["nick"]);
1876 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $contact["url"]);
1877 xml::add_element($doc, $object, "link", "", $attributes);
1879 $attributes = array(
1881 "type" => "image/jpeg", // To-Do?
1882 "media:width" => 175,
1883 "media:height" => 175,
1884 "href" => $contact["photo"]);
1885 xml::add_element($doc, $object, "link", "", $attributes);
1887 xml::add_element($doc, $object, "poco:preferredUsername", $contact["nick"]);
1888 xml::add_element($doc, $object, "poco:displayName", $contact["name"]);
1890 if (trim($contact["location"]) != "") {
1891 $element = $doc->createElement("poco:address");
1892 xml::add_element($doc, $element, "poco:formatted", $contact["location"]);
1893 $object->appendChild($element);
1900 * @brief Adds a follow/unfollow entry element
1902 * @param object $doc XML document
1903 * @param array $item Data of the follow/unfollow message
1904 * @param array $owner Contact data of the poster
1905 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1907 * @return object Entry element
1909 private function follow_entry($doc, $item, $owner, $toplevel) {
1911 $item["id"] = $item["parent"] = 0;
1912 $item["created"] = $item["edited"] = date("c");
1913 $item["private"] = true;
1915 $contact = Probe::uri($item['follow']);
1917 if ($contact['alias'] == '') {
1918 $contact['alias'] = $contact["url"];
1920 $item['follow'] = $contact['alias'];
1923 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1924 intval($owner['uid']), dbesc(normalise_link($contact["url"])));
1926 if (dbm::is_result($r)) {
1927 $connect_id = $r[0]['id'];
1932 if ($item['verb'] == ACTIVITY_FOLLOW) {
1933 $message = t('%s is now following %s.');
1934 $title = t('following');
1935 $action = "subscription";
1937 $message = t('%s stopped following %s.');
1938 $title = t('stopped following');
1939 $action = "unfollow";
1942 $item["uri"] = $item['parent-uri'] = $item['thr-parent'] =
1943 'tag:'.get_app()->get_hostname().
1944 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1945 ':person:'.$connect_id.':'.$item['created'];
1947 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1949 self::entry_header($doc, $entry, $owner, $toplevel);
1951 self::entry_content($doc, $entry, $item, $owner, $title);
1953 $object = self::add_person_object($doc, $owner, $contact);
1954 $entry->appendChild($object);
1956 self::entry_footer($doc, $entry, $item, $owner);
1962 * @brief Adds a regular entry element
1964 * @param object $doc XML document
1965 * @param array $item Data of the item that is to be posted
1966 * @param array $owner Contact data of the poster
1967 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1969 * @return object Entry element
1971 private function note_entry($doc, $item, $owner, $toplevel) {
1973 if (($item["id"] != $item["parent"]) AND (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1974 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1977 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1979 xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1981 self::entry_content($doc, $entry, $item, $owner, $title);
1983 self::entry_footer($doc, $entry, $item, $owner);
1989 * @brief Adds a header element to the XML document
1991 * @param object $doc XML document
1992 * @param object $entry The entry element where the elements are added
1993 * @param array $owner Contact data of the poster
1994 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1996 * @return string The title for the element
1998 private function entry_header($doc, &$entry, $owner, $toplevel) {
1999 /// @todo Check if this title stuff is really needed (I guess not)
2001 $entry = $doc->createElement("entry");
2002 $title = sprintf("New note by %s", $owner["nick"]);
2004 $entry = $doc->createElementNS(NAMESPACE_ATOM1, "entry");
2006 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
2007 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
2008 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
2009 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
2010 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
2011 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
2012 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
2013 $entry->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
2015 $author = self::add_author($doc, $owner);
2016 $entry->appendChild($author);
2018 $title = sprintf("New comment by %s", $owner["nick"]);
2024 * @brief Adds elements to the XML document
2026 * @param object $doc XML document
2027 * @param object $entry Entry element where the content is added
2028 * @param array $item Data of the item that is to be posted
2029 * @param array $owner Contact data of the poster
2030 * @param string $title Title for the post
2031 * @param string $verb The activity verb
2032 * @param bool $complete Add the "status_net" element?
2034 private function entry_content($doc, $entry, $item, $owner, $title, $verb = "", $complete = true) {
2037 $verb = self::construct_verb($item);
2039 xml::add_element($doc, $entry, "id", $item["uri"]);
2040 xml::add_element($doc, $entry, "title", $title);
2042 $body = self::format_picture_post($item['body']);
2044 if ($item['title'] != "")
2045 $body = "[b]".$item['title']."[/b]\n\n".$body;
2047 $body = bbcode($body, false, false, 7);
2049 xml::add_element($doc, $entry, "content", $body, array("type" => "html"));
2051 xml::add_element($doc, $entry, "link", "", array("rel" => "alternate", "type" => "text/html",
2052 "href" => App::get_baseurl()."/display/".$item["guid"]));
2054 if ($complete AND ($item["id"] > 0))
2055 xml::add_element($doc, $entry, "status_net", "", array("notice_id" => $item["id"]));
2057 xml::add_element($doc, $entry, "activity:verb", $verb);
2059 xml::add_element($doc, $entry, "published", datetime_convert("UTC","UTC",$item["created"]."+00:00",ATOM_TIME));
2060 xml::add_element($doc, $entry, "updated", datetime_convert("UTC","UTC",$item["edited"]."+00:00",ATOM_TIME));
2064 * @brief Adds the elements at the foot of an entry to the XML document
2066 * @param object $doc XML document
2067 * @param object $entry The entry element where the elements are added
2068 * @param array $item Data of the item that is to be posted
2069 * @param array $owner Contact data of the poster
2072 private function entry_footer($doc, $entry, $item, $owner, $complete = true) {
2074 $mentioned = array();
2076 if (($item['parent'] != $item['id']) OR ($item['parent-uri'] !== $item['uri']) OR (($item['thr-parent'] !== '') AND ($item['thr-parent'] !== $item['uri']))) {
2077 $parent = q("SELECT `guid`, `author-link`, `owner-link` FROM `item` WHERE `id` = %d", intval($item["parent"]));
2078 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
2080 $thrparent = q("SELECT `guid`, `author-link`, `owner-link`, `plink` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
2081 intval($owner["uid"]),
2082 dbesc($parent_item));
2084 $mentioned[$thrparent[0]["author-link"]] = $thrparent[0]["author-link"];
2085 $mentioned[$thrparent[0]["owner-link"]] = $thrparent[0]["owner-link"];
2086 $parent_plink = $thrparent[0]["plink"];
2088 $mentioned[$parent[0]["author-link"]] = $parent[0]["author-link"];
2089 $mentioned[$parent[0]["owner-link"]] = $parent[0]["owner-link"];
2090 $parent_plink = App::get_baseurl()."/display/".$parent[0]["guid"];
2093 $attributes = array(
2094 "ref" => $parent_item,
2095 "href" => $parent_plink);
2096 xml::add_element($doc, $entry, "thr:in-reply-to", "", $attributes);
2098 $attributes = array(
2100 "href" => $parent_plink);
2101 xml::add_element($doc, $entry, "link", "", $attributes);
2104 if (intval($item["parent"]) > 0) {
2105 $conversation_href = App::get_baseurl()."/display/".$owner["nick"]."/".$item["parent"];
2106 $conversation_uri = $conversation_href;
2108 if (isset($parent_item)) {
2109 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $parent_item);
2110 if (dbm::is_result($r)) {
2111 if ($r['conversation-uri'] != '') {
2112 $conversation_uri = $r['conversation-uri'];
2114 if ($r['conversation-href'] != '') {
2115 $conversation_href = $r['conversation-href'];
2120 xml::add_element($doc, $entry, "link", "", array("rel" => "ostatus:conversation", "href" => $conversation_href));
2122 $attributes = array(
2123 "href" => $conversation_href,
2124 "local_id" => $item["parent"],
2125 "ref" => $conversation_uri);
2127 xml::add_element($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
2130 $tags = item_getfeedtags($item);
2133 foreach($tags as $t)
2135 $mentioned[$t[1]] = $t[1];
2137 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
2138 $newmentions = array();
2139 foreach ($mentioned AS $mention) {
2140 $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
2141 $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
2143 $mentioned = $newmentions;
2145 foreach ($mentioned AS $mention) {
2146 $r = q("SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
2147 intval($owner["uid"]),
2148 dbesc(normalise_link($mention)));
2149 if ($r[0]["forum"] OR $r[0]["prv"])
2150 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
2151 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
2152 "href" => $mention));
2154 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
2155 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
2156 "href" => $mention));
2159 if (!$item["private"]) {
2160 xml::add_element($doc, $entry, "link", "", array("rel" => "ostatus:attention",
2161 "href" => "http://activityschema.org/collection/public"));
2162 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
2163 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
2164 "href" => "http://activityschema.org/collection/public"));
2165 xml::add_element($doc, $entry, "mastodon:scope", "public");
2169 foreach($tags as $t)
2171 xml::add_element($doc, $entry, "category", "", array("term" => $t[2]));
2173 self::get_attachment($doc, $entry, $item);
2175 if ($complete AND ($item["id"] > 0)) {
2176 $app = $item["app"];
2180 $attributes = array("local_id" => $item["id"], "source" => $app);
2182 if (isset($parent["id"]))
2183 $attributes["repeat_of"] = $parent["id"];
2185 if ($item["coord"] != "")
2186 xml::add_element($doc, $entry, "georss:point", $item["coord"]);
2188 xml::add_element($doc, $entry, "statusnet:notice_info", "", $attributes);
2193 * @brief Creates the XML feed for a given nickname
2195 * @param app $a The application class
2196 * @param string $owner_nick Nickname of the feed owner
2197 * @param string $last_update Date of the last update
2199 * @return string XML feed
2201 public static function feed(App $a, $owner_nick, $last_update) {
2203 $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`
2204 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
2205 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
2206 dbesc($owner_nick));
2212 if(!strlen($last_update))
2213 $last_update = 'now -30 days';
2215 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
2216 $authorid = get_contact($owner["url"], 0);
2218 $items = q("SELECT `item`.*, `item`.`id` AS `item_id` FROM `item` USE INDEX (`uid_contactid_created`)
2219 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `item`.`parent`
2220 WHERE `item`.`uid` = %d AND `item`.`contact-id` = %d AND
2221 `item`.`author-id` = %d AND `item`.`created` > '%s' AND
2222 NOT `item`.`deleted` AND NOT `item`.`private` AND
2223 `thread`.`network` IN ('%s', '%s')
2224 ORDER BY `item`.`created` DESC LIMIT 300",
2225 intval($owner["uid"]), intval($owner["id"]),
2226 intval($authorid), dbesc($check_date),
2227 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
2229 /* 2016-10-23: The old query will be kept until we are sure that the query above is a good and fast replacement
2231 $items = q("SELECT `item`.*, `item`.`id` AS `item_id` FROM `item`
2232 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `item`.`parent`
2233 LEFT JOIN `item` AS `thritem` ON `thritem`.`uri`=`item`.`thr-parent` AND `thritem`.`uid`=`item`.`uid`
2234 WHERE `item`.`uid` = %d AND `item`.`received` > '%s' AND NOT `item`.`private` AND NOT `item`.`deleted`
2235 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
2236 AND ((`item`.`wall` AND (`item`.`parent` = `item`.`id`))
2237 OR (`item`.`network` = '%s' AND ((`thread`.`network` IN ('%s', '%s')) OR (`thritem`.`network` IN ('%s', '%s')))) AND `thread`.`mention`)
2238 AND ((`item`.`owner-link` IN ('%s', '%s') AND (`item`.`parent` = `item`.`id`))
2239 OR (`item`.`author-link` IN ('%s', '%s')))
2240 ORDER BY `item`.`id` DESC
2242 intval($owner["uid"]), dbesc($check_date), dbesc(NETWORK_DFRN),
2243 //dbesc(NETWORK_OSTATUS), dbesc(NETWORK_OSTATUS),
2244 //dbesc(NETWORK_OSTATUS), dbesc(NETWORK_OSTATUS),
2245 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN),
2246 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN),
2247 dbesc($owner["nurl"]), dbesc(str_replace("http://", "https://", $owner["nurl"])),
2248 dbesc($owner["nurl"]), dbesc(str_replace("http://", "https://", $owner["nurl"]))
2251 $doc = new DOMDocument('1.0', 'utf-8');
2252 $doc->formatOutput = true;
2254 $root = self::add_header($doc, $owner);
2256 foreach ($items AS $item) {
2257 if (Config::get('system', 'ostatus_debug')) {
2258 $item['body'] .= '🍼';
2260 $entry = self::entry($doc, $item, $owner);
2261 $root->appendChild($entry);
2264 return(trim($doc->saveXML()));
2268 * @brief Creates the XML for a salmon message
2270 * @param array $item Data of the item that is to be posted
2271 * @param array $owner Contact data of the poster
2273 * @return string XML for the salmon
2275 public static function salmon($item,$owner) {
2277 $doc = new DOMDocument('1.0', 'utf-8');
2278 $doc->formatOutput = true;
2280 if (Config::get('system', 'ostatus_debug')) {
2281 $item['body'] .= '🐟';
2284 $entry = self::entry($doc, $item, $owner, true);
2286 $doc->appendChild($entry);
2288 return(trim($doc->saveXML()));