Subversion Repositories oidplus

Rev

Rev 1130 | Rev 1199 | 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
1086 daniel-mar 5
 * Copyright 2019 - 2023 Daniel Marschall, ViaThinkSoft
635 daniel-mar 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
 
1050 daniel-mar 20
namespace ViaThinkSoft\OIDplus;
635 daniel-mar 21
 
1086 daniel-mar 22
// phpcs:disable PSR1.Files.SideEffects
23
\defined('INSIDE_OIDPLUS') or die;
24
// phpcs:enable PSR1.Files.SideEffects
25
 
635 daniel-mar 26
class OIDplusPageRaInvite extends OIDplusPagePluginRa {
27
 
1116 daniel-mar 28
        /**
29
         * @param string $actionID
30
         * @param array $params
1143 daniel-mar 31
         * @return array
1116 daniel-mar 32
         * @throws OIDplusException
33
         * @throws OIDplusMailException
34
         */
35
        public function action(string $actionID, array $params): array {
635 daniel-mar 36
                if ($actionID == 'invite_ra') {
37
                        $email = $params['email'];
38
 
39
                        if (!OIDplus::mailUtils()->validMailAddress($email)) {
40
                                throw new OIDplusException(_L('Invalid email address'));
41
                        }
42
 
702 daniel-mar 43
                        OIDplus::getActiveCaptchaPlugin()->captchaVerify($params, 'captcha');
635 daniel-mar 44
 
45
                        $this->inviteSecurityCheck($email);
46
                        // TODO: should we also log who has invited?
47
                        OIDplus::logger()->log("[INFO]RA($email)!", "RA '$email' has been invited");
48
 
49
                        $timestamp = time();
801 daniel-mar 50
                        $activate_url = OIDplus::webpath(null,OIDplus::PATH_ABSOLUTE_CANONICAL) . '?goto='.urlencode('oidplus:activate_ra$'.$email.'$'.$timestamp.'$'.OIDplus::authUtils()->makeAuthKey('activate_ra;'.$email.';'.$timestamp));
635 daniel-mar 51
 
52
                        $message = $this->getInvitationText($email);
53
                        $message = str_replace('{{ACTIVATE_URL}}', $activate_url, $message);
54
 
875 daniel-mar 55
                        OIDplus::mailUtils()->sendMail($email, OIDplus::config()->getValue('system_title').' - Invitation', $message);
635 daniel-mar 56
 
57
                        return array("status" => 0);
58
 
59
                } else if ($actionID == 'activate_ra') {
60
 
61
                        _CheckParamExists($params, 'password1');
62
                        _CheckParamExists($params, 'password2');
63
                        _CheckParamExists($params, 'email');
64
                        _CheckParamExists($params, 'auth');
65
                        _CheckParamExists($params, 'timestamp');
66
 
67
                        $password1 = $params['password1'];
68
                        $password2 = $params['password2'];
69
                        $email = $params['email'];
70
                        $auth = $params['auth'];
71
                        $timestamp = $params['timestamp'];
72
 
73
                        if (!OIDplus::authUtils()->validateAuthKey('activate_ra;'.$email.';'.$timestamp, $auth)) {
74
                                throw new OIDplusException(_L('Invalid auth key'));
75
                        }
76
 
77
                        if ((OIDplus::config()->getValue('max_ra_invite_time') > 0) && (time()-$timestamp > OIDplus::config()->getValue('max_ra_invite_time'))) {
78
                                throw new OIDplusException(_L('Invitation expired!'));
79
                        }
80
 
81
                        if ($password1 !== $password2) {
82
                                throw new OIDplusException(_L('Passwords do not match'));
83
                        }
84
 
85
                        if (strlen($password1) < OIDplus::config()->getValue('ra_min_password_length')) {
86
                                $minlen = OIDplus::config()->getValue('ra_min_password_length');
87
                                throw new OIDplusException(_L('Password is too short. Need at least %1 characters',$minlen));
88
                        }
89
 
90
                        OIDplus::logger()->log("[OK]RA($email)!", "RA '$email' has been registered due to invitation");
91
 
92
                        $ra = new OIDplusRA($email);
93
                        $ra->register_ra($password1);
94
 
95
                        return array("status" => 0);
96
                } else {
1116 daniel-mar 97
                        return parent::action($actionID, $params);
635 daniel-mar 98
                }
99
        }
100
 
1116 daniel-mar 101
        /**
102
         * @param bool $html
103
         * @return void
104
         * @throws OIDplusException
105
         */
106
        public function init(bool $html=true) {
635 daniel-mar 107
                OIDplus::config()->prepareConfigKey('max_ra_invite_time', 'Max RA invite time in seconds (0 = infinite)', '0', OIDplusConfig::PROTECTION_EDITABLE, function($value) {
108
                        if (!is_numeric($value) || ($value < 0)) {
109
                                throw new OIDplusException(_L('Please enter a valid value.'));
110
                        }
111
                });
112
                OIDplus::config()->prepareConfigKey('ra_invitation_enabled', 'May RAs be invited? (0=no, 1=yes)', '1', OIDplusConfig::PROTECTION_EDITABLE, function($value) {
113
                        if (($value != 0) && ($value != 1)) {
114
                                throw new OIDplusException(_L('Please enter a valid value (0=no, 1=yes).'));
115
                        }
116
                });
117
        }
118
 
1116 daniel-mar 119
        /**
120
         * @param string $id
121
         * @param array $out
122
         * @param bool $handled
123
         * @return void
124
         * @throws OIDplusException
125
         */
126
        public function gui(string $id, array &$out, bool &$handled) {
635 daniel-mar 127
                if (explode('$',$id)[0] == 'oidplus:invite_ra') {
128
                        $handled = true;
129
 
130
                        $email = explode('$',$id)[1];
131
                        $origin = explode('$',$id)[2];
132
 
133
                        $out['title'] = _L('Invite a Registration Authority');
134
 
135
                        if (!OIDplus::config()->getValue('ra_invitation_enabled')) {
800 daniel-mar 136
                                $out['icon'] = 'img/error.png';
635 daniel-mar 137
                                $out['text'] = '<p>'._L('Invitations are disabled by the administrator.').'</p>';
138
                                return;
139
                        }
140
 
801 daniel-mar 141
                        $out['icon'] = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'img/invite_icon.png';
635 daniel-mar 142
 
143
                        try {
144
                                $this->inviteSecurityCheck($email);
145
                                $cont = $this->getInvitationText($email);
146
 
147
                                $out['text'] .= '<p>'._L('You have chosen to invite %1 as a Registration Authority. If you click "Send", the following email will be sent to %2:','<b>'.$email.'</b>',$email).'</p><p><i>'.nl2br(htmlentities($cont)).'</i></p>
148
                                  <form id="inviteForm" action="javascript:void(0);" onsubmit="return OIDplusPageRaInvite.inviteFormOnSubmit();">
149
                                    <input type="hidden" id="email" value="'.htmlentities($email).'"/>
702 daniel-mar 150
                                    <input type="hidden" id="origin" value="'.htmlentities($origin).'"/>
151
                                    '.OIDplus::getActiveCaptchaPlugin()->captchaGenerate().'
152
                                    <br>
635 daniel-mar 153
                                    <input type="submit" value="'._L('Send invitation').'">
154
                                  </form>';
155
 
1050 daniel-mar 156
                        } catch (\Exception $e) {
635 daniel-mar 157
 
800 daniel-mar 158
                                $out['icon'] = 'img/error.png';
635 daniel-mar 159
                                $out['text'] = _L('Error: %1',$e->getMessage());
160
 
161
                        }
162
                } else if (explode('$',$id)[0] == 'oidplus:activate_ra') {
163
                        $handled = true;
164
 
165
                        $email = explode('$',$id)[1];
166
                        $timestamp = explode('$',$id)[2];
167
                        $auth = explode('$',$id)[3];
168
 
169
                        $out['title'] = _L('Register as Registration Authority');
170
 
171
                        if (!OIDplus::config()->getValue('ra_invitation_enabled')) {
800 daniel-mar 172
                                $out['icon'] = 'img/error.png';
635 daniel-mar 173
                                $out['text'] = '<p>'._L('Invitations are disabled by the administrator.').'</p>';
174
                                return;
175
                        }
176
 
801 daniel-mar 177
                        $out['icon'] = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'img/activate_icon.png';
635 daniel-mar 178
 
179
                        $res = OIDplus::db()->query("select * from ###ra where email = ?", array($email));
790 daniel-mar 180
                        if ($res->any()) {
635 daniel-mar 181
                                $out['text'] = _L('This RA is already registered and does not need to be invited.');
182
                        } else {
183
                                if (!OIDplus::authUtils()->validateAuthKey('activate_ra;'.$email.';'.$timestamp, $auth)) {
800 daniel-mar 184
                                        $out['icon'] = 'img/error.png';
635 daniel-mar 185
                                        $out['text'] = _L('Invalid authorization. Is the URL OK?');
186
                                } else {
187
                                        // TODO: like in the FreeOID plugin, we could ask here at least for a name for the RA
188
                                        $out['text'] = '<p>'._L('E-Mail-Address').': <b>'.$email.'</b></p>
189
 
190
                                          <form id="activateRaForm" action="javascript:void(0);" onsubmit="return OIDplusPageRaInvite.activateRaFormOnSubmit();">
191
                                            <input type="hidden" id="email" value="'.htmlentities($email).'"/>
192
                                            <input type="hidden" id="timestamp" value="'.htmlentities($timestamp).'"/>
193
                                            <input type="hidden" id="auth" value="'.htmlentities($auth).'"/>
194
                                            <div><label class="padding_label">'._L('New password').':</label><input type="password" id="password1" value=""/></div>
195
                                            <div><label class="padding_label">'._L('Repeat').':</label><input type="password" id="password2" value=""/></div>
196
                                            <br><input type="submit" value="'._L('Register').'">
197
                                          </form>';
198
                                }
199
                        }
200
                }
201
        }
202
 
1116 daniel-mar 203
        /**
204
         * @param array $json
205
         * @param string|null $ra_email
206
         * @param bool $nonjs
207
         * @param string $req_goto
208
         * @return bool
209
         */
210
        public function tree(array &$json, string $ra_email=null, bool $nonjs=false, string $req_goto=''): bool {
635 daniel-mar 211
                //if (!$ra_email) return false;
212
                //if (!OIDplus::authUtils()->isRaLoggedIn($ra_email) && !OIDplus::authUtils()->isAdminLoggedIn()) return false;
213
 
214
                return false;
215
        }
216
 
1116 daniel-mar 217
        /**
1125 daniel-mar 218
         * @param string $email
1116 daniel-mar 219
         * @return void
220
         * @throws OIDplusException
221
         */
1125 daniel-mar 222
        private function inviteSecurityCheck(string $email) {
635 daniel-mar 223
                $res = OIDplus::db()->query("select * from ###ra where email = ?", array($email));
790 daniel-mar 224
                if ($res->any()) {
635 daniel-mar 225
                        throw new OIDplusException(_L('This RA is already registered and does not need to be invited.'));
226
                }
227
 
228
                if (!OIDplus::authUtils()->isAdminLoggedIn()) {
229
                        // Check if the RA may invite the user (i.e. the they are the parent of an OID of that person)
230
                        $ok = false;
231
                        $res = OIDplus::db()->query("select parent from ###objects where ra_email = ?", array($email));
232
                        while ($row = $res->fetch_array()) {
1120 daniel-mar 233
                                if (!$row['parent']) continue;
635 daniel-mar 234
                                $objParent = OIDplusObject::parse($row['parent']);
1116 daniel-mar 235
                                if (!$objParent) throw new OIDplusException(_L('Type of %1 unknown',$row['parent']));
635 daniel-mar 236
                                if ($objParent->userHasWriteRights()) {
237
                                        $ok = true;
238
                                }
239
                        }
240
                        if (!$ok) {
241
                                throw new OIDplusException(_L('You may not invite this RA. Maybe you need to <a %1>log in</a> again.',OIDplus::gui()->link('oidplus:login')));
242
                        }
243
                }
244
        }
245
 
1116 daniel-mar 246
        /**
1125 daniel-mar 247
         * @param string $email
1116 daniel-mar 248
         * @return string
249
         * @throws OIDplusException
250
         */
1125 daniel-mar 251
        private function getInvitationText(string $email): string {
635 daniel-mar 252
                $list_of_oids = array();
253
                $res = OIDplus::db()->query("select id from ###objects where ra_email = ?", array($email));
254
                while ($row = $res->fetch_array()) {
255
                        $list_of_oids[] = $row['id'];
256
                }
257
 
258
                $message = file_get_contents(__DIR__ . '/invite_msg.tpl');
259
 
260
                // Resolve stuff
1130 daniel-mar 261
                // Note: {{ACTIVATE_URL}} will be resolved in ajax.php
262
 
801 daniel-mar 263
                $message = str_replace('{{SYSTEM_URL}}', OIDplus::webpath(null,OIDplus::PATH_ABSOLUTE_CANONICAL), $message);
635 daniel-mar 264
                $message = str_replace('{{OID_LIST}}', implode("\n", $list_of_oids), $message);
265
                $message = str_replace('{{ADMIN_EMAIL}}', OIDplus::config()->getValue('admin_email'), $message);
266
 
1130 daniel-mar 267
                return str_replace('{{PARTY}}', OIDplus::authUtils()->isAdminLoggedIn() ? 'the system administrator' : 'a superior Registration Authority', $message);
635 daniel-mar 268
        }
269
 
1116 daniel-mar 270
        /**
271
         * @param string $request
272
         * @return array|false
273
         */
274
        public function tree_search(string $request) {
635 daniel-mar 275
                return false;
276
        }
277
}