From c3277515ae8ad8aea53e53562fef01d339fcdeb1 Mon Sep 17 00:00:00 2001 From: ewinslow Date: Mon, 1 Nov 2010 22:47:29 +0000 Subject: Refs #2538: Pulled in support for ajax actions git-svn-id: http://code.elgg.org/elgg/trunk@7184 36083f99-b078-4883-b0ff-0f9b5a30f544 --- engine/lib/actions.php | 87 +++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 86 insertions(+), 1 deletion(-) (limited to 'engine') diff --git a/engine/lib/actions.php b/engine/lib/actions.php index 63ddfcbfb..fef6004cc 100644 --- a/engine/lib/actions.php +++ b/engine/lib/actions.php @@ -351,4 +351,89 @@ function elgg_action_exist($action) { global $CONFIG; return (isset($CONFIG->actions[$action]) && file_exists($CONFIG->actions[$action]['file'])); -} \ No newline at end of file +} + +/** + * Initialize some ajaxy actions features + */ +function actions_init() +{ + register_action('security/refreshtoken', TRUE); + + elgg_view_register_simplecache('js/languages/en'); + + register_plugin_hook('action', 'all', 'ajax_action_hook'); + register_plugin_hook('forward', 'all', 'ajax_forward_hook'); +} + +/** + * Checks whether the request was requested via ajax + * + * @return bool whether page was requested via ajax + */ +function elgg_is_xhr() { + return isset($_SERVER['HTTP_X_REQUESTED_WITH']) + && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'; +} + +/** + * Catch calls to forward() in ajax request and force an exit. + * + * Forces response is json of the following form: + *
+ * {
+ *     "current_url": "the.url.we/were/coming/from",
+ *     "forward_url": "the.url.we/were/going/to",
+ *     "system_messages": {
+ *         "messages": ["msg1", "msg2", ...],
+ *         "errors": ["err1", "err2", ...]
+ *     },
+ *     "status": -1 //or 0 for success if there are no error messages present
+ * }
+ * 
+ * where "system_messages" is all message registers at the point of forwarding + * + * @param string $hook + * @param string $type + * @param string $reason + * @param array $params + * + */ +function ajax_forward_hook($hook, $type, $reason, $params) { + if (elgg_is_xhr()) { + //grab any data echo'd in the action + $output = ob_get_clean(); + + //Avoid double-encoding in case data is json + $json = json_decode($output); + if (isset($json)) { + $params['output'] = $json; + } else { + $params['output'] = $output; + } + + //Grab any system messages so we can inject them via ajax too + $params['system_messages'] = system_messages(NULL, ""); + + if (isset($params['system_messages']['errors'])) { + $params['status'] = -1; + } else { + $params['status'] = 0; + } + + header("Content-type: application/json"); + echo json_encode($params); + exit; + } +} + +/** + * Buffer all output echo'd directly in the action for inclusion in the returned JSON. + */ +function ajax_action_hook() { + if (elgg_is_xhr()) { + ob_start(); + } +} + +register_elgg_event_handler('init', 'system', 'actions_init'); \ No newline at end of file -- cgit v1.2.3