Completed
Push — 3.0 ( 9dd29c...237018 )
by Jeroen
53:05
created

mod/web_services/lib/api_user.php (1 issue)

1
<?php
2
/**
3
 * A library for managing users of the web services API
4
 */
5
6
// API key functions /////////////////////////////////////////////////////////////////////
7
8
/**
9
 * Generate a new API user for a site, returning a new keypair on success.
10
 *
11
 * @return stdClass object or false
12
 */
13
function create_api_user() {
14
	$dbprefix = elgg_get_config('dbprefix');
15
	$public = _elgg_services()->crypto->getRandomString(40, ElggCrypto::CHARS_HEX);
16
	$secret = _elgg_services()->crypto->getRandomString(40, ElggCrypto::CHARS_HEX);
17
18
	$insert = elgg()->db->insertData("INSERT into {$dbprefix}api_users
19
		(api_key, secret) values
20
		('$public', '$secret')");
21
22
	if ($insert) {
23
		return get_api_user($public);
24
	}
25
26
	return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type stdClass.
Loading history...
27
}
28
29
/**
30
 * Find an API User's details based on the provided public api key.
31
 * These users are not users in the traditional sense.
32
 *
33
 * @param string $api_key The API Key
34
 *
35
 * @return mixed stdClass representing the database row or false.
36
 */
37
function get_api_user($api_key) {
38 1
	$dbprefix = elgg_get_config('dbprefix');
39
40
	$query = "SELECT *
41 1
		FROM {$dbprefix}api_users
42
		WHERE api_key = :api_key
43
		AND active = 1";
44
	$params = [
45 1
		':api_key' => $api_key,
46
	];
47
48 1
	return elgg()->db->getDataRow($query, null, $params);
49
}
50
51
/**
52
 * Revoke an api user key.
53
 *
54
 * @param string $api_key The API Key (public).
55
 *
56
 * @return bool
57
 */
58
function remove_api_user($api_key) {
59
	$dbprefix = elgg_get_config('dbprefix');
60
	$keypair = get_api_user($api_key);
61
	if ($keypair) {
62
		return elgg()->db->deleteData("DELETE from {$dbprefix}api_users where id={$keypair->id}");
63
	}
64
65
	return false;
66
}
67