Subversion Repositories oidplus

Rev

Rev 1282 | Rev 1293 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

  1. <?php
  2.  
  3. /*
  4.  * OIDplus 2.0
  5.  * Copyright 2019 - 2023 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. namespace ViaThinkSoft\OIDplus;
  21.  
  22. // phpcs:disable PSR1.Files.SideEffects
  23. \defined('INSIDE_OIDPLUS') or die;
  24. // phpcs:enable PSR1.Files.SideEffects
  25.  
  26. class OIDplusPageRaInvite extends OIDplusPagePluginRa {
  27.  
  28.         /**
  29.          * @param string $actionID
  30.          * @param array $params
  31.          * @return array
  32.          * @throws OIDplusException
  33.          * @throws OIDplusMailException
  34.          */
  35.         public function action(string $actionID, array $params): array {
  36.                 if ($actionID == 'invite_ra') {
  37.                         $email = $params['email'];
  38.  
  39.                         if (!OIDplus::mailUtils()->validMailAddress($email)) {
  40.                                 throw new OIDplusException(_L('Invalid email address'));
  41.                         }
  42.  
  43.                         OIDplus::getActiveCaptchaPlugin()->captchaVerify($params, 'captcha');
  44.  
  45.                         $this->inviteSecurityCheck($email);
  46.                         // TODO: should we also log who has invited?
  47.                         OIDplus::logger()->log("V2:[INFO]RA(%1)", "RA '%1' has been invited", $email);
  48.  
  49.                         $activate_url = OIDplus::webpath(null,OIDplus::PATH_ABSOLUTE_CANONICAL) . '?goto='.urlencode('oidplus:activate_ra$'.$email.'$'.OIDplus::authUtils()->makeAuthKey(['ed840c3e-f4fa-11ed-b67e-3c4a92df8582',$email]));
  50.  
  51.                         $message = $this->getInvitationText($email);
  52.                         $message = str_replace('{{ACTIVATE_URL}}', $activate_url, $message);
  53.  
  54.                         OIDplus::mailUtils()->sendMail($email, OIDplus::config()->getValue('system_title').' - Invitation', $message);
  55.  
  56.                         return array("status" => 0);
  57.  
  58.                 } else if ($actionID == 'activate_ra') {
  59.  
  60.                         _CheckParamExists($params, 'password1');
  61.                         _CheckParamExists($params, 'password2');
  62.                         _CheckParamExists($params, 'email');
  63.                         _CheckParamExists($params, 'auth');
  64.  
  65.                         $password1 = $params['password1'];
  66.                         $password2 = $params['password2'];
  67.                         $email = $params['email'];
  68.                         $auth = $params['auth'];
  69.  
  70.                         if (!OIDplus::authUtils()->validateAuthKey(['ed840c3e-f4fa-11ed-b67e-3c4a92df8582',$email], $auth, OIDplus::config()->getValue('max_ra_invite_time',-1))) {
  71.                                 throw new OIDplusException(_L('Invalid or expired authentication key'));
  72.                         }
  73.  
  74.                         if ($password1 !== $password2) {
  75.                                 throw new OIDplusException(_L('Passwords do not match'));
  76.                         }
  77.  
  78.                         if (strlen($password1) < OIDplus::config()->getValue('ra_min_password_length')) {
  79.                                 $minlen = OIDplus::config()->getValue('ra_min_password_length');
  80.                                 throw new OIDplusException(_L('Password is too short. Need at least %1 characters',$minlen));
  81.                         }
  82.  
  83.                         OIDplus::logger()->log("V2:[OK]RA(%1)", "RA '%1' has been registered due to invitation", $email);
  84.  
  85.                         $ra = new OIDplusRA($email);
  86.                         $ra->register_ra($password1);
  87.  
  88.                         return array("status" => 0);
  89.                 } else {
  90.                         return parent::action($actionID, $params);
  91.                 }
  92.         }
  93.  
  94.         /**
  95.          * @param bool $html
  96.          * @return void
  97.          * @throws OIDplusException
  98.          */
  99.         public function init(bool $html=true) {
  100.                 OIDplus::config()->prepareConfigKey('max_ra_invite_time', 'Max RA invite time in seconds (0 = infinite)', '0', OIDplusConfig::PROTECTION_EDITABLE, function($value) {
  101.                         if (!is_numeric($value) || ($value < 0)) {
  102.                                 throw new OIDplusException(_L('Please enter a valid value.'));
  103.                         }
  104.                 });
  105.                 OIDplus::config()->prepareConfigKey('ra_invitation_enabled', 'May RAs be invited? (0=no, 1=yes)', '1', OIDplusConfig::PROTECTION_EDITABLE, function($value) {
  106.                         if (($value != 0) && ($value != 1)) {
  107.                                 throw new OIDplusException(_L('Please enter a valid value (0=no, 1=yes).'));
  108.                         }
  109.                 });
  110.         }
  111.  
  112.         /**
  113.          * @param string $id
  114.          * @param array $out
  115.          * @param bool $handled
  116.          * @return void
  117.          * @throws OIDplusException
  118.          */
  119.         public function gui(string $id, array &$out, bool &$handled) {
  120.                 if (explode('$',$id)[0] == 'oidplus:invite_ra') {
  121.                         $handled = true;
  122.  
  123.                         $email = explode('$',$id)[1];
  124.                         $origin = explode('$',$id)[2];
  125.  
  126.                         $out['title'] = _L('Invite a Registration Authority');
  127.  
  128.                         if (!OIDplus::config()->getValue('ra_invitation_enabled')) {
  129.                                 throw new OIDplusException(_L('Invitations are disabled by the administrator.'), $out['title']);
  130.                         }
  131.  
  132.                         $out['icon'] = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'img/invite_icon.png';
  133.  
  134.                         try {
  135.                                 $this->inviteSecurityCheck($email);
  136.                                 $cont = $this->getInvitationText($email);
  137.  
  138.                                 $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>
  139.                                   <form id="inviteForm" action="javascript:void(0);" onsubmit="return OIDplusPageRaInvite.inviteFormOnSubmit();">
  140.                                     <input type="hidden" id="email" value="'.htmlentities($email).'"/>
  141.                                     <input type="hidden" id="origin" value="'.htmlentities($origin).'"/>
  142.                                     '.OIDplus::getActiveCaptchaPlugin()->captchaGenerate().'
  143.                                     <br>
  144.                                     <input type="submit" value="'._L('Send invitation').'">
  145.                                   </form>';
  146.  
  147.                         } catch (\Exception $e) {
  148.  
  149.                                 $htmlmsg = $e instanceof OIDplusException ? $e->getHtmlMessage() : htmlentities($e->getMessage());
  150.                                 throw new OIDplusHtmlException(_L('Error: %1',$htmlmsg), $out['title']);
  151.  
  152.                         }
  153.                 } else if (explode('$',$id)[0] == 'oidplus:activate_ra') {
  154.                         $handled = true;
  155.  
  156.                         $email = explode('$',$id)[1];
  157.                         $auth = explode('$',$id)[2];
  158.  
  159.                         $out['title'] = _L('Register as Registration Authority');
  160.  
  161.                         if (!OIDplus::config()->getValue('ra_invitation_enabled')) {
  162.                                 throw new OIDplusException(_L('Invitations are disabled by the administrator.'), $out['title']);
  163.                         }
  164.  
  165.                         $out['icon'] = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'img/activate_icon.png';
  166.  
  167.                         $res = OIDplus::db()->query("select * from ###ra where email = ?", array($email));
  168.                         if ($res->any()) {
  169.                                 $out['text'] = _L('This RA is already registered and does not need to be invited.');
  170.                         } else {
  171.                                 if (!OIDplus::authUtils()->validateAuthKey(['ed840c3e-f4fa-11ed-b67e-3c4a92df8582',$email], $auth, OIDplus::config()->getValue('max_ra_invite_time',-1))) {
  172.                                         throw new OIDplusException(_L('Invalid authorization. Is the URL OK?'), $out['title']);
  173.                                 } else {
  174.                                         // TODO: like in the FreeOID plugin, we could ask here at least for a name for the RA
  175.                                         $out['text'] = '<p>'._L('E-Mail-Address').': <b>'.$email.'</b></p>
  176.  
  177.                                           <form id="activateRaForm" action="javascript:void(0);" onsubmit="return OIDplusPageRaInvite.activateRaFormOnSubmit();">
  178.                                             <input type="hidden" id="email" value="'.htmlentities($email).'"/>
  179.                                             <input type="hidden" id="auth" value="'.htmlentities($auth).'"/>
  180.                                             <div><label class="padding_label">'._L('New password').':</label><input type="password" id="password1" value=""/></div>
  181.                                             <div><label class="padding_label">'._L('Repeat').':</label><input type="password" id="password2" value=""/></div>
  182.                                             <br><input type="submit" value="'._L('Register').'">
  183.                                           </form>';
  184.                                 }
  185.                         }
  186.                 }
  187.         }
  188.  
  189.         /**
  190.          * @param array $json
  191.          * @param string|null $ra_email
  192.          * @param bool $nonjs
  193.          * @param string $req_goto
  194.          * @return bool
  195.          */
  196.         public function tree(array &$json, string $ra_email=null, bool $nonjs=false, string $req_goto=''): bool {
  197.                 //if (!$ra_email) return false;
  198.                 //if (!OIDplus::authUtils()->isRaLoggedIn($ra_email) && !OIDplus::authUtils()->isAdminLoggedIn()) return false;
  199.  
  200.                 return false;
  201.         }
  202.  
  203.         /**
  204.          * @param string $email
  205.          * @return void
  206.          * @throws OIDplusException
  207.          */
  208.         private function inviteSecurityCheck(string $email) {
  209.                 $res = OIDplus::db()->query("select * from ###ra where email = ?", array($email));
  210.                 if ($res->any()) {
  211.                         throw new OIDplusException(_L('This RA is already registered and does not need to be invited.'));
  212.                 }
  213.  
  214.                 if (!OIDplus::authUtils()->isAdminLoggedIn()) {
  215.                         // Check if the RA may invite the user (i.e. the they are the parent of an OID of that person)
  216.                         $ok = false;
  217.                         $res = OIDplus::db()->query("select parent from ###objects where ra_email = ?", array($email));
  218.                         while ($row = $res->fetch_array()) {
  219.                                 if (!$row['parent']) continue;
  220.                                 $objParent = OIDplusObject::parse($row['parent']);
  221.                                 if (!$objParent) throw new OIDplusException(_L('Type of %1 unknown',$row['parent']));
  222.                                 if ($objParent->userHasWriteRights()) {
  223.                                         $ok = true;
  224.                                 }
  225.                         }
  226.                         if (!$ok) {
  227.                                 throw new OIDplusHtmlException(_L('You may not invite this RA. Maybe you need to <a %1>log in</a> again.',OIDplus::gui()->link('oidplus:login')), null, 401);
  228.                         }
  229.                 }
  230.         }
  231.  
  232.         /**
  233.          * @param string $email
  234.          * @return string
  235.          * @throws OIDplusException
  236.          */
  237.         private function getInvitationText(string $email): string {
  238.                 $list_of_oids = array();
  239.                 $res = OIDplus::db()->query("select id from ###objects where ra_email = ?", array($email));
  240.                 while ($row = $res->fetch_array()) {
  241.                         $list_of_oids[] = $row['id'];
  242.                 }
  243.  
  244.                 $message = file_get_contents(__DIR__ . '/invite_msg.tpl');
  245.  
  246.                 // Resolve stuff
  247.                 // Note: {{ACTIVATE_URL}} will be resolved in ajax.php
  248.  
  249.                 $message = str_replace('{{SYSTEM_URL}}', OIDplus::webpath(null,OIDplus::PATH_ABSOLUTE_CANONICAL), $message);
  250.                 $message = str_replace('{{OID_LIST}}', implode("\n", $list_of_oids), $message);
  251.                 $message = str_replace('{{ADMIN_EMAIL}}', OIDplus::config()->getValue('admin_email'), $message);
  252.  
  253.                 return str_replace('{{PARTY}}', OIDplus::authUtils()->isAdminLoggedIn() ? 'the system administrator' : 'a superior Registration Authority', $message);
  254.         }
  255.  
  256.         /**
  257.          * @param string $request
  258.          * @return array|false
  259.          */
  260.         public function tree_search(string $request) {
  261.                 return false;
  262.         }
  263. }
  264.