Subversion Repositories oidplus

Rev

Rev 1283 | 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 OIDplusPagePublicFreeOID extends OIDplusPagePluginPublic {
  27.  
  28.         /**
  29.          * @param bool $with_ns
  30.          * @return string|null
  31.          * @throws OIDplusException
  32.          */
  33.         private static function getFreeRootOid(bool $with_ns)/*: ?string*/ {
  34.                 if (!in_array('ViaThinkSoft\OIDplus\OIDplusOid',OIDplus::getEnabledObjectTypes())) {
  35.                         return null;
  36.                 } else {
  37.                         $res = ($with_ns ? 'oid:' : '').OIDplus::config()->getValue('freeoid_root_oid');
  38.                         return !empty($res) ? $res : null;
  39.                 }
  40.         }
  41.  
  42.         /**
  43.          * @param string $email
  44.          * @param bool $getId
  45.          * @return string|null|bool If $getId=true, then returns ID or NULL.  If $getId=False, then returns TRUE or FALSE.
  46.          * @throws OIDplusException
  47.          */
  48.         public static function alreadyHasFreeOid(string $email, bool $getId = false) {
  49.                 $res = OIDplus::db()->query("select id from ###objects where ra_email = ? and id like ?", array($email, self::getFreeRootOid(true).'.%'));
  50.                 $res->naturalSortByField('id');
  51.                 if ($row = $res->fetch_array()) {
  52.                         return $getId ? $row['id'] : true;
  53.                 }
  54.                 return $getId ? null : false;
  55.         }
  56.  
  57.         /**
  58.          * @param array $params
  59.          * @return array
  60.          * @throws OIDplusException
  61.          * @throws OIDplusMailException
  62.          */
  63.         private function action_Request(array $params): array {
  64.                 if (empty(self::getFreeRootOid(false))) throw new OIDplusException(_L('FreeOID service not available. Please ask your administrator.'));
  65.  
  66.                 _CheckParamExists($params, 'email');
  67.                 $email = $params['email'];
  68.  
  69.                 if ($already_registered_oid = $this->alreadyHasFreeOid($email, true)) {
  70.                         throw new OIDplusHtmlException(_L('This email address already has a FreeOID registered (%1)', '<a '.OIDplus::gui()->link($already_registered_oid).'>'.htmlentities($already_registered_oid).'</a>'));
  71.                 }
  72.  
  73.                 if (!OIDplus::mailUtils()->validMailAddress($email)) {
  74.                         throw new OIDplusException(_L('Invalid email address'));
  75.                 }
  76.  
  77.                 OIDplus::getActiveCaptchaPlugin()->captchaVerify($params, 'captcha');
  78.  
  79.                 $root_oid = self::getFreeRootOid(false);
  80.                 OIDplus::logger()->log("V2:[INFO]OID(oid:%1)+RA(%2)", "Requested a free OID for email '%2' to be placed into root '%1'", $root_oid, $email);
  81.  
  82.                 $activate_url = OIDplus::webpath(null,OIDplus::PATH_ABSOLUTE_CANONICAL) . '?goto='.urlencode('oidplus:com.viathinksoft.freeoid.activate_freeoid$'.$email.'$'.OIDplus::authUtils()->makeAuthKey(['40c87e20-f4fb-11ed-86ca-3c4a92df8582',$email]));
  83.  
  84.                 $message = file_get_contents(__DIR__ . '/request_msg.tpl');
  85.                 $message = str_replace('{{SYSTEM_URL}}', OIDplus::webpath(null,OIDplus::PATH_ABSOLUTE_CANONICAL), $message);
  86.                 $message = str_replace('{{SYSTEM_TITLE}}', OIDplus::config()->getValue('system_title'), $message);
  87.                 $message = str_replace('{{ADMIN_EMAIL}}', OIDplus::config()->getValue('admin_email'), $message);
  88.                 $message = str_replace('{{ACTIVATE_URL}}', $activate_url, $message);
  89.  
  90.                 OIDplus::mailUtils()->sendMail($email, OIDplus::config()->getValue('system_title').' - Free OID request', $message);
  91.  
  92.                 return array("status" => 0);
  93.         }
  94.  
  95.         /**
  96.          * @param array $params
  97.          * @return array
  98.          * @throws OIDplusException
  99.          * @throws OIDplusMailException
  100.          */
  101.         private function action_Activate(array $params): array {
  102.                 if (empty(self::getFreeRootOid(false))) throw new OIDplusException(_L('FreeOID service not available. Please ask your administrator.'));
  103.  
  104.                 _CheckParamExists($params, 'email');
  105.                 _CheckParamExists($params, 'auth');
  106.  
  107.                 $email = $params['email'];
  108.                 $auth = $params['auth'];
  109.  
  110.                 if (!OIDplus::authUtils()->validateAuthKey(['40c87e20-f4fb-11ed-86ca-3c4a92df8582',$email], $auth, OIDplus::config()->getValue('max_ra_invite_time', -1))) {
  111.                         throw new OIDplusException(_L('Invalid or expired authentication key'));
  112.                 }
  113.  
  114.                 // 1. step: Check entered data and add the RA to the database
  115.  
  116.                 $ra = new OIDplusRA($email);
  117.                 if (!$ra->existing()) {
  118.                         _CheckParamExists($params, 'password1');
  119.                         _CheckParamExists($params, 'password2');
  120.                         _CheckParamExists($params, 'ra_name');
  121.  
  122.                         $password1 = $params['password1'];
  123.                         $password2 = $params['password2'];
  124.                         $ra_name = $params['ra_name'];
  125.  
  126.                         if ($password1 !== $password2) {
  127.                                 throw new OIDplusException(_L('Passwords do not match'));
  128.                         }
  129.  
  130.                         if (strlen($password1) < OIDplus::config()->getValue('ra_min_password_length')) {
  131.                                 $minlen = OIDplus::config()->getValue('ra_min_password_length');
  132.                                 throw new OIDplusException(_L('Password is too short. Need at least %1 characters',$minlen));
  133.                         }
  134.  
  135.                         if (empty($ra_name)) {
  136.                                 throw new OIDplusException(_L('Please enter your personal name or the name of your group.'));
  137.                         }
  138.  
  139.                         $ra->register_ra($password1);
  140.                         $ra->setRaName($ra_name);
  141.                 } else {
  142.                         // RA already exists (e.g. was logged in using Google OAuth)
  143.                         $ra_name = $ra->raName();
  144.                 }
  145.  
  146.                 // 2. step: Add the new OID to the database
  147.  
  148.                 $url = $params['url'] ?? '';
  149.                 $title = $params['title'] ?? '';
  150.  
  151.                 $root_oid = self::getFreeRootOid(false);
  152.                 $new_oid = OIDplusOid::parse('oid:'.$root_oid)->appendArcs($this->freeoid_max_id()+1)->nodeId(false);
  153.  
  154.                 OIDplus::logger()->log("V2:[INFO]OID(oid:%2)+OIDRA(oid:%2)", "Child OID '%1' added automatically by '%3' (RA Name: '%4')", $new_oid, $root_oid, $email, $ra_name);
  155.                 OIDplus::logger()->log("V2:[INFO]OID(oid:%1)+[OK]RA(%3)",    "Free OID '%1' activated (RA Name: '%4')",                    $new_oid, $root_oid, $email, $ra_name);
  156.  
  157.                 if ((!empty($url)) && (substr($url, 0, 4) != 'http')) $url = 'http://'.$url;
  158.  
  159.                 $description = ''; // '<p>'.htmlentities($ra_name).'</p>';
  160.                 if (!empty($url)) {
  161.                         $description .= '<p>'._L('More information at %1','<a href="'.htmlentities($url).'">'.htmlentities($url).'</a>').'</p>';
  162.                 }
  163.  
  164.                 if (empty($title)) $title = $ra_name;
  165.  
  166.                 try {
  167.                         $maxlen = OIDplus::baseConfig()->getValue('LIMITS_MAX_ID_LENGTH')-strlen('oid:');
  168.                         if (strlen($new_oid) > $maxlen) {
  169.                                 throw new OIDplusException(_L('The resulting OID %1 is too long (max allowed length: %2)',$new_oid,$maxlen));
  170.                         }
  171.  
  172.                         OIDplus::db()->query("insert into ###objects (id, ra_email, parent, title, description, confidential, created) values (?, ?, ?, ?, ?, ?, ".OIDplus::db()->sqlDate().")", array('oid:'.$new_oid, $email, self::getFreeRootOid(true), $title, $description, false));
  173.                         OIDplusObject::resetObjectInformationCache();
  174.                 } catch (\Exception $e) {
  175.                         $ra->delete();
  176.                         throw $e;
  177.                 }
  178.  
  179.                 // Send delegation report email to admin
  180.  
  181.                 $message  = "OID delegation report\n";
  182.                 $message .= "\n";
  183.                 $message .= "OID: ".$new_oid."\n";
  184.                 $message .= "\n";
  185.                 $message .= "RA Name: $ra_name\n";
  186.                 $message .= "RA eMail: $email\n";
  187.                 $message .= "URL for more information: $url\n";
  188.                 $message .= "OID Name: $title\n";
  189.                 $message .= "\n";
  190.                 $message .= "More details: ".OIDplus::webpath(null,OIDplus::PATH_ABSOLUTE_CANONICAL)."?goto=oid%3A$new_oid\n";
  191.  
  192.                 OIDplus::mailUtils()->sendMail($email, OIDplus::config()->getValue('system_title')." - OID $new_oid registered", $message);
  193.  
  194.                 // Send delegation information to user
  195.  
  196.                 $message = file_get_contents(__DIR__ . '/allocated_msg.tpl');
  197.                 $message = str_replace('{{SYSTEM_URL}}', OIDplus::webpath(null,OIDplus::PATH_ABSOLUTE_CANONICAL), $message);
  198.                 $message = str_replace('{{SYSTEM_TITLE}}', OIDplus::config()->getValue('system_title'), $message);
  199.                 $message = str_replace('{{ADMIN_EMAIL}}', OIDplus::config()->getValue('admin_email'), $message);
  200.                 $message = str_replace('{{NEW_OID}}', $new_oid, $message);
  201.                 OIDplus::mailUtils()->sendMail($email, OIDplus::config()->getValue('system_title').' - Free OID allocated', $message);
  202.  
  203.                 return array(
  204.                         "new_oid" => $new_oid,
  205.                         "status" => 0
  206.                 );
  207.         }
  208.  
  209.         /**
  210.          * @param string $actionID
  211.          * @param array $params
  212.          * @return array
  213.          * @throws OIDplusException
  214.          * @throws OIDplusMailException
  215.          */
  216.         public function action(string $actionID, array $params): array {
  217.                 if ($actionID == 'request_freeoid') {
  218.                         return $this->action_Request($params);
  219.                 } else if ($actionID == 'activate_freeoid') {
  220.                         return $this->action_Activate($params);
  221.                 } else {
  222.                         return parent::action($actionID, $params);
  223.                 }
  224.         }
  225.  
  226.         /**
  227.          * @param bool $html
  228.          * @return void
  229.          * @throws OIDplusException
  230.          */
  231.         public function init(bool $html=true) {
  232.                 OIDplus::config()->prepareConfigKey('freeoid_root_oid', 'Root-OID of free OID service (a service where visitors can create their own OID using email verification)', '', OIDplusConfig::PROTECTION_EDITABLE, function($value) {
  233.                         if (($value != '') && !oid_valid_dotnotation($value,false,false,1)) {
  234.                                 throw new OIDplusException(_L('Please enter a valid OID in dot notation or nothing'));
  235.                         }
  236.                 });
  237.         }
  238.  
  239.         /**
  240.          * @param string $id
  241.          * @param array $out
  242.          * @param bool $handled
  243.          * @return void
  244.          * @throws OIDplusException
  245.          */
  246.         public function gui(string $id, array &$out, bool &$handled) {
  247.                 if (empty(self::getFreeRootOid(false))) return;
  248.  
  249.                 if (explode('$',$id)[0] == 'oidplus:com.viathinksoft.freeoid') {
  250.                         $handled = true;
  251.  
  252.                         $out['title'] = _L('Register a free OID');
  253.                         $out['icon'] = file_exists(__DIR__.'/img/main_icon.png') ? OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'img/main_icon.png' : '';
  254.  
  255.                         // Note: We are using the highest OID instead of the rowcount, because there might be OIDs which could have been deleted in between
  256.                         $highest_id = $this->freeoid_max_id();
  257.  
  258.                         $out['text'] .= '<p>'._L('Currently <a %1>%2 free OIDs have been</a> registered. Please enter your email below to receive a free OID.',OIDplus::gui()->link(self::getFreeRootOid(true)),$highest_id).'</p>';
  259.  
  260.                         try {
  261.                                 $out['text'] .= '
  262.                                   <form id="freeOIDForm" action="javascript:void(0);" onsubmit="return OIDplusPagePublicFreeOID.freeOIDFormOnSubmit();">
  263.                                     '._L('E-Mail').': <input type="text" id="email" value=""/><br><br>
  264.                                     '.OIDplus::getActiveCaptchaPlugin()->captchaGenerate().'
  265.                                     <br>
  266.                                     <input type="submit" value="'._L('Request a free OID').'">
  267.                                   </form>';
  268.  
  269.                                 $obj = OIDplusOid::parse(self::getFreeRootOid(true));
  270.  
  271.                                 if (file_exists(__DIR__ . '/tos$'.OIDplus::getCurrentLang().'.html')) {
  272.                                         $tos = file_get_contents(__DIR__ . '/tos$'.OIDplus::getCurrentLang().'.html');
  273.                                 } else {
  274.                                         $tos = file_get_contents(__DIR__ . '/tos.html');
  275.                                 }
  276.  
  277.                                 list($html, $js, $css) = extractHtmlContents($tos);
  278.                                 $tos = '';
  279.                                 if (!empty($js))  $tos .= "<script>\n$js\n</script>";
  280.                                 if (!empty($css)) $tos .= "<style>\n$css\n</style>";
  281.                                 $tos .= stripHtmlComments($html);
  282.  
  283.                                 $tos = str_replace('{{ADMIN_EMAIL}}', OIDplus::config()->getValue('admin_email'), $tos);
  284.                                 if ($obj) {
  285.                                         $tos = str_replace('{{ROOT_OID}}', $obj->getDotNotation(), $tos);
  286.                                         $tos = str_replace('{{ROOT_OID_ASN1}}', $obj->getAsn1Notation(), $tos);
  287.                                         $tos = str_replace('{{ROOT_OID_IRI}}', $obj->getIriNotation(), $tos);
  288.                                 }
  289.                                 $out['text'] .= $tos;
  290.  
  291.                                 if (OIDplus::config()->getValue('freeoid_root_oid') == '1.3.6.1.4.1.37476.9000') {
  292.                                         $out['text'] .= '<p>'._L('<b>Note:</b> Since September 2022, owners of FreeOID automatically receive a free ISO-7816 compliant <b>Application Identifier</b> (AID) with the format <code>D2:76:00:01:86:F0:(FreeOID):FF:(PIX)</code> (up to 64 bits application specific PIX, depending on the length of the FreeOID number).');
  293.                                         $out['text'] .= ' - <a '.OIDplus::gui()->link('aid:D276000186F1').'>'._L('More information').'</a></p>';
  294.                                 }
  295.                         } catch (\Exception $e) {
  296.                                 $htmlmsg = $e instanceof OIDplusException ? $e->getHtmlMessage() : htmlentities($e->getMessage());
  297.                                 $out['text'] = _L('Error: %1',$htmlmsg);
  298.                         }
  299.                 } else if (explode('$',$id)[0] == 'oidplus:com.viathinksoft.freeoid.activate_freeoid') {
  300.                         $handled = true;
  301.  
  302.                         $email = explode('$',$id)[1];
  303.                         $auth = explode('$',$id)[2];
  304.  
  305.                         $out['title'] = _L('Activate Free OID');
  306.                         $out['icon'] = file_exists(__DIR__.'/img/main_icon.png') ? OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'img/main_icon.png' : '';
  307.  
  308.                         if ($already_registered_oid = $this->alreadyHasFreeOid($email, true)) {
  309.                                 throw new OIDplusHtmlException(_L('This email address already has a FreeOID registered (%1)', '<a '.OIDplus::gui()->link($already_registered_oid).'>'.htmlentities($already_registered_oid).'</a>'));
  310.                         } else {
  311.                                 if (!OIDplus::authUtils()->validateAuthKey(['40c87e20-f4fb-11ed-86ca-3c4a92df8582',$email], $auth, OIDplus::config()->getValue('max_ra_invite_time', -1))) {
  312.                                         throw new OIDplusException(_L('Invalid authorization. Is the URL OK?'), $out['title']);
  313.                                 } else {
  314.                                         $ra = new OIDplusRA($email);
  315.                                         $ra_existing = $ra->existing();
  316.  
  317.                                         $out['text'] = '<p>'._L('eMail-Address').': <b>'.$email.'</b></p>';
  318.  
  319.                                         $out['text'] .= '  <form id="activateFreeOIDForm" action="javascript:void(0);" onsubmit="return OIDplusPagePublicFreeOID.activateFreeOIDFormOnSubmit();">';
  320.                                         $out['text'] .= '    <input type="hidden" id="email" value="'.htmlentities($email).'"/>';
  321.                                         $out['text'] .= '    <input type="hidden" id="auth" value="'.htmlentities($auth).'"/>';
  322.  
  323.                                         if ($ra_existing) {
  324.                                                 $out['text'] .= '    '._L('Your personal name or the name of your group').':<br><b>'.htmlentities($ra->raName()).'</b><br><br>';
  325.                                         } else {
  326.                                                 $out['text'] .= '    '._L('Your personal name or the name of your group').':<br><input type="text" id="ra_name" value=""/><br><br>'; // TODO: disable autocomplete
  327.                                         }
  328.                                         $out['text'] .= '    '._L('Title of your OID (usually equal to your name, optional)').':<br><input type="text" id="title" value=""/><br><br>';
  329.                                         $out['text'] .= '    '._L('URL for more information about your project(s) (optional)').':<br><input type="text" id="url" value=""/><br><br>';
  330.  
  331.                                         if (!$ra_existing) {
  332.                                                 $out['text'] .= '    <div><label class="padding_label">'._L('Password').':</label><input type="password" id="password1" value=""/></div>';
  333.                                                 $out['text'] .= '    <div><label class="padding_label">'._L('Repeat').':</label><input type="password" id="password2" value=""/></div>';
  334.                                         }
  335.                                         $out['text'] .= '    <br><input type="submit" value="'._L('Register').'">';
  336.                                         $out['text'] .= '  </form>';
  337.                                 }
  338.                         }
  339.                 }
  340.         }
  341.  
  342.         /**
  343.          * @param array $out
  344.          * @return void
  345.          * @throws OIDplusException
  346.          */
  347.         public function publicSitemap(array &$out) {
  348.                 if (empty(self::getFreeRootOid(false))) return;
  349.                 $out[] = 'oidplus:com.viathinksoft.freeoid';
  350.         }
  351.  
  352.         /**
  353.          * @param array $json
  354.          * @param string|null $ra_email
  355.          * @param bool $nonjs
  356.          * @param string $req_goto
  357.          * @return bool
  358.          * @throws OIDplusException
  359.          */
  360.         public function tree(array &$json, string $ra_email=null, bool $nonjs=false, string $req_goto=''): bool {
  361.                 if (empty(self::getFreeRootOid(false))) return false;
  362.  
  363.                 if (file_exists(__DIR__.'/img/main_icon16.png')) {
  364.                         $tree_icon = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'img/main_icon16.png';
  365.                 } else {
  366.                         $tree_icon = null; // default icon (folder)
  367.                 }
  368.  
  369.                 $json[] = array(
  370.                         'id' => 'oidplus:com.viathinksoft.freeoid',
  371.                         'icon' => $tree_icon,
  372.                         'text' => _L('Register a free OID')
  373.                 );
  374.  
  375.                 return true;
  376.         }
  377.  
  378.         # ---
  379.  
  380.         /**
  381.          * @return int
  382.          * @throws OIDplusException
  383.          */
  384.         protected static function freeoid_max_id(): int {
  385.                 $res = OIDplus::db()->query("select id from ###objects where id like ?", array(self::getFreeRootOid(true).'.%'));
  386.                 $res->naturalSortByField('id');
  387.                 $highest_id = 0;
  388.                 while ($row = $res->fetch_array()) {
  389.                         $arc = substr_count(self::getFreeRootOid(false), '.')+1;
  390.                         $highest_id = explode('.',$row['id'])[$arc];
  391.                 }
  392.                 return (int)$highest_id;
  393.         }
  394.  
  395.         /**
  396.          * @param string $request
  397.          * @return array|false
  398.          */
  399.         public function tree_search(string $request) {
  400.                 return false;
  401.         }
  402. }
  403.