Subversion Repositories oidplus

Rev

Rev 496 | Go to most recent revision | Blame | Last modification | View Log | RSS feed

  1. <?php
  2.  
  3. /*
  4.  * OIDplus 2.0
  5.  * Copyright 2019 - 2021 Daniel Marschall, ViaThinkSoft
  6.  *
  7.  * Licensed under the Apache License, Version 2.0 (the "License");
  8.  * you may not use this file except in compliance with the License.
  9.  * You may obtain a copy of the License at
  10.  *
  11.  *     http://www.apache.org/licenses/LICENSE-2.0
  12.  *
  13.  * Unless required by applicable law or agreed to in writing, software
  14.  * distributed under the License is distributed on an "AS IS" BASIS,
  15.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16.  * See the License for the specific language governing permissions and
  17.  * limitations under the License.
  18.  */
  19.  
  20. if (!defined('INSIDE_OIDPLUS')) die();
  21.  
  22. class OIDplusPageRaInvite extends OIDplusPagePluginRa {
  23.  
  24.         public function action($actionID, $params) {
  25.                 if ($actionID == 'invite_ra') {
  26.                         $email = $params['email'];
  27.  
  28.                         if (!OIDplus::mailUtils()->validMailAddress($email)) {
  29.                                 throw new OIDplusException(_L('Invalid email address'));
  30.                         }
  31.  
  32.                         if (OIDplus::baseConfig()->getValue('RECAPTCHA_ENABLED', false)) {
  33.                                 $secret=OIDplus::baseConfig()->getValue('RECAPTCHA_PRIVATE', '');
  34.                                 $response=$params["captcha"];
  35.                                 $verify=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret={$secret}&response={$response}");
  36.                                 $captcha_success=json_decode($verify);
  37.                                 if ($captcha_success->success==false) {
  38.                                         throw new OIDplusException(_L('CAPTCHA not successfully verified'));
  39.                                 }
  40.                         }
  41.  
  42.                         $this->inviteSecurityCheck($email);
  43.                         // TODO: should we also log who has invited?
  44.                         OIDplus::logger()->log("[INFO]RA($email)!", "RA '$email' has been invited");
  45.  
  46.                         $timestamp = time();
  47.                         $activate_url = OIDplus::webpath() . '?goto='.urlencode('oidplus:activate_ra$'.$email.'$'.$timestamp.'$'.OIDplus::authUtils()::makeAuthKey('activate_ra;'.$email.';'.$timestamp));
  48.  
  49.                         $message = $this->getInvitationText($email);
  50.                         $message = str_replace('{{ACTIVATE_URL}}', $activate_url, $message);
  51.  
  52.                         OIDplus::mailUtils()->sendMail($email, OIDplus::config()->getValue('system_title').' - Invitation', $message, OIDplus::config()->getValue('global_cc'));
  53.  
  54.                         return array("status" => 0);
  55.  
  56.                 } else if ($actionID == 'activate_ra') {
  57.  
  58.                         $password1 = $params['password1'];
  59.                         $password2 = $params['password2'];
  60.                         $email = $params['email'];
  61.                         $auth = $params['auth'];
  62.                         $timestamp = $params['timestamp'];
  63.  
  64.                         if (!OIDplus::authUtils()::validateAuthKey('activate_ra;'.$email.';'.$timestamp, $auth)) {
  65.                                 throw new OIDplusException(_L('Invalid auth key'));
  66.                         }
  67.  
  68.                         if ((OIDplus::config()->getValue('max_ra_invite_time') > 0) && (time()-$timestamp > OIDplus::config()->getValue('max_ra_invite_time'))) {
  69.                                 throw new OIDplusException(_L('Invitation expired!'));
  70.                         }
  71.  
  72.                         if ($password1 !== $password2) {
  73.                                 throw new OIDplusException(_L('Passwords do not match'));
  74.                         }
  75.  
  76.                         if (strlen($password1) < OIDplus::config()->getValue('ra_min_password_length')) {
  77.                                 $minlen = OIDplus::config()->getValue('ra_min_password_length');
  78.                                 throw new OIDplusException(_L('Password is too short. Need at least %1 characters',$minlen));
  79.                         }
  80.  
  81.                         OIDplus::logger()->log("[OK]RA($email)!", "RA '$email' has been registered due to invitation");
  82.  
  83.                         $ra = new OIDplusRA($email);
  84.                         $ra->register_ra($password1);
  85.  
  86.                         return array("status" => 0);
  87.                 } else {
  88.                         throw new OIDplusException(_L('Unknown action ID'));
  89.                 }
  90.         }
  91.  
  92.         public function init($html=true) {
  93.                 OIDplus::config()->prepareConfigKey('max_ra_invite_time', 'Max RA invite time in seconds (0 = infinite)', '0', OIDplusConfig::PROTECTION_EDITABLE, function($value) {
  94.                         if (!is_numeric($value) || ($value < 0)) {
  95.                                 throw new OIDplusException(_L('Please enter a valid value.'));
  96.                         }
  97.                 });
  98.                 OIDplus::config()->prepareConfigKey('ra_invitation_enabled', 'May RAs be invited? (0=no, 1=yes)', '1', OIDplusConfig::PROTECTION_EDITABLE, function($value) {
  99.                         if (($value != 0) && ($value != 1)) {
  100.                                 throw new OIDplusException(_L('Please enter a valid value (0=no, 1=yes).'));
  101.                         }
  102.                 });
  103.         }
  104.  
  105.         public function gui($id, &$out, &$handled) {
  106.                 if (explode('$',$id)[0] == 'oidplus:invite_ra') {
  107.                         $handled = true;
  108.  
  109.                         $email = explode('$',$id)[1];
  110.                         $origin = explode('$',$id)[2];
  111.  
  112.                         $out['title'] = _L('Invite a Registration Authority');
  113.  
  114.                         if (!OIDplus::config()->getValue('ra_invitation_enabled')) {
  115.                                 $out['icon'] = 'img/error_big.png';
  116.                                 $out['text'] = '<p>'._L('Invitations are disabled by the administrator.').'</p>';
  117.                                 return;
  118.                         }
  119.  
  120.                         $out['icon'] = OIDplus::webpath(__DIR__).'invite_ra_big.png';
  121.  
  122.                         try {
  123.                                 $this->inviteSecurityCheck($email);
  124.                                 $cont = $this->getInvitationText($email);
  125.  
  126.                                 $out['text'] .= '<p>'._L('You have chosen to invite %1 as a Registration Authority. If you click "Send", the following email will be sent to %2:','<b>'.$email.'</b>',$email).'</p><p><i>'.nl2br(htmlentities($cont)).'</i></p>
  127.                                   <form id="inviteForm" action="javascript:void(0);" onsubmit="return inviteFormOnSubmit();">
  128.                                     <input type="hidden" id="email" value="'.htmlentities($email).'"/>
  129.                                     <input type="hidden" id="origin" value="'.htmlentities($origin).'"/>'.
  130.                                  (OIDplus::baseConfig()->getValue('RECAPTCHA_ENABLED', false) ?
  131.                                  '<script> grecaptcha.render(document.getElementById("g-recaptcha"), { "sitekey" : "'.OIDplus::baseConfig()->getValue('RECAPTCHA_PUBLIC', '').'" }); </script>'.
  132.                                  '<div id="g-recaptcha" class="g-recaptcha" data-sitekey="'.OIDplus::baseConfig()->getValue('RECAPTCHA_PUBLIC', '').'"></div>' : '').
  133.                                 ' <br>
  134.                                     <input type="submit" value="'._L('Send invitation').'">
  135.                                   </form>';
  136.  
  137.                         } catch (Exception $e) {
  138.  
  139.                                 $out['icon'] = 'img/error_big.png';
  140.                                 $out['text'] = _L('Error: %1',$e->getMessage());
  141.  
  142.                         }
  143.                 } else if (explode('$',$id)[0] == 'oidplus:activate_ra') {
  144.                         $handled = true;
  145.  
  146.                         $email = explode('$',$id)[1];
  147.                         $timestamp = explode('$',$id)[2];
  148.                         $auth = explode('$',$id)[3];
  149.  
  150.                         $out['title'] = _L('Register as Registration Authority');
  151.  
  152.                         if (!OIDplus::config()->getValue('ra_invitation_enabled')) {
  153.                                 $out['icon'] = 'img/error_big.png';
  154.                                 $out['text'] = '<p>'._L('Invitations are disabled by the administrator.').'</p>';
  155.                                 return;
  156.                         }
  157.  
  158.                         $out['icon'] = OIDplus::webpath(__DIR__).'activate_ra_big.png';
  159.  
  160.                         $res = OIDplus::db()->query("select * from ###ra where email = ?", array($email));
  161.                         if ($res->num_rows() > 0) {
  162.                                 $out['text'] = _L('This RA is already registered and does not need to be invited.');
  163.                         } else {
  164.                                 if (!OIDplus::authUtils()::validateAuthKey('activate_ra;'.$email.';'.$timestamp, $auth)) {
  165.                                         $out['icon'] = 'img/error_big.png';
  166.                                         $out['text'] = _L('Invalid authorization. Is the URL OK?');
  167.                                 } else {
  168.                                         // TODO: like in the FreeOID plugin, we could ask here at least for a name for the RA
  169.                                         $out['text'] = '<p>'._L('E-Mail-Address').': <b>'.$email.'</b></p>
  170.  
  171.                                           <form id="activateRaForm" action="javascript:void(0);" onsubmit="return activateRaFormOnSubmit();">
  172.                                             <input type="hidden" id="email" value="'.htmlentities($email).'"/>
  173.                                             <input type="hidden" id="timestamp" value="'.htmlentities($timestamp).'"/>
  174.                                             <input type="hidden" id="auth" value="'.htmlentities($auth).'"/>
  175.                                             <div><label class="padding_label">'._L('New password').':</label><input type="password" id="password1" value=""/></div>
  176.                                             <div><label class="padding_label">'._L('Repeat').':</label><input type="password" id="password2" value=""/></div>
  177.                                             <br><input type="submit" value="'._L('Register').'">
  178.                                           </form>';
  179.                                 }
  180.                         }
  181.                 }
  182.         }
  183.  
  184.         public function tree(&$json, $ra_email=null, $nonjs=false, $req_goto='') {
  185.                 //if (!$ra_email) return false;
  186.                 //if (!OIDplus::authUtils()::isRaLoggedIn($ra_email) && !OIDplus::authUtils()::isAdminLoggedIn()) return false;
  187.  
  188.                 return false;
  189.         }
  190.  
  191.         private function inviteSecurityCheck($email) {
  192.                 $res = OIDplus::db()->query("select * from ###ra where email = ?", array($email));
  193.                 if ($res->num_rows() > 0) {
  194.                         throw new OIDplusException(_L('This RA is already registered and does not need to be invited.'));
  195.                 }
  196.  
  197.                 if (!OIDplus::authUtils()::isAdminLoggedIn()) {
  198.                         // Check if the RA may invite the user (i.e. the they are the parent of an OID of that person)
  199.                         $ok = false;
  200.                         $res = OIDplus::db()->query("select parent from ###objects where ra_email = ?", array($email));
  201.                         while ($row = $res->fetch_array()) {
  202.                                 $objParent = OIDplusObject::parse($row['parent']);
  203.                                 if (is_null($objParent)) throw new OIDplusException(_L('Type of %1 unknown',$row['parent']));
  204.                                 if ($objParent->userHasWriteRights()) {
  205.                                         $ok = true;
  206.                                 }
  207.                         }
  208.                         if (!$ok) {
  209.                                 throw new OIDplusException(_L('You may not invite this RA. Maybe you need to <a %1>log in</a> again.',OIDplus::gui()->link('oidplus:login')));
  210.                         }
  211.                 }
  212.         }
  213.  
  214.         private function getInvitationText($email) {
  215.                 $list_of_oids = array();
  216.                 $res = OIDplus::db()->query("select id from ###objects where ra_email = ?", array($email));
  217.                 while ($row = $res->fetch_array()) {
  218.                         $list_of_oids[] = $row['id'];
  219.                 }
  220.  
  221.                 $message = file_get_contents(__DIR__ . '/invite_msg.tpl');
  222.  
  223.                 // Resolve stuff
  224.                 $message = str_replace('{{SYSTEM_URL}}', OIDplus::webpath(null,false), $message);
  225.                 $message = str_replace('{{OID_LIST}}', implode("\n", $list_of_oids), $message);
  226.                 $message = str_replace('{{ADMIN_EMAIL}}', OIDplus::config()->getValue('admin_email'), $message);
  227.                 $message = str_replace('{{PARTY}}', OIDplus::authUtils()::isAdminLoggedIn() ? 'the system administrator' : 'a superior Registration Authority', $message);
  228.  
  229.                 // {{ACTIVATE_URL}} will be resolved in ajax.php
  230.  
  231.                 return $message;
  232.         }
  233.  
  234.         public function tree_search($request) {
  235.                 return false;
  236.         }
  237. }