3 * @file include/ostatus.php
7 use Friendica\Core\Config;
8 use Friendica\Network\Probe;
10 require_once 'include/Contact.php';
11 require_once 'include/threads.php';
12 require_once 'include/html2bbcode.php';
13 require_once 'include/bbcode.php';
14 require_once 'include/items.php';
15 require_once 'mod/share.php';
16 require_once 'include/enotify.php';
17 require_once 'include/socgraph.php';
18 require_once 'include/Photo.php';
19 require_once 'include/probe.php';
20 require_once 'include/follow.php';
21 require_once 'include/api.php';
22 require_once 'mod/proxy.php';
23 require_once 'include/xml.php';
26 * @brief This class contain functions for the OStatus protocol
30 const OSTATUS_DEFAULT_POLL_INTERVAL = 30; // given in minutes
31 const OSTATUS_DEFAULT_POLL_TIMEFRAME = 1440; // given in minutes
32 const OSTATUS_DEFAULT_POLL_TIMEFRAME_MENTIONS = 14400; // given in minutes
35 * @brief Fetches author data
37 * @param object $xpath The xpath object
38 * @param object $context The xml context of the author detals
39 * @param array $importer user record of the importing user
40 * @param array $contact Called by reference, will contain the fetched contact
41 * @param bool $onlyfetch Only fetch the header without updating the contact entries
43 * @return array Array of author related entries for the item
45 private function fetchauthor($xpath, $context, $importer, &$contact, $onlyfetch) {
48 $author["author-link"] = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
49 $author["author-name"] = $xpath->evaluate('atom:author/atom:name/text()', $context)->item(0)->nodeValue;
50 $addr = $xpath->evaluate('atom:author/atom:email/text()', $context)->item(0)->nodeValue;
52 $aliaslink = $author["author-link"];
54 $alternate = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0)->attributes;
55 if (is_object($alternate)) {
56 foreach ($alternate AS $attributes) {
57 if (($attributes->name == "href") AND ($attributes->textContent != "")) {
58 $author["author-link"] = $attributes->textContent;
63 $author["contact-id"] = $contact["id"];
65 if ($author["author-link"] != "") {
66 if ($aliaslink == "") {
67 $aliaslink = $author["author-link"];
70 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` IN ('%s', '%s') AND `network` != '%s'",
71 intval($importer["uid"]), dbesc(normalise_link($author["author-link"])),
72 dbesc(normalise_link($aliaslink)), dbesc(NETWORK_STATUSNET));
73 if (dbm::is_result($r)) {
75 $author["contact-id"] = $r[0]["id"];
76 $author["author-link"] = $r[0]["url"];
78 } elseif ($addr != "") {
80 $contact = dba::fetch_first("SELECT * FROM `contact` WHERE `uid` = ? AND `addr` = ? AND `network` != ?",
81 $importer["uid"], $addr, NETWORK_STATUSNET);
82 if (dbm::is_result($contact)) {
83 $author["contact-id"] = $contact["id"];
84 $author["author-link"] = $contact["url"];
88 $avatarlist = array();
89 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
90 foreach($avatars AS $avatar) {
93 foreach($avatar->attributes AS $attributes) {
94 if ($attributes->name == "href")
95 $href = $attributes->textContent;
96 if ($attributes->name == "width")
97 $width = $attributes->textContent;
99 if (($width > 0) AND ($href != ""))
100 $avatarlist[$width] = $href;
102 if (count($avatarlist) > 0) {
104 $author["author-avatar"] = Probe::fix_avatar(current($avatarlist), $author["author-link"]);
107 $displayname = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
108 if ($displayname != "")
109 $author["author-name"] = $displayname;
111 $author["owner-name"] = $author["author-name"];
112 $author["owner-link"] = $author["author-link"];
113 $author["owner-avatar"] = $author["author-avatar"];
115 // Only update the contacts if it is an OStatus contact
116 if ($r AND !$onlyfetch AND ($contact["network"] == NETWORK_OSTATUS)) {
118 // Update contact data
120 // This query doesn't seem to work
121 // $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
123 // $contact["notify"] = $value;
125 // This query doesn't seem to work as well - I hate these queries
126 // $value = $xpath->query("atom:link[@rel='self' and @type='application/atom+xml']", $context)->item(0)->nodeValue;
128 // $contact["poll"] = $value;
130 $value = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
132 $contact["alias"] = $value;
134 $value = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
136 $contact["name"] = $value;
138 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
140 $contact["nick"] = $value;
142 $value = $xpath->evaluate('atom:author/poco:note/text()', $context)->item(0)->nodeValue;
144 $contact["about"] = html2bbcode($value);
146 $value = $xpath->evaluate('atom:author/poco:address/poco:formatted/text()', $context)->item(0)->nodeValue;
148 $contact["location"] = $value;
150 if (($contact["name"] != $r[0]["name"]) OR ($contact["nick"] != $r[0]["nick"]) OR ($contact["about"] != $r[0]["about"]) OR
151 ($contact["alias"] != $r[0]["alias"]) OR ($contact["location"] != $r[0]["location"])) {
153 logger("Update contact data for contact ".$contact["id"], LOGGER_DEBUG);
155 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `alias` = '%s', `about` = '%s', `location` = '%s', `name-date` = '%s' WHERE `id` = %d",
156 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["alias"]),
157 dbesc($contact["about"]), dbesc($contact["location"]),
158 dbesc(datetime_convert()), intval($contact["id"]));
161 if (isset($author["author-avatar"]) AND ($author["author-avatar"] != $r[0]['avatar'])) {
162 logger("Update profile picture for contact ".$contact["id"], LOGGER_DEBUG);
164 update_contact_avatar($author["author-avatar"], $importer["uid"], $contact["id"]);
167 // Ensure that we are having this contact (with uid=0)
168 $cid = get_contact($author["author-link"], 0);
171 // Update it with the current values
172 q("UPDATE `contact` SET `url` = '%s', `name` = '%s', `nick` = '%s', `alias` = '%s',
173 `about` = '%s', `location` = '%s',
174 `success_update` = '%s', `last-update` = '%s'
176 dbesc($author["author-link"]), dbesc($contact["name"]), dbesc($contact["nick"]),
177 dbesc($contact["alias"]), dbesc($contact["about"]), dbesc($contact["location"]),
178 dbesc(datetime_convert()), dbesc(datetime_convert()), intval($cid));
181 update_contact_avatar($author["author-avatar"], 0, $cid);
184 $contact["generation"] = 2;
185 $contact["hide"] = false; // OStatus contacts are never hidden
186 $contact["photo"] = $author["author-avatar"];
187 $gcid = update_gcontact($contact);
189 link_gcontact($gcid, $contact["uid"], $contact["id"]);
196 * @brief Fetches author data from a given XML string
198 * @param string $xml The XML
199 * @param array $importer user record of the importing user
201 * @return array Array of author related entries for the item
203 public static function salmon_author($xml, $importer) {
208 $doc = new DOMDocument();
209 @$doc->loadXML($xml);
211 $xpath = new DomXPath($doc);
212 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
213 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
214 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
215 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
216 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
217 $xpath->registerNamespace('poco', NAMESPACE_POCO);
218 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
219 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
221 $entries = $xpath->query('/atom:entry');
223 foreach ($entries AS $entry) {
225 $author = self::fetchauthor($xpath, $entry, $importer, $contact, true);
231 * @brief Read attributes from element
233 * @param object $element Element object
235 * @return array attributes
237 private static function read_attributes($element) {
238 $attribute = array();
240 foreach ($element->attributes AS $attributes) {
241 $attribute[$attributes->name] = $attributes->textContent;
248 * @brief Imports an XML string containing OStatus elements
250 * @param string $xml The XML
251 * @param array $importer user record of the importing user
253 * @param array $hub Called by reference, returns the fetched hub data
255 public static function import($xml,$importer,&$contact, &$hub) {
256 /// @todo this function is too long. It has to be split in many parts
258 logger("Import OStatus message", LOGGER_DEBUG);
263 //$tempfile = tempnam(get_temppath(), "import");
264 //file_put_contents($tempfile, $xml);
266 $doc = new DOMDocument();
267 @$doc->loadXML($xml);
269 $xpath = new DomXPath($doc);
270 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
271 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
272 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
273 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
274 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
275 $xpath->registerNamespace('poco', NAMESPACE_POCO);
276 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
277 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
280 $hub_attributes = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0)->attributes;
281 if (is_object($hub_attributes)) {
282 foreach ($hub_attributes AS $hub_attribute) {
283 if ($hub_attribute->name == "href") {
284 $hub = $hub_attribute->textContent;
285 logger("Found hub ".$hub, LOGGER_DEBUG);
290 $header["uid"] = $importer["uid"];
291 $header["network"] = NETWORK_OSTATUS;
292 $header["type"] = "remote";
294 $header["origin"] = 0;
295 $header["gravity"] = GRAVITY_PARENT;
297 // it could either be a received post or a post we fetched by ourselves
298 // depending on that, the first node is different
299 $first_child = $doc->firstChild->tagName;
301 if ($first_child == "feed") {
302 $entries = $xpath->query('/atom:feed/atom:entry');
303 $header["protocol"] = PROTOCOL_OSTATUS_FEED;
305 $entries = $xpath->query('/atom:entry');
306 $header["protocol"] = PROTOCOL_OSTATUS_SALMON;
309 $conversationlist = array();
312 // Reverse the order of the entries
313 $entrylist = array();
315 foreach ($entries AS $entry) {
316 $entrylist[] = $entry;
318 foreach (array_reverse($entrylist) AS $entry) {
323 if ($first_child == "feed") {
324 $author = self::fetchauthor($xpath, $doc->firstChild, $importer, $contact, false);
326 $author = self::fetchauthor($xpath, $entry, $importer, $contact, false);
328 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
332 $nickname = $author["author-name"];
334 $item = array_merge($header, $author);
337 $item["uri"] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
339 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
340 intval($importer["uid"]), dbesc($item["uri"]));
341 if (dbm::is_result($r)) {
342 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already existed under id ".$r[0]["id"], LOGGER_DEBUG);
346 $item["body"] = add_page_info_to_body(html2bbcode($xpath->query('atom:content/text()', $entry)->item(0)->nodeValue));
347 $item["object-type"] = $xpath->query('activity:object-type/text()', $entry)->item(0)->nodeValue;
348 $item["verb"] = $xpath->query('activity:verb/text()', $entry)->item(0)->nodeValue;
350 // Mastodon Content Warning
351 if (($item["verb"] == ACTIVITY_POST) AND $xpath->evaluate('boolean(atom:summary)', $entry)) {
352 $clear_text = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
354 $item["body"] = html2bbcode($clear_text) . '[spoiler]' . $item["body"] . '[/spoiler]';
357 if (($item["object-type"] == ACTIVITY_OBJ_BOOKMARK) OR ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
358 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
359 $item["body"] = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
360 } elseif ($item["object-type"] == ACTIVITY_OBJ_QUESTION) {
361 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
363 $item["source"] = $xml;
367 if ($item["verb"] == "qvitter-delete-notice" || $item["verb"] == ACTIVITY_DELETE) {
368 // ignore "Delete" messages (by now)
369 logger("Ignore delete message ".print_r($item, true));
373 if ($item["verb"] == ACTIVITY_JOIN) {
374 // ignore "Join" messages
375 logger("Ignore join message ".print_r($item, true));
379 if ($item["verb"] == ACTIVITY_FOLLOW) {
380 new_follower($importer, $contact, $item, $nickname);
384 if ($item["verb"] == NAMESPACE_OSTATUS."/unfollow") {
385 lose_follower($importer, $contact, $item, $dummy);
389 if ($item["verb"] == ACTIVITY_FAVORITE) {
390 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
391 logger("Favorite ".$orig_uri." ".print_r($item, true));
393 $item["verb"] = ACTIVITY_LIKE;
394 $item["parent-uri"] = $orig_uri;
395 $item["gravity"] = GRAVITY_LIKE;
398 if ($item["verb"] == NAMESPACE_OSTATUS."/unfavorite") {
399 // Ignore "Unfavorite" message
400 logger("Ignore unfavorite message ".print_r($item, true));
404 // http://activitystrea.ms/schema/1.0/rsvp-yes
405 if (!in_array($item["verb"], array(ACTIVITY_POST, ACTIVITY_LIKE, ACTIVITY_SHARE))) {
406 logger("Unhandled verb ".$item["verb"]." ".print_r($item, true));
408 $item["created"] = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
409 $item["edited"] = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
410 $conversation = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
411 $item['conversation-uri'] = $conversation;
413 $conv = $xpath->query('ostatus:conversation', $entry);
414 if (is_object($conv->item(0))) {
415 foreach ($conv->item(0)->attributes AS $attributes) {
416 if ($attributes->name == "ref") {
417 $item['conversation-uri'] = $attributes->textContent;
419 if ($attributes->name == "href") {
420 $item['conversation-href'] = $attributes->textContent;
427 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
428 if (is_object($inreplyto->item(0))) {
429 foreach ($inreplyto->item(0)->attributes AS $attributes) {
430 if ($attributes->name == "ref") {
431 $item["parent-uri"] = $attributes->textContent;
433 if ($attributes->name == "href") {
434 $related = $attributes->textContent;
439 $georsspoint = $xpath->query('georss:point', $entry);
441 $item["coord"] = $georsspoint->item(0)->nodeValue;
443 $categories = $xpath->query('atom:category', $entry);
445 foreach ($categories AS $category) {
446 foreach ($category->attributes AS $attributes) {
447 if ($attributes->name == "term") {
448 $term = $attributes->textContent;
449 if(strlen($item["tag"])) {
452 $item["tag"] .= "#[url=".App::get_baseurl()."/search?tag=".$term."]".$term."[/url]";
461 $links = $xpath->query('atom:link', $entry);
463 foreach ($links AS $link) {
464 $attribute = self::read_attributes($link);
466 if (($attribute['rel'] != "") AND ($attribute['href'] != "")) {
467 switch ($attribute['rel']) {
469 $item["plink"] = $attribute['href'];
470 if (($item["object-type"] == ACTIVITY_OBJ_QUESTION) OR
471 ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
472 $item["body"] .= add_page_info($attribute['href']);
475 case "ostatus:conversation":
476 $conversation = $attribute['href'];
477 $item['conversation-href'] = $conversation;
478 if (!isset($item['conversation-uri'])) {
479 $item['conversation-uri'] = $item['conversation-href'];
483 $enclosure = $attribute['href'];
484 if (strlen($item["attach"])) {
485 $item["attach"] .= ',';
487 if (!isset($attribute['length'])) {
488 $attribute['length'] = "0";
490 $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.$attribute['title'].'"[/attach]';
493 if ($item["object-type"] != ACTIVITY_OBJ_BOOKMARK) {
494 if (!isset($item["parent-uri"])) {
495 $item["parent-uri"] = $attribute['href'];
497 if ($related == "") {
498 $related = $attribute['href'];
501 $item["body"] .= add_page_info($attribute['href']);
505 $self = $attribute['href'];
508 // Notification check
509 if ($importer["nurl"] == normalise_link($attribute['href'])) {
521 $notice_info = $xpath->query('statusnet:notice_info', $entry);
522 if ($notice_info AND ($notice_info->length > 0)) {
523 foreach ($notice_info->item(0)->attributes AS $attributes) {
524 if ($attributes->name == "source") {
525 $item["app"] = strip_tags($attributes->textContent);
527 if ($attributes->name == "local_id") {
528 $local_id = $attributes->textContent;
530 if ($attributes->name == "repeat_of") {
531 $repeat_of = $attributes->textContent;
536 // Is it a repeated post?
537 if (($repeat_of != "") OR ($item["verb"] == ACTIVITY_SHARE)) {
538 $activityobjects = $xpath->query('activity:object', $entry)->item(0);
540 if (is_object($activityobjects)) {
542 $orig_uri = $xpath->query("activity:object/atom:id", $activityobjects)->item(0)->nodeValue;
543 if (!isset($orig_uri)) {
544 $orig_uri = $xpath->query('atom:id/text()', $activityobjects)->item(0)->nodeValue;
546 $orig_links = $xpath->query("activity:object/atom:link[@rel='alternate']", $activityobjects);
547 if ($orig_links AND ($orig_links->length > 0)) {
548 foreach ($orig_links->item(0)->attributes AS $attributes) {
549 if ($attributes->name == "href") {
550 $orig_link = $attributes->textContent;
554 if (!isset($orig_link)) {
555 $orig_link = $xpath->query("atom:link[@rel='alternate']", $activityobjects)->item(0)->nodeValue;
557 if (!isset($orig_link)) {
558 $orig_link = self::convert_href($orig_uri);
560 $orig_body = $xpath->query('activity:object/atom:content/text()', $activityobjects)->item(0)->nodeValue;
561 if (!isset($orig_body)) {
562 $orig_body = $xpath->query('atom:content/text()', $activityobjects)->item(0)->nodeValue;
564 $orig_created = $xpath->query('atom:published/text()', $activityobjects)->item(0)->nodeValue;
565 $orig_edited = $xpath->query('atom:updated/text()', $activityobjects)->item(0)->nodeValue;
567 $orig_contact = $contact;
568 $orig_author = self::fetchauthor($xpath, $activityobjects, $importer, $orig_contact, false);
570 $item["author-name"] = $orig_author["author-name"];
571 $item["author-link"] = $orig_author["author-link"];
572 $item["author-avatar"] = $orig_author["author-avatar"];
574 $item["body"] = add_page_info_to_body(html2bbcode($orig_body));
575 $item["created"] = $orig_created;
576 $item["edited"] = $orig_edited;
578 $item["uri"] = $orig_uri;
580 if (!isset($item["plink"])) {
581 $item["plink"] = $orig_link;
584 $item["verb"] = $xpath->query('activity:verb/text()', $activityobjects)->item(0)->nodeValue;
586 $item["object-type"] = $xpath->query('activity:object/activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
587 if (!isset($item["object-type"])) {
588 $item["object-type"] = $xpath->query('activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
591 $enclosures = $xpath->query("atom:link[@rel='alternate']", $activityobjects);
593 foreach ($enclosures AS $link) {
594 $attribute = self::read_attributes($link);
596 $enclosure = $attribute['href'];
597 if (strlen($item["attach"])) {
598 $item["attach"] .= ',';
600 if (!isset($attribute['length'])) {
601 $attribute['length'] = "0";
603 $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.$attribute['title'].'"[/attach]';
610 //if ($enclosure != "")
611 // $item["body"] .= add_page_info($enclosure);
613 if (isset($item["parent-uri"])) {
614 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
615 intval($importer["uid"]), dbesc($item["parent-uri"]));
617 // Only fetch missing stuff if it is a comment or reshare.
618 if (in_array($item["verb"], array(ACTIVITY_POST, ACTIVITY_SHARE)) AND
619 !dbm::is_result($r) AND ($related != "")) {
620 $reply_path = str_replace("/notice/", "/api/statuses/show/", $related).".atom";
622 if ($reply_path != $related) {
623 logger("Fetching related items for user ".$importer["uid"]." from ".$reply_path, LOGGER_DEBUG);
624 $reply_xml = fetch_url($reply_path);
626 $reply_contact = $contact;
627 self::import($reply_xml,$importer,$reply_contact, $reply_hub);
629 // After the import try to fetch the parent item again
630 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
631 intval($importer["uid"]), dbesc($item["parent-uri"]));
634 if (dbm::is_result($r)) {
635 $item["type"] = 'remote-comment';
636 $item["gravity"] = GRAVITY_COMMENT;
639 $item["parent-uri"] = $item["uri"];
641 $item_id = self::completion($conversation, $importer["uid"], $item, $self);
644 logger("Error storing item", LOGGER_DEBUG);
648 logger("Item was stored with id ".$item_id, LOGGER_DEBUG);
653 * @brief Create an url out of an uri
655 * @param string $href URI in the format "parameter1:parameter1:..."
657 * @return string URL in the format http(s)://....
659 public static function convert_href($href) {
660 $elements = explode(":",$href);
662 if ((count($elements) <= 2) OR ($elements[0] != "tag"))
665 $server = explode(",", $elements[1]);
666 $conversation = explode("=", $elements[2]);
668 if ((count($elements) == 4) AND ($elements[2] == "post"))
669 return "http://".$server[0]."/notice/".$elements[3];
671 if ((count($conversation) != 2) OR ($conversation[1] ==""))
674 if ($elements[3] == "objectType=thread")
675 return "http://".$server[0]."/conversation/".$conversation[1];
677 return "http://".$server[0]."/notice/".$conversation[1];
683 * @brief Checks if there are entries in conversations that aren't present on our side
685 * @param bool $mentions Fetch conversations where we are mentioned
686 * @param bool $override Override the interval setting
688 public static function check_conversations($mentions = false, $override = false) {
689 $last = get_config('system','ostatus_last_poll');
691 $poll_interval = intval(get_config('system','ostatus_poll_interval'));
692 if (!$poll_interval) {
693 $poll_interval = self::OSTATUS_DEFAULT_POLL_INTERVAL;
696 // Don't poll if the interval is set negative
697 if (($poll_interval < 0) AND !$override) {
702 $poll_timeframe = intval(get_config('system','ostatus_poll_timeframe'));
703 if (!$poll_timeframe) {
704 $poll_timeframe = self::OSTATUS_DEFAULT_POLL_TIMEFRAME;
707 $poll_timeframe = intval(get_config('system','ostatus_poll_timeframe'));
708 if (!$poll_timeframe) {
709 $poll_timeframe = self::OSTATUS_DEFAULT_POLL_TIMEFRAME_MENTIONS;
714 if ($last AND !$override) {
715 $next = $last + ($poll_interval * 60);
716 if ($next > time()) {
717 logger('poll interval not reached');
722 logger('cron_start');
724 $start = date("Y-m-d H:i:s", time() - ($poll_timeframe * 60));
727 $conversations = q("SELECT `term`.`oid`, `term`.`url`, `term`.`uid` FROM `term`
728 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `term`.`oid` AND `thread`.`uid` = `term`.`uid`
729 WHERE `term`.`type` = 7 AND `term`.`term` > '%s' AND `thread`.`mention`
730 GROUP BY `term`.`url`, `term`.`uid`, `term`.`oid`, `term`.`term` ORDER BY `term`.`term` DESC", dbesc($start));
732 $conversations = q("SELECT `oid`, `url`, `uid` FROM `term`
733 WHERE `type` = 7 AND `term` > '%s'
734 GROUP BY `url`, `uid`, `oid`, `term` ORDER BY `term` DESC", dbesc($start));
737 foreach ($conversations AS $conversation) {
738 self::completion($conversation['url'], $conversation['uid']);
743 set_config('system','ostatus_last_poll', time());
747 * @brief Updates the gcontact table with actor data from the conversation
749 * @param object $actor The actor object that contains the contact data
751 private function conv_fetch_actor($actor) {
753 // We set the generation to "3" since the data here is not as reliable as the data we get on other occasions
754 $contact = array("network" => NETWORK_OSTATUS, "generation" => 3);
756 if (isset($actor->url))
757 $contact["url"] = $actor->url;
759 if (isset($actor->displayName))
760 $contact["name"] = $actor->displayName;
762 if (isset($actor->portablecontacts_net->displayName))
763 $contact["name"] = $actor->portablecontacts_net->displayName;
765 if (isset($actor->portablecontacts_net->preferredUsername))
766 $contact["nick"] = $actor->portablecontacts_net->preferredUsername;
768 if (isset($actor->id))
769 $contact["alias"] = $actor->id;
771 if (isset($actor->summary))
772 $contact["about"] = $actor->summary;
774 if (isset($actor->portablecontacts_net->note))
775 $contact["about"] = $actor->portablecontacts_net->note;
777 if (isset($actor->portablecontacts_net->addresses->formatted))
778 $contact["location"] = $actor->portablecontacts_net->addresses->formatted;
781 if (isset($actor->image->url))
782 $contact["photo"] = $actor->image->url;
784 if (isset($actor->image->width))
785 $avatarwidth = $actor->image->width;
787 if (is_array($actor->status_net->avatarLinks))
788 foreach ($actor->status_net->avatarLinks AS $avatar) {
789 if ($avatarsize < $avatar->width) {
790 $contact["photo"] = $avatar->url;
791 $avatarsize = $avatar->width;
795 $contact["hide"] = false; // OStatus contacts are never hidden
796 update_gcontact($contact);
800 * @brief Fetches the conversation url for a given item link or conversation id
802 * @param string $self The link to the posting
803 * @param string $conversation_id The conversation id
805 * @return string The conversation url
807 private function fetch_conversation($self, $conversation_id = "") {
809 if ($conversation_id != "") {
810 $elements = explode(":", $conversation_id);
812 if ((count($elements) <= 2) OR ($elements[0] != "tag"))
813 return $conversation_id;
819 $json = str_replace(".atom", ".json", $self);
821 $raw = fetch_url($json);
825 $data = json_decode($raw);
826 if (!is_object($data))
829 $conversation_id = $data->statusnet_conversation_id;
831 $pos = strpos($self, "/api/statuses/show/");
832 $base_url = substr($self, 0, $pos);
834 return $base_url."/conversation/".$conversation_id;
838 * @brief Fetches actor details of a given actor and user id
840 * @param string $actor The actor url
841 * @param int $uid The user id
842 * @param int $contact_id The default contact-id
844 * @return array Array with actor details
846 private function get_actor_details($actor, $uid, $contact_id) {
850 $contact = q("SELECT `id`, `rel`, `network` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'",
851 $uid, normalise_link($actor), NETWORK_STATUSNET);
854 $contact = q("SELECT `id`, `rel`, `network` FROM `contact` WHERE `uid` = %d AND `alias` IN ('%s', '%s') AND `network` != '%s'",
855 $uid, $actor, normalise_link($actor), NETWORK_STATUSNET);
858 logger("Found contact for url ".$actor, LOGGER_DEBUG);
859 $details["contact_id"] = $contact[0]["id"];
860 $details["network"] = $contact[0]["network"];
862 $details["not_following"] = !in_array($contact[0]["rel"], array(CONTACT_IS_SHARING, CONTACT_IS_FRIEND));
864 logger("No contact found for user ".$uid." and url ".$actor, LOGGER_DEBUG);
866 // Adding a global contact
867 /// @TODO Use this data for the post
868 $details["global_contact_id"] = get_contact($actor, 0);
870 logger("Global contact ".$global_contact_id." found for url ".$actor, LOGGER_DEBUG);
872 $details["contact_id"] = $contact_id;
873 $details["network"] = NETWORK_OSTATUS;
875 $details["not_following"] = true;
882 * @brief Stores an item and completes the thread
884 * @param string $conversation_url The URI of the conversation
885 * @param integer $uid The user id
886 * @param array $item Data of the item that is to be posted
888 * @return integer The item id of the posted item array
890 private function completion($conversation_url, $uid, $item = array(), $self = "") {
892 /// @todo This function is totally ugly and has to be rewritten totally
894 // Import all threads or only threads that were started by our followers?
895 $all_threads = !get_config('system','ostatus_full_threads');
899 $conversation_url = self::fetch_conversation($self, $conversation_url);
901 // If the thread shouldn't be completed then store the item and go away
902 // Don't do a completion on liked content
903 if (((intval(get_config('system','ostatus_poll_interval')) == -2) AND (count($item) > 0)) OR
904 ($item["verb"] == ACTIVITY_LIKE) OR ($conversation_url == "")) {
905 $item_stored = item_store($item, $all_threads);
907 } elseif (count($item) > 0) {
908 $item = store_conversation($item);
912 $parents = q("SELECT `item`.`id`, `item`.`parent`, `item`.`uri`, `item`.`contact-id`, `item`.`type`,
913 `item`.`verb`, `item`.`visible` FROM `term`
914 STRAIGHT_JOIN `item` AS `thritem` ON `thritem`.`parent` = `term`.`oid`
915 STRAIGHT_JOIN `item` ON `item`.`parent` = `thritem`.`parent`
916 WHERE `term`.`uid` = %d AND `term`.`otype` = %d AND `term`.`type` = %d AND `term`.`url` = '%s'",
917 intval($uid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION), dbesc($conversation_url));
919 /* 2016-10-23: The old query will be kept until we are sure that the query above is a good and fast replacement
921 $parents = q("SELECT `id`, `parent`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `id` IN
922 (SELECT `parent` FROM `item` WHERE `id` IN
923 (SELECT `oid` FROM `term` WHERE `uid` = %d AND `otype` = %d AND `type` = %d AND `url` = '%s'))",
924 intval($uid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION), dbesc($conversation_url));
927 $parent = $parents[0];
928 elseif (count($item) > 0) {
930 $parent["type"] = "remote";
931 $parent["verb"] = ACTIVITY_POST;
932 $parent["visible"] = 1;
935 $r = q("SELECT `id` FROM `contact` WHERE `self` AND `uid`=%d", $uid);
941 $parent["parent"] = 0;
943 $parent["contact-id"] = $r[0]["id"];
944 $parent["type"] = "remote";
945 $parent["verb"] = ACTIVITY_POST;
946 $parent["visible"] = 1;
949 $conv = str_replace("/conversation/", "/api/statusnet/conversation/", $conversation_url).".as";
953 logger('fetching conversation url '.$conv.' (Self: '.$self.') for user '.$uid);
956 $conv_arr = z_fetch_url($conv."?page=".$pageno);
958 // If it is a non-ssl site and there is an error, then try ssl or vice versa
959 if (!$conv_arr["success"] AND (substr($conv, 0, 7) == "http://")) {
960 $conv = str_replace("http://", "https://", $conv);
961 $conv_as = fetch_url($conv."?page=".$pageno);
962 } elseif (!$conv_arr["success"] AND (substr($conv, 0, 8) == "https://")) {
963 $conv = str_replace("https://", "http://", $conv);
964 $conv_as = fetch_url($conv."?page=".$pageno);
966 $conv_as = $conv_arr["body"];
968 $conv_as = str_replace(',"statusnet:notice_info":', ',"statusnet_notice_info":', $conv_as);
969 $conv_as = json_decode($conv_as);
971 $no_of_items = sizeof($items);
973 if (@is_array($conv_as->items))
974 foreach ($conv_as->items AS $single_item)
975 $items[$single_item->id] = $single_item;
977 if ($no_of_items == sizeof($items))
984 logger('fetching conversation done. Found '.count($items).' items');
986 if (!sizeof($items)) {
987 if (count($item) > 0) {
988 $item_stored = item_store($item, $all_threads);
991 logger("Conversation ".$conversation_url." couldn't be fetched. Item uri ".$item["uri"]." stored: ".$item_stored, LOGGER_DEBUG);
992 self::store_conversation($item_id, $conversation_url);
995 return($item_stored);
1000 $items = array_reverse($items);
1002 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self`", intval($uid));
1007 foreach ($items as $single_conv) {
1009 // Update the gcontact table
1010 self::conv_fetch_actor($single_conv->actor);
1012 // Test - remove before flight
1013 //$tempfile = tempnam(get_temppath(), "conversation");
1014 //file_put_contents($tempfile, json_encode($single_conv));
1018 if (isset($single_conv->object->id))
1019 $single_conv->id = $single_conv->object->id;
1021 $plink = self::convert_href($single_conv->id);
1022 if (isset($single_conv->object->url))
1023 $plink = self::convert_href($single_conv->object->url);
1025 if (@!$single_conv->id)
1028 logger("Got id ".$single_conv->id, LOGGER_DEBUG);
1030 if ($first_id == "") {
1031 $first_id = $single_conv->id;
1033 // The first post of the conversation isn't our first post. There are three options:
1034 // 1. Our conversation hasn't the "real" thread starter
1035 // 2. This first post is a post inside our thread
1036 // 3. This first post is a post inside another thread
1037 if (($first_id != $parent["uri"]) AND ($parent["uri"] != "")) {
1041 $new_parents = q("SELECT `id`, `parent`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `id` IN
1042 (SELECT `parent` FROM `item`
1043 WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s')) LIMIT 1",
1044 intval($uid), dbesc($first_id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
1046 if ($new_parents[0]["parent"] == $parent["parent"]) {
1047 // Option 2: This post is already present inside our thread - but not as thread starter
1048 logger("Option 2: uri present in our thread: ".$first_id, LOGGER_DEBUG);
1049 $first_id = $parent["uri"];
1051 // Option 3: Not so good. We have mixed parents. We have to see how to clean this up.
1052 // For now just take the new parent.
1053 $parent = $new_parents[0];
1054 $first_id = $parent["uri"];
1055 logger("Option 3: mixed parents for uri ".$first_id, LOGGER_DEBUG);
1058 // Option 1: We hadn't got the real thread starter
1059 // We have to clean up our existing messages.
1061 $parent["uri"] = $first_id;
1062 logger("Option 1: we have a new parent: ".$first_id, LOGGER_DEBUG);
1064 } elseif ($parent["uri"] == "") {
1066 $parent["uri"] = $first_id;
1070 $parent_uri = $parent["uri"];
1072 // "context" only seems to exist on older servers
1073 if (isset($single_conv->context->inReplyTo->id)) {
1074 $parent_exists = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
1075 intval($uid), dbesc($single_conv->context->inReplyTo->id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
1077 $parent_uri = $single_conv->context->inReplyTo->id;
1080 // This is the current way
1081 if (isset($single_conv->object->inReplyTo->id)) {
1082 $parent_exists = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
1083 intval($uid), dbesc($single_conv->object->inReplyTo->id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
1085 $parent_uri = $single_conv->object->inReplyTo->id;
1088 $message_exists = q("SELECT `id`, `parent`, `uri` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
1089 intval($uid), dbesc($single_conv->id),
1090 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
1091 if ($message_exists) {
1092 logger("Message ".$single_conv->id." already existed on the system", LOGGER_DEBUG);
1094 if ($parent["id"] != 0) {
1095 $existing_message = $message_exists[0];
1097 // We improved the way we fetch OStatus messages, this shouldn't happen very often now
1098 /// @TODO We have to change the shadow copies as well. This way here is really ugly.
1099 if ($existing_message["parent"] != $parent["id"]) {
1100 logger('updating id '.$existing_message["id"].' with parent '.$existing_message["parent"].' to parent '.$parent["id"].' uri '.$parent["uri"].' thread '.$parent_uri, LOGGER_DEBUG);
1102 // Update the parent id of the selected item
1103 $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s' WHERE `id` = %d",
1104 intval($parent["id"]), dbesc($parent["uri"]), intval($existing_message["id"]));
1106 // Update the parent uri in the thread - but only if it points to itself
1107 $r = q("UPDATE `item` SET `thr-parent` = '%s' WHERE `id` = %d AND `uri` = `thr-parent`",
1108 dbesc($parent_uri), intval($existing_message["id"]));
1110 // try to change all items of the same parent
1111 $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s' WHERE `parent` = %d",
1112 intval($parent["id"]), dbesc($parent["uri"]), intval($existing_message["parent"]));
1114 // Update the parent uri in the thread - but only if it points to itself
1115 $r = q("UPDATE `item` SET `thr-parent` = '%s' WHERE (`parent` = %d) AND (`uri` = `thr-parent`)",
1116 dbesc($parent["uri"]), intval($existing_message["parent"]));
1118 // Now delete the thread
1119 delete_thread($existing_message["parent"]);
1123 // The item we are having on the system is the one that we wanted to store via the item array
1124 if (isset($item["uri"]) AND ($item["uri"] == $existing_message["uri"])) {
1132 if (is_array($single_conv->to))
1133 foreach($single_conv->to AS $to)
1134 if ($importer["nurl"] == normalise_link($to->id))
1137 $actor = $single_conv->actor->id;
1138 if (isset($single_conv->actor->url))
1139 $actor = $single_conv->actor->url;
1141 $details = self::get_actor_details($actor, $uid, $parent["contact-id"]);
1143 // Do we only want to import threads that were started by our contacts?
1144 if ($details["not_following"] AND $new_parent AND get_config('system','ostatus_full_threads')) {
1145 logger("Don't import uri ".$first_id." because user ".$uid." doesn't follow the person ".$actor, LOGGER_DEBUG);
1150 $arr["network"] = $details["network"];
1151 $arr["uri"] = $single_conv->id;
1152 $arr["plink"] = $plink;
1154 $arr["contact-id"] = $details["contact_id"];
1155 $arr["parent-uri"] = $parent_uri;
1156 $arr["created"] = $single_conv->published;
1157 $arr["edited"] = $single_conv->published;
1158 $arr["owner-name"] = $single_conv->actor->displayName;
1159 if ($arr["owner-name"] == '')
1160 $arr["owner-name"] = $single_conv->actor->contact->displayName;
1161 if ($arr["owner-name"] == '')
1162 $arr["owner-name"] = $single_conv->actor->portablecontacts_net->displayName;
1164 $arr["owner-link"] = $actor;
1165 $arr["owner-avatar"] = Probe::fix_avatar($single_conv->actor->image->url, $arr["owner-link"]);
1167 $arr["author-name"] = $arr["owner-name"];
1168 $arr["author-link"] = $arr["owner-link"];
1169 $arr["author-avatar"] = $arr["owner-avatar"];
1170 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->content));
1172 if (isset($single_conv->status_net->conversation)) {
1173 $arr['conversation-uri'] = $single_conv->status_net->conversation;
1176 if (isset($single_conv->status_net->notice_info->source))
1177 $arr["app"] = strip_tags($single_conv->status_net->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->statusnet_notice_info->source))
1181 $arr["app"] = strip_tags($single_conv->statusnet_notice_info->source);
1182 elseif (isset($single_conv->provider->displayName))
1183 $arr["app"] = $single_conv->provider->displayName;
1185 $arr["app"] = "OStatus";
1188 $arr["source"] = json_encode($single_conv);
1189 $arr["protocol"] = PROTOCOL_GS_CONVERSATION;
1191 $arr["verb"] = $parent["verb"];
1192 $arr["visible"] = $parent["visible"];
1193 $arr["location"] = $single_conv->location->displayName;
1194 $arr["coord"] = trim($single_conv->location->lat." ".$single_conv->location->lon);
1196 // Is it a reshared item?
1197 if (isset($single_conv->verb) AND ($single_conv->verb == "share") AND isset($single_conv->object)) {
1198 if (is_array($single_conv->object))
1199 $single_conv->object = $single_conv->object[0];
1201 logger("Found reshared item ".$single_conv->object->id);
1203 // $single_conv->object->context->conversation;
1205 if (isset($single_conv->object->object->id))
1206 $arr["uri"] = $single_conv->object->object->id;
1208 $arr["uri"] = $single_conv->object->id;
1210 if (isset($single_conv->object->object->url))
1211 $plink = self::convert_href($single_conv->object->object->url);
1213 $plink = self::convert_href($single_conv->object->url);
1215 if (isset($single_conv->object->object->content))
1216 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->object->content));
1218 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->content));
1220 $arr["plink"] = $plink;
1222 $arr["created"] = $single_conv->object->published;
1223 $arr["edited"] = $single_conv->object->published;
1225 $arr["author-name"] = $single_conv->object->actor->displayName;
1226 if ($arr["owner-name"] == '') {
1227 $arr["author-name"] = $single_conv->object->actor->contact->displayName;
1229 $arr["author-link"] = $single_conv->object->actor->url;
1230 $arr["author-avatar"] = Probe::fix_avatar($single_conv->object->actor->image->url, $arr["author-link"]);
1232 $arr["app"] = $single_conv->object->provider->displayName."#";
1233 //$arr["verb"] = $single_conv->object->verb;
1235 $arr["location"] = $single_conv->object->location->displayName;
1236 $arr["coord"] = trim($single_conv->object->location->lat." ".$single_conv->object->location->lon);
1239 if ($arr["location"] == "")
1240 unset($arr["location"]);
1242 if ($arr["coord"] == "")
1243 unset($arr["coord"]);
1245 // Copy fields from given item array
1246 if (isset($item["uri"]) AND (($item["uri"] == $arr["uri"]) OR ($item["uri"] == $single_conv->id))) {
1247 $copy_fields = array("owner-name", "owner-link", "owner-avatar", "author-name", "author-link", "author-avatar",
1248 "gravity", "body", "object-type", "object", "verb", "created", "edited", "coord", "tag",
1249 "title", "attach", "app", "type", "location", "contact-id", "uri");
1250 foreach ($copy_fields AS $field)
1251 if (isset($item[$field]))
1252 $arr[$field] = $item[$field];
1256 $newitem = item_store($arr);
1258 logger("Item wasn't stored ".print_r($arr, true), LOGGER_DEBUG);
1262 if (isset($item["uri"]) AND ($item["uri"] == $arr["uri"])) {
1264 $item_stored = $newitem;
1267 logger('Stored new item '.$plink.' for parent '.$arr["parent-uri"].' under id '.$newitem, LOGGER_DEBUG);
1269 // Add the conversation entry (but don't fetch the whole conversation)
1270 self::store_conversation($newitem, $conversation_url);
1272 // If the newly created item is the top item then change the parent settings of the thread
1273 // This shouldn't happen anymore. This is supposed to be absolote.
1274 if ($arr["uri"] == $first_id) {
1275 logger('setting new parent to id '.$newitem);
1276 $new_parents = q("SELECT `id`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `uid` = %d AND `id` = %d LIMIT 1",
1277 intval($uid), intval($newitem));
1279 $parent = $new_parents[0];
1283 if (($item_stored < 0) AND (count($item) > 0)) {
1285 if (get_config('system','ostatus_full_threads')) {
1286 $details = self::get_actor_details($item["owner-link"], $uid, $item["contact-id"]);
1287 if ($details["not_following"]) {
1288 logger("Don't import uri ".$item["uri"]." because user ".$uid." doesn't follow the person ".$item["owner-link"], LOGGER_DEBUG);
1293 $item_stored = item_store($item, $all_threads);
1295 logger("Uri ".$item["uri"]." wasn't found in conversation ".$conversation_url, LOGGER_DEBUG);
1296 self::store_conversation($item_stored, $conversation_url);
1300 return($item_stored);
1304 * @brief Stores conversation data into the database
1306 * @param integer $itemid The id of the item
1307 * @param string $conversation_url The uri of the conversation
1309 private function store_conversation($itemid, $conversation_url) {
1311 $conversation_url = self::convert_href($conversation_url);
1313 $messages = q("SELECT `uid`, `parent`, `created`, `received`, `guid` FROM `item` WHERE `id` = %d LIMIT 1", intval($itemid));
1316 $message = $messages[0];
1318 // Store conversation url if not done before
1319 $conversation = q("SELECT `url` FROM `term` WHERE `uid` = %d AND `oid` = %d AND `otype` = %d AND `type` = %d",
1320 intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION));
1322 if (!$conversation) {
1323 $r = q("INSERT INTO `term` (`uid`, `oid`, `otype`, `type`, `term`, `url`, `created`, `received`, `guid`) VALUES (%d, %d, %d, %d, '%s', '%s', '%s', '%s', '%s')",
1324 intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION),
1325 dbesc($message["created"]), dbesc($conversation_url), dbesc($message["created"]), dbesc($message["received"]), dbesc($message["guid"]));
1326 logger('Storing conversation url '.$conversation_url.' for id '.$itemid);
1331 * @brief Checks if the current post is a reshare
1333 * @param array $item The item array of thw post
1335 * @return string The guid if the post is a reshare
1337 private function get_reshared_guid($item) {
1338 $body = trim($item["body"]);
1340 // Skip if it isn't a pure repeated messages
1341 // Does it start with a share?
1342 if (strpos($body, "[share") > 0)
1345 // Does it end with a share?
1346 if (strlen($body) > (strrpos($body, "[/share]") + 8))
1349 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
1350 // Skip if there is no shared message in there
1351 if ($body == $attributes)
1355 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
1356 if ($matches[1] != "")
1357 $guid = $matches[1];
1359 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
1360 if ($matches[1] != "")
1361 $guid = $matches[1];
1367 * @brief Cleans the body of a post if it contains picture links
1369 * @param string $body The body
1371 * @return string The cleaned body
1373 private function format_picture_post($body) {
1374 $siteinfo = get_attached_data($body);
1376 if (($siteinfo["type"] == "photo")) {
1377 if (isset($siteinfo["preview"]))
1378 $preview = $siteinfo["preview"];
1380 $preview = $siteinfo["image"];
1382 // Is it a remote picture? Then make a smaller preview here
1383 $preview = proxy_url($preview, false, PROXY_SIZE_SMALL);
1385 // Is it a local picture? Then make it smaller here
1386 $preview = str_replace(array("-0.jpg", "-0.png"), array("-2.jpg", "-2.png"), $preview);
1387 $preview = str_replace(array("-1.jpg", "-1.png"), array("-2.jpg", "-2.png"), $preview);
1389 if (isset($siteinfo["url"]))
1390 $url = $siteinfo["url"];
1392 $url = $siteinfo["image"];
1394 $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1401 * @brief Adds the header elements to the XML document
1403 * @param object $doc XML document
1404 * @param array $owner Contact data of the poster
1406 * @return object header root element
1408 private function add_header($doc, $owner) {
1412 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
1413 $doc->appendChild($root);
1415 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1416 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1417 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1418 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1419 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
1420 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1421 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1422 $root->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1424 $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
1425 xml::add_element($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1426 xml::add_element($doc, $root, "id", App::get_baseurl()."/profile/".$owner["nick"]);
1427 xml::add_element($doc, $root, "title", sprintf("%s timeline", $owner["name"]));
1428 xml::add_element($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], $a->config["sitename"]));
1429 xml::add_element($doc, $root, "logo", $owner["photo"]);
1430 xml::add_element($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
1432 $author = self::add_author($doc, $owner);
1433 $root->appendChild($author);
1435 $attributes = array("href" => $owner["url"], "rel" => "alternate", "type" => "text/html");
1436 xml::add_element($doc, $root, "link", "", $attributes);
1438 /// @TODO We have to find out what this is
1439 /// $attributes = array("href" => App::get_baseurl()."/sup",
1440 /// "rel" => "http://api.friendfeed.com/2008/03#sup",
1441 /// "type" => "application/json");
1442 /// xml::add_element($doc, $root, "link", "", $attributes);
1444 self::hublinks($doc, $root);
1446 $attributes = array("href" => App::get_baseurl()."/salmon/".$owner["nick"], "rel" => "salmon");
1447 xml::add_element($doc, $root, "link", "", $attributes);
1449 $attributes = array("href" => App::get_baseurl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies");
1450 xml::add_element($doc, $root, "link", "", $attributes);
1452 $attributes = array("href" => App::get_baseurl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention");
1453 xml::add_element($doc, $root, "link", "", $attributes);
1455 $attributes = array("href" => App::get_baseurl()."/api/statuses/user_timeline/".$owner["nick"].".atom",
1456 "rel" => "self", "type" => "application/atom+xml");
1457 xml::add_element($doc, $root, "link", "", $attributes);
1463 * @brief Add the link to the push hubs to the XML document
1465 * @param object $doc XML document
1466 * @param object $root XML root element where the hub links are added
1468 public static function hublinks($doc, $root) {
1469 $hub = get_config('system','huburl');
1473 $hubs = explode(',', $hub);
1475 foreach($hubs as $h) {
1479 if ($h === '[internal]')
1480 $h = App::get_baseurl() . '/pubsubhubbub';
1481 xml::add_element($doc, $root, "link", "", array("href" => $h, "rel" => "hub"));
1488 * @brief Adds attachement data to the XML document
1490 * @param object $doc XML document
1491 * @param object $root XML root element where the hub links are added
1492 * @param array $item Data of the item that is to be posted
1494 private function get_attachment($doc, $root, $item) {
1496 $siteinfo = get_attached_data($item["body"]);
1498 switch ($siteinfo["type"]) {
1500 $imgdata = get_photo_info($siteinfo["image"]);
1501 $attributes = array("rel" => "enclosure",
1502 "href" => $siteinfo["image"],
1503 "type" => $imgdata["mime"],
1504 "length" => intval($imgdata["size"]));
1505 xml::add_element($doc, $root, "link", "", $attributes);
1508 $attributes = array("rel" => "enclosure",
1509 "href" => $siteinfo["url"],
1510 "type" => "text/html; charset=UTF-8",
1512 "title" => $siteinfo["title"]);
1513 xml::add_element($doc, $root, "link", "", $attributes);
1519 if (($siteinfo["type"] != "photo") AND isset($siteinfo["image"])) {
1520 $imgdata = get_photo_info($siteinfo["image"]);
1521 $attributes = array("rel" => "enclosure",
1522 "href" => $siteinfo["image"],
1523 "type" => $imgdata["mime"],
1524 "length" => intval($imgdata["size"]));
1526 xml::add_element($doc, $root, "link", "", $attributes);
1529 $arr = explode('[/attach],', $item['attach']);
1531 foreach ($arr as $r) {
1533 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1535 $attributes = array("rel" => "enclosure",
1536 "href" => $matches[1],
1537 "type" => $matches[3]);
1539 if (intval($matches[2])) {
1540 $attributes["length"] = intval($matches[2]);
1542 if (trim($matches[4]) != "") {
1543 $attributes["title"] = trim($matches[4]);
1545 xml::add_element($doc, $root, "link", "", $attributes);
1552 * @brief Adds the author element to the XML document
1554 * @param object $doc XML document
1555 * @param array $owner Contact data of the poster
1557 * @return object author element
1559 private function add_author($doc, $owner) {
1561 $r = q("SELECT `homepage`, `publish` FROM `profile` WHERE `uid` = %d AND `is-default` LIMIT 1", intval($owner["uid"]));
1565 $author = $doc->createElement("author");
1566 xml::add_element($doc, $author, "id", $owner["url"]);
1567 xml::add_element($doc, $author, "activity:object-type", ACTIVITY_OBJ_PERSON);
1568 xml::add_element($doc, $author, "uri", $owner["url"]);
1569 xml::add_element($doc, $author, "name", $owner["nick"]);
1570 xml::add_element($doc, $author, "email", $owner["addr"]);
1571 xml::add_element($doc, $author, "summary", bbcode($owner["about"], false, false, 7));
1573 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $owner["url"]);
1574 xml::add_element($doc, $author, "link", "", $attributes);
1576 $attributes = array(
1578 "type" => "image/jpeg", // To-Do?
1579 "media:width" => 175,
1580 "media:height" => 175,
1581 "href" => $owner["photo"]);
1582 xml::add_element($doc, $author, "link", "", $attributes);
1584 if (isset($owner["thumb"])) {
1585 $attributes = array(
1587 "type" => "image/jpeg", // To-Do?
1588 "media:width" => 80,
1589 "media:height" => 80,
1590 "href" => $owner["thumb"]);
1591 xml::add_element($doc, $author, "link", "", $attributes);
1594 xml::add_element($doc, $author, "poco:preferredUsername", $owner["nick"]);
1595 xml::add_element($doc, $author, "poco:displayName", $owner["name"]);
1596 xml::add_element($doc, $author, "poco:note", bbcode($owner["about"], false, false, 7));
1598 if (trim($owner["location"]) != "") {
1599 $element = $doc->createElement("poco:address");
1600 xml::add_element($doc, $element, "poco:formatted", $owner["location"]);
1601 $author->appendChild($element);
1604 if (trim($profile["homepage"]) != "") {
1605 $urls = $doc->createElement("poco:urls");
1606 xml::add_element($doc, $urls, "poco:type", "homepage");
1607 xml::add_element($doc, $urls, "poco:value", $profile["homepage"]);
1608 xml::add_element($doc, $urls, "poco:primary", "true");
1609 $author->appendChild($urls);
1612 if (count($profile)) {
1613 xml::add_element($doc, $author, "followers", "", array("url" => App::get_baseurl()."/viewcontacts/".$owner["nick"]));
1614 xml::add_element($doc, $author, "statusnet:profile_info", "", array("local_id" => $owner["uid"]));
1617 if ($profile["publish"]) {
1618 xml::add_element($doc, $author, "mastodon:scope", "public");
1624 * @TODO Picture attachments should look like this:
1625 * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1626 * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1631 * @brief Returns the given activity if present - otherwise returns the "post" activity
1633 * @param array $item Data of the item that is to be posted
1635 * @return string activity
1637 function construct_verb($item) {
1639 return $item['verb'];
1640 return ACTIVITY_POST;
1644 * @brief Returns the given object type if present - otherwise returns the "note" object type
1646 * @param array $item Data of the item that is to be posted
1648 * @return string Object type
1650 function construct_objecttype($item) {
1651 if (in_array($item['object-type'], array(ACTIVITY_OBJ_NOTE, ACTIVITY_OBJ_COMMENT)))
1652 return $item['object-type'];
1653 return ACTIVITY_OBJ_NOTE;
1657 * @brief Adds an entry element to the XML document
1659 * @param object $doc XML document
1660 * @param array $item Data of the item that is to be posted
1661 * @param array $owner Contact data of the poster
1662 * @param bool $toplevel
1664 * @return object Entry element
1666 private function entry($doc, $item, $owner, $toplevel = false) {
1667 $repeated_guid = self::get_reshared_guid($item);
1668 if ($repeated_guid != "")
1669 $xml = self::reshare_entry($doc, $item, $owner, $repeated_guid, $toplevel);
1674 if ($item["verb"] == ACTIVITY_LIKE) {
1675 return self::like_entry($doc, $item, $owner, $toplevel);
1676 } elseif (in_array($item["verb"], array(ACTIVITY_FOLLOW, NAMESPACE_OSTATUS."/unfollow"))) {
1677 return self::follow_entry($doc, $item, $owner, $toplevel);
1679 return self::note_entry($doc, $item, $owner, $toplevel);
1684 * @brief Adds a source entry to the XML document
1686 * @param object $doc XML document
1687 * @param array $contact Array of the contact that is added
1689 * @return object Source element
1691 private function source_entry($doc, $contact) {
1692 $source = $doc->createElement("source");
1693 xml::add_element($doc, $source, "id", $contact["poll"]);
1694 xml::add_element($doc, $source, "title", $contact["name"]);
1695 xml::add_element($doc, $source, "link", "", array("rel" => "alternate",
1696 "type" => "text/html",
1697 "href" => $contact["alias"]));
1698 xml::add_element($doc, $source, "link", "", array("rel" => "self",
1699 "type" => "application/atom+xml",
1700 "href" => $contact["poll"]));
1701 xml::add_element($doc, $source, "icon", $contact["photo"]);
1702 xml::add_element($doc, $source, "updated", datetime_convert("UTC","UTC",$contact["success_update"]."+00:00",ATOM_TIME));
1708 * @brief Fetches contact data from the contact or the gcontact table
1710 * @param string $url URL of the contact
1711 * @param array $owner Contact data of the poster
1713 * @return array Contact array
1715 private function contact_entry($url, $owner) {
1717 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
1718 dbesc(normalise_link($url)), intval($owner["uid"]));
1721 $contact["uid"] = -1;
1725 $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1726 dbesc(normalise_link($url)));
1729 $contact["uid"] = -1;
1730 $contact["success_update"] = $contact["updated"];
1737 if (!isset($contact["poll"])) {
1738 $data = probe_url($url);
1739 $contact["poll"] = $data["poll"];
1741 if (!$contact["alias"])
1742 $contact["alias"] = $data["alias"];
1745 if (!isset($contact["alias"]))
1746 $contact["alias"] = $contact["url"];
1752 * @brief Adds an entry element with reshared content
1754 * @param object $doc XML document
1755 * @param array $item Data of the item that is to be posted
1756 * @param array $owner Contact data of the poster
1757 * @param $repeated_guid
1758 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1760 * @return object Entry element
1762 private function reshare_entry($doc, $item, $owner, $repeated_guid, $toplevel) {
1764 if (($item["id"] != $item["parent"]) AND (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1765 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1768 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1770 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' AND NOT `private` AND `network` IN ('%s', '%s', '%s') LIMIT 1",
1771 intval($owner["uid"]), dbesc($repeated_guid),
1772 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS));
1774 $repeated_item = $r[0];
1778 $contact = self::contact_entry($repeated_item['author-link'], $owner);
1780 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1782 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1784 self::entry_content($doc, $entry, $item, $owner, $title, ACTIVITY_SHARE, false);
1786 $as_object = $doc->createElement("activity:object");
1788 xml::add_element($doc, $as_object, "activity:object-type", NAMESPACE_ACTIVITY_SCHEMA."activity");
1790 self::entry_content($doc, $as_object, $repeated_item, $owner, "", "", false);
1792 $author = self::add_author($doc, $contact);
1793 $as_object->appendChild($author);
1795 $as_object2 = $doc->createElement("activity:object");
1797 xml::add_element($doc, $as_object2, "activity:object-type", self::construct_objecttype($repeated_item));
1799 $title = sprintf("New comment by %s", $contact["nick"]);
1801 self::entry_content($doc, $as_object2, $repeated_item, $owner, $title);
1803 $as_object->appendChild($as_object2);
1805 self::entry_footer($doc, $as_object, $item, $owner, false);
1807 $source = self::source_entry($doc, $contact);
1809 $as_object->appendChild($source);
1811 $entry->appendChild($as_object);
1813 self::entry_footer($doc, $entry, $item, $owner);
1819 * @brief Adds an entry element with a "like"
1821 * @param object $doc XML document
1822 * @param array $item Data of the item that is to be posted
1823 * @param array $owner Contact data of the poster
1824 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1826 * @return object Entry element with "like"
1828 private function like_entry($doc, $item, $owner, $toplevel) {
1830 if (($item["id"] != $item["parent"]) AND (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1831 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1834 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1836 $verb = NAMESPACE_ACTIVITY_SCHEMA."favorite";
1837 self::entry_content($doc, $entry, $item, $owner, "Favorite", $verb, false);
1839 $as_object = $doc->createElement("activity:object");
1841 $parent = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d",
1842 dbesc($item["thr-parent"]), intval($item["uid"]));
1843 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1845 xml::add_element($doc, $as_object, "activity:object-type", self::construct_objecttype($parent[0]));
1847 self::entry_content($doc, $as_object, $parent[0], $owner, "New entry");
1849 $entry->appendChild($as_object);
1851 self::entry_footer($doc, $entry, $item, $owner);
1857 * @brief Adds the person object element to the XML document
1859 * @param object $doc XML document
1860 * @param array $owner Contact data of the poster
1861 * @param array $contact Contact data of the target
1863 * @return object author element
1865 private function add_person_object($doc, $owner, $contact) {
1867 $object = $doc->createElement("activity:object");
1868 xml::add_element($doc, $object, "activity:object-type", ACTIVITY_OBJ_PERSON);
1870 if ($contact['network'] == NETWORK_PHANTOM) {
1871 xml::add_element($doc, $object, "id", $contact['url']);
1875 xml::add_element($doc, $object, "id", $contact["alias"]);
1876 xml::add_element($doc, $object, "title", $contact["nick"]);
1878 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $contact["url"]);
1879 xml::add_element($doc, $object, "link", "", $attributes);
1881 $attributes = array(
1883 "type" => "image/jpeg", // To-Do?
1884 "media:width" => 175,
1885 "media:height" => 175,
1886 "href" => $contact["photo"]);
1887 xml::add_element($doc, $object, "link", "", $attributes);
1889 xml::add_element($doc, $object, "poco:preferredUsername", $contact["nick"]);
1890 xml::add_element($doc, $object, "poco:displayName", $contact["name"]);
1892 if (trim($contact["location"]) != "") {
1893 $element = $doc->createElement("poco:address");
1894 xml::add_element($doc, $element, "poco:formatted", $contact["location"]);
1895 $object->appendChild($element);
1902 * @brief Adds a follow/unfollow entry element
1904 * @param object $doc XML document
1905 * @param array $item Data of the follow/unfollow message
1906 * @param array $owner Contact data of the poster
1907 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1909 * @return object Entry element
1911 private function follow_entry($doc, $item, $owner, $toplevel) {
1913 $item["id"] = $item["parent"] = 0;
1914 $item["created"] = $item["edited"] = date("c");
1915 $item["private"] = true;
1917 $contact = Probe::uri($item['follow']);
1919 if ($contact['alias'] == '') {
1920 $contact['alias'] = $contact["url"];
1922 $item['follow'] = $contact['alias'];
1925 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1926 intval($owner['uid']), dbesc(normalise_link($contact["url"])));
1928 if (dbm::is_result($r)) {
1929 $connect_id = $r[0]['id'];
1934 if ($item['verb'] == ACTIVITY_FOLLOW) {
1935 $message = t('%s is now following %s.');
1936 $title = t('following');
1937 $action = "subscription";
1939 $message = t('%s stopped following %s.');
1940 $title = t('stopped following');
1941 $action = "unfollow";
1944 $item["uri"] = $item['parent-uri'] = $item['thr-parent'] =
1945 'tag:'.get_app()->get_hostname().
1946 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1947 ':person:'.$connect_id.':'.$item['created'];
1949 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1951 self::entry_header($doc, $entry, $owner, $toplevel);
1953 self::entry_content($doc, $entry, $item, $owner, $title);
1955 $object = self::add_person_object($doc, $owner, $contact);
1956 $entry->appendChild($object);
1958 self::entry_footer($doc, $entry, $item, $owner);
1964 * @brief Adds a regular entry element
1966 * @param object $doc XML document
1967 * @param array $item Data of the item that is to be posted
1968 * @param array $owner Contact data of the poster
1969 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1971 * @return object Entry element
1973 private function note_entry($doc, $item, $owner, $toplevel) {
1975 if (($item["id"] != $item["parent"]) AND (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1976 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1979 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1981 xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1983 self::entry_content($doc, $entry, $item, $owner, $title);
1985 self::entry_footer($doc, $entry, $item, $owner);
1991 * @brief Adds a header element to the XML document
1993 * @param object $doc XML document
1994 * @param object $entry The entry element where the elements are added
1995 * @param array $owner Contact data of the poster
1996 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1998 * @return string The title for the element
2000 private function entry_header($doc, &$entry, $owner, $toplevel) {
2001 /// @todo Check if this title stuff is really needed (I guess not)
2003 $entry = $doc->createElement("entry");
2004 $title = sprintf("New note by %s", $owner["nick"]);
2006 $entry = $doc->createElementNS(NAMESPACE_ATOM1, "entry");
2008 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
2009 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
2010 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
2011 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
2012 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
2013 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
2014 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
2015 $entry->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
2017 $author = self::add_author($doc, $owner);
2018 $entry->appendChild($author);
2020 $title = sprintf("New comment by %s", $owner["nick"]);
2026 * @brief Adds elements to the XML document
2028 * @param object $doc XML document
2029 * @param object $entry Entry element where the content is added
2030 * @param array $item Data of the item that is to be posted
2031 * @param array $owner Contact data of the poster
2032 * @param string $title Title for the post
2033 * @param string $verb The activity verb
2034 * @param bool $complete Add the "status_net" element?
2036 private function entry_content($doc, $entry, $item, $owner, $title, $verb = "", $complete = true) {
2039 $verb = self::construct_verb($item);
2041 xml::add_element($doc, $entry, "id", $item["uri"]);
2042 xml::add_element($doc, $entry, "title", $title);
2044 $body = self::format_picture_post($item['body']);
2046 if ($item['title'] != "")
2047 $body = "[b]".$item['title']."[/b]\n\n".$body;
2049 $body = bbcode($body, false, false, 7);
2051 xml::add_element($doc, $entry, "content", $body, array("type" => "html"));
2053 xml::add_element($doc, $entry, "link", "", array("rel" => "alternate", "type" => "text/html",
2054 "href" => App::get_baseurl()."/display/".$item["guid"]));
2056 if ($complete AND ($item["id"] > 0))
2057 xml::add_element($doc, $entry, "status_net", "", array("notice_id" => $item["id"]));
2059 xml::add_element($doc, $entry, "activity:verb", $verb);
2061 xml::add_element($doc, $entry, "published", datetime_convert("UTC","UTC",$item["created"]."+00:00",ATOM_TIME));
2062 xml::add_element($doc, $entry, "updated", datetime_convert("UTC","UTC",$item["edited"]."+00:00",ATOM_TIME));
2066 * @brief Adds the elements at the foot of an entry to the XML document
2068 * @param object $doc XML document
2069 * @param object $entry The entry element where the elements are added
2070 * @param array $item Data of the item that is to be posted
2071 * @param array $owner Contact data of the poster
2074 private function entry_footer($doc, $entry, $item, $owner, $complete = true) {
2076 $mentioned = array();
2078 if (($item['parent'] != $item['id']) OR ($item['parent-uri'] !== $item['uri']) OR (($item['thr-parent'] !== '') AND ($item['thr-parent'] !== $item['uri']))) {
2079 $parent = q("SELECT `guid`, `author-link`, `owner-link` FROM `item` WHERE `id` = %d", intval($item["parent"]));
2080 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
2082 $thrparent = q("SELECT `guid`, `author-link`, `owner-link`, `plink` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
2083 intval($owner["uid"]),
2084 dbesc($parent_item));
2086 $mentioned[$thrparent[0]["author-link"]] = $thrparent[0]["author-link"];
2087 $mentioned[$thrparent[0]["owner-link"]] = $thrparent[0]["owner-link"];
2088 $parent_plink = $thrparent[0]["plink"];
2090 $mentioned[$parent[0]["author-link"]] = $parent[0]["author-link"];
2091 $mentioned[$parent[0]["owner-link"]] = $parent[0]["owner-link"];
2092 $parent_plink = App::get_baseurl()."/display/".$parent[0]["guid"];
2095 $attributes = array(
2096 "ref" => $parent_item,
2097 "href" => $parent_plink);
2098 xml::add_element($doc, $entry, "thr:in-reply-to", "", $attributes);
2100 $attributes = array(
2102 "href" => $parent_plink);
2103 xml::add_element($doc, $entry, "link", "", $attributes);
2106 if (intval($item["parent"]) > 0) {
2107 $conversation_href = App::get_baseurl()."/display/".$owner["nick"]."/".$item["parent"];
2108 $conversation_uri = $conversation_href;
2110 if (isset($parent_item)) {
2111 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $parent_item);
2112 if (dbm::is_result($r)) {
2113 if ($r['conversation-uri'] != '') {
2114 $conversation_uri = $r['conversation-uri'];
2116 if ($r['conversation-href'] != '') {
2117 $conversation_href = $r['conversation-href'];
2122 xml::add_element($doc, $entry, "link", "", array("rel" => "ostatus:conversation", "href" => $conversation_href));
2124 $attributes = array(
2125 "href" => $conversation_href,
2126 "local_id" => $item["parent"],
2127 "ref" => $conversation_uri);
2129 xml::add_element($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
2132 $tags = item_getfeedtags($item);
2135 foreach($tags as $t)
2137 $mentioned[$t[1]] = $t[1];
2139 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
2140 $newmentions = array();
2141 foreach ($mentioned AS $mention) {
2142 $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
2143 $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
2145 $mentioned = $newmentions;
2147 foreach ($mentioned AS $mention) {
2148 $r = q("SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
2149 intval($owner["uid"]),
2150 dbesc(normalise_link($mention)));
2151 if ($r[0]["forum"] OR $r[0]["prv"])
2152 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
2153 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
2154 "href" => $mention));
2156 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
2157 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
2158 "href" => $mention));
2161 if (!$item["private"]) {
2162 xml::add_element($doc, $entry, "link", "", array("rel" => "ostatus:attention",
2163 "href" => "http://activityschema.org/collection/public"));
2164 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
2165 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
2166 "href" => "http://activityschema.org/collection/public"));
2167 xml::add_element($doc, $entry, "mastodon:scope", "public");
2171 foreach($tags as $t)
2173 xml::add_element($doc, $entry, "category", "", array("term" => $t[2]));
2175 self::get_attachment($doc, $entry, $item);
2177 if ($complete AND ($item["id"] > 0)) {
2178 $app = $item["app"];
2182 $attributes = array("local_id" => $item["id"], "source" => $app);
2184 if (isset($parent["id"]))
2185 $attributes["repeat_of"] = $parent["id"];
2187 if ($item["coord"] != "")
2188 xml::add_element($doc, $entry, "georss:point", $item["coord"]);
2190 xml::add_element($doc, $entry, "statusnet:notice_info", "", $attributes);
2195 * @brief Creates the XML feed for a given nickname
2197 * @param App $a The application class
2198 * @param string $owner_nick Nickname of the feed owner
2199 * @param string $last_update Date of the last update
2201 * @return string XML feed
2203 public static function feed(App $a, $owner_nick, $last_update) {
2205 $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`
2206 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
2207 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
2208 dbesc($owner_nick));
2214 if(!strlen($last_update))
2215 $last_update = 'now -30 days';
2217 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
2218 $authorid = get_contact($owner["url"], 0);
2220 $items = q("SELECT `item`.*, `item`.`id` AS `item_id` FROM `item` USE INDEX (`uid_contactid_created`)
2221 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `item`.`parent`
2222 WHERE `item`.`uid` = %d AND `item`.`contact-id` = %d AND
2223 `item`.`author-id` = %d AND `item`.`created` > '%s' AND
2224 NOT `item`.`deleted` AND NOT `item`.`private` AND
2225 `thread`.`network` IN ('%s', '%s')
2226 ORDER BY `item`.`created` DESC LIMIT 300",
2227 intval($owner["uid"]), intval($owner["id"]),
2228 intval($authorid), dbesc($check_date),
2229 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
2231 /* 2016-10-23: The old query will be kept until we are sure that the query above is a good and fast replacement
2233 $items = q("SELECT `item`.*, `item`.`id` AS `item_id` FROM `item`
2234 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `item`.`parent`
2235 LEFT JOIN `item` AS `thritem` ON `thritem`.`uri`=`item`.`thr-parent` AND `thritem`.`uid`=`item`.`uid`
2236 WHERE `item`.`uid` = %d AND `item`.`received` > '%s' AND NOT `item`.`private` AND NOT `item`.`deleted`
2237 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
2238 AND ((`item`.`wall` AND (`item`.`parent` = `item`.`id`))
2239 OR (`item`.`network` = '%s' AND ((`thread`.`network` IN ('%s', '%s')) OR (`thritem`.`network` IN ('%s', '%s')))) AND `thread`.`mention`)
2240 AND ((`item`.`owner-link` IN ('%s', '%s') AND (`item`.`parent` = `item`.`id`))
2241 OR (`item`.`author-link` IN ('%s', '%s')))
2242 ORDER BY `item`.`id` DESC
2244 intval($owner["uid"]), dbesc($check_date), dbesc(NETWORK_DFRN),
2245 //dbesc(NETWORK_OSTATUS), dbesc(NETWORK_OSTATUS),
2246 //dbesc(NETWORK_OSTATUS), dbesc(NETWORK_OSTATUS),
2247 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN),
2248 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN),
2249 dbesc($owner["nurl"]), dbesc(str_replace("http://", "https://", $owner["nurl"])),
2250 dbesc($owner["nurl"]), dbesc(str_replace("http://", "https://", $owner["nurl"]))
2253 $doc = new DOMDocument('1.0', 'utf-8');
2254 $doc->formatOutput = true;
2256 $root = self::add_header($doc, $owner);
2258 foreach ($items AS $item) {
2259 if (Config::get('system', 'ostatus_debug')) {
2260 $item['body'] .= '🍼';
2262 $entry = self::entry($doc, $item, $owner);
2263 $root->appendChild($entry);
2266 return(trim($doc->saveXML()));
2270 * @brief Creates the XML for a salmon message
2272 * @param array $item Data of the item that is to be posted
2273 * @param array $owner Contact data of the poster
2275 * @return string XML for the salmon
2277 public static function salmon($item,$owner) {
2279 $doc = new DOMDocument('1.0', 'utf-8');
2280 $doc->formatOutput = true;
2282 if (Config::get('system', 'ostatus_debug')) {
2283 $item['body'] .= '🐟';
2286 $entry = self::entry($doc, $item, $owner, true);
2288 $doc->appendChild($entry);
2290 return(trim($doc->saveXML()));