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