/
InstallerController.php
1109 lines (963 loc) · 43.6 KB
/
InstallerController.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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php if (!defined('BASEPATH')) {
exit('No direct script access allowed');
}
/*
* LimeSurvey (tm)
* Copyright (C) 2011 The LimeSurvey Project Team / Carsten Schmitz
* All rights reserved.
* License: GNU/GPL License v2 or later, see LICENSE.php
* LimeSurvey is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details.
*
* @author Shubham Sachdeva
*/
/**
* Installer
*
*
* @package LimeSurvey
* @copyright 2019
* @access public
*/
class InstallerController extends CController
{
/**
* @var CDbConnection
*/
public $connection;
/**
* clang
*/
public $lang = null;
public $layout = 'installer';
/**
* Checks for action specific authorization and then executes an action
*
* @access public
* @param string $action
* @return void
*/
public function run($action = 'index')
{
$this->_checkInstallation();
$this->_sessioncontrol();
Yii::import('application.helpers.common_helper', true);
switch ($action) {
case 'welcome':
$this->stepWelcome();
break;
case 'license':
$this->stepLicense();
break;
case 'viewlicense':
$this->stepViewLicense();
break;
case 'precheck':
$this->stepPreInstallationCheck();
break;
case 'database':
$this->stepDatabaseConfiguration();
break;
case 'createdb':
$this->stepCreateDb();
break;
case 'populatedb':
$this->stepPopulateDb();
break;
case 'optional':
$this->stepOptionalConfiguration();
break;
case 'index' :
default :
$this->redirect(array('installer/welcome'));
break;
}
}
/**
* Installer::_checkInstallation()
*
* Based on existance of 'sample_installer_file.txt' file, check if
* installation should proceed further or not.
* @return void
*/
private function _checkInstallation()
{
if (file_exists(APPPATH.'config/config.php')) {
throw new CHttpException(500, 'Installation has been done already. Installer disabled.');
}
}
/**
* Load and set session vars
*
* @access protected
* @return void
*/
protected function _sessioncontrol()
{
if (empty(Yii::app()->session['installerLang'])) {
Yii::app()->session['installerLang'] = 'en';
}
Yii::app()->setLanguage(Yii::app()->session['installerLang']);
}
/**
* welcome and language selection install step
*/
private function stepWelcome()
{
Yii::import('application.helpers.surveytranslator_helper', true);
if (!is_null(Yii::app()->request->getPost('installerLang'))) {
Yii::app()->session['installerLang'] = Yii::app()->request->getPost('installerLang');
$this->redirect(array('installer/license'));
}
Yii::app()->session->remove('configFileWritten');
$aData = [];
$aData['title'] = gT('Welcome');
$aData['descp'] = gT('Welcome to the LimeSurvey installation wizard. This wizard will guide you through the installation, database setup and initial configuration of LimeSurvey.');
$aData['classesForStep'] = array('on', 'off', 'off', 'off', 'off', 'off');
$aData['progressValue'] = 10;
if (isset(Yii::app()->session['installerLang'])) {
$sCurrentLanguage = Yii::app()->session['installerLang'];
} else {
$sCurrentLanguage = 'en';
}
$aLanguages = [];
foreach (getLanguageData(true, $sCurrentLanguage) as $sKey => $aLanguageInfo) {
$aLanguages[htmlspecialchars($sKey)] = sprintf('%s - %s', $aLanguageInfo['nativedescription'], $aLanguageInfo['description']);
}
$aData['languages'] = $aLanguages;
$this->render('/installer/welcome_view', $aData);
}
/**
* Display license
*/
private function stepLicense()
{
// $aData array contain all the information required by view.
$aData = [];
$aData['title'] = gT('License');
$aData['descp'] = gT('GNU General Public License:');
$aData['classesForStep'] = array('off', 'on', 'off', 'off', 'off', 'off');
$aData['progressValue'] = 15;
if (strtolower($_SERVER['REQUEST_METHOD']) == 'post') {
$this->redirect(array('installer/precheck'));
}
Yii::app()->session['saveCheck'] = 'save'; // Checked in next step
$this->render('/installer/license_view', $aData);
}
/**
* display the license file as IIS for example
* does not display it via the server.
*/
public function stepViewLicense()
{
header('Content-Type: text/plain; charset=UTF-8');
readfile(dirname((string) BASEPATH).'/LICENSE');
exit;
}
/**
* check a few writing permissions and optional settings
*/
private function stepPreInstallationCheck()
{
$oModel = new InstallerConfigForm();
//usual data required by view
$aData = [];
$aData['model'] = $oModel;
$aData['title'] = gT('Pre-installation check');
$aData['descp'] = gT('Pre-installation check for LimeSurvey ').Yii::app()->getConfig('versionnumber');
$aData['classesForStep'] = array('off', 'off', 'on', 'off', 'off', 'off');
$aData['progressValue'] = 20;
// variable storing next button link.initially null
$aData['next'] = '';
// Silently check some default PHP extensions
$this->checkDefaultExtensions();
$bProceed = $oModel->hasMinimumRequirements;
$sessionWritable = (Yii::app()->session->get('saveCheck', null) === 'save');
$aData['sessionWritable'] = $sessionWritable;
if (!$sessionWritable) {
// For recheck, try to set the value again
$session['saveCheck'] = 'save';
$bProceed = false;
}
// after all check, if flag value is true, show next button and sabe step2 status.
if ($bProceed) {
$aData['next'] = true;
Yii::app()->session['step2'] = true;
}
$this->render('/installer/precheck_view', $aData);
}
/**
* Configure database screen
*/
private function stepDatabaseConfiguration()
{
Yii::import('application.helpers.surveytranslator_helper', true);
// usual data required by view
$aData = [];
$aData['title'] = gT('Database configuration');
$aData['descp'] = gT('Please enter the database settings you want to use for LimeSurvey:');
$aData['classesForStep'] = array('off', 'off', 'off', 'on', 'off', 'off');
$aData['progressValue'] = 40;
$aData['model'] = $oModel = new InstallerConfigForm;
if (!empty(Yii::app()->session['populateerror'])) {
if(is_string(Yii::app()->session['populateerror'])) {
$oModel->addError('dblocation', Yii::app()->session['populateerror']);
} else {
foreach(Yii::app()->session['populateerror'] as $error) {
$oModel->addError('dblocation', $error);
}
}
//~ $oModel->addError('dbpwd', '');
//~ $oModel->addError('dbuser', '');
unset(Yii::app()->session['populateerror']);
}
if (!is_null(Yii::app()->request->getPost('InstallerConfigForm'))) {
$oModel->setAttributes(Yii::app()->request->getPost('InstallerConfigForm'), false);
//run validation, if it fails, load the view again else proceed to next step.
if ($oModel->validate()) {
//saving the form data to session
foreach (array('dblocation', 'dbname', 'dbengine', 'dbtype', 'dbpwd', 'dbuser', 'dbprefix') as $sStatusKey) {
Yii::app()->session[$sStatusKey] = $oModel->$sStatusKey;
}
//check if table exists or not
$bTablesDoNotExist = false;
// Check if the surveys table exists or not
if ($oModel->dbExists) {
try {
// We do the following check because DBLIB does not throw an exception on a missing table
if ($oModel->db->createCommand()->select()->from('{{users}}')->query()->rowCount == 0) {
$bTablesDoNotExist = true;
}
} catch (Exception $e) {
$bTablesDoNotExist = true;
}
}
$bDBExistsButEmpty = ($oModel->dbExists && $bTablesDoNotExist);
//store them in session
Yii::app()->session['databaseexist'] = $oModel->dbExists;
Yii::app()->session['tablesexist'] = !$bTablesDoNotExist;
// If database is up to date, redirect to administration screen.
if ($oModel->dbExists && !$bTablesDoNotExist) {
Yii::app()->session['optconfig_message'] = sprintf('<b>%s</b>', gT('The database you specified does already exist.'));
Yii::app()->session['step3'] = true;
//Write config file as we no longer redirect to optional view
$this->_writeConfigFile();
header("refresh:5;url=".$this->createUrl("/admin"));
$aData['noticeMessage'] = gT('The database exists and contains LimeSurvey tables.');
$aData['text'] = sprintf(gT("You'll be redirected to the database update or (if your database is already up to date) to the administration login in 5 seconds. If not, please click %shere%s."), "<a href='".$this->createUrl("/admin")."'>", "</a>");
$this->render('/installer/redirectmessage_view', $aData);
exit();
}
if ($oModel->isMysql) {
//for development - use mysql in the strictest mode
if (Yii::app()->getConfig('debug') > 1) {
$oModel->db->createCommand("SET SESSION SQL_MODE='STRICT_ALL_TABLES,ANSI'")->execute();
}
}
//$aData array won't work here. changing the name
$aValues = [];
$aValues['title'] = gT('Database settings');
$aValues['descp'] = gT('Database settings');
$aValues['classesForStep'] = array('off', 'off', 'off', 'off', 'on', 'off');
$aValues['progressValue'] = 60;
//it store text content
$aValues['adminoutputText'] = '';
//it store the form code to be displayed
$aValues['adminoutputForm'] = '';
//if DB exist, check if its empty or up to date. if not, tell user LS can create it.
if (!$oModel->dbExists) {
Yii::app()->session['databaseDontExist'] = true;
$aValues['dbname'] = $oModel->dbname;
$aValues['model'] = $oModel;
$aValues['next'] = array(
'action' => 'installer/createdb',
'label' => gT('Create database'),
'name' => '',
);
} elseif ($bDBExistsButEmpty) {
Yii::app()->session['populatedatabase'] = true;
$aValues['model'] = $oModel;
//$this->connection->database = $model->dbname;
// //$this->connection->createCommand("USE DATABASE `".$model->dbname."`")->execute();
$aValues['adminoutputText'] .= sprintf(gT('A database named "%s" already exists.'), $oModel->dbname)."<br /><br />\n"
.gT("Do you want to populate that database now by creating the necessary tables?")."<br /><br />";
$aValues['next'] = array(
'action' => 'installer/populatedb',
'label' => gT("Populate database", 'unescaped'),
'name' => 'createdbstep2',
);
} elseif (!$bDBExistsButEmpty) {
$aValues['adminoutput'] .= "<br />".sprintf(gT('Please <a href="%s">log in</a>.', 'unescaped'), $this->createUrl("/admin"));
}
$this->render('/installer/populatedb_view', $aValues);
return;
}
}
$this->render('/installer/dbconfig_view', $aData);
}
/**
* Installer::stepCreateDb()
* Create database.
* @return void
* @throws Exception
*/
public function stepCreateDb()
{
Yii::import('application.helpers.surveytranslator_helper', true);
// check status. to be called only when database don't exist else redirect to proper link.
if (!Yii::app()->session['databaseDontExist']) {
$this->redirect(array('installer/welcome'));
}
$aData = [];
$oModel = $this->getModelFromSession();
$oModel->dbConnect();
$aData['model'] = $oModel;
$aData['title'] = gT("Database configuration");
$aData['descp'] = gT("Please enter the database settings you want to use for LimeSurvey:");
$aData['classesForStep'] = array('off', 'off', 'off', 'on', 'off', 'off');
$aData['progressValue'] = 40;
// unset database name for connection, since we want to create it and it doesn't already exists
$aDbConfig['sDatabaseName'] = '';
$aData['adminoutputForm'] = '';
try {
$oModel->createDatabase();
Yii::app()->session['populatedatabase'] = true;
Yii::app()->session['databaseexist'] = true;
unset(Yii::app()->session['databaseDontExist']);
$aData['adminoutputText'] = "<tr bgcolor='#efefef'><td colspan='2' align='center'>"
."<div class='alert alert-success''><strong>\n"
.gT("Database has been created.")."</strong></div>\n"
.gT("Please continue with populating the database.")."<br /><br />\n";
$aData['next'] = array(
'action' => 'installer/populatedb',
'label' => gT("Populate database"),
'name' => 'createdbstep2',
);
$aData['title'] = gT("Database settings");
$aData['descp'] = gT("Database settings");
$aData['classesForStep'] = array('off', 'off', 'off', 'off', 'on', 'off');
$aData['progressValue'] = 60;
$this->render('/installer/populatedb_view', $aData);
} catch (Exception $e) {
$oModel->addError('dbname', gT('Try again! Creation of database failed.'));
$oModel->addError('dbname', $e->getMessage());
$aData['title'] = gT('Database configuration');
$aData['descp'] = gT('Please enter the database settings you want to use for LimeSurvey:');
$aData['classesForStep'] = array('off', 'off', 'off', 'on', 'off', 'off');
$aData['progressValue'] = 40;
$aData['model'] = $oModel;
$this->render('/installer/dbconfig_view', $aData);
}
}
/**
* Installer::stepPopulateDb()
* Function to populate the database.
* @return void
*/
public function stepPopulateDb()
{
if (!Yii::app()->session['populatedatabase']) {
$this->redirect(array('installer/welcome'));
}
$aData = [];
$model = $this->getModelFromSession();
$model->dbConnect();
$aData['model'] = $model;
$aData['title'] = gT("Database configuration");
$aData['descp'] = gT("Please enter the database settings you want to use for LimeSurvey:");
$aData['classesForStep'] = array('off', 'off', 'off', 'on', 'off', 'off');
$aData['progressValue'] = 40;
//checking DB Connection
$result = $model->setupTables();
if ($result === true) {
$sConfirmation = sprintf(gT("Database %s has been successfully populated."), sprintf('<b>%s</b>', Yii::app()->session['dbname']));
} elseif (is_array($result)) {
$errors = [];
$errors[] = gT('There were errors when trying to populate the database:');
foreach ($result as $error) {
$errors[] = $error;
}
Yii::app()->session['populateerror'] = $errors;
$this->redirect(array('installer/database'));
} else {
throw new UnexpectedValueException('setupTables is expected to return true or an array of strings');
}
Yii::app()->session['tablesexist'] = true;
Yii::app()->session['step3'] = true;
Yii::app()->session['optconfig_message'] = $sConfirmation;
unset(Yii::app()->session['populatedatabase']);
$this->redirect(array('installer/optional'));
}
/**
* Optional settings screen
*/
private function stepOptionalConfiguration()
{
Yii::import('application.helpers.surveytranslator_helper', true);
$aData = [];
$aData['confirmation'] = Yii::app()->session['optconfig_message'];
$aData['title'] = gT("Administrator settings");
$aData['descp'] = gT("Further settings for application administrator");
$aData['classesForStep'] = array('off', 'off', 'off', 'off', 'off', 'on');
$aData['progressValue'] = 80;
$aData['model'] = $model = $this->getModelFromSession('optional');
// Backup the default, needed only for $sDefaultAdminPassword
$sDefaultAdminPassword = $model->adminLoginPwd;
if (!is_null(Yii::app()->request->getPost('InstallerConfigForm'))) {
$model->setAttributes(Yii::app()->request->getPost('InstallerConfigForm'), false);
//run validation, if it fails, load the view again else proceed to next step.
if ($model->validate()) {
$aData['title'] = gT("Database configuration");
$aData['descp'] = gT("Please enter the database settings you want to use for LimeSurvey:");
$aData['classesForStep'] = array('off', 'off', 'off', 'on', 'off', 'off');
$aData['progressValue'] = 40;
// Flush query cache because Yii does not handle properly the new DB prefix
if (method_exists(Yii::app()->cache, 'flush')) {
Yii::app()->cache->flush();
}
$aDbConfigArray = $this->_getDatabaseConfigArray();
$aDbConfigArray['class'] = '\CDbConnection';
\Yii::app()->setComponent('db', $aDbConfigArray, false);
$model->db->setActive(true);
//checking DB Connection
if ($model->db->getActive() == true) {
try {
if (User::model()->count() > 0) {
safeDie('Fatal error: Already an admin user in the system.');
}
// Save user
$user = new User;
// Fix UserID to 1 for MySQL even if installed in master-master configuration scenario
if ($model->isMysql) {
$user->uid = 1;
}
$user->users_name = $model->adminLoginName;
$user->setPassword($model->adminLoginPwd);
$user->full_name = $model->adminName;
$user->parent_id = 0;
$user->lang = $model->surveylang;
$user->email = $model->adminEmail;
$user->save();
// Save permissions
$permission = new Permission;
$permission->entity_id = 0;
$permission->entity = 'global';
$permission->uid = $user->uid;
$permission->permission = 'superadmin';
$permission->read_p = 1;
$permission->save();
// Save global settings
$model->db->createCommand()->insert("{{settings_global}}", array('stg_name' => 'SessionName', 'stg_value' => $this->_getRandomString()));
$model->db->createCommand()->insert("{{settings_global}}", array('stg_name' => 'sitename', 'stg_value' => $model->siteName));
$model->db->createCommand()->insert("{{settings_global}}", array('stg_name' => 'siteadminname', 'stg_value' => $model->adminName));
$model->db->createCommand()->insert("{{settings_global}}", array('stg_name' => 'siteadminemail', 'stg_value' => $model->adminEmail));
$model->db->createCommand()->insert("{{settings_global}}", array('stg_name' => 'siteadminbounce', 'stg_value' => $model->adminEmail));
$model->db->createCommand()->insert("{{settings_global}}", array('stg_name' => 'defaultlang', 'stg_value' => $model->surveylang));
// only continue if we're error free otherwise setup is broken.
Yii::app()->session['deletedirectories'] = true;
$aData['title'] = gT("Success!");
$aData['descp'] = gT("LimeSurvey has been installed successfully.");
$aData['classesForStep'] = array('off', 'off', 'off', 'off', 'off', 'off');
$aData['progressValue'] = 100;
$aData['user'] = $model->adminLoginName;
if ($sDefaultAdminPassword == $model->adminLoginPwd) {
$aData['pwd'] = $model->adminLoginPwd;
} else {
$aData['pwd'] = gT("The password you have chosen at the optional settings step.");
}
$this->_writeConfigFile();
$this->clearSession();
$this->render('/installer/success_view', $aData);
return;
} catch (Exception $e) {
throw new Exception(sprintf('Could not add administrator settings: %s.', $e));
}
}
} else {
unset($aData['confirmation']);
}
}
$this->render('/installer/optconfig_view', $aData);
}
/**
* Loads a helper
*
* @access public
* @param string $helper
* @return void
*/
public function loadHelper($helper)
{
Yii::import('application.helpers.'.$helper.'_helper', true);
}
/**
* Loads a library
*
* @access public
* @return void
*/
public function loadLibrary($library)
{
Yii::import('application.libraries.'.$library, true);
}
/**
* check image HTML template
*
* @param bool $result
* @return string Span with check if $result is true; otherwise a span with warning
*/
public function check_HTML_image($result)
{
if ($result) {
return "<span class='fa fa-check text-success' alt='right'></span>";
} else {
return "<span class='fa fa-exclamation-triangle text-danger' alt='wrong'></span>";
}
}
/**
* @param string $sDirectory
*/
public function is_writable_recursive($sDirectory)
{
$sFolder = opendir($sDirectory);
if ($sFolder === false) {
return false; // Dir does not exist
}
while ($sFile = readdir($sFolder)) {
if ($sFile != '.' && $sFile != '..' &&
(!is_writable($sDirectory."/".$sFile) ||
(is_dir($sDirectory."/".$sFile) && !$this->is_writable_recursive($sDirectory."/".$sFile)))) {
closedir($sFolder);
return false;
}
}
closedir($sFolder);
return true;
}
/**
* check for a specific PHPFunction, return HTML image
*
* @param string $sFunctionName
* @param string $sImage return
* @return bool result
*/
public function checkPHPFunction($sFunctionName, &$sImage)
{
$bExists = function_exists($sFunctionName);
$sImage = $this->check_HTML_image($bExists);
return $bExists;
}
/**
* check if file or directory exists and is writeable, returns via parameters by reference
*
* @param string $path file or directory to check
* @param int $type 0:undefined (invalid), 1:file, 2:directory
* @param string $base key for data manipulation
* @param string $keyError key for error data
* @param string $aData
* @return bool result of check (that it is writeable which implies existance)
*/
public function checkPathWriteable($path, $type, &$aData, $base, $keyError, $bRecursive = false)
{
$bResult = false;
$aData[$base.'Present'] = 'Not Found';
$aData[$base.'Writable'] = '';
switch ($type) {
case 1:
$exists = is_file($path);
break;
case 2:
$exists = is_dir($path);
break;
default:
throw new Exception('Invalid type given.');
}
if ($exists) {
$aData[$base.'Present'] = 'Found';
if ((!$bRecursive && is_writable($path)) || ($bRecursive && $this->is_writable_recursive($path))) {
$aData[$base.'Writable'] = 'Writable';
$bResult = true;
} else {
$aData[$base.'Writable'] = 'Unwritable';
}
}
$bResult || $aData[$keyError] = true;
return $bResult;
}
/**
* check if file exists and is writeable, returns via parameters by reference
*
* @param string $file to check
* @param string $data to manipulate
* @param string $base key for data manipulation
* @param string $keyError key for error data
* @return bool result of check (that it is writeable which implies existance)
*/
public function checkFileWriteable($file, &$data, $base, $keyError)
{
return $this->checkPathWriteable($file, 1, $data, $base, $keyError);
}
/**
* check if directory exists and is writeable, returns via parameters by reference
*
* @param string $directory to check
* @param string $data to manipulate
* @param string $base key for data manipulation
* @param string $keyError key for error data
* @return bool result of check (that it is writeable which implies existance)
*/
public function checkDirectoryWriteable($directory, &$data, $base, $keyError, $bRecursive = false)
{
return $this->checkPathWriteable($directory, 2, $data, $base, $keyError, $bRecursive);
}
/**
* check requirements
*
* @return bool requirements met
*/
private function _check_requirements(&$aData)
{
// proceed variable check if all requirements are true. If any of them is false, proceed is set false.
$bProceed = true; //lets be optimistic!
// version check
if (version_compare(PHP_VERSION, '5.5.9', '<')) {
$bProceed = !$aData['verror'] = true;
}
if (convertPHPSizeToBytes(ini_get('memory_limit')) / 1024 / 1024 < 128 && ini_get('memory_limit') != -1) {
$bProceed = !$aData['bMemoryError'] = true;
}
// mbstring library check
if (!$this->checkPHPFunction('mb_convert_encoding', $aData['mbstringPresent'])) {
$bProceed = false;
}
// zlib library check
if (!$this->checkPHPFunction('zlib_get_coding_type', $aData['zlibPresent'])) {
$bProceed = false;
}
// JSON library check
if (!$this->checkPHPFunction('json_encode', $aData['bJSONPresent'])) {
$bProceed = false;
}
// ** file and directory permissions checking **
// config directory
if (!$this->checkDirectoryWriteable(Yii::app()->getConfig('rootdir').'/application/config', $aData, 'config', 'derror')) {
$bProceed = false;
}
// templates directory check
if (!$this->checkDirectoryWriteable(Yii::app()->getConfig('tempdir').'/', $aData, 'tmpdir', 'tperror', true)) {
$bProceed = false;
}
//upload directory check
if (!$this->checkDirectoryWriteable(Yii::app()->getConfig('uploaddir').'/', $aData, 'uploaddir', 'uerror', true)) {
$bProceed = false;
}
// Session writable check
$session = Yii::app()->session; /* @var $session CHttpSession */
$sessionWritable = ($session->get('saveCheck', null) === 'save');
$aData['sessionWritable'] = $sessionWritable;
$aData['sessionWritableImg'] = $this->check_HTML_image($sessionWritable);
if (!$sessionWritable) {
// For recheck, try to set the value again
$session['saveCheck'] = 'save';
$bProceed = false;
}
// ** optional settings check **
// gd library check
if (function_exists('gd_info')) {
$aData['gdPresent'] = $this->check_HTML_image(array_key_exists('FreeType Support', gd_info()));
} else {
$aData['gdPresent'] = $this->check_HTML_image(false);
}
// ldap library check
$this->checkPHPFunction('ldap_connect', $aData['ldapPresent']);
// php zip library check
$this->checkPHPFunction('zip_open', $aData['zipPresent']);
// zlib php library check
$this->checkPHPFunction('zlib_get_coding_type', $aData['zlibPresent']);
// imap php library check
$this->checkPHPFunction('imap_open', $aData['bIMAPPresent']);
// Sodium php check
$this->checkPHPFunction('sodium_crypto_sign_open', $aData['sodiumPresent']);
// Silently check some default PHP extensions
$this->checkDefaultExtensions();
return $bProceed;
}
/**
* Executes an SQL file
*
* @param string $sFileName
* @param string $sDatabasePrefix
*/
public function _executeSQLFile($sFileName, $sDatabasePrefix)
{
$aMessages = array();
$sCommand = '';
if (!is_readable($sFileName)) {
return false;
} else {
$aLines = file($sFileName);
}
foreach ($aLines as $sLine) {
$sLine = rtrim($sLine);
$iLineLength = strlen($sLine);
if ($iLineLength && $sLine[0] != '#' && substr($sLine, 0, 2) != '--') {
if (substr($sLine, $iLineLength - 1, 1) == ';') {
$sCommand .= $sLine;
$sCommand = str_replace('prefix_', $sDatabasePrefix, $sCommand); // Table prefixes
try {
$this->connection->createCommand($sCommand)->execute();
} catch (Exception $e) {
$aMessages[] = "Executing: ".$sCommand." failed! Reason: ".$e;
}
$sCommand = '';
} else {
$sCommand .= $sLine;
}
}
}
return $aMessages;
}
/**
* Function to write given database settings in APPPATH.'config/config.php'
*/
private function _writeConfigFile()
{
//write config.php if database exists and has been populated.
if (Yii::app()->session['databaseexist'] && Yii::app()->session['tablesexist']) {
$model = $this->getModelFromSession();
$model->dbConnect();
$sDsn = $model->db->connectionString;
// mod_rewrite existence check
// Section commented out until a better method of knowing whether the mod_rewrite actually
// works is found. In the meantime, it is better to set $showScriptName to 'true' so it
// works on all installations, and allow users to change it manually later.
//if ((function_exists('apache_get_modules') && in_array('mod_rewrite', apache_get_modules())) || strtolower(getenv('HTTP_MOD_REWRITE')) == 'on')
//{
// $showScriptName = 'false';
//}
//else
//{
$sShowScriptName = 'true';
//}
if (stripos($_SERVER['SERVER_SOFTWARE'], 'apache') !== false || (ini_get('security.limit_extensions') && ini_get('security.limit_extensions') != '')) {
$sURLFormat = 'path';
} else {
// Apache
$sURLFormat = 'get'; // Fall back to get if an Apache server cannot be determined reliably
}
$sCharset = 'utf8';
if ($model->isMysql) {
$sCharset = 'utf8mb4';
}
if ($model->dbtype) {
$sConfig = "<?php if (!defined('BASEPATH')) exit('No direct script access allowed');"."\n"
."/*"."\n"
."| -------------------------------------------------------------------"."\n"
."| DATABASE CONNECTIVITY SETTINGS"."\n"
."| -------------------------------------------------------------------"."\n"
."| This file will contain the settings needed to access your database."."\n"
."|"."\n"
."| For complete instructions please consult the 'Database Connection'"."\n"
."| page of the User Guide."."\n"
."|"."\n"
."| -------------------------------------------------------------------"."\n"
."| EXPLANATION OF VARIABLES"."\n"
."| -------------------------------------------------------------------"."\n"
."|"."\n"
."| 'connectionString' Hostname, database, port and database type for "."\n"
."| the connection. Driver example: mysql. Currently supported:"."\n"
."| mysql, pgsql, mssql, sqlite, oci"."\n"
."| 'username' The username used to connect to the database"."\n"
."| 'password' The password used to connect to the database"."\n"
."| 'tablePrefix' You can add an optional prefix, which will be added"."\n"
."| to the table name when using the Active Record class"."\n"
."|"."\n"
."*/"."\n"
. "return array("."\n"
/*
."\t" . "'basePath' => dirname(dirname(__FILE__))," . "\n"
."\t" . "'runtimePath' => dirname(dirname(dirname(__FILE__))).DIRECTORY_SEPARATOR.'tmp'.DIRECTORY_SEPARATOR.'runtime'," . "\n"
."\t" . "'name' => 'LimeSurvey'," . "\n"
."\t" . "'defaultController' => 'survey'," . "\n"
."\t" . "" . "\n"
."\t" . "'import' => array(" . "\n"
."\t\t" . "'application.core.*'," . "\n"
."\t\t" . "'application.models.*'," . "\n"
."\t\t" . "'application.controllers.*'," . "\n"
."\t\t" . "'application.modules.*'," . "\n"
."\t" . ")," . "\n"
."\t" . "" . "\n"
*/
."\t"."'components' => array("."\n"
."\t\t"."'db' => array("."\n"
."\t\t\t"."'connectionString' => '$sDsn',"."\n";
}
if ($model->dbtype != InstallerConfigForm::DB_TYPE_SQLSRV && $model->dbtype != InstallerConfigForm::DB_TYPE_DBLIB) {
$sConfig .= "\t\t\t"."'emulatePrepare' => true,"."\n";
}
$sConfig .= "\t\t\t"."'username' => '".addcslashes($model->dbuser, "'")."',"."\n"
."\t\t\t"."'password' => '".addcslashes($model->dbpwd, "'")."',"."\n"
."\t\t\t"."'charset' => '{$sCharset}',"."\n"
."\t\t\t"."'tablePrefix' => '{$model->dbprefix}',"."\n";
if ($model->isMSSql) {
$sConfig .= "\t\t\t"."'initSQLs'=>array('SET DATEFORMAT ymd;','SET QUOTED_IDENTIFIER ON;'),"."\n";
}
$sConfig .= "\t\t"."),"."\n"
."\t\t".""."\n"
."\t\t"." 'session' => array ("."\n"
."\t\t\t"."'sessionName'=>'LS-".$this->_getRandomString(16)."'"."\n"
."\t\t\t"."// Uncomment the following lines if you need table-based sessions."."\n"
."\t\t\t"."// Note: Table-based sessions are currently not supported on MSSQL server."."\n"
."\t\t\t"."// 'class' => 'application.core.web.DbHttpSession',"."\n"
."\t\t\t"."// 'connectionID' => 'db',"."\n"
."\t\t\t"."// 'sessionTableName' => '{{sessions}}',"."\n"
."\t\t"." ),"."\n"
."\t\t".""."\n"
/** @todo Uncomment after implementing the error controller */
/*
."\t\t" . "'errorHandler' => array(" . "\n"
."\t\t\t" . "'errorAction' => 'error'," . "\n"
."\t\t" . ")," . "\n"
."\t\t" . "" . "\n"
*/
."\t\t"."'urlManager' => array("."\n"
."\t\t\t"."'urlFormat' => '{$sURLFormat}',"."\n"
."\t\t\t"."'rules' => array("."\n"
."\t\t\t\t"."// You can add your own rules here"."\n"
."\t\t\t"."),"."\n"
."\t\t\t"."'showScriptName' => {$sShowScriptName},"."\n"
."\t\t"."),"."\n"
."\t".""."\n"
."\t"."),"."\n"
."\t"."// For security issue : it's better to set runtimePath out of web access"."\n"
."\t"."// Directory must be readable and writable by the webuser"."\n"
."\t"."// 'runtimePath'=>'/var/limesurvey/runtime/'"."\n"
."\t"."// Use the following config variable to set modified optional settings copied from config-defaults.php"."\n"
."\t"."'config'=>array("."\n"
."\t"."// debug: Set this to 1 if you are looking for errors. If you still get no errors after enabling this"."\n"
."\t"."// then please check your error-logs - either in your hosting provider admin panel or in some /logs directory"."\n"
."\t"."// on your webspace."."\n"
."\t"."// LimeSurvey developers: Set this to 2 to additionally display STRICT PHP error messages and get full access to standard templates"."\n"
."\t\t"."'debug'=>0,"."\n"
."\t\t"."'debugsql'=>0, // Set this to 1 to enanble sql logging, only active when debug = 2"."\n";
if ($model->isMysql) {
$sConfig .= "\t\t"."// Mysql database engine (INNODB|MYISAM):"."\n"
."\t\t 'mysqlEngine' => '{$model->dbengine}'\n\n,";
}
$sConfig .= "\t\t"."// Update default LimeSurvey config here"."\n"
."\t".")"."\n"
. ");"."\n"
. "/* End of file config.php */"."\n"
. "/* Location: ./application/config/config.php */";
if (is_writable(APPPATH.'config')) {
file_put_contents(APPPATH.'config/config.php', $sConfig);
Yii::app()->session['configFileWritten'] = true;
$oUrlManager = Yii::app()->getComponent('urlManager');
/* @var $oUrlManager CUrlManager */
$oUrlManager->setUrlFormat($sURLFormat);
} else {
header('refresh:5;url='.$this->createUrl("installer/welcome"));
echo "<b>".gT("Configuration directory is not writable")."</b><br/>";
printf(gT('You will be redirected in about 5 secs. If not, click <a href="%s">here</a>.', 'unescaped'), $this->createUrl('installer/welcome'));
Yii::app()->end();
}
}
}