Subversion Repositories oidplus

Rev

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

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