3 * @file include/ostatus.php
7 use Friendica\Core\System;
8 use Friendica\Core\Config;
9 use Friendica\Network\Probe;
11 require_once 'include/Contact.php';
12 require_once 'include/threads.php';
13 require_once 'include/html2bbcode.php';
14 require_once 'include/bbcode.php';
15 require_once 'include/items.php';
16 require_once 'mod/share.php';
17 require_once 'include/enotify.php';
18 require_once 'include/socgraph.php';
19 require_once 'include/Photo.php';
20 require_once 'include/probe.php';
21 require_once 'include/follow.php';
22 require_once 'include/api.php';
23 require_once 'mod/proxy.php';
24 require_once 'include/xml.php';
25 require_once 'include/cache.php';
28 * @brief This class contain functions for the OStatus protocol
32 const OSTATUS_DEFAULT_POLL_INTERVAL = 30; // given in minutes
33 const OSTATUS_DEFAULT_POLL_TIMEFRAME = 1440; // given in minutes
34 const OSTATUS_DEFAULT_POLL_TIMEFRAME_MENTIONS = 14400; // given in minutes
37 * @brief Fetches author data
39 * @param object $xpath The xpath object
40 * @param object $context The xml context of the author detals
41 * @param array $importer user record of the importing user
42 * @param array $contact Called by reference, will contain the fetched contact
43 * @param bool $onlyfetch Only fetch the header without updating the contact entries
45 * @return array Array of author related entries for the item
47 private static function fetchauthor($xpath, $context, $importer, &$contact, $onlyfetch) {
50 $author["author-link"] = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
51 $author["author-name"] = $xpath->evaluate('atom:author/atom:name/text()', $context)->item(0)->nodeValue;
52 $addr = $xpath->evaluate('atom:author/atom:email/text()', $context)->item(0)->nodeValue;
54 $aliaslink = $author["author-link"];
56 $alternate = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0)->attributes;
57 if (is_object($alternate)) {
58 foreach ($alternate AS $attributes) {
59 if (($attributes->name == "href") && ($attributes->textContent != "")) {
60 $author["author-link"] = $attributes->textContent;
65 $author["contact-id"] = $contact["id"];
67 if ($author["author-link"] != "") {
68 if ($aliaslink == "") {
69 $aliaslink = $author["author-link"];
72 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` IN ('%s', '%s') AND `network` != '%s'",
73 intval($importer["uid"]), dbesc(normalise_link($author["author-link"])),
74 dbesc(normalise_link($aliaslink)), dbesc(NETWORK_STATUSNET));
76 if (dbm::is_result($r)) {
78 $author["contact-id"] = $r[0]["id"];
79 $author["author-link"] = $r[0]["url"];
81 } elseif ($addr != "") {
83 $contact = dba::fetch_first("SELECT * FROM `contact` WHERE `uid` = ? AND `addr` = ? AND `network` != ?",
84 $importer["uid"], $addr, NETWORK_STATUSNET);
86 if (dbm::is_result($contact)) {
87 $author["contact-id"] = $contact["id"];
88 $author["author-link"] = $contact["url"];
92 $avatarlist = array();
93 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
94 foreach ($avatars AS $avatar) {
97 foreach ($avatar->attributes AS $attributes) {
98 if ($attributes->name == "href") {
99 $href = $attributes->textContent;
101 if ($attributes->name == "width") {
102 $width = $attributes->textContent;
106 $avatarlist[$width] = $href;
109 if (count($avatarlist) > 0) {
111 $author["author-avatar"] = Probe::fixAvatar(current($avatarlist), $author["author-link"]);
114 $displayname = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
115 if ($displayname != "") {
116 $author["author-name"] = $displayname;
119 $author["owner-name"] = $author["author-name"];
120 $author["owner-link"] = $author["author-link"];
121 $author["owner-avatar"] = $author["author-avatar"];
123 // Only update the contacts if it is an OStatus contact
124 if ($r && !$onlyfetch && ($contact["network"] == NETWORK_OSTATUS)) {
126 // Update contact data
128 // This query doesn't seem to work
129 // $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
131 // $contact["notify"] = $value;
133 // This query doesn't seem to work as well - I hate these queries
134 // $value = $xpath->query("atom:link[@rel='self' and @type='application/atom+xml']", $context)->item(0)->nodeValue;
136 // $contact["poll"] = $value;
138 $value = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
140 $contact["alias"] = $value;
142 $value = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
144 $contact["name"] = $value;
146 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
148 $contact["nick"] = $value;
150 $value = $xpath->evaluate('atom:author/poco:note/text()', $context)->item(0)->nodeValue;
152 $contact["about"] = html2bbcode($value);
154 $value = $xpath->evaluate('atom:author/poco:address/poco:formatted/text()', $context)->item(0)->nodeValue;
156 $contact["location"] = $value;
158 if (($contact["name"] != $r[0]["name"]) || ($contact["nick"] != $r[0]["nick"]) || ($contact["about"] != $r[0]["about"]) ||
159 ($contact["alias"] != $r[0]["alias"]) || ($contact["location"] != $r[0]["location"])) {
161 logger("Update contact data for contact ".$contact["id"], LOGGER_DEBUG);
163 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `alias` = '%s', `about` = '%s', `location` = '%s', `name-date` = '%s' WHERE `id` = %d",
164 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["alias"]),
165 dbesc($contact["about"]), dbesc($contact["location"]),
166 dbesc(datetime_convert()), intval($contact["id"]));
169 if (isset($author["author-avatar"]) && ($author["author-avatar"] != $r[0]['avatar'])) {
170 logger("Update profile picture for contact ".$contact["id"], LOGGER_DEBUG);
172 update_contact_avatar($author["author-avatar"], $importer["uid"], $contact["id"]);
175 // Ensure that we are having this contact (with uid=0)
176 $cid = get_contact($author["author-link"], 0);
179 // Update it with the current values
180 q("UPDATE `contact` SET `url` = '%s', `name` = '%s', `nick` = '%s', `alias` = '%s',
181 `about` = '%s', `location` = '%s',
182 `success_update` = '%s', `last-update` = '%s'
184 dbesc($author["author-link"]), dbesc($contact["name"]), dbesc($contact["nick"]),
185 dbesc($contact["alias"]), dbesc($contact["about"]), dbesc($contact["location"]),
186 dbesc(datetime_convert()), dbesc(datetime_convert()), intval($cid));
189 update_contact_avatar($author["author-avatar"], 0, $cid);
192 $contact["generation"] = 2;
193 $contact["hide"] = false; // OStatus contacts are never hidden
194 $contact["photo"] = $author["author-avatar"];
195 $gcid = update_gcontact($contact);
197 link_gcontact($gcid, $contact["uid"], $contact["id"]);
204 * @brief Fetches author data from a given XML string
206 * @param string $xml The XML
207 * @param array $importer user record of the importing user
209 * @return array Array of author related entries for the item
211 public static function salmon_author($xml, $importer) {
216 $doc = new DOMDocument();
217 @$doc->loadXML($xml);
219 $xpath = new DomXPath($doc);
220 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
221 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
222 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
223 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
224 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
225 $xpath->registerNamespace('poco', NAMESPACE_POCO);
226 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
227 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
229 $entries = $xpath->query('/atom:entry');
231 foreach ($entries AS $entry) {
233 $author = self::fetchauthor($xpath, $entry, $importer, $contact, true);
239 * @brief Read attributes from element
241 * @param object $element Element object
243 * @return array attributes
245 private static function read_attributes($element) {
246 $attribute = array();
248 foreach ($element->attributes AS $attributes) {
249 $attribute[$attributes->name] = $attributes->textContent;
256 * @brief Imports an XML string containing OStatus elements
258 * @param string $xml The XML
259 * @param array $importer user record of the importing user
261 * @param array $hub Called by reference, returns the fetched hub data
263 public static function import($xml,$importer,&$contact, &$hub) {
264 /// @todo this function is too long. It has to be split in many parts
266 logger("Import OStatus message", LOGGER_DEBUG);
271 //$tempfile = tempnam(get_temppath(), "import");
272 //file_put_contents($tempfile, $xml);
274 $doc = new DOMDocument();
275 @$doc->loadXML($xml);
277 $xpath = new DomXPath($doc);
278 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
279 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
280 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
281 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
282 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
283 $xpath->registerNamespace('poco', NAMESPACE_POCO);
284 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
285 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
288 $hub_attributes = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0)->attributes;
289 if (is_object($hub_attributes)) {
290 foreach ($hub_attributes AS $hub_attribute) {
291 if ($hub_attribute->name == "href") {
292 $hub = $hub_attribute->textContent;
293 logger("Found hub ".$hub, LOGGER_DEBUG);
298 $header["uid"] = $importer["uid"];
299 $header["network"] = NETWORK_OSTATUS;
300 $header["type"] = "remote";
302 $header["origin"] = 0;
303 $header["gravity"] = GRAVITY_PARENT;
305 // it could either be a received post or a post we fetched by ourselves
306 // depending on that, the first node is different
307 $first_child = $doc->firstChild->tagName;
309 if ($first_child == "feed") {
310 $entries = $xpath->query('/atom:feed/atom:entry');
311 $header["protocol"] = PROTOCOL_OSTATUS_FEED;
313 $entries = $xpath->query('/atom:entry');
314 $header["protocol"] = PROTOCOL_OSTATUS_SALMON;
317 $conversationlist = array();
320 // Reverse the order of the entries
321 $entrylist = array();
323 foreach ($entries AS $entry) {
324 $entrylist[] = $entry;
326 foreach (array_reverse($entrylist) AS $entry) {
331 if ($first_child == "feed") {
332 $author = self::fetchauthor($xpath, $doc->firstChild, $importer, $contact, false);
334 $author = self::fetchauthor($xpath, $entry, $importer, $contact, false);
336 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
340 $nickname = $author["author-name"];
342 $item = array_merge($header, $author);
345 $item["uri"] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
347 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
348 intval($importer["uid"]), dbesc($item["uri"]));
349 if (dbm::is_result($r)) {
350 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already existed under id ".$r[0]["id"], LOGGER_DEBUG);
354 $item["body"] = html2bbcode($xpath->query('atom:content/text()', $entry)->item(0)->nodeValue);
355 $item["object-type"] = $xpath->query('activity:object-type/text()', $entry)->item(0)->nodeValue;
356 $item["verb"] = $xpath->query('activity:verb/text()', $entry)->item(0)->nodeValue;
358 if (($item["object-type"] == ACTIVITY_OBJ_BOOKMARK) || ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
359 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
360 $item["body"] = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
361 } elseif ($item["object-type"] == ACTIVITY_OBJ_QUESTION) {
362 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
364 $item["source"] = $xml;
368 if ($item["verb"] == "qvitter-delete-notice" || $item["verb"] == ACTIVITY_DELETE) {
369 // ignore "Delete" messages (by now)
370 logger("Ignore delete message ".print_r($item, true));
374 if ($item["verb"] == ACTIVITY_JOIN) {
375 // ignore "Join" messages
376 logger("Ignore join message ".print_r($item, true));
380 if ($item["verb"] == ACTIVITY_FOLLOW) {
381 new_follower($importer, $contact, $item, $nickname);
385 if ($item["verb"] == NAMESPACE_OSTATUS."/unfollow") {
386 lose_follower($importer, $contact, $item, $dummy);
390 if ($item["verb"] == ACTIVITY_FAVORITE) {
391 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
392 logger("Favorite ".$orig_uri." ".print_r($item, true));
394 $item["verb"] = ACTIVITY_LIKE;
395 $item["parent-uri"] = $orig_uri;
396 $item["gravity"] = GRAVITY_LIKE;
399 if ($item["verb"] == NAMESPACE_OSTATUS."/unfavorite") {
400 // Ignore "Unfavorite" message
401 logger("Ignore unfavorite message ".print_r($item, true));
405 // http://activitystrea.ms/schema/1.0/rsvp-yes
406 if (!in_array($item["verb"], array(ACTIVITY_POST, ACTIVITY_LIKE, ACTIVITY_SHARE))) {
407 logger("Unhandled verb ".$item["verb"]." ".print_r($item, true));
409 $item["created"] = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
410 $item["edited"] = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
411 $conversation = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
412 $item['conversation-uri'] = $conversation;
414 $conv = $xpath->query('ostatus:conversation', $entry);
415 if (is_object($conv->item(0))) {
416 foreach ($conv->item(0)->attributes AS $attributes) {
417 if ($attributes->name == "ref") {
418 $item['conversation-uri'] = $attributes->textContent;
420 if ($attributes->name == "href") {
421 $item['conversation-href'] = $attributes->textContent;
428 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
429 if (is_object($inreplyto->item(0))) {
430 foreach ($inreplyto->item(0)->attributes AS $attributes) {
431 if ($attributes->name == "ref") {
432 $item["parent-uri"] = $attributes->textContent;
434 if ($attributes->name == "href") {
435 $related = $attributes->textContent;
440 $georsspoint = $xpath->query('georss:point', $entry);
442 $item["coord"] = $georsspoint->item(0)->nodeValue;
444 $categories = $xpath->query('atom:category', $entry);
446 foreach ($categories AS $category) {
447 foreach ($category->attributes AS $attributes) {
448 if ($attributes->name == "term") {
449 $term = $attributes->textContent;
450 if (strlen($item["tag"])) {
453 $item["tag"] .= "#[url=".System::baseUrl()."/search?tag=".$term."]".$term."[/url]";
463 $links = $xpath->query('atom:link', $entry);
465 foreach ($links AS $link) {
466 $attribute = self::read_attributes($link);
468 if (($attribute['rel'] != "") && ($attribute['href'] != "")) {
469 switch ($attribute['rel']) {
471 $item["plink"] = $attribute['href'];
472 if (($item["object-type"] == ACTIVITY_OBJ_QUESTION) ||
473 ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
474 $item["body"] .= add_page_info($attribute['href']);
477 case "ostatus:conversation":
478 $conversation = $attribute['href'];
479 $item['conversation-href'] = $conversation;
480 if (!isset($item['conversation-uri'])) {
481 $item['conversation-uri'] = $item['conversation-href'];
485 $filetype = strtolower(substr($attribute['type'], 0, strpos($attribute['type'],'/')));
486 if ($filetype == 'image') {
487 $add_body .= "\n[img]".$attribute['href'].'[/img]';
489 if (strlen($item["attach"])) {
490 $item["attach"] .= ',';
492 if (!isset($attribute['length'])) {
493 $attribute['length'] = "0";
495 $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.$attribute['title'].'"[/attach]';
499 if ($item["object-type"] != ACTIVITY_OBJ_BOOKMARK) {
500 if (!isset($item["parent-uri"])) {
501 $item["parent-uri"] = $attribute['href'];
503 if ($related == "") {
504 $related = $attribute['href'];
507 $item["body"] .= add_page_info($attribute['href']);
511 $self = $attribute['href'];
514 // Notification check
515 if ($importer["nurl"] == normalise_link($attribute['href'])) {
527 $notice_info = $xpath->query('statusnet:notice_info', $entry);
528 if ($notice_info && ($notice_info->length > 0)) {
529 foreach ($notice_info->item(0)->attributes AS $attributes) {
530 if ($attributes->name == "source") {
531 $item["app"] = strip_tags($attributes->textContent);
533 if ($attributes->name == "local_id") {
534 $local_id = $attributes->textContent;
536 if ($attributes->name == "repeat_of") {
537 $repeat_of = $attributes->textContent;
542 // Is it a repeated post?
543 if (($repeat_of != "") || ($item["verb"] == ACTIVITY_SHARE)) {
544 $activityobjects = $xpath->query('activity:object', $entry)->item(0);
546 if (is_object($activityobjects)) {
548 $orig_uri = $xpath->query("activity:object/atom:id", $activityobjects)->item(0)->nodeValue;
549 if (!isset($orig_uri)) {
550 $orig_uri = $xpath->query('atom:id/text()', $activityobjects)->item(0)->nodeValue;
552 $orig_links = $xpath->query("activity:object/atom:link[@rel='alternate']", $activityobjects);
553 if ($orig_links && ($orig_links->length > 0)) {
554 foreach ($orig_links->item(0)->attributes AS $attributes) {
555 if ($attributes->name == "href") {
556 $orig_link = $attributes->textContent;
560 if (!isset($orig_link)) {
561 $orig_link = $xpath->query("atom:link[@rel='alternate']", $activityobjects)->item(0)->nodeValue;
563 if (!isset($orig_link)) {
564 $orig_link = self::convert_href($orig_uri);
566 $orig_body = $xpath->query('activity:object/atom:content/text()', $activityobjects)->item(0)->nodeValue;
567 if (!isset($orig_body)) {
568 $orig_body = $xpath->query('atom:content/text()', $activityobjects)->item(0)->nodeValue;
570 $orig_created = $xpath->query('atom:published/text()', $activityobjects)->item(0)->nodeValue;
571 $orig_edited = $xpath->query('atom:updated/text()', $activityobjects)->item(0)->nodeValue;
573 $orig_contact = $contact;
574 $orig_author = self::fetchauthor($xpath, $activityobjects, $importer, $orig_contact, false);
576 $item["author-name"] = $orig_author["author-name"];
577 $item["author-link"] = $orig_author["author-link"];
578 $item["author-avatar"] = $orig_author["author-avatar"];
580 $item["body"] = html2bbcode($orig_body);
581 $item["created"] = $orig_created;
582 $item["edited"] = $orig_edited;
584 $item["uri"] = $orig_uri;
586 if (!isset($item["plink"])) {
587 $item["plink"] = $orig_link;
590 $item["verb"] = $xpath->query('activity:verb/text()', $activityobjects)->item(0)->nodeValue;
592 $item["object-type"] = $xpath->query('activity:object/activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
593 if (!isset($item["object-type"])) {
594 $item["object-type"] = $xpath->query('activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
597 $enclosures = $xpath->query("atom:link[@rel='alternate']", $activityobjects);
599 foreach ($enclosures AS $link) {
600 $attribute = self::read_attributes($link);
602 if (strlen($item["attach"])) {
603 $item["attach"] .= ',';
605 if (!isset($attribute['length'])) {
606 $attribute['length'] = "0";
608 $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.$attribute['title'].'"[/attach]';
615 $item["body"] .= $add_body;
617 // Only add additional data when there is no picture in the post
618 if (!strstr($item["body"],'[/img]')) {
619 $item["body"] = add_page_info_to_body($item["body"]);
622 // Mastodon Content Warning
623 if (($item["verb"] == ACTIVITY_POST) && $xpath->evaluate('boolean(atom:summary)', $entry)) {
624 $clear_text = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
626 $item["body"] = html2bbcode($clear_text) . '[spoiler]' . $item["body"] . '[/spoiler]';
629 if (isset($item["parent-uri"])) {
630 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
631 intval($importer["uid"]), dbesc($item["parent-uri"]));
633 // Only fetch missing stuff if it is a comment or reshare.
634 if (in_array($item["verb"], array(ACTIVITY_POST, ACTIVITY_SHARE)) &&
635 !dbm::is_result($r) && ($related != "")) {
636 $reply_path = str_replace("/notice/", "/api/statuses/show/", $related).".atom";
638 if ($reply_path != $related) {
639 logger("Fetching related items for user ".$importer["uid"]." from ".$reply_path, LOGGER_DEBUG);
640 $reply_xml = fetch_url($reply_path);
642 $reply_contact = $contact;
643 self::import($reply_xml,$importer,$reply_contact, $reply_hub);
645 // After the import try to fetch the parent item again
646 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
647 intval($importer["uid"]), dbesc($item["parent-uri"]));
650 if (dbm::is_result($r)) {
651 $item["type"] = 'remote-comment';
652 $item["gravity"] = GRAVITY_COMMENT;
655 $item["parent-uri"] = $item["uri"];
657 $item_id = self::completion($conversation, $importer["uid"], $item, $self);
660 // Store the conversation data. This is normally done in "item_store"
661 // but since something went wrong, we want to be sure to save the data.
662 store_conversation($item);
663 logger("Error storing item", LOGGER_DEBUG);
667 logger("Item was stored with id ".$item_id, LOGGER_DEBUG);
672 * @brief Create an url out of an uri
674 * @param string $href URI in the format "parameter1:parameter1:..."
676 * @return string URL in the format http(s)://....
678 public static function convert_href($href) {
679 $elements = explode(":",$href);
681 if ((count($elements) <= 2) || ($elements[0] != "tag"))
684 $server = explode(",", $elements[1]);
685 $conversation = explode("=", $elements[2]);
687 if ((count($elements) == 4) && ($elements[2] == "post"))
688 return "http://".$server[0]."/notice/".$elements[3];
690 if ((count($conversation) != 2) || ($conversation[1] =="")) {
693 if ($elements[3] == "objectType=thread") {
694 return "http://".$server[0]."/conversation/".$conversation[1];
696 return "http://".$server[0]."/notice/".$conversation[1];
702 * @brief Checks if there are entries in conversations that aren't present on our side
704 * @param bool $mentions Fetch conversations where we are mentioned
705 * @param bool $override Override the interval setting
707 public static function check_conversations($mentions = false, $override = false) {
708 $last = get_config('system','ostatus_last_poll');
710 $poll_interval = intval(get_config('system','ostatus_poll_interval'));
711 if (!$poll_interval) {
712 $poll_interval = self::OSTATUS_DEFAULT_POLL_INTERVAL;
715 // Don't poll if the interval is set negative
716 if (($poll_interval < 0) && !$override) {
721 $poll_timeframe = intval(get_config('system','ostatus_poll_timeframe'));
722 if (!$poll_timeframe) {
723 $poll_timeframe = self::OSTATUS_DEFAULT_POLL_TIMEFRAME;
726 $poll_timeframe = intval(get_config('system','ostatus_poll_timeframe'));
727 if (!$poll_timeframe) {
728 $poll_timeframe = self::OSTATUS_DEFAULT_POLL_TIMEFRAME_MENTIONS;
733 if ($last && !$override) {
734 $next = $last + ($poll_interval * 60);
735 if ($next > time()) {
736 logger('poll interval not reached');
741 logger('cron_start');
743 $start = date("Y-m-d H:i:s", time() - ($poll_timeframe * 60));
746 $conversations = q("SELECT `term`.`oid`, `term`.`url`, `term`.`uid` FROM `term`
747 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `term`.`oid` AND `thread`.`uid` = `term`.`uid`
748 WHERE `term`.`type` = 7 AND `term`.`term` > '%s' AND `thread`.`mention`
749 GROUP BY `term`.`url`, `term`.`uid`, `term`.`oid`, `term`.`term` ORDER BY `term`.`term` DESC", dbesc($start));
751 $conversations = q("SELECT `oid`, `url`, `uid` FROM `term`
752 WHERE `type` = 7 AND `term` > '%s'
753 GROUP BY `url`, `uid`, `oid`, `term` ORDER BY `term` DESC", dbesc($start));
756 foreach ($conversations AS $conversation) {
757 self::completion($conversation['url'], $conversation['uid']);
762 set_config('system','ostatus_last_poll', time());
766 * @brief Updates the gcontact table with actor data from the conversation
768 * @param object $actor The actor object that contains the contact data
770 private static function conv_fetch_actor($actor) {
772 // We set the generation to "3" since the data here is not as reliable as the data we get on other occasions
773 $contact = array("network" => NETWORK_OSTATUS, "generation" => 3);
775 if (isset($actor->url))
776 $contact["url"] = $actor->url;
778 if (isset($actor->displayName))
779 $contact["name"] = $actor->displayName;
781 if (isset($actor->portablecontacts_net->displayName))
782 $contact["name"] = $actor->portablecontacts_net->displayName;
784 if (isset($actor->portablecontacts_net->preferredUsername))
785 $contact["nick"] = $actor->portablecontacts_net->preferredUsername;
787 if (isset($actor->id))
788 $contact["alias"] = $actor->id;
790 if (isset($actor->summary))
791 $contact["about"] = $actor->summary;
793 if (isset($actor->portablecontacts_net->note))
794 $contact["about"] = $actor->portablecontacts_net->note;
796 if (isset($actor->portablecontacts_net->addresses->formatted))
797 $contact["location"] = $actor->portablecontacts_net->addresses->formatted;
800 if (isset($actor->image->url))
801 $contact["photo"] = $actor->image->url;
803 if (isset($actor->image->width))
804 $avatarwidth = $actor->image->width;
806 if (is_array($actor->status_net->avatarLinks))
807 foreach ($actor->status_net->avatarLinks AS $avatar) {
808 if ($avatarsize < $avatar->width) {
809 $contact["photo"] = $avatar->url;
810 $avatarsize = $avatar->width;
814 $contact["hide"] = false; // OStatus contacts are never hidden
815 update_gcontact($contact);
819 * @brief Fetches the conversation url for a given item link or conversation id
821 * @param string $self The link to the posting
822 * @param string $conversation_id The conversation id
824 * @return string The conversation url
826 private static function fetch_conversation($self, $conversation_id = "") {
828 if ($conversation_id != "") {
829 $elements = explode(":", $conversation_id);
831 if ((count($elements) <= 2) || ($elements[0] != "tag"))
832 return $conversation_id;
838 $json = str_replace(".atom", ".json", $self);
840 $raw = fetch_url($json);
844 $data = json_decode($raw);
845 if (!is_object($data))
848 $conversation_id = $data->statusnet_conversation_id;
850 $pos = strpos($self, "/api/statuses/show/");
851 $base_url = substr($self, 0, $pos);
853 return $base_url."/conversation/".$conversation_id;
857 * @brief Fetches a shared object from a given conversation object
859 * Sometimes GNU Social seems to fail when returning shared objects.
860 * Then they don't contains all needed data.
861 * We then try to find this object in the conversation
863 * @param string $id Message id
864 * @param object $conversation Conversation object
866 * @return object The shared object
868 private static function shared_object($id, $conversation) {
869 if (!is_array($conversation->items)) {
872 foreach ($conversation->items AS $single_conv) {
873 if ($single_conv->id == $id) {
881 * @brief Fetches actor details of a given actor and user id
883 * @param string $actor The actor url
884 * @param int $uid The user id
885 * @param int $contact_id The default contact-id
887 * @return array Array with actor details
889 private static function get_actor_details($actor, $uid, $contact_id) {
893 $contact = q("SELECT `id`, `rel`, `network` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'",
894 $uid, normalise_link($actor), NETWORK_STATUSNET);
897 $contact = q("SELECT `id`, `rel`, `network` FROM `contact` WHERE `uid` = %d AND `alias` IN ('%s', '%s') AND `network` != '%s'",
898 $uid, $actor, normalise_link($actor), NETWORK_STATUSNET);
901 logger("Found contact for url ".$actor, LOGGER_DEBUG);
902 $details["contact_id"] = $contact[0]["id"];
903 $details["network"] = $contact[0]["network"];
905 $details["not_following"] = !in_array($contact[0]["rel"], array(CONTACT_IS_SHARING, CONTACT_IS_FRIEND));
907 logger("No contact found for user ".$uid." and url ".$actor, LOGGER_DEBUG);
909 // Adding a global contact
910 /// @TODO Use this data for the post
911 $details["global_contact_id"] = get_contact($actor, 0);
913 logger("Global contact ".$global_contact_id." found for url ".$actor, LOGGER_DEBUG);
915 $details["contact_id"] = $contact_id;
916 $details["network"] = NETWORK_OSTATUS;
918 $details["not_following"] = true;
925 * @brief Stores an item and completes the thread
927 * @param string $conversation_url The URI of the conversation
928 * @param integer $uid The user id
929 * @param array $item Data of the item that is to be posted
931 * @return integer The item id of the posted item array
933 private static function completion($conversation_url, $uid, $item = array(), $self = "") {
935 /// @todo This function is totally ugly and has to be rewritten totally
937 // Import all threads or only threads that were started by our followers?
938 $all_threads = !get_config('system','ostatus_full_threads');
942 $conversation_url = self::fetch_conversation($self, $conversation_url);
944 // If the thread shouldn't be completed then store the item and go away
945 // Don't do a completion on liked content
946 if (((intval(get_config('system','ostatus_poll_interval')) == -2) && (count($item) > 0)) ||
947 ($item["verb"] == ACTIVITY_LIKE) || ($conversation_url == "")) {
948 $item_stored = item_store($item, $all_threads);
953 $parents = q("SELECT `item`.`id`, `item`.`parent`, `item`.`uri`, `item`.`contact-id`, `item`.`type`,
954 `item`.`verb`, `item`.`visible` FROM `term`
955 STRAIGHT_JOIN `item` AS `thritem` ON `thritem`.`parent` = `term`.`oid`
956 STRAIGHT_JOIN `item` ON `item`.`parent` = `thritem`.`parent`
957 WHERE `term`.`uid` = %d AND `term`.`otype` = %d AND `term`.`type` = %d AND `term`.`url` = '%s'",
958 intval($uid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION), dbesc($conversation_url));
960 $parent = $parents[0];
961 } elseif (count($item) > 0) {
963 $parent["type"] = "remote";
964 $parent["verb"] = ACTIVITY_POST;
965 $parent["visible"] = 1;
968 $r = q("SELECT `id` FROM `contact` WHERE `self` AND `uid`=%d", $uid);
969 if (!dbm::is_result($r)) {
974 $parent["parent"] = 0;
976 $parent["contact-id"] = $r[0]["id"];
977 $parent["type"] = "remote";
978 $parent["verb"] = ACTIVITY_POST;
979 $parent["visible"] = 1;
982 $conv = str_replace("/conversation/", "/api/statusnet/conversation/", $conversation_url).".as";
986 logger('fetching conversation url '.$conv.' (Self: '.$self.') for user '.$uid);
989 $conv_arr = z_fetch_url($conv."?page=".$pageno);
991 // If it is a non-ssl site and there is an error, then try ssl or vice versa
992 if (!$conv_arr["success"] && (substr($conv, 0, 7) == "http://")) {
993 $conv = str_replace("http://", "https://", $conv);
994 $conv_as = fetch_url($conv."?page=".$pageno);
995 } elseif (!$conv_arr["success"] && (substr($conv, 0, 8) == "https://")) {
996 $conv = str_replace("https://", "http://", $conv);
997 $conv_as = fetch_url($conv."?page=".$pageno);
999 $conv_as = $conv_arr["body"];
1001 $conv_as = str_replace(',"statusnet:notice_info":', ',"statusnet_notice_info":', $conv_as);
1002 $conv_as = json_decode($conv_as);
1004 $no_of_items = sizeof($items);
1006 if (@is_array($conv_as->items))
1007 foreach ($conv_as->items AS $single_item)
1008 $items[$single_item->id] = $single_item;
1010 if ($no_of_items == sizeof($items))
1017 logger('fetching conversation done. Found '.count($items).' items');
1019 if (!sizeof($items)) {
1020 if (count($item) > 0) {
1021 $item_stored = item_store($item, $all_threads);
1024 logger("Conversation ".$conversation_url." couldn't be fetched. Item uri ".$item["uri"]." stored: ".$item_stored, LOGGER_DEBUG);
1025 self::store_conversation($item_id, $conversation_url);
1028 return $item_stored;
1034 $items = array_reverse($items);
1036 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self`", intval($uid));
1041 foreach ($items as $single_conv) {
1043 // Update the gcontact table
1044 self::conv_fetch_actor($single_conv->actor);
1046 // Test - remove before flight
1047 //$tempfile = tempnam(get_temppath(), "conversation");
1048 //file_put_contents($tempfile, json_encode($single_conv));
1052 if (isset($single_conv->object->id))
1053 $single_conv->id = $single_conv->object->id;
1055 $plink = self::convert_href($single_conv->id);
1056 if (isset($single_conv->object->url))
1057 $plink = self::convert_href($single_conv->object->url);
1059 if (@!$single_conv->id)
1062 logger("Got id ".$single_conv->id, LOGGER_DEBUG);
1064 if ($first_id == "") {
1065 $first_id = $single_conv->id;
1067 // The first post of the conversation isn't our first post. There are three options:
1068 // 1. Our conversation hasn't the "real" thread starter
1069 // 2. This first post is a post inside our thread
1070 // 3. This first post is a post inside another thread
1071 if (($first_id != $parent["uri"]) && ($parent["uri"] != "")) {
1075 $new_parents = q("SELECT `id`, `parent`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `id` IN
1076 (SELECT `parent` FROM `item`
1077 WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s')) LIMIT 1",
1078 intval($uid), dbesc($first_id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
1080 if ($new_parents[0]["parent"] == $parent["parent"]) {
1081 // Option 2: This post is already present inside our thread - but not as thread starter
1082 logger("Option 2: uri present in our thread: ".$first_id, LOGGER_DEBUG);
1083 $first_id = $parent["uri"];
1085 // Option 3: Not so good. We have mixed parents. We have to see how to clean this up.
1086 // For now just take the new parent.
1087 $parent = $new_parents[0];
1088 $first_id = $parent["uri"];
1089 logger("Option 3: mixed parents for uri ".$first_id, LOGGER_DEBUG);
1092 // Option 1: We hadn't got the real thread starter
1093 // We have to clean up our existing messages.
1095 $parent["uri"] = $first_id;
1096 logger("Option 1: we have a new parent: ".$first_id, LOGGER_DEBUG);
1098 } elseif ($parent["uri"] == "") {
1100 $parent["uri"] = $first_id;
1104 $parent_uri = $parent["uri"];
1106 // "context" only seems to exist on older servers
1107 if (isset($single_conv->context->inReplyTo->id)) {
1108 $parent_exists = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
1109 intval($uid), dbesc($single_conv->context->inReplyTo->id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
1111 $parent_uri = $single_conv->context->inReplyTo->id;
1114 // This is the current way
1115 if (isset($single_conv->object->inReplyTo->id)) {
1116 $parent_exists = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
1117 intval($uid), dbesc($single_conv->object->inReplyTo->id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
1119 $parent_uri = $single_conv->object->inReplyTo->id;
1122 $message_exists = q("SELECT `id`, `parent`, `uri` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
1123 intval($uid), dbesc($single_conv->id),
1124 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
1125 if ($message_exists) {
1126 logger("Message ".$single_conv->id." already existed on the system", LOGGER_DEBUG);
1128 if ($parent["id"] != 0) {
1129 $existing_message = $message_exists[0];
1131 // We improved the way we fetch OStatus messages, this shouldn't happen very often now
1132 /// @TODO We have to change the shadow copies as well. This way here is really ugly.
1133 if ($existing_message["parent"] != $parent["id"]) {
1134 logger('updating id '.$existing_message["id"].' with parent '.$existing_message["parent"].' to parent '.$parent["id"].' uri '.$parent["uri"].' thread '.$parent_uri, LOGGER_DEBUG);
1136 // Update the parent id of the selected item
1137 $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s' WHERE `id` = %d",
1138 intval($parent["id"]), dbesc($parent["uri"]), intval($existing_message["id"]));
1140 // Update the parent uri in the thread - but only if it points to itself
1141 $r = q("UPDATE `item` SET `thr-parent` = '%s' WHERE `id` = %d AND `uri` = `thr-parent`",
1142 dbesc($parent_uri), intval($existing_message["id"]));
1144 // try to change all items of the same parent
1145 $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s' WHERE `parent` = %d",
1146 intval($parent["id"]), dbesc($parent["uri"]), intval($existing_message["parent"]));
1148 // Update the parent uri in the thread - but only if it points to itself
1149 $r = q("UPDATE `item` SET `thr-parent` = '%s' WHERE (`parent` = %d) AND (`uri` = `thr-parent`)",
1150 dbesc($parent["uri"]), intval($existing_message["parent"]));
1152 // Now delete the thread
1153 delete_thread($existing_message["parent"]);
1157 // The item we are having on the system is the one that we wanted to store via the item array
1158 if (isset($item["uri"]) && ($item["uri"] == $existing_message["uri"])) {
1166 if (is_array($single_conv->to))
1167 foreach ($single_conv->to AS $to)
1168 if ($importer["nurl"] == normalise_link($to->id))
1171 $actor = $single_conv->actor->id;
1172 if (isset($single_conv->actor->url))
1173 $actor = $single_conv->actor->url;
1175 $details = self::get_actor_details($actor, $uid, $parent["contact-id"]);
1177 // Do we only want to import threads that were started by our contacts?
1178 if ($details["not_following"] && $new_parent && get_config('system','ostatus_full_threads')) {
1179 logger("Don't import uri ".$first_id." because user ".$uid." doesn't follow the person ".$actor, LOGGER_DEBUG);
1183 /// @TODO One statment is okay (until if () )
1185 $arr["network"] = $details["network"];
1186 $arr["uri"] = $single_conv->id;
1187 $arr["plink"] = $plink;
1189 $arr["contact-id"] = $details["contact_id"];
1190 $arr["parent-uri"] = $parent_uri;
1191 $arr["created"] = $single_conv->published;
1192 $arr["edited"] = $single_conv->published;
1193 $arr["owner-name"] = $single_conv->actor->displayName;
1194 if ($arr["owner-name"] == '')
1195 $arr["owner-name"] = $single_conv->actor->contact->displayName;
1196 if ($arr["owner-name"] == '')
1197 $arr["owner-name"] = $single_conv->actor->portablecontacts_net->displayName;
1199 $arr["owner-link"] = $actor;
1200 $arr["owner-avatar"] = Probe::fixAvatar($single_conv->actor->image->url, $arr["owner-link"]);
1202 $arr["author-name"] = $arr["owner-name"];
1203 $arr["author-link"] = $arr["owner-link"];
1204 $arr["author-avatar"] = $arr["owner-avatar"];
1205 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->content));
1207 if (isset($single_conv->status_net->conversation)) {
1208 $arr['conversation-uri'] = $single_conv->status_net->conversation;
1211 if (isset($single_conv->status_net->notice_info->source)) {
1212 $arr["app"] = strip_tags($single_conv->status_net->notice_info->source);
1213 } elseif (isset($single_conv->statusnet->notice_info->source)) {
1214 $arr["app"] = strip_tags($single_conv->statusnet->notice_info->source);
1215 } elseif (isset($single_conv->statusnet_notice_info->source)) {
1216 $arr["app"] = strip_tags($single_conv->statusnet_notice_info->source);
1217 } elseif (isset($single_conv->provider->displayName)) {
1218 $arr["app"] = $single_conv->provider->displayName;
1220 $arr["app"] = "OStatus";
1223 $arr["source"] = json_encode($single_conv);
1224 $arr["protocol"] = PROTOCOL_GS_CONVERSATION;
1226 $arr["verb"] = $parent["verb"];
1227 $arr["visible"] = $parent["visible"];
1228 $arr["location"] = $single_conv->location->displayName;
1229 $arr["coord"] = trim($single_conv->location->lat." ".$single_conv->location->lon);
1231 // Is it a reshared item?
1232 if (isset($single_conv->verb) && ($single_conv->verb == "share") && isset($single_conv->object)) {
1233 if (is_array($single_conv->object))
1234 $single_conv->object = $single_conv->object[0];
1236 // Sometimes GNU Social doesn't returns a complete object
1237 if (!isset($single_conv->object->actor->url)) {
1238 $object = self::shared_object($single_conv->object->id, $conversation);
1239 if (is_object($object)) {
1240 $single_conv->object = $object;
1244 if (isset($single_conv->object->actor->url)) {
1245 logger("Found reshared item ".$single_conv->object->id);
1247 // $single_conv->object->context->conversation;
1249 if (isset($single_conv->object->object->id)) {
1250 $arr["uri"] = $single_conv->object->object->id;
1252 $arr["uri"] = $single_conv->object->id;
1254 if (isset($single_conv->object->object->url)) {
1255 $plink = self::convert_href($single_conv->object->object->url);
1257 $plink = self::convert_href($single_conv->object->url);
1259 if (isset($single_conv->object->object->content)) {
1260 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->object->content));
1262 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->content));
1264 $arr["plink"] = $plink;
1266 $arr["created"] = $single_conv->object->published;
1267 $arr["edited"] = $single_conv->object->published;
1269 $arr["author-name"] = $single_conv->object->actor->displayName;
1270 if ($arr["owner-name"] == '') {
1271 $arr["author-name"] = $single_conv->object->actor->contact->displayName;
1273 $arr["author-link"] = $single_conv->object->actor->url;
1274 $arr["author-avatar"] = Probe::fixAvatar($single_conv->object->actor->image->url, $arr["author-link"]);
1276 $arr["app"] = $single_conv->object->provider->displayName."#";
1277 //$arr["verb"] = $single_conv->object->verb;
1279 $arr["location"] = $single_conv->object->location->displayName;
1280 $arr["coord"] = trim($single_conv->object->location->lat." ".$single_conv->object->location->lon);
1284 if ($arr["location"] == "")
1285 unset($arr["location"]);
1287 if ($arr["coord"] == "")
1288 unset($arr["coord"]);
1290 // Copy fields from given item array
1291 if (isset($item["uri"]) && (($item["uri"] == $arr["uri"]) || ($item["uri"] == $single_conv->id))) {
1292 logger('Use stored item array for item with URI '.$item["uri"], LOGGER_DEBUG);
1293 $newitem = item_store($item);
1295 $item_stored = $newitem;
1297 $newitem = item_store($arr);
1301 logger("Item wasn't stored ".print_r($arr, true), LOGGER_DEBUG);
1305 logger('Stored new item '.$plink.' for parent '.$arr["parent-uri"].' under id '.$newitem, LOGGER_DEBUG);
1307 // Add the conversation entry (but don't fetch the whole conversation)
1308 self::store_conversation($newitem, $conversation_url);
1310 // If the newly created item is the top item then change the parent settings of the thread
1311 // This shouldn't happen anymore. This is supposed to be absolote.
1312 if ($arr["uri"] == $first_id) {
1313 logger('setting new parent to id '.$newitem);
1314 $new_parents = q("SELECT `id`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `uid` = %d AND `id` = %d LIMIT 1",
1315 intval($uid), intval($newitem));
1317 $parent = $new_parents[0];
1321 if (($item_stored < 0) && (count($item) > 0)) {
1323 if (get_config('system','ostatus_full_threads')) {
1324 $details = self::get_actor_details($item["owner-link"], $uid, $item["contact-id"]);
1325 if ($details["not_following"]) {
1326 logger("Don't import uri ".$item["uri"]." because user ".$uid." doesn't follow the person ".$item["owner-link"], LOGGER_DEBUG);
1331 $item_stored = item_store($item, $all_threads);
1333 logger("Uri ".$item["uri"]." wasn't found in conversation ".$conversation_url, LOGGER_DEBUG);
1334 self::store_conversation($item_stored, $conversation_url);
1338 return $item_stored;
1342 * @brief Stores conversation data into the database
1344 * @param integer $itemid The id of the item
1345 * @param string $conversation_url The uri of the conversation
1347 private static function store_conversation($itemid, $conversation_url) {
1349 $conversation_url = self::convert_href($conversation_url);
1351 $messages = q("SELECT `uid`, `parent`, `created`, `received`, `guid` FROM `item` WHERE `id` = %d LIMIT 1", intval($itemid));
1354 $message = $messages[0];
1356 // Store conversation url if not done before
1357 $conversation = q("SELECT `url` FROM `term` WHERE `uid` = %d AND `oid` = %d AND `otype` = %d AND `type` = %d",
1358 intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION));
1360 if (!$conversation) {
1361 $r = q("INSERT INTO `term` (`uid`, `oid`, `otype`, `type`, `term`, `url`, `created`, `received`, `guid`) VALUES (%d, %d, %d, %d, '%s', '%s', '%s', '%s', '%s')",
1362 intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION),
1363 dbesc($message["created"]), dbesc($conversation_url), dbesc($message["created"]), dbesc($message["received"]), dbesc($message["guid"]));
1364 logger('Storing conversation url '.$conversation_url.' for id '.$itemid);
1369 * @brief Checks if the current post is a reshare
1371 * @param array $item The item array of thw post
1373 * @return string The guid if the post is a reshare
1375 private static function get_reshared_guid($item) {
1376 $body = trim($item["body"]);
1378 // Skip if it isn't a pure repeated messages
1379 // Does it start with a share?
1380 if (strpos($body, "[share") > 0)
1383 // Does it end with a share?
1384 if (strlen($body) > (strrpos($body, "[/share]") + 8))
1387 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
1388 // Skip if there is no shared message in there
1389 if ($body == $attributes)
1393 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
1394 if ($matches[1] != "")
1395 $guid = $matches[1];
1397 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
1398 if ($matches[1] != "")
1399 $guid = $matches[1];
1405 * @brief Cleans the body of a post if it contains picture links
1407 * @param string $body The body
1409 * @return string The cleaned body
1411 private static function format_picture_post($body) {
1412 $siteinfo = get_attached_data($body);
1414 if (($siteinfo["type"] == "photo")) {
1415 if (isset($siteinfo["preview"]))
1416 $preview = $siteinfo["preview"];
1418 $preview = $siteinfo["image"];
1420 // Is it a remote picture? Then make a smaller preview here
1421 $preview = proxy_url($preview, false, PROXY_SIZE_SMALL);
1423 // Is it a local picture? Then make it smaller here
1424 $preview = str_replace(array("-0.jpg", "-0.png"), array("-2.jpg", "-2.png"), $preview);
1425 $preview = str_replace(array("-1.jpg", "-1.png"), array("-2.jpg", "-2.png"), $preview);
1427 if (isset($siteinfo["url"]))
1428 $url = $siteinfo["url"];
1430 $url = $siteinfo["image"];
1432 $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1439 * @brief Adds the header elements to the XML document
1441 * @param object $doc XML document
1442 * @param array $owner Contact data of the poster
1444 * @return object header root element
1446 private static function add_header($doc, $owner) {
1450 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
1451 $doc->appendChild($root);
1453 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1454 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1455 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1456 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1457 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
1458 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1459 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1460 $root->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1462 $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
1463 xml::add_element($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1464 xml::add_element($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]);
1465 xml::add_element($doc, $root, "title", sprintf("%s timeline", $owner["name"]));
1466 xml::add_element($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], $a->config["sitename"]));
1467 xml::add_element($doc, $root, "logo", $owner["photo"]);
1468 xml::add_element($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
1470 $author = self::add_author($doc, $owner);
1471 $root->appendChild($author);
1473 $attributes = array("href" => $owner["url"], "rel" => "alternate", "type" => "text/html");
1474 xml::add_element($doc, $root, "link", "", $attributes);
1476 /// @TODO We have to find out what this is
1477 /// $attributes = array("href" => System::baseUrl()."/sup",
1478 /// "rel" => "http://api.friendfeed.com/2008/03#sup",
1479 /// "type" => "application/json");
1480 /// xml::add_element($doc, $root, "link", "", $attributes);
1482 self::hublinks($doc, $root, $owner["nick"]);
1484 $attributes = array("href" => System::baseUrl()."/salmon/".$owner["nick"], "rel" => "salmon");
1485 xml::add_element($doc, $root, "link", "", $attributes);
1487 $attributes = array("href" => System::baseUrl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies");
1488 xml::add_element($doc, $root, "link", "", $attributes);
1490 $attributes = array("href" => System::baseUrl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention");
1491 xml::add_element($doc, $root, "link", "", $attributes);
1493 $attributes = array("href" => System::baseUrl()."/api/statuses/user_timeline/".$owner["nick"].".atom",
1494 "rel" => "self", "type" => "application/atom+xml");
1495 xml::add_element($doc, $root, "link", "", $attributes);
1501 * @brief Add the link to the push hubs to the XML document
1503 * @param object $doc XML document
1504 * @param object $root XML root element where the hub links are added
1506 public static function hublinks($doc, $root, $nick) {
1507 $h = System::baseUrl() . '/pubsubhubbub/'.$nick;
1508 xml::add_element($doc, $root, "link", "", array("href" => $h, "rel" => "hub"));
1512 * @brief Adds attachement data to the XML document
1514 * @param object $doc XML document
1515 * @param object $root XML root element where the hub links are added
1516 * @param array $item Data of the item that is to be posted
1518 private static function get_attachment($doc, $root, $item) {
1520 $siteinfo = get_attached_data($item["body"]);
1522 switch ($siteinfo["type"]) {
1524 $imgdata = get_photo_info($siteinfo["image"]);
1525 $attributes = array("rel" => "enclosure",
1526 "href" => $siteinfo["image"],
1527 "type" => $imgdata["mime"],
1528 "length" => intval($imgdata["size"]));
1529 xml::add_element($doc, $root, "link", "", $attributes);
1532 $attributes = array("rel" => "enclosure",
1533 "href" => $siteinfo["url"],
1534 "type" => "text/html; charset=UTF-8",
1536 "title" => $siteinfo["title"]);
1537 xml::add_element($doc, $root, "link", "", $attributes);
1543 if (!Config::get('system', 'ostatus_not_attach_preview') && ($siteinfo["type"] != "photo") && isset($siteinfo["image"])) {
1544 $imgdata = get_photo_info($siteinfo["image"]);
1545 $attributes = array("rel" => "enclosure",
1546 "href" => $siteinfo["image"],
1547 "type" => $imgdata["mime"],
1548 "length" => intval($imgdata["size"]));
1550 xml::add_element($doc, $root, "link", "", $attributes);
1553 $arr = explode('[/attach],', $item['attach']);
1555 foreach ($arr as $r) {
1557 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1559 $attributes = array("rel" => "enclosure",
1560 "href" => $matches[1],
1561 "type" => $matches[3]);
1563 if (intval($matches[2])) {
1564 $attributes["length"] = intval($matches[2]);
1566 if (trim($matches[4]) != "") {
1567 $attributes["title"] = trim($matches[4]);
1569 xml::add_element($doc, $root, "link", "", $attributes);
1576 * @brief Adds the author element to the XML document
1578 * @param object $doc XML document
1579 * @param array $owner Contact data of the poster
1581 * @return object author element
1583 private static function add_author($doc, $owner) {
1585 $r = q("SELECT `homepage`, `publish` FROM `profile` WHERE `uid` = %d AND `is-default` LIMIT 1", intval($owner["uid"]));
1586 if (dbm::is_result($r)) {
1589 $author = $doc->createElement("author");
1590 xml::add_element($doc, $author, "id", $owner["url"]);
1591 xml::add_element($doc, $author, "activity:object-type", ACTIVITY_OBJ_PERSON);
1592 xml::add_element($doc, $author, "uri", $owner["url"]);
1593 xml::add_element($doc, $author, "name", $owner["nick"]);
1594 xml::add_element($doc, $author, "email", $owner["addr"]);
1595 xml::add_element($doc, $author, "summary", bbcode($owner["about"], false, false, 7));
1597 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $owner["url"]);
1598 xml::add_element($doc, $author, "link", "", $attributes);
1600 $attributes = array(
1602 "type" => "image/jpeg", // To-Do?
1603 "media:width" => 175,
1604 "media:height" => 175,
1605 "href" => $owner["photo"]);
1606 xml::add_element($doc, $author, "link", "", $attributes);
1608 if (isset($owner["thumb"])) {
1609 $attributes = array(
1611 "type" => "image/jpeg", // To-Do?
1612 "media:width" => 80,
1613 "media:height" => 80,
1614 "href" => $owner["thumb"]);
1615 xml::add_element($doc, $author, "link", "", $attributes);
1618 xml::add_element($doc, $author, "poco:preferredUsername", $owner["nick"]);
1619 xml::add_element($doc, $author, "poco:displayName", $owner["name"]);
1620 xml::add_element($doc, $author, "poco:note", bbcode($owner["about"], false, false, 7));
1622 if (trim($owner["location"]) != "") {
1623 $element = $doc->createElement("poco:address");
1624 xml::add_element($doc, $element, "poco:formatted", $owner["location"]);
1625 $author->appendChild($element);
1628 if (trim($profile["homepage"]) != "") {
1629 $urls = $doc->createElement("poco:urls");
1630 xml::add_element($doc, $urls, "poco:type", "homepage");
1631 xml::add_element($doc, $urls, "poco:value", $profile["homepage"]);
1632 xml::add_element($doc, $urls, "poco:primary", "true");
1633 $author->appendChild($urls);
1636 if (count($profile)) {
1637 xml::add_element($doc, $author, "followers", "", array("url" => System::baseUrl()."/viewcontacts/".$owner["nick"]));
1638 xml::add_element($doc, $author, "statusnet:profile_info", "", array("local_id" => $owner["uid"]));
1641 if ($profile["publish"]) {
1642 xml::add_element($doc, $author, "mastodon:scope", "public");
1648 * @TODO Picture attachments should look like this:
1649 * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1650 * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1655 * @brief Returns the given activity if present - otherwise returns the "post" activity
1657 * @param array $item Data of the item that is to be posted
1659 * @return string activity
1661 private static function construct_verb($item) {
1663 return $item['verb'];
1664 return ACTIVITY_POST;
1668 * @brief Returns the given object type if present - otherwise returns the "note" object type
1670 * @param array $item Data of the item that is to be posted
1672 * @return string Object type
1674 private static function construct_objecttype($item) {
1675 if (in_array($item['object-type'], array(ACTIVITY_OBJ_NOTE, ACTIVITY_OBJ_COMMENT)))
1676 return $item['object-type'];
1677 return ACTIVITY_OBJ_NOTE;
1681 * @brief Adds an entry element to the XML document
1683 * @param object $doc XML document
1684 * @param array $item Data of the item that is to be posted
1685 * @param array $owner Contact data of the poster
1686 * @param bool $toplevel
1688 * @return object Entry element
1690 private static function entry($doc, $item, $owner, $toplevel = false) {
1691 $repeated_guid = self::get_reshared_guid($item);
1692 if ($repeated_guid != "")
1693 $xml = self::reshare_entry($doc, $item, $owner, $repeated_guid, $toplevel);
1698 if ($item["verb"] == ACTIVITY_LIKE) {
1699 return self::like_entry($doc, $item, $owner, $toplevel);
1700 } elseif (in_array($item["verb"], array(ACTIVITY_FOLLOW, NAMESPACE_OSTATUS."/unfollow"))) {
1701 return self::follow_entry($doc, $item, $owner, $toplevel);
1703 return self::note_entry($doc, $item, $owner, $toplevel);
1708 * @brief Adds a source entry to the XML document
1710 * @param object $doc XML document
1711 * @param array $contact Array of the contact that is added
1713 * @return object Source element
1715 private static function source_entry($doc, $contact) {
1716 $source = $doc->createElement("source");
1717 xml::add_element($doc, $source, "id", $contact["poll"]);
1718 xml::add_element($doc, $source, "title", $contact["name"]);
1719 xml::add_element($doc, $source, "link", "", array("rel" => "alternate",
1720 "type" => "text/html",
1721 "href" => $contact["alias"]));
1722 xml::add_element($doc, $source, "link", "", array("rel" => "self",
1723 "type" => "application/atom+xml",
1724 "href" => $contact["poll"]));
1725 xml::add_element($doc, $source, "icon", $contact["photo"]);
1726 xml::add_element($doc, $source, "updated", datetime_convert("UTC","UTC",$contact["success_update"]."+00:00",ATOM_TIME));
1732 * @brief Fetches contact data from the contact or the gcontact table
1734 * @param string $url URL of the contact
1735 * @param array $owner Contact data of the poster
1737 * @return array Contact array
1739 private static function contact_entry($url, $owner) {
1741 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
1742 dbesc(normalise_link($url)), intval($owner["uid"]));
1743 if (dbm::is_result($r)) {
1745 $contact["uid"] = -1;
1748 if (!dbm::is_result($r)) {
1749 $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1750 dbesc(normalise_link($url)));
1751 if (dbm::is_result($r)) {
1753 $contact["uid"] = -1;
1754 $contact["success_update"] = $contact["updated"];
1758 if (!dbm::is_result($r))
1761 if (!isset($contact["poll"])) {
1762 $data = probe_url($url);
1763 $contact["poll"] = $data["poll"];
1765 if (!$contact["alias"])
1766 $contact["alias"] = $data["alias"];
1769 if (!isset($contact["alias"]))
1770 $contact["alias"] = $contact["url"];
1776 * @brief Adds an entry element with reshared content
1778 * @param object $doc XML document
1779 * @param array $item Data of the item that is to be posted
1780 * @param array $owner Contact data of the poster
1781 * @param $repeated_guid
1782 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1784 * @return object Entry element
1786 private static function reshare_entry($doc, $item, $owner, $repeated_guid, $toplevel) {
1788 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1789 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1792 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1794 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' AND NOT `private` AND `network` IN ('%s', '%s', '%s') LIMIT 1",
1795 intval($owner["uid"]), dbesc($repeated_guid),
1796 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS));
1797 if (dbm::is_result($r)) {
1798 $repeated_item = $r[0];
1802 $contact = self::contact_entry($repeated_item['author-link'], $owner);
1804 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1806 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1808 self::entry_content($doc, $entry, $item, $owner, $title, ACTIVITY_SHARE, false);
1810 $as_object = $doc->createElement("activity:object");
1812 xml::add_element($doc, $as_object, "activity:object-type", NAMESPACE_ACTIVITY_SCHEMA."activity");
1814 self::entry_content($doc, $as_object, $repeated_item, $owner, "", "", false);
1816 $author = self::add_author($doc, $contact);
1817 $as_object->appendChild($author);
1819 $as_object2 = $doc->createElement("activity:object");
1821 xml::add_element($doc, $as_object2, "activity:object-type", self::construct_objecttype($repeated_item));
1823 $title = sprintf("New comment by %s", $contact["nick"]);
1825 self::entry_content($doc, $as_object2, $repeated_item, $owner, $title);
1827 $as_object->appendChild($as_object2);
1829 self::entry_footer($doc, $as_object, $item, $owner, false);
1831 $source = self::source_entry($doc, $contact);
1833 $as_object->appendChild($source);
1835 $entry->appendChild($as_object);
1837 self::entry_footer($doc, $entry, $item, $owner);
1843 * @brief Adds an entry element with a "like"
1845 * @param object $doc XML document
1846 * @param array $item Data of the item that is to be posted
1847 * @param array $owner Contact data of the poster
1848 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1850 * @return object Entry element with "like"
1852 private static function like_entry($doc, $item, $owner, $toplevel) {
1854 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1855 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1858 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1860 $verb = NAMESPACE_ACTIVITY_SCHEMA."favorite";
1861 self::entry_content($doc, $entry, $item, $owner, "Favorite", $verb, false);
1863 $as_object = $doc->createElement("activity:object");
1865 $parent = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d",
1866 dbesc($item["thr-parent"]), intval($item["uid"]));
1867 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1869 xml::add_element($doc, $as_object, "activity:object-type", self::construct_objecttype($parent[0]));
1871 self::entry_content($doc, $as_object, $parent[0], $owner, "New entry");
1873 $entry->appendChild($as_object);
1875 self::entry_footer($doc, $entry, $item, $owner);
1881 * @brief Adds the person object element to the XML document
1883 * @param object $doc XML document
1884 * @param array $owner Contact data of the poster
1885 * @param array $contact Contact data of the target
1887 * @return object author element
1889 private static function add_person_object($doc, $owner, $contact) {
1891 $object = $doc->createElement("activity:object");
1892 xml::add_element($doc, $object, "activity:object-type", ACTIVITY_OBJ_PERSON);
1894 if ($contact['network'] == NETWORK_PHANTOM) {
1895 xml::add_element($doc, $object, "id", $contact['url']);
1899 xml::add_element($doc, $object, "id", $contact["alias"]);
1900 xml::add_element($doc, $object, "title", $contact["nick"]);
1902 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $contact["url"]);
1903 xml::add_element($doc, $object, "link", "", $attributes);
1905 $attributes = array(
1907 "type" => "image/jpeg", // To-Do?
1908 "media:width" => 175,
1909 "media:height" => 175,
1910 "href" => $contact["photo"]);
1911 xml::add_element($doc, $object, "link", "", $attributes);
1913 xml::add_element($doc, $object, "poco:preferredUsername", $contact["nick"]);
1914 xml::add_element($doc, $object, "poco:displayName", $contact["name"]);
1916 if (trim($contact["location"]) != "") {
1917 $element = $doc->createElement("poco:address");
1918 xml::add_element($doc, $element, "poco:formatted", $contact["location"]);
1919 $object->appendChild($element);
1926 * @brief Adds a follow/unfollow entry element
1928 * @param object $doc XML document
1929 * @param array $item Data of the follow/unfollow message
1930 * @param array $owner Contact data of the poster
1931 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1933 * @return object Entry element
1935 private static function follow_entry($doc, $item, $owner, $toplevel) {
1937 $item["id"] = $item["parent"] = 0;
1938 $item["created"] = $item["edited"] = date("c");
1939 $item["private"] = true;
1941 $contact = Probe::uri($item['follow']);
1943 if ($contact['alias'] == '') {
1944 $contact['alias'] = $contact["url"];
1946 $item['follow'] = $contact['alias'];
1949 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1950 intval($owner['uid']), dbesc(normalise_link($contact["url"])));
1952 if (dbm::is_result($r)) {
1953 $connect_id = $r[0]['id'];
1958 if ($item['verb'] == ACTIVITY_FOLLOW) {
1959 $message = t('%s is now following %s.');
1960 $title = t('following');
1961 $action = "subscription";
1963 $message = t('%s stopped following %s.');
1964 $title = t('stopped following');
1965 $action = "unfollow";
1968 $item["uri"] = $item['parent-uri'] = $item['thr-parent'] =
1969 'tag:'.get_app()->get_hostname().
1970 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1971 ':person:'.$connect_id.':'.$item['created'];
1973 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1975 self::entry_header($doc, $entry, $owner, $toplevel);
1977 self::entry_content($doc, $entry, $item, $owner, $title);
1979 $object = self::add_person_object($doc, $owner, $contact);
1980 $entry->appendChild($object);
1982 self::entry_footer($doc, $entry, $item, $owner);
1988 * @brief Adds a regular entry element
1990 * @param object $doc XML document
1991 * @param array $item Data of the item that is to be posted
1992 * @param array $owner Contact data of the poster
1993 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1995 * @return object Entry element
1997 private static function note_entry($doc, $item, $owner, $toplevel) {
1999 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
2000 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
2003 $title = self::entry_header($doc, $entry, $owner, $toplevel);
2005 xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
2007 self::entry_content($doc, $entry, $item, $owner, $title);
2009 self::entry_footer($doc, $entry, $item, $owner);
2015 * @brief Adds a header element to the XML document
2017 * @param object $doc XML document
2018 * @param object $entry The entry element where the elements are added
2019 * @param array $owner Contact data of the poster
2020 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
2022 * @return string The title for the element
2024 private static function entry_header($doc, &$entry, $owner, $toplevel) {
2025 /// @todo Check if this title stuff is really needed (I guess not)
2027 $entry = $doc->createElement("entry");
2028 $title = sprintf("New note by %s", $owner["nick"]);
2030 $entry = $doc->createElementNS(NAMESPACE_ATOM1, "entry");
2032 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
2033 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
2034 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
2035 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
2036 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
2037 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
2038 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
2039 $entry->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
2041 $author = self::add_author($doc, $owner);
2042 $entry->appendChild($author);
2044 $title = sprintf("New comment by %s", $owner["nick"]);
2050 * @brief Adds elements to the XML document
2052 * @param object $doc XML document
2053 * @param object $entry Entry element where the content is added
2054 * @param array $item Data of the item that is to be posted
2055 * @param array $owner Contact data of the poster
2056 * @param string $title Title for the post
2057 * @param string $verb The activity verb
2058 * @param bool $complete Add the "status_net" element?
2060 private static function entry_content($doc, $entry, $item, $owner, $title, $verb = "", $complete = true) {
2063 $verb = self::construct_verb($item);
2065 xml::add_element($doc, $entry, "id", $item["uri"]);
2066 xml::add_element($doc, $entry, "title", $title);
2068 $body = self::format_picture_post($item['body']);
2070 if ($item['title'] != "")
2071 $body = "[b]".$item['title']."[/b]\n\n".$body;
2073 $body = bbcode($body, false, false, 7);
2075 xml::add_element($doc, $entry, "content", $body, array("type" => "html"));
2077 xml::add_element($doc, $entry, "link", "", array("rel" => "alternate", "type" => "text/html",
2078 "href" => System::baseUrl()."/display/".$item["guid"]));
2080 if ($complete && ($item["id"] > 0))
2081 xml::add_element($doc, $entry, "status_net", "", array("notice_id" => $item["id"]));
2083 xml::add_element($doc, $entry, "activity:verb", $verb);
2085 xml::add_element($doc, $entry, "published", datetime_convert("UTC","UTC",$item["created"]."+00:00",ATOM_TIME));
2086 xml::add_element($doc, $entry, "updated", datetime_convert("UTC","UTC",$item["edited"]."+00:00",ATOM_TIME));
2090 * @brief Adds the elements at the foot of an entry to the XML document
2092 * @param object $doc XML document
2093 * @param object $entry The entry element where the elements are added
2094 * @param array $item Data of the item that is to be posted
2095 * @param array $owner Contact data of the poster
2098 private static function entry_footer($doc, $entry, $item, $owner, $complete = true) {
2100 $mentioned = array();
2102 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
2103 $parent = q("SELECT `guid`, `author-link`, `owner-link` FROM `item` WHERE `id` = %d", intval($item["parent"]));
2104 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
2106 $thrparent = q("SELECT `guid`, `author-link`, `owner-link`, `plink` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
2107 intval($owner["uid"]),
2108 dbesc($parent_item));
2110 $mentioned[$thrparent[0]["author-link"]] = $thrparent[0]["author-link"];
2111 $mentioned[$thrparent[0]["owner-link"]] = $thrparent[0]["owner-link"];
2112 $parent_plink = $thrparent[0]["plink"];
2114 $mentioned[$parent[0]["author-link"]] = $parent[0]["author-link"];
2115 $mentioned[$parent[0]["owner-link"]] = $parent[0]["owner-link"];
2116 $parent_plink = System::baseUrl()."/display/".$parent[0]["guid"];
2119 $attributes = array(
2120 "ref" => $parent_item,
2121 "href" => $parent_plink);
2122 xml::add_element($doc, $entry, "thr:in-reply-to", "", $attributes);
2124 $attributes = array(
2126 "href" => $parent_plink);
2127 xml::add_element($doc, $entry, "link", "", $attributes);
2130 if (intval($item["parent"]) > 0) {
2131 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
2132 $conversation_uri = $conversation_href;
2134 if (isset($parent_item)) {
2135 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $parent_item);
2136 if (dbm::is_result($r)) {
2137 if ($r['conversation-uri'] != '') {
2138 $conversation_uri = $r['conversation-uri'];
2140 if ($r['conversation-href'] != '') {
2141 $conversation_href = $r['conversation-href'];
2146 xml::add_element($doc, $entry, "link", "", array("rel" => "ostatus:conversation", "href" => $conversation_href));
2148 $attributes = array(
2149 "href" => $conversation_href,
2150 "local_id" => $item["parent"],
2151 "ref" => $conversation_uri);
2153 xml::add_element($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
2156 $tags = item_getfeedtags($item);
2159 foreach ($tags as $t)
2161 $mentioned[$t[1]] = $t[1];
2163 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
2164 $newmentions = array();
2165 foreach ($mentioned AS $mention) {
2166 $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
2167 $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
2169 $mentioned = $newmentions;
2171 foreach ($mentioned AS $mention) {
2172 $r = q("SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
2173 intval($owner["uid"]),
2174 dbesc(normalise_link($mention)));
2175 if ($r[0]["forum"] || $r[0]["prv"])
2176 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
2177 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
2178 "href" => $mention));
2180 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
2181 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
2182 "href" => $mention));
2185 if (!$item["private"]) {
2186 xml::add_element($doc, $entry, "link", "", array("rel" => "ostatus:attention",
2187 "href" => "http://activityschema.org/collection/public"));
2188 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
2189 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
2190 "href" => "http://activityschema.org/collection/public"));
2191 xml::add_element($doc, $entry, "mastodon:scope", "public");
2195 foreach ($tags as $t)
2197 xml::add_element($doc, $entry, "category", "", array("term" => $t[2]));
2199 self::get_attachment($doc, $entry, $item);
2201 if ($complete && ($item["id"] > 0)) {
2202 $app = $item["app"];
2206 $attributes = array("local_id" => $item["id"], "source" => $app);
2208 if (isset($parent["id"]))
2209 $attributes["repeat_of"] = $parent["id"];
2211 if ($item["coord"] != "")
2212 xml::add_element($doc, $entry, "georss:point", $item["coord"]);
2214 xml::add_element($doc, $entry, "statusnet:notice_info", "", $attributes);
2219 * @brief Creates the XML feed for a given nickname
2221 * @param App $a The application class
2222 * @param string $owner_nick Nickname of the feed owner
2223 * @param string $last_update Date of the last update
2224 * @param integer $max_items Number of maximum items to fetch
2226 * @return string XML feed
2228 public static function feed(App $a, $owner_nick, &$last_update, $max_items = 300) {
2229 $stamp = microtime(true);
2231 $cachekey = "ostatus:feed:".$owner_nick.":".$last_update;
2233 $previous_created = $last_update;
2235 $result = Cache::get($cachekey);
2236 if (!is_null($result)) {
2237 logger('Feed duration: '.number_format(microtime(true) - $stamp, 3).' - '.$owner_nick.' - '.$previous_created.' (cached)', LOGGER_DEBUG);
2238 $last_update = $result['last_update'];
2239 return $result['feed'];
2242 $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`
2243 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
2244 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
2245 dbesc($owner_nick));
2246 if (!dbm::is_result($r)) {
2252 if (!strlen($last_update)) {
2253 $last_update = 'now -30 days';
2256 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
2257 $authorid = get_contact($owner["url"], 0);
2259 $items = q("SELECT `item`.*, `item`.`id` AS `item_id` FROM `item` USE INDEX (`uid_contactid_created`)
2260 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `item`.`parent`
2261 WHERE `item`.`uid` = %d AND `item`.`contact-id` = %d AND
2262 `item`.`author-id` = %d AND `item`.`created` > '%s' AND
2263 NOT `item`.`deleted` AND NOT `item`.`private` AND
2264 `thread`.`network` IN ('%s', '%s')
2265 ORDER BY `item`.`created` DESC LIMIT %d",
2266 intval($owner["uid"]), intval($owner["id"]),
2267 intval($authorid), dbesc($check_date),
2268 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN), intval($max_items));
2270 $doc = new DOMDocument('1.0', 'utf-8');
2271 $doc->formatOutput = true;
2273 $root = self::add_header($doc, $owner);
2275 foreach ($items AS $item) {
2276 if (Config::get('system', 'ostatus_debug')) {
2277 $item['body'] .= '🍼';
2279 $entry = self::entry($doc, $item, $owner);
2280 $root->appendChild($entry);
2282 if ($last_update < $item['created']) {
2283 $last_update = $item['created'];
2287 $feeddata = trim($doc->saveXML());
2289 $msg = array('feed' => $feeddata, 'last_update' => $last_update);
2290 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
2292 logger('Feed duration: '.number_format(microtime(true) - $stamp, 3).' - '.$owner_nick.' - '.$previous_created, LOGGER_DEBUG);
2298 * @brief Creates the XML for a salmon message
2300 * @param array $item Data of the item that is to be posted
2301 * @param array $owner Contact data of the poster
2303 * @return string XML for the salmon
2305 public static function salmon($item,$owner) {
2307 $doc = new DOMDocument('1.0', 'utf-8');
2308 $doc->formatOutput = true;
2310 if (Config::get('system', 'ostatus_debug')) {
2311 $item['body'] .= '🐟';
2314 $entry = self::entry($doc, $item, $owner, true);
2316 $doc->appendChild($entry);
2318 return trim($doc->saveXML());