/
common_helper.php
5068 lines (4674 loc) · 196 KB
/
common_helper.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
* Copyright (C) 2007-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.
*/
Yii::import('application.helpers.sanitize_helper', true);
/**
* Returns $sToTranslate translated to $sLanguage (defaults to lang set in session) escaped with $sEscapeMode
*
* @param string $sToTranslate
* @param string $sEscapeMode Valid values are html (this is the default, js and unescaped)
* @param string $sLanguage
* @return string
*/
function gT($sToTranslate, $sEscapeMode = 'html', $sLanguage = null)
{
return quoteText(Yii::t('', $sToTranslate, array(), null, $sLanguage), $sEscapeMode);
}
/**
* As gT(), but echoes directly
*
* @param string $sToTranslate
* @param string $sEscapeMode
* @return void
*/
function eT($sToTranslate, $sEscapeMode = 'html')
{
echo gT($sToTranslate, $sEscapeMode);
}
/**
* Translation helper function for plural forms
* @param string $sTextToTranslate
* @param integer $iCount
* @param string $sEscapeMode
* @return string
*/
function ngT($sTextToTranslate, $iCount, $sEscapeMode = 'html')
{
return quoteText(Yii::t('', $sTextToTranslate, $iCount), $sEscapeMode);
}
/**
* Translation helper function for plural forms which outputs right away
* @param string $sToTranslate
* @param integer $iCount
* @param string $sEscapeMode
*/
function neT($sToTranslate, $iCount, $sEscapeMode = 'html')
{
echo ngT($sToTranslate, $iCount, $sEscapeMode);
}
/**
* Quotes a translation according to purpose
* if sEscapeMode is null, we use HTML method because probably we had to specify null as sEscapeMode upstream
*
* @param mixed $sText Text to quote
* @param string $sEscapeMode Optional - One of the values 'html','js' or 'unescaped' - defaults to 'html'
* @return mixed|string
*/
function quoteText($sText, $sEscapeMode = 'html')
{
if ($sEscapeMode === null) {
$sEscapeMode = 'html';
}
switch ($sEscapeMode) {
case 'html':
return HTMLEscape($sText);
case 'js':
return javascriptEscape($sText);
case 'json':
return jsonEscape($sText);
case 'unescaped':
return $sText;
default:
return "Unsupported EscapeMode in gT method";
}
}
/**
* getSurveyList() Queries the database (survey table) for a list of existing surveys
*
* @param boolean $bReturnArray If set to true an array instead of an HTML option list is given back (unused by core (2023-04-12))
* @return string|array This string is returned containing <option></option> formatted list of existing surveys
*
*/
function getSurveyList($bReturnArray = false)
{
static $cached = null;
$timeadjust = getGlobalSetting('timeadjust');
App()->setLanguage((Yii::app()->session['adminlang'] ?? 'en'));
$surveynames = array();
if (is_null($cached)) {
$criteria = new CDBCriteria();
$criteria->select = ['sid','language', 'active', 'expires','startdate'];
$criteria->with = ['languagesettings' => [
'select'=>'surveyls_title',
'where'=>'t.language = languagesettings.language'
]
];
$surveyidresult = Survey::model()
->permission(Yii::app()->user->getId())
->findAll($criteria);
foreach ($surveyidresult as $result) {
if (isset($result->languagesettings[$result->language])) {
$surveynames[] = array_merge(
$result->attributes,
$result->languagesettings[$result->language]->attributes
);
}
}
usort($surveynames, function ($a, $b) {
return strcmp((string) $a['surveyls_title'], (string) $b['surveyls_title']);
});
$cached = $surveynames;
} else {
$surveynames = $cached;
}
$surveyselecter = "";
if ($bReturnArray === true) {
return $surveynames;
}
$activesurveys = '';
$inactivesurveys = '';
$expiredsurveys = '';
foreach ($surveynames as $sv) {
$surveylstitle = CHtml::encode($sv['surveyls_title']) . " [" . $sv['sid'] . "]";
if ($sv['active'] != 'Y') {
$inactivesurveys .= "<option ";
if (Yii::app()->user->getId() == $sv['owner_id']) {
$inactivesurveys .= " class='mysurvey emphasis inactivesurvey'";
}
$inactivesurveys .= " value='{$sv['sid']}'>{$surveylstitle}</option>\n";
} elseif ($sv['expires'] != '' && $sv['expires'] < dateShift((string) date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust)) {
$expiredsurveys .= "<option ";
if (Yii::app()->user->getId() == $sv['owner_id']) {
$expiredsurveys .= " class='mysurvey emphasis expiredsurvey'";
}
$expiredsurveys .= " value='{$sv['sid']}'>{$surveylstitle}</option>\n";
} else {
$activesurveys .= "<option ";
if (Yii::app()->user->getId() == $sv['owner_id']) {
$activesurveys .= " class='mysurvey emphasis activesurvey'";
}
$activesurveys .= " value='{$sv['sid']}'>{$surveylstitle}</option>\n";
}
} // End Foreach
//Only show each activesurvey group if there are some
if ($activesurveys != '') {
$surveyselecter .= "<optgroup label='" . gT("Active") . "' class='activesurveyselect'>\n";
$surveyselecter .= $activesurveys . "</optgroup>";
}
if ($expiredsurveys != '') {
$surveyselecter .= "<optgroup label='" . gT("Expired") . "' class='expiredsurveyselect'>\n";
$surveyselecter .= $expiredsurveys . "</optgroup>";
}
if ($inactivesurveys != '') {
$surveyselecter .= "<optgroup label='" . gT("Inactive") . "' class='inactivesurveyselect'>\n";
$surveyselecter .= $inactivesurveys . "</optgroup>";
}
$surveyselecter = "<option selected='selected' value=''>" . gT("Please choose...") . "</option>\n" . $surveyselecter;
return $surveyselecter;
}
/**
* getGidPrevious() returns the Gid of the group prior to the current active group
*
* @param integer $surveyid
* @param integer $gid
*
* @return integer|string The GID of the previous group or blank string if no group
*/
function getGidPrevious($surveyid, $gid)
{
$surveyid = (int) $surveyid;
$qresult = QuestionGroup::model()->findAllByAttributes(array('sid' => $surveyid), array('order' => 'group_order'));
$i = 0;
$iPrev = -1;
foreach ($qresult as $qrow) {
$qrow = $qrow->attributes;
if ($gid == $qrow['gid']) {
$iPrev = $i - 1;
}
$i += 1;
}
if ($iPrev >= 0) {
$GidPrev = $qresult[$iPrev]->gid;
} else {
$GidPrev = "";
}
return $GidPrev;
}
/**
* getGidNext() returns the Gid of the group next to the current active group
*
* @param integer $surveyid
* @param integer $gid
*
* @return integer|string The Gid of the next group or blank string if no group
*/
function getGidNext($surveyid, $gid)
{
$surveyid = (int) $surveyid;
$qresult = QuestionGroup::model()->findAllByAttributes(array('sid' => $surveyid), array('order' => 'group_order'));
$i = 0;
$iNext = 0;
foreach ($qresult as $qrow) {
$qrow = $qrow->attributes;
if ($gid == $qrow['gid']) {
$iNext = $i + 1;
}
$i += 1;
}
if ($iNext < count($qresult)) {
$GidNext = $qresult[$iNext]->gid;
} else {
$GidNext = "";
}
return $GidNext;
}
/**
* convertGETtoPOST a function to create a post Request from get parameters
* !!! This functions result has to be wrappen in singlequotes!
*
* @param String $url | The complete url with all parameters
* @return String | The onclick action for the element
*/
function convertGETtoPOST($url)
{
$url = preg_replace('/&/i', '&', (string) $url);
$stack = explode('?', $url);
$calledscript = array_shift($stack);
$query = array_shift($stack);
$aqueryitems = explode('&', $query);
$postArray = [];
$getArray = [];
foreach ($aqueryitems as $queryitem) {
$stack = explode('=', $queryitem);
$paramname = array_shift($stack);
$value = array_shift($stack);
if (in_array($paramname, array(Yii::app()->getComponent('urlManager')->routeVar))) {
$getArray[$paramname] = $value;
} else {
$postArray[$paramname] = $value;
}
}
if (!empty($getArray)) {
$calledscript = $calledscript . "?" . implode('&', array_map(
function ($v, $k) {
return $k . '=' . $v;
},
$getArray,
array_keys($getArray)
));
}
$callscript = "window.LS.sendPost(\"" . $calledscript . "\",\"\"," . json_encode($postArray) . ");";
return $callscript;
}
/**
* This function calculates how much space is actually used by all files uploaded
* using the File Upload question type
*
* @returns integer Actual space used in MB
*/
function calculateTotalFileUploadUsage()
{
$aRows = Survey::findAll();
$iTotalSize = 0.0;
foreach ($aRows as $aRow) {
$sFilesPath = Yii::app()->getConfig("uploaddir") . '/surveys/' . $aRow->sid . '/files';
if (file_exists($sFilesPath)) {
$iTotalSize += (float) getDirectorySize($sFilesPath);
}
}
return (float) $iTotalSize / 1024 / 1024;
}
/**
* @param string $directory
* @return int
*/
function getDirectorySize($directory)
{
$size = 0;
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory)) as $file) {
$size += $file->getSize();
}
return $size;
}
/**
* Queries the database for the maximum sortorder of a group and returns the next higher one.
*
* @param integer $surveyid The survey ID
* @return int Next free sortorder digit
*/
function getMaxGroupOrder($surveyid)
{
$queryResult = QuestionGroup::model()->find(array(
'condition' => 'sid = :sid',
'params' => array(':sid' => $surveyid),
'order' => 'group_order desc',
'limit' => '1'
));
$current_max = !is_null($queryResult) ? $queryResult->group_order : -1;
$current_max += 1;
return $current_max;
}
/**
* Queries the database for the sortorder of a group.
*
* @param mixed $gid The groups ID
* @return int The sortorder digit
*/
function getGroupOrder($gid)
{
$arGroup = QuestionGroup::model()->findByAttributes(array('gid' => $gid)); //Checked
if (empty($arGroup)) {
return 0;
}
return (int) $arGroup->group_order;
}
/**
* Queries the database for the maximum sort order of questions inside question group.
*
* @param integer $gid
* @return integer
*/
function getMaxQuestionOrder($gid)
{
$gid = (int) $gid;
$max_sql = "SELECT max( question_order ) AS max FROM {{questions}} WHERE gid={$gid}";
$current_max = Yii::app()->db->createCommand($max_sql)->queryScalar(); //Checked
if ($current_max == false) {
return 0;
}
return (int) $current_max;
}
/**
* setupColumns() defines all the html tags to be wrapped around
* various list type answers.
*
* @param integer $columns - the number of columns, usually supplied by $dcols
* @param integer $answer_count - the number of answers to a question, usually supplied by $anscount
* @param string $wrapperclass - a global class for the wrapper
* @param string $itemclass - a class for the item
* @return array with all the various opening and closing tags to generate a set of columns.
* @deprecated Don't use anymore. Only usage left in printabel survey where it needs to be replaced
*
* It returns an array with the following items:
* $wrapper['whole-start'] = Opening wrapper for the whole list
* $wrapper['whole-end'] = closing wrapper for the whole list
* $wrapper['col-devide'] = normal column devider
* $wrapper['col-devide-last'] = the last column devider (to allow
* for different styling of the last
* column
* $wrapper['item-start'] = opening wrapper tag for individual
* option
* $wrapper['item-start-other'] = opening wrapper tag for other
* option
* $wrapper['item-start-noanswer'] = opening wrapper tag for no answer
* option
* $wrapper['item-end'] = closing wrapper tag for individual
* option
* $wrapper['maxrows'] = maximum number of rows in each
* column
* $wrapper['cols'] = Number of columns to be inserted
* (and checked against)
*
*
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* Columns are a problem.
* Really there is no perfect solution to columns at the moment.
*
* - Using Tables is problematic semanticly.
* - Using inline or float to create columns, causes the answers
* flows horizontally, not vertically which is not ideal visually.
* - Using CSS3 columns is also a problem because of browser support
* and also because if you have answeres split across two or more
* lines, and those answeres happen to fall at the bottom of a
* column, the answer might be split across columns as well as
* lines.
* - Using nested unordered list with the first level of <LI>s
* floated is the same as using tables and so is bad semantically
* for the same reason tables are bad.
* - Breaking the unordered lists into consecutive floated unordered
* lists is not great semantically but probably not as bad as
* using tables.
*
* Because I haven't been able to decide which option is the least
* bad, I have handed over that responsibility to the admin who sets
* LimeSurvey up on their server.
*
* There are four options:
* 'css' using one of the various CSS only methods for
* rendering columns.
* (Check the CSS file for your chosen template to see
* how columns are defined.)
* 'ul' using multiple floated unordered lists. (DEFAULT)
* 'table' using conventional tables based layout.
* NULL blocks the use of columns
*
* 'ul' is the default because it's the best possible compromise
* between semantic markup and visual layout.
*/
function setupColumns($columns, $answer_count, $wrapperclass = "", $itemclass = "")
{
$column_style = Yii::app()->getConfig('column_style');
if (!in_array($column_style, array('css', 'ul', 'table')) && !is_null($column_style)) {
$column_style = 'ul';
};
if (!is_null($column_style) && $columns != 1) {
// Add a global class for all column
$wrapperclass .= " colstyle-{$column_style}";
}
if ($columns < 2) {
$column_style = null;
$columns = 1;
}
if (($columns > $answer_count) && $answer_count > 0) {
$columns = $answer_count;
};
$class_first = ' class="' . $wrapperclass . '"';
if ($columns > 1 && !is_null($column_style)) {
if ($column_style == 'ul') {
$ul = '-ul';
} else {
$ul = '';
}
$class_first = ' class="' . $wrapperclass . ' cols-' . $columns . $ul . ' first"';
$class = ' class="' . $wrapperclass . ' cols-' . $columns . $ul . '"';
$class_last_ul = ' class="' . $wrapperclass . ' cols-' . $columns . $ul . ' last"';
$class_last_table = ' class="' . $wrapperclass . ' cols-' . $columns . ' last"';
} else {
$class = ' class="' . $wrapperclass . '"';
$class_last_ul = ' class="' . $wrapperclass . '"';
$class_last_table = ' class="' . $wrapperclass . '"';
};
$wrapper = array(
'whole-start' => "\n<ul$class_first>\n"
,'whole-end' => "</ul>\n"
,'col-devide' => ''
,'col-devide-last' => ''
,'item-start' => "\t<li class=\"{$itemclass}\">\n"
,'item-start-other' => "\t<li class=\"{$itemclass} other other-item\">\n"
,'item-start-noanswer' => "\t<li class=\"{$itemclass} noanswer-item\">\n"
,'item-end' => "\t</li>\n"
,'maxrows' => ceil($answer_count / $columns) //Always rounds up to nearest whole number
,'cols' => $columns
);
switch ($column_style) {
case 'ul':
if ($columns > 1) {
$wrapper['col-devide'] = "\n</ul>\n\n<ul$class>\n";
$wrapper['col-devide-last'] = "\n</ul>\n\n<ul$class_last_ul>\n";
}
break;
case 'table':
$table_cols = '';
for ($cols = $columns; $cols > 0; --$cols) {
switch ($cols) {
case $columns:
$table_cols .= "\t<col$class_first />\n";
break;
case 1:
$table_cols .= "\t<col$class_last_table />\n";
break;
default:
$table_cols .= "\t<col$class />\n";
};
};
if ($columns > 1) {
$wrapper['col-devide'] = "\t</ul>\n</td>\n\n<td>\n\t<ul>\n";
$wrapper['col-devide-last'] = "\t</ul>\n</td>\n\n<td class=\"last\">\n\t<ul>\n";
};
$wrapper['whole-start'] = "\n<table$class>\n$table_cols\n\t<tbody>\n<tr>\n<td>\n\t<ul>\n";
$wrapper['whole-end'] = "\t</ul>\n</td>\n</tr>\n\t</tbody>\n</table>\n";
$wrapper['item-start'] = "<li class=\"{$itemclass}\">\n";
$wrapper['item-end'] = "</li class=\"{$itemclass}\">\n";
};
return $wrapper;
};
function alternation($alternate = '', $type = 'col')
{
/**
* alternation() Returns a class identifyer for alternating between
* two options. Used to style alternate elements differently. creates
* or alternates between the odd string and the even string used in
* as column and row classes for array type questions.
*
* @param string $alternate = '' (empty) (default) , 'array2' , 'array1' , 'odd' , 'even'
* @param string $type = 'col' (default) or 'row'
*
* @return string representing either the first alternation or the opposite alternation to the one supplied..
* @deprecated Should be done by CSS/JS on display. Needs to be fixed.
*/
/*
// The following allows type to be left blank for row in subsequent
// function calls.
// It has been left out because 'row' must be defined the first time
// alternation() is called. Since it is only ever written once for each
// while statement within a function, 'row' is always defined.
if(!empty($alternate) && $type != 'row')
{ if($alternate == ('array2' || 'array1'))
{
$type = 'row';
};
};
// It has been left in case it becomes useful but probably should be
// removed.
*/
if ($type == 'row') {
// Row is sub question OR Y Axis subquestion : it must be column for array by column
$odd = 'ls-odd';
$even = 'ls-even';
} else {
// cols is answers part OR X axis subquestion : it must the row in array by column
$odd = 'ls-col-odd';
$even = 'ls-col-even';
};
if ($alternate == $odd) {
$alternate = $even;
} else {
$alternate = $odd;
};
return $alternate;
}
/**
* longestString() returns the length of the longest string past to it.
* @peram string $new_string
* @peram integer $longest_length length of the (previously) longest string passed to it.
* @param integer $longest_length
* @return integer representing the length of the longest string passed (updated if $new_string was longer than $longest_length)
*
* usage should look like this: $longest_length = longestString( $new_string , $longest_length );
*
*/
function longestString($new_string, $longest_length)
{
if ($longest_length < strlen(trim(strip_tags((string) $new_string)))) {
$longest_length = strlen(trim(strip_tags((string) $new_string)));
};
return $longest_length;
};
//FIXME rename and/or document this
function getGroupList3($gid, $surveyid)
{
$gid = sanitize_int($gid);
$surveyid = sanitize_int($surveyid);
if (!$surveyid) {
$surveyid = returnGlobal('sid', true);
}
$groupselecter = "";
$sBaseLanguage = Survey::model()->findByPk($surveyid)->language;
$gidresult = QuestionGroup::model()->findAllByAttributes(array('sid' => $surveyid), array('order' => 'group_order'));
foreach ($gidresult as $gv) {
$groupselecter .= "<option";
if ($gv->gid == $gid) {
$groupselecter .= " selected='selected'";
}
$groupselecter .= " value='" . $gv->gid . "'>" . htmlspecialchars((string) $gv->questiongroupl10ns[$sBaseLanguage]->group_name) . " (ID:" . $gv->gid . ")</option>\n";
}
return $groupselecter;
}
/**
* put your comment there...
*
* @param mixed $gid
* @param mixed $language
* @return string
*/
function getGroupListLang($gid, $language, $surveyid)
{
$groupselecter = "";
if (!$surveyid) {
$surveyid = returnGlobal('sid', true);
}
$gidresult = QuestionGroup::model()->findAll(array('condition' => 'sid=:surveyid',
'order' => 'group_order',
'params' => array(':surveyid' => $surveyid))); //Checked)
foreach ($gidresult as $oGroup) {
$aAttributes = $oGroup->attributes;
$groupselecter .= "<option";
if ($aAttributes['gid'] == $gid) {
$groupselecter .= " selected='selected'";
$gvexist = 1;
}
$link = Yii::app()->getController()->createUrl("/questionGroupsAdministration/view/surveyid/" . $surveyid . "/gid/" . $aAttributes['gid']);
$groupselecter .= " value='{$link}'>";
$groupselecter .= htmlspecialchars(strip_tags((string) $oGroup->questiongroupl10ns[$language]->group_name));
$groupselecter .= "</option>\n";
}
if ($groupselecter) {
$link = Yii::app()->getController()->createUrl("/surveyAdministration/view/surveyid/" . $surveyid);
if (!isset($gvexist)) {
$groupselecter = "<option selected='selected'>" . gT("Please choose...") . "</option>\n" . $groupselecter;
} else {
$groupselecter .= "<option value='{$link}'>" . gT("None") . "</option>\n";
}
}
return $groupselecter;
}
/**
* Returns a user list. If 'usercontrolSameGroupPolicy' is set and set to true, only users which are in the same
* group as me (--> logged in user) will be returned. Superadmin always gets the full list of users.
*
* @param $outputformat string could be 'onlyuidarray' which only returns array with userids, default is 'fullinfoarray'
* @return array returns a list of user ids (param='onlyuidarray') or a list with full user details (e.g. uid, name, full_name etc.)
*/
function getUserList($outputformat = 'fullinfoarray')
{
if (!empty(Yii::app()->session['loginID'])) {
$myuid = sanitize_int(Yii::app()->session['loginID']);
}
$usercontrolSameGroupPolicy = App()->getConfig('usercontrolSameGroupPolicy');
if (
!Permission::model()->hasGlobalPermission('superadmin', 'read') && isset($usercontrolSameGroupPolicy) &&
$usercontrolSameGroupPolicy == true
) {
if (isset($myuid)) {
$sDatabaseType = Yii::app()->db->getDriverName();
if ($sDatabaseType == 'mssql' || $sDatabaseType == "sqlsrv" || $sDatabaseType == "dblib") {
$sSelectFields = 'users_name,uid,email,full_name,parent_id,CAST(password as varchar) as password';
} else {
$sSelectFields = 'users_name,uid,email,full_name,parent_id,password';
}
// List users from same group as me + all my childs
// a subselect is used here because MSSQL does not like to group by text
// also Postgres does like this one better
$uquery = " SELECT {$sSelectFields} from {{users}} where uid in (
SELECT uid from {{user_in_groups}} where ugid in (
SELECT ugid from {{user_in_groups}} where uid={$myuid}
)
)
UNION
SELECT {$sSelectFields} from {{users}} v where v.parent_id={$myuid}
UNION
SELECT {$sSelectFields} from {{users}} v where uid={$myuid}";
} else {
return array(); // Or die maybe
}
} else {
$uquery = "SELECT * FROM {{users}} ORDER BY uid";
}
$uresult = Yii::app()->db->createCommand($uquery)->query()->readAll(); //Checked
if (count($uresult) == 0 && !empty($myuid)) {
//user is not in a group and usercontrolSameGroupPolicy is activated - at least show their own userinfo
$uquery = "SELECT u.* FROM {{users}} AS u WHERE u.uid=" . $myuid;
$uresult = Yii::app()->db->createCommand($uquery)->query()->readAll(); //Checked
}
$userlist = array();
$userlist[0] = "Reserved for logged in user";
foreach ($uresult as $srow) {
if ($outputformat != 'onlyuidarray') {
if ($srow['uid'] != Yii::app()->session['loginID']) {
$userlist[] = array(
"user" => $srow['users_name'],
"uid" => $srow['uid'],
"email" => $srow['email'],
"password" => $srow['password'],
"full_name" => $srow['full_name'],
"parent_id" => $srow['parent_id']
);
} else {
$userlist[0] = array(
"user" => $srow['users_name'],
"uid" => $srow['uid'],
"email" => $srow['email'],
"password" => $srow['password'],
"full_name" => $srow['full_name'],
"parent_id" => $srow['parent_id']
);
}
} else {
if ($srow['uid'] != Yii::app()->session['loginID']) {
$userlist[] = $srow['uid'];
} else {
$userlist[0] = $srow['uid'];
}
}
}
return $userlist;
}
/**
* Gets all survey infos in one big array including the language specific settings
*
* @param integer $surveyid The survey ID
* @param string $languagecode The language code - if not given the base language of the particular survey is used
* @param boolean $force If true, don't use memoization
* @return array|bool Returns array with survey info or false, if survey does not exist
*/
function getSurveyInfo($surveyid, $languagecode = '', $force = false)
{
static $staticSurveyInfo = array(); // Use some static
if ($force) {
$staticSurveyInfo[$surveyid] = null;
}
$surveyid = sanitize_int($surveyid);
$languagecode = sanitize_languagecode($languagecode);
$thissurvey = false;
$oSurvey = Survey::model()->findByPk($surveyid);
// Do job only if this survey exist
if (!$oSurvey) {
return false;
}
//todo: here ipanonymize is wrong in $oSurvey->aOptions where is that initialized ???
$aSurveyOptions = $oSurvey->aOptions;
// if no language code is set then get the base language one
if ((!isset($languagecode) || $languagecode == '')) {
$languagecode = $oSurvey->language;
}
if (isset($staticSurveyInfo[$surveyid][$languagecode])) {
$thissurvey = $staticSurveyInfo[$surveyid][$languagecode];
} else {
$result = SurveyLanguageSetting::model()->with('survey')->findByPk(array('surveyls_survey_id' => $surveyid, 'surveyls_language' => $languagecode));
if (is_null($result)) {
// When additional language was added, but not saved it does not exists
// We should revert to the base language then
$languagecode = $oSurvey->language;
$result = SurveyLanguageSetting::model()->with('survey')->findByPk(array('surveyls_survey_id' => $surveyid, 'surveyls_language' => $languagecode));
}
if ($result) {
$aSurveyAtrributes = array_replace($result->survey->attributes, $aSurveyOptions);
$thissurvey = array_merge($aSurveyAtrributes, $result->attributes);
$thissurvey['name'] = $thissurvey['surveyls_title'];
$thissurvey['description'] = $thissurvey['surveyls_description'];
$thissurvey['welcome'] = $thissurvey['surveyls_welcometext'];
$thissurvey['datasecurity_notice_label'] = $thissurvey['surveyls_policy_notice_label'];
$thissurvey['datasecurity_error'] = $thissurvey['surveyls_policy_error'];
$thissurvey['datasecurity_notice'] = $thissurvey['surveyls_policy_notice'];
$thissurvey['templatedir'] = $thissurvey['template'];
$thissurvey['adminname'] = $thissurvey['admin'];
$thissurvey['tablename'] = $oSurvey->responsesTableName;
$thissurvey['urldescrip'] = $thissurvey['surveyls_urldescription'];
$thissurvey['url'] = $thissurvey['surveyls_url'];
$thissurvey['expiry'] = $thissurvey['expires'];
$thissurvey['email_invite_subj'] = $thissurvey['surveyls_email_invite_subj'];
$thissurvey['email_invite'] = $thissurvey['surveyls_email_invite'];
$thissurvey['email_remind_subj'] = $thissurvey['surveyls_email_remind_subj'];
$thissurvey['email_remind'] = $thissurvey['surveyls_email_remind'];
$thissurvey['email_confirm_subj'] = $thissurvey['surveyls_email_confirm_subj'];
$thissurvey['email_confirm'] = $thissurvey['surveyls_email_confirm'];
$thissurvey['email_register_subj'] = $thissurvey['surveyls_email_register_subj'];
$thissurvey['email_register'] = $thissurvey['surveyls_email_register'];
$thissurvey['attributedescriptions'] = $result->survey->tokenAttributes;
$thissurvey['attributecaptions'] = $result->attributeCaptions;
$thissurvey['googleanalyticsapikey'] = $oSurvey->getGoogleanalyticsapikey();
if (!isset($thissurvey['adminname'])) {
$thissurvey['adminname'] = Yii::app()->getConfig('siteadminemail');
}
if (!isset($thissurvey['adminemail'])) {
$thissurvey['adminemail'] = Yii::app()->getConfig('siteadminname');
}
if (!isset($thissurvey['urldescrip']) || $thissurvey['urldescrip'] == '') {
$thissurvey['urldescrip'] = $thissurvey['surveyls_url'];
}
if ($result->survey->owner_id == -1 && !empty($oSurvey->oOptions->owner_id)) {
$thissurvey['owner_username'] = User::model()->find("uid=:uid", array(':uid' => $oSurvey->oOptions->owner_id))['users_name'];
} elseif (!empty($result->survey->owner->users_name)) {
$thissurvey['owner_username'] = $result->survey->owner->users_name;
} else {
$thissurvey['owner_username'] = '';
}
$staticSurveyInfo[$surveyid][$languagecode] = $thissurvey;
}
}
$thissurvey['oSurvey'] = $oSurvey;
return $thissurvey;
}
/**
* Returns the default email template texts as array
*
* @param mixed $sLanguage Required language translationb object
* @param string $mode Escape mode for the translation function
* @return array
* @todo Move to defaulttexts helper
*/
function templateDefaultTexts($sLanguage, $mode = 'html', $sNewlines = 'text')
{
$aDefaultTexts = LsDefaultDataSets::getTemplateDefaultTexts($mode, $sLanguage);
if ($sNewlines == 'html') {
$aDefaultTexts = array_map('nl2br', $aDefaultTexts);
}
return $aDefaultTexts;
}
/**
* Compares two elements from an array (passed by the usort function)
* and returns -1, 0 or 1 depending on the result of the comparison of
* the sort order of the group_order and question_order field
* Used by :
* - remotecontrol_handle->export_statistics with merging group and question attributes (all in same array)
* - checkQuestions() in activate_helper function with ?
* @param mixed $a
* @param mixed $b
* @return int
*/
function groupOrderThenQuestionOrder($a, $b)
{
if (isset($a->group['group_order']) && isset($b->group['group_order'])) {
$GroupResult = strnatcasecmp((string) $a->group['group_order'], (string) $b->group['group_order']);
} else {
$GroupResult = "";
}
if ($GroupResult == 0) {
$TitleResult = strnatcasecmp((string) $a["question_order"], (string) $b["question_order"]);
return $TitleResult;
}
return $GroupResult;
}
/**
* @param integer $iSurveyID
* @param integer $qid
* @param integer $newgid
*/
function fixMovedQuestionConditions($qid, $oldgid, $newgid, $iSurveyID = null) //Function rewrites the cfieldname for a question after group change
{
if (!isset($iSurveyID)) {
$iSurveyID = Yii::app()->getConfig('sid');
}
$qid = (int) $qid;
$oldgid = (int) $oldgid;
$newgid = (int) $newgid;
Condition::model()->updateCFieldName($iSurveyID, $qid, $oldgid, $newgid);
// TMSW Condition->Relevance: Call LEM->ConvertConditionsToRelevance() when done
}
/**
* This function returns POST/REQUEST vars, for some vars like SID and others they are also sanitized
* TODO: extends Yii:getParam
*
* @param string $stringname
* @param boolean $bRestrictToString
* @return array|bool|mixed|int|null
*/
function returnGlobal($stringname, $bRestrictToString = false)
{
$urlParam = Yii::app()->request->getParam($stringname);
$aCookies = Yii::app()->request->getCookies();
if (is_null($urlParam) && $stringname != 'sid') {
if (isset($aCookies[$stringname])) {
$urlParam = $aCookies[$stringname];
}
}
$bUrlParamIsArray = is_array($urlParam); // Needed to array map or if $bRestrictToString
if (is_null($urlParam) || $stringname == '' || ($bUrlParamIsArray && $bRestrictToString)) {
return null;
}
if (in_array($stringname, ['sid', 'gid', 'oldqid', 'qid', 'tid', 'lid', 'ugid','thisstep', 'scenario', 'cqid', 'cid', 'qaid', 'scid'])) {
if ($bUrlParamIsArray) {
return array_map("sanitize_int", $urlParam);
} else {
return sanitize_int($urlParam);
}
} elseif ($stringname == "lang" || $stringname == "adminlang") {
if ($bUrlParamIsArray) {
return array_map("sanitize_languagecode", $urlParam);
} else {
return sanitize_languagecode($urlParam);
}
} elseif (
$stringname == "htmleditormode" ||
$stringname == "subaction" ||
$stringname == "questionselectormode" ||
$stringname == "templateeditormode"
) {
if ($bUrlParamIsArray) {
return array_map("sanitize_paranoid_string", $urlParam);
} else {
return sanitize_paranoid_string($urlParam);
}
} elseif ($stringname == "cquestions") {
if ($bUrlParamIsArray) {
return array_map("sanitize_cquestions", $urlParam);
} else {
return sanitize_cquestions($urlParam);
}
}
return $urlParam;
}
function sendCacheHeaders()
{
if (!headers_sent()) {
if (Yii::app()->getConfig('x_frame_options', 'allow') == 'sameorigin') {
header('X-Frame-Options: SAMEORIGIN');
}
header('P3P:CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"'); // this line lets IE7 run LimeSurvey in an iframe
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
header("Cache-Control: no-store, no-cache, must-revalidate"); // HTTP/1.1
header('Content-Type: text/html; charset=utf-8');
}
}
/**
* @param integer $iSurveyID The Survey ID
* @param string $sFieldCode Field code of the particular field
* @param string $sValue The stored response value
* @param string $sLanguage Initialized limesurvey_lang object for the resulting response data
* @return string
*/
function getExtendedAnswer($iSurveyID, $sFieldCode, $sValue, $sLanguage)
{
if ($sValue == null || $sValue == '') {
return '';
}
$survey = Survey::model()->findByPk($iSurveyID);
//Fieldcode used to determine question, $sValue used to match against answer code
//Returns NULL if question type does not suit
if (strpos($sFieldCode, "{$iSurveyID}X") === 0) {
//Only check if it looks like a real fieldcode
$fieldmap = createFieldMap($survey, 'short', false, false, $sLanguage);
if (isset($fieldmap[$sFieldCode])) {
$fields = $fieldmap[$sFieldCode];
} else {
return '';
}
// If it is a comment field there is nothing to convert here
if ($fields['aid'] == 'comment') {
return $sValue;