Subversion Repositories oidplus

Rev

Rev 1283 | 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 OIDplusPageRaChangeEMail 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.                 if (!OIDplus::config()->getValue('allow_ra_email_change') && !OIDplus::authUtils()->isAdminLoggedIn()) {
  36.                         throw new OIDplusException(_L('This functionality has been disabled by the administrator.'));
  37.                 }
  38.  
  39.                 _CheckParamExists($params, 'old_email');
  40.                 _CheckParamExists($params, 'new_email');
  41.  
  42.                 $old_email = $params['old_email'];
  43.                 $new_email = $params['new_email'];
  44.  
  45.                 $ra = new OIDplusRA($old_email);
  46.                 if ($ra->isPasswordLess() && !OIDplus::authUtils()->isAdminLoggedIn()) {
  47.                         throw new OIDplusException(_L('E-Mail-Address cannot be changed because this user does not have a password'));
  48.                 }
  49.  
  50.                 if (!OIDplus::authUtils()->isRaLoggedIn($old_email) && !OIDplus::authUtils()->isAdminLoggedIn()) {
  51.                         throw new OIDplusException(_L('Authentication error. Please log in as admin, or as the RA to update its email address.'), null, 401);
  52.                 }
  53.  
  54.                 if (!OIDplus::mailUtils()->validMailAddress($new_email)) {
  55.                         throw new OIDplusException(_L('eMail address is invalid.'));
  56.                 }
  57.  
  58.                 $res = OIDplus::db()->query("select * from ###ra where email = ?", array($old_email));
  59.                 if (!$res->any()) {
  60.                         throw new OIDplusException(_L('eMail address does not exist anymore. It was probably already changed.'));
  61.                 }
  62.  
  63.                 $res = OIDplus::db()->query("select * from ###ra where email = ?", array($new_email));
  64.                 if ($res->any()) {
  65.                         throw new OIDplusException(_L('eMail address is already used by another RA. To merge accounts, please contact the superior RA of your objects and request an owner change of your objects.'));
  66.                 }
  67.  
  68.                 if (OIDplus::authUtils()->isAdminLoggedIn()) {
  69.                         $ra_was_logged_in = OIDplus::authUtils()->isRaLoggedIn($old_email);
  70.  
  71.                         $ra = new OIDplusRA($old_email);
  72.  
  73.                         // Change RA email
  74.                         $ra->change_email($new_email);
  75.                         OIDplus::logger()->log("V2:[WARN]RA(%1)+[INFO]RA(%2)+[OK]A", "Admin changed email address '%1' to '%2'", $old_email, $new_email);
  76.  
  77.                         // Change objects
  78.                         $res = OIDplus::db()->query("select id from ###objects where ra_email = ?", array($old_email));
  79.                         while ($row = $res->fetch_array()) {
  80.                                 OIDplus::logger()->log("V2:[INFO]OID(%1)+SUPOID(%1)", "Admin changed email address of RA '%2' (owner of %1) to '%3'", $row['id'], $old_email, $new_email);
  81.                         }
  82.                         OIDplus::db()->query("update ###objects set ra_email = ? where ra_email = ?", array($new_email, $old_email));
  83.                         OIDplusObject::resetObjectInformationCache();
  84.  
  85.                         // Re-login
  86.                         if ($ra_was_logged_in) {
  87.                                 OIDplus::authUtils()->raLogout($old_email);
  88.                                 OIDplus::authUtils()->raLogin($new_email);
  89.                         }
  90.  
  91.                         return array("status" => 0);
  92.                 } else {
  93.                         OIDplus::logger()->log("V2:[INFO]RA(%1)+RA(%2)", "Requested email address change from '%1' to '%2'", $old_email, $new_email);
  94.  
  95.                         $activate_url = OIDplus::webpath(null,OIDplus::PATH_ABSOLUTE_CANONICAL) . '?goto='.urlencode('oidplus:activate_new_ra_email$'.$old_email.'$'.$new_email.'$'.OIDplus::authUtils()->makeAuthKey(['5ef24124-f4fb-11ed-b67e-3c4a92df8582',$old_email,$new_email]));
  96.  
  97.                         $message = file_get_contents(__DIR__ . '/change_request_email.tpl');
  98.                         $message = str_replace('{{SYSTEM_URL}}', OIDplus::webpath(null,OIDplus::PATH_ABSOLUTE_CANONICAL), $message);
  99.                         $message = str_replace('{{SYSTEM_TITLE}}', OIDplus::config()->getValue('system_title'), $message);
  100.                         $message = str_replace('{{ADMIN_EMAIL}}', OIDplus::config()->getValue('admin_email'), $message);
  101.                         $message = str_replace('{{OLD_EMAIL}}', $old_email, $message);
  102.                         $message = str_replace('{{NEW_EMAIL}}', $new_email, $message);
  103.                         $message = str_replace('{{ACTIVATE_URL}}', $activate_url, $message);
  104.                         OIDplus::mailUtils()->sendMail($new_email, OIDplus::config()->getValue('system_title').' - Change email request', $message);
  105.  
  106.                         return array("status" => 0);
  107.                 }
  108.         }
  109.  
  110.         /**
  111.          * @param array $params
  112.          * @return array
  113.          * @throws OIDplusException
  114.          * @throws OIDplusMailException
  115.          */
  116.         private function action_Activate(array $params): array {
  117.                 if (!OIDplus::config()->getValue('allow_ra_email_change')) {
  118.                         throw new OIDplusException(_L('This functionality has been disabled by the administrator.'));
  119.                 }
  120.  
  121.                 _CheckParamExists($params, 'old_email');
  122.                 _CheckParamExists($params, 'new_email');
  123.                 _CheckParamExists($params, 'password');
  124.                 _CheckParamExists($params, 'auth');
  125.  
  126.                 $old_email = $params['old_email'];
  127.                 $new_email = $params['new_email'];
  128.                 $password = $params['password'];
  129.  
  130.                 $auth = $params['auth'];
  131.  
  132.                 $ra_was_logged_in = OIDplus::authUtils()->isRaLoggedIn($old_email);
  133.  
  134.                 $ra = new OIDplusRA($old_email);
  135.                 if ($ra->isPasswordLess() && !OIDplus::authUtils()->isAdminLoggedIn()) {
  136.                         throw new OIDplusException(_L('E-Mail-Address cannot be changed because this user does not have a password'));
  137.                 }
  138.  
  139.                 if (!OIDplus::authUtils()->validateAuthKey(['5ef24124-f4fb-11ed-b67e-3c4a92df8582',$old_email,$new_email], $auth, OIDplus::config()->getValue('max_ra_email_change_time', -1))) {
  140.                         throw new OIDplusException(_L('Invalid or expired authentication key'));
  141.                 }
  142.  
  143.                 $res = OIDplus::db()->query("select * from ###ra where email = ?", array($old_email));
  144.                 if (!$res->any()) {
  145.                         throw new OIDplusException(_L('eMail address does not exist anymore. It was probably already changed.'));
  146.                 }
  147.  
  148.                 $res = OIDplus::db()->query("select * from ###ra where email = ?", array($new_email));
  149.                 if ($res->any()) {
  150.                         throw new OIDplusException(_L('eMail address is already used by another RA. To merge accounts, please contact the superior RA of your objects and request an owner change of your objects.'));
  151.                 }
  152.  
  153.                 $ra = new OIDplusRA($old_email);
  154.                 if (!$ra->isPasswordLess()) {
  155.                         if (!$ra->checkPassword($password)) {
  156.                                 throw new OIDplusException(_L('Wrong password'));
  157.                         }
  158.                 }
  159.  
  160.                 // Change address of RA
  161.                 $ra->change_email($new_email);
  162.                 OIDplus::logger()->log("V2:[OK]RA(%2)+RA(%1)", "RA '%1' has changed their email address to '%2'", $old_email, $new_email);
  163.  
  164.                 // Change objects
  165.                 $res = OIDplus::db()->query("select id from ###objects where ra_email = ?", array($old_email));
  166.                 while ($row = $res->fetch_array()) {
  167.                         OIDplus::logger()->log("V2:[INFO]OID(%1)+SUPOID(%1)", "RA '%2' (owner of %1) has changed their email address to '%3'", $row['id'], $old_email, $new_email);
  168.                 }
  169.                 OIDplus::db()->query("update ###objects set ra_email = ? where ra_email = ?", array($new_email, $old_email));
  170.                 OIDplusObject::resetObjectInformationCache();
  171.  
  172.                 // Re-login
  173.                 if ($ra_was_logged_in) {
  174.                         OIDplus::authUtils()->raLogout($old_email);
  175.                         OIDplus::authUtils()->raLogin($new_email);
  176.                 }
  177.  
  178.                 // Send email
  179.                 $message = file_get_contents(__DIR__ . '/email_change_confirmation.tpl');
  180.                 $message = str_replace('{{SYSTEM_URL}}', OIDplus::webpath(null,OIDplus::PATH_ABSOLUTE_CANONICAL), $message);
  181.                 $message = str_replace('{{SYSTEM_TITLE}}', OIDplus::config()->getValue('system_title'), $message);
  182.                 $message = str_replace('{{ADMIN_EMAIL}}', OIDplus::config()->getValue('admin_email'), $message);
  183.                 $message = str_replace('{{OLD_EMAIL}}', $old_email, $message);
  184.                 $message = str_replace('{{NEW_EMAIL}}', $new_email, $message);
  185.                 OIDplus::mailUtils()->sendMail($old_email, OIDplus::config()->getValue('system_title').' - eMail address changed', $message);
  186.  
  187.                 return array("status" => 0);
  188.         }
  189.  
  190.         /**
  191.          * @param string $actionID
  192.          * @param array $params
  193.          * @return array
  194.          * @throws OIDplusException
  195.          * @throws OIDplusMailException
  196.          */
  197.         public function action(string $actionID, array $params): array {
  198.                 if ($actionID == 'change_ra_email') {
  199.                         return $this->action_Request($params);
  200.                 } else if ($actionID == 'activate_new_ra_email') {
  201.                         return $this->action_Activate($params);
  202.                 } else {
  203.                         return parent::action($actionID, $params);
  204.                 }
  205.         }
  206.  
  207.         /**
  208.          * @param bool $html
  209.          * @return void
  210.          * @throws OIDplusException
  211.          */
  212.         public function init(bool $html=true) {
  213.                 OIDplus::config()->prepareConfigKey('max_ra_email_change_time', 'Max RA email change time in seconds (0 = infinite)', '0', OIDplusConfig::PROTECTION_EDITABLE, function($value) {
  214.                         if (!is_numeric($value) || ($value < 0)) {
  215.                                 throw new OIDplusException(_L('Please enter a valid value.'));
  216.                         }
  217.                 });
  218.                 OIDplus::config()->prepareConfigKey('allow_ra_email_change', 'Allow that RAs change their email address (0/1)', '1', OIDplusConfig::PROTECTION_EDITABLE, function($value) {
  219.                         if (($value != '0') && ($value != '1')) {
  220.                                 throw new OIDplusException(_L('Please enter a valid value (0=no, 1=yes).'));
  221.                         }
  222.                 });
  223.         }
  224.  
  225.         /**
  226.          * @param string $id
  227.          * @param array $out
  228.          * @param bool $handled
  229.          * @return void
  230.          * @throws OIDplusException
  231.          */
  232.         public function gui(string $id, array &$out, bool &$handled) {
  233.                 if (explode('$',$id)[0] == 'oidplus:change_ra_email') {
  234.                         $handled = true;
  235.  
  236.                         $ra_email = explode('$',$id)[1];
  237.  
  238.                         $out['title'] = _L('Change RA email');
  239.                         $out['icon'] = file_exists(__DIR__.'/img/main_icon.png') ? OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'img/main_icon.png' : '';
  240.  
  241.                         if (!OIDplus::authUtils()->isRaLoggedIn($ra_email) && !OIDplus::authUtils()->isAdminLoggedIn()) {
  242.                                 throw new OIDplusHtmlException(_L('You need to <a %1>log in</a> as the requested RA %2 or as admin.',OIDplus::gui()->link('oidplus:login$ra$'.$ra_email),'<b>'.htmlentities($ra_email).'</b>'), $out['title'], 401);
  243.                         }
  244.  
  245.                         $res = OIDplus::db()->query("select * from ###ra where email = ?", array($ra_email));
  246.                         if (!$res->any()) {
  247.                                 throw new OIDplusHtmlException(_L('RA "%1" does not exist','<b>'.htmlentities($ra_email).'</b>'), $out['title']);
  248.                         }
  249.  
  250.                         if (!OIDplus::config()->getValue('allow_ra_email_change') && !OIDplus::authUtils()->isAdminLoggedIn()) {
  251.                                 throw new OIDplusException(_L('This functionality has been disabled by the administrator.'), $out['title']);
  252.                         }
  253.  
  254.                         if (OIDplus::authUtils()->isAdminLoggedIn()) {
  255.                                 $ra = new OIDplusRA($ra_email);
  256.                                 if ($ra->isPasswordLess()) {
  257.                                         $out['text'] .= '<p>'._L('Attention: This user does not have a password because they log in using LDAP or Google OAuth etc.').'</p>';
  258.                                         $out['text'] .= '<p>'._L('If you change the email address, the user cannot log in anymore, because the LDAP/OAuth plugin identifies the user via email address, not OpenID.').'</p>';
  259.                                         $out['text'] .= '<p>'._L('If you want to change the email address of the user, please <a %1>define a password</a> for them, so that they can use the regular login method using their new email address.', OIDplus::gui()->link('oidplus:change_ra_password$'.$ra_email)).'</p>';
  260.                                 }
  261.  
  262.                                 $out['text'] .= '<form id="changeRaEmailForm" action="javascript:void(0);" action="javascript:void(0);" onsubmit="return OIDplusPageRaChangeEMail.changeRaEmailFormOnSubmit(true);">';
  263.                                 $out['text'] .= '<input type="hidden" id="old_email" value="'.htmlentities($ra_email).'"/><br>';
  264.                                 $out['text'] .= '<div><label class="padding_label">'._L('Old address').':</label><b>'.htmlentities($ra_email).'</b></div>';
  265.                                 $out['text'] .= '<div><label class="padding_label">'._L('New address').':</label><input type="text" id="new_email" value=""/></div>';
  266.                                 $out['text'] .= '<br><input type="submit" value="'._L('Change password').'"> '._L('(admin does not require email verification)').'</form>';
  267.                         } else {
  268.                                 $ra = new OIDplusRA($ra_email);
  269.                                 if ($ra->isPasswordLess()) {
  270.                                         $out['icon'] = 'img/error.png';
  271.                                         $out['text'] .= '<p>'._L('Attention: You are logged in without password (via LDAP or Google OAuth etc.).').'</p>';
  272.                                         $out['text'] .= '<p>'._L('Therefore, you cannot change your email address, otherwise you would lose access to your account!').'</p>';
  273.                                         $out['text'] .= '<p>'._L('If you want to change your email address, then please <a %1>setup a password</a> first, and then use the regular login method to log in using your new email address.', OIDplus::gui()->link('oidplus:change_ra_password$'.$ra_email)).'</p>';
  274.                                         return; // throw new OIDplusHtmlException($out['text'], $out['title']);
  275.                                 }
  276.  
  277.                                 $out['text'] .= '<form id="changeRaEmailForm" action="javascript:void(0);" action="javascript:void(0);" onsubmit="return OIDplusPageRaChangeEMail.changeRaEmailFormOnSubmit(false);">';
  278.                                 $out['text'] .= '<input type="hidden" id="old_email" value="'.htmlentities($ra_email).'"/><br>';
  279.                                 $out['text'] .= '<div><label class="padding_label">'._L('Old address').':</label><b>'.htmlentities($ra_email).'</b></div>';
  280.                                 $out['text'] .= '<div><label class="padding_label">'._L('New address').':</label><input type="text" id="new_email" value=""/></div>';
  281.                                 $out['text'] .= '<br><input type="submit" value="'._L('Send new activation email').'"></form>';
  282.                         }
  283.                 } else if (explode('$',$id)[0] == 'oidplus:activate_new_ra_email') {
  284.                         $handled = true;
  285.  
  286.                         $old_email = explode('$',$id)[1];
  287.                         $new_email = explode('$',$id)[2];
  288.                         $auth = explode('$',$id)[3];
  289.  
  290.                         $out['title'] = _L('Perform email address change');
  291.                         $out['icon'] = file_exists(__DIR__.'/img/main_icon.png') ? OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'img/main_icon.png' : '';
  292.  
  293.                         if (!OIDplus::config()->getValue('allow_ra_email_change') && !OIDplus::authUtils()->isAdminLoggedIn()) {
  294.                                 throw new OIDplusException(_L('This functionality has been disabled by the administrator.'), $out['title']);
  295.                         }
  296.  
  297.                         $ra = new OIDplusRA($old_email);
  298.                         if ($ra->isPasswordLess() && !OIDplus::authUtils()->isAdminLoggedIn()) {
  299.                                 throw new OIDplusException(_L('E-Mail-Address cannot be changed because this user does not have a password'), $out['title']);
  300.                         }
  301.  
  302.                         $res = OIDplus::db()->query("select * from ###ra where email = ?", array($old_email));
  303.                         if (!$res->any()) {
  304.                                 throw new OIDplusException(_L('eMail address does not exist anymore. It was probably already changed.'), $out['title']);
  305.                         } else {
  306.                                 $res = OIDplus::db()->query("select * from ###ra where email = ?", array($new_email));
  307.                                 if ($res->any()) {
  308.                                         throw new OIDplusException(_L('eMail address is already used by another RA. To merge accounts, please contact the superior RA of your objects and request an owner change of your objects.'), $out['title']);
  309.                                 } else {
  310.                                         if (!OIDplus::authUtils()->validateAuthKey(['5ef24124-f4fb-11ed-b67e-3c4a92df8582',$old_email,$new_email], $auth, OIDplus::config()->getValue('max_ra_email_change_time', -1))) {
  311.                                                 throw new OIDplusException(_L('Invalid authorization. Is the URL OK?'), $out['title']);
  312.                                         } else {
  313.                                                 $out['text'] = '<p>'._L('Old eMail-Address').': <b>'.$old_email.'</b></p>
  314.                                                 <p>'._L('New eMail-Address').': <b>'.$new_email.'</b></p>
  315.  
  316.                                                  <form id="activateNewRaEmailForm" action="javascript:void(0);" onsubmit="return OIDplusPageRaChangeEMail.activateNewRaEmailFormOnSubmit();">
  317.                                             <input type="hidden" id="old_email" value="'.htmlentities($old_email).'"/>
  318.                                             <input type="hidden" id="new_email" value="'.htmlentities($new_email).'"/>
  319.                                             <input type="hidden" id="auth" value="'.htmlentities($auth).'"/>
  320.  
  321.                                             <div><label class="padding_label">'._L('Please verify your password').':</label><input type="password" id="password" value=""/></div>
  322.                                             <br><input type="submit" value="'._L('Change email address').'">
  323.                                           </form>';
  324.                                         }
  325.                                 }
  326.                         }
  327.                 }
  328.         }
  329.  
  330.         /**
  331.          * @param array $json
  332.          * @param string|null $ra_email
  333.          * @param bool $nonjs
  334.          * @param string $req_goto
  335.          * @return bool
  336.          * @throws OIDplusException
  337.          */
  338.         public function tree(array &$json, string $ra_email=null, bool $nonjs=false, string $req_goto=''): bool {
  339.                 if (!$ra_email) return false;
  340.                 if (!OIDplus::authUtils()->isRaLoggedIn($ra_email) && !OIDplus::authUtils()->isAdminLoggedIn()) return false;
  341.  
  342.                 if (file_exists(__DIR__.'/img/main_icon16.png')) {
  343.                         $tree_icon = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'img/main_icon16.png';
  344.                 } else {
  345.                         $tree_icon = null; // default icon (folder)
  346.                 }
  347.  
  348.                 $json[] = array(
  349.                         'id' => 'oidplus:change_ra_email$'.$ra_email,
  350.                         'icon' => $tree_icon,
  351.                         'text' => _L('Change email address')
  352.                 );
  353.  
  354.                 return true;
  355.         }
  356.  
  357.         /**
  358.          * @param string $request
  359.          * @return array|false
  360.          */
  361.         public function tree_search(string $request) {
  362.                 return false;
  363.         }
  364. }
  365.