Subversion Repositories oidplus

Rev

Rev 279 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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