Repository navigation
Expand file tree
/
Copy pathclass.API.inc.php
More file actions
486 lines (396 loc) · 9.88 KB
/
Copy pathclass.API.inc.php
File metadata and controls
486 lines (396 loc) · 9.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
<?php
/**
* The API class, for all interactions with APIs
*
* PHP version 8
*
* @license http://www.gnu.org/licenses/gpl.html GPL 3
* @version 1.1
* @link https://www.statedecoded.com/
* @since 0.6
*
*/
/**
* Functions for the API.
*/
#[\AllowDynamicProperties]
class API
{
/**
* Generate a listing of every registered API key.
*/
function list_all_keys()
{
/*
* If an in-memory cache is running, retrieve the keys.
*/
global $cache;
if (isset($cache))
{
$api_keys = $cache->retrieve('api_keys');
if ($api_keys !== false)
{
$this->all_keys = $api_keys;
return true;
}
}
/*
* We're going to need access to the database connection within this method.
*/
global $db;
/* Only retrieve those keys that have been verified -- that is, for people who have been
* sent an e-mail with a unique URL, and that have clicked on that link to confirm their
* e-mail address.
*/
$sql = 'SELECT api_key
FROM api_keys
WHERE verified=:verified';
$sql_args = [
':verified' => 'y'
];
$statement = $db->prepare($sql);
$result = $statement->execute($sql_args);
/* If the database has returned an error. */
if ($result === false)
{
throw new Exception('API keys could not be retrieved.');
return false;
}
/*
* If the query succeeds then retrieve each row and build up an object containing a list
* of all keys.
*/
/*
* If no API keys have been registered.
*/
if ($statement->rowCount() == 0)
{
return true;
}
/*
* If API keys have been registered, iterate through them and store them.
*/
$this->all_keys = new stdClass();
while ($key = $statement->fetch(PDO::FETCH_OBJ))
{
$this->all_keys->{$key->api_key} = true;
}
/*
* If an in-memory cache is running, store the API keys within it.
*/
if (isset($cache))
{
$cache->store('api_keys', $this->all_keys);
}
return true;
}
/**
* Get all available information about a given API key.
*/
function get_key()
{
/*
* We're going to need access to the database connection within this method.
*/
global $db;
/*
* Select all necessary fields from the api_keys table.
*/
$sql = 'SELECT id, api_key, email, name, url, verified, secret, date_created
FROM api_keys
WHERE api_key = :key';
$sql_args = [
':key' => $this->key
];
$statement = $db->prepare($sql);
$result = $statement->execute($sql_args);
/*
* If the query succeeds then retrieve the result.
*/
if ($result != false && $statement->rowCount() > 0)
{
$api_key = $statement->fetch(PDO::FETCH_OBJ);
/*
* Bring the result into the scope of the object.
*/
foreach ($api_key as $key => $value)
{
$this->$key = $value;
}
}
else
{
return false;
}
}
/**
* Validate a key.
*
* Accepts a key provided directly from the GET request. Invalid keys yield errors
*/
function validate_key()
{
/*
* Only proceed if a key has been provided.
*/
if (!isset($this->key))
{
throw new Exception('No API key provided.');
return false;
}
/*
* Make sure that the provided API key is the correct length.
*/
if ( strlen($this->key) != 16 )
{
throw new Exception('Invalid API key.');
return false;
}
/*
* Clean up the API key, filtering out unsafe characters.
*/
$this->key = filter_var($this->key, FILTER_DEFAULT);
/*
* Retrieve a list of every valid key.
*/
$this->list_all_keys();
/*
* If the provided API key has no content, post-filtering, or if there are no registered API
* keys.
*/
if ( empty($this->key) || empty(get_object_vars($this->all_keys ?? new stdClass())) )
{
throw new Exception('API key not provided. Please register for an API key.');
return false;
}
/*
* But if there are API keys, and our key is valid-looking, check whether the key is registered.
*/
elseif (!isset($this->all_keys->{$this->key}))
{
throw new Exception('Invalid API key.');
return false;
}
return true;
}
/**
* Display a registration form.
*/
function display_form()
{
$form = '
<form method="post" action="/downloads/" id="api-registration">
<label for="name">Your Name</label>
<input type="name" id="name" name="form_data[name]" placeholder="John Doe" value="' . ((isset($this->form)) ? $this->form->name : '' ) . '" />
<label for="email">E-Mail Address <span class="required">*</span></label>
<input type="email" id="email" name="form_data[email]" placeholder="[email protected]" required value="' . ((isset($this->form)) ? $this->form->email : '' ) . '" />
<label for="url">Website URL</label>
<input type="url" id="url" name="form_data[url]" placeholder="http://www.example.com/" value="' . ((isset($this->form)) ? $this->form->url : '' ) . '" />
<input type="submit" value="Submit" />
</form>
<p id="required-note"><span class="required">*</span> Required field</p>';
return $form;
}
/**
* Validate a submitted form.
*/
function validate_form()
{
if (!isset($this->form))
{
return false;
}
if (empty($this->form->email))
{
$this->form_errors = 'Please provide your e-mail address.';
return false;
}
elseif (filter_var($this->form->email, FILTER_VALIDATE_EMAIL) === false)
{
$this->form_errors = 'Please enter a valid e-mail address.';
return false;
}
if ( !empty($this->form_url) && (filter_var($this->form->url, FILTER_VALIDATE_URL) === false) )
{
$this->form_errors = 'Please enter a valid URL.';
return false;
}
return true;
}
/**
* Register a new API key. Note that a registered key must be activated before it can be used.
*/
function register_key()
{
/*
* We're going to need access to the database connection within this method.
*/
global $db;
$this->email = $this->form->email;
if (isset($this->form->name))
{
$this->name = $this->form->name;
}
if (isset($this->form->url))
{
$this->url = $this->form->url;
}
/*
* Generate an API key and a secret hash.
*/
API::generate_key();
API::generate_secret();
/*
* Assemble the SQL query.
*/
$sql = 'INSERT INTO api_keys
SET api_key = :key,
email = :email,
secret = :secret,
date_created = now()';
$sql_args = [
':key' => $this->key,
':email' => $this->email,
':secret' => $this->secret
];
if (!empty($this->name))
{
$sql .= ', name = :name';
$sql_args[':name'] = $this->name;
}
if (!empty($this->url))
{
$sql .= ', url = :url';
$sql_args[':url'] = $this->url;
}
$statement = $db->prepare($sql);
$result = $statement->execute($sql_args);
/*
* Insert this record.
*/
if ($result === false)
{
throw new Exception('API key could not be created.');
}
/*
* Send an activation e-mail, unless instructed otherwise.
*/
if ( !isset($this->suppress_activation_email) || ($this->suppress_activation_email !== true) )
{
API::send_activation_email();
}
}
/**
* Activate an API key. (A registered key's default state is inactivate.)
*/
function activate_key()
{
/*
* We're going to need access to the database connection within this method.
*/
global $db;
/*
* Assemble the SQL query and execute it.
*/
$sql = 'UPDATE api_keys
SET verified = "y"
WHERE secret = :secret';
$sql_args = [
':secret' => $this->secret
];
$statement = $db->prepare($sql);
$result = $statement->execute($sql_args);
if ($result === false)
{
throw new Exception('API key could not be activated.');
}
$sql = 'SELECT api_key
FROM api_keys
WHERE secret = :secret';
$sql_args = [
':secret' => $this->secret
];
$statement = $db->prepare($sql);
$result = $statement->execute($sql_args);
if ($result !== false)
{
$api_key = $statement->fetch(PDO::FETCH_OBJ);
$this->key = $api_key->api_key;
}
/*
* If an in-memory cache is running, then delete the cache of the keys, since it's been
* invalidated by the addition of this key.
*/
global $cache;
if (isset($cache))
{
$cache->erase('api_keys');
}
return true;
}
/**
* E-mail an API activation URL to the provided e-mail address.
*
* Uses PHP's mail() directly — no templating or queuing — as there is no
* other e-mail infrastructure in the project to hook into.
*/
function send_activation_email()
{
if (!isset($this->email) || !isset($this->secret))
{
return false;
}
$url = 'http://';
if ( (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || ($_SERVER['SERVER_PORT'] == 443) )
{
$url = 'https://';
}
$url .= $_SERVER['SERVER_NAME'];
if($_SERVER['SERVER_PORT'] != '80')
{
$url .= ':80';
}
$url .= '/downloads/?secret=' . $this->secret;
$email = new stdClass();
$email->body = 'Click on the following link to activate your ' . SITE_TITLE . ' API key.'
. "\r\r"
. $url;
$email->subject = SITE_TITLE . ' API Registration';
$email->headers = 'From: ' . EMAIL_NAME . ' <' . EMAIL_ADDRESS . ">\n"
.'Return-Path: ' . EMAIL_NAME . ' <' . EMAIL_ADDRESS . ">\n"
.'Reply-To: ' . EMAIL_NAME . ' <' . EMAIL_ADDRESS . ">\n"
.'X-Originating-IP: ' . $_SERVER['REMOTE_ADDR'];
$email->parameters = '-f' . EMAIL_ADDRESS;
/*
* Send the e-mail.
*/
mail($this->email, $email->subject, $email->body, $email->headers, $email->parameters);
return true;
}
/**
* Generate an API key 16 characters in length.
*/
function generate_key()
{
$this->key = '';
$valid_chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
for ($i=0; $i<16; $i++)
{
$random = mt_rand(1, strlen($valid_chars));
$this->key .= $valid_chars[$random-1];
}
}
/**
* Generate a secret hash five characters in length.
*/
function generate_secret()
{
$this->secret = '';
$valid_chars = 'bcdfghjkmnpqrstvwxz23456789';
for ($i=0; $i<5; $i++)
{
$random = mt_rand(1, strlen($valid_chars));
$this->secret .= $valid_chars[$random-1];
}
}
}