Subversion Repositories oidplus

Rev

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