Passed
Push — 1.11.x ( bce6cd...c146d9 )
by Angel Fernando Quiroz
12:25
created

plugin/vchamilo/views/editinstance_form.php (1 issue)

1
<?php
2
/* For licensing terms, see /license.txt */
3
4
/**
5
 * Class ChamiloForm.
6
 */
7
abstract class ChamiloForm
8
{
9
    public $_definition_finalized;
10
    protected $_form;
11
    protected $_mode;
12
    protected $_cancelurl;
13
    protected $_customdata;
14
15
    /**
16
     * ChamiloForm constructor.
17
     *
18
     * @param $mode
19
     * @param $returnurl
20
     * @param $cancelurl
21
     * @param $customdata
22
     */
23
    public function __construct($mode, $returnurl, $cancelurl, $customdata = [])
24
    {
25
        global $text_dir;
26
        $this->_mode = $mode;
27
        $this->_cancelurl = $cancelurl;
28
        $this->_customdata = $customdata;
29
30
        $attributes = ['style' => 'width: 60%; float: '.($text_dir == 'rtl' ? 'right;' : 'left;')];
31
        $this->_form = new FormValidator(
32
            $mode.'_instance',
33
            'post',
34
            $returnurl,
35
            '',
36
            $attributes
37
        );
38
    }
39
40
    abstract public function definition();
41
42
    abstract public function validation($data, $files = null);
43
44
    public function validate()
45
    {
46
        return $this->_form->validate();
47
    }
48
49
    public function display()
50
    {
51
        return $this->_form->display();
52
    }
53
54
    public function definition_after_data()
55
    {
56
    }
57
58
    public function return_form()
59
    {
60
        return $this->_form->toHtml();
61
    }
62
63
    public function is_in_add_mode()
64
    {
65
        return $this->_mode == 'add';
66
    }
67
68
    /**
69
     * Return submitted data if properly submitted or returns NULL if validation fails or
70
     * if there is no submitted data.
71
     *
72
     * @param bool $slashed true means return data with addslashes applied
73
     *
74
     * @return object submitted data; NULL if not valid or not submitted
75
     */
76
    public function get_data($slashed = true)
77
    {
78
        $cform = &$this->_form;
79
80
        if ($this->is_submitted() and $this->is_validated()) {
81
            $data = $cform->exportValues(null, $slashed);
82
            unset($data['sesskey']); // we do not need to return sesskey
83
            if (empty($data)) {
84
                return null;
85
            } else {
86
                return (object) $data;
87
            }
88
        } else {
89
            return null;
90
        }
91
    }
92
93
    /**
94
     * Return submitted data without validation or NULL if there is no submitted data.
95
     *
96
     * @param bool $slashed true means return data with addslashes applied
97
     *
98
     * @return object submitted data; NULL if not submitted
99
     */
100
    public function get_submitted_data($slashed = true)
101
    {
102
        $cform = &$this->_form;
103
104
        if ($this->is_submitted()) {
105
            $data = $cform->exportValues(null, $slashed);
106
            unset($data['sesskey']); // we do not need to return sesskey
107
            if (empty($data)) {
108
                return null;
109
            } else {
110
                return (object) $data;
111
            }
112
        } else {
113
            return null;
114
        }
115
    }
116
117
    /**
118
     * Check that form was submitted. Does not check validity of submitted data.
119
     *
120
     * @return bool true if form properly submitted
121
     */
122
    public function is_submitted()
123
    {
124
        return $this->_form->isSubmitted();
125
    }
126
127
    /**
128
     * Return true if a cancel button has been pressed resulting in the form being submitted.
129
     *
130
     * @return bool true if a cancel button has been pressed
131
     */
132
    public function is_cancelled()
133
    {
134
        $cform = &$this->_form;
135
        if ($cform->isSubmitted()) {
136
            foreach ($cform->_cancelButtons as $cancelbutton) {
137
                if (optional_param($cancelbutton, 0, PARAM_RAW)) {
138
                    return true;
139
                }
140
            }
141
        }
142
143
        return false;
144
    }
145
146
    /**
147
     * Check that form data is valid.
148
     * You should almost always use this, rather than {@see validate_defined_fields}.
149
     *
150
     * @return bool true if form data valid
151
     */
152
    public function is_validated()
153
    {
154
        //finalize the form definition before any processing
155
        if (!$this->_definition_finalized) {
156
            $this->_definition_finalized = true;
157
            $this->definition_after_data();
158
        }
159
160
        return $this->validate_defined_fields();
161
    }
162
163
    /**
164
     * Validate the form.
165
     *
166
     * You almost always want to call {@see is_validated} instead of this
167
     * because it calls {@see definition_after_data} first, before validating the form,
168
     * which is what you want in 99% of cases.
169
     *
170
     * This is provided as a separate function for those special cases where
171
     * you want the form validated before definition_after_data is called
172
     * for example, to selectively add new elements depending on a no_submit_button press,
173
     * but only when the form is valid when the no_submit_button is pressed,
174
     *
175
     * @param bool $validateonnosubmit optional, defaults to false.  The default behaviour
176
     *                                 is NOT to validate the form when a no submit button has been pressed.
177
     *                                 pass true here to override this behaviour
178
     *
179
     * @return bool true if form data valid
180
     */
181
    public function validate_defined_fields($validateonnosubmit = false)
182
    {
183
        static $validated = null; // one validation is enough
184
        $cform = &$this->_form;
185
186
        if ($this->no_submit_button_pressed() && empty($validateonnosubmit)) {
187
            return false;
188
        } elseif ($validated === null) {
189
            $internal_val = $cform->validate();
190
191
            $files = [];
192
            $file_val = $this->_validate_files($files);
193
            if ($file_val !== true) {
194
                if (!empty($file_val)) {
195
                    foreach ($file_val as $element => $msg) {
196
                        $cform->setElementError($element, $msg);
197
                    }
198
                }
199
                $file_val = false;
200
            }
201
202
            $data = $cform->exportValues(null, true);
203
            $chamilo_val = $this->validation($data, $files);
204
            if ((is_array($chamilo_val) && count($chamilo_val) !== 0)) {
205
                // non-empty array means errors
206
                foreach ($chamilo_val as $element => $msg) {
207
                    $cform->setElementError($element, $msg);
208
                }
209
                $chamilo_val = false;
210
            } else {
211
                // anything else means validation ok
212
                $chamilo_val = true;
213
            }
214
215
            $validated = ($internal_val && $chamilo_val && $file_val);
216
        }
217
218
        return $validated;
219
    }
220
221
    public function no_submit_button_pressed()
222
    {
223
        static $nosubmit = null; // one check is enough
224
225
        if (!is_null($nosubmit)) {
226
            return $nosubmit;
227
        }
228
229
        $cform = &$this->_form;
230
        $nosubmit = false;
231
        if (!$this->is_submitted()) {
232
            return false;
233
        }
234
235
        /*
236
        foreach ($cform->_noSubmitButtons as $nosubmitbutton){
237
            if (optional_param($nosubmitbutton, 0, PARAM_RAW)){
238
                $nosubmit = true;
239
                break;
240
            }
241
        }
242
        return $nosubmit;
243
        */
244
        return false;
245
    }
246
247
    /**
248
     * Load in existing data as form defaults. Usually new entry defaults are stored directly in
249
     * form definition (new entry form); this function is used to load in data where values
250
     * already exist and data is being edited (edit entry form).
251
     *
252
     * @param mixed $default_values object or array of default values
253
     * @param bool  $slashed        true if magic quotes applied to data values
254
     */
255
    public function set_data($default_values, $slashed = false)
256
    {
257
        if (is_object($default_values)) {
258
            $default_values = (array) $default_values;
259
        }
260
        $filter = $slashed ? 'stripslashes' : null;
261
        $this->_form->setDefaults($default_values, $filter);
262
    }
263
264
    /**
265
     * Internal method. Validates all uploaded files.
266
     */
267
    public function _validate_files(&$files)
268
    {
269
        $files = [];
270
271
        if (empty($_FILES)) {
272
            // we do not need to do any checks because no files were submitted
273
            // note: server side rules do not work for files - use custom verification in validate() instead
274
            return true;
275
        }
276
277
        $errors = [];
278
        $mform = &$this->_form;
279
280
        // check the files
281
        $status = $this->_upload_manager->preprocess_files();
282
283
        // now check that we really want each file
284
        foreach ($_FILES as $elname => $file) {
285
            if ($mform->elementExists($elname) and $mform->getElementType($elname) == 'file') {
286
                $required = $mform->isElementRequired($elname);
287
                if (!empty($this->_upload_manager->files[$elname]['uploadlog']) &&
288
                    empty($this->_upload_manager->files[$elname]['clear'])
289
                ) {
290
                    if (!$required and $file['error'] == UPLOAD_ERR_NO_FILE) {
291
                        // file not uploaded and not required - ignore it
292
                        continue;
293
                    }
294
                    $errors[$elname] = $this->_upload_manager->files[$elname]['uploadlog'];
295
                } elseif (!empty($this->_upload_manager->files[$elname]['clear'])) {
296
                    $files[$elname] = $this->_upload_manager->files[$elname]['tmp_name'];
297
                }
298
            } else {
299
                error('Incorrect upload attempt!');
300
            }
301
        }
302
303
        // return errors if found
304
        if ($status && 0 == count($errors)) {
305
            return true;
306
        } else {
307
            $files = [];
308
309
            return $errors;
310
        }
311
    }
312
}
313
314
/**
315
 * Class InstanceForm.
316
 */
317
class InstanceForm extends ChamiloForm
318
{
319
    /** @var Plugin */
320
    public $_plugin;
321
    public $instance;
322
323
    /**
324
     * InstanceForm constructor.
325
     *
326
     * @param $plugin
327
     * @param string $mode
328
     */
329
    public function __construct($plugin, $mode = 'add', $instance = [])
330
    {
331
        global $_configuration;
332
333
        $this->_plugin = $plugin;
334
        $returnUrl = $_configuration['root_web'].'plugin/vchamilo/views/editinstance.php';
335
        if ($mode == 'update') {
336
            $returnUrl = $_configuration['root_web'].'plugin/vchamilo/views/editinstance.php?vid='.intval($_GET['vid']);
337
        }
338
339
        $cancelurl = $_configuration['root_web'].'plugin/vchamilo/views/manage.php';
340
        parent::__construct($mode, $returnUrl, $cancelurl);
341
        $this->instance = $instance;
342
        $this->definition();
343
    }
344
345
    public function definition()
346
    {
347
        global $_configuration;
348
349
        $form = $this->_form;
350
        $plugin = $this->_plugin;
351
352
        $form->addElement('hidden', 'vid');
353
        $form->addElement('hidden', 'what', $this->_mode.'instance');
354
        $form->addElement('hidden', 'registeronly');
355
356
        $form->addHeader($plugin->get_lang('hostdefinition'));
357
        $form->addText(
358
            'sitename',
359
            [
360
                $plugin->get_lang('sitename'),
361
                $plugin->get_lang('SiteNameExample'),
362
            ]
363
        );
364
        $form->applyFilter('sitename', 'trim');
365
        $form->addText(
366
            'institution',
367
            [
368
                $plugin->get_lang('institution'),
369
                $plugin->get_lang('InstitutionExample'),
370
            ]
371
        );
372
        $form->applyFilter('institution', 'trim');
373
374
        // Host's name.
375
        $elementWeb = $form->addElement(
376
            'text',
377
            'root_web',
378
            [$this->_plugin->get_lang('rootweb'), $plugin->get_lang('RootWebExample')]
379
        );
380
        $form->applyFilter('root_web', 'trim');
381
382
        $form->addElement(
383
            'text',
384
            'url_append',
385
            ['url_append', $plugin->get_lang('UrlAppendExample')]
386
        );
387
388
        if ($this->_mode == 'update') {
389
            $encryptList = Virtual::getEncryptList();
390
            $encryptMethod = $form->addElement(
391
                'select',
392
                'password_encryption',
393
                get_lang('EncryptMethodUserPass'),
394
                $encryptList
395
            );
396
            $encryptMethod->freeze();
397
            $elementWeb->freeze();
398
        }
399
400
        /*
401
         * Database fieldset.
402
         */
403
        $form->addElement('header', $plugin->get_lang('dbgroup'));
404
405
        // Database host.
406
        $form->addElement(
407
            'text',
408
            'db_host',
409
            $this->_plugin->get_lang('dbhost'),
410
            ['id' => 'id_vdbhost']
411
        );
412
        $form->applyFilter('db_host', 'trim');
413
414
        // Database login.
415
        $form->addElement(
416
            'text',
417
            'db_user',
418
            $this->_plugin->get_lang('dbuser'),
419
            ['id' => 'id_vdbuser']
420
        );
421
        $form->applyFilter('db_user', 'trim');
422
423
        // Database password.
424
        $form->addElement(
425
            'password',
426
            'db_password',
427
            $this->_plugin->get_lang('dbpassword'),
428
            ['id' => 'id_vdbpassword']
429
        );
430
431
        // Database name.
432
        $form->addText(
433
            'main_database',
434
            [
435
                $plugin->get_lang('maindatabase'),
436
                $plugin->get_lang('DatabaseDescription'),
437
            ]
438
        );
439
440
        // Button for testing database connection.
441
        $form->addElement(
442
            'button',
443
            'testconnection',
444
            $this->_plugin->get_lang('testconnection'),
445
            'check',
446
            'default',
447
            'default',
448
            '',
449
            'onclick="opencnxpopup(\''.$_configuration['root_web'].'\'); return false;"'
450
        );
451
452
        $form->addText('archive_url', $this->_plugin->get_lang('ArchiveUrl'));
453
        $form->addText('home_url', $this->_plugin->get_lang('HomeUrl'));
454
        $form->addText('upload_url', $this->_plugin->get_lang('UploadUrl'));
455
        $form->addText(
456
            'css_theme_folder',
457
            [
458
                $this->_plugin->get_lang('ThemeFolder'),
459
                $this->_plugin->get_lang('ThemeFolderExplanation'),
460
            ],
461
            false
462
        );
463
        //$form->addText('course_url', $this->_plugin->get_lang('CourseUrl'));
464
465
        /**
466
         * Template selection.
467
         */
468
        if ($this->is_in_add_mode()) {
469
            $form->addElement('header', $this->_plugin->get_lang('templating'));
470
471
            $templateoptions = Virtual::getAvailableTemplates();
472
473
            // Template choice
474
            $form->addSelect(
475
                'template',
476
                $this->_plugin->get_lang('template'),
477
                $templateoptions
478
            );
479
        } else {
480
            if ($this->instance) {
481
                $form->addLabel(
482
                    'slug',
483
                    $this->instance['slug']
484
                );
485
486
                $form->addLabel(
487
                    'archive_real_root',
488
                    api_add_trailing_slash(Virtual::getConfig('vchamilo', 'archive_real_root')).
489
                    $this->instance['slug']
490
                );
491
492
                $form->addLabel(
493
                    'course_real_root',
494
                    api_add_trailing_slash(Virtual::getConfig('vchamilo', 'course_real_root')).
495
                        $this->instance['slug']
496
                );
497
498
                $form->addLabel(
499
                    'home_real_root',
500
                    api_add_trailing_slash(Virtual::getConfig('vchamilo', 'home_real_root')).$this->instance['slug']
501
                );
502
503
                $form->addLabel(
504
                    'upload_real_root',
505
                    api_add_trailing_slash(Virtual::getConfig('vchamilo', 'upload_real_root')).$this->instance['slug']
506
                );
507
508
                $form->addLabel(
509
                    $this->_plugin->get_lang('template'),
510
                    $this->instance['template']
511
                );
512
            }
513
        }
514
515
        $form->addButtonSave(
516
            $this->_plugin->get_lang('savechanges'),
517
            'submitbutton'
518
        );
519
520
        // Rules
521
        $form->addRule(
522
            'sitename',
523
            $this->_plugin->get_lang('sitenameinputerror'),
524
            'required',
525
            null,
526
            'client'
527
        );
528
        $form->addRule(
529
            'institution',
530
            $this->_plugin->get_lang('institutioninputerror'),
531
            'required',
532
            null,
533
            'client'
534
        );
535
536
        $form->addRule(
537
            'root_web',
538
            $this->_plugin->get_lang('rootwebinputerror'),
539
            'required',
540
            null,
541
            'client'
542
        );
543
        $form->addRule(
544
            'main_database',
545
            $this->_plugin->get_lang('databaseinputerror'),
546
            'required',
547
            null,
548
            'client'
549
        );
550
    }
551
552
    /**
553
     * @param array $data
554
     * @param null  $files
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $files is correct as it would always require null to be passed?
Loading history...
555
     *
556
     * @return array
557
     */
558
    public function validation($data, $files = null)
559
    {
560
        global $plugin;
561
562
        $errors = [];
563
        $tablename = Database::get_main_table('vchamilo');
564
        $vchamilo = Database::select(
565
            '*',
566
            $tablename,
567
            ['where' => [' root_web = ? ' => [$data['root_web']]]],
568
            'first'
569
        );
570
571
        if ($vchamilo && isset($data['vid']) && $data['vid'] != $vchamilo['id']) {
572
            $errors['root_web'] = $plugin->get_lang('RootWebExists');
573
        }
574
575
        if (!empty($errors)) {
576
            return $errors;
577
        }
578
    }
579
}
580