/
common.php
3405 lines (3088 loc) · 133 KB
/
common.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
/*
#############################################################
# >>> PHPSurveyor #
#############################################################
# > Author: Jason Cleeland #
# > E-mail: jason@cleeland.org #
# > Mail: Box 99, Trades Hall, 54 Victoria St, #
# > CARLTON SOUTH 3053, AUSTRALIA #
# > Date: 20 February 2003 #
# #
# This set of scripts allows you to develop, publish and #
# perform data-entry on surveys. #
#############################################################
# #
# Copyright (C) 2003 Jason Cleeland #
# #
# This program is free software; you can redistribute #
# it and/or modify it under the terms of the GNU General #
# Public License Version 2 as published by the Free #
# Software Foundation. #
# #
# #
# This program 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., 59 Temple Place - #
# Suite 330, Boston, MA 02111-1307, USA. #
#############################################################
*/
//Ensure script is not run directly, avoid path disclosure
if (!isset($dbprefix)) {die("Cannot run this script directly");}
$versionnumber = "1.45a";
$dbversionnumber = 111;
if ($debug==1) {error_reporting(E_ALL);} //For debug purposes - switch on in config.phh
##################################################################################
## DO NOT EDIT BELOW HERE
##################################################################################
require_once (dirname(__FILE__).'/classes/adodb/adodb.inc.php');
require_once (dirname(__FILE__).'/classes/phpmailer/class.phpmailer.php');
require_once (dirname(__FILE__).'/classes/php-gettext/gettextinc.php');
require_once (dirname(__FILE__).'/classes/core/surveytranslator.php');
require_once (dirname(__FILE__).'/classes/core/sanitize.php');
$dbprefix=strtolower($dbprefix);
define("_PHPVERSION", phpversion());
if($_SERVER['SERVER_SOFTWARE'] == "Xitami") //Deal with Xitami Issue
{
$_SERVER['PHP_SELF'] = substr($_SERVER['SERVER_URL'], 0, -1) .$_SERVER['SCRIPT_NAME'];
}
/*
* $sourcefrom variable checks the location of the current script against
* the administration directory, and if the current script is running
* in the administration directory, it is set to "admin". Otherwise it is set
* to "public". When $sourcefrom is "admin" certain administration only functions
* are loaded.
*/
if ((!isset($rootsymlinked)) || $rootsymlinked==0 ) {$scriptlocation=realpath(".");}
elseif ($rootsymlinked==1) {$scriptlocation = dirname($_SERVER['SCRIPT_FILENAME']);}
else {
echo "ERROR: Cannot locate path - the PHP server does not have a setting for realpath or SCRIPT_FILENAME. Contact our support at phpsurveyor.org for assistance!";
exit;
}
$slashlesspath=str_replace(array("\\", "/"), "", $scriptlocation);
$slashlesshome=str_replace(array("\\", "/"), "", $homedir);
// Uncomment the following line for debug purposes
// echo $slashlesspath." - ".$slashlesshome;
if (eregi($slashlesshome, $slashlesspath) || eregi("dump", $_SERVER['PHP_SELF'])) {
if (!eregi($slashlesshome."install", $slashlesspath))
{
$sourcefrom="admin";
}
else
{
$sourcefrom="install";
}
} else {
$sourcefrom="public";
}
//BEFORE SESSIONCONTOL BECAUSE OF THE CONNECTION
//CACHE DATA
$connect=&ADONewConnection($databasetype);
$database_exists = FALSE;
switch ($databasetype)
{
case "mysql" :if ($databaseport!="default") {$dbport="$databaselocation:$databaseport";}
else {$dbport=$databaselocation;}
break;
case "odbc_mssql": $dbport="Driver={SQL Server};Server=$databaselocation;Database=".$databasename;
break;
default: echo "Unknown database type"; die;
}
if (@$connect->Connect($dbport, $databaseuser, $databasepass, $databasename))
{ $database_exists = TRUE;}
else {
$connect->database = '';
if ($databasetype=='odbc_mssql') {$dbport="Driver={SQL Server};Server=$databaselocation;";}
$connect->Connect($dbport, $databaseuser, $databasepass);
}
# TODO: seems to be defaulting to ADODB_FETCH_NUM. New behaviour - can't see why
$connect->SetFetchMode(ADODB_FETCH_ASSOC);
$dbexistsbutempty=(checkifemptydb() && $database_exists);
// The following line is for mysql debug purposes
//$tmpresult=@mysql_query("SET SESSION SQL_MODE='STRICT_ALL_TABLES'");
if ($databasetype=='mysql') {$connect->Execute("SET CHARACTER SET 'utf8'");}
//Admin menus and standards
//IF THIS IS AN ADMIN SCRIPT, RUN THE SESSIONCONTROL SCRIPT
if ($sourcefrom == "admin")
{
include(dirname(__FILE__)."/admin/sessioncontrol.php");
/**
* @param string $htmlheader
* This is the html header text for all administration pages
*
*/
$htmlheader = getAdminHeader();
}
//SET LANGUAGE DIRECTORY
if ($sourcefrom == "admin")
{
$langdir="$publicurl/locale/".$_SESSION['adminlang']."/help";
$langdirlocal="$rootdir/locale/".$_SESSION['adminlang']."/help";
if (!is_dir($langdirlocal)) // is_dir only works on local dirs
{
$langdir="$publicurl/locale/en/help"; //default to english if there is no matching language dir
}
}
//SET LOCAL TIME
$localtimedate=(strftime("%Y-%m-%d %H:%M", mktime(date("H")+$timeadjust)));
// SITE STYLES
$setfont = "<font size='2' face='verdana'>";
$singleborderstyle = "style='border: 1px solid #111111'";
/**
* showadminmenu() function returns html text for the administration button bar
* @global string $accesscontrol
* @global string $homedir
* @global string $scriptname
* @global string $surveyid
* @global string $setfont
* @global string $imagefiles
* @return string $adminmenu
*/
function showadminmenu()
{
global $accesscontrol, $homedir, $scriptname, $surveyid, $setfont, $imagefiles, $clang;
$adminmenu = "<table width='100%' border='0' bgcolor='#DDDDDD'>\n"
. "\t<tr>\n"
. "\t\t<td>\n"
. "\t\t\t<table width='100%' style='border: 1px solid #555555' cellpadding='1' cellspacing='0'>\n"
. "\t\t\t<tr bgcolor='#555555'>\n"
. "\t\t\t\t<td colspan='2' height='8' align='left'>\n"
. "\t\t\t\t<font size='1' color='white'><strong>".$clang->gT("Administration")."</strong>";
if(isset($_SESSION['loginID']))
{
$adminmenu .= " -- ".$clang->gT("Logged in as"). ": <strong>". $_SESSION['user'] ."</strong>"."\n";
}
$adminmenu .= "\t\t\t\t</font></td>\n"
. "\t\t\t</tr>\n"
. "\t\t\t<tr bgcolor='#999999'>\n"
. "\t\t\t\t<td>\n"
. "\t\t\t\t\t<a href=\"#\" onClick=\"window.open('$scriptname', '_top')\"" .
"onmouseout=\"hideTooltip()\" onmouseover=\"showTooltip(event,'".$clang->gT("Default Administration Page", "js")."');return false\">" .
"<img src='$imagefiles/home.png' name='HomeButton' alt='".$clang->gT("Default Administration Page")."' "
."title=''" ."align='left' /></a>\n";
$adminmenu .= "\t\t\t\t\t<img src='$imagefiles/blank.gif' alt='' width='11' align='left' />\n"
. "\t\t\t\t\t<img src='$imagefiles/seperator.gif' alt='' align='left' />\n";
// edit users
$adminmenu .= "\t\t\t\t\t<a href=\"#\" onClick=\"window.open('$scriptname?action=editusers', '_top')\"" .
"onmouseout=\"hideTooltip()\""
. "onmouseover=\"showTooltip(event,'".$clang->gT("Create/Edit Users", "js")."');return false\">" .
"<img src='$imagefiles/security.png' name='AdminSecurity'"
." title='' alt='".$clang->gT("Create/Edit Users")."' align='left' /></a>";
$adminmenu .="<a href=\"#\" onclick=\"window.open('$scriptname?action=editusergroups', '_top')\""
. "onmouseout=\"hideTooltip()\""
. "onmouseover=\"showTooltip(event,'".$clang->gT("Create/Edit Groups", "js")."');return false\">" .
"<img src='$imagefiles/usergroup.png' title='' align='left' alt='".$clang->gT("Create/Edit Groups")."' /></a>\n" ;
// check settings
//"\t\t\t\t\t<img src='$imagefiles/blank.gif' alt='' width='34' align='left'>\n".
$adminmenu .= "<a href=\"#\" onClick=\"window.open('$scriptname?action=checksettings', '_top')\""
. "onmouseout=\"hideTooltip()\""
. "onmouseover=\"showTooltip(event,'".$clang->gT("Check Settings", "js")."');return false\">"
. "\t\t\t\t\t<img src='$imagefiles/summary.png' name='CheckSettings' title='"
. "' alt='". $clang->gT("Check Settings")."' align='left' /></a>"
. "\t\t\t\t\t<img src='$imagefiles/seperator.gif' alt='' align='left' border='0' hspace='0' />\n";
// check data cosistency
if($_SESSION['USER_RIGHT_CONFIGURATOR'] == 1)
{
$adminmenu .= "<a href=\"#\" onClick=\"window.open('$scriptname?action=checkintegrity', '_top')\"".
"onmouseout=\"hideTooltip()\""
."onmouseover=\"showTooltip(event,'".$clang->gT("Check Data Integrity", "js")."');return false\">".
"<img src='$imagefiles/checkdb.png' name='CheckDataINtegrity' title='' alt='".$clang->gT("Check Data Integrity")."' align='left' /></a>\n";
}
else
{
$adminmenu .= "\t\t\t\t\t<img src='$imagefiles/blank.gif' alt='' width='40' align='left' />\n";
}
// list surveys
$adminmenu .= "<a href=\"#\" onClick=\"window.open('$scriptname?action=listsurveys', '_top')\""
."onmouseout=\"hideTooltip()\""
."onmouseover=\"showTooltip(event,'".$clang->gT("List Surveys", "js")."');return false\">\n"
."<img src='$imagefiles/surveylist.png' name='ListSurveys' title=''"
." alt='".$clang->gT("List Surveys")."' align='left' onClick=\"window.open('$scriptname?action=listsurveys', '_top')\" />"
."</a>" ;
// db backup & label editor
if($_SESSION['USER_RIGHT_CONFIGURATOR'] == 1)
{
$adminmenu .= "<a href=\"#\""
. "onClick=\"window.open('dumpdb.php?action=dumpdb', '_top')\""
. "onmouseout=\"hideTooltip()\""
. "onmouseover=\"showTooltip(event,'".$clang->gT("Backup Entire Database", "js")."');return false\">"
."<img src='$imagefiles/backup.png' name='ExportDB' title='' alt='". $clang->gT("Backup Entire Database")."($surveyid)' align='left' />"
."</a>\n"
. "\t\t\t\t\t<img src='$imagefiles/seperator.gif' alt='' align='left' border='0' hspace='0' />\n";
}
else
{
$adminmenu .= "\t\t\t\t\t<img src='$imagefiles/blank.gif' alt='' width='40' align='left' />\n";
}
if($_SESSION['USER_RIGHT_MANAGE_LABEL'] == 1)
{
$adminmenu .= "<a href=\"#\" onClick=\"window.open('$scriptname?action=labels', '_top')\""
. "onmouseout=\"hideTooltip()\""
. "onmouseover=\"showTooltip(event,'".$clang->gT("Edit/Add Label Sets", "js")."');return false\">" .
"<img src='$imagefiles/labels.png' align='left' name='LabelsEditor' title='' alt='". $clang->gT("Edit/Add Label Sets")."' /></a>\n"
. "\t\t\t\t\t<img src='$imagefiles/seperator.gif' alt='' align='left' border='0' hspace='0' />\n";
}
else
{
$adminmenu .= "\t\t\t\t\t<img src='$imagefiles/blank.gif' alt='' width='40' align='left' />\n";
}
if($_SESSION['USER_RIGHT_MANAGE_TEMPLATE'] == 1)
{
$adminmenu .= "<a href=\"#\" " .
"onClick=\"window.open('$scriptname?action=templates', '_top')\""
. "onmouseout=\"hideTooltip()\""
. "onmouseover=\"showTooltip(event,'".$clang->gT("Template Editor", "js")."');return false\">" .
"<img src='$imagefiles/templates.png' name='EditTemplates' title='' alt='". $clang->gT("Template Editor")."' align='left' /></a>\n"
. "\t\t\t\t</td>\n";
}
if(isset($_SESSION['loginID'])) //ADDED by Moses to prevent errors by reading db while not logged in.
{
$adminmenu .= "\t\t\t\t<td align='right' width='430'>\n"
. "<a href=\"#\" onClick=\"showhelp('show')\""
. "onmouseout=\"hideTooltip()\""
. "onmouseover=\"showTooltip(event,'".$clang->gT("Show Help", "js")."');return false\">"
. "<img src='$imagefiles/showhelp.png' name='ShowHelp' title=''"
. "alt='". $clang->gT("Show Help")."' align='right' /></a>"
. "\t\t\t\t\t<a href=\"#\" onClick=\"window.open('$scriptname?action=logout', '_top')\""
. "onmouseout=\"hideTooltip()\""
. "onmouseover=\"showTooltip(event,'".$clang->gT("Logout", "js")."');return false\">"
. "<img src='$imagefiles/logout.png' name='Logout'"
. "title='' alt='".$clang->gT("Logout")."' align='right' /></a>"
. "\t\t\t\t\t<img src='$imagefiles/seperator.gif' alt='' align='right' border='0' hspace='0' />\n";
if($_SESSION['USER_RIGHT_CREATE_SURVEY'] == 1)
{
$adminmenu .= "<a href=\"#\" onClick=\"window.open('$scriptname?action=newsurvey', '_top')\""
. "onmouseout=\"hideTooltip()\""
. "onmouseover=\"showTooltip(event,'".$clang->gT("Create or Import New Survey", "js")."');return false\">" .
"<img src='$imagefiles/add.png' align='right' name='AddSurvey' title='' alt='". $clang->gT("Create or Import New Survey")."' /></a>\n";
}
$adminmenu .= "\t\t\t\t\t<font class=\"boxcaption\">".$clang->gT("Surveys").":</font>"
. "\t\t\t\t\t<select class=\"listboxsurveys\""
. "onChange=\"window.open(this.options[this.selectedIndex].value,'_top')\">\n"
. getsurveylist()
. "\t\t\t\t\t</select>\n"
. "\t\t\t\t</td>\n";
}
$adminmenu .= "\t\t\t</tr>\n"
. "\t\t</table>\n"
. "\t</td>\n"
. "</tr>\n"
. "</table>\n";
return $adminmenu;
}
//DATA TYPES
$qtypeselect = getqtypelist();
function &db_execute_num($sql,$inputarr=false)
{
global $connect;
// Todo: Set fetchmode to previous state after changing
//$oldfetchmode=
$connect->SetFetchMode(ADODB_FETCH_NUM);
$dataset=$connect->Execute($sql,$inputarr);
//$connect->SetFetchMode($oldfetchmode);
return $dataset;
}
function &db_select_limit_num($sql,$numrows=-1,$offset=-1,$inputarr=false)
{
global $connect;
$dataset=$connect->SelectLimit($sql,$numrows=-1,$offset=-1,$inputarr=false) or die($sql);
return $dataset;
}
function &db_execute_assoc($sql,$inputarr=false)
{
global $connect;
// Todo: Set fetchmode to previous state after changing
// $oldfetchmode=
$connect->SetFetchMode(ADODB_FETCH_ASSOC);
$dataset=$connect->Execute($sql,$inputarr) or die($sql);
// $connect->SetFetchMode($oldfetchmode);
return $dataset;
}
function &db_select_limit_assoc($sql,$numrows=-1,$offset=-1,$inputarr=false)
{
global $connect;
$connect->SetFetchMode(ADODB_FETCH_ASSOC);
$dataset=$connect->SelectLimit($sql,$numrows=-1,$offset=-1,$inputarr=false) or die($sql);
return $dataset;
}
function db_quote_id($id)
{
global $connect;
$quote = $connect->nameQuote;
return $quote.str_replace($quote,$quote.$quote,$id).$quote;
}
function db_quote($str)
{
global $connect;
return $connect->escape($str);
}
function db_table_name($name)
{
global $dbprefix;
return db_quote_id($dbprefix.$name);
}
/*
* Return a sql statement for finding LIKE named tables
*/
function db_select_tables_like($table)
{
global $connect;
switch ($connect->databaseType) {
case 'mysql' :
return "SHOW TABLES LIKE '$table'";
case 'odbc_mssql' :
return "SELECT * FROM INFORMATION_SCHEMA.TABLES where TABLE_TYPE='BASE TABLE' and TABLE_NAME LIKE '$table'";
default: die ("Couldn't create 'select tables like' query for connection type '$connect->databaseType'");
}
}
/*
* Return a boolean stating if the table(s) exist(s)
* Accepts '%' in names since it uses the 'like' statement
*/
function db_tables_exist($table)
{
global $connect;
$surveyHasTokensTblQ = db_select_tables_like("$table");
$surveyHasTokensTblResult = db_execute_num($surveyHasTokensTblQ);
if ($surveyHasTokensTblResult->RecordCount() >= 1)
{
return TRUE;
}
else
{
return FALSE;
}
}
/**
* getsurveylist() Queries the database (survey table) for a list of existing surveys
* @global string $surveyid
* @global string $dbprefix
* @global string $scriptname
* @return string This string is returned containing <option></option> formatted list of existing surveys
*
*/
function getsurveylist()
{
global $surveyid, $dbprefix, $scriptname, $connect, $clang;
$surveyidquery = "SELECT a.sid, a.owner_id, surveyls_title, surveyls_description, a.admin, a.active, surveyls_welcometext, a.useexpiry, a.expires, "
. "a.adminemail, a.private, a.faxto, a.format, a.template, a.url, "
. "a.language, a.datestamp, a.ipaddr, a.refurl, a.usecookie, a.notification, a.allowregister, a.attribute1, a.attribute2, "
. "a.allowsave, a.autoredirect, a.allowprev, a.datecreated FROM ".db_table_name('surveys')." AS a INNER JOIN ".db_table_name('surveys_rights')." AS b ON a.sid = b.sid "
. "INNER JOIN ".db_table_name('surveys_languagesettings')." on (surveyls_survey_id=a.sid and surveyls_language=a.language) "
. "WHERE b.uid =".$_SESSION['loginID'];//CHANGED by Moses only with rights
$surveyidresult = db_execute_num($surveyidquery);
if (!$surveyidresult) {return "Database Error";}
$surveyselecter = "";
$surveynames = $surveyidresult->GetRows();
if ($surveynames)
{
foreach($surveynames as $sv)
{
$surveyselecter .= "\t\t\t<option";
if($_SESSION['loginID'] == $sv[1]) {$surveyselecter .= " style=\"font-weight: bold;\"";}
if ($sv[0] == $surveyid) {$surveyselecter .= " selected"; $svexist = 1;}
$surveyselecter .=" value='$scriptname?sid=$sv[0]'>$sv[2]</option>\n";
}
}
if (!isset($svexist)) {$surveyselecter = "\t\t\t<option selected>".$clang->gT("Please Choose...")."</option>\n".$surveyselecter;}
else {$surveyselecter = "\t\t\t<option value='$scriptname?sid='>".$clang->gT("None")."</option>\n".$surveyselecter;}
return $surveyselecter;
}
/**
* getquestions() queries the database for a list of all questions matching the current survey sid
* @global string $surveyid
* @global string $gid
* @global string $qid
* @global string $dbprefix
* @global string $scriptname
* @return This string is returned containing <option></option> formatted list of questions to current survey
*/
function getquestions()
{
global $surveyid, $gid, $qid, $dbprefix, $scriptname, $connect, $clang;
//MOD for multilanguage surveys
$s_lang = GetBaseLanguageFromSurveyID($surveyid);
$qquery = 'SELECT * FROM '.db_table_name('questions')." WHERE sid=$surveyid AND gid=$gid AND language='{$s_lang}'";
$qresult = db_execute_assoc($qquery);
$qrows = $qresult->GetRows();
// Perform a case insensitive natural sort on group name then question title of a multidimensional array
usort($qrows, 'CompareGroupThenTitle');
if (!isset($questionselecter)) {$questionselecter="";}
foreach ($qrows as $qrow)
{
$qrow['title'] = htmlspecialchars($qrow['title']);
$questionselecter .= "\t\t<option value='$scriptname?sid=$surveyid&gid=$gid&qid={$qrow['qid']}'";
if ($qid == $qrow['qid']) {$questionselecter .= " selected"; $qexists="Y";}
$questionselecter .=">{$qrow['title']}:";
$questionselecter .= " ";
$question=strip_tags($qrow['question']);
if (strlen($question)<35)
{
$questionselecter .= htmlspecialchars($question);
}
else
{
$questionselecter .= htmlspecialchars(substr($question, 0, 35))."..";
}
$questionselecter .= "</option>\n";
}
if (!isset($qexists))
{
$questionselecter = "\t\t<option selected>".$clang->gT("Please Choose...")."</option>\n".$questionselecter;
}
return $questionselecter;
}
// Gets number of groups inside a particular survey
function getGroupSum($surveyid, $lang)
{
global $surveyid,$dbprefix ;
$sumquery3 = "SELECT * FROM ".db_table_name('groups')." WHERE sid=$surveyid AND language='".$lang."'"; //Getting a count of questions for this survey
$sumresult3 = db_execute_assoc($sumquery3);
$groupscount = $sumresult3->RecordCount();
return $groupscount ;
}
// Gets number of questions inside a particular group
function getQuestionSum($surveyid, $groupid)
{
global $surveyid,$dbprefix ;
$s_lang = GetBaseLanguageFromSurveyID($surveyid);
$sumquery3 = "SELECT * FROM ".db_table_name('questions')." WHERE gid=$groupid and sid=$surveyid AND language='{$s_lang}'"; //Getting a count of questions for this survey
$sumresult3 = db_execute_assoc($sumquery3);
$questionscount = $sumresult3->RecordCount();
return $questionscount ;
}
/**
* getMaxgrouporder($surveyid) queries the database for the maximum sortorder of a group.
* @global string $surveyid
*/
function getMaxgrouporder($surveyid)
{
global $surveyid ;
$s_lang = GetBaseLanguageFromSurveyID($surveyid);
$max_sql = "SELECT max( group_order ) AS max FROM ".db_table_name('groups')." WHERE sid =$surveyid AND language='{$s_lang}'" ;
$max_result =db_execute_assoc($max_sql) ;
$maxrow = $max_result->FetchRow() ;
$current_max = $maxrow['max'];
if($current_max=="")
{
return "0" ;
}
else return ++$current_max ;
}
/**
* getMaxquestionorder($gid) queries the database for the maximum sortorder of a question.
* @global string $surveyid
*/
function getMaxquestionorder($gid)
{
global $surveyid ;
$s_lang = GetBaseLanguageFromSurveyID($surveyid);
$max_sql = "SELECT max( question_order ) AS max FROM ".db_table_name('questions')." WHERE gid='$gid' AND language='$s_lang'";
// echo "debug: ".$max_sql."<br />" and die;
$max_result =db_execute_assoc($max_sql) ;
$maxrow = $max_result->FetchRow() ;
$current_max = $maxrow['max'];
if($current_max=="")
{
return "0" ;
}
else return ++$current_max ;
}
/**
* getanswers() queries the database for a list of all answers matching the current question qid
* @global string $surveyid
* @global string $gid
* @global string $qid
* @global string $dbprefix
* @global string $code
* @return This string is returned containing <option></option> formatted list of answers matching current qid
*/
function getanswers()
{
global $surveyid, $gid, $qid, $code, $dbprefix, $connect, $clang;
$s_lang = GetBaseLanguageFromSurveyID($surveyid);
$aquery = "SELECT code, answer FROM ".db_table_name('answers')." WHERE qid=$qid AND language='$s_lang' ORDER BY sortorder, answer";
$aresult = db_execute_assoc($aquery);
$answerselecter = "";
while ($arow = $aresult->FetchRow())
{
$answerselecter .= "\t\t<option value='$scriptname?sid=$surveyid&gid=$gid&qid=$qid&code={$arow['code']}'";
if ($code == $arow['code']) {$answerselecter .= " selected"; $aexists="Y";}
$answerselecter .= ">{$arow['code']}: {$arow['answer']}</option>\n";
}
if (!$aexists) {$answerselecter = "\t\t<option selected>".$clang->gT("Please Choose...")."</option>\n".$answerselecter;}
return $answerselecter;
}
/**
* getqtypelist() Returnst list of question types available in PHPSurveyor. Edit this if you are adding a new
* question type
* @global string $publicurl
* @global string $sourcefrom
* @param string $SelectedCode Value of the Question Type (defaults to "T")
* @param string $ReturnType Type of output from this function (defaults to selector)
* @return depending on $ReturnType param, returns a straight "array" of question types, or an <option></option> list
*/
function getqtypelist($SelectedCode = "T", $ReturnType = "selector")
{
global $publicurl;
global $sourcefrom, $clang;
if ($sourcefrom == "admin")
{
$qtypes = array(
"5"=>$clang->gT("5 Point Choice"),
"A"=>$clang->gT("Array (5 Point Choice)"),
"B"=>$clang->gT("Array (10 Point Choice)"),
"C"=>$clang->gT("Array (Yes/No/Uncertain)"),
"D"=>$clang->gT("Date"),
"E"=>$clang->gT("Array (Increase, Same, Decrease)"),
"F"=>$clang->gT("Array (Flexible Labels)"),
"G"=>$clang->gT("Gender"),
"H"=>$clang->gT("Array (Flexible Labels) by Column"),
"I"=>$clang->gT("Language Switch"),
"L"=>$clang->gT("List (Radio)"),
"M"=>$clang->gT("Multiple Options"),
"N"=>$clang->gT("Numerical Input"),
"O"=>$clang->gT("List With Comment"),
"P"=>$clang->gT("Multiple Options With Comments"),
"Q"=>$clang->gT("Multiple Short Text"),
"R"=>$clang->gT("Ranking"),
"S"=>$clang->gT("Short free text"),
"T"=>$clang->gT("Long free text"),
"U"=>$clang->gT("Huge Free Text"),
"W"=>$clang->gT("List (Flexible Labels) (Dropdown)"),
"X"=>$clang->gT("Boilerplate Question"),
"Y"=>$clang->gT("Yes/No"),
"Z"=>$clang->gT("List (Flexible Labels) (Radio)"),
"!"=>$clang->gT("List (Dropdown)")
// "^"=>$clang->gT("Slider"),
);
asort($qtypes);
if ($ReturnType == "array") {return $qtypes;}
$qtypeselecter = "";
foreach($qtypes as $TypeCode=>$TypeDescription)
{
$qtypeselecter .= "\t\t<option value='$TypeCode'";
if ($SelectedCode == $TypeCode) {$qtypeselecter .= " selected";}
$qtypeselecter .= ">$TypeDescription</option>\n";
}
return $qtypeselecter;
}
}
/**
* getNotificationlist() returns different options for notifications
* @param string $notificationcode - the currently selected one
* @return This string is returned containing <option></option> formatted list of notification methods for current survey
*/
function getNotificationlist($notificationcode)
{
global $clang;
$ntypes = array(
"0"=>$clang->gT("No email notification"),
"1"=>$clang->gT("Basic email notification"),
"2"=>$clang->gT("Detailed email notification with result codes")
);
if (!isset($ntypeselector)) {$ntypeselector="";}
foreach($ntypes as $ntcode=>$ntdescription)
{
$ntypeselector .= "\t\t<option value='$ntcode'";
if ($notificationcode == $ntcode) {$ntypeselector .= " selected";}
$ntypeselector .= ">$ntdescription</option>\n";
}
return $ntypeselector;
}
/**
* getgrouplist() queries the database for a list of all groups matching the current survey sid
* @global string $surveyid
* @global string $dbprefix
* @global string $scriptname
* @param string $gid - the currently selected gid/group
* @return This string is returned containing <option></option> formatted list of groups to current survey
*/
function getgrouplist($gid)
{
global $surveyid, $dbprefix, $scriptname, $connect, $clang;
$groupselecter="";
if (!$surveyid) {$surveyid=$_POST['sid'];}
$s_lang = GetBaseLanguageFromSurveyID($surveyid);
$gidquery = "SELECT gid, group_name FROM ".db_table_name('groups')." WHERE sid='{$surveyid}' AND language='{$s_lang}' ORDER BY group_order";
//
$gidresult = db_execute_num($gidquery) or die("Couldn't get group list in common.php<br />$gidquery<br />".htmlspecialchars($connect->ErrorMsg()));
while($gv = $gidresult->FetchRow())
{
$groupselecter .= "\t\t<option";
if ($gv[0] == $gid) {$groupselecter .= " selected"; $gvexist = 1;}
$groupselecter .= " value='$scriptname?sid=$surveyid&gid=$gv[0]'>".htmlspecialchars($gv[1])."</option>\n";
}
if ($groupselecter)
{
if (!isset($gvexist)) {$groupselecter = "\t\t<option selected>".$clang->gT("Please Choose...")."</option>\n".$groupselecter;}
else {$groupselecter .= "\t\t<option value='$scriptname?sid=$surveyid&gid='>".$clang->gT("None")."</option>\n";}
}
return $groupselecter;
}
function getgrouplist2($gid)
{
global $surveyid, $dbprefix, $connect, $clang;
$groupselecter = "";
if (!$surveyid) {$surveyid=$_POST['sid'];}
$s_lang = GetBaseLanguageFromSurveyID($surveyid);
$gidquery = "SELECT gid, group_name FROM ".db_table_name('groups')." WHERE sid=$surveyid AND language='{$s_lang}' ORDER BY group_order";
$gidresult = db_execute_num($gidquery) or die("Plain old did not work!");
while ($gv = $gidresult->FetchRow())
{
$groupselecter .= "\t\t<option";
if ($gv[0] == $gid) {$groupselecter .= " selected"; $gvexist = 1;}
$groupselecter .= " value='$gv[0]'>".htmlspecialchars($gv[1])."</option>\n";
}
if ($groupselecter)
{
if (!$gvexist) {$groupselecter = "\t\t<option selected>".$clang->gT("Please Choose...")."</option>\n".$groupselecter;}
else {$groupselecter .= "\t\t<option value=''>".$clang->gT("None")."</option>\n";}
}
return $groupselecter;
}
function getgrouplist3($gid)
{
global $surveyid, $dbprefix, $connect;
if (!$surveyid) {$surveyid=$_POST['sid'];}
$groupselecter = "";
$s_lang = GetBaseLanguageFromSurveyID($surveyid);
$gidquery = "SELECT gid, group_name FROM ".db_table_name('groups')." WHERE sid=$surveyid AND language='{$s_lang}' ORDER BY group_order";
$gidresult = db_execute_num($gidquery) or die("Plain old did not work!");
while ($gv = $gidresult->FetchRow())
{
$groupselecter .= "\t\t<option";
if ($gv[0] == $gid) {$groupselecter .= " selected"; $gvexist = 1;}
$groupselecter .= " value='$gv[0]'>".htmlspecialchars($gv[1])."</option>\n";
}
return $groupselecter;
}
function getgrouplistlang($gid, $language)
{
global $surveyid, $scriptname, $connect, $clang;
$groupselecter="";
if (!$surveyid) {$surveyid=$_POST['sid'];}
$gidquery = "SELECT gid, group_name FROM ".db_table_name('groups')." WHERE sid=$surveyid AND language='".$language."' ORDER BY group_order";
$gidresult = db_execute_num($gidquery) or die("Couldn't get group list in common.php<br />$gidquery<br />".htmlspecialchars($connect->ErrorMsg()));
while($gv = $gidresult->FetchRow())
{
$groupselecter .= "\t\t<option";
if ($gv[0] == $gid) {$groupselecter .= " selected"; $gvexist = 1;}
$groupselecter .= " value='$scriptname?sid=$surveyid&gid=$gv[0]'>".htmlspecialchars($gv[1])."</option>\n";
}
if ($groupselecter)
{
if (!isset($gvexist)) {$groupselecter = "\t\t<option selected>".$clang->gT("Please Choose...")."</option>\n".$groupselecter;}
else {$groupselecter .= "\t\t<option value='$scriptname?sid=$surveyid&gid='>".$clang->gT("None")."</option>\n";}
}
return $groupselecter;
}
function getuserlist()
{
global $dbprefix, $connect;
$uquery = "SELECT * FROM ".db_table_name('users')." ORDER BY uid";
$uresult = db_execute_assoc($uquery);
$userlist = array();
while ($srow = $uresult->FetchRow())
{
$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'], "create_survey"=>$srow['create_survey'], "configurator"=>$srow['configurator'], "create_user"=>$srow['create_user'], "delete_user"=>$srow['delete_user'], "move_user"=>$srow['move_user'], "manage_template"=>$srow['manage_template'], "manage_label"=>$srow['manage_label']); //added by Dennis modified by Moses
}
return $userlist;
}
function gettemplatelist()
{
global $publicdir;
if (!$publicdir) {$publicdir=dirname(getcwd());}
$tloc="$publicdir/templates";
if ($handle = opendir($tloc))
{
while (false !== ($file = readdir($handle)))
{
if (!is_file("$tloc/$file") && $file != "." && $file != ".." && $file!=".svn")
{
$list_of_files[] = $file;
}
}
closedir($handle);
}
usort($list_of_files, 'StandardSort');
return $list_of_files;
}
function getSurveyInfo($surveyid, $languagecode='')
// Gets all survey infos in one big array including the language specific settings
// if $languagecode is not set then the base language from the survey is used
//
{
global $dbprefix, $siteadminname, $siteadminemail, $connect;
// if no language code is set then get the base language one
if (!isset($languagecode) || $languagecode=='')
{
$languagecode=GetBaseLanguageFromSurveyID($surveyid);;
}
$query="SELECT * FROM ".db_table_name('surveys')." WHERE sid=$surveyid";
$result=db_execute_assoc($query) or die ("Couldn't access surveys<br />$query<br />".htmlspecialchars($connect->ErrorMsg()));
$query2="SELECT * FROM ".db_table_name('surveys_languagesettings')." WHERE surveyls_survey_id=$surveyid and surveyls_language='$languagecode'";
$result2=db_execute_assoc($query2) or die ("Couldn't access surveys<br />$query<br />".htmlspecialchars($connect->ErrorMsg()));
while ($row=$result->FetchRow())
{
$row2 = $result2->FetchRow();
$thissurvey=array("name"=>$row2['surveyls_title'],
"description"=>$row2['surveyls_description'],
"welcome"=>$row2['surveyls_welcometext'],
"templatedir"=>$row['template'],
"adminname"=>$row['admin'],
"adminemail"=>$row['adminemail'],
"active"=>$row['active'],
"useexpiry"=>$row['useexpiry'],
"expiry"=>$row['expires'],
"private"=>$row['private'],
"faxto"=>$row['faxto'],
"template"=>$row['template'],
"tablename"=>$dbprefix."survey_".$row['sid'],
"url"=>$row['url'],
"urldescrip"=>$row2['surveyls_urldescription'],
"format"=>$row['format'],
"language"=>$row['language'],
"datestamp"=>$row['datestamp'],
"ipaddr"=>$row['ipaddr'],
"refurl"=>$row['refurl'],
"usecookie"=>$row['usecookie'],
"sendnotification"=>$row['notification'],
"allowregister"=>$row['allowregister'],
"attribute1"=>$row['attribute1'],
"attribute2"=>$row['attribute2'],
"email_invite_subj"=>$row2['surveyls_email_invite_subj'],
"email_invite"=>$row2['surveyls_email_invite'],
"email_remind_subj"=>$row2['surveyls_email_remind_subj'],
"email_remind"=>$row2['surveyls_email_remind'],
"email_confirm_subj"=>$row2['surveyls_email_confirm_subj'],
"email_confirm"=>$row2['surveyls_email_confirm'],
"email_register_subj"=>$row2['surveyls_email_register_subj'],
"email_register"=>$row2['surveyls_email_register'],
"allowsave"=>$row['allowsave'],
"autonumber_start"=>$row['autonumber_start'],
"autoredirect"=>$row['autoredirect'],
"allowprev"=>$row['allowprev']);
if (!$thissurvey['adminname']) {$thissurvey['adminname']=$siteadminname;}
if (!$thissurvey['adminemail']) {$thissurvey['adminemail']=$siteadminemail;}
if (!$thissurvey['urldescrip']) {$thissurvey['urldescrip']=$thissurvey['url'];}
}
return $thissurvey;
}
function getlabelsets()
{
global $dbprefix, $connect, $surveyid;
$query = "SELECT ".db_table_name('labelsets').".lid as lid, label_name FROM ".db_table_name('labelsets')." order by label_name";
$result = db_execute_assoc($query) or die ("Couldn't get list of label sets<br />$query<br />".htmlspecialchars($connect->ErrorMsg()));
$labelsets=array();
while ($row=$result->FetchRow())
{
$labelsets[] = array($row['lid'], $row['lid'].": ".$row['label_name']);
}
return $labelsets;
}
function checkactivations()
{
global $dbprefix, $connect;
$tablelist = $connect->MetaTables();
$tablenames[] = "ListofTables"; //dummy entry because in_array never finds the first one!
foreach ($tablelist as $tbl)
{
$tablenames[] = $tbl;
}
$caquery = "SELECT sid FROM ".db_table_name('surveys')." WHERE active='Y'";
$caresult = db_execute_assoc($caquery);
if (!$caresult) {return "Database Error";}
while ($carow = $caresult->FetchRow())
{
$surveyname = "{$dbprefix}survey_{$carow['sid']}";
if (!in_array($surveyname, $tablenames))
{
$udquery = "UPDATE ".db_table_name('surveys')." SET active='N' WHERE sid={$carow['sid']}";
$udresult = $connect->Execute($udquery);
}
}
}
function checkifemptydb()
{
global $connect;
$tablelist = $connect->MetaTables('TABLES');
if (count($tablelist)==0) {Return(true);}
else {Return(false);}
}
// This functions checks if the databaseversion in the settings table is the same one as required
// If no settings table does exists it is a upgrade from <=1.0 (mysql only)
// Then the old checker script is run prior to the standard upgrade
function checkforupgrades()
{
global $connect, $databasetype, $dbprefix, $dbversionnumber;
include ('admin/install/upgrade-'.$databasetype.'.php');
$tables = $connect->MetaTables();
if ($databasetype=='mysql')
{
$usquery = 'SELECT stg_value FROM '.db_table_name("settings_global").' where stg_name="DBVersion"';
$usresult = db_execute_assoc($usquery);
if ($usresult->RecordCount()==0) {mysqlcheckfields();}
else
{
$usrow = $usresult->FetchRow();
if (intval($usrow['stg_value'])<$dbversionnumber) {db_upgrade(intval($usrow['stg_value']));}
}
}
}
function checkfortables()
{
global $scriptname, $dbprefix, $setfont, $connect, $clang;
$alltables=array("{$dbprefix}surveys",
"{$dbprefix}groups",
"{$dbprefix}questions",
"{$dbprefix}answers",
"{$dbprefix}conditions",
"{$dbprefix}users",
"{$dbprefix}labelsets",
"{$dbprefix}labels");
$tables = $connect->MetaTables();
foreach($alltables as $at)
{
if (!sql_table_exists($at, $tables))
{
$checkfields="Y";
}
}
if (!isset($checkfields)) {$checkfields="";}
if ($checkfields=="Y")
{
echo "<br />\n"
."<table width='350' align='center' style='border: 1px solid #555555' cellpadding='1' cellspacing='0'>\n"
."\t<tr bgcolor='#555555'><td colspan='2' height='4'><font size='1' face='verdana' color='white'><strong>"
.$clang->gT("PHPSurveyor Setup")."</strong></td></tr>\n"
."\t<tr bgcolor='#CCCCCC'><td align='center'>$setfont\n"
."\t\t<font color='red'><strong>"
.$clang->gT("Error")."</strong></font><br />\n"
."\t\t"
.$clang->gT("It appears as if some tables or fields are missing from your database.")."<br /><br />\n"
."\t\t<input type='submit' value='"
.$clang->gT("Check Database Fields")."' onClick=\"window.open('checkfields.php', '_top')\" />\n"
."\t</td></tr>\n"
."</table>\n"
."</body></html>\n";
exit;
}
}
function sql_table_exists($tableName, $tables)
{
return(in_array($tableName, $tables));
}
################################################################################
# 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
# group_name and then title.
function CompareGroupThenTitle($a, $b)
{
if (isset($a["group_order"]) && isset($b["group_order"]))
{
$GroupResult = strnatcasecmp($a["group_order"], $b["group_order"]);
}
else