Subversion Repositories oidplus

Rev

Rev 702 | 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 - 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 OIDplusPagePublicFreeOID extends OIDplusPagePluginPublic {
  23.  
  24.         private static function getFreeRootOid($with_ns) {
  25.                 return ($with_ns ? 'oid:' : '').OIDplus::config()->getValue('freeoid_root_oid');
  26.         }
  27.  
  28.         public static function alreadyHasFreeOid($email, $getId = false){
  29.                 $res = OIDplus::db()->query("select id from ###objects where ra_email = ? and id like ? order by ".OIDplus::db()->natOrder('id'), array($email, self::getFreeRootOid(true).'.%'));
  30.                 while ($row = $res->fetch_array()) {
  31.                         return $getId ? $row['id'] : true;
  32.                 }
  33.                 return $getId ? null : false;
  34.         }
  35.  
  36.         public function action($actionID, $params) {
  37.                 if (empty(self::getFreeRootOid(false))) throw new OIDplusException(_L('FreeOID service not available. Please ask your administrator.'));
  38.  
  39.                 if ($actionID == 'request_freeoid') {
  40.                         _CheckParamExists($params, 'email');
  41.                         $email = $params['email'];
  42.  
  43.                         if ($already_registered_oid = $this->alreadyHasFreeOid($email, true)) {
  44.                                 throw new OIDplusException(_L('This email address already has a FreeOID registered (%1)', $already_registered_oid));
  45.                         }
  46.  
  47.                         if (!OIDplus::mailUtils()->validMailAddress($email)) {
  48.                                 throw new OIDplusException(_L('Invalid email address'));
  49.                         }
  50.  
  51.                         if (OIDplus::baseConfig()->getValue('RECAPTCHA_ENABLED', false)) {
  52.                                 $secret=OIDplus::baseConfig()->getValue('RECAPTCHA_PRIVATE', '');
  53.                                 _CheckParamExists($params, 'captcha');
  54.                                 $response=$params["captcha"];
  55.                                 $verify=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret={$secret}&response={$response}");
  56.                                 $captcha_success=json_decode($verify);
  57.                                 if ($captcha_success->success==false) {
  58.                                         throw new OIDplusException(_L('CAPTCHA not successfully verified'));
  59.                                 }
  60.                         }
  61.  
  62.                         $root_oid = self::getFreeRootOid(false);
  63.                         OIDplus::logger()->log("[INFO]OID(oid:$root_oid)+RA($email)!", "Requested a free OID for email '$email' to be placed into root '$root_oid'");
  64.  
  65.                         $timestamp = time();
  66.                         $activate_url = OIDplus::webpath(null,false) . '?goto='.urlencode('oidplus:com.viathinksoft.freeoid.activate_freeoid$'.$email.'$'.$timestamp.'$'.OIDplus::authUtils()->makeAuthKey('com.viathinksoft.freeoid.activate_freeoid;'.$email.';'.$timestamp));
  67.  
  68.                         $message = file_get_contents(__DIR__ . '/request_msg.tpl');
  69.                         $message = str_replace('{{SYSTEM_URL}}', OIDplus::webpath(null,false), $message);
  70.                         $message = str_replace('{{SYSTEM_TITLE}}', OIDplus::config()->getValue('system_title'), $message);
  71.                         $message = str_replace('{{ADMIN_EMAIL}}', OIDplus::config()->getValue('admin_email'), $message);
  72.                         $message = str_replace('{{ACTIVATE_URL}}', $activate_url, $message);
  73.  
  74.                         OIDplus::mailUtils()->sendMail($email, OIDplus::config()->getValue('system_title').' - Free OID request', $message, OIDplus::config()->getValue('global_cc'));
  75.  
  76.                         return array("status" => 0);
  77.  
  78.                 } else if ($actionID == 'activate_freeoid') {
  79.                         _CheckParamExists($params, 'email');
  80.                         _CheckParamExists($params, 'auth');
  81.                         _CheckParamExists($params, 'timestamp');
  82.  
  83.                         $email = $params['email'];
  84.                         $auth = $params['auth'];
  85.                         $timestamp = $params['timestamp'];
  86.  
  87.                         if (!OIDplus::authUtils()->validateAuthKey('com.viathinksoft.freeoid.activate_freeoid;'.$email.';'.$timestamp, $auth)) {
  88.                                 throw new OIDplusException(_L('Invalid auth key'));
  89.                         }
  90.  
  91.                         if ((OIDplus::config()->getValue('max_ra_invite_time') > 0) && (time()-$timestamp > OIDplus::config()->getValue('max_ra_invite_time'))) {
  92.                                 throw new OIDplusException(_L('Invitation expired!'));
  93.                         }
  94.  
  95.                         // 1. step: Check entered data and add the RA to the database
  96.  
  97.                         $ra = new OIDplusRA($email);
  98.                         if (!$ra->existing()) {
  99.                                 _CheckParamExists($params, 'password1');
  100.                                 _CheckParamExists($params, 'password2');
  101.                                 _CheckParamExists($params, 'ra_name');
  102.                                
  103.                                 $password1 = $params['password1'];
  104.                                 $password2 = $params['password2'];
  105.                                 $ra_name = $params['ra_name'];
  106.  
  107.                                 if ($password1 !== $password2) {
  108.                                         throw new OIDplusException(_L('Passwords do not match'));
  109.                                 }
  110.  
  111.                                 if (strlen($password1) < OIDplus::config()->getValue('ra_min_password_length')) {
  112.                                         $minlen = OIDplus::config()->getValue('ra_min_password_length');
  113.                                         throw new OIDplusException(_L('Password is too short. Need at least %1 characters',$minlen));
  114.                                 }
  115.  
  116.                                 if (empty($ra_name)) {
  117.                                         throw new OIDplusException(_L('Please enter your personal name or the name of your group.'));
  118.                                 }
  119.  
  120.                                 $ra->register_ra($password1);
  121.                                 $ra->setRaName($ra_name);
  122.                         } else {
  123.                                 // RA already exists (e.g. was logged in using Google OAuth)
  124.                                 $ra_name = $ra->raName();
  125.                         }
  126.  
  127.                         // 2. step: Add the new OID to the database
  128.  
  129.                         $url = isset($params['url']) ? $params['url'] : '';
  130.                         $title = isset($params['title']) ? $params['title'] : '';
  131.  
  132.                         $root_oid = self::getFreeRootOid(false);
  133.                         $new_oid = OIDplusOid::parse('oid:'.$root_oid)->appendArcs($this->freeoid_max_id()+1)->nodeId(false);
  134.  
  135.                         OIDplus::logger()->log("[INFO]OID(oid:$root_oid)+OIDRA(oid:$root_oid)!", "Child OID '$new_oid' added automatically by '$email' (RA Name: '$ra_name')");
  136.                         OIDplus::logger()->log("[INFO]OID(oid:$new_oid)+[OK]RA($email)!",            "Free OID '$new_oid' activated (RA Name: '$ra_name')");
  137.  
  138.                         if ((!empty($url)) && (substr($url, 0, 4) != 'http')) $url = 'http://'.$url;
  139.  
  140.                         $description = ''; // '<p>'.htmlentities($ra_name).'</p>';
  141.                         if (!empty($url)) {
  142.                                 $description .= '<p>'._L('More information at %1','<a href="'.htmlentities($url).'">'.htmlentities($url).'</a>').'</p>';
  143.                         }
  144.  
  145.                         if (empty($title)) $title = $ra_name;
  146.  
  147.                         try {
  148.                                 $maxlen = OIDplus::baseConfig()->getValue('LIMITS_MAX_ID_LENGTH')-strlen('oid:');
  149.                                 if (strlen($new_oid) > $maxlen) {
  150.                                         throw new OIDplusException(_L('The resulting OID %1 is too long (max allowed length: %2)',$new_oid,$maxlen));
  151.                                 }
  152.  
  153.                                 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));
  154.                         } catch (Exception $e) {
  155.                                 $ra->delete();
  156.                                 throw $e;
  157.                         }
  158.  
  159.                         // Send delegation report email to admin
  160.  
  161.                         $message  = "OID delegation report\n";
  162.                         $message .= "\n";
  163.                         $message .= "OID: ".$new_oid."\n";;
  164.                         $message .= "\n";
  165.                         $message .= "RA Name: $ra_name\n";
  166.                         $message .= "RA eMail: $email\n";
  167.                         $message .= "URL for more information: $url\n";
  168.                         $message .= "OID Name: $title\n";
  169.                         $message .= "\n";
  170.                         $message .= "More details: ".OIDplus::webpath(null,false)."?goto=oid:$new_oid\n";
  171.  
  172.                         OIDplus::mailUtils()->sendMail($email, OIDplus::config()->getValue('system_title')." - OID $new_oid registered", $message, OIDplus::config()->getValue('global_cc'));
  173.  
  174.                         // Send delegation information to user
  175.  
  176.                         $message = file_get_contents(__DIR__ . '/allocated_msg.tpl');
  177.                         $message = str_replace('{{SYSTEM_URL}}', OIDplus::webpath(null,false), $message);
  178.                         $message = str_replace('{{SYSTEM_TITLE}}', OIDplus::config()->getValue('system_title'), $message);
  179.                         $message = str_replace('{{ADMIN_EMAIL}}', OIDplus::config()->getValue('admin_email'), $message);
  180.                         $message = str_replace('{{NEW_OID}}', $new_oid, $message);
  181.                         OIDplus::mailUtils()->sendMail($email, OIDplus::config()->getValue('system_title').' - Free OID allocated', $message, OIDplus::config()->getValue('global_cc'));
  182.  
  183.                         return array(
  184.                                 "new_oid" => $new_oid,
  185.                                 "status" => 0
  186.                         );
  187.                 } else {
  188.                         throw new OIDplusException(_L('Unknown action ID'));
  189.                 }
  190.         }
  191.  
  192.         public function init($html=true) {
  193.                 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) {
  194.                         if (($value != '') && !oid_valid_dotnotation($value,false,false,1)) {
  195.                                 throw new OIDplusException(_L('Please enter a valid OID in dot notation or nothing'));
  196.                         }
  197.                 });
  198.         }
  199.  
  200.         public function gui($id, &$out, &$handled) {
  201.                 if (empty(self::getFreeRootOid(false))) return;
  202.  
  203.                 if (explode('$',$id)[0] == 'oidplus:com.viathinksoft.freeoid') {
  204.                         $handled = true;
  205.  
  206.                         $out['title'] = _L('Register a free OID');
  207.                         $out['icon'] = file_exists(__DIR__.'/icon_big.png') ? OIDplus::webpath(__DIR__).'icon_big.png' : '';
  208.  
  209.                         // Note: We are using the highest OID instead of the rowcount, because there might be OIDs which could have been deleted in between
  210.                         $highest_id = $this->freeoid_max_id();
  211.  
  212.                         $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>';
  213.  
  214.                         try {
  215.                                 $out['text'] .= '
  216.                                   <form id="freeOIDForm" action="javascript:void(0);" onsubmit="return OIDplusPagePublicFreeOID.freeOIDFormOnSubmit();">
  217.                                     '._L('E-Mail').': <input type="text" id="email" value=""/><br><br>'.
  218.                                  (OIDplus::baseConfig()->getValue('RECAPTCHA_ENABLED', false) ?
  219.                                  '<div id="g-recaptcha" class="g-recaptcha" data-sitekey="'.OIDplus::baseConfig()->getValue('RECAPTCHA_PUBLIC', '').'"></div>'.
  220.                                  '<script> grecaptcha.render($("#g-recaptcha")[0], { "sitekey" : "'.OIDplus::baseConfig()->getValue('RECAPTCHA_PUBLIC', '').'" }); </script>' : '').
  221.                                 ' <br>
  222.                                     <input type="submit" value="'._L('Request free OID').'">
  223.                                   </form>';
  224.  
  225.                                 $obj = OIDplusOid::parse(self::getFreeRootOid(true));
  226.  
  227.                                 if (file_exists(__DIR__ . '/tos$'.OIDplus::getCurrentLang().'.html')) {
  228.                                         $tos = file_get_contents(__DIR__ . '/tos$'.OIDplus::getCurrentLang().'.html');
  229.                                 } else {
  230.                                         $tos = file_get_contents(__DIR__ . '/tos.html');
  231.                                 }
  232.  
  233.                                 list($html, $js, $css) = extractHtmlContents($tos);
  234.                                 $tos = '';
  235.                                 if (!empty($js))  $tos .= "<script>\n$js\n</script>";
  236.                                 if (!empty($css)) $tos .= "<style>\n$css\n</style>";
  237.                                 $tos .= $html;
  238.  
  239.                                 $tos = str_replace('{{ADMIN_EMAIL}}', OIDplus::config()->getValue('admin_email'), $tos);
  240.                                 if ($obj) {
  241.                                         $tos = str_replace('{{ROOT_OID}}', $obj->getDotNotation(), $tos);
  242.                                         $tos = str_replace('{{ROOT_OID_ASN1}}', $obj->getAsn1Notation(), $tos);
  243.                                         $tos = str_replace('{{ROOT_OID_IRI}}', $obj->getIriNotation(), $tos);
  244.                                 }
  245.                                 $out['text'] .= $tos;
  246.                         } catch (Exception $e) {
  247.                                 $out['text'] = _L('Error: %1',$e->getMessage());
  248.                         }
  249.                 } else if (explode('$',$id)[0] == 'oidplus:com.viathinksoft.freeoid.activate_freeoid') {
  250.                         $handled = true;
  251.  
  252.                         $email = explode('$',$id)[1];
  253.                         $timestamp = explode('$',$id)[2];
  254.                         $auth = explode('$',$id)[3];
  255.  
  256.                         $out['title'] = _L('Activate Free OID');
  257.                         $out['icon'] = file_exists(__DIR__.'/icon_big.png') ? OIDplus::webpath(__DIR__).'icon_big.png' : '';
  258.  
  259.                         if ($already_registered_oid = $this->alreadyHasFreeOid($email, true)) {
  260.                                 throw new OIDplusException(_L('This email address already has a FreeOID registered (%1)', $already_registered_oid));
  261.                         } else {
  262.                                 if (!OIDplus::authUtils()->validateAuthKey('com.viathinksoft.freeoid.activate_freeoid;'.$email.';'.$timestamp, $auth)) {
  263.                                         $out['icon'] = 'img/error_big.png';
  264.                                         $out['text'] = _L('Invalid authorization. Is the URL OK?');
  265.                                 } else {
  266.                                         $ra = new OIDplusRA($email);
  267.                                         $ra_existing = $ra->existing();
  268.  
  269.                                         $out['text'] = '<p>'._L('eMail-Address').': <b>'.$email.'</b></p>';
  270.  
  271.                                         $out['text'] .= '  <form id="activateFreeOIDForm" action="javascript:void(0);" onsubmit="return OIDplusPagePublicFreeOID.activateFreeOIDFormOnSubmit();">';
  272.                                         $out['text'] .= '    <input type="hidden" id="email" value="'.htmlentities($email).'"/>';
  273.                                         $out['text'] .= '    <input type="hidden" id="timestamp" value="'.htmlentities($timestamp).'"/>';
  274.                                         $out['text'] .= '    <input type="hidden" id="auth" value="'.htmlentities($auth).'"/>';
  275.  
  276.                                         if ($ra_existing) {
  277.                                                 $out['text'] .= '    '._L('Your personal name or the name of your group').':<br><b>'.htmlentities($ra->raName()).'</b><br><br>';
  278.                                         } else {
  279.                                                 $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
  280.                                         }
  281.                                         $out['text'] .= '    '._L('Title of your OID (usually equal to your name, optional)').':<br><input type="text" id="title" value=""/><br><br>';
  282.                                         $out['text'] .= '    '._L('URL for more information about your project(s) (optional)').':<br><input type="text" id="url" value=""/><br><br>';
  283.  
  284.                                         if (!$ra_existing) {
  285.                                                 $out['text'] .= '    <div><label class="padding_label">'._L('Password').':</label><input type="password" id="password1" value=""/></div>';
  286.                                                 $out['text'] .= '    <div><label class="padding_label">'._L('Repeat').':</label><input type="password" id="password2" value=""/></div>';
  287.                                         }
  288.                                         $out['text'] .= '    <br><input type="submit" value="'._L('Register').'">';
  289.                                         $out['text'] .= '  </form>';
  290.                                 }
  291.                         }
  292.                 }
  293.         }
  294.  
  295.         public function publicSitemap(&$out) {
  296.                 if (empty(self::getFreeRootOid(false))) return;
  297.                 $out[] = 'oidplus:com.viathinksoft.freeoid';
  298.         }
  299.  
  300.         public function tree(&$json, $ra_email=null, $nonjs=false, $req_goto='') {
  301.                 if (empty(self::getFreeRootOid(false))) return false;
  302.  
  303.                 if (file_exists(__DIR__.'/treeicon.png')) {
  304.                         $tree_icon = OIDplus::webpath(__DIR__).'treeicon.png';
  305.                 } else {
  306.                         $tree_icon = null; // default icon (folder)
  307.                 }
  308.  
  309.                 $json[] = array(
  310.                         'id' => 'oidplus:com.viathinksoft.freeoid',
  311.                         'icon' => $tree_icon,
  312.                         'text' => _L('Register a free OID')
  313.                 );
  314.  
  315.                 return true;
  316.         }
  317.  
  318.         # ---
  319.  
  320.         protected static function freeoid_max_id() {
  321.                 $res = OIDplus::db()->query("select id from ###objects where id like ? order by ".OIDplus::db()->natOrder('id'), array(self::getFreeRootOid(true).'.%'));
  322.                 $highest_id = 0;
  323.                 while ($row = $res->fetch_array()) {
  324.                         $arc = substr_count(self::getFreeRootOid(false), '.')+1;
  325.                         $highest_id = explode('.',$row['id'])[$arc];
  326.                 }
  327.                 return $highest_id;
  328.         }
  329.  
  330.         public function tree_search($request) {
  331.                 return false;
  332.         }
  333. }
  334.