Indefero

Indefero Git Source Tree


Root/src/IDF/Form/UserAccount.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
<?php
/* -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
# ***** BEGIN LICENSE BLOCK *****
# This file is part of InDefero, an open source project management application.
# Copyright (C) 2008 Céondo Ltd and contributors.
#
# InDefero is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# InDefero is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
#
# ***** END LICENSE BLOCK ***** */
 
Pluf::loadFunction('Pluf_HTTP_URL_urlForView');
 
/**
 * Allow a user to update its details.
 */
class IDF_Form_UserAccount  extends Pluf_Form
{
    public $user = null;
 
    public function initFields($extra=array())
    {
        $this->user = $extra['user'];
        $user_data = IDF_UserData::factory($this->user);
 
        $this->fields['first_name'] = new Pluf_Form_Field_Varchar(
                                      array('required' => false,
                                            'label' => __('First name'),
                                            'initial' => $this->user->first_name,
                                            'widget_attrs' => array(
                                                       'maxlength' => 50,
                                                       'size' => 15,
                                                                    ),
                                            ));
        $this->fields['last_name'] = new Pluf_Form_Field_Varchar(
                                      array('required' => true,
                                            'label' => __('Last name'),
                                            'initial' => $this->user->last_name,
                                            'widget_attrs' => array(
                                                       'maxlength' => 50,
                                                       'size' => 20,
                                                                    ),
                                            ));
 
        $this->fields['email'] = new Pluf_Form_Field_Email(
                                      array('required' => true,
                                            'label' => __('Your mail'),
                                            'initial' => $this->user->email,
                                            'help_text' => __('If you change your email address, an email will be sent to the new address to confirm it.'),
                                            ));
 
        $this->fields['language'] = new Pluf_Form_Field_Varchar(
                                      array('required' => true,
                                            'label' => __('Language'),
                                            'initial' => $this->user->language,
                                            'widget' => 'Pluf_Form_Widget_SelectInput',
                                            'widget_attrs' => array(
                                                       'choices' =>
                                                       Pluf_L10n::getInstalledLanguages()
                                                                    ),
                                            ));
 
        $this->fields['password'] = new Pluf_Form_Field_Varchar(
                                      array('required' => false,
                                            'label' => __('Your password'),
                                            'initial' => '',
                                            'widget' => 'Pluf_Form_Widget_PasswordInput',
                                            'help_text' => Pluf_Template::markSafe(__('Leave blank if you do not want to change your password.').'<br />'.__('Your password must be hard for other people to find it, but easy for you to remember.')),
                                            'widget_attrs' => array(
                                                       'autocomplete' => 'off',
                                                       'maxlength' => 50,
                                                       'size' => 15,
                                                                    ),
                                            ));
        $this->fields['password2'] = new Pluf_Form_Field_Varchar(
                                      array('required' => false,
                                            'label' => __('Confirm your password'),
                                            'initial' => '',
                                            'widget' => 'Pluf_Form_Widget_PasswordInput',
                                            'widget_attrs' => array(
                                                       'autocomplete' => 'off',
                                                       'maxlength' => 50,
                                                       'size' => 15,
                                                                    ),
                                            ));
 
        $this->fields['description'] = new Pluf_Form_Field_Varchar(
                                      array('required' => false,
                                            'label' => __('Description'),
                                            'initial' => $user_data->description,
                                            'widget_attrs' => array('rows' => 3,
                                                                    'cols' => 40),
                                            'widget' => 'Pluf_Form_Widget_TextareaInput',
                                            ));
 
        $this->fields['twitter'] = new Pluf_Form_Field_Varchar(
                                      array('required' => false,
                                            'label' => __('Twitter username'),
                                            'initial' => $user_data->twitter,
                                            'widget_attrs' => array(
                                                       'maxlength' => 50,
                                                       'size' => 15,
                                                                    ),
                                            ));
 
        $this->fields['public_email'] = new Pluf_Form_Field_Email(
                                      array('required' => false,
                                            'label' => __('Public email address'),
                                            'initial' => $user_data->public_email,
                                            'widget_attrs' => array(
                                                       'maxlength' => 50,
                                                       'size' => 15,
                                                                    ),
                                            ));
 
        $this->fields['website'] = new Pluf_Form_Field_Url(
                                      array('required' => false,
                                            'label' => __('Website URL'),
                                            'initial' => $user_data->website,
                                            'widget_attrs' => array(
                                                       'maxlength' => 50,
                                                       'size' => 15,
                                                                    ),
                                            ));
 
        $this->fields['custom_avatar'] = new Pluf_Form_Field_File(
                                      array('required' => false,
                                            'label' => __('Upload custom avatar'),
                                            'initial' => '',
                                            'max_size' => Pluf::f('max_upload_size', 2097152),
                                            'move_function_params' => array('upload_path' => Pluf::f('upload_path').'/avatars',
                                                                            'upload_path_create' => true,
                                                                            'upload_overwrite' => true,
                                                                            'file_name' => 'user_'.$this->user->id.'_%s'),
                                            'help_text' => __('An image file with a width and height not larger than 60 pixels (bigger images are scaled down).'),
                                            ));
 
        $this->fields['remove_custom_avatar'] = new Pluf_Form_Field_Boolean(
                                      array('required' => false,
                                            'label' => __('Remove custom avatar'),
                                            'initial' => false,
                                            'widget' => 'Pluf_Form_Widget_CheckboxInput',
                                            'widget_attrs' => array(),
                                            'help_text' => __('Tick this to delete the custom avatar.'),
                                            ));
 
        $this->fields['public_key'] = new Pluf_Form_Field_Varchar(
                                      array('required' => false,
                                            'label' => __('Add a public key'),
                                            'initial' => '',
                                            'widget_attrs' => array('rows' => 3,
                                                                    'cols' => 40),
                                            'widget' => 'Pluf_Form_Widget_TextareaInput',
                                            'help_text' => __('Paste a SSH or monotone public key. Be careful to not provide your private key here!')
                                            ));
 
        $this->fields['secondary_mail'] = new Pluf_Form_Field_Email(
                                      array('required' => false,
                                            'label' => __('Add a secondary mail address'),
                                            'initial' => '',
                                            'help_text' => __('You will get a mail to confirm that you own the address you specify.'),
                                            ));
    }
 
    private function send_validation_mail($new_email, $secondary_mail=false)
    {
        if ($secondary_mail) {
            $type = "secondary";
        } else {
            $type = "primary";
        }
        $cr = new Pluf_Crypt(md5(Pluf::f('secret_key')));
        $encrypted = trim($cr->encrypt($new_email.':'.$this->user->id.':'.time().':'.$type), '~');
        $key = substr(md5(Pluf::f('secret_key').$encrypted), 0, 2).$encrypted;
        $url = Pluf::f('url_base').Pluf_HTTP_URL_urlForView('IDF_Views_User::changeEmailDo', array($key), array(), false);
        $urlik = Pluf::f('url_base').Pluf_HTTP_URL_urlForView('IDF_Views_User::changeEmailInputKey', array(), array(), false);
        $context = new Pluf_Template_Context(
             array('key' => Pluf_Template::markSafe($key),
                   'url' => Pluf_Template::markSafe($url),
                   'urlik' => Pluf_Template::markSafe($urlik),
                   'email' => $new_email,
                   'user'=> $this->user,
                   )
        );
        $tmpl = new Pluf_Template('idf/user/changeemail-email.txt');
        $text_email = $tmpl->render($context);
        $email = new Pluf_Mail(Pluf::f('from_email'), $new_email,
                               __('Confirm your new email address.'));
        $email->addTextMessage($text_email);
        $email->sendMail();
        $this->user->setMessage(sprintf(__('A validation email has been sent to "%s" to validate the email address change.'), Pluf_esc($new_email)));
    }
 
    /**
     * Save the model in the database.
     *
     * @param bool Commit in the database or not. If not, the object
     *             is returned but not saved in the database.
     * @return Object Model with data set from the form.
     */
    function save($commit=true)
    {
        if (!$this->isValid()) {
            throw new Exception(__('Cannot save the model from an invalid form.'));
        }
        unset($this->cleaned_data['password2']);
        $update_pass = false;
        if (strlen($this->cleaned_data['password']) == 0) {
            unset($this->cleaned_data['password']);
        } else {
            $update_pass = true;
        }
        $old_email = $this->user->email;
        $new_email = $this->cleaned_data['email'];
        unset($this->cleaned_data['email']);
        if ($old_email != $new_email) {
            $this->send_validation_mail($new_email);
        }
        $this->user->setFromFormData($this->cleaned_data);
        // Add key as needed.
        if ('' !== $this->cleaned_data['public_key']) {
            $key = new IDF_Key();
            $key->user = $this->user;
            $key->content = $this->cleaned_data['public_key'];
            if ($commit) {
                $key->create();
            }
        }
        if ('' !== $this->cleaned_data['secondary_mail']) {
            $this->send_validation_mail($this->cleaned_data['secondary_mail'], true);
        }
 
        if ($commit) {
            $this->user->update();
 
            // FIXME: go the extra mile and check the input lengths for
            // all fields here!
            // FIXME: this is all doubled in admin/UserUpdate!
 
            $user_data = IDF_UserData::factory($this->user);
 
            // Add or remove avatar - we need to do this here because every
            // single setter directly leads to a save in the database
            if ($user_data->avatar != '' &&
                    ($this->cleaned_data['remove_custom_avatar'] == 1 ||
                     $this->cleaned_data['custom_avatar'] != '')) {
                $avatar_path = Pluf::f('upload_path').'/avatars/'.basename($user_data->avatar);
                if (basename($avatar_path) != '' && is_file($avatar_path)) {
                    unlink($avatar_path);
                }
                $user_data->avatar = '';
            }
 
            if ($this->cleaned_data['custom_avatar'] != '') {
                $user_data->avatar = $this->cleaned_data['custom_avatar'];
            }
 
            $user_data->description  = $this->cleaned_data['description'];
            $user_data->twitter      = $this->cleaned_data['twitter'];
            $user_data->public_email = $this->cleaned_data['public_email'];
            $user_data->website      = $this->cleaned_data['website'];
 
            if ($update_pass) {
                /**
                 * [signal]
                 *
                 * Pluf_User::passwordUpdated
                 *
                 * [sender]
                 *
                 * IDF_Form_UserAccount
                 *
                 * [description]
                 *
                 * This signal is sent when the user updated his
                 * password from his account page.
                 *
                 * [parameters]
                 *
                 * array('user' => $user)
                 *
                 */
                $params = array('user' => $this->user);
                Pluf_Signal::send('Pluf_User::passwordUpdated',
                                  'IDF_Form_UserAccount', $params);
            }
        }
        return $this->user;
    }
 
    /**
     * Check arbitrary public keys.
     *
     * It will throw a Pluf_Form_Invalid exception if it cannot
     * validate the key.
     *
     * @param $key string The key
     * @param $user int The user id of the user of the key (0)
     * @return string The clean key
     */
    public static function checkPublicKey($key, $user=0)
    {
        $key = trim($key);
        if (strlen($key) == 0) {
            return '';
        }
 
        if (preg_match('#^ssh\-[a-z]{3}\s\S+(\s\S+)?$#', $key)) {
            $key = str_replace(array("\n", "\r"), '', $key);
 
            if (Pluf::f('idf_strong_key_check', false)) {
 
                $tmpfile = Pluf::f('tmp_folder', '/tmp').'/'.$user.'-key';
                file_put_contents($tmpfile, $key, LOCK_EX);
                $cmd = Pluf::f('idf_exec_cmd_prefix', '').
                    'ssh-keygen -l -f '.escapeshellarg($tmpfile).' > /dev/null 2>&1';
                exec($cmd, $out, $return);
                unlink($tmpfile);
 
                if ($return != 0) {
                    throw new Pluf_Form_Invalid(
                        __('Please check the key as it does not appear '.
                           'to be a valid SSH public key.')
                    );
                }
            }
        }
        else if (preg_match('#^\[pubkey [^\]]+\]\s*\S+\s*\[end\]$#', $key)) {
            if (Pluf::f('idf_strong_key_check', false)) {
 
                // if monotone can read it, it should be valid
                $mtn_opts = implode(' ', Pluf::f('mtn_opts', array()));
                $cmd = Pluf::f('idf_exec_cmd_prefix', '').
                    sprintf('%s %s -d :memory: read >/tmp/php-out 2>&1',
                            Pluf::f('mtn_path', 'mtn'), $mtn_opts);
                $fp = popen($cmd, 'w');
                fwrite($fp, $key);
                $return = pclose($fp);
 
                if ($return != 0) {
                       throw new Pluf_Form_Invalid(
                        __('Please check the key as it does not appear '.
                           'to be a valid monotone public key.')
                    );
                }
            }
        }
        else {
            throw new Pluf_Form_Invalid(
                __('Public key looks neither like a SSH '.
                   'nor monotone public key.'));
        }
 
        // If $user, then check if not the same key stored
        if ($user) {
            $ruser = Pluf::factory('Pluf_User', $user);
            if ($ruser->id > 0) {
                $sql = new Pluf_SQL('content=%s', array($key));
                $keys = Pluf::factory('IDF_Key')->getList(array('filter' => $sql->gen()));
                if (count($keys) > 0) {
                    throw new Pluf_Form_Invalid(
                        __('You already have uploaded this key.')
                    );
                }
            }
        }
        return $key;
    }
 
 
    function clean_custom_avatar()
    {
        // Just png, jpeg/jpg or gif
        if (!preg_match('/\.(png|jpg|jpeg|gif)$/i', $this->cleaned_data['custom_avatar']) &&
            $this->cleaned_data['custom_avatar'] != '') {
            @unlink(Pluf::f('upload_path').'/avatars/'.$this->cleaned_data['custom_avatar']);
            throw new Pluf_Form_Invalid(__('For security reason, you cannot upload a file with this extension.'));
        }
        return $this->cleaned_data['custom_avatar'];
    }
 
 
    function clean_last_name()
    {
        $last_name = trim($this->cleaned_data['last_name']);
        if ($last_name == mb_strtoupper($last_name)) {
            return mb_convert_case(mb_strtolower($last_name),
                                   MB_CASE_TITLE, 'UTF-8');
        }
        return $last_name;
    }
 
    function clean_first_name()
    {
        $first_name = trim($this->cleaned_data['first_name']);
        if ($first_name == mb_strtoupper($first_name)) {
            return mb_convert_case(mb_strtolower($first_name),
                                   MB_CASE_TITLE, 'UTF-8');
        }
        return $first_name;
    }
 
    function clean_email()
    {
        $this->cleaned_data['email'] = mb_strtolower(trim($this->cleaned_data['email']));
        $user = Pluf::factory('IDF_EmailAddress')->get_user_for_email_address($this->cleaned_data['email']);
        if ($user != null and $user->id != $this->user->id) {
            throw new Pluf_Form_Invalid(sprintf(__('The email "%s" is already used.'), $this->cleaned_data['email']));
        }
        return $this->cleaned_data['email'];
    }
 
    function clean_secondary_mail()
    {
        $this->cleaned_data['secondary_mail'] = mb_strtolower(trim($this->cleaned_data['secondary_mail']));
        if (Pluf::factory('IDF_EmailAddress')->get_user_for_email_address($this->cleaned_data['secondary_mail']) != null) {
            throw new Pluf_Form_Invalid(sprintf(__('The email "%s" is already used.'), $this->cleaned_data['secondary_mail']));
        }
        return $this->cleaned_data['secondary_mail'];
    }
 
    function clean_public_key()
    {
        $this->cleaned_data['public_key'] =
                self::checkPublicKey($this->cleaned_data['public_key'],
                                     $this->user->id);
        return $this->cleaned_data['public_key'];
    }
 
    /**
     * Check to see if the 2 passwords are the same
     */
    public function clean()
    {
        if (!isset($this->errors['password'])
            && !isset($this->errors['password2'])) {
            $password1 = $this->cleaned_data['password'];
            $password2 = $this->cleaned_data['password2'];
            if ($password1 != $password2) {
                throw new Pluf_Form_Invalid(__('The passwords do not match. Please give them again.'));
            }
        }
 
        return $this->cleaned_data;
    }
 
 
}

Archive Download this file

Page rendered in 0.12123s using 11 queries.