Daniel Ansari’s blog Random software musings

December 10, 2008

How to use the REST API in Elgg 1.1

Filed under: Open Source — Tags: , , — admin @ 3:50 pm

The Elgg documentation describes the REST API rather superficially, yet provides no samples, and is now inaccurate for the recent versions of Elgg.

After a minor modification to your .htaccess file, using the REST API is very simple, and, in many cases, avoids the need to create individual files in your Elgg root directory to provide custom functionality.

First, let’s look at how your API method would be called:

http://localhost:8080/elgg/pg/api/rest?method=login&username=dansari&password=apples

Let me explain technically what’s going on first. Any API calls in Elgg are handled by a page handler, i.e., when the HTTP request begins with /pg/..., the .htaccess (containing mod_rewrite rules) tells Apache to use the Elgg file engine/handlers/pagehandler.php to handle the request. Elgg then determines which page handler to use, and invokes it. The REST API is known as an “API endpoint”. In this case, because the next part of the URL is rest, the API page handler passes control to the file services/api/rest.php.

The problem with the .htaccess that ships with Elgg is that it would cause the page handler to be invoked as pagehandler.php?handler=api&page=rest, discarding the querystring entirely. services/api/rest.php actually expects the method parameters to be in the querystring, so to get this to work, we simply change the following line in .htaccess:

RewriteRule ^pg\/([A-Za-z\_\-]+)\/(.*)$
engine/handlers/pagehandler.php?handler=$1&page=$2

to this:

RewriteRule ^pg\/([A-Za-z\_\-]+)\/(.*)$
engine/handlers/pagehandler.php?handler=$1&page=$2 [QSA]

Here is the code for a sample REST method, which would be implemented via a plugin. For this example, the following file is located at mod/rest_login/start.php (NB I had to put a space character before the ?php in line 1 for WordPress to render this listing):

  1. < ?php
  2.  
  3. function rest_login_init() {
  4. expose_function('login', 'rest_login_handler', array(
  5. "username" => array("type" => "string"),
  6. "password" => array("type" => "string")
  7. ), "", "GET", false, true);
  8. }
  9.  
  10. function rest_login_handler($username, $password) {
  11. $persistent = "1";
  12. $result = false;
  13. if (!empty($username) && !empty($password)) {
  14. if ($user = authenticate($username,$password)) {
  15. $result = login($user, $persistent);
  16. }
  17. }
  18. return $result;
  19. }
  20.  
  21. // Add the plugin's init function to the system's init event
  22. register_elgg_event_handler('init','system','rest_login_init');
  23.  
  24. ?>

The important differences between what is stated in the Elgg documentation and here are:

  • There is no register_method function. Instead, use expose_function as in line 4.
  • "type" must be specified for each parameter, as in lines 5-6.

Finally, here is an excerpt from engine/lib/api.php, which explains the parameters in more detail:

  1. /**
  2. * Expose an arbitrary function as an api call.
  3. *
  4. * Limitations: Currently can not expose functions which expect objects.
  5. *
  6. * @param string $method The api name to expose this as, eg "myapi.dosomething"
  7. * @param string $function Your function callback.
  8. * @param array $parameters Optional list of parameters in the same order as in your function, with optional parameters last.
  9. *       This array should be in the format
  10. *   "variable" = array (
  11. *                                       type => 'int' | 'bool' | 'float' | 'string' | 'array'
  12. *                                       required => true (default) | false
  13. *        )
  14. * @param string $description Optional human readable description of the function.
  15. * @param string $call_method Define what call method should be used for this function.
  16. * @param bool $require_auth_token Whether this requires a user authentication token or not (default is true).
  17. * @param bool $anonymous Can anonymous (non-authenticated in any way) users execute this call.
  18. * @return bool
  19. */
  20. function expose_function($method, $function, array $parameters = NULL, $description = "", $call_method = "GET", $require_auth_token = true, $anonymous = false)

There are limitations of the REST API, one of them being that the return value is rendered in a view. You can override the view by including the directory structure and file views/default/api/output.php in your module directory, but Elgg will still render it as HTML; if you need to process the result, you will need to parse this HTML. Also, if you decide to override this view, it will be overridden for any REST API method calls, not just the one implemented in your module.

One particular limitation of the sample above is that it does not authenticate! At least I couldn’t get it to work; the reason is that the API method is registered as not requiring a user authentication token. As a result, the method executes in unauthenticated fashion, and when authenticate() is called to attempt to authenticate the user, it always succeeds – regardless of the password – because pam_authenticate() returns true for the executing method. (Hopefully this would make sense to you if you’ve written an authentication plugin.)

September 30, 2008

Adding “Friends” access level to Elgg 1.1

Filed under: Open Source — Tags: , , — admin @ 10:43 am

Out of the box, Elgg 1.1 has three access levels: private, logged-in users, and public.

A few people have asked about how to add a further access level: friends. Currently, the only way to give friends access to an item is to create a friends collection, then specify that collection for the access level. The problem with this approach is that every you add or remove a friend, you need to update your collection manually.

The Elgg development philosophy is not to modify the core files, but instead to write plugins, if you need to modify any of the core functionality. However, in this case, there are no Elgg events that we can hook into, as access level is such a fundamental part of the core. Thus, we are forced to modify a couple of the core files.

Note that this won’t work for MySQL versions prior to 4.1, as they do not support subqueries.

Add line 147 in engine/lib/access.php:

  1. function get_access_sql_suffix($table_prefix = "")
  2. {
  3. global $CONFIG;
  4. global $ENTITY_SHOW_HIDDEN_OVERRIDE;
  5.  

Change line 167 in engine/lib/access.php:

  1. if (empty($sql))
  2. $sql = " ({$table_prefix}access_id in {$access} or ({$table_prefix}access_id = 0 and {$table_prefix}owner_guid = $owner) or ({$table_prefix}access_id = -1 and ({$table_prefix}owner_guid = $owner or {$table_prefix}owner_guid in (select guid_two from {$CONFIG->dbprefix}entity_relationships er where er.guid_one = $owner and er.relationship = 'friend'))))";

Change line 201 to the following:

  1. $tmp_access_array = array(0 => elgg_echo("PRIVATE"), -1 => elgg_echo("FRIENDS"), 1 => elgg_echo("LOGGED_IN"), 2 => elgg_echo("PUBLIC"));

The last change in core is to add line 190 in languages/en.php:

  1. 'PRIVATE' => "Private",
  2. 'LOGGED_IN' => "Logged in users",
  3. 'PUBLIC' => "Public",
  4. 'FRIENDS' => "Friends",
  5. 'access' => "Access",

Finally, the pages module needs to respect the new access level, so modify mod/pages/start.php by adding lines 252-256, and 262-269:

  1. if (($write_permission!=0) && (in_array($write_permission,$list)))
  2. return true;
  3.  
  4. if ($write_permission == -1) {
  5. $friends = get_friends($params['entity']);
  6. if (in_array($user->guid, $friends))
  7. return true;
  8. }
  9.  
  10. }
  11. }
  12. }
  13.  
  14. function get_friends($entity)
  15. {
  16. $friends = array();
  17. $entities = get_entities_from_relationship('friend', $entity->owner_guid, false, 'user', '', 0, '', 1000000);
  18. foreach ($entities as $friend)
  19. $friends[] = $friend->guid;
  20. return $friends;
  21. }
  22.  

Powered by WordPress