Subversion Repositories oidplus

Rev

Rev 362 | Go to most recent revision | Blame | Last modification | View Log | RSS feed

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