actions.php 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. <?php
  2. /**
  3. * Elgg Actions
  4. *
  5. * @see http://learn.elgg.org/en/latest/guides/actions.html
  6. *
  7. * @package Elgg.Core
  8. * @subpackage Actions
  9. */
  10. /**
  11. * Handle a request for an action
  12. *
  13. * @param array $segments URL segments that make up action name
  14. *
  15. * @return void
  16. * @access private
  17. */
  18. function _elgg_action_handler(array $segments) {
  19. _elgg_services()->actions->execute(implode('/', $segments));
  20. }
  21. /**
  22. * Perform an action.
  23. *
  24. * This function executes the action with name $action as registered
  25. * by {@link elgg_register_action()}.
  26. *
  27. * The plugin hook 'action', $action_name will be triggered before the action
  28. * is executed. If a handler returns false, it will prevent the action script
  29. * from being called.
  30. *
  31. * @note If an action isn't registered in the system or is registered
  32. * to an unavailable file the user will be forwarded to the site front
  33. * page and an error will be emitted via {@link register_error()}.
  34. *
  35. * @warning All actions require CSRF tokens.
  36. *
  37. * @param string $action The requested action
  38. * @param string $forwarder Optionally, the location to forward to
  39. *
  40. * @see elgg_register_action()
  41. *
  42. * @return void
  43. * @access private
  44. */
  45. function action($action, $forwarder = "") {
  46. _elgg_services()->actions->execute($action, $forwarder);
  47. }
  48. /**
  49. * Registers an action.
  50. *
  51. * Actions are registered to a script in the system and are executed
  52. * by the URL http://elggsite.org/action/action_name/.
  53. *
  54. * $filename must be the full path of the file to register or a path relative
  55. * to the core actions/ dir.
  56. *
  57. * Actions should be namedspaced for your plugin. Example:
  58. * <code>
  59. * elgg_register_action('myplugin/save_settings', ...);
  60. * </code>
  61. *
  62. * @tip Put action files under the actions/<plugin_name> directory of your plugin.
  63. *
  64. * @tip You don't need to include engine/start.php in your action files.
  65. *
  66. * @note Internal: Actions are saved in $CONFIG->actions as an array in the form:
  67. * <code>
  68. * array(
  69. * 'file' => '/location/to/file.php',
  70. * 'access' => 'public', 'logged_in', or 'admin'
  71. * )
  72. * </code>
  73. *
  74. * @param string $action The name of the action (eg "register", "account/settings/save")
  75. * @param string $filename Optionally, the filename where this action is located. If not specified,
  76. * will assume the action is in elgg/actions/<action>.php
  77. * @param string $access Who is allowed to execute this action: public, logged_in, admin.
  78. * (default: logged_in)
  79. *
  80. * @return bool
  81. */
  82. function elgg_register_action($action, $filename = "", $access = 'logged_in') {
  83. return _elgg_services()->actions->register($action, $filename, $access);
  84. }
  85. /**
  86. * Unregisters an action
  87. *
  88. * @param string $action Action name
  89. * @return bool
  90. * @since 1.8.1
  91. */
  92. function elgg_unregister_action($action) {
  93. return _elgg_services()->actions->unregister($action);
  94. }
  95. /**
  96. * Get an HMAC token builder/validator object
  97. *
  98. * @param mixed $data HMAC data string or serializable data
  99. * @return \Elgg\Security\Hmac
  100. * @since 1.11
  101. */
  102. function elgg_build_hmac($data) {
  103. return _elgg_services()->crypto->getHmac($data);
  104. }
  105. /**
  106. * Validate an action token.
  107. *
  108. * Calls to actions will automatically validate tokens. If tokens are not
  109. * present or invalid, the action will be denied and the user will be redirected.
  110. *
  111. * Plugin authors should never have to manually validate action tokens.
  112. *
  113. * @param bool $visible_errors Emit {@link register_error()} errors on failure?
  114. * @param mixed $token The token to test against. Default: $_REQUEST['__elgg_token']
  115. * @param mixed $ts The time stamp to test against. Default: $_REQUEST['__elgg_ts']
  116. *
  117. * @return bool
  118. * @see generate_action_token()
  119. * @access private
  120. */
  121. function validate_action_token($visible_errors = true, $token = null, $ts = null) {
  122. return _elgg_services()->actions->validateActionToken($visible_errors, $token, $ts);
  123. }
  124. /**
  125. * Validates the presence of action tokens.
  126. *
  127. * This function is called for all actions. If action tokens are missing,
  128. * the user will be forwarded to the site front page and an error emitted.
  129. *
  130. * This function verifies form input for security features (like a generated token),
  131. * and forwards if they are invalid.
  132. *
  133. * @param string $action The action being performed
  134. *
  135. * @return mixed True if valid or redirects.
  136. * @access private
  137. */
  138. function action_gatekeeper($action) {
  139. return _elgg_services()->actions->gatekeeper($action);
  140. }
  141. /**
  142. * Generate an action token.
  143. *
  144. * Action tokens are based on timestamps as returned by {@link time()}.
  145. * They are valid for one hour.
  146. *
  147. * Action tokens should be passed to all actions name __elgg_ts and __elgg_token.
  148. *
  149. * @warning Action tokens are required for all actions.
  150. *
  151. * @param int $timestamp Unix timestamp
  152. *
  153. * @see @elgg_view input/securitytoken
  154. * @see @elgg_view input/form
  155. *
  156. * @return string|false
  157. * @access private
  158. */
  159. function generate_action_token($timestamp) {
  160. return _elgg_services()->actions->generateActionToken($timestamp);
  161. }
  162. /**
  163. * Initialise the site secret (32 bytes: "z" to indicate format + 186-bit key in Base64 URL).
  164. *
  165. * Used during installation and saves as a datalist.
  166. *
  167. * Note: Old secrets were hex encoded.
  168. *
  169. * @return mixed The site secret hash or false
  170. * @access private
  171. * @todo Move to better file.
  172. */
  173. function init_site_secret() {
  174. return _elgg_services()->siteSecret->init();
  175. }
  176. /**
  177. * Returns the site secret.
  178. *
  179. * Used to generate difficult to guess hashes for sessions and action tokens.
  180. *
  181. * @return string Site secret.
  182. * @access private
  183. * @todo Move to better file.
  184. */
  185. function get_site_secret() {
  186. return _elgg_services()->siteSecret->get();
  187. }
  188. /**
  189. * Get the strength of the site secret
  190. *
  191. * @return string "strong", "moderate", or "weak"
  192. * @access private
  193. */
  194. function _elgg_get_site_secret_strength() {
  195. return _elgg_services()->siteSecret->getStrength();
  196. }
  197. /**
  198. * Check if an action is registered and its script exists.
  199. *
  200. * @param string $action Action name
  201. *
  202. * @return bool
  203. * @since 1.8.0
  204. */
  205. function elgg_action_exists($action) {
  206. return _elgg_services()->actions->exists($action);
  207. }
  208. /**
  209. * Checks whether the request was requested via ajax
  210. *
  211. * @return bool whether page was requested via ajax
  212. * @since 1.8.0
  213. */
  214. function elgg_is_xhr() {
  215. return _elgg_services()->request->isXmlHttpRequest();
  216. }
  217. /**
  218. * Catch calls to forward() in ajax request and force an exit.
  219. *
  220. * Forces response is json of the following form:
  221. * <pre>
  222. * {
  223. * "current_url": "the.url.we/were/coming/from",
  224. * "forward_url": "the.url.we/were/going/to",
  225. * "system_messages": {
  226. * "messages": ["msg1", "msg2", ...],
  227. * "errors": ["err1", "err2", ...]
  228. * },
  229. * "status": -1 //or 0 for success if there are no error messages present
  230. * }
  231. * </pre>
  232. * where "system_messages" is all message registers at the point of forwarding
  233. *
  234. * @internal registered for the 'forward', 'all' plugin hook
  235. *
  236. * @param string $hook
  237. * @param string $type
  238. * @param string $reason
  239. * @param array $params
  240. * @return void
  241. * @access private
  242. */
  243. function ajax_forward_hook($hook, $type, $reason, $params) {
  244. _elgg_services()->actions->ajaxForwardHook($hook, $type, $reason, $params);
  245. }
  246. /**
  247. * Buffer all output echo'd directly in the action for inclusion in the returned JSON.
  248. * @return void
  249. * @access private
  250. */
  251. function ajax_action_hook() {
  252. _elgg_services()->actions->ajaxActionHook();
  253. }
  254. /**
  255. * Send an updated CSRF token
  256. *
  257. * @access private
  258. */
  259. function _elgg_csrf_token_refresh() {
  260. if (!elgg_is_xhr()) {
  261. return false;
  262. }
  263. $ts = time();
  264. $token = generate_action_token($ts);
  265. $data = array(
  266. '__elgg_ts' => $ts,
  267. '__elgg_token' => $token,
  268. 'logged_in' => elgg_is_logged_in(),
  269. );
  270. header("Content-Type: application/json;charset=utf-8");
  271. echo json_encode($data);
  272. return true;
  273. }
  274. /**
  275. * Initialize some ajaxy actions features
  276. * @access private
  277. */
  278. function actions_init() {
  279. elgg_register_page_handler('action', '_elgg_action_handler');
  280. elgg_register_page_handler('refresh_token', '_elgg_csrf_token_refresh');
  281. elgg_register_simplecache_view('js/languages/en');
  282. elgg_register_plugin_hook_handler('action', 'all', 'ajax_action_hook');
  283. elgg_register_plugin_hook_handler('forward', 'all', 'ajax_forward_hook');
  284. }
  285. return function(\Elgg\EventsService $events, \Elgg\HooksRegistrationService $hooks) {
  286. $events->registerHandler('init', 'system', 'actions_init');
  287. };