make the JS compatible with older IE versions, though this is a hack that hardcodes...
[authserver.git] / index.php
1 <?php
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
4  * You can obtain one at http://mozilla.org/MPL/2.0/. */
5
6 // Include the common auth system files (including the OAuth2 Server object).
7 require_once(__DIR__.'/authsystem.inc.php');
8
9 // Start HTML document as a DOM object.
10 extract(ExtendedDocument::initHTML5()); // sets $document, $html, $head, $title, $body
11 $document->formatOutput = true; // we want a nice output
12
13 $style = $head->appendElement('link');
14 $style->setAttribute('rel', 'stylesheet');
15 $style->setAttribute('href', 'authsystem.css');
16 $head->appendJSFile('authsystem.js');
17 $title->appendText('KaiRo.at Authentication Server');
18 $h1 = $body->appendElement('h1', 'KaiRo.at Authentication Server');
19
20 $errors = $utils->checkForSecureConnection();
21 $utils->sendSecurityHeaders();
22
23 $para = $body->appendElement('p', _('This login system does not work without JavaScript. Please activate JavaScript for this site to log in.'));
24 $para->setAttribute('id', 'jswarning');
25 $para->setAttribute('class', 'warn');
26
27 if (!count($errors)) {
28   $session = $utils->initSession(); // Read session or create new session and set cookie.
29   $user = array('id' => 0, 'email' => '');
30   $pagetype = 'default';
31   if (is_null($session)) {
32     $errors[] = _('The session system is not working. Please <a href="https://www.kairo.at/contact">contact KaiRo.at</a> and tell the team about this.');
33   }
34   elseif (array_key_exists('logout', $_GET)) {
35     $result = $db->prepare('UPDATE `auth_sessions` SET `logged_in` = FALSE WHERE `id` = :sessid;');
36     if (!$result->execute(array(':sessid' => $session['id']))) {
37       $utils->log('logout_failure', 'session: '.$session['id']);
38       $errors[] = _('The email address is invalid.');
39     }
40     $session['logged_in'] = 0;
41   }
42   elseif (array_key_exists('email', $_POST)) {
43     if (!preg_match('/^[^@]+@[^@]+\.[^@]+$/', $_POST['email'])) {
44       $errors[] = _('The email address is invalid.');
45     }
46     elseif ($utils->verifyTimeCode(@$_POST['tcode'], $session)) {
47       $result = $db->prepare('SELECT `id`, `pwdhash`, `email`, `status`, `verify_hash` FROM `auth_users` WHERE `email` = :email;');
48       $result->execute(array(':email' => $_POST['email']));
49       $user = $result->fetch(PDO::FETCH_ASSOC);
50       if ($user['id'] && array_key_exists('pwd', $_POST)) {
51         // existing user, check password
52         if (($user['status'] == 'ok') && $utils->pwdVerify(@$_POST['pwd'], $user)) {
53           // Check if a newer hashing algorithm is available
54           // or the cost has changed
55           if ($utils->pwdNeedsRehash($user)) {
56             // If so, create a new hash, and replace the old one
57             $newHash = $utils->pwdHash($_POST['pwd']);
58             $result = $db->prepare('UPDATE `auth_users` SET `pwdhash` = :pwdhash WHERE `id` = :userid;');
59             if (!$result->execute(array(':pwdhash' => $newHash, ':userid' => $user['id']))) {
60               $utils->log('user_hash_save_failure', 'user: '.$user['id']);
61             }
62             else {
63               $utils->log('pwd_rehash_success', 'user: '.$user['id']);
64             }
65           }
66
67           // Log user in - update session key for that, see https://wiki.mozilla.org/WebAppSec/Secure_Coding_Guidelines#Login
68           $utils->log('login', 'user: '.$user['id']);
69           $sesskey = $utils->createSessionKey();
70           setcookie('sessionkey', $sesskey, 0, "", "", !$utils->running_on_localhost, true); // Last two params are secure and httponly, secure is not set on localhost.
71           // If the session has a redirect set, make sure it's performed.
72           if (strlen(@$session['saved_redirect'])) {
73             header('Location: '.$utils->getDomainBaseURL().$session['saved_redirect']);
74             // Remove redirect.
75             $result = $db->prepare('UPDATE `auth_sessions` SET `saved_redirect` = :redir WHERE `id` = :sessid;');
76             if (!$result->execute(array(':redir' => '', ':sessid' => $session['id']))) {
77               $utils->log('redir_save_failure', 'session: '.$session['id'].', redirect: (empty)');
78             }
79           }
80           // If the session has a user set, create a new one - otherwise take existing session entry.
81           if (intval($session['user'])) {
82             $result = $db->prepare('INSERT INTO `auth_sessions` (`sesskey`, `time_expire`, `user`, `logged_in`) VALUES (:sesskey, :expire, :userid, TRUE);');
83             $result->execute(array(':sesskey' => $sesskey, ':userid' => $user['id'], ':expire' => gmdate('Y-m-d H:i:s', strtotime('+1 day'))));
84             // After insert, actually fetch the session row from the DB so we have all values.
85             $result = $db->prepare('SELECT * FROM auth_sessions WHERE `sesskey` = :sesskey AND `time_expire` > :expire;');
86             $result->execute(array(':sesskey' => $sesskey, ':expire' => gmdate('Y-m-d H:i:s')));
87             $row = $result->fetch(PDO::FETCH_ASSOC);
88             if ($row) {
89               $session = $row;
90             }
91             else {
92               $utils->log('create_session_failure', 'at login, prev session: '.$session['id'].', new user: '.$user['id']);
93               $errors[] = _('The session system is not working. Please <a href="https://www.kairo.at/contact">contact KaiRo.at</a> and tell the team about this.');
94             }
95           }
96           else {
97             $result = $db->prepare('UPDATE `auth_sessions` SET `sesskey` = :sesskey, `user` = :userid, `logged_in` = TRUE, `time_expire` = :expire WHERE `id` = :sessid;');
98             if (!$result->execute(array(':sesskey' => $sesskey, ':userid' => $user['id'], ':expire' => gmdate('Y-m-d H:i:s', strtotime('+1 day')), ':sessid' => $session['id']))) {
99               $utils->log('login_failure', 'session: '.$session['id'].', user: '.$user['id']);
100               $errors[] = _('Login failed unexpectedly. Please <a href="https://www.kairo.at/contact">contact KaiRo.at</a> and tell the team about this.');
101             }
102             else {
103               // After update, actually fetch the session row from the DB so we have all values.
104               $result = $db->prepare('SELECT * FROM auth_sessions WHERE `sesskey` = :sesskey AND `time_expire` > :expire;');
105               $result->execute(array(':sesskey' => $sesskey, ':expire' => gmdate('Y-m-d H:i:s')));
106               $row = $result->fetch(PDO::FETCH_ASSOC);
107               if ($row) {
108                 $session = $row;
109               }
110             }
111           }
112           // If a verify_hash if set on a verified user, a password reset had been requested. As a login works right now, cancel that reset request by deleting the hash.
113           if (strlen(@$user['verify_hash'])) {
114             $result = $db->prepare('UPDATE `auth_users` SET `verify_hash` = \'\' WHERE `id` = :userid;');
115             if (!$result->execute(array(':userid' => $user['id']))) {
116               $utils->log('empty_vhash_failure', 'user: '.$user['id']);
117             }
118             else {
119               $user['verify_hash'] = '';
120             }
121           }
122         }
123         else {
124           $errors[] = _('This password is invalid or your email is not verified yet. Did you type them correctly?');
125         }
126       }
127       else {
128         // new user: check password, create user and send verification; existing users: re-send verification or send password change instructions
129         if (array_key_exists('pwd', $_POST)) {
130           $errors += $utils->checkPasswordConstraints(strval($_POST['pwd']), $_POST['email']);
131         }
132         if (!count($errors)) {
133           // Put user into the DB
134           if (!$user['id']) {
135             $newHash = $utils->pwdHash($_POST['pwd']);
136             $vcode = $utils->createVerificationCode();
137             $result = $db->prepare('INSERT INTO `auth_users` (`email`, `pwdhash`, `status`, `verify_hash`) VALUES (:email, :pwdhash, \'unverified\', :vcode);');
138             if (!$result->execute(array(':email' => $_POST['email'], ':pwdhash' => $newHash, ':vcode' => $vcode))) {
139               $utils->log('user_insert_failure', 'email: '.$_POST['email']);
140               $errors[] = _('Could not add user. Please <a href="https://www.kairo.at/contact">contact KaiRo.at</a> and tell the team about this.');
141             }
142             $user = array('id' => $db->lastInsertId(),
143                           'email' => $_POST['email'],
144                           'pwdhash' => $newHash,
145                           'status' => 'unverified',
146                           'verify_hash' => $vcode);
147             $utils->log('new_user', 'user: '.$user['id'].', email: '.$user['email']);
148           }
149           if ($user['status'] == 'unverified') {
150             // Send email for verification and show message to point to it.
151             $mail = new email();
152             $mail->setCharset('utf-8');
153             $mail->addHeader('X-KAIRO-AUTH', 'email_verification');
154             $mail->addRecipient($user['email']);
155             $mail->setSender('noreply@auth.kairo.at', _('KaiRo.at Authentication Service'));
156             $mail->setSubject('Email Verification for KaiRo.at Authentication');
157             $mail->addMailText(_('Welcome!')."\n\n");
158             $mail->addMailText(sprintf(_('This email address, %s, has been used for registration on "%s".'),
159                                       $user['email'], _('KaiRo.at Authentication Service'))."\n\n");
160             $mail->addMailText(_('Please confirm that registration by clicking the following link (or calling it up in your browser):')."\n");
161             $mail->addMailText($utils->getDomainBaseURL().strstr($_SERVER['REQUEST_URI'], '?', true)
162                               .'?email='.rawurlencode($user['email']).'&verification_code='.rawurlencode($user['verify_hash'])."\n\n");
163             $mail->addMailText(_('With this confirmation, you accept that we handle your data for the purpose of logging you into other websites when you request that.')."\n");
164             $mail->addMailText(_('Those websites will get to know your email address but not your password, which we store securely.')."\n");
165             $mail->addMailText(_('If you do not call this confirmation link within 72 hours, your data will be deleted from our database.')."\n\n");
166             $mail->addMailText(sprintf(_('The %s team'), 'KaiRo.at'));
167             //$mail->setDebugAddress("robert@localhost");
168             $mailsent = $mail->send();
169             if ($mailsent) {
170               $pagetype = 'verification_sent';
171             }
172             else {
173               $utils->log('verify_mail_failure', 'user: '.$user['id'].', email: '.$user['email']);
174               $errors[] = _('The confirmation email could not be sent to you. Please <a href="https://www.kairo.at/contact">contact KaiRo.at</a> and tell the team about this.');
175             }
176           }
177           else {
178             // Password reset requested with "Password forgotten?" function.
179             $vcode = $utils->createVerificationCode();
180             $result = $db->prepare('UPDATE `auth_users` SET `verify_hash` = :vcode WHERE `id` = :userid;');
181             if (!$result->execute(array(':vcode' => $vcode, ':userid' => $user['id']))) {
182               $utils->log('vhash_set_failure', 'user: '.$user['id']);
183               $errors[] = _('Could not initiate reset request. Please <a href="https://www.kairo.at/contact">contact KaiRo.at</a> and tell the team about this.');
184             }
185             else {
186               $utils->log('pwd_reset_request', 'user: '.$user['id'].', email: '.$user['email']);
187               $resetcode = $vcode.dechex($user['id'] + $session['id']).'_'.$utils->createTimeCode($session, null, 60);
188               // Send email with instructions for resetting the password.
189               $mail = new email();
190               $mail->setCharset('utf-8');
191               $mail->addHeader('X-KAIRO-AUTH', 'password_reset');
192               $mail->addRecipient($user['email']);
193               $mail->setSender('noreply@auth.kairo.at', _('KaiRo.at Authentication Service'));
194               $mail->setSubject('How to reset your password for KaiRo.at Authentication');
195               $mail->addMailText(_('Hi,')."\n\n");
196               $mail->addMailText(sprintf(_('A request for setting a new password for this email address, %s, has been submitted on "%s".'),
197                                         $user['email'], _('KaiRo.at Authentication Service'))."\n\n");
198               $mail->addMailText(_('You can set a new password by clicking the following link (or calling it up in your browser):')."\n");
199               $mail->addMailText($utils->getDomainBaseURL().strstr($_SERVER['REQUEST_URI'], '?', true)
200                                 .'?email='.rawurlencode($user['email']).'&reset_code='.rawurlencode($resetcode)."\n\n");
201               $mail->addMailText(_('If you do not call this confirmation link within 1 hour, this link expires and the existing password is being kept in place.')."\n\n");
202               $mail->addMailText(sprintf(_('The %s team'), 'KaiRo.at'));
203               //$mail->setDebugAddress("robert@localhost");
204               $mailsent = $mail->send();
205               if ($mailsent) {
206                 $pagetype = 'resetmail_sent';
207               }
208               else {
209                 $utils->log('pwd_reset_mail_failure', 'user: '.$user['id'].', email: '.$user['email']);
210                 $errors[] = _('The email with password reset instructions could not be sent to you. Please <a href="https://www.kairo.at/contact">contact KaiRo.at</a> and tell the team about this.');
211               }
212             }
213           }
214         }
215       }
216     }
217     else {
218       $errors[] = _('The form you used was not valid. Possibly it has expired and you need to initiate the action again.');
219     }
220   }
221   elseif (array_key_exists('reset', $_GET)) {
222     if ($session['logged_in']) {
223       $result = $db->prepare('SELECT `id`,`email` FROM `auth_users` WHERE `id` = :userid;');
224       $result->execute(array(':userid' => $session['user']));
225       $user = $result->fetch(PDO::FETCH_ASSOC);
226       if (!$user['id']) {
227         $utils->log('reset_user_read_failure', 'user: '.$session['user']);
228       }
229       $pagetype = 'resetpwd';
230     }
231     else {
232       // Display form for entering email.
233       $pagetype = 'resetstart';
234     }
235   }
236   elseif (array_key_exists('verification_code', $_GET)) {
237     $result = $db->prepare('SELECT `id`,`email` FROM `auth_users` WHERE `email` = :email AND `status` = \'unverified\' AND `verify_hash` = :vcode;');
238     $result->execute(array(':email' => @$_GET['email'], ':vcode' => $_GET['verification_code']));
239     $user = $result->fetch(PDO::FETCH_ASSOC);
240     if ($user['id']) {
241       $result = $db->prepare('UPDATE `auth_users` SET `verify_hash` = \'\', `status` = \'ok\' WHERE `id` = :userid;');
242       if (!$result->execute(array(':userid' => $user['id']))) {
243         $utils->log('verification_save_failure', 'user: '.$user['id']);
244         $errors[] = _('Could not save confirmation. Please <a href="https://www.kairo.at/contact">contact KaiRo.at</a> and tell the team about this.');
245       }
246       $pagetype = 'verification_done';
247     }
248     else {
249       $errors[] = _('The confirmation link you called is not valid. Possibly it has expired and you need to try registering again.');
250     }
251   }
252   elseif (array_key_exists('reset_code', $_GET)) {
253     $reset_fail = true;
254     $result = $db->prepare('SELECT `id`,`email`,`verify_hash` FROM `auth_users` WHERE `email` = :email');
255     $result->execute(array(':email' => @$_GET['email']));
256     $user = $result->fetch(PDO::FETCH_ASSOC);
257     if ($user['id']) {
258       // Deconstruct reset code and verify it.
259       if (preg_match('/^([0-9a-f]{'.strlen($user['verify_hash']).'})([0-9a-f]+)_(\d+\.\d+)$/', $_GET['reset_code'], $regs)) {
260         $tcode_sessid = hexdec($regs[2]) - $user['id'];
261         $result = $db->prepare('SELECT `id`,`sesskey` FROM `auth_sessions` WHERE `id` = :sessid;');
262         $result->execute(array(':sessid' => $tcode_sessid));
263         $row = $result->fetch(PDO::FETCH_ASSOC);
264         if ($row) {
265           $tcode_session = $row;
266           if (($regs[1] == $user['verify_hash']) &&
267               $utils->verifyTimeCode($regs[3], $session, 60)) {
268             // Set a new verify_hash for the actual password reset.
269             $user['verify_hash'] = $utils->createVerificationCode();
270             $result = $db->prepare('UPDATE `auth_users` SET `verify_hash` = :vcode WHERE `id` = :userid;');
271             if (!$result->execute(array(':vcode' => $user['verify_hash'], ':userid' => $user['id']))) {
272               $utils->log('vhash_reset_failure', 'user: '.$user['id']);
273             }
274             $result = $db->prepare('UPDATE `auth_sessions` SET `user` = :userid WHERE `id` = :sessid;');
275             if (!$result->execute(array(':userid' => $user['id'], ':sessid' => $session['id']))) {
276               $utils->log('reset_session_set_user_failure', 'session: '.$session['id']);
277             }
278             $pagetype = 'resetpwd';
279             $reset_fail = false;
280           }
281         }
282       }
283     }
284     if ($reset_fail) {
285       $errors[] = _('The password reset link you called is not valid. Possibly it has expired and you need to call the "Password forgotten?" function again.');
286     }
287   }
288   elseif (array_key_exists('clients', $_GET)) {
289     $result = $db->prepare('SELECT `id`,`email` FROM `auth_users` WHERE `id` = :userid;');
290     $result->execute(array(':userid' => $session['user']));
291     $user = $result->fetch(PDO::FETCH_ASSOC);
292     if ($session['logged_in'] && $user['id']) {
293       if (array_key_exists('client_id', $_POST) && (strlen($_POST['client_id']) >= 5)) {
294         $clientid = $_POST['client_id'];
295         $clientsecret = $utils->createClientSecret();
296         $rediruri = strval(@$_POST['redirect_uri']);
297         $scope = strval(@$_POST['scope']);
298         $result = $db->prepare('INSERT INTO `oauth_clients` (`client_id`, `client_secret`, `redirect_uri`, `scope`, `user_id`) VALUES (:clientid, :secret, :rediruri, :scope, :userid);');
299         if (!$result->execute(array(':clientid' => $clientid,
300                                     ':secret' => $clientsecret,
301                                     ':rediruri' => $rediruri,
302                                     ':scope' => $scope,
303                                     ':userid' => $user['id']))) {
304           $utils->log('client_save_failure', 'client: '.$clientid);
305           $errors[] = 'Unexpectedly failed to save new client information. Please <a href="https://www.kairo.at/contact">contact KaiRo.at</a> and tell the team about this.';
306         }
307       }
308       if (!count($errors)) {
309         // List clients
310         $result = $db->prepare('SELECT `client_id`,`client_secret`,`redirect_uri`,`scope` FROM `oauth_clients` WHERE `user_id` = :userid;');
311         $result->execute(array(':userid' => $user['id']));
312         $clients = $result->fetchAll(PDO::FETCH_ASSOC);
313         if (!$clients) { $clients = array(); }
314         $pagetype = 'clientlist';
315       }
316     }
317     else {
318       $errors[] = _('This function is only available if you are logged in.');
319     }
320   }
321   elseif (intval($session['user'])) {
322     $result = $db->prepare('SELECT `id`,`email`,`verify_hash` FROM `auth_users` WHERE `id` = :userid;');
323     $result->execute(array(':userid' => $session['user']));
324     $user = $result->fetch(PDO::FETCH_ASSOC);
325     if (!$user['id']) {
326       $utils->log('user_read_failure', 'user: '.$session['user']);
327     }
328     // Password reset requested.
329     if (array_key_exists('pwd', $_POST) && array_key_exists('reset', $_POST) && array_key_exists('tcode', $_POST)) {
330       // If not logged in, a password reset needs to have the proper vcode set.
331       if (!$session['logged_in'] && (!strlen(@$_POST['vcode']) || ($_POST['vcode'] != $user['verify_hash']))) {
332         $errors[] = _('Password reset failed. The reset form you used was not valid. Possibly it has expired and you need to initiate the password reset again.');
333       }
334       // If not logged in, a password reset also needs to have the proper email set.
335       if (!$session['logged_in'] && !count($errors) && (@$_POST['email_hidden'] != $user['email'])) {
336         $errors[] = _('Password reset failed. The reset form you used was not valid. Possibly it has expired and you need to initiate the password reset again.');
337       }
338       // Check validity of time code.
339       if (!count($errors) && !$utils->verifyTimeCode($_POST['tcode'], $session)) {
340         $errors[] = _('Password reset failed. The reset form you used was not valid. Possibly it has expired and you need to initiate the password reset again.');
341       }
342       $errors += $utils->checkPasswordConstraints(strval($_POST['pwd']), $user['email']);
343       if (!count($errors)) {
344         $newHash = $utils->pwdHash($_POST['pwd']);
345         $result = $db->prepare('UPDATE `auth_users` SET `pwdhash` = :pwdhash, `verify_hash` = \'\' WHERE `id` = :userid;');
346         if (!$result->execute(array(':pwdhash' => $newHash, ':userid' => $session['user']))) {
347           $utils->log('pwd_reset_failure', 'user: '.$session['user']);
348           $errors[] = _('Password reset failed. Please <a href="https://www.kairo.at/contact">contact KaiRo.at</a> and tell the team about this.');
349         }
350         else {
351           $pagetype = 'reset_done';
352         }
353       }
354     }
355   }
356 }
357
358 if (!count($errors)) {
359   if ($pagetype == 'verification_sent') {
360     $para = $body->appendElement('p', sprintf(_('An email for confirmation has been sent to %s. Please follow the link provided there to complete the process.'), $user['email']));
361     $para->setAttribute('class', 'verifyinfo pending');
362     $para = $body->appendElement('p', _('Reload this page after you confirm to continue.'));
363     $para->setAttribute('class', 'verifyinfo pending');
364   }
365   elseif ($pagetype == 'resetmail_sent') {
366     $para = $body->appendElement('p',
367         _('An email has been sent to the requested account with further information. If you do not receive an email then please confirm you have entered the same email address used during account registration.'));
368     $para->setAttribute('class', 'resetinfo pending');
369   }
370   elseif ($pagetype == 'resetstart') {
371     $para = $body->appendElement('p', _('If you forgot your password or didn\'t receive the registration confirmation, please enter your email here.'));
372     $para->setAttribute('class', '');
373     $form = $body->appendForm('./?reset', 'POST', 'resetform');
374     $form->setAttribute('id', 'loginform');
375     $form->setAttribute('class', 'loginarea hidden');
376     $ulist = $form->appendElement('ul');
377     $ulist->setAttribute('class', 'flat login');
378     $litem = $ulist->appendElement('li');
379     $inptxt = $litem->appendInputEmail('email', 30, 20, 'login_email');
380     $inptxt->setAttribute('autocomplete', 'email');
381     $inptxt->setAttribute('required', '');
382     $inptxt->setAttribute('placeholder', _('Email'));
383     $litem = $ulist->appendElement('li');
384     $litem->appendInputHidden('tcode', $utils->createTimeCode($session));
385     $submit = $litem->appendInputSubmit(_('Send instructions to email'));
386   }
387   elseif ($pagetype == 'resetpwd') {
388     $para = $body->appendElement('p', sprintf(_('You can set a new password for %s here.'), $user['email']));
389     $para->setAttribute('class', '');
390     $form = $body->appendForm('./', 'POST', 'newpwdform');
391     $form->setAttribute('id', 'loginform');
392     $form->setAttribute('class', 'loginarea hidden');
393     $ulist = $form->appendElement('ul');
394     $ulist->setAttribute('class', 'flat login');
395     $litem = $ulist->appendElement('li');
396     $litem->setAttribute('class', 'donotshow');
397     $inptxt = $litem->appendInputEmail('email_hidden', 30, 20, 'login_email', $user['email']);
398     $inptxt->setAttribute('autocomplete', 'email');
399     $inptxt->setAttribute('placeholder', _('Email'));
400     $litem = $ulist->appendElement('li');
401     $inptxt = $litem->appendInputPassword('pwd', 20, 20, 'login_pwd', '');
402     $inptxt->setAttribute('required', '');
403     $inptxt->setAttribute('placeholder', _('Password'));
404     $inptxt->setAttribute('class', 'login');
405     $litem = $ulist->appendElement('li');
406     $litem->appendInputHidden('reset', '');
407     $litem->appendInputHidden('tcode', $utils->createTimeCode($session));
408     if (!$session['logged_in'] && strlen(@$user['verify_hash'])) {
409       $litem->appendInputHidden('vcode', $user['verify_hash']);
410     }
411     $submit = $litem->appendInputSubmit(_('Save password'));
412   }
413   elseif ($pagetype == 'clientlist') {
414     $scopes = array('clientreg', 'email');
415     $form = $body->appendForm('?clients', 'POST', 'newclientform');
416     $form->setAttribute('id', 'clientform');
417     $tbl = $form->appendElement('table');
418     $tbl->setAttribute('class', 'clientlist border');
419     $thead = $tbl->appendElement('thead');
420     $trow = $thead->appendElement('tr');
421     $trow->appendElement('th', _('Client ID'));
422     $trow->appendElement('th', _('Client Secrect'));
423     $trow->appendElement('th', _('Redirect URI'));
424     $trow->appendElement('th', _('Scope'));
425     $trow->appendElement('th');
426     $tbody = $tbl->appendElement('tbody');
427     foreach ($clients as $client) {
428       $trow = $tbody->appendElement('tr');
429       $trow->appendElement('td', $client['client_id']);
430       $trow->appendElement('td', $client['client_secret']);
431       $trow->appendElement('td', $client['redirect_uri']);
432       $trow->appendElement('td', $client['scope']);
433       $trow->appendElement('td'); // Future: Delete link?
434     }
435     // Form fields for adding a new one.
436     $tfoot = $tbl->appendElement('tfoot');
437     $trow = $tfoot->appendElement('tr');
438     $cell = $trow->appendElement('td');
439     $inptxt = $cell->appendInputText('client_id', 80, 25, 'client_id');
440     $cell = $trow->appendElement('td'); // Empty, as secret will be generated.
441     $cell = $trow->appendElement('td');
442     $inptxt = $cell->appendInputText('redirect_uri', 500, 50, 'redirect_uri');
443     $cell = $trow->appendElement('td');
444     $select = $cell->appendElementSelect('scope');
445     foreach ($scopes as $scope) {
446       $select->appendElementOption($scope, $scope);
447     }
448     //$inptxt = $cell->appendInputText('scope', 100, 20, 'scope');
449     $cell = $trow->appendElement('td');
450     $submit = $cell->appendInputSubmit(_('Create'));
451   }
452   elseif ($session['logged_in']) {
453     if ($pagetype == 'reset_done') {
454       $para = $body->appendElement('p', _('Your password has successfully been reset.'));
455       $para->setAttribute('class', 'resetinfo done');
456     }
457     $div = $body->appendElement('div', $user['email']);
458     $div->setAttribute('class', 'loginheader');
459     $div = $body->appendElement('div');
460     $div->setAttribute('class', 'loginlinks');
461     $ulist = $div->appendElement('ul');
462     $ulist->setAttribute('class', 'flat');
463     $litem = $ulist->appendElement('li');
464     $link = $litem->appendLink('./?logout', _('Log out'));
465     if (in_array($user['email'], $utils->client_reg_email_whitelist)) {
466       $litem = $ulist->appendElement('li');
467       $link = $litem->appendLink('./?clients', _('Manage OAuth2 clients'));
468     }
469     $litem = $ulist->appendElement('li');
470     $litem->appendLink('./?reset', _('Set new password'));
471   }
472   else { // not logged in
473     if ($pagetype == 'verification_done') {
474       $para = $body->appendElement('p', _('Hooray! Your email was successfully confirmed! You can log in now.'));
475       $para->setAttribute('class', 'verifyinfo done');
476     }
477     elseif ($pagetype == 'reset_done') {
478       $para = $body->appendElement('p', _('Your password has successfully been reset. You can log in now with the new password.'));
479       $para->setAttribute('class', 'resetinfo done');
480     }
481     $utils->appendLoginForm($body, $session, $user);
482   }
483 }
484
485 if (count($errors)) {
486   $body->appendElement('p', ((count($errors) <= 1)
487                             ?_('The following error was detected')
488                             :_('The following errors were detected')).':');
489   $list = $body->appendElement('ul');
490   $list->setAttribute('class', 'flat warn');
491   foreach ($errors as $msg) {
492     $item = $list->appendElement('li', $msg);
493   }
494   $body->appendButton(_('Back'), 'history.back();');
495 }
496
497 // Send HTML to client.
498 print($document->saveHTML());
499 ?>