diff --git a/admin/databasestrings.php b/admin/databasestrings.php index 6a26a07c..c3ae8419 100755 --- a/admin/databasestrings.php +++ b/admin/databasestrings.php @@ -72,5 +72,6 @@ T_("Thursday"); T_("Friday"); T_("Saturday"); T_("Sunday"); +T_("Quota filled"); ?> diff --git a/admin/index.php b/admin/index.php index 52ab1155..2a142889 100644 --- a/admin/index.php +++ b/admin/index.php @@ -64,6 +64,8 @@ print "
  • " . T_("Data print "
  • " . T_("Questionnaire progress") . "

    "; print "
  • "; print "
  • " . T_("Performance") . "

    "; diff --git a/admin/new.php b/admin/new.php index d18a8842..d391c002 100644 --- a/admin/new.php +++ b/admin/new.php @@ -96,10 +96,11 @@ if (isset($_POST['import_file'])) if ($rs) { $qid = $db->Insert_ID(); - print "

    Successfully inserted $name as questionnaire $qid, linked to $lime_sid

    "; + print "

    " . T_("Successfully inserted") . " $name " . T_("as questionnaire") . " $qid, " . T_("linked to") . " $lime_sid

    "; + print "

    " . T_("You must now edit and activate the questionnaire") . "

    "; }else { - print "

    Error: Failed to insert questionnaire

    "; + print "

    " . T_("Error: Failed to insert questionnaire") . "

    "; } diff --git a/admin/operatorperformance.php b/admin/operatorperformance.php index 5cb96ba0..839f48b6 100644 --- a/admin/operatorperformance.php +++ b/admin/operatorperformance.php @@ -64,12 +64,11 @@ include("../functions/functions.input.php"); */ include("../functions/functions.operator.php"); -xhtml_head(T_("Operator Performance"),true,false,array("../js/window.js")); +xhtml_head(T_("Operator Performance"),true,array("../css/table.css"),array("../js/window.js")); -$rs = get_CPH(); +$rs = get_stats_total(get_stats()); print "

    " . T_("Overall") . "

    "; -xhtml_table($rs,array("firstName","completions","time","CPH"),array(T_("Operator"),T_("Completions"),T_("Total time"),T_("Completions per hour")),"tclass"); -xhtml_table(get_effectiveness(),array("firstName","effectiveness"),array(T_("Operator"),T_("Effectiveness (proportion of time on a call in a case)")),"tclass"); +xhtml_table($rs,array("firstName","completions","totalcalls","time","callt","CPH","CALLSPH","effectiveness"),array(T_("Operator"),T_("Completions"),T_("Calls"),T_("Total time"),T_("Call time"),T_("Completions p/h"),T_("Calls p/h"),T_("Effectiveness"))); $questionnaire_id = false; if (isset($_GET['questionnaire_id'])) $questionnaire_id = bigintval($_GET['questionnaire_id']); @@ -77,10 +76,9 @@ display_questionnaire_chooser($questionnaire_id); if ($questionnaire_id) { - $rs = get_CPH_by_questionnaire($questionnaire_id); + $rs = get_stats_total(get_stats_by_questionnaire($questionnaire_id)); print "

    " . T_("This project") . "

    "; - xhtml_table($rs,array("firstName","completions","time","CPH"),array(T_("Operator"),T_("Completions"),T_("Total time"),T_("Completions per hour")),"tclass"); - xhtml_table(get_effectiveness_by_questionnaire($questionnaire_id),array("firstName","effectiveness"),array(T_("Operator"),T_("Effectiveness (proportion of time on a call in a case)")),"tclass"); + xhtml_table($rs,array("firstName","completions","totalcalls","time","callt","CPH","CALLSPH","effectiveness"),array(T_("Operator"),T_("Completions"),T_("Calls"),T_("Total time"),T_("Call time"),T_("Completions p/h"),T_("Calls p/h"),T_("Effectiveness"))); $operator_id = get_operator_id(); @@ -99,9 +97,9 @@ if ($questionnaire_id) if ($shift_id) { - $rs = get_CPH_by_shift($questionnaire_id,$shift_id); + $rs = get_stats_total(get_stats_by_shift($questionnaire_id,$shift_id)); print "

    " . T_("This shift") . "

    "; - xhtml_table($rs,array("firstName","completions","time","CPH"),array(T_("Operator"),T_("Completions"),T_("Total time"),T_("Completions per hour")),"tclass"); + xhtml_table($rs,array("firstName","completions","totalcalls","time","callt","CPH","CALLSPH","effectiveness"),array(T_("Operator"),T_("Completions"),T_("Calls"),T_("Total time"),T_("Call time"),T_("Completions p/h"),T_("Calls p/h"),T_("Effectiveness"))); } } diff --git a/admin/outcomes.php b/admin/outcomes.php index 7951ffdf..0ed4e81d 100644 --- a/admin/outcomes.php +++ b/admin/outcomes.php @@ -69,7 +69,7 @@ include ("../functions/functions.operator.php"); */ include("../functions/functions.input.php"); -$operator_id = get_operator_id(); +$admin_operator_id = get_operator_id(); $questionnaire_id = false; if (isset($_GET['questionnaire_id'])) $questionnaire_id = bigintval($_GET['questionnaire_id']); @@ -122,7 +122,7 @@ if ($questionnaire_id != false) print ""; - $sql = "SELECT o.description as des, o.outcome_id, count( c.case_id ) as count + $sql = "SELECT o.description as des, o.outcome_id, count( c.case_id ) as count, ROUND((count(c.case_id) / (SELECT count(case_id) FROM `case` WHERE questionnaire_id = '$questionnaire_id')) * 100,2) as perc FROM `case` AS c, `outcome` AS o WHERE c.questionnaire_id = '$questionnaire_id' AND c.current_outcome_id = o.outcome_id @@ -133,75 +133,111 @@ if ($questionnaire_id != false) if (!empty($rs)) { translate_array($rs,array("des")); - xhtml_table($rs,array("des","count"),array(T_("Outcome"),T_("Count")),"tclass",array("des" => "Complete")); + xhtml_table($rs,array("des","count","perc"),array(T_("Outcome"),T_("Count"),T_("%")),"tclass",array("des" => "Complete"),array("count","perc")); + + $operator_id = false; + if (isset($_GET['operator_id'])) $operator_id = bigintval($_GET['operator_id']); + + //display a list of operators + $sql = "SELECT s.operator_id as value,s.firstname as description, CASE WHEN s.operator_id = '$operator_id' THEN 'selected=\'selected\'' ELSE '' END AS selected + FROM operator as s, operator_questionnaire as q + WHERE s.operator_id = q.operator_id + AND q.questionnaire_id = '$questionnaire_id'"; + + $r = $db->GetAll($sql); + + print "

    " . T_("Operator") . ": " . "

    "; + if(!empty($r)) + display_chooser($r,"operator_id","operator_id",true,"questionnaire_id=$questionnaire_id"); + + if ($operator_id != false) + { + print "

    " . T_("Operator call outcomes") . "

    "; + + $sql = "SELECT o.description as des, o.outcome_id, count( c.call_id ) as count, ROUND((count(c.call_id) / (SELECT count(call.call_id) FROM `call` JOIN `case` ON (call.case_id = `case`.case_id AND `case`.questionnaire_id = $questionnaire_id ) WHERE call.operator_id = '$operator_id')) * 100,2) as perc + FROM `call` AS c, `case` as ca, `outcome` AS o + WHERE ca.questionnaire_id = '$questionnaire_id' + AND ca.case_id = c.case_id + AND c.operator_id = '$operator_id' + AND c.outcome_id = o.outcome_id + GROUP BY o.outcome_id"; + + $rs = $db->GetAll($sql); + + if (!empty($rs)) + { + translate_array($rs,array("des")); + xhtml_table($rs,array("des","count","perc"),array(T_("Outcome"),T_("Count"),T_("%")),"tclass",array("des" => "Complete"),array("count","perc")); + } + } + + $sample_import_id = false; + if (isset($_GET['sample_import_id'])) $sample_import_id = bigintval($_GET['sample_import_id']); + + //display a list of samples + $sql = "SELECT s.sample_import_id as value,s.description, CASE WHEN s.sample_import_id = '$sample_import_id' THEN 'selected=\'selected\'' ELSE '' END AS selected + FROM sample_import as s, questionnaire_sample as q + WHERE s.sample_import_id = q.sample_import_id + AND q.questionnaire_id = '$questionnaire_id'"; + + $r = $db->GetAll($sql); + + + print "

    " . T_("Sample") . ": " . "

    "; + if(!empty($r)) + display_chooser($r,"sample_import_id","sample_import_id",true,"questionnaire_id=$questionnaire_id"); + + + if ($sample_import_id != false) + { + print "

    " . T_("Sample status") . "

    "; + + $sql = "SELECT CASE WHEN (c.sample_id is not null) = 1 THEN '" . T_("Drawn from sample") . "' ELSE '" . T_("Remain in sample") . "' END as drawn, + count(*) as count + FROM sample as s + JOIN questionnaire_sample as qs ON (qs.questionnaire_id = '$questionnaire_id' and qs.sample_import_id = s.import_id) + LEFT JOIN `case` as c ON (c.questionnaire_id = qs.questionnaire_id and c.sample_id = s.sample_id) + WHERE s.import_id = '$sample_import_id' + GROUP BY (c.sample_id is not null)"; + + xhtml_table($db->GetAll($sql),array("drawn","count"),array(T_("Status"),T_("Number"))); + + + print "

    " . T_("Outcomes") . "

    "; + + + $sql = "SELECT o.description as des, o.outcome_id, count( c.case_id ) as count,ROUND(count(c.case_id) / (SELECT count(case_id) FROM `case` JOIN sample ON (`case`.sample_id = sample.sample_id AND sample.import_id = '$sample_import_id') WHERE questionnaire_id = '$questionnaire_id' ) * 100,2) as perc + + FROM `case` AS c, `outcome` AS o, sample as s + WHERE c.questionnaire_id = '$questionnaire_id' + AND c.sample_id = s.sample_id + AND s.import_id = '$sample_import_id' + AND c.current_outcome_id = o.outcome_id + GROUP BY o.outcome_id"; + + $rs = $db->GetAll($sql); + + if (!empty($rs)) + { + translate_array($rs,array("des")); + xhtml_table($rs,array("des","count","perc"),array(T_("Outcome"),T_("Count"),T_("%")),"tclass",array("des" => "Complete"),array("count","perc")); + } + else + print "

    " . T_("No outcomes recorded for this sample") . "

    "; + } + } else print "

    " . T_("No outcomes recorded for this questionnaire") . "

    "; - $sample_import_id = false; - if (isset($_GET['sample_import_id'])) $sample_import_id = bigintval($_GET['sample_import_id']); - - //display a list of samples - $sql = "SELECT s.sample_import_id as value,s.description, CASE WHEN s.sample_import_id = '$sample_import_id' THEN 'selected=\'selected\'' ELSE '' END AS selected - FROM sample_import as s, questionnaire_sample as q - WHERE s.sample_import_id = q.sample_import_id - AND q.questionnaire_id = '$questionnaire_id'"; - - $r = $db->GetAll($sql); - - - print "

    " . T_("Sample") . ": " . "

    "; - if(!empty($r)) - display_chooser($r,"sample_import_id","sample_import_id",true,"questionnaire_id=$questionnaire_id"); - - - if ($sample_import_id != false) - { - print "

    " . T_("Sample status") . "

    "; - - $sql = "SELECT CASE WHEN (c.sample_id is not null) = 1 THEN '" . T_("Drawn from sample") . "' ELSE '" . T_("Remain in sample") . "' END as drawn, - count(*) as count - FROM sample as s - JOIN questionnaire_sample as qs ON (qs.questionnaire_id = '$questionnaire_id' and qs.sample_import_id = s.import_id) - LEFT JOIN `case` as c ON (c.questionnaire_id = qs.questionnaire_id and c.sample_id = s.sample_id) - WHERE s.import_id = '$sample_import_id' - GROUP BY (c.sample_id is not null)"; - - xhtml_table($db->GetAll($sql),array("drawn","count"),array(T_("Status"),T_("Number"))); - - - print "

    " . T_("Outcomes") . "

    "; - - - $sql = "SELECT o.description as des, o.outcome_id, count( c.case_id ) as count - FROM `case` AS c, `outcome` AS o, sample as s - WHERE c.questionnaire_id = '$questionnaire_id' - AND c.sample_id = s.sample_id - AND s.import_id = '$sample_import_id' - AND c.current_outcome_id = o.outcome_id - GROUP BY o.outcome_id"; - - $rs = $db->GetAll($sql); - - if (!empty($rs)) - { - translate_array($rs,array("des")); - xhtml_table($rs,array("des","count"),array(T_("Outcome"),T_("Count")),"tclass",array("des" => "Complete")); - } - else - print "

    " . T_("No outcomes recorded for this sample") . "

    "; - } - - - //display a list of shifts with completions and a link to either add a report or view reports print "

    " . T_("Shifts") . "

    "; $sql = "SELECT s.shift_id, CONCAT(DATE_FORMAT(CONVERT_TZ(s.start,'UTC',o.Time_zone_name),'" . DATE_TIME_FORMAT ."'), ' - ', DATE_FORMAT(CONVERT_TZ(s.end,'UTC',o.Time_zone_name),'" . DATE_TIME_FORMAT ."')) as description, CASE WHEN sr.shift_id IS NULL THEN CONCAT('" . T_("No shift reports: Add report") . "') ELSE CONCAT('" . T_("View shift reports") . "') END AS link, c.completions as completions, CONCAT('" . T_("View operator performance") . "') as operform FROM `shift` as s - JOIN operator as o on (o.operator_id = '$operator_id') + JOIN operator as o on (o.operator_id = '$admin_operator_id') LEFT JOIN shift_report as sr on (sr.shift_id = s.shift_id) LEFT JOIN ( SELECT count(*) as completions,sh.shift_id FROM `call` as a, `case` as b, shift as sh diff --git a/admin/quotareport.php b/admin/quotareport.php new file mode 100644 index 00000000..3ff63856 --- /dev/null +++ b/admin/quotareport.php @@ -0,0 +1,245 @@ + + * @copyright Australian Consortium for Social and Political Research Incorporated (ACSPRI) 2009 + * @package queXS + * @subpackage admin + * @link http://www.acspri.org.au/ queXS was writen for ACSPRI + * @license http://opensource.org/licenses/gpl-2.0.php The GNU General Public License (GPL) Version 2 + * + */ + +/** + * Configuration file + */ +include_once(dirname(__FILE__).'/../config.inc.php'); + +/** + * Database file + */ +include ("../db.inc.php"); + +/** + * XHTML functions + */ +include ("../functions/functions.xhtml.php"); + +/** + * Display functions + */ +include("../functions/functions.display.php"); + +/** + * Input functions + */ +include("../functions/functions.input.php"); + +/** + * Operator functions + */ +include("../functions/functions.operator.php"); + +/** + * Limesurvey functions + */ +include("../functions/functions.limesurvey.php"); + +xhtml_head(T_("Quota report"),true,array("../css/table.css"),array("../js/window.js")); + +print "

    " . T_("Select a questionnaire from the list below") . "

    "; +$questionnaire_id = false; +if (isset($_GET['questionnaire_id'])) $questionnaire_id = bigintval($_GET['questionnaire_id']); +display_questionnaire_chooser($questionnaire_id); + +if ($questionnaire_id) +{ + print "

    " . T_("Select a sample from the list below") . "

    "; + $sample_import_id = false; + if (isset($_GET['sample_import_id'])) $sample_import_id = bigintval($_GET['sample_import_id']); + display_sample_chooser($questionnaire_id,$sample_import_id); + + if ($sample_import_id) + { + if (isset($_GET['rowquota'])) + { + $qsq = bigintval($_GET['rowquota']); + $qr = 0; + if (isset($_GET['close'])) $qr = 1; + $sql = "UPDATE questionnaire_sample_quota_row + SET quota_reached = $qr + WHERE questionnaire_sample_quota_row_id = '$qsq'"; + $db->Execute($sql); + if ($qr == 1) + close_row_quota($qsq); + else + open_row_quota($qsq,false); + } + + //Display report of quotas + $report = array(); + + //Rows to display: Strata Status Quota Sample Sample Used Sample Remaining Completes % Complete + + // Firstly, for the entire sample + + //We need to calc Sample size, Sample drawn, Sample remain, Completions, %complete + $sql = "SELECT (c.sample_id is not null) as type, count(*) as count + FROM sample as s + JOIN questionnaire_sample as qs ON (qs.questionnaire_id = '$questionnaire_id' and qs.sample_import_id = s.import_id) + LEFT JOIN `case` as c ON (c.questionnaire_id = qs.questionnaire_id and c.sample_id = s.sample_id) + WHERE s.import_id = '$sample_import_id' + GROUP BY (c.sample_id is not null)"; + + $rs = $db->GetAll($sql); + + //type == 1 is drawn from sample, type == 0 is remains in sample + $drawn = 0; + $remain = 0; + + foreach ($rs as $r) + { + if ($r['type'] == 1) $drawn = $r['count']; + if ($r['type'] == 0) $remain = $r['count']; + } + + $sql = "SELECT count(*) as count + FROM `case` as c, sample as s + WHERE c.current_outcome_id = 10 + AND s.import_id = '$sample_import_id' + AND s.sample_id = c.sample_id + AND c.questionnaire_id = '$questionnaire_id'"; + + $rs = $db->GetRow($sql); + + $completions = $rs['count']; + + $report[] = array("strata" => T_("Total sample"), "quota" => $drawn + $remain, "sample" => $drawn + $remain, "sampleused" => $drawn, "sampleremain" => $remain, "completions" => $completions, "perc" => ROUND(($completions / ($drawn + $remain)) * 100,2)); + + //a. (Standard quota) Monitor outcomes of questions in completed questionnaires, and exclude selected sample records when completion limit is reached + //b. (Replicate quota) Exclude selected sample records (where lime_sgqa == -1) + $sql = "SELECT questionnaire_sample_quota_row_id,lime_sgqa,value,completions,quota_reached,lime_sid,comparison,exclude_var,exclude_val,qsq.description + FROM questionnaire_sample_quota_row as qsq, questionnaire as q + WHERE qsq.questionnaire_id = '$questionnaire_id' + AND qsq.sample_import_id = '$sample_import_id' + AND q.questionnaire_id = '$questionnaire_id'"; + + $r = $db->GetAll($sql); + + foreach ($r as $v) + { + if ($v['lime_sgqa'] == -1) + { + $completions = limesurvey_quota_replicate_completions($v['lime_sid'],$questionnaire_id,$sample_import_id,$v['exclude_val'],$v['exclude_var']); + $v['completions'] = ""; + $perc = ""; + } + else + { + $completions = limesurvey_quota_completions($v['lime_sgqa'],$v['lime_sid'],$questionnaire_id,$sample_import_id,$v['value'],$v['comparison']); + $perc = ROUND(($completions / ($v['completions'])) * 100,2); + } + + //We need to calc Sample size, Sample drawn, Sample remain + $sql = "SELECT (c.sample_id is not null) as type, count(*) as count + FROM sample as s + JOIN questionnaire_sample as qs ON (qs.questionnaire_id = '$questionnaire_id' and qs.sample_import_id = s.import_id) + JOIN sample_var as sv ON (sv.sample_id = s.sample_id AND sv.var LIKE '{$v['exclude_var']}' AND sv.val LIKE '{$v['exclude_val']}') + LEFT JOIN `case` as c ON (c.questionnaire_id = qs.questionnaire_id and c.sample_id = s.sample_id) + WHERE s.import_id = '$sample_import_id' + GROUP BY (c.sample_id is not null)"; + + $rs = $db->GetAll($sql); + //type == 1 is drawn from sample, type == 0 is remains in sample + $drawn = 0; + $remain = 0; + + foreach ($rs as $r) + { + if ($r['type'] == 1) $drawn = $r['count']; + if ($r['type'] == 0) $remain = $r['count']; + } + + if ($completions < $v['completions'] || $v['lime_sgqa'] == -1) //if completions less than the quota, allow for closing/opening + { + if ($v['quota_reached'] == 1) + $status = "" . T_("closed") . ""; + else + $status = "" . T_("open") . ""; + } + else + { + if ($v['quota_reached'] == 1) + $status = T_("closed"); + else + $status = T_("open"); + } + + $report[] = array("strata" => "" . $v['description'] . "", "status" => $status, "quota" => $v['completions'], "sample" => $drawn + $remain, "sampleused" => $drawn, "sampleremain" => $remain, "completions" => $completions, "perc" => $perc); + } + + //c. (Questionnaire quota) Monitor outcomes of questions in completed questionnaires, and abort interview when completion limit is reached + $sql = "SELECT * + FROM " . LIME_PREFIX . "quota as qu, questionnaire as q + WHERE qu.sid = q.lime_sid + AND qu.active = 1 + AND q.questionnaire_id = '$questionnaire_id'"; + + $rs = $db->GetAll($sql); + + //for each limesurvey quota + foreach($rs as $r) + { + //limesurvey quotas for this question + $quotas = (get_limesurvey_quota_info($r['id'])); + $sqlq = array(); + + foreach ($quotas as $q) + $sqlq[] = "s." . $q['fieldname'] . " = '" . $q['value'] . "'"; + + $sql = "SELECT COUNT(id) as count + FROM ".LIME_PREFIX."survey_{$r['sid']} as s + JOIN `case` as c ON (c.questionnaire_id = '$questionnaire_id') + JOIN `sample` as sam ON (c.sample_id = sam.sample_id AND sam.import_id = '$sample_import_id') + WHERE ".implode(' AND ',$sqlq)." "." + AND submitdate IS NOT NULL + AND s.token = c.case_id"; + + $rs = $db->GetRow($sql); + + $completions = $rs['count']; + $perc = ROUND(($completions / $r['qlimit']) * 100,2); + + $report[] = array("strata" => "" . $r['name'] . "", "quota" => $r['qlimit'], "completions" => $completions, "perc" => $perc); + } + + xhtml_table($report,array("strata","status","quota","sample","sampleused","sampleremain","completions","perc"),array(T_("Strata"),T_("Status"),T_("Quota"),T_("Sample"),T_("Sample Used"),T_("Sample Remaining"),T_("Completions"),T_("% Complete")),"tclass",false,false); + } +} + +xhtml_foot(); + + +?> diff --git a/admin/quotarow.php b/admin/quotarow.php index 6332557e..c04c519a 100755 --- a/admin/quotarow.php +++ b/admin/quotarow.php @@ -69,22 +69,29 @@ include("../functions/functions.operator.php"); global $db; - if (isset($_GET['questionnaire_id']) && isset($_GET['sgqa']) && isset($_GET['value']) && isset($_GET['completions']) && isset($_GET['sample_import_id']) && isset($_GET['comparison']) && isset($_GET['exclude_var']) && isset($_GET['exclude_val'])) { //need to add quota + $value = -1; + $comparison = -1; + $completions = -1; + $sgqa = -1; $questionnaire_id = bigintval($_GET['questionnaire_id']); $sample_import_id = bigintval($_GET['sample_import_id']); - $value = $db->quote($_GET['value']); - $completions = $db->quote($_GET['completions']); - $sgqa = $db->quote($_GET['sgqa']); - $comparison = $db->quote($_GET['comparison']); + if ($_GET['sgqa'] != -1) + { + $sgqa = $db->quote($_GET['sgqa']); + $comparison = $db->quote($_GET['comparison']); + $value = $db->quote($_GET['value']); + $completions = $db->quote($_GET['completions']); + } $exclude_val = $db->quote($_GET['exclude_val']); $exclude_var = $db->quote($_GET['exclude_var']); + $description = $db->quote($_GET['description']); - $sql = "INSERT INTO questionnaire_sample_quota_row(questionnaire_id, sample_import_id, lime_sgqa,value,completions,comparison,exclude_var,exclude_val) - VALUES ($questionnaire_id, $sample_import_id, $sgqa, $value, $completions, $comparison, $exclude_var, $exclude_val)"; + $sql = "INSERT INTO questionnaire_sample_quota_row(questionnaire_id, sample_import_id, lime_sgqa,value,completions,comparison,exclude_var,exclude_val,description) + VALUES ($questionnaire_id, $sample_import_id, $sgqa, $value, $completions, $comparison, $exclude_var, $exclude_val, $description)"; $db->Execute($sql); @@ -99,20 +106,7 @@ if (isset($_GET['questionnaire_id']) && isset($_GET['questionnaire_sample_quota_ $questionnaire_id = bigintval($_GET['questionnaire_id']); $questionnaire_sample_quota_row_id = bigintval($_GET['questionnaire_sample_quota_row_id']); - $db->StartTrans(); - - $sql = "DELETE FROM questionnaire_sample_quota_row - WHERE questionnaire_sample_quota_row_id = '$questionnaire_sample_quota_row_id'"; - - $db->Execute($sql); - - $sql = "DELETE FROM questionnaire_sample_quota_row_exclude - WHERE questionnaire_sample_quota_row_id = '$questionnaire_sample_quota_row_id'"; - - $db->Execute($sql); - - $db->CompleteTrans(); - + open_row_quota($questionnaire_sample_quota_row_id); } $questionnaire_id = false; @@ -142,6 +136,12 @@ if ($questionnaire_id != false) if ($sample_import_id != false) { + if (isset($_POST['copy_sample_import_id'])) + { + copy_row_quota($questionnaire_id,$sample_import_id,bigintval($_POST['copy_sample_import_id'])); + print "

    " . T_("Copied quotas") . "

    "; + } + print "

    " . T_("Current row quotas (click to delete)") . "

    "; $sql = "SELECT questionnaire_sample_quota_row_id,lime_sgqa,value,completions,quota_reached,lime_sid,comparison,exclude_var,exclude_val @@ -160,18 +160,39 @@ if ($questionnaire_id != false) { foreach($r as $v) { - print "
    " . T_("Stop calling") . " " . $v['exclude_var'] . " " . T_("like") . " " . $v['exclude_val'] . " " . T_("rows from this sample when:") . " {$v['lime_sgqa']} {$v['comparison']} {$v['value']} " . T_("for") . ": {$v['completions']} " . T_("completions") ." - "; + if ($v['lime_sgqa'] == -1) + print "
    " . T_("Replicate: Where") . " " . $v['exclude_var'] . " " . T_("like") . " " . $v['exclude_val'] . " - "; + else + print "
    " . T_("Stop calling") . " " . $v['exclude_var'] . " " . T_("like") . " " . $v['exclude_val'] . " " . T_("rows from this sample when:") . " {$v['lime_sgqa']} {$v['comparison']} {$v['value']} " . T_("for") . ": {$v['completions']} " . T_("completions") ." - "; if ($v['quota_reached'] == 1) - print T_("Row quota reached"); + print T_("Row quota reached (Closed)"); else - print T_("Row quota not yet reached"); + print T_("Row quota not yet reached (Open)"); - print " - " . T_("Current completions: ") . limesurvey_quota_completions($v['lime_sgqa'],$v['lime_sid'],$questionnaire_id,$sample_import_id,$v['value'],$v['comparison']); + if ($v['lime_sgqa'] != -1) + print " - " . T_("Current completions: ") . limesurvey_quota_completions($v['lime_sgqa'],$v['lime_sid'],$questionnaire_id,$sample_import_id,$v['value'],$v['comparison']); print "
    "; } + + + $sql = "SELECT s.sample_import_id as value,s.description, '' AS selected + FROM sample_import as s, questionnaire_sample as q + WHERE q.questionnaire_id = $questionnaire_id + AND q.sample_import_id = s.sample_import_id + AND s.sample_import_id != '$sample_import_id'"; + + $ss = $db->GetAll($sql); + + if (!empty($ss)) + { + print "

    " . T_("Copy quotas for this sample to (No error/duplicate checking): "); + display_chooser($ss,"copy_sample_import_id","copy_sample_import_id",false,false,false,false); + print "

    "; + } + } @@ -193,8 +214,13 @@ if ($questionnaire_id != false) LEFT JOIN `" . LIME_PREFIX . "answers` AS a ON ( a.qid = q.qid ) WHERE q.sid = '$lime_sid'"; - - display_chooser($db->GetAll($sql),"sgqa","sgqa",true,"questionnaire_id=$questionnaire_id&sample_import_id=$sample_import_id"); + $rs = $db->GetAll($sql); + + $selected = ""; + if ($sgqa == -1) $selected = "selected='selected'"; + array_unshift($rs,array("value" => -1, "description" => T_("No question (Replicate)"), "selected" => $selected)); + + display_chooser($rs,"sgqa","sgqa",true,"questionnaire_id=$questionnaire_id&sample_import_id=$sample_import_id"); if ($sgqa != false) { @@ -236,9 +262,16 @@ if ($questionnaire_id != false) ?>

    +
    +


    + + + + + + * @copyright Australian Consortium for Social and Political Research Incorporated (ACSPRI) 2009 + * @package queXS + * @subpackage admin + * @link http://www.acspri.org.au/ queXS was writen for ACSPRI + * @license http://opensource.org/licenses/gpl-2.0.php The GNU General Public License (GPL) Version 2 + * + */ + +/** + * Configuration file + */ +include_once(dirname(__FILE__).'/../config.inc.php'); + +/** + * Database file + */ +include ("../db.inc.php"); + +/** + * XHTML functions + */ +include ("../functions/functions.xhtml.php"); + +/** + * Display functions + */ +include("../functions/functions.display.php"); + +/** + * Input functions + */ +include("../functions/functions.input.php"); + +xhtml_head(T_("Sample call attempt"),true,array("../css/table.css"),array("../js/window.js")); + +print "

    " . T_("Overall") . "

    "; + +$sql = "SELECT ca1 AS callattempts, COUNT( ca1 ) AS sample + FROM ( SELECT count( call_attempt_id ) AS ca1 + FROM call_attempt + GROUP BY case_id) AS t1 + GROUP BY ca1"; + +xhtml_table($db->GetAll($sql),array("sample","callattempts"),array(T_("Number of cases"),T_("Call attempts made")),"tclass",false,array("sample")); + +$questionnaire_id = false; +if (isset($_GET['questionnaire_id'])) $questionnaire_id = bigintval($_GET['questionnaire_id']); +display_questionnaire_chooser($questionnaire_id); + +if ($questionnaire_id) +{ + $sql = "SELECT ca1 AS callattempts, COUNT( ca1 ) AS sample + FROM ( SELECT count( call_attempt.call_attempt_id ) AS ca1 + FROM call_attempt + JOIN `case` ON (`case`.case_id = call_attempt.case_id AND `case`.questionnaire_id = '$questionnaire_id') + GROUP BY call_attempt.case_id) AS t1 + GROUP BY ca1"; + + print "

    " . T_("This project") . "

    "; + xhtml_table($db->GetAll($sql),array("sample","callattempts"),array(T_("Number of cases"),T_("Call attempts made")),"tclass",false,array("sample")); + + $sample_import_id = false; + if (isset($_GET['sample_import_id'])) $sample_import_id = bigintval($_GET['sample_import_id']); + display_sample_chooser($questionnaire_id,$sample_import_id); + + if ($sample_import_id) + { + $sql = "SELECT ca1 AS callattempts, COUNT( ca1 ) AS sample + FROM ( SELECT count( call_attempt.call_attempt_id ) AS ca1 + FROM call_attempt + JOIN `case` ON (`case`.case_id = call_attempt.case_id AND `case`.questionnaire_id = '$questionnaire_id') + JOIN sample ON (sample.sample_id = `case`.sample_id AND sample.import_id = '$sample_import_id') + GROUP BY call_attempt.case_id) AS t1 + GROUP BY ca1"; + + print "

    " . T_("This sample") . "

    "; + xhtml_table($db->GetAll($sql),array("sample","callattempts"),array(T_("Number of cases"),T_("Call attempts made")),"tclass",false,array("sample")); + + $questionnaire_sample_quota_row_id = false; + if (isset($_GET['questionnaire_sample_quota_row_id'])) $questionnaire_sample_quota_row_id = bigintval($_GET['questionnaire_sample_quota_row_id']); + display_quota_chooser($questionnaire_id,$sample_import_id,$questionnaire_sample_quota_row_id); + + if ($questionnaire_sample_quota_row_id) + { + $sql = "SELECT ca1 AS callattempts, COUNT( ca1 ) AS sample + FROM ( SELECT count( call_attempt.call_attempt_id ) AS ca1 + FROM call_attempt + JOIN `case` ON (`case`.case_id = call_attempt.case_id AND `case`.questionnaire_id = '$questionnaire_id') + JOIN sample ON (sample.sample_id = `case`.sample_id AND sample.import_id = '$sample_import_id') + JOIN questionnaire_sample_quota_row as q ON (q.questionnaire_sample_quota_row_id = '$questionnaire_sample_quota_row_id') + JOIN sample_var ON (sample_var.sample_id = `case`.sample_id AND sample_var.var LIKE q.exclude_var AND sample_var.val LIKE q.exclude_val) + GROUP BY call_attempt.case_id) AS t1 + GROUP BY ca1"; + + print "

    " . T_("This quota") . "

    "; + xhtml_table($db->GetAll($sql),array("sample","callattempts"),array(T_("Number of cases"),T_("Call attempts made")),"tclass",false,array("sample")); + + } + } +} + +xhtml_foot(); + + + +?> + diff --git a/call.php b/call.php index db14cf86..002d0f69 100644 --- a/call.php +++ b/call.php @@ -83,6 +83,12 @@ function display_outcomes($contacted,$ca,$case_id) FROM outcome WHERE outcome_id = 10"; } + else if (limesurvey_is_quota_full($case_id)) + { + $sql = "SELECT outcome_id,description + FROM outcome + WHERE outcome_id = 32"; + } else { //see if we have made an appointment on this call attempt diff --git a/database/quexs.sql b/database/quexs.sql index 757d5e73..e376d05a 100644 --- a/database/quexs.sql +++ b/database/quexs.sql @@ -405,6 +405,7 @@ INSERT INTO `outcome` VALUES(28, '2.332', 'Respondent language problem', 0, 4, 0 INSERT INTO `outcome` VALUES(29, '3.14', 'Answering machine - Not a household', 0, 4, 1, 1, 0, 0, 0, 'UH'); INSERT INTO `outcome` VALUES(30, '4.10', 'Out of sample', 0, 4, 0, 1, 0, 0, 0, ''); INSERT INTO `outcome` VALUES(31, '2.20', 'Non contact', 180, 1, 1, 1, 1, 1, 0, 'NC'); +INSERT INTO `outcome` VALUES(32, '4.80', 'Quota filled', 0, 4, 0, 1, 0, 0, 0, ''); -- -------------------------------------------------------- @@ -534,6 +535,7 @@ CREATE TABLE IF NOT EXISTS `questionnaire_sample_quota_row` ( `exclude_var` char(128) collate utf8_unicode_ci NOT NULL, `exclude_val` varchar(256) collate utf8_unicode_ci NOT NULL, `quota_reached` tinyint(1) NOT NULL default '0', + `description` text collate utf8_unicode_ci NOT NULL, PRIMARY KEY (`questionnaire_sample_quota_row_id`), KEY `questionnaire_id` (`questionnaire_id`), KEY `sample_import_id` (`sample_import_id`), diff --git a/functions/functions.display.php b/functions/functions.display.php index 30dec9d7..99cc0dcb 100644 --- a/functions/functions.display.php +++ b/functions/functions.display.php @@ -104,7 +104,6 @@ function display_shift_chooser($questionnaire_id, $shift_id = false) print "
    "; } - /** * Display a list of samples to choose from in a drop down list * @@ -133,6 +132,35 @@ function display_sample_chooser($questionnaire_id, $sample_import_id = false) print "
    "; } +/** + * Display a list of quota rows to choose from in a drop down list + * + * @param int $questionnaire_id The questionnaire id + * @param int $sample_import_id The sample import id + * @param int|bool $qsqri The sample import id or false if none selected + */ +function display_quota_chooser($questionnaire_id, $sample_import_id, $qsqri = false) +{ + global $db; + + $sql = "SELECT q.questionnaire_sample_quota_row_id,q.description,CASE WHEN q.questionnaire_sample_quota_row_id = '$qsqri' THEN 'selected=\'selected\'' ELSE '' END AS selected + FROM questionnaire_sample_quota_row as q + WHERE q.questionnaire_id = '$questionnaire_id' + AND q.sample_import_id = '$sample_import_id'"; + + $rs = $db->GetAll($sql); + + print "
    "; +} + ?> diff --git a/functions/functions.limesurvey.php b/functions/functions.limesurvey.php index 669f709d..2b0bcb14 100644 --- a/functions/functions.limesurvey.php +++ b/functions/functions.limesurvey.php @@ -42,6 +42,40 @@ include_once(dirname(__FILE__).'/../config.inc.php'); */ include_once(dirname(__FILE__).'/../db.inc.php'); +/** + * Return the number of completions for a given + * questionnaire, where the given sample var has + * the given sample value + * + * @param int $lime_sid The limesurvey survey id + * @param int $questionnaire_id The questionnaire ID + * @param int $sample_import_id The sample import ID + * @param string $val The value to compare + * @param string $var The variable to compare + * @return bool|int False if failed, otherwise the number of completions + * + */ +function limesurvey_quota_replicate_completions($lime_sid,$questionnaire_id,$sample_import_id,$val,$var) +{ + global $db; + + $sql = "SELECT count(*) as c + FROM " . LIME_PREFIX . "survey_$lime_sid as s + JOIN `case` as c ON (c.questionnaire_id = '$questionnaire_id') + JOIN `sample` as sam ON (c.sample_id = sam.sample_id AND sam.import_id = '$sample_import_id') + JOIN `sample_var` as sv ON (sv.sample_id = sam.sample_id AND sv.var LIKE '$var' AND sv.val LIKE '$val') + WHERE s.submitdate IS NOT NULL + AND s.token = c.case_id"; + + $rs = $db->GetRow($sql); + + if (isset($rs) && !empty($rs)) + return $rs['c']; + + return false; +} + + /** * Return the number of completions for a given @@ -77,6 +111,71 @@ function limesurvey_quota_completions($lime_sgqa,$lime_sid,$questionnaire_id,$sa return false; } +/** + * Get information on limesurvey quota's + * Based on GetQuotaInformation() from common.php in Limesurvey + * + * @param int $lime_quota_id The quota id to get information on + * @param string $baselang The base language for getting information from questions + * @return array An array containing the question information for comparison + */ +function get_limesurvey_quota_info($lime_quota_id,$baselang = DEFAULT_LOCALE) +{ + global $db; + + $ret = array(); + + $sql = "SELECT * + FROM ".LIME_PREFIX."quota_members + WHERE quota_id='$lime_quota_id'"; + + $rs = $db->GetAll($sql); + + foreach($rs as $quota_entry) + { + $lime_qid = $quota_entry['qid']; + $surveyid = $quota_entry['sid']; + + $sql = "SELECT type, title,gid + FROM ".LIME_PREFIX."questions + WHERE qid='$lime_qid' + AND language='$baselang'"; + + $qtype = $db->GetRow($sql); + + $fieldnames = "0"; + + if ($qtype['type'] == "I" || $qtype['type'] == "G" || $qtype['type'] == "Y") + { + $fieldnames= ($surveyid.'X'.$qtype['gid'].'X'.$quota_entry['qid']); + $value = $quota_entry['code']; + } + + if($qtype['type'] == "L" || $qtype['type'] == "O" || $qtype['type'] =="!") + { + $fieldnames=( $surveyid.'X'.$qtype['gid'].'X'.$quota_entry['qid']); + $value = $quota_entry['code']; + } + + if($qtype['type'] == "M") + { + $fieldnames=( $surveyid.'X'.$qtype['gid'].'X'.$quota_entry['qid'].$quota_entry['code']); + $value = "Y"; + } + + if($qtype['type'] == "A" || $qtype['type'] == "B") + { + $temp = explode('-',$quota_entry['code']); + $fieldnames=( $surveyid.'X'.$qtype['gid'].'X'.$quota_entry['qid'].$temp[0]); + $value = $temp[1]; + } + + + $ret[] = array('code' => $quota_entry['code'], 'value' => $value, 'qid' => $quota_entry['qid'], 'fieldname' => $fieldnames); + } + + return $ret; +} /** * Taken from common.php in the LimeSurvey package @@ -133,33 +232,33 @@ function create_limesurvey_questionnaire($title) while (!empty($isresult) && $isresult->RecordCount() > 0); $isquery = "INSERT INTO ". LIME_PREFIX ."surveys\n" - . "(sid, owner_id, admin, active, useexpiry, expires, " - . "adminemail, private, faxto, format, template, url, " - . "language, datestamp, ipaddr, refurl, usecookie, notification, allowregister, attribute1, attribute2, " + . "(sid, owner_id, admin, active, expires, " + . "adminemail, private, faxto, format, template, " + . "language, datestamp, ipaddr, refurl, usecookie, notification, allowregister, " . "allowsave, autoredirect, allowprev,datecreated,tokenanswerspersistence)\n" . "VALUES ($surveyid, 1,\n" . "'', 'N', \n" - . "'N','1980-01-01', '', 'N',\n" - . "'', 'S', 'quexs', '" . QUEXS_URL . "rs_project_end.php',\n" - . "'en', 'Y', 'N', 'N',\n" + . "NULL, '', 'N',\n" + . "'', 'S', 'quexs',\n" + . "'" . DEFAULT_LOCALE . "', 'Y', 'N', 'N',\n" . "'N', '0', 'Y',\n" - . "'att1', 'att2', \n" . "'Y', 'Y', 'Y','".date("Y-m-d")."','Y')"; - $isresult = $db->Execute($isquery); + $isresult = $db->Execute($isquery) or die ($isquery."
    ".$db->ErrorMsg()); // insert base language into surveys_language_settings $isquery = "INSERT INTO ".db_table_name('surveys_languagesettings') . "(surveyls_survey_id, surveyls_language, surveyls_title, surveyls_description, surveyls_welcometext, surveyls_urldescription, " . "surveyls_email_invite_subj, surveyls_email_invite, surveyls_email_remind_subj, surveyls_email_remind, " - . "surveyls_email_register_subj, surveyls_email_register, surveyls_email_confirm_subj, surveyls_email_confirm)\n" - . "VALUES ($surveyid, 'en', $title, $title,\n" + . "surveyls_email_register_subj, surveyls_email_register, surveyls_email_confirm_subj, surveyls_email_confirm,surveyls_url)\n" + . "VALUES ($surveyid, '" . DEFAULT_LOCALE . "', $title, $title,\n" . "'',\n" . "'', '',\n" . "'', '',\n" . "'', '',\n" . "'', '',\n" - . "'')"; - $isresult = $db->Execute($isquery); + . "'', '" . QUEXS_URL . "rs_project_end.php')"; + $isresult = $db->Execute($isquery) or die ($isquery."
    ".$db->ErrorMsg()); + // Insert into survey_rights $isrquery = "INSERT INTO ". LIME_PREFIX . "surveys_rights VALUES($surveyid,1,1,1,1,1,1,1)"; @@ -249,6 +348,32 @@ function get_lime_sid($case_id) return $l['lime_sid']; } +/** + * Check if LimeSurvey has marked a questionnaire as quota filled + * + * @param int $case_id The case id + * @return bool True if complete, false if not or unknown + * + */ +function limesurvey_is_quota_full($case_id) +{ + global $db; + + $lime_sid = get_lime_sid($case_id); + if ($lime_sid == false) return false; + + $sql = "SELECT completed + FROM " . LIME_PREFIX . "tokens_$lime_sid + WHERE token = '$case_id'"; + + $r = $db->GetRow($sql); + + if (!empty($r)) + if ($r['completed'] == 'Q') return true; + + return false; +} + /** * Check if LimeSurvey has marked a questionnaire as complete @@ -271,12 +396,9 @@ function limesurvey_is_completed($case_id) $r = $db->GetRow($sql); if (!empty($r)) - if ($r['completed'] != 'N') return true; + if ($r['completed'] != 'N' && $r['completed'] != 'Q') return true; return false; - - - } diff --git a/functions/functions.operator.php b/functions/functions.operator.php index 4a0baa24..377a5c32 100644 --- a/functions/functions.operator.php +++ b/functions/functions.operator.php @@ -464,8 +464,8 @@ function get_case_id($operator_id, $create = false) if ($lime_sid) { - $sql = "INSERT INTO ".LIME_PREFIX."tokens_$lime_sid (tid,firstname,lastname,email,token,language,sent,completed,attribute_1,attribute_2,mpid) - VALUES (NULL,'','','',$case_id,'en','N','N','','',NULL)"; + $sql = "INSERT INTO ".LIME_PREFIX."tokens_$lime_sid (tid,firstname,lastname,email,token,language,sent,completed,mpid) + VALUES (NULL,'','','',$case_id,'en','N','N',NULL)"; $db->Execute($sql); } @@ -1035,6 +1035,98 @@ function update_quota($questionnaire_id) } +/** + * "Open" a row quota (allow to access) + * + * @param int $questionnaire_sample_quota_row_id The qsqri + */ +function open_row_quota($questionnaire_sample_quota_row_id,$delete = true) +{ + global $db; + + $db->StartTrans(); + + if ($delete) + { + $sql = "DELETE FROM questionnaire_sample_quota_row + WHERE questionnaire_sample_quota_row_id = '$questionnaire_sample_quota_row_id'"; + + $db->Execute($sql); + } + + $sql = "DELETE FROM questionnaire_sample_quota_row_exclude + WHERE questionnaire_sample_quota_row_id = '$questionnaire_sample_quota_row_id'"; + + $db->Execute($sql); + + $db->CompleteTrans(); +} + +/** + * "Close" a row quota (set to completed) + * + * + */ +function close_row_quota($questionnaire_sample_quota_row_id) +{ + global $db; + + $db->StartTrans(); + + //only insert where we have to + $sql = "SELECT count(*) as c + FROM questionnaire_sample_quota_row_exclude + WHERE questionnaire_sample_quota_row_id = '$questionnaire_sample_quota_row_id'"; + + $coun = $db->GetRow($sql); + + if (isset($coun['c']) && $coun['c'] == 0) + { + //store list of sample records to exclude + $sql = "INSERT INTO questionnaire_sample_quota_row_exclude (questionnaire_sample_quota_row_id,questionnaire_id,sample_id) + SELECT $questionnaire_sample_quota_row_id,qs.questionnaire_id,s.sample_id + FROM sample as s, sample_var as sv, questionnaire_sample_quota_row as qs + WHERE s.import_id = qs.sample_import_id + AND qs.questionnaire_sample_quota_row_id = $questionnaire_sample_quota_row_id + AND s.sample_id = sv.sample_id + AND sv.var = qs.exclude_var + AND qs.exclude_val LIKE sv.val"; + + $db->Execute($sql); + } + + $db->CompleteTrans(); +} + + +/** + * Copy row quotas from one sample to another + * Set quota_reached to 0 by default + * + * @param int $questionnaire_id + * @param int $sample_import_id + * @param int $copy_sample_import_id The sample_import_id to copy to + */ +function copy_row_quota($questionnaire_id,$sample_import_id,$copy_sample_import_id) +{ + global $db; + + $db->StartTrans(); + + //Set quota_reached to 0 always + + $sql = "INSERT INTO questionnaire_sample_quota_row (questionnaire_id,sample_import_id,lime_sgqa,value,comparison,completions,exclude_var,exclude_val,quota_reached,description) + SELECT questionnaire_id, $copy_sample_import_id, lime_sgqa,value,comparison,completions,exclude_var,exclude_val,0,description + FROM questionnaire_sample_quota_row + WHERE questionnaire_id = '$questionnaire_id' + AND sample_import_id = '$sample_import_id'"; + + $db->Execute($sql); + + update_quotas($questionnaire_id); + + $db->CompleteTrans(); +} /** * Update the row quota table @@ -1051,7 +1143,8 @@ function update_row_quota($questionnaire_id) FROM questionnaire_sample_quota_row as qsq, questionnaire as q WHERE qsq.questionnaire_id = '$questionnaire_id' AND q.questionnaire_id = '$questionnaire_id' - AND qsq.quota_reached != '1'"; + AND qsq.quota_reached != '1' + AND qsq.lime_sgqa != -1"; $rs = $db->GetAll($sql); @@ -1074,28 +1167,7 @@ function update_row_quota($questionnaire_id) $db->Execute($sql); - - //only insert where we have to - $sql = "SELECT count(*) as c - FROM questionnaire_sample_quota_row_exclude - WHERE questionnaire_sample_quota_row_id = '{$r['questionnaire_sample_quota_row_id']}'"; - - $coun = $db->GetRow($sql); - - if (isset($coun['c']) && $coun['c'] == 0) - { - //store list of sample records to exclude - $sql = "INSERT INTO questionnaire_sample_quota_row_exclude (questionnaire_sample_quota_row_id,questionnaire_id,sample_id) - SELECT {$r['questionnaire_sample_quota_row_id']},'$questionnaire_id',s.sample_id - FROM sample as s, sample_var as sv - WHERE s.import_id = '{$r['sample_import_id']}' - AND s.sample_id = sv.sample_id - AND sv.var = '{$r['exclude_var']}' - AND '{$r['exclude_val']}' LIKE sv.val"; - - $db->Execute($sql); - } - + close_row_quota($r['questionnaire_sample_quota_row_id']); } } diff --git a/functions/functions.performance.php b/functions/functions.performance.php index e2ed3def..70aeaeb9 100644 --- a/functions/functions.performance.php +++ b/functions/functions.performance.php @@ -51,7 +51,7 @@ function get_CPH_by_shift($qid,$sid) { global $db; - $sql = "SELECT o.firstName,o.operator_id,c.completions,ca.time, c.completions/ca.time as CPH + $sql = "SELECT o.firstName,o.operator_id,c.completions,SEC_TO_TIME(ca.time) as time, c.completions/(ca.time / 3600) as CPH FROM operator as o JOIN ( SELECT count(*) as completions,a.operator_id FROM `call` as a, `case` as b, `shift` as s @@ -62,7 +62,7 @@ function get_CPH_by_shift($qid,$sid) AND s.`start` <= a.`start` AND s.`end` >= a.`start` GROUP BY a.operator_id) as c on (c.operator_id = o.operator_id) - JOIN ( SELECT SUM( TIMESTAMPDIFF(SECOND , a.start, IFNULL(a.end,CONVERT_TZ(NOW(),'System','UTC')))) /3600 as time, a.operator_id + JOIN ( SELECT SUM( TIMESTAMPDIFF(SECOND , a.start, IFNULL(a.end,CONVERT_TZ(NOW(),'System','UTC')))) as time, a.operator_id FROM `call_attempt` as a, `case` as b, `shift` as s WHERE a.case_id = b.case_id AND b.questionnaire_id = '$qid' @@ -85,7 +85,7 @@ function get_CPH_by_questionnaire($qid) { global $db; - $sql = "SELECT o.firstName,o.operator_id,c.completions,ca.time, c.completions/ca.time as CPH + $sql = "SELECT o.firstName,o.operator_id,c.completions,SEC_TO_TIME(ca.time) as time, c.completions/(ca.time / 3600) as CPH FROM operator as o JOIN ( SELECT count(*) as completions,a.operator_id FROM `call` as a, `case` as b @@ -93,13 +93,216 @@ function get_CPH_by_questionnaire($qid) AND a.case_id = b.case_id AND b.questionnaire_id = '$qid' GROUP BY a.operator_id) as c on (c.operator_id = o.operator_id) - JOIN ( SELECT SUM( TIMESTAMPDIFF(SECOND , a.start, IFNULL(a.end,CONVERT_TZ(NOW(),'System','UTC')))) /3600 as time, a.operator_id + JOIN ( SELECT SUM( TIMESTAMPDIFF(SECOND , a.start, IFNULL(a.end,CONVERT_TZ(NOW(),'System','UTC')))) as time, a.operator_id FROM `call_attempt` as a, `case` as b WHERE a.case_id = b.case_id AND b.questionnaire_id = '$qid' GROUP BY operator_id) as ca on (ca.operator_id = o.operator_id) ORDER BY cph DESC"; + + return $db->GetAll($sql); +} + +/** + * Get stats by interviewer by questionnaire by shift + * + * @param int $questionnaire_id The questionnaire + * @param int $shift_id The shift id + * @return arrayh An array containing operator_id,firstName,CPH,effectiveness, + */ +function get_stats_by_shift($questionnaire_id,$shift_id) +{ + global $db; + + $sql = "SELECT o.operator_id, o.firstName, (calltime.totaltime / callattempttime.totaltime) AS effectiveness, c.completions,SEC_TO_TIME(callattempttime.totaltime) as time, c.completions/(callattempttime.totaltime / 3600) as CPH, SEC_TO_TIME(calltime.totaltime) as callt, SEC_TO_TIME(callattempttime.totaltime) as callatemptt, calls.calls as totalcalls, calls.calls/(callattempttime.totaltime / 3600) as CALLSPH, calltime.totaltime as calltotaltime, callattempttime.totaltime as callattempttotaltime + + FROM operator AS o + JOIN ( + SELECT SUM( TIMESTAMPDIFF( + SECOND , c.start, IFNULL( c.end, CONVERT_TZ( NOW( ) , 'System', 'UTC' ) ) ) ) AS totaltime, operator_id + FROM `call` AS c, `case` as b, `shift` as s + WHERE c.case_id = b.case_id + AND b.questionnaire_id = '$questionnaire_id' + AND s.shift_id = '$shift_id' + AND s.`start` <= c.`start` + AND s.`end` >= c.`start` + GROUP BY operator_id + ) AS calltime ON ( calltime.operator_id = o.operator_id ) + JOIN ( + SELECT SUM( TIMESTAMPDIFF( + SECOND , c.start, IFNULL( c.end, CONVERT_TZ( NOW( ) , 'System', 'UTC' ) ) ) ) AS totaltime, operator_id + FROM `call_attempt` AS c, `case` as b, `shift` as s + WHERE c.case_id = b.case_id + AND s.shift_id = '$shift_id' + AND s.`start` <= c.`start` + AND s.`end` >= c.`start` + AND b.questionnaire_id = '$questionnaire_id' + GROUP BY operator_id + ) AS callattempttime ON ( callattempttime.operator_id = o.operator_id ) + JOIN ( SELECT count(*) as completions,a.operator_id + FROM `call` as a, `case` as b, `shift` as s + WHERE a.outcome_id = '10' + AND s.shift_id = '$shift_id' + AND s.`start` <= a.`start` + AND s.`end` >= a.`start` + AND a.case_id = b.case_id + AND b.questionnaire_id = '$questionnaire_id' + GROUP BY a.operator_id) as c on (c.operator_id = o.operator_id) + JOIN ( SELECT count(*) as calls,a.operator_id + FROM `call` as a, `case` as b, `shift` as s + WHERE a.case_id = b.case_id + AND s.shift_id = '$shift_id' + AND s.`start` <= a.`start` + AND s.`end` >= a.`start` + AND b.questionnaire_id = '$questionnaire_id' + GROUP BY a.operator_id) as calls on (calls.operator_id = o.operator_id) + ORDER BY effectiveness DESC"; + + return $db->GetAll($sql); +} + +/** + * Convert seconds to time in HH:MM:SS + * + * @param int Seconds + * @return string Time in format HH:MM:SS + */ +function sec_to_time($seconds) +{ + + if($seconds >= 3600){ + $h = floor($seconds/3600); + $seconds = ($seconds%3600); + } + if($seconds >= 60){ + $m = floor($seconds/60); + $seconds = ($seconds%60); + } + $s = floor($seconds); + + return sprintf("%02d:%02d:%02d", $h, $m, $s); +} + + +/** + * Given the stats, add a total line + * + * @param array The result set from the database + * @return array The result set plus a total row + */ +function get_stats_total($rs) +{ + $completions = 0; + $calls = 0; + $totaltime = 0; + $calltime = 0; + + foreach($rs as $r) + { + $completions += $r['completions']; + $calls += $r['totalcalls']; + $totaltime += $r['callattempttotaltime']; + $calltime += $r['calltotaltime']; + } + + if ($totaltime == 0) + { + $effectiveness = 0; + $cph = 0; + $callsph = 0; + } + else + { + $effectiveness = round($calltime / $totaltime,4); + $cph = round($completions/($totaltime/3600),4); + $callsph = round($calls/($totaltime/3600),4); + } + + $rs[] = array("effectiveness" => $effectiveness, "completions" => $completions,"time" => sec_to_time($totaltime),"totalcalls" => $calls,"callt" => sec_to_time($calltime),"CPH" => $cph,"CALLSPH" => $callsph); + + return $rs; +} + + +/** + * Get stats by interviewer + * + * @return arrayh An array containing operator_id,firstName,CPH,effectiveness, + */ +function get_stats() +{ + global $db; + + $sql = "SELECT o.operator_id, o.firstName, (calltime.totaltime / callattempttime.totaltime) AS effectiveness, c.completions,SEC_TO_TIME(callattempttime.totaltime) as time, c.completions/(callattempttime.totaltime / 3600) as CPH, SEC_TO_TIME(calltime.totaltime) as callt, SEC_TO_TIME(callattempttime.totaltime) as callatemptt, calls.calls as totalcalls, calls.calls/(callattempttime.totaltime / 3600) as CALLSPH, calltime.totaltime as calltotaltime, callattempttime.totaltime as callattempttotaltime + FROM operator AS o + JOIN ( + SELECT SUM( TIMESTAMPDIFF( + SECOND , c.start, IFNULL( c.end, CONVERT_TZ( NOW( ) , 'System', 'UTC' ) ) ) ) AS totaltime, operator_id + FROM `call` AS c + GROUP BY operator_id + ) AS calltime ON ( calltime.operator_id = o.operator_id ) + JOIN ( + SELECT SUM( TIMESTAMPDIFF( + SECOND , c.start, IFNULL( c.end, CONVERT_TZ( NOW( ) , 'System', 'UTC' ) ) ) ) AS totaltime, operator_id + FROM `call_attempt` AS c, `case` as b + GROUP BY operator_id + ) AS callattempttime ON ( callattempttime.operator_id = o.operator_id ) + JOIN ( SELECT count(*) as completions,a.operator_id + FROM `call` as a + WHERE a.outcome_id = '10' + GROUP BY a.operator_id) as c on (c.operator_id = o.operator_id) + JOIN ( SELECT count(*) as calls,a.operator_id + FROM `call` as a + GROUP BY a.operator_id) as calls on (calls.operator_id = o.operator_id) + ORDER BY effectiveness DESC"; + + return $db->GetAll($sql); +} + + +/** + * Get stats by interviewer by questionnaire + * + * @param int $questionnaire_id The questionnaire + * @return arrayh An array containing operator_id,firstName,CPH,effectiveness, + */ +function get_stats_by_questionnaire($questionnaire_id) +{ + global $db; + + $sql = "SELECT o.operator_id, o.firstName, (calltime.totaltime / callattempttime.totaltime) AS effectiveness, c.completions,SEC_TO_TIME(callattempttime.totaltime) as time, c.completions/(callattempttime.totaltime / 3600) as CPH, SEC_TO_TIME(calltime.totaltime) as callt, SEC_TO_TIME(callattempttime.totaltime) as callatemptt, calls.calls as totalcalls, calls.calls/(callattempttime.totaltime / 3600) as CALLSPH, calltime.totaltime as calltotaltime, callattempttime.totaltime as callattempttotaltime + + FROM operator AS o + JOIN ( + SELECT SUM( TIMESTAMPDIFF( + SECOND , c.start, IFNULL( c.end, CONVERT_TZ( NOW( ) , 'System', 'UTC' ) ) ) ) AS totaltime, operator_id + FROM `call` AS c, `case` as b + WHERE c.case_id = b.case_id + AND b.questionnaire_id = '$questionnaire_id' + GROUP BY operator_id + ) AS calltime ON ( calltime.operator_id = o.operator_id ) + JOIN ( + SELECT SUM( TIMESTAMPDIFF( + SECOND , c.start, IFNULL( c.end, CONVERT_TZ( NOW( ) , 'System', 'UTC' ) ) ) ) AS totaltime, operator_id + FROM `call_attempt` AS c, `case` as b + WHERE c.case_id = b.case_id + AND b.questionnaire_id = '$questionnaire_id' + GROUP BY operator_id + ) AS callattempttime ON ( callattempttime.operator_id = o.operator_id ) + JOIN ( SELECT count(*) as completions,a.operator_id + FROM `call` as a, `case` as b + WHERE a.outcome_id = '10' + AND a.case_id = b.case_id + AND b.questionnaire_id = '$questionnaire_id' + GROUP BY a.operator_id) as c on (c.operator_id = o.operator_id) + JOIN ( SELECT count(*) as calls,a.operator_id + FROM `call` as a, `case` as b + WHERE a.case_id = b.case_id + AND b.questionnaire_id = '$questionnaire_id' + GROUP BY a.operator_id) as calls on (calls.operator_id = o.operator_id) + ORDER BY effectiveness DESC"; + return $db->GetAll($sql); } @@ -113,13 +316,13 @@ function get_CPH() { global $db; - $sql = "SELECT o.firstName,o.operator_id,c.completions,ca.time, c.completions/ca.time as CPH + $sql = "SELECT o.firstName,o.operator_id,c.completions,SEC_TO_TIME(ca.time) as time, c.completions/(ca.time / 3600) as CPH FROM operator as o JOIN ( SELECT count(*) as completions,operator_id FROM `call` WHERE outcome_id = '10' GROUP BY operator_id) as c on (c.operator_id = o.operator_id) - JOIN ( SELECT SUM( TIMESTAMPDIFF(SECOND , start, IFNULL(end,CONVERT_TZ(NOW(),'System','UTC')))) /3600 as time, operator_id + JOIN ( SELECT SUM( TIMESTAMPDIFF(SECOND , start, IFNULL(end,CONVERT_TZ(NOW(),'System','UTC')))) as time, operator_id FROM `call_attempt` GROUP BY operator_id) as ca on (ca.operator_id = o.operator_id) ORDER BY cph DESC"; diff --git a/functions/functions.xhtml.php b/functions/functions.xhtml.php index 383338b0..b73a93f9 100644 --- a/functions/functions.xhtml.php +++ b/functions/functions.xhtml.php @@ -94,10 +94,12 @@ function xhtml_foot() * @param bool|array $head False if no header otherwise array of header titles * @param string $class Table CSS class * @param bool|array $highlight False if nothing to highlight else an array containing the field to highlight + * @param bool|array $total False if nothing to total else an array containing the fields to total * */ -function xhtml_table($content,$fields,$head = false,$class = "tclass",$highlight=false) +function xhtml_table($content,$fields,$head = false,$class = "tclass",$highlight=false,$total=false) { + $tot = array(); print ""; if ($head) { @@ -114,8 +116,23 @@ function xhtml_table($content,$fields,$head = false,$class = "tclass",$highlight print ""; foreach ($fields as $e) + { print ""; - + if ($total && in_array($e,$total)) + $tot[$e] += $row[$e]; + } + print ""; + } + if ($total) + { + print ""; + foreach ($fields as $e) + { + print ""; + } print ""; } print "
    {$row[$e]}
    "; + if (in_array($e,$total)) + print $tot[$e]; + print "
    "; diff --git a/include/limesurvey/COPYRIGHT.php b/include/limesurvey/COPYRIGHT.php index 0e44020f..c232f231 100644 --- a/include/limesurvey/COPYRIGHT.php +++ b/include/limesurvey/COPYRIGHT.php @@ -1,96 +1,101 @@ - - -LimeSurvey derives from copyrighted works licensed under the GNU General -Public License. This version has been modified pursuant to the -GNU General Public License as of August 5, 2007, 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, including -works copyrighted by any or all of the following, from 2003 through 2007: -Jason Cleeland, Carsten Schmitz, Thibault Le Meur, Josef Prandstetter, -David Olivier, Gustavo San Roman, Sébastien Gaugry, Esteban Adrián Pérez, -Gasper Koren, Yeung Kai Sun, Shawn Wales, Ronald Leenes, Mario Marani, -Darrel O'Pry, Marco Ermini, Patrick McKnight, Chris Wessells, Johannes Kutsam, -Karyl Stein, Arjen Gideonse, Nikolay Tsanov, Thomas Lee, Liang Zhao, -Katarina Pavic, Mikkel Skovgaard Sørensen, Rolf Njor Jensen, Johan Geertsma, -Ronald Leenes, Peter De Berdt, Patrick Drews, Peter Sereinigg, -Artemis Mendrinos, David Selmeczi, Gabriele Carioli, Masaru Ryumae, -Odd-Jarle Kristoffersen, Eirik Sunde, Rosaura Gazzola, Job Vieira Lúcio, -Bogdan Anastasiei, Alexei G. Tchernov, Alexander Shilov, Gasper Koren, -Luis M. Martinez, Juan Rafael Fernández, Jose Luis Ramirez, Björn Mildh, -Niklas Andersson, Vinh Ngo and Mitchell Butler. - -LimeSurvey also includes or is derivative of works distributed under the following copyright notices: - -PHPSurveyor ----- -Copyright: Jason Cleeland, 2003 -License: GNU General Public License (GPL V2 or later) - -ADOdb ----- -Copyright: John Lim, 2004 -License: GNU Lesser General Public License (LGPL) - -PHP-gettext ----- -Copyright: Danilo Segan, 2003, 2006 -License: GNU General Public License (GPL V2 or later) - -DHTML Calendar Widget ----- -Copyright: Mihai Bazon, 2002-2005 -License: GNU Lesser General Public License (LGPL) - -Slider ----- -Copyright: Erik Arvidsson, 1999 - 2002 -License: GNU General Public License - -SHA256 static class ----- -Copyright: Developer's Network (2005) -Author: feyd _at_ devnetwork .dot. net -License: GNU Lesser General Public License (LGPL) - -tabPANE ----- -Copyright: Emil A Eklund (2004) http://webfx.eae.net -License: Apache Software License 2.0 - -PEAR ----- -Copyright: 1997-2004 The PHP Group -License: PHP license - -phpMailer ----- -Copyright: 2001 - 2003 Brent R. Matzelle -License: GNU Lesser General Public License (LGPL) - -Sanitize Library ---- -Copyright: 2002,2003 Free Software Foundation -License: GNU General Public License (GPL) - -TCPDF Class ---- -Copyright: 2006 Nicola Asuni -License: GNU Lesser General Public License (LGPL) - + + +LimeSurvey derives from copyrighted works licensed under the GNU General +Public License. This version has been modified pursuant to the +GNU General Public License as of August 5, 2007, 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, including +works copyrighted by any or all of the following, from 2003 through 2007: +Jason Cleeland, Carsten Schmitz, Thibault Le Meur, Josef Prandstetter, +David Olivier, Gustavo San Roman, Sébastien Gaugry, Esteban Adrián Pérez, +Gasper Koren, Yeung Kai Sun, Shawn Wales, Ronald Leenes, Mario Marani, +Darrel O'Pry, Marco Ermini, Patrick McKnight, Chris Wessells, Johannes Kutsam, +Karyl Stein, Arjen Gideonse, Nikolay Tsanov, Thomas Lee, Liang Zhao, +Katarina Pavic, Mikkel Skovgaard Sørensen, Rolf Njor Jensen, Johan Geertsma, +Ronald Leenes, Peter De Berdt, Patrick Drews, Peter Sereinigg, +Artemis Mendrinos, David Selmeczi, Gabriele Carioli, Masaru Ryumae, +Odd-Jarle Kristoffersen, Eirik Sunde, Rosaura Gazzola, Job Vieira Lúcio, +Bogdan Anastasiei, Alexei G. Tchernov, Alexander Shilov, Gasper Koren, +Luis M. Martinez, Juan Rafael Fernández, Jose Luis Ramirez, Björn Mildh, +Niklas Andersson, Vinh Ngo and Mitchell Butler. + +LimeSurvey also includes or is derivative of works distributed under the following copyright notices: + +PHPSurveyor +---- +Copyright: Jason Cleeland, 2003 +License: GNU General Public License (GPL V2 or later) + +ADOdb +---- +Copyright: John Lim, 2004 +License: GNU Lesser General Public License (LGPL) + +PHP-gettext +---- +Copyright: Danilo Segan, 2003, 2006 +License: GNU General Public License (GPL V2 or later) + +DHTML Calendar Widget +---- +Copyright: Mihai Bazon, 2002-2005 +License: GNU Lesser General Public License (LGPL) + +Slider +---- +Copyright: Erik Arvidsson, 1999 - 2002 +License: GNU General Public License + +SHA256 static class +---- +Copyright: Developer's Network (2005) +Author: feyd _at_ devnetwork .dot. net +License: GNU Lesser General Public License (LGPL) + +tabPANE +---- +Copyright: Emil A Eklund (2004) http://webfx.eae.net +License: Apache Software License 2.0 + +PEAR +---- +Copyright: 1997-2004 The PHP Group +License: PHP license + +phpMailer +---- +Copyright: 2001 - 2003 Brent R. Matzelle +License: GNU Lesser General Public License (LGPL) + +Sanitize Library +---- +Copyright: 2002,2003 Free Software Foundation +License: GNU General Public License (GPL) + +TCPDF Class +---- +Copyright: 2006 Nicola Asuni +License: GNU Lesser General Public License (LGPL) + +mint_idea Template +---- +Copyright: David Kohout http://www.davidkohout.cz +License: GNU General Public License (GPL) + \ No newline at end of file diff --git a/include/limesurvey/LICENSE.php b/include/limesurvey/LICENSE.php index bd6dccb1..0ca61f3f 100644 --- a/include/limesurvey/LICENSE.php +++ b/include/limesurvey/LICENSE.php @@ -1,340 +1,340 @@ -GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 - - Copyright (C) 1989, 1991 Free Software Foundation, Inc. - 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Library General Public License instead.) You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -this service if you wish), that you receive source code or can get it -if you want it, that you can change the software or use pieces of it -in new free programs; and that you know you can do these things. - - To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. - - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. - - The precise terms and conditions for copying, distribution and -modification follow. - - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - - 1. You may copy and distribute verbatim copies of the Program's -source code as you receive it, in any medium, provided that you -conspicuously and appropriately publish on each copy an appropriate -copyright notice and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. - -You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a fee. - - 2. You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. - -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: - - a) Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. - -If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this License. -However, parties who have received copies, or rights, from you under -this License will not have their licenses terminated so long as such -parties remain in full compliance. - - 5. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject to -these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to -this License. - - 7. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 9. The Free Software Foundation may publish revised and/or new versions -of the General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - -Each version is given a distinguishing version number. If the Program -specifies a version number of this License which applies to it and "any -later version", you have the option of following the terms and conditions -either of that version or of any later version published by the Free -Software Foundation. If the Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. - - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the author -to ask for permission. For software which is copyrighted by the Free -Software Foundation, write to the Free Software Foundation; we sometimes -make exceptions for this. Our decision will be guided by the two goals -of preserving the free status of all derivatives of our free software and -of promoting the sharing and reuse of software generally. - - NO WARRANTY - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS -TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, -REPAIR OR CORRECTION. - - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR -REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING -OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED -TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER -PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - 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 - - -Also add information on how to contact you by electronic and paper mail. - -If the program is interactive, make it output a short notice like this -when it starts in an interactive mode: - - Gnomovision version 69, Copyright (C) year name of author - Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, the commands you use may -be called something other than `show w' and `show c'; they could even be -mouse-clicks or menu items--whatever suits your program. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the program, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the program - `Gnomovision' (which makes passes at compilers) written by James Hacker. - - , 1 April 1989 - Ty Coon, President of Vice - -This General Public License does not permit incorporating your program into -proprietary programs. If your program is a subroutine library, you may -consider it more useful to permit linking proprietary applications with the -library. If this is what you want to do, use the GNU Library General -Public License instead of this License. +GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Library General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + 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 + + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Library General +Public License instead of this License. diff --git a/include/limesurvey/admin/access_denied.php b/include/limesurvey/admin/access_denied.php index 937de1d7..c68cf317 100644 --- a/include/limesurvey/admin/access_denied.php +++ b/include/limesurvey/admin/access_denied.php @@ -1,141 +1,141 @@ -".$clang->gT("Access denied!")."
    \n"; - - $action=returnglobal('action'); - if ( $action == "dumpdb" ) - { - $accesssummary .= "

    ".$clang->gT("You are not allowed dump the database!")."

    "; - $accesssummary .= "".$clang->gT("Continue")."
     \n"; - } - elseif($action == "dumplabel") - { - $accesssummary .= "

    ".$clang->gT("You are not allowed export a label set!")."

    "; - $accesssummary .= "".$clang->gT("Continue")."
     \n"; - } - elseif($action == "edituser") - { - $accesssummary .= $clang->gT("You are not allowed to change user data!"); - $accesssummary .= "

    ".$clang->gT("Continue")."
     \n"; - } - elseif($action == "newsurvey") - { - $accesssummary .= "

    ".$clang->gT("You are not allowed to create new surveys!")."

    "; - $accesssummary .= "".$clang->gT("Continue")."
     \n"; - } - elseif($action == "deletesurvey") - { - $accesssummary .= "

    ".$clang->gT("You are not allowed to delete this survey!")."

    "; - $accesssummary .= "".$clang->gT("Continue")."
     \n"; - } - elseif($action == "addquestion") - { - $accesssummary .= "

    ".$clang->gT("You are not allowed to add new questions for this survey!")."

    "; - $accesssummary .= "".$clang->gT("Continue")."
     \n"; - } - elseif($action == "activate") - { - $accesssummary .= "

    ".$clang->gT("You are not allowed to activate this survey!")."

    "; - $accesssummary .= "".$clang->gT("Continue")."
     \n"; - } - elseif($action == "deactivate") - { - $accesssummary .= "

    ".$clang->gT("You are not allowed to deactivate this survey!")."

    "; - $accesssummary .= "".$clang->gT("Continue")."
     \n"; - } - elseif($action == "addgroup") - { - $accesssummary .= "

    ".$clang->gT("You are not allowed to add a group to this survey!")."

    "; - $accesssummary .= "".$clang->gT("Continue")."
     \n"; - } - elseif($action == "ordergroups") - { - $accesssummary .= "

    ".$clang->gT("You are not allowed to order groups in this survey!")."

    "; - $accesssummary .= "".$clang->gT("Continue")."
     \n"; - } - elseif($action == "editsurvey") - { - $accesssummary .= "

    ".$clang->gT("You are not allowed to edit this survey!")."

    "; - $accesssummary .= "".$clang->gT("Continue")."
     \n"; - } - elseif($action == "editgroup") - { - $accesssummary .= "

    ".$clang->gT("You are not allowed to edit groups in this survey!")."

    "; - $accesssummary .= "".$clang->gT("Continue")."
     \n"; - } - elseif($action == "browse_response" || $action == "listcolumn" || $action == "vvexport" || $action == "vvimport") - { - $accesssummary .= "

    ".$clang->gT("You are not allowed to browse responses!")."

    "; - $accesssummary .= "".$clang->gT("Continue")."
     \n"; - } - elseif($action == "assessment") - { - $accesssummary .= "

    ".$clang->gT("You are not allowed to set assessment rules!")."

    "; - $accesssummary .= "".$clang->gT("Continue")."
     \n"; - } - elseif($action == "delusergroup") - { - $accesssummary .= "

    ".$clang->gT("You are not allowed to delete this group!")."

    "; - $accesssummary .= "".$clang->gT("Continue")."
     \n"; - } - elseif($action == "importsurvey") - { - $accesssummary .= "

    ".$clang->gT("You are not allowed to import a survey!")."

    "; - $accesssummary .= "".$clang->gT("Continue")."
     \n"; - } - - elseif($action == "importgroup") - { - $accesssummary .= "

    ".$clang->gT("You are not allowed to import a group!")."

    "; - $accesssummary .= "".$clang->gT("Continue")."
     \n"; - } - elseif($action == "importquestion") - { - $accesssummary .= "

    ".$clang->gT("You are not allowed to to import a question!")."

    "; - $accesssummary .= "".$clang->gT("Continue")."
     \n"; - } - elseif($action == "CSRFwarn") - { - $accesssummary .= "

    ".$clang->gT("Security Alert").": ".$clang->gT("Someone may be trying to use your LimeSurvey session (CSRF attack suspected). If you just clicked on a malicious link, please report this to your system administrator.")."

    "; - $accesssummary .= "".$clang->gT("Continue")."
     \n"; - } - elseif($action == "FakeGET") - { - $accesssummary .= "

    ".$clang->gT("Security Alert").": ".$clang->gT("Someone may be trying to use your LimeSurvey session by using dangerous GET requests (CSRF attack suspected). If you just clicked on a malicious link, please report this to your system administrator.")."

    "; - $accesssummary .= "".$clang->gT("Continue")."
     \n"; - } - else - { - $accesssummary .= "
    ".$clang->gT("You are not allowed to perform this operation!")."
    \n"; - if(!empty($sid)) - $accesssummary .= "

    gT("Continue")."
     \n"; - } - else - $accesssummary .= "

    ".$clang->gT("Continue")."
     \n"; - } - - } -?> +".$clang->gT("Access denied!")."
    \n"; + + $action=returnglobal('action'); + if ( $action == "dumpdb" ) + { + $accesssummary .= "

    ".$clang->gT("You are not allowed dump the database!")."

    "; + $accesssummary .= "".$clang->gT("Continue")."
     \n"; + } + elseif($action == "dumplabel") + { + $accesssummary .= "

    ".$clang->gT("You are not allowed export a label set!")."

    "; + $accesssummary .= "".$clang->gT("Continue")."
     \n"; + } + elseif($action == "edituser") + { + $accesssummary .= $clang->gT("You are not allowed to change user data!"); + $accesssummary .= "

    ".$clang->gT("Continue")."
     \n"; + } + elseif($action == "newsurvey") + { + $accesssummary .= "

    ".$clang->gT("You are not allowed to create new surveys!")."

    "; + $accesssummary .= "".$clang->gT("Continue")."
     \n"; + } + elseif($action == "deletesurvey") + { + $accesssummary .= "

    ".$clang->gT("You are not allowed to delete this survey!")."

    "; + $accesssummary .= "".$clang->gT("Continue")."
     \n"; + } + elseif($action == "addquestion") + { + $accesssummary .= "

    ".$clang->gT("You are not allowed to add new questions for this survey!")."

    "; + $accesssummary .= "".$clang->gT("Continue")."
     \n"; + } + elseif($action == "activate") + { + $accesssummary .= "

    ".$clang->gT("You are not allowed to activate this survey!")."

    "; + $accesssummary .= "".$clang->gT("Continue")."
     \n"; + } + elseif($action == "deactivate") + { + $accesssummary .= "

    ".$clang->gT("You are not allowed to deactivate this survey!")."

    "; + $accesssummary .= "".$clang->gT("Continue")."
     \n"; + } + elseif($action == "addgroup") + { + $accesssummary .= "

    ".$clang->gT("You are not allowed to add a group to this survey!")."

    "; + $accesssummary .= "".$clang->gT("Continue")."
     \n"; + } + elseif($action == "ordergroups") + { + $accesssummary .= "

    ".$clang->gT("You are not allowed to order groups in this survey!")."

    "; + $accesssummary .= "".$clang->gT("Continue")."
     \n"; + } + elseif($action == "editsurvey") + { + $accesssummary .= "

    ".$clang->gT("You are not allowed to edit this survey!")."

    "; + $accesssummary .= "".$clang->gT("Continue")."
     \n"; + } + elseif($action == "editgroup") + { + $accesssummary .= "

    ".$clang->gT("You are not allowed to edit groups in this survey!")."

    "; + $accesssummary .= "".$clang->gT("Continue")."
     \n"; + } + elseif($action == "browse_response" || $action == "listcolumn" || $action == "vvexport" || $action == "vvimport") + { + $accesssummary .= "

    ".$clang->gT("You are not allowed to browse responses!")."

    "; + $accesssummary .= "".$clang->gT("Continue")."
     \n"; + } + elseif($action == "assessment") + { + $accesssummary .= "

    ".$clang->gT("You are not allowed to set assessment rules!")."

    "; + $accesssummary .= "".$clang->gT("Continue")."
     \n"; + } + elseif($action == "delusergroup") + { + $accesssummary .= "

    ".$clang->gT("You are not allowed to delete this group!")."

    "; + $accesssummary .= "".$clang->gT("Continue")."
     \n"; + } + elseif($action == "importsurvey") + { + $accesssummary .= "

    ".$clang->gT("You are not allowed to import a survey!")."

    "; + $accesssummary .= "".$clang->gT("Continue")."
     \n"; + } + + elseif($action == "importgroup") + { + $accesssummary .= "

    ".$clang->gT("You are not allowed to import a group!")."

    "; + $accesssummary .= "".$clang->gT("Continue")."
     \n"; + } + elseif($action == "importquestion") + { + $accesssummary .= "

    ".$clang->gT("You are not allowed to to import a question!")."

    "; + $accesssummary .= "".$clang->gT("Continue")."
     \n"; + } + elseif($action == "CSRFwarn") + { + $accesssummary .= "

    ".$clang->gT("Security Alert").": ".$clang->gT("Someone may be trying to use your LimeSurvey session (CSRF attack suspected). If you just clicked on a malicious link, please report this to your system administrator.")."

    "; + $accesssummary .= "".$clang->gT("Continue")."
     \n"; + } + elseif($action == "FakeGET") + { + $accesssummary .= "

    ".$clang->gT("Security Alert").": ".$clang->gT("Someone may be trying to use your LimeSurvey session by using dangerous GET requests (CSRF attack suspected). If you just clicked on a malicious link, please report this to your system administrator.")."

    "; + $accesssummary .= "".$clang->gT("Continue")."
     \n"; + } + else + { + $accesssummary .= "
    ".$clang->gT("You are not allowed to perform this operation!")."
    \n"; + if(!empty($sid)) + $accesssummary .= "

    gT("Continue")."
     \n"; + } + else + $accesssummary .= "

    ".$clang->gT("Continue")."
     \n"; + } + + } +?> diff --git a/include/limesurvey/admin/activate.php b/include/limesurvey/admin/activate.php index 68df1576..7a05378e 100644 --- a/include/limesurvey/admin/activate.php +++ b/include/limesurvey/admin/activate.php @@ -1,550 +1,588 @@ -".$connect->ErrorMsg()); - while ($row=$result->FetchRow()) {$lastqid=$row['qid'];} - $newqid=$lastqid+1; - $query = "UPDATE {$dbprefix}questions SET qid=$newqid WHERE qid=$oldqid"; - $result = $connect->Execute($query) or safe_die($query."
    ".$connect->ErrorMsg()); - //Update conditions.. firstly conditions FOR this question - $query = "UPDATE {$dbprefix}conditions SET qid=$newqid WHERE qid=$oldqid"; - $result = $connect->Execute($query) or safe_die($query."
    ".$connect->ErrorMsg()); - //Now conditions based upon this question - $query = "SELECT cqid, cfieldname FROM {$dbprefix}conditions WHERE cqid=$oldqid"; - $result = db_execute_assoc($query) or safe_die($query."
    ".$connect->ErrorMsg()); - while ($row=$result->FetchRow()) - { - $switcher[]=array("cqid"=>$row['cqid'], "cfieldname"=>$row['cfieldname']); - } - if (isset($switcher)) - { - foreach ($switcher as $switch) - { - $query = "UPDATE {$dbprefix}conditions - SET cqid=$newqid, - cfieldname='".str_replace("X".$oldqid, "X".$newqid, $switch['cfieldname'])."' - WHERE cqid=$oldqid"; - $result = $connect->Execute($query) or safe_die($query."
    ".$connect->ErrorMsg()); - } - } - //Now question_attributes - $query = "UPDATE {$dbprefix}question_attributes SET qid=$newqid WHERE qid=$oldqid"; - $result = $connect->Execute($query) or safe_die($query."
    ".$connect->ErrorMsg()); - //Now answers - $query = "UPDATE {$dbprefix}answers SET qid=$newqid WHERE qid=$oldqid"; - $result = $connect->Execute($query) or safe_die($query."
    ".$connect->ErrorMsg()); - } - //CHECK TO MAKE SURE ALL QUESTION TYPES THAT REQUIRE ANSWERS HAVE ACTUALLY GOT ANSWERS - //THESE QUESTION TYPES ARE: - // # "L" -> LIST - // # "O" -> LIST WITH COMMENT - // # "M" -> MULTIPLE OPTIONS - // # "P" -> MULTIPLE OPTIONS WITH COMMENTS - // # "A", "B", "C", "E", "F", "H", "^" -> Various Array Types - // # "R" -> RANKING - // # "U" -> FILE CSV MORE - // # "I" -> FILE CSV ONE - // # "1" -> MULTI SCALE - - - - $chkquery = "SELECT qid, question, gid FROM {$dbprefix}questions WHERE sid={$_GET['sid']} AND type IN ('L', 'O', 'M', 'P', 'A', 'B', 'C', 'E', 'F', 'R', 'J', '!', '^', '1')"; - $chkresult = db_execute_assoc($chkquery) or safe_die ("Couldn't get list of questions
    $chkquery
    ".$connect->ErrorMsg()); - while ($chkrow = $chkresult->FetchRow()) - { - $chaquery = "SELECT * FROM {$dbprefix}answers WHERE qid = {$chkrow['qid']} ORDER BY sortorder, answer"; - $charesult=$connect->Execute($chaquery); - $chacount=$charesult->RecordCount(); - if (!$chacount > 0) - { - $failedcheck[]=array($chkrow['qid'], $chkrow['question'], ": ".$clang->gT("This question is a multiple answer type question but has no answers."), $chkrow['gid']); - } - } - - //NOW CHECK THAT ALL QUESTIONS HAVE A 'QUESTION TYPE' FIELD - $chkquery = "SELECT qid, question, gid FROM {$dbprefix}questions WHERE sid={$_GET['sid']} AND type = ''"; - $chkresult = db_execute_assoc($chkquery) or safe_die ("Couldn't check questions for missing types
    $chkquery
    ".$connect->ErrorMsg()); - while ($chkrow = $chkresult->FetchRow()) - { - $failedcheck[]=array($chkrow['qid'], $chkrow['question'], ": ".$clang->gT("This question does not have a question 'type' set."), $chkrow['gid']); - } - - - - - //CHECK THAT FLEXIBLE LABEL TYPE QUESTIONS HAVE AN "LID" SET - $chkquery = "SELECT qid, question, gid FROM {$dbprefix}questions WHERE sid={$_GET['sid']} AND type IN ('F', 'H', 'W', 'Z', '1') AND (lid = 0 OR lid is null)"; - $chkresult = db_execute_assoc($chkquery) or safe_die ("Couldn't check questions for missing LIDs
    $chkquery
    ".$connect->ErrorMsg()); - while($chkrow = $chkresult->FetchRow()){ - $failedcheck[]=array($chkrow['qid'], $chkrow['question'], ": ".$clang->gT("This question requires a Labelset, but none is set."), $chkrow['gid']); - } // while - - //CHECK THAT FLEXIBLE LABEL TYPE QUESTIONS HAVE AN "LID1" SET FOR MULTI SCALE - $chkquery = "SELECT qid, question, gid FROM {$dbprefix}questions WHERE sid={$_GET['sid']} AND (type ='1') AND (lid1 = 0 OR lid1 is null)"; - $chkresult = db_execute_assoc($chkquery) or safe_die ("Couldn't check questions for missing LIDs
    $chkquery
    ".$connect->ErrorMsg()); - while($chkrow = $chkresult->FetchRow()){ - $failedcheck[]=array($chkrow['qid'], $chkrow['question'], ": ".$clang->gT("This question requires a second Labelset, but none is set."), $chkrow['gid']); - } // while - - - //NOW check that all used labelsets have all necessary languages - $chkquery = "SELECT qid, question, gid, lid FROM {$dbprefix}questions WHERE sid={$_GET['sid']} AND type IN ('F', 'H', 'W', 'Z', '1') AND (lid > 0) AND (lid is not null)"; - $chkresult = db_execute_assoc($chkquery) or safe_die ("Couldn't check questions for missing LID languages
    $chkquery
    ".$connect->ErrorMsg()); - $slangs = GetAdditionalLanguagesFromSurveyID($surveyid); - $baselang = GetBaseLanguageFromSurveyID($surveyid); - array_unshift($slangs,$baselang); - while ($chkrow = $chkresult->FetchRow()) - { - foreach ($slangs as $surveylanguage) - { - $chkquery2 = "SELECT lid FROM {$dbprefix}labels WHERE language='$surveylanguage' AND (lid = {$chkrow['lid']}) "; - $chkresult2 = db_execute_assoc($chkquery2); - if ($chkresult2->RecordCount()==0) - { - $failedcheck[]=array($chkrow['qid'], $chkrow['question'], ": ".$clang->gT("The labelset used in this question does not exists or is missing a translation."), $chkrow['gid']); - } - } //foreach - } //while - - //CHECK THAT ALL CONDITIONS SET ARE FOR QUESTIONS THAT PRECEED THE QUESTION CONDITION - //A: Make an array of all the qids in order of appearance - // $qorderquery="SELECT * FROM {$dbprefix}questions, {$dbprefix}groups WHERE {$dbprefix}questions.gid={$dbprefix}groups.gid AND {$dbprefix}questions.sid={$_GET['sid']} ORDER BY {$dbprefix}groups.sortorder, {$dbprefix}questions.title"; - // $qorderresult=$connect->Execute($qorderquery) or safe_die("Couldn't generate a list of questions in order
    $qorderquery
    ".$connect->ErrorMsg()); - // $qordercount=$qorderresult->RecordCount(); - // $c=0; - // while ($qorderrow=$qorderresult->FetchRow()) - // { - // $qidorder[]=array($c, $qorderrow['qid']); - // $c++; - // } - //TO AVOID NATURAL SORT ORDER ISSUES, FIRST GET ALL QUESTIONS IN NATURAL SORT ORDER, AND FIND OUT WHICH NUMBER IN THAT ORDER THIS QUESTION IS - $qorderquery = "SELECT * FROM {$dbprefix}questions WHERE sid=$surveyid AND type not in ('S', 'D', 'T', 'Q')"; - $qorderresult = db_execute_assoc($qorderquery) or safe_die ("$qorderquery
    ".$connect->ErrorMsg()); - $qrows = array(); //Create an empty array in case FetchRow does not return any rows - while ($qrow = $qorderresult->FetchRow()) {$qrows[] = $qrow;} // Get table output into array - usort($qrows, 'CompareGroupThenTitle'); // Perform a case insensitive natural sort on group name then question title of a multidimensional array - $c=0; - foreach ($qrows as $qr) - { - $qidorder[]=array($c, $qrow['qid']); - $c++; - } - $qordercount=""; - //1: Get each condition's question id - $conquery= "SELECT {$dbprefix}conditions.qid, cqid, {$dbprefix}questions.question, " - . "{$dbprefix}questions.gid " - . "FROM {$dbprefix}conditions, {$dbprefix}questions, {$dbprefix}groups " - . "WHERE {$dbprefix}conditions.qid={$dbprefix}questions.qid " - . "AND {$dbprefix}questions.gid={$dbprefix}groups.gid ORDER BY {$dbprefix}conditions.qid"; - $conresult=db_execute_assoc($conquery) or safe_die("Couldn't check conditions for relative consistency
    $conquery
    ".$connect->ErrorMsg()); - //2: Check each conditions cqid that it occurs later than the cqid - while ($conrow=$conresult->FetchRow()) - { - $cqidfound=0; - $qidfound=0; - $b=0; - while ($b<$qordercount) - { - if ($conrow['cqid'] == $qidorder[$b][1]) - { - $cqidfound = 1; - $b=$qordercount; - } - if ($conrow['qid'] == $qidorder[$b][1]) - { - $qidfound = 1; - $b=$qordercount; - } - if ($qidfound == 1) - { - $failedcheck[]=array($conrow['qid'], $conrow['question'], ": ".$clang->gT("This question has a condition set, however the condition is based on a question that appears after it."), $conrow['gid']); - } - $b++; - } - } - //CHECK THAT ALL THE CREATED FIELDS WILL BE UNIQUE - $fieldmap=createFieldMap($surveyid, "full"); - if (isset($fieldmap)) - { - foreach($fieldmap as $fielddata) - { - $fieldlist[]=$fielddata['fieldname']; - } - $fieldlist=array_reverse($fieldlist); //let's always change the later duplicate, not the earlier one - } - $checkKeysUniqueComparison = create_function('$value','if ($value > 1) return true;'); - @$duplicates = array_keys (array_filter (array_count_values($fieldlist), $checkKeysUniqueComparison)); - if (isset($duplicates)) - { - foreach ($duplicates as $dup) - { - $badquestion=arraySearchByKey($dup, $fieldmap, "fieldname", 1); - $fix = "[Click Here to Fix]"; - $failedcheck[]=array($badquestion['qid'], $badquestion['question'], ": Bad duplicate fieldname $fix", $badquestion['gid']); - } - } - - //IF ANY OF THE CHECKS FAILED, PRESENT THIS SCREEN - if (isset($failedcheck) && $failedcheck) - { - $activateoutput .= "
    \n\n"; - $activateoutput .= "\t\t\t\t\n"; - $activateoutput .= "\t\n"; - $activateoutput .= "\t\t\n"; - $activateoutput .= "\t\n"; - $activateoutput .= "\t\n"; - $activateoutput .= "\t\t\n"; - $activateoutput .= "\t\n"; - $activateoutput .= "
    ".$clang->gT("Activate Survey")." ($surveyid)
    \n"; - $activateoutput .= "\t\t\t".$clang->gT("Error")."
    \n"; - $activateoutput .= "\t\t\t".$clang->gT("Survey does not pass consistency check")."
    \n"; - $activateoutput .= "\t\t
    \n"; - $activateoutput .= "\t\t\t".$clang->gT("The following problems have been found:")."
    \n"; - $activateoutput .= "\t\t\t
      \n"; - foreach ($failedcheck as $fc) - { - $activateoutput .= "\t\t\t\t
    • Question qid-{$fc[0]} (\"{$fc[1]}\"){$fc[2]}
    • \n"; - } - $activateoutput .= "\t\t\t
    \n"; - $activateoutput .= "\t\t\t".$clang->gT("The survey cannot be activated until these problems have been resolved.")."\n"; - $activateoutput .= "\t\t

     \n"; - - return; - } - - $activateoutput .= "
    \n\n"; - $activateoutput .= "\t\t\t\t\n"; - $activateoutput .= "\t\n"; - $activateoutput .= "\t\t\n"; - $activateoutput .= "\t\n"; - $activateoutput .= "\t\n"; - $activateoutput .= "\t\t\n"; - $activateoutput .= "\t\n"; - $activateoutput .= "\t\n"; - $activateoutput .= "\t\t\n"; - $activateoutput .= "\t\n"; - $activateoutput .= "
    ".$clang->gT("Activate Survey")." ($surveyid)
    \n"; - $activateoutput .= "\t\t\t".$clang->gT("Warning")."
    \n"; - $activateoutput .= "\t\t\t".$clang->gT("READ THIS CAREFULLY BEFORE PROCEEDING")."\n"; - $activateoutput .= "\t\t\t
    \n"; - $activateoutput .= "\t\t
    \n"; - $activateoutput .= $clang->gT("You should only activate a survey when you are absolutely certain that your survey setup is finished and will not need changing.")."

    \n"; - $activateoutput .= $clang->gT("Once a survey is activated you can no longer:")."
    • ".$clang->gT("Add or delete groups")."
    • ".$clang->gT("Add or remove answers to Multiple Answer questions")."
    • ".$clang->gT("Add or delete questions")."
    \n"; - $activateoutput .= $clang->gT("However you can still:")."
    • ".$clang->gT("Edit (change) your questions code, text or type")."
    • ".$clang->gT("Edit (change) your group names")."
    • ".$clang->gT("Add, Remove or Edit pre-defined question answers (except for Multi-answer questions)")."
    • ".$clang->gT("Change survey name or description")."
    \n"; - $activateoutput .= $clang->gT("Once data has been entered into this survey, if you want to add or remove groups or questions, you will need to de-activate this survey, which will move all data that has already been entered into a separate archived table.")."

    \n"; - $activateoutput .= "\t\t
    \n"; -// $activateoutput .= "\t\t\tgT("Activate Survey")."\" onclick=\"window.open('$scriptname?action=activate&ok=Y&sid={$_GET['sid']}', '_self')\" />\n"; - $activateoutput .= "\t\t\tgT("Activate Survey")."\" onclick=\"".get2post("$scriptname?action=activate&ok=Y&sid={$_GET['sid']}")."\" />\n"; - $activateoutput .= "\t\t
     

     \n"; - -} -else -{ - //Create the survey responses table - $createsurvey = "id I NOTNULL AUTO PRIMARY,\n"; - $createsurvey .= " submitdate T,\n"; - $createsurvey .= " startlanguage C(20) NOTNULL ,\n"; - //Check for any additional fields for this survey and create necessary fields (token and datestamp) - $pquery = "SELECT private, allowregister, datestamp, ipaddr, refurl FROM {$dbprefix}surveys WHERE sid={$postsid}"; - $presult=db_execute_assoc($pquery); - while($prow=$presult->FetchRow()) - { - if ($prow['private'] == "N") - { - $createsurvey .= " token C(36),\n"; - $surveynotprivate="TRUE"; - } - if ($prow['allowregister'] == "Y") - { - $surveyallowsregistration="TRUE"; - } - if ($prow['datestamp'] == "Y") - { - $createsurvey .= " datestamp T NOTNULL,\n"; - $createsurvey .= " startdate T NOTNULL,\n"; - } - if ($prow['ipaddr'] == "Y") - { - $createsurvey .= " ipaddr X,\n"; - } - //Check to see if 'refurl' field is required. - if ($prow['refurl'] == "Y") - { - $createsurvey .= " refurl X,\n"; - } - } - //Get list of questions for the base language - $aquery = " SELECT * FROM ".db_table_name('questions').", ".db_table_name('groups') - ." WHERE ".db_table_name('questions').".gid=".db_table_name('groups').".gid " - ." AND ".db_table_name('questions').".sid={$postsid} " - ." AND ".db_table_name('groups').".language='".GetbaseLanguageFromSurveyid($postsid). "' " - ." AND ".db_table_name('questions').".language='".GetbaseLanguageFromSurveyid($postsid). "' " - ." ORDER BY ".db_table_name('groups').".group_order, title"; - $aresult = db_execute_assoc($aquery); - while ($arow=$aresult->FetchRow()) //With each question, create the appropriate field(s) - { - if ( substr($createsurvey, strlen($createsurvey)-2, 2) != ",\n") {$createsurvey .= ",\n";} - - if ($arow['type'] != "M" && $arow['type'] != "A" && $arow['type'] != "B" && - $arow['type'] != "C" && $arow['type'] != "E" && $arow['type'] != "F" && - $arow['type'] != "H" && $arow['type'] != "P" && $arow['type'] != "R" && - $arow['type'] != "Q" && $arow['type'] != "^" && $arow['type'] != "J" && - $arow['type'] != "K" && $arow['type'] != "1") - { - $createsurvey .= " `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}`"; - switch($arow['type']) - { - case "N": //NUMERICAL - $createsurvey .= " C(20)"; - break; - case "S": //SHORT TEXT - if ($databasetype=='mysql') {$createsurvey .= " X";} - else {$createsurvey .= " C(255)";} - break; - case "L": //LIST (RADIO) - case "!": //LIST (DROPDOWN) - case "W": - case "Z": - $createsurvey .= " C(5)"; - if ($arow['other'] == "Y") - { - $createsurvey .= ",\n`{$arow['sid']}X{$arow['gid']}X{$arow['qid']}other` X"; - } - break; - case "I": // CSV ONE - $createsurvey .= " C(5)"; - break; - case "O": //DROPDOWN LIST WITH COMMENT - $createsurvey .= " C(5),\n `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}comment` X"; - break; - case "T": //LONG TEXT - $createsurvey .= " X"; - break; - case "U": //HUGE TEXT - $createsurvey .= " X"; - break; - case "D": //DATE - $createsurvey .= " D"; - break; - case "5": //5 Point Choice - case "G": //Gender - case "Y": //YesNo - case "X": //Boilerplate - $createsurvey .= " C(1)"; - break; - } - } - elseif ($arow['type'] == "M" || $arow['type'] == "A" || $arow['type'] == "B" || - $arow['type'] == "C" || $arow['type'] == "E" || $arow['type'] == "F" || - $arow['type'] == "H" || $arow['type'] == "P" || $arow['type'] == "^") - { - //MULTI ENTRY - $abquery = "SELECT a.*, q.other FROM {$dbprefix}answers as a, {$dbprefix}questions as q" - ." WHERE a.qid=q.qid AND sid={$postsid} AND q.qid={$arow['qid']} " - ." AND a.language='".GetbaseLanguageFromSurveyid($postsid). "' " - ." AND q.language='".GetbaseLanguageFromSurveyid($postsid). "' " - ." ORDER BY a.sortorder, a.answer"; - $abresult=db_execute_assoc($abquery) or safe_die ("Couldn't get perform answers query
    $abquery
    ".$connect->ErrorMsg()); - while ($abrow=$abresult->FetchRow()) - { - $createsurvey .= " `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$abrow['code']}` C(5),\n"; - if ($abrow['other']=="Y") {$alsoother="Y";} - if ($arow['type'] == "P") - { - $createsurvey .= " `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$abrow['code']}comment` X,\n"; - } - } - if ((isset($alsoother) && $alsoother=="Y") && ($arow['type']=="M" || $arow['type']=="P" || $arow['type']=="1")) //Sc: check! - { - $createsurvey .= " `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}other` C(255),\n"; - if ($arow['type']=="P") - { - $createsurvey .= " `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}othercomment` X,\n"; - } - } - } - elseif ($arow['type'] == "Q") - { - $abquery = "SELECT a.*, q.other FROM {$dbprefix}answers as a, {$dbprefix}questions as q WHERE a.qid=q.qid AND sid={$postsid} AND q.qid={$arow['qid']} " - ." AND a.language='".GetbaseLanguageFromSurveyid($postsid). "' " - ." AND q.language='".GetbaseLanguageFromSurveyid($postsid). "' " - ." ORDER BY a.sortorder, a.answer"; - $abresult=db_execute_assoc($abquery) or safe_die ("Couldn't get perform answers query
    $abquery
    ".$connect->ErrorMsg()); - while ($abrow = $abresult->FetchRow()) - { - $createsurvey .= " `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$abrow['code']}`"; - if ($databasetype=='mysql') - { - $createsurvey .= " X"; - } - else - { - $createsurvey .= " C(255)"; - } - $createsurvey .= ",\n"; - } - } - - elseif ($arow['type'] == "K") //Multiple Numeric - replica of multiple short text, except numbers only - { - $abquery = "SELECT a.*, q.other FROM {$dbprefix}answers as a, {$dbprefix}questions as q WHERE a.qid=q.qid AND sid={$postsid} AND q.qid={$arow['qid']} " - ." AND a.language='".GetbaseLanguageFromSurveyid($postsid). "' " - ." AND q.language='".GetbaseLanguageFromSurveyid($postsid). "' " - ." ORDER BY a.sortorder, a.answer"; - $abresult=db_execute_assoc($abquery) or safe_die ("Couldn't get perform answers query
    $abquery
    ".$connect->ErrorMsg()); - while ($abrow = $abresult->FetchRow()) - { - $createsurvey .= " `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$abrow['code']}` C(20),\n"; - } - } //End if ($arow['type'] == "K") -/* elseif ($arow['type'] == "J") - { - $abquery = "SELECT {$dbprefix}answers.*, {$dbprefix}questions.other FROM {$dbprefix}answers, {$dbprefix}questions WHERE {$dbprefix}answers.qid={$dbprefix}questions.qid AND sid={$_GET['sid']} AND {$dbprefix}questions.qid={$arow['qid']} ORDER BY {$dbprefix}answers.sortorder, {$dbprefix}answers.answer"; - $abresult=db_execute_assoc($abquery) or safe_die ("Couldn't get perform answers query
    $abquery
    ".$connect->ErrorMsg()); - while ($abrow = $abresultt->FetchRow()) - { - $createsurvey .= " `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$abrow['code']}` C(5),\n"; - } - }*/ - elseif ($arow['type'] == "R") - { - //MULTI ENTRY - $abquery = "SELECT a.*, q.other FROM {$dbprefix}answers as a, {$dbprefix}questions as q" - ." WHERE a.qid=q.qid AND sid={$postsid} AND q.qid={$arow['qid']} " - ." AND a.language='".GetbaseLanguageFromSurveyid($postsid). "' " - ." AND q.language='".GetbaseLanguageFromSurveyid($postsid). "' " - ." ORDER BY a.sortorder, a.answer"; - $abresult=$connect->Execute($abquery) or safe_die ("Couldn't get perform answers query
    $abquery
    ".$connect->ErrorMsg()); - $abcount=$abresult->RecordCount(); - for ($i=1; $i<=$abcount; $i++) - { - $createsurvey .= " `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}$i` C(5),\n"; - } - } - elseif ($arow['type'] == "1") - { - $abquery = "SELECT a.*, q.other FROM {$dbprefix}answers as a, {$dbprefix}questions as q" - ." WHERE a.qid=q.qid AND sid={$postsid} AND q.qid={$arow['qid']} " - ." AND a.language='".GetbaseLanguageFromSurveyid($postsid). "' " - ." AND q.language='".GetbaseLanguageFromSurveyid($postsid). "' " - ." ORDER BY a.sortorder, a.answer"; - $abresult=db_execute_assoc($abquery) or safe_die ("Couldn't get perform answers query
    $abquery
    ".$connect->ErrorMsg()); - $abcount=$abresult->RecordCount(); - while ($abrow = $abresult->FetchRow()) - { - $abmultiscalequery = "SELECT a.*, q.other FROM {$dbprefix}answers as a, {$dbprefix}questions as q, {$dbprefix}labels as l" - ." WHERE a.qid=q.qid AND sid={$postsid} AND q.qid={$arow['qid']} " - ." AND l.lid=q.lid AND sid={$postsid} AND q.qid={$arow['qid']} AND l.title = '' " - ." AND l.language='".GetbaseLanguageFromSurveyid($postsid). "' " - ." AND q.language='".GetbaseLanguageFromSurveyid($postsid). "' "; - $abmultiscaleresult=$connect->Execute($abmultiscalequery) or safe_die ("Couldn't get perform answers query
    $abmultiscalequery
    ".$connect->ErrorMsg()); - $abmultiscaleresultcount =$abmultiscaleresult->RecordCount(); - $abmultiscaleresultcount = 1; - for ($j=0; $j<=$abmultiscaleresultcount; $j++) - { - $createsurvey .= " `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$abrow['code']}#$j` C(5),\n"; - } - } - } - } - - // If last question is of type MCABCEFHP^QKJR let's get rid of the ending coma in createsurvey - $createsurvey = rtrim($createsurvey, ",\n")."\n"; // Does nothing if not ending with a comma - $tabname = "{$dbprefix}survey_{$postsid}"; # not using db_table_name as it quotes the table name (as does CreateTableSQL) - - $taboptarray = array('mysql' => 'TYPE='.$databasetabletype.' CHARACTER SET utf8 COLLATE utf8_unicode_ci'); - $dict = NewDataDictionary($connect); - $sqlarray = $dict->CreateTableSQL($tabname, $createsurvey, $taboptarray); - $execresult=$dict->ExecuteSQLArray($sqlarray,1); - if ($execresult==0 || $execresult==1) - { - $activateoutput .= "
    \n\n" . - "\n" . - "
    ".$clang->gT("Activate Survey")." ($surveyid)
    \n" . - "".$clang->gT("Survey could not be actived.")."
    \n" . - "
    ".$clang->gT("Main Admin Screen")."
    \n" . - "DB ".$clang->gT("Error").":
    \n" . $connect->ErrorMsg() . "\n" . - "
    $createsurvey
    \n" . - "

     \n" . - "\n"; - } - if ($execresult != 0 && $execresult !=1) - { - $anquery = "SELECT autonumber_start FROM {$dbprefix}surveys WHERE sid={$postsid}"; - if ($anresult=db_execute_assoc($anquery)) - { - //if there is an autonumber_start field, start auto numbering here - while($row=$anresult->FetchRow()) - { - if ($row['autonumber_start'] > 0) - { - $autonumberquery = "ALTER TABLE {$dbprefix}survey_{$postsid} AUTO_INCREMENT = ".$row['autonumber_start']; - if ($result = $connect->Execute($autonumberquery)) - { - //We're happy it worked! - } - else - { - //Continue regardless - it's not the end of the world - } - } - } - } - - $activateoutput .= "
    \n\n"; - $activateoutput .= "\t\t\t\t\n"; - $activateoutput .= "\t\t\t\t
    ".$clang->gT("Activate Survey")." ($surveyid)
    ".$clang->gT("Survey has been activated. Results table has been successfully created.")."

    \n"; - - $acquery = "UPDATE {$dbprefix}surveys SET active='Y' WHERE sid=".returnglobal('sid'); - $acresult = $connect->Execute($acquery); - -// Private means data privacy, not closed access survey -// if (isset($surveynotprivate) && $surveynotprivate) //This survey is tracked, and therefore a tokens table MUST exist -// { -// $activateoutput .= $clang->gT("This is not an anonymous survey. A token table must also be created.")."

    \n"; -// $activateoutput .= "\n"; -// } -// elseif (isset($surveyallowsregistration) && $surveyallowsregistration == "TRUE") - if (isset($surveyallowsregistration) && $surveyallowsregistration == "TRUE") - { - $activateoutput .= $clang->gT("This survey allows public registration. A token table must also be created.")."

    \n"; -// $activateoutput .= "\n"; - $activateoutput .= "\n"; - } - else - { - $activateoutput .= $clang->gT("This survey is now active, and responses can be recorded.")."

    \n"; - $activateoutput .= "".$clang->gT("Open-access mode").": ".$clang->gT("No invitation code is needed to complete the survey.")."
    ".$clang->gT("You can switch to the closed-access mode by initialising a token table with the button below.")."

    \n"; -// $activateoutput .= $clang->gT("Optional").": \n"; - $activateoutput .= $clang->gT("Optional").": \n"; - } - $activateoutput .= "\t\t\t\t

     \n"; - } - -} - -?> +".$connect->ErrorMsg()); + while ($row=$result->FetchRow()) {$lastqid=$row['qid'];} + $newqid=$lastqid+1; + $query = "UPDATE {$dbprefix}questions SET qid=$newqid WHERE qid=$oldqid"; + $result = $connect->Execute($query) or safe_die($query."
    ".$connect->ErrorMsg()); + //Update conditions.. firstly conditions FOR this question + $query = "UPDATE {$dbprefix}conditions SET qid=$newqid WHERE qid=$oldqid"; + $result = $connect->Execute($query) or safe_die($query."
    ".$connect->ErrorMsg()); + //Now conditions based upon this question + $query = "SELECT cqid, cfieldname FROM {$dbprefix}conditions WHERE cqid=$oldqid"; + $result = db_execute_assoc($query) or safe_die($query."
    ".$connect->ErrorMsg()); + while ($row=$result->FetchRow()) + { + $switcher[]=array("cqid"=>$row['cqid'], "cfieldname"=>$row['cfieldname']); + } + if (isset($switcher)) + { + foreach ($switcher as $switch) + { + $query = "UPDATE {$dbprefix}conditions + SET cqid=$newqid, + cfieldname='".str_replace("X".$oldqid, "X".$newqid, $switch['cfieldname'])."' + WHERE cqid=$oldqid"; + $result = $connect->Execute($query) or safe_die($query."
    ".$connect->ErrorMsg()); + } + } + //Now question_attributes + $query = "UPDATE {$dbprefix}question_attributes SET qid=$newqid WHERE qid=$oldqid"; + $result = $connect->Execute($query) or safe_die($query."
    ".$connect->ErrorMsg()); + //Now answers + $query = "UPDATE {$dbprefix}answers SET qid=$newqid WHERE qid=$oldqid"; + $result = $connect->Execute($query) or safe_die($query."
    ".$connect->ErrorMsg()); + } + + $baselang = GetBaseLanguageFromSurveyID($postsid); + $groupquery = "SELECT g.gid,g.group_name,count(q.qid) as count from {$dbprefix}questions as q RIGHT JOIN {$dbprefix}groups as g ON q.gid=g.gid WHERE g.sid=$postsid AND g.language='$baselang' AND q.language='$baselang' group by g.gid,g.group_name;"; + $groupresult=db_execute_assoc($groupquery) or safe_die($groupquery."
    ".$connect->ErrorMsg()); + while ($row=$groupresult->FetchRow()) + { //TIBO + if ($row['count'] == 0) + { + $failedgroupcheck[]=array($row['gid'], $row['group_name'], ": ".$clang->gT("This group does not contain any question(s).")); + } + } + + + //CHECK TO MAKE SURE ALL QUESTION TYPES THAT REQUIRE ANSWERS HAVE ACTUALLY GOT ANSWERS + //THESE QUESTION TYPES ARE: + // # "L" -> LIST + // # "O" -> LIST WITH COMMENT + // # "M" -> MULTIPLE OPTIONS + // # "P" -> MULTIPLE OPTIONS WITH COMMENTS + // # "A", "B", "C", "E", "F", "H", "^" -> Various Array Types + // # "R" -> RANKING + // # "U" -> FILE CSV MORE + // # "I" -> FILE CSV ONE + // # ":" -> Array Multi Flexi Numbers + // # ";" -> Array Multi Flexi Text + // # "1" -> MULTI SCALE + + + + $chkquery = "SELECT qid, question, gid FROM {$dbprefix}questions WHERE sid={$_GET['sid']} AND type IN ('L', 'O', 'M', 'P', 'A', 'B', 'C', 'E', 'F', 'R', 'J', '!', '^', ':', '1')"; + $chkresult = db_execute_assoc($chkquery) or safe_die ("Couldn't get list of questions
    $chkquery
    ".$connect->ErrorMsg()); + while ($chkrow = $chkresult->FetchRow()) + { + $chaquery = "SELECT * FROM {$dbprefix}answers WHERE qid = {$chkrow['qid']} ORDER BY sortorder, answer"; + $charesult=$connect->Execute($chaquery); + $chacount=$charesult->RecordCount(); + if (!$chacount > 0) + { + $failedcheck[]=array($chkrow['qid'], $chkrow['question'], ": ".$clang->gT("This question is a multiple answer type question but has no answers."), $chkrow['gid']); + } + } + + //NOW CHECK THAT ALL QUESTIONS HAVE A 'QUESTION TYPE' FIELD + $chkquery = "SELECT qid, question, gid FROM {$dbprefix}questions WHERE sid={$_GET['sid']} AND type = ''"; + $chkresult = db_execute_assoc($chkquery) or safe_die ("Couldn't check questions for missing types
    $chkquery
    ".$connect->ErrorMsg()); + while ($chkrow = $chkresult->FetchRow()) + { + $failedcheck[]=array($chkrow['qid'], $chkrow['question'], ": ".$clang->gT("This question does not have a question 'type' set."), $chkrow['gid']); + } + + + + + //CHECK THAT FLEXIBLE LABEL TYPE QUESTIONS HAVE AN "LID" SET + $chkquery = "SELECT qid, question, gid FROM {$dbprefix}questions WHERE sid={$_GET['sid']} AND type IN ('F', 'H', 'W', 'Z', ':', '1') AND (lid = 0 OR lid is null)"; + $chkresult = db_execute_assoc($chkquery) or safe_die ("Couldn't check questions for missing LIDs
    $chkquery
    ".$connect->ErrorMsg()); + while($chkrow = $chkresult->FetchRow()){ + $failedcheck[]=array($chkrow['qid'], $chkrow['question'], ": ".$clang->gT("This question requires a Labelset, but none is set."), $chkrow['gid']); + } // while + + //CHECK THAT FLEXIBLE LABEL TYPE QUESTIONS HAVE AN "LID1" SET FOR MULTI SCALE + $chkquery = "SELECT qid, question, gid FROM {$dbprefix}questions WHERE sid={$_GET['sid']} AND (type ='1') AND (lid1 = 0 OR lid1 is null)"; + $chkresult = db_execute_assoc($chkquery) or safe_die ("Couldn't check questions for missing LIDs
    $chkquery
    ".$connect->ErrorMsg()); + while($chkrow = $chkresult->FetchRow()){ + $failedcheck[]=array($chkrow['qid'], $chkrow['question'], ": ".$clang->gT("This question requires a second Labelset, but none is set."), $chkrow['gid']); + } // while + + + //NOW check that all used labelsets have all necessary languages + $chkquery = "SELECT qid, question, gid, lid FROM {$dbprefix}questions WHERE sid={$_GET['sid']} AND type IN ('F', 'H', 'W', 'Z', ':', '1') AND (lid > 0) AND (lid is not null)"; + $chkresult = db_execute_assoc($chkquery) or safe_die ("Couldn't check questions for missing LID languages
    $chkquery
    ".$connect->ErrorMsg()); + $slangs = GetAdditionalLanguagesFromSurveyID($surveyid); + $baselang = GetBaseLanguageFromSurveyID($surveyid); + array_unshift($slangs,$baselang); + while ($chkrow = $chkresult->FetchRow()) + { + foreach ($slangs as $surveylanguage) + { + $chkquery2 = "SELECT lid FROM {$dbprefix}labels WHERE language='$surveylanguage' AND (lid = {$chkrow['lid']}) "; + $chkresult2 = db_execute_assoc($chkquery2); + if ($chkresult2->RecordCount()==0) + { + $failedcheck[]=array($chkrow['qid'], $chkrow['question'], ": ".$clang->gT("The labelset used in this question does not exists or is missing a translation."), $chkrow['gid']); + } + } //foreach + } //while + + //CHECK THAT ALL CONDITIONS SET ARE FOR QUESTIONS THAT PRECEED THE QUESTION CONDITION + //A: Make an array of all the qids in order of appearance + // $qorderquery="SELECT * FROM {$dbprefix}questions, {$dbprefix}groups WHERE {$dbprefix}questions.gid={$dbprefix}groups.gid AND {$dbprefix}questions.sid={$_GET['sid']} ORDER BY {$dbprefix}groups.sortorder, {$dbprefix}questions.title"; + // $qorderresult=$connect->Execute($qorderquery) or safe_die("Couldn't generate a list of questions in order
    $qorderquery
    ".$connect->ErrorMsg()); + // $qordercount=$qorderresult->RecordCount(); + // $c=0; + // while ($qorderrow=$qorderresult->FetchRow()) + // { + // $qidorder[]=array($c, $qorderrow['qid']); + // $c++; + // } + //TO AVOID NATURAL SORT ORDER ISSUES, FIRST GET ALL QUESTIONS IN NATURAL SORT ORDER, AND FIND OUT WHICH NUMBER IN THAT ORDER THIS QUESTION IS + $qorderquery = "SELECT * FROM {$dbprefix}questions WHERE sid=$surveyid AND type not in ('S', 'D', 'T', 'Q')"; + $qorderresult = db_execute_assoc($qorderquery) or safe_die ("$qorderquery
    ".$connect->ErrorMsg()); + $qrows = array(); //Create an empty array in case FetchRow does not return any rows + while ($qrow = $qorderresult->FetchRow()) {$qrows[] = $qrow;} // Get table output into array + usort($qrows, 'CompareGroupThenTitle'); // Perform a case insensitive natural sort on group name then question title of a multidimensional array + $c=0; + foreach ($qrows as $qr) + { + $qidorder[]=array($c, $qrow['qid']); + $c++; + } + $qordercount=""; + //1: Get each condition's question id + $conquery= "SELECT {$dbprefix}conditions.qid, cqid, {$dbprefix}questions.question, " + . "{$dbprefix}questions.gid " + . "FROM {$dbprefix}conditions, {$dbprefix}questions, {$dbprefix}groups " + . "WHERE {$dbprefix}conditions.qid={$dbprefix}questions.qid " + . "AND {$dbprefix}questions.gid={$dbprefix}groups.gid ORDER BY {$dbprefix}conditions.qid"; + $conresult=db_execute_assoc($conquery) or safe_die("Couldn't check conditions for relative consistency
    $conquery
    ".$connect->ErrorMsg()); + //2: Check each conditions cqid that it occurs later than the cqid + while ($conrow=$conresult->FetchRow()) + { + $cqidfound=0; + $qidfound=0; + $b=0; + while ($b<$qordercount) + { + if ($conrow['cqid'] == $qidorder[$b][1]) + { + $cqidfound = 1; + $b=$qordercount; + } + if ($conrow['qid'] == $qidorder[$b][1]) + { + $qidfound = 1; + $b=$qordercount; + } + if ($qidfound == 1) + { + $failedcheck[]=array($conrow['qid'], $conrow['question'], ": ".$clang->gT("This question has a condition set, however the condition is based on a question that appears after it."), $conrow['gid']); + } + $b++; + } + } + //CHECK THAT ALL THE CREATED FIELDS WILL BE UNIQUE + $fieldmap=createFieldMap($surveyid, "full"); + if (isset($fieldmap)) + { + foreach($fieldmap as $fielddata) + { + $fieldlist[]=$fielddata['fieldname']; + } + $fieldlist=array_reverse($fieldlist); //let's always change the later duplicate, not the earlier one + } + $checkKeysUniqueComparison = create_function('$value','if ($value > 1) return true;'); + @$duplicates = array_keys (array_filter (array_count_values($fieldlist), $checkKeysUniqueComparison)); + if (isset($duplicates)) + { + foreach ($duplicates as $dup) + { + $badquestion=arraySearchByKey($dup, $fieldmap, "fieldname", 1); + $fix = "[Click Here to Fix]"; + $failedcheck[]=array($badquestion['qid'], $badquestion['question'], ": Bad duplicate fieldname $fix", $badquestion['gid']); + } + } + + //IF ANY OF THE CHECKS FAILED, PRESENT THIS SCREEN + if ((isset($failedcheck) && $failedcheck) || (isset($failedgroupcheck) && $failedgroupcheck)) + { + $activateoutput .= "
    \n\n"; + $activateoutput .= "\t\t\t\t\n"; + $activateoutput .= "\t\n"; + $activateoutput .= "\t\t\n"; + $activateoutput .= "\t\n"; + $activateoutput .= "\t\n"; + $activateoutput .= "\t\t\n"; + $activateoutput .= "\t\n"; + $activateoutput .= "
    ".$clang->gT("Activate Survey")." ($surveyid)
    \n"; + $activateoutput .= "\t\t\t".$clang->gT("Error")."
    \n"; + $activateoutput .= "\t\t\t".$clang->gT("Survey does not pass consistency check")."
    \n"; + $activateoutput .= "\t\t
    \n"; + $activateoutput .= "\t\t\t".$clang->gT("The following problems have been found:")."
    \n"; + $activateoutput .= "\t\t\t
      \n"; + foreach ($failedcheck as $fc) + { + $activateoutput .= "\t\t\t\t
    • Question qid-{$fc[0]} (\"{$fc[1]}\"){$fc[2]}
    • \n"; + } + foreach ($failedgroupcheck as $fg) + { + $activateoutput .= "\t\t\t\t
    • Group gid-{$fg[0]} (\"{$fg[1]}\"){$fg[2]}
    • \n"; + } + $activateoutput .= "\t\t\t
    \n"; + $activateoutput .= "\t\t\t".$clang->gT("The survey cannot be activated until these problems have been resolved.")."\n"; + $activateoutput .= "\t\t

     \n"; + + return; + } + + $activateoutput .= "
    \n
    \n"; + $activateoutput .= "\t\t\t\t
    ".$clang->gT("Activate Survey")." ($surveyid)
    \n"; + $activateoutput .= "\t\t
    \n"; + $activateoutput .= $clang->gT("Warning")."
    \n"; + $activateoutput .= $clang->gT("READ THIS CAREFULLY BEFORE PROCEEDING")."\n"; + $activateoutput .= "\t\t\t
    \n"; + $activateoutput .= $clang->gT("You should only activate a survey when you are absolutely certain that your survey setup is finished and will not need changing.")."

    \n"; + $activateoutput .= $clang->gT("Once a survey is activated you can no longer:")."
    • ".$clang->gT("Add or delete groups")."
    • ".$clang->gT("Add or remove answers to Multiple Answer questions")."
    • ".$clang->gT("Add or delete questions")."
    \n"; + $activateoutput .= $clang->gT("However you can still:")."
    • ".$clang->gT("Edit (change) your questions code, text or type")."
    • ".$clang->gT("Edit (change) your group names")."
    • ".$clang->gT("Add, Remove or Edit pre-defined question answers (except for Multi-answer questions)")."
    • ".$clang->gT("Change survey name or description")."
    \n"; + $activateoutput .= $clang->gT("Once data has been entered into this survey, if you want to add or remove groups or questions, you will need to de-activate this survey, which will move all data that has already been entered into a separate archived table.")."

    \n"; + $activateoutput .= "\t\t\tgT("Activate Survey")."\" onclick=\"".get2post("$scriptname?action=activate&ok=Y&sid={$_GET['sid']}")."\" />\n"; + $activateoutput .= "

     \n"; + +} +else +{ + //Create the survey responses table + $createsurvey = "id I NOTNULL AUTO PRIMARY,\n"; + $createsurvey .= " submitdate T,\n"; + $createsurvey .= " startlanguage C(20) NOTNULL ,\n"; + //Check for any additional fields for this survey and create necessary fields (token and datestamp) + $pquery = "SELECT private, allowregister, datestamp, ipaddr, refurl FROM {$dbprefix}surveys WHERE sid={$postsid}"; + $presult=db_execute_assoc($pquery); + while($prow=$presult->FetchRow()) + { + if ($prow['private'] == "N") + { + $createsurvey .= " token C(36),\n"; + $surveynotprivate="TRUE"; + } + if ($prow['allowregister'] == "Y") + { + $surveyallowsregistration="TRUE"; + } + if ($prow['datestamp'] == "Y") + { + $createsurvey .= " datestamp T NOTNULL,\n"; + $createsurvey .= " startdate T NOTNULL,\n"; + } + if ($prow['ipaddr'] == "Y") + { + $createsurvey .= " ipaddr X,\n"; + } + //Check to see if 'refurl' field is required. + if ($prow['refurl'] == "Y") + { + $createsurvey .= " refurl X,\n"; + } + } + //Get list of questions for the base language + $aquery = " SELECT * FROM ".db_table_name('questions').", ".db_table_name('groups') + ." WHERE ".db_table_name('questions').".gid=".db_table_name('groups').".gid " + ." AND ".db_table_name('questions').".sid={$postsid} " + ." AND ".db_table_name('groups').".language='".GetbaseLanguageFromSurveyid($postsid). "' " + ." AND ".db_table_name('questions').".language='".GetbaseLanguageFromSurveyid($postsid). "' " + ." ORDER BY group_order, question_order"; + $aresult = db_execute_assoc($aquery); + while ($arow=$aresult->FetchRow()) //With each question, create the appropriate field(s) + { + if ( substr($createsurvey, strlen($createsurvey)-2, 2) != ",\n") {$createsurvey .= ",\n";} + + if ($arow['type'] != "M" && $arow['type'] != "A" && $arow['type'] != "B" && + $arow['type'] != "C" && $arow['type'] != "E" && $arow['type'] != "F" && + $arow['type'] != "H" && $arow['type'] != "P" && $arow['type'] != "R" && + $arow['type'] != "Q" && $arow['type'] != "^" && $arow['type'] != "J" && + $arow['type'] != "K" && $arow['type'] != ":" && $arow['type'] != ";" && + $arow['type'] != "1") + { + $createsurvey .= " `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}`"; + switch($arow['type']) + { + case "N": //NUMERICAL + $createsurvey .= " F"; + break; + case "S": //SHORT TEXT + if ($databasetype=='mysql' || $databasetype=='mysqli') {$createsurvey .= " X";} + else {$createsurvey .= " C(255)";} + break; + case "L": //LIST (RADIO) + case "!": //LIST (DROPDOWN) + case "W": + case "Z": + $createsurvey .= " C(5)"; + if ($arow['other'] == "Y") + { + $createsurvey .= ",\n`{$arow['sid']}X{$arow['gid']}X{$arow['qid']}other` X"; + } + break; + case "I": // CSV ONE + $createsurvey .= " C(5)"; + break; + case "O": //DROPDOWN LIST WITH COMMENT + $createsurvey .= " C(5),\n `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}comment` X"; + break; + case "T": //LONG TEXT + $createsurvey .= " X"; + break; + case "U": //HUGE TEXT + $createsurvey .= " X"; + break; + case "D": //DATE + $createsurvey .= " D"; + break; + case "5": //5 Point Choice + case "G": //Gender + case "Y": //YesNo + case "X": //Boilerplate + $createsurvey .= " C(1)"; + break; + } + } + elseif ($arow['type'] == "M" || $arow['type'] == "A" || $arow['type'] == "B" || + $arow['type'] == "C" || $arow['type'] == "E" || $arow['type'] == "F" || + $arow['type'] == "H" || $arow['type'] == "P" || $arow['type'] == "^") + { + //MULTI ENTRY + $abquery = "SELECT a.*, q.other FROM {$dbprefix}answers as a, {$dbprefix}questions as q" + ." WHERE a.qid=q.qid AND sid={$postsid} AND q.qid={$arow['qid']} " + ." AND a.language='".GetbaseLanguageFromSurveyid($postsid). "' " + ." AND q.language='".GetbaseLanguageFromSurveyid($postsid). "' " + ." ORDER BY a.sortorder, a.answer"; + $abresult=db_execute_assoc($abquery) or safe_die ("Couldn't get perform answers query
    $abquery
    ".$connect->ErrorMsg()); + while ($abrow=$abresult->FetchRow()) + { + $createsurvey .= " `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$abrow['code']}` C(5),\n"; + if ($abrow['other']=="Y") {$alsoother="Y";} + if ($arow['type'] == "P") + { + $createsurvey .= " `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$abrow['code']}comment` X,\n"; + } + } + if ((isset($alsoother) && $alsoother=="Y") && ($arow['type']=="M" || $arow['type']=="P" || $arow['type']=="1")) //Sc: check! + { + $createsurvey .= " `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}other` X,\n"; + if ($arow['type']=="P") + { + $createsurvey .= " `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}othercomment` X,\n"; + } + } + } + elseif ($arow['type'] == ":" || $arow['type'] == ";") + { + //MULTI ENTRY + $abquery = "SELECT a.*, q.other FROM {$dbprefix}answers as a, {$dbprefix}questions as q" + ." WHERE a.qid=q.qid AND sid={$postsid} AND q.qid={$arow['qid']} " + ." AND a.language='".GetbaseLanguageFromSurveyid($postsid). "' " + ." AND q.language='".GetbaseLanguageFromSurveyid($postsid). "' " + ." ORDER BY a.sortorder, a.answer"; + $abresult=db_execute_assoc($abquery) or die ("Couldn't get perform answers query
    $abquery
    ".$connect->ErrorMsg()); + $ab2query = "SELECT ".db_table_name('labels').".* + FROM ".db_table_name('questions').", ".db_table_name('labels')." + WHERE sid=$surveyid + AND ".db_table_name('labels').".lid=".db_table_name('questions').".lid + AND ".db_table_name('labels').".language='".GetbaseLanguageFromSurveyid($postsid)."' + AND ".db_table_name('questions').".qid=".$arow['qid']." + ORDER BY ".db_table_name('labels').".sortorder, ".db_table_name('labels').".title"; + $ab2result=db_execute_assoc($ab2query) or die("Couldn't get list of labels in createFieldMap function (case :)
    $ab2query
    ".htmlspecialchars($connection->ErrorMsg())); + while($ab2row=$ab2result->FetchRow()) + { + $lset[]=$ab2row; + } + while ($abrow=$abresult->FetchRow()) + { + foreach($lset as $ls) + { + $createsurvey .= " `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$abrow['code']}_{$ls['code']}` X,\n"; + } + } + unset($lset); + } + elseif ($arow['type'] == "Q") + { + $abquery = "SELECT a.*, q.other FROM {$dbprefix}answers as a, {$dbprefix}questions as q WHERE a.qid=q.qid AND sid={$postsid} AND q.qid={$arow['qid']} " + ." AND a.language='".GetbaseLanguageFromSurveyid($postsid). "' " + ." AND q.language='".GetbaseLanguageFromSurveyid($postsid). "' " + ." ORDER BY a.sortorder, a.answer"; + $abresult=db_execute_assoc($abquery) or safe_die ("Couldn't get perform answers query
    $abquery
    ".$connect->ErrorMsg()); + while ($abrow = $abresult->FetchRow()) + { + $createsurvey .= " `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$abrow['code']}`"; + if ($databasetype=='mysql' || $databasetype=='mysqli') + { + $createsurvey .= " X"; + } + else + { + $createsurvey .= " C(255)"; + } + $createsurvey .= ",\n"; + } + } + + elseif ($arow['type'] == "K") //Multiple Numeric - replica of multiple short text, except numbers only + { + $abquery = "SELECT a.*, q.other FROM {$dbprefix}answers as a, {$dbprefix}questions as q WHERE a.qid=q.qid AND sid={$postsid} AND q.qid={$arow['qid']} " + ." AND a.language='".GetbaseLanguageFromSurveyid($postsid). "' " + ." AND q.language='".GetbaseLanguageFromSurveyid($postsid). "' " + ." ORDER BY a.sortorder, a.answer"; + $abresult=db_execute_assoc($abquery) or safe_die ("Couldn't get perform answers query
    $abquery
    ".$connect->ErrorMsg()); + while ($abrow = $abresult->FetchRow()) + { + $createsurvey .= " `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$abrow['code']}` F,\n"; + } + } //End if ($arow['type'] == "K") +/* elseif ($arow['type'] == "J") + { + $abquery = "SELECT {$dbprefix}answers.*, {$dbprefix}questions.other FROM {$dbprefix}answers, {$dbprefix}questions WHERE {$dbprefix}answers.qid={$dbprefix}questions.qid AND sid={$_GET['sid']} AND {$dbprefix}questions.qid={$arow['qid']} ORDER BY {$dbprefix}answers.sortorder, {$dbprefix}answers.answer"; + $abresult=db_execute_assoc($abquery) or safe_die ("Couldn't get perform answers query
    $abquery
    ".$connect->ErrorMsg()); + while ($abrow = $abresultt->FetchRow()) + { + $createsurvey .= " `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$abrow['code']}` C(5),\n"; + } + }*/ + elseif ($arow['type'] == "R") + { + //MULTI ENTRY + $abquery = "SELECT a.*, q.other FROM {$dbprefix}answers as a, {$dbprefix}questions as q" + ." WHERE a.qid=q.qid AND sid={$postsid} AND q.qid={$arow['qid']} " + ." AND a.language='".GetbaseLanguageFromSurveyid($postsid). "' " + ." AND q.language='".GetbaseLanguageFromSurveyid($postsid). "' " + ." ORDER BY a.sortorder, a.answer"; + $abresult=$connect->Execute($abquery) or safe_die ("Couldn't get perform answers query
    $abquery
    ".$connect->ErrorMsg()); + $abcount=$abresult->RecordCount(); + for ($i=1; $i<=$abcount; $i++) + { + $createsurvey .= " `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}$i` C(5),\n"; + } + } + elseif ($arow['type'] == "1") + { + $abquery = "SELECT a.*, q.other FROM {$dbprefix}answers as a, {$dbprefix}questions as q" + ." WHERE a.qid=q.qid AND sid={$postsid} AND q.qid={$arow['qid']} " + ." AND a.language='".GetbaseLanguageFromSurveyid($postsid). "' " + ." AND q.language='".GetbaseLanguageFromSurveyid($postsid). "' " + ." ORDER BY a.sortorder, a.answer"; + $abresult=db_execute_assoc($abquery) or safe_die ("Couldn't get perform answers query
    $abquery
    ".$connect->ErrorMsg()); + $abcount=$abresult->RecordCount(); + while ($abrow = $abresult->FetchRow()) + { + $abmultiscalequery = "SELECT a.*, q.other FROM {$dbprefix}answers as a, {$dbprefix}questions as q, {$dbprefix}labels as l" + ." WHERE a.qid=q.qid AND sid={$postsid} AND q.qid={$arow['qid']} " + ." AND l.lid=q.lid AND sid={$postsid} AND q.qid={$arow['qid']} AND l.title = '' " + ." AND l.language='".GetbaseLanguageFromSurveyid($postsid). "' " + ." AND q.language='".GetbaseLanguageFromSurveyid($postsid). "' "; + $abmultiscaleresult=$connect->Execute($abmultiscalequery) or safe_die ("Couldn't get perform answers query
    $abmultiscalequery
    ".$connect->ErrorMsg()); + $abmultiscaleresultcount =$abmultiscaleresult->RecordCount(); + $abmultiscaleresultcount = 1; + for ($j=0; $j<=$abmultiscaleresultcount; $j++) + { + $createsurvey .= " `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$abrow['code']}#$j` C(5),\n"; + } + } + } + } + + // If last question is of type MCABCEFHP^QKJR let's get rid of the ending coma in createsurvey + $createsurvey = rtrim($createsurvey, ",\n")."\n"; // Does nothing if not ending with a comma + $tabname = "{$dbprefix}survey_{$postsid}"; # not using db_table_name as it quotes the table name (as does CreateTableSQL) + + $taboptarray = array('mysql' => 'ENGINE='.$databasetabletype.' CHARACTER SET utf8 COLLATE utf8_unicode_ci', + 'mysqli'=> 'ENGINE='.$databasetabletype.' CHARACTER SET utf8 COLLATE utf8_unicode_ci'); + $dict = NewDataDictionary($connect); + $sqlarray = $dict->CreateTableSQL($tabname, $createsurvey, $taboptarray); + $execresult=$dict->ExecuteSQLArray($sqlarray,1); + if ($execresult==0 || $execresult==1) + { + $activateoutput .= "
    \n\n" . + "\n" . + "
    ".$clang->gT("Activate Survey")." ($surveyid)
    \n" . + "".$clang->gT("Survey could not be actived.")."
    \n" . + "
    ".$clang->gT("Main Admin Screen")."
    \n" . + "DB ".$clang->gT("Error").":
    \n" . $connect->ErrorMsg() . "\n" . + "
    $createsurvey
    \n" . + "

     \n" . + "\n"; + } + if ($execresult != 0 && $execresult !=1) + { + $anquery = "SELECT autonumber_start FROM {$dbprefix}surveys WHERE sid={$postsid}"; + if ($anresult=db_execute_assoc($anquery)) + { + //if there is an autonumber_start field, start auto numbering here + while($row=$anresult->FetchRow()) + { + if ($row['autonumber_start'] > 0) + { + $autonumberquery = "ALTER TABLE {$dbprefix}survey_{$postsid} AUTO_INCREMENT = ".$row['autonumber_start']; + if ($result = $connect->Execute($autonumberquery)) + { + //We're happy it worked! + } + else + { + //Continue regardless - it's not the end of the world + } + } + } + } + + $activateoutput .= "
    \n\n"; + $activateoutput .= "\t\t\t\t\n"; + $activateoutput .= "\t\t\t\t
    ".$clang->gT("Activate Survey")." ($surveyid)
    ".$clang->gT("Survey has been activated. Results table has been successfully created.")."

    \n"; + + $acquery = "UPDATE {$dbprefix}surveys SET active='Y' WHERE sid=".returnglobal('sid'); + $acresult = $connect->Execute($acquery); + +// Private means data privacy, not closed access survey +// if (isset($surveynotprivate) && $surveynotprivate) //This survey is tracked, and therefore a tokens table MUST exist +// { +// $activateoutput .= $clang->gT("This is not an anonymous survey. A token table must also be created.")."

    \n"; +// $activateoutput .= "\n"; +// } +// elseif (isset($surveyallowsregistration) && $surveyallowsregistration == "TRUE") + if (isset($surveyallowsregistration) && $surveyallowsregistration == "TRUE") + { + $activateoutput .= $clang->gT("This survey allows public registration. A token table must also be created.")."

    \n"; + $activateoutput .= "\n"; + } + else + { + $activateoutput .= $clang->gT("This survey is now active, and responses can be recorded.")."

    \n"; + $activateoutput .= "".$clang->gT("Open-access mode").": ".$clang->gT("No invitation code is needed to complete the survey.")."
    ".$clang->gT("You can switch to the closed-access mode by initialising a token table with the button below.")."

    \n"; + $activateoutput .= "\n"; + $activateoutput .= "\n"; + } + $activateoutput .= "\t\t\t\t

     \n"; + } + +} + +?> diff --git a/include/limesurvey/admin/admin.php b/include/limesurvey/admin/admin.php index 621ef5be..6d3d2d86 100644 --- a/include/limesurvey/admin/admin.php +++ b/include/limesurvey/admin/admin.php @@ -1,656 +1,713 @@ -=')) -{ - require_once(dirname(__FILE__).'/classes/core/domxml-php4-to-php5.php'); -} -require_once(dirname(__FILE__).'/../config-defaults.php'); -require_once(dirname(__FILE__).'/../common.php'); -require_once($rootdir.'/classes/core/html_entity_decode_php4.php'); // has been secured - - -require_once('htmleditor-functions.php'); - -//@ini_set('session.gc_maxlifetime', $sessionlifetime); Might cause problems in client?? - -// Reset FileManagerContext -$_SESSION['FileManagerContext']=''; - -if (!isset($adminlang)) {$adminlang=returnglobal('adminlang');} // Admin language -if (!isset($surveyid)) {$surveyid=returnglobal('sid');} //SurveyID -if (!isset($ugid)) {$ugid=returnglobal('ugid');} //Usergroup-ID -if (!isset($gid)) {$gid=returnglobal('gid');} //GroupID -if (!isset($qid)) {$qid=returnglobal('qid');} //QuestionID -if (!isset($lid)) {$lid=returnglobal('lid');} //LabelID -if (!isset($code)) {$code=returnglobal('code');} // ?? -if (!isset($action)) {$action=returnglobal('action');} //Desired action -if (!isset($subaction)) {$subaction=returnglobal('subaction');} //Desired subaction -if (!isset($editedaction)) {$editedaction=returnglobal('editedaction');} // for html editor integration - -if ($action != "showprintablesurvey") -{ - $adminoutput = helpscreenscript(); - $adminoutput .= "\n" - ."\t\n" - ."\t\t\n".helpscreen() - . "\t\n" - . "
    \n"; -} else {$adminoutput='';} -include_once("login_check.php"); - - -if ( $action == 'CSRFwarn') -{ - include("access_denied.php"); -} - -if ( $action == 'FakeGET') -{ - include("access_denied.php"); -} - -if(isset($_SESSION['loginID']) && $action!='login') -{ - //VARIOUS DATABASE OPTIONS/ACTIONS PERFORMED HERE - if ($action == "delsurvey" || $action == "delgroup" || $action == "delgroupall" || - $action == "delquestion" || $action == "delquestionall" || $action == "insertnewsurvey" || - $action == "copynewquestion" || $action == "insertnewgroup" || $action == "insertCSV" || - $action == "insertnewquestion" || $action == "updatesurvey" || $action == "updatesurvey2" || - $action == "updategroup" || $action == "deactivate" || - $action == "updatequestion" || $action == "modanswer" || $action == "renumberquestions" || - $action == "delattribute" || $action == "addattribute" || $action == "editattribute") - { - include("database.php"); - } - -sendcacheheaders(); - -/* Check user right actions for validity - Currently existing user rights: - `configurator` - `create_survey` - `create_user` - `delete_user` - `manage_label` - `manage_template` - `superadmin` -*/ - -if ($action == "importsurvey") - { - if ($_SESSION['USER_RIGHT_CREATE_SURVEY']==1) {include("http_importsurvey.php");} - else { include("access_denied.php");} - } -elseif ($action == "dumpdb") - { - if ($_SESSION['USER_RIGHT_CONFIGURATOR']==1) {include("dumpdb.php");} - else { include("access_denied.php");} - } -elseif ($action == "dumplabel") - { - if ($_SESSION['USER_RIGHT_MANAGE_LABEL']==1) {include("dumplabel.php");} - else { include("access_denied.php");} - } -elseif ($action == "exportlabelresources") - { - if ($_SESSION['USER_RIGHT_MANAGE_TEMPLATE']==1) {$_SESSION['FileManagerContext']="edit:label:$lid"; include("export_resources_zip.php");} - else { include("access_denied.php");} - } -elseif ($action == "checkintegrity") - { - if ($_SESSION['USER_RIGHT_CONFIGURATOR']==1) {include("integritycheck.php");} - else { include("access_denied.php");} - } -elseif ($action=="labels" || $action=="newlabelset" || $action=="insertlabelset" || - $action=="deletelabelset" || $action=="editlabelset" || $action=="modlabelsetanswers" || - $action=="updateset" || $action=="importlabels" ||$action == "importlabelresources") - { - if ($_SESSION['USER_RIGHT_MANAGE_LABEL']==1) {$_SESSION['FileManagerContext']="edit:label:$lid"; include("labels.php");} - else { include("access_denied.php");} - } -elseif ($action=="templates" || $action=="templatecopy" || $action=="templatesavechanges" || - $action=="templaterename" || $action=="templateupload" || $action=="templatefiledelete" || - $action=="templatezip" || $action=="templaterefresh") - { - if ($_SESSION['USER_RIGHT_MANAGE_TEMPLATE']==1) {include("templates.php");} - else { include("access_denied.php");} - } - - - -/* Check survey right actions for validity - Currently existing survey rights: - `edit_survey_property` - `define_questions` - `browse_response` - `export` - `delete_survey` - `activate_survey` -*/ - -if (isset($surveyid) && $surveyid) -{ -$surquery = "SELECT * FROM {$dbprefix}surveys_rights WHERE sid=".db_quote($surveyid)." AND uid = ".db_quote($_SESSION['loginID']); //Getting rights for this survey -$surresult = db_execute_assoc($surquery); -$surrows = $surresult->FetchRow(); -} - -if ($action == "activate") - { - if($surrows['activate_survey'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include("activate.php");} - else { include("access_denied.php");} - } -elseif ($action == "conditions") -{ - if($surrows['define_questions'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include("conditions.php");} - else { include("access_denied.php");} - } -elseif ($action == "importsurvresources") - { - if ($surrows['define_questions'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {$_SESSION['FileManagerContext']="edit:survey:$surveyid";include("import_resources_zip.php");} - else { include("access_denied.php");} - } -elseif ($action == "exportstructurecsv") - { - if($surrows['export'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include("export_structure_csv.php");} - else { include("access_denied.php");} - } -elseif ($action == "exportstructurequexml") - { - if($surrows['export'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include("export_structure_quexml.php");} - else { include("access_denied.php");} - } -elseif ($action == "exportsurvresources") - { - if($surrows['export'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {$_SESSION['FileManagerContext']="edit:survey:$surveyid";include("export_resources_zip.php");} - else { include("access_denied.php");} - } -elseif ($action == "dumpquestion") - { - if($surrows['export'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include("dumpquestion.php");} - else { include("access_denied.php");} - } -elseif ($action == "dumpgroup") - { - if($surrows['export'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include("dumpgroup.php");} - else { include("access_denied.php");} - } -elseif ($action == "deactivate") - { - if($surrows['activate_survey'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include("deactivate.php");} - else { include("access_denied.php");} - } -elseif ($action == "deletesurvey") - { - if($surrows['delete_survey'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include("deletesurvey.php");} - else { include("access_denied.php");} - } -elseif ($action == "resetsurveylogic") - { - if($surrows['define_questions'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include("resetsurveylogic.php");} - else { include("access_denied.php");} - } -elseif ($action == "importgroup") - { - if($surrows['define_questions'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include("importgroup.php");} - else { include("access_denied.php");} - } -elseif ($action == "importquestion") - { - if($surrows['define_questions'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include("importquestion.php");} - else { include("access_denied.php");} - } -elseif ($action == "listcolumn") - { - if($surrows['browse_response'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include("listcolumn.php");} - else { include("access_denied.php");} - } -elseif ($action == "previewquestion") - { - if($surrows['define_questions'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include("preview.php");} - else { include("access_denied.php");} - } -elseif ($action=="addgroup" || $action=="editgroup") - { - if($surrows['define_questions'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {$_SESSION['FileManagerContext']="edit:group:$surveyid"; include("grouphandling.php");} - else { include("access_denied.php");} - } -elseif ($action == "vvexport") - { - if($surrows['browse_response'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include("vvexport.php");} - else { include("access_denied.php");} - } -elseif ($action == "vvimport") - { - if($surrows['browse_response'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include("vvimport.php");} - else { include("access_denied.php");} - } -elseif ($action == "importoldresponses") - { - if($surrows['browse_response'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include("importoldresponses.php");} - else { include("access_denied.php");} - } -elseif ($action == "saved") - { - if($surrows['browse_response'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include("saved.php");} - else { include("access_denied.php");} - } -elseif ($action == "exportresults") - { - if($surrows['export'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include("exportresults.php");} - else { include("access_denied.php");} - } -elseif ($action == "exportspss") - { - if($surrows['export'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include("spss.php");} - else { include("access_denied.php");} - } -elseif ($action == "statistics") - { - if($surrows['browse_response'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include("statistics.php");} - else { include("access_denied.php");} - } -elseif ($action == "dataentry") - { - if($surrows['browse_response'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include("dataentry.php");} - else { include("access_denied.php");} - } -elseif ($action == "browse") - { - if($surrows['browse_response'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include("browse.php");} - else { include("access_denied.php");} - } -elseif ($action == "tokens") - { - if($surrows['activate_survey'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {$_SESSION['FileManagerContext']="edit:emailsettings:$surveyid"; include("tokens.php");} - else { include("access_denied.php"); } - } -elseif ($action=="showprintablesurvey") - { - include("printablesurvey.php"); //No special right needed to show the printable survey - } -elseif ($action=="assessments" || $action=="assessmentdelete" || $action=="assessmentedit" || $action=="assessmentadd" || $action=="assessmentupdate") - { - if($surrows['define_questions'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include("assessments.php");} - else { include("access_denied.php");} - } -elseif ($action == "replacementfields") - { - switch ($editedaction) - { - case 'labels': - if ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $_SESSION['USER_RIGHT_MANAGE_LABEL']==1) - { - include("fck_LimeReplacementFields.php");exit; - } - else - { - include("access_denied.php"); - } - break; - case 'newsurvey': - if ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $_SESSION['USER_RIGHT_CREATE_SURVEY'] == 1) - { - include("fck_LimeReplacementFields.php");exit; - } - else - { - include("access_denied.php"); - } - break; - case 'updatesurvey': - if ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $surrows['edit_survey_property']) - { - include("fck_LimeReplacementFields.php");exit; - } - else - { - include("access_denied.php"); - } - break; - case 'tokens': // email - if ( $_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $surrows['activate_survey']) - { - include("fck_LimeReplacementFields.php");exit; - } - else - { - include("access_denied.php"); - } - case 'editquestion': - case 'copyquestion': - case 'editgroup': - case 'addquestion': - case 'addgroup': - case 'editanswer': - if ( $_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $surrows['define_questions']) - { - include("fck_LimeReplacementFields.php");exit; - } - else - { - include("access_denied.php"); - } - break; - default: - break; - } - } - - - - if (!isset($assessmentsoutput) && !isset($statisticsoutput) && !isset($browseoutput) && !isset($savedsurveyoutput) && !isset( $listcolumnoutput ) && - !isset($dataentryoutput) && !isset($conditionsoutput) && !isset($importoldresponsesoutput) && - !isset($vvoutput) && !isset($tokenoutput) && !isset($exportoutput) && !isset($templatesoutput) && - (isset($surveyid) || $action=="listurveys" || $action=="changelang" || $action=="changehtmleditormode" || $action=="checksettings" || //Still to check - $action=="editsurvey" || $action=="updatesurvey" || $action=="ordergroups" || - $action=="newsurvey" || $action=="listsurveys" || - $action=="surveyrights" || $action=="quotas") ) -{ - if ($action=="editsurvey" || $action=="updatesurvey") - { - $_SESSION['FileManagerContext']="edit:survey:$surveyid"; - } - include("html.php"); -} - - if ($action=="addquestion" || $action=="copyquestion" || $action=="editquestion" || - $action=="orderquestions" || $action=="editattribute" || $action=="delattribute" || - $action=="addattribute" ) - {if($surrows['define_questions'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {$_SESSION['FileManagerContext']="edit:question:$surveyid";include("questionhandling.php");} - else { include("access_denied.php");} - } - - - if ($action=="adduser" || $action=="deluser" || $action=="moduser" || $action=="setusertemplates" || $action=="usertemplates" || //Still to check - $action=="userrights" || $action=="modifyuser" || $action=="editusers" || - $action=="addusergroup" || $action=="editusergroup" || $action=="mailusergroup" || - $action=="delusergroup" || $action=="usergroupindb" || $action=="mailsendusergroup" || - $action=="editusergroupindb" || $action=="editusergroups" || $action=="deleteuserfromgroup" || - $action=="addusertogroup" || $action=="setuserrights" || $action=="setasadminchild") - - { - include ("userrighthandling.php"); - } - - - // For some output we dont want to have the standard admin menu bar - if (!isset($labelsoutput) && !isset($templatesoutput) && !isset($printablesurveyoutput) && - !isset($assessmentsoutput) && !isset($tokenoutput) && !isset($browseoutput) && - !isset($dataentryoutput) && !isset($statisticsoutput)&& !isset($savedsurveyoutput) && - !isset($exportoutput) && !isset($importoldresponsesoutput) && !isset($conditionsoutput) && - !isset($vvoutput) && !isset($listcolumnoutput) && !isset($importlabelresources)) - { - $adminoutput.= showadminmenu(); - } - - - if (isset($databaseoutput)) {$adminoutput.= $databaseoutput;} - if (isset($templatesoutput)) {$adminoutput.= $templatesoutput;} - if (isset($accesssummary )) {$adminoutput.= $accesssummary;} - if (isset($surveysummary )) {$adminoutput.= $surveysummary;} - if (isset($usergroupsummary)){$adminoutput.= $usergroupsummary;} - if (isset($usersummary )) {$adminoutput.= $usersummary;} - if (isset($groupsummary )) {$adminoutput.= $groupsummary;} - if (isset($questionsummary)) {$adminoutput.= $questionsummary;} - if (isset($vasummary )) {$adminoutput.= $vasummary;} - if (isset($addsummary )) {$adminoutput.= $addsummary;} - if (isset($answersummary )) {$adminoutput.= $answersummary;} - if (isset($cssummary )) {$adminoutput.= $cssummary;} - if (isset($listcolumnoutput)) {$adminoutput.= $listcolumnoutput;} - - - if (isset($editgroup)) {$adminoutput.= $editgroup;} - if (isset($editquestion)) {$adminoutput.= $editquestion;} - if (isset($editsurvey)) {$adminoutput.= $editsurvey;} - if (isset($quotasoutput)) {$adminoutput.= $quotasoutput;} - if (isset($labelsoutput)) {$adminoutput.= $labelsoutput;} - if (isset($listsurveys)) {$adminoutput.= $listsurveys; } - if (isset($integritycheck)) {$adminoutput.= $integritycheck;} - if (isset($ordergroups)){$adminoutput.= $ordergroups;} - if (isset($orderquestions)) {$adminoutput.= $orderquestions;} - if (isset($surveysecurity)) {$adminoutput.= $surveysecurity;} - if (isset($exportstructure)) {$adminoutput.= $exportstructure;} - if (isset($newsurvey)) {$adminoutput.= $newsurvey;} - if (isset($newgroupoutput)) {$adminoutput.= $newgroupoutput;} - if (isset($newquestionoutput)) {$adminoutput.= $newquestionoutput;} - if (isset($newanswer)) {$adminoutput.= $newanswer;} - if (isset($editanswer)) {$adminoutput.= $editanswer;} - if (isset($assessmentsoutput)) {$adminoutput.= $assessmentsoutput;} - - if (isset($importsurvey)) {$adminoutput.= $importsurvey;} - if (isset($importsurvresourcesoutput)) {$adminoutput.= $importsurvresourcesoutput;} - if (isset($importgroup)) {$adminoutput.= $importgroup;} - if (isset($importquestion)) {$adminoutput.= $importquestion;} - if (isset($printablesurveyoutput)) {$adminoutput.= $printablesurveyoutput;} - if (isset($activateoutput)) {$adminoutput.= $activateoutput;} - if (isset($deactivateoutput)) {$adminoutput.= $deactivateoutput;} - if (isset($tokenoutput)) {$adminoutput.= $tokenoutput;} - if (isset($browseoutput)) {$adminoutput.= $browseoutput;} - if (isset($dataentryoutput)) {$adminoutput.= $dataentryoutput;} - if (isset($statisticsoutput)) {$adminoutput.= $statisticsoutput;} - if (isset($exportoutput)) {$adminoutput.= $exportoutput;} - if (isset($savedsurveyoutput)) {$adminoutput.= $savedsurveyoutput;} - if (isset($importoldresponsesoutput)) {$adminoutput.= $importoldresponsesoutput;} - if (isset($conditionsoutput)) {$adminoutput.= $conditionsoutput;} - if (isset($deletesurveyoutput)) {$adminoutput.= $deletesurveyoutput;} - if (isset($resetsurveylogicoutput)) {$adminoutput.= $resetsurveylogicoutput;} - if (isset($vvoutput)) {$adminoutput.= $vvoutput;} - if (isset($dumpdboutput)) {$adminoutput.= $dumpdboutput;} - - - if (!isset($printablesurveyoutput) && ($subaction!='export')) - { - if (!isset($_SESSION['metaHeader'])) {$_SESSION['metaHeader']='';} - - $adminoutput = getAdminHeader($_SESSION['metaHeader']).$adminoutput; // All future output is written into this and then outputted at the end of file - unset($_SESSION['metaHeader']); - $adminoutput.= "\t\t
    \n"; - - $adminoutput .= "\n"; - - $adminoutput .= "" - . getAdminFooter("http://docs.limesurvey.org", $clang->gT("LimeSurvey Online Manual")); - } - -} - else - { //not logged in - sendcacheheaders(); - if (!isset($_SESSION['metaHeader'])) {$_SESSION['metaHeader']='';} - $adminoutput = getAdminHeader($_SESSION['metaHeader']).$adminoutput; // All future output is written into this and then outputted at the end of file - unset($_SESSION['metaHeader']); - $adminoutput.= "\t\t\n".helpscreen() - . "\t\n" - . "\n" - . getAdminFooter("http://docs.limesurvey.org", $clang->gT("LimeSurvey Online Manual")); - - } - -if (($action=='showphpinfo') && ($_SESSION['USER_RIGHT_CONFIGURATOR'] == 1)) -{ - phpinfo(); -} -else -{ - echo $adminoutput; -} - - - function helpscreenscript() - // returns the script part for online help to be included outside a table - { - $helpoutput= "\n"; - return $helpoutput; - } - - - function helpscreen() - // This functions loads the nescessary helpscreens for each action and hides the help window - // - { - global $homeurl, $langdir, $imagefiles; - global $surveyid, $gid, $qid, $action, $clang; - - $helpoutput="\t\t\n" - ."\t\t\t
    " - ."\n" - ."\t\t\t\t\n" - ."\t\t\t\t\t\n" - ."\t\t\t\t\n" - ."\t\t\t\t\n" - ."\t\t\t\t\t\n" - ."\t\t\t\t\n" - ."\t\t\t\t\n" - ."\t\t\t\t\t" - ."\t\t\t\t\n" - ."\t\t\t
    \n" - ."\t\t\t\t\t\t" - .$clang->gT("Help")."\n" - ."\t\t\t\t\t
    \n" - ."\t\t\t\t\t\t\n" - ."\t\t\t\t\t\t\n" - ."\t\t\t\t\t
    \n"; - //determine which help document to show - if (!$surveyid && $action != "editusers") - { - $helpdoc = "$langdir/admin.html"; - } - elseif (!$surveyid && $action=="editusers") - { - $helpdoc = "$langdir/users.html"; - } - elseif ($surveyid && !$gid) - { - $helpdoc = "$langdir/survey.html"; - } - elseif ($surveyid && $gid && !$qid) - { - $helpdoc = "$langdir/group.html"; - } - elseif ($surveyid && $gid && $qid && !returnglobal('viewanswer')) - { - $helpdoc = "$langdir/question.html"; - } - elseif ($surveyid && $gid && $qid && (returnglobal('viewanswer'))) - { - $helpdoc = "$langdir/answer.html"; - } - $helpoutput.= "\t\t\t\t\t\t\n" - ."\t\t\t\t\t
    \n" - ."\t\t\n"; - return $helpoutput; - } - - - -function convertToArray($stringtoconvert, $seperator, $start, $end) -// this function is still used to read SQL files from version 1.0 or older -{ - $begin=strpos($stringtoconvert, $start)+strlen($start); - $len=strpos($stringtoconvert, $end)-$begin; - $stringtoconvert=substr($stringtoconvert, $begin, $len); - $stringtoconvert=str_replace('\n',"\n",$stringtoconvert); //removes masking - $stringtoconvert=stripslashes($stringtoconvert); - $resultarray=explode($seperator, $stringtoconvert); - return $resultarray; -} - -function get2post($url) -{ - $url = preg_replace('/&/i','&',$url); - list($calledscript,$query) = explode('?',$url); - $aqueryitems = explode('&',$query); - $arrayParam = Array(); - $arrayVal = Array(); - - foreach ($aqueryitems as $queryitem) - { - list($paramname, $value) = explode ('=', $queryitem); - //error_log("TIBO URL=$url Form Action=$calledscript, param=$paramname, value=$value"); - $arrayParam[] = "'".$paramname."'"; - $arrayVal[] = "'".$value."'"; - } -// $Paramlist = "[" . implode(",",$arrayParam) . "]"; -// $Valuelist = "[" . implode(",",$arrayVal) . "]"; - $Paramlist = "new Array(" . implode(",",$arrayParam) . ")"; - $Valuelist = "new Array(" . implode(",",$arrayVal) . ")"; - $callscript = "sendPost('$calledscript','".$_SESSION['checksessionpost']."',$Paramlist,$Valuelist);"; - //error_log("TIBO = $callscript"); - return $callscript; -} - -?> +=')&& !(function_exists('domxml_new_doc'))) +{ + require_once(dirname(__FILE__).'/classes/core/domxml-php4-to-php5.php'); +} +require_once(dirname(__FILE__).'/../config-defaults.php'); +require_once(dirname(__FILE__).'/../common.php'); + + +require_once('htmleditor-functions.php'); + +//@ini_set('session.gc_maxlifetime', $sessionlifetime); Might cause problems in client?? + +// Reset FileManagerContext +$_SESSION['FileManagerContext']=''; + +if (!isset($adminlang)) {$adminlang=returnglobal('adminlang');} // Admin language +if (!isset($surveyid)) {$surveyid=returnglobal('sid');} //SurveyID +if (!isset($ugid)) {$ugid=returnglobal('ugid');} //Usergroup-ID +if (!isset($gid)) {$gid=returnglobal('gid');} //GroupID +if (!isset($qid)) {$qid=returnglobal('qid');} //QuestionID +if (!isset($lid)) {$lid=returnglobal('lid');} //LabelID +if (!isset($code)) {$code=returnglobal('code');} // ?? +if (!isset($action)) {$action=returnglobal('action');} //Desired action +if (!isset($subaction)) {$subaction=returnglobal('subaction');} //Desired subaction +if (!isset($editedaction)) {$editedaction=returnglobal('editedaction');} // for html editor integration + + + +if ($action != 'showprintablesurvey') +{ + $adminoutput = helpscreenscript(); + $adminoutput .= "\n" + ."\t\n" + ."\t\t\n".helpscreen() + . "\t\n" + . "
    \n"; +} else {$adminoutput='';} + +if($casEnabled) +{ + include_once("login_check_cas.php"); +} +else +{ + include_once('login_check.php'); +} + +if ( $action == 'CSRFwarn') +{ + include('access_denied.php'); +} + +if ( $action == 'FakeGET') +{ + include('access_denied.php'); +} + +if(isset($_SESSION['loginID']) && $action!='login') +{ + //VARIOUS DATABASE OPTIONS/ACTIONS PERFORMED HERE + if ($action == 'delsurvey' || $action == 'delgroup' || + $action == 'delquestion' || $action == 'insertnewsurvey'|| + $action == 'copynewquestion' || $action == 'insertnewgroup' || $action == 'insertCSV' || + $action == 'insertnewquestion' || $action == 'updatesurvey' || $action == 'updatesurvey2' || + $action == 'updategroup' || $action == 'deactivate' || $action == 'savepersonalsettings' || + $action == 'updatequestion' || $action == 'modanswer' || $action == 'renumberquestions' || + $action == 'delattribute' || $action == 'addattribute' || $action == 'editattribute') + { + include('database.php'); + } + +sendcacheheaders(); + +/* Check user right actions for validity + Currently existing user rights: + `configurator` + `create_survey` + `create_user` + `delete_user` + `manage_label` + `manage_template` + `superadmin` +*/ + +if ($action == 'importsurvey') + { + if ($_SESSION['USER_RIGHT_CREATE_SURVEY']==1) {include('http_importsurvey.php');} + else { include('access_denied.php');} + } +elseif ($action == 'dumpdb') + { + if ($_SESSION['USER_RIGHT_CONFIGURATOR']==1) {include('dumpdb.php');} + else { include('access_denied.php');} + } +elseif ($action == 'dumplabel') + { + if ($_SESSION['USER_RIGHT_MANAGE_LABEL']==1) {include('dumplabel.php');} + else { include('access_denied.php');} + } +elseif ($action == 'exportlabelresources') + { + if ($_SESSION['USER_RIGHT_MANAGE_TEMPLATE']==1) {$_SESSION['FileManagerContext']="edit:label:$lid"; include('export_resources_zip.php');} + else { include('access_denied.php');} + } +elseif ($action == 'checkintegrity') + { + if ($_SESSION['USER_RIGHT_CONFIGURATOR']==1) {include('integritycheck.php');} + else { include('access_denied.php');} + } +elseif ($action=='labels' || $action=='newlabelset' || $action=='insertlabelset' || + $action=='deletelabelset' || $action=='editlabelset' || $action=='modlabelsetanswers' || + $action=='updateset' || $action=='importlabels' ||$action == 'importlabelresources') + { + if ($_SESSION['USER_RIGHT_MANAGE_LABEL']==1) {$_SESSION['FileManagerContext']="edit:label:$lid"; include('labels.php');} + else { include('access_denied.php');} + } +elseif ($action=='templates' || $action=='templatecopy' || $action=='templatesavechanges' || + $action=='templaterename' || $action=='templateuploadfile' || $action=='templatefiledelete' || + $action=='templatezip' || $action=='templaterefresh' || $action=='templateupload') + { + if ($_SESSION['USER_RIGHT_MANAGE_TEMPLATE']==1) {include('templates.php');} + else { include('access_denied.php');} + } + + + +/* Check survey right actions for validity + Currently existing survey rights: + `edit_survey_property` + `define_questions` + `browse_response` + `export` + `delete_survey` + `activate_survey` +*/ + +if (isset($surveyid) && $surveyid) +{ +$surquery = "SELECT * FROM {$dbprefix}surveys_rights WHERE sid=".db_quote($surveyid)." AND uid = ".db_quote($_SESSION['loginID']); //Getting rights for this survey +$surresult = db_execute_assoc($surquery); +$surrows = $surresult->FetchRow(); +} + +if ($action == 'activate') + { + if($surrows['activate_survey'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include('activate.php');} + else { include('access_denied.php');} + } +elseif ($action == 'conditions') +{ + if($surrows['define_questions'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include('conditionshandling.php');} + else { include('access_denied.php');} + } +elseif ($action == 'importsurvresources') + { + if ($surrows['define_questions'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {$_SESSION['FileManagerContext']="edit:survey:$surveyid";include('import_resources_zip.php');} + else { include('access_denied.php');} + } +elseif ($action == 'exportstructurecsv') + { + if($surrows['export'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include('export_structure_csv.php');} + else { include('access_denied.php');} + } +elseif ($action == 'exportstructureLsrcCsv') + { + if($surrows['export'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include('export_structure_lsrc.php');} + else { include('access_denied.php');} + } +elseif ($action == 'exportstructurequexml') + { + if($surrows['export'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include('export_structure_quexml.php');} + else { include('access_denied.php');} + } +elseif ($action == 'exportsurvresources') + { + if($surrows['export'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {$_SESSION['FileManagerContext']="edit:survey:$surveyid";include('export_resources_zip.php');} + else { include('access_denied.php');} + } +elseif ($action == 'dumpquestion') + { + if($surrows['export'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include('dumpquestion.php');} + else { include('access_denied.php');} + } +elseif ($action == 'dumpgroup') + { + if($surrows['export'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include('dumpgroup.php');} + else { include('access_denied.php');} + } +elseif ($action == 'deactivate') + { + if($surrows['activate_survey'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include('deactivate.php');} + else { include('access_denied.php');} + } +elseif ($action == 'deletesurvey') + { + if($surrows['delete_survey'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include('deletesurvey.php');} + else { include('access_denied.php');} + } +elseif ($action == 'resetsurveylogic') + { + if($surrows['define_questions'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include('resetsurveylogic.php');} + else { include('access_denied.php');} + } +elseif ($action == 'importgroup') + { + if($surrows['define_questions'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include('importgroup.php');} + else { include('access_denied.php');} + } +elseif ($action == 'importquestion') + { + if($surrows['define_questions'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include('importquestion.php');} + else { include('access_denied.php');} + } +elseif ($action == 'listcolumn') + { + if($surrows['browse_response'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include('listcolumn.php');} + else { include('access_denied.php');} + } +elseif ($action == 'previewquestion') + { + if($surrows['define_questions'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include('preview.php');} + else { include('access_denied.php');} + } +elseif ($action=='addgroup' || $action=='editgroup') + { + if($surrows['define_questions'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {$_SESSION['FileManagerContext']="edit:group:$surveyid"; include('grouphandling.php');} + else { include('access_denied.php');} + } +elseif ($action == 'vvexport') + { + if($surrows['browse_response'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include('vvexport.php');} + else { include('access_denied.php');} + } +elseif ($action == 'vvimport') + { + if($surrows['browse_response'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include('vvimport.php');} + else { include('access_denied.php');} + } +elseif ($action == 'importoldresponses') + { + if($surrows['browse_response'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include('importoldresponses.php');} + else { include('access_denied.php');} + } +elseif ($action == 'saved') + { + if($surrows['browse_response'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include('saved.php');} + else { include('access_denied.php');} + } +elseif ($action == 'exportresults') + { + if($surrows['export'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include('exportresults.php');} + else { include('access_denied.php');} + } +elseif ($action == 'exportspss') + { + if($surrows['export'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include('export_data_spss.php');} + else { include('access_denied.php');} + } +elseif ($action == 'exportr') + { + if($surrows['export'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include('export_data_r.php');} + else { include('access_denied.php');} + } +elseif ($action == 'statistics') + { + if($surrows['browse_response'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include('statistics.php');} + else { include('access_denied.php');} + } +elseif ($action == 'dataentry') + { + if($surrows['browse_response'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include('dataentry.php');} + else { include('access_denied.php');} + } +elseif ($action == 'browse') + { + if($surrows['browse_response'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include('browse.php');} + else { include('access_denied.php');} + } +elseif ($action == 'tokens') + { + if($surrows['activate_survey'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {$_SESSION['FileManagerContext']="edit:emailsettings:$surveyid"; include('tokens.php');} + else { include('access_denied.php'); } + } +elseif ($action == 'iteratesurvey') + { + if( ($surrows['browse_response'] && $surrows['activate_survey']) || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include('iterate_survey.php');} + else { include('access_denied.php');} + } +elseif ($action=='showprintablesurvey') + { + include('printablesurvey.php'); //No special right needed to show the printable survey + } +elseif ($action=='assessments' || $action=='assessmentdelete' || $action=='assessmentedit' || $action=='assessmentadd' || $action=='assessmentupdate') + { + if($surrows['define_questions'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) { + $_SESSION['FileManagerContext']="edit:assessments:$surveyid"; + include('assessments.php'); + } + else { include('access_denied.php');} + } +elseif ($action == 'replacementfields') + { + switch ($editedaction) + { + case 'labels': + if ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $_SESSION['USER_RIGHT_MANAGE_LABEL']==1) + { + $_SESSION['FileManagerContext']="edit:label:$lid"; + include('fck_LimeReplacementFields.php');exit; + } + else + { + include('access_denied.php'); + } + break; + case 'newsurvey': + if ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $_SESSION['USER_RIGHT_CREATE_SURVEY'] == 1) + { + include('fck_LimeReplacementFields.php');exit; + } + else + { + include('access_denied.php'); + } + break; + case 'updatesurvey': + if ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $surrows['edit_survey_property']) + { + $_SESSION['FileManagerContext']="edit:survey:$surveyid"; + include('fck_LimeReplacementFields.php');exit; + } + else + { + include('access_denied.php'); + } + break; + case 'tokens': // email + if ( $_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $surrows['activate_survey']) + { + $_SESSION['FileManagerContext']="edit:emailsettings:$surveyid"; + include('fck_LimeReplacementFields.php');exit; + } + else + { + include('access_denied.php'); + } + break; + case 'editquestion': + case 'copyquestion': + case 'addquestion': + if ( $_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $surrows['define_questions']) + { + $_SESSION['FileManagerContext']="edit:question:$surveyid"; + include('fck_LimeReplacementFields.php');exit; + } + else + { + include('access_denied.php'); + } + break; + case 'editgroup': + case 'addgroup': + if ( $_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $surrows['define_questions']) + { + $_SESSION['FileManagerContext']="edit:group:$surveyid"; + include('fck_LimeReplacementFields.php');exit; + } + else + { + include('access_denied.php'); + } + break; + case 'editanswer': + if ( $_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $surrows['define_questions']) + { + $_SESSION['FileManagerContext']="edit:answer:$surveyid"; + include('fck_LimeReplacementFields.php');exit; + } + else + { + include('access_denied.php'); + } + break; + case 'assessments': + case 'assessmentedit': + if($surrows['define_questions'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) { + $_SESSION['FileManagerContext']="edit:assessments:$surveyid"; + include('fck_LimeReplacementFields.php'); + } + else { include('access_denied.php');} + break; + default: + break; + } + } + + if (!isset($assessmentsoutput) && !isset($statisticsoutput) && !isset($browseoutput) && !isset($savedsurveyoutput) && !isset( $listcolumnoutput ) && + !isset($dataentryoutput) && !isset($conditionsoutput) && !isset($importoldresponsesoutput) && !isset($exportspssoutput) && !isset($exportroutput) && + !isset($vvoutput) && !isset($tokenoutput) && !isset($exportoutput) && !isset($templatesoutput) && !isset($iteratesurveyoutput) && + (isset($surveyid) || $action=='listurveys' || $action=='personalsettings' || $action=='checksettings' || //Still to check + $action=='editsurvey' || $action=='updatesurvey' || $action=='ordergroups' || + $action=='newsurvey' || $action=='listsurveys' || + $action=='surveyrights' || $action=='quotas') ) +{ + if ($action=='editsurvey' || $action=='updatesurvey') + { + $_SESSION['FileManagerContext']="edit:survey:$surveyid"; + } + include('html.php'); +} + + if ($action=='addquestion' || $action=='copyquestion' || $action=='editquestion' || + $action=='orderquestions' || $action=='editattribute' || $action=='delattribute' || + $action=='addattribute' ) + {if($surrows['define_questions'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {$_SESSION['FileManagerContext']="edit:question:$surveyid";include('questionhandling.php');} + else { include('access_denied.php');} + } + + + if ($action=='adduser' || $action=='deluser' || $action=='moduser' || $action=='setusertemplates' || $action=='usertemplates' || //Still to check + $action=='userrights' || $action=='modifyuser' || $action=='editusers' || + $action=='addusergroup' || $action=='editusergroup' || $action=='mailusergroup' || + $action=='delusergroup' || $action=='usergroupindb' || $action=='mailsendusergroup' || + $action=='editusergroupindb' || $action=='editusergroups' || $action=='deleteuserfromgroup' || + $action=='addusertogroup' || $action=='setuserrights' || $action=='setasadminchild') + + { + include ('userrighthandling.php'); + } + + + // For some output we dont want to have the standard admin menu bar + if (!isset($labelsoutput) && !isset($templatesoutput) && !isset($printablesurveyoutput) && + !isset($assessmentsoutput) && !isset($tokenoutput) && !isset($browseoutput) && !isset($exportspssoutput) && !isset($exportroutput) && + !isset($dataentryoutput) && !isset($statisticsoutput)&& !isset($savedsurveyoutput) && + !isset($exportoutput) && !isset($importoldresponsesoutput) && !isset($conditionsoutput) && + !isset($vvoutput) && !isset($listcolumnoutput) && !isset($importlabelresources) && !isset($iteratesurveyoutput)) + { + $adminoutput.= showadminmenu(); + } + + + if (isset($databaseoutput)) {$adminoutput.= $databaseoutput;} + if (isset($templatesoutput)) {$adminoutput.= $templatesoutput;} + if (isset($accesssummary )) {$adminoutput.= $accesssummary;} + if (isset($surveysummary )) {$adminoutput.= $surveysummary;} + if (isset($usergroupsummary)){$adminoutput.= $usergroupsummary;} + if (isset($usersummary )) {$adminoutput.= $usersummary;} + if (isset($groupsummary )) {$adminoutput.= $groupsummary;} + if (isset($questionsummary)) {$adminoutput.= $questionsummary;} + if (isset($vasummary )) {$adminoutput.= $vasummary;} + if (isset($addsummary )) {$adminoutput.= $addsummary;} + if (isset($answersummary )) {$adminoutput.= $answersummary;} + if (isset($cssummary )) {$adminoutput.= $cssummary;} + if (isset($listcolumnoutput)) {$adminoutput.= $listcolumnoutput;} + + + if (isset($editgroup)) {$adminoutput.= $editgroup;} + if (isset($editquestion)) {$adminoutput.= $editquestion;} + if (isset($editsurvey)) {$adminoutput.= $editsurvey;} + if (isset($quotasoutput)) {$adminoutput.= $quotasoutput;} + if (isset($labelsoutput)) {$adminoutput.= $labelsoutput;} + if (isset($listsurveys)) {$adminoutput.= $listsurveys; } + if (isset($integritycheck)) {$adminoutput.= $integritycheck;} + if (isset($ordergroups)){$adminoutput.= $ordergroups;} + if (isset($orderquestions)) {$adminoutput.= $orderquestions;} + if (isset($surveysecurity)) {$adminoutput.= $surveysecurity;} + if (isset($exportstructure)) {$adminoutput.= $exportstructure;} + if (isset($newsurvey)) {$adminoutput.= $newsurvey;} + if (isset($newgroupoutput)) {$adminoutput.= $newgroupoutput;} + if (isset($newquestionoutput)) {$adminoutput.= $newquestionoutput;} + if (isset($newanswer)) {$adminoutput.= $newanswer;} + if (isset($editanswer)) {$adminoutput.= $editanswer;} + if (isset($assessmentsoutput)) {$adminoutput.= $assessmentsoutput;} + + if (isset($importsurvey)) {$adminoutput.= $importsurvey;} + if (isset($importsurvresourcesoutput)) {$adminoutput.= $importsurvresourcesoutput;} + if (isset($importgroup)) {$adminoutput.= $importgroup;} + if (isset($importquestion)) {$adminoutput.= $importquestion;} + if (isset($printablesurveyoutput)) {$adminoutput.= $printablesurveyoutput;} + if (isset($activateoutput)) {$adminoutput.= $activateoutput;} + if (isset($deactivateoutput)) {$adminoutput.= $deactivateoutput;} + if (isset($tokenoutput)) {$adminoutput.= $tokenoutput;} + if (isset($browseoutput)) {$adminoutput.= $browseoutput;} + if (isset($iteratesurveyoutput)) {$adminoutput.= $iteratesurveyoutput;} + if (isset($dataentryoutput)) {$adminoutput.= $dataentryoutput;} + if (isset($statisticsoutput)) {$adminoutput.= $statisticsoutput;} + if (isset($exportoutput)) {$adminoutput.= $exportoutput;} + if (isset($savedsurveyoutput)) {$adminoutput.= $savedsurveyoutput;} + if (isset($importoldresponsesoutput)) {$adminoutput.= $importoldresponsesoutput;} + if (isset($conditionsoutput)) {$adminoutput.= $conditionsoutput;} + if (isset($deletesurveyoutput)) {$adminoutput.= $deletesurveyoutput;} + if (isset($resetsurveylogicoutput)) {$adminoutput.= $resetsurveylogicoutput;} + if (isset($vvoutput)) {$adminoutput.= $vvoutput;} + if (isset($dumpdboutput)) {$adminoutput.= $dumpdboutput;} + if (isset($exportspssoutput)) {$adminoutput.= $exportspssoutput;} + if (isset($exportroutput)) {$adminoutput.= $exportroutput;} + + + if (!isset($printablesurveyoutput) && ($subaction!='export')) + { + if (!isset($_SESSION['metaHeader'])) {$_SESSION['metaHeader']='';} + + $adminoutput = getAdminHeader($_SESSION['metaHeader']).$adminoutput; // All future output is written into this and then outputted at the end of file + unset($_SESSION['metaHeader']); + $adminoutput.= "\t\t
    \n"; + if(!isset($_SESSION['checksessionpost'])) + $_SESSION['checksessionpost'] = ''; + $adminoutput .= "\n"; + + $adminoutput .= "".getAdminFooter("http://docs.limesurvey.org", $clang->gT("LimeSurvey Online Manual")); + } + +} + else + { //not logged in + sendcacheheaders(); + if (!isset($_SESSION['metaHeader'])) {$_SESSION['metaHeader']='';} + $adminoutput = getAdminHeader($_SESSION['metaHeader']).$adminoutput; // All future output is written into this and then outputted at the end of file + unset($_SESSION['metaHeader']); + $adminoutput.= "\t\t\n".helpscreen() + . "\t\n" + . "\n" + . getAdminFooter("http://docs.limesurvey.org", $clang->gT("LimeSurvey Online Manual")); + + } + +if (($action=='showphpinfo') && ($_SESSION['USER_RIGHT_CONFIGURATOR'] == 1)) +{ + phpinfo(); +} +else +{ + echo $adminoutput; +} + + + function helpscreenscript() + // returns the script part for online help to be included outside a table + { + $helpoutput= "\n"; + return $helpoutput; + } + + + function helpscreen() + // This functions loads the nescessary helpscreens for each action and hides the help window + // + { + global $homeurl, $langdir, $imagefiles; + global $surveyid, $gid, $qid, $action, $clang; + + $helpoutput="\t\t\n" + ."\t\t\t
    " + ."\n" + ."\t\t\t\t\n" + ."\t\t\t\t\t\n" + ."\t\t\t\t\n" + ."\t\t\t\t\n" + ."\t\t\t\t\t\n" + ."\t\t\t\t\n" + ."\t\t\t\t\n" + ."\t\t\t\t\t" + ."\t\t\t\t\n" + ."\t\t\t
    \n" + ."\t\t\t\t\t\t" + .$clang->gT("Help")."\n" + ."\t\t\t\t\t
    \n" + ."\t\t\t\t\t\t\n" + ."\t\t\t\t\t\t\n" + ."\t\t\t\t\t
    \n"; + //determine which help document to show + if (!$surveyid && $action != "editusers") + { + $helpdoc = "$langdir/admin.html"; + } + elseif (!$surveyid && $action=="editusers") + { + $helpdoc = "$langdir/users.html"; + } + elseif ($surveyid && !$gid) + { + $helpdoc = "$langdir/survey.html"; + } + elseif ($surveyid && $gid && !$qid) + { + $helpdoc = "$langdir/group.html"; + } + elseif ($surveyid && $gid && $qid && !returnglobal('viewanswer')) + { + $helpdoc = "$langdir/question.html"; + } + elseif ($surveyid && $gid && $qid && (returnglobal('viewanswer'))) + { + $helpdoc = "$langdir/answer.html"; + } + $helpoutput.= "\t\t\t\t\t\t\n" + ."\t\t\t\t\t
    \n" + ."\t\t\n"; + return $helpoutput; + } + + + +function convertToArray($stringtoconvert, $seperator, $start, $end) +// this function is still used to read SQL files from version 1.0 or older +{ + $begin=strpos($stringtoconvert, $start)+strlen($start); + $len=strpos($stringtoconvert, $end)-$begin; + $stringtoconvert=substr($stringtoconvert, $begin, $len); + $stringtoconvert=str_replace('\n',"\n",$stringtoconvert); //removes masking + $stringtoconvert=stripslashes($stringtoconvert); + $resultarray=explode($seperator, $stringtoconvert); + return $resultarray; +} + +function get2post($url) +{ + $url = preg_replace('/&/i','&',$url); + list($calledscript,$query) = explode('?',$url); + $aqueryitems = explode('&',$query); + $arrayParam = Array(); + $arrayVal = Array(); + + foreach ($aqueryitems as $queryitem) + { + list($paramname, $value) = explode ('=', $queryitem); + $arrayParam[] = "'".$paramname."'"; + $arrayVal[] = "'".$value."'"; + } +// $Paramlist = "[" . implode(",",$arrayParam) . "]"; +// $Valuelist = "[" . implode(",",$arrayVal) . "]"; + $Paramlist = "new Array(" . implode(",",$arrayParam) . ")"; + $Valuelist = "new Array(" . implode(",",$arrayVal) . ")"; + $callscript = "sendPost('$calledscript','".$_SESSION['checksessionpost']."',$Paramlist,$Valuelist);"; + return $callscript; +} + +?> diff --git a/include/limesurvey/admin/assessments.php b/include/limesurvey/admin/assessments.php index e67a2c8b..3fc0919e 100644 --- a/include/limesurvey/admin/assessments.php +++ b/include/limesurvey/admin/assessments.php @@ -1,223 +1,330 @@ -Execute($actsurquery) or safe_die($connect->ErrorMsg()); -$actsurrows = $actsurresult->FetchRow(); - -if($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $actsurrows['edit_survey_property']){ - - if ($action == "assessmentadd") { - $inserttable=$dbprefix."assessments"; - $query = $connect->GetInsertSQL($inserttable, array( - 'sid' => $surveyid, - 'scope' => $_POST['scope'], - 'gid' => $_POST['gid'], - 'minimum' => $_POST['minimum'], - 'maximum' => $_POST['maximum'], - 'name' => $_POST['name'], - 'message' => $_POST['message'], - 'link' => $_POST['link'] )); - $result=$connect->Execute($query) or safe_die("Error inserting
    $query
    ".$connect->ErrorMsg()); - } elseif ($action == "assessmentupdate") { - $query = "UPDATE {$dbprefix}assessments - SET scope='".db_quote($_POST['scope'])."', - gid=".sanitize_int($_POST['gid']).", - minimum='".sanitize_int($_POST['minimum'])."', - maximum='".sanitize_int($_POST['maximum'])."', - name='".db_quote($_POST['name'])."', - message='".db_quote($_POST['message'])."', - link='".db_quote($_POST['link'])."' - WHERE id=".sanitize_int($_POST['id']); - $result = $connect->Execute($query) or safe_die("Error updating
    $query
    ".$connect->ErrorMsg()); - } elseif ($action == "assessmentdelete") { - $query = "DELETE FROM {$dbprefix}assessments - WHERE id=".sanitize_int($_POST['id']); - $result=$connect->Execute($query); - } - - $assessmentsoutput= "\n" - . "\t\n" - . "\t\t
    \n" - . "\t\t\t\n" - . "\t\t\t\n" - . "\t\t\t\t\n"; - - $assessmentsoutput.= "\t\n" - . "\t\t\n" - . "\t\n"; - $assessmentsoutput.= ""; - - if ($surveyid == "") { - $assessmentsoutput.= $clang->gT("No SID Provided"); - exit; - } - - $assessments=getAssessments($surveyid); - //$assessmentsoutput.= "
    ";print_r($assessments);echo "
    "; - $groups=getGroups($surveyid); - $groupselect="\n"; - $headings=array($clang->gT("Scope"), $clang->gT("Group"), $clang->gT("Minimum"), $clang->gT("Maximum"), $clang->gT("Heading"), $clang->gT("Message"), $clang->gT("URL")); - $inputs=array("", - $groupselect, - "", - "", - "", - "", - ""); - $actiontitle=$clang->gT("Add"); - $actionvalue="assessmentadd"; - $thisid=""; - - if ($action == "assessmentedit") { - $query = "SELECT * FROM {$dbprefix}assessments WHERE id=".sanitize_int($_POST['id']); - $results = db_execute_assoc($query); - while($row=$results->FetchRow()) { - $editdata=$row; - } - $scopeselect = ""; - $groupselect=str_replace("'".$editdata['gid']."'", "'".$editdata['gid']."' selected", $groupselect); - $inputs=array($scopeselect, - $groupselect, - "", - "", - "", - "", - ""); - $actiontitle=$clang->gT("Edit"); - $actionvalue="assessmentupdate"; - $thisid=$editdata['id']; - } - //$assessmentsoutput.= "
    "; print_r($edits); $assessmentsoutput.= "
    "; - //PRESENT THE PAGE - - $assessmentsoutput.= "
    - " - ."\n"; - foreach ($headings as $head) { - $assessmentsoutput.= "\n"; - } - $assessmentsoutput.= ""; - $assessmentsoutput.= "\n"; - $flipflop=true; - foreach($assessments as $assess) { - $flipflop=!$flipflop; - if ($flipflop==true){$assessmentsoutput.= "\n";} - else {$assessmentsoutput.= "\n";} - $assessmentsoutput.= "\n"; - $assessmentsoutput.= "\n"; - - if ($assess['scope'] == "T") { $assessmentsoutput.= "\n"; } - else {$assessmentsoutput.= "\n"; } - - $assessmentsoutput.= "\n"; - - $assessmentsoutput.= "\n"; - $assessmentsoutput.= "\n"; - $assessmentsoutput.= "\n"; - $assessmentsoutput.= "\n"; - $assessmentsoutput.= "\n"; - - $assessmentsoutput.= "\n"; - $assessmentsoutput.= "\n"; - } - $assessmentsoutput.= "
    ".$clang->gT("If you create any assessments in this page, for the currently selected survey, the assessment will be performed at the end of the survey after submission")."
    IDSID$head".$clang->gT("Actions")."
    ".$assess['id']."".$assess['sid']."".$clang->gT("Total")."".$clang->gT("Group")."".$groups[$assess['gid']]['group_name']." (".$assess['gid'].")".$assess['minimum']."".$assess['maximum']."".stripslashes($assess['name'])."".stripslashes($assess['message'])."".stripslashes($assess['link'])." - - - - -
    - - - -
    - - - -
    -
    -
    "; - $assessmentsoutput.= "
    \n"; - $assessmentsoutput.= "\n"; - $i=0; - - foreach ($headings as $head) { - $assessmentsoutput.= "\n"; - $i++; - } - $assessmentsoutput.= "\n" - ."
    $actiontitle
    $head".$inputs[$i]."
    \n"; - if ($action == "assessmentedit") $assessmentsoutput.= "    \n"; - $assessmentsoutput.= "\n" - ."\n" - ."\n" - ."
    \n"; - } -else - { - $action = "assessment"; - include("access_denied.php"); - include("admin.php"); - } - -function getAssessments($surveyid) { - global $dbprefix, $connect; - $query = "SELECT id, sid, scope, gid, minimum, maximum, name, message, link - FROM ".db_table_name('assessments')." - WHERE sid='$surveyid' - ORDER BY scope, gid"; - $result=db_execute_assoc($query) or safe_die("Error getting assessments
    $query
    ".$connect->ErrorMsg()); - $output=array(); - while($row=$result->FetchRow()) { - $output[]=$row; - } - return $output; -} - -function getGroups($surveyid) { - global $dbprefix, $connect; - $baselang = GetBaseLanguageFromSurveyID($surveyid); - $query = "SELECT gid, group_name - FROM ".db_table_name('groups')." - WHERE sid='$surveyid' and language='$baselang' - ORDER BY group_order"; - $result = db_execute_assoc($query) or safe_die("Error getting groups
    $query
    ".$connect->ErrorMsg()); - $output=array(); - while($row=$result->FetchRow()) { - $output[$row['gid']]=$row; - } - return $output; -} -?> +\n"; + + +$actsurquery = "SELECT edit_survey_property FROM {$dbprefix}surveys_rights WHERE sid=$surveyid AND uid = ".$_SESSION['loginID']; //Getting rights for this survey +$actsurresult = $connect->Execute($actsurquery) or safe_die($connect->ErrorMsg()); +$actsurrows = $actsurresult->FetchRow(); + + +$assessmentlangs = GetAdditionalLanguagesFromSurveyID($surveyid); +$baselang = GetBaseLanguageFromSurveyID($surveyid); +array_unshift($assessmentlangs,$baselang); // makes an array with ALL the languages supported by the survey -> $assessmentlangs + + +if($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $actsurrows['edit_survey_property']){ + + if ($action == "assessmentadd") { + $inserttable=$dbprefix."assessments"; + $first=true; + foreach ($assessmentlangs as $assessmentlang) + { + if (!isset($_POST['gid'])) $_POST['gid']=0; + + $datarray=array( + 'sid' => $surveyid, + 'scope' => $_POST['scope'], + 'gid' => $_POST['gid'], + 'minimum' => $_POST['minimum'], + 'maximum' => $_POST['maximum'], + 'name' => $_POST['name_'.$assessmentlang], + 'language' => $assessmentlang, + 'message' => $_POST['assessmentmessage_'.$assessmentlang]); + + if ($first==false) + { + $datarray['id']=$aid; + } + + $query = $connect->GetInsertSQL($inserttable, $datarray, get_magic_quotes_gpc()); + $result=$connect->Execute($query) or safe_die("Error inserting
    $query
    ".$connect->ErrorMsg()); + if ($first==true) + { + $first=false; + $aid=$connect->Insert_ID(db_table_name_nq('assessments'),"id"); + } + } + } elseif ($action == "assessmentupdate") { + + if ($filterxsshtml) + { + require_once("../classes/inputfilter/class.inputfilter_clean.php"); + $myFilter = new InputFilter('','',1,1,1); + } + + foreach ($assessmentlangs as $assessmentlang) + { + + if (!isset($_POST['gid'])) $_POST['gid']=0; + if ($filterxsshtml) + { + $_POST['name_'.$assessmentlang]=$myFilter->process($_POST['name_'.$assessmentlang]); + $_POST['assessmentmessage_'.$assessmentlang]=$myFilter->process($_POST['assessmentmessage_'.$assessmentlang]); + } + $query = "UPDATE {$dbprefix}assessments + SET scope='".db_quote($_POST['scope'])."', + gid=".sanitize_int($_POST['gid']).", + minimum='".sanitize_signedint($_POST['minimum'])."', + maximum='".sanitize_signedint($_POST['maximum'])."', + name='".db_quote($_POST['name_'.$assessmentlang],true)."', + message='".db_quote($_POST['assessmentmessage_'.$assessmentlang],true)."' + WHERE language='$assessmentlang' and id=".sanitize_int($_POST['id']); + $result = $connect->Execute($query) or safe_die("Error updating
    $query
    ".$connect->ErrorMsg()); + } + } elseif ($action == "assessmentdelete") { + $query = "DELETE FROM {$dbprefix}assessments + WHERE id=".sanitize_int($_POST['id']); + $result=$connect->Execute($query); + } + + $assessmentsoutput=PrepareEditorScript(); + $assessmentsoutput.=""; + $assessmentsoutput.="\n" + . "\t\n" + . "\t\t\n" - ."\t
    \n" + . "\n"; + $assessmentsoutput .= "

     

    "; //CSS Firefox 2 transition fix + + if ($surveyid == "") { + $assessmentsoutput.= $clang->gT("No SID Provided"); + exit; + } + + $assessments=getAssessments($surveyid); + //$assessmentsoutput.= "
    ";print_r($assessments);echo "
    "; + $groups=getGroups($surveyid); + $groupselect="\n"; + $headings=array($clang->gT("Scope"), $clang->gT("Question group"), $clang->gT("Minimum"), $clang->gT("Maximum")); + $inputs=array("".$clang->gT("Total")."".$clang->gT("Group")."", + $groupselect, + "", + ""); + $actiontitle=$clang->gT("Add"); + $actionvalue="assessmentadd"; + $thisid=""; + + if ($action == "assessmentedit") { + $query = "SELECT * FROM {$dbprefix}assessments WHERE id=".sanitize_int($_POST['id'])." and language='$baselang'"; + $results = db_execute_assoc($query); + while($row=$results->FetchRow()) { + $editdata=$row; + } + $scopeselect = "gT("Total").""; + $scopeselect .= "gT("Question group").""; + $groupselect=str_replace("'".$editdata['gid']."'", "'".$editdata['gid']."' selected", $groupselect); + $inputs=array($scopeselect, + $groupselect, + "", + "", + "", + ""); + $actiontitle=$clang->gT("Edit"); + $actionvalue="assessmentupdate"; + $thisid=$editdata['id']; + } + //$assessmentsoutput.= "
    "; print_r($edits); $assessmentsoutput.= "
    "; + //PRESENT THE PAGE + + + $assessmentsoutput.= "
    + " + ."\n"; + foreach ($headings as $head) { + $assessmentsoutput.= "\n"; + } + $assessmentsoutput.= ""; + $assessmentsoutput.= "\n"; + $flipflop=true; + foreach($assessments as $assess) { + $flipflop=!$flipflop; + if ($flipflop==true){$assessmentsoutput.= "\n";} + else {$assessmentsoutput.= "\n";} + $assessmentsoutput.= "\n"; + $assessmentsoutput.= "\n"; + + if ($assess['scope'] == "T") + { + $assessmentsoutput.= "\n"; + $assessmentsoutput.= "\n"; + } + else + { + $assessmentsoutput.= "\n"; + $assessmentsoutput.= "\n"; + } + + + $assessmentsoutput.= "\n"; + $assessmentsoutput.= "\n"; + $assessmentsoutput.= "\n"; + $assessmentsoutput.= "\n"; + + $assessmentsoutput.= "\n"; + $assessmentsoutput.= "\n"; + } + $assessmentsoutput.= "
    ".$clang->gT("Assessment rules")."
    ".$clang->gT("ID")."".$clang->gT("SID")."$head".$clang->gT("Title")."".$clang->gT("Message")."".$clang->gT("Actions")."
    ".$assess['id']."".$assess['sid']."".$clang->gT("Total")."-".$clang->gT("Question group")."".$groups[$assess['gid']]['group_name']." (".$assess['gid'].")".$assess['minimum']."".$assess['maximum']."".stripslashes($assess['name'])."".strip_tags(strip_javascript($assess['message']))." + + + + +
    + + + +
    + + + +
    +
    +
    "; + + + //now present edit/insert form + $assessmentsoutput.= "
    \n"; + $assessmentsoutput.= "\n"; + $i=0; + + foreach ($headings as $head) { + $assessmentsoutput.= "\n"; + $i++; + } + + + // start tabs + $assessmentsoutput.= "\n"; + $assessmentsoutput.='
    $actiontitle
    $head".$inputs[$i]."
      
    ' + .''; + foreach ($assessmentlangs as $assessmentlang) + { + $heading=''; $message=''; + if ($action == "assessmentedit") + { + $query = "SELECT * FROM {$dbprefix}assessments WHERE id=".sanitize_int($_POST['id'])." and language='$assessmentlang'"; + $results = db_execute_assoc($query); + while($row=$results->FetchRow()) { + $editdata=$row; + } + $heading=$editdata['name']; + $message=$editdata['message']; + } + $assessmentsoutput .= '
    '; + $assessmentsoutput .= $clang->gT("Heading")."
    " + ."

    " + .$clang->gT("Message") + .""; + + $assessmentsoutput .='
    '; + } + $assessmentsoutput .='
    '; + + + $assessmentsoutput.= "
    \n"; + if ($action == "assessmentedit") $assessmentsoutput.= "    \n"; + $assessmentsoutput.= "\n" + ."\n" + ."\n" + ."
    \n" + ."\n"; + foreach ($assessmentlangs as $assessmentlang) + { + $assessmentsoutput.=getEditor("assessment-text","assessmentmessage_$assessmentlang", "[".$clang->gT("Message:", "js")."]",$surveyid,$gid,$qid,$action); + } + + } +else + { + $action = "assessment"; + include("access_denied.php"); + include("admin.php"); + } + +function getAssessments($surveyid) { + global $dbprefix, $connect, $baselang; + $query = "SELECT id, sid, scope, gid, minimum, maximum, name, message + FROM ".db_table_name('assessments')." + WHERE sid='$surveyid' and language='$baselang' + ORDER BY scope, gid"; + $result=db_execute_assoc($query) or safe_die("Error getting assessments
    $query
    ".$connect->ErrorMsg()); + $output=array(); + while($row=$result->FetchRow()) { + $output[]=$row; + } + return $output; +} + +function getGroups($surveyid) { + global $dbprefix, $connect; + $baselang = GetBaseLanguageFromSurveyID($surveyid); + $query = "SELECT gid, group_name + FROM ".db_table_name('groups')." + WHERE sid='$surveyid' and language='$baselang' + ORDER BY group_order"; + $result = db_execute_assoc($query) or safe_die("Error getting groups
    $query
    ".$connect->ErrorMsg()); + $output=array(); + while($row=$result->FetchRow()) { + $output[$row['gid']]=$row; + } + return $output; +} +?> diff --git a/include/limesurvey/admin/browse.php b/include/limesurvey/admin/browse.php index bb8f796e..022656bd 100644 --- a/include/limesurvey/admin/browse.php +++ b/include/limesurvey/admin/browse.php @@ -1,728 +1,808 @@ -MetaTables() or safe_die ("Error getting tokens
    ".$connect->ErrorMsg()); -foreach ($tablelist as $tbl) -{ - if (db_quote_id($tbl) == db_table_name('survey_'.$surveyid)) $resultsexist = 1; -} - -if (!isset($resultsexist)) die("Your results table is missing!"); - -$sumquery5 = "SELECT b.* FROM {$dbprefix}surveys AS a INNER JOIN {$dbprefix}surveys_rights AS b ON a.sid = b.sid WHERE a.sid=$surveyid AND b.uid = ".$_SESSION['loginID']; //Getting rights for this survey and user -$sumresult5 = db_execute_assoc($sumquery5); -$sumrows5 = $sumresult5->FetchRow(); - -require_once(dirname(__FILE__).'/sessioncontrol.php'); - -// Set language for questions and labels to base language of this survey - -if (isset($browselang) && $browselang!='') -{ - $_SESSION['browselang']=$browselang; - $language=$_SESSION['browselang']; -} -elseif (isset($_SESSION['browselang'])) -{ - $language=$_SESSION['browselang']; -} -else -{ - $language = GetBaseLanguageFromSurveyID($surveyid); -} - - -$surveyoptions = browsemenubar(); -$browseoutput = "
    \n" -."\n"; - -if (!$database_exists) //DATABASE DOESN'T EXIST OR CAN'T CONNECT -{ - $browseoutput .= "\t\n" - ."\t\n" - ."\n"; - return; -} -if (!$surveyid && !$subaction) //NO SID OR ACTION PROVIDED -{ - $browseoutput .= "\t
    " - . $clang->gT("Browse Responses")."
    $setfont\n" - ."".$clang->gT("Error")."
    \n" - . $clang->gT("You have not selected a survey to browse.")."

    \n" - ."
    \n" - ."
    \n"; - return; -} - -//CHECK IF SURVEY IS ACTIVATED AND EXISTS -$actquery = "SELECT * FROM ".db_table_name('surveys')." as a inner join ".db_table_name('surveys_languagesettings')." as b on (b.surveyls_survey_id=a.sid and b.surveyls_language=a.language) WHERE a.sid=$surveyid"; - -$actresult = db_execute_assoc($actquery); -$actcount = $actresult->RecordCount(); -if ($actcount > 0) -{ - while ($actrow = $actresult->FetchRow()) - { - $surveytable = db_table_name("survey_".$actrow['sid']); - $surveyname = "{$actrow['surveyls_title']}"; - if ($actrow['active'] == "N") //SURVEY IS NOT ACTIVE YET - { - $browseoutput .= "\t" - . $clang->gT("Browse Responses").": $surveyname\n" - ."\t\n" - ."".$clang->gT("Error")."
    \n" - . $clang->gT("This survey has not been activated. There are no results to browse.")."

    \n" - ."
    \n" - ."\n" - ."\n"; - return; - } - } -} -else //SURVEY MATCHING $surveyid DOESN'T EXIST -{ - $browseoutput .= "\t" - . $clang->gT("Browse Responses")."\n" - ."\t\n" - ."".$clang->gT("Error")."
    \n" - . $clang->gT("There is no matching survey.")." ($surveyid)

    \n" - ."
    \n" - ."\n" - ."\n"; - return; -} - -//OK. IF WE GOT THIS FAR, THEN THE SURVEY EXISTS AND IT IS ACTIVE, SO LETS GET TO WORK. -$qulanguage = GetBaseLanguageFromSurveyID($surveyid); -if ($subaction == "id") // Looking at a SINGLE entry -{ - //SHOW HEADER - $browseoutput .= "\t".$clang->gT("Browse Responses").": $surveyname\n"; - if (!isset($_POST['sql']) || !$_POST['sql']) {$browseoutput .= "$surveyoptions";} // Don't show options if coming from tokens script - $browseoutput .= "\n" - ."
    \n"; - //FIRST LETS GET THE NAMES OF THE QUESTIONS AND MATCH THEM TO THE FIELD NAMES FOR THE DATABASE - $fnquery = "SELECT * FROM ".db_table_name("questions").", ".db_table_name("groups").", ".db_table_name("surveys")." - WHERE ".db_table_name("questions").".gid=".db_table_name("groups").".gid AND ".db_table_name("groups").".sid=".db_table_name("surveys").".sid - AND ".db_table_name("questions").".sid='$surveyid' AND - ".db_table_name("questions").".language='{$language}' AND ".db_table_name("groups").".language='{$language}' ORDER BY ".db_table_name("groups").".group_order, ".db_table_name("questions").".title"; - $fnresult = db_execute_assoc($fnquery); - $fncount = 0; - - $fnrows = array(); //Create an empty array in case fetch_array does not return any rows - while ($fnrow = $fnresult->FetchRow()) {++$fncount; $fnrows[] = $fnrow; $private = $fnrow['private']; $datestamp=$fnrow['datestamp']; $ipaddr=$fnrow['ipaddr']; $refurl=$fnrow['refurl'];} // Get table output into array - - // Perform a case insensitive natural sort on group name then question title of a multidimensional array - usort($fnrows, 'CompareGroupThenTitle'); - - $fnames[] = array("id", "id", "id"); - if ($private == "N") //add token to top ofl ist is survey is not private - { - $fnames[] = array("token", "token", $clang->gT("Token ID")); - } - - $fnames[] = array("completed", "Completed", $clang->gT("Completed"), "0"); - - if ($datestamp == "Y") //add datetime to list if survey is datestamped - { - // submitdate for not-datestamped surveys is always 1980/01/01 - // so only display it when datestamped - $fnames[] = array("startdate", "startdate", $clang->gT("Date Started")); - $fnames[] = array("datestamp", "datestamp", $clang->gT("Date Last Action")); - $fnames[] = array("submitdate", "submitdate", $clang->gT("Date Submitted")); - } - if ($ipaddr == "Y") //add ipaddr to list if survey should save submitters IP address - { - $fnames[] = array("ipaddr", "ipaddr", $clang->gT("IP Address")); - } - if ($refurl == "Y") //add refer_URL to list if survey should save referring URL - { - $fnames[] = array("refurl", "refurl", $clang->gT("Referring URL")); - } - foreach ($fnrows as $fnrow) - { - $field = "{$fnrow['sid']}X{$fnrow['gid']}X{$fnrow['qid']}"; - $ftitle = "Grp{$fnrow['gid']}Qst{$fnrow['title']}"; - $fquestion = $fnrow['question']; - if ($fnrow['type'] == "Q" || $fnrow['type'] == "M" || - $fnrow['type'] == "A" || $fnrow['type'] == "B" || - $fnrow['type'] == "C" || $fnrow['type'] == "E" || - $fnrow['type'] == "F" || $fnrow['type'] == "H" || - $fnrow['type'] == "J" || $fnrow['type'] == "K" || - $fnrow['type'] == "P" || $fnrow['type'] == "^") - { - $fnrquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid={$fnrow['qid']} AND language='{$language}' ORDER BY sortorder, answer"; - $fnrresult = db_execute_assoc($fnrquery); - while ($fnrrow = $fnrresult->FetchRow()) - { - $fnames[] = array("$field{$fnrrow['code']}", "$ftitle ({$fnrrow['code']})", "{$fnrow['question']} ({$fnrrow['answer']})"); - if ($fnrow['type'] == "P") {$fnames[] = array("$field{$fnrrow['code']}"."comment", "$ftitle"."comment", "{$fnrow['question']} (".$clang->gT("Comment").")");} - } - if ($fnrow['other'] == "Y" and ($fnrow['type']=="!" or $fnrow['type']=="L" or $fnrow['type']=="M" or $fnrow['type']=="P" || $fnrow['type'] == "Z" || $fnrow['type'] == "W")) - { - $fnames[] = array("$field"."other", "$ftitle"."other", "{$fnrow['question']}(".$clang->gT("Other").")"); - } - } - elseif ($fnrow['type'] == "R") - { - $fnrquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid={$fnrow['qid']} AND - language='{$language}' - ORDER BY sortorder, answer"; - $fnrresult = $connect->Execute($fnrquery); - $fnrcount = $fnrresult->RecordCount(); - for ($i=1; $i<=$fnrcount; $i++) - { - $fnames[] = array("$field$i", "$ftitle ($i)", "{$fnrow['question']} ($i)"); - } - } - elseif ($fnrow['type'] == "O") - { - $fnames[] = array("$field", "$ftitle", "{$fnrow['question']}"); - $field2 = $field."comment"; - $ftitle2 = $ftitle."[Comment]"; - $longtitle = "{$fnrow['question']}
    [Comment]"; - $fnames[] = array("$field2", "$ftitle2", "$longtitle"); - } - elseif ($fnrow['type'] == "1") // multi scale - { - $i2query = "SELECT ".db_table_name("answers").".*, ".db_table_name("questions").".other FROM ".db_table_name("answers").", ".db_table_name("questions")." - WHERE ".db_table_name("answers").".qid=".db_table_name("questions").".qid AND - ".db_table_name("answers").".language='{$language}' AND ".db_table_name("questions").".language='{$language}' AND - ".db_table_name("questions").".qid={$fnrow['qid']} AND ".db_table_name("questions").".sid=$surveyid - ORDER BY ".db_table_name("answers").".sortorder, ".db_table_name("answers").".answer"; - $i2result = db_execute_assoc($i2query); - $otherexists = ""; - while ($i2row = $i2result->FetchRow()) - { - // first scale - $field = "{$fnrow['sid']}X{$fnrow['gid']}X{$fnrow['qid']}{$i2row['code']}#0"; - $ftitle = "Grp{$fnrow['gid']}Qst{$fnrow['title']}Opt{$i2row['code']}"; - if ($i2row['other'] == "Y") {$otherexists = "Y";} - $fnames[] = array("$field", "$ftitle", "{$fnrow['question']}
    \n[{$i2row['answer']}]
    [".$clang->gT("1. scale")."]", "{$fnrow['gid']}"); - // second scale - $field = "{$fnrow['sid']}X{$fnrow['gid']}X{$fnrow['qid']}{$i2row['code']}#1"; - $ftitle = "Grp{$fnrow['gid']}Qst{$fnrow['title']}Opt{$i2row['code']}"; - if ($i2row['other'] == "Y") {$otherexists = "Y";} - $fnames[] = array("$field", "$ftitle", "{$fnrow['question']}
    \n[{$i2row['answer']}]
    [".$clang->gT("2. scale")."]", "{$fnrow['gid']}"); - } - if ($otherexists == "Y") - { - $field = "{$fnrow['sid']}X{$fnrow['gid']}X{$fnrow['qid']}"."other"; - $ftitle = "Grp{$fnrow['gid']}Qst{$fnrow['title']}OptOther"; - $fnames[] = array("$field", "$ftitle", "{$fnrow['question']}
    \n[Other]", "{$fnrow['gid']}"); - } - } - - else - { - $fnames[] = array("$field", "$ftitle", "{$fnrow['question']}"); - if (($fnrow['type'] == "L" || $fnrow['type'] == "!" || $fnrow['type'] == "W" || $fnrow['type'] == "Z") && $fnrow['other'] == "Y") - { - $fnames[] = array("$field"."other", "$ftitle"."other", "{$fnrow['question']}(".$clang->gT("Other").")"); - } - } - } - $nfncount = count($fnames)-1; - //SHOW INDIVIDUAL RECORD - $idquery = "SELECT *, CASE WHEN submitdate IS NULL THEN 'N' ELSE 'Y' END as completed FROM $surveytable WHERE "; - if (incompleteAnsFilterstate() === true) {$idquery .= "submitdate >= ".$connect->DBDate('1980-01-01'). " AND ";} - if ($id<1) {$id=1;} - if (isset($_POST['sql']) && $_POST['sql']) - { - if (get_magic_quotes_gpc()) {$idquery .= stripslashes($_POST['sql']);} - else {$idquery .= "{$_POST['sql']}";} - } - else {$idquery .= "id=$id";} - $idresult = db_execute_assoc($idquery) or safe_die ("Couldn't get entry
    \n$idquery
    \n".$connect->ErrorMsg()); - while ($idrow = $idresult->FetchRow()) {$id=$idrow['id']; $rlangauge=$idrow['startlanguage'];} - $next=$id+1; - $last=$id-1; - $browseoutput .= "\n" - ."\t\n" - ."\t\t\n" - ."\t\n" - ."\t\n" - ."\t\n"; - $idresult = db_execute_assoc($idquery) or safe_die ("Couldn't get entry
    $idquery
    ".$connect->ErrorMsg()); - while ($idrow = $idresult->FetchRow()) - { - $i=0; - for ($i; $i<$nfncount+1; $i++) - { - $browseoutput .= "\t\n" - ."\t\t\n" - ."\t\t\n" - ."\t\n" - ."\t\n"; - } - } - $browseoutput .= "
    " - . $clang->gT("View Response").": $id
    \n" - ."\t\t\t\n" - ."\t\t\t\n"; - if (isset($rlangauge)) - { - $browseoutput .="\t\t\tgT("Edit this entry", "js")."')\">" . - "\n"; - } - if ($sumrows5['delete_survey']) - { -// $browseoutput .= "\t\t\tgT("Delete this entry", "js")."')\">" -// ."gT("Are you sure you want to delete this entry?","js")."')\" />\n"; - $browseoutput .= "\t\t\tgT("Delete this entry", "js")."')\">" - ."gT("Are you sure you want to delete this entry?","js")."')) {".get2post("$scriptname?action=dataentry&subaction=delete&id=$id&sid=$surveyid&surveytable=$surveytable")."}\" />\n"; - } - $browseoutput .= "\t\t\tgT("Export this Response", "js")."')\">" . - "". $clang->gT("Export this Response")."\n" - ."\t\t\t\n" - ."\t\t\t\n" - ."\t\t\tgT("Show previous...", "js")."')\">". - "\n" - ."\t\t\t\n" - ."\t\t\tgT("Show next...", "js")."')\">" . - "\n" - ."\t\t
    " - ."$setfont{$fnames[$i][2]}$setfont" - .htmlspecialchars(getextendedanswer($fnames[$i][0], $idrow[$fnames[$i][0]]), ENT_QUOTES) - ."
    \n" - ."\n" - ."\t\n" - ."\t\t\n" - ."\t\n" - ."
    \n"; -// if (isset($_POST['sql']) && $_POST['sql']) {$browseoutput .= "\t\t\t\n";} - $browseoutput .= "\t\t
    \n"; -} - -elseif ($subaction == "all") -{ - $browseoutput .= ("\t" - . $clang->gT("Browse Responses").": $surveyname\n"); - - if (!isset($_POST['sql'])) - {$browseoutput .= "$surveyoptions";} //don't show options when called from another script with a filter on - else - { - $browseoutput .= "\n\n" - ."\t\n" - ."\t\t\n" - ."\t\n" - ."
    \n" - ."\t\t\t".$clang->gT("Showing Filtered Results")."
    \n" - ."\t\t\t [".$clang->gT("Close")."]" - ."\t\t
    \n"; - - } - $browseoutput .= "\n"; - //FIRST LETS GET THE NAMES OF THE QUESTIONS AND MATCH THEM TO THE FIELD NAMES FOR THE DATABASE - $fnquery = "SELECT * FROM ".db_table_name("questions").", ".db_table_name("groups").", - ".db_table_name("surveys")." WHERE ".db_table_name("questions").".gid=".db_table_name("groups").".gid AND - ".db_table_name("questions").".language='{$language}' AND ".db_table_name("groups").".language='{$language}' AND - ".db_table_name("groups").".sid=".db_table_name("surveys").".sid AND ".db_table_name("questions").".sid='$surveyid' ORDER BY ".db_table_name("groups").".group_order"; - $fnresult = db_execute_assoc($fnquery); - $fncount = 0; - $fnrows = array(); //Create an empty array in case FetchRow does not return any rows - while ($fnrow = $fnresult->FetchRow()) - { - ++$fncount; - $fnrows[] = $fnrow; - $private = $fnrow['private']; - $datestamp=$fnrow['datestamp']; - $ipaddr=$fnrow['ipaddr']; - $refurl=$fnrow['refurl']; - } // Get table output into array - - // Perform a case insensitive natural sort on group name then question title of a multidimensional array - usort($fnrows, 'CompareGroupThenTitle'); - - if ($private == "N") //Add token to list - { - $fnames[] = array("token", $clang->gT("Token"), $clang->gT("Token ID"), "0"); - } - - $fnames[] = array("completed", "Completed", $clang->gT("Completed"), "0"); - - if ($datestamp == "Y") //Add datestamp - { - // submitdate for not-datestamped surveys is always 1980/01/01 - // so only display it when datestamped - $fnames[] = array("startdate", "startdate", $clang->gT("Date Started"), "0"); - $fnames[] = array("datestamp", "Datestamp", $clang->gT("Date Last Action"), "0"); - $fnames[] = array("submitdate", "submitdate", $clang->gT("Date Submitted"), "0"); - - - } - if ($ipaddr == "Y") // Add IP Address - { - $fnames[] = array("ipaddr", "IPAddress", $clang->gT("IP Address"), "0"); - } - if ($refurl == "Y") // refurl - { - $fnames[] = array("refurl", "refurl", $clang->gT("Referring URL"), "0"); - } - foreach ($fnrows as $fnrow) - { - if ($fnrow['type'] != "Q" && $fnrow['type'] != "M" && $fnrow['type'] != "A" && - $fnrow['type'] != "B" && $fnrow['type'] != "C" && $fnrow['type'] != "E" && - $fnrow['type'] != "F" && $fnrow['type'] != "H" && $fnrow['type'] != "P" && - $fnrow['type'] != "J" && $fnrow['type'] != "K" && $fnrow['type'] != "1" && - $fnrow['type'] != "O" && $fnrow['type'] != "R" && $fnrow['type'] != "^") - { - $field = "{$fnrow['sid']}X{$fnrow['gid']}X{$fnrow['qid']}"; - $ftitle = "Grp{$fnrow['gid']}Qst{$fnrow['title']}"; - $fquestion = $fnrow['question']; - $fnames[] = array("$field", "$ftitle", "$fquestion", "{$fnrow['gid']}"); - if (($fnrow['type'] == "L" || $fnrow['type'] == "!" || $fnrow['type'] == "W" || $fnrow['type'] == "Z") && $fnrow['other'] == "Y") - { - $fnames[] = array("$field"."other", "$ftitle"."other", "{$fnrow['question']}(".$clang->gT("Other").")", "{$fnrow['gid']}"); - } - - } - elseif ($fnrow['type'] == "O") - { - $field = "{$fnrow['sid']}X{$fnrow['gid']}X{$fnrow['qid']}"; - $ftitle = "Grp{$fnrow['gid']}Qst{$fnrow['title']}"; - $fquestion = $fnrow['question']; - $fnames[] = array("$field", "$ftitle", "$fquestion", "{$fnrow['gid']}"); - $field .= "comment"; - $ftitle .= "[comment]"; - $fquestion .= " (comment)"; - $fnames[] = array("$field", "$ftitle", "$fquestion", "{$fnrow['gid']}"); - } - elseif ($fnrow['type'] == "1") // multi scale - { - $i2query = "SELECT ".db_table_name("answers").".*, ".db_table_name("questions").".other FROM ".db_table_name("answers").", ".db_table_name("questions")." - WHERE ".db_table_name("answers").".qid=".db_table_name("questions").".qid AND - ".db_table_name("answers").".language='{$language}' AND ".db_table_name("questions").".language='{$language}' AND - ".db_table_name("questions").".qid={$fnrow['qid']} AND ".db_table_name("questions").".sid=$surveyid - ORDER BY ".db_table_name("answers").".sortorder, ".db_table_name("answers").".answer"; - $i2result = db_execute_assoc($i2query); - $otherexists = ""; - while ($i2row = $i2result->FetchRow()) - { - // first scale - $field = "{$fnrow['sid']}X{$fnrow['gid']}X{$fnrow['qid']}{$i2row['code']}#0"; - $ftitle = "Grp{$fnrow['gid']}Qst{$fnrow['title']}Opt{$i2row['code']}"; - if ($i2row['other'] == "Y") {$otherexists = "Y";} - $fnames[] = array("$field", "$ftitle", "{$fnrow['question']}
    \n[{$i2row['answer']}]
    [".$clang->gT("1. scale")."]", "{$fnrow['gid']}"); - // second scale - $field = "{$fnrow['sid']}X{$fnrow['gid']}X{$fnrow['qid']}{$i2row['code']}#1"; - $ftitle = "Grp{$fnrow['gid']}Qst{$fnrow['title']}Opt{$i2row['code']}"; - if ($i2row['other'] == "Y") {$otherexists = "Y";} - $fnames[] = array("$field", "$ftitle", "{$fnrow['question']}
    \n[{$i2row['answer']}]
    [".$clang->gT("2. scale")."]", "{$fnrow['gid']}"); - } - if ($otherexists == "Y") - { - $field = "{$fnrow['sid']}X{$fnrow['gid']}X{$fnrow['qid']}"."other"; - $ftitle = "Grp{$fnrow['gid']}Qst{$fnrow['title']}OptOther"; - $fnames[] = array("$field", "$ftitle", "{$fnrow['question']}
    \n[Other]", "{$fnrow['gid']}"); - if ($fnrow['type'] == "P") - { - $fnames[] = array("$field"."comment", "$ftitle"."Comment", "{$fnrow['question']}
    \n[Other]
    \n[Comment]", "{$fnrow['gid']}"); - } - } - } - elseif ($fnrow['type'] == "R") - { - $i2query = "SELECT ".db_table_name("answers").".*, ".db_table_name("questions").".other FROM - ".db_table_name("answers").", ".db_table_name("questions")." - WHERE ".db_table_name("answers").".qid=".db_table_name("questions").".qid AND - ".db_table_name("answers").".language='{$language}' AND ".db_table_name("questions").".language='{$language}' - AND ".db_table_name("questions").".qid={$fnrow['qid']} AND ".db_table_name("questions").".sid=$surveyid - ORDER BY ".db_table_name("answers").".sortorder, ".db_table_name("answers").".answer"; - $i2result = $connect->Execute($i2query); - $i2count = $i2result->RecordCount(); - for ($i=1; $i<=$i2count; $i++) - { - $field = "{$fnrow['sid']}X{$fnrow['gid']}X{$fnrow['qid']}$i"; - $ftitle = "Grp{$fnrow['qid']}Qst{$fnrow['title']}Opt$i"; - $fnames[] = array("$field", "$ftitle", "{$fnrow['question']}
    \n[$i]", "{$fnrow['gid']}"); - } - } - else - { - $i2query = "SELECT ".db_table_name("answers").".*, ".db_table_name("questions").".other FROM ".db_table_name("answers").", ".db_table_name("questions")." - WHERE ".db_table_name("answers").".qid=".db_table_name("questions").".qid AND - ".db_table_name("answers").".language='{$language}' AND ".db_table_name("questions").".language='{$language}' AND - ".db_table_name("questions").".qid={$fnrow['qid']} AND ".db_table_name("questions").".sid=$surveyid - ORDER BY ".db_table_name("answers").".sortorder, ".db_table_name("answers").".answer"; - $i2result = db_execute_assoc($i2query); - $otherexists = ""; - while ($i2row = $i2result->FetchRow()) - { - $field = "{$fnrow['sid']}X{$fnrow['gid']}X{$fnrow['qid']}{$i2row['code']}"; - $ftitle = "Grp{$fnrow['gid']}Qst{$fnrow['title']}Opt{$i2row['code']}"; - if ($i2row['other'] == "Y") {$otherexists = "Y";} - $fnames[] = array("$field", "$ftitle", "{$fnrow['question']}
    \n[{$i2row['answer']}]", "{$fnrow['gid']}"); - if ($fnrow['type'] == "P") {$fnames[] = array("$field"."comment", "$ftitle", "{$fnrow['question']}
    \n[{$i2row['answer']}]
    \n[Comment]", "{$fnrow['gid']}");} - } - if ($otherexists == "Y") - { - $field = "{$fnrow['sid']}X{$fnrow['gid']}X{$fnrow['qid']}"."other"; - $ftitle = "Grp{$fnrow['gid']}Qst{$fnrow['title']}OptOther"; - $fnames[] = array("$field", "$ftitle", "{$fnrow['question']}
    \n[Other]", "{$fnrow['gid']}"); - if ($fnrow['type'] == "P") - { - $fnames[] = array("$field"."comment", "$ftitle"."Comment", "{$fnrow['question']}
    \n[Other]
    \n[Comment]", "{$fnrow['gid']}"); - } - } - } - } - $fncount = count($fnames); - - //NOW LETS CREATE A TABLE WITH THOSE HEADINGS - if ($fncount < 10) {$cellwidth = "10%";} else {$cellwidth = "100";} - $tableheader = ""; - if ($fncount < 10) {$tableheader .= "\n";} - else {$fnwidth = (($fncount-1)*180); $tableheader .= "\n";} - $tableheader .= "\t\n" - . "\t\t\n"; - foreach ($fnames as $fn) - { - if (!isset($currentgroup)) {$currentgroup = $fn[3]; $gbc = "oddrow";} - if ($currentgroup != $fn[3]) - { - $currentgroup = $fn[3]; - if ($gbc == "oddrow") {$gbc = "evenrow";} - else {$gbc = "oddrow";} - } - $tableheader .= "\t\t\n"; - } - $tableheader .= "\t\n\n"; - - $start=returnglobal('start'); - $limit=returnglobal('limit'); - if (!isset($limit) || $limit== '') {$limit = 50;} - if (!isset($start) || $start =='') {$start = 0;} - - //LETS COUNT THE DATA - $dtquery = "SELECT count(*) FROM $surveytable"; - if (incompleteAnsFilterstate() === true) {$dtquery .= " WHERE submitdate is not null ";} - $dtresult=db_execute_num($dtquery); - while ($dtrow=$dtresult->FetchRow()) {$dtcount=$dtrow[0];} - - if ($limit > $dtcount) {$limit=$dtcount;} - - //NOW LETS SHOW THE DATA - if (isset($_POST['sql'])) - { - if ($_POST['sql'] == "NULL") - { - $dtquery = "SELECT *, CASE WHEN submitdate IS NULL THEN 'N' ELSE 'Y' END as completed FROM $surveytable "; - if (incompleteAnsFilterstate() === true) {$dtquery .= " WHERE submitdate is not null ";} - $dtquery .= " ORDER BY id"; - } - else - { - $dtquery = "SELECT *, CASE WHEN submitdate IS NULL THEN 'N' ELSE 'Y' END as completed FROM $surveytable WHERE "; - if (incompleteAnsFilterstate() === true) { - $dtquery .= " submitdate is not null "; - if (stripcslashes($_POST['sql']) !== "") { $dtquery .= " AND "; } - } - if (stripcslashes($_POST['sql']) !== "") { $dtquery .= stripcslashes($_POST['sql'])." "; } - $dtquery .= " ORDER BY id"; - } - } - else - { - $dtquery = "SELECT *, CASE WHEN submitdate IS NULL THEN 'N' ELSE 'Y' END as completed FROM $surveytable "; - if (incompleteAnsFilterstate() === true) {$dtquery .= " WHERE submitdate is not null ";} - $dtquery .= " ORDER BY id"; - } - if ($order == "desc") {$dtquery .= " DESC";} - - if (isset($limit)) - { - if (!isset($start)) {$start = 0;} - $dtresult = db_select_limit_assoc($dtquery, $limit, $start) or safe_die("Couldn't get surveys
    $dtquery
    ".$connect->ErrorMsg()); - } - else - { - $dtresult = db_execute_assoc($dtquery) or safe_die("Couldn't get surveys
    $dtquery
    ".$connect->ErrorMsg()); - } - $dtcount2 = $dtresult->RecordCount(); - $cells = $fncount+1; - - - //CONTROL MENUBAR - $last=$start-$limit; - $next=$start+$limit; - $end=$dtcount-$limit; - if ($end < 0) {$end=0;} - if ($last <0) {$last=0;} - if ($next >= $dtcount) {$next=$dtcount-$limit;} - if ($end < 0) {$end=0;} - - $browseoutput .= "
    id" - . strip_tags("$fn[2]") - . "
    \n" - ."\n" - ."\t\n"; - if (!isset($_POST['sql'])) - { - $browseoutput .= "\t\n" - ."\t\t\n" - ."\t\n" - ."\n" - ."
    \n"; - - $browseoutput .= $tableheader; - - while ($dtrow = $dtresult->FetchRow()) - { - if (!isset($bgcc)) {$bgcc="evenrow";} - else - { - if ($bgcc == "evenrow") {$bgcc = "oddrow";} - else {$bgcc = "evenrow";} - } - $browseoutput .= "\t\n" - ."\t\t\n" - ."\t\t\t" - ."{$dtrow['id']}\n"; - - $i = 0; - if ($private == "N") - { - $SQL = "Select * FROM ".db_table_name('tokens_'.$surveyid)." WHERE token=?"; - if ( db_tables_exist(db_table_name_nq('tokens_'.$surveyid)) && - $SQLResult = db_execute_assoc($SQL, $dtrow['token'])) - { - $TokenRow = $SQLResult->FetchRow(); - } - $browseoutput .= "\t\t\n"; - if (isset($TokenRow) && $TokenRow) - { - $browseoutput .= "\t\t"; - } - $browseoutput .= "{$dtrow['token']}"; - if (isset($TokenRow) && $TokenRow) - { - $browseoutput .= "\n"; - } - $i++; - } - - for ($i; $i<$fncount; $i++) - { - $browseoutput .= "\t\t" - . htmlspecialchars($dtrow[$fnames[$i][0]]) - ."\n"; - } - $browseoutput .= "\t\n"; - } - $browseoutput .= "\n
    \n"; -} -else -{ - $browseoutput .= "\t" - . $clang->gT("Browse Responses").": $surveyname\n" - . $surveyoptions; - $browseoutput .= "\n"; - $num_total_answers=0; - $num_completed_answers=0; - $gnquery = "SELECT count(id) FROM $surveytable"; - $gnquery2 = "SELECT count(id) FROM $surveytable WHERE submitdate is not null"; - $gnresult = db_execute_num($gnquery); - $gnresult2 = db_execute_num($gnquery2); - - while ($gnrow=$gnresult->FetchRow()) {$num_total_answers=$gnrow[0];} - while ($gnrow2=$gnresult2->FetchRow()) {$num_completed_answers=$gnrow2[0];} - $browseoutput .= "\n" - ."\t\n" - ."
    ".sprintf($clang->gT("%d responses for this survey"), $num_total_answers)." (" - .sprintf($clang->gT("%d full responses"), $num_completed_answers).", " - .sprintf($clang->gT("%d responses not completely filled out"), $num_total_answers-$num_completed_answers).")" - ."\t
    \n"; - -} - -?> +MetaTables() or safe_die ("Error getting tokens
    ".$connect->ErrorMsg()); +foreach ($tablelist as $tbl) +{ + if (db_quote_id($tbl) == db_table_name('survey_'.$surveyid)) $resultsexist = 1; +} + +if (!isset($resultsexist)) die("Your results table is missing!"); + +$sumquery5 = "SELECT b.* FROM {$dbprefix}surveys AS a INNER JOIN {$dbprefix}surveys_rights AS b ON a.sid = b.sid WHERE a.sid=$surveyid AND b.uid = ".$_SESSION['loginID']; //Getting rights for this survey and user +$sumresult5 = db_execute_assoc($sumquery5); +$sumrows5 = $sumresult5->FetchRow(); + +require_once(dirname(__FILE__).'/sessioncontrol.php'); + +// Set language for questions and labels to base language of this survey + +if (isset($browselang) && $browselang!='') +{ + $_SESSION['browselang']=$browselang; + $language=$_SESSION['browselang']; +} +elseif (isset($_SESSION['browselang'])) +{ + $language=$_SESSION['browselang']; +} +else +{ + $language = GetBaseLanguageFromSurveyID($surveyid); +} + +$surveyoptions = browsemenubar($clang->gT("Browse Responses")); +$browseoutput = "\n"; + +if (!$database_exists) //DATABASE DOESN'T EXIST OR CAN'T CONNECT +{ + $browseoutput .= "\t\n" + ."\t
    " + . $clang->gT("Browse Responses")."
    \n" + ."".$clang->gT("Error")."
    \n" + . $clang->gT("The defined LimeSurvey database does not exist")."
    \n" + . $clang->gT("Either your selected database has not yet been created or there is a problem accessing it.")."

    \n" + ."
    \n" + ."
    \n" + ."\n"; + return; +} +if (!$surveyid && !$subaction) //NO SID OR ACTION PROVIDED +{ + $browseoutput .= "\t" + . $clang->gT("Browse Responses")."\n" + ."\t\n" + ."".$clang->gT("Error")."
    \n" + . $clang->gT("You have not selected a survey to browse.")."

    \n" + ."
    \n" + ."\n"; + return; +} + +//CHECK IF SURVEY IS ACTIVATED AND EXISTS +$actquery = "SELECT * FROM ".db_table_name('surveys')." as a inner join ".db_table_name('surveys_languagesettings')." as b on (b.surveyls_survey_id=a.sid and b.surveyls_language=a.language) WHERE a.sid=$surveyid"; + +$actresult = db_execute_assoc($actquery); +$actcount = $actresult->RecordCount(); +if ($actcount > 0) +{ + while ($actrow = $actresult->FetchRow()) + { + $surveytable = db_table_name("survey_".$actrow['sid']); + /* + * DO NEVER EVER PUT VARIABLES AND FUNCTIONS WHICH GIVE BACK DIFFERENT QUOTES + * IN DOUBLE QUOTED(' and " and \" is used) JAVASCRIPT/HTML CODE!!! (except for: you know what you are doing) + * + * Used for deleting a record, fix quote bugs.. + */ + $surveytableNq = db_table_name_nq("survey_".$surveyid); + + $surveyname = "{$actrow['surveyls_title']}"; + if ($actrow['active'] == "N") //SURVEY IS NOT ACTIVE YET + { + $browseoutput .= "\t" + . $clang->gT("Browse Responses").": $surveyname\n" + ."\t\n" + ."".$clang->gT("Error")."
    \n" + . $clang->gT("This survey has not been activated. There are no results to browse.")."

    \n" + ."
    \n" + ."\n" + ."\n"; + return; + } + } +} +else //SURVEY MATCHING $surveyid DOESN'T EXIST +{ + $browseoutput .= "\t" + . $clang->gT("Browse Responses")."\n" + ."\t\n" + ."".$clang->gT("Error")."
    \n" + . $clang->gT("There is no matching survey.")." ($surveyid)

    \n" + ."
    \n" + ."\n" + ."\n"; + return; +} + +//OK. IF WE GOT THIS FAR, THEN THE SURVEY EXISTS AND IT IS ACTIVE, SO LETS GET TO WORK. +$qulanguage = GetBaseLanguageFromSurveyID($surveyid); +if ($subaction == "id") // Looking at a SINGLE entry +{ + $dateformatdetails=getDateFormatData($_SESSION['dateformat']); + //SHOW HEADER + if (!isset($_POST['sql']) || !$_POST['sql']) {$browseoutput .= ''.$surveyoptions;} // Don't show options if coming from tokens script + //FIRST LETS GET THE NAMES OF THE QUESTIONS AND MATCH THEM TO THE FIELD NAMES FOR THE DATABASE + $fnquery = "SELECT * FROM ".db_table_name("questions").", ".db_table_name("groups").", ".db_table_name("surveys")." + WHERE ".db_table_name("questions").".gid=".db_table_name("groups").".gid AND ".db_table_name("groups").".sid=".db_table_name("surveys").".sid + AND ".db_table_name("questions").".sid='$surveyid' AND + ".db_table_name("questions").".language='{$language}' AND ".db_table_name("groups").".language='{$language}' ORDER BY ".db_table_name("groups").".group_order, ".db_table_name("questions").".title"; + $fnresult = db_execute_assoc($fnquery); + $fncount = 0; + + $fnrows = array(); //Create an empty array in case fetch_array does not return any rows + while ($fnrow = $fnresult->FetchRow()) {++$fncount; $fnrows[] = $fnrow; $private = $fnrow['private']; $datestamp=$fnrow['datestamp']; $ipaddr=$fnrow['ipaddr']; $refurl=$fnrow['refurl'];} // Get table output into array + + // Perform a case insensitive natural sort on group name then question title of a multidimensional array + usort($fnrows, 'CompareGroupThenTitle'); + + $fnames[] = array("id", "id", "id"); + if ($private == "N") //add token to top ofl ist is survey is not private + { + $fnames[] = array("token", "token", $clang->gT("Token ID")); + } + + $fnames[] = array("completed", "Completed", $clang->gT("Completed"), "0"); + + if ($datestamp == "Y") //add datetime to list if survey is datestamped + { + // submitdate for not-datestamped surveys is always 1980/01/01 + // so only display it when datestamped + $fnames[] = array("startdate", "startdate", $clang->gT("Date Started")); + $fnames[] = array("datestamp", "datestamp", $clang->gT("Date Last Action")); + $fnames[] = array("submitdate", "submitdate", $clang->gT("Date Submitted")); + } + if ($ipaddr == "Y") //add ipaddr to list if survey should save submitters IP address + { + $fnames[] = array("ipaddr", "ipaddr", $clang->gT("IP Address")); + } + if ($refurl == "Y") //add refer_URL to list if survey should save referring URL + { + $fnames[] = array("refurl", "refurl", $clang->gT("Referring URL")); + } + foreach ($fnrows as $fnrow) + { + $field = "{$fnrow['sid']}X{$fnrow['gid']}X{$fnrow['qid']}"; + $ftitle = "Grp{$fnrow['gid']}Qst{$fnrow['title']}"; + $fquestion = $fnrow['question']; + if ($fnrow['type'] == "Q" || $fnrow['type'] == "M" || + $fnrow['type'] == "A" || $fnrow['type'] == "B" || + $fnrow['type'] == "C" || $fnrow['type'] == "E" || + $fnrow['type'] == "F" || $fnrow['type'] == "H" || + $fnrow['type'] == "J" || $fnrow['type'] == "K" || + $fnrow['type'] == "P" || $fnrow['type'] == "^") + { + $fnrquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid={$fnrow['qid']} AND language='{$language}' ORDER BY sortorder, answer"; + $fnrresult = db_execute_assoc($fnrquery); + while ($fnrrow = $fnrresult->FetchRow()) + { + $fnames[] = array("$field{$fnrrow['code']}", "$ftitle ({$fnrrow['code']})", "{$fnrow['question']} ({$fnrrow['answer']})"); + if ($fnrow['type'] == "P") {$fnames[] = array("$field{$fnrrow['code']}"."comment", "$ftitle"."comment", "{$fnrow['question']} (".$clang->gT("Comment").")");} + } + if ($fnrow['other'] == "Y" and ($fnrow['type']=="!" or $fnrow['type']=="L" or $fnrow['type']=="M" or $fnrow['type']=="P" || $fnrow['type'] == "Z" || $fnrow['type'] == "W")) + { + $fnames[] = array("$field"."other", "$ftitle"."other", "{$fnrow['question']}(".$clang->gT("Other").")"); + if ($fnrow['type'] == "P") {$fnames[] = array("$field{$fnrrow['code']}"."othercomment", "$ftitle"."othercomment", "{$fnrow['question']} (".$clang->gT("Other Comment").")");} + } + } + elseif ($fnrow['type'] == ":" || $fnrow['type'] == ";") + { + $lset=array(); + $fnrquery = "SELECT * + FROM ".db_table_name('answers')." + WHERE qid={$fnrow['qid']} + AND language='{$language}' + ORDER BY sortorder, answer"; + $fnrresult = db_execute_assoc($fnrquery); + $fnr2query = "SELECT * + FROM ".db_table_name('labels')." + WHERE lid={$fnrow['lid']} + AND language = '{$language}' + ORDER BY sortorder, title"; + $fnr2result = db_execute_assoc($fnr2query); + while( $fnr2row = $fnr2result->FetchRow()) + { + $lset[]=$fnr2row; + } + while ($fnrrow = $fnrresult->FetchRow()) + { + foreach($lset as $ls) + { + $fnames[] = array("$field{$fnrrow['code']}_{$ls['code']}", "$ftitle ({$fnrrow['code']})", "{$fnrow['question']} ({$fnrrow['answer']}: {$ls['title']})"); + } + } + } + elseif ($fnrow['type'] == "R") + { + $fnrquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid={$fnrow['qid']} AND + language='{$language}' + ORDER BY sortorder, answer"; + $fnrresult = $connect->Execute($fnrquery); + $fnrcount = $fnrresult->RecordCount(); + for ($i=1; $i<=$fnrcount; $i++) + { + $fnames[] = array("$field$i", "$ftitle ($i)", "{$fnrow['question']} ($i)"); + } + } + elseif ($fnrow['type'] == "O") + { + $fnames[] = array("$field", "$ftitle", "{$fnrow['question']}"); + $field2 = $field."comment"; + $ftitle2 = $ftitle."[Comment]"; + $longtitle = "{$fnrow['question']}
    [Comment]"; + $fnames[] = array("$field2", "$ftitle2", "$longtitle"); + } + elseif ($fnrow['type'] == "1") // multi scale + { + $i2query = "SELECT ".db_table_name("answers").".*, ".db_table_name("questions").".other FROM ".db_table_name("answers").", ".db_table_name("questions")." + WHERE ".db_table_name("answers").".qid=".db_table_name("questions").".qid AND + ".db_table_name("answers").".language='{$language}' AND ".db_table_name("questions").".language='{$language}' AND + ".db_table_name("questions").".qid={$fnrow['qid']} AND ".db_table_name("questions").".sid=$surveyid + ORDER BY ".db_table_name("answers").".sortorder, ".db_table_name("answers").".answer"; + $i2result = db_execute_assoc($i2query); + $otherexists = ""; + while ($i2row = $i2result->FetchRow()) + { + // first scale + $field = "{$fnrow['sid']}X{$fnrow['gid']}X{$fnrow['qid']}{$i2row['code']}#0"; + $ftitle = "Grp{$fnrow['gid']}Qst{$fnrow['title']}Opt{$i2row['code']}"; + if ($i2row['other'] == "Y") {$otherexists = "Y";} + $fnames[] = array("$field", "$ftitle", "{$fnrow['question']}
    \n[{$i2row['answer']}]
    [".$clang->gT("1. scale")."]", "{$fnrow['gid']}"); + // second scale + $field = "{$fnrow['sid']}X{$fnrow['gid']}X{$fnrow['qid']}{$i2row['code']}#1"; + $ftitle = "Grp{$fnrow['gid']}Qst{$fnrow['title']}Opt{$i2row['code']}"; + if ($i2row['other'] == "Y") {$otherexists = "Y";} + $fnames[] = array("$field", "$ftitle", "{$fnrow['question']}
    \n[{$i2row['answer']}]
    [".$clang->gT("2. scale")."]", "{$fnrow['gid']}"); + } + if ($otherexists == "Y") + { + $field = "{$fnrow['sid']}X{$fnrow['gid']}X{$fnrow['qid']}"."other"; + $ftitle = "Grp{$fnrow['gid']}Qst{$fnrow['title']}OptOther"; + $fnames[] = array("$field", "$ftitle", "{$fnrow['question']}
    \n[Other]", "{$fnrow['gid']}"); + } + } + + else + { + $fnames[] = array("$field", "$ftitle", "{$fnrow['question']}"); + if (($fnrow['type'] == "L" || $fnrow['type'] == "!" || $fnrow['type'] == "W" || $fnrow['type'] == "Z") && $fnrow['other'] == "Y") + { + $fnames[] = array("$field"."other", "$ftitle"."other", "{$fnrow['question']}(".$clang->gT("Other").")"); + } + } + } + $nfncount = count($fnames)-1; + //SHOW INDIVIDUAL RECORD + $idquery = "SELECT *, CASE WHEN submitdate IS NULL THEN 'N' ELSE 'Y' END as completed FROM $surveytable WHERE "; + if (incompleteAnsFilterstate() == "inc") {$idquery .= "(submitdate = ".$connect->DBDate('1980-01-01'). " OR submitdate IS NULL) AND ";} + elseif (incompleteAnsFilterstate() == "filter") {$idquery .= "submitdate >= ".$connect->DBDate('1980-01-01'). " AND ";} + if ($id<1) {$id=1;} + if (isset($_POST['sql']) && $_POST['sql']) + { + if (get_magic_quotes_gpc()) {$idquery .= stripslashes($_POST['sql']);} + else {$idquery .= "{$_POST['sql']}";} + } + else {$idquery .= "id=$id";} + $idresult = db_execute_assoc($idquery) or safe_die ("Couldn't get entry
    \n$idquery
    \n".$connect->ErrorMsg()); + while ($idrow = $idresult->FetchRow()) {$id=$idrow['id']; $rlangauge=$idrow['startlanguage'];} + $next=$id+1; + $last=$id-1; + $browseoutput .= "\n"; + + $browseoutput .= "\n"; + $idresult = db_execute_assoc($idquery) or safe_die ("Couldn't get entry
    $idquery
    ".$connect->ErrorMsg()); + while ($idrow = $idresult->FetchRow()) + { + $i=0; + for ($i; $i<$nfncount+1; $i++) + { + $browseoutput .= "\t\n" + ."\t\t\n" + ."\t\t\n" + ."\t\n"; + } + } + $browseoutput .= "
    " + .strip_tags(strip_javascript($fnames[$i][2]))."" + .htmlspecialchars(strip_tags(strip_javascript(getextendedanswer($fnames[$i][0], $idrow[$fnames[$i][0]], '', $dateformatdetails['phpdate']))), ENT_QUOTES) + ."
    \n"; + +} + +elseif ($subaction == "all") +{ + + if (!isset($_POST['sql'])) + {$browseoutput .= ''.$surveyoptions;} //don't show options when called from another script with a filter on + else + { + $browseoutput .= "\t".$clang->gT("Browse Responses").": $surveyname\n" + ."\n\n" + ."\t\n" + ."\t\t\n" + ."\t\n" + ."
    \n" + ."\t\t\t".$clang->gT("Showing Filtered Results")."
    \n" + ."\t\t\t [".$clang->gT("Close")."]" + ."\t\t
    \n"; + + } + $browseoutput .= "\n"; + //FIRST LETS GET THE NAMES OF THE QUESTIONS AND MATCH THEM TO THE FIELD NAMES FOR THE DATABASE + $fnquery = "SELECT * FROM ".db_table_name("questions").", ".db_table_name("groups").", + ".db_table_name("surveys")." WHERE ".db_table_name("questions").".gid=".db_table_name("groups").".gid AND + ".db_table_name("questions").".language='{$language}' AND ".db_table_name("groups").".language='{$language}' AND + ".db_table_name("groups").".sid=".db_table_name("surveys").".sid AND ".db_table_name("questions").".sid='$surveyid' ORDER BY ".db_table_name("groups").".group_order"; + $fnresult = db_execute_assoc($fnquery); + $fncount = 0; + $fnrows = array(); //Create an empty array in case FetchRow does not return any rows + while ($fnrow = $fnresult->FetchRow()) + { + ++$fncount; + $fnrows[] = $fnrow; + $private = $fnrow['private']; + $datestamp=$fnrow['datestamp']; + $ipaddr=$fnrow['ipaddr']; + $refurl=$fnrow['refurl']; + } // Get table output into array + + // Perform a case insensitive natural sort on group name then question title of a multidimensional array + usort($fnrows, 'CompareGroupThenTitle'); + + if ($private == "N") //Add token to list + { + $fnames[] = array("token", $clang->gT("Token"), $clang->gT("Token ID"), "0", ''); + } + + $fnames[] = array("completed", "Completed", $clang->gT("Completed"), "0", 'D'); + + if ($datestamp == "Y") //Add datestamp + { + // submitdate for not-datestamped surveys is always 1980/01/01 + // so only display it when datestamped + $fnames[] = array("startdate", "startdate", $clang->gT("Date Started"), "0", 'D'); + $fnames[] = array("datestamp", "Datestamp", $clang->gT("Date Last Action"), "0", 'D'); + $fnames[] = array("submitdate", "submitdate", $clang->gT("Date Submitted"), "0", 'D'); + + + } + if ($ipaddr == "Y") // Add IP Address + { + $fnames[] = array("ipaddr", "IPAddress", $clang->gT("IP Address"), "0",''); + } + if ($refurl == "Y") // refurl + { + $fnames[] = array("refurl", "refurl", $clang->gT("Referring URL"), "0",''); + } + foreach ($fnrows as $fnrow) + { + if ($fnrow['type'] != "Q" && $fnrow['type'] != "M" && $fnrow['type'] != "A" && + $fnrow['type'] != "B" && $fnrow['type'] != "C" && $fnrow['type'] != "E" && + $fnrow['type'] != "F" && $fnrow['type'] != "H" && $fnrow['type'] != "P" && + $fnrow['type'] != "J" && $fnrow['type'] != "K" && $fnrow['type'] != "1" && + $fnrow['type'] != "O" && $fnrow['type'] != "R" && $fnrow['type'] != "^" && + $fnrow['type'] != ":" && $fnrow['type'] != ";") + { + $field = "{$fnrow['sid']}X{$fnrow['gid']}X{$fnrow['qid']}"; + $ftitle = "Grp{$fnrow['gid']}Qst{$fnrow['title']}"; + $fquestion = $fnrow['question']; + + $fnames[] = array("$field", "$ftitle", "$fquestion", $fnrow['gid'], $fnrow['type']); + if (($fnrow['type'] == "L" || $fnrow['type'] == "!" || $fnrow['type'] == "W" || $fnrow['type'] == "Z") && $fnrow['other'] == "Y") + { + $fnames[] = array("$field"."other", "$ftitle"."other", "{$fnrow['question']}(".$clang->gT("Other").")", $fnrow['gid'], $fnrow['type']); + } + + } + elseif ($fnrow['type'] == "O") + { + $field = "{$fnrow['sid']}X{$fnrow['gid']}X{$fnrow['qid']}"; + $ftitle = "Grp{$fnrow['gid']}Qst{$fnrow['title']}"; + $fquestion = $fnrow['question']; + $fnames[] = array("$field", "$ftitle", "$fquestion", $fnrow['gid'], $fnrow['type']); + $field .= "comment"; + $ftitle .= "[comment]"; + $fquestion .= " (comment)"; + $fnames[] = array("$field", "$ftitle", "$fquestion", $fnrow['gid'], $fnrow['type']); + } + elseif ($fnrow['type'] == "1") // multi scale + { + $i2query = "SELECT ".db_table_name("answers").".*, ".db_table_name("questions").".other FROM ".db_table_name("answers").", ".db_table_name("questions")." + WHERE ".db_table_name("answers").".qid=".db_table_name("questions").".qid AND + ".db_table_name("answers").".language='{$language}' AND ".db_table_name("questions").".language='{$language}' AND + ".db_table_name("questions").".qid={$fnrow['qid']} AND ".db_table_name("questions").".sid=$surveyid + ORDER BY ".db_table_name("answers").".sortorder, ".db_table_name("answers").".answer"; + $i2result = db_execute_assoc($i2query); + $otherexists = ""; + while ($i2row = $i2result->FetchRow()) + { + // first scale + $field = "{$fnrow['sid']}X{$fnrow['gid']}X{$fnrow['qid']}{$i2row['code']}#0"; + $ftitle = "Grp{$fnrow['gid']}Qst{$fnrow['title']}Opt{$i2row['code']}"; + if ($i2row['other'] == "Y") {$otherexists = "Y";} + $fnames[] = array("$field", "$ftitle", "{$fnrow['question']}
    \n[{$i2row['answer']}]
    [".$clang->gT("1. scale")."]", $fnrow['gid'], $fnrow['type']); + // second scale + $field = "{$fnrow['sid']}X{$fnrow['gid']}X{$fnrow['qid']}{$i2row['code']}#1"; + $ftitle = "Grp{$fnrow['gid']}Qst{$fnrow['title']}Opt{$i2row['code']}"; + if ($i2row['other'] == "Y") {$otherexists = "Y";} + $fnames[] = array("$field", "$ftitle", "{$fnrow['question']}
    \n[{$i2row['answer']}]
    [".$clang->gT("2. scale")."]", $fnrow['gid'], $fnrow['type']); + } + if ($otherexists == "Y") + { + $field = "{$fnrow['sid']}X{$fnrow['gid']}X{$fnrow['qid']}"."other"; + $ftitle = "Grp{$fnrow['gid']}Qst{$fnrow['title']}OptOther"; + $fnames[] = array("$field", "$ftitle", "{$fnrow['question']}
    \n[Other]", $fnrow['gid'], $fnrow['type']); + if ($fnrow['type'] == "P") + { + $fnames[] = array("$field"."comment", "$ftitle"."Comment", "{$fnrow['question']}
    \n[Other]
    \n[Comment]", $fnrow['gid'], $fnrow['type']); + } + } + } + elseif ($fnrow['type'] == "R") + { + $i2query = "SELECT ".db_table_name("answers").".*, ".db_table_name("questions").".other FROM + ".db_table_name("answers").", ".db_table_name("questions")." + WHERE ".db_table_name("answers").".qid=".db_table_name("questions").".qid AND + ".db_table_name("answers").".language='{$language}' AND ".db_table_name("questions").".language='{$language}' + AND ".db_table_name("questions").".qid={$fnrow['qid']} AND ".db_table_name("questions").".sid=$surveyid + ORDER BY ".db_table_name("answers").".sortorder, ".db_table_name("answers").".answer"; + $i2result = $connect->Execute($i2query); + $i2count = $i2result->RecordCount(); + for ($i=1; $i<=$i2count; $i++) + { + $field = "{$fnrow['sid']}X{$fnrow['gid']}X{$fnrow['qid']}$i"; + $ftitle = "Grp{$fnrow['qid']}Qst{$fnrow['title']}Opt$i"; + $fnames[] = array("$field", "$ftitle", "{$fnrow['question']}
    \n[$i]", $fnrow['gid'], $fnrow['type']); + } + } + elseif ($fnrow['type'] == ":" || $fnrow['type'] == ";") + { + $lset=array(); + $i2query = "SELECT ".db_table_name("answers").".*, ".db_table_name("questions").".other FROM ".db_table_name("answers").", ".db_table_name("questions")." + WHERE ".db_table_name("answers").".qid=".db_table_name("questions").".qid AND + ".db_table_name("answers").".language='{$language}' AND ".db_table_name("questions").".language='{$language}' AND + ".db_table_name("questions").".qid={$fnrow['qid']} AND ".db_table_name("questions").".sid=$surveyid + ORDER BY ".db_table_name("answers").".sortorder, ".db_table_name("answers").".answer"; + $i2result = db_execute_assoc($i2query); + $ab2query = "SELECT ".db_table_name('labels').".* + FROM ".db_table_name('questions').", ".db_table_name('labels')." + WHERE sid=$surveyid + AND ".db_table_name('labels').".lid=".db_table_name('questions').".lid + AND ".db_table_name('questions').".language='".$language."' + AND ".db_table_name('labels').".language='".$language."' + AND ".db_table_name('questions').".qid=".$fnrow['qid']." + ORDER BY ".db_table_name('labels').".sortorder, ".db_table_name('labels').".title"; + $ab2result=db_execute_assoc($ab2query) or die("Couldn't get list of labels in createFieldMap function (case :)
    $ab2query
    ".htmlspecialchars($connection->ErrorMsg())); + while($ab2row=$ab2result->FetchRow()) + { + $lset[]=$ab2row; + } + while ($i2row = $i2result->FetchRow()) + { + foreach($lset as $ls) + { + $field = "{$fnrow['sid']}X{$fnrow['gid']}X{$fnrow['qid']}{$i2row['code']}_{$ls['code']}"; + $ftitle = "Grp{$fnrow['gid']}Qst{$fnrow['title']}Item{$i2row['code']}Label{$ls['code']}"; + $fnames[]=array($field, $ftitle, "{$fnrow['question']}
    \n[{$i2row['answer']}]
    [{$ls['title']}]", $fnrow['qid'], $fnrow['type']); + } + } + } + else + { + $i2query = "SELECT ".db_table_name("answers").".*, ".db_table_name("questions").".other FROM ".db_table_name("answers").", ".db_table_name("questions")." + WHERE ".db_table_name("answers").".qid=".db_table_name("questions").".qid AND + ".db_table_name("answers").".language='{$language}' AND ".db_table_name("questions").".language='{$language}' AND + ".db_table_name("questions").".qid={$fnrow['qid']} AND ".db_table_name("questions").".sid=$surveyid + ORDER BY ".db_table_name("answers").".sortorder, ".db_table_name("answers").".answer"; + $i2result = db_execute_assoc($i2query); + $otherexists = ""; + while ($i2row = $i2result->FetchRow()) + { + $field = "{$fnrow['sid']}X{$fnrow['gid']}X{$fnrow['qid']}{$i2row['code']}"; + $ftitle = "Grp{$fnrow['gid']}Qst{$fnrow['title']}Opt{$i2row['code']}"; + if ($i2row['other'] == "Y") {$otherexists = "Y";} + $fnames[] = array("$field", "$ftitle", "{$fnrow['question']}
    \n[{$i2row['answer']}]", $fnrow['gid'], $fnrow['type']); + if ($fnrow['type'] == "P") {$fnames[] = array("$field"."comment", "$ftitle", "{$fnrow['question']}
    \n[{$i2row['answer']}]
    \n[Comment]", $fnrow['gid'], $fnrow['type']);} + } + if ($otherexists == "Y") + { + $field = "{$fnrow['sid']}X{$fnrow['gid']}X{$fnrow['qid']}"."other"; + $ftitle = "Grp{$fnrow['gid']}Qst{$fnrow['title']}OptOther"; + $fnames[] = array("$field", "$ftitle", "{$fnrow['question']}
    \n[Other]", $fnrow['gid'], $fnrow['type']); + if ($fnrow['type'] == "P") + { + $fnames[] = array("$field"."comment", "$ftitle"."Comment", "{$fnrow['question']}
    \n[Other]
    \n[Comment]", $fnrow['gid'], $fnrow['type']); + } + } + } + } + $fncount = count($fnames); + + //NOW LETS CREATE A TABLE WITH THOSE HEADINGS + if ($fncount < 10) {$cellwidth = "10%";} else {$cellwidth = "100";} + $tableheader = ""; + if ($fncount < 10) {$tableheader .= "\n";} + else {$tableheader .= "
    \n";} + $tableheader .= "\t\n" + . "\t\t\n"; + foreach ($fnames as $fn) + { + if (!isset($currentgroup)) {$currentgroup = $fn[3]; $gbc = "oddrow";} + if ($currentgroup != $fn[3]) + { + $currentgroup = $fn[3]; + if ($gbc == "oddrow") {$gbc = "evenrow";} + else {$gbc = "oddrow";} + } + $tableheader .= "\t\t\n"; + } + $tableheader .= "\t\n\n"; + + $start=returnglobal('start'); + $limit=returnglobal('limit'); + if (!isset($limit) || $limit== '') {$limit = 50;} + if (!isset($start) || $start =='') {$start = 0;} + + //LETS COUNT THE DATA + $dtquery = "SELECT count(*) FROM $surveytable"; + if (incompleteAnsFilterstate() == "inc") {$dtquery .= "WHERE submitdate IS NULL ";} + elseif (incompleteAnsFilterstate() == "filter") {$dtquery .= " WHERE submitdate is not null ";} + $dtresult=db_execute_num($dtquery); + while ($dtrow=$dtresult->FetchRow()) {$dtcount=$dtrow[0];} + + if ($limit > $dtcount) {$limit=$dtcount;} + + //NOW LETS SHOW THE DATA + if (isset($_POST['sql'])) + { + if ($_POST['sql'] == "NULL") + { + $dtquery = "SELECT *, CASE WHEN submitdate IS NULL THEN 'N' ELSE 'Y' END as completed FROM $surveytable "; + if (incompleteAnsFilterstate() == "inc") {$dtquery .= "WHERE submitdate is null";} + elseif (incompleteAnsFilterstate() == "filter") {$dtquery .= " WHERE submitdate is not null ";} + $dtquery .= " ORDER BY id"; + } + else + { + $dtquery = "SELECT *, CASE WHEN submitdate IS NULL THEN 'N' ELSE 'Y' END as completed FROM $surveytable WHERE "; + if (incompleteAnsFilterstate() == "inc") { + $dtquery .= "submitdate is null "; + if (stripcslashes($_POST['sql']) !== "") { $dtquery .= " AND "; } + } + elseif (incompleteAnsFilterstate() == "filter") { + $dtquery .= " submitdate is not null "; + if (stripcslashes($_POST['sql']) !== "") { $dtquery .= " AND "; } + } + if (stripcslashes($_POST['sql']) !== "") { $dtquery .= stripcslashes($_POST['sql'])." "; } + $dtquery .= " ORDER BY id"; + } + } + else + { + $dtquery = "SELECT *, CASE WHEN submitdate IS NULL THEN 'N' ELSE 'Y' END as completed FROM $surveytable "; + if (incompleteAnsFilterstate() == "inc") {$dtquery .= " WHERE submitdate is null ";} + elseif (incompleteAnsFilterstate() == "filter") {$dtquery .= " WHERE submitdate is not null ";} + $dtquery .= " ORDER BY id"; + } + if ($order == "desc") {$dtquery .= " DESC";} + + if (isset($limit)) + { + if (!isset($start)) {$start = 0;} + $dtresult = db_select_limit_assoc($dtquery, $limit, $start) or safe_die("Couldn't get surveys
    $dtquery
    ".$connect->ErrorMsg()); + } + else + { + $dtresult = db_execute_assoc($dtquery) or safe_die("Couldn't get surveys
    $dtquery
    ".$connect->ErrorMsg()); + } + $dtcount2 = $dtresult->RecordCount(); + $cells = $fncount+1; + + + //CONTROL MENUBAR + $last=$start-$limit; + $next=$start+$limit; + $end=$dtcount-$limit; + if ($end < 0) {$end=0;} + if ($last <0) {$last=0;} + if ($next >= $dtcount) {$next=$dtcount-$limit;} + if ($end < 0) {$end=0;} + + $browseoutput .= "
    id" + . strip_tags(strip_javascript("$fn[2]")) + . "
    \n" + ."\n" + ."\t\n"; + if (!isset($_POST['sql'])) + { + $browseoutput .= "\t\n" + ."\t\t\n" + ."\t\n" + ."\n" + ."
    \n"; + + $browseoutput .= $tableheader; + $dateformatdetails=getDateFormatData($_SESSION['dateformat']); + + while ($dtrow = $dtresult->FetchRow()) + { + if (!isset($bgcc)) {$bgcc="evenrow";} + else + { + if ($bgcc == "evenrow") {$bgcc = "oddrow";} + else {$bgcc = "evenrow";} + } + $browseoutput .= "\t\n" + ."\t\t\n" + ."\t\t\t" + ."{$dtrow['id']}\n"; + + $i = 0; + if ($private == "N" && $dtrow['token']) + { + $SQL = "Select * FROM ".db_table_name('tokens_'.$surveyid)." WHERE token=?"; + if ( db_tables_exist(db_table_name_nq('tokens_'.$surveyid)) && + $SQLResult = db_execute_assoc($SQL, $dtrow['token'])) + { + $TokenRow = $SQLResult->FetchRow(); + } + $browseoutput .= "\t\t\n"; + if (isset($TokenRow) && $TokenRow) + { + $browseoutput .= "\t\t"; + } + $browseoutput .= "{$dtrow['token']}"; + if (isset($TokenRow) && $TokenRow) + { + $browseoutput .= "\n"; + } + $i++; + } + + for ($i; $i<$fncount; $i++) + { + $browsedatafield=htmlspecialchars($dtrow[$fnames[$i][0]]); + if ($fnames[$i][4]=='D' && $dtrow[$fnames[$i][0]]!='N' && $dtrow[$fnames[$i][0]]!='Y' && $dtrow[$fnames[$i][0]]!='') + { + $datetimeobj = new Date_Time_Converter($dtrow[$fnames[$i][0]] , "Y-m-d H:i:s"); + $browsedatafield=$datetimeobj->convert($dateformatdetails['phpdate'].' H:i'); + } + if (trim($browsedatafield=='')) $browsedatafield=' '; + $browseoutput .= "\t\t$browsedatafield\n"; + } + $browseoutput .= "\t\n"; + } + $browseoutput .= "\n
    \n"; +} +else +{ + $browseoutput .= ''.$surveyoptions; + $num_total_answers=0; + $num_completed_answers=0; + $gnquery = "SELECT count(id) FROM $surveytable"; + $gnquery2 = "SELECT count(id) FROM $surveytable WHERE submitdate is not null"; + $gnresult = db_execute_num($gnquery); + $gnresult2 = db_execute_num($gnquery2); + + while ($gnrow=$gnresult->FetchRow()) {$num_total_answers=$gnrow[0];} + while ($gnrow2=$gnresult2->FetchRow()) {$num_completed_answers=$gnrow2[0];} + $browseoutput .= "\n" + ."\t\n" + ."
    ".sprintf($clang->gT("%d responses for this survey"), $num_total_answers)." (" + .sprintf($clang->gT("%d full responses"), $num_completed_answers).", " + .sprintf($clang->gT("%d responses not completely filled out"), $num_total_answers-$num_completed_answers).")" + ."\t
    \n"; + +} + +?> diff --git a/include/limesurvey/admin/classes/core/domxml-php4-to-php5.php b/include/limesurvey/admin/classes/core/domxml-php4-to-php5.php index cf2147ab..1fdebc31 100644 --- a/include/limesurvey/admin/classes/core/domxml-php4-to-php5.php +++ b/include/limesurvey/admin/classes/core/domxml-php4-to-php5.php @@ -30,7 +30,7 @@ If you want to distribute this code, please do it as a link to: http://alexandre.alapetite.net/doc-alex/domxml-php4-php5/ */ - +@ini_set('zend.ze1_compatibility_mode', '0'); define('DOMXML_LOAD_PARSING',0); define('DOMXML_LOAD_VALIDATING',1); define('DOMXML_LOAD_RECOVERING',2); @@ -79,7 +79,7 @@ function xmldocfile($filename) {return domxml_open_file($filename);} function xpath_eval($xpath_context,$eval_str,$contextnode=null) {return $xpath_context->xpath_eval($eval_str,$contextnode);} function xpath_new_context($dom_document) {return new php4DOMXPath($dom_document);} function xpath_register_ns($xpath_context,$prefix,$namespaceURI) {return $xpath_context->myDOMXPath->registerNamespace($prefix,$namespaceURI);} -function _entityDecode($text) {return html_entity_decode_php4(strtr($text,array('''=>'\'')),ENT_QUOTES,'UTF-8');} +function _entityDecode($text) {return html_entity_decode(strtr($text,array('''=>'\'')),ENT_QUOTES,'UTF-8');} function _error_report($error) {return array('errormessage'=>$error->message,'nodename'=>'','line'=>$error->line,'col'=>$error->column)+($error->file==''?array():array('directory'=>dirname($error->file),'file'=>basename($error->file)));} class php4DOMAttr extends php4DOMNode diff --git a/include/limesurvey/admin/classes/core/sha256.php b/include/limesurvey/admin/classes/core/sha256.php index c1e4e770..5ac165f2 100644 --- a/include/limesurvey/admin/classes/core/sha256.php +++ b/include/limesurvey/admin/classes/core/sha256.php @@ -3,7 +3,7 @@ /******************************************************************************* * - * SHA256 static class for PHP4 + * SHA256 static class for PHP * implemented by feyd _at_ devnetwork .dot. net * specification from http://csrc.nist.gov/cryptval/shs/sha256-384-512.pdf * @@ -15,10 +15,10 @@ *----- Version 1.0.1 ---------------------------------------------------------- * * Syntax: - * string SHA256::hash( string message[, string format ]) + * string SHA256::hashing( string message[, string format ]) * * Description: - * SHA256::hash() is a static function that must be called with `message` + * SHA256::hashing() is a static function that must be called with `message` * and optionally `format`. Possible values for `format` are: * 'bin' binary string output * 'hex' default; hexidecimal string output (lower case) @@ -26,7 +26,7 @@ * Failures return FALSE. * * Usage: - * $hash = SHA256::hash('string to hash'); + * $hash = SHA256::hashing('string to hash'); * ******************************************************************************/ @@ -136,7 +136,7 @@ class SHA256Data extends hashData // static class. Access via SHA256::hash() class SHA256 extends hash { - function hash($str, $mode = 'hex') + static function hashing($str, $mode = 'hex') { static $modes = array( 'hex', 'bin', 'bit' ); $ret = false; @@ -147,7 +147,7 @@ class SHA256 extends hash } else { - $data =& new SHA256Data($str); + $data = new SHA256Data($str); SHA256::compute($data); @@ -171,7 +171,7 @@ class SHA256 extends hash // begin internal functions // 32-bit summation - function sum() + static function sum() { $T = 0; for($x = 0, $y = func_num_args(); $x < $y; $x++) @@ -202,7 +202,7 @@ class SHA256 extends hash // compute the hash - function compute(&$hashData) + static function compute(&$hashData) { static $vars = 'abcdefgh'; static $K = null; @@ -292,7 +292,7 @@ class SHA256 extends hash // set up the display of the hash in hex. - function hashHex(&$hashData) + static function hashHex(&$hashData) { $str = ''; @@ -385,7 +385,7 @@ function test1() echo 'Testing ' . var_export($str,true) . "\n"; list($s1,$s2) = explode(' ', microtime()); for($x = 0; $x < $it; $x++) - $data =& new SHA256Data($str); + $data = new SHA256Data($str); list($e1,$e2) = explode(' ', microtime()); echo hexerize($data->chunks); echo hexerize($data->hash); diff --git a/include/limesurvey/admin/classes/pear/OLE/OLE.php b/include/limesurvey/admin/classes/pear/OLE/OLE.php index bc6c2a22..0fd1cd55 100644 --- a/include/limesurvey/admin/classes/pear/OLE/OLE.php +++ b/include/limesurvey/admin/classes/pear/OLE/OLE.php @@ -305,7 +305,7 @@ class OLE extends PEAR * @param string $ascii The ASCII string to transform * @return string The string in Unicode */ - function Asc2Ucs($ascii) + static function Asc2Ucs($ascii) { $rawname = ''; for ($i = 0; $i < strlen($ascii); $i++) { @@ -323,7 +323,7 @@ class OLE extends PEAR * @param integer $date A timestamp * @return string The string for the OLE container */ - function LocalDate2OLE($date = null) + static function LocalDate2OLE($date = null) { if (!isset($date)) { return "\x00\x00\x00\x00\x00\x00\x00\x00"; @@ -370,7 +370,7 @@ class OLE extends PEAR * @param integer $string A binary string with the encoded date * @return string The timestamp corresponding to the string */ - function OLE2LocalDate($string) + static function OLE2LocalDate($string) { if (strlen($string) != 8) { return new PEAR_Error("Expecting 8 byte string"); diff --git a/include/limesurvey/admin/classes/pear/PEAR.php b/include/limesurvey/admin/classes/pear/PEAR.php index 2cf28266..a471ec33 100644 --- a/include/limesurvey/admin/classes/pear/PEAR.php +++ b/include/limesurvey/admin/classes/pear/PEAR.php @@ -263,10 +263,10 @@ class PEAR * $code is an integer and $obj->getCode() == $code * @access public * @return bool true if parameter is an error - */ + */ function isError($data, $code = null) { - if (is_a($data, 'PEAR_Error')) { + if ($data instanceof PEAR_Error) { if (is_null($code)) { return true; } elseif (is_string($code)) { @@ -554,10 +554,10 @@ class PEAR $ec = 'PEAR_Error'; } if ($skipmsg) { - $a = &new $ec($code, $mode, $options, $userinfo); + $a = new $ec($code, $mode, $options, $userinfo); return $a; } else { - $a = &new $ec($message, $code, $mode, $options, $userinfo); + $a = new $ec($message, $code, $mode, $options, $userinfo); return $a; } } diff --git a/include/limesurvey/admin/classes/pear/Spreadsheet/Excel/Writer/Parser.php b/include/limesurvey/admin/classes/pear/Spreadsheet/Excel/Writer/Parser.php index 4335ea46..69d3a261 100644 --- a/include/limesurvey/admin/classes/pear/Spreadsheet/Excel/Writer/Parser.php +++ b/include/limesurvey/admin/classes/pear/Spreadsheet/Excel/Writer/Parser.php @@ -1207,7 +1207,7 @@ class Spreadsheet_Excel_Writer_Parser extends PEAR default: // if it's a reference if (preg_match('/^\$?[A-Ia-i]?[A-Za-z]\$?[0-9]+$/',$token) and - !ereg("[0-9]",$this->_lookahead) and + !preg_match("/[0-9]/",$this->_lookahead) and ($this->_lookahead != ':') and ($this->_lookahead != '.') and ($this->_lookahead != '!')) { @@ -1215,39 +1215,39 @@ class Spreadsheet_Excel_Writer_Parser extends PEAR } // If it's an external reference (Sheet1!A1 or Sheet1:Sheet2!A1) elseif (preg_match("/^\w+(\:\w+)?\![A-Ia-i]?[A-Za-z][0-9]+$/u",$token) and - !ereg("[0-9]",$this->_lookahead) and + !preg_match("/[0-9]/",$this->_lookahead) and ($this->_lookahead != ':') and ($this->_lookahead != '.')) { return $token; } // If it's an external reference ('Sheet1'!A1 or 'Sheet1:Sheet2'!A1) elseif (preg_match("/^'[\w -]+(\:[\w -]+)?'\![A-Ia-i]?[A-Za-z][0-9]+$/u",$token) and - !ereg("[0-9]",$this->_lookahead) and + !preg_match("/[0-9]/",$this->_lookahead) and ($this->_lookahead != ':') and ($this->_lookahead != '.')) { return $token; } // if it's a range (A1:A2) elseif (preg_match("/^(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+:(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+$/",$token) and - !ereg("[0-9]",$this->_lookahead)) + !preg_match("/[0-9]/",$this->_lookahead)) { return $token; } // if it's a range (A1..A2) elseif (preg_match("/^(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+\.\.(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+$/",$token) and - !ereg("[0-9]",$this->_lookahead)) + !preg_match("/[0-9]/",$this->_lookahead)) { return $token; } // If it's an external range like Sheet1!A1 or Sheet1:Sheet2!A1:B2 elseif (preg_match("/^\w+(\:\w+)?\!([A-Ia-i]?[A-Za-z])?[0-9]+:([A-Ia-i]?[A-Za-z])?[0-9]+$/u",$token) and - !ereg("[0-9]",$this->_lookahead)) + !preg_match("/[0-9]/",$this->_lookahead)) { return $token; } // If it's an external range like 'Sheet1'!A1 or 'Sheet1:Sheet2'!A1:B2 elseif (preg_match("/^'[\w -]+(\:[\w -]+)?'\!([A-Ia-i]?[A-Za-z])?[0-9]+:([A-Ia-i]?[A-Za-z])?[0-9]+$/u",$token) and - !ereg("[0-9]",$this->_lookahead)) + !preg_match("/[0-9]/",$this->_lookahead)) { return $token; } @@ -1259,12 +1259,12 @@ class Spreadsheet_Excel_Writer_Parser extends PEAR return $token; } // If it's a string (of maximum 255 characters) - elseif (ereg("^\"[^\"]{0,255}\"$",$token)) + elseif (preg_match("/^\"[^\"]{0,255}\"$/",$token)) { return $token; } // if it's a function call - elseif (eregi("^[A-Z0-9\xc0-\xdc\.]+$",$token) and ($this->_lookahead == "(")) + elseif (preg_match("/^[A-Z0-9\xc0-\xdc\.]+$/i",$token) and ($this->_lookahead == "(")) { return $token; } @@ -1364,7 +1364,7 @@ class Spreadsheet_Excel_Writer_Parser extends PEAR function _expression() { // If it's a string return a string node - if (ereg("^\"[^\"]{0,255}\"$", $this->_current_token)) { + if (preg_match("/^\"[^\"]{0,255}\"$/", $this->_current_token)) { $result = $this->_createTree($this->_current_token, '', ''); $this->_advance(); return $result; @@ -1522,7 +1522,7 @@ class Spreadsheet_Excel_Writer_Parser extends PEAR return $result; } // if it's a function call - elseif (eregi("^[A-Z0-9\xc0-\xdc\.]+$",$this->_current_token)) + elseif (preg_match("/^[A-Z0-9\xc0-\xdc\.]+$/i",$this->_current_token)) { $result = $this->_func(); return $result; diff --git a/include/limesurvey/admin/classes/pear/Spreadsheet/Excel/Writer/Workbook.php b/include/limesurvey/admin/classes/pear/Spreadsheet/Excel/Writer/Workbook.php index 586f4b2b..4b0f4ca7 100644 --- a/include/limesurvey/admin/classes/pear/Spreadsheet/Excel/Writer/Workbook.php +++ b/include/limesurvey/admin/classes/pear/Spreadsheet/Excel/Writer/Workbook.php @@ -184,7 +184,7 @@ class Spreadsheet_Excel_Writer_Workbook extends Spreadsheet_Excel_Writer_BIFFwri $this->Spreadsheet_Excel_Writer_BIFFwriter(); $this->_filename = $filename; - $this->_parser =& new Spreadsheet_Excel_Writer_Parser($this->_byte_order, $this->_BIFF_version); + $this->_parser = new Spreadsheet_Excel_Writer_Parser($this->_byte_order, $this->_BIFF_version); $this->_1904 = 0; $this->_activesheet = 0; $this->_firstsheet = 0; @@ -193,7 +193,7 @@ class Spreadsheet_Excel_Writer_Workbook extends Spreadsheet_Excel_Writer_BIFFwri $this->_fileclosed = 0; $this->_biffsize = 0; $this->_sheetname = 'Sheet'; - $this->_tmp_format =& new Spreadsheet_Excel_Writer_Format($this->_BIFF_version); + $this->_tmp_format = new Spreadsheet_Excel_Writer_Format($this->_BIFF_version); $this->_worksheets = array(); $this->_sheetnames = array(); $this->_formats = array(); diff --git a/include/limesurvey/admin/classes/phpCAS/CAS.php b/include/limesurvey/admin/classes/phpCAS/CAS.php new file mode 100644 index 00000000..008d50cd --- /dev/null +++ b/include/limesurvey/admin/classes/phpCAS/CAS.php @@ -0,0 +1,1475 @@ +=')) { +// require_once(dirname(__FILE__).'/CAS/domxml-php4-php5.php'); +//} + +/** + * @file CAS/CAS.php + * Interface class of the phpCAS library + * + * @ingroup public + */ + +// ######################################################################## +// CONSTANTS +// ######################################################################## + +// ------------------------------------------------------------------------ +// CAS VERSIONS +// ------------------------------------------------------------------------ + +/** + * phpCAS version. accessible for the user by phpCAS::getVersion(). + */ +define('PHPCAS_VERSION','1.0.1'); + +// ------------------------------------------------------------------------ +// CAS VERSIONS +// ------------------------------------------------------------------------ + /** + * @addtogroup public + * @{ + */ + +/** + * CAS version 1.0 + */ +define("CAS_VERSION_1_0",'1.0'); +/*! + * CAS version 2.0 + */ +define("CAS_VERSION_2_0",'2.0'); + +/** @} */ + /** + * @addtogroup publicPGTStorage + * @{ + */ +// ------------------------------------------------------------------------ +// FILE PGT STORAGE +// ------------------------------------------------------------------------ + /** + * Default path used when storing PGT's to file + */ +define("CAS_PGT_STORAGE_FILE_DEFAULT_PATH",'/tmp'); +/** + * phpCAS::setPGTStorageFile()'s 2nd parameter to write plain text files + */ +define("CAS_PGT_STORAGE_FILE_FORMAT_PLAIN",'plain'); +/** + * phpCAS::setPGTStorageFile()'s 2nd parameter to write xml files + */ +define("CAS_PGT_STORAGE_FILE_FORMAT_XML",'xml'); +/** + * Default format used when storing PGT's to file + */ +define("CAS_PGT_STORAGE_FILE_DEFAULT_FORMAT",CAS_PGT_STORAGE_FILE_FORMAT_PLAIN); +// ------------------------------------------------------------------------ +// DATABASE PGT STORAGE +// ------------------------------------------------------------------------ + /** + * default database type when storing PGT's to database + */ +define("CAS_PGT_STORAGE_DB_DEFAULT_DATABASE_TYPE",'mysql'); +/** + * default host when storing PGT's to database + */ +define("CAS_PGT_STORAGE_DB_DEFAULT_HOSTNAME",'localhost'); +/** + * default port when storing PGT's to database + */ +define("CAS_PGT_STORAGE_DB_DEFAULT_PORT",''); +/** + * default database when storing PGT's to database + */ +define("CAS_PGT_STORAGE_DB_DEFAULT_DATABASE",'phpCAS'); +/** + * default table when storing PGT's to database + */ +define("CAS_PGT_STORAGE_DB_DEFAULT_TABLE",'pgt'); + +/** @} */ +// ------------------------------------------------------------------------ +// SERVICE ACCESS ERRORS +// ------------------------------------------------------------------------ + /** + * @addtogroup publicServices + * @{ + */ + +/** + * phpCAS::service() error code on success + */ +define("PHPCAS_SERVICE_OK",0); +/** + * phpCAS::service() error code when the PT could not retrieve because + * the CAS server did not respond. + */ +define("PHPCAS_SERVICE_PT_NO_SERVER_RESPONSE",1); +/** + * phpCAS::service() error code when the PT could not retrieve because + * the response of the CAS server was ill-formed. + */ +define("PHPCAS_SERVICE_PT_BAD_SERVER_RESPONSE",2); +/** + * phpCAS::service() error code when the PT could not retrieve because + * the CAS server did not want to. + */ +define("PHPCAS_SERVICE_PT_FAILURE",3); +/** + * phpCAS::service() error code when the service was not available. + */ +define("PHPCAS_SERVICE_NOT AVAILABLE",4); + +/** @} */ +// ------------------------------------------------------------------------ +// LANGUAGES +// ------------------------------------------------------------------------ + /** + * @addtogroup publicLang + * @{ + */ + +define("PHPCAS_LANG_ENGLISH", 'english'); +define("PHPCAS_LANG_FRENCH", 'french'); +define("PHPCAS_LANG_GREEK", 'greek'); +define("PHPCAS_LANG_GERMAN", 'german'); +define("PHPCAS_LANG_JAPANESE", 'japanese'); +define("PHPCAS_LANG_SPANISH", 'spanish'); +define("PHPCAS_LANG_CATALAN", 'catalan'); + +/** @} */ + +/** + * @addtogroup internalLang + * @{ + */ + +/** + * phpCAS default language (when phpCAS::setLang() is not used) + */ +define("PHPCAS_LANG_DEFAULT", PHPCAS_LANG_ENGLISH); + +/** @} */ +// ------------------------------------------------------------------------ +// DEBUG +// ------------------------------------------------------------------------ + /** + * @addtogroup publicDebug + * @{ + */ + +/** + * The default directory for the debug file under Unix. + */ +define('DEFAULT_DEBUG_DIR','/tmp/'); + +/** @} */ +// ------------------------------------------------------------------------ +// MISC +// ------------------------------------------------------------------------ + /** + * @addtogroup internalMisc + * @{ + */ + +/** + * This global variable is used by the interface class phpCAS. + * + * @hideinitializer + */ +$GLOBALS['PHPCAS_CLIENT'] = null; + +/** + * This global variable is used to store where the initializer is called from + * (to print a comprehensive error in case of multiple calls). + * + * @hideinitializer + */ +$GLOBALS['PHPCAS_INIT_CALL'] = array('done' => FALSE, + 'file' => '?', + 'line' => -1, + 'method' => '?'); + +/** + * This global variable is used to store where the method checking + * the authentication is called from (to print comprehensive errors) + * + * @hideinitializer + */ +$GLOBALS['PHPCAS_AUTH_CHECK_CALL'] = array('done' => FALSE, + 'file' => '?', + 'line' => -1, + 'method' => '?', + 'result' => FALSE); + +/** + * This global variable is used to store phpCAS debug mode. + * + * @hideinitializer + */ +$GLOBALS['PHPCAS_DEBUG'] = array('filename' => FALSE, + 'indent' => 0, + 'unique_id' => ''); + +/** @} */ + +// ######################################################################## +// CLIENT CLASS +// ######################################################################## + +// include client class +include_once(dirname(__FILE__).'/CAS/client.php'); + +// ######################################################################## +// INTERFACE CLASS +// ######################################################################## + +/** + * @class phpCAS + * The phpCAS class is a simple container for the phpCAS library. It provides CAS + * authentication for web applications written in PHP. + * + * @ingroup public + * @author Pascal Aubry + * + * \internal All its methods access the same object ($PHPCAS_CLIENT, declared + * at the end of CAS/client.php). + */ + + + +class phpCAS +{ + + // ######################################################################## + // INITIALIZATION + // ######################################################################## + + /** + * @addtogroup publicInit + * @{ + */ + + /** + * phpCAS client initializer. + * @note Only one of the phpCAS::client() and phpCAS::proxy functions should be + * called, only once, and before all other methods (except phpCAS::getVersion() + * and phpCAS::setDebug()). + * + * @param $server_version the version of the CAS server + * @param $server_hostname the hostname of the CAS server + * @param $server_port the port the CAS server is running on + * @param $server_uri the URI the CAS server is responding on + * @param $start_session Have phpCAS start PHP sessions (default true) + * + * @return a newly created CASClient object + */ + function client($server_version, + $server_hostname, + $server_port, + $server_uri, + $start_session = true) + { + global $PHPCAS_CLIENT, $PHPCAS_INIT_CALL; + + phpCAS::traceBegin(); + if ( is_object($PHPCAS_CLIENT) ) { + phpCAS::error($PHPCAS_INIT_CALL['method'].'() has already been called (at '.$PHPCAS_INIT_CALL['file'].':'.$PHPCAS_INIT_CALL['line'].')'); + } + if ( gettype($server_version) != 'string' ) { + phpCAS::error('type mismatched for parameter $server_version (should be `string\')'); + } + if ( gettype($server_hostname) != 'string' ) { + phpCAS::error('type mismatched for parameter $server_hostname (should be `string\')'); + } + if ( gettype($server_port) != 'integer' ) { + phpCAS::error('type mismatched for parameter $server_port (should be `integer\')'); + } + if ( gettype($server_uri) != 'string' ) { + phpCAS::error('type mismatched for parameter $server_uri (should be `string\')'); + } + + // store where the initialzer is called from + $dbg = phpCAS::backtrace(); + $PHPCAS_INIT_CALL = array('done' => TRUE, + 'file' => $dbg[0]['file'], + 'line' => $dbg[0]['line'], + 'method' => __CLASS__.'::'.__FUNCTION__); + + // initialize the global object $PHPCAS_CLIENT + $PHPCAS_CLIENT = new CASClient($server_version,FALSE/*proxy*/,$server_hostname,$server_port,$server_uri,$start_session); + phpCAS::traceEnd(); + } + + /** + * phpCAS proxy initializer. + * @note Only one of the phpCAS::client() and phpCAS::proxy functions should be + * called, only once, and before all other methods (except phpCAS::getVersion() + * and phpCAS::setDebug()). + * + * @param $server_version the version of the CAS server + * @param $server_hostname the hostname of the CAS server + * @param $server_port the port the CAS server is running on + * @param $server_uri the URI the CAS server is responding on + * @param $start_session Have phpCAS start PHP sessions (default true) + * + * @return a newly created CASClient object + */ + function proxy($server_version, + $server_hostname, + $server_port, + $server_uri, + $start_session = true) + { + global $PHPCAS_CLIENT, $PHPCAS_INIT_CALL; + + phpCAS::traceBegin(); + if ( is_object($PHPCAS_CLIENT) ) { + phpCAS::error($PHPCAS_INIT_CALL['method'].'() has already been called (at '.$PHPCAS_INIT_CALL['file'].':'.$PHPCAS_INIT_CALL['line'].')'); + } + if ( gettype($server_version) != 'string' ) { + phpCAS::error('type mismatched for parameter $server_version (should be `string\')'); + } + if ( gettype($server_hostname) != 'string' ) { + phpCAS::error('type mismatched for parameter $server_hostname (should be `string\')'); + } + if ( gettype($server_port) != 'integer' ) { + phpCAS::error('type mismatched for parameter $server_port (should be `integer\')'); + } + if ( gettype($server_uri) != 'string' ) { + phpCAS::error('type mismatched for parameter $server_uri (should be `string\')'); + } + + // store where the initialzer is called from + $dbg = phpCAS::backtrace(); + $PHPCAS_INIT_CALL = array('done' => TRUE, + 'file' => $dbg[0]['file'], + 'line' => $dbg[0]['line'], + 'method' => __CLASS__.'::'.__FUNCTION__); + + // initialize the global object $PHPCAS_CLIENT + $PHPCAS_CLIENT = new CASClient($server_version,TRUE/*proxy*/,$server_hostname,$server_port,$server_uri,$start_session); + phpCAS::traceEnd(); + } + + /** @} */ + // ######################################################################## + // DEBUGGING + // ######################################################################## + + /** + * @addtogroup publicDebug + * @{ + */ + + /** + * Set/unset debug mode + * + * @param $filename the name of the file used for logging, or FALSE to stop debugging. + */ + function setDebug($filename='') + { + global $PHPCAS_DEBUG; + + if ( $filename != FALSE && gettype($filename) != 'string' ) { + phpCAS::error('type mismatched for parameter $dbg (should be FALSE or the name of the log file)'); + } + + if ( empty($filename) ) { + if ( preg_match('/^Win.*/',getenv('OS')) ) { + if ( isset($_ENV['TMP']) ) { + $debugDir = $_ENV['TMP'].'/'; + } else if ( isset($_ENV['TEMP']) ) { + $debugDir = $_ENV['TEMP'].'/'; + } else { + $debugDir = ''; + } + } else { + $debugDir = DEFAULT_DEBUG_DIR; + } + $filename = $debugDir . 'phpCAS.log'; + } + + if ( empty($PHPCAS_DEBUG['unique_id']) ) { + $PHPCAS_DEBUG['unique_id'] = substr(strtoupper(md5(uniqid(''))),0,4); + } + + $PHPCAS_DEBUG['filename'] = $filename; + + phpCAS::trace('START ******************'); + } + + /** @} */ + /** + * @addtogroup internalDebug + * @{ + */ + + /** + * This method is a wrapper for debug_backtrace() that is not available + * in all PHP versions (>= 4.3.0 only) + */ + function backtrace() + { + if ( function_exists('debug_backtrace') ) { + return debug_backtrace(); + } else { + // poor man's hack ... but it does work ... + return array(); + } + } + + /** + * Logs a string in debug mode. + * + * @param $str the string to write + * + * @private + */ + function log($str) + { + $indent_str = "."; + global $PHPCAS_DEBUG; + + if ( $PHPCAS_DEBUG['filename'] ) { + for ($i=0;$i<$PHPCAS_DEBUG['indent'];$i++) { + $indent_str .= '| '; + } + error_log($PHPCAS_DEBUG['unique_id'].' '.$indent_str.$str."\n",3,$PHPCAS_DEBUG['filename']); + } + + } + + /** + * This method is used by interface methods to print an error and where the function + * was originally called from. + * + * @param $msg the message to print + * + * @private + */ + function error($msg) + { + $dbg = phpCAS::backtrace(); + $function = '?'; + $file = '?'; + $line = '?'; + if ( is_array($dbg) ) { + for ( $i=1; $i\nphpCAS error: ".__CLASS__."::".$function.'(): '.htmlentities($msg)." in ".$file." on line ".$line."
    \n"; + phpCAS::trace($msg); + phpCAS::traceExit(); + exit(); + } + + /** + * This method is used to log something in debug mode. + */ + function trace($str) + { + $dbg = phpCAS::backtrace(); + phpCAS::log($str.' ['.basename($dbg[1]['file']).':'.$dbg[1]['line'].']'); + } + + /** + * This method is used to indicate the start of the execution of a function in debug mode. + */ + function traceBegin() + { + global $PHPCAS_DEBUG; + + $dbg = phpCAS::backtrace(); + $str = '=> '; + if ( !empty($dbg[2]['class']) ) { + $str .= $dbg[2]['class'].'::'; + } + $str .= $dbg[2]['function'].'('; + if ( is_array($dbg[2]['args']) ) { + foreach ($dbg[2]['args'] as $index => $arg) { + if ( $index != 0 ) { + $str .= ', '; + } + $str .= str_replace("\n","",var_export($arg,TRUE)); + } + } + $str .= ') ['.basename($dbg[2]['file']).':'.$dbg[2]['line'].']'; + phpCAS::log($str); + $PHPCAS_DEBUG['indent'] ++; + } + + /** + * This method is used to indicate the end of the execution of a function in debug mode. + * + * @param $res the result of the function + */ + function traceEnd($res='') + { + global $PHPCAS_DEBUG; + + $PHPCAS_DEBUG['indent'] --; + $dbg = phpCAS::backtrace(); + $str = ''; + $str .= '<= '.str_replace("\n","",var_export($res,TRUE)); + phpCAS::log($str); + } + + /** + * This method is used to indicate the end of the execution of the program + */ + function traceExit() + { + global $PHPCAS_DEBUG; + + phpCAS::log('exit()'); + while ( $PHPCAS_DEBUG['indent'] > 0 ) { + phpCAS::log('-'); + $PHPCAS_DEBUG['indent'] --; + } + } + + /** @} */ + // ######################################################################## + // INTERNATIONALIZATION + // ######################################################################## + /** + * @addtogroup publicLang + * @{ + */ + + /** + * This method is used to set the language used by phpCAS. + * @note Can be called only once. + * + * @param $lang a string representing the language. + * + * @sa PHPCAS_LANG_FRENCH, PHPCAS_LANG_ENGLISH + */ + function setLang($lang) + { + global $PHPCAS_CLIENT; + if ( !is_object($PHPCAS_CLIENT) ) { + phpCAS::error('this method should not be called before '.__CLASS__.'::client() or '.__CLASS__.'::proxy()'); + } + if ( gettype($lang) != 'string' ) { + phpCAS::error('type mismatched for parameter $lang (should be `string\')'); + } + $PHPCAS_CLIENT->setLang($lang); + } + + /** @} */ + // ######################################################################## + // VERSION + // ######################################################################## + /** + * @addtogroup public + * @{ + */ + + /** + * This method returns the phpCAS version. + * + * @return the phpCAS version. + */ + function getVersion() + { + return PHPCAS_VERSION; + } + + /** @} */ + // ######################################################################## + // HTML OUTPUT + // ######################################################################## + /** + * @addtogroup publicOutput + * @{ + */ + + /** + * This method sets the HTML header used for all outputs. + * + * @param $header the HTML header. + */ + function setHTMLHeader($header) + { + global $PHPCAS_CLIENT; + if ( !is_object($PHPCAS_CLIENT) ) { + phpCAS::error('this method should not be called before '.__CLASS__.'::client() or '.__CLASS__.'::proxy()'); + } + if ( gettype($header) != 'string' ) { + phpCAS::error('type mismatched for parameter $header (should be `string\')'); + } + $PHPCAS_CLIENT->setHTMLHeader($header); + } + + /** + * This method sets the HTML footer used for all outputs. + * + * @param $footer the HTML footer. + */ + function setHTMLFooter($footer) + { + global $PHPCAS_CLIENT; + if ( !is_object($PHPCAS_CLIENT) ) { + phpCAS::error('this method should not be called before '.__CLASS__.'::client() or '.__CLASS__.'::proxy()'); + } + if ( gettype($footer) != 'string' ) { + phpCAS::error('type mismatched for parameter $footer (should be `string\')'); + } + $PHPCAS_CLIENT->setHTMLFooter($footer); + } + + /** @} */ + // ######################################################################## + // PGT STORAGE + // ######################################################################## + /** + * @addtogroup publicPGTStorage + * @{ + */ + + /** + * This method is used to tell phpCAS to store the response of the + * CAS server to PGT requests onto the filesystem. + * + * @param $format the format used to store the PGT's (`plain' and `xml' allowed) + * @param $path the path where the PGT's should be stored + */ + function setPGTStorageFile($format='', + $path='') + { + global $PHPCAS_CLIENT,$PHPCAS_AUTH_CHECK_CALL; + + phpCAS::traceBegin(); + if ( !is_object($PHPCAS_CLIENT) ) { + phpCAS::error('this method should only be called after '.__CLASS__.'::proxy()'); + } + if ( !$PHPCAS_CLIENT->isProxy() ) { + phpCAS::error('this method should only be called after '.__CLASS__.'::proxy()'); + } + if ( $PHPCAS_AUTH_CHECK_CALL['done'] ) { + phpCAS::error('this method should only be called before '.$PHPCAS_AUTH_CHECK_CALL['method'].'() (called at '.$PHPCAS_AUTH_CHECK_CALL['file'].':'.$PHPCAS_AUTH_CHECK_CALL['line'].')'); + } + if ( gettype($format) != 'string' ) { + phpCAS::error('type mismatched for parameter $format (should be `string\')'); + } + if ( gettype($path) != 'string' ) { + phpCAS::error('type mismatched for parameter $format (should be `string\')'); + } + $PHPCAS_CLIENT->setPGTStorageFile($format,$path); + phpCAS::traceEnd(); + } + + /** + * This method is used to tell phpCAS to store the response of the + * CAS server to PGT requests into a database. + * @note The connection to the database is done only when needed. + * As a consequence, bad parameters are detected only when + * initializing PGT storage, except in debug mode. + * + * @param $user the user to access the data with + * @param $password the user's password + * @param $database_type the type of the database hosting the data + * @param $hostname the server hosting the database + * @param $port the port the server is listening on + * @param $database the name of the database + * @param $table the name of the table storing the data + */ + function setPGTStorageDB($user, + $password, + $database_type='', + $hostname='', + $port=0, + $database='', + $table='') + { + global $PHPCAS_CLIENT,$PHPCAS_AUTH_CHECK_CALL; + + phpCAS::traceBegin(); + if ( !is_object($PHPCAS_CLIENT) ) { + phpCAS::error('this method should only be called after '.__CLASS__.'::proxy()'); + } + if ( !$PHPCAS_CLIENT->isProxy() ) { + phpCAS::error('this method should only be called after '.__CLASS__.'::proxy()'); + } + if ( $PHPCAS_AUTH_CHECK_CALL['done'] ) { + phpCAS::error('this method should only be called before '.$PHPCAS_AUTH_CHECK_CALL['method'].'() (called at '.$PHPCAS_AUTH_CHECK_CALL['file'].':'.$PHPCAS_AUTH_CHECK_CALL['line'].')'); + } + if ( gettype($user) != 'string' ) { + phpCAS::error('type mismatched for parameter $user (should be `string\')'); + } + if ( gettype($password) != 'string' ) { + phpCAS::error('type mismatched for parameter $password (should be `string\')'); + } + if ( gettype($database_type) != 'string' ) { + phpCAS::error('type mismatched for parameter $database_type (should be `string\')'); + } + if ( gettype($hostname) != 'string' ) { + phpCAS::error('type mismatched for parameter $hostname (should be `string\')'); + } + if ( gettype($port) != 'integer' ) { + phpCAS::error('type mismatched for parameter $port (should be `integer\')'); + } + if ( gettype($database) != 'string' ) { + phpCAS::error('type mismatched for parameter $database (should be `string\')'); + } + if ( gettype($table) != 'string' ) { + phpCAS::error('type mismatched for parameter $table (should be `string\')'); + } + $PHPCAS_CLIENT->setPGTStorageDB($this,$user,$password,$hostname,$port,$database,$table); + phpCAS::traceEnd(); + } + + /** @} */ + // ######################################################################## + // ACCESS TO EXTERNAL SERVICES + // ######################################################################## + /** + * @addtogroup publicServices + * @{ + */ + + /** + * This method is used to access an HTTP[S] service. + * + * @param $url the service to access. + * @param $err_code an error code Possible values are PHPCAS_SERVICE_OK (on + * success), PHPCAS_SERVICE_PT_NO_SERVER_RESPONSE, PHPCAS_SERVICE_PT_BAD_SERVER_RESPONSE, + * PHPCAS_SERVICE_PT_FAILURE, PHPCAS_SERVICE_NOT AVAILABLE. + * @param $output the output of the service (also used to give an error + * message on failure). + * + * @return TRUE on success, FALSE otherwise (in this later case, $err_code + * gives the reason why it failed and $output contains an error message). + */ + function serviceWeb($url,&$err_code,&$output) + { + global $PHPCAS_CLIENT, $PHPCAS_AUTH_CHECK_CALL; + + phpCAS::traceBegin(); + if ( !is_object($PHPCAS_CLIENT) ) { + phpCAS::error('this method should only be called after '.__CLASS__.'::proxy()'); + } + if ( !$PHPCAS_CLIENT->isProxy() ) { + phpCAS::error('this method should only be called after '.__CLASS__.'::proxy()'); + } + if ( !$PHPCAS_AUTH_CHECK_CALL['done'] ) { + phpCAS::error('this method should only be called after the programmer is sure the user has been authenticated (by calling '.__CLASS__.'::checkAuthentication() or '.__CLASS__.'::forceAuthentication()'); + } + if ( !$PHPCAS_AUTH_CHECK_CALL['result'] ) { + phpCAS::error('authentication was checked (by '.$PHPCAS_AUTH_CHECK_CALL['method'].'() at '.$PHPCAS_AUTH_CHECK_CALL['file'].':'.$PHPCAS_AUTH_CHECK_CALL['line'].') but the method returned FALSE'); + } + if ( gettype($url) != 'string' ) { + phpCAS::error('type mismatched for parameter $url (should be `string\')'); + } + + $res = $PHPCAS_CLIENT->serviceWeb($url,$err_code,$output); + + phpCAS::traceEnd($res); + return $res; + } + + /** + * This method is used to access an IMAP/POP3/NNTP service. + * + * @param $url a string giving the URL of the service, including the mailing box + * for IMAP URLs, as accepted by imap_open(). + * @param $flags options given to imap_open(). + * @param $err_code an error code Possible values are PHPCAS_SERVICE_OK (on + * success), PHPCAS_SERVICE_PT_NO_SERVER_RESPONSE, PHPCAS_SERVICE_PT_BAD_SERVER_RESPONSE, + * PHPCAS_SERVICE_PT_FAILURE, PHPCAS_SERVICE_NOT AVAILABLE. + * @param $err_msg an error message on failure + * @param $pt the Proxy Ticket (PT) retrieved from the CAS server to access the URL + * on success, FALSE on error). + * + * @return an IMAP stream on success, FALSE otherwise (in this later case, $err_code + * gives the reason why it failed and $err_msg contains an error message). + */ + function serviceMail($url,$flags,&$err_code,&$err_msg,&$pt) + { + global $PHPCAS_CLIENT, $PHPCAS_AUTH_CHECK_CALL; + + phpCAS::traceBegin(); + if ( !is_object($PHPCAS_CLIENT) ) { + phpCAS::error('this method should only be called after '.__CLASS__.'::proxy()'); + } + if ( !$PHPCAS_CLIENT->isProxy() ) { + phpCAS::error('this method should only be called after '.__CLASS__.'::proxy()'); + } + if ( !$PHPCAS_AUTH_CHECK_CALL['done'] ) { + phpCAS::error('this method should only be called after the programmer is sure the user has been authenticated (by calling '.__CLASS__.'::checkAuthentication() or '.__CLASS__.'::forceAuthentication()'); + } + if ( !$PHPCAS_AUTH_CHECK_CALL['result'] ) { + phpCAS::error('authentication was checked (by '.$PHPCAS_AUTH_CHECK_CALL['method'].'() at '.$PHPCAS_AUTH_CHECK_CALL['file'].':'.$PHPCAS_AUTH_CHECK_CALL['line'].') but the method returned FALSE'); + } + if ( gettype($url) != 'string' ) { + phpCAS::error('type mismatched for parameter $url (should be `string\')'); + } + + if ( gettype($flags) != 'integer' ) { + phpCAS::error('type mismatched for parameter $flags (should be `integer\')'); + } + + $res = $PHPCAS_CLIENT->serviceMail($url,$flags,$err_code,$err_msg,$pt); + + phpCAS::traceEnd($res); + return $res; + } + + /** @} */ + // ######################################################################## + // AUTHENTICATION + // ######################################################################## + /** + * @addtogroup publicAuth + * @{ + */ + + /** + * Set the times authentication will be cached before really accessing the CAS server in gateway mode: + * - -1: check only once, and then never again (until you pree login) + * - 0: always check + * - n: check every "n" time + * + * @param $n an integer. + */ + function setCacheTimesForAuthRecheck($n) + { + global $PHPCAS_CLIENT; + if ( !is_object($PHPCAS_CLIENT) ) { + phpCAS::error('this method should not be called before '.__CLASS__.'::client() or '.__CLASS__.'::proxy()'); + } + if ( gettype($n) != 'integer' ) { + phpCAS::error('type mismatched for parameter $header (should be `string\')'); + } + $PHPCAS_CLIENT->setCacheTimesForAuthRecheck($n); + } + + /** + * This method is called to check if the user is authenticated (use the gateway feature). + * @return TRUE when the user is authenticated; otherwise FALSE. + */ + function checkAuthentication() + { + global $PHPCAS_CLIENT, $PHPCAS_AUTH_CHECK_CALL; + + phpCAS::traceBegin(); + if ( !is_object($PHPCAS_CLIENT) ) { + phpCAS::error('this method should not be called before '.__CLASS__.'::client() or '.__CLASS__.'::proxy()'); + } + + $auth = $PHPCAS_CLIENT->checkAuthentication(); + + // store where the authentication has been checked and the result + $dbg = phpCAS::backtrace(); + $PHPCAS_AUTH_CHECK_CALL = array('done' => TRUE, + 'file' => $dbg[0]['file'], + 'line' => $dbg[0]['line'], + 'method' => __CLASS__.'::'.__FUNCTION__, + 'result' => $auth ); + phpCAS::traceEnd($auth); + return $auth; + } + + /** + * This method is called to force authentication if the user was not already + * authenticated. If the user is not authenticated, halt by redirecting to + * the CAS server. + */ + function forceAuthentication() + { + global $PHPCAS_CLIENT, $PHPCAS_AUTH_CHECK_CALL; + + phpCAS::traceBegin(); + if ( !is_object($PHPCAS_CLIENT) ) { + phpCAS::error('this method should not be called before '.__CLASS__.'::client() or '.__CLASS__.'::proxy()'); + } + + $auth = $PHPCAS_CLIENT->forceAuthentication(); + + // store where the authentication has been checked and the result + $dbg = phpCAS::backtrace(); + $PHPCAS_AUTH_CHECK_CALL = array('done' => TRUE, + 'file' => $dbg[0]['file'], + 'line' => $dbg[0]['line'], + 'method' => __CLASS__.'::'.__FUNCTION__, + 'result' => $auth ); + + if ( !$auth ) { + phpCAS::trace('user is not authenticated, redirecting to the CAS server'); + $PHPCAS_CLIENT->forceAuthentication(); + } else { + phpCAS::trace('no need to authenticate (user `'.phpCAS::getUser().'\' is already authenticated)'); + } + + phpCAS::traceEnd(); + return $auth; + } + + /** + * This method is called to renew the authentication. + **/ + function renewAuthentication() { + global $PHPCAS_CLIENT, $PHPCAS_AUTH_CHECK_CALL; + + phpCAS::traceBegin(); + if ( !is_object($PHPCAS_CLIENT) ) { + phpCAS::error('this method should not be called before'.__CLASS__.'::client() or '.__CLASS__.'::proxy()'); + } + + // store where the authentication has been checked and the result + $dbg = phpCAS::backtrace(); + $PHPCAS_AUTH_CHECK_CALL = array('done' => TRUE, 'file' => $dbg[0]['file'], 'line' => $dbg[0]['line'], 'method' => __CLASS__.'::'.__FUNCTION__, 'result' => $auth ); + + $PHPCAS_CLIENT->renewAuthentication(); + phpCAS::traceEnd(); + } + + /** + * This method has been left from version 0.4.1 for compatibility reasons. + */ + function authenticate() + { + phpCAS::error('this method is deprecated. You should use '.__CLASS__.'::forceAuthentication() instead'); + } + + /** + * This method is called to check if the user is authenticated (previously or by + * tickets given in the URL). + * + * @return TRUE when the user is authenticated. + */ + function isAuthenticated() + { + global $PHPCAS_CLIENT, $PHPCAS_AUTH_CHECK_CALL; + + phpCAS::traceBegin(); + if ( !is_object($PHPCAS_CLIENT) ) { + phpCAS::error('this method should not be called before '.__CLASS__.'::client() or '.__CLASS__.'::proxy()'); + } + + // call the isAuthenticated method of the global $PHPCAS_CLIENT object + $auth = $PHPCAS_CLIENT->isAuthenticated(); + + // store where the authentication has been checked and the result + $dbg = phpCAS::backtrace(); + $PHPCAS_AUTH_CHECK_CALL = array('done' => TRUE, + 'file' => $dbg[0]['file'], + 'line' => $dbg[0]['line'], + 'method' => __CLASS__.'::'.__FUNCTION__, + 'result' => $auth ); + phpCAS::traceEnd($auth); + return $auth; + } + + /** + * Checks whether authenticated based on $_SESSION. Useful to avoid + * server calls. + * @return true if authenticated, false otherwise. + * @since 0.4.22 by Brendan Arnold + */ + function isSessionAuthenticated () + { + global $PHPCAS_CLIENT; + if ( !is_object($PHPCAS_CLIENT) ) { + phpCAS::error('this method should not be called before '.__CLASS__.'::client() or '.__CLASS__.'::proxy()'); + } + return($PHPCAS_CLIENT->isSessionAuthenticated()); + } + + /** + * This method returns the CAS user's login name. + * @warning should not be called only after phpCAS::forceAuthentication() + * or phpCAS::checkAuthentication(). + * + * @return the login name of the authenticated user + */ + function getUser() + { + global $PHPCAS_CLIENT, $PHPCAS_AUTH_CHECK_CALL; + if ( !is_object($PHPCAS_CLIENT) ) { + phpCAS::error('this method should not be called before '.__CLASS__.'::client() or '.__CLASS__.'::proxy()'); + } + if ( !$PHPCAS_AUTH_CHECK_CALL['done'] ) { + phpCAS::error('this method should only be called after '.__CLASS__.'::forceAuthentication() or '.__CLASS__.'::isAuthenticated()'); + } + if ( !$PHPCAS_AUTH_CHECK_CALL['result'] ) { + phpCAS::error('authentication was checked (by '.$PHPCAS_AUTH_CHECK_CALL['method'].'() at '.$PHPCAS_AUTH_CHECK_CALL['file'].':'.$PHPCAS_AUTH_CHECK_CALL['line'].') but the method returned FALSE'); + } + return $PHPCAS_CLIENT->getUser(); + } + + /** + * Handle logout requests. + */ + function handleLogoutRequests($check_client=true, $allowed_clients=false) + { + global $PHPCAS_CLIENT; + if ( !is_object($PHPCAS_CLIENT) ) { + phpCAS::error('this method should not be called before '.__CLASS__.'::client() or '.__CLASS__.'::proxy()'); + } + return($PHPCAS_CLIENT->handleLogoutRequests($check_client, $allowed_clients)); + } + + /** + * This method returns the URL to be used to login. + * or phpCAS::isAuthenticated(). + * + * @return the login name of the authenticated user + */ + function getServerLoginURL() + { + global $PHPCAS_CLIENT; + if ( !is_object($PHPCAS_CLIENT) ) { + phpCAS::error('this method should not be called before '.__CLASS__.'::client() or '.__CLASS__.'::proxy()'); + } + return $PHPCAS_CLIENT->getServerLoginURL(); + } + + /** + * Set the login URL of the CAS server. + * @param $url the login URL + * @since 0.4.21 by Wyman Chan + */ + function setServerLoginURL($url='') + { + global $PHPCAS_CLIENT; + phpCAS::traceBegin(); + if ( !is_object($PHPCAS_CLIENT) ) { + phpCAS::error('this method should only be called after + '.__CLASS__.'::client()'); + } + if ( gettype($url) != 'string' ) { + phpCAS::error('type mismatched for parameter $url (should be + `string\')'); + } + $PHPCAS_CLIENT->setServerLoginURL($url); + phpCAS::traceEnd(); + } + + /** + * This method returns the URL to be used to login. + * or phpCAS::isAuthenticated(). + * + * @return the login name of the authenticated user + */ + function getServerLogoutURL() + { + global $PHPCAS_CLIENT; + if ( !is_object($PHPCAS_CLIENT) ) { + phpCAS::error('this method should not be called before '.__CLASS__.'::client() or '.__CLASS__.'::proxy()'); + } + return $PHPCAS_CLIENT->getServerLogoutURL(); + } + + /** + * Set the logout URL of the CAS server. + * @param $url the logout URL + * @since 0.4.21 by Wyman Chan + */ + function setServerLogoutURL($url='') + { + global $PHPCAS_CLIENT; + phpCAS::traceBegin(); + if ( !is_object($PHPCAS_CLIENT) ) { + phpCAS::error('this method should only be called after + '.__CLASS__.'::client()'); + } + if ( gettype($url) != 'string' ) { + phpCAS::error('type mismatched for parameter $url (should be + `string\')'); + } + $PHPCAS_CLIENT->setServerLogoutURL($url); + phpCAS::traceEnd(); + } + + /** + * This method is used to logout from CAS. + * @params $params an array that contains the optional url and service parameters that will be passed to the CAS server + * @public + */ + function logout($params = "") { + global $PHPCAS_CLIENT; + phpCAS::traceBegin(); + if (!is_object($PHPCAS_CLIENT)) { + phpCAS::error('this method should only be called after '.__CLASS__.'::client() or'.__CLASS__.'::proxy()'); + } + $parsedParams = array(); + if ($params != "") { + if (is_string($params)) { + phpCAS::error('method `phpCAS::logout($url)\' is now deprecated, use `phpCAS::logoutWithUrl($url)\' instead'); + } + if (!is_array($params)) { + phpCAS::error('type mismatched for parameter $params (should be `array\')'); + } + foreach ($params as $key => $value) { + if ($key != "service" && $key != "url") { + phpCAS::error('only `url\' and `service\' parameters are allowed for method `phpCAS::logout($params)\''); + } + $parsedParams[$key] = $value; + } + } + $PHPCAS_CLIENT->logout($parsedParams); + // never reached + phpCAS::traceEnd(); + } + + /** + * This method is used to logout from CAS. Halts by redirecting to the CAS server. + * @param $service a URL that will be transmitted to the CAS server + */ + function logoutWithRedirectService($service) { + global $PHPCAS_CLIENT; + phpCAS::traceBegin(); + if ( !is_object($PHPCAS_CLIENT) ) { + phpCAS::error('this method should only be called after '.__CLASS__.'::client() or'.__CLASS__.'::proxy()'); + } + if (!is_string($service)) { + phpCAS::error('type mismatched for parameter $service (should be `string\')'); + } + $PHPCAS_CLIENT->logout(array("service" => $service)); + // never reached + phpCAS::traceEnd(); + } + + /** + * This method is used to logout from CAS. Halts by redirecting to the CAS server. + * @param $url a URL that will be transmitted to the CAS server + */ + function logoutWithUrl($url) { + global $PHPCAS_CLIENT; + phpCAS::traceBegin(); + if ( !is_object($PHPCAS_CLIENT) ) { + phpCAS::error('this method should only be called after '.__CLASS__.'::client() or'.__CLASS__.'::proxy()'); + } + if (!is_string($url)) { + phpCAS::error('type mismatched for parameter $url (should be `string\')'); + } + $PHPCAS_CLIENT->logout(array("url" => $url)); + // never reached + phpCAS::traceEnd(); + } + + /** + * This method is used to logout from CAS. Halts by redirecting to the CAS server. + * @param $service a URL that will be transmitted to the CAS server + * @param $url a URL that will be transmitted to the CAS server + */ + function logoutWithRedirectServiceAndUrl($service, $url) { + global $PHPCAS_CLIENT; + phpCAS::traceBegin(); + if ( !is_object($PHPCAS_CLIENT) ) { + phpCAS::error('this method should only be called after '.__CLASS__.'::client() or'.__CLASS__.'::proxy()'); + } + if (!is_string($service)) { + phpCAS::error('type mismatched for parameter $service (should be `string\')'); + } + if (!is_string($url)) { + phpCAS::error('type mismatched for parameter $url (should be `string\')'); + } + $PHPCAS_CLIENT->logout(array("service" => $service, "url" => $url)); + // never reached + phpCAS::traceEnd(); + } + + /** + * Set the fixed URL that will be used by the CAS server to transmit the PGT. + * When this method is not called, a phpCAS script uses its own URL for the callback. + * + * @param $url the URL + */ + function setFixedCallbackURL($url='') + { + global $PHPCAS_CLIENT; + phpCAS::traceBegin(); + if ( !is_object($PHPCAS_CLIENT) ) { + phpCAS::error('this method should only be called after '.__CLASS__.'::proxy()'); + } + if ( !$PHPCAS_CLIENT->isProxy() ) { + phpCAS::error('this method should only be called after '.__CLASS__.'::proxy()'); + } + if ( gettype($url) != 'string' ) { + phpCAS::error('type mismatched for parameter $url (should be `string\')'); + } + $PHPCAS_CLIENT->setCallbackURL($url); + phpCAS::traceEnd(); + } + + /** + * Set the fixed URL that will be set as the CAS service parameter. When this + * method is not called, a phpCAS script uses its own URL. + * + * @param $url the URL + */ + function setFixedServiceURL($url) + { + global $PHPCAS_CLIENT; + phpCAS::traceBegin(); + if ( !is_object($PHPCAS_CLIENT) ) { + phpCAS::error('this method should only be called after '.__CLASS__.'::proxy()'); + } + if ( gettype($url) != 'string' ) { + phpCAS::error('type mismatched for parameter $url (should be `string\')'); + } + $PHPCAS_CLIENT->setURL($url); + phpCAS::traceEnd(); + } + + /** + * Get the URL that is set as the CAS service parameter. + */ + function getServiceURL() + { + global $PHPCAS_CLIENT; + if ( !is_object($PHPCAS_CLIENT) ) { + phpCAS::error('this method should only be called after '.__CLASS__.'::proxy()'); + } + return($PHPCAS_CLIENT->getURL()); + } + + /** + * Retrieve a Proxy Ticket from the CAS server. + */ + function retrievePT($target_service,&$err_code,&$err_msg) + { + global $PHPCAS_CLIENT; + if ( !is_object($PHPCAS_CLIENT) ) { + phpCAS::error('this method should only be called after '.__CLASS__.'::proxy()'); + } + if ( gettype($target_service) != 'string' ) { + phpCAS::error('type mismatched for parameter $target_service(should be `string\')'); + } + return($PHPCAS_CLIENT->retrievePT($target_service,$err_code,$err_msg)); + } + + /** + * Set the certificate of the CAS server. + * + * @param $cert the PEM certificate + */ + function setCasServerCert($cert) + { + global $PHPCAS_CLIENT; + phpCAS::traceBegin(); + if ( !is_object($PHPCAS_CLIENT) ) { + phpCAS::error('this method should only be called after '.__CLASS__.'::client() or'.__CLASS__.'::proxy()'); + } + if ( gettype($cert) != 'string' ) { + phpCAS::error('type mismatched for parameter $cert (should be `string\')'); + } + $PHPCAS_CLIENT->setCasServerCert($cert); + phpCAS::traceEnd(); + } + + /** + * Set the certificate of the CAS server CA. + * + * @param $cert the CA certificate + */ + function setCasServerCACert($cert) + { + global $PHPCAS_CLIENT; + phpCAS::traceBegin(); + if ( !is_object($PHPCAS_CLIENT) ) { + phpCAS::error('this method should only be called after '.__CLASS__.'::client() or'.__CLASS__.'::proxy()'); + } + if ( gettype($cert) != 'string' ) { + phpCAS::error('type mismatched for parameter $cert (should be `string\')'); + } + $PHPCAS_CLIENT->setCasServerCACert($cert); + phpCAS::traceEnd(); + } + + /** + * Set no SSL validation for the CAS server. + */ + function setNoCasServerValidation() + { + global $PHPCAS_CLIENT; + phpCAS::traceBegin(); + if ( !is_object($PHPCAS_CLIENT) ) { + phpCAS::error('this method should only be called after '.__CLASS__.'::client() or'.__CLASS__.'::proxy()'); + } + $PHPCAS_CLIENT->setNoCasServerValidation(); + phpCAS::traceEnd(); + } + + /** @} */ + + /** + * Change CURL options. + * CURL is used to connect through HTTPS to CAS server + * @param $key the option key + * @param $value the value to set + */ + function setExtraCurlOption($key, $value) + { + global $PHPCAS_CLIENT; + phpCAS::traceBegin(); + if ( !is_object($PHPCAS_CLIENT) ) { + phpCAS::error('this method should only be called after '.__CLASS__.'::client() or'.__CLASS__.'::proxy()'); + } + $PHPCAS_CLIENT->setExtraCurlOption($key, $value); + phpCAS::traceEnd(); + } + +} + +// ######################################################################## +// DOCUMENTATION +// ######################################################################## + +// ######################################################################## +// MAIN PAGE + +/** + * @mainpage + * + * The following pages only show the source documentation. + * + */ + +// ######################################################################## +// MODULES DEFINITION + +/** @defgroup public User interface */ + +/** @defgroup publicInit Initialization + * @ingroup public */ + +/** @defgroup publicAuth Authentication + * @ingroup public */ + +/** @defgroup publicServices Access to external services + * @ingroup public */ + +/** @defgroup publicConfig Configuration + * @ingroup public */ + +/** @defgroup publicLang Internationalization + * @ingroup publicConfig */ + +/** @defgroup publicOutput HTML output + * @ingroup publicConfig */ + +/** @defgroup publicPGTStorage PGT storage + * @ingroup publicConfig */ + +/** @defgroup publicDebug Debugging + * @ingroup public */ + + +/** @defgroup internal Implementation */ + +/** @defgroup internalAuthentication Authentication + * @ingroup internal */ + +/** @defgroup internalBasic CAS Basic client features (CAS 1.0, Service Tickets) + * @ingroup internal */ + +/** @defgroup internalProxy CAS Proxy features (CAS 2.0, Proxy Granting Tickets) + * @ingroup internal */ + +/** @defgroup internalPGTStorage PGT storage + * @ingroup internalProxy */ + +/** @defgroup internalPGTStorageDB PGT storage in a database + * @ingroup internalPGTStorage */ + +/** @defgroup internalPGTStorageFile PGT storage on the filesystem + * @ingroup internalPGTStorage */ + +/** @defgroup internalCallback Callback from the CAS server + * @ingroup internalProxy */ + +/** @defgroup internalProxied CAS proxied client features (CAS 2.0, Proxy Tickets) + * @ingroup internal */ + +/** @defgroup internalConfig Configuration + * @ingroup internal */ + +/** @defgroup internalOutput HTML output + * @ingroup internalConfig */ + +/** @defgroup internalLang Internationalization + * @ingroup internalConfig + * + * To add a new language: + * - 1. define a new constant PHPCAS_LANG_XXXXXX in CAS/CAS.php + * - 2. copy any file from CAS/languages to CAS/languages/XXXXXX.php + * - 3. Make the translations + */ + +/** @defgroup internalDebug Debugging + * @ingroup internal */ + +/** @defgroup internalMisc Miscellaneous + * @ingroup internal */ + +// ######################################################################## +// EXAMPLES + +/** + * @example example_simple.php + */ + /** + * @example example_proxy.php + */ + /** + * @example example_proxy2.php + */ + /** + * @example example_lang.php + */ + /** + * @example example_html.php + */ + /** + * @example example_file.php + */ + /** + * @example example_db.php + */ + /** + * @example example_service.php + */ + /** + * @example example_session_proxy.php + */ + /** + * @example example_session_service.php + */ + /** + * @example example_gateway.php + */ + + + +?> diff --git a/include/limesurvey/admin/classes/phpCAS/CAS/PGTStorage/pgt-db.php b/include/limesurvey/admin/classes/phpCAS/CAS/PGTStorage/pgt-db.php new file mode 100644 index 00000000..5a589e4b --- /dev/null +++ b/include/limesurvey/admin/classes/phpCAS/CAS/PGTStorage/pgt-db.php @@ -0,0 +1,190 @@ + + * + * @ingroup internalPGTStorageDB + */ + +class PGTStorageDB extends PGTStorage +{ + /** + * @addtogroup internalPGTStorageDB + * @{ + */ + + /** + * a string representing a PEAR DB URL to connect to the database. Written by + * PGTStorageDB::PGTStorageDB(), read by getURL(). + * + * @hideinitializer + * @private + */ + var $_url=''; + + /** + * This method returns the PEAR DB URL to use to connect to the database. + * + * @return a PEAR DB URL + * + * @private + */ + function getURL() + { + return $this->_url; + } + + /** + * The handle of the connection to the database where PGT's are stored. Written by + * PGTStorageDB::init(), read by getLink(). + * + * @hideinitializer + * @private + */ + var $_link = null; + + /** + * This method returns the handle of the connection to the database where PGT's are + * stored. + * + * @return a handle of connection. + * + * @private + */ + function getLink() + { + return $this->_link; + } + + /** + * The name of the table where PGT's are stored. Written by + * PGTStorageDB::PGTStorageDB(), read by getTable(). + * + * @hideinitializer + * @private + */ + var $_table = ''; + + /** + * This method returns the name of the table where PGT's are stored. + * + * @return the name of a table. + * + * @private + */ + function getTable() + { + return $this->_table; + } + + // ######################################################################## + // DEBUGGING + // ######################################################################## + + /** + * This method returns an informational string giving the type of storage + * used by the object (used for debugging purposes). + * + * @return an informational string. + * @public + */ + function getStorageType() + { + return "database"; + } + + /** + * This method returns an informational string giving informations on the + * parameters of the storage.(used for debugging purposes). + * + * @public + */ + function getStorageInfo() + { + return 'url=`'.$this->getURL().'\', table=`'.$this->getTable().'\''; + } + + // ######################################################################## + // CONSTRUCTOR + // ######################################################################## + + /** + * The class constructor, called by CASClient::SetPGTStorageDB(). + * + * @param $cas_parent the CASClient instance that creates the object. + * @param $user the user to access the data with + * @param $password the user's password + * @param $database_type the type of the database hosting the data + * @param $hostname the server hosting the database + * @param $port the port the server is listening on + * @param $database the name of the database + * @param $table the name of the table storing the data + * + * @public + */ + function PGTStorageDB($cas_parent,$user,$password,$database_type,$hostname,$port,$database,$table) + { + phpCAS::traceBegin(); + + // call the ancestor's constructor + $this->PGTStorage($cas_parent); + + if ( empty($database_type) ) $database_type = CAS_PGT_STORAGE_DB_DEFAULT_DATABASE_TYPE; + if ( empty($hostname) ) $hostname = CAS_PGT_STORAGE_DB_DEFAULT_HOSTNAME; + if ( $port==0 ) $port = CAS_PGT_STORAGE_DB_DEFAULT_PORT; + if ( empty($database) ) $database = CAS_PGT_STORAGE_DB_DEFAULT_DATABASE; + if ( empty($table) ) $table = CAS_PGT_STORAGE_DB_DEFAULT_TABLE; + + // build and store the PEAR DB URL + $this->_url = $database_type.':'.'//'.$user.':'.$password.'@'.$hostname.':'.$port.'/'.$database; + + // XXX should use setURL and setTable + phpCAS::traceEnd(); + } + + // ######################################################################## + // INITIALIZATION + // ######################################################################## + + /** + * This method is used to initialize the storage. Halts on error. + * + * @public + */ + function init() + { + phpCAS::traceBegin(); + // if the storage has already been initialized, return immediatly + if ( $this->isInitialized() ) + return; + // call the ancestor's method (mark as initialized) + parent::init(); + + //include phpDB library (the test was introduced in release 0.4.8 for + //the integration into Tikiwiki). + if (!class_exists('DB')) { + include_once('DB.php'); + } + + // try to connect to the database + $this->_link = DB::connect($this->getURL()); + if ( DB::isError($this->_link) ) { + phpCAS::error('could not connect to database ('.DB::errorMessage($this->_link).')'); + } + var_dump($this->_link); + phpCAS::traceBEnd(); + } + + /** @} */ +} + +?> \ No newline at end of file diff --git a/include/limesurvey/admin/classes/phpCAS/CAS/PGTStorage/pgt-file.php b/include/limesurvey/admin/classes/phpCAS/CAS/PGTStorage/pgt-file.php new file mode 100644 index 00000000..bc07485b --- /dev/null +++ b/include/limesurvey/admin/classes/phpCAS/CAS/PGTStorage/pgt-file.php @@ -0,0 +1,249 @@ + + * + * @ingroup internalPGTStorageFile + */ + +class PGTStorageFile extends PGTStorage +{ + /** + * @addtogroup internalPGTStorageFile + * @{ + */ + + /** + * a string telling where PGT's should be stored on the filesystem. Written by + * PGTStorageFile::PGTStorageFile(), read by getPath(). + * + * @private + */ + var $_path; + + /** + * This method returns the name of the directory where PGT's should be stored + * on the filesystem. + * + * @return the name of a directory (with leading and trailing '/') + * + * @private + */ + function getPath() + { + return $this->_path; + } + + /** + * a string telling the format to use to store PGT's (plain or xml). Written by + * PGTStorageFile::PGTStorageFile(), read by getFormat(). + * + * @private + */ + var $_format; + + /** + * This method returns the format to use when storing PGT's on the filesystem. + * + * @return a string corresponding to the format used (plain or xml). + * + * @private + */ + function getFormat() + { + return $this->_format; + } + + // ######################################################################## + // DEBUGGING + // ######################################################################## + + /** + * This method returns an informational string giving the type of storage + * used by the object (used for debugging purposes). + * + * @return an informational string. + * @public + */ + function getStorageType() + { + return "file"; + } + + /** + * This method returns an informational string giving informations on the + * parameters of the storage.(used for debugging purposes). + * + * @return an informational string. + * @public + */ + function getStorageInfo() + { + return 'path=`'.$this->getPath().'\', format=`'.$this->getFormat().'\''; + } + + // ######################################################################## + // CONSTRUCTOR + // ######################################################################## + + /** + * The class constructor, called by CASClient::SetPGTStorageFile(). + * + * @param $cas_parent the CASClient instance that creates the object. + * @param $format the format used to store the PGT's (`plain' and `xml' allowed). + * @param $path the path where the PGT's should be stored + * + * @public + */ + function PGTStorageFile($cas_parent,$format,$path) + { + phpCAS::traceBegin(); + // call the ancestor's constructor + $this->PGTStorage($cas_parent); + + if (empty($format) ) $format = CAS_PGT_STORAGE_FILE_DEFAULT_FORMAT; + if (empty($path) ) $path = CAS_PGT_STORAGE_FILE_DEFAULT_PATH; + + // check that the path is an absolute path + if (getenv("OS")=="Windows_NT"){ + + if (!preg_match('`^[a-zA-Z]:`', $path)) { + phpCAS::error('an absolute path is needed for PGT storage to file'); + } + + } + else + { + + if ( $path[0] != '/' ) { + phpCAS::error('an absolute path is needed for PGT storage to file'); + } + + // store the path (with a leading and trailing '/') + $path = preg_replace('|[/]*$|','/',$path); + $path = preg_replace('|^[/]*|','/',$path); + } + + $this->_path = $path; + // check the format and store it + switch ($format) { + case CAS_PGT_STORAGE_FILE_FORMAT_PLAIN: + case CAS_PGT_STORAGE_FILE_FORMAT_XML: + $this->_format = $format; + break; + default: + phpCAS::error('unknown PGT file storage format (`'.CAS_PGT_STORAGE_FILE_FORMAT_PLAIN.'\' and `'.CAS_PGT_STORAGE_FILE_FORMAT_XML.'\' allowed)'); + } + phpCAS::traceEnd(); + } + + // ######################################################################## + // INITIALIZATION + // ######################################################################## + + /** + * This method is used to initialize the storage. Halts on error. + * + * @public + */ + function init() + { + phpCAS::traceBegin(); + // if the storage has already been initialized, return immediatly + if ( $this->isInitialized() ) + return; + // call the ancestor's method (mark as initialized) + parent::init(); + phpCAS::traceEnd(); + } + + // ######################################################################## + // PGT I/O + // ######################################################################## + + /** + * This method returns the filename corresponding to a PGT Iou. + * + * @param $pgt_iou the PGT iou. + * + * @return a filename + * @private + */ + function getPGTIouFilename($pgt_iou) + { + phpCAS::traceBegin(); + $filename = $this->getPath().$pgt_iou.'.'.$this->getFormat(); + phpCAS::traceEnd($filename); + return $filename; + } + + /** + * This method stores a PGT and its corresponding PGT Iou into a file. Echoes a + * warning on error. + * + * @param $pgt the PGT + * @param $pgt_iou the PGT iou + * + * @public + */ + function write($pgt,$pgt_iou) + { + phpCAS::traceBegin(); + $fname = $this->getPGTIouFilename($pgt_iou); + if ( $f=fopen($fname,"w") ) { + if ( fputs($f,$pgt) === FALSE ) { + phpCAS::error('could not write PGT to `'.$fname.'\''); + } + fclose($f); + } else { + phpCAS::error('could not open `'.$fname.'\''); + } + phpCAS::traceEnd(); + } + + /** + * This method reads a PGT corresponding to a PGT Iou and deletes the + * corresponding file. + * + * @param $pgt_iou the PGT iou + * + * @return the corresponding PGT, or FALSE on error + * + * @public + */ + function read($pgt_iou) + { + phpCAS::traceBegin(); + $pgt = FALSE; + $fname = $this->getPGTIouFilename($pgt_iou); + if ( !($f=fopen($fname,"r")) ) { + phpCAS::trace('could not open `'.$fname.'\''); + } else { + if ( ($pgt=fgets($f)) === FALSE ) { + phpCAS::trace('could not read PGT from `'.$fname.'\''); + } + fclose($f); + } + + // delete the PGT file + @unlink($fname); + + phpCAS::traceEnd($pgt); + return $pgt; + } + + /** @} */ + +} + + +?> \ No newline at end of file diff --git a/include/limesurvey/admin/classes/phpCAS/CAS/PGTStorage/pgt-main.php b/include/limesurvey/admin/classes/phpCAS/CAS/PGTStorage/pgt-main.php new file mode 100644 index 00000000..cd9b4996 --- /dev/null +++ b/include/limesurvey/admin/classes/phpCAS/CAS/PGTStorage/pgt-main.php @@ -0,0 +1,188 @@ + + * + * @ingroup internalPGTStorage + */ + +class PGTStorage +{ + /** + * @addtogroup internalPGTStorage + * @{ + */ + + // ######################################################################## + // CONSTRUCTOR + // ######################################################################## + + /** + * The constructor of the class, should be called only by inherited classes. + * + * @param $cas_parent the CASclient instance that creates the current object. + * + * @protected + */ + function PGTStorage($cas_parent) + { + phpCAS::traceBegin(); + if ( !$cas_parent->isProxy() ) { + phpCAS::error('defining PGT storage makes no sense when not using a CAS proxy'); + } + phpCAS::traceEnd(); + } + + // ######################################################################## + // DEBUGGING + // ######################################################################## + + /** + * This virtual method returns an informational string giving the type of storage + * used by the object (used for debugging purposes). + * + * @public + */ + function getStorageType() + { + phpCAS::error(__CLASS__.'::'.__FUNCTION__.'() should never be called'); + } + + /** + * This virtual method returns an informational string giving informations on the + * parameters of the storage.(used for debugging purposes). + * + * @public + */ + function getStorageInfo() + { + phpCAS::error(__CLASS__.'::'.__FUNCTION__.'() should never be called'); + } + + // ######################################################################## + // ERROR HANDLING + // ######################################################################## + + /** + * string used to store an error message. Written by PGTStorage::setErrorMessage(), + * read by PGTStorage::getErrorMessage(). + * + * @hideinitializer + * @private + * @deprecated not used. + */ + var $_error_message=FALSE; + + /** + * This method sets en error message, which can be read later by + * PGTStorage::getErrorMessage(). + * + * @param $error_message an error message + * + * @protected + * @deprecated not used. + */ + function setErrorMessage($error_message) + { + $this->_error_message = $error_message; + } + + /** + * This method returns an error message set by PGTStorage::setErrorMessage(). + * + * @return an error message when set by PGTStorage::setErrorMessage(), FALSE + * otherwise. + * + * @public + * @deprecated not used. + */ + function getErrorMessage() + { + return $this->_error_message; + } + + // ######################################################################## + // INITIALIZATION + // ######################################################################## + + /** + * a boolean telling if the storage has already been initialized. Written by + * PGTStorage::init(), read by PGTStorage::isInitialized(). + * + * @hideinitializer + * @private + */ + var $_initialized = FALSE; + + /** + * This method tells if the storage has already been intialized. + * + * @return a boolean + * + * @protected + */ + function isInitialized() + { + return $this->_initialized; + } + + /** + * This virtual method initializes the object. + * + * @protected + */ + function init() + { + $this->_initialized = TRUE; + } + + // ######################################################################## + // PGT I/O + // ######################################################################## + + /** + * This virtual method stores a PGT and its corresponding PGT Iuo. + * @note Should never be called. + * + * @param $pgt the PGT + * @param $pgt_iou the PGT iou + * + * @protected + */ + function write($pgt,$pgt_iou) + { + phpCAS::error(__CLASS__.'::'.__FUNCTION__.'() should never be called'); + } + + /** + * This virtual method reads a PGT corresponding to a PGT Iou and deletes + * the corresponding storage entry. + * @note Should never be called. + * + * @param $pgt_iou the PGT iou + * + * @protected + */ + function read($pgt_iou) + { + phpCAS::error(__CLASS__.'::'.__FUNCTION__.'() should never be called'); + } + + /** @} */ + +} + +// include specific PGT storage classes +include_once(dirname(__FILE__).'/pgt-file.php'); +include_once(dirname(__FILE__).'/pgt-db.php'); + +?> \ No newline at end of file diff --git a/include/limesurvey/admin/classes/phpCAS/CAS/client.php b/include/limesurvey/admin/classes/phpCAS/CAS/client.php new file mode 100644 index 00000000..bfea5905 --- /dev/null +++ b/include/limesurvey/admin/classes/phpCAS/CAS/client.php @@ -0,0 +1,2297 @@ + + */ + +class CASClient +{ + + // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX + // XX XX + // XX CONFIGURATION XX + // XX XX + // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX + + // ######################################################################## + // HTML OUTPUT + // ######################################################################## + /** + * @addtogroup internalOutput + * @{ + */ + + /** + * This method filters a string by replacing special tokens by appropriate values + * and prints it. The corresponding tokens are taken into account: + * - __CAS_VERSION__ + * - __PHPCAS_VERSION__ + * - __SERVER_BASE_URL__ + * + * Used by CASClient::PrintHTMLHeader() and CASClient::printHTMLFooter(). + * + * @param $str the string to filter and output + * + * @private + */ + function HTMLFilterOutput($str) + { + $str = str_replace('__CAS_VERSION__',$this->getServerVersion(),$str); + $str = str_replace('__PHPCAS_VERSION__',phpCAS::getVersion(),$str); + $str = str_replace('__SERVER_BASE_URL__',$this->getServerBaseURL(),$str); + echo $str; + } + + /** + * A string used to print the header of HTML pages. Written by CASClient::setHTMLHeader(), + * read by CASClient::printHTMLHeader(). + * + * @hideinitializer + * @private + * @see CASClient::setHTMLHeader, CASClient::printHTMLHeader() + */ + var $_output_header = ''; + + /** + * This method prints the header of the HTML output (after filtering). If + * CASClient::setHTMLHeader() was not used, a default header is output. + * + * @param $title the title of the page + * + * @see HTMLFilterOutput() + * @private + */ + function printHTMLHeader($title) + { + $this->HTMLFilterOutput(str_replace('__TITLE__', + $title, + (empty($this->_output_header) + ? '__TITLE__

    __TITLE__

    ' + : $this->_output_header) + ) + ); + } + + /** + * A string used to print the footer of HTML pages. Written by CASClient::setHTMLFooter(), + * read by printHTMLFooter(). + * + * @hideinitializer + * @private + * @see CASClient::setHTMLFooter, CASClient::printHTMLFooter() + */ + var $_output_footer = ''; + + /** + * This method prints the footer of the HTML output (after filtering). If + * CASClient::setHTMLFooter() was not used, a default footer is output. + * + * @see HTMLFilterOutput() + * @private + */ + function printHTMLFooter() + { + $this->HTMLFilterOutput(empty($this->_output_footer) + ?('
    phpCAS __PHPCAS_VERSION__ '.$this->getString(CAS_STR_USING_SERVER).' __SERVER_BASE_URL__ (CAS __CAS_VERSION__)
    ') + :$this->_output_footer); + } + + /** + * This method set the HTML header used for all outputs. + * + * @param $header the HTML header. + * + * @public + */ + function setHTMLHeader($header) + { + $this->_output_header = $header; + } + + /** + * This method set the HTML footer used for all outputs. + * + * @param $footer the HTML footer. + * + * @public + */ + function setHTMLFooter($footer) + { + $this->_output_footer = $footer; + } + + /** @} */ + // ######################################################################## + // INTERNATIONALIZATION + // ######################################################################## + /** + * @addtogroup internalLang + * @{ + */ + /** + * A string corresponding to the language used by phpCAS. Written by + * CASClient::setLang(), read by CASClient::getLang(). + + * @note debugging information is always in english (debug purposes only). + * + * @hideinitializer + * @private + * @sa CASClient::_strings, CASClient::getString() + */ + var $_lang = ''; + + /** + * This method returns the language used by phpCAS. + * + * @return a string representing the language + * + * @private + */ + function getLang() + { + if ( empty($this->_lang) ) + $this->setLang(PHPCAS_LANG_DEFAULT); + return $this->_lang; + } + + /** + * array containing the strings used by phpCAS. Written by CASClient::setLang(), read by + * CASClient::getString() and used by CASClient::setLang(). + * + * @note This array is filled by instructions in CAS/languages/<$this->_lang>.php + * + * @private + * @see CASClient::_lang, CASClient::getString(), CASClient::setLang(), CASClient::getLang() + */ + var $_strings; + + /** + * This method returns a string depending on the language. + * + * @param $str the index of the string in $_string. + * + * @return the string corresponding to $index in $string. + * + * @private + */ + function getString($str) + { + // call CASclient::getLang() to be sure the language is initialized + $this->getLang(); + + if ( !isset($this->_strings[$str]) ) { + trigger_error('string `'.$str.'\' not defined for language `'.$this->getLang().'\'',E_USER_ERROR); + } + return $this->_strings[$str]; + } + + /** + * This method is used to set the language used by phpCAS. + * @note Can be called only once. + * + * @param $lang a string representing the language. + * + * @public + * @sa CAS_LANG_FRENCH, CAS_LANG_ENGLISH + */ + function setLang($lang) + { + // include the corresponding language file + include_once(dirname(__FILE__).'/languages/'.$lang.'.php'); + + if ( !is_array($this->_strings) ) { + trigger_error('language `'.$lang.'\' is not implemented',E_USER_ERROR); + } + $this->_lang = $lang; + } + + /** @} */ + // ######################################################################## + // CAS SERVER CONFIG + // ######################################################################## + /** + * @addtogroup internalConfig + * @{ + */ + + /** + * a record to store information about the CAS server. + * - $_server["version"]: the version of the CAS server + * - $_server["hostname"]: the hostname of the CAS server + * - $_server["port"]: the port the CAS server is running on + * - $_server["uri"]: the base URI the CAS server is responding on + * - $_server["base_url"]: the base URL of the CAS server + * - $_server["login_url"]: the login URL of the CAS server + * - $_server["service_validate_url"]: the service validating URL of the CAS server + * - $_server["proxy_url"]: the proxy URL of the CAS server + * - $_server["proxy_validate_url"]: the proxy validating URL of the CAS server + * - $_server["logout_url"]: the logout URL of the CAS server + * + * $_server["version"], $_server["hostname"], $_server["port"] and $_server["uri"] + * are written by CASClient::CASClient(), read by CASClient::getServerVersion(), + * CASClient::getServerHostname(), CASClient::getServerPort() and CASClient::getServerURI(). + * + * The other fields are written and read by CASClient::getServerBaseURL(), + * CASClient::getServerLoginURL(), CASClient::getServerServiceValidateURL(), + * CASClient::getServerProxyValidateURL() and CASClient::getServerLogoutURL(). + * + * @hideinitializer + * @private + */ + var $_server = array( + 'version' => -1, + 'hostname' => 'none', + 'port' => -1, + 'uri' => 'none' + ); + + /** + * This method is used to retrieve the version of the CAS server. + * @return the version of the CAS server. + * @private + */ + function getServerVersion() + { + return $this->_server['version']; + } + + /** + * This method is used to retrieve the hostname of the CAS server. + * @return the hostname of the CAS server. + * @private + */ + function getServerHostname() + { return $this->_server['hostname']; } + + /** + * This method is used to retrieve the port of the CAS server. + * @return the port of the CAS server. + * @private + */ + function getServerPort() + { return $this->_server['port']; } + + /** + * This method is used to retrieve the URI of the CAS server. + * @return a URI. + * @private + */ + function getServerURI() + { return $this->_server['uri']; } + + /** + * This method is used to retrieve the base URL of the CAS server. + * @return a URL. + * @private + */ + function getServerBaseURL() + { + // the URL is build only when needed + if ( empty($this->_server['base_url']) ) { + $this->_server['base_url'] = 'https://' + .$this->getServerHostname() + .':' + .$this->getServerPort() + .$this->getServerURI(); + } + return $this->_server['base_url']; + } + + /** + * This method is used to retrieve the login URL of the CAS server. + * @param $gateway true to check authentication, false to force it + * @param $renew true to force the authentication with the CAS server + * NOTE : It is recommended that CAS implementations ignore the + "gateway" parameter if "renew" is set + * @return a URL. + * @private + */ + function getServerLoginURL($gateway=false,$renew=false) { + phpCAS::traceBegin(); + // the URL is build only when needed + if ( empty($this->_server['login_url']) ) { + $this->_server['login_url'] = $this->getServerBaseURL(); + $this->_server['login_url'] .= 'login?service='; + // $this->_server['login_url'] .= preg_replace('/&/','%26',$this->getURL()); + $this->_server['login_url'] .= urlencode($this->getURL()); + if($renew) { + // It is recommended that when the "renew" parameter is set, its value be "true" + $this->_server['login_url'] .= '&renew=true'; + } elseif ($gateway) { + // It is recommended that when the "gateway" parameter is set, its value be "true" + $this->_server['login_url'] .= '&gateway=true'; + } + } + phpCAS::traceEnd($this->_server['login_url']); + return $this->_server['login_url']; + } + + /** + * This method sets the login URL of the CAS server. + * @param $url the login URL + * @private + * @since 0.4.21 by Wyman Chan + */ + function setServerLoginURL($url) + { + return $this->_server['login_url'] = $url; + } + + /** + * This method is used to retrieve the service validating URL of the CAS server. + * @return a URL. + * @private + */ + function getServerServiceValidateURL() + { + // the URL is build only when needed + if ( empty($this->_server['service_validate_url']) ) { + switch ($this->getServerVersion()) { + case CAS_VERSION_1_0: + $this->_server['service_validate_url'] = $this->getServerBaseURL().'validate'; + break; + case CAS_VERSION_2_0: + $this->_server['service_validate_url'] = $this->getServerBaseURL().'serviceValidate'; + break; + } + } + // return $this->_server['service_validate_url'].'?service='.preg_replace('/&/','%26',$this->getURL()); + return $this->_server['service_validate_url'].'?service='.urlencode($this->getURL()); + } + + /** + * This method is used to retrieve the proxy validating URL of the CAS server. + * @return a URL. + * @private + */ + function getServerProxyValidateURL() + { + // the URL is build only when needed + if ( empty($this->_server['proxy_validate_url']) ) { + switch ($this->getServerVersion()) { + case CAS_VERSION_1_0: + $this->_server['proxy_validate_url'] = ''; + break; + case CAS_VERSION_2_0: + $this->_server['proxy_validate_url'] = $this->getServerBaseURL().'proxyValidate'; + break; + } + } + // return $this->_server['proxy_validate_url'].'?service='.preg_replace('/&/','%26',$this->getURL()); + return $this->_server['proxy_validate_url'].'?service='.urlencode($this->getURL()); + } + + /** + * This method is used to retrieve the proxy URL of the CAS server. + * @return a URL. + * @private + */ + function getServerProxyURL() + { + // the URL is build only when needed + if ( empty($this->_server['proxy_url']) ) { + switch ($this->getServerVersion()) { + case CAS_VERSION_1_0: + $this->_server['proxy_url'] = ''; + break; + case CAS_VERSION_2_0: + $this->_server['proxy_url'] = $this->getServerBaseURL().'proxy'; + break; + } + } + return $this->_server['proxy_url']; + } + + /** + * This method is used to retrieve the logout URL of the CAS server. + * @return a URL. + * @private + */ + function getServerLogoutURL() + { + // the URL is build only when needed + if ( empty($this->_server['logout_url']) ) { + $this->_server['logout_url'] = $this->getServerBaseURL().'logout'; + } + return $this->_server['logout_url']; + } + + /** + * This method sets the logout URL of the CAS server. + * @param $url the logout URL + * @private + * @since 0.4.21 by Wyman Chan + */ + function setServerLogoutURL($url) + { + return $this->_server['logout_url'] = $url; + } + + /** + * An array to store extra curl options. + */ + var $_curl_options = array(); + + /** + * This method is used to set additional user curl options. + */ + function setExtraCurlOption($key, $value) + { + $this->_curl_options[$key] = $value; + } + + /** + * This method checks to see if the request is secured via HTTPS + * @return true if https, false otherwise + * @private + */ + function isHttps() { + //if ( isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) ) { + //0.4.24 by Hinnack + if ( isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') { + return true; + } else { + return false; + } + } + + // ######################################################################## + // CONSTRUCTOR + // ######################################################################## + /** + * CASClient constructor. + * + * @param $server_version the version of the CAS server + * @param $proxy TRUE if the CAS client is a CAS proxy, FALSE otherwise + * @param $server_hostname the hostname of the CAS server + * @param $server_port the port the CAS server is running on + * @param $server_uri the URI the CAS server is responding on + * @param $start_session Have phpCAS start PHP sessions (default true) + * + * @return a newly created CASClient object + * + * @public + */ + function CASClient( + $server_version, + $proxy, + $server_hostname, + $server_port, + $server_uri, + $start_session = true) { + + phpCAS::traceBegin(); + + if (!$this->isLogoutRequest() && !empty($_GET['ticket']) && $start_session) { + // copy old session vars and destroy the current session + if (!isset($_SESSION)) { + session_start(); + } + $old_session = $_SESSION; + session_destroy(); + // set up a new session, of name based on the ticket + $session_id = preg_replace('/[^\w]/','',$_GET['ticket']); + phpCAS::LOG("Session ID: " . $session_id); + session_id($session_id); + if (!isset($_SESSION)) { + session_start(); + } + // restore old session vars + $_SESSION = $old_session; + // Redirect to location without ticket. + header('Location: '.$this->getURL()); + } + + //activate session mechanism if desired + if (!$this->isLogoutRequest() && $start_session) { + session_start(); + } + + $this->_proxy = $proxy; + + //check version + switch ($server_version) { + case CAS_VERSION_1_0: + if ( $this->isProxy() ) + phpCAS::error('CAS proxies are not supported in CAS ' + .$server_version); + break; + case CAS_VERSION_2_0: + break; + default: + phpCAS::error('this version of CAS (`' + .$server_version + .'\') is not supported by phpCAS ' + .phpCAS::getVersion()); + } + $this->_server['version'] = $server_version; + + //check hostname + if ( empty($server_hostname) + || !preg_match('/[\.\d\-abcdefghijklmnopqrstuvwxyz]*/',$server_hostname) ) { + phpCAS::error('bad CAS server hostname (`'.$server_hostname.'\')'); + } + $this->_server['hostname'] = $server_hostname; + + //check port + if ( $server_port == 0 + || !is_int($server_port) ) { + phpCAS::error('bad CAS server port (`'.$server_hostname.'\')'); + } + $this->_server['port'] = $server_port; + + //check URI + if ( !preg_match('/[\.\d\-_abcdefghijklmnopqrstuvwxyz\/]*/',$server_uri) ) { + phpCAS::error('bad CAS server URI (`'.$server_uri.'\')'); + } + //add leading and trailing `/' and remove doubles + $server_uri = preg_replace('/\/\//','/','/'.$server_uri.'/'); + $this->_server['uri'] = $server_uri; + + //set to callback mode if PgtIou and PgtId CGI GET parameters are provided + if ( $this->isProxy() ) { + $this->setCallbackMode(!empty($_GET['pgtIou'])&&!empty($_GET['pgtId'])); + } + + if ( $this->isCallbackMode() ) { + //callback mode: check that phpCAS is secured + if ( !$this->isHttps() ) { + phpCAS::error('CAS proxies must be secured to use phpCAS; PGT\'s will not be received from the CAS server'); + } + } else { + //normal mode: get ticket and remove it from CGI parameters for developpers + $ticket = (isset($_GET['ticket']) ? $_GET['ticket'] : null); + switch ($this->getServerVersion()) { + case CAS_VERSION_1_0: // check for a Service Ticket + if( preg_match('/^ST-/',$ticket) ) { + phpCAS::trace('ST \''.$ticket.'\' found'); + //ST present + $this->setST($ticket); + //ticket has been taken into account, unset it to hide it to applications + unset($_GET['ticket']); + } else if ( !empty($ticket) ) { + //ill-formed ticket, halt + phpCAS::error('ill-formed ticket found in the URL (ticket=`'.htmlentities($ticket).'\')'); + } + break; + case CAS_VERSION_2_0: // check for a Service or Proxy Ticket + if( preg_match('/^[SP]T-/',$ticket) ) { + phpCAS::trace('ST or PT \''.$ticket.'\' found'); + $this->setPT($ticket); + unset($_GET['ticket']); + } else if ( !empty($ticket) ) { + //ill-formed ticket, halt + phpCAS::error('ill-formed ticket found in the URL (ticket=`'.htmlentities($ticket).'\')'); + } + break; + } + } + phpCAS::traceEnd(); + } + + /** @} */ + + // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX + // XX XX + // XX AUTHENTICATION XX + // XX XX + // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX + + /** + * @addtogroup internalAuthentication + * @{ + */ + + /** + * The Authenticated user. Written by CASClient::setUser(), read by CASClient::getUser(). + * @attention client applications should use phpCAS::getUser(). + * + * @hideinitializer + * @private + */ + var $_user = ''; + + /** + * This method sets the CAS user's login name. + * + * @param $user the login name of the authenticated user. + * + * @private + */ + function setUser($user) + { + $this->_user = $user; + } + + /** + * This method returns the CAS user's login name. + * @warning should be called only after CASClient::forceAuthentication() or + * CASClient::isAuthenticated(), otherwise halt with an error. + * + * @return the login name of the authenticated user + */ + function getUser() + { + if ( empty($this->_user) ) { + phpCAS::error('this method should be used only after '.__CLASS__.'::forceAuthentication() or '.__CLASS__.'::isAuthenticated()'); + } + return $this->_user; + } + + /** + * This method is called to renew the authentication of the user + * If the user is authenticated, renew the connection + * If not, redirect to CAS + * @public + */ + function renewAuthentication(){ + phpCAS::traceBegin(); + // Either way, the user is authenticated by CAS + if( isset( $_SESSION['phpCAS']['auth_checked'] ) ) + unset($_SESSION['phpCAS']['auth_checked']); + if ( $this->isAuthenticated() ) { + phpCAS::trace('user already authenticated; renew'); + $this->redirectToCas(false,true); + } else { + $this->redirectToCas(); + } + phpCAS::traceEnd(); + } + + /** + * This method is called to be sure that the user is authenticated. When not + * authenticated, halt by redirecting to the CAS server; otherwise return TRUE. + * @return TRUE when the user is authenticated; otherwise halt. + * @public + */ + function forceAuthentication() + { + phpCAS::traceBegin(); + + if ( $this->isAuthenticated() ) { + // the user is authenticated, nothing to be done. + phpCAS::trace('no need to authenticate'); + $res = TRUE; + } else { + // the user is not authenticated, redirect to the CAS server + if (isset($_SESSION['phpCAS']['auth_checked'])) { + unset($_SESSION['phpCAS']['auth_checked']); + } + $this->redirectToCas(FALSE/* no gateway */); + // never reached + $res = FALSE; + } + phpCAS::traceEnd($res); + return $res; + } + + /** + * An integer that gives the number of times authentication will be cached before rechecked. + * + * @hideinitializer + * @private + */ + var $_cache_times_for_auth_recheck = 0; + + /** + * Set the number of times authentication will be cached before rechecked. + * + * @param $n an integer. + * + * @public + */ + function setCacheTimesForAuthRecheck($n) + { + $this->_cache_times_for_auth_recheck = $n; + } + + /** + * This method is called to check whether the user is authenticated or not. + * @return TRUE when the user is authenticated, FALSE otherwise. + * @public + */ + function checkAuthentication() + { + phpCAS::traceBegin(); + + if ( $this->isAuthenticated() ) { + phpCAS::trace('user is authenticated'); + $res = TRUE; + } else if (isset($_SESSION['phpCAS']['auth_checked'])) { + // the previous request has redirected the client to the CAS server with gateway=true + unset($_SESSION['phpCAS']['auth_checked']); + $res = FALSE; + } else { + // $_SESSION['phpCAS']['auth_checked'] = true; + // $this->redirectToCas(TRUE/* gateway */); + // // never reached + // $res = FALSE; + // avoid a check against CAS on every request + if (! isset($_SESSION['phpCAS']['unauth_count']) ) + $_SESSION['phpCAS']['unauth_count'] = -2; // uninitialized + + if (($_SESSION['phpCAS']['unauth_count'] != -2 && $this->_cache_times_for_auth_recheck == -1) + || ($_SESSION['phpCAS']['unauth_count'] >= 0 && $_SESSION['phpCAS']['unauth_count'] < $this->_cache_times_for_auth_recheck)) + { + $res = FALSE; + + if ($this->_cache_times_for_auth_recheck != -1) + { + $_SESSION['phpCAS']['unauth_count']++; + phpCAS::trace('user is not authenticated (cached for '.$_SESSION['phpCAS']['unauth_count'].' times of '.$this->_cache_times_for_auth_recheck.')'); + } + else + { + phpCAS::trace('user is not authenticated (cached for until login pressed)'); + } + } + else + { + $_SESSION['phpCAS']['unauth_count'] = 0; + $_SESSION['phpCAS']['auth_checked'] = true; + phpCAS::trace('user is not authenticated (cache reset)'); + $this->redirectToCas(TRUE/* gateway */); + // never reached + $res = FALSE; + } + } + phpCAS::traceEnd($res); + return $res; + } + + /** + * This method is called to check if the user is authenticated (previously or by + * tickets given in the URL). + * + * @return TRUE when the user is authenticated. + * + * @public + */ + function isAuthenticated() + { + phpCAS::traceBegin(); + $res = FALSE; + $validate_url = ''; + + if ( $this->wasPreviouslyAuthenticated() ) { + // the user has already (previously during the session) been + // authenticated, nothing to be done. + phpCAS::trace('user was already authenticated, no need to look for tickets'); + $res = TRUE; + } + elseif ( $this->hasST() ) { + // if a Service Ticket was given, validate it + phpCAS::trace('ST `'.$this->getST().'\' is present'); + $this->validateST($validate_url,$text_response,$tree_response); // if it fails, it halts + phpCAS::trace('ST `'.$this->getST().'\' was validated'); + if ( $this->isProxy() ) { + $this->validatePGT($validate_url,$text_response,$tree_response); // idem + phpCAS::trace('PGT `'.$this->getPGT().'\' was validated'); + $_SESSION['phpCAS']['pgt'] = $this->getPGT(); + } + $_SESSION['phpCAS']['user'] = $this->getUser(); + $res = TRUE; + } + elseif ( $this->hasPT() ) { + // if a Proxy Ticket was given, validate it + phpCAS::trace('PT `'.$this->getPT().'\' is present'); + $this->validatePT($validate_url,$text_response,$tree_response); // note: if it fails, it halts + phpCAS::trace('PT `'.$this->getPT().'\' was validated'); + if ( $this->isProxy() ) { + $this->validatePGT($validate_url,$text_response,$tree_response); // idem + phpCAS::trace('PGT `'.$this->getPGT().'\' was validated'); + $_SESSION['phpCAS']['pgt'] = $this->getPGT(); + } + $_SESSION['phpCAS']['user'] = $this->getUser(); + $res = TRUE; + } + else { + // no ticket given, not authenticated + phpCAS::trace('no ticket found'); + } + + phpCAS::traceEnd($res); + return $res; + } + + /** + * This method tells if the current session is authenticated. + * @return true if authenticated based soley on $_SESSION variable + * @since 0.4.22 by Brendan Arnold + */ + function isSessionAuthenticated () + { + return !empty($_SESSION['phpCAS']['user']); + } + + /** + * This method tells if the user has already been (previously) authenticated + * by looking into the session variables. + * + * @note This function switches to callback mode when needed. + * + * @return TRUE when the user has already been authenticated; FALSE otherwise. + * + * @private + */ + function wasPreviouslyAuthenticated() + { + phpCAS::traceBegin(); + + if ( $this->isCallbackMode() ) { + $this->callback(); + } + + $auth = FALSE; + + if ( $this->isProxy() ) { + // CAS proxy: username and PGT must be present + if ( $this->isSessionAuthenticated() && !empty($_SESSION['phpCAS']['pgt']) ) { + // authentication already done + $this->setUser($_SESSION['phpCAS']['user']); + $this->setPGT($_SESSION['phpCAS']['pgt']); + phpCAS::trace('user = `'.$_SESSION['phpCAS']['user'].'\', PGT = `'.$_SESSION['phpCAS']['pgt'].'\''); + $auth = TRUE; + } elseif ( $this->isSessionAuthenticated() && empty($_SESSION['phpCAS']['pgt']) ) { + // these two variables should be empty or not empty at the same time + phpCAS::trace('username found (`'.$_SESSION['phpCAS']['user'].'\') but PGT is empty'); + // unset all tickets to enforce authentication + unset($_SESSION['phpCAS']); + $this->setST(''); + $this->setPT(''); + } elseif ( !$this->isSessionAuthenticated() && !empty($_SESSION['phpCAS']['pgt']) ) { + // these two variables should be empty or not empty at the same time + phpCAS::trace('PGT found (`'.$_SESSION['phpCAS']['pgt'].'\') but username is empty'); + // unset all tickets to enforce authentication + unset($_SESSION['phpCAS']); + $this->setST(''); + $this->setPT(''); + } else { + phpCAS::trace('neither user not PGT found'); + } + } else { + // `simple' CAS client (not a proxy): username must be present + if ( $this->isSessionAuthenticated() ) { + // authentication already done + $this->setUser($_SESSION['phpCAS']['user']); + phpCAS::trace('user = `'.$_SESSION['phpCAS']['user'].'\''); + $auth = TRUE; + } else { + phpCAS::trace('no user found'); + } + } + + phpCAS::traceEnd($auth); + return $auth; + } + + /** + * This method is used to redirect the client to the CAS server. + * It is used by CASClient::forceAuthentication() and CASClient::checkAuthentication(). + * @param $gateway true to check authentication, false to force it + * @param $renew true to force the authentication with the CAS server + * @public + */ + function redirectToCas($gateway=false,$renew=false){ + phpCAS::traceBegin(); + $cas_url = $this->getServerLoginURL($gateway,$renew); + header('Location: '.$cas_url); + phpCAS::log( "Redirect to : ".$cas_url ); + + $this->printHTMLHeader($this->getString(CAS_STR_AUTHENTICATION_WANTED)); + + printf('

    '.$this->getString(CAS_STR_SHOULD_HAVE_BEEN_REDIRECTED).'

    ',$cas_url); + $this->printHTMLFooter(); + phpCAS::traceExit(); + exit(); + } + +// /** +// * This method is used to logout from CAS. +// * @param $url a URL that will be transmitted to the CAS server (to come back to when logged out) +// * @public +// */ +// function logout($url = "") { +// phpCAS::traceBegin(); +// $cas_url = $this->getServerLogoutURL(); +// // v0.4.14 sebastien.gougeon at univ-rennes1.fr +// // header('Location: '.$cas_url); +// if ( $url != "" ) { +// // Adam Moore 1.0.0RC2 +// $url = '?service=' . $url . '&url=' . $url; +// } +// header('Location: '.$cas_url . $url); +// session_unset(); +// session_destroy(); +// $this->printHTMLHeader($this->getString(CAS_STR_LOGOUT)); +// printf('

    '.$this->getString(CAS_STR_SHOULD_HAVE_BEEN_REDIRECTED).'

    ',$cas_url); +// $this->printHTMLFooter(); +// phpCAS::traceExit(); +// exit(); +// } + + /** + * This method is used to logout from CAS. + * @params $params an array that contains the optional url and service parameters that will be passed to the CAS server + * @public + */ + function logout($params) { + phpCAS::traceBegin(); + $cas_url = $this->getServerLogoutURL(); + $paramSeparator = '?'; + if (isset($params['url'])) { + $cas_url = $cas_url . $paramSeparator . "url=" . urlencode($params['url']); + $paramSeparator = '&'; + } + if (isset($params['service'])) { + $cas_url = $cas_url . $paramSeparator . "service=" . urlencode($params['service']); + } + header('Location: '.$cas_url); + session_unset(); + session_destroy(); + $this->printHTMLHeader($this->getString(CAS_STR_LOGOUT)); + printf('

    '.$this->getString(CAS_STR_SHOULD_HAVE_BEEN_REDIRECTED).'

    ',$cas_url); + $this->printHTMLFooter(); + phpCAS::traceExit(); + exit(); + } + + /** + * @return true if the current request is a logout request. + * @private + */ + function isLogoutRequest() { + return !empty($_POST['logoutRequest']); + } + + /** + * @return true if a logout request is allowed. + * @private + */ + function isLogoutRequestAllowed() { + } + + /** + * This method handles logout requests. + * @param $check_client true to check the client bofore handling the request, + * false not to perform any access control. True by default. + * @param $allowed_clients an array of host names allowed to send logout requests. + * By default, only the CAs server (declared in the constructor) will be allowed. + * @public + */ + function handleLogoutRequests($check_client=true, $allowed_clients=false) { + phpCAS::traceBegin(); + if (!$this->isLogoutRequest()) { + phpCAS::log("Not a logout request"); + phpCAS::traceEnd(); + return; + } + phpCAS::log("Logout requested"); + phpCAS::log("SAML REQUEST: ".$_POST['logoutRequest']); + if ($check_client) { + if (!$allowed_clients) { + $allowed_clients = array( $this->getServerHostname() ); + } + $client_ip = $_SERVER['REMOTE_ADDR']; + $client = gethostbyaddr($client_ip); + phpCAS::log("Client: ".$client); + $allowed = false; + foreach ($allowed_clients as $allowed_client) { + if ($client == $allowed_client) { + phpCAS::log("Allowed client '".$allowed_client."' matches, logout request is allowed"); + $allowed = true; + break; + } else { + phpCAS::log("Allowed client '".$allowed_client."' does not match"); + } + } + if (!$allowed) { + phpCAS::error("Unauthorized logout request from client '".$client."'"); + printf("Unauthorized!"); + phpCAS::traceExit(); + exit(); + } + } else { + phpCAS::log("No access control set"); + } + // Extract the ticket from the SAML Request + preg_match("|(.*)|", $_POST['logoutRequest'], $tick, PREG_OFFSET_CAPTURE, 3); + $wrappedSamlSessionIndex = preg_replace('||','',$tick[0][0]); + $ticket2logout = preg_replace('||','',$wrappedSamlSessionIndex); + phpCAS::log("Ticket to logout: ".$ticket2logout); + $session_id = preg_replace('/[^\w]/','',$ticket2logout); + phpCAS::log("Session id: ".$session_id); + + // fix New session ID + session_id($session_id); + $_COOKIE[session_name()]=$session_id; + $_GET[session_name()]=$session_id; + + // Overwrite session + session_start(); + session_unset(); + session_destroy(); + printf("Disconnected!"); + phpCAS::traceExit(); + exit(); + } + + /** @} */ + + // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX + // XX XX + // XX BASIC CLIENT FEATURES (CAS 1.0) XX + // XX XX + // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX + + // ######################################################################## + // ST + // ######################################################################## + /** + * @addtogroup internalBasic + * @{ + */ + + /** + * the Service Ticket provided in the URL of the request if present + * (empty otherwise). Written by CASClient::CASClient(), read by + * CASClient::getST() and CASClient::hasPGT(). + * + * @hideinitializer + * @private + */ + var $_st = ''; + + /** + * This method returns the Service Ticket provided in the URL of the request. + * @return The service ticket. + * @private + */ + function getST() + { return $this->_st; } + + /** + * This method stores the Service Ticket. + * @param $st The Service Ticket. + * @private + */ + function setST($st) + { $this->_st = $st; } + + /** + * This method tells if a Service Ticket was stored. + * @return TRUE if a Service Ticket has been stored. + * @private + */ + function hasST() + { return !empty($this->_st); } + + /** @} */ + + // ######################################################################## + // ST VALIDATION + // ######################################################################## + /** + * @addtogroup internalBasic + * @{ + */ + + /** + * the certificate of the CAS server. + * + * @hideinitializer + * @private + */ + var $_cas_server_cert = ''; + + /** + * the certificate of the CAS server CA. + * + * @hideinitializer + * @private + */ + var $_cas_server_ca_cert = ''; + + /** + * Set to true not to validate the CAS server. + * + * @hideinitializer + * @private + */ + var $_no_cas_server_validation = false; + + /** + * Set the certificate of the CAS server. + * + * @param $cert the PEM certificate + */ + function setCasServerCert($cert) + { + $this->_cas_server_cert = $cert; + } + + /** + * Set the CA certificate of the CAS server. + * + * @param $cert the PEM certificate of the CA that emited the cert of the server + */ + function setCasServerCACert($cert) + { + $this->_cas_server_ca_cert = $cert; + } + + /** + * Set no SSL validation for the CAS server. + */ + function setNoCasServerValidation() + { + $this->_no_cas_server_validation = true; + } + + /** + * This method is used to validate a ST; halt on failure, and sets $validate_url, + * $text_reponse and $tree_response on success. These parameters are used later + * by CASClient::validatePGT() for CAS proxies. + * + * @param $validate_url the URL of the request to the CAS server. + * @param $text_response the response of the CAS server, as is (XML text). + * @param $tree_response the response of the CAS server, as a DOM XML tree. + * + * @return bool TRUE when successfull, halt otherwise by calling CASClient::authError(). + * + * @private + */ + function validateST($validate_url,&$text_response,&$tree_response) + { + phpCAS::traceBegin(); + // build the URL to validate the ticket + $validate_url = $this->getServerServiceValidateURL().'&ticket='.$this->getST(); + if ( $this->isProxy() ) { + // pass the callback url for CAS proxies + $validate_url .= '&pgtUrl='.$this->getCallbackURL(); + } + + // open and read the URL + if ( !$this->readURL($validate_url,''/*cookies*/,$headers,$text_response,$err_msg) ) { + phpCAS::trace('could not open URL \''.$validate_url.'\' to validate ('.$err_msg.')'); + $this->authError('ST not validated', + $validate_url, + TRUE/*$no_response*/); + } + + // analyze the result depending on the version + switch ($this->getServerVersion()) { + case CAS_VERSION_1_0: + if (preg_match('/^no\n/',$text_response)) { + phpCAS::trace('ST has not been validated'); + $this->authError('ST not validated', + $validate_url, + FALSE/*$no_response*/, + FALSE/*$bad_response*/, + $text_response); + } + if (!preg_match('/^yes\n/',$text_response)) { + phpCAS::trace('ill-formed response'); + $this->authError('ST not validated', + $validate_url, + FALSE/*$no_response*/, + TRUE/*$bad_response*/, + $text_response); + } + // ST has been validated, extract the user name + $arr = preg_split('/\n/',$text_response); + $this->setUser(trim($arr[1])); + break; + case CAS_VERSION_2_0: + // read the response of the CAS server into a DOM object + if ( !($dom = domxml_open_mem($text_response))) { + phpCAS::trace('domxml_open_mem() failed'); + $this->authError('ST not validated', + $validate_url, + FALSE/*$no_response*/, + TRUE/*$bad_response*/, + $text_response); + } + // read the root node of the XML tree + if ( !($tree_response = $dom->document_element()) ) { + phpCAS::trace('document_element() failed'); + $this->authError('ST not validated', + $validate_url, + FALSE/*$no_response*/, + TRUE/*$bad_response*/, + $text_response); + } + // insure that tag name is 'serviceResponse' + if ( $tree_response->node_name() != 'serviceResponse' ) { + phpCAS::trace('bad XML root node (should be `serviceResponse\' instead of `'.$tree_response->node_name().'\''); + $this->authError('ST not validated', + $validate_url, + FALSE/*$no_response*/, + TRUE/*$bad_response*/, + $text_response); + } + if ( sizeof($success_elements = $tree_response->get_elements_by_tagname("authenticationSuccess")) != 0) { + // authentication succeded, extract the user name + if ( sizeof($user_elements = $success_elements[0]->get_elements_by_tagname("user")) == 0) { + phpCAS::trace(' found, but no '); + $this->authError('ST not validated', + $validate_url, + FALSE/*$no_response*/, + TRUE/*$bad_response*/, + $text_response); + } + $user = trim($user_elements[0]->get_content()); + phpCAS::trace('user = `'.$user); + $this->setUser($user); + + } else if ( sizeof($failure_elements = $tree_response->get_elements_by_tagname("authenticationFailure")) != 0) { + phpCAS::trace(' found'); + // authentication failed, extract the error code and message + $this->authError('ST not validated', + $validate_url, + FALSE/*$no_response*/, + FALSE/*$bad_response*/, + $text_response, + $failure_elements[0]->get_attribute('code')/*$err_code*/, + trim($failure_elements[0]->get_content())/*$err_msg*/); + } else { + phpCAS::trace('neither nor found'); + $this->authError('ST not validated', + $validate_url, + FALSE/*$no_response*/, + TRUE/*$bad_response*/, + $text_response); + } + break; + } + + // at this step, ST has been validated and $this->_user has been set, + phpCAS::traceEnd(TRUE); + return TRUE; + } + + /** @} */ + + // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX + // XX XX + // XX PROXY FEATURES (CAS 2.0) XX + // XX XX + // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX + + // ######################################################################## + // PROXYING + // ######################################################################## + /** + * @addtogroup internalProxy + * @{ + */ + + /** + * A boolean telling if the client is a CAS proxy or not. Written by CASClient::CASClient(), + * read by CASClient::isProxy(). + * + * @private + */ + var $_proxy; + + /** + * Tells if a CAS client is a CAS proxy or not + * + * @return TRUE when the CAS client is a CAs proxy, FALSE otherwise + * + * @private + */ + function isProxy() + { + return $this->_proxy; + } + + /** @} */ + // ######################################################################## + // PGT + // ######################################################################## + /** + * @addtogroup internalProxy + * @{ + */ + + /** + * the Proxy Grnting Ticket given by the CAS server (empty otherwise). + * Written by CASClient::setPGT(), read by CASClient::getPGT() and CASClient::hasPGT(). + * + * @hideinitializer + * @private + */ + var $_pgt = ''; + + /** + * This method returns the Proxy Granting Ticket given by the CAS server. + * @return The Proxy Granting Ticket. + * @private + */ + function getPGT() + { return $this->_pgt; } + + /** + * This method stores the Proxy Granting Ticket. + * @param $pgt The Proxy Granting Ticket. + * @private + */ + function setPGT($pgt) + { $this->_pgt = $pgt; } + + /** + * This method tells if a Proxy Granting Ticket was stored. + * @return TRUE if a Proxy Granting Ticket has been stored. + * @private + */ + function hasPGT() + { return !empty($this->_pgt); } + + /** @} */ + + // ######################################################################## + // CALLBACK MODE + // ######################################################################## + /** + * @addtogroup internalCallback + * @{ + */ + /** + * each PHP script using phpCAS in proxy mode is its own callback to get the + * PGT back from the CAS server. callback_mode is detected by the constructor + * thanks to the GET parameters. + */ + + /** + * a boolean to know if the CAS client is running in callback mode. Written by + * CASClient::setCallBackMode(), read by CASClient::isCallbackMode(). + * + * @hideinitializer + * @private + */ + var $_callback_mode = FALSE; + + /** + * This method sets/unsets callback mode. + * + * @param $callback_mode TRUE to set callback mode, FALSE otherwise. + * + * @private + */ + function setCallbackMode($callback_mode) + { + $this->_callback_mode = $callback_mode; + } + + /** + * This method returns TRUE when the CAs client is running i callback mode, + * FALSE otherwise. + * + * @return A boolean. + * + * @private + */ + function isCallbackMode() + { + return $this->_callback_mode; + } + + /** + * the URL that should be used for the PGT callback (in fact the URL of the + * current request without any CGI parameter). Written and read by + * CASClient::getCallbackURL(). + * + * @hideinitializer + * @private + */ + var $_callback_url = ''; + + /** + * This method returns the URL that should be used for the PGT callback (in + * fact the URL of the current request without any CGI parameter, except if + * phpCAS::setFixedCallbackURL() was used). + * + * @return The callback URL + * + * @private + */ + function getCallbackURL() + { + // the URL is built when needed only + if ( empty($this->_callback_url) ) { + $final_uri = ''; + // remove the ticket if present in the URL + $final_uri = 'https://'; + /* replaced by Julien Marchal - v0.4.6 + * $this->uri .= $_SERVER['SERVER_NAME']; + */ + if(empty($_SERVER['HTTP_X_FORWARDED_SERVER'])){ + /* replaced by teedog - v0.4.12 + * $final_uri .= $_SERVER['SERVER_NAME']; + */ + if (empty($_SERVER['SERVER_NAME'])) { + $final_uri .= $_SERVER['HTTP_HOST']; + } else { + $final_uri .= $_SERVER['SERVER_NAME']; + } + } else { + $final_uri .= $_SERVER['HTTP_X_FORWARDED_SERVER']; + } + if ( ($this->isHttps() && $_SERVER['SERVER_PORT']!=443) + || (!$this->isHttps() && $_SERVER['SERVER_PORT']!=80) ) { + $final_uri .= ':'; + $final_uri .= $_SERVER['SERVER_PORT']; + } + $request_uri = $_SERVER['REQUEST_URI']; + $request_uri = preg_replace('/\?.*$/','',$request_uri); + $final_uri .= $request_uri; + $this->setCallbackURL($final_uri); + } + return $this->_callback_url; + } + + /** + * This method sets the callback url. + * + * @param $callback_url url to set callback + * + * @private + */ + function setCallbackURL($url) + { + return $this->_callback_url = $url; + } + + /** + * This method is called by CASClient::CASClient() when running in callback + * mode. It stores the PGT and its PGT Iou, prints its output and halts. + * + * @private + */ + function callback() + { + phpCAS::traceBegin(); + $this->printHTMLHeader('phpCAS callback'); + $pgt_iou = $_GET['pgtIou']; + $pgt = $_GET['pgtId']; + phpCAS::trace('Storing PGT `'.$pgt.'\' (id=`'.$pgt_iou.'\')'); + echo '

    Storing PGT `'.$pgt.'\' (id=`'.$pgt_iou.'\').

    '; + $this->storePGT($pgt,$pgt_iou); + $this->printHTMLFooter(); + phpCAS::traceExit(); + } + + /** @} */ + + // ######################################################################## + // PGT STORAGE + // ######################################################################## + /** + * @addtogroup internalPGTStorage + * @{ + */ + + /** + * an instance of a class inheriting of PGTStorage, used to deal with PGT + * storage. Created by CASClient::setPGTStorageFile() or CASClient::setPGTStorageDB(), used + * by CASClient::setPGTStorageFile(), CASClient::setPGTStorageDB() and CASClient::initPGTStorage(). + * + * @hideinitializer + * @private + */ + var $_pgt_storage = null; + + /** + * This method is used to initialize the storage of PGT's. + * Halts on error. + * + * @private + */ + function initPGTStorage() + { + // if no SetPGTStorageXxx() has been used, default to file + if ( !is_object($this->_pgt_storage) ) { + $this->setPGTStorageFile(); + } + + // initializes the storage + $this->_pgt_storage->init(); + } + + /** + * This method stores a PGT. Halts on error. + * + * @param $pgt the PGT to store + * @param $pgt_iou its corresponding Iou + * + * @private + */ + function storePGT($pgt,$pgt_iou) + { + // ensure that storage is initialized + $this->initPGTStorage(); + // writes the PGT + $this->_pgt_storage->write($pgt,$pgt_iou); + } + + /** + * This method reads a PGT from its Iou and deletes the corresponding storage entry. + * + * @param $pgt_iou the PGT Iou + * + * @return The PGT corresponding to the Iou, FALSE when not found. + * + * @private + */ + function loadPGT($pgt_iou) + { + // ensure that storage is initialized + $this->initPGTStorage(); + // read the PGT + return $this->_pgt_storage->read($pgt_iou); + } + + /** + * This method is used to tell phpCAS to store the response of the + * CAS server to PGT requests onto the filesystem. + * + * @param $format the format used to store the PGT's (`plain' and `xml' allowed) + * @param $path the path where the PGT's should be stored + * + * @public + */ + function setPGTStorageFile($format='', + $path='') + { + // check that the storage has not already been set + if ( is_object($this->_pgt_storage) ) { + phpCAS::error('PGT storage already defined'); + } + + // create the storage object + $this->_pgt_storage = &new PGTStorageFile($this,$format,$path); + } + + /** + * This method is used to tell phpCAS to store the response of the + * CAS server to PGT requests into a database. + * @note The connection to the database is done only when needed. + * As a consequence, bad parameters are detected only when + * initializing PGT storage. + * + * @param $user the user to access the data with + * @param $password the user's password + * @param $database_type the type of the database hosting the data + * @param $hostname the server hosting the database + * @param $port the port the server is listening on + * @param $database the name of the database + * @param $table the name of the table storing the data + * + * @public + */ + function setPGTStorageDB($user, + $password, + $database_type, + $hostname, + $port, + $database, + $table) + { + // check that the storage has not already been set + if ( is_object($this->_pgt_storage) ) { + phpCAS::error('PGT storage already defined'); + } + + // warn the user that he should use file storage... + trigger_error('PGT storage into database is an experimental feature, use at your own risk',E_USER_WARNING); + + // create the storage object + $this->_pgt_storage = & new PGTStorageDB($this,$user,$password,$database_type,$hostname,$port,$database,$table); + } + + // ######################################################################## + // PGT VALIDATION + // ######################################################################## + /** + * This method is used to validate a PGT; halt on failure. + * + * @param $validate_url the URL of the request to the CAS server. + * @param $text_response the response of the CAS server, as is (XML text); result + * of CASClient::validateST() or CASClient::validatePT(). + * @param $tree_response the response of the CAS server, as a DOM XML tree; result + * of CASClient::validateST() or CASClient::validatePT(). + * + * @return bool TRUE when successfull, halt otherwise by calling CASClient::authError(). + * + * @private + */ + function validatePGT(&$validate_url,$text_response,$tree_response) + { + phpCAS::traceBegin(); + if ( sizeof($arr = $tree_response->get_elements_by_tagname("proxyGrantingTicket")) == 0) { + phpCAS::trace(' not found'); + // authentication succeded, but no PGT Iou was transmitted + $this->authError('Ticket validated but no PGT Iou transmitted', + $validate_url, + FALSE/*$no_response*/, + FALSE/*$bad_response*/, + $text_response); + } else { + // PGT Iou transmitted, extract it + $pgt_iou = trim($arr[0]->get_content()); + $pgt = $this->loadPGT($pgt_iou); + if ( $pgt == FALSE ) { + phpCAS::trace('could not load PGT'); + $this->authError('PGT Iou was transmitted but PGT could not be retrieved', + $validate_url, + FALSE/*$no_response*/, + FALSE/*$bad_response*/, + $text_response); + } + $this->setPGT($pgt); + } + phpCAS::traceEnd(TRUE); + return TRUE; + } + + // ######################################################################## + // PGT VALIDATION + // ######################################################################## + + /** + * This method is used to retrieve PT's from the CAS server thanks to a PGT. + * + * @param $target_service the service to ask for with the PT. + * @param $err_code an error code (PHPCAS_SERVICE_OK on success). + * @param $err_msg an error message (empty on success). + * + * @return a Proxy Ticket, or FALSE on error. + * + * @private + */ + function retrievePT($target_service,&$err_code,&$err_msg) + { + phpCAS::traceBegin(); + + // by default, $err_msg is set empty and $pt to TRUE. On error, $pt is + // set to false and $err_msg to an error message. At the end, if $pt is FALSE + // and $error_msg is still empty, it is set to 'invalid response' (the most + // commonly encountered error). + $err_msg = ''; + + // build the URL to retrieve the PT + // $cas_url = $this->getServerProxyURL().'?targetService='.preg_replace('/&/','%26',$target_service).'&pgt='.$this->getPGT(); + $cas_url = $this->getServerProxyURL().'?targetService='.urlencode($target_service).'&pgt='.$this->getPGT(); + + // open and read the URL + if ( !$this->readURL($cas_url,''/*cookies*/,$headers,$cas_response,$err_msg) ) { + phpCAS::trace('could not open URL \''.$cas_url.'\' to validate ('.$err_msg.')'); + $err_code = PHPCAS_SERVICE_PT_NO_SERVER_RESPONSE; + $err_msg = 'could not retrieve PT (no response from the CAS server)'; + phpCAS::traceEnd(FALSE); + return FALSE; + } + + $bad_response = FALSE; + + if ( !$bad_response ) { + // read the response of the CAS server into a DOM object + if ( !($dom = @domxml_open_mem($cas_response))) { + phpCAS::trace('domxml_open_mem() failed'); + // read failed + $bad_response = TRUE; + } + } + + if ( !$bad_response ) { + // read the root node of the XML tree + if ( !($root = $dom->document_element()) ) { + phpCAS::trace('document_element() failed'); + // read failed + $bad_response = TRUE; + } + } + + if ( !$bad_response ) { + // insure that tag name is 'serviceResponse' + if ( $root->node_name() != 'serviceResponse' ) { + phpCAS::trace('node_name() failed'); + // bad root node + $bad_response = TRUE; + } + } + + if ( !$bad_response ) { + // look for a proxySuccess tag + if ( sizeof($arr = $root->get_elements_by_tagname("proxySuccess")) != 0) { + // authentication succeded, look for a proxyTicket tag + if ( sizeof($arr = $root->get_elements_by_tagname("proxyTicket")) != 0) { + $err_code = PHPCAS_SERVICE_OK; + $err_msg = ''; + phpCAS::trace('original PT: '.trim($arr[0]->get_content())); + $pt = trim($arr[0]->get_content()); + phpCAS::traceEnd($pt); + return $pt; + } else { + phpCAS::trace(' was found, but not '); + } + } + // look for a proxyFailure tag + else if ( sizeof($arr = $root->get_elements_by_tagname("proxyFailure")) != 0) { + // authentication failed, extract the error + $err_code = PHPCAS_SERVICE_PT_FAILURE; + $err_msg = 'PT retrieving failed (code=`' + .$arr[0]->get_attribute('code') + .'\', message=`' + .trim($arr[0]->get_content()) + .'\')'; + phpCAS::traceEnd(FALSE); + return FALSE; + } else { + phpCAS::trace('neither nor found'); + } + } + + // at this step, we are sure that the response of the CAS server was ill-formed + $err_code = PHPCAS_SERVICE_PT_BAD_SERVER_RESPONSE; + $err_msg = 'Invalid response from the CAS server (response=`'.$cas_response.'\')'; + + phpCAS::traceEnd(FALSE); + return FALSE; + } + + // ######################################################################## + // ACCESS TO EXTERNAL SERVICES + // ######################################################################## + + /** + * This method is used to acces a remote URL. + * + * @param $url the URL to access. + * @param $cookies an array containing cookies strings such as 'name=val' + * @param $headers an array containing the HTTP header lines of the response + * (an empty array on failure). + * @param $body the body of the response, as a string (empty on failure). + * @param $err_msg an error message, filled on failure. + * + * @return TRUE on success, FALSE otherwise (in this later case, $err_msg + * contains an error message). + * + * @private + */ + function readURL($url,$cookies,&$headers,&$body,&$err_msg) + { + phpCAS::traceBegin(); + $headers = ''; + $body = ''; + $err_msg = ''; + + $res = TRUE; + + // initialize the CURL session + $ch = curl_init($url); + + if (version_compare(PHP_VERSION,'5.1.3','>=')) { + //only avaible in php5 + curl_setopt_array($ch, $this->_curl_options); + } else { + foreach ($this->_curl_options as $key => $value) { + curl_setopt($ch, $key, $value); + } + } + + if ($this->_cas_server_cert == '' && $this->_cas_server_ca_cert == '' && !$this->_no_cas_server_validation) { + phpCAS::error('one of the methods phpCAS::setCasServerCert(), phpCAS::setCasServerCACert() or phpCAS::setNoCasServerValidation() must be called.'); + } + if ($this->_cas_server_cert != '' ) { + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1); + curl_setopt($ch, CURLOPT_SSLCERT, $this->_cas_server_cert); + } else if ($this->_cas_server_ca_cert != '') { + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1); + curl_setopt($ch, CURLOPT_CAINFO, $this->_cas_server_ca_cert); + } else { + curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); + } + + // return the CURL output into a variable + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + // get the HTTP header with a callback + $this->_curl_headers = array(); // empty the headers array + curl_setopt($ch, CURLOPT_HEADERFUNCTION, array($this, '_curl_read_headers')); + // add cookies headers + if ( is_array($cookies) ) { + curl_setopt($ch,CURLOPT_COOKIE,implode(';',$cookies)); + } + // perform the query + $buf = curl_exec ($ch); + if ( $buf === FALSE ) { + phpCAS::trace('curl_exec() failed'); + $err_msg = 'CURL error #'.curl_errno($ch).': '.curl_error($ch); + // close the CURL session + curl_close ($ch); + $res = FALSE; + } else { + // close the CURL session + curl_close ($ch); + + $headers = $this->_curl_headers; + $body = $buf; + } + + phpCAS::traceEnd($res); + return $res; + } + + /** + * This method is the callback used by readURL method to request HTTP headers. + */ + var $_curl_headers = array(); + function _curl_read_headers($ch, $header) + { + $this->_curl_headers[] = $header; + return strlen($header); + } + + /** + * This method is used to access an HTTP[S] service. + * + * @param $url the service to access. + * @param $err_code an error code Possible values are PHPCAS_SERVICE_OK (on + * success), PHPCAS_SERVICE_PT_NO_SERVER_RESPONSE, PHPCAS_SERVICE_PT_BAD_SERVER_RESPONSE, + * PHPCAS_SERVICE_PT_FAILURE, PHPCAS_SERVICE_NOT AVAILABLE. + * @param $output the output of the service (also used to give an error + * message on failure). + * + * @return TRUE on success, FALSE otherwise (in this later case, $err_code + * gives the reason why it failed and $output contains an error message). + * + * @public + */ + function serviceWeb($url,&$err_code,&$output) + { + phpCAS::traceBegin(); + // at first retrieve a PT + $pt = $this->retrievePT($url,$err_code,$output); + + $res = TRUE; + + // test if PT was retrieved correctly + if ( !$pt ) { + // note: $err_code and $err_msg are filled by CASClient::retrievePT() + phpCAS::trace('PT was not retrieved correctly'); + $res = FALSE; + } else { + // add cookies if necessary + if ( is_array($_SESSION['phpCAS']['services'][$url]['cookies']) ) { + foreach ( $_SESSION['phpCAS']['services'][$url]['cookies'] as $name => $val ) { + $cookies[] = $name.'='.$val; + } + } + + // build the URL including the PT + if ( strstr($url,'?') === FALSE ) { + $service_url = $url.'?ticket='.$pt; + } else { + $service_url = $url.'&ticket='.$pt; + } + + phpCAS::trace('reading URL`'.$service_url.'\''); + if ( !$this->readURL($service_url,$cookies,$headers,$output,$err_msg) ) { + phpCAS::trace('could not read URL`'.$service_url.'\''); + $err_code = PHPCAS_SERVICE_NOT_AVAILABLE; + // give an error message + $output = sprintf($this->getString(CAS_STR_SERVICE_UNAVAILABLE), + $service_url, + $err_msg); + $res = FALSE; + } else { + // URL has been fetched, extract the cookies + phpCAS::trace('URL`'.$service_url.'\' has been read, storing cookies:'); + foreach ( $headers as $header ) { + // test if the header is a cookie + if ( preg_match('/^Set-Cookie:/',$header) ) { + // the header is a cookie, remove the beginning + $header_val = preg_replace('/^Set-Cookie: */','',$header); + // extract interesting information + $name_val = strtok($header_val,'; '); + // extract the name and the value of the cookie + $cookie_name = strtok($name_val,'='); + $cookie_val = strtok('='); + // store the cookie + $_SESSION['phpCAS']['services'][$url]['cookies'][$cookie_name] = $cookie_val; + phpCAS::trace($cookie_name.' -> '.$cookie_val); + } + } + } + } + + phpCAS::traceEnd($res); + return $res; + } + + /** + * This method is used to access an IMAP/POP3/NNTP service. + * + * @param $url a string giving the URL of the service, including the mailing box + * for IMAP URLs, as accepted by imap_open(). + * @param $flags options given to imap_open(). + * @param $err_code an error code Possible values are PHPCAS_SERVICE_OK (on + * success), PHPCAS_SERVICE_PT_NO_SERVER_RESPONSE, PHPCAS_SERVICE_PT_BAD_SERVER_RESPONSE, + * PHPCAS_SERVICE_PT_FAILURE, PHPCAS_SERVICE_NOT AVAILABLE. + * @param $err_msg an error message on failure + * @param $pt the Proxy Ticket (PT) retrieved from the CAS server to access the URL + * on success, FALSE on error). + * + * @return an IMAP stream on success, FALSE otherwise (in this later case, $err_code + * gives the reason why it failed and $err_msg contains an error message). + * + * @public + */ + function serviceMail($url,$flags,&$err_code,&$err_msg,&$pt) + { + phpCAS::traceBegin(); + // at first retrieve a PT + $pt = $this->retrievePT($target_service,$err_code,$output); + + $stream = FALSE; + + // test if PT was retrieved correctly + if ( !$pt ) { + // note: $err_code and $err_msg are filled by CASClient::retrievePT() + phpCAS::trace('PT was not retrieved correctly'); + } else { + phpCAS::trace('opening IMAP URL `'.$url.'\'...'); + $stream = @imap_open($url,$this->getUser(),$pt,$flags); + if ( !$stream ) { + phpCAS::trace('could not open URL'); + $err_code = PHPCAS_SERVICE_NOT_AVAILABLE; + // give an error message + $err_msg = sprintf($this->getString(CAS_STR_SERVICE_UNAVAILABLE), + $service_url, + var_export(imap_errors(),TRUE)); + $pt = FALSE; + $stream = FALSE; + } else { + phpCAS::trace('ok'); + } + } + + phpCAS::traceEnd($stream); + return $stream; + } + + /** @} */ + + // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX + // XX XX + // XX PROXIED CLIENT FEATURES (CAS 2.0) XX + // XX XX + // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX + + // ######################################################################## + // PT + // ######################################################################## + /** + * @addtogroup internalProxied + * @{ + */ + + /** + * the Proxy Ticket provided in the URL of the request if present + * (empty otherwise). Written by CASClient::CASClient(), read by + * CASClient::getPT() and CASClient::hasPGT(). + * + * @hideinitializer + * @private + */ + var $_pt = ''; + + /** + * This method returns the Proxy Ticket provided in the URL of the request. + * @return The proxy ticket. + * @private + */ + function getPT() + { + // return 'ST'.substr($this->_pt, 2); + return $this->_pt; + } + + /** + * This method stores the Proxy Ticket. + * @param $pt The Proxy Ticket. + * @private + */ + function setPT($pt) + { $this->_pt = $pt; } + + /** + * This method tells if a Proxy Ticket was stored. + * @return TRUE if a Proxy Ticket has been stored. + * @private + */ + function hasPT() + { return !empty($this->_pt); } + + /** @} */ + // ######################################################################## + // PT VALIDATION + // ######################################################################## + /** + * @addtogroup internalProxied + * @{ + */ + + /** + * This method is used to validate a PT; halt on failure + * + * @return bool TRUE when successfull, halt otherwise by calling CASClient::authError(). + * + * @private + */ + function validatePT(&$validate_url,&$text_response,&$tree_response) + { + phpCAS::traceBegin(); + // build the URL to validate the ticket + $validate_url = $this->getServerProxyValidateURL().'&ticket='.$this->getPT(); + + if ( $this->isProxy() ) { + // pass the callback url for CAS proxies + $validate_url .= '&pgtUrl='.$this->getCallbackURL(); + } + + // open and read the URL + if ( !$this->readURL($validate_url,''/*cookies*/,$headers,$text_response,$err_msg) ) { + phpCAS::trace('could not open URL \''.$validate_url.'\' to validate ('.$err_msg.')'); + $this->authError('PT not validated', + $validate_url, + TRUE/*$no_response*/); + } + + // read the response of the CAS server into a DOM object + if ( !($dom = domxml_open_mem($text_response))) { + // read failed + $this->authError('PT not validated', + $validate_url, + FALSE/*$no_response*/, + TRUE/*$bad_response*/, + $text_response); + } + // read the root node of the XML tree + if ( !($tree_response = $dom->document_element()) ) { + // read failed + $this->authError('PT not validated', + $validate_url, + FALSE/*$no_response*/, + TRUE/*$bad_response*/, + $text_response); + } + // insure that tag name is 'serviceResponse' + if ( $tree_response->node_name() != 'serviceResponse' ) { + // bad root node + $this->authError('PT not validated', + $validate_url, + FALSE/*$no_response*/, + TRUE/*$bad_response*/, + $text_response); + } + if ( sizeof($arr = $tree_response->get_elements_by_tagname("authenticationSuccess")) != 0) { + // authentication succeded, extract the user name + if ( sizeof($arr = $tree_response->get_elements_by_tagname("user")) == 0) { + // no user specified => error + $this->authError('PT not validated', + $validate_url, + FALSE/*$no_response*/, + TRUE/*$bad_response*/, + $text_response); + } + $this->setUser(trim($arr[0]->get_content())); + + } else if ( sizeof($arr = $tree_response->get_elements_by_tagname("authenticationFailure")) != 0) { + // authentication succeded, extract the error code and message + $this->authError('PT not validated', + $validate_url, + FALSE/*$no_response*/, + FALSE/*$bad_response*/, + $text_response, + $arr[0]->get_attribute('code')/*$err_code*/, + trim($arr[0]->get_content())/*$err_msg*/); + } else { + $this->authError('PT not validated', + $validate_url, + FALSE/*$no_response*/, + TRUE/*$bad_response*/, + $text_response); + } + + // at this step, PT has been validated and $this->_user has been set, + + phpCAS::traceEnd(TRUE); + return TRUE; + } + + /** @} */ + + // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX + // XX XX + // XX MISC XX + // XX XX + // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX + + /** + * @addtogroup internalMisc + * @{ + */ + + // ######################################################################## + // URL + // ######################################################################## + /** + * the URL of the current request (without any ticket CGI parameter). Written + * and read by CASClient::getURL(). + * + * @hideinitializer + * @private + */ + var $_url = ''; + + /** + * This method returns the URL of the current request (without any ticket + * CGI parameter). + * + * @return The URL + * + * @private + */ + function getURL() + { + phpCAS::traceBegin(); + // the URL is built when needed only + if ( empty($this->_url) ) { + $final_uri = ''; + // remove the ticket if present in the URL + $final_uri = ($this->isHttps()) ? 'https' : 'http'; + $final_uri .= '://'; + /* replaced by Julien Marchal - v0.4.6 + * $this->_url .= $_SERVER['SERVER_NAME']; + */ + if(empty($_SERVER['HTTP_X_FORWARDED_SERVER'])){ + /* replaced by teedog - v0.4.12 + * $this->_url .= $_SERVER['SERVER_NAME']; + */ + if (empty($_SERVER['SERVER_NAME'])) { + $server_name = $_SERVER['HTTP_HOST']; + } else { + $server_name = $_SERVER['SERVER_NAME']; + } + } else { + $server_name = $_SERVER['HTTP_X_FORWARDED_SERVER']; + } + $final_uri .= $server_name; + if (!strpos($server_name, ':')) { + if ( ($this->isHttps() && $_SERVER['SERVER_PORT']!=443) + || (!$this->isHttps() && $_SERVER['SERVER_PORT']!=80) ) { + $final_uri .= ':'; + $final_uri .= $_SERVER['SERVER_PORT']; + } + } + + $final_uri .= strtok($_SERVER['REQUEST_URI'],"?"); + $cgi_params = '?'.strtok("?"); + // remove the ticket if present in the CGI parameters + $cgi_params = preg_replace('/&ticket=[^&]*/','',$cgi_params); + $cgi_params = preg_replace('/\?ticket=[^&;]*/','?',$cgi_params); + $cgi_params = preg_replace('/\?%26/','?',$cgi_params); + $cgi_params = preg_replace('/\?&/','?',$cgi_params); + $cgi_params = preg_replace('/\?$/','',$cgi_params); + $final_uri .= $cgi_params; + $this->setURL($final_uri); + } + phpCAS::traceEnd($this->_url); + return $this->_url; + } + + /** + * This method sets the URL of the current request + * + * @param $url url to set for service + * + * @private + */ + function setURL($url) + { + $this->_url = $url; + } + + // ######################################################################## + // AUTHENTICATION ERROR HANDLING + // ######################################################################## + /** + * This method is used to print the HTML output when the user was not authenticated. + * + * @param $failure the failure that occured + * @param $cas_url the URL the CAS server was asked for + * @param $no_response the response from the CAS server (other + * parameters are ignored if TRUE) + * @param $bad_response bad response from the CAS server ($err_code + * and $err_msg ignored if TRUE) + * @param $cas_response the response of the CAS server + * @param $err_code the error code given by the CAS server + * @param $err_msg the error message given by the CAS server + * + * @private + */ + function authError($failure,$cas_url,$no_response,$bad_response='',$cas_response='',$err_code='',$err_msg='') + { + phpCAS::traceBegin(); + + $this->printHTMLHeader($this->getString(CAS_STR_AUTHENTICATION_FAILED)); + printf($this->getString(CAS_STR_YOU_WERE_NOT_AUTHENTICATED),$this->getURL(),$_SERVER['SERVER_ADMIN']); + phpCAS::trace('CAS URL: '.$cas_url); + phpCAS::trace('Authentication failure: '.$failure); + if ( $no_response ) { + phpCAS::trace('Reason: no response from the CAS server'); + } else { + if ( $bad_response ) { + phpCAS::trace('Reason: bad response from the CAS server'); + } else { + switch ($this->getServerVersion()) { + case CAS_VERSION_1_0: + phpCAS::trace('Reason: CAS error'); + break; + case CAS_VERSION_2_0: + if ( empty($err_code) ) + phpCAS::trace('Reason: no CAS error'); + else + phpCAS::trace('Reason: ['.$err_code.'] CAS error: '.$err_msg); + break; + } + } + phpCAS::trace('CAS response: '.$cas_response); + } + $this->printHTMLFooter(); + phpCAS::traceExit(); + exit(); + } + + /** @} */ +} + +?> \ No newline at end of file diff --git a/include/limesurvey/admin/classes/phpCAS/CAS/domxml-php4-php5.php b/include/limesurvey/admin/classes/phpCAS/CAS/domxml-php4-php5.php new file mode 100644 index 00000000..b7dc13aa --- /dev/null +++ b/include/limesurvey/admin/classes/phpCAS/CAS/domxml-php4-php5.php @@ -0,0 +1,277 @@ + + * { + * if (version_compare(PHP_VERSION,'5','>=')) + * require_once('domxml-php4-to-php5.php'); + * } + * + * + * Version 1.5.5, 2005-01-18, http://alexandre.alapetite.net/doc-alex/domxml-php4-php5/ + * + * ------------------------------------------------------------------
    + * Written by Alexandre Alapetite, http://alexandre.alapetite.net/cv/ + * + * Copyright 2004, Licence: Creative Commons "Attribution-ShareAlike 2.0 France" BY-SA (FR), + * http://creativecommons.org/licenses/by-sa/2.0/fr/ + * http://alexandre.alapetite.net/divers/apropos/#by-sa + * - Attribution. You must give the original author credit + * - Share Alike. If you alter, transform, or build upon this work, + * you may distribute the resulting work only under a license identical to this one + * - The French law is authoritative + * - Any of these conditions can be waived if you get permission from Alexandre Alapetite + * - Please send to Alexandre Alapetite the modifications you make, + * in order to improve this file for the benefit of everybody + * + * If you want to distribute this code, please do it as a link to: + * http://alexandre.alapetite.net/doc-alex/domxml-php4-php5/ + */ + +function domxml_new_doc($version) {return new php4DOMDocument('');} +function domxml_open_file($filename) {return new php4DOMDocument($filename);} +function domxml_open_mem($str) +{ + $dom=new php4DOMDocument(''); + $dom->myDOMNode->loadXML($str); + return $dom; +} +function xpath_eval($xpath_context,$eval_str,$contextnode=null) {return $xpath_context->query($eval_str,$contextnode);} +function xpath_new_context($dom_document) {return new php4DOMXPath($dom_document);} + +class php4DOMAttr extends php4DOMNode +{ + function php4DOMAttr($aDOMAttr) {$this->myDOMNode=$aDOMAttr;} + function Name() {return $this->myDOMNode->name;} + function Specified() {return $this->myDOMNode->specified;} + function Value() {return $this->myDOMNode->value;} +} + +class php4DOMDocument extends php4DOMNode +{ + function php4DOMDocument($filename='') + { + $this->myDOMNode=new DOMDocument(); + if ($filename!='') $this->myDOMNode->load($filename); + } + function create_attribute($name,$value) + { + $myAttr=$this->myDOMNode->createAttribute($name); + $myAttr->value=$value; + return new php4DOMAttr($myAttr,$this); + } + function create_cdata_section($content) {return new php4DOMNode($this->myDOMNode->createCDATASection($content),$this);} + function create_comment($data) {return new php4DOMNode($this->myDOMNode->createComment($data),$this);} + function create_element($name) {return new php4DOMElement($this->myDOMNode->createElement($name),$this);} + function create_text_node($content) {return new php4DOMNode($this->myDOMNode->createTextNode($content),$this);} + function document_element() {return new php4DOMElement($this->myDOMNode->documentElement,$this);} + function dump_file($filename,$compressionmode=false,$format=false) {return $this->myDOMNode->save($filename);} + function dump_mem($format=false,$encoding=false) {return $this->myDOMNode->saveXML();} + function get_element_by_id($id) {return new php4DOMElement($this->myDOMNode->getElementById($id),$this);} + function get_elements_by_tagname($name) + { + $myDOMNodeList=$this->myDOMNode->getElementsByTagName($name); + $nodeSet=array(); + $i=0; + if (isset($myDOMNodeList)) + while ($node=$myDOMNodeList->item($i)) + { + $nodeSet[]=new php4DOMElement($node,$this); + $i++; + } + return $nodeSet; + } + function html_dump_mem() {return $this->myDOMNode->saveHTML();} + function root() {return new php4DOMElement($this->myDOMNode->documentElement,$this);} +} + +class php4DOMElement extends php4DOMNode +{ + function get_attribute($name) {return $this->myDOMNode->getAttribute($name);} + function get_elements_by_tagname($name) + { + $myDOMNodeList=$this->myDOMNode->getElementsByTagName($name); + $nodeSet=array(); + $i=0; + if (isset($myDOMNodeList)) + while ($node=$myDOMNodeList->item($i)) + { + $nodeSet[]=new php4DOMElement($node,$this->myOwnerDocument); + $i++; + } + return $nodeSet; + } + function has_attribute($name) {return $this->myDOMNode->hasAttribute($name);} + function remove_attribute($name) {return $this->myDOMNode->removeAttribute($name);} + function set_attribute($name,$value) {return $this->myDOMNode->setAttribute($name,$value);} + function tagname() {return $this->myDOMNode->tagName;} +} + +class php4DOMNode +{ + var $myDOMNode; + var $myOwnerDocument; + function php4DOMNode($aDomNode,$aOwnerDocument) + { + $this->myDOMNode=$aDomNode; + $this->myOwnerDocument=$aOwnerDocument; + } + function __get($name) + { + if ($name=='type') return $this->myDOMNode->nodeType; + elseif ($name=='tagname') return $this->myDOMNode->tagName; + elseif ($name=='content') return $this->myDOMNode->textContent; + else + { + $myErrors=debug_backtrace(); + trigger_error('Undefined property: '.get_class($this).'::$'.$name.' ['.$myErrors[0]['file'].':'.$myErrors[0]['line'].']',E_USER_NOTICE); + return false; + } + } + function append_child($newnode) {return new php4DOMElement($this->myDOMNode->appendChild($newnode->myDOMNode),$this->myOwnerDocument);} + function append_sibling($newnode) {return new php4DOMElement($this->myDOMNode->parentNode->appendChild($newnode->myDOMNode),$this->myOwnerDocument);} + function attributes() + { + $myDOMNodeList=$this->myDOMNode->attributes; + $nodeSet=array(); + $i=0; + if (isset($myDOMNodeList)) + while ($node=$myDOMNodeList->item($i)) + { + $nodeSet[]=new php4DOMAttr($node,$this->myOwnerDocument); + $i++; + } + return $nodeSet; + } + function child_nodes() + { + $myDOMNodeList=$this->myDOMNode->childNodes; + $nodeSet=array(); + $i=0; + if (isset($myDOMNodeList)) + while ($node=$myDOMNodeList->item($i)) + { + $nodeSet[]=new php4DOMElement($node,$this->myOwnerDocument); + $i++; + } + return $nodeSet; + } + function children() {return $this->child_nodes();} + function clone_node($deep=false) {return new php4DOMElement($this->myDOMNode->cloneNode($deep),$this->myOwnerDocument);} + function first_child() {return new php4DOMElement($this->myDOMNode->firstChild,$this->myOwnerDocument);} + function get_content() {return $this->myDOMNode->textContent;} + function has_attributes() {return $this->myDOMNode->hasAttributes();} + function has_child_nodes() {return $this->myDOMNode->hasChildNodes();} + function insert_before($newnode,$refnode) {return new php4DOMElement($this->myDOMNode->insertBefore($newnode->myDOMNode,$refnode->myDOMNode),$this->myOwnerDocument);} + function is_blank_node() + { + $myDOMNodeList=$this->myDOMNode->childNodes; + $i=0; + if (isset($myDOMNodeList)) + while ($node=$myDOMNodeList->item($i)) + { + if (($node->nodeType==XML_ELEMENT_NODE)|| + (($node->nodeType==XML_TEXT_NODE)&&!preg_match('/^([[:cntrl:]]|[[:space:]])*$/',$node->nodeValue))) + return false; + $i++; + } + return true; + } + function last_child() {return new php4DOMElement($this->myDOMNode->lastChild,$this->myOwnerDocument);} + function new_child($name,$content) + { + $mySubNode=$this->myDOMNode->ownerDocument->createElement($name); + $mySubNode->appendChild($this->myDOMNode->ownerDocument->createTextNode($content)); + $this->myDOMNode->appendChild($mySubNode); + return new php4DOMElement($mySubNode,$this->myOwnerDocument); + } + function next_sibling() {return new php4DOMElement($this->myDOMNode->nextSibling,$this->myOwnerDocument);} + function node_name() {return $this->myDOMNode->localName;} + function node_type() {return $this->myDOMNode->nodeType;} + function node_value() {return $this->myDOMNode->nodeValue;} + function owner_document() {return $this->myOwnerDocument;} + function parent_node() {return new php4DOMElement($this->myDOMNode->parentNode,$this->myOwnerDocument);} + function prefix() {return $this->myDOMNode->prefix;} + function previous_sibling() {return new php4DOMElement($this->myDOMNode->previousSibling,$this->myOwnerDocument);} + function remove_child($oldchild) {return new php4DOMElement($this->myDOMNode->removeChild($oldchild->myDOMNode),$this->myOwnerDocument);} + function replace_child($oldnode,$newnode) {return new php4DOMElement($this->myDOMNode->replaceChild($oldnode->myDOMNode,$newnode->myDOMNode),$this->myOwnerDocument);} + function set_content($text) + { + if (($this->myDOMNode->hasChildNodes())&&($this->myDOMNode->firstChild->nodeType==XML_TEXT_NODE)) + $this->myDOMNode->removeChild($this->myDOMNode->firstChild); + return $this->myDOMNode->appendChild($this->myDOMNode->ownerDocument->createTextNode($text)); + } +} + +class php4DOMNodelist +{ + var $myDOMNodelist; + var $nodeset; + function php4DOMNodelist($aDOMNodelist,$aOwnerDocument) + { + $this->myDOMNodelist=$aDOMNodelist; + $this->nodeset=array(); + $i=0; + if (isset($this->myDOMNodelist)) + while ($node=$this->myDOMNodelist->item($i)) + { + $this->nodeset[]=new php4DOMElement($node,$aOwnerDocument); + $i++; + } + } +} + +class php4DOMXPath +{ + var $myDOMXPath; + var $myOwnerDocument; + function php4DOMXPath($dom_document) + { + $this->myOwnerDocument=$dom_document; + $this->myDOMXPath=new DOMXPath($dom_document->myDOMNode); + } + function query($eval_str,$contextnode) + { + if (isset($contextnode)) return new php4DOMNodelist($this->myDOMXPath->query($eval_str,$contextnode->myDOMNode),$this->myOwnerDocument); + else return new php4DOMNodelist($this->myDOMXPath->query($eval_str),$this->myOwnerDocument); + } + function xpath_register_ns($prefix,$namespaceURI) {return $this->myDOMXPath->registerNamespace($prefix,$namespaceURI);} +} + +if (extension_loaded('xsl')) +{//See also: http://alexandre.alapetite.net/doc-alex/xslt-php4-php5/ + function domxml_xslt_stylesheet($xslstring) {return new php4DomXsltStylesheet(DOMDocument::loadXML($xslstring));} + function domxml_xslt_stylesheet_doc($dom_document) {return new php4DomXsltStylesheet($dom_document);} + function domxml_xslt_stylesheet_file($xslfile) {return new php4DomXsltStylesheet(DOMDocument::load($xslfile));} + class php4DomXsltStylesheet + { + var $myxsltProcessor; + function php4DomXsltStylesheet($dom_document) + { + $this->myxsltProcessor=new xsltProcessor(); + $this->myxsltProcessor->importStyleSheet($dom_document); + } + function process($dom_document,$xslt_parameters=array(),$param_is_xpath=false) + { + foreach ($xslt_parameters as $param=>$value) + $this->myxsltProcessor->setParameter('',$param,$value); + $myphp4DOMDocument=new php4DOMDocument(); + $myphp4DOMDocument->myDOMNode=$this->myxsltProcessor->transformToDoc($dom_document->myDOMNode); + return $myphp4DOMDocument; + } + function result_dump_file($dom_document,$filename) + { + $html=$dom_document->myDOMNode->saveHTML(); + file_put_contents($filename,$html); + return $html; + } + function result_dump_mem($dom_document) {return $dom_document->myDOMNode->saveHTML();} + } +} +?> \ No newline at end of file diff --git a/include/limesurvey/admin/classes/phpCAS/CAS/languages/catalan.php b/include/limesurvey/admin/classes/phpCAS/CAS/languages/catalan.php new file mode 100644 index 00000000..3d67473d --- /dev/null +++ b/include/limesurvey/admin/classes/phpCAS/CAS/languages/catalan.php @@ -0,0 +1,27 @@ + + * @sa @link internalLang Internationalization @endlink + * @ingroup internalLang + */ + +$this->_strings = array( + CAS_STR_USING_SERVER + => 'usant servidor', + CAS_STR_AUTHENTICATION_WANTED + => 'Autentificació CAS necessària!', + CAS_STR_LOGOUT + => 'Sortida de CAS necessària!', + CAS_STR_SHOULD_HAVE_BEEN_REDIRECTED + => 'Ja hauria d\ haver estat redireccionat al servidor CAS. Feu click aquí per a continuar.', + CAS_STR_AUTHENTICATION_FAILED + => 'Autentificació CAS fallida!', + CAS_STR_YOU_WERE_NOT_AUTHENTICATED + => '

    No estàs autentificat.

    Pots tornar a intentar-ho fent click aquí.

    Si el problema persisteix hauría de contactar amb l\'administrador d\'aquest llocc.

    ', + CAS_STR_SERVICE_UNAVAILABLE + => 'El servei `%s\' no està disponible (%s).' +); + +?> diff --git a/include/limesurvey/admin/classes/phpCAS/CAS/languages/english.php b/include/limesurvey/admin/classes/phpCAS/CAS/languages/english.php new file mode 100644 index 00000000..c1434503 --- /dev/null +++ b/include/limesurvey/admin/classes/phpCAS/CAS/languages/english.php @@ -0,0 +1,27 @@ + + * @sa @link internalLang Internationalization @endlink + * @ingroup internalLang + */ + +$this->_strings = array( + CAS_STR_USING_SERVER + => 'using server', + CAS_STR_AUTHENTICATION_WANTED + => 'CAS Authentication wanted!', + CAS_STR_LOGOUT + => 'CAS logout wanted!', + CAS_STR_SHOULD_HAVE_BEEN_REDIRECTED + => 'You should already have been redirected to the CAS server. Click here to continue.', + CAS_STR_AUTHENTICATION_FAILED + => 'CAS Authentication failed!', + CAS_STR_YOU_WERE_NOT_AUTHENTICATED + => '

    You were not authenticated.

    You may submit your request again by clicking here.

    If the problem persists, you may contact the administrator of this site.

    ', + CAS_STR_SERVICE_UNAVAILABLE + => 'The service `%s\' is not available (%s).' +); + +?> \ No newline at end of file diff --git a/include/limesurvey/admin/classes/phpCAS/CAS/languages/french.php b/include/limesurvey/admin/classes/phpCAS/CAS/languages/french.php new file mode 100644 index 00000000..675a7fc0 --- /dev/null +++ b/include/limesurvey/admin/classes/phpCAS/CAS/languages/french.php @@ -0,0 +1,28 @@ + + * @sa @link internalLang Internationalization @endlink + * @ingroup internalLang + */ + +$this->_strings = array( + CAS_STR_USING_SERVER + => 'utilisant le serveur', + CAS_STR_AUTHENTICATION_WANTED + => 'Authentication CAS nécessaire !', + CAS_STR_LOGOUT + => 'Déconnexion demandée !', + CAS_STR_SHOULD_HAVE_BEEN_REDIRECTED + => 'Vous auriez du etre redirigé(e) vers le serveur CAS. Cliquez ici pour continuer.', + CAS_STR_AUTHENTICATION_FAILED + => 'Authentification CAS infructueuse !', + CAS_STR_YOU_WERE_NOT_AUTHENTICATED + => '

    Vous n\'avez pas été authentifié(e).

    Vous pouvez soumettre votre requete à nouveau en cliquant ici.

    Si le problème persiste, vous pouvez contacter l\'administrateur de ce site.

    ', + CAS_STR_SERVICE_UNAVAILABLE + => 'Le service `%s\' est indisponible (%s)' + +); + +?> \ No newline at end of file diff --git a/include/limesurvey/admin/classes/phpCAS/CAS/languages/german.php b/include/limesurvey/admin/classes/phpCAS/CAS/languages/german.php new file mode 100644 index 00000000..29daeb35 --- /dev/null +++ b/include/limesurvey/admin/classes/phpCAS/CAS/languages/german.php @@ -0,0 +1,27 @@ + + * @sa @link internalLang Internationalization @endlink + * @ingroup internalLang + */ + +$this->_strings = array( + CAS_STR_USING_SERVER + => 'via Server', + CAS_STR_AUTHENTICATION_WANTED + => 'CAS Authentifizierung erforderlich!', + CAS_STR_LOGOUT + => 'CAS Abmeldung!', + CAS_STR_SHOULD_HAVE_BEEN_REDIRECTED + => 'eigentlich häten Sie zum CAS Server weitergeleitet werden sollen. Drücken Sie hier um fortzufahren.', + CAS_STR_AUTHENTICATION_FAILED + => 'CAS Anmeldung fehlgeschlagen!', + CAS_STR_YOU_WERE_NOT_AUTHENTICATED + => '

    Sie wurden nicht angemeldet.

    Um es erneut zu versuchen klicken Sie hier.

    Wenn das Problem bestehen bleibt, kontkatieren Sie den Administrator dieser Seite.

    ', + CAS_STR_SERVICE_UNAVAILABLE + => 'Der Dienst `%s\' ist nicht verfügbar (%s).' +); + +?> \ No newline at end of file diff --git a/include/limesurvey/admin/classes/phpCAS/CAS/languages/greek.php b/include/limesurvey/admin/classes/phpCAS/CAS/languages/greek.php new file mode 100644 index 00000000..c17b1d66 --- /dev/null +++ b/include/limesurvey/admin/classes/phpCAS/CAS/languages/greek.php @@ -0,0 +1,27 @@ + + * @sa @link internalLang Internationalization @endlink + * @ingroup internalLang + */ + +$this->_strings = array( + CAS_STR_USING_SERVER + => '÷ñçóéìïðïéåßôáé ï åîõðçñåôçôÞò', + CAS_STR_AUTHENTICATION_WANTED + => 'Áðáéôåßôáé ç ôáõôïðïßçóç CAS!', + CAS_STR_LOGOUT + => 'Áðáéôåßôáé ç áðïóýíäåóç áðü CAS!', + CAS_STR_SHOULD_HAVE_BEEN_REDIRECTED + => 'Èá Ýðñåðå íá åß÷áôå áíáêáôåõèõíèåß óôïí åîõðçñåôçôÞ CAS. ÊÜíôå êëßê åäþ ãéá íá óõíå÷ßóåôå.', + CAS_STR_AUTHENTICATION_FAILED + => 'Ç ôáõôïðïßçóç CAS áðÝôõ÷å!', + CAS_STR_YOU_WERE_NOT_AUTHENTICATED + => '

    Äåí ôáõôïðïéçèÞêáôå.

    Ìðïñåßôå íá îáíáðñïóðáèÞóåôå, êÜíïíôáò êëßê åäþ.

    Åáí ôï ðñüâëçìá åðéìåßíåé, åëÜôå óå åðáöÞ ìå ôïí äéá÷åéñéóôÞ.

    ', + CAS_STR_SERVICE_UNAVAILABLE + => 'Ç õðçñåóßá `%s\' äåí åßíáé äéáèÝóéìç (%s).' +); + +?> \ No newline at end of file diff --git a/include/limesurvey/admin/classes/phpCAS/CAS/languages/japanese.php b/include/limesurvey/admin/classes/phpCAS/CAS/languages/japanese.php new file mode 100644 index 00000000..333bb17b --- /dev/null +++ b/include/limesurvey/admin/classes/phpCAS/CAS/languages/japanese.php @@ -0,0 +1,27 @@ +_strings = array( + CAS_STR_USING_SERVER + => 'using server', + CAS_STR_AUTHENTICATION_WANTED + => 'CAS¤Ë¤è¤ëǧ¾Ú¤ò¹Ô¤¤¤Þ¤¹', + CAS_STR_LOGOUT + => 'CAS¤«¤é¥í¥°¥¢¥¦¥È¤·¤Þ¤¹!', + CAS_STR_SHOULD_HAVE_BEEN_REDIRECTED + => 'CAS¥µ¡¼¥Ð¤Ë¹Ô¤¯É¬Íפ¬¤¢¤ê¤Þ¤¹¡£¼«Æ°Åª¤ËžÁ÷¤µ¤ì¤Ê¤¤¾ì¹ç¤Ï ¤³¤Á¤é ¤ò¥¯¥ê¥Ã¥¯¤·¤ÆÂ³¹Ô¤·¤Þ¤¹¡£', + CAS_STR_AUTHENTICATION_FAILED + => 'CAS¤Ë¤è¤ëǧ¾Ú¤Ë¼ºÇÔ¤·¤Þ¤·¤¿', + CAS_STR_YOU_WERE_NOT_AUTHENTICATED + => '

    ǧ¾Ú¤Ç¤­¤Þ¤»¤ó¤Ç¤·¤¿.

    ¤â¤¦°ìÅ٥ꥯ¥¨¥¹¥È¤òÁ÷¿®¤¹¤ë¾ì¹ç¤Ï¤³¤Á¤é¤ò¥¯¥ê¥Ã¥¯.

    ÌäÂ꤬²ò·è¤·¤Ê¤¤¾ì¹ç¤Ï ¤³¤Î¥µ¥¤¥È¤Î´ÉÍý¼Ô¤ËÌ䤤¹ç¤ï¤»¤Æ¤¯¤À¤µ¤¤.

    ', + CAS_STR_SERVICE_UNAVAILABLE + => '¥µ¡¼¥Ó¥¹ `%s\' ¤ÏÍøÍѤǤ­¤Þ¤»¤ó (%s).' +); + +?> \ No newline at end of file diff --git a/include/limesurvey/admin/classes/phpCAS/CAS/languages/languages.php b/include/limesurvey/admin/classes/phpCAS/CAS/languages/languages.php new file mode 100644 index 00000000..2c6f8bb3 --- /dev/null +++ b/include/limesurvey/admin/classes/phpCAS/CAS/languages/languages.php @@ -0,0 +1,24 @@ + + * @sa @link internalLang Internationalization @endlink + * @ingroup internalLang + */ + +//@{ +/** + * a phpCAS string index + */ +define("CAS_STR_USING_SERVER", 1); +define("CAS_STR_AUTHENTICATION_WANTED", 2); +define("CAS_STR_LOGOUT", 3); +define("CAS_STR_SHOULD_HAVE_BEEN_REDIRECTED", 4); +define("CAS_STR_AUTHENTICATION_FAILED", 5); +define("CAS_STR_YOU_WERE_NOT_AUTHENTICATED", 6); +define("CAS_STR_SERVICE_UNAVAILABLE", 7); +//@} + +?> \ No newline at end of file diff --git a/include/limesurvey/admin/classes/phpCAS/CAS/languages/spanish.php b/include/limesurvey/admin/classes/phpCAS/CAS/languages/spanish.php new file mode 100644 index 00000000..3a8ffc25 --- /dev/null +++ b/include/limesurvey/admin/classes/phpCAS/CAS/languages/spanish.php @@ -0,0 +1,27 @@ + + * @sa @link internalLang Internationalization @endlink + * @ingroup internalLang + */ + +$this->_strings = array( + CAS_STR_USING_SERVER + => 'usando servidor', + CAS_STR_AUTHENTICATION_WANTED + => '¡Autentificación CAS necesaria!', + CAS_STR_LOGOUT + => '¡Salida CAS necesaria!', + CAS_STR_SHOULD_HAVE_BEEN_REDIRECTED + => 'Ya debería haber sido redireccionado al servidor CAS. Haga click aquí para continuar.', + CAS_STR_AUTHENTICATION_FAILED + => '¡Autentificación CAS fallida!', + CAS_STR_YOU_WERE_NOT_AUTHENTICATED + => '

    No estás autentificado.

    Puedes volver a intentarlo haciendo click aquí.

    Si el problema persiste debería contactar con el administrador de este sitio.

    ', + CAS_STR_SERVICE_UNAVAILABLE + => 'El servicio `%s\' no está disponible (%s).' +); + +?> diff --git a/include/limesurvey/admin/classes/phpCAS/README b/include/limesurvey/admin/classes/phpCAS/README new file mode 100644 index 00000000..9b38b2ad --- /dev/null +++ b/include/limesurvey/admin/classes/phpCAS/README @@ -0,0 +1,36 @@ +README +phpCAS - http://www.ja-sig.org/wiki/display/CASC/phpCAS +This software contains a client library for PHP, which can be used to identify +Central Authentication Service (CAS) authenticated users. + +Please see the phpCAS website for more information. + +http://www.ja-sig.org/wiki/display/CASC/phpCAS + +LICENSE +Copyright © 2003-2008, The ESUP-Portail consortium & the JA-SIG Collaborative. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + * Neither the name of the ESUP-Portail consortium & the JA-SIG + Collaborative nor the names of its contributors may be used to endorse or + promote products derived from this software without specific prior + written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/include/limesurvey/admin/classes/phpzip/phpzip.inc.php b/include/limesurvey/admin/classes/phpzip/phpzip.inc.php index b1c64243..41b76446 100644 --- a/include/limesurvey/admin/classes/phpzip/phpzip.inc.php +++ b/include/limesurvey/admin/classes/phpzip/phpzip.inc.php @@ -1,273 +1,271 @@ - GetFileList($dir); - } - - if ((!empty($dir))&&(!is_array($dir))&&(file_exists($dir))) chdir($dir); - else chdir($curdir); - - if (count($filelist)>0) - { - foreach($filelist as $filename) - { - if (is_file($filename)) - { - $fd = fopen ($filename, "r"); - $content = fread ($fd, filesize ($filename)); - fclose ($fd); - - if (is_array($dir)) $filename = basename($filename); - $this -> addFile($content, $filename); - } - } - $out = $this -> file(); - - chdir($curdir); - $fp = fopen($zipfilename, "w"); - fwrite($fp, $out, strlen($out)); - fclose($fp); - } - return 1; - } - else return 0; - } - - function GetFileList($dir) - { - $file=Array(); - if (file_exists($dir)) - { - $args = func_get_args(); - if(isset($args[1])) {$pref = $args[1];} else {$pref="";} - - $dh = opendir($dir); - while($files = readdir($dh)) - { - if (($files!=".")&&($files!="..")) - { - if (!is_dir($dir.$files)) - { - $file[]=$pref.$files; - } - } - } - closedir($dh); - } - return $file; - } - - var $datasec = array(); - var $ctrl_dir = array(); - var $eof_ctrl_dir = "\x50\x4b\x05\x06\x00\x00\x00\x00"; - var $old_offset = 0; - - /** - * Converts an Unix timestamp to a four byte DOS date and time format (date - * in high two bytes, time in low two bytes allowing magnitude comparison). - * - * @param integer the current Unix timestamp - * - * @return integer the current date in a four byte DOS format - * - * @access private - */ - function unix2DosTime($unixtime = 0) { - $timearray = ($unixtime == 0) ? getdate() : getdate($unixtime); - - if ($timearray['year'] < 1980) { - $timearray['year'] = 1980; - $timearray['mon'] = 1; - $timearray['mday'] = 1; - $timearray['hours'] = 0; - $timearray['minutes'] = 0; - $timearray['seconds'] = 0; - } // end if - - return (($timearray['year'] - 1980) << 25) | ($timearray['mon'] << 21) | ($timearray['mday'] << 16) | - ($timearray['hours'] << 11) | ($timearray['minutes'] << 5) | ($timearray['seconds'] >> 1); - } // end of the 'unix2DosTime()' method - - - /** - * Adds "file" to archive - * - * @param string file contents - * @param string name of the file in the archive (may contains the path) - * @param integer the current timestamp - * - * @access public - */ - function addFile($data, $name, $time = 0) - { - $name = str_replace('\\', '/', $name); - - $dtime = dechex($this->unix2DosTime($time)); - $hexdtime = '\x' . $dtime[6] . $dtime[7] - . '\x' . $dtime[4] . $dtime[5] - . '\x' . $dtime[2] . $dtime[3] - . '\x' . $dtime[0] . $dtime[1]; - eval('$hexdtime = "' . $hexdtime . '";'); - - $fr = "\x50\x4b\x03\x04"; - $fr .= "\x14\x00"; // ver needed to extract - $fr .= "\x00\x00"; // gen purpose bit flag - $fr .= "\x08\x00"; // compression method - $fr .= $hexdtime; // last mod time and date - - // "local file header" segment - $unc_len = strlen($data); - $crc = crc32($data); - $zdata = gzcompress($data); - $c_len = strlen($zdata); - $zdata = substr(substr($zdata, 0, strlen($zdata) - 4), 2); // fix crc bug - $fr .= pack('V', $crc); // crc32 - $fr .= pack('V', $c_len); // compressed filesize - $fr .= pack('V', $unc_len); // uncompressed filesize - $fr .= pack('v', strlen($name)); // length of filename - $fr .= pack('v', 0); // extra field length - $fr .= $name; - - // "file data" segment - $fr .= $zdata; - - // "data descriptor" segment (optional but necessary if archive is not - // served as file) - $fr .= pack('V', $crc); // crc32 - $fr .= pack('V', $c_len); // compressed filesize - $fr .= pack('V', $unc_len); // uncompressed filesize - - // add this entry to array - $this -> datasec[] = $fr; - $new_offset = strlen(implode('', $this->datasec)); - - // now add to central directory record - $cdrec = "\x50\x4b\x01\x02"; - $cdrec .= "\x00\x00"; // version made by - $cdrec .= "\x14\x00"; // version needed to extract - $cdrec .= "\x00\x00"; // gen purpose bit flag - $cdrec .= "\x08\x00"; // compression method - $cdrec .= $hexdtime; // last mod time & date - $cdrec .= pack('V', $crc); // crc32 - $cdrec .= pack('V', $c_len); // compressed filesize - $cdrec .= pack('V', $unc_len); // uncompressed filesize - $cdrec .= pack('v', strlen($name) ); // length of filename - $cdrec .= pack('v', 0 ); // extra field length - $cdrec .= pack('v', 0 ); // file comment length - $cdrec .= pack('v', 0 ); // disk number start - $cdrec .= pack('v', 0 ); // internal file attributes - $cdrec .= pack('V', 32 ); // external file attributes - 'archive' bit set - - $cdrec .= pack('V', $this -> old_offset ); // relative offset of local header - $this -> old_offset = $new_offset; - - $cdrec .= $name; - - // optional extra field, file comment goes here - // save to central directory - $this -> ctrl_dir[] = $cdrec; - } // end of the 'addFile()' method - - - /** - * Dumps out file - * - * @return string the zipped file - * - * @access public - */ - function file() - { - $data = implode('', $this -> datasec); - $ctrldir = implode('', $this -> ctrl_dir); - - return - $data . - $ctrldir . - $this -> eof_ctrl_dir . - pack('v', sizeof($this -> ctrl_dir)) . // total # of entries "on this disk" - pack('v', sizeof($this -> ctrl_dir)) . // total # of entries overall - pack('V', strlen($ctrldir)) . // size of central dir - pack('V', strlen($data)) . // offset to start of central dir - "\x00\x00"; // .zip file comment length - } // end of the 'file()' method - - -// This comes from http://de.tikiwiki.org/xref-BRANCH-1-9/nav.html?lib/sheet/include/org/apicnet/io/archive/CZip.php.source.html -function extract($dir, $zipfilename){ - if (function_exists("zip_open")) { - //$dir = eregi_replace("(\..*$)", "", $zipfilename); - - $this->createDir($dir); - $zip = zip_open($zipfilename); - if ($zip) { - while ($zip_entry = zip_read($zip)) { - if (zip_entry_open($zip, $zip_entry, "r")) { - $buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry)); -// if (eregi("(\/)", zip_entry_name($zip_entry))) $this->createDir($dir."/".eregi_replace("\/.*$", "", zip_entry_name($zip_entry))); - -// LimeSurvey Only extract first dir for the moment - if ( ! eregi("(\/)", zip_entry_name($zip_entry))) - { - $this->createFile($dir."/".zip_entry_name($zip_entry), $buf,zip_entry_filesize($zip_entry)); - } - zip_entry_close($zip_entry); - } - } - zip_close($zip); - } - else - { - return "Error:OpenZip"; - } - } - return 'OK'; - } - - function createDir($dir){ - if (eregi("(\/$)", $dir)) @mkdir (substr($dir, 0, strlen($dir) - 1)); - else @mkdir ($dir); - } - - - // This comes from http://fr.php.net/zip - function createFile($file, $data, $size){ - //$file = new File($file, TRUE); - //if ($file->exists()) { - // $file->delFile(); - // $file->createFile(); - //} - //$file->writeData($data); - - if (is_file($file)) - { - unlink($file); - } - $fopen = fopen($file, "w"); - fwrite($fopen,$data,$size); - } - -} // end of the 'PHPZip' class -?> + GetFileList($dir); + } + + if ((!empty($dir))&&(!is_array($dir))&&(file_exists($dir))) chdir($dir); + else chdir($curdir); + + if (count($filelist)>0) + { + foreach($filelist as $filename) + { + if (is_file($filename)) + { + $fd = fopen ($filename, "r"); + $content = @fread ($fd, filesize ($filename)); + fclose ($fd); + + if (is_array($dir)) $filename = basename($filename); + $this -> addFile($content, $filename); + } + } + $out = $this -> file(); + + chdir($curdir); + $fp = fopen($zipfilename, "w"); + fwrite($fp, $out, strlen($out)); + fclose($fp); + } + return 1; + } + else return 0; + } + + function GetFileList($dir) + { + $file=Array(); + if (file_exists($dir)) + { + $args = func_get_args(); + if(isset($args[1])) {$pref = $args[1];} else {$pref="";} + + $dh = opendir($dir); + while($files = readdir($dh)) + { + if (($files!=".")&&($files!="..")) + { + if (!is_dir($dir.$files)) + { + $file[]=$pref.$files; + } + } + } + closedir($dh); + } + return $file; + } + + var $datasec = array(); + var $ctrl_dir = array(); + var $eof_ctrl_dir = "\x50\x4b\x05\x06\x00\x00\x00\x00"; + var $old_offset = 0; + + /** + * Converts an Unix timestamp to a four byte DOS date and time format (date + * in high two bytes, time in low two bytes allowing magnitude comparison). + * + * @param integer the current Unix timestamp + * + * @return integer the current date in a four byte DOS format + * + * @access private + */ + function unix2DosTime($unixtime = 0) { + $timearray = ($unixtime == 0) ? getdate() : getdate($unixtime); + + if ($timearray['year'] < 1980) { + $timearray['year'] = 1980; + $timearray['mon'] = 1; + $timearray['mday'] = 1; + $timearray['hours'] = 0; + $timearray['minutes'] = 0; + $timearray['seconds'] = 0; + } // end if + + return (($timearray['year'] - 1980) << 25) | ($timearray['mon'] << 21) | ($timearray['mday'] << 16) | + ($timearray['hours'] << 11) | ($timearray['minutes'] << 5) | ($timearray['seconds'] >> 1); + } // end of the 'unix2DosTime()' method + + + /** + * Adds "file" to archive + * + * @param string file contents + * @param string name of the file in the archive (may contains the path) + * @param integer the current timestamp + * + * @access public + */ + function addFile($data, $name, $time = 0) + { + $name = str_replace('\\', '/', $name); + + $dtime = dechex($this->unix2DosTime($time)); + $hexdtime = '\x' . $dtime[6] . $dtime[7] + . '\x' . $dtime[4] . $dtime[5] + . '\x' . $dtime[2] . $dtime[3] + . '\x' . $dtime[0] . $dtime[1]; + eval('$hexdtime = "' . $hexdtime . '";'); + + $fr = "\x50\x4b\x03\x04"; + $fr .= "\x14\x00"; // ver needed to extract + $fr .= "\x00\x00"; // gen purpose bit flag + $fr .= "\x08\x00"; // compression method + $fr .= $hexdtime; // last mod time and date + + // "local file header" segment + $unc_len = strlen($data); + $crc = crc32($data); + $zdata = gzcompress($data); + $c_len = strlen($zdata); + $zdata = substr(substr($zdata, 0, strlen($zdata) - 4), 2); // fix crc bug + $fr .= pack('V', $crc); // crc32 + $fr .= pack('V', $c_len); // compressed filesize + $fr .= pack('V', $unc_len); // uncompressed filesize + $fr .= pack('v', strlen($name)); // length of filename + $fr .= pack('v', 0); // extra field length + $fr .= $name; + + // "file data" segment + $fr .= $zdata; + + // "data descriptor" segment (optional but necessary if archive is not + // served as file) + $fr .= pack('V', $crc); // crc32 + $fr .= pack('V', $c_len); // compressed filesize + $fr .= pack('V', $unc_len); // uncompressed filesize + + // add this entry to array + $this -> datasec[] = $fr; + $new_offset = strlen(implode('', $this->datasec)); + + // now add to central directory record + $cdrec = "\x50\x4b\x01\x02"; + $cdrec .= "\x00\x00"; // version made by + $cdrec .= "\x14\x00"; // version needed to extract + $cdrec .= "\x00\x00"; // gen purpose bit flag + $cdrec .= "\x08\x00"; // compression method + $cdrec .= $hexdtime; // last mod time & date + $cdrec .= pack('V', $crc); // crc32 + $cdrec .= pack('V', $c_len); // compressed filesize + $cdrec .= pack('V', $unc_len); // uncompressed filesize + $cdrec .= pack('v', strlen($name) ); // length of filename + $cdrec .= pack('v', 0 ); // extra field length + $cdrec .= pack('v', 0 ); // file comment length + $cdrec .= pack('v', 0 ); // disk number start + $cdrec .= pack('v', 0 ); // internal file attributes + $cdrec .= pack('V', 32 ); // external file attributes - 'archive' bit set + + $cdrec .= pack('V', $this -> old_offset ); // relative offset of local header + $this -> old_offset = $new_offset; + + $cdrec .= $name; + + // optional extra field, file comment goes here + // save to central directory + $this -> ctrl_dir[] = $cdrec; + } // end of the 'addFile()' method + + + /** + * Dumps out file + * + * @return string the zipped file + * + * @access public + */ + function file() + { + $data = implode('', $this -> datasec); + $ctrldir = implode('', $this -> ctrl_dir); + + return + $data . + $ctrldir . + $this -> eof_ctrl_dir . + pack('v', sizeof($this -> ctrl_dir)) . // total # of entries "on this disk" + pack('v', sizeof($this -> ctrl_dir)) . // total # of entries overall + pack('V', strlen($ctrldir)) . // size of central dir + pack('V', strlen($data)) . // offset to start of central dir + "\x00\x00"; // .zip file comment length + } // end of the 'file()' method + + +// This comes from http://de.tikiwiki.org/xref-BRANCH-1-9/nav.html?lib/sheet/include/org/apicnet/io/archive/CZip.php.source.html +function extract($dir, $zipfilename){ + if (function_exists("zip_open")) { + + $this->createDir($dir); + $zip = zip_open($zipfilename); + if ($zip) { + while ($zip_entry = zip_read($zip)) { + if (zip_entry_open($zip, $zip_entry, "r")) { + $buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry)); + + // LimeSurvey Only extract first dir for the moment + if ( ! preg_match("/(\/)/i", zip_entry_name($zip_entry))) + { + $this->createFile($dir."/".zip_entry_name($zip_entry), $buf,zip_entry_filesize($zip_entry)); + } + zip_entry_close($zip_entry); + } + } + zip_close($zip); + } + else + { + return "Error:OpenZip"; + } + } + return 'OK'; + } + + function createDir($dir){ + if (preg_match("/(\/$)/", $dir)) @mkdir (substr($dir, 0, strlen($dir) - 1)); + else @mkdir ($dir); + } + + + // This comes from http://fr.php.net/zip + function createFile($file, $data, $size){ + //$file = new File($file, TRUE); + //if ($file->exists()) { + // $file->delFile(); + // $file->createFile(); + //} + //$file->writeData($data); + + if (is_file($file)) + { + unlink($file); + } + $fopen = fopen($file, "w"); + fwrite($fopen,$data,$size); + } + +} // end of the 'PHPZip' class +?> diff --git a/include/limesurvey/admin/classes/tcpdf/checkphpversion.php b/include/limesurvey/admin/classes/tcpdf/checkphpversion.php deleted file mode 100644 index 692d0938..00000000 --- a/include/limesurvey/admin/classes/tcpdf/checkphpversion.php +++ /dev/null @@ -1,10 +0,0 @@ -')) -{ - require_once('tcpdf_php4.php'); -} -else if (version_compare(PHP_VERSION, '5.0.0', '>')) -{ - require_once('tcpdf.php'); -} -?> diff --git a/include/limesurvey/admin/classes/tcpdf/extensiontcpdf.php b/include/limesurvey/admin/classes/tcpdf/extensiontcpdf.php index 79a52893..0d7f387b 100644 --- a/include/limesurvey/admin/classes/tcpdf/extensiontcpdf.php +++ b/include/limesurvey/admin/classes/tcpdf/extensiontcpdf.php @@ -1,19 +1,12 @@ ')) - { - parent::TCPDF($orientation,$unit,$format); - } - else if(version_compare(PHP_VERSION, '5.0.0', '>')) - { - parent::__construct($orientation,$unit,$format); - } + parent::__construct($orientation,$unit,$format); $this->SetAutoPageBreak(true,10); $this->AliasNbPages(); @@ -21,6 +14,7 @@ class PDF extends TCPDF function intopdf($text,$format='') { + $text = $this->delete_html($text); $oldformat = $this->FontStyle; $this->SetFont('',$format,$this->FontSizePt); $this->Write(5,$text); @@ -31,7 +25,7 @@ class PDF extends TCPDF { $oldsize = $this->FontSizePt; $this->SetFontSize($oldsize-2); - $this->Write(5,$text); + $this->Write(5,$this->delete_html($text)); $this->ln(5); $this->SetFontSize($oldsize); } @@ -39,6 +33,7 @@ class PDF extends TCPDF { if(!empty($title)) { + $title = $this->delete_html($title); $oldsize = $this->FontSizePt; $this->SetFontSize($oldsize+4); $this->Line(5,$this->y,($this->w-5),$this->y); @@ -46,6 +41,7 @@ class PDF extends TCPDF $this->MultiCell('','',$title,'','C',0); if(!empty($description) && isset($description)) { + $description = $this->delete_html($description); $this->ln(7); $this->SetFontSize($oldsize+2); $this->MultiCell('','',$description,'','C',0); @@ -68,7 +64,7 @@ class PDF extends TCPDF { for($b=0;$bCell($maxwidth[$b]*($this->FontSize),4,$array[$a][$b],0,0,'C'); + $this->Cell($maxwidth[$b]*($this->FontSize),4,$this->delete_html($array[$a][$b]),0,0,'C'); } $this->ln(); } @@ -99,5 +95,11 @@ class PDF extends TCPDF { $this->Output($name,"D"); } + + function delete_html($text) + { + $text = html_entity_decode($text); + return strip_tags($text); + } } ?> diff --git a/include/limesurvey/admin/classes/tcpdf/tcpdf.php b/include/limesurvey/admin/classes/tcpdf/tcpdf.php index e55b1f08..b266800c 100644 --- a/include/limesurvey/admin/classes/tcpdf/tcpdf.php +++ b/include/limesurvey/admin/classes/tcpdf/tcpdf.php @@ -5548,7 +5548,7 @@ if(!class_exists('TCPDF', false)) { if (isset($dash)) { $dash_string = ""; if ($dash) { - if (ereg("^.+,", $dash)) { + if (preg_match("/^.+,/", $dash)) { $tab = explode(",", $dash); } else { $tab = array($dash); diff --git a/include/limesurvey/admin/classes/tcpdf/tcpdf_php4.php b/include/limesurvey/admin/classes/tcpdf/tcpdf_php4.php deleted file mode 100644 index 39cd5a14..00000000 --- a/include/limesurvey/admin/classes/tcpdf/tcpdf_php4.php +++ /dev/null @@ -1,7786 +0,0 @@ -. -// -// See LICENSE.TXT file for more information. -// ---------------------------------------------------------------------------- -// -// Description : This is a PHP class for generating PDF -// documents without requiring external -// extensions. -// -// NOTE: -// This class was originally derived in 2002 from the Public -// Domain FPDF class by Olivier Plathey (http://www.fpdf.org). -// -// Main features: -// * no external libraries are required for the basic functions; -// * supports all ISO page formats; -// * supports UTF-8 Unicode and Right-To-Left languages; -// * supports document encryption; -// * includes methods to publish some xhtml code; -// * includes graphic and transformation methods; -// * includes bookmarks; -// * includes Javascript and forms support; -// * includes a method to print various barcode formats (requires GD library); -// * supports TrueTypeUnicode, TrueType, Type1 and encoding; -// * supports custom page formats, margins and units of measure; -// * includes methods for page header and footer management; -// * supports automatic page break; -// * supports automatic page numbering and page groups; -// * supports automatic line break and text justification; -// * supports JPEG and PNG images whitout GD library and all images supported by GD: GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM; -// * supports stroke and clipping mode for text; -// * supports Grayscale, RGB and CMYK colors and transparency; -// * supports links; -// * supports page compression (requires zlib extension); -// * supports PDF user's rights. -// -// ----------------------------------------------------------- -// THANKS TO: -// -// Olivier Plathey (http://www.fpdf.org) for original FPDF. -// Efthimios Mavrogeorgiadis (emavro@yahoo.com) for suggestions on RTL language support. -// Klemen Vodopivec (http://www.fpdf.de/downloads/addons/37/) for Encryption algorithm. -// Warren Sherliker (wsherliker@gmail.com) for better image handling. -// dullus for text Justification. -// Bob Vincent (pillarsdotnet@users.sourceforge.net) for
  • value attribute. -// Patrick Benny for text stretch suggestion on Cell(). -// Johannes Güntert for JavaScript support. -// Denis Van Nuffelen for Dynamic Form. -// Jacek Czekaj for multibyte justification -// Anthony Ferrara for the reintroduction of legacy image methods. -// Sourceforge user 1707880 (hucste) for line-trough mode. -// Larry Stanbery for page groups. -// Martin Hall-May for transparency. -// Aaron C. Spike for Polycurve method. -// Saleh AlMatrafe for arabic support. -// Mohamad Ali Golkar for persian and arabic shaping support. -// Anyone that has reported a bug or sent a suggestion. -//============================================================+ - -/** - * This is a PHP class for generating PDF documents without requiring external extensions.
    - * TCPDF project (http://www.tcpdf.org) was originally derived in 2002 from the Public Domain FPDF class by Olivier Plathey (http://www.fpdf.org).
    - *

    TCPDF main features are:

    - * - * Tools to encode your unicode fonts are on fonts/ttf2ufm directory.

    - * @name TCPDF - * @package com.tecnick.tcpdf - * @abstract Class for generating PDF files on-the-fly without requiring external extensions. - * @author Nicola Asuni - * @copyright 2004-2008 Nicola Asuni - Tecnick.com S.r.l (www.tecnick.com) Via Della Pace, 11 - 09044 - Quartucciu (CA) - ITALY - www.tecnick.com - info@tecnick.com - * @link http://www.tcpdf.org - * @license http://www.gnu.org/copyleft/lesser.html LGPL - * @version 3.0.014_PHP4 - */ - -/** - * include configuration file - */ -require_once(dirname(__FILE__).'/config/tcpdf_config.php'); - -if(!class_exists('TCPDF')) { - /** - * define default PDF document producer - */ - define('PDF_PRODUCER','TCPDF 3.0.014_PHP4 (http://www.tcpdf.org)'); - - /** - * This is a PHP class for generating PDF files on-the-fly without requiring external extensions.
    - * TCPDF project (http://tcpdf.sourceforge.net) has been originally derived from the Public Domain FPDF class by Olivier Plathey (http://www.fpdf.org).
    - * To add your own TTF fonts please read /fonts/README.TXT - * @name TCPDF - * @package com.tecnick.tcpdf - * @version 3.0.014_PHP4 - * @author Nicola Asuni - * @link http://www.tcpdf.org - * @license http://www.gnu.org/copyleft/lesser.html LGPL - */ - class TCPDF { - - // protected or Protected properties - - /** - * @var current page number - * @access protected - */ - var $page; - - /** - * @var current object number - * @access protected - */ - var $n; - - /** - * @var array of object offsets - * @access protected - */ - var $offsets; - - /** - * @var buffer holding in-memory PDF - * @access protected - */ - var $buffer; - - /** - * @var array containing pages - * @access protected - */ - var $pages; - - /** - * @var current document state - * @access protected - */ - var $state; - - /** - * @var compression flag - * @access protected - */ - var $compress; - - /** - * @var default page orientation (P = Portrait, L = Landscape) - * @access protected - */ - var $DefOrientation; - - /** - * @var current page orientation (P = Portrait, L = Landscape) - * @access protected - */ - var $CurOrientation; - - /** - * @var array indicating page orientation changes - * @access protected - */ - var $OrientationChanges; - - /** - * @var scale factor (number of points in user unit) - * @access protected - */ - var $k; - - /** - * @var width of page format in points - * @access protected - */ - var $fwPt; - - /** - * @var height of page format in points - * @access protected - */ - var $fhPt; - - /** - * @var width of page format in user unit - * @access protected - */ - var $fw; - - /** - * @var height of page format in user unit - * @access protected - */ - var $fh; - - /** - * @var current width of page in points - * @access protected - */ - var $wPt; - - /** - * @var current height of page in points - * @access protected - */ - var $hPt; - - /** - * @var current width of page in user unit - * @access protected - */ - var $w; - - /** - * @var current height of page in user unit - * @access protected - */ - var $h; - - /** - * @var left margin - * @access protected - */ - var $lMargin; - - /** - * @var top margin - * @access protected - */ - var $tMargin; - - /** - * @var right margin - * @access protected - */ - var $rMargin; - - /** - * @var page break margin - * @access protected - */ - var $bMargin; - - /** - * @var cell internal padding - * @access protected - */ - var $cMargin; - - /** - * @var current horizontal position in user unit for cell positioning - * @access protected - */ - var $x; - - /** - * @var current vertical position in user unit for cell positioning - * @access protected - */ - var $y; - - /** - * @var height of last cell printed - * @access protected - */ - var $lasth; - - /** - * @var line width in user unit - * @access protected - */ - var $LineWidth; - - /** - * @var array of standard font names - * @access protected - */ - var $CoreFonts; - - /** - * @var array of used fonts - * @access protected - */ - var $fonts; - - /** - * @var array of font files - * @access protected - */ - var $FontFiles; - - /** - * @var array of encoding differences - * @access protected - */ - var $diffs; - - /** - * @var array of used images - * @access protected - */ - var $images; - - /** - * @var array of links in pages - * @access protected - */ - var $PageLinks; - - /** - * @var array of internal links - * @access protected - */ - var $links; - - /** - * @var current font family - * @access protected - */ - var $FontFamily; - - /** - * @var current font style - * @access protected - */ - var $FontStyle; - - /** - * @var current font ascent (distance between font top and baseline) - * @access protected - * @since 2.8.000 (2007-03-29) - */ - var $FontAscent; - - /** - * @var current font descent (distance between font bottom and baseline) - * @access protected - * @since 2.8.000 (2007-03-29) - */ - var $FontDescent; - - /** - * @var underlining flag - * @access protected - */ - var $underline; - - /** - * @var current font info - * @access protected - */ - var $CurrentFont; - - /** - * @var current font size in points - * @access protected - */ - var $FontSizePt; - - /** - * @var current font size in user unit - * @access protected - */ - var $FontSize; - - /** - * @var commands for drawing color - * @access protected - */ - var $DrawColor; - - /** - * @var commands for filling color - * @access protected - */ - var $FillColor; - - /** - * @var commands for text color - * @access protected - */ - var $TextColor; - - /** - * @var indicates whether fill and text colors are different - * @access protected - */ - var $ColorFlag; - - /** - * @var word spacing - * @access protected - */ - var $ws; - - /** - * @var automatic page breaking - * @access protected - */ - var $AutoPageBreak; - - /** - * @var threshold used to trigger page breaks - * @access protected - */ - var $PageBreakTrigger; - - /** - * @var flag set when processing footer - * @access protected - */ - var $InFooter; - - /** - * @var zoom display mode - * @access protected - */ - var $ZoomMode; - - /** - * @var layout display mode - * @access protected - */ - var $LayoutMode; - - /** - * @var title - * @access protected - */ - var $title; - - /** - * @var subject - * @access protected - */ - var $subject; - - /** - * @var author - * @access protected - */ - var $author; - - /** - * @var keywords - * @access protected - */ - var $keywords; - - /** - * @var creator - * @access protected - */ - var $creator; - - /** - * @var alias for total number of pages - * @access protected - */ - var $AliasNbPages; - - /** - * @var right-bottom corner X coordinate of inserted image - * @since 2002-07-31 - * @author Nicola Asuni - * @access protected - */ - var $img_rb_x; - - /** - * @var right-bottom corner Y coordinate of inserted image - * @since 2002-07-31 - * @author Nicola Asuni - * @access protected - */ - var $img_rb_y; - - /** - * @var image scale factor - * @since 2004-06-14 - * @author Nicola Asuni - * @access protected - */ - var $imgscale = 1; - - /** - * @var boolean set to true when the input text is unicode (require unicode fonts) - * @since 2005-01-02 - * @author Nicola Asuni - * @access protected - */ - var $isunicode = false; - - /** - * @var PDF version - * @since 1.5.3 - * @access protected - */ - var $PDFVersion = "1.5"; - - - // ---------------------- - - /** - * @var Minimum distance between header and top page margin. - * @access protected - */ - var $header_margin; - - /** - * @var Minimum distance between footer and bottom page margin. - * @access protected - */ - var $footer_margin; - - /** - * @var original left margin value - * @access protected - * @since 1.53.0.TC013 - */ - var $original_lMargin; - - /** - * @var original right margin value - * @access protected - * @since 1.53.0.TC013 - */ - var $original_rMargin; - - /** - * @var Header font. - * @access protected - */ - var $header_font; - - /** - * @var Footer font. - * @access protected - */ - var $footer_font; - - /** - * @var Language templates. - * @access protected - */ - var $l; - - /** - * @var Barcode to print on page footer (only if set). - * @access protected - */ - var $barcode = false; - - /** - * @var If true prints header - * @access protected - */ - var $print_header = true; - - /** - * @var If true prints footer. - * @access protected - */ - var $print_footer = true; - - /** - * @var Header width (0 = full page width). - * @access protected - */ - var $header_width = 0; - - /** - * @var Header image logo. - * @access protected - */ - var $header_logo = ""; - - /** - * @var Header image logo width in mm. - * @access protected - */ - var $header_logo_width = 30; - - /** - * @var String to print as title on document header. - * @access protected - */ - var $header_title = ""; - - /** - * @var String to print on document header. - * @access protected - */ - var $header_string = ""; - - /** - * @var Default number of columns for html table. - * @access protected - */ - var $default_table_columns = 4; - - - // variables for html parser - - /** - * @var HTML PARSER: store current link. - * @access protected - */ - var $HREF; - - /** - * @var HTML PARSER: store font list. - * @access protected - */ - var $fontList; - - /** - * @var HTML PARSER: true when font attribute is set. - * @access protected - */ - var $issetfont; - - /** - * @var HTML PARSER: array of foreground colors - * @access protected - */ - var $fgcolor; - - /** - * @var HTML PARSER: true in case of ordered list (OL), false otherwise. - * @access protected - */ - var $listordered = false; - - /** - * @var HTML PARSER: count list items. - * @access protected - */ - var $listcount = 0; - - /** - * @var HTML PARSER: size of table border. - * @access protected - */ - var $tableborder = 0; - - /** - * @var HTML PARSER: 'th' or 'td' ath the beginning of HTML cell. - * @access protected - */ - var $tdbegin = false; - - /** - * @var HTML PARSER: table width. - * @access protected - */ - var $tdwidth = 0; - - /** - * @var HTML PARSER: table height. - * @access protected - */ - var $tdheight = 0; - - /** - * @var HTML PARSER: table align. - * @access protected - */ - var $tdalign = "L"; - - /** - * @var HTML PARSER: array of background colors - * @access protected - */ - var $bgcolor; - - /** - * @var Store temporary font size in points. - * @access protected - */ - var $tempfontsize = 10; - - /** - * @var Bold font style status. - * @access protected - */ - var $b; - - /** - * @var Underlined font style status. - * @access protected - */ - var $u; - - /** - * @var Italic font style status. - * @access protected - */ - var $i; - - /** - * @var Line through font style status. - * @access protected - * @since 2.8.000 (2008-03-19) - */ - var $d; - - /** - * @var spacer for LI tags. - * @access protected - */ - var $lispacer = ""; - - /** - * @var default encoding - * @access protected - * @since 1.53.0.TC010 - */ - var $encoding = "UTF-8"; - - /** - * @var PHP internal encoding - * @access protected - * @since 1.53.0.TC016 - */ - var $internal_encoding; - - /** - * @var store previous font family - * @access protected - * @since 1.53.0.TC017 - */ - var $prevFontFamily; - - /** - * @var store previous font style - * @access protected - * @since 1.53.0.TC017 - */ - var $prevFontStyle; - - /** - * @var indicates if the document language is Right-To-Left - * @access protected - * @since 2.0.000 - */ - var $rtl = false; - - /** - * @var used to force RTL or LTR string inversion - * @access protected - * @since 2.0.000 - */ - var $tmprtl = false; - - // --- Variables used for document encryption: - - /** - * Indicates whether document is protected - * @access protected - * @since 2.0.000 (2008-01-02) - */ - var $encrypted; - - /** - * U entry in pdf document - * @access protected - * @since 2.0.000 (2008-01-02) - */ - var $Uvalue; - - /** - * O entry in pdf document - * @access protected - * @since 2.0.000 (2008-01-02) - */ - var $Ovalue; - - /** - * P entry in pdf document - * @access protected - * @since 2.0.000 (2008-01-02) - */ - var $Pvalue; - - /** - * encryption object id - * @access protected - * @since 2.0.000 (2008-01-02) - */ - var $enc_obj_id; - - /** - * last RC4 key encrypted (cached for optimisation) - * @access protected - * @since 2.0.000 (2008-01-02) - */ - var $last_rc4_key; - - /** - * last RC4 computed key - * @access protected - * @since 2.0.000 (2008-01-02) - */ - var $last_rc4_key_c; - - // --- bookmark --- - - /** - * Outlines for bookmark - * @access protected - * @since 2.1.002 (2008-02-12) - */ - var $outlines = array(); - - /** - * Outline root for bookmark - * @access protected - * @since 2.1.002 (2008-02-12) - */ - var $OutlineRoot; - - - // --- javascript and form --- - - /** - * javascript code - * @access protected - * @since 2.1.002 (2008-02-12) - */ - var $javascript = ""; - - /** - * javascript counter - * @access protected - * @since 2.1.002 (2008-02-12) - */ - var $n_js; - - /** - * line trough state - * @access protected - * @since 2.8.000 (2008-03-19) - */ - var $linethrough; - - /** - * ID of html tags with bgcolor attribute - * @access protected - * @since 2.9.000 (2008-03-25) - */ - var $bgtag; - - // --- Variables used for User's Rights --- - // See PDF reference chapter 8.7 Digital Signatures - - /** - * If true enables user's rights on PDF reader - * @access protected - * @since 2.9.000 (2008-03-26) - */ - var $ur; - - /** - * Names specifying additional document-wide usage rights for the document. - * @access protected - * @since 2.9.000 (2008-03-26) - */ - var $ur_document; - - /** - * Names specifying additional annotation-related usage rights for the document. - * @access protected - * @since 2.9.000 (2008-03-26) - */ - var $ur_annots; - - /** - * Names specifying additional form-field-related usage rights for the document. - * @access protected - * @since 2.9.000 (2008-03-26) - */ - var $ur_form; - - /** - * Names specifying additional signature-related usage rights for the document. - * @access protected - * @since 2.9.000 (2008-03-26) - */ - var $ur_signature; - - /** - * Dot Per Inch Document Resolution (do not change) - * @access protected - * @since 3.0.000 (2008-03-27) - */ - var $dpi = 72; - - /** - * Indicates whether a new page group was requested - * @access protected - * @since 3.0.000 (2008-03-27) - */ - var $newpagegroup; - - /** - * Contains the number of pages of the groups - * @access protected - * @since 3.0.000 (2008-03-27) - */ - var $pagegroups; - - /** - * Contains the alias of the current page group - * @access protected - * @since 3.0.000 (2008-03-27) - */ - var $currpagegroup; - - /** - * Restrict the rendering of some elements to screen or printout. - * @access protected - * @since 3.0.000 (2008-03-27) - */ - var $visibility="all"; - - /** - * Print visibility. - * @access protected - * @since 3.0.000 (2008-03-27) - */ - var $n_ocg_print; - - /** - * View visibility. - * @access protected - * @since 3.0.000 (2008-03-27) - */ - var $n_ocg_view; - - /** - * Array of transparency objects and parameters. - * @access protected - * @since 3.0.000 (2008-03-27) - */ - var $extgstates; - - /** - * Set the default JPEG compression quality (1-100) - * @access protected - * @since 3.0.000 (2008-03-27) - */ - var $jpeg_quality; - - /** - * Colspan attribute value for the current HTML cell. - * @access protected - * @since 3.0.011 (2008-05-23) - */ - var $tdcolspan = 1; - - /** - * Default cell height ratio. - * @access protected - * @since 3.0.014_PHP4 (2008-05-23) - */ - var $cell_height_ratio = K_CELL_HEIGHT_RATIO; - - //------------------------------------------------------------ - // Public methods - //------------------------------------------------------------ - - /** - * This is the class constructor. - * It allows to set up the page format, the orientation and - * the measure unit used in all the methods (except for the font sizes). - * @since 1.0 - * @param string $orientation page orientation. Possible values are (case insensitive): - * @param string $unit User measure unit. Possible values are:
    A point equals 1/72 of inch, that is to say about 0.35 mm (an inch being 2.54 cm). This is a very common unit in typography; font sizes are expressed in that unit. - * @param mixed $format The format used for pages. It can be either one of the following values (case insensitive) or a custom format in the form of a two-element array containing the width and the height (expressed in the unit given by unit). - * @param boolean $unicode TRUE means that the input text is unicode (default = true) - * @param String $encoding charset encoding; default is UTF-8 - */ - function TCPDF($orientation='P', $unit='mm', $format='A4', $unicode=true, $encoding="UTF-8") { - - /* Set internal character encoding to ASCII */ - if (function_exists("mb_internal_encoding") AND mb_internal_encoding()) { - $this->internal_encoding = mb_internal_encoding(); - mb_internal_encoding("ASCII"); - } - - // set language direction - $this->rtl = $this->l['a_meta_dir']=='rtl' ? true : false; - $this->tmprtl = false; - - //Some checks - $this->_dochecks(); - - //Initialization of properties - $this->isunicode=$unicode; - $this->page=0; - $this->n=2; - $this->buffer=''; - $this->pages=array(); - $this->OrientationChanges=array(); - $this->state=0; - $this->fonts=array(); - $this->FontFiles=array(); - $this->diffs=array(); - $this->images=array(); - $this->links=array(); - $this->InFooter=false; - $this->lasth=0; - $this->FontFamily=''; - $this->FontStyle=''; - $this->FontSizePt=12; - $this->underline=false; - $this->linethrough=false; - $this->DrawColor='0 G'; - $this->FillColor='0 g'; - $this->TextColor='0 g'; - $this->ColorFlag=false; - $this->ws=0; - // encryption values - $this->encrypted=false; - $this->last_rc4_key=''; - $this->padding="\x28\xBF\x4E\x5E\x4E\x75\x8A\x41\x64\x00\x4E\x56\xFF\xFA\x01\x08\x2E\x2E\x00\xB6\xD0\x68\x3E\x80\x2F\x0C\xA9\xFE\x64\x53\x69\x7A"; - - //Standard Unicode fonts - $this->CoreFonts=array( - 'courier'=>'Courier', - 'courierB'=>'Courier-Bold', - 'courierI'=>'Courier-Oblique', - 'courierBI'=>'Courier-BoldOblique', - 'helvetica'=>'Helvetica', - 'helveticaB'=>'Helvetica-Bold', - 'helveticaI'=>'Helvetica-Oblique', - 'helveticaBI'=>'Helvetica-BoldOblique', - 'times'=>'Times-Roman', - 'timesB'=>'Times-Bold', - 'timesI'=>'Times-Italic', - 'timesBI'=>'Times-BoldItalic', - 'symbol'=>'Symbol', - 'zapfdingbats'=>'ZapfDingbats' - ); - - //Set scale factor - switch (strtolower($unit)) { - // points - case 'pt': {$this->k = 1; break;} - // millimeters - case 'mm': {$this->k = $this->dpi / 25.4; break;} - // centimeters - case 'cm': {$this->k = $this->dpi / 2.54; break;} - // inches - case 'in': {$this->k = $this->dpi; break;} - // unsupported unit - default : {$this->Error('Incorrect unit: '.$unit); break;} - } - - //Page format - if(is_string($format)) { - // Page formats (45 standard ISO paper formats and 4 american common formats). - // Paper cordinates are calculated in this way: (inches * 72) where (1 inch = 2.54 cm) - switch (strtoupper($format)){ - case '4A0': {$format = array(4767.87,6740.79); break;} - case '2A0': {$format = array(3370.39,4767.87); break;} - case 'A0': {$format = array(2383.94,3370.39); break;} - case 'A1': {$format = array(1683.78,2383.94); break;} - case 'A2': {$format = array(1190.55,1683.78); break;} - case 'A3': {$format = array(841.89,1190.55); break;} - case 'A4': default: {$format = array(595.28,841.89); break;} - case 'A5': {$format = array(419.53,595.28); break;} - case 'A6': {$format = array(297.64,419.53); break;} - case 'A7': {$format = array(209.76,297.64); break;} - case 'A8': {$format = array(147.40,209.76); break;} - case 'A9': {$format = array(104.88,147.40); break;} - case 'A10': {$format = array(73.70,104.88); break;} - case 'B0': {$format = array(2834.65,4008.19); break;} - case 'B1': {$format = array(2004.09,2834.65); break;} - case 'B2': {$format = array(1417.32,2004.09); break;} - case 'B3': {$format = array(1000.63,1417.32); break;} - case 'B4': {$format = array(708.66,1000.63); break;} - case 'B5': {$format = array(498.90,708.66); break;} - case 'B6': {$format = array(354.33,498.90); break;} - case 'B7': {$format = array(249.45,354.33); break;} - case 'B8': {$format = array(175.75,249.45); break;} - case 'B9': {$format = array(124.72,175.75); break;} - case 'B10': {$format = array(87.87,124.72); break;} - case 'C0': {$format = array(2599.37,3676.54); break;} - case 'C1': {$format = array(1836.85,2599.37); break;} - case 'C2': {$format = array(1298.27,1836.85); break;} - case 'C3': {$format = array(918.43,1298.27); break;} - case 'C4': {$format = array(649.13,918.43); break;} - case 'C5': {$format = array(459.21,649.13); break;} - case 'C6': {$format = array(323.15,459.21); break;} - case 'C7': {$format = array(229.61,323.15); break;} - case 'C8': {$format = array(161.57,229.61); break;} - case 'C9': {$format = array(113.39,161.57); break;} - case 'C10': {$format = array(79.37,113.39); break;} - case 'RA0': {$format = array(2437.80,3458.27); break;} - case 'RA1': {$format = array(1729.13,2437.80); break;} - case 'RA2': {$format = array(1218.90,1729.13); break;} - case 'RA3': {$format = array(864.57,1218.90); break;} - case 'RA4': {$format = array(609.45,864.57); break;} - case 'SRA0': {$format = array(2551.18,3628.35); break;} - case 'SRA1': {$format = array(1814.17,2551.18); break;} - case 'SRA2': {$format = array(1275.59,1814.17); break;} - case 'SRA3': {$format = array(907.09,1275.59); break;} - case 'SRA4': {$format = array(637.80,907.09); break;} - case 'LETTER': {$format = array(612.00,792.00); break;} - case 'LEGAL': {$format = array(612.00,1008.00); break;} - case 'EXECUTIVE': {$format = array(521.86,756.00); break;} - case 'FOLIO': {$format = array(612.00,936.00); break;} - // default: {$this->Error('Unknown page format: '.$format); break;} - } - $this->fwPt=$format[0]; - $this->fhPt=$format[1]; - } - else { - $this->fwPt=$format[0]*$this->k; - $this->fhPt=$format[1]*$this->k; - } - - $this->fw=$this->fwPt/$this->k; - $this->fh=$this->fhPt/$this->k; - - //Page orientation - $orientation=strtolower($orientation); - if($orientation=='p' or $orientation=='portrait') { - $this->DefOrientation='P'; - $this->wPt=$this->fwPt; - $this->hPt=$this->fhPt; - } - elseif($orientation=='l' or $orientation=='landscape') { - $this->DefOrientation='L'; - $this->wPt=$this->fhPt; - $this->hPt=$this->fwPt; - } - else { - $this->Error('Incorrect orientation: '.$orientation); - } - - $this->CurOrientation=$this->DefOrientation; - $this->w=$this->wPt/$this->k; - $this->h=$this->hPt/$this->k; - //Page margins (1 cm) - $margin=28.35/$this->k; - $this->SetMargins($margin,$margin); - //Interior cell margin (1 mm) - $this->cMargin=$margin/10; - //Line width (0.2 mm) - $this->LineWidth=.567/$this->k; - //Automatic page break - $this->SetAutoPageBreak(true,2*$margin); - //Full width display mode - $this->SetDisplayMode('fullwidth'); - //Compression - $this->SetCompression(true); - //Set default PDF version number - $this->PDFVersion = "1.5"; - - $this->encoding = $encoding; - $this->b = 0; - $this->i = 0; - $this->u = 0; - $this->HREF = ''; - $this->fontlist = array("arial", "times", "courier", "helvetica", "symbol"); - $this->issetfont = false; - $this->fgcolor = array(); - $this->bgcolor = array(); - $this->extgstates = array(); - $this->bgtag = array(); - $this->tableborder = 0; - $this->tdbegin = false; - $this->tdwidth= 0; - $this->tdheight = 0; - if($this->rtl) { - $this->tdalign = "R"; - } else { - $this->tdalign = "L"; - } - $this->SetFillColor(200, 200, 200, true); - $this->SetTextColor(0, 0, 0, true); - - // user's rights - $this->ur = false; - $this->ur_document = "/FullSave"; - $this->ur_annots = "/Create/Delete/Modify/Copy/Import/Export"; - $this->ur_form = "/Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate"; - $this->ur_signature = "/Modify"; - - // set default JPEG quality - $this->jpeg_quality = 75; - - // initialize some settings - $this->utf8Bidi(array("")); - } - - /** - * Enable or disable Right-To-Left language mode - * @param Boolean $enable if true enable Right-To-Left language mode. - * @since 2.0.000 (2008-01-03) - */ - function setRTL($enable) { - $this->rtl = $enable ? true : false; - $this->tmprtl = false; - } - - /** - * Force temporary RTL language direction - * @param mixed $mode can be false, 'L' for LTR or 'R' for RTL - * @since 2.1.000 (2008-01-09) - */ - function setTempRTL($mode) { - switch ($mode) { - case false: - case 'L': - case 'R': { - $this->tmprtl = $mode; - } - } - } - - /** - * Set the last cell height. - * @param float $h cell height. - * @author Nicola Asuni - * @since 1.53.0.TC034 - */ - function setLastH($h) { - $this->lasth=$h; - } - - /** - * Set the image scale. - * @param float $scale image scale. - * @author Nicola Asuni - * @since 1.5.2 - */ - function setImageScale($scale) { - $this->imgscale=$scale; - } - - /** - * Returns the image scale. - * @return float image scale. - * @author Nicola Asuni - * @since 1.5.2 - */ - function getImageScale() { - return $this->imgscale; - } - - /** - * Returns the page width in units. - * @return int page width. - * @author Nicola Asuni - * @since 1.5.2 - */ - function getPageWidth() { - return $this->w; - } - - /** - * Returns the page height in units. - * @return int page height. - * @author Nicola Asuni - * @since 1.5.2 - */ - function getPageHeight() { - return $this->h; - } - - /** - * Returns the page break margin. - * @return int page break margin. - * @author Nicola Asuni - * @since 1.5.2 - */ - function getBreakMargin() { - return $this->bMargin; - } - - /** - * Returns the scale factor (number of points in user unit). - * @return int scale factor. - * @author Nicola Asuni - * @since 1.5.2 - */ - function getScaleFactor() { - return $this->k; - } - - /** - * Defines the left, top and right margins. By default, they equal 1 cm. Call this method to change them. - * @param float $left Left margin. - * @param float $top Top margin. - * @param float $right Right margin. Default value is the left one. - * @since 1.0 - * @see SetLeftMargin(), SetTopMargin(), SetRightMargin(), SetAutoPageBreak() - */ - function SetMargins($left, $top, $right=-1) { - //Set left, top and right margins - $this->lMargin=$left; - $this->tMargin=$top; - if($right==-1) { - $right=$left; - } - $this->rMargin=$right; - } - - /** - * Defines the left margin. The method can be called before creating the first page. If the current abscissa gets out of page, it is brought back to the margin. - * @param float $margin The margin. - * @since 1.4 - * @see SetTopMargin(), SetRightMargin(), SetAutoPageBreak(), SetMargins() - */ - function SetLeftMargin($margin) { - //Set left margin - $this->lMargin=$margin; - if(($this->page > 0) AND ($this->x < $margin)) { - $this->x = $margin; - } - } - - /** - * Defines the top margin. The method can be called before creating the first page. - * @param float $margin The margin. - * @since 1.5 - * @see SetLeftMargin(), SetRightMargin(), SetAutoPageBreak(), SetMargins() - */ - function SetTopMargin($margin) { - //Set top margin - $this->tMargin=$margin; - if(($this->page > 0) AND ($this->y < $margin)) { - $this->y = $margin; - } - } - - /** - * Defines the right margin. The method can be called before creating the first page. - * @param float $margin The margin. - * @since 1.5 - * @see SetLeftMargin(), SetTopMargin(), SetAutoPageBreak(), SetMargins() - */ - function SetRightMargin($margin) { - $this->rMargin=$margin; - if(($this->page > 0) AND ($this->x > ($this->w - $margin))) { - $this->x = $this->w - $margin; - } - } - - /** - * Set the internal Cell padding. - * @param float $pad internal padding. - * @since 2.1.000 (2008-01-09) - * @see Cell(), SetLeftMargin(), SetTopMargin(), SetAutoPageBreak(), SetMargins() - */ - function SetCellPadding($pad) { - $this->cMargin=$pad; - } - - /** - * Enables or disables the automatic page breaking mode. When enabling, the second parameter is the distance from the bottom of the page that defines the triggering limit. By default, the mode is on and the margin is 2 cm. - * @param boolean $auto Boolean indicating if mode should be on or off. - * @param float $margin Distance from the bottom of the page. - * @since 1.0 - * @see Cell(), MultiCell(), AcceptPageBreak() - */ - function SetAutoPageBreak($auto, $margin=0) { - //Set auto page break mode and triggering margin - $this->AutoPageBreak = $auto; - $this->bMargin = $margin; - $this->PageBreakTrigger = $this->h - $margin; - } - - /** - * Defines the way the document is to be displayed by the viewer. The zoom level can be set: pages can be displayed entirely on screen, occupy the full width of the window, use real size, be scaled by a specific zooming factor or use viewer default (configured in the Preferences menu of Acrobat). The page layout can be specified too: single at once, continuous display, two columns or viewer default. By default, documents use the full width mode with continuous display. - * @param mixed $zoom The zoom to use. It can be one of the following string values or a number indicating the zooming factor to use. - * @param string $layout The page layout. Possible values are: - * @since 1.2 - */ - function SetDisplayMode($zoom, $layout='continuous') { - //Set display mode in viewer - if($zoom=='fullpage' or $zoom=='fullwidth' or $zoom=='real' or $zoom=='default' or !is_string($zoom)) { - $this->ZoomMode=$zoom; - } - else { - $this->Error('Incorrect zoom display mode: '.$zoom); - } - if($layout=='single' or $layout=='continuous' or $layout=='two' or $layout=='default') { - $this->LayoutMode=$layout; - } - else { - $this->Error('Incorrect layout display mode: '.$layout); - } - } - - /** - * Activates or deactivates page compression. When activated, the internal representation of each page is compressed, which leads to a compression ratio of about 2 for the resulting document. Compression is on by default. - * Note: the Zlib extension is required for this feature. If not present, compression will be turned off. - * @param boolean $compress Boolean indicating if compression must be enabled. - * @since 1.4 - */ - function SetCompression($compress) { - //Set page compression - if(function_exists('gzcompress')) { - $this->compress=$compress; - } - else { - $this->compress=false; - } - } - - /** - * Defines the title of the document. - * @param string $title The title. - * @since 1.2 - * @see SetAuthor(), SetCreator(), SetKeywords(), SetSubject() - */ - function SetTitle($title) { - //Title of document - $this->title=$title; - } - - /** - * Defines the subject of the document. - * @param string $subject The subject. - * @since 1.2 - * @see SetAuthor(), SetCreator(), SetKeywords(), SetTitle() - */ - function SetSubject($subject) { - //Subject of document - $this->subject=$subject; - } - - /** - * Defines the author of the document. - * @param string $author The name of the author. - * @since 1.2 - * @see SetCreator(), SetKeywords(), SetSubject(), SetTitle() - */ - function SetAuthor($author) { - //Author of document - $this->author=$author; - } - - /** - * Associates keywords with the document, generally in the form 'keyword1 keyword2 ...'. - * @param string $keywords The list of keywords. - * @since 1.2 - * @see SetAuthor(), SetCreator(), SetSubject(), SetTitle() - */ - function SetKeywords($keywords) { - //Keywords of document - $this->keywords=$keywords; - } - - /** - * Defines the creator of the document. This is typically the name of the application that generates the PDF. - * @param string $creator The name of the creator. - * @since 1.2 - * @see SetAuthor(), SetKeywords(), SetSubject(), SetTitle() - */ - function SetCreator($creator) { - //Creator of document - $this->creator=$creator; - } - - /** - * Defines an alias for the total number of pages. It will be substituted as the document is closed.
    - * Example:
    - *
    -		* class PDF extends TCPDF {
    -		* 	function Footer() {
    -		* 		//Go to 1.5 cm from bottom
    -		* 		$this->SetY(-15);
    -		* 		//Select vera italic 8
    -		* 		$this->SetFont('vera','I',8);
    -		* 		//Print current and total page numbers
    -		* 		$this->Cell(0,10,'Page '.$this->PageNo().'/{nb}',0,0,'C');
    -		* 	}
    -		* }
    -		* $pdf=new PDF();
    -		* $pdf->AliasNbPages();
    -		* 
    - * @param string $alias The alias. Default value: {nb}. - * @since 1.4 - * @see PageNo(), Footer() - */ - function AliasNbPages($alias='{nb}') { - //Define an alias for total number of pages - $this->AliasNbPages = $this->_escapetext($alias); - } - - /** - * This method is automatically called in case of fatal error; it simply outputs the message and halts the execution. An inherited class may override it to customize the error handling but should always halt the script, or the resulting document would probably be invalid. - * 2004-06-11 :: Nicola Asuni : changed bold tag with strong - * @param string $msg The error message - * @since 1.0 - */ - function Error($msg) { - //Fatal error - die('TCPDF error: '.$msg); - } - - /** - * This method begins the generation of the PDF document. It is not necessary to call it explicitly because AddPage() does it automatically. - * Note: no page is created by this method - * @since 1.0 - * @see AddPage(), Close() - */ - function Open() { - //Begin document - $this->state=1; - } - - /** - * Terminates the PDF document. It is not necessary to call this method explicitly because Output() does it automatically. If the document contains no page, AddPage() is called to prevent from getting an invalid document. - * @since 1.0 - * @see Open(), Output() - */ - function Close() { - //Terminate document - if($this->state==3) { - return; - } - if($this->page==0) { - $this->AddPage(); - } - //Page footer - $this->InFooter=true; - $this->Footer(); - $this->InFooter=false; - //Close page - $this->_endpage(); - //Close document - $this->_enddoc(); - } - - /** - * Reset pointer to the last document page. - * @since 2.0.000 (2008-01-04) - * @see setPage(), getPage(), getNumPages() - */ - function lastPage() { - $this->page = count($this->pages); - } - - /** - * Move pointer to the apecified document page. - * @param int $pnum page number - * @since 2.1.000 (2008-01-07) - * @see getPage(), lastpage(), getNumPages() - */ - function setPage($pnum) { - if(($pnum > 0) AND ($pnum <= count($this->pages))) { - $this->page = $pnum; - } - } - - /** - * Get current document page number. - * @return int page number - * @since 2.1.000 (2008-01-07) - * @see setPage(), lastpage(), getNumPages() - */ - function getPage() { - return $this->page; - } - - - /** - * Get the total number of insered pages. - * @return int number of pages - * @since 2.1.000 (2008-01-07) - * @see setPage(), getPage(), lastpage() - */ - function getNumPages() { - return count($this->pages); - } - - /** - * Adds a new page to the document. If a page is already present, the Footer() method is called first to output the footer. Then the page is added, the current position set to the top-left corner according to the left and top margins, and Header() is called to display the header. - * The font which was set before calling is automatically restored. There is no need to call SetFont() again if you want to continue with the same font. The same is true for colors and line width. - * The origin of the coordinate system is at the top-left corner and increasing ordinates go downwards. - * @param string $orientation Page orientation. Possible values are (case insensitive): The default value is the one passed to the constructor. - * @since 1.0 - * @see TCPDF(), Header(), Footer(), SetMargins() - */ - function AddPage($orientation='') { - // store current margin values - $lMargin = $this->lMargin; - $rMargin = $this->rMargin; - - if (!isset($this->original_lMargin)) { - $this->original_lMargin = $this->lMargin; - } - if (!isset($this->original_rMargin)) { - $this->original_rMargin = $this->rMargin; - } - - if (count($this->pages) > $this->page) { - // this page has been already added - $this->page++; - $this->y = $this->tMargin; - return; - } - //Start a new page - if($this->state==0) { - $this->Open(); - } - $family=$this->FontFamily; - $style=$this->FontStyle.($this->underline ? 'U' : '').($this->linethrough ? 'D' : ''); - $size=$this->FontSizePt; - $lw=$this->LineWidth; - $dc=$this->DrawColor; - $fc=$this->FillColor; - $tc=$this->TextColor; - $cf=$this->ColorFlag; - if($this->page>0) { - //Page footer - $this->InFooter=true; - $this->Footer(); - $this->InFooter=false; - //Close page - $this->_endpage(); - } - //Start new page - $this->_beginpage($orientation); - //Set line cap style to square - $this->_out('2 J'); - //Set line width - $this->LineWidth=$lw; - $this->_out(sprintf('%.2f w',$lw*$this->k)); - //Set font - if($family) { - $this->SetFont($family,$style,$size); - } - //Set colors - $this->DrawColor=$dc; - if($dc!='0 G') { - $this->_out($dc); - } - $this->FillColor=$fc; - if($fc!='0 g') { - $this->_out($fc); - } - $this->TextColor=$tc; - $this->ColorFlag=$cf; - //Page header - $this->Header(); - //Restore line width - if($this->LineWidth!=$lw) { - $this->LineWidth=$lw; - $this->_out(sprintf('%.2f w',$lw*$this->k)); - } - //Restore font - if($family) { - $this->SetFont($family,$style,$size); - } - //Restore colors - if($this->DrawColor!=$dc) { - $this->DrawColor=$dc; - $this->_out($dc); - } - if($this->FillColor!=$fc) { - $this->FillColor=$fc; - $this->_out($fc); - } - $this->TextColor=$tc; - $this->ColorFlag=$cf; - - // restore previous margin values - $this->SetLeftMargin($lMargin); - $this->SetRightMargin($rMargin); - } - - /** - * Set header data. - * @param string $ln header image logo - * @param string $lw header image logo width in mm - * @param string $ht string to print as title on document header - * @param string $hs string to print on document header - */ - function setHeaderData($ln="", $lw=0, $ht="", $hs="") { - $this->header_logo = $ln; - $this->header_logo_width = $lw; - $this->header_title = $ht; - $this->header_string = $hs; - } - - /** - * Set header margin. - * (minimum distance between header and top page margin) - * @param int $hm distance in millimeters - */ - function setHeaderMargin($hm=10) { - $this->header_margin = $hm; - } - - /** - * Set footer margin. - * (minimum distance between footer and bottom page margin) - * @param int $fm distance in millimeters - */ - function setFooterMargin($fm=10) { - $this->footer_margin = $fm; - } - - /** - * Set a flag to print page header. - * @param boolean $val set to true to print the page header (default), false otherwise. - */ - function setPrintHeader($val=true) { - $this->print_header = $val; - } - - /** - * Set a flag to print page footer. - * @param boolean $value set to true to print the page footer (default), false otherwise. - */ - function setPrintFooter($val=true) { - $this->print_footer = $val; - } - - /** - * This method is used to render the page header. - * It is automatically called by AddPage() and could be overwritten in your own inherited class. - */ - function Header() { - if ($this->print_header) { - - if (!isset($this->original_lMargin)) { - $this->original_lMargin = $this->lMargin; - } - if (!isset($this->original_rMargin)) { - $this->original_rMargin = $this->rMargin; - } - - // reset original header margins - $this->rMargin = $this->original_rMargin; - $this->lMargin = $this->original_lMargin; - - // save current font values - $font_family = $this->FontFamily; - $font_style = $this->FontStyle; - $font_size = $this->FontSizePt; - - //set current position - if ($this->rtl) { - $this->SetXY($this->original_rMargin, $this->header_margin); - } else { - $this->SetXY($this->original_lMargin, $this->header_margin); - } - - if (($this->header_logo) AND ($this->header_logo != K_BLANK_IMAGE)) { - $this->Image(K_PATH_IMAGES.$this->header_logo, $this->GetX(), $this->header_margin, $this->header_logo_width); - } else { - $this->img_rb_x = $this->GetX(); - $this->img_rb_y = $this->GetY(); - } - - $cell_height = round(($this->cell_height_ratio * $this->header_font[2]) / $this->k, 2); - // set starting margin for text data cell - if ($this->rtl) { - $header_x = $this->original_rMargin + ($this->header_logo_width * 1.1); - } else { - $header_x = $this->original_lMargin + ($this->header_logo_width * 1.1); - } - - $this->SetTextColor(0, 0, 0, false); - - // header title - $this->SetFont($this->header_font[0], 'B', $this->header_font[2] + 1); - $this->SetX($header_x); - $this->Cell($this->header_width, $cell_height, $this->header_title, 0, 1, ''); - - // header string - $this->SetFont($this->header_font[0], $this->header_font[1], $this->header_font[2]); - $this->SetX($header_x); - $this->MultiCell($this->header_width, $cell_height, $this->header_string, 0, '', 0, 1, 0, 0, true, 0); - - // print an ending header line - //set style for cell border - $prevlinewidth = $this->GetLineWidth(); - $line_width = 0.3; - $this->SetLineWidth($line_width); - $this->SetDrawColor(0, 0, 0); - $this->SetY(1 + max($this->img_rb_y, $this->GetY())); - if ($this->rtl) { - $this->SetX($this->original_rMargin); - } else { - $this->SetX($this->original_lMargin); - } - $this->Cell(0, 0, '', 'T', 0, 'C'); - $this->SetLineWidth($prevlinewidth); - - //restore position - if ($this->rtl) { - $this->SetXY($this->original_rMargin, $this->tMargin); - } else { - $this->SetXY($this->original_lMargin, $this->tMargin); - } - - // restore font values - $this->SetFont($font_family, $font_style, $font_size); - } - } - - /** - * This method is used to render the page footer. - * It is automatically called by AddPage() and could be overwritten in your own inherited class. - */ - function Footer() { - if ($this->print_footer) { - - if (!isset($this->original_lMargin)) { - $this->original_lMargin = $this->lMargin; - } - if (!isset($this->original_rMargin)) { - $this->original_rMargin = $this->rMargin; - } - - // reset original header margins - $this->rMargin = $this->original_rMargin; - $this->lMargin = $this->original_lMargin; - - // save current font values - $font_family = $this->FontFamily; - $font_style = $this->FontStyle; - $font_size = $this->FontSizePt; - - $this->SetTextColor(0, 0, 0, false); - - //set font - $this->SetFont($this->footer_font[0], $this->footer_font[1] , $this->footer_font[2]); - //set style for cell border - $prevlinewidth = $this->GetLineWidth(); - $line_width = 0.3; - $this->SetLineWidth($line_width); - $this->SetDrawColor(0, 0, 0); - - $footer_height = round(($this->cell_height_ratio * $this->footer_font[2]) / $this->k, 2); //footer height - //get footer y position - $footer_y = $this->h - $this->footer_margin - $footer_height; - //set current position - if ($this->rtl) { - $this->SetXY($this->original_rMargin, $footer_y); - } else { - $this->SetXY($this->original_lMargin, $footer_y); - } - - //print document barcode - if ($this->barcode) { - $this->Ln(); - $barcode_width = round(($this->w - $this->original_lMargin - $this->original_rMargin)/3); //max width - $this->writeBarcode($this->GetX(), $footer_y + $line_width, $barcode_width, $footer_height - $line_width, "C128B", false, false, 2, $this->barcode); - } - - $pagenumtxt = $this->l['w_page']." ".$this->PageNo().' / {nb}'; - - $this->SetY($footer_y); - - //Print page number - if ($this->rtl) { - $this->SetX($this->original_rMargin); - $this->Cell(0, $footer_height, $pagenumtxt, 'T', 0, 'L'); - } else { - $this->SetX($this->original_lMargin); - $this->Cell(0, $footer_height, $pagenumtxt, 'T', 0, 'R'); - } - // restore line width - $this->SetLineWidth($prevlinewidth); - - // restore font values - $this->SetFont($font_family, $font_style, $font_size); - } - } - - /** - * Returns the current page number. - * @return int page number - * @since 1.0 - * @see AliasNbPages() - */ - function PageNo() { - //Get current page number - return $this->page; - } - - /** - * Defines the color used for all drawing operations (lines, rectangles and cell borders). It can be expressed in RGB components or gray scale. The method can be called before the first page is created and the value is retained from page to page. - * @param int $col1 Gray level for single color, or Red color for RGB, or Cyan color for CMYK. Value between 0 and 255 - * @param int $col2 Green color for RGB, or Magenta color for CMYK. Value between 0 and 255 - * @param int $col3 Blue color for RGB, or Yellow color for CMYK. Value between 0 and 255 - * @param int $col4 Key (Black) color for CMYK. Value between 0 and 255 - * @since 1.3 - * @see SetFillColor(), SetTextColor(), Line(), Rect(), Cell(), MultiCell() - */ - function SetDrawColor($col1=0, $col2=-1, $col3=-1, $col4=-1) { - // set default values - if (!is_numeric($col1)) { - $col1=0; - } - if (!is_numeric($col2)) { - $col2=-1; - } - if (!is_numeric($col3)) { - $col3=-1; - } - if (!is_numeric($col4)) { - $col4=-1; - } - //Set color for all stroking operations - if (($col2==-1) AND ($col3==-1) AND ($col4==-1)) { - // Grey scale - $this->DrawColor=sprintf('%.3f G', $col1/255); - } elseif ($col4==-1) { - // RGB - $this->DrawColor=sprintf('%.3f %.3f %.3f RG', $col1/255, $col2/255, $col3/255); - } else { - // CMYK - $this->DrawColor = sprintf('%.3f %.3f %.3f %.3f K', $col1/100, $col2/100, $col3/100, $col4/100); - } - if($this->page>0) { - $this->_out($this->DrawColor); - } - } - - /** - * Defines the color used for all filling operations (filled rectangles and cell backgrounds). It can be expressed in RGB components or gray scale. The method can be called before the first page is created and the value is retained from page to page. - * @param int $col1 Gray level for single color, or Red color for RGB, or Cyan color for CMYK. Value between 0 and 255 - * @param int $col2 Green color for RGB, or Magenta color for CMYK. Value between 0 and 255 - * @param int $col3 Blue color for RGB, or Yellow color for CMYK. Value between 0 and 255 - * @param boolean $storeprev if true stores the current color on $bgcolor array. - * @param int $col4 Key (Black) color for CMYK. Value between 0 and 255 - * @since 1.3 - * @see SetDrawColor(), SetTextColor(), Rect(), Cell(), MultiCell() - */ - function SetFillColor($col1=0, $col2=-1, $col3=-1, $storeprev=false, $col4=-1) { - // set default values - if (!is_numeric($col1)) { - $col1=0; - } - if (!is_numeric($col2)) { - $col2=-1; - } - if (!is_numeric($col3)) { - $col3=-1; - } - if (!is_numeric($col4)) { - $col4=-1; - } - //Set color for all filling operations - if (($col2==-1) AND ($col3==-1) AND ($col4==-1)) { - // Grey scale - $this->FillColor = sprintf('%.3f g', $col1/255); - if ($storeprev) { - array_push($this->bgcolor, array('G' => $col1)); - } - } elseif ($col4==-1) { - // RGB - $this->FillColor = sprintf('%.3f %.3f %.3f rg', $col1/255, $col2/255, $col3/255); - if ($storeprev) { - array_push($this->bgcolor, array('R' => $col1, 'G' => $col2, 'B' => $col3)); - } - } else { - // CMYK - $this->FillColor = sprintf('%.3f %.3f %.3f %.3f k', $col1/100, $col2/100, $col3/100, $col4/100); - if ($storeprev) { - array_push($this->bgcolor, array('C' => $col1, 'M' => $col2, 'Y' => $col3, 'K' => $col4)); - } - } - $this->ColorFlag = ($this->FillColor != $this->TextColor); - if($this->page>0) { - $this->_out($this->FillColor); - } - } - - /** - * Defines the color used for text. It can be expressed in RGB components or gray scale. The method can be called before the first page is created and the value is retained from page to page. - * @param int $col1 Gray level for single color, or Red color for RGB, or Cyan color for CMYK. Value between 0 and 255 - * @param int $col2 Green color for RGB, or Magenta color for CMYK. Value between 0 and 255 - * @param int $col3 Blue color for RGB, or Yellow color for CMYK. Value between 0 and 255 - * @param boolean $storeprev if true stores the current color on $fgcolor array. - * @param int $col4 Key (Black) color for CMYK. Value between 0 and 255 - * @since 1.3 - * @see SetDrawColor(), SetFillColor(), Text(), Cell(), MultiCell() - */ - function SetTextColor($col1=0, $col2=-1, $col3=-1, $storeprev=false, $col4=-1) { - // set default values - if (!is_numeric($col1)) { - $col1=0; - } - if (!is_numeric($col2)) { - $col2=-1; - } - if (!is_numeric($col3)) { - $col3=-1; - } - if (!is_numeric($col4)) { - $col4=-1; - } - //Set color for text - if (($col2==-1) AND ($col3==-1) AND ($col4==-1)) { - // Grey scale - $this->TextColor = sprintf('%.3f g', $col1/255); - if ($storeprev) { - array_push($this->fgcolor, array('G' => $col1)); - } - } elseif ($col4==-1) { - // RGB - $this->TextColor = sprintf('%.3f %.3f %.3f rg', $col1/255, $col2/255, $col3/255); - if ($storeprev) { - array_push($this->fgcolor, array('R' => $col1, 'G' => $col2, 'B' => $col3)); - } - } else { - // CMYK - $this->TextColor = sprintf('%.3f %.3f %.3f %.3f k', $col1/100, $col2/100, $col3/100, $col4/100); - if ($storeprev) { - array_push($this->fgcolor, array('C' => $col1, 'M' => $col2, 'Y' => $col3, 'K' => $col4)); - } - } - $this->ColorFlag = ($this->FillColor != $this->TextColor); - } - - /** - * Returns the length of a string in user unit. A font must be selected.
    - * @param string $s The string whose length is to be computed - * @return int string length - * @author Nicola Asuni - * @since 1.2 - */ - function GetStringWidth($s) { - return $this->GetArrStringWidth($this->utf8Bidi($this->UTF8StringToArray($s), $this->tmprtl)); - } - - /** - * Returns the string length of an array of chars in user unit. A font must be selected.
    - * @param string $arr The array of chars whose total length is to be computed - * @return int string length - * @author Nicola Asuni - * @since 2.4.000 (2008-03-06) - */ - function GetArrStringWidth($sa) { - $w = 0; - foreach($sa as $char) { - $w += $this->GetCharWidth($char); - } - return $w; - } - - /** - * Returns the length of the char in user unit. A font must be selected.
    - * @param string $char The char whose length is to be returned - * @return int char width - * @author Nicola Asuni - * @since 2.4.000 (2008-03-06) - */ - function GetCharWidth($char) { - $cw = &$this->CurrentFont['cw']; - if (isset($cw[$char])) { - $w = $cw[$char]; - } elseif(isset($cw[ord($char)])) { - $w = $cw[ord($char)]; - } elseif(isset($cw[chr($char)])) { - $w = $cw[chr($char)]; - } elseif(isset($this->CurrentFont['desc']['MissingWidth'])) { - $w = $this->CurrentFont['desc']['MissingWidth']; // set default size - } else { - $w = 500; - } - return ($w * $this->FontSize / 1000); - } - - /** - * Returns the numbero of characters in a string. - * @param string $s The input string. - * @return int number of characters - * @since 2.0.0001 (2008-01-07) - */ - function GetNumChars($s) { - if($this->isunicode) { - return count($this->UTF8StringToArray($s)); - } - return strlen($s); - } - - /** - * Imports a TrueType or Type1 font and makes it available. It is necessary to generate a font definition file first with the makefont.php utility. The definition file (and the font file itself when embedding) must be present either in the current directory or in the one indicated by K_PATH_FONTS if the constant is defined. If it could not be found, the error "Could not include font definition file" is generated. - * Support UTF-8 Unicode [Nicola Asuni, 2005-01-02]. - * Example:
    - *
    -		* $pdf->AddFont('Comic','I');
    -		* // is equivalent to:
    -		* $pdf->AddFont('Comic','I','comici.php');
    -		* 
    - * @param string $family Font family. The name can be chosen arbitrarily. If it is a standard family name, it will override the corresponding font. - * @param string $style Font style. Possible values are (case insensitive): - * @param string $file The font definition file. By default, the name is built from the family and style, in lower case with no space. - * @since 1.5 - * @see SetFont() - */ - function AddFont($family, $style='', $file='') { - if(empty($family)) { - return; - } - - //Add a TrueType or Type1 font - $family = strtolower($family); - if((!$this->isunicode) AND ($family == 'arial')) { - $family = 'helvetica'; - } - - $style=strtoupper($style); - $style=str_replace('U','',$style); - if($style == 'IB') { - $style = 'BI'; - } - - $fontkey = $family.$style; - // check if the font has been already added - if(isset($this->fonts[$fontkey])) { - return; - } - - if($file=='') { - $file = str_replace(' ', '', $family).strtolower($style).'.php'; - } - if(!file_exists($this->_getfontpath().$file)) { - // try to load the basic file without styles - $file = str_replace(' ', '', $family).'.php'; - } - - include($this->_getfontpath().$file); - - if(!isset($name) AND !isset($fpdf_charwidths)) { - $this->Error('Could not include font definition file'); - } - - $i = count($this->fonts)+1; - - if($this->isunicode) { - $this->fonts[$fontkey] = array('i'=>$i, 'type'=>$type, 'name'=>$name, 'desc'=>$desc, 'up'=>$up, 'ut'=>$ut, 'cw'=>$cw, 'enc'=>$enc, 'file'=>$file, 'ctg'=>$ctg); - $fpdf_charwidths[$fontkey] = $cw; - } else { - $this->fonts[$fontkey]=array('i'=>$i, 'type'=>'core', 'name'=>$this->CoreFonts[$fontkey], 'up'=>-100, 'ut'=>50, 'cw'=>$fpdf_charwidths[$fontkey]); - } - - if(isset($diff) AND (!empty($diff))) { - //Search existing encodings - $d=0; - $nb=count($this->diffs); - for($i=1;$i<=$nb;$i++) { - if($this->diffs[$i]==$diff) { - $d=$i; - break; - } - } - if($d==0) { - $d=$nb+1; - $this->diffs[$d]=$diff; - } - $this->fonts[$fontkey]['diff']=$d; - } - if(!empty($file)) { - if((strcasecmp($type,"TrueType") == 0) OR (strcasecmp($type,"TrueTypeUnicode") == 0)) { - $this->FontFiles[$file]=array('length1'=>$originalsize); - } - else { - $this->FontFiles[$file]=array('length1'=>$size1,'length2'=>$size2); - } - } - } - - /** - * Sets the font used to print character strings. It is mandatory to call this method at least once before printing text or the resulting document would not be valid. - * The font can be either a standard one or a font added via the AddFont() method. Standard fonts use Windows encoding cp1252 (Western Europe). - * The method can be called before the first page is created and the font is retained from page to page. - If you just wish to change the current font size, it is simpler to call SetFontSize(). - * Note: for the standard fonts, the font metric files must be accessible. There are three possibilities for this:
    - * Example for the last case (note the trailing slash):
    - *
    -		* define('K_PATH_FONTS','/home/www/font/');
    -		* require('tcpdf.php');
    -		*
    -		* //Times regular 12
    -		* $pdf->SetFont('Times');
    -		* //Arial bold 14
    -		* $pdf->SetFont('vera','B',14);
    -		* //Removes bold
    -		* $pdf->SetFont('');
    -		* //Times bold, italic and underlined 14
    -		* $pdf->SetFont('Times','BIU');
    -		* 

    - * If the file corresponding to the requested font is not found, the error "Could not include font metric file" is generated. - * @param string $family Family font. It can be either a name defined by AddFont() or one of the standard families (case insensitive):It is also possible to pass an empty string. In that case, the current family is retained. - * @param string $style Font style. Possible values are (case insensitive):or any combination. The default value is regular. Bold and italic styles do not apply to Symbol and ZapfDingbats - * @param float $size Font size in points. The default value is the current size. If no size has been specified since the beginning of the document, the value taken is 12 - * @since 1.0 - * @see AddFont(), SetFontSize() - */ - function SetFont($family, $style='', $size=0) { - // save previous values - $this->prevFontFamily = $this->FontFamily; - $this->prevFontStyle = $this->FontStyle; - - //Select a font; size given in points - global $fpdf_charwidths; - - $family=strtolower($family); - if($family=='') { - $family=$this->FontFamily; - } - if((!$this->isunicode) AND ($family == 'arial')) { - $family = 'helvetica'; - } - elseif(($family=="symbol") OR ($family=="zapfdingbats")) { - $style=''; - } - $style=strtoupper($style); - - // underline - if(strpos($style,'U')!==false) { - $this->underline=true; - $style=str_replace('U','',$style); - } - else { - $this->underline=false; - } - //line through (deleted) - if(strpos($style,'D')!==false) { - $this->linethrough=true; - $style=str_replace('D','',$style); - } - else { - $this->linethrough=false; - } - if($style=='IB') { - $style='BI'; - } - if($size==0) { - $size=$this->FontSizePt; - } - - // try to add font (if not already added) - if($this->isunicode) { - $this->AddFont($family, $style); - } - - //Test if font is already selected - if(($this->FontFamily == $family) AND ($this->FontStyle == $style) AND ($this->FontSizePt == $size)) { - return; - } - - $fontkey = $family.$style; - - - //Test if used for the first time - if(!isset($this->fonts[$fontkey])) { - //Check if one of the standard fonts - if(isset($this->CoreFonts[$fontkey])) { - if(!isset($fpdf_charwidths[$fontkey])) { - //Load metric file - $file = $family; - if(($family!='symbol') AND ($family!='zapfdingbats')) { - $file .= strtolower($style); - } - if(!file_exists($this->_getfontpath().$file.'.php')) { - // try to load the basic file without styles - $file = $family; - $fontkey = $family; - } - include($this->_getfontpath().$file.'.php'); - if (($this->isunicode AND !isset($ctg)) OR ((!$this->isunicode) AND (!isset($fpdf_charwidths[$fontkey]))) ) { - $this->Error("Could not include font metric file [".$fontkey."]: ".$this->_getfontpath().$file.".php"); - } - } - $i = count($this->fonts) + 1; - - if($this->isunicode) { - $this->fonts[$fontkey] = array('i'=>$i, 'type'=>$type, 'name'=>$name, 'desc'=>$desc, 'up'=>$up, 'ut'=>$ut, 'cw'=>$cw, 'enc'=>$enc, 'file'=>$file, 'ctg'=>$ctg); - $fpdf_charwidths[$fontkey] = $cw; - } else { - $this->fonts[$fontkey]=array('i'=>$i, 'type'=>'core', 'name'=>$this->CoreFonts[$fontkey], 'up'=>-100, 'ut'=>50, 'cw'=>$fpdf_charwidths[$fontkey]); - } - } - else { - $this->Error('Undefined font: '.$family.' '.$style); - } - } - //Select it - $this->FontFamily = $family; - $this->FontStyle = $style; - $this->CurrentFont = &$this->fonts[$fontkey]; - $this->SetFontSize($size); - } - - /** - * Defines the size of the current font. - * @param float $size The size (in points) - * @since 1.0 - * @see SetFont() - */ - function SetFontSize($size) { - //Set font size in points - $this->FontSizePt = $size; - $this->FontSize = $size / $this->k; - if (isset($this->CurrentFont['desc']['Ascent']) AND ($this->CurrentFont['desc']['Ascent'] > 0)) { - $this->FontAscent = $this->CurrentFont['desc']['Ascent'] * $this->FontSize / 1000; - } else { - $this->FontAscent = 0.8 * $this->FontSize; - } - if (isset($this->CurrentFont['desc']['Descent']) AND ($this->CurrentFont['desc']['Descent'] > 0)) { - $this->FontDescent = - $this->CurrentFont['desc']['Descent'] * $this->FontSize / 1000; - } else { - $this->FontDescent = 0.2 * $this->FontSize; - } - if (($this->page > 0) AND (isset($this->CurrentFont['i']))) { - $this->_out(sprintf('BT /F%d %.2f Tf ET', $this->CurrentFont['i'], $this->FontSizePt)); - } - } - - /** - * Creates a new internal link and returns its identifier. An internal link is a clickable area which directs to another place within the document.
    - * The identifier can then be passed to Cell(), Write(), Image() or Link(). The destination is defined with SetLink(). - * @since 1.5 - * @see Cell(), Write(), Image(), Link(), SetLink() - */ - function AddLink() { - //Create a new internal link - $n=count($this->links)+1; - $this->links[$n]=array(0,0); - return $n; - } - - /** - * Defines the page and position a link points to - * @param int $link The link identifier returned by AddLink() - * @param float $y Ordinate of target position; -1 indicates the current position. The default value is 0 (top of page) - * @param int $page Number of target page; -1 indicates the current page. This is the default value - * @since 1.5 - * @see AddLink() - */ - function SetLink($link, $y=0, $page=-1) { - //Set destination of internal link - if($y==-1) { - $y=$this->y; - } - if($page==-1) { - $page=$this->page; - } - $this->links[$link]=array($page,$y); - } - - /** - * Puts a link on a rectangular area of the page. Text or image links are generally put via Cell(), Write() or Image(), but this method can be useful for instance to define a clickable area inside an image. - * @param float $x Abscissa of the upper-left corner of the rectangle (or upper-right for RTL languages) - * @param float $y Ordinate of the upper-left corner of the rectangle (or upper-right for RTL languages) - * @param float $w Width of the rectangle - * @param float $h Height of the rectangle - * @param mixed $link URL or identifier returned by AddLink() - * @since 1.5 - * @see AddLink(), Cell(), Write(), Image() - */ - function Link($x, $y, $w, $h, $link) { - $this->PageLinks[$this->page][] = array($x * $this->k, $this->hPt - $y * $this->k, $w * $this->k, $h*$this->k, $link); - } - - /** - * Prints a character string. The origin is on the left of the first charcter, on the baseline. This method allows to place a string precisely on the page, but it is usually easier to use Cell(), MultiCell() or Write() which are the standard methods to print text. - * @param float $x Abscissa of the origin - * @param float $y Ordinate of the origin - * @param string $txt String to print - * @param int $stroke outline size in points (0 = disable) - * @param boolean $clip if true activate clipping mode (you must call StartTransform() before this function and StopTransform() to stop the clipping tranformation). - * @since 1.0 - * @see SetFont(), SetTextColor(), Cell(), MultiCell(), Write() - */ - function Text($x, $y, $txt, $stroke=0, $clip=false) { - //Output a string - if($this->rtl) { - // bidirectional algorithm (some chars may be changed affecting the line length) - $s = $this->utf8Bidi($this->UTF8StringToArray($txt), $this->tmprtl); - $l = $this->GetArrStringWidth($s); - $xr = $this->w - $x - $this->GetArrStringWidth($s); - } else { - $xr = $x; - } - $opt = ""; - if (($stroke > 0) AND (!$clip)) { - $opt .= "1 Tr ".intval($stroke)." w "; - } elseif (($stroke > 0) AND $clip) { - $opt .= "5 Tr ".intval($stroke)." w "; - } elseif ($clip) { - $opt .= "7 Tr "; - } - $s = sprintf('BT %.2f %.2f Td %s(%s) Tj ET', $xr * $this->k, ($this->h-$y) * $this->k, $opt, $this->_escapetext($txt)); - if($this->underline AND ($txt!='')) { - $s .= ' '.$this->_dounderline($xr, $y, $txt); - } - if($this->linethrough AND ($txt!='')) { - $s .= ' '.$this->_dolinethrough($xr, $y, $txt); - } - if($this->ColorFlag AND (!$clip)) { - $s='q '.$this->TextColor.' '.$s.' Q'; - } - $this->_out($s); - } - - /** - * Whenever a page break condition is met, the method is called, and the break is issued or not depending on the returned value. The default implementation returns a value according to the mode selected by SetAutoPageBreak().
    - * This method is called automatically and should not be called directly by the application.
    - * Example:
    - * The method is overriden in an inherited class in order to obtain a 3 column layout:
    - *
    -		* class PDF extends TCPDF {
    -		* 	var $col=0;
    -		*
    -		* 	function SetCol($col) {
    -		* 		//Move position to a column
    -		* 		$this->col=$col;
    -		* 		$x=10+$col*65;
    -		* 		$this->SetLeftMargin($x);
    -		* 		$this->SetX($x);
    -		* 	}
    -		*
    -		* 	function AcceptPageBreak() {
    -		* 		if($this->col<2) {
    -		* 			//Go to next column
    -		* 			$this->SetCol($this->col+1);
    -		* 			$this->SetY(10);
    -		* 			return false;
    -		* 		}
    -		* 		else {
    -		* 			//Go back to first column and issue page break
    -		* 			$this->SetCol(0);
    -		* 			return true;
    -		* 		}
    -		* 	}
    -		* }
    -		*
    -		* $pdf=new PDF();
    -		* $pdf->Open();
    -		* $pdf->AddPage();
    -		* $pdf->SetFont('vera','',12);
    -		* for($i=1;$i<=300;$i++) {
    -		*     $pdf->Cell(0,5,"Line $i",0,1);
    -		* }
    -		* $pdf->Output();
    -		* 
    - * @return boolean - * @since 1.4 - * @see SetAutoPageBreak() - */ - function AcceptPageBreak() { - //Accept automatic page break or not - return $this->AutoPageBreak; - } - - /** - * Prints a cell (rectangular area) with optional borders, background color and character string. The upper-left corner of the cell corresponds to the current position. The text can be aligned or centered. After the call, the current position moves to the right or to the next line. It is possible to put a link on the text.
    - * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting. - * @param float $w Cell width. If 0, the cell extends up to the right margin. - * @param float $h Cell height. Default value: 0. - * @param string $txt String to print. Default value: empty string. - * @param mixed $border Indicates if borders must be drawn around the cell. The value can be either a number:or a string containing some or all of the following characters (in any order): - * @param int $ln Indicates where the current position should go after the call. Possible values are: - Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0. - * @param string $align Allows to center or align the text. Possible values are: - * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0. - * @param mixed $link URL or identifier returned by AddLink(). - * @param int $stretch stretch carachter mode: - * @since 1.0 - * @see SetFont(), SetDrawColor(), SetFillColor(), SetTextColor(), SetLineWidth(), AddLink(), Ln(), MultiCell(), Write(), SetAutoPageBreak() - */ - function Cell($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=0, $link='', $stretch=0) { - - $k = $this->k; - - //$min_cell_height = $this->FontAscent + $this->FontDescent; - $min_cell_height = $this->FontSize * $this->cell_height_ratio; - if ($h < $min_cell_height) { - $h = $min_cell_height; - } - - if((($this->y + $h) > $this->PageBreakTrigger) AND empty($this->InFooter) AND $this->AcceptPageBreak()) { - //Automatic page break - $x = $this->x; - $ws = $this->ws; - if($ws > 0) { - $this->ws = 0; - $this->_out('0 Tw'); - } - $this->AddPage($this->CurOrientation); - if($ws > 0) { - $this->ws = $ws; - $this->_out(sprintf('%.3f Tw',$ws * $k)); - } - $this->x = $x; - } - if(empty($w) OR ($w <= 0)) { - if ($this->rtl) { - $w = $this->x - $this->lMargin; - } else { - $w = $this->w - $this->rMargin - $this->x; - } - } - $s = ''; - if(($fill == 1) OR ($border == 1)) { - if($fill == 1) { - $op = ($border == 1) ? 'B' : 'f'; - } else { - $op = 'S'; - } - if ($this->rtl) { - $xk = ($this->x - $w) * $k; - } else { - $xk = $this->x * $k; - } - $s .= sprintf('%.2f %.2f %.2f %.2f re %s ', $xk, ($this->h - $this->y) * $k, $w * $k, -$h * $k, $op); - } - if(is_string($border)) { - $x=$this->x; - $y=$this->y; - if(strpos($border,'L')!==false) { - if ($this->rtl) { - $xk = ($x - $w) * $k; - } else { - $xk = $x * $k; - } - $s.=sprintf('%.2f %.2f m %.2f %.2f l S ',$xk,($this->h-$y)*$k,$xk,($this->h-($y+$h))*$k); - } - if(strpos($border,'T')!==false) { - if ($this->rtl) { - $xk = ($x - $w) * $k; - $xwk = $x * $k; - } else { - $xk = $x * $k; - $xwk = ($x + $w) * $k; - } - $s.=sprintf('%.2f %.2f m %.2f %.2f l S ',$xk,($this->h-$y)*$k,$xwk,($this->h-$y)*$k); - } - if(strpos($border,'R')!==false) { - if ($this->rtl) { - $xk = $x * $k; - } else { - $xk = ($x + $w) * $k; - } - $s.=sprintf('%.2f %.2f m %.2f %.2f l S ',$xk,($this->h-$y)*$k,$xk,($this->h-($y+$h))*$k); - } - if(strpos($border,'B')!==false) { - if ($this->rtl) { - $xk = ($x - $w) * $k; - $xwk = $x * $k; - } else { - $xk = $x * $k; - $xwk = ($x + $w) * $k; - } - $s.=sprintf('%.2f %.2f m %.2f %.2f l S ',$xk,($this->h-($y+$h))*$k,$xwk,($this->h-($y+$h))*$k); - } - } - if($txt != '') { - // text lenght - $width = $this->GetStringWidth($txt); - // ratio between cell lenght and text lenght - $ratio = ($w - (2 * $this->cMargin)) / $width; - - // stretch text if required - if (($stretch > 0) AND (($ratio < 1) OR (($ratio > 1) AND (($stretch % 2) == 0)))) { - if ($stretch > 2) { - // spacing - //Calculate character spacing in points - $char_space = (($w - $width - (2 * $this->cMargin)) * $this->k) / max($this->GetNumChars($txt)-1,1); - //Set character spacing - $this->_out(sprintf('BT %.2f Tc ET', $char_space)); - } else { - // scaling - //Calculate horizontal scaling - $horiz_scale = $ratio*100.0; - //Set horizontal scaling - $this->_out(sprintf('BT %.2f Tz ET', $horiz_scale)); - } - $align = ''; - $width = $w - (2 * $this->cMargin); - } else { - $stretch == 0; - } - - if($align == 'L') { - if ($this->rtl) { - $dx = $w - $width - $this->cMargin; - } else { - $dx = $this->cMargin; - } - } elseif($align == 'R') { - if ($this->rtl) { - $dx = $this->cMargin; - } else { - $dx = $w - $width - $this->cMargin; - } - } elseif($align=='C') { - $dx = ($w - $width)/2; - } elseif($align=='J') { - if ($this->rtl) { - $dx = $w - $width - $this->cMargin; - } else { - $dx = $this->cMargin; - } - } else { - $dx = $this->cMargin; - } - if($this->ColorFlag) { - $s .= 'q '.$this->TextColor.' '; - } - $txt2 = $this->_escapetext($txt); - if ($this->rtl) { - $xdk = ($this->x - $dx - $width) * $k; - } else { - $xdk = ($this->x + $dx) * $k; - } - - // Justification - if ($align == 'J') { - // count number of spaces - $ns = substr_count($txt, ' '); - if ($this->isunicode) { - // get string width without spaces - $width = $this->GetStringWidth(str_replace(' ', '', $txt)); - // calculate average space width - $spacewidth = ($w-$width-(2*$this->cMargin))/($ns?$ns:1)/$this->FontSize/$this->k; - // set word position to be used with TJ operator - $txt2 = str_replace(chr(0).' ', ') '.(-2830*$spacewidth).' (', $txt2); - } else { - // get string width - $width = $this->GetStringWidth($txt); - $spacewidth = (($w-$width-(2*$this->cMargin))/($ns?$ns:1)) * $this->k; - $this->_out(sprintf('BT %.3f Tw ET', $spacewidth)); - } - } - - // calculate approximate position of the font base line - //$basefonty = $this->y + (($h + $this->FontAscent - $this->FontDescent)/2); - $basefonty = $this->y + ($h/2) + ($this->FontSize/3); - - // print text - $s.=sprintf('BT %.2f %.2f Td [(%s)] TJ ET', $xdk, ($this->h - $basefonty) * $k, $txt2); - - if ($this->rtl) { - $xdx = $this->x - $dx - $width; - } else { - $xdx = $this->x + $dx; - } - - if($this->underline) { - $s.=' '.$this->_dounderline($xdx, $basefonty, $txt); - } - if($this->linethrough) { - $s.=' '.$this->_dolinethrough($xdx, $basefonty, $txt); - } - if($this->ColorFlag) { - $s.=' Q'; - } - if($link) { - $this->Link($xdx, $this->y + (($h - $this->FontSize)/2), $width, $this->FontSize, $link); - } - } - - // output cell - if($s) { - // output cell - $this->_out($s); - // reset text stretching - if($stretch > 2) { - //Reset character horizontal spacing - $this->_out('BT 0 Tc ET'); - } elseif($stretch > 0) { - //Reset character horizontal scaling - $this->_out('BT 100 Tz ET'); - } - } - - // reset word spacing - if ((!$this->isunicode) AND ($align == 'J')) { - $this->_out('BT 0 Tw ET'); - } - - $this->lasth = $h; - - if($ln>0) { - //Go to the beginning of the next line - $this->y += $h; - if($ln == 1) { - if ($this->rtl) { - $this->x = $this->w - $this->rMargin; - } else { - $this->x = $this->lMargin; - } - } - } else { - // go left or right by case - if ($this->rtl) { - $this->x -= $w; - } else { - $this->x += $w; - } - } - } - - /** - * This method allows printing text with line breaks. They can be automatic (as soon as the text reaches the right border of the cell) or explicit (via the \n character). As many cells as necessary are output, one below the other.
    - * Text can be aligned, centered or justified. The cell block can be framed and the background painted. - * @param float $w Width of cells. If 0, they extend up to the right margin of the page. - * @param float $h Cell minimum height. The cell extends automatically if needed. - * @param string $txt String to print - * @param mixed $border Indicates if borders must be drawn around the cell block. The value can be either a number:or a string containing some or all of the following characters (in any order): - * @param string $align Allows to center or align the text. Possible values are: - * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0. - * @param int $ln Indicates where the current position should go after the call. Possible values are: - * @param int $x x position in user units - * @param int $y y position in user units - * @param boolean $reseth if true reset the last cell height (default true). - * @param int $stretch stretch carachter mode: - * @param boolean $ishtml se to true if $txt is HTML content (default = false). - * @return int Return the number of cells or 1 for html mode. - * @since 1.3 - * @see SetFont(), SetDrawColor(), SetFillColor(), SetTextColor(), SetLineWidth(), Cell(), Write(), SetAutoPageBreak() - */ - function MultiCell($w, $h, $txt, $border=0, $align='J', $fill=0, $ln=1, $x='', $y='', $reseth=true, $stretch=0, $ishtml=false) { - - if ((empty($this->lasth))OR ($reseth)) { - //set row height - $this->lasth = $this->FontSize * $this->cell_height_ratio; - } - - // get current page number - $startpage = $this->page; - - if (!empty($y)) { - $this->SetY($y); - } else { - $y = $this->GetY(); - } - if (!empty($x)) { - $this->SetX($x); - } else { - $x = $this->GetX(); - } - - if(empty($w) OR ($w <= 0)) { - if ($this->rtl) { - $w = $this->x - $this->lMargin; - } else { - $w = $this->w - $this->rMargin - $this->x; - } - } - - // store original margin values - $lMargin = $this->lMargin; - $rMargin = $this->rMargin; - - if ($this->rtl) { - $this->SetRightMargin($this->w - $this->x); - $this->SetLeftMargin($this->x - $w); - } else { - $this->SetLeftMargin($this->x); - $this->SetRightMargin($this->w - $this->x - $w); - } - - // set special margins for html alignment - if ($ishtml) { - // HTML mode requires special alignment - $strwidth = $this->GetStringWidth($this->unhtmlentities(strip_tags($txt))); - if ($this->tdalign == "C") { - if ($strwidth < $w) { - $mdiff = (($w - $strwidth) / 2) - $this->cMargin; - } else { - $mdiff = 0; - } - if ($this->rtl) { - $this->SetRightMargin($this->w - $this->x + $mdiff); - $this->SetLeftMargin($this->x - $w + $mdiff); - } else { - $this->SetLeftMargin($this->x + $mdiff); - $this->SetRightMargin($this->w - $this->x - $w); - } - } elseif (($this->tdalign == "R") AND (!$this->rtl)){ - $this->SetLeftMargin($this->x + $w - $strwidth - 2*$this->cMargin); - $this->SetRightMargin($this->w - $this->x - $w); - } elseif (($this->tdalign == "L") AND ($this->rtl)){ - $this->SetRightMargin($this->w - $this->x + $w - $strwidth - 2*$this->cMargin); - $this->SetLeftMargin($this->x - $w); - } - } - - // calculate remaining vertical space on first page ($startpage) - $restspace = $this->getPageHeight() - $this->GetY() - $this->getBreakMargin(); - - // Adjust internal padding - if ($this->cMargin < ($this->LineWidth/2)) { - $this->cMargin = ($this->LineWidth/2); - } - - // Add top space if needed - if (($this->lasth - $this->FontSize) < $this->LineWidth) { - $this->y += $this->LineWidth/2; - } - - if ($ishtml) { - // Write HTML text - $this->writeHTML($txt, true, $fill, $reseth, true); - $nl = 1; - } else { - // Write text - $nl = $this->Write($this->lasth, $txt, '', $fill, $align, true, $stretch); - } - - // Add bottom space if needed - if (($this->lasth - $this->FontSize) < $this->LineWidth) { - $this->y += $this->LineWidth/2; - } - - // Get end-of-text Y position - $currentY = $this->GetY(); - - // get latest page number - $endpage = $this->page; - - // calculate last page - $rh = $y + $h; - while ($rh > $this->PageBreakTrigger) { - if (count($this->pages) == $endpage) { - $this->AddPage(); - } - $endpage++; - $rh -= $this->PageBreakTrigger; - } - - // check if a new page has been created - if ($endpage > $startpage) { - // design borders around HTML cells. - for ($page=$startpage; $page<=$endpage; $page++) { - $this->page = $page; - if ($page==$startpage) { - $this->SetY($this->getPageHeight() - $restspace - $this->getBreakMargin()); - $h = $restspace - 1; - } elseif ($page==$endpage) { - $this->SetY($this->tMargin); // put cursor at the beginning of text - $h = $currentY - $this->tMargin; - } else { - $this->SetY($this->tMargin); // put cursor at the beginning of text - $h = $this->getPageHeight() - $this->tMargin - $this->getBreakMargin(); - } - $this->SetX($x); - $this->Cell($w, $h, "", $border, 1, '', 0); - } - } else { - $h = max($h, ($currentY - $y)); - $this->SetY($y); // put cursor at the beginning of text - $this->SetX($x); - // design a cell around the text - $this->Cell($w, $h, "", $border, 1, '', 0); - } - - // Get end-of-text Y position - $currentY = $this->GetY(); - - // restore original margin values - $this->SetLeftMargin($lMargin); - $this->SetRightMargin($rMargin); - - if($ln>0) { - //Go to the beginning of the next line - $this->SetY($currentY); - if($ln == 2) { - $this->SetX($x + $w); - } - } else { - // go left or right by case - $this->page = $startpage; - $this->y = $y; - $this->SetX($x + $w); - } - - return $nl; - } - - /** - * This method prints text from the current position.
    - * @param float $h Line height - * @param string $txt String to print - * @param mixed $link URL or identifier returned by AddLink() - * @param int $fill Indicates if the background must be painted (1) or transparent (0). Default value: 0. - * @param string $align Allows to center or align the text. Possible values are: - * @param boolean $ln if true set cursor at the bottom of the line, otherwise set cursor at the top of the line. - * @param int $stretch stretch carachter mode: - * @return int Return the number of cells. - * @since 1.5 - */ - function Write($h, $txt, $link='', $fill=0, $align='', $ln=false, $stretch=0) { - require_once(dirname(__FILE__).'/unicode_data.php'); - - // remove carriage returns - $s = str_replace("\r", '', $txt); - - // check if string contains arabic text - if (preg_match(K_RE_PATTERN_ARABIC, $s)) { - $arabic = true; - } else { - $arabic = false; - } - - // get array of chars - $chars = $this->UTF8StringToArray($s); - - // get the number of characters - $nb = count($chars); - - // handle single space character - if(($nb==1) AND preg_match("/[\s]/u", $s)) { - if ($this->rtl) { - $this->x -= $this->GetStringWidth($s); - } else { - $this->x += $this->GetStringWidth($s); - } - return; - } - - // store current position - $prevx = $this->x; - $prevy = $this->y; - - // calculate remaining line width ($w) - if ($this->rtl) { - $w = $this->x - $this->lMargin; - } else { - $w = $this->w - $this->rMargin - $this->x; - } - - // max column width - $wmax = $w - (2 * $this->cMargin); - - $i = 0; // character position - $j = 0; // current starting position - $sep = -1; // position of the last blank space - $l = 0; // current string lenght - $nl = 0; //number of lines - $linebreak = false; - - // for each character - while($i < $nb) { - //Get the current character - $c = $chars[$i]; - if ($c == 10) { // 10 = "\n" = new line - //Explicit line break - if ($align == "J") { - if ($this->rtl) { - $talign = "R"; - } else { - $talign = "L"; - } - } else { - $talign = $align; - } - $this->Cell($w, $h, $this->UTF8ArrSubString($chars, $j, $i), 0, 1, $talign, $fill, $link, $stretch); - $nl++; - $j = $i + 1; - $l = 0; - $sep = -1; - $w = $this->getRemainingWidth(); - $wmax = $w - (2 * $this->cMargin); - } else { - if(preg_match("/[\s]/u", $this->unichr($c))) { - // update last blank space position - $sep = $i; - } - // update string length - if (($this->isunicode) AND ($arabic)) { - // with bidirectional algorithm some chars may be changed affecting the line length - // *** very slow *** - $l = $this->GetArrStringWidth($this->utf8Bidi(array_slice($chars, $j, $i-$j+1), $this->tmprtl)); - } else { - $l += $this->GetCharWidth($c); - } - if($l > $wmax) { - // we have reached the end of column - if($sep == -1) { - // check if the line was already started - if (($this->rtl AND ($this->x < ($this->w - $this->rMargin))) - OR ((!$this->rtl) AND ($this->x > $this->lMargin))) { - // print a void cell and go to next line - $this->Cell($w, $h, "", 0, 1); - $linebreak = true; - } else { - // truncate the word because do not fit on column - $this->Cell($w, $h, $this->UTF8ArrSubString($chars, $j, $i), 0, 1, $align, $fill, $link, $stretch); - $j = $i; - $i--; - } - } else { - // word wrapping - $this->Cell($w, $h, $this->UTF8ArrSubString($chars, $j, $sep), 0, 1, $align, $fill, $link, $stretch); - $i = $sep; - $sep = -1; - $j = ($i+1); - } - if(strlen($this->lispacer) > 0) { - if ($this->rtl) { - $this->x -= $this->GetStringWidth($this->lispacer); - } else { - $this->x += $this->GetStringWidth($this->lispacer); - } - } - $w = $this->getRemainingWidth(); - $wmax = $w - (2 * $this->cMargin); - if ($linebreak) { - $linebreak = false; - } else { - $nl++; - $l = 0; - } - } - } - $i++; - } // end while i < nb - - // print last substring (if any) - if($l > 0) { - switch ($align) { - case "J": - case "C": { - $w = $w; - break; - } - case "L": { - if ($this->rtl) { - $w = $w; - } else { - $w = $l; - } - break; - } - case "R": { - if ($this->rtl) { - $w = $l; - } else { - $w = $w; - } - break; - } - default: { - $w = $l; - break; - } - } - $this->Cell($w, $h, $this->UTF8ArrSubString($chars, $j, $nb), 0, $ln, $align, $fill, $link, $stretch); - $nl++; - } - - return $nl; - } - - /** - * Returns the remaining width between the current position and margins. - * @return int Return the remaining width - * @access protected - */ - function getRemainingWidth() { - if ($this->rtl) { - return ($this->x - $this->lMargin); - } - else { - return ($this->w - $this->rMargin - $this->x); - } - } - - /** - * Extract a slice of the $strarr array and return it as string. - * @param string $strarr The input array of characters. - * @param int $start the starting element of $strarr. - * @param int $end first element that will not be returned. - * @return Return part of a string - */ - function UTF8ArrSubString($strarr, $start='', $end='') { - if (strlen($start) == 0) { - $start = 0; - } - if (strlen($end) == 0) { - $end = count($strarr); - } - $string = ""; - for ($i=$start; $i < $end; $i++) { - $string .= $this->unichr($strarr[$i]); - } - return $string; - } - - /** - * Returns the unicode caracter specified by UTF-8 code - * @param int $c UTF-8 code - * @return Returns the specified character. - * @author Miguel Perez, Nicola Asuni - * @since 2.3.000 (2008-03-05) - */ - function unichr($c) { - if (!$this->isunicode) { - return chr($c); - } elseif ($c <= 0x7F) { - // one byte - return chr($c); - } else if ($c <= 0x7FF) { - // two bytes - return chr(0xC0 | $c >> 6).chr(0x80 | $c & 0x3F); - } else if ($c <= 0xFFFF) { - // three bytes - return chr(0xE0 | $c >> 12).chr(0x80 | $c >> 6 & 0x3F).chr(0x80 | $c & 0x3F); - } else if ($c <= 0x10FFFF) { - // four bytes - return chr(0xF0 | $c >> 18).chr(0x80 | $c >> 12 & 0x3F).chr(0x80 | $c >> 6 & 0x3F).chr(0x80 | $c & 0x3F); - } else { - return ""; - } - } - - /** - * Puts an image in the page. - * The upper-left corner must be given. - * The dimensions can be specified in different ways: - * Supported formats are JPEG and PNG images whitout GD library and all images supported by GD: GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM; - * The format can be specified explicitly or inferred from the file extension.
    - * It is possible to put a link on the image.
    - * Remark: if an image is used several times, only one copy will be embedded in the file.
    - * @param string $file Name of the file containing the image. - * @param float $x Abscissa of the upper-left corner. - * @param float $y Ordinate of the upper-left corner. - * @param float $w Width of the image in the page. If not specified or equal to zero, it is automatically calculated. - * @param float $h Height of the image in the page. If not specified or equal to zero, it is automatically calculated. - * @param string $type Image format. Possible values are (case insensitive): JPEG and PNG (whitout GD library) and all images supported by GD: GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM;. If not specified, the type is inferred from the file extension. - * @param mixed $link URL or identifier returned by AddLink(). - * @param string $align Indicates the alignment of the pointer next to image insertion relative to image height. The value can be: - * @param boolean $resize If true resize (reduce) the image to fit $w and $h (requires GD library). - * @param int $dpi dot-per-inch resolution used on resize - * @since 1.1 - * @see AddLink() - */ - function Image($file, $x, $y, $w=0, $h=0, $type='', $link='', $align='', $resize=false, $dpi=300) { - // get image size - list($pixw, $pixh) = getimagesize($file); - // calculate image width and height on document - if(($w <= 0) AND ($h <= 0)) { - // convert image size to document unit - $w = $pixw / ($this->imgscale * $this->k); - $h = $pixh / ($this->imgscale * $this->k); - } elseif($w <= 0) { - $w = $h * $pixw / $pixh; - } elseif($h <= 0) { - $h = $w * $pixh / $pixw; - } - // calculate new minimum dimensions in pixels - $neww = round($w * $this->k * $dpi / $this->dpi); - $newh = round($h * $this->k * $dpi / $this->dpi); - // check if resize is necessary (resize is used only to reduce the image) - if (($neww * $newh) >= ($pixw * $pixh)) { - $resize = false; - } - // check if image has been already added on document - if(!isset($this->images[$file])) { - //First use of image, get info - if($type == '') { - $pos = strrpos($file,'.'); - if(empty($pos)) { - $this->Error('Image file has no extension and no type was specified: '.$file); - } - $type = substr($file, $pos+1); - } - $type = strtolower($type); - if ($type == "jpg") { - $type = "jpeg"; - } - - $mqr = get_magic_quotes_runtime(); - set_magic_quotes_runtime(0); - - // Check for GD image handler function - $gdfunction = "imagecreatefrom".$type; - if (function_exists($gdfunction)) { - $img = $gdfunction($file); - if ($resize) { - $imgr = imagecreatetruecolor($neww, $newh); - imagecopyresampled($imgr, $img, 0, 0, 0, 0, $neww, $newh, $pixw, $pixh); - $info = $this->_toJPEG($imgr); - } else { - $info = $this->_toJPEG($img); - } - } else { - // try other image handlers - $mtd = '_parse'.$type; - if(!method_exists($this,$mtd)) { - return; - } - $info = $this->$mtd($file); - } - if($info === false) { - //If false, we cannot process image - return; - } - - set_magic_quotes_runtime($mqr); - - $info['i'] = count($this->images) + 1; - // add image to document - $this->images[$file] = $info; - } else { - $info = $this->images[$file]; - } - - // 2007-10-19 Warren Sherliker - // Check whether we need a new page first as this does not fit - // Copied from Cell() - if((($this->y + $h) > $this->PageBreakTrigger) AND empty($this->InFooter) AND $this->AcceptPageBreak()) { - // Automatic page break - $this->AddPage($this->CurOrientation); - // Reset coordinates to top fo next page - $x = $this->GetX(); - $y = $this->GetY(); - } - // 2007-10-19 Warren Sherliker: End Edit - - // set bottomcoordinates - $this->img_rb_y = $y + $h; - if ($this->rtl) { - $ximg = ($this->w - $x -$w); - // set left side coordinate - $this->img_rb_x = $ximg; - } else { - $ximg = $x; - // set right side coordinate - $this->img_rb_x = $ximg + $w; - } - $xkimg = $ximg * $this->k; - $this->_out(sprintf('q %.2f 0 0 %.2f %.2f %.2f cm /I%d Do Q', $w*$this->k, $h*$this->k, $xkimg, ($this->h-($y+$h))*$this->k, $info['i'])); - - if($link) { - $this->Link($ximg, $y, $w, $h, $link); - } - - // set pointer to align the successive text/objects - switch($align) { - case 'T':{ - $this->y = $y; - $this->x = $this->img_rb_x; - break; - } - case 'M':{ - $this->y = $y + round($h/2); - $this->x = $this->img_rb_x; - break; - } - case 'B':{ - $this->y = $this->img_rb_y; - $this->x = $this->img_rb_x; - break; - } - case 'N':{ - $this->SetY($this->img_rb_y); - break; - } - default:{ - break; - } - } - } - - /** - * Convert the loaded php image to a JPEG and then return a structure for the PDF creator. - * This function requires GD library and write access to the directory defined on K_PATH_CACHE constant. - * @param string $file Image file name. - * @param image $image Image object. - * return image JPEG image object. - * @access protected - */ - function _toJPEG($image) { - $tempname = tempnam(K_PATH_CACHE,'jpg'); - imagejpeg($image, $tempname, $this->jpeg_quality); - imagedestroy($image); - $retvars = $this->_parsejpeg($tempname); - // tidy up by removing temporary image - unlink($tempname); - return $retvars; - } - - /** - * Extract info from a JPEG file without using GD library - * @param string $file image file to parse - * @return array structure containing the image data - * @access protected - */ - function _parsejpeg($file) { - $a = getimagesize($file); - if (empty($a)) { - $this->Error('Missing or incorrect image file: '.$file); - } - if ($a[2] != 2) { - $this->Error('Not a JPEG file: '.$file); - } - if ((!isset($a['channels'])) OR ($a['channels']==3)) { - $colspace='DeviceRGB'; - } elseif ($a['channels']==4) { - $colspace='DeviceCMYK'; - } else { - $colspace='DeviceGray'; - } - $bpc=isset($a['bits']) ? $a['bits'] : 8; - //Read whole file - $f = fopen($file, 'rb'); - $data = ''; - while(!feof($f)) { - $data .= fread($f,4096); - } - fclose($f); - return array('w' => $a[0], 'h' => $a[1], 'cs' => $colspace, 'bpc' => $bpc, 'f' => 'DCTDecode', 'data' => $data); - } - - /** - * Extract info from a PNG file without using GD - * @param string $file image file to parse - * @return array structure containing the image data - * @access protected - */ - function _parsepng($file) { - $f = fopen($file,'rb'); - if(empty($f)) { - $this->Error('Can\'t open image file: '.$file); - } - //Check signature - if(fread($f,8)!=chr(137).'PNG'.chr(13).chr(10).chr(26).chr(10)) { - $this->Error('Not a PNG file: '.$file); - } - //Read header chunk - fread($f,4); - if(fread($f,4)!='IHDR') { - $this->Error('Incorrect PNG file: '.$file); - } - $w = $this->_freadint($f); - $h = $this->_freadint($f); - $bpc = ord(fread($f,1)); - if($bpc > 8) { - $this->Error('16-bit depth not supported: '.$file); - } - $ct = ord(fread($f,1)); - if($ct == 0) { - $colspace = 'DeviceGray'; - } elseif($ct == 2) { - $colspace = 'DeviceRGB'; - } elseif($ct == 3) { - $colspace = 'Indexed'; - } else { - $this->Error('Alpha channel not supported: '.$file); - } - if(ord(fread($f,1)) != 0) { - $this->Error('Unknown compression method: '.$file); - } - if(ord(fread($f,1)) != 0) { - $this->Error('Unknown filter method: '.$file); - } - if(ord(fread($f,1)) != 0) { - $this->Error('Interlacing not supported: '.$file); - } - fread($f,4); - $parms='/DecodeParms <>'; - //Scan chunks looking for palette, transparency and image data - $pal = ''; - $trns = ''; - $data = ''; - do { - $n=$this->_freadint($f); - $type=fread($f,4); - if($type=='PLTE') { - //Read palette - $pal=fread($f,$n); - fread($f,4); - } - elseif($type=='tRNS') { - //Read transparency info - $t=fread($f,$n); - if($ct==0) { - $trns=array(ord(substr($t,1,1))); - } - elseif($ct==2) { - $trns=array(ord(substr($t,1,1)),ord(substr($t,3,1)),ord(substr($t,5,1))); - } - else { - $pos=strpos($t,chr(0)); - if($pos!==false) { - $trns=array($pos); - } - } - fread($f,4); - } - elseif($type=='IDAT') { - //Read image data block - $data.=fread($f,$n); - fread($f,4); - } - elseif($type=='IEND') { - break; - } - else { - fread($f,$n+4); - } - } - while($n); - if($colspace=='Indexed' and empty($pal)) { - $this->Error('Missing palette in '.$file); - } - fclose($f); - return array('w' => $w, 'h' => $h, 'cs' => $colspace, 'bpc' => $bpc, 'f' => 'FlateDecode', 'parms' => $parms, 'pal' => $pal, 'trns' => $trns, 'data' => $data); - } - - /** - * Performs a line break. The current abscissa goes back to the left margin and the ordinate increases by the amount passed in parameter. - * @param float $h The height of the break. By default, the value equals the height of the last printed cell. - * @since 1.0 - * @see Cell() - */ - function Ln($h='') { - //Line feed; default value is last cell height - if ($this->rtl) { - $this->x = $this->w - $this->rMargin; - } else { - $this->x = $this->lMargin; - } - if(is_string($h)) { - $this->y += $this->lasth; - } else { - $this->y += $h; - } - } - - /** - * Returns the relative X value of current position. - * The value is relative to the left border for LTR languages and to the right border for RTL languages. - * @return float - * @since 1.2 - * @see SetX(), GetY(), SetY() - */ - function GetX() { - //Get x position - if ($this->rtl) { - return ($this->w - $this->x); - } else { - return $this->x; - } - } - - /** - * Returns the absolute X value of current position. - * @return float - * @since 1.2 - * @see SetX(), GetY(), SetY() - */ - function GetAbsX() { - return $this->x; - } - - /** - * Returns the ordinate of the current position. - * @return float - * @since 1.0 - * @see SetY(), GetX(), SetX() - */ - function GetY() { - //Get y position - return $this->y; - } - - /** - * Defines the abscissa of the current position. - * If the passed value is negative, it is relative to the right of the page (or left if language is RTL). - * @param float $x The value of the abscissa. - * @since 1.2 - * @see GetX(), GetY(), SetY(), SetXY() - */ - function SetX($x) { - //Set x position - if ($this->rtl) { - if($x >= 0) { - $this->x = $this->w - $x; - } else { - $this->x = abs($x); - } - } else { - if($x >= 0) { - $this->x = $x; - } else { - $this->x = $this->w + $x; - } - } - } - - /** - * Moves the current abscissa back to the left margin and sets the ordinate. - * If the passed value is negative, it is relative to the bottom of the page. - * @param float $y The value of the ordinate. - * @since 1.0 - * @see GetX(), GetY(), SetY(), SetXY() - */ - function SetY($y) { - //Set y position and reset x - if ($this->rtl) { - $this->x = $this->w - $this->rMargin; - } else { - $this->x = $this->lMargin; - } - if($y >= 0) { - $this->y = $y; - } else { - $this->y = $this->h + $y; - } - } - - - /** - * Defines the abscissa and ordinate of the current position. If the passed values are negative, they are relative respectively to the right and bottom of the page. - * @param float $x The value of the abscissa - * @param float $y The value of the ordinate - * @since 1.2 - * @see SetX(), SetY() - */ - function SetXY($x, $y) { - //Set x and y positions - $this->SetY($y); - $this->SetX($x); - } - - /** - * Send the document to a given destination: string, local file or browser. In the last case, the plug-in may be used (if present) or a download ("Save as" dialog box) may be forced.
    - * The method first calls Close() if necessary to terminate the document. - * @param string $name The name of the file. If not given, the document will be sent to the browser (destination I) with the name doc.pdf. - * @param string $dest Destination where to send the document. It can take one of the following values:If the parameter is not specified but a name is given, destination is F. If no parameter is specified at all, destination is I.
    Note: for compatibility with previous versions, a boolean value is also accepted (false for F and true for D). - * @since 1.0 - * @see Close() - */ - function Output($name='',$dest='') { - //Output PDF to some destination - //Finish document if necessary - if($this->state < 3) { - $this->Close(); - } - //Normalize parameters - if(is_bool($dest)) { - $dest=$dest ? 'D' : 'F'; - } - $dest=strtoupper($dest); - if($dest=='') { - if($name=='') { - $name='doc.pdf'; - $dest='I'; - } else { - $dest='F'; - } - } - switch($dest) { - case 'I': { - //Send to standard output - if(ob_get_contents()) { - $this->Error('Some data has already been output, can\'t send PDF file'); - } - if(php_sapi_name()!='cli') { - //We send to a browser - header('Content-Type: application/pdf'); - if(headers_sent()) { - $this->Error('Some data has already been output to browser, can\'t send PDF file'); - } - header('Content-Length: '.strlen($this->buffer)); - header('Content-disposition: inline; filename="'.$name.'"'); - } - echo $this->buffer; - break; - } - case 'D': { - //Download file - if(ob_get_contents()) { - $this->Error('Some data has already been output, can\'t send PDF file'); - } - if(isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'],'MSIE')) { - header('Content-Type: application/force-download'); - } else { - header('Content-Type: application/octet-stream'); - } - if(headers_sent()) { - $this->Error('Some data has already been output to browser, can\'t send PDF file'); - } - header('Content-Length: '.strlen($this->buffer)); - header('Content-disposition: attachment; filename="'.$name.'"'); - echo $this->buffer; - break; - } - case 'F': { - //Save to local file - $f=fopen($name,'wb'); - if(!$f) { - $this->Error('Unable to create output file: '.$name); - } - fwrite($f,$this->buffer,strlen($this->buffer)); - fclose($f); - break; - } - case 'S': { - //Return as a string - return $this->buffer; - } - default: { - $this->Error('Incorrect output destination: '.$dest); - } - } - return ''; - } - - // Protected methods - - /** - * Check for locale-related bug - * @access protected - */ - function _dochecks() { - //Check for locale-related bug - if(1.1==1) { - $this->Error('Don\'t alter the locale before including class file'); - } - //Check for decimal separator - if(sprintf('%.1f',1.0)!='1.0') { - setlocale(LC_NUMERIC,'C'); - } - } - - /** - * Return fonts path - * @access protected - */ - function _getfontpath() { - if(!defined('K_PATH_FONTS') AND is_dir(dirname(__FILE__).'/font')) { - define('K_PATH_FONTS', dirname(__FILE__).'/font/'); - } - return defined('K_PATH_FONTS') ? K_PATH_FONTS : ''; - } - - /** - * Start document - * @access protected - */ - function _begindoc() { - //Start document - $this->state=1; - $this->_out('%PDF-'.$this->PDFVersion); - } - - /** - * Output pages. - * @access protected - */ - function _putpages() { - $nb = $this->page; - if (!empty($this->pagegroups)) { - // do page number replacement - foreach ($this->pagegroups as $k => $v) { - $alias = $this->_escapetext($k); - $nbstr = $this->UTF8ToUTF16BE($v, false); - for ($n = 1; $n <= $nb; $n++) { - $this->pages[$n] = str_replace($alias, $nbstr, $this->pages[$n]); - } - } - } - if(!empty($this->AliasNbPages)) { - $nbstr = $this->UTF8ToUTF16BE($nb, false); - //Replace number of pages - for($n = 1; $n <= $nb; $n++) { - $this->pages[$n] = str_replace($this->AliasNbPages, $nbstr, $this->pages[$n]); - } - } - if($this->DefOrientation=='P') { - $wPt=$this->fwPt; - $hPt=$this->fhPt; - } - else { - $wPt=$this->fhPt; - $hPt=$this->fwPt; - } - $filter=($this->compress) ? '/Filter /FlateDecode ' : ''; - for($n=1;$n<=$nb;$n++) { - //Page - $this->_newobj(); - $this->_out('<_out('/Parent 1 0 R'); - if(isset($this->OrientationChanges[$n])) { - $this->_out(sprintf('/MediaBox [0 0 %.2f %.2f]',$hPt,$wPt)); - } - $this->_out('/Resources 2 0 R'); - if(isset($this->PageLinks[$n])) { - //Links - $annots='/Annots ['; - foreach($this->PageLinks[$n] as $pl) { - $rect=sprintf('%.2f %.2f %.2f %.2f',$pl[0],$pl[1],$pl[0]+$pl[2],$pl[1]-$pl[3]); - $annots.='<_uristring($pl[4]).'>>>>'; - } - else { - $l=$this->links[$pl[4]]; - $h=isset($this->OrientationChanges[$l[0]]) ? $wPt : $hPt; - $annots.=sprintf('/Dest [%d 0 R /XYZ 0 %.2f null]>>',1+2*$l[0],$h-$l[1]*$this->k); - } - } - $this->_out($annots.']'); - } - $this->_out('/Contents '.($this->n+1).' 0 R>>'); - $this->_out('endobj'); - //Page content - $p=($this->compress) ? gzcompress($this->pages[$n]) : $this->pages[$n]; - $this->_newobj(); - $this->_out('<<'.$filter.'/Length '.strlen($p).'>>'); - $this->_putstream($p); - $this->_out('endobj'); - } - //Pages root - $this->offsets[1]=strlen($this->buffer); - $this->_out('1 0 obj'); - $this->_out('<_out($kids.']'); - $this->_out('/Count '.$nb); - $this->_out(sprintf('/MediaBox [0 0 %.2f %.2f]',$wPt,$hPt)); - $this->_out('>>'); - $this->_out('endobj'); - } - - /** - * Adds fonts - * _putfonts - * @access protected - */ - function _putfonts() { - $nf=$this->n; - foreach($this->diffs as $diff) { - //Encodings - $this->_newobj(); - $this->_out('<>'); - $this->_out('endobj'); - } - $mqr=get_magic_quotes_runtime(); - set_magic_quotes_runtime(0); - foreach($this->FontFiles as $file=>$info) { - //Font file embedding - $this->_newobj(); - $this->FontFiles[$file]['n']=$this->n; - $font=''; - $f=fopen($this->_getfontpath().strtolower($file),'rb',1); - if(!$f) { - $this->Error('Font file not found: '.$file); - } - while(!feof($f)) { - $font .= fread($f, 8192); - } - fclose($f); - $compressed=(substr($file,-2)=='.z'); - if(!$compressed && isset($info['length2'])) { - $header=(ord($font{0})==128); - if($header) { - //Strip first binary header - $font=substr($font,6); - } - if($header && ord($font{$info['length1']})==128) { - //Strip second binary header - $font=substr($font,0,$info['length1']).substr($font,$info['length1']+6); - } - } - $this->_out('<_out('/Filter /FlateDecode'); - } - $this->_out('/Length1 '.$info['length1']); - if(isset($info['length2'])) { - $this->_out('/Length2 '.$info['length2'].' /Length3 0'); - } - $this->_out('>>'); - $this->_putstream($font); - $this->_out('endobj'); - } - set_magic_quotes_runtime($mqr); - foreach($this->fonts as $k=>$font) { - //Font objects - $this->fonts[$k]['n']=$this->n+1; - $type=$font['type']; - $name=$font['name']; - if($type=='core') { - //Standard font - $this->_newobj(); - $this->_out('<_out('/BaseFont /'.$name); - $this->_out('/Subtype /Type1'); - if($name!='Symbol' && $name!='ZapfDingbats') { - $this->_out('/Encoding /WinAnsiEncoding'); - } - $this->_out('>>'); - $this->_out('endobj'); - } elseif($type=='Type1' OR $type=='TrueType') { - //Additional Type1 or TrueType font - $this->_newobj(); - $this->_out('<_out('/BaseFont /'.$name); - $this->_out('/Subtype /'.$type); - $this->_out('/FirstChar 32 /LastChar 255'); - $this->_out('/Widths '.($this->n+1).' 0 R'); - $this->_out('/FontDescriptor '.($this->n+2).' 0 R'); - if($font['enc']) { - if(isset($font['diff'])) { - $this->_out('/Encoding '.($nf+$font['diff']).' 0 R'); - } else { - $this->_out('/Encoding /WinAnsiEncoding'); - } - } - $this->_out('>>'); - $this->_out('endobj'); - //Widths - $this->_newobj(); - $cw=&$font['cw']; - $s='['; - for($i=32;$i<=255;$i++) { - $s.=$cw[chr($i)].' '; - } - $this->_out($s.']'); - $this->_out('endobj'); - //Descriptor - $this->_newobj(); - $s='<$v) { - $s.=' /'.$k.' '.$v; - } - $file = $font['file']; - if($file) { - $s.=' /FontFile'.($type=='Type1' ? '' : '2').' '.$this->FontFiles[$file]['n'].' 0 R'; - } - $this->_out($s.'>>'); - $this->_out('endobj'); - } else { - //Allow for additional types - $mtd='_put'.strtolower($type); - if(!method_exists($this, $mtd)) { - $this->Error('Unsupported font type: '.$type); - } - $this->$mtd($font); - } - } - } - - /** - * _putimages - * @access protected - */ - function _putimages() { - $filter=($this->compress) ? '/Filter /FlateDecode ' : ''; - reset($this->images); - while(list($file,$info)=each($this->images)) { - $this->_newobj(); - $this->images[$file]['n']=$this->n; - $this->_out('<_out('/Subtype /Image'); - $this->_out('/Width '.$info['w']); - $this->_out('/Height '.$info['h']); - - if (isset($info["masked"])) { - $this->_out('/SMask '.($this->n-1).' 0 R'); - } - - if($info['cs']=='Indexed') { - $this->_out('/ColorSpace [/Indexed /DeviceRGB '.(strlen($info['pal'])/3-1).' '.($this->n+1).' 0 R]'); - } - else { - $this->_out('/ColorSpace /'.$info['cs']); - if($info['cs']=='DeviceCMYK') { - $this->_out('/Decode [1 0 1 0 1 0 1 0]'); - } - } - $this->_out('/BitsPerComponent '.$info['bpc']); - if(isset($info['f'])) { - $this->_out('/Filter /'.$info['f']); - } - if(isset($info['parms'])) { - $this->_out($info['parms']); - } - if(isset($info['trns']) and is_array($info['trns'])) { - $trns=''; - for($i=0;$i_out('/Mask ['.$trns.']'); - } - $this->_out('/Length '.strlen($info['data']).'>>'); - $this->_putstream($info['data']); - unset($this->images[$file]['data']); - $this->_out('endobj'); - //Palette - if($info['cs']=='Indexed') { - $this->_newobj(); - $pal=($this->compress) ? gzcompress($info['pal']) : $info['pal']; - $this->_out('<<'.$filter.'/Length '.strlen($pal).'>>'); - $this->_putstream($pal); - $this->_out('endobj'); - } - } - } - - /** - * _putxobjectdict - * @access protected - */ - function _putxobjectdict() { - foreach($this->images as $image) { - $this->_out('/I'.$image['i'].' '.$image['n'].' 0 R'); - } - } - - /** - * Put Resources Dictionary. - * @access protected - */ - function _putresourcedict(){ - $this->_out('/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]'); - $this->_out('/Font <<'); - foreach($this->fonts as $font) { - $this->_out('/F'.$font['i'].' '.$font['n'].' 0 R'); - } - $this->_out('>>'); - $this->_out('/XObject <<'); - $this->_putxobjectdict(); - $this->_out('>>'); - // visibility - $this->_out('/Properties <n_ocg_print.' 0 R /OC2 '.$this->n_ocg_view.' 0 R>>'); - // transparency - $this->_out('/ExtGState <<'); - foreach($this->extgstates as $k => $extgstate) { - $this->_out('/GS'.$k.' '.$extgstate['n'].' 0 R'); - } - $this->_out('>>'); - - } - - /** - * Put Resources. - * @access protected - */ - function _putresources() { - $this->_putextgstates(); - $this->_putocg(); - $this->_putfonts(); - $this->_putimages(); - //Resource dictionary - $this->offsets[2]=strlen($this->buffer); - $this->_out('2 0 obj'); - $this->_out('<<'); - $this->_putresourcedict(); - $this->_out('>>'); - $this->_out('endobj'); - $this->_putjavascript(); - $this->_putbookmarks(); - // encryption - if ($this->encrypted) { - $this->_newobj(); - $this->enc_obj_id = $this->n; - $this->_out('<<'); - $this->_putencryption(); - $this->_out('>>'); - $this->_out('endobj'); - } - } - - /** - * Adds some Metadata information - * (see Chapter 10.2 of PDF Reference) - * @access protected - */ - function _putinfo() { - if(!empty($this->title)) { - $this->_out('/Title '.$this->_textstring($this->title)); - } - if(!empty($this->author)) { - $this->_out('/Author '.$this->_textstring($this->author)); - } - if(!empty($this->subject)) { - $this->_out('/Subject '.$this->_textstring($this->subject)); - } - if(!empty($this->keywords)) { - $this->_out('/Keywords '.$this->_textstring($this->keywords)); - } - if(!empty($this->creator)) { - $this->_out('/Creator '.$this->_textstring($this->creator)); - } - if(defined('PDF_PRODUCER')) { - $this->_out('/Producer '.$this->_textstring(PDF_PRODUCER)); - } - $this->_out('/CreationDate '.$this->_datestring('D:'.date('YmdHis'))); - $this->_out('/ModDate '.$this->_datestring('D:'.date('YmdHis'))); - } - - /** - * Format a date string for meta information - * @param string $s date string to escape. - * @return string escaped string. - * @access protected - */ - function _datestring($s) { - if ($this->encrypted) { - $s = $this->_RC4($this->_objectkey($this->n), $s); - } - return '('. $this->_escape($s).')'; - } - - /** - * _putcatalog - * @access protected - */ - function _putcatalog() { - $this->_out('/Type /Catalog'); - $this->_out('/Pages 1 0 R'); - if($this->ZoomMode=='fullpage') { - $this->_out('/OpenAction [3 0 R /Fit]'); - } - elseif($this->ZoomMode=='fullwidth') { - $this->_out('/OpenAction [3 0 R /FitH null]'); - } - elseif($this->ZoomMode=='real') { - $this->_out('/OpenAction [3 0 R /XYZ null null 1]'); - } - elseif(!is_string($this->ZoomMode)) { - $this->_out('/OpenAction [3 0 R /XYZ null null '.($this->ZoomMode/100).']'); - } - if($this->LayoutMode=='single') { - $this->_out('/PageLayout /SinglePage'); - } - elseif($this->LayoutMode=='continuous') { - $this->_out('/PageLayout /OneColumn'); - } - elseif($this->LayoutMode=='two') { - $this->_out('/PageLayout /TwoColumnLeft'); - } - if (!empty($this->javascript)) { - $this->_out('/Names <n_js).' 0 R>>'); - } - if(count($this->outlines)>0) { - $this->_out('/Outlines '.$this->OutlineRoot.' 0 R'); - $this->_out('/PageMode /UseOutlines'); - } - if($this->rtl) { - $this->_out('/ViewerPreferences << /Direction /R2L >>'); - } - $p = $this->n_ocg_print.' 0 R'; - $v = $this->n_ocg_view.' 0 R'; - $as = "<> <>"; - $this->_out("/OCProperties <>>>"); - $this->_putuserrights(); - } - - /** - * _puttrailer - * @access protected - */ - function _puttrailer() { - $this->_out('/Size '.($this->n+1)); - $this->_out('/Root '.$this->n.' 0 R'); - $this->_out('/Info '.($this->n-1).' 0 R'); - if ($this->encrypted) { - $this->_out('/Encrypt '.$this->enc_obj_id.' 0 R'); - $this->_out('/ID [()()]'); - } - } - - /** - * _putheader - * @access protected - */ - function _putheader() { - $this->_out('%PDF-'.$this->PDFVersion); - } - - /** - * End of document. - * @access protected - */ - function _enddoc() { - $this->_putheader(); - $this->_putpages(); - $this->_putresources(); - //Info - $this->_newobj(); - $this->_out('<<'); - $this->_putinfo(); - $this->_out('>>'); - $this->_out('endobj'); - //Catalog - $this->_newobj(); - $this->_out('<<'); - $this->_putcatalog(); - $this->_out('>>'); - $this->_out('endobj'); - //Cross-ref - $o=strlen($this->buffer); - $this->_out('xref'); - $this->_out('0 '.($this->n+1)); - $this->_out('0000000000 65535 f '); - for($i=1;$i<=$this->n;$i++) { - $this->_out(sprintf('%010d 00000 n ',$this->offsets[$i])); - } - //Trailer - $this->_out('trailer'); - $this->_out('<<'); - $this->_puttrailer(); - $this->_out('>>'); - $this->_out('startxref'); - $this->_out($o); - $this->_out('%%EOF'); - $this->state=3; - } - - /** - * Initialize a page. - * @param string $orientation page orientation. Possible values are (case insensitive):
    • P or Portrait (default)
    • L or Landscape
    - * @access protected - */ - function _beginpage($orientation) { - $this->page++; - $this->pages[$this->page]=''; - $this->state=2; - if ($this->rtl) { - $this->x = $this->w - $this->rMargin; - } else { - $this->x = $this->lMargin; - } - $this->y = $this->tMargin; - $this->FontFamily=''; - //Page orientation - if(empty($orientation)) { - $orientation=$this->DefOrientation; - } - else { - $orientation=strtoupper($orientation{0}); - if($orientation!=$this->DefOrientation) { - $this->OrientationChanges[$this->page]=true; - } - } - if($orientation!=$this->CurOrientation) { - //Change orientation - if($orientation=='P') { - $this->wPt=$this->fwPt; - $this->hPt=$this->fhPt; - $this->w=$this->fw; - $this->h=$this->fh; - } - else { - $this->wPt=$this->fhPt; - $this->hPt=$this->fwPt; - $this->w=$this->fh; - $this->h=$this->fw; - } - $this->PageBreakTrigger=$this->h-$this->bMargin; - $this->CurOrientation=$orientation; - } - if($this->newpagegroup){ - // start a new group - $n = sizeof($this->pagegroups) + 1; - $alias = "{nb".$n."}"; - $this->pagegroups[$alias] = 1; - $this->currpagegroup = $alias; - $this->newpagegroup = false; - } elseif($this->currpagegroup) { - $this->pagegroups[$this->currpagegroup]++; - } - } - - /** - * End of page contents - * @access protected - */ - function _endpage() { - $this->setVisibility("all"); - $this->state=1; - } - - /** - * Begin a new object - * @access protected - */ - function _newobj() { - $this->n++; - $this->offsets[$this->n]=strlen($this->buffer); - $this->_out($this->n.' 0 obj'); - } - - /** - * Underline text - * @param int $x X coordinate - * @param int $y Y coordinate - * @param string $txt text to underline - * @access protected - */ - function _dounderline($x, $y, $txt) { - $up = $this->CurrentFont['up']; - $ut = $this->CurrentFont['ut']; - $w = $this->GetStringWidth($txt); - return sprintf('%.2f %.2f %.2f %.2f re f', $x * $this->k, ($this->h - ($y - $up / 1000 * $this->FontSize)) * $this->k, $w * $this->k, -$ut / 1000 * $this->FontSizePt); - } - - /** - * Line through text - * @param int $x X coordinate - * @param int $y Y coordinate - * @param string $txt text to underline - * @access protected - */ - function _dolinethrough($x, $y, $txt) { - $up = $this->CurrentFont['up']; - $ut = $this->CurrentFont['ut']; - $w = $this->GetStringWidth($txt); - return sprintf('%.2f %.2f %.2f %.2f re f', $x * $this->k, ($this->h - ($y - ($this->FontSize/2) - $up / 1000 * $this->FontSize)) * $this->k, $w * $this->k, -$ut / 1000 * $this->FontSizePt); - } - - /** - * Read a 4-byte integer from file - * @param string $f file name. - * @return 4-byte integer - * @access protected - */ - function _freadint($f) { - $a=unpack('Ni',fread($f,4)); - return $a['i']; - } - - /** - * Format a text string for meta information - * @param string $s string to escape. - * @return string escaped string. - * @access protected - */ - function _textstring($s) { - if($this->isunicode) { - //Convert string to UTF-16BE - $s = $this->UTF8ToUTF16BE($s, true); - } - if ($this->encrypted) { - $s = $this->_RC4($this->_objectkey($this->n), $s); - } - return '('. $this->_escape($s).')'; - } - - /** - * Format an URI string - * @param string $s string to escape. - * @return string escaped string. - * @access protected - */ - function _uristring($s) { - if ($this->encrypted) { - $s = $this->_RC4($this->_objectkey($this->n), $s); - } - return '('.$this->_escape($s).')'; - } - - /** - * Format a text string - * @param string $s string to escape. - * @return string escaped string. - * @access protected - */ - function _escapetext($s) { - if($this->isunicode) { - //Convert string to UTF-16BE and reverse RTL language - $s = $this->utf8StrRev($s, false, $this->tmprtl); - } - return $this->_escape($s); - } - - /** - * Add \ before \, ( and ) - * @param string $s string to escape. - * @return string escaped string. - * @access protected - */ - function _escape($s) { - // the chr(13) substitution fixes the Bugs item #1421290. - return strtr($s, array(')' => '\\)', '(' => '\\(', '\\' => '\\\\', chr(13) => '\r')); - } - - /** - * Output a stream. - * @param string $s string to output. - * @access protected - */ - function _putstream($s) { - if ($this->encrypted) { - $s = $this->_RC4($this->_objectkey($this->n), $s); - } - $this->_out('stream'); - $this->_out($s); - $this->_out('endstream'); - } - - /** - * Output a string to the document. - * @param string $s string to output. - * @access protected - */ - function _out($s) { - if($this->state==2) { - $this->pages[$this->page] .= $s."\n"; - } - else { - $this->buffer .= $s."\n"; - } - } - - /** - * Adds unicode fonts.
    - * Based on PDF Reference 1.3 (section 5) - * @access protected - * @author Nicola Asuni - * @since 1.52.0.TC005 (2005-01-05) - */ - function _puttruetypeunicode($font) { - // Type0 Font - // A composite font composed of other fonts, organized hierarchically - $this->_newobj(); - $this->_out('<_out('/Subtype /Type0'); - $this->_out('/BaseFont /'.$font['name'].''); - $this->_out('/Encoding /Identity-H'); //The horizontal identity mapping for 2-byte CIDs; may be used with CIDFonts using any Registry, Ordering, and Supplement values. - $this->_out('/DescendantFonts ['.($this->n + 1).' 0 R]'); - $this->_out('/ToUnicode '.($this->n + 2).' 0 R'); - $this->_out('>>'); - $this->_out('endobj'); - - // CIDFontType2 - // A CIDFont whose glyph descriptions are based on TrueType font technology - $this->_newobj(); - $this->_out('<_out('/Subtype /CIDFontType2'); - $this->_out('/BaseFont /'.$font['name'].''); - $this->_out('/CIDSystemInfo '.($this->n + 2).' 0 R'); - $this->_out('/FontDescriptor '.($this->n + 3).' 0 R'); - if (isset($font['desc']['MissingWidth'])){ - $this->_out('/DW '.$font['desc']['MissingWidth'].''); // The default width for glyphs in the CIDFont MissingWidth - } - $w = ""; - foreach ($font['cw'] as $cid => $width) { - $w .= ''.$cid.' ['.$width.'] '; // define a specific width for each individual CID - } - $this->_out('/W ['.$w.']'); // A description of the widths for the glyphs in the CIDFont - $this->_out('/CIDToGIDMap '.($this->n + 4).' 0 R'); - $this->_out('>>'); - $this->_out('endobj'); - - // ToUnicode - // is a stream object that contains the definition of the CMap - // (PDF Reference 1.3 chap. 5.9) - $this->_newobj(); - $this->_out('<>'); - $this->_out('stream'); - $this->_out('/CIDInit /ProcSet findresource begin'); - $this->_out('12 dict begin'); - $this->_out('begincmap'); - $this->_out('/CIDSystemInfo'); - $this->_out('<_out('/Ordering (UCS)'); - $this->_out('/Supplement 0'); - $this->_out('>> def'); - $this->_out('/CMapName /Adobe-Identity-UCS def'); - $this->_out('/CMapType 2 def'); - $this->_out('1 begincodespacerange'); - $this->_out('<0000> '); - $this->_out('endcodespacerange'); - $this->_out('1 beginbfrange'); - $this->_out('<0000> <0000>'); - $this->_out('endbfrange'); - $this->_out('endcmap'); - $this->_out('CMapName currentdict /CMap defineresource pop'); - $this->_out('end'); - $this->_out('end'); - $this->_out('endstream'); - $this->_out('endobj'); - - // CIDSystemInfo dictionary - // A dictionary containing entries that define the character collection of the CIDFont. - $this->_newobj(); - $this->_out('<_out('/Ordering (UCS)'); // A string that uniquely names a character collection issued by a specific registry - $this->_out('/Supplement 0'); // The supplement number of the character collection. - $this->_out('>>'); - $this->_out('endobj'); - - // Font descriptor - // A font descriptor describing the CIDFont default metrics other than its glyph widths - $this->_newobj(); - $this->_out('<_out('/FontName /'.$font['name']); - foreach ($font['desc'] as $key => $value) { - $this->_out('/'.$key.' '.$value); - } - if ($font['file']) { - // A stream containing a TrueType font program - $this->_out('/FontFile2 '.$this->FontFiles[$font['file']]['n'].' 0 R'); - } - $this->_out('>>'); - $this->_out('endobj'); - - // Embed CIDToGIDMap - // A specification of the mapping from CIDs to glyph indices - $this->_newobj(); - $ctgfile = $this->_getfontpath().strtolower($font['ctg']); - if(!file_exists($ctgfile)) { - $this->Error('Font file not found: '.$ctgfile); - } - $size = filesize($ctgfile); - $this->_out('<_out('/Filter /FlateDecode'); - } - $this->_out('>>'); - $this->_putstream(file_get_contents($ctgfile)); - $this->_out('endobj'); - } - - /** - * Converts UTF-8 strings to codepoints array.
    - * Invalid byte sequences will be replaced with 0xFFFD (replacement character)
    - * Based on: http://www.faqs.org/rfcs/rfc3629.html - *
    -		 * 	  Char. number range  |        UTF-8 octet sequence
    -		 *       (hexadecimal)    |              (binary)
    -		 *    --------------------+-----------------------------------------------
    -		 *    0000 0000-0000 007F | 0xxxxxxx
    -		 *    0000 0080-0000 07FF | 110xxxxx 10xxxxxx
    -		 *    0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
    -		 *    0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
    -		 *    ---------------------------------------------------------------------
    -		 *
    -		 *   ABFN notation:
    -		 *   ---------------------------------------------------------------------
    -		 *   UTF8-octets = *( UTF8-char )
    -		 *   UTF8-char   = UTF8-1 / UTF8-2 / UTF8-3 / UTF8-4
    -		 *   UTF8-1      = %x00-7F
    -		 *   UTF8-2      = %xC2-DF UTF8-tail
    -		 *
    -		 *   UTF8-3      = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
    -		 *                 %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
    -		 *   UTF8-4      = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
    -		 *                 %xF4 %x80-8F 2( UTF8-tail )
    -		 *   UTF8-tail   = %x80-BF
    -		 *   ---------------------------------------------------------------------
    -		 * 
    - * @param string $str string to process. - * @return array containing codepoints (UTF-8 characters values) - * @access protected - * @author Nicola Asuni - * @since 1.53.0.TC005 (2005-01-05) - */ - function UTF8StringToArray($str) { - if(!$this->isunicode) { - // split string into array of chars - $strarr = str_split($str); - // convert chars to equivalent code - while(list($pos,$char)=each($strarr)) { - $strarr[$pos] = ord($char); - } - return $strarr; - } - $unicode = array(); // array containing unicode values - $bytes = array(); // array containing single character byte sequences - $numbytes = 1; // number of octetc needed to represent the UTF-8 character - - $str .= ""; // force $str to be a string - $length = strlen($str); - - for($i = 0; $i < $length; $i++) { - $char = ord($str{$i}); // get one string character at time - if(count($bytes) == 0) { // get starting octect - if ($char <= 0x7F) { - $unicode[] = $char; // use the character "as is" because is ASCII - $numbytes = 1; - } elseif (($char >> 0x05) == 0x06) { // 2 bytes character (0x06 = 110 BIN) - $bytes[] = ($char - 0xC0) << 0x06; - $numbytes = 2; - } elseif (($char >> 0x04) == 0x0E) { // 3 bytes character (0x0E = 1110 BIN) - $bytes[] = ($char - 0xE0) << 0x0C; - $numbytes = 3; - } elseif (($char >> 0x03) == 0x1E) { // 4 bytes character (0x1E = 11110 BIN) - $bytes[] = ($char - 0xF0) << 0x12; - $numbytes = 4; - } else { - // use replacement character for other invalid sequences - $unicode[] = 0xFFFD; - $bytes = array(); - $numbytes = 1; - } - } elseif (($char >> 0x06) == 0x02) { // bytes 2, 3 and 4 must start with 0x02 = 10 BIN - $bytes[] = $char - 0x80; - if (count($bytes) == $numbytes) { - // compose UTF-8 bytes to a single unicode value - $char = $bytes[0]; - for($j = 1; $j < $numbytes; $j++) { - $char += ($bytes[$j] << (($numbytes - $j - 1) * 0x06)); - } - if ((($char >= 0xD800) AND ($char <= 0xDFFF)) OR ($char >= 0x10FFFF)) { - /* The definition of UTF-8 prohibits encoding character numbers between - U+D800 and U+DFFF, which are reserved for use with the UTF-16 - encoding form (as surrogate pairs) and do not directly represent - characters. */ - $unicode[] = 0xFFFD; // use replacement character - } - else { - $unicode[] = $char; // add char to array - } - // reset data for next char - $bytes = array(); - $numbytes = 1; - } - } else { - // use replacement character for other invalid sequences - $unicode[] = 0xFFFD; - $bytes = array(); - $numbytes = 1; - } - } - return $unicode; - } - - /** - * Converts UTF-8 strings to UTF16-BE.
    - * @param string $str string to process. - * @param boolean $setbom if true set the Byte Order Mark (BOM = 0xFEFF) - * @return string - * @access protected - * @author Nicola Asuni - * @since 1.53.0.TC005 (2005-01-05) - * @uses UTF8StringToArray(), arrUTF8ToUTF16BE() - */ - function UTF8ToUTF16BE($str, $setbom=true) { - if(!$this->isunicode) { - return $str; // string is not in unicode - } - $unicode = $this->UTF8StringToArray($str); // array containing UTF-8 unicode values - return $this->arrUTF8ToUTF16BE($unicode, $setbom); - } - - /** - * Converts array of UTF-8 characters to UTF16-BE string.
    - * Based on: http://www.faqs.org/rfcs/rfc2781.html - *
    -		 *   Encoding UTF-16:
    -		 * 
    - 		 *   Encoding of a single character from an ISO 10646 character value to
    -		 *    UTF-16 proceeds as follows. Let U be the character number, no greater
    -		 *    than 0x10FFFF.
    -		 * 
    -		 *    1) If U < 0x10000, encode U as a 16-bit unsigned integer and
    -		 *       terminate.
    -		 * 
    -		 *    2) Let U' = U - 0x10000. Because U is less than or equal to 0x10FFFF,
    -		 *       U' must be less than or equal to 0xFFFFF. That is, U' can be
    -		 *       represented in 20 bits.
    -		 * 
    -		 *    3) Initialize two 16-bit unsigned integers, W1 and W2, to 0xD800 and
    -		 *       0xDC00, respectively. These integers each have 10 bits free to
    -		 *       encode the character value, for a total of 20 bits.
    -		 * 
    -		 *    4) Assign the 10 high-order bits of the 20-bit U' to the 10 low-order
    -		 *       bits of W1 and the 10 low-order bits of U' to the 10 low-order
    -		 *       bits of W2. Terminate.
    -		 * 
    -		 *    Graphically, steps 2 through 4 look like:
    -		 *    U' = yyyyyyyyyyxxxxxxxxxx
    -		 *    W1 = 110110yyyyyyyyyy
    -		 *    W2 = 110111xxxxxxxxxx
    -		 * 
    - * @param array $unicode array containing UTF-8 unicode values - * @param boolean $setbom if true set the Byte Order Mark (BOM = 0xFEFF) - * @return string - * @access protected - * @author Nicola Asuni - * @since 2.1.000 (2008-01-08) - * @see UTF8ToUTF16BE() - */ - function arrUTF8ToUTF16BE($unicode, $setbom=true) { - $outstr = ""; // string to be returned - if ($setbom) { - $outstr .= "\xFE\xFF"; // Byte Order Mark (BOM) - } - foreach($unicode as $char) { - if($char == 0xFFFD) { - $outstr .= "\xFF\xFD"; // replacement character - } elseif ($char < 0x10000) { - $outstr .= chr($char >> 0x08); - $outstr .= chr($char & 0xFF); - } else { - $char -= 0x10000; - $w1 = 0xD800 | ($char >> 0x10); - $w2 = 0xDC00 | ($char & 0x3FF); - $outstr .= chr($w1 >> 0x08); - $outstr .= chr($w1 & 0xFF); - $outstr .= chr($w2 >> 0x08); - $outstr .= chr($w2 & 0xFF); - } - } - return $outstr; - } - // ==================================================== - - /** - * Set header font. - * @param array $font font - * @since 1.1 - */ - function setHeaderFont($font) { - $this->header_font = $font; - } - - /** - * Set footer font. - * @param array $font font - * @since 1.1 - */ - function setFooterFont($font) { - $this->footer_font = $font; - } - - /** - * Set language array. - * @param array $language - * @since 1.1 - */ - function setLanguageArray($language) { - $this->l = $language; - $this->rtl = $this->l['a_meta_dir']=='rtl' ? true : false; - } - - /** - * Set document barcode. - * @param string $bc barcode - */ - function setBarcode($bc="") { - $this->barcode = $bc; - } - - /** - * Print Barcode. - * @param int $x x position in user units - * @param int $y y position in user units - * @param int $w width in user units - * @param int $h height position in user units - * @param string $type type of barcode (I25, C128A, C128B, C128C, C39) - * @param string $style barcode style - * @param string $font font for text - * @param int $xres x resolution - * @param string $code code to print - */ - function writeBarcode($x, $y, $w, $h, $type, $style, $font, $xres, $code) { - require_once(dirname(__FILE__)."/barcode/barcode.php"); - require_once(dirname(__FILE__)."/barcode/i25object.php"); - require_once(dirname(__FILE__)."/barcode/c39object.php"); - require_once(dirname(__FILE__)."/barcode/c128aobject.php"); - require_once(dirname(__FILE__)."/barcode/c128bobject.php"); - require_once(dirname(__FILE__)."/barcode/c128cobject.php"); - - if (empty($code)) { - return; - } - - if (empty($style)) { - $style = BCS_ALIGN_LEFT; - $style |= BCS_IMAGE_PNG; - $style |= BCS_TRANSPARENT; - //$style |= BCS_BORDER; - //$style |= BCS_DRAW_TEXT; - //$style |= BCS_STRETCH_TEXT; - //$style |= BCS_REVERSE_COLOR; - } - if (empty($font)) {$font = BCD_DEFAULT_FONT;} - if (empty($xres)) {$xres = BCD_DEFAULT_XRES;} - - $scale_factor = $xres * $this->k; - $bc_w = round($w * $scale_factor); //width in points - $bc_h = round($h * $scale_factor); //height in points - - switch (strtoupper($type)) { - case "I25": { - $obj = new I25Object($bc_w, $bc_h, $style, $code); - break; - } - case "C128A": { - $obj = new C128AObject($bc_w, $bc_h, $style, $code); - break; - } - default: - case "C128B": { - $obj = new C128BObject($bc_w, $bc_h, $style, $code); - break; - } - case "C128C": { - $obj = new C128CObject($bc_w, $bc_h, $style, $code); - break; - } - case "C39": { - $obj = new C39Object($bc_w, $bc_h, $style, $code); - break; - } - } - - $obj->SetFont($font); - $obj->DrawObject(1); - - //use a temporary file.... - $tmpName = tempnam(K_PATH_CACHE,'img'); - imagepng($obj->getImage(), $tmpName); - $this->Image($tmpName, $x, $y, $w, $h, 'png'); - $obj->DestroyObject(); - unset($obj); - unlink($tmpName); - } - - /** - * Returns the PDF data. - */ - function getPDFData() { - if($this->state < 3) { - $this->Close(); - } - return $this->buffer; - } - - // --- HTML PARSER FUNCTIONS --- - - /** - * Allows to preserve some HTML formatting (limited support).
    - * Supported tags are: a, b, blockquote, br, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, img, li, ol, p, small, span, strong, sub, sup, table, td, th, tr, u, ul, - * @param string $html text to display - * @param boolean $ln if true add a new line after text (default = true) - * @param int $fill Indicates if the background must be painted (1) or transparent (0). Default value: 0. - * @param boolean $reseth if true reset the last cell height (default false). - * @param boolean $cell if true add the default cMargin space to each Write (default false). - */ - function writeHTML($html, $ln=true, $fill=0, $reseth=false, $cell=false) { - // reset foreground color stack - $tmp = $this->fgcolor[0]; - unset($this->fgcolor); - $this->fgcolor = array(); - $this->fgcolor[] = $tmp; - - // reset background color stack - $tmp = $this->bgcolor[0]; - unset($this->bgcolor); - $this->bgcolor = array(); - $this->bgcolor[] = $tmp; - - unset($this->bgtag); - $this->bgtag = array(); - - // store some variables - $html=strip_tags($html,"



      • "); //remove all unsupported tags - //replace carriage returns, newlines and tabs - $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ", "\\" => "\\\\"); - $html = strtr($html, $repTable); - $pattern = '/(<[^>]+>)/Uu'; - $a = preg_split($pattern, $html, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); //explodes the string - - if ((empty($this->lasth))OR ($reseth)) { - //set row height - $this->lasth = $this->FontSize * $this->cell_height_ratio; - } - - // count elements - $maxel = count($a); - $key = 0; - - while($key < $maxel) { - $element = $a[$key]; - $cfill = (count($this->bgtag) > 0); - $wfill = ($fill OR $cfill); - - if($this->tdbegin) { - // we are inside an HTML cell
      \n" -."
      or - // find the corresponding closing tag - $closetag = "tdbegin.">"; - $nesting = 0; // account for nested tables - $i = $key + 1; - while ($i < $maxel) { - if (substr($a[$i],0,3) == "<".$this->tdbegin."") { - $nesting++; - } elseif (strtolower($a[$i]) == $closetag) { - if ($nesting > 0) { - $nesting--; - } else { - break; - } - } - $element .= $a[$i]; - $i++; - $key++; - } - $this->tdbegin = false; // this must be fixed for nesting tables - // output multicell in HTML mode - $this->MultiCell(($this->tdcolspan * $this->tdwidth), $this->tdheight, $element, $this->tableborder, $this->tdalign, 0, 0, '', '', true, 0, true); - } elseif (!preg_match($pattern, $element)) { - // the current element is not an HTML tag - //Text - if($this->HREF) { - // HTML Link - $this->addHtmlLink($this->HREF, $element, $wfill); - } else { - $ctmpmargin = $this->cMargin; - if(!$cell) { - $this->cMargin = 0; - } - $this->Write($this->lasth, stripslashes($this->unhtmlentities($element)), '', $wfill, '', false, 0); - $this->cMargin = $ctmpmargin; - } - } else { - // the current element is an HTML tag - $element = substr($element, 1, -1); - if($element{0}=='/') { - // closing html tag - $this->closedHTMLTagHandler(strtolower(substr($element, 1))); - } - else { - //Extract attributes - // get tag name - preg_match('/([a-zA-Z0-9]*)/', $element, $tag); - $tag = strtolower($tag[0]); - // get attributes - preg_match_all('/([^=\s]*)=["\']?([^"\']*)["\']?/', $element, $attr_array, PREG_PATTERN_ORDER); - $attr = array(); // reset attribute array - while(list($id,$name)=each($attr_array[1])) { - $attr[strtolower($name)] = $attr_array[2][$id]; - } - $this->openHTMLTagHandler($tag, $attr, $fill); - } - } - $key++; - } - if ($ln) { - $this->Ln($this->lasth); - } - } - - /** - * Prints a cell (rectangular area) with optional borders, background color and html text string. The upper-left corner of the cell corresponds to the current position. After the call, the current position moves to the right or to the next line.
      - * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting. - * @param float $w Cell width. If 0, the cell extends up to the right margin. - * @param float $h Cell minimum height. The cell extends automatically if needed. - * @param float $x upper-left corner X coordinate - * @param float $y upper-left corner Y coordinate - * @param string $html html text to print. Default value: empty string. - * @param mixed $border Indicates if borders must be drawn around the cell. The value can be either a number:
      • 0: no border (default)
      • 1: frame
      or a string containing some or all of the following characters (in any order):
      • L: left
      • T: top
      • R: right
      • B: bottom
      - * @param int $ln Indicates where the current position should go after the call. Possible values are:
      • 0: to the right (or left for RTL language)
      • 1: to the beginning of the next line
      • 2: below
      - Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0. - * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0. - * @param boolean $reseth if true reset the last cell height (default true). - * @uses MultiCell() - * @see Multicell(), writeHTML(), Cell() - */ - function writeHTMLCell($w, $h, $x, $y, $html='', $border=0, $ln=0, $fill=0, $reseth=true) { - return $this->MultiCell($w, $h, $html, $border, '', $fill, $ln, $x, $y, $reseth, 0, true); - } - - /** - * Process opening tags. - * @param string $tag tag name (in uppercase) - * @param string $attr tag attribute (in uppercase) - * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0. - * @access protected - */ - function openHTMLTagHandler($tag, $attr, $fill=0) { - // check for text direction attribute - if (isset($attr['dir'])) { - $this->tmprtl = $attr['dir']=='rtl' ? 'R' : 'L'; - } else { - $this->tmprtl = false; - } - - if (($tag != 'br') AND ($tag != 'hr') AND ($tag != 'img') ) { - // set foreground color attribute - if (isset($attr['color']) AND $attr['color']!='') { - $col = $this->convertHTMLColorToDec($attr['color']); - } else { - $col = end($this->fgcolor); - } - $this->SetTextColor($col['R'], $col['G'], $col['B'], true); - - // set background color attribute - if ((isset($attr['bgcolor'])) AND ($attr['bgcolor'] != '')) { - $col = $this->convertHTMLColorToDec($attr['bgcolor']); - array_push($this->bgtag, count($this->bgcolor)); - } else { - $col = end($this->bgcolor); - } - $this->SetFillColor($col['R'], $col['G'], $col['B'], true); - } - - //Opening tag - switch($tag) { - case 'table': { - if ((isset($attr['border'])) AND ($attr['border'] != '')) { - $this->tableborder = $attr['border']; - } - else { - $this->tableborder = 0; - } - break; - } - case 'tr': { - break; - } - case 'td': - case 'th': { - $this->tdbegin=$tag; - if ((isset($attr['width'])) AND ($attr['width'] != '')) { - $this->tdwidth = ($attr['width']/4); - } - else { - $this->tdwidth = (($this->w - $this->lMargin - $this->rMargin) / $this->default_table_columns); - } - if ((isset($attr['height'])) AND ($attr['height'] != '')) { - $this->tdheight=($attr['height'] / $this->k); - } - else { - $this->tdheight = $this->lasth; - } - if ((isset($attr['align'])) AND ($attr['align'] != '')) { - switch ($attr['align']) { - case 'center': { - $this->tdalign = "C"; - break; - } - case 'right': { - $this->tdalign = "R"; - break; - } - default: - case 'left': { - $this->tdalign = "L"; - break; - } - } - } else { - if($this->rtl) { - $this->tdalign = "R"; - } else { - $this->tdalign = "L"; - } - } - if ((isset($attr['colspan'])) AND (is_numeric($attr['colspan']))) { - $this->tdcolspan = intval($attr['colspan']); - } else { - $this->tdcolspan = 1; - } - // write a void cell - $cfill = (count($this->bgtag) > 0); - $cell_start_x = $this->x; - $cell_start_y = $this->y; - $this->Cell(($this->tdcolspan * $this->tdwidth), $this->tdheight, '', $this->tableborder, '', $this->tdalign, $cfill); - // restore the cursor at the previous position - $this->x = $cell_start_x; - $this->y = $cell_start_y; - break; - } - case 'hr': { - $this->Ln(); - if ((isset($attr['width'])) AND ($attr['width'] != '')) { - $hrWidth = $attr['width']; - } - else { - $hrWidth = $this->w - $this->lMargin - $this->rMargin; - } - $x = $this->GetX(); - $y = $this->GetY(); - $this->GetLineWidth(); - $prevlinewidth = $this->SetLineWidth(0.2); - $this->Line($x, $y, $x + $hrWidth, $y); - $this->SetLineWidth($prevlinewidth); - $this->Ln(); - break; - } - case 'strong': { - $this->setStyle('b', true); - break; - } - case 'em': { - $this->setStyle('i', true); - break; - } - case 'b': - case 'i': - case 'u': { - $this->setStyle($tag, true); - break; - } - case 'del': { - $this->setStyle('d', true); - break; - } - case 'a': { - $this->HREF = $attr['href']; - break; - } - case 'img': { - if(isset($attr['src'])) { - // replace relative path with real server path - if ($attr['src'][0] == '/') { - $attr['src'] = $_SERVER['DOCUMENT_ROOT'].$attr['src']; - } - $attr['src'] = str_replace(K_PATH_URL, K_PATH_MAIN, $attr['src']); - if(!isset($attr['width'])) { - $attr['width'] = 0; - } - if(!isset($attr['height'])) { - $attr['height'] = 0; - } - if(!isset($attr['align'])) { - $align = 'N'; - } else { - switch($attr['align']) { - case 'top':{ - $align = 'T'; - break; - } - case 'middle':{ - $align = 'M'; - break; - } - case 'bottom':{ - $align = 'B'; - break; - } - default:{ - $align = 'N'; - break; - } - } - } - $this->Image($attr['src'], $this->GetX(),$this->GetY(), $this->pixelsToUnits($attr['width']), $this->pixelsToUnits($attr['height']), '', '', $align); - - } - break; - } - case 'dl': - case 'ul': { - $this->listordered = false; - $this->listcount = 0; - break; - } - case 'ol': { - $this->listordered = true; - $this->listcount = 0; - break; - } - case 'dd': - case 'li': { - $this->Ln(); - if($tag == 'li') { - if ($this->listordered) { - if (isset($attr['value'])) { - $this->listcount = intval($attr['value']); - } - $this->lispacer = " ".(++$this->listcount).". "; - } else { - //unordered list simbol - $this->lispacer = " - "; - } - } else { - $this->lispacer = " "; - } - $rtldir = $this->tmprtl; - $this->tmprtl = false; - $this->Write($this->lasth, $this->lispacer, '', $fill, '', false, 0); - $this->tmprtl = $rtldir; - break; - } - case 'dt': { - $this->Ln(); - break; - } - case 'blockquote': - case 'br': { - $this->Ln(); - if(strlen($this->lispacer) > 0) { - if ($this->rtl) { - $this->x -= $this->GetStringWidth($this->lispacer); - } else { - $this->x += $this->GetStringWidth($this->lispacer); - } - } - break; - } - case 'p': { - $this->Ln(); - $this->Ln(); - break; - } - case 'sup': { - $currentFontSize = $this->FontSize; - $this->tempfontsize = $this->FontSizePt; - $this->SetFontSize($this->FontSizePt * K_SMALL_RATIO); - $this->SetXY($this->GetX(), $this->GetY() - (($currentFontSize - $this->FontSize)*(K_SMALL_RATIO))); - break; - } - case 'sub': { - $currentFontSize = $this->FontSize; - $this->tempfontsize = $this->FontSizePt; - $this->SetFontSize($this->FontSizePt * K_SMALL_RATIO); - $this->SetXY($this->GetX(), $this->GetY() + (($currentFontSize - $this->FontSize)*(K_SMALL_RATIO))); - break; - } - case 'small': { - $currentFontSize = $this->FontSize; - $this->tempfontsize = $this->FontSizePt; - $this->SetFontSize($this->FontSizePt * K_SMALL_RATIO); - $this->SetXY($this->GetX(), $this->GetY() + (($currentFontSize - $this->FontSize)/3)); - break; - } - case 'font': { - if (isset($attr['face'])) { - $fontslist = split(",", strtolower($attr['face'])); - foreach($fontslist as $font) { - $font = trim($font); - if(in_array($font, $this->fontlist)){ - $this->SetFont($font); - $this->issetfont = true; - break; - } - } - } - if (isset($attr['size'])) { - $headsize = intval($attr['size']); - } else { - $headsize = 0; - } - $currentFontSize = $this->FontSize; - $this->tempfontsize = $this->FontSizePt; - $this->SetFontSize($this->FontSizePt + $headsize); - $this->lasth = $this->FontSize * $this->cell_height_ratio; - break; - } - case 'h1': - case 'h2': - case 'h3': - case 'h4': - case 'h5': - case 'h6': { - $headsize = (4 - substr($tag, 1)) * 2; - $currentFontSize = $this->FontSize; - $this->tempfontsize = $this->FontSizePt; - $this->SetFontSize($this->FontSizePt + $headsize); - $this->setStyle('b', true); - $this->lasth = $this->FontSize * $this->cell_height_ratio; - break; - } - } - } - - /** - * Process closing tags. - * @param string $tag tag name (in uppercase) - * @access protected - */ - function closedHTMLTagHandler($tag) { - // restore foreground color - $nfg = count($this->fgcolor); - if ($nfg > 1) { - array_pop($this->fgcolor); - $this->SetTextColor($this->fgcolor[$nfg-2]['R'], $this->fgcolor[$nfg-2]['G'], $this->fgcolor[$nfg-2]['B'], false); - } - - //restore background color - $nbg = count($this->bgcolor); - if ($nbg > 1) { - array_pop($this->bgcolor); - if (end($this->bgtag) == ($nbg-1)) { - array_pop($this->bgtag); - } - $this->SetFillColor($this->bgcolor[$nbg-2]['R'], $this->bgcolor[$nbg-2]['G'], $this->bgcolor[$nbg-2]['B'], false); - } - - //Closing tag - switch($tag) { - case 'td': - case 'th': { - $this->tdbegin = false; - $this->tdwidth = 0; - $this->tdheight = 0; - if($this->rtl) { - $this->tdalign = "R"; - } else { - $this->tdalign = "L"; - } - break; - } - case 'tr': { - $this->Ln(); - break; - } - case 'table': { - $this->tableborder=0; - break; - } - case 'strong': { - $this->setStyle('b', false); - break; - } - case 'em': { - $this->setStyle('i', false); - break; - } - case 'b': - case 'i': - case 'u': { - $this->setStyle($tag, false); - break; - } - case 'del': { - $this->setStyle('d', false); - break; - } - case 'a': { - $this->HREF = ''; - break; - } - case 'sup': { - $currentFontSize = $this->FontSize; - $this->SetFontSize($this->tempfontsize); - $this->tempfontsize = $this->FontSizePt; - $this->SetXY($this->GetX(), $this->GetY() - (($currentFontSize - $this->FontSize)*(K_SMALL_RATIO))); - break; - } - case 'sub': { - $currentFontSize = $this->FontSize; - $this->SetFontSize($this->tempfontsize); - $this->tempfontsize = $this->FontSizePt; - $this->SetXY($this->GetX(), $this->GetY() + (($currentFontSize - $this->FontSize)*(K_SMALL_RATIO))); - break; - } - case 'small': { - $currentFontSize = $this->FontSize; - $this->SetFontSize($this->tempfontsize); - $this->tempfontsize = $this->FontSizePt; - $this->SetXY($this->GetX(), $this->GetY() - (($this->FontSize - $currentFontSize)/3)); - break; - } - case 'font': { - if ($this->issetfont) { - $this->FontFamily = $this->prevFontFamily; - $this->FontStyle = $this->prevFontStyle; - $this->SetFont($this->FontFamily); - $this->issetfont = false; - } - $currentFontSize = $this->FontSize; - $this->SetFontSize($this->tempfontsize); - $this->tempfontsize = $this->FontSizePt; - $this->lasth = $this->FontSize * $this->cell_height_ratio; - break; - } - case 'p': { - $this->Ln(); - $this->Ln(); - break; - } - case 'dl': - case 'ul': - case 'ol': { - $this->Ln(); - $this->Ln(); - break; - } - case 'dd': - case 'li': { - $this->lispacer = ""; - break; - } - case 'h1': - case 'h2': - case 'h3': - case 'h4': - case 'h5': - case 'h6': { - $currentFontSize = $this->FontSize; - $this->SetFontSize($this->tempfontsize); - $this->tempfontsize = $this->FontSizePt; - $this->setStyle('b', false); - $this->Ln(); - $this->lasth = $this->FontSize * $this->cell_height_ratio; - break; - } - default : { - break; - } - } - $this->tmprtl = false; - } - - /** - * Sets font style. - * @param string $tag tag name in lowercase. Supported tags are:
        - *
      • b : bold text
      • - *
      • i : italic
      • - *
      • u : underlined
      • - *
      • lt : line-through
      - * @param boolean $enable - * @access protected - */ - function setStyle($tag, $enable) { - //Modify style and select corresponding font - $this->$tag += ($enable ? 1 : -1); - $style=''; - foreach(array('b', 'i', 'u', 'd') as $s) { - if($this->$s > 0) { - $style .= $s; - } - } - $this->SetFont('', $style); - } - - /** - * Output anchor link. - * @param string $url link URL - * @param string $name link name - * @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0. - * @access public - */ - function addHtmlLink($url, $name, $fill=0) { - //Put a hyperlink - $prevcolor = end($this->fgcolor); - $this->SetTextColor(0, 0, 255, false); - $this->setStyle('u', true); - $this->Write($this->lasth, $name, $url, $fill, '', false, 0); - $this->setStyle('u', false); - $this->SetTextColor($prevcolor['R'], $prevcolor['G'], $prevcolor['B'], false); - } - - /** - * Returns an associative array (keys: R,G,B) from - * an html color name or a six-digit or three-digit - * hexadecimal color representation (i.e. #3FE5AA or #7FF). - * @param string $color html color - * @return array - * @access protected - */ - function convertHTMLColorToDec($color = "#000000") { - // set default color to be returned in case of error - $returncolor = array ('R' => 0, 'G' => 0, 'B' => 0); - if(empty($color)) { - return $returncolor; - } - if (substr($color, 0, 1) != "#") { - // decode color name - require_once(dirname(__FILE__).'/htmlcolors.php'); - if (isset($webcolor[strtolower($color)])) { - $color_code = $webcolor[strtolower($color)]; - } else { - return $returncolor; - } - } else { - $color_code = substr($color, 1); - } - switch (strlen($color_code)) { - case 3: { - // three-digit hexadecimal representation - $r = substr($color_code, 0, 1); - $g = substr($color_code, 1, 1); - $b = substr($color_code, 2, 1); - $returncolor['R'] = hexdec($r.$r); - $returncolor['G'] = hexdec($g.$g); - $returncolor['B'] = hexdec($b.$b); - break; - } - case 6: { - // six-digit hexadecimal representation - $returncolor['R'] = hexdec(substr($color_code, 0, 2)); - $returncolor['G'] = hexdec(substr($color_code, 2, 2)); - $returncolor['B'] = hexdec(substr($color_code, 4, 2)); - break; - } - } - return $returncolor; - } - - /** - * Converts pixels to Units. - * @param int $px pixels - * @return float millimeters - * @access public - */ - function pixelsToUnits($px){ - return $px / $this->k; - } - - /** - * Reverse function for htmlentities. - * Convert entities in UTF-8. - * - * @param $text_to_convert Text to convert. - * @return string converted - */ - function unhtmlentities($text_to_convert) { - if (!$this->isunicode) { - return html_entity_decode($text_to_convert); - } - require_once(dirname(__FILE__).'/html_entity_decode_php4.php'); - return html_entity_decode_php4($text_to_convert); - } - - // ENCRYPTION METHODS ---------------------------------- - // SINCE 2.0.000 (2008-01-02) - /** - * Compute encryption key depending on object number where the encrypted data is stored - * @param int $n object number - * @since 2.0.000 (2008-01-02) - */ - function _objectkey($n) { - return substr($this->_md5_16($this->encryption_key.pack('VXxx',$n)),0,10); - } - - /** - * Put encryption on PDF document - * @since 2.0.000 (2008-01-02) - */ - function _putencryption() { - $this->_out('/Filter /Standard'); - $this->_out('/V 1'); - $this->_out('/R 2'); - $this->_out('/O ('.$this->_escape($this->Ovalue).')'); - $this->_out('/U ('.$this->_escape($this->Uvalue).')'); - $this->_out('/P '.$this->Pvalue); - } - - /** - * Returns the input text exrypted using RC4 algorithm and the specified key. - * RC4 is the standard encryption algorithm used in PDF format - * @param string $key encryption key - * @param String $text input text to be encrypted - * @return String encrypted text - * @since 2.0.000 (2008-01-02) - * @author Klemen Vodopivec - */ - function _RC4($key, $text) { - if ($this->last_rc4_key != $key) { - $k = str_repeat($key, 256/strlen($key)+1); - $rc4 = range(0,255); - $j = 0; - for ($i=0; $i<256; $i++) { - $t = $rc4[$i]; - $j = ($j + $t + ord($k{$i})) % 256; - $rc4[$i] = $rc4[$j]; - $rc4[$j] = $t; - } - $this->last_rc4_key = $key; - $this->last_rc4_key_c = $rc4; - } else { - $rc4 = $this->last_rc4_key_c; - } - $len = strlen($text); - $a = 0; - $b = 0; - $out = ''; - for ($i=0; $i<$len; $i++) { - $a = ($a+1)%256; - $t= $rc4[$a]; - $b = ($b+$t)%256; - $rc4[$a] = $rc4[$b]; - $rc4[$b] = $t; - $k = $rc4[($rc4[$a]+$rc4[$b])%256]; - $out.=chr(ord($text{$i}) ^ $k); - } - return $out; - } - - /** - * Encrypts a string using MD5 and returns it's value as a binary string. - * @param string $str input string - * @return String MD5 encrypted binary string - * @since 2.0.000 (2008-01-02) - * @author Klemen Vodopivec - */ - function _md5_16($str) { - return pack('H*',md5($str)); - } - - /** - * Compute O value (used for RC4 encryption) - * @param String $user_pass user password - * @param String $owner_pass user password - * @return String O value - * @since 2.0.000 (2008-01-02) - * @author Klemen Vodopivec - */ - function _Ovalue($user_pass, $owner_pass) { - $tmp = $this->_md5_16($owner_pass); - $owner_RC4_key = substr($tmp,0,5); - return $this->_RC4($owner_RC4_key, $user_pass); - } - - /** - * Compute U value (used for RC4 encryption) - * @return String U value - * @since 2.0.000 (2008-01-02) - * @author Klemen Vodopivec - */ - function _Uvalue() { - return $this->_RC4($this->encryption_key, $this->padding); - } - - /** - * Compute encryption key - * @param String $user_pass user password - * @param String $owner_pass user password - * @param String $protection protection type - * @since 2.0.000 (2008-01-02) - * @author Klemen Vodopivec - */ - function _generateencryptionkey($user_pass, $owner_pass, $protection) { - // Pad passwords - $user_pass = substr($user_pass.$this->padding,0,32); - $owner_pass = substr($owner_pass.$this->padding,0,32); - // Compute O value - $this->Ovalue = $this->_Ovalue($user_pass,$owner_pass); - // Compute encyption key - $tmp = $this->_md5_16($user_pass.$this->Ovalue.chr($protection)."\xFF\xFF\xFF"); - $this->encryption_key = substr($tmp,0,5); - // Compute U value - $this->Uvalue = $this->_Uvalue(); - // Compute P value - $this->Pvalue = -(($protection^255)+1); - } - - /** - * Set document protection - * The permission array is composed of values taken from the following ones: - * - copy: copy text and images to the clipboard - * - print: print the document - * - modify: modify it (except for annotations and forms) - * - annot-forms: add annotations and forms - * Remark: the protection against modification is for people who have the full Acrobat product. - * If you don't set any password, the document will open as usual. If you set a user password, the PDF viewer will ask for it before displaying the document. The master password, if different from the user one, can be used to get full access. - * Note: protecting a document requires to encrypt it, which increases the processing time a lot. This can cause a PHP time-out in some cases, especially if the document contains images or fonts. - * @param Array $permissions the set of permissions. Empty by default (only viewing is allowed). (print, modify, copy, annot-forms) - * @param String $user_pass user password. Empty by default. - * @param String $owner_pass owner password. If not specified, a random value is used. - * @since 2.0.000 (2008-01-02) - * @author Klemen Vodopivec - */ - function SetProtection($permissions=array(),$user_pass='',$owner_pass=null) { - $options = array('print' => 4, 'modify' => 8, 'copy' => 16, 'annot-forms' => 32); - $protection = 192; - foreach($permissions as $permission) { - if (!isset($options[$permission])) { - $this->Error('Incorrect permission: '.$permission); - } - $protection += $options[$permission]; - } - if ($owner_pass === null) { - $owner_pass = uniqid(rand()); - } - $this->encrypted = true; - $this->_generateencryptionkey($user_pass, $owner_pass, $protection); - } - - // END OF ENCRYPTION FUNCTIONS ------------------------- - - // START TRANSFORMATIONS SECTION ----------------------- - // authors: Moritz Wagner, Andreas Wurmser, Nicola Asuni - - /** - * Starts a 2D tranformation saving current graphic state. - * This function must be called before scaling, mirroring, translation, rotation and skewing. - * Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior. - * @since 2.1.000 (2008-01-07) - * @see StartTransform(), StopTransform() - */ - function StartTransform() { - $this->_out('q'); - } - - /** - * Stops a 2D tranformation restoring previous graphic state. - * This function must be called after scaling, mirroring, translation, rotation and skewing. - * Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior. - * @since 2.1.000 (2008-01-07) - * @see StartTransform(), StopTransform() - */ - function StopTransform() { - $this->_out('Q'); - } - /** - * Horizontal Scaling. - * @param float $s_x scaling factor for width as percent. 0 is not allowed. - * @param int $x abscissa of the scaling center. Default is current x position - * @param int $y ordinate of the scaling center. Default is current y position - * @since 2.1.000 (2008-01-07) - * @see StartTransform(), StopTransform() - */ - function ScaleX($s_x, $x='', $y=''){ - $this->Scale($s_x, 100, $x, $y); - } - - /** - * Vertical Scaling. - * @param float $s_y scaling factor for height as percent. 0 is not allowed. - * @param int $x abscissa of the scaling center. Default is current x position - * @param int $y ordinate of the scaling center. Default is current y position - * @since 2.1.000 (2008-01-07) - * @see StartTransform(), StopTransform() - */ - function ScaleY($s_y, $x='', $y=''){ - $this->Scale(100, $s_y, $x, $y); - } - - /** - * Vertical and horizontal proportional Scaling. - * @param float $s scaling factor for width and height as percent. 0 is not allowed. - * @param int $x abscissa of the scaling center. Default is current x position - * @param int $y ordinate of the scaling center. Default is current y position - * @since 2.1.000 (2008-01-07) - * @see StartTransform(), StopTransform() - */ - function ScaleXY($s, $x='', $y=''){ - $this->Scale($s, $s, $x, $y); - } - - /** - * Vertical and horizontal non-proportional Scaling. - * @param float $s_x scaling factor for width as percent. 0 is not allowed. - * @param float $s_y scaling factor for height as percent. 0 is not allowed. - * @param int $x abscissa of the scaling center. Default is current x position - * @param int $y ordinate of the scaling center. Default is current y position - * @since 2.1.000 (2008-01-07) - * @see StartTransform(), StopTransform() - */ - function Scale($s_x, $s_y, $x='', $y=''){ - if($x === '') { - $x=$this->x; - } - if($y === '') { - $y=$this->y; - } - if($this->rtl) { - $x = $this->w - $x; - } - if($s_x == 0 OR $s_y == 0) - $this->Error('Please use values unequal to zero for Scaling'); - $y=($this->h-$y)*$this->k; - $x*=$this->k; - //calculate elements of transformation matrix - $s_x/=100; - $s_y/=100; - $tm[0]=$s_x; - $tm[1]=0; - $tm[2]=0; - $tm[3]=$s_y; - $tm[4]=$x*(1-$s_x); - $tm[5]=$y*(1-$s_y); - //scale the coordinate system - $this->Transform($tm); - } - - /** - * Horizontal Mirroring. - * @param int $x abscissa of the point. Default is current x position - * @since 2.1.000 (2008-01-07) - * @see StartTransform(), StopTransform() - */ - function MirrorH($x=''){ - $this->Scale(-100, 100, $x); - } - - /** - * Verical Mirroring. - * @param int $y ordinate of the point. Default is current y position - * @since 2.1.000 (2008-01-07) - * @see StartTransform(), StopTransform() - */ - function MirrorV($y=''){ - $this->Scale(100, -100, '', $y); - } - - /** - * Point reflection mirroring. - * @param int $x abscissa of the point. Default is current x position - * @param int $y ordinate of the point. Default is current y position - * @since 2.1.000 (2008-01-07) - * @see StartTransform(), StopTransform() - */ - function MirrorP($x='',$y=''){ - $this->Scale(-100, -100, $x, $y); - } - - /** - * Reflection against a straight line through point (x, y) with the gradient angle (angle). - * @param float $angle gradient angle of the straight line. Default is 0 (horizontal line). - * @param int $x abscissa of the point. Default is current x position - * @param int $y ordinate of the point. Default is current y position - * @since 2.1.000 (2008-01-07) - * @see StartTransform(), StopTransform() - */ - function MirrorL($angle=0, $x='',$y=''){ - $this->Scale(-100, 100, $x, $y); - $this->Rotate(-2*($angle-90),$x,$y); - } - - /** - * Translate graphic object horizontally. - * @param int $t_x movement to the right - * @since 2.1.000 (2008-01-07) - * @see StartTransform(), StopTransform() - */ - function TranslateX($t_x){ - $this->Translate($t_x, 0); - } - - /** - * Translate graphic object vertically. - * @param int $t_y movement to the bottom - * @since 2.1.000 (2008-01-07) - * @see StartTransform(), StopTransform() - */ - function TranslateY($t_y){ - $this->Translate(0, $t_y); - } - - /** - * Translate graphic object horizontally and vertically. - * @param int $t_x movement to the right - * @param int $t_y movement to the bottom - * @since 2.1.000 (2008-01-07) - * @see StartTransform(), StopTransform() - */ - function Translate($t_x, $t_y){ - if($this->rtl) { - $t_x = -$t_x; - } - //calculate elements of transformation matrix - $tm[0]=1; - $tm[1]=0; - $tm[2]=0; - $tm[3]=1; - $tm[4]=$t_x*$this->k; - $tm[5]=-$t_y*$this->k; - //translate the coordinate system - $this->Transform($tm); - } - - /** - * Rotate object. - * @param float $angle angle in degrees for counter-clockwise rotation - * @param int $x abscissa of the rotation center. Default is current x position - * @param int $y ordinate of the rotation center. Default is current y position - * @since 2.1.000 (2008-01-07) - * @see StartTransform(), StopTransform() - */ - function Rotate($angle, $x='', $y=''){ - if($x === '') { - $x=$this->x; - } - if($y === '') { - $y=$this->y; - } - if($this->rtl) { - $x = $this->w - $x; - $angle = -$angle; - } - $y=($this->h-$y)*$this->k; - $x*=$this->k; - //calculate elements of transformation matrix - $tm[0]=cos(deg2rad($angle)); - $tm[1]=sin(deg2rad($angle)); - $tm[2]=-$tm[1]; - $tm[3]=$tm[0]; - $tm[4]=$x+$tm[1]*$y-$tm[0]*$x; - $tm[5]=$y-$tm[0]*$y-$tm[1]*$x; - //rotate the coordinate system around ($x,$y) - $this->Transform($tm); - } - - /** - * Skew horizontally. - * @param float $angle_x angle in degrees between -90 (skew to the left) and 90 (skew to the right) - * @param int $x abscissa of the skewing center. default is current x position - * @param int $y ordinate of the skewing center. default is current y position - * @since 2.1.000 (2008-01-07) - * @see StartTransform(), StopTransform() - */ - function SkewX($angle_x, $x='', $y=''){ - $this->Skew($angle_x, 0, $x, $y); - } - - /** - * Skew vertically. - * @param float $angle_y angle in degrees between -90 (skew to the bottom) and 90 (skew to the top) - * @param int $x abscissa of the skewing center. default is current x position - * @param int $y ordinate of the skewing center. default is current y position - * @since 2.1.000 (2008-01-07) - * @see StartTransform(), StopTransform() - */ - function SkewY($angle_y, $x='', $y=''){ - $this->Skew(0, $angle_y, $x, $y); - } - - /** - * Skew. - * @param float $angle_x angle in degrees between -90 (skew to the left) and 90 (skew to the right) - * @param float $angle_y angle in degrees between -90 (skew to the bottom) and 90 (skew to the top) - * @param int $x abscissa of the skewing center. default is current x position - * @param int $y ordinate of the skewing center. default is current y position - * @since 2.1.000 (2008-01-07) - * @see StartTransform(), StopTransform() - */ - function Skew($angle_x, $angle_y, $x='', $y=''){ - if($x === '') { - $x=$this->x; - } - if($y === '') { - $y=$this->y; - } - if($this->rtl) { - $x = $this->w - $x; - $angle_x = -$angle_x; - } - if($angle_x <= -90 OR $angle_x >= 90 OR $angle_y <= -90 OR $angle_y >= 90) - $this->Error('Please use values between -90� and 90� for skewing'); - $x*=$this->k; - $y=($this->h-$y)*$this->k; - //calculate elements of transformation matrix - $tm[0]=1; - $tm[1]=tan(deg2rad($angle_y)); - $tm[2]=tan(deg2rad($angle_x)); - $tm[3]=1; - $tm[4]=-$tm[2]*$y; - $tm[5]=-$tm[1]*$x; - //skew the coordinate system - $this->Transform($tm); - } - - /** - * Apply graphic transformations. - * @since 2.1.000 (2008-01-07) - * @see StartTransform(), StopTransform() - */ - function Transform($tm){ - $this->_out(sprintf('%.3f %.3f %.3f %.3f %.3f %.3f cm', $tm[0],$tm[1],$tm[2],$tm[3],$tm[4],$tm[5])); - } - - // END TRANSFORMATIONS SECTION ------------------------- - - - // START GRAPHIC FUNCTIONS SECTION --------------------- - // The following section is based on the code provided by David Hernandez Sanz - - /** - * Defines the line width. By default, the value equals 0.2 mm. The method can be called before the first page is created and the value is retained from page to page. - * @param float $width The width. - * @since 1.0 - * @see Line(), Rect(), Cell(), MultiCell() - */ - function SetLineWidth($width) { - //Set line width - $this->LineWidth = $width; - if($this->page>0) { - $this->_out(sprintf('%.2f w',$width*$this->k)); - } - } - - /** - * Returns the current the line width. - * @return int Line width - * @since 2.1.000 (2008-01-07) - * @see Line(), SetLineWidth() - */ - function GetLineWidth() { - return $this->LineWidth; - } - - /** - * Set line style. - * - * @param array $style Line style. Array with keys among the following: - *
        - *
      • width (float): Width of the line in user units.
      • - *
      • cap (string): Type of cap to put on the line. Possible values are: - * butt, round, square. The difference between "square" and "butt" is that - * "square" projects a flat end past the end of the line.
      • - *
      • join (string): Type of join. Possible values are: miter, round, - * bevel.
      • - *
      • dash (mixed): Dash pattern. Is 0 (without dash) or string with - * series of length values, which are the lengths of the on and off dashes. - * For example: "2" represents 2 on, 2 off, 2 on, 2 off, ...; "2,1" is 2 on, - * 1 off, 2 on, 1 off, ...
      • - *
      • phase (integer): Modifier on the dash pattern which is used to shift - * the point at which the pattern starts.
      • - *
      • color (array): Draw color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K).
      • - *
      - * @access public - * @since 2.1.000 (2008-01-08) - */ - function SetLineStyle($style) { - extract($style); - if (isset($width)) { - $width_prev = $this->LineWidth; - $this->SetLineWidth($width); - $this->LineWidth = $width_prev; - } - if (isset($cap)) { - $ca = array("butt" => 0, "round"=> 1, "square" => 2); - if (isset($ca[$cap])) { - $this->_out($ca[$cap] . " J"); - } - } - if (isset($join)) { - $ja = array("miter" => 0, "round" => 1, "bevel" => 2); - if (isset($ja[$join])) { - $this->_out($ja[$join] . " j"); - } - } - if (isset($dash)) { - $dash_string = ""; - if ($dash) { - if (ereg("^.+,", $dash)) { - $tab = explode(",", $dash); - } else { - $tab = array($dash); - } - $dash_string = ""; - foreach ($tab as $i => $v) { - if ($i) { - $dash_string .= " "; - } - $dash_string .= sprintf("%.2f", $v); - } - } - if (!isset($phase) OR !$dash) { - $phase = 0; - } - $this->_out(sprintf("[%s] %.2f d", $dash_string, $phase)); - } - if (isset($color)) { - list($r, $g, $b, $k) = $color; - $this->SetDrawColor($r, $g, $b, $k); - } - } - - /* - * Set a draw point. - * @param float $x Abscissa of point. - * @param float $y Ordinate of point. - * @access protected - * @since 2.1.000 (2008-01-08) - */ - function _outPoint($x, $y) { - if($this->rtl) { - $x = $this->w - $x; - } - $this->_out(sprintf("%.2f %.2f m", $x * $this->k, ($this->h - $y) * $this->k)); - } - - /* - * Draws a line from last draw point. - * @param float $x Abscissa of end point. - * @param float $y Ordinate of end point. - * @access protected - * @since 2.1.000 (2008-01-08) - */ - function _outLine($x, $y) { - if($this->rtl) { - $x = $this->w - $x; - } - $this->_out(sprintf("%.2f %.2f l", $x * $this->k, ($this->h - $y) * $this->k)); - } - - /** - * Draws a rectangle. - * @param float $x Abscissa of upper-left corner (or upper-right corner for RTL language). - * @param float $y Ordinate of upper-left corner (or upper-right corner for RTL language). - * @param float $w Width. - * @param float $h Height. - * @param string $op options - * @access protected - * @since 2.1.000 (2008-01-08) - */ - function _outRect($x, $y, $w, $h, $op) { - if($this->rtl) { - $x = $this->w - $x - $w; - } - $this->_out(sprintf('%.2f %.2f %.2f %.2f re %s',$x*$this->k,($this->h-$y)*$this->k,$w*$this->k,-$h*$this->k,$op)); - } - - /* - * Draws a Bezier curve from last draw point. - * The Bezier curve is a tangent to the line between the control points at either end of the curve. - * @param float $x1 Abscissa of control point 1. - * @param float $y1 Ordinate of control point 1. - * @param float $x2 Abscissa of control point 2. - * @param float $y2 Ordinate of control point 2. - * @param float $x3 Abscissa of end point. - * @param float $y3 Ordinate of end point. - * @access protected - * @since 2.1.000 (2008-01-08) - */ - function _outCurve($x1, $y1, $x2, $y2, $x3, $y3) { - if($this->rtl) { - $x1 = $this->w - $x1; - $x2 = $this->w - $x2; - $x3 = $this->w - $x3; - } - $this->_out(sprintf("%.2f %.2f %.2f %.2f %.2f %.2f c", $x1 * $this->k, ($this->h - $y1) * $this->k, $x2 * $this->k, ($this->h - $y2) * $this->k, $x3 * $this->k, ($this->h - $y3) * $this->k)); - } - - /** - * Draws a line between two points. - * @param float $x1 Abscissa of first point. - * @param float $y1 Ordinate of first point. - * @param float $x2 Abscissa of second point. - * @param float $y2 Ordinate of second point. - * @param array $style Line style. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array). - * @access public - * @since 1.0 - * @see SetLineWidth(), SetDrawColor(), SetLineStyle() - */ - function Line($x1, $y1, $x2, $y2, $style = array()) { - if ($style) { - $this->SetLineStyle($style); - } - $this->_outPoint($x1, $y1); - $this->_outLine($x2, $y2); - $this->_out(" S"); - } - - /** - * Draws a rectangle. - * @param float $x Abscissa of upper-left corner (or upper-right corner for RTL language). - * @param float $y Ordinate of upper-left corner (or upper-right corner for RTL language). - * @param float $w Width. - * @param float $h Height. - * @param string $style Style of rendering. Possible values are: - *
        - *
      • D or empty string: Draw (default).
      • - *
      • F: Fill.
      • - *
      • DF or FD: Draw and fill.
      • - *
      - * @param array $border_style Border style of rectangle. Array with keys among the following: - *
        - *
      • all: Line style of all borders. Array like for {@link SetLineStyle SetLineStyle}.
      • - *
      • L, T, R, B or combinations: Line style of left, top, right or bottom border. Array like for {@link SetLineStyle SetLineStyle}.
      • - *
      - * If a key is not present or is null, not draws the border. Default value: default line style (empty array). - * @param array $fill_color Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array). - * @access public - * @since 1.0 - * @see SetLineStyle() - */ - function Rect($x, $y, $w, $h, $style='', $border_style = array(), $fill_color = array()) { - if (!(false === strpos($style, "F")) AND $fill_color) { - list($r, $g, $b, $k) = $fill_color; - $this->SetFillColor($r, $g, $b, false, $k); - } - switch ($style) { - case "F": { - $op='f'; - $border_style = array(); - $this->_outRect($x, $y, $w, $h, $op); - break; - } - case "DF": - case "FD": { - if (!$border_style OR isset($border_style["all"])) { - $op='B'; - if (isset($border_style["all"])) { - $this->SetLineStyle($border_style["all"]); - $border_style = array(); - } - } else { - $op='f'; - } - $this->_outRect($x, $y, $w, $h, $op); - break; - } - default: { - $op='S'; - if (!$border_style OR isset($border_style["all"])) { - if (isset($border_style["all"]) && $border_style["all"]) { - $this->SetLineStyle($border_style["all"]); - $border_style = array(); - } - $this->_outRect($x, $y, $w, $h, $op); - } - break; - } - } - if ($border_style) { - $border_style2 = array(); - foreach ($border_style as $line => $value) { - $lenght = strlen($line); - for ($i = 0; $i < $lenght; $i++) { - $border_style2[$line[$i]] = $value; - } - } - $border_style = $border_style2; - if (isset($border_style["L"]) && $border_style["L"]) { - $this->Line($x, $y, $x, $y + $h, $border_style["L"]); - } - if (isset($border_style["T"]) && $border_style["T"]) { - $this->Line($x, $y, $x + $w, $y, $border_style["T"]); - } - if (isset($border_style["R"]) && $border_style["R"]) { - $this->Line($x + $w, $y, $x + $w, $y + $h, $border_style["R"]); - } - if (isset($border_style["B"]) && $border_style["B"]) { - $this->Line($x, $y + $h, $x + $w, $y + $h, $border_style["B"]); - } - } - } - - - /** - * Draws a Bezier curve. - * The Bezier curve is a tangent to the line between the control points at - * either end of the curve. - * @param float $x0 Abscissa of start point. - * @param float $y0 Ordinate of start point. - * @param float $x1 Abscissa of control point 1. - * @param float $y1 Ordinate of control point 1. - * @param float $x2 Abscissa of control point 2. - * @param float $y2 Ordinate of control point 2. - * @param float $x3 Abscissa of end point. - * @param float $y3 Ordinate of end point. - * @param string $style Style of rendering. Possible values are: - *
        - *
      • D or empty string: Draw (default).
      • - *
      • F: Fill.
      • - *
      • DF or FD: Draw and fill.
      • - *
      - * @param array $line_style Line style of curve. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array). - * @param array $fill_color Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array). - * @access public - * @see SetLineStyle() - * @since 2.1.000 (2008-01-08) - */ - function Curve($x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3, $style = "", $line_style = array(), $fill_color = array()) { - if (!(false === strpos($style, "F")) AND $fill_color) { - list($r, $g, $b, $k) = $fill_color; - $this->SetFillColor($r, $g, $b, false, $k); - } - switch ($style) { - case "F": { - $op = "f"; - $line_style = array(); - break; - } - case "FD": - case "DF": { - $op = "B"; - break; - } - default: { - $op = "S"; - break; - } - } - if ($line_style) { - $this->SetLineStyle($line_style); - } - $this->_outPoint($x0, $y0); - $this->_outCurve($x1, $y1, $x2, $y2, $x3, $y3); - $this->_out($op); - } - - /** - * Draws a poly-Bezier curve. - * Each Bezier curve segment is a tangent to the line between the control points at - * either end of the curve. - * @param float $x0 Abscissa of start point. - * @param float $y0 Ordinate of start point. - * @param float $segments An array of bezier descriptions. Format: array(x1, y1, x2, y2, x3, y3). - * @param string $style Style of rendering. Possible values are: - *
        - *
      • D or empty string: Draw (default).
      • - *
      • F: Fill.
      • - *
      • DF or FD: Draw and fill.
      • - *
      - * @param array $line_style Line style of curve. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array). - * @param array $fill_color Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array). - * @access public - * @see SetLineStyle() - * @since 3.0008 (2008-05-12) - */ - function Polycurve($x0, $y0, $segments, $style = "", $line_style = array(), $fill_color = array()) { - if (!(false === strpos($style, "F")) AND $fill_color) { - list($r, $g, $b, $k) = $fill_color; - $this->SetFillColor($r, $g, $b, false, $k); - } - switch ($style) { - case "F": { - $op = "f"; - $line_style = array(); - break; - } - case "FD": - case "DF": { - $op = "B"; - break; - } - default: { - $op = "S"; - break; - } - } - if ($line_style) { - $this->SetLineStyle($line_style); - } - $this->_outPoint($x0, $y0); - foreach ($segments as $segment) { - list($x1, $y1, $x2, $y2, $x3, $y3) = $segment; - $this->_outCurve($x1, $y1, $x2, $y2, $x3, $y3); - } - $this->_out($op); - } - - /** - * Draws an ellipse. - * An ellipse is formed from n Bezier curves. - * @param float $x0 Abscissa of center point. - * @param float $y0 Ordinate of center point. - * @param float $rx Horizontal radius. - * @param float $ry Vertical radius (if ry = 0 then is a circle, see {@link Circle Circle}). Default value: 0. - * @param float $angle: Angle oriented (anti-clockwise). Default value: 0. - * @param float $astart: Angle start of draw line. Default value: 0. - * @param float $afinish: Angle finish of draw line. Default value: 360. - * @param string $style Style of rendering. Possible values are: - *
        - *
      • D or empty string: Draw (default).
      • - *
      • F: Fill.
      • - *
      • DF or FD: Draw and fill.
      • - *
      • C: Draw close.
      • - *
      - * @param array $line_style Line style of ellipse. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array). - * @param array $fill_color Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array). - * @param integer $nc Number of curves used in ellipse. Default value: 8. - * @access public - * @since 2.1.000 (2008-01-08) - */ - function Ellipse($x0, $y0, $rx, $ry = 0, $angle = 0, $astart = 0, $afinish = 360, $style = "", $line_style = array(), $fill_color = array(), $nc = 8) { - if ($angle) { - $this->StartTransform(); - $this->Rotate($angle, $x0, $y0); - $this->Ellipse($x0, $y0, $rx, $ry, 0, $astart, $afinish, $style, $line_style, $fill_color, $nc); - $this->StopTransform(); - return; - } - if ($rx) { - if (!(false === strpos($style, "F")) AND $fill_color) { - list($r, $g, $b, $k) = $fill_color; - $this->SetFillColor($r, $g, $b, false, $k); - } - switch ($style) { - case "F": { - $op = "f"; - $line_style = array(); - break; - } - case "FD": - case "DF": { - $op = "B"; - break; - } - case "C": { - $op = "s"; // Small "s" signifies closing the path as well - break; - } - default: { - $op = "S"; - break; - } - } - if ($line_style) { - $this->SetLineStyle($line_style); - } - if (!$ry) { - $ry = $rx; - } - $rx *= $this->k; - $ry *= $this->k; - if ($nc < 2){ - $nc = 2; - } - $astart = deg2rad((float) $astart); - $afinish = deg2rad((float) $afinish); - $total_angle = $afinish - $astart; - $dt = $total_angle / $nc; - $dtm = $dt/3; - $x0 *= $this->k; - $y0 = ($this->h - $y0) * $this->k; - $t1 = $astart; - $a0 = $x0 + ($rx * cos($t1)); - $b0 = $y0 + ($ry * sin($t1)); - $c0 = -$rx * sin($t1); - $d0 = $ry * cos($t1); - $this->_outPoint($a0 / $this->k, $this->h - ($b0 / $this->k)); - for ($i = 1; $i <= $nc; $i++) { - // Draw this bit of the total curve - $t1 = ($i * $dt) + $astart; - $a1 = $x0 + ($rx * cos($t1)); - $b1 = $y0 + ($ry * sin($t1)); - $c1 = -$rx * sin($t1); - $d1 = $ry * cos($t1); - $this->_outCurve(($a0 + ($c0 * $dtm)) / $this->k, $this->h - (($b0 + ($d0 * $dtm)) / $this->k), ($a1 - ($c1 * $dtm)) / $this->k, $this->h - (($b1 - ($d1 * $dtm)) / $this->k), $a1 / $this->k, $this->h - ($b1 / $this->k)); - $a0 = $a1; - $b0 = $b1; - $c0 = $c1; - $d0 = $d1; - } - $this->_out($op); - } - } - - /** - * Draws a circle. - * A circle is formed from n Bezier curves. - * @param float $x0 Abscissa of center point. - * @param float $y0 Ordinate of center point. - * @param float $r Radius. - * @param float $astart: Angle start of draw line. Default value: 0. - * @param float $afinish: Angle finish of draw line. Default value: 360. - * @param string $style Style of rendering. Possible values are: - *
        - *
      • D or empty string: Draw (default).
      • - *
      • F: Fill.
      • - *
      • DF or FD: Draw and fill.
      • - *
      • C: Draw close.
      • - *
      - * @param array $line_style Line style of circle. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array). - * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array). - * @param integer $nc Number of curves used in circle. Default value: 8. - * @access public - * @since 2.1.000 (2008-01-08) - */ - function Circle($x0, $y0, $r, $astart = 0, $afinish = 360, $style = "", $line_style = array(), $fill_color = array(), $nc = 8) { - $this->Ellipse($x0, $y0, $r, 0, 0, $astart, $afinish, $style, $line_style, $fill_color, $nc); - } - - /** - * Draws a polygon. - * @param array $p Points 0 to ($np - 1). Array with values (x0, y0, x1, y1,..., x(np-1), y(np - 1)) - * @param string $style Style of rendering. Possible values are: - *
        - *
      • D or empty string: Draw (default).
      • - *
      • F: Fill.
      • - *
      • DF or FD: Draw and fill.
      • - *
      - * @param array $line_style Line style of polygon. Array with keys among the following: - *
        - *
      • all: Line style of all lines. Array like for {@link SetLineStyle SetLineStyle}.
      • - *
      • 0 to ($np - 1): Line style of each line. Array like for {@link SetLineStyle SetLineStyle}.
      • - *
      - * If a key is not present or is null, not draws the line. Default value is default line style (empty array). - * @param array $fill_color Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array). - * @access public - * @since 2.1.000 (2008-01-08) - */ - function Polygon($p, $style = "", $line_style = array(), $fill_color = array()) { - $np = count($p) / 2; - if (!(false === strpos($style, "F")) AND $fill_color) { - list($r, $g, $b, $k) = $fill_color; - $this->SetFillColor($r, $g, $b, false, $k); - } - switch ($style) { - case "F": { - $line_style = array(); - $op = "f"; - break; - } - case "FD": - case "DF": { - $op = "B"; - break; - } - default: { - $op = "S"; - break; - } - } - $draw = true; - if ($line_style) { - if (isset($line_style["all"])) { - $this->SetLineStyle($line_style["all"]); - } - else { // 0 .. (np - 1), op = {B, S} - $draw = false; - if ("B" == $op) { - $op = "f"; - $this->_outPoint($p[0], $p[1]); - for ($i = 2; $i < ($np * 2); $i = $i + 2) { - $this->_outLine($p[$i], $p[$i + 1]); - } - $this->_outLine($p[0], $p[1]); - $this->_out($op); - } - $p[$np * 2] = $p[0]; - $p[($np * 2) + 1] = $p[1]; - for ($i = 0; $i < $np; $i++) { - if (isset($line_style[$i])) { - $this->Line($p[$i * 2], $p[($i * 2) + 1], $p[($i * 2) + 2], $p[($i * 2) + 3], $line_style[$i]); - } - } - } - } - if ($draw) { - $this->_outPoint($p[0], $p[1]); - for ($i = 2; $i < ($np * 2); $i = $i + 2) { - $this->_outLine($p[$i], $p[$i + 1]); - } - $this->_outLine($p[0], $p[1]); - $this->_out($op); - } - } - - /** - * Draws a regular polygon. - * @param float $x0 Abscissa of center point. - * @param float $y0 Ordinate of center point. - * @param float $r: Radius of inscribed circle. - * @param integer $ns Number of sides. - * @param float $angle Angle oriented (anti-clockwise). Default value: 0. - * @param boolean $draw_circle Draw inscribed circle or not. Default value: false. - * @param string $style Style of rendering. Possible values are: - *
        - *
      • D or empty string: Draw (default).
      • - *
      • F: Fill.
      • - *
      • DF or FD: Draw and fill.
      • - *
      - * @param array $line_style Line style of polygon sides. Array with keys among the following: - *
        - *
      • all: Line style of all sides. Array like for {@link SetLineStyle SetLineStyle}.
      • - *
      • 0 to ($ns - 1): Line style of each side. Array like for {@link SetLineStyle SetLineStyle}.
      • - *
      - * If a key is not present or is null, not draws the side. Default value is default line style (empty array). - * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array). - * @param string $circle_style Style of rendering of inscribed circle (if draws). Possible values are: - *
        - *
      • D or empty string: Draw (default).
      • - *
      • F: Fill.
      • - *
      • DF or FD: Draw and fill.
      • - *
      - * @param array $circle_outLine_style Line style of inscribed circle (if draws). Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array). - * @param array $circle_fill_color Fill color of inscribed circle (if draws). Format: array(red, green, blue). Default value: default color (empty array). - * @access public - * @since 2.1.000 (2008-01-08) - */ - function RegularPolygon($x0, $y0, $r, $ns, $angle = 0, $draw_circle = false, $style = "", $line_style = array(), $fill_color = array(), $circle_style = "", $circle_outLine_style = array(), $circle_fill_color = array()) { - if (3 > $ns) { - $ns = 3; - } - if ($draw_circle) { - $this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color); - } - $p = array(); - for ($i = 0; $i < $ns; $i++) { - $a = $angle + ($i * 360 / $ns); - $a_rad = deg2rad((float) $a); - $p[] = $x0 + ($r * sin($a_rad)); - $p[] = $y0 + ($r * cos($a_rad)); - } - $this->Polygon($p, $style, $line_style, $fill_color); - } - - /** - * Draws a star polygon - * @param float $x0 Abscissa of center point. - * @param float $y0 Ordinate of center point. - * @param float $r Radius of inscribed circle. - * @param integer $nv Number of vertices. - * @param integer $ng Number of gap (if ($ng % $nv = 1) then is a regular polygon). - * @param float $angle: Angle oriented (anti-clockwise). Default value: 0. - * @param boolean $draw_circle: Draw inscribed circle or not. Default value is false. - * @param string $style Style of rendering. Possible values are: - *
        - *
      • D or empty string: Draw (default).
      • - *
      • F: Fill.
      • - *
      • DF or FD: Draw and fill.
      • - *
      - * @param array $line_style Line style of polygon sides. Array with keys among the following: - *
        - *
      • all: Line style of all sides. Array like for - * {@link SetLineStyle SetLineStyle}.
      • - *
      • 0 to (n - 1): Line style of each side. Array like for {@link SetLineStyle SetLineStyle}.
      • - *
      - * If a key is not present or is null, not draws the side. Default value is default line style (empty array). - * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array). - * @param string $circle_style Style of rendering of inscribed circle (if draws). Possible values are: - *
        - *
      • D or empty string: Draw (default).
      • - *
      • F: Fill.
      • - *
      • DF or FD: Draw and fill.
      • - *
      - * @param array $circle_outLine_style Line style of inscribed circle (if draws). Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array). - * @param array $circle_fill_color Fill color of inscribed circle (if draws). Format: array(red, green, blue). Default value: default color (empty array). - * @access public - * @since 2.1.000 (2008-01-08) - */ - function StarPolygon($x0, $y0, $r, $nv, $ng, $angle = 0, $draw_circle = false, $style = "", $line_style = array(), $fill_color = array(), $circle_style = "", $circle_outLine_style = array(), $circle_fill_color = array()) { - if (2 > $nv) { - $nv = 2; - } - if ($draw_circle) { - $this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color); - } - $p2 = array(); - $visited = array(); - for ($i = 0; $i < $nv; $i++) { - $a = $angle + ($i * 360 / $nv); - $a_rad = deg2rad((float) $a); - $p2[] = $x0 + ($r * sin($a_rad)); - $p2[] = $y0 + ($r * cos($a_rad)); - $visited[] = false; - } - $p = array(); - $i = 0; - do { - $p[] = $p2[$i * 2]; - $p[] = $p2[($i * 2) + 1]; - $visited[$i] = true; - $i += $ng; - $i %= $nv; - } while (!$visited[$i]); - $this->Polygon($p, $style, $line_style, $fill_color); - } - - /** - * Draws a rounded rectangle. - * @param float $x Abscissa of upper-left corner. - * @param float $y Ordinate of upper-left corner. - * @param float $w Width. - * @param float $h Height. - * @param float $r Radius of the rounded corners. - * @param string $round_corner Draws rounded corner or not. String with a 0 (not rounded i-corner) or 1 (rounded i-corner) in i-position. Positions are, in order and begin to 0: top left, top right, bottom right and bottom left. Default value: all rounded corner ("1111"). - * @param string $style Style of rendering. Possible values are: - *
        - *
      • D or empty string: Draw (default).
      • - *
      • F: Fill.
      • - *
      • DF or FD: Draw and fill.
      • - *
      - * @param array $border_style Border style of rectangle. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array). - * @param array $fill_color Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array). - * @access public - * @since 2.1.000 (2008-01-08) - */ - function RoundedRect($x, $y, $w, $h, $r, $round_corner = "1111", $style = "", $border_style = array(), $fill_color = array()) { - if ("0000" == $round_corner) { // Not rounded - $this->Rect($x, $y, $w, $h, $style, $border_style, $fill_color); - } else { // Rounded - if (!(false === strpos($style, "F")) AND $fill_color) { - list($rc, $g, $b, $k) = $fill_color; - $this->SetFillColor($rc, $g, $b, false, $k); - } - switch ($style) { - case "F": { - $border_style = array(); - $op = "f"; - break; - } - case "FD": - case "DF": { - $op = "B"; - break; - } - default: { - $op = "S"; - break; - } - } - if ($border_style) { - $this->SetLineStyle($border_style); - } - $MyArc = 4 / 3 * (sqrt(2) - 1); - $this->_outPoint($x + $r, $y); - $xc = $x + $w - $r; - $yc = $y + $r; - $this->_outLine($xc, $y); - if ($round_corner[0]) { - $this->_outCurve($xc + ($r * $MyArc), $yc - $r, $xc + $r, $yc - ($r * $MyArc), $xc + $r, $yc); - } else { - $this->_outLine($x + $w, $y); - } - $xc = $x + $w - $r; - $yc = $y + $h - $r; - $this->_outLine($x + $w, $yc); - if ($round_corner[1]) { - $this->_outCurve($xc + $r, $yc + ($r * $MyArc), $xc + ($r * $MyArc), $yc + $r, $xc, $yc + $r); - } else { - $this->_outLine($x + $w, $y + $h); - } - $xc = $x + $r; - $yc = $y + $h - $r; - $this->_outLine($xc, $y + $h); - if ($round_corner[2]) { - $this->_outCurve($xc - ($r * $MyArc), $yc + $r, $xc - $r, $yc + ($r * $MyArc), $xc - $r, $yc); - } else { - $this->_outLine($x, $y + $h); - } - $xc = $x + $r; - $yc = $y + $r; - $this->_outLine($x, $yc); - if ($round_corner[3]) { - $this->_outCurve($xc - $r, $yc - ($r * $MyArc), $xc - ($r * $MyArc), $yc - $r, $xc, $yc - $r); - } else { - $this->_outLine($x, $y); - $this->_outLine($x + $r, $y); - } - $this->_out($op); - } - } - - // END GRAPHIC FUNCTIONS SECTION ----------------------- - - // BIDIRECTIONAL TEXT SECTION -------------------------- - /** - * Reverse the RLT substrings using the Bidirectional Algorithm (http://unicode.org/reports/tr9/). - * @param string $str string to manipulate. - * @param bool $forcertl if 'R' forces RTL, if 'L' forces LTR - * @return string - * @author Nicola Asuni - * @since 2.1.000 (2008-01-08) - */ - function utf8StrRev($str, $setbom=false, $forcertl=false) { - return $this->arrUTF8ToUTF16BE($this->utf8Bidi($this->UTF8StringToArray($str), $forcertl), $setbom); - } - - /** - * Reverse the RLT substrings using the Bidirectional Algorithm (http://unicode.org/reports/tr9/). - * @param array $ta array of characters composing the string. - * @param bool $forcertl if 'R' forces RTL, if 'L' forces LTR - * @return string - * @author Nicola Asuni - * @since 2.4.000 (2008-03-06) - */ - function utf8Bidi($ta, $forcertl=false) { - global $unicode, $unicode_mirror, $unicode_arlet, $laa_array, $diacritics; - - require_once(dirname(__FILE__).'/unicode_data.php'); - - // paragraph embedding level - $pel = 0; - // max level - $maxlevel = 0; - - // create string from array - $str = $this->UTF8ArrSubString($ta); - - // check if string contains arabic text - if (preg_match(K_RE_PATTERN_ARABIC, $str)) { - $arabic = true; - } else { - $arabic = false; - } - - // check if string contains RTL text - if (!($forcertl OR $arabic OR preg_match(K_RE_PATTERN_RTL, $str))) { - return $ta; - } - - // get number of chars - $numchars = count($ta); - - if ($forcertl == 'R') { - $pel = 1; - } elseif ($forcertl == 'L') { - $pel = 0; - } else { - // P2. In each paragraph, find the first character of type L, AL, or R. - // P3. If a character is found in P2 and it is of type AL or R, then set the paragraph embedding level to one; otherwise, set it to zero. - for ($i=0; $i < $numchars; $i++) { - $type = $unicode[$ta[$i]]; - if ($type == 'L') { - $pel = 0; - break; - } elseif (($type == 'AL') OR ($type == 'R')) { - $pel = 1; - break; - } - } - } - - // Current Embedding Level - $cel = $pel; - // directional override status - $dos = 'N'; - $remember = array(); - // start-of-level-run - $sor = $pel % 2 ? 'R' : 'L'; - $eor = $sor; - - //$levels = array(array('level' => $cel, 'sor' => $sor, 'eor' => '', 'chars' => array())); - //$current_level = &$levels[count( $levels )-1]; - - // Array of characters data - $chardata = Array(); - - // X1. Begin by setting the current embedding level to the paragraph embedding level. Set the directional override status to neutral. Process each character iteratively, applying rules X2 through X9. Only embedding levels from 0 to 61 are valid in this phase. - // In the resolution of levels in rules I1 and I2, the maximum embedding level of 62 can be reached. - for ($i=0; $i < $numchars; $i++) { - if ($ta[$i] == K_RLE) { - // X2. With each RLE, compute the least greater odd embedding level. - // a. If this new level would be valid, then this embedding code is valid. Remember (push) the current embedding level and override status. Reset the current level to this new level, and reset the override status to neutral. - // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status. - $next_level = $cel + ($cel % 2) + 1; - if ($next_level < 62) { - $remember[] = array('num' => K_RLE, 'cel' => $cel, 'dos' => $dos); - $cel = $next_level; - $dos = 'N'; - $sor = $eor; - $eor = $cel % 2 ? 'R' : 'L'; - } - } elseif ($ta[$i] == K_LRE) { - // X3. With each LRE, compute the least greater even embedding level. - // a. If this new level would be valid, then this embedding code is valid. Remember (push) the current embedding level and override status. Reset the current level to this new level, and reset the override status to neutral. - // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status. - $next_level = $cel + 2 - ($cel % 2); - if ( $next_level < 62 ) { - $remember[] = array('num' => K_LRE, 'cel' => $cel, 'dos' => $dos); - $cel = $next_level; - $dos = 'N'; - $sor = $eor; - $eor = $cel % 2 ? 'R' : 'L'; - } - } elseif ($ta[$i] == K_RLO) { - // X4. With each RLO, compute the least greater odd embedding level. - // a. If this new level would be valid, then this embedding code is valid. Remember (push) the current embedding level and override status. Reset the current level to this new level, and reset the override status to right-to-left. - // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status. - $next_level = $cel + ($cel % 2) + 1; - if ($next_level < 62) { - $remember[] = array('num' => K_RLO, 'cel' => $cel, 'dos' => $dos); - $cel = $next_level; - $dos = 'R'; - $sor = $eor; - $eor = $cel % 2 ? 'R' : 'L'; - } - } elseif ($ta[$i] == K_LRO) { - // X5. With each LRO, compute the least greater even embedding level. - // a. If this new level would be valid, then this embedding code is valid. Remember (push) the current embedding level and override status. Reset the current level to this new level, and reset the override status to left-to-right. - // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status. - $next_level = $cel + 2 - ($cel % 2); - if ( $next_level < 62 ) { - $remember[] = array('num' => K_LRO, 'cel' => $cel, 'dos' => $dos); - $cel = $next_level; - $dos = 'L'; - $sor = $eor; - $eor = $cel % 2 ? 'R' : 'L'; - } - } elseif ($ta[$i] == K_PDF) { - // X7. With each PDF, determine the matching embedding or override code. If there was a valid matching code, restore (pop) the last remembered (pushed) embedding level and directional override. - if (count($remember)) { - $last = count($remember ) - 1; - if (($remember[$last]['num'] == K_RLE) OR - ($remember[$last]['num'] == K_LRE) OR - ($remember[$last]['num'] == K_RLO) OR - ($remember[$last]['num'] == K_LRO)) { - $match = array_pop($remember); - $cel = $match['cel']; - $dos = $match['dos']; - $sor = $eor; - $eor = ($cel > $match['cel'] ? $cel : $match['cel']) % 2 ? 'R' : 'L'; - } - } - } elseif (($ta[$i] != K_RLE) AND - ($ta[$i] != K_LRE) AND - ($ta[$i] != K_RLO) AND - ($ta[$i] != K_LRO) AND - ($ta[$i] != K_PDF)) { - // X6. For all types besides RLE, LRE, RLO, LRO, and PDF: - // a. Set the level of the current character to the current embedding level. - // b. Whenever the directional override status is not neutral, reset the current character type to the directional override status. - if ($dos != 'N') { - $chardir = $dos; - } else { - $chardir = $unicode[$ta[$i]]; - } - // stores string characters and other information - $chardata[] = array('char' => $ta[$i], 'level' => $cel, 'type' => $chardir, 'sor' => $sor, 'eor' => $eor); - } - } // end for each char - - // X8. All explicit directional embeddings and overrides are completely terminated at the end of each paragraph. Paragraph separators are not included in the embedding. - // X9. Remove all RLE, LRE, RLO, LRO, PDF, and BN codes. - // X10. The remaining rules are applied to each run of characters at the same level. For each run, determine the start-of-level-run (sor) and end-of-level-run (eor) type, either L or R. This depends on the higher of the two levels on either side of the boundary (at the start or end of the paragraph, the level of the “other” run is the base embedding level). If the higher level is odd, the type is R; otherwise, it is L. - - // 3.3.3 Resolving Weak Types - // Weak types are now resolved one level run at a time. At level run boundaries where the type of the character on the other side of the boundary is required, the type assigned to sor or eor is used. - // Nonspacing marks are now resolved based on the previous characters. - $numchars = count($chardata); - - // W1. Examine each nonspacing mark (NSM) in the level run, and change the type of the NSM to the type of the previous character. If the NSM is at the start of the level run, it will get the type of sor. - $prevlevel = -1; // track level changes - $levcount = 0; // counts consecutive chars at the same level - for ($i=0; $i < $numchars; $i++) { - if ($chardata[$i]['type'] == 'NSM') { - if ($levcount) { - $chardata[$i]['type'] = $chardata[$i]['sor']; - } elseif ($i > 0) { - $chardata[$i]['type'] = $chardata[($i-1)]['type']; - } - } - if ($chardata[$i]['level'] != $prevlevel) { - $levcount = 0; - } else { - $levcount++; - } - $prevlevel = $chardata[$i]['level']; - } - - // W2. Search backward from each instance of a European number until the first strong type (R, L, AL, or sor) is found. If an AL is found, change the type of the European number to Arabic number. - $prevlevel = -1; - $levcount = 0; - for ($i=0; $i < $numchars; $i++) { - if ($chardata[$i]['char'] == 'EN') { - for ($j=$levcount; $j >= 0; $j--) { - if ($chardata[$j]['type'] == 'AL') { - $chardata[$i]['type'] = 'AN'; - } elseif (($chardata[$j]['type'] == 'L') OR ($chardata[$j]['type'] == 'R')) { - break; - } - } - } - if ($chardata[$i]['level'] != $prevlevel) { - $levcount = 0; - } else { - $levcount++; - } - $prevlevel = $chardata[$i]['level']; - } - - // W3. Change all ALs to R. - for ($i=0; $i < $numchars; $i++) { - if ($chardata[$i]['type'] == 'AL') { - $chardata[$i]['type'] = 'R'; - } - } - - // W4. A single European separator between two European numbers changes to a European number. A single common separator between two numbers of the same type changes to that type. - $prevlevel = -1; - $levcount = 0; - for ($i=0; $i < $numchars; $i++) { - if (($levcount > 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) { - if (($chardata[$i]['type'] == 'ES') AND ($chardata[($i-1)]['type'] == 'EN') AND ($chardata[($i+1)]['type'] == 'EN')) { - $chardata[$i]['type'] = 'EN'; - } elseif (($chardata[$i]['type'] == 'CS') AND ($chardata[($i-1)]['type'] == 'EN') AND ($chardata[($i+1)]['type'] == 'EN')) { - $chardata[$i]['type'] = 'EN'; - } elseif (($chardata[$i]['type'] == 'CS') AND ($chardata[($i-1)]['type'] == 'AN') AND ($chardata[($i+1)]['type'] == 'AN')) { - $chardata[$i]['type'] = 'AN'; - } - } - if ($chardata[$i]['level'] != $prevlevel) { - $levcount = 0; - } else { - $levcount++; - } - $prevlevel = $chardata[$i]['level']; - } - - // W5. A sequence of European terminators adjacent to European numbers changes to all European numbers. - $prevlevel = -1; - $levcount = 0; - for ($i=0; $i < $numchars; $i++) { - if($chardata[$i]['type'] == 'ET') { - if (($levcount > 0) AND ($chardata[($i-1)]['type'] == 'EN')) { - $chardata[$i]['type'] = 'EN'; - } else { - $j = $i+1; - while (($j < $numchars) AND ($chardata[$j]['level'] == $prevlevel)) { - if ($chardata[$j]['type'] == 'EN') { - $chardata[$i]['type'] = 'EN'; - break; - } elseif ($chardata[$j]['type'] != 'ET') { - break; - } - $j++; - } - } - } - if ($chardata[$i]['level'] != $prevlevel) { - $levcount = 0; - } else { - $levcount++; - } - $prevlevel = $chardata[$i]['level']; - } - - // W6. Otherwise, separators and terminators change to Other Neutral. - $prevlevel = -1; - $levcount = 0; - for ($i=0; $i < $numchars; $i++) { - if (($chardata[$i]['type'] == 'ET') OR ($chardata[$i]['type'] == 'ES') OR ($chardata[$i]['type'] == 'CS')) { - $chardata[$i]['type'] = 'ON'; - } - if ($chardata[$i]['level'] != $prevlevel) { - $levcount = 0; - } else { - $levcount++; - } - $prevlevel = $chardata[$i]['level']; - } - - //W7. Search backward from each instance of a European number until the first strong type (R, L, or sor) is found. If an L is found, then change the type of the European number to L. - $prevlevel = -1; - $levcount = 0; - for ($i=0; $i < $numchars; $i++) { - if ($chardata[$i]['char'] == 'EN') { - for ($j=$levcount; $j >= 0; $j--) { - if ($chardata[$j]['type'] == 'L') { - $chardata[$i]['type'] = 'L'; - } elseif ($chardata[$j]['type'] == 'R') { - break; - } - } - } - if ($chardata[$i]['level'] != $prevlevel) { - $levcount = 0; - } else { - $levcount++; - } - $prevlevel = $chardata[$i]['level']; - } - - // N1. A sequence of neutrals takes the direction of the surrounding strong text if the text on both sides has the same direction. European and Arabic numbers act as if they were R in terms of their influence on neutrals. Start-of-level-run (sor) and end-of-level-run (eor) are used at level run boundaries. - $prevlevel = -1; - $levcount = 0; - for ($i=0; $i < $numchars; $i++) { - if (($levcount > 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) { - if (($chardata[$i]['type'] == 'N') AND ($chardata[($i-1)]['type'] == 'L') AND ($chardata[($i+1)]['type'] == 'L')) { - $chardata[$i]['type'] = 'L'; - } elseif (($chardata[$i]['type'] == 'N') AND - (($chardata[($i-1)]['type'] == 'R') OR ($chardata[($i-1)]['type'] == 'EN') OR ($chardata[($i-1)]['type'] == 'AN')) AND - (($chardata[($i+1)]['type'] == 'R') OR ($chardata[($i+1)]['type'] == 'EN') OR ($chardata[($i+1)]['type'] == 'AN'))) { - $chardata[$i]['type'] = 'R'; - } elseif ($chardata[$i]['type'] == 'N') { - // N2. Any remaining neutrals take the embedding direction - $chardata[$i]['type'] = $chardata[$i]['sor']; - } - } elseif (($levcount == 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) { - // first char - if (($chardata[$i]['type'] == 'N') AND ($chardata[$i]['sor'] == 'L') AND ($chardata[($i+1)]['type'] == 'L')) { - $chardata[$i]['type'] = 'L'; - } elseif (($chardata[$i]['type'] == 'N') AND - (($chardata[$i]['sor'] == 'R') OR ($chardata[$i]['sor'] == 'EN') OR ($chardata[$i]['sor'] == 'AN')) AND - (($chardata[($i+1)]['type'] == 'R') OR ($chardata[($i+1)]['type'] == 'EN') OR ($chardata[($i+1)]['type'] == 'AN'))) { - $chardata[$i]['type'] = 'R'; - } elseif ($chardata[$i]['type'] == 'N') { - // N2. Any remaining neutrals take the embedding direction - $chardata[$i]['type'] = $chardata[$i]['sor']; - } - } elseif (($levcount > 0) AND ((($i+1) == $numchars) OR (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] != $prevlevel))) { - //last char - if (($chardata[$i]['type'] == 'N') AND ($chardata[($i-1)]['type'] == 'L') AND ($chardata[$i]['eor'] == 'L')) { - $chardata[$i]['type'] = 'L'; - } elseif (($chardata[$i]['type'] == 'N') AND - (($chardata[($i-1)]['type'] == 'R') OR ($chardata[($i-1)]['type'] == 'EN') OR ($chardata[($i-1)]['type'] == 'AN')) AND - (($chardata[$i]['eor'] == 'R') OR ($chardata[$i]['eor'] == 'EN') OR ($chardata[$i]['eor'] == 'AN'))) { - $chardata[$i]['type'] = 'R'; - } elseif ($chardata[$i]['type'] == 'N') { - // N2. Any remaining neutrals take the embedding direction - $chardata[$i]['type'] = $chardata[$i]['sor']; - } - } elseif ($chardata[$i]['type'] == 'N') { - // N2. Any remaining neutrals take the embedding direction - $chardata[$i]['type'] = $chardata[$i]['sor']; - } - if ($chardata[$i]['level'] != $prevlevel) { - $levcount = 0; - } else { - $levcount++; - } - $prevlevel = $chardata[$i]['level']; - } - - // I1. For all characters with an even (left-to-right) embedding direction, those of type R go up one level and those of type AN or EN go up two levels. - // I2. For all characters with an odd (right-to-left) embedding direction, those of type L, EN or AN go up one level. - for ($i=0; $i < $numchars; $i++) { - $odd = $chardata[$i]['level'] % 2; - if ($odd) { - if (($chardata[$i]['type'] == 'L') OR ($chardata[$i]['type'] == 'AN') OR ($chardata[$i]['type'] == 'EN')){ - $chardata[$i]['level'] += 1; - } - } else { - if ($chardata[$i]['type'] == 'R') { - $chardata[$i]['level'] += 1; - } elseif (($chardata[$i]['type'] == 'AN') OR ($chardata[$i]['type'] == 'EN')){ - $chardata[$i]['level'] += 2; - } - } - $maxlevel = max($chardata[$i]['level'],$maxlevel); - } - - // L1. On each line, reset the embedding level of the following characters to the paragraph embedding level: - // 1. Segment separators, - // 2. Paragraph separators, - // 3. Any sequence of whitespace characters preceding a segment separator or paragraph separator, and - // 4. Any sequence of white space characters at the end of the line. - for ($i=0; $i < $numchars; $i++) { - if (($chardata[$i]['type'] == 'B') OR ($chardata[$i]['type'] == 'S')) { - $chardata[$i]['level'] = $pel; - } elseif ($chardata[$i]['type'] == 'WS') { - $j = $i+1; - while ($j < $numchars) { - if ((($chardata[$j]['type'] == 'B') OR ($chardata[$j]['type'] == 'S')) OR - (($j == ($numchars-1)) AND ($chardata[$j]['type'] == 'WS'))) { - $chardata[$i]['level'] = $pel;; - break; - } elseif ($chardata[$j]['type'] != 'WS') { - break; - } - $j++; - } - } - } - - // Arabic Shaping - // Cursively connected scripts, such as Arabic or Syriac, require the selection of positional character shapes that depend on adjacent characters. Shaping is logically applied after the Bidirectional Algorithm is used and is limited to characters within the same directional run. - if ($arabic) { - $endedletter = array(1569,1570,1571,1572,1573,1575,1577,1583,1584,1585,1586,1608,1688); - $alfletter = array(1570,1571,1573,1575); - $chardata2 = $chardata; - $prevALchar = ""; - $laaletter = false; - $charAL = array(); - $x = 0; - for ($i=0; $i < $numchars; $i++) { - if (($unicode[$chardata[$i]['char']] == 'AL') OR ($chardata[$i]['char'] == 32)) { - $charAL[$x] = $chardata[$i]; - $charAL[$x]['i'] = $i; - $chardata[$i]['x'] = $x; - ++$x; - } - } - for ($i=0; $i < $numchars; $i++) { - $thischar = $chardata[$i]; - if ($i > 0) { - $prevchar = $chardata[($i-1)]; - } else { - $prevchar = false; - } - if (($i+1) < $numchars) { - $nextchar = $chardata[($i+1)]; - } else { - $nextchar = false; - } - if ($unicode[$thischar['char']] == 'AL') { - $x = $thischar['x']; - if ($i > 0) { - $prevchar = $charAL[($x-1)]; - } else { - $prevchar = false; - } - if (($i+1) < $numchars) { - $nextchar = $charAL[($x+1)]; - } else { - $nextchar = false; - } - // if laa letter - if (($i > 0) AND ($prevchar['char'] == 1604) AND (in_array($thischar['char'], $alfletter))) { - $arabicarr = $laa_array; - $laaletter = true; - $prevchar = $charAL[($x-2)]; - } else { - $arabicarr = $unicode_arlet; - $laaletter = false; - } - if (($i > 0) AND (($i+1) < $numchars) AND - (($unicode[$prevchar['char']] == 'AL') OR ($unicode[$prevchar['char']] == 'NSM')) AND - (($unicode[$nextchar['char']] == 'AL') OR ($unicode[$nextchar['char']] == 'NSM')) AND - ($prevchar['type'] == $thischar['type']) AND - ($nextchar['type'] == $thischar['type']) AND - ($nextchar['char'] != 1567)) { - if (in_array($prevchar['char'], $endedletter)) { - if (isset($arabicarr[$thischar['char']][2])) { - // initial - $chardata2[$i]['char'] = $arabicarr[$thischar['char']][2]; - } - } else { - if (isset($arabicarr[$thischar['char']][3])) { - // medial - $chardata2[$i]['char'] = $arabicarr[$thischar['char']][3]; - } - } - } elseif ((($i+1) < $numchars) AND - (($unicode[$nextchar['char']] == 'AL') OR ($unicode[$nextchar['char']] == 'NSM')) AND - ($nextchar['type'] == $thischar['type']) AND - ($nextchar['char'] != 1567)) { - if (isset($unicode_arlet[$chardata[$i]['char']][2])) { - // initial - $chardata2[$i]['char'] = $unicode_arlet[$thischar['char']][2]; - } - } elseif ((($i > 0) AND - (($unicode[$prevchar['char']] == 'AL') OR ($unicode[$prevchar['char']] == 'NSM')) AND - ($prevchar['type'] == $thischar['type'])) OR - ($nextchar['char'] == 1567)) { - // final - if (($thischar['char'] == 1607) AND - ($chardata[$i-1]['char'] == 1604) AND - ($chardata[$i-2]['char'] == 1604)) { - //Allah Word - // mark characters to delete with false - $chardata2[$i-2]['char'] = false; - $chardata2[$i-1]['char'] = false; - $chardata2[$i]['char'] = 65010; - } else { - if (in_array($prevchar['char'], $endedletter)) { - if (isset($arabicarr[$thischar['char']][0])) { - // isolated - $chardata2[$i]['char'] = $arabicarr[$thischar['char']][0]; - } - } else { - if (isset($arabicarr[$thischar['char']][1])) { - // final - $chardata2[$i]['char'] = $arabicarr[$thischar['char']][1]; - } - } - } - } elseif (isset($arabicarr[$thischar['char']][0])) { - // isolated - $chardata2[$i]['char'] = $arabicarr[$thischar['char']][0]; - } - // if laa letter - if($laaletter) { - // mark characters to delete with false - $chardata2[($charAL[($x-1)]['i'])]['char'] = false; - } - } // end if AL (Arabic Letter) - } // end for each char - /* - * Combining characters that can occur with Shadda (0651 HEX, 1617 DEC) are placed in UE586-UE594. - * Putting the combining mark and shadda in the same glyph allows us to avoid the two marks overlapping each other in an illegible manner. - */ - $cw = &$this->CurrentFont['cw']; - for ($i=0; $i < ($numchars-1); $i++) { - if (($chardata2[$i]['char'] == 1617) AND (isset($diacritics[($chardata2[$i+1]['char'])]))) { - // check if the subtitution font is defined on current font - if (isset($cw[($diacritics[($chardata2[$i+1]['char'])])])) { - $chardata2[$i]['char'] = false; - $chardata2[$i+1]['char'] = $diacritics[($chardata2[$i+1]['char'])]; - } - } - } - // remove marked characters - foreach($chardata2 as $key => $value) { - if ($value['char'] === false) { - unset($chardata2[$key]); - } - } - $chardata = array_values($chardata2); - - unset($chardata2); - unset($arabicarr); - unset($laaletter); - unset($charAL); - } - - // L2. From the highest level found in the text to the lowest odd level on each line, including intermediate levels not actually present in the text, reverse any contiguous sequence of characters that are at that level or higher. - for ($j=$maxlevel; $j > 0; $j--) { - $ordarray = Array(); - $revarr = Array(); - $onlevel = false; - for ($i=0; $i < $numchars; $i++) { - if ($chardata[$i]['level'] >= $j) { - $onlevel = true; - if (isset($unicode_mirror[$chardata[$i]['char']])) { - // L4. A character is depicted by a mirrored glyph if and only if (a) the resolved directionality of that character is R, and (b) the Bidi_Mirrored property value of that character is true. - $chardata[$i]['char'] = $unicode_mirror[$chardata[$i]['char']]; - } - $revarr[] = $chardata[$i]; - } else { - if($onlevel) { - $revarr = array_reverse($revarr); - $ordarray = array_merge($ordarray, $revarr); - $revarr = Array(); - $onlevel = false; - } - $ordarray[] = $chardata[$i]; - } - } - if($onlevel) { - $revarr = array_reverse($revarr); - $ordarray = array_merge($ordarray, $revarr); - } - $chardata = $ordarray; - } - - $ordarray = array(); - for ($i=0; $i < $numchars; $i++) { - $ordarray[] = $chardata[$i]['char']; - } - - return $ordarray; - } - - // END OF BIDIRECTIONAL TEXT SECTION ------------------- - - /* - * Adds a bookmark. - * @param string $txt bookmark description. - * @param int $level bookmark level. - * @param float $y Ordinate of the boorkmark position (default = -1 = current position). - * @access public - * @author Olivier Plathey, Nicola Asuni - * @since 2.1.002 (2008-02-12) - */ - function Bookmark($txt, $level=0, $y=-1) { - if($y == -1) { - $y = $this->GetY(); - } - $this->outlines[]=array('t'=>$txt,'l'=>$level,'y'=>$y,'p'=>$this->PageNo()); - } - - /* - * Create a bookmark PDF string. - * @access protected - * @author Olivier Plathey, Nicola Asuni - * @since 2.1.002 (2008-02-12) - */ - function _putbookmarks() { - $nb = count($this->outlines); - if($nb == 0) { - return; - } - $lru = array(); - $level = 0; - foreach($this->outlines as $i=>$o) { - if($o['l'] > 0) { - $parent = $lru[$o['l'] - 1]; - //Set parent and last pointers - $this->outlines[$i]['parent'] = $parent; - $this->outlines[$parent]['last'] = $i; - if($o['l'] > $level) { - //Level increasing: set first pointer - $this->outlines[$parent]['first'] = $i; - } - } else { - $this->outlines[$i]['parent']=$nb; - } - if($o['l']<=$level and $i>0) { - //Set prev and next pointers - $prev = $lru[$o['l']]; - $this->outlines[$prev]['next'] = $i; - $this->outlines[$i]['prev'] = $prev; - } - $lru[$o['l']] = $i; - $level = $o['l']; - } - //Outline items - $n = $this->n+1; - foreach($this->outlines as $i=>$o) { - $this->_newobj(); - $this->_out('<_textstring($o['t'])); - $this->_out('/Parent '.($n+$o['parent']).' 0 R'); - if(isset($o['prev'])) - $this->_out('/Prev '.($n+$o['prev']).' 0 R'); - if(isset($o['next'])) - $this->_out('/Next '.($n+$o['next']).' 0 R'); - if(isset($o['first'])) - $this->_out('/First '.($n+$o['first']).' 0 R'); - if(isset($o['last'])) - $this->_out('/Last '.($n+$o['last']).' 0 R'); - $this->_out(sprintf('/Dest [%d 0 R /XYZ 0 %.2f null]',1+2*$o['p'],($this->h-$o['y'])*$this->k)); - $this->_out('/Count 0>>'); - $this->_out('endobj'); - } - //Outline root - $this->_newobj(); - $this->OutlineRoot=$this->n; - $this->_out('<_out('/Last '.($n+$lru[0]).' 0 R>>'); - $this->_out('endobj'); - } - - - // --- JAVASCRIPT - FORMS ------------------------------ - - /* - * Adds a javascript - * @access public - * @author Johannes Güntert, Nicola Asuni - * @since 2.1.002 (2008-02-12) - */ - function IncludeJS($script) { - $this->javascript .= $script; - } - - /* - * Create a javascript PDF string. - * @access protected - * @author Johannes Güntert, Nicola Asuni - * @since 2.1.002 (2008-02-12) - */ - function _putjavascript() { - if (empty($this->javascript)) { - return; - } - $this->_newobj(); - $this->n_js = $this->n; - $this->_out('<<'); - $this->_out('/Names [(EmbeddedJS) '.($this->n+1).' 0 R ]'); - $this->_out('>>'); - $this->_out('endobj'); - $this->_newobj(); - $this->_out('<<'); - $this->_out('/S /JavaScript'); - $this->_out('/JS '.$this->_textstring($this->javascript)); - $this->_out('>>'); - $this->_out('endobj'); - } - - /* - * Convert color to javascript color. - * @param string $color color name or #RRGGBB - * @access protected - * @author Denis Van Nuffelen, Nicola Asuni - * @since 2.1.002 (2008-02-12) - */ - function _JScolor($color) { - static $aColors = array('transparent','black','white','red','green','blue','cyan','magenta','yellow','dkGray','gray','ltGray'); - if(substr($color,0,1) == '#') { - return sprintf("['RGB',%.3f,%.3f,%.3f]", hexdec(substr($color,1,2))/255, hexdec(substr($color,3,2))/255, hexdec(substr($color,5,2))/255); - } - if(!in_array($color,$aColors)) { - $this->Error('Invalid color: '.$color); - } - return 'color.'.$color; - } - - /* - * Adds a javascript form field. - * @param string $type field type - * @param string $name field name - * @param int $x horizontal position - * @param int $y vertical position - * @param int $w width - * @param int $h height - * @param array $prop array of properties. Possible values are (http://www.adobe.com/devnet/acrobat/pdfs/js_developer_guide.pdf):
      • rect: Position and size of field on page.
      • borderStyle: Rectangle border appearance.
      • strokeColor: Color of bounding rectangle.
      • lineWidth: Width of the edge of the surrounding rectangle.
      • rotation: Rotation of field in 90-degree increments.
      • fillColor: Background color of field (gray, transparent, RGB, or CMYK).
      • userName: Short description of field that appears on mouse-over.
      • readonly: Whether the user may change the field contents.
      • doNotScroll: Whether text fields may scroll.
      • display: Whether visible or hidden on screen or in print.
      • textFont: Text font.
      • textColor: Text color.
      • textSize: Text size.
      • richText: Rich text.
      • richValue: Text.
      • comb: Text comb format.
      • multiline: Text multiline.
      • charLimit: Text limit to number of characters.
      • fileSelect: Text file selection format.
      • password: Text password format.
      • alignment: Text layout in text fields.
      • buttonAlignX: X alignment of icon on button face.
      • buttonAlignY: Y alignment of icon on button face.
      • buttonFitBounds: Relative scaling of an icon to fit inside a button face.
      • buttonScaleHow: Relative scaling of an icon to fit inside a button face.
      • buttonScaleWhen: Relative scaling of an icon to fit inside a button face.
      • highlight: Appearance of a button when pushed.
      • style: Glyph style for checkbox and radio buttons.
      • numItems: Number of items in a combo box or list box.
      • editable: Whether the user can type in a combo box.
      • multipleSelection: Whether multiple list box items may be selected.
      - * @access protected - * @author Denis Van Nuffelen, Nicola Asuni - * @since 2.1.002 (2008-02-12) - */ - function _addfield($type, $name, $x, $y, $w, $h, $prop) { - $k = $this->k; - $this->javascript .= sprintf("f".$name."=this.addField('%s','%s',%d,[%.2f,%.2f,%.2f,%.2f]);",$name,$type,$this->PageNo()-1,$x*$k,($this->h-$y)*$k+1,($x+$w)*$k,($this->h-$y-$h)*$k+1)."\n"; - $this->javascript .= "f".$name.".textSize=".$this->FontSizePt.";\n"; - while(list($key, $val) = each($prop)) { - if (strcmp(substr($key,-5),"Color") == 0) { - $val = $this->_JScolor($val); - } else { - $val = "'".$val."'"; - } - $this->javascript .= "f".$name.".".$key."=".$val.";\n"; - } - $this->x += $w; - } - - /* - * Creates a text field - * @param string $name field name - * @param int $w width - * @param int $h height - * @param string $prop properties. The value property allows to set the initial value. The multiline property allows to define the field as multiline. Possible values are (http://www.adobe.com/devnet/acrobat/pdfs/js_developer_guide.pdf):
      • rect: Position and size of field on page.
      • borderStyle: Rectangle border appearance.
      • strokeColor: Color of bounding rectangle.
      • lineWidth: Width of the edge of the surrounding rectangle.
      • rotation: Rotation of field in 90-degree increments.
      • fillColor: Background color of field (gray, transparent, RGB, or CMYK).
      • userName: Short description of field that appears on mouse-over.
      • readonly: Whether the user may change the field contents.
      • doNotScroll: Whether text fields may scroll.
      • display: Whether visible or hidden on screen or in print.
      • textFont: Text font.
      • textColor: Text color.
      • textSize: Text size.
      • richText: Rich text.
      • richValue: Text.
      • comb: Text comb format.
      • multiline: Text multiline.
      • charLimit: Text limit to number of characters.
      • fileSelect: Text file selection format.
      • password: Text password format.
      • alignment: Text layout in text fields.
      • buttonAlignX: X alignment of icon on button face.
      • buttonAlignY: Y alignment of icon on button face.
      • buttonFitBounds: Relative scaling of an icon to fit inside a button face.
      • buttonScaleHow: Relative scaling of an icon to fit inside a button face.
      • buttonScaleWhen: Relative scaling of an icon to fit inside a button face.
      • highlight: Appearance of a button when pushed.
      • style: Glyph style for checkbox and radio buttons.
      • numItems: Number of items in a combo box or list box.
      • editable: Whether the user can type in a combo box.
      • multipleSelection: Whether multiple list box items may be selected.
      - * @access public - * @author Denis Van Nuffelen, Nicola Asuni - * @since 2.1.002 (2008-02-12) - */ - function TextField($name, $w, $h, $prop=array()) { - $this->_addfield('text',$name,$this->x,$this->y,$w,$h,$prop); - } - - /* - * Creates a RadioButton field - * @param string $name field name - * @param int $w width - * @param string $prop properties. Possible values are (http://www.adobe.com/devnet/acrobat/pdfs/js_developer_guide.pdf):
      • rect: Position and size of field on page.
      • borderStyle: Rectangle border appearance.
      • strokeColor: Color of bounding rectangle.
      • lineWidth: Width of the edge of the surrounding rectangle.
      • rotation: Rotation of field in 90-degree increments.
      • fillColor: Background color of field (gray, transparent, RGB, or CMYK).
      • userName: Short description of field that appears on mouse-over.
      • readonly: Whether the user may change the field contents.
      • doNotScroll: Whether text fields may scroll.
      • display: Whether visible or hidden on screen or in print.
      • textFont: Text font.
      • textColor: Text color.
      • textSize: Text size.
      • richText: Rich text.
      • richValue: Text.
      • comb: Text comb format.
      • multiline: Text multiline.
      • charLimit: Text limit to number of characters.
      • fileSelect: Text file selection format.
      • password: Text password format.
      • alignment: Text layout in text fields.
      • buttonAlignX: X alignment of icon on button face.
      • buttonAlignY: Y alignment of icon on button face.
      • buttonFitBounds: Relative scaling of an icon to fit inside a button face.
      • buttonScaleHow: Relative scaling of an icon to fit inside a button face.
      • buttonScaleWhen: Relative scaling of an icon to fit inside a button face.
      • highlight: Appearance of a button when pushed.
      • style: Glyph style for checkbox and radio buttons.
      • numItems: Number of items in a combo box or list box.
      • editable: Whether the user can type in a combo box.
      • multipleSelection: Whether multiple list box items may be selected.
      - * @access public - * @author Nicola Asuni - * @since 2.2.003 (2008-03-03) - */ - function RadioButton($name, $w, $prop=array()) { - if(!isset($prop['strokeColor'])) { - $prop['strokeColor']='black'; - } - $this->_addfield('radiobutton',$name,$this->x,$this->y,$w,$w,$prop); - } - - /* - * Creates a List-box field - * @param string $name field name - * @param int $w width - * @param int $h height - * @param array $values array containing the list of values. - * @param string $prop properties. Possible values are (http://www.adobe.com/devnet/acrobat/pdfs/js_developer_guide.pdf):
      • rect: Position and size of field on page.
      • borderStyle: Rectangle border appearance.
      • strokeColor: Color of bounding rectangle.
      • lineWidth: Width of the edge of the surrounding rectangle.
      • rotation: Rotation of field in 90-degree increments.
      • fillColor: Background color of field (gray, transparent, RGB, or CMYK).
      • userName: Short description of field that appears on mouse-over.
      • readonly: Whether the user may change the field contents.
      • doNotScroll: Whether text fields may scroll.
      • display: Whether visible or hidden on screen or in print.
      • textFont: Text font.
      • textColor: Text color.
      • textSize: Text size.
      • richText: Rich text.
      • richValue: Text.
      • comb: Text comb format.
      • multiline: Text multiline.
      • charLimit: Text limit to number of characters.
      • fileSelect: Text file selection format.
      • password: Text password format.
      • alignment: Text layout in text fields.
      • buttonAlignX: X alignment of icon on button face.
      • buttonAlignY: Y alignment of icon on button face.
      • buttonFitBounds: Relative scaling of an icon to fit inside a button face.
      • buttonScaleHow: Relative scaling of an icon to fit inside a button face.
      • buttonScaleWhen: Relative scaling of an icon to fit inside a button face.
      • highlight: Appearance of a button when pushed.
      • style: Glyph style for checkbox and radio buttons.
      • numItems: Number of items in a combo box or list box.
      • editable: Whether the user can type in a combo box.
      • multipleSelection: Whether multiple list box items may be selected.
      - * @access public - * @author Nicola Asuni - * @since 2.2.003 (2008-03-03) - */ - function ListBox($name, $w, $h, $values, $prop=array()) { - if(!isset($prop['strokeColor'])) { - $prop['strokeColor']='ltGray'; - } - $this->_addfield('listbox',$name,$this->x,$this->y,$w,$h,$prop); - $s = ''; - foreach($values as $value) { - $s .= "'".addslashes($value)."',"; - } - $this->javascript .= "f".$name.".setItems([".substr($s,0,-1)."]);\n"; - } - - /* - * Creates a Combo-box field - * @param string $name field name - * @param int $w width - * @param int $h height - * @param array $values array containing the list of values. - * @param string $prop properties. Possible values are (http://www.adobe.com/devnet/acrobat/pdfs/js_developer_guide.pdf):
      • rect: Position and size of field on page.
      • borderStyle: Rectangle border appearance.
      • strokeColor: Color of bounding rectangle.
      • lineWidth: Width of the edge of the surrounding rectangle.
      • rotation: Rotation of field in 90-degree increments.
      • fillColor: Background color of field (gray, transparent, RGB, or CMYK).
      • userName: Short description of field that appears on mouse-over.
      • readonly: Whether the user may change the field contents.
      • doNotScroll: Whether text fields may scroll.
      • display: Whether visible or hidden on screen or in print.
      • textFont: Text font.
      • textColor: Text color.
      • textSize: Text size.
      • richText: Rich text.
      • richValue: Text.
      • comb: Text comb format.
      • multiline: Text multiline.
      • charLimit: Text limit to number of characters.
      • fileSelect: Text file selection format.
      • password: Text password format.
      • alignment: Text layout in text fields.
      • buttonAlignX: X alignment of icon on button face.
      • buttonAlignY: Y alignment of icon on button face.
      • buttonFitBounds: Relative scaling of an icon to fit inside a button face.
      • buttonScaleHow: Relative scaling of an icon to fit inside a button face.
      • buttonScaleWhen: Relative scaling of an icon to fit inside a button face.
      • highlight: Appearance of a button when pushed.
      • style: Glyph style for checkbox and radio buttons.
      • numItems: Number of items in a combo box or list box.
      • editable: Whether the user can type in a combo box.
      • multipleSelection: Whether multiple list box items may be selected.
      - * @access public - * @author Denis Van Nuffelen, Nicola Asuni - * @since 2.1.002 (2008-02-12) - */ - function ComboBox($name, $w, $h, $values, $prop=array()) { - $this->_addfield('combobox',$name,$this->x,$this->y,$w,$h,$prop); - $s = ''; - foreach($values as $value) { - $s .= "'".addslashes($value)."',"; - } - $this->javascript .= "f".$name.".setItems([".substr($s,0,-1)."]);\n"; - } - - /* - * Creates a CheckBox field - * @param string $name field name - * @param int $w width - * @param boolean $checked define the initial state (default = false). - * @param string $prop properties. Possible values are (http://www.adobe.com/devnet/acrobat/pdfs/js_developer_guide.pdf):
      • rect: Position and size of field on page.
      • borderStyle: Rectangle border appearance.
      • strokeColor: Color of bounding rectangle.
      • lineWidth: Width of the edge of the surrounding rectangle.
      • rotation: Rotation of field in 90-degree increments.
      • fillColor: Background color of field (gray, transparent, RGB, or CMYK).
      • userName: Short description of field that appears on mouse-over.
      • readonly: Whether the user may change the field contents.
      • doNotScroll: Whether text fields may scroll.
      • display: Whether visible or hidden on screen or in print.
      • textFont: Text font.
      • textColor: Text color.
      • textSize: Text size.
      • richText: Rich text.
      • richValue: Text.
      • comb: Text comb format.
      • multiline: Text multiline.
      • charLimit: Text limit to number of characters.
      • fileSelect: Text file selection format.
      • password: Text password format.
      • alignment: Text layout in text fields.
      • buttonAlignX: X alignment of icon on button face.
      • buttonAlignY: Y alignment of icon on button face.
      • buttonFitBounds: Relative scaling of an icon to fit inside a button face.
      • buttonScaleHow: Relative scaling of an icon to fit inside a button face.
      • buttonScaleWhen: Relative scaling of an icon to fit inside a button face.
      • highlight: Appearance of a button when pushed.
      • style: Glyph style for checkbox and radio buttons.
      • numItems: Number of items in a combo box or list box.
      • editable: Whether the user can type in a combo box.
      • multipleSelection: Whether multiple list box items may be selected.
      - * @access public - * @author Denis Van Nuffelen, Nicola Asuni - * @since 2.1.002 (2008-02-12) - */ - function CheckBox($name, $w, $checked=false, $prop=array()) { - $prop['value'] = ($checked ? 'Yes' : 'Off'); - if(!isset($prop['strokeColor'])) { - $prop['strokeColor']='black'; - } - $this->_addfield('checkbox',$name,$this->x,$this->y,$w,$w,$prop); - } - - /* - * Creates a button field - * @param string $name field name - * @param int $w width - * @param int $h height - * @param string $caption caption. - * @param string $action action triggered by the button (JavaScript code). - * @param string $prop properties. Possible values are (http://www.adobe.com/devnet/acrobat/pdfs/js_developer_guide.pdf):
      • rect: Position and size of field on page.
      • borderStyle: Rectangle border appearance.
      • strokeColor: Color of bounding rectangle.
      • lineWidth: Width of the edge of the surrounding rectangle.
      • rotation: Rotation of field in 90-degree increments.
      • fillColor: Background color of field (gray, transparent, RGB, or CMYK).
      • userName: Short description of field that appears on mouse-over.
      • readonly: Whether the user may change the field contents.
      • doNotScroll: Whether text fields may scroll.
      • display: Whether visible or hidden on screen or in print.
      • textFont: Text font.
      • textColor: Text color.
      • textSize: Text size.
      • richText: Rich text.
      • richValue: Text.
      • comb: Text comb format.
      • multiline: Text multiline.
      • charLimit: Text limit to number of characters.
      • fileSelect: Text file selection format.
      • password: Text password format.
      • alignment: Text layout in text fields.
      • buttonAlignX: X alignment of icon on button face.
      • buttonAlignY: Y alignment of icon on button face.
      • buttonFitBounds: Relative scaling of an icon to fit inside a button face.
      • buttonScaleHow: Relative scaling of an icon to fit inside a button face.
      • buttonScaleWhen: Relative scaling of an icon to fit inside a button face.
      • highlight: Appearance of a button when pushed.
      • style: Glyph style for checkbox and radio buttons.
      • numItems: Number of items in a combo box or list box.
      • editable: Whether the user can type in a combo box.
      • multipleSelection: Whether multiple list box items may be selected.
      - * @access public - * @author Denis Van Nuffelen, Nicola Asuni - * @since 2.1.002 (2008-02-12) - */ - function Button($name, $w, $h, $caption, $action, $prop=array()) { - if(!isset($prop['strokeColor'])) { - $prop['strokeColor']='black'; - } - if(!isset($prop['borderStyle'])) { - $prop['borderStyle']='beveled'; - } - $this->_addfield('button',$name,$this->x,$this->y,$w,$h,$prop); - $this->javascript .= "f".$name.".buttonSetCaption('".addslashes($caption)."');\n"; - $this->javascript .= "f".$name.".setAction('MouseUp','".addslashes($action)."');\n"; - $this->javascript .= "f".$name.".highlight='push';\n"; - $this->javascript .= "f".$name.".print=false;\n"; - } - - // END JAVASCRIPT - FORMS ------------------------------ - - /* - * Enable Write permissions for PDF Reader. - * @access protected - * @author Nicola Asuni - * @since 2.9.000 (2008-03-26) - */ - function _putuserrights() { - if (!$this->ur) { - return; - } - $this->_out('/Perms'); - $this->_out('<<'); - $this->_out('/UR3'); - $this->_out('<<'); - //$this->_out('/SubFilter/adbe.pkcs7.detached/Filter/Adobe.PPKLite/Contents'); - //$this->_out('<0>'); - //$this->_out('/ByteRange[0 3]'); - $this->_out('/M '.$this->_datestring('D:'.date('YmdHis'))); - $this->_out('/Name(TCPDF)'); - $this->_out('/Reference['); - $this->_out('<<'); - $this->_out('/TransformParams'); - $this->_out('<<'); - $this->_out('/Type/TransformParams'); - $this->_out('/V/2.2'); - if (!empty($this->ur_document)) { - $this->_out('/Document['.$this->ur_document.']'); - } - if (!empty($this->ur_annots)) { - $this->_out('/Annots['.$this->ur_annots.']'); - } - if (!empty($this->ur_form)) { - $this->_out('/Form['.$this->ur_form.']'); - } - if (!empty($this->ur_signature)) { - $this->_out('/Signature['.$this->ur_signature.']'); - } - $this->_out('>>'); - $this->_out('/TransformMethod/UR3'); - $this->_out('/Type/SigRef'); - $this->_out('>>'); - $this->_out(']'); - $this->_out('/Type/Sig'); - $this->_out('>>'); - $this->_out('>>'); - } - - /* - * Set User's Rights for PDF Reader - * Check the PDF Reference 8.7.1 Transform Methods, - * Table 8.105 Entries in the UR transform parameters dictionary - * @param boolean $enable if true enable user's rights on PDF reader - * @param string $document Names specifying additional document-wide usage rights for the document. The only defined value is "/FullSave", which permits a user to save the document along with modified form and/or annotation data. - * @param string $annots Names specifying additional annotation-related usage rights for the document. Valid names in PDF 1.5 and later are /Create/Delete/Modify/Copy/Import/Export, which permit the user to perform the named operation on annotations. - * @param string $form Names specifying additional form-field-related usage rights for the document. Valid names are: /Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate - * @param string $signature Names specifying additional signature-related usage rights for the document. The only defined value is /Modify, which permits a user to apply a digital signature to an existing signature form field or clear a signed signature form field. - * @access public - * @author Nicola Asuni - * @since 2.9.000 (2008-03-26) - */ - function setUserRights( - $enable=true, - $document="/FullSave", - $annots="/Create/Delete/Modify/Copy/Import/Export", - $form="/Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate", - $signature="/Modify") { - $this->ur = $enable; - $this->ur_document = $document; - $this->ur_annots = $annots; - $this->ur_form = $form; - $this->ur_signature = $signature; - } - - /* - * Create a new page group. - * NOTE: call this function before calling AddPage() - * @access public - * @since 3.0.000 (2008-03-27) - */ - function startPageGroup() { - $this->newpagegroup = true; - } - - /* - * Return the current page in the group. - * @return current page in the group - * @access public - * @since 3.0.000 (2008-03-27) - */ - function getGroupPageNo() { - return $this->pagegroups[$this->currpagegroup]; - } - - /* - * Return the alias of the current page group - * (will be replaced by the total number of pages in this group). - * @return alias of the current page group - * @access public - * @since 3.0.000 (2008-03-27) - */ - function getPageGroupAlias() { - return $this->currpagegroup; - } - - /* - * Put visibility settings. - * @access protected - * @since 3.0.000 (2008-03-27) - */ - function _putocg() { - $this->_newobj(); - $this->n_ocg_print = $this->n; - $this->_out('<_textstring('print')); - $this->_out('/Usage <> /View <>>>>>'); - $this->_out('endobj'); - $this->_newobj(); - $this->n_ocg_view=$this->n; - $this->_out('<_textstring('view')); - $this->_out('/Usage <> /View <>>>>>'); - $this->_out('endobj'); - } - - /* - * Set the visibility of the successive elements. - * This can be useful, for instance, to put a background - * image or color that will show on screen but won't print. - * @param string $v visibility mode. Legal values are: all, print, screen. - * @access public - * @since 3.0.000 (2008-03-27) - */ - function setVisibility($v) { - switch($v) { - case "print": { - $this->_out('EMC /OC /OC1 BDC'); - break; - } - case "screen": { - $this->_out('EMC /OC /OC2 BDC'); - break; - } - case "all": { - $this->_out('EMC'); - break; - } - default: { - $this->Error('Incorrect visibility: '.$v); - break; - } - } - $this->visibility = $v; - } - - /* - * Add transparency parameters to the current extgstate - * @param array $params parameters - * @return the number of extgstates - * @access protected - * @since 3.0.000 (2008-03-27) - */ - function addExtGState($parms) { - $n = count($this->extgstates) + 1; - $this->extgstates[$n]['parms'] = $parms; - return $n; - } - - /* - * Add an extgstate - * @param array $gs extgstate - * @access protected - * @since 3.0.000 (2008-03-27) - */ - function setExtGState($gs) { - $this->_out(sprintf('/GS%d gs', $gs)); - } - - /* - * Put extgstates for object transparency - * @param array $gs extgstate - * @access protected - * @since 3.0.000 (2008-03-27) - */ - function _putextgstates() { - $ne = count($this->extgstates); - for ($i = 1; $i <= $ne; $i++) { - $this->_newobj(); - $this->extgstates[$i]['n'] = $this->n; - $this->_out('<extgstates[$i]['parms'] as $k => $v) { - $this->_out('/'.$k.' '.$v); - } - $this->_out('>>'); - $this->_out('endobj'); - } - } - - /* - * Set alpha for stroking (CA) and non-stroking (ca) operations. - * @param float $alpha real value from 0 (transparent) to 1 (opaque) - * @param string $bm blend mode, one of the following: Normal, Multiply, Screen, Overlay, Darken, Lighten, ColorDodge, ColorBurn, HardLight, SoftLight, Difference, Exclusion, Hue, Saturation, Color, Luminosity - * @access public - * @since 3.0.000 (2008-03-27) - */ - function setAlpha($alpha, $bm='Normal') { - $gs = $this->addExtGState(array('ca' => $alpha, 'CA' => $alpha, 'BM' => '/'.$bm)); - $this->setExtGState($gs); - } - - /* - * Set the default JPEG compression quality (1-100) - * @param int $quality JPEG quality, integer between 1 and 100 - * @access public - * @since 3.0.000 (2008-03-27) - */ - function setJPEGQuality($quality) { - if (($quality < 1) OR ($quality > 100)) { - $quality = 75; - } - $this->jpeg_quality = intval($quality); - } - - /* - * Set the default number of columns in a row for HTML tables. - * @param int $cols number of columns - * @access public - * @since 3.0.014_PHP4 (2008-06-04) - */ - function setDefaultTableColumns($cols=4) { - $this->default_table_columns = intval($cols); - } - - /* - * Set the height of cell repect font height. - * @param int $h cell proportion respect font height (typical value = 1.25). - * @access public - * @since 3.0.014_PHP4 (2008-06-04) - */ - function setCellHeightRatio($h) { - $this->cell_height_ratio = $h; - } - - } // END OF TCPDF CLASS - - //Handle special IE contype request - if(isset($_SERVER['HTTP_USER_AGENT']) AND ($_SERVER['HTTP_USER_AGENT']=='contype')) { - header('Content-Type: application/pdf'); - exit; - } - -} -//============================================================+ -// END OF FILE -//============================================================+ -?> \ No newline at end of file diff --git a/include/limesurvey/admin/cmdline_importsurvey.php b/include/limesurvey/admin/cmdline_importsurvey.php index e7e843c8..0083e329 100644 --- a/include/limesurvey/admin/cmdline_importsurvey.php +++ b/include/limesurvey/admin/cmdline_importsurvey.php @@ -1,92 +1,92 @@ - - -This is a command line LimeSurvey Survey importer. - - Usage: - php [ ] - - has to be a LimeSurvey survey dump. - and are only required if the control access is active - With the --help, -help, -h, or -? options, you can get this help. - -2)? $argv[2] : ""; - $userpass = ($argc>3)? $argv[3] : ""; -} - -if (!file_exists($the_full_file_path)) { - echo "\nThe file $the_full_file_path does not exist\n"; - exit; -} - -$_SERVER['SERVER_NAME'] = ""; // just to avoid notices -$_SERVER['SERVER_SOFTWARE'] = ""; // just to avoid notices -require_once(dirname(__FILE__).'/../config-defaults.php'); -require_once(dirname(__FILE__).'/../common.php'); - -if (isset($_REQUEST['homedir'])) {die('');} -require_once($homedir."/classes/core/sha256.php"); -$adminoutput =""; // just to avoid notices -include("database.php"); -$query = "SELECT uid, password, lang FROM ".db_table_name('users')." WHERE users_name=".$connect->qstr($username); -$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC; -$result = $connect->SelectLimit($query, 1) or die ($query."\n".$connect->ErrorMsg()); -if ($result->RecordCount() < 1) - { - // wrong or unknown username and/or email - echo "\n".$clang->gT("User name invalid!")."\n"; - exit; - } -else - { - $fields = $result->FetchRow(); - if (SHA256::hash($userpass) == $fields['password']) - { - $_SESSION['loginID'] = intval($fields['uid']); - $clang = new limesurvey_lang($fields['lang']); - - GetSessionUserRights($_SESSION['loginID']); - if (!$_SESSION['USER_RIGHT_CREATE_SURVEY']) - { - // no permission to create survey! - echo "\n".$clang->gT("You are not allowed to import a survey!")."\n"; - exit; - } - } - else - { - // password don't match username - echo "\n".$clang->gT("User name and password do not match!")."\n"; - exit; - } - } - -echo "\n"; - -$importsurvey = ""; - -$importingfrom = "cmdline"; // "http" for the web version and "cmdline" for the command line version -include("importsurvey.php"); - -?> + + +This is a command line LimeSurvey Survey importer. + + Usage: + php [ ] + + has to be a LimeSurvey survey dump. + and are only required if the control access is active + With the --help, -help, -h, or -? options, you can get this help. + +2)? $argv[2] : ""; + $userpass = ($argc>3)? $argv[3] : ""; +} + +if (!file_exists($the_full_file_path)) { + echo "\nThe file $the_full_file_path does not exist\n"; + exit; +} + +$_SERVER['SERVER_NAME'] = ""; // just to avoid notices +$_SERVER['SERVER_SOFTWARE'] = ""; // just to avoid notices +require_once(dirname(__FILE__).'/../config-defaults.php'); +require_once(dirname(__FILE__).'/../common.php'); + +if (isset($_REQUEST['homedir'])) {die('');} +require_once($homedir."/classes/core/sha256.php"); +$adminoutput =""; // just to avoid notices +include("database.php"); +$query = "SELECT uid, password, lang FROM ".db_table_name('users')." WHERE users_name=".$connect->qstr($username); +$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC; +$result = $connect->SelectLimit($query, 1) or die ($query."\n".$connect->ErrorMsg()); +if ($result->RecordCount() < 1) + { + // wrong or unknown username and/or email + echo "\n".$clang->gT("User name invalid!")."\n"; + exit; + } +else + { + $fields = $result->FetchRow(); + if (SHA256::hashing($userpass) == $fields['password']) + { + $_SESSION['loginID'] = intval($fields['uid']); + $clang = new limesurvey_lang($fields['lang']); + + GetSessionUserRights($_SESSION['loginID']); + if (!$_SESSION['USER_RIGHT_CREATE_SURVEY']) + { + // no permission to create survey! + echo "\n".$clang->gT("You are not allowed to import a survey!")."\n"; + exit; + } + } + else + { + // password don't match username + echo "\n".$clang->gT("User name and password do not match!")."\n"; + exit; + } + } + +echo "\n"; + +$importsurvey = ""; + +$importingfrom = "cmdline"; // "http" for the web version and "cmdline" for the command line version +include("importsurvey.php"); + +?> diff --git a/include/limesurvey/admin/conditions.php b/include/limesurvey/admin/conditions.php deleted file mode 100644 index da572b89..00000000 --- a/include/limesurvey/admin/conditions.php +++ /dev/null @@ -1,1049 +0,0 @@ -\n" -."\t
      " -.$clang->gT("Condition Designer")."
      \n"; - - -if (!isset($surveyid)) -{ - $conditionsoutput .= "

      " - .$clang->gT("You have not selected a Survey.")." ".$clang->gT("You cannot run this script directly.") - ."
      \n" - ."\n"; - return; -} -if (!isset($_GET['qid']) && !isset($_POST['qid'])) -{ - $conditionsoutput .= "
      " - .$clang->gT("You have not selected a Question.")." ".$clang->gT("You cannot run this script directly.") - ."
      \n" - ."\n"; - return; -} - -$markcidarray=Array(); -if (isset($_GET['markcid'])) -{ - $markcidarray=explode("-",$_GET['markcid']); - -} - -//ADD NEW ENTRY IF THIS IS AN ADD -if (isset($_POST['subaction']) && $_POST['subaction'] == "insertcondition") -{ - if ((!isset($_POST['canswers']) && - !isset($_POST['ValOrRegEx'])) || - !isset($_POST['cquestions'])) - { - $conditionsoutput .= "\n"; - } - else - { - if (isset($_POST['canswers'])) - { - foreach ($_POST['canswers'] as $ca) - { -// There I must add the indicated field for condition method -// Original -// $query = "INSERT INTO {$dbprefix}conditions (qid, cqid, cfieldname, value) VALUES " -// . "('{$_POST['qid']}', '{$_POST['cqid']}', '{$_POST['cquestions']}', '$ca')"; -// Modified - $query = "INSERT INTO {$dbprefix}conditions (qid, cqid, cfieldname, method, value) VALUES " - . "('{$_POST['qid']}', '{$_POST['cqid']}', '{$_POST['cquestions']}', '{$_POST['method']}', '$ca')"; - $result = $connect->Execute($query) or safe_die ("Couldn't insert new condition
      $query
      ".$connect->ErrorMsg()); - } - } - if (isset($_POST['ValOrRegEx']) && $_POST['ValOrRegEx']) //Remmember: '', ' ', 0 are evaluated as FALSE - { //here is saved the textarea for constants or regex - $query = "INSERT INTO {$dbprefix}conditions (qid, cqid, cfieldname, method, value) VALUES " - . "('{$_POST['qid']}', '{$_POST['cqid']}', '{$_POST['cquestions']}', '{$_POST['method']}', '{$_POST['ValOrRegEx']}')"; - $result = $connect->Execute($query) or safe_die ("Couldn't insert new condition
      $query
      ".$connect->ErrorMsg()); - } - } -} -//DELETE ENTRY IF THIS IS DELETE -if (isset($_POST['subaction']) && $_POST['subaction'] == "delete") -{ - $query = "DELETE FROM {$dbprefix}conditions WHERE cid={$_POST['cid']}"; - $result = $connect->Execute($query) or safe_die ("Couldn't delete condition
      $query
      ".$connect->ErrorMsg()); -} -//COPY CONDITIONS IF THIS IS COPY -if (isset($_POST['subaction']) && $_POST['subaction'] == "copyconditions") -{ - $qid=returnglobal('qid'); - $copyconditionsfrom=returnglobal('copyconditionsfrom'); - $copyconditionsto=returnglobal('copyconditionsto'); - if (isset($copyconditionsto) && is_array($copyconditionsto) && isset($copyconditionsfrom) && is_array($copyconditionsfrom)) - { - //Get the conditions we are going to copy - $query = "SELECT * FROM {$dbprefix}conditions\n" - ."WHERE cid in ('"; - $query .= implode("', '", $copyconditionsfrom); - $query .= "')"; - $result = db_execute_assoc($query) or safe_die("Couldn't get conditions for copy
      $query
      ".$connect->ErrorMsg()); - while($row=$result->FetchRow()) - { - $proformaconditions[]=array("cqid"=>$row['cqid'], - "cfieldname"=>$row['cfieldname'], - "method"=>$row['method'], - "value"=>$row['value']); - } // while - foreach ($copyconditionsto as $copyc) - { - list($newsid, $newgid, $newqid)=explode("X", $copyc); - foreach ($proformaconditions as $pfc) - { - //First lets make sure there isn't already an exact replica of this condition - $query = "SELECT * FROM {$dbprefix}conditions\n" - ."WHERE qid='$newqid'\n" - ."AND cqid='".$pfc['cqid']."'\n" - ."AND cfieldname='".$pfc['cfieldname']."'\n" - ."AND method='".$pfc['method']."'\n" - ."AND value='".$pfc['value']."'"; - $result = $connect->Execute($query) or safe_die("Couldn't check for existing condition
      $query
      ".$connect->ErrorMsg()); - $count = $result->RecordCount(); - if ($count == 0) //If there is no match, add the condition. - { - $query = "INSERT INTO {$dbprefix}conditions ( qid,cqid,cfieldname,method,value) \n" - ."VALUES ( '$newqid', '".$pfc['cqid']."'," - ."'".$pfc['cfieldname']."', '".$pfc['method']."'," - ."'".$pfc['value']."')"; - $result=$connect->Execute($query) or safe_die ("Couldn't insert query
      $query
      ".$connect->ErrorMsg()); - } - } - } - } - else - { - $message = $clang->gT("Did not copy questions","js").": "; - if (!isset($copyconditionsfrom)) - { - $message .= $clang->gT("No condition selected to copy from","js").". "; - } - if (!isset($copyconditionsto)) - { - $message .= $clang->gT("No question selected to copy condition to","js")."."; - } - $conditionsoutput .= "\n"; - } -} - -unset($cquestions); -unset($canswers); - - -// ******************************************************************* -// ** ADD FORM -// ******************************************************************* -//1: Get information for this question -if (!isset($qid)) {$qid=returnglobal('qid');} -if (!isset($surveyid)) {$surveyid=returnglobal('sid');} - -$query = "SELECT * " - ."FROM {$dbprefix}questions, " - ."{$dbprefix}groups " - ."WHERE {$dbprefix}questions.gid={$dbprefix}groups.gid " - ."AND qid=$qid " - ."AND {$dbprefix}questions.language='".GetBaseLanguageFromSurveyID($surveyid)."'" ; -$result = db_execute_assoc($query) or safe_die ("Couldn't get information for question $qid
      $query
      ".$connect->ErrorMsg()); -while ($rows=$result->FetchRow()) -{ - $questiongroupname=$rows['group_name']; - $questiontitle=$rows['title']; - $questiontext=$rows['question']; - $questiontype=$rows['type']; -} - -//2: Get all other questions that occur before this question that are pre-determined answer types - -//TO AVOID NATURAL SORT ORDER ISSUES, -//FIRST GET ALL QUESTIONS IN NATURAL SORT ORDER -//, AND FIND OUT WHICH NUMBER IN THAT ORDER THIS QUESTION IS -$qquery = "SELECT * " - ."FROM {$dbprefix}questions, " - ."{$dbprefix}groups " - ."WHERE {$dbprefix}questions.gid={$dbprefix}groups.gid " - ."AND {$dbprefix}questions.sid=$surveyid " - ."AND {$dbprefix}questions.language='".GetBaseLanguageFromSurveyID($surveyid)."' " - ."AND {$dbprefix}groups.language='".GetBaseLanguageFromSurveyID($surveyid)."' " ; - -$qresult = db_execute_assoc($qquery) or safe_die ("$qquery
      ".$connect->ErrorMsg()); -$qrows = $qresult->GetRows(); -// Perform a case insensitive natural sort on group name then question title (known as "code" in the form) of a multidimensional array -usort($qrows, 'CompareGroupThenTitle'); - -$position="before"; -//Go through each question until we reach the current one -foreach ($qrows as $qrow) -{ - if ($qrow["qid"] != $qid && $position=="before") - { - if ($qrow['type'] != "UNSUPPORTEDTYPE") - { - // There is currently no unsupported question - // type for use in conditions - // So remember the questions of this type - $questionlist[]=$qrow["qid"]; - } - } - elseif ($qrow["qid"] == $qid) - { - break; - } -} - -//Now, using the same array which is now properly sorted by group then question -//Create an array of all the questions that appear AFTER the current one -$position = "before"; -foreach ($qrows as $qrow) //Go through each question until we reach the current one -{ - if ($qrow["qid"] == $qid) - { - $position="after"; - //break; - } - elseif ($qrow["qid"] != $qid && $position=="after") - { - $postquestionlist[]=$qrow['qid']; - } -} - -$theserows=array(); - -if (isset($questionlist) && is_array($questionlist)) -{ - foreach ($questionlist as $ql) - { - $query = "SELECT {$dbprefix}questions.qid, " - ."{$dbprefix}questions.sid, " - ."{$dbprefix}questions.gid, " - ."{$dbprefix}questions.question, " - ."{$dbprefix}questions.type, " - ."{$dbprefix}questions.lid, " - ."{$dbprefix}questions.lid1, " - ."{$dbprefix}questions.title, " - ."{$dbprefix}questions.other, " - ."{$dbprefix}questions.mandatory " - ."FROM {$dbprefix}questions, " - ."{$dbprefix}groups " - ."WHERE {$dbprefix}questions.gid={$dbprefix}groups.gid " - ."AND {$dbprefix}questions.qid=$ql " - ."AND {$dbprefix}questions.language='".GetBaseLanguageFromSurveyID($surveyid)."' " - ."AND {$dbprefix}groups.language='".GetBaseLanguageFromSurveyID($surveyid)."'" ; - - $result=db_execute_assoc($query) or die("Couldn't get question $qid"); - - $thiscount=$result->RecordCount(); - - // And store again these questions in this array... - while ($myrows=$result->FetchRow()) - { //key => value - $theserows[]=array("qid"=>$myrows['qid'], - "sid"=>$myrows['sid'], - "gid"=>$myrows['gid'], - "question"=>$myrows['question'], - "type"=>$myrows['type'], - "lid"=>$myrows['lid'], - "lid1"=>$myrows['lid1'], - "mandatory"=>$myrows['mandatory'], - "other"=>$myrows['other'], - "title"=>$myrows['title']); - } - } -} - -if (isset($postquestionlist) && is_array($postquestionlist)) -{ - foreach ($postquestionlist as $pq) - { - $query = "SELECT {$dbprefix}questions.qid, " - ."{$dbprefix}questions.sid, " - ."{$dbprefix}questions.gid, " - ."{$dbprefix}questions.question, " - ."{$dbprefix}questions.type, " - ."{$dbprefix}questions.lid, " - ."{$dbprefix}questions.lid1, " - ."{$dbprefix}questions.title, " - ."{$dbprefix}questions.other, " - ."{$dbprefix}questions.mandatory " - ."FROM {$dbprefix}questions, " - ."{$dbprefix}groups " - ."WHERE {$dbprefix}questions.gid={$dbprefix}groups.gid AND " - ."{$dbprefix}questions.qid=$pq AND " - ."{$dbprefix}questions.language='".GetBaseLanguageFromSurveyID($surveyid)."'" ; - - $result = db_execute_assoc($query) or safe_die("Couldn't get postquestions $qid
      $query
      ".$connect->ErrorMsg()); - - $postcount=$result->RecordCount(); - - while($myrows=$result->FetchRow()) - { - $postrows[]=array("qid"=>$myrows['qid'], - "sid"=>$myrows['sid'], - "gid"=>$myrows['gid'], - "question"=>$myrows['question'], - "type"=>$myrows['type'], - "lid"=>$myrows['lid'], - "lid1"=>$myrows['lid1'], - "mandatory"=>$myrows['mandatory'], - "other"=>$myrows['other'], - "title"=>$myrows['title']); - } // while - } - $postquestionscount=count($postrows); -} - -$questionscount=count($theserows); - -if (isset($postquestionscount) && $postquestionscount > 0) //Build the select box for questions after this one -{ - foreach ($postrows as $pr) - { - $pquestions[]=array("text"=>$pr['title'].": ".substr($pr['question'], 0, 30), - "fieldname"=>$pr['sid']."X".$pr['gid']."X".$pr['qid']); - } -} - -if ($questionscount > 0) -{ - $X="X"; - // Will detect if the questions are type D to use latter - - $dquestions=array(); - - foreach($theserows as $rows) - { - $shortquestion=$rows['title'].": ".strip_tags($rows['question']); - - if ($rows['type'] == "A" || - $rows['type'] == "B" || - $rows['type'] == "C" || - $rows['type'] == "E" || - $rows['type'] == "F" || - $rows['type'] == "H") - { - $aquery="SELECT * " - ."FROM {$dbprefix}answers " - ."WHERE qid={$rows['qid']} " - ."AND {$dbprefix}answers.language='".GetBaseLanguageFromSurveyID($surveyid)."' " - ."ORDER BY sortorder, " - ."answer"; - - $aresult=db_execute_assoc($aquery) or safe_die ("Couldn't get answers to Array questions
      $aquery
      ".$connect->ErrorMsg()); - - while ($arows = $aresult->FetchRow()) - { - $shortanswer = strip_tags($arows['answer']); - - $shortanswer .= " [{$arows['code']}]"; - $cquestions[]=array("$shortquestion [$shortanswer]", $rows['qid'], $rows['type'], $rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['code']); - - switch ($rows['type']) - { - case "A": //Array 5 buttons - for ($i=1; $i<=5; $i++) - { - $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['code'], $i, $i); - } - break; - case "B": //Array 10 buttons - for ($i=1; $i<=10; $i++) - { - $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['code'], $i, $i); - } - break; - case "C": //Array Y/N/NA - $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['code'], "Y", $clang->gT("Yes")); - $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['code'], "U", $clang->gT("Uncertain")); - $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['code'], "N", $clang->gT("No")); - break; - case "E": //Array >/=/< - $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['code'], "I", $clang->gT("Increase")); - $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['code'], "S", $clang->gT("Same")); - $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['code'], "D", $clang->gT("Decrease")); - break; - case "F": //Array Flexible Row - case "H": //Array Flexible Column - $fquery = "SELECT * " - ."FROM {$dbprefix}labels " - ."WHERE lid={$rows['lid']} " - ."AND language='".GetBaseLanguageFromSurveyID($surveyid)."' " - ."ORDER BY sortorder, code "; - $fresult = db_execute_assoc($fquery); - while ($frow=$fresult->FetchRow()) - { - $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['code'], $frow['code'], $frow['title']); - } - break; - } - // Only Show No-Answer if question is not mandatory - if ($rows['mandatory'] != 'Y') - { - $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['code'], "", $clang->gT("No answer")); - } - } //while - } //if A,B,C,E,F,H - elseif ($rows['type'] == "1") //Multi Scale - { - $aquery="SELECT * " - ."FROM {$dbprefix}answers " - ."WHERE qid={$rows['qid']} " - ."AND {$dbprefix}answers.language='".GetBaseLanguageFromSurveyID($surveyid)."' " - ."ORDER BY sortorder, " - ."answer"; - $aresult=db_execute_assoc($aquery) or safe_die ("Couldn't get answers to Array questions
      $aquery
      ".$connect->ErrorMsg()); - - while ($arows = $aresult->FetchRow()) - { - $shortanswer = strip_tags($arows['answer']); - $shortanswer .= "[[Label 1]{$arows['code']}]"; - $cquestions[]=array("$shortquestion [$shortanswer]", $rows['qid'], $rows['type'], $rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['code']."#0"); - - $shortanswer = strip_tags($arows['answer']); - $shortanswer .= "[[Label 2]{$arows['code']}]"; - $cquestions[]=array("$shortquestion [$shortanswer]", $rows['qid'], $rows['type'], $rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['code']."#1"); - - // first label - $lquery="SELECT * " - ."FROM {$dbprefix}labels " - ."WHERE lid={$rows['lid']} " - ."AND {$dbprefix}labels.language='".GetBaseLanguageFromSurveyID($surveyid)."' " - ."ORDER BY sortorder, " - ."lid"; - $lresult=db_execute_assoc($lquery) or safe_die ("Couldn't get labels to Array
      $lquery
      ".$connect->ErrorMsg()); - while ($lrows = $lresult->FetchRow()) - { - $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['code']."#0", "{$lrows['code']}", "{$lrows['code']}"); - } - - // second label - $lquery="SELECT * " - ."FROM {$dbprefix}labels " - ."WHERE lid={$rows['lid1']} " - ."AND {$dbprefix}labels.language='".GetBaseLanguageFromSurveyID($surveyid)."' " - ."ORDER BY sortorder, " - ."lid"; - $lresult=db_execute_assoc($lquery) or safe_die ("Couldn't get labels to Array
      $lquery
      ".$connect->ErrorMsg()); - while ($lrows = $lresult->FetchRow()) - { - $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['code']."#1", "{$lrows['code']}", "{$lrows['code']}"); - } - - // Only Show No-Answer if question is not mandatory - if ($rows['mandatory'] != 'Y') - { - $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['code']."#0", "", $clang->gT("No answer")); - $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['code']."#1", "", $clang->gT("No answer")); - } - } //while - } - elseif ($rows['type'] == "K" ||$rows['type'] == "Q") //Multi shorttext/numerical - { - $aquery="SELECT * " - ."FROM {$dbprefix}answers " - ."WHERE qid={$rows['qid']} " - ."AND {$dbprefix}answers.language='".GetBaseLanguageFromSurveyID($surveyid)."' " - ."ORDER BY sortorder, " - ."answer"; - $aresult=db_execute_assoc($aquery) or safe_die ("Couldn't get answers to Array questions
      $aquery
      ".$connect->ErrorMsg()); - - while ($arows = $aresult->FetchRow()) - { - $shortanswer = strip_tags($arows['answer']); - $shortanswer .= "[{$arows['code']}]"; - $cquestions[]=array("$shortquestion [$shortanswer]", $rows['qid'], $rows['type'], $rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['code']); - - // Only Show No-Answer if question is not mandatory - if ($rows['mandatory'] != 'Y') - { - $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['code'], "", $clang->gT("No answer")); - } - } //while - } - elseif ($rows['type'] == "R") //Answer Ranking - { - $aquery="SELECT * " - ."FROM {$dbprefix}answers " - ."WHERE qid={$rows['qid']} " - ."AND ".db_table_name('answers').".language='".GetBaseLanguageFromSurveyID($surveyid)."' " - ."ORDER BY sortorder, answer"; - $aresult=db_execute_assoc($aquery) or safe_die ("Couldn't get answers to Ranking question
      $aquery
      ".$connect->ErrorMsg()); - $acount=$aresult->RecordCount(); - while ($arow=$aresult->FetchRow()) - { - $theanswer = addcslashes($arow['answer'], "'"); - $quicky[]=array($arow['code'], $theanswer); - } - for ($i=1; $i<=$acount; $i++) - { - $cquestions[]=array("$shortquestion [RANK $i]", $rows['qid'], $rows['type'], $rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$i); - foreach ($quicky as $qck) - { - $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$i, $qck[0], $qck[1]); - } - // Only Show No-Answer if question is not mandatory - if ($rows['mandatory'] != 'Y') - { - $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$i, " ", $clang->gT("No answer")); - } - } - unset($quicky); - } // End if type R - else - { - $cquestions[]=array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'].$X.$rows['gid'].$X.$rows['qid']); - switch ($rows['type']) - { - case "Y": // Y/N/NA - $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'], "Y", $clang->gT("Yes")); - $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'], "N", $clang->gT("No")); - // Only Show No-Answer if question is not mandatory - if ($rows['mandatory'] != 'Y') - { - $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'], " ", $clang->gT("No answer")); - } - break; - case "G": //Gender - $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'], "F", $clang->gT("Female")); - $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'], "M", $clang->gT("Male")); - // Only Show No-Answer if question is not mandatory - if ($rows['mandatory'] != 'Y') - { - $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'], " ", $clang->gT("No answer")); - } - break; - case "5": // 5 choice - for ($i=1; $i<=5; $i++) - { - $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'], $i, $i); - } - // Only Show No-Answer if question is not mandatory - if ($rows['mandatory'] != 'Y') - { - $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'], " ", $clang->gT("No answer")); - } - break; - case "W": // List Flexibel Label Dropdown - case "Z": // List Flexible Radio Button - $fquery = "SELECT * FROM {$dbprefix}labels\n" - . "WHERE lid={$rows['lid']} AND language='".GetBaseLanguageFromSurveyID($surveyid)."' " - . "ORDER BY sortorder, code"; - - $fresult = db_execute_assoc($fquery); - - if (!isset($arows['code'])) {$arows['code']='';} // for some questions types there is no code - while ($frow=$fresult->FetchRow()) - { - $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['code'], $frow['code'], $frow['title']); - } - // Only Show No-Answer if question is not mandatory - if ($rows['mandatory'] != 'Y') - { - $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'], " ", $clang->gT("No answer")); - } - break; - default: - $aquery="SELECT * " - ."FROM {$dbprefix}answers " - ."WHERE qid={$rows['qid']} " - ."AND language='".GetBaseLanguageFromSurveyID($surveyid)."' " - ."ORDER BY sortorder, " - ."answer"; - // Ranking question? Replacing "Ranking" by "this" - $aresult=db_execute_assoc($aquery) or safe_die ("Couldn't get answers to this question
      $aquery
      ".$connect->ErrorMsg()); - - while ($arows=$aresult->FetchRow()) - { - $theanswer = addcslashes($arows['answer'], "'"); - $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'], $arows['code'], $theanswer); - } - if ($rows['type'] == "D") - { - // Only Show No-Answer if question is not mandatory - if ($rows['mandatory'] != 'Y') - { - $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'], " ", $clang->gT("No answer")); - } - - // Now, save the questions type D only, then - // it don´t need pass by all the array elements... - $dquestions[]=$rows; - - // offer previous date questions to compare - foreach ($dquestions as $dq) - { - if ($rows['qid'] != $dq['qid'] && - $dq['type'] == "D") - { // Can´t compare with the same question, and only if are D - // The question tittle is enclossed by @ to be identified latter - // and be processed accordingly - $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'], "@".$dq['title']."@", $dq['title'].": ".$dq['question']); - } - } - } - elseif ($rows['type'] != "M" && - $rows['type'] != "P" && - $rows['type'] != "J" && - $rows['type'] != "I" ) - { - // For dropdown questions - // optinnaly add the 'Other' answer - if ( ($rows['type'] == "L" || - $rows['type'] == "!") && - $rows['other'] == "Y") - { - $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'], "-oth-", $clang->gT("Other")); - } - - // Only Show No-Answer if question is not mandatory - if ($rows['mandatory'] != 'Y') - { - $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'], " ", $clang->gT("No answer")); - } - } - break; - // types X,D,!,0,Q,N,S,T,U,^ just have an option as "No Answer" originally - // but now if type is D could have a list of questions D after it. - }//switch row type - } //else - } //foreach theserows -} //if questionscount > 0 - -// Now I´ll add a hack to add the questions before as option -// if they are date type - -//JAVASCRIPT TO SHOW MATCHING ANSWERS TO SELECTED QUESTION -$conditionsoutput .= "\n"; - -//SHOW FORM TO CREATE IT! -$conditionsoutput .= "\n" -."\t\n" -."\t\t\n" -."\t\n"; - -//3: Get other conditions currently set for this question -$query = "SELECT {$dbprefix}conditions.cid, " - ."{$dbprefix}conditions.cqid, " - ."{$dbprefix}conditions.cfieldname, " - ."{$dbprefix}conditions.method, " - ."{$dbprefix}conditions.value, " - ."{$dbprefix}questions.type " - ."FROM {$dbprefix}conditions, " - ."{$dbprefix}questions " - ."WHERE {$dbprefix}conditions.cqid={$dbprefix}questions.qid " - ."AND {$dbprefix}questions.language='".GetBaseLanguageFromSurveyID($surveyid)."' " - ."AND {$dbprefix}conditions.qid=$qid\n" - ."ORDER BY {$dbprefix}conditions.cfieldname"; -$result = db_execute_assoc($query) or safe_die ("Couldn't get other conditions for question $qid
      $query
      ".$connect->ErrorMsg()); -$conditionscount=$result->RecordCount(); - -// this array will be used soon, -// to explain wich conditions is used to evaluate the question -$method = array( "<" => $clang->gT("Less than"), - "<=" => $clang->gT("Less than or Equal to"), - "==" => $clang->gT("Equals"), - "!=" => $clang->gT("Not Equal to"), - ">=" => $clang->gT("Greater than or Equal to"), - ">" => $clang->gT("Greater than"), - "RX" => $clang->gT("Regular Expression") - ); - -if ($conditionscount > 0) -{ - while ($rows=$result->FetchRow()) - { - if($rows['method'] == "") {$rows['method'] = "==";} //Fill in the empty method from previous versions - if (is_null(array_search($rows['cid'], $markcidarray)) || // PHP4 - array_search($rows['cid'], $markcidarray) === FALSE) // PHP5 - // === required cause key 0 would otherwise be interpreted as FALSE - { - $markcidstyle=""; - } - else { - $markcidstyle="background-color: #5670A1;"; - } - - if (isset($currentfield) && $currentfield != $rows['cfieldname']) - { - $conditionsoutput .= "\t\t\t\t\n" - ."\t\t\t\t\t\n" - ."\t\t\t\t\t\n" - ."\t\n"; - $currentfield=$rows['cfieldname']; - } - $conditionsoutput .= "\t\n" - ."\t\t\n" - ."\t\n"; -} -else -{ - $conditionsoutput .= "\t\n" - ."\t\t\n" - ."\t\n"; -} - -$conditionsoutput .= "\t\n"; - -if ($conditionscount > 0 && isset($postquestionscount) && $postquestionscount > 0) -{ - $conditionsoutput .= "\n" - ."\t\n"; -} - -$conditionsoutput .= "
      \n"; -$showreplace="$questiontitle". showSpeaker($questiontext); -$onlyshow=str_replace("{QID}", $showreplace, $clang->gT("Only show question {QID} IF")); -$conditionsoutput .= "\t\t\t$onlyshow\n" -."\t\t
      \n" - ."" - .$clang->gT("and").""; - } - elseif (isset($currentfield)) - { - $conditionsoutput .= "\t\t\t\t
      \n" - ."" - .$clang->gT("OR").""; - } - $conditionsoutput .= "\t
      \n" - ."\t\t\n" - ."\t\t\t\n" - ."\t\t\t\t\n" - ."\t\t\t\t\t" - .$method[$rows['method']] - ."\t\t\t\t\t\t\n" - ."\t\t\t\t\t\n" - ."\n" - ."\t\t\t\t\t\n" - ."\t\t\t\t\t\n" - ."\t
      \n" - ."\t\t\t\t\t\n"; - //BUILD FIELDNAME? - foreach ($cquestions as $cqn) - { - if ($cqn[3] == $rows['cfieldname']) - { - $conditionsoutput .= "\t\t\t$cqn[0] (qid{$rows['cqid']})\n"; - $conditionsList[]=array("cid"=>$rows['cid'], - "text"=>$cqn[0]." ({$rows['value']})"); - } - else - { - //$conditionsoutput .= "\t\t\tERROR: Delete this condition. It is out of order.\n"; - } - } - - $conditionsoutput .= "\t\t\t\t\t\n" - ."\t\t\t\t\t\t\n" // .$clang->gT("Equals")."\n" - ."\t\t\t\t\t\t\n"; - // Here will be searched the conditional answer for this question - // this conditional part is the labeled one - // But there is another kind of condition - // the specified in ValOrRegEx and is in $rows['value'] - $bHasAnswer = false; - foreach ($canswers as $can) - { - //$conditionsoutput .= $rows['cfieldname'] . "- $can[0]
      "; - //$conditionsoutput .= $can[1]; - if ($can[0] == $rows['cfieldname'] && $can[1] == $rows['value']) - { - $conditionsoutput .= "\t\t\t\t\t\t$can[2] ($can[1])\n"; - $bHasAnswer = true; - } - } - if (!$bHasAnswer) - { - if ($rows['value'] == ' ' || - $rows['value'] == '') - { - $conditionsoutput .= "\t\t\t\t\t\t".$clang->gT("No Answer")."\n"; - } - else - { - $conditionsoutput .= "\t\t\t\t\t\t".$rows['value']."\n"; - } - } - $conditionsoutput .= "\t\t\t\t\t
      \n" - ."\t\t\t\t\t\t\n" - ."\t\t\t\t\t\n" - ."\t\t\t\t\t\n" - ."\t\t\t\t\t\n" - ."\t\t\t\t\t\n" - ."\t\t\t\t\t
      \n" - ."\t
      \n" - ."\t\t
      \n" - ."\t\t
      \n"; - - $conditionsoutput .= "\t\n" - ."\t\t\n" - ."\t\n"; - - $conditionsoutput .= "\t\n" - ."\t\t\n" - ."\t\n"; - - $conditionsoutput .= "\t\n" - ."\t\t\n" - ."\t\t\n" - ."\t\t\n" - ."\t\n"; - - $conditionsoutput .= "\t
      \n" - ."\t\t" - .$clang->gT("Copy Conditions")."\n" - ."\t\t
      ".$clang->gT("Condition")."".$clang->gT("Question")."
      \n" - ."\t\t\n" - ."\t\t\n" - ."\t\t".$clang->gT("copy to")."\n" - ."\t\t\n" - ."\t\t\n"; - $conditionsoutput .= "\t\t
      \n" - ."gT("Are you sure you want to copy these condition(s) to the questions you have selected?","js")."')\" />" - ."\t\t\n"; - - $conditionsoutput .= "\n" - ."\n" - ."\n" - ."
      \n"; - - $conditionsoutput .= "\t
      \n"; -$qcount=isset($cquestions) ? count($cquestions) : 0; -$conditionsoutput .= "
      \n"; -$conditionsoutput .= "\n"; -$conditionsoutput .= "\t\n" -."\t\t\n" -."\t\n" -."\t\n" -."\t\t\n" -."\t\t\n" -."\t\t\n" -."\t\n" -."\t\n" -."\t\t\n" -."\t\t" -."\t\n" -."\t\n" -."\t\t\n" -."\t\n" -."
      \n" -."\t\t\t".$clang->gT("Add Condition")."\n" -."\t\t
      \n" -."\t\t\t".$clang->gT("Question")."\n" -."\t\t\n" -."\t\t\n" -."\t\t\t".$clang->gT("Answer")."\n" -."\t\t
      \n" -."\t\t\t\n"; -// Originally was planned to do that: -//$conditionsoutput .= "\t\t\t\n"; -// ---------------------------------------- -// Perhaps was leaved for this time with -//$conditionsoutput .= "\t\t\t".$clang->gT("Equals")."\n" -// Here I go -$conditionsoutput .= "\t\t\t
      \n"; -$conditionsoutput .= "\t\t\t
      ".$clang->gT("NOTE: If you use a pre-defined answer as your condition, only the equals or not-equal-to conditions apply.")."
      \n"; -$conditionsoutput .= "\t\t
      \n" -."\t\t\t
      \n\t\t\t\n"; -// Some one request to hidde this if it is not necesary -// It will be showed when answers array is empty -// on HTML´s JS code. I fixed that enclosing it in a div called -// CONST_RGX and it will be showed or not. -$conditionsoutput .= "" -."\t\t
      \n" -."\t\t\t\n" -."\t\t\t\n" -."\n" -."\n" -."\n" -."\n" -."\t\t
      \n" -."
      \n" -."\n"; -$conditionsoutput .= "\t\n" -."\t\n" -."\t\t\n"; -$conditionsoutput .= "\t\n" -."\t\t\n" -."\t\n"; -$conditionsoutput .= "\t\n" -."
      \n" -."\t\t
      \n" -."\t\t\t\n" -."\t\t

       \n"; - -function showSpeaker($hinttext) -{ - global $imagefiles, $clang; - $reshtml= "\"".strip_tags($hinttext)."\"gT("Question","js").": ".javascript_escape($hinttext,true,true)."')\" />"; - return $reshtml; -} - - -?> diff --git a/include/limesurvey/admin/conditionshandling.php b/include/limesurvey/admin/conditionshandling.php new file mode 100644 index 00000000..4dce7d0f --- /dev/null +++ b/include/limesurvey/admin/conditionshandling.php @@ -0,0 +1,2072 @@ + $val) + { + $p_canswers[$key]= preg_replace("/[^_.a-zA-Z0-9]@/", "", $val); + } + } +} +if (isset($_POST['method'])) +{ + if (!in_array($_POST['method'], array('<','<=','>','>=','==','!=','RX'))) + { + $p_method = "=="; + } + else + { + $p_method = trim ($_POST['method']); + } +} + +/** +if (isset($_POST['ConditionConst'])) +{ + $html_ConditionConst = html_escape(auto_unescape($_POST['ConditionConst'])); +} +if (isset($_POST['prevQuestionSGQA'])) +{ + $html_prevQuestionSGQA = html_escape(auto_unescape($_POST['prevQuestionSGQA'])); +} +if (isset($_POST['tokenAttr'])) +{ + $html_tokenAttr = html_escape(auto_unescape($_POST['tokenAttr'])); +} +if (isset($_POST['ConditionRegexp'])) +{ + $html_ConditionRegexp = html_escape(auto_unescape($_POST['ConditionRegexp'])); +} +if (isset($_POST['csrctoken'])) +{ + $html_csrctoken = html_escape(auto_unescape($_POST['csrctoken'])); +} +**/ + +if (isset($_POST['newscenarionum'])) +{ + $p_newscenarionum = sanitize_int($_POST['newscenarionum']); +} +//END Sanitizing POSTed data + +include_once("login_check.php"); +include_once("database.php"); + + +$conditionsoutput = ""; + +// add the conditions container table +$conditionsoutput .= "\n" + ."\t\n" + ."
      \n"; + +//MAKE SURE THAT THERE IS A SID +if (!isset($surveyid) || !$surveyid) +{ + $conditionsoutput .= "\t
      " + .$clang->gT("Conditions manager").":

      " + .$clang->gT("Error")."
      ".$clang->gT("You have not selected a survey")."

      " + ."

      \n" + ."\n"; + return; +} + +//MAKE SURE THAT THERE IS A QID +if (!isset($qid) || !$qid) +{ + $conditionsoutput .= "\t" + .$clang->gT("Conditions manager").":\n" + ."\t
      " + .$clang->gT("Error")."
      ".$clang->gT("You have not selected a question")."

      " + ."

      \n" + ."\n" + ."\n"; + return; +} + + $conditionsoutput .= "\t
      \n" + ."

      " + ."\n"; + + +$markcidarray=Array(); +if (isset($_GET['markcid'])) +{ + $markcidarray=explode("-",$_GET['markcid']); +} + + +//BEGIN PROCESS ACTIONS +// ADD NEW ENTRY IF THIS IS AN ADD +if (isset($p_subaction) && $p_subaction == "insertcondition") +{ + if ((!isset($p_canswers) && + !isset($_POST['ConditionConst']) && + !isset($_POST['prevQuestionSGQA']) && + !isset($_POST['tokenAttr']) && + !isset($_POST['ConditionRegexp'])) || + (!isset($p_cquestions) && !isset($p_csrctoken))) + { + $conditionsoutput .= "\n"; + } + else + { + if (isset($p_cquestions) && $p_cquestions != '') + { + $conditionCfieldname=$p_cquestions; + } + elseif(isset($p_csrctoken) && $p_csrctoken != '') + { + $conditionCfieldname=$p_csrctoken; + } + + if (isset($p_canswers)) + { + foreach ($p_canswers as $ca) + { + $query = "INSERT INTO {$dbprefix}conditions (qid, scenario, cqid, cfieldname, method, value) VALUES " + . "('{$qid}', '{$p_scenario}', '{$p_cqid}', '{$conditionCfieldname}', '{$p_method}', '$ca')"; + $result = $connect->Execute($query) or safe_die ("Couldn't insert new condition
      $query
      ".$connect->ErrorMsg()); + } + } + + unset($posted_condition_value); + if (isset($_POST['ConditionConst']) && $_POST['ConditionConst']!='') + { + $posted_condition_value = $connect->qstr($_POST['ConditionConst'],get_magic_quotes_gpc()); + } + elseif (isset($_POST['prevQuestionSGQA']) && $_POST['prevQuestionSGQA']!='') + { + $posted_condition_value = $connect->qstr($_POST['prevQuestionSGQA'],get_magic_quotes_gpc()); + } + elseif (isset($_POST['tokenAttr']) && $_POST['tokenAttr']!='') + { + $posted_condition_value = $connect->qstr($_POST['tokenAttr'],get_magic_quotes_gpc()); + } + elseif (isset($_POST['ConditionRegexp']) && $_POST['ConditionRegexp']!='') + { + $posted_condition_value = $connect->qstr($_POST['ConditionRegexp'],get_magic_quotes_gpc()); + } + + if (isset($posted_condition_value)) + { + $query = "INSERT INTO {$dbprefix}conditions (qid, scenario, cqid, cfieldname, method, value) VALUES " + . "('{$qid}', '{$p_scenario}', '{$p_cqid}', '{$conditionCfieldname}', '{$p_method}', ".$posted_condition_value.")"; + $result = $connect->Execute($query) or safe_die ("Couldn't insert new condition
      $query
      ".$connect->ErrorMsg()); + } + } +} + +// UPDATE ENTRY IF THIS IS AN EDIT +if (isset($p_subaction) && $p_subaction == "updatecondition") +{ + if ((!isset($p_canswers) && + !isset($_POST['ConditionConst']) && + !isset($_POST['prevQuestionSGQA']) && + !isset($_POST['tokenAttr']) && + !isset($_POST['ConditionRegexp'])) || + (!isset($p_cquestions) && !isset($p_csrctoken))) + { + $conditionsoutput .= "\n"; + } + else + { + if (isset($p_cquestions) && $p_cquestions != '') + { + $conditionCfieldname=$p_cquestions; + } + elseif(isset($p_csrctoken) && $p_csrctoken != '') + { + $conditionCfieldname=$p_csrctoken; + } + + if (isset($p_canswers)) + { + foreach ($p_canswers as $ca) + { // This is an Edit, there will only be ONE VALUE + $query = "UPDATE {$dbprefix}conditions SET qid='{$qid}', scenario='{$p_scenario}', cqid='{$p_cqid}', cfieldname='{$conditionCfieldname}', method='{$p_method}', value='$ca' " + . " WHERE cid={$p_cid}"; + $result = $connect->Execute($query) or safe_die ("Couldn't update condition
      $query
      ".$connect->ErrorMsg()); + } + } + + unset($posted_condition_value); + if (isset($_POST['ConditionConst']) && $_POST['ConditionConst']!='') + { + $posted_condition_value = $connect->qstr($_POST['ConditionConst'],get_magic_quotes_gpc()); + } + elseif (isset($_POST['prevQuestionSGQA']) && $_POST['prevQuestionSGQA']!='') + { + $posted_condition_value = $connect->qstr($_POST['prevQuestionSGQA'],get_magic_quotes_gpc()); + } + elseif (isset($_POST['tokenAttr']) && $_POST['tokenAttr']!='') + { + $posted_condition_value = $connect->qstr($_POST['tokenAttr'],get_magic_quotes_gpc()); + } + elseif (isset($_POST['ConditionRegexp']) && $_POST['ConditionRegexp']!='') + { + $posted_condition_value = $connect->qstr($_POST['ConditionRegexp'],get_magic_quotes_gpc()); + } + + if (isset($posted_condition_value)) + { + $query = "UPDATE {$dbprefix}conditions SET qid='{$qid}', scenario='{$p_scenario}' , cqid='{$p_cqid}', cfieldname='{$conditionCfieldname}', method='{$p_method}', value=".$posted_condition_value." " + . " WHERE cid={$p_cid}"; + $result = $connect->Execute($query) or safe_die ("Couldn't insert new condition
      $query
      ".$connect->ErrorMsg()); + } + } +} + +// DELETE ENTRY IF THIS IS DELETE +if (isset($p_subaction) && $p_subaction == "delete") +{ + $query = "DELETE FROM {$dbprefix}conditions WHERE cid={$p_cid}"; + $result = $connect->Execute($query) or safe_die ("Couldn't delete condition
      $query
      ".$connect->ErrorMsg()); +} + +// DELETE ALL CONDITIONS IN THIS SCENARIO +if (isset($p_subaction) && $p_subaction == "deletescenario") +{ + $query = "DELETE FROM {$dbprefix}conditions WHERE qid={$qid} AND scenario={$p_scenario}"; + $result = $connect->Execute($query) or safe_die ("Couldn't delete scenario
      $query
      ".$connect->ErrorMsg()); +} + +// UPDATE SCENARIO +if (isset($p_subaction) && $p_subaction == "updatescenario" && isset($p_newscenarionum)) +{ + $query = "UPDATE {$dbprefix}conditions SET scenario=$p_newscenarionum WHERE qid={$qid} AND scenario={$p_scenario}"; + $result = $connect->Execute($query) or safe_die ("Couldn't delete scenario
      $query
      ".$connect->ErrorMsg()); +} + +// DELETE ALL CONDITIONS FOR THIS QUESTION +if (isset($p_subaction) && $p_subaction == "deleteallconditions") +{ + $query = "DELETE FROM {$dbprefix}conditions WHERE qid={$qid}"; + $result = $connect->Execute($query) or safe_die ("Couldn't delete scenario
      $query
      ".$connect->ErrorMsg()); +} + +// RENUMBER SCENARIOS +if (isset($p_subaction) && $p_subaction == "renumberscenarios") +{ + $query = "SELECT DISTINCT scenario FROM {$dbprefix}conditions WHERE qid={$qid} ORDER BY scenario"; + $result = $connect->Execute($query) or safe_die ("Couldn't select scenario
      $query
      ".$connect->ErrorMsg()); + $newindex=1; + while ($srow = $result->FetchRow()) + { + $query2 = "UPDATE {$dbprefix}conditions set scenario=$newindex WHERE qid={$qid} AND scenario=".$srow['scenario'].";"; + $result2 = $connect->Execute($query2) or safe_die ("Couldn't renumber scenario
      $query
      ".$connect->ErrorMsg()); + $newindex++; + } + +} + +// COPY CONDITIONS IF THIS IS COPY +if (isset($p_subaction) && $p_subaction == "copyconditions") +{ + $qid=returnglobal('qid'); + $copyconditionsfrom=returnglobal('copyconditionsfrom'); + $copyconditionsto=returnglobal('copyconditionsto'); + if (isset($copyconditionsto) && is_array($copyconditionsto) && isset($copyconditionsfrom) && is_array($copyconditionsfrom)) + { + //Get the conditions we are going to copy + $query = "SELECT * FROM {$dbprefix}conditions\n" + ."WHERE cid in ('"; + $query .= implode("', '", $copyconditionsfrom); + $query .= "')"; + $result = db_execute_assoc($query) or safe_die("Couldn't get conditions for copy
      $query
      ".$connect->ErrorMsg()); + while($row=$result->FetchRow()) + { + $proformaconditions[]=array("scenario"=>$row['scenario'], + "cqid"=>$row['cqid'], + "cfieldname"=>$row['cfieldname'], + "method"=>$row['method'], + "value"=>$row['value']); + } // while + foreach ($copyconditionsto as $copyc) + { + list($newsid, $newgid, $newqid)=explode("X", $copyc); + foreach ($proformaconditions as $pfc) + { + //First lets make sure there isn't already an exact replica of this condition + $query = "SELECT * FROM {$dbprefix}conditions\n" + ."WHERE qid='$newqid'\n" + ."AND scenario='".$pfc['scenario']."'\n" + ."AND cqid='".$pfc['cqid']."'\n" + ."AND cfieldname='".$pfc['cfieldname']."'\n" + ."AND method='".$pfc['method']."'\n" + ."AND value='".$pfc['value']."'"; + $result = $connect->Execute($query) or safe_die("Couldn't check for existing condition
      $query
      ".$connect->ErrorMsg()); + $count = $result->RecordCount(); + if ($count == 0) //If there is no match, add the condition. + { + $query = "INSERT INTO {$dbprefix}conditions ( qid,scenario,cqid,cfieldname,method,value) \n" + ."VALUES ( '$newqid', '".$pfc['scenario']."', '".$pfc['cqid']."'," + ."'".$pfc['cfieldname']."', '".$pfc['method']."'," + ."'".$pfc['value']."')"; + $result=$connect->Execute($query) or safe_die ("Couldn't insert query
      $query
      ".$connect->ErrorMsg()); + $conditionCopied=true; + } + else + { + $conditionDuplicated=true; + } + } + } + if (isset($conditionCopied) && $conditionCopied === true) + { + if (isset($conditionDuplicated) && $conditionDuplicated ==true) + { + $CopyConditionsMessage = "(".$clang->gT("Conditions successfully copied (some were skipped because they were duplicates)").")"; + } + else + { + $CopyConditionsMessage = "(".$clang->gT("Conditions successfully copied").")"; + } + } + else + { + $CopyConditionsMessage = "(".$clang->gT("No conditions could be copied (due to duplicates)").")"; + } + } + else + { + $message = $clang->gT("Did not copy questions","js").": "; + if (!isset($copyconditionsfrom)) + { + $message .= $clang->gT("No condition selected to copy from","js").". "; + } + if (!isset($copyconditionsto)) + { + $message .= $clang->gT("No question selected to copy condition to","js")."."; + } + $conditionsoutput .= "\n"; + } +} +//END PROCESS ACTIONS + + + +$cquestions=Array(); +$canswers=Array(); + + + +//BEGIN: GATHER INFORMATION +// 1: Get information for this question +if (!isset($qid)) {$qid=returnglobal('qid');} +if (!isset($surveyid)) {$surveyid=returnglobal('sid');} +$thissurvey=getSurveyInfo($surveyid); + +$query = "SELECT * " + ."FROM {$dbprefix}questions, " + ."{$dbprefix}groups " + ."WHERE {$dbprefix}questions.gid={$dbprefix}groups.gid " + ."AND qid=$qid " + ."AND {$dbprefix}questions.language='".GetBaseLanguageFromSurveyID($surveyid)."'" ; +$result = db_execute_assoc($query) or safe_die ("Couldn't get information for question $qid
      $query
      ".$connect->ErrorMsg()); +while ($rows=$result->FetchRow()) +{ + $questiongroupname=$rows['group_name']; + $questiontitle=$rows['title']; + $questiontext=$rows['question']; + $questiontype=$rows['type']; +} + +// 2: Get all other questions that occur before this question that are pre-determined answer types + +// To avoid natural sort order issues, +// first get all questions in natural sort order +// , and find out which number in that order this question is +$qquery = "SELECT * " + ."FROM {$dbprefix}questions, " + ."{$dbprefix}groups " + ."WHERE {$dbprefix}questions.gid={$dbprefix}groups.gid " + ."AND {$dbprefix}questions.sid=$surveyid " + ."AND {$dbprefix}questions.language='".GetBaseLanguageFromSurveyID($surveyid)."' " + ."AND {$dbprefix}groups.language='".GetBaseLanguageFromSurveyID($surveyid)."' " ; + +$qresult = db_execute_assoc($qquery) or safe_die ("$qquery
      ".$connect->ErrorMsg()); +$qrows = $qresult->GetRows(); +// Perform a case insensitive natural sort on group name then question title (known as "code" in the form) of a multidimensional array +usort($qrows, 'CompareGroupThenTitle'); + +$position="before"; +// Go through each question until we reach the current one +foreach ($qrows as $qrow) +{ + if ($qrow["qid"] != $qid && $position=="before") + { + // remember all previous questions + // all question types are supported. + $questionlist[]=$qrow["qid"]; + } + elseif ($qrow["qid"] == $qid) + { + break; + } +} + +// Now, using the same array which is now properly sorted by group then question +// Create an array of all the questions that appear AFTER the current one +$position = "before"; +foreach ($qrows as $qrow) //Go through each question until we reach the current one +{ + if ($qrow["qid"] == $qid) + { + $position="after"; + //break; + } + elseif ($qrow["qid"] != $qid && $position=="after") + { + $postquestionlist[]=$qrow['qid']; + } +} + +$theserows=array(); +$postrows=array(); + +if (isset($questionlist) && is_array($questionlist)) +{ + foreach ($questionlist as $ql) + { + $query = "SELECT {$dbprefix}questions.qid, " + ."{$dbprefix}questions.sid, " + ."{$dbprefix}questions.gid, " + ."{$dbprefix}questions.question, " + ."{$dbprefix}questions.type, " + ."{$dbprefix}questions.lid, " + ."{$dbprefix}questions.lid1, " + ."{$dbprefix}questions.title, " + ."{$dbprefix}questions.other, " + ."{$dbprefix}questions.mandatory " + ."FROM {$dbprefix}questions, " + ."{$dbprefix}groups " + ."WHERE {$dbprefix}questions.gid={$dbprefix}groups.gid " + ."AND {$dbprefix}questions.qid=$ql " + ."AND {$dbprefix}questions.language='".GetBaseLanguageFromSurveyID($surveyid)."' " + ."AND {$dbprefix}groups.language='".GetBaseLanguageFromSurveyID($surveyid)."'" ; + + $result=db_execute_assoc($query) or die("Couldn't get question $qid"); + + $thiscount=$result->RecordCount(); + + // And store again these questions in this array... + while ($myrows=$result->FetchRow()) + { //key => value + $theserows[]=array("qid"=>$myrows['qid'], + "sid"=>$myrows['sid'], + "gid"=>$myrows['gid'], + "question"=>$myrows['question'], + "type"=>$myrows['type'], + "lid"=>$myrows['lid'], + "lid1"=>$myrows['lid1'], + "mandatory"=>$myrows['mandatory'], + "other"=>$myrows['other'], + "title"=>$myrows['title']); + } + } +} + +if (isset($postquestionlist) && is_array($postquestionlist)) +{ + foreach ($postquestionlist as $pq) + { + $query = "SELECT {$dbprefix}questions.qid, " + ."{$dbprefix}questions.sid, " + ."{$dbprefix}questions.gid, " + ."{$dbprefix}questions.question, " + ."{$dbprefix}questions.type, " + ."{$dbprefix}questions.lid, " + ."{$dbprefix}questions.lid1, " + ."{$dbprefix}questions.title, " + ."{$dbprefix}questions.other, " + ."{$dbprefix}questions.mandatory " + ."FROM {$dbprefix}questions, " + ."{$dbprefix}groups " + ."WHERE {$dbprefix}questions.gid={$dbprefix}groups.gid AND " + ."{$dbprefix}questions.qid=$pq AND " + ."{$dbprefix}questions.language='".GetBaseLanguageFromSurveyID($surveyid)."' AND " + ."{$dbprefix}groups.language='".GetBaseLanguageFromSurveyID($surveyid)."'"; + + + $result = db_execute_assoc($query) or safe_die("Couldn't get postquestions $qid
      $query
      ".$connect->ErrorMsg()); + + $postcount=$result->RecordCount(); + + while($myrows=$result->FetchRow()) + { + $postrows[]=array("qid"=>$myrows['qid'], + "sid"=>$myrows['sid'], + "gid"=>$myrows['gid'], + "question"=>$myrows['question'], + "type"=>$myrows['type'], + "lid"=>$myrows['lid'], + "lid1"=>$myrows['lid1'], + "mandatory"=>$myrows['mandatory'], + "other"=>$myrows['other'], + "title"=>$myrows['title']); + } // while + } + $postquestionscount=count($postrows); +} + +$questionscount=count($theserows); + +if (isset($postquestionscount) && $postquestionscount > 0) +{ //Build the array used for the questionNav and copyTo select boxes + foreach ($postrows as $pr) + { + $pquestions[]=array("text"=>$pr['title'].": ".substr(strip_tags($pr['question']), 0, 80), + "fieldname"=>$pr['sid']."X".$pr['gid']."X".$pr['qid']); + } +} + +// Previous question parsing ==> building cquestions[] and canswers[] +if ($questionscount > 0) +{ + $X="X"; + + foreach($theserows as $rows) + { + $shortquestion=$rows['title'].": ".strip_tags($rows['question']); + + if ($rows['type'] == "A" || + $rows['type'] == "B" || + $rows['type'] == "C" || + $rows['type'] == "E" || + $rows['type'] == "F" || + $rows['type'] == "H" ) + { + $aquery="SELECT * " + ."FROM {$dbprefix}answers " + ."WHERE qid={$rows['qid']} " + ."AND {$dbprefix}answers.language='".GetBaseLanguageFromSurveyID($surveyid)."' " + ."ORDER BY sortorder, " + ."answer"; + + $aresult=db_execute_assoc($aquery) or safe_die ("Couldn't get answers to Array questions
      $aquery
      ".$connect->ErrorMsg()); + + while ($arows = $aresult->FetchRow()) + { + $shortanswer = strip_tags($arows['answer']); + + $shortanswer .= " [{$arows['code']}]"; + $cquestions[]=array("$shortquestion [$shortanswer]", $rows['qid'], $rows['type'], $rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['code']); + + switch ($rows['type']) + { + case "A": //Array 5 buttons + for ($i=1; $i<=5; $i++) + { + $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['code'], $i, $i); + } + break; + case "B": //Array 10 buttons + for ($i=1; $i<=10; $i++) + { + $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['code'], $i, $i); + } + break; + case "C": //Array Y/N/NA + $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['code'], "Y", $clang->gT("Yes")); + $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['code'], "U", $clang->gT("Uncertain")); + $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['code'], "N", $clang->gT("No")); + break; + case "E": //Array >/=/< + $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['code'], "I", $clang->gT("Increase")); + $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['code'], "S", $clang->gT("Same")); + $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['code'], "D", $clang->gT("Decrease")); + break; + case "F": //Array Flexible Row + case "H": //Array Flexible Column + $fquery = "SELECT * " + ."FROM {$dbprefix}labels " + ."WHERE lid={$rows['lid']} " + ."AND language='".GetBaseLanguageFromSurveyID($surveyid)."' " + ."ORDER BY sortorder, code "; + $fresult = db_execute_assoc($fquery); + while ($frow=$fresult->FetchRow()) + { + $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['code'], $frow['code'], $frow['title']); + } + break; + } + // Only Show No-Answer if question is not mandatory + if ($rows['mandatory'] != 'Y') + { + $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['code'], "", $clang->gT("No answer")); + } + + } //while + } elseif ($rows['type'] == ":" || $rows['type'] == ";") { // Multiflexi + //Get question attribute for $canswers + $qidattributes=getQuestionAttributes($rows['qid']); + if ($maxvalue=arraySearchByKey("multiflexible_max", $qidattributes, "attribute", 1)) { + $maxvalue=$maxvalue['value']; + } else { + $maxvalue=10; + } + if ($minvalue=arraySearchByKey("multiflexible_min", $qidattributes, "attribute", 1)) { + $minvalue=$minvalue['value']; + } else { + $minvalue=1; + } + if ($stepvalue=arraySearchByKey("multiflexible_step", $qidattributes, "attribute", 1)) { + $stepvalue=$stepvalue['value']; + } else { + $stepvalue=1; + } + if (arraySearchByKey("multiflexible_checkbox", $qidattributes, "attribute", 1)) { + $minvalue=0; + $maxvalue=1; + $stepvalue=1; + } + //Get the LIDs + $fquery = "SELECT * " + ."FROM {$dbprefix}labels " + ."WHERE lid={$rows['lid']} " + ."AND language='".GetBaseLanguageFromSurveyID($surveyid)."' " + ."ORDER BY sortorder, code "; + $fresult = db_execute_assoc($fquery); + while ($frow=$fresult->FetchRow()) + { + $lids[$frow['code']]=$frow['title']; + } + //Now cycle through the answers + $aquery="SELECT * " + ."FROM {$dbprefix}answers " + ."WHERE qid={$rows['qid']} " + ."AND {$dbprefix}answers.language='".GetBaseLanguageFromSurveyID($surveyid)."' " + ."ORDER BY sortorder, " + ."answer"; + $aresult=db_execute_assoc($aquery) or safe_die ("Couldn't get answers to Array questions
      $aquery
      ".$connect->ErrorMsg()); + + while ($arows = $aresult->FetchRow()) + { + $shortanswer = strip_tags($arows['answer']); + + $shortanswer .= " [{$arows['code']}]"; + foreach($lids as $key=>$val) + { + $cquestions[]=array("$shortquestion [$shortanswer [$val]] ", $rows['qid'], $rows['type'], $rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['code']."_".$key); + if ($rows['type'] == ":") + { + for($ii=$minvalue; $ii<=$maxvalue; $ii+=$stepvalue) + { + $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['code']."_".$key, $ii, $ii); + } + } + } + } + + } //if A,B,C,E,F,H + elseif ($rows['type'] == "1") //Multi Scale + { + $aquery="SELECT * " + ."FROM {$dbprefix}answers " + ."WHERE qid={$rows['qid']} " + ."AND {$dbprefix}answers.language='".GetBaseLanguageFromSurveyID($surveyid)."' " + ."ORDER BY sortorder, " + ."answer"; + $aresult=db_execute_assoc($aquery) or safe_die ("Couldn't get answers to Array questions
      $aquery
      ".$connect->ErrorMsg()); + + while ($arows = $aresult->FetchRow()) + { + $shortanswer = strip_tags($arows['answer']); + $shortanswer .= "[[Label 1]{$arows['code']}]"; + $cquestions[]=array("$shortquestion [$shortanswer]", $rows['qid'], $rows['type'], $rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['code']."#0"); + + $shortanswer = strip_tags($arows['answer']); + $shortanswer .= "[[Label 2]{$arows['code']}]"; + $cquestions[]=array("$shortquestion [$shortanswer]", $rows['qid'], $rows['type'], $rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['code']."#1"); + + // first label + $lquery="SELECT * " + ."FROM {$dbprefix}labels " + ."WHERE lid={$rows['lid']} " + ."AND {$dbprefix}labels.language='".GetBaseLanguageFromSurveyID($surveyid)."' " + ."ORDER BY sortorder, " + ."lid"; + $lresult=db_execute_assoc($lquery) or safe_die ("Couldn't get labels to Array
      $lquery
      ".$connect->ErrorMsg()); + while ($lrows = $lresult->FetchRow()) + { + $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['code']."#0", "{$lrows['code']}", "{$lrows['code']}"); + } + + // second label + $lquery="SELECT * " + ."FROM {$dbprefix}labels " + ."WHERE lid={$rows['lid1']} " + ."AND {$dbprefix}labels.language='".GetBaseLanguageFromSurveyID($surveyid)."' " + ."ORDER BY sortorder, " + ."lid"; + $lresult=db_execute_assoc($lquery) or safe_die ("Couldn't get labels to Array
      $lquery
      ".$connect->ErrorMsg()); + while ($lrows = $lresult->FetchRow()) + { + $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['code']."#1", "{$lrows['code']}", "{$lrows['code']}"); + } + + // Only Show No-Answer if question is not mandatory + if ($rows['mandatory'] != 'Y') + { + $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['code']."#0", "", $clang->gT("No answer")); + $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['code']."#1", "", $clang->gT("No answer")); + } + } //while + } + elseif ($rows['type'] == "K" ||$rows['type'] == "Q") //Multi shorttext/numerical + { + $aquery="SELECT * " + ."FROM {$dbprefix}answers " + ."WHERE qid={$rows['qid']} " + ."AND {$dbprefix}answers.language='".GetBaseLanguageFromSurveyID($surveyid)."' " + ."ORDER BY sortorder, " + ."answer"; + $aresult=db_execute_assoc($aquery) or safe_die ("Couldn't get answers to Array questions
      $aquery
      ".$connect->ErrorMsg()); + + while ($arows = $aresult->FetchRow()) + { + $shortanswer = strip_tags($arows['answer']); + $shortanswer .= "[{$arows['code']}]"; + $cquestions[]=array("$shortquestion [$shortanswer]", $rows['qid'], $rows['type'], $rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['code']); + + // Only Show No-Answer if question is not mandatory + if ($rows['mandatory'] != 'Y') + { + $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['code'], "", $clang->gT("No answer")); + } + + } //while + } + elseif ($rows['type'] == "R") //Answer Ranking + { + $aquery="SELECT * " + ."FROM {$dbprefix}answers " + ."WHERE qid={$rows['qid']} " + ."AND ".db_table_name('answers').".language='".GetBaseLanguageFromSurveyID($surveyid)."' " + ."ORDER BY sortorder, answer"; + $aresult=db_execute_assoc($aquery) or safe_die ("Couldn't get answers to Ranking question
      $aquery
      ".$connect->ErrorMsg()); + $acount=$aresult->RecordCount(); + while ($arow=$aresult->FetchRow()) + { + $theanswer = addcslashes($arow['answer'], "'"); + $quicky[]=array($arow['code'], $theanswer); + } + for ($i=1; $i<=$acount; $i++) + { + $cquestions[]=array("$shortquestion [RANK $i]", $rows['qid'], $rows['type'], $rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$i); + foreach ($quicky as $qck) + { + $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$i, $qck[0], $qck[1]); + } + // Only Show No-Answer if question is not mandatory + if ($rows['mandatory'] != 'Y') + { + $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$i, " ", $clang->gT("No answer")); + } + } + unset($quicky); + } // End if type R + elseif($rows['type'] == "M" || $rows['type'] == "P") + { + $cquestions[]=array("$shortquestion [".$clang->gT("Group of checkboxes")."]", $rows['qid'], $rows['type'], $rows['sid'].$X.$rows['gid'].$X.$rows['qid']); + $aquery="SELECT * " + ."FROM {$dbprefix}answers " + ."WHERE qid={$rows['qid']} " + ."AND language='".GetBaseLanguageFromSurveyID($surveyid)."' " + ."ORDER BY sortorder, " + ."answer"; + $aresult=db_execute_assoc($aquery) or safe_die ("Couldn't get answers to this question
      $aquery
      ".$connect->ErrorMsg()); + + while ($arows=$aresult->FetchRow()) + { + $theanswer = addcslashes($arows['answer'], "'"); + $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'], $arows['code'], $theanswer); + + $shortanswer = strip_tags($arows['answer']); + $shortanswer .= "[{$arows['code']}]"; + $cquestions[]=array("$shortquestion ($shortanswer) [".$clang->gT("Single checkbox")."]", $rows['qid'], $rows['type'], "+".$rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['code']); + $canswers[]=array("+".$rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['code'], 'Y', 'checked'); + $canswers[]=array("+".$rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['code'], '', 'not checked'); + } + } + else + { + $cquestions[]=array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'].$X.$rows['gid'].$X.$rows['qid']); + switch ($rows['type']) + { + case "Y": // Y/N/NA + $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'], "Y", $clang->gT("Yes")); + $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'], "N", $clang->gT("No")); + // Only Show No-Answer if question is not mandatory + if ($rows['mandatory'] != 'Y') + { + $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'], " ", $clang->gT("No answer")); + } + break; + case "G": //Gender + $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'], "F", $clang->gT("Female")); + $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'], "M", $clang->gT("Male")); + // Only Show No-Answer if question is not mandatory + if ($rows['mandatory'] != 'Y') + { + $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'], " ", $clang->gT("No answer")); + } + break; + case "5": // 5 choice + for ($i=1; $i<=5; $i++) + { + $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'], $i, $i); + } + // Only Show No-Answer if question is not mandatory + if ($rows['mandatory'] != 'Y') + { + $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'], " ", $clang->gT("No answer")); + } + break; + case "W": // List Flexibel Label Dropdown + case "Z": // List Flexible Radio Button + $fquery = "SELECT * FROM {$dbprefix}labels\n" + . "WHERE lid={$rows['lid']} AND language='".GetBaseLanguageFromSurveyID($surveyid)."' " + . "ORDER BY sortorder, code"; + + $fresult = db_execute_assoc($fquery); + + if (!isset($arows['code'])) {$arows['code']='';} // for some questions types there is no code + while ($frow=$fresult->FetchRow()) + { + $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['code'], $frow['code'], $frow['title']); + } + // Only Show No-Answer if question is not mandatory + if ($rows['mandatory'] != 'Y') + { + $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'], " ", $clang->gT("No answer")); + } + break; + + case "N": // Simple Numerical questions + + // Only Show No-Answer if question is not mandatory + if ($rows['mandatory'] != 'Y') + { + $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'], " ", $clang->gT("No answer")); + } + break; + + default: + $aquery="SELECT * " + ."FROM {$dbprefix}answers " + ."WHERE qid={$rows['qid']} " + ."AND language='".GetBaseLanguageFromSurveyID($surveyid)."' " + ."ORDER BY sortorder, " + ."answer"; + // Ranking question? Replacing "Ranking" by "this" + $aresult=db_execute_assoc($aquery) or safe_die ("Couldn't get answers to this question
      $aquery
      ".$connect->ErrorMsg()); + + while ($arows=$aresult->FetchRow()) + { + $theanswer = addcslashes($arows['answer'], "'"); + $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'], $arows['code'], $theanswer); + } + if ($rows['type'] == "D") + { + // Only Show No-Answer if question is not mandatory + if ($rows['mandatory'] != 'Y') + { + $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'], " ", $clang->gT("No answer")); + } + } + elseif ($rows['type'] != "M" && + $rows['type'] != "P" && + $rows['type'] != "J" && + $rows['type'] != "I" ) + { + // For dropdown questions + // optinnaly add the 'Other' answer + if ( ($rows['type'] == "L" || + $rows['type'] == "!") && + $rows['other'] == "Y") + { + $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'], "-oth-", $clang->gT("Other")); + } + + // Only Show No-Answer if question is not mandatory + if ($rows['mandatory'] != 'Y') + { + $canswers[]=array($rows['sid'].$X.$rows['gid'].$X.$rows['qid'], " ", $clang->gT("No answer")); + } + } + break; + }//switch row type + } //else + } //foreach theserows +} //if questionscount > 0 +//END Gather Information for this question + +$conditionsoutput .= "\t\n" +."\t\t\n"; + +// BEGIN UPDATE THE questionNav SELECT INPUT +$conditionsoutput .= "\n"; +// END UPDATE THE questionNav SELECT INPUT + +//Now display the information and forms +//BEGIN: PREPARE JAVASCRIPT TO SHOW MATCHING ANSWERS TO SELECTED QUESTION +$conditionsoutput .= "\n"; + +$conditionsoutput .= "\n"; +//END: PREPARE JAVASCRIPT TO SHOW MATCHING ANSWERS TO SELECTED QUESTION + +//BEGIN DISPLAY CONDITIONS FOR THIS QUESTION +if ($subaction=='' || + $subaction=='editconditionsform' || $subaction=='insertcondition' || + $subaction == "editthiscondition" || $subaction == "delete" || + $subaction == "updatecondition" || $subaction == "deletescenario" || + $subaction == "renumberscenarios" || $subaction == "deleteallconditions" || + $subaction == "updatescenario" || + $subaction=='copyconditionsform' || $subaction=='copyconditions') +{ + $conditionsoutput .= "\n"; + + //3: Get other conditions currently set for this question + $conditionscount=0; + $s=0; + $scenarioquery = "SELECT DISTINCT {$dbprefix}conditions.scenario " + ."FROM {$dbprefix}conditions " + ."WHERE {$dbprefix}conditions.qid=$qid\n" + ."ORDER BY {$dbprefix}conditions.scenario"; + $scenarioresult = db_execute_assoc($scenarioquery) or safe_die ("Couldn't get other (scenario) conditions for question $qid
      $query
      ".$connect->Error); + $scenariocount=$scenarioresult->RecordCount(); + + $conditionsoutput .= "\n" + ."\t\n" + ."\t\t\n"; + + if ($scenariocount > 0) + { + $js_adminheader_includes[]= $homeurl.'/scripts/assessments.js'; + $js_adminheader_includes[]= $rooturl.'/scripts/jquery/jquery-checkgroup.js'; + while ($scenarionr=$scenarioresult->FetchRow()) + { + $scenariotext = ""; + if ($s == 0 && $scenariocount > 1) + { + $scenariotext = " -------- Scenario {$scenarionr['scenario']} --------"; + } + if ($s > 0) + { + $scenariotext = " -------- ".$clang->gT("OR")." Scenario {$scenarionr['scenario']} --------"; + } + if ($subaction == "copyconditionsform" || $subaction == "copyconditions") + { + $initialCheckbox = "\n"; + } + else + { + $initialCheckbox = ""; + } + + $conditionsoutput .= "\n"; + + unset($currentfield); + + $query = "SELECT {$dbprefix}conditions.cid, " + ."{$dbprefix}conditions.scenario, " + ."{$dbprefix}conditions.cqid, " + ."{$dbprefix}conditions.cfieldname, " + ."{$dbprefix}conditions.method, " + ."{$dbprefix}conditions.value, " + ."{$dbprefix}questions.type " + ."FROM {$dbprefix}conditions, " + ."{$dbprefix}questions " + ."WHERE {$dbprefix}conditions.cqid={$dbprefix}questions.qid " + ."AND {$dbprefix}questions.language='".GetBaseLanguageFromSurveyID($surveyid)."' " + ."AND {$dbprefix}conditions.qid=$qid " + ."AND {$dbprefix}conditions.scenario={$scenarionr['scenario']}\n" + ."AND {$dbprefix}conditions.cfieldname NOT LIKE '{%' \n" // avoid catching SRCtokenAttr conditions +// ."AND {$dbprefix}conditions.cfieldname NOT LIKE '+%' \n" // avoid catching SRCtokenAttr conditions + ."ORDER BY {$dbprefix}conditions.cfieldname"; + $result = db_execute_assoc($query) or safe_die ("Couldn't get other conditions for question $qid
      $query
      ".$connect->ErrorMsg()); + $conditionscount=$result->RecordCount(); + + $querytoken = "SELECT {$dbprefix}conditions.cid, " + ."{$dbprefix}conditions.scenario, " + ."{$dbprefix}conditions.cqid, " + ."{$dbprefix}conditions.cfieldname, " + ."{$dbprefix}conditions.method, " + ."{$dbprefix}conditions.value, " + ."'' AS type " + ."FROM {$dbprefix}conditions " + ."WHERE " + ." {$dbprefix}conditions.qid=$qid " + ."AND {$dbprefix}conditions.scenario={$scenarionr['scenario']}\n" + ."AND {$dbprefix}conditions.cfieldname LIKE '{%' \n" // only catching SRCtokenAttr conditions + ."ORDER BY {$dbprefix}conditions.cfieldname"; + $resulttoken = db_execute_assoc($querytoken) or safe_die ("Couldn't get other conditions for question $qid
      $query
      ".$connect->ErrorMsg()); + $conditionscounttoken=$resulttoken->RecordCount(); + + $conditionscount=$conditionscount+$conditionscounttoken; + + // this array will be used soon, + // to explain wich conditions is used to evaluate the question + $method = array( "<" => $clang->gT("Less than"), + "<=" => $clang->gT("Less than or equal to"), + "==" => $clang->gT("equals"), + "!=" => $clang->gT("Not equal to"), + ">=" => $clang->gT("Greater than or equal to"), + ">" => $clang->gT("Greater than"), + "RX" => $clang->gT("Regular expression") + ); + + if ($conditionscount > 0) + { + $aConditionsMerged=Array(); + while ($arow=$resulttoken->FetchRow()) + { + $aConditionsMerged[]=$arow; + } + while ($arow=$result->FetchRow()) + { + $aConditionsMerged[]=$arow; + } + +// while ($rows=$result->FetchRow()) + foreach ($aConditionsMerged as $rows) + { + if($rows['method'] == "") {$rows['method'] = "==";} //Fill in the empty method from previous versions + $markcidstyle=""; + if (array_search($rows['cid'], $markcidarray) === FALSE) // PHP5 + // === required cause key 0 would otherwise be interpreted as FALSE + { + $markcidstyle=""; + } + else { + // This is the style used when the condition editor is called + // in order to check which conditions prevent a question deletion + $markcidstyle="background-color: #5670A1;"; + } + if ($subaction == "editthiscondition" && isset($p_cid) && + $rows['cid'] === $p_cid) + { + // Style used when editing a condition + $markcidstyle="background-color: #FCCFFF;"; + } + + if (isset($currentfield) && $currentfield != $rows['cfieldname']) + { + $conditionsoutput .= "\t\t\t\t\n" + ."\t\t\t\t\t"; + } + elseif (isset($currentfield)) + { + $conditionsoutput .= "\t\t\t\t\n" + ."\t\t\t\t\t"; + } + $conditionsoutput .= "\t\n" + ."\t\n"; + $currentfield=$rows['cfieldname']; + } + $conditionsoutput .= "\t\n" + ."\t\t\n" + ."\t\n"; + } + else + { + $conditionsoutput .= "\t\n" + ."\t\t\n" + ."\t\n"; + } + $s++; + } + } + else + { // no condition ==> disable delete all conditions button, and display a simple comment + $conditionsoutput .= "\n"; + } + $conditionsoutput .= "" + . "
      \n"; + $showreplace="$questiontitle". showSpeaker($questiontext); + $onlyshow=str_replace("{QID}", $showreplace, $clang->gT("Only show question {QID} IF")); + + + if ($subaction== "editconditionsform" || $subaction=='insertcondition' || + $subaction == "editthiscondition" || $subaction == "delete" || + $subaction == "updatecondition" || $subaction == "deletescenario" || + $subaction == "updatescenario" || + $subaction == "renumberscenarios") + { + $conditionsoutput .= "\t\t\t\n" + ."\t\t
      $onlyshow\n" + ."\t\t
      \n" + ."\t\t\n" + ."\t\t\n" + ."\t\t\n" + ."\t\t\n"; + + + if ($scenariocount > 0) + { // show the Delete all conditions for this question button + $conditionsoutput .= "\t\tgT("Are you sure you want to delete all conditions set to the questions you have selected?","js")."')) {document.getElementById('deleteallconditions').submit();}\"" + ." onmouseover=\"showTooltip(event,'".$clang->gT("Delete all conditions","js")."');return false\"" + ." onmouseout=\"hideTooltip()\">" + ." \n"; + } + + if ($scenariocount > 1) + { // show the renumber scenario button for this question + $conditionsoutput .= "\t\tgT("Are you sure you want to renumber the scenarios with incremented numbers beginning from 1?","js")."')) {document.getElementById('toplevelsubaction').value='renumberscenarios'; document.getElementById('deleteallconditions').submit();}\"" + ." onmouseover=\"showTooltip(event,'".$clang->gT("Renumber scenario automatically","js")."');return false\"" + ." onmouseout=\"hideTooltip()\">" + ." \n"; + } + } + else + { + $conditionsoutput .= "\t\t\t
      $onlyshow\n" + ."\t\t\n" + ."\t\t\n" + ."\t\t\n" + ."\t\t\n"; + } + + $conditionsoutput .= "
      \n" + ."\t
      \n" + ."" + ." 
      \n" + ."$initialCheckbox\n" + . "
      $scenariotext \n" + ."
      \n"; + + if ($scenariotext != "" && ($subaction == "editconditionsform" ||$subaction == "insertcondition" || + $subaction == "updatecondition" || $subaction == "editthiscondition" || + $subaction == "renumberscenarios" || $subaction == "updatescenario" || + $subaction == "deletescenario" || $subaction == "delete") ) + { + $conditionsoutput .= "\tgT("Are you sure you want to delete all conditions set in this scenario?","js")."')) {document.getElementById('deletescenario{$scenarionr['scenario']}').submit();}\"" + ." onmouseover=\"showTooltip(event,'".$clang->gT("Delete this scenario","js")."');return false\"" + ." onmouseout=\"hideTooltip()\">" + ." \n"; + + $conditionsoutput .= "\tgT("Edit scenario","js")."');return false\"" + ." onmouseout=\"hideTooltip()\">" + ." \n"; + + } + + $conditionsoutput .= "\t\n" + ."\t\n" + ."\t\n" + ."\t\n" + ."
      \n" + ."" + .$clang->gT("and")."
      \n" + ."" + .$clang->gT("OR")."
      \n" + ."\t\t\n" + ."\t\t\t\n"; + + if ( $subaction == "copyconditionsform" || $subaction == "copyconditions") + { + $conditionsoutput .= "\t\t\t\t" + . "\t\t\t\t\n"; + } + $conditionsoutput .= "" + ."\t\t\t\t\n" + ."\t\t\t\t\t" + .$method[trim ($rows['method'])] + ."\t\t\t\t\t\t\n" + ."\t\t\t\t\t\n" + ."\n" + ."\t\t\t\t\t\n" + ."\t\t\t\t\t\n" + ."\t
        \n" + . "\t\t\t\t\t\n" + . "\t\t\t\t\n" + ."\t\t\t\t\t\n"; + + $leftOperandType = 'unknown'; // prevquestion, tokenattr + if ($thissurvey['private'] != 'Y' && preg_match('/^{TOKEN:([^}]*)}$/',$rows['cfieldname'],$extractedTokenAttr) > 0) + { + $leftOperandType = 'tokenattr'; + $aTokenAttrNames=GetTokenFieldsAndNames($surveyid); + if (count($aTokenAttrNames) != 0) + { + $thisAttrName=html_escape($aTokenAttrNames[strtolower($extractedTokenAttr[1])])." [".$clang->gT("From token table")."]"; + } + else + { + $thisAttrName=html_escape($extractedTokenAttr[1])." [".$clang->gT("Inexistant token table")."]"; + } + $conditionsoutput .= "\t\t\t$thisAttrName\n"; + // TIBO not sure this is used anymore !! + $conditionsList[]=array("cid"=>$rows['cid'], + "text"=>$thisAttrName); + } + else + { + $leftOperandType = 'prevquestion'; + foreach ($cquestions as $cqn) + { + if ($cqn[3] == $rows['cfieldname']) + { + $conditionsoutput .= "\t\t\t$cqn[0] (qid{$rows['cqid']})\n"; + $conditionsList[]=array("cid"=>$rows['cid'], + "text"=>$cqn[0]." ({$rows['value']})"); + } + else + { + //$conditionsoutput .= "\t\t\tERROR: Delete this condition. It is out of order.\n"; + } + } + } + + $conditionsoutput .= "\t\t\t\t\t\n" + ."\t\t\t\t\t\t\n" // .$clang->gT("Equals")."\n" + ."\t\t\t\t\t\t\n"; + + // let's read the condition's right operand + // determine its type and display it + $rightOperandType = 'unknown'; // predefinedAnsw,constantVal, prevQsgqa, tokenAttr, regexp + if ($rows['method'] == 'RX') + { + $rightOperandType = 'regexp'; + $conditionsoutput .= "\t\t\t\t\t\t".html_escape($rows['value'])."\n"; + } + elseif (preg_match('/^@([0-9]+X[0-9]+X[^@]*)@$/',$rows['value'],$matchedSGQA) > 0) + { // TIBO SGQA + $rightOperandType = 'prevQsgqa'; + $textfound=false; + foreach ($cquestions as $cqn) + { + if ($cqn[3] == $matchedSGQA[1]) + { + $matchedSGQAText=$cqn[0]; + $textfound=true; + break; + } + } + if ($textfound === false) + { + $matchedSGQAText=$rows['value'].' ('.$clang->gT("Not found").')'; + } + + $conditionsoutput .= "\t\t\t\t\t\t".html_escape($matchedSGQAText)."\n"; + } + elseif ($thissurvey['private'] != 'Y' && preg_match('/^{TOKEN:([^}]*)}$/',$rows['value'],$extractedTokenAttr) > 0) + { + $rightOperandType = 'tokenAttr'; + $aTokenAttrNames=GetTokenFieldsAndNames($surveyid); + if (count($aTokenAttrNames) != 0) + { + $thisAttrName=html_escape($aTokenAttrNames[strtolower($extractedTokenAttr[1])])." [".$clang->gT("From token table")."]"; + } + else + { + $thisAttrName=html_escape($extractedTokenAttr[1])." [".$clang->gT("Inexistant token table")."]"; + } + $conditionsoutput .= "\t\t\t$thisAttrName\n"; + } + elseif (isset($canswers)) + { + foreach ($canswers as $can) + { + if ($can[0] == $rows['cfieldname'] && $can[1] == $rows['value']) + { + $conditionsoutput .= "\t\t\t\t\t\t$can[2] ($can[1])\n"; + $rightOperandType = 'predefinedAnsw'; + + } + } + } + // if $rightOperandType is still unkown then it is a simple constant + if ($rightOperandType == 'unknown') + { + $rightOperandType = 'constantVal'; + if ($rows['value'] == ' ' || + $rows['value'] == '') + { + $conditionsoutput .= "\t\t\t\t\t\t".$clang->gT("No answer")."\n"; + } + else + { + $conditionsoutput .= "\t\t\t\t\t\t".html_escape($rows['value'])."\n"; + } + } + + $conditionsoutput .= "\t\t\t\t\t\n"; + + if ($subaction == "editconditionsform" ||$subaction == "insertcondition" || + $subaction == "updatecondition" || $subaction == "editthiscondition" || + $subaction == "renumberscenarios" || $subaction == "deleteallconditions" || + $subaction == "updatescenario" || + $subaction == "deletescenario" || $subaction == "delete") + { // show single condition action buttons in edit mode + $conditionsoutput .= "" + ."\t\t\t\t\t\tgT("Are you sure you want to delete this condition?","js")."')) {\$('#editModeTargetVal{$rows['cid']}').remove();\$('#cquestions{$rows['cid']}').remove();document.getElementById('conditionaction{$rows['cid']}').submit();}\"" + ." onmouseover=\"showTooltip(event,'".$clang->gT("Delete this condition","js")."');return false\"" + ." onmouseout=\"hideTooltip()\">" + ." \n" + ."\t\t\t\t\t\tgT("Edit this condition","js")."');return false\"" + ." onmouseout=\"hideTooltip()\">" + ." \n" + ."\t\t\t\t\t\n" + ."\t\t\t\t\t\n" + ."\t\t\t\t\t\n" +// ."\t\t\t\t\t\n" + ."\t\t\t\t\t\n" + ."\t\t\t\t\t\n" + ."\t\t\t\t\t\n" + ."\t\t\t\t\t\n"; + // now sets e corresponding hidden input field + // depending on the leftOperandType + if ($leftOperandType == 'tokenattr') + { + $conditionsoutput .= "" + ."\t\t\t\t\t\n"; + } + else + { + $conditionsoutput .= "" + ."\t\t\t\t\t\n"; + } + + // now set the corresponding hidden input field + // depending on the rightOperandType + // This is used when Editting a condition + if ($rightOperandType == 'predefinedAnsw') + { + $conditionsoutput .= "" + ."\t\t\t\t\t\n"; + } + elseif ($rightOperandType == 'prevQsgqa') + { + $conditionsoutput .= "" + ."\t\t\t\t\t\n"; + } + elseif ($rightOperandType == 'tokenAttr') + { + $conditionsoutput .= "" + ."\t\t\t\t\t\n"; + } + elseif ($rightOperandType == 'regexp') + { + $conditionsoutput .= "" + ."\t\t\t\t\t\n"; + } + else + { + $conditionsoutput .= "" + ."\t\t\t\t\t\n"; + } + } + + $conditionsoutput .= "" + ."\t\t\t\t\t
      \n" + ."\t
      \n" + ."\t\t
      \n" + ."\t\t
      ".$clang->gT("This question is always shown.")."\n" + . "
      \n"; + + $conditionsoutput .= "\n"; +} +//END DISPLAY CONDITIONS FOR THIS QUESTION + + +// Separator +$conditionsoutput .= "\t\n"; + + +// BEGIN: DISPLAY THE COPY CONDITIONS FORM +if ($subaction == "copyconditionsform" || $subaction == "copyconditions") +{ + $conditionsoutput .= "
      \n"; + + $conditionsoutput .= "\t\n" + ."\t\t\n" + ."\t\n"; + + if (isset($conditionsList) && is_array($conditionsList)) + { + + $conditionsoutput .= "\t\n" + ."\t\t\n" + ."\t\t\n" + ."\t\n"; + + if ( !isset($pquestions) || count($pquestions) == 0) + { + $disableCopyCondition=" disabled='disabled'"; + } + else + { + $disableCopyCondition=" "; + } + $conditionsoutput .= "\t"; + + } + else + { + $conditionsoutput .= "\t\n" + ."\t\t\n" + ."\t\n"; + } + $conditionsoutput .= "
      \n" + ."\t\t" + .$clang->gT("Copy conditions").""; + + if (isset ($CopyConditionsMessage)) + { + $conditionsoutput .= " $CopyConditionsMessage"; + } + //CopyConditionsMessage + $conditionsoutput .= "\n" + ."\t\t
      \n" + ."\t\t".$clang->gT("Copy the selected conditions to").":\n" + ."\t\t\n" + ."\t\t\n"; + $conditionsoutput .= "\t\t
      \n" + ."gT("Are you sure you want to copy these condition(s) to the questions you have selected?","js")."')){prepareCopyconditions(); return true;} else {return false;}\" $disableCopyCondition/>" + ."\t\t\n"; + + $conditionsoutput .= "\n" + ."\n" + ."\n" + ."\n"; + + $conditionsoutput .= "\n" + ."
      ".$clang->gT("Condition")."".$clang->gT("Question")."
      \n"; + + $conditionsoutput .= "\t\n" + ."\t\n"; +} +// END: DISPLAY THE COPY CONDITIONS FORM + +if ( isset($cquestions) ) +{ + if ( count($cquestions) > 0 && count($cquestions) <=10) + { + $qcount = count($cquestions); + } + else + { + $qcount = 9; + } +} +else +{ + $qcount = 0; +} + + +//BEGIN: DISPLAY THE ADD or EDIT CONDITION FORM +if ($subaction == "editconditionsform" || $subaction == "insertcondition" || + $subaction == "updatecondition" || $subaction == "deletescenario" || + $subaction == "renumberscenarios" || $subaction == "deleteallconditions" || + $subaction == "updatescenario" || + $subaction == "editthiscondition" || $subaction == "delete") +{ + $conditionsoutput .= "\n"; + $conditionsoutput .= "
      \n"; + $conditionsoutput .= "\n"; + if ($subaction == "editthiscondition" && isset($p_cid)) + { + $mytitle = $clang->gT("Edit condition"); + } + else + { + $mytitle = $clang->gT("Add condition"); + } + + $conditionsoutput .= "\t\n" + ."\t\t\n" + ."\t\n" + ."\t\n" + ."\t\t\n" + ."\t\t\n" + ."\t\n"; + + if (isset($scenariocount) && ($scenariocount == 1 || $scenariocount==0)) + { + $scenarioAddBtn = "\t\t\t\n"; + $scenarioTxt = "".$clang->gT("Default scenario").""; + $scenarioInputStyle = "style = 'display: none;'"; + } + else + { + $scenarioAddBtn = ""; + $scenarioTxt = ""; + $scenarioInputStyle = "style = ''"; + } + + $conditionsoutput .= "\t\n" + . "\t\t\n" + . "\t\t\n" + . "\t\n" + . "\t\n"; + + // Source condition selection + $conditionsoutput .= "" + . "\t\t\n" + ."\t\t\n" + . "\t\n" + . "\t\n" + . "\t\t\n" + . "\t\t\n" + . "\t\n" + . "\t\n" + . "\t\t\n"; + + if ($subaction == "editthiscondition") + { + $multipletext = ""; + } + else + { + $multipletext = "multiple"; + } + + + $conditionsoutput .= "" + ."\t\t" + ."\t\n" + ."\t\n" + ."\t\t\n" + ."\t\n" + ."
      \n" + ."\t\t\t".$mytitle."\n" + ."\t\t
      $scenarioAddBtn ".$clang->gT("Scenario")."" + . "$scenarioTxt
      ".$clang->gT("Question")."\n" + ."\t\t\t
      \n" + ."\t\t\t\n"; + + // Previous question tab + $conditionsoutput .= "\t\t\t\t
      \n"; + foreach (GetTokenFieldsAndNames($surveyid) as $tokenattr => $tokenattrName) + { + // Check to select + if (isset($p_csrctoken) && $p_csrctoken == '{TOKEN:'.strtoupper($tokenattr).'}') + { + $selectThisSrcTokenAttr = "selected=\"selected\""; + } + else + { + $selectThisSrcTokenAttr = ""; + } + $conditionsoutput .= "\t\t\t\t\n"; + } + + $conditionsoutput .= "\t\t\t\t\n" + ."\t\t\t\t
      \n\t\t\t\t\n"; + + $conditionsoutput .= "\t\t\t
      \n" // End Source tabs + . "\t\t\t
      ".$clang->gT("Comparison operator")."
      ".$clang->gT("Answer")."\n" + ."\t\t
      \n" + ."\t\t\n"; + + // Predefined answers tab + $conditionsoutput .= "\t\t\t
      \n" + ."\t\t\t
      ".$clang->gT("Predefined answers for this question")."\n" + ."\t\t\t
      \n\t\t\t\n"; + // Constant tab + $conditionsoutput .= "
      " + ."\t\t\n" + ."\t\t
      ".$clang->gT("Constant value")."
      \n" + ."\t\t
      \n"; + // Previous answers tab @SGQA@ placeholders + $conditionsoutput .= "\t\t\t
      \n"; + foreach (GetTokenFieldsAndNames($surveyid) as $tokenattr => $tokenattrName) + { + $conditionsoutput .= "\t\t\t\t\n"; + } + + $conditionsoutput .= "\t\t\t\n" + ."\t\t\t
      ".$clang->gT("Attributes values from the participant's token")."\n" + ."\t\t\t
      \n\t\t\t\n"; + + // Regexp Tab + $conditionsoutput .= "
      " + ."\t\t\n" + ."\t\t
      \n" + ."\t\t
      \n"; + $conditionsoutput .= "\t\t
      \n"; // end conditiontarget div + + + $js_adminheader_includes[]= $homeurl.'/scripts/assessments.js'; + $js_adminheader_includes[]= $rooturl.'/scripts/jquery/lime-conditions-tabs.js'; + $js_adminheader_includes[]= $rooturl.'/scripts/jquery/jquery-ui.js'; + + $css_adminheader_includes[]= $homeurl."/styles/default/jquery-ui-tibo.css"; + + if ($subaction == "editthiscondition" && isset($p_cid)) + { + $submitLabel = $clang->gT("Update condition"); + $submitSubaction = "updatecondition"; + $submitcid = sanitize_int($p_cid); + } + else + { + $submitLabel = $clang->gT("Add condition"); + $submitSubaction = "insertcondition"; + $submitcid = ""; + } + + $conditionsoutput .= "" + ."\t\t
      \n" + ."\t\t\t\n" + ."\t\t\t\n" + ."\n" + ."\n" + ."\n" + ."\n" + ."\n" + ."\n" + ."\n" // auto-select tab by jQuery when editing a condition + ."\n" // auto-select tab by jQuery when editing a condition + ."\n" // auto-select target answers by jQuery when editing a condition + ."\t\t
      \n" + ."
      \n"; + + if (!isset($js_getAnswers_onload)) + { + $js_getAnswers_onload = ''; + } + + $conditionsoutput .= "\n"; + $conditionsoutput .= "\n"; + } +//END: DISPLAY THE ADD or EDIT CONDITION FORM + + +$conditionsoutput .= "\n"; + + +////////////// FUNCTIONS ///////////////////////////// + +function showSpeaker($hinttext) +{ + global $clang, $imagefiles, $max; + + if(!isset($max)) + { + $max = 20; + } + $htmlhinttext=str_replace("'",''',$hinttext); //the string is already HTML except for single quotes so we just replace these only + $jshinttext=javascript_escape($hinttext,true,true); + + if(strlen(html_entity_decode($hinttext,ENT_QUOTES,'UTF-8')) > ($max+3)) + { + $shortstring = FlattenText($hinttext); + + $shortstring = htmlspecialchars(mb_strcut(html_entity_decode($shortstring,ENT_QUOTES,'UTF-8'), 0, $max, 'UTF-8')); + + //output with hoover effect + $reshtml= "gT("Question","js").": $jshinttext')\" />" + ." \"$shortstring...\" " + ."$htmlhinttextgT("Question","js").": $jshinttext')\" />"; + } + else + { + $reshtml= " \"$htmlhinttext\""; + } + + return $reshtml; + +} + +?> diff --git a/include/limesurvey/admin/database.php b/include/limesurvey/admin/database.php index 6176a8f3..bfda5b03 100644 --- a/include/limesurvey/admin/database.php +++ b/include/limesurvey/admin/database.php @@ -1,1451 +1,1428 @@ -RenameTableSQL($oldtable, $newtable); - return $result[0]; -} - - -/* -* Gets the maximum question_order field value for a group -* @gid: The id of the group -*/ -function get_max_question_order($gid) -{ - global $connect ; - global $dbprefix ; - $query="SELECT MAX(question_order) as maxorder FROM {$dbprefix}questions where gid=".$gid ; - // echo $query; - $result = db_execute_assoc($query); - $gv = $result->FetchRow(); - return $gv['maxorder']; -} - -$databaseoutput =''; - -if(isset($surveyid)) -{ - $actsurquery = "SELECT define_questions, edit_survey_property, delete_survey FROM {$dbprefix}surveys_rights WHERE sid=$surveyid AND uid = ".$_SESSION['loginID']; //Getting rights for this survey - $actsurresult = db_execute_assoc($actsurquery); - $actsurrows = $actsurresult->FetchRow(); - - if ($action == "delattribute" && ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $actsurrows['define_questions'])) - { - $query = "DELETE FROM ".db_table_name('question_attributes')." - WHERE qaid={$postqaid} AND qid={$postqid}"; - $result=$connect->Execute($query) or safe_die("Couldn't delete attribute
      ".$query."
      ".$connect->ErrorMsg()); - } - elseif ($action == "addattribute" && ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $actsurrows['define_questions'])) - { - if (isset($_POST['attribute_value']) && $_POST['attribute_value']) - { - if ($_POST['attribute_name']=='dropdown_separators' || $_POST['attribute_name']=='dualscale_headerA' || $_POST['attribute_name']=='dualscale_headerB' || - $_POST['attribute_name']=='dropdown_prepostfix' || $_POST['attribute_name']=='prefix' || $_POST['attribute_name']=='suffix') - { - if ($filterxsshtml) - { - require_once("../classes/inputfilter/class.inputfilter_clean.php"); - $myFilter = new InputFilter('','',1,1,1); - $_POST['attribute_value']=$myFilter->process($_POST['attribute_value']); - } - else - { - $_POST['attribute_value'] = html_entity_decode_php4($_POST['attribute_value'], ENT_QUOTES, "UTF-8"); - } - } - - $_POST = array_map('db_quote', $_POST); - $query = "INSERT INTO ".db_table_name('question_attributes')." - (qid, attribute, value) - VALUES ('{$postqid}', '{$_POST['attribute_name']}', '{$_POST['attribute_value']}')"; - $result = $connect->Execute($query) or safe_die("Error
      ".$query."
      ".$connect->ErrorMsg()); - } - } - elseif ($action == "editattribute" && ( $_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $actsurrows['define_questions'])) - { - if (isset($_POST['attribute_value']) && $_POST['attribute_value']) - { - $query = "UPDATE ".db_table_name('question_attributes')." - SET value='{$_POST['attribute_value']}' WHERE qaid=".$postqaid." AND qid=".returnglobal('qid'); - $result = $connect->Execute($query) or safe_die("Error
      ".$query."
      ".$connect->ErrorMsg()); - } - } - elseif ($action == "insertnewgroup" && ( $_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $actsurrows['define_questions'])) - { - $grplangs = GetAdditionalLanguagesFromSurveyID($postsid); - $baselang = GetBaseLanguageFromSurveyID($postsid); - $grplangs[] = $baselang; - $errorstring = ''; - foreach ($grplangs as $grouplang) - { - if (!$_POST['group_name_'.$grouplang]) { $errorstring.= GetLanguageNameFromCode($grouplang,false)."\\n";} - } - if ($errorstring!='') - { - $databaseoutput .= "\n"; - } - - else - { - $first=true; - require_once("../classes/inputfilter/class.inputfilter_clean.php"); - $myFilter = new InputFilter('','',1,1,1); - - foreach ($grplangs as $grouplang) - { - //Clean XSS - if ($filterxsshtml) - { - $_POST['group_name_'.$grouplang]=$myFilter->process($_POST['group_name_'.$grouplang]); - $_POST['description_'.$grouplang]=$myFilter->process($_POST['description_'.$grouplang]); - } - else - { - $_POST['group_name_'.$grouplang] = html_entity_decode_php4($_POST['group_name_'.$grouplang], ENT_QUOTES, "UTF-8"); - $_POST['description_'.$grouplang] = html_entity_decode_php4($_POST['description_'.$grouplang], ENT_QUOTES, "UTF-8"); - } - - // Fix bug with FCKEditor saving strange BR types - $_POST['group_name_'.$grouplang]=str_replace('
      ','',$_POST['group_name_'.$grouplang]); - $_POST['description_'.$grouplang]=str_replace('
      ','',$_POST['description_'.$grouplang]); - if ($_POST['group_name_'.$grouplang] == "
      ") - { - $_POST['group_name_'.$grouplang] = ''; - } - if ($_POST['description_'.$grouplang] == "
      ") - { - $_POST['description_'.$grouplang] = ''; - } - - //$_POST = array_map('db_quote', $_POST); - - if ($first) - { - $query = "INSERT INTO ".db_table_name('groups')." (sid, group_name, description,group_order,language) VALUES ('".db_quote($postsid)."', '".db_quote($_POST['group_name_'.$grouplang])."', '".db_quote($_POST['description_'.$grouplang])."',".getMaxgrouporder(returnglobal('sid')).",'{$grouplang}')"; - $result = $connect->Execute($query); - $groupid=$connect->Insert_Id(db_table_name_nq('groups'),"gid"); - $first=false; - } - else{ - $query = "INSERT INTO ".db_table_name('groups')." (gid, sid, group_name, description,group_order,language) VALUES ('{$groupid}','{$postsid}', '{$_POST['group_name_'.$grouplang]}', '{$_POST['description_'.$grouplang]}',".getMaxgrouporder(returnglobal('sid')).",'{$grouplang}')"; - if ($connect->databaseType == 'odbc_mssql') $query = "SET IDENTITY_INSERT ".db_table_name('groups')." ON; " . $query . "SET IDENTITY_INSERT ".db_table_name('groups')." OFF;"; - $result = $connect->Execute($query) or safe_die("Error
      ".$query."
      ".$connect->ErrorMsg()); - } - if (!$result) - { - $databaseoutput .= $clang->gT("Error: The database reported the following error:")."
      \n"; - $databaseoutput .= "" . htmlspecialchars($connect->ErrorMsg()) . "\n"; - $databaseoutput .= "
      ".htmlspecialchars($query)."
      \n"; - $databaseoutput .= "\n"; - exit; - } - } - // This line sets the newly inserted group as the new group - if (isset($groupid)){$gid=$groupid;} - - } - } - - elseif ($action == "updategroup" && ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $actsurrows['define_questions'])) - { - $grplangs = GetAdditionalLanguagesFromSurveyID($postsid); - $baselang = GetBaseLanguageFromSurveyID($postsid); - array_push($grplangs,$baselang); - require_once("../classes/inputfilter/class.inputfilter_clean.php"); - $myFilter = new InputFilter('','',1,1,1); - foreach ($grplangs as $grplang) - { - if (isset($grplang) && $grplang != "") - { - if ($filterxsshtml) - { - $_POST['group_name_'.$grplang]=$myFilter->process($_POST['group_name_'.$grplang]); - $_POST['description_'.$grplang]=$myFilter->process($_POST['description_'.$grplang]); - } - else - { - $_POST['group_name_'.$grplang] = html_entity_decode_php4($_POST['group_name_'.$grplang], ENT_QUOTES, "UTF-8"); - $_POST['description_'.$grplang] = html_entity_decode_php4($_POST['description_'.$grplang], ENT_QUOTES, "UTF-8"); - } - - // Fix bug with FCKEditor saving strange BR types - $_POST['group_name_'.$grplang]=str_replace('
      ','',$_POST['group_name_'.$grplang]); - $_POST['description_'.$grplang]=str_replace('
      ','',$_POST['description_'.$grplang]); - if ($_POST['group_name_'.$grplang] == "
      ") - { - $_POST['group_name_'.$grplang] = ''; - } - if ($_POST['description_'.$grplang] == "
      ") - { - $_POST['description_'.$grplang] = ''; - } - - // don't use array_map db_quote on POST - // since this is iterated for each language - //$_POST = array_map('db_quote', $_POST); - $ugquery = "UPDATE ".db_table_name('groups')." SET group_name='".db_quote($_POST['group_name_'.$grplang])."', description='".db_quote($_POST['description_'.$grplang])."' WHERE sid=".db_quote($postsid)." AND gid=".db_quote($postgid)." AND language='{$grplang}'"; - $ugresult = $connect->Execute($ugquery); - if ($ugresult) - { - $groupsummary = getgrouplist($postgid); - } - else - { - $databaseoutput .= "\n"; - } - } - } - - } - - elseif ($action == "delgroupnone" && ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $actsurrows['define_questions'])) - { - if (!isset($gid)) $gid=returnglobal('gid'); - $query = "DELETE FROM ".db_table_name('groups')." WHERE sid=$surveyid AND gid=$gid"; - $result = $connect->Execute($query) or safe_die($connect->ErrorMsg()) ; - - if ($result) - { - $gid = ""; - $groupselect = getgrouplist($gid); - fixsortorderGroups(); - } - else - { - $databaseoutput .= "\n"; - } - } - - elseif ($action == "delgroup" && ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $actsurrows['define_questions'])) - { - if (!isset($gid)) $gid=returnglobal('gid'); - $query = "SELECT qid FROM ".db_table_name('groups').", ".db_table_name('questions')." WHERE ".db_table_name('groups').".gid=".db_table_name('questions').".gid AND ".db_table_name('groups').".gid=$gid"; - if ($result = db_execute_assoc($query)) - { - if (!isset($total)) $total=0; - $qtodel=$result->RecordCount(); - while ($row=$result->FetchRow()) - { - $dquery = "DELETE FROM ".db_table_name('conditions')." WHERE qid={$row['qid']}"; - if ($dresult=$connect->Execute($dquery)) {$total++;} - $dquery = "DELETE FROM ".db_table_name('answers')." WHERE qid={$row['qid']}"; - if ($dresult=$connect->Execute($dquery)) {$total++;} - $dquery = "DELETE FROM ".db_table_name('question_attributes')." WHERE qid={$row['qid']}"; - if ($dresult=$connect->Execute($dquery)) {$total++;} - $dquery = "DELETE FROM ".db_table_name('questions')." WHERE qid={$row['qid']}"; - if ($dresult=$connect->Execute($dquery)) {$total++;} - } - if ($total != $qtodel*4) - { - $databaseoutput .= "\n"; - } - } - $query = "DELETE FROM ".db_table_name('groups')." WHERE sid=$surveyid AND gid=$gid"; - $result = $connect->Execute($query) or safe_die($connect->ErrorMsg()) ; - if ($result) - { - $gid = ""; - $groupselect = getgrouplist($gid); - fixsortorderGroups(); - } - else - { - $databaseoutput .= "\n"; - } - } - - elseif ($action == "insertnewquestion" && ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $actsurrows['define_questions'])) - { - if (strlen($_POST['title']) < 1) - { - $databaseoutput .= "\n"; - } - else - { - if (!isset($_POST['lid']) || $_POST['lid'] == '') {$_POST['lid']="0";} - if (!isset($_POST['lid1']) || $_POST['lid1'] == '') {$_POST['lid1']="0";} - $baselang = GetBaseLanguageFromSurveyID($postsid); - if(!empty($_POST['questionposition']) || $_POST['questionposition'] == '0') - { - $question_order=(sanitize_int($_POST['questionposition'])+1); - //Need to renumber all questions on or after this - $cdquery = "UPDATE ".db_table_name('questions')." SET question_order=question_order+1 WHERE gid=".$postgid." AND question_order >= ".$question_order; - $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); - } else { - $question_order=(getMaxquestionorder($postgid)); - $question_order++; - } - - if ($filterxsshtml) - { - require_once("../classes/inputfilter/class.inputfilter_clean.php"); - $myFilter = new InputFilter('','',1,1,1); - $_POST['title']=$myFilter->process($_POST['title']); - $_POST['question']=$myFilter->process($_POST['question']); - $_POST['help']=$myFilter->process($_POST['help']); - } - else - { - $_POST['title'] = html_entity_decode_php4($_POST['title'], ENT_QUOTES, "UTF-8"); - $_POST['question'] = html_entity_decode_php4($_POST['question'], ENT_QUOTES, "UTF-8"); - $_POST['help'] = html_entity_decode_php4($_POST['help'], ENT_QUOTES, "UTF-8"); - } - - // Fix bug with FCKEditor saving strange BR types - $_POST['title']=str_replace('
      ','',$_POST['title']); - $_POST['question']=str_replace('
      ','',$_POST['question']); - $_POST['help']=str_replace('
      ','',$_POST['help']); - - if ($_POST['title'] == "
      ") - { - $_POST['title'] = ''; - } - - if ($_POST['question'] == "
      ") - { - $_POST['question'] = ''; - } - - if ($_POST['help'] == "
      ") - { - $_POST['help'] = ''; - } - - $_POST = array_map('db_quote', $_POST); - $query = "INSERT INTO ".db_table_name('questions')." (sid, gid, type, title, question, preg, help, other, mandatory, lid, lid1, question_order, language)" - ." VALUES ('{$postsid}', '{$postgid}', '{$_POST['type']}', '{$_POST['title']}'," - ." '{$_POST['question']}', '{$_POST['preg']}', '{$_POST['help']}', '{$_POST['other']}', '{$_POST['mandatory']}', '{$_POST['lid']}', '{$_POST['lid1']}',$question_order,'{$baselang}')"; - $result = $connect->Execute($query); - // Get the last inserted questionid for other languages - $qid=$connect->Insert_ID(db_table_name_nq('questions'),"qid"); - - // Add other languages - if ($result) - { - $addlangs = GetAdditionalLanguagesFromSurveyID($postsid); - foreach ($addlangs as $alang) - { - if ($alang != "") - { - $query = "INSERT INTO ".db_table_name('questions')." (qid, sid, gid, type, title, question, preg, help, other, mandatory, lid, lid1, question_order, language)" - ." VALUES ('$qid','{$postsid}', '{$postgid}', '{$_POST['type']}', '{$_POST['title']}'," - ." '{$_POST['question']}', '{$_POST['preg']}', '{$_POST['help']}', '{$_POST['other']}', '{$_POST['mandatory']}', '{$_POST['lid']}', '{$_POST['lid1']}',".getMaxquestionorder($postgid).",'{$alang}')"; - if ($connect->databaseType == 'odbc_mssql') $query = "SET IDENTITY_INSERT ".db_table_name('questions')." ON; " . $query . "SET IDENTITY_INSERT ".db_table_name('questions')." OFF;"; - $result2 = $connect->Execute($query); - if (!$result2) - { - $databaseoutput .= "\n"; - - } - } - } - } - - - if (!$result) - { - $databaseoutput .= "\n"; - - } - if (isset($_POST['attribute_value']) && $_POST['attribute_value']) - { - $query = "INSERT INTO ".db_table_name('question_attributes')." - (qid, attribute, value) - VALUES - ($qid, '".$_POST['attribute_name']."', '".$_POST['attribute_value']."')"; - $result = $connect->Execute($query); - } - } - } - elseif ($action == "renumberquestions" && ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $actsurrows['define_questions'])) - { - //Automatically renumbers the "question codes" so that they follow - //a methodical numbering method - $question_number=1; - $group_number=0; - $gselect="SELECT a.qid, a.gid\n" - ."FROM ".db_table_name('questions')." as a, ".db_table_name('groups')."\n" - ."WHERE a.gid=".db_table_name('groups').".gid\n" - ."AND a.sid=$surveyid\n" - ."group BY a.gid, a.qid\n" - ."ORDER BY ".db_table_name('groups').".group_order, question_order"; - $gresult=db_execute_assoc($gselect) or safe_die ("Error: ".$connect->ErrorMsg()); - $grows = array(); //Create an empty array in case FetchRow does not return any rows - while ($grow = $gresult->FetchRow()) {$grows[] = $grow;} // Get table output into array - foreach($grows as $grow) - { - //Go through all the questions - if ((isset($_POST['style']) && $_POST['style']=="bygroup") && (!isset($group_number) || $group_number != $grow['gid'])) - { //If we're doing this by group, restart the numbering when the group number changes - $question_number=1; - $group_number++; - } - $usql="UPDATE ".db_table_name('questions')."\n" - ."SET title='".str_pad($question_number, 4, "0", STR_PAD_LEFT)."'\n" - ."WHERE qid=".$grow['qid']; - //$databaseoutput .= "[$sql]"; - $uresult=$connect->Execute($usql) or safe_die("Error: ".$connect->ErrorMsg()); - $question_number++; - $group_number=$grow['gid']; - } - } - - elseif ($action == "updatequestion" && ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $actsurrows['define_questions'])) - { - $cqquery = "SELECT type, gid FROM ".db_table_name('questions')." WHERE qid={$postqid}"; - $cqresult=db_execute_assoc($cqquery) or safe_die ("Couldn't get question type to check for change
      ".$cqquery."
      ".$connect->ErrorMsg()); - $cqr=$cqresult->FetchRow(); - $oldtype=$cqr['type']; - $oldgid=$cqr['gid']; - - // Remove invalid question attributes on saving - $qattributes=questionAttributes(); - $attsql="delete from ".db_table_name('question_attributes')." where qid='{$postqid}' and "; - if (isset($qattributes[$_POST['type']])){ - $validAttributes=$qattributes[$_POST['type']]; - foreach ($validAttributes as $validAttribute) - { - $attsql.='attribute<>'.db_quoteall($validAttribute['name'])." and "; - } - } - $attsql.='1=1'; - db_execute_assoc($attsql) or safe_die ("Couldn't delete obsolete question attributes
      ".$attsql."
      ".$connect->ErrorMsg()); - - $keepanswers = "1"; // Generally we try to keep answers if the question type has changed - - // These are the questions types that have no answers and therefore we delete the answer in that case - if (($_POST['type']== "5") || ($_POST['type']== "D") || ($_POST['type']== "G") || - ($_POST['type']== "I") || ($_POST['type']== "N") || ($_POST['type']== "S") || - ($_POST['type']== "T") || ($_POST['type']== "U") || ($_POST['type']== "X") || - ($_POST['type']=="Y")) - { - $keepanswers = "0"; - } - - // These are the questions types that use labelsets and - // therefore we set the label set of all other question types to 0 - if (($_POST['type']!= "F") && ($_POST['type']!= "H") && ($_POST['type']!= "W") && - ($_POST['type']!= "Z") && ($_POST['type']!= "1")) - { - $_POST['lid']=0; - } - - // These are the questions types that have the other option therefore we set everything else to 'No Other' - if (($_POST['type']!= "L") && ($_POST['type']!= "!") && ($_POST['type']!= "P") && ($_POST['type']!="M") && ($_POST['type'] != "W") && ($_POST['type'] != "Z")) - { - $_POST['other']='N'; - } - - - - - if ($oldtype != $_POST['type']) - { - //Make sure there are no conditions based on this question, since we are changing the type - $ccquery = "SELECT * FROM ".db_table_name('conditions')." WHERE cqid={$postqid}"; - $ccresult = db_execute_assoc($ccquery) or safe_die ("Couldn't get list of cqids for this question
      ".$ccquery."
      ".$connect->ErrorMsg()); - $cccount=$ccresult->RecordCount(); - while ($ccr=$ccresult->FetchRow()) {$qidarray[]=$ccr['qid'];} - if (isset($qidarray) && $qidarray) {$qidlist=implode(", ", $qidarray);} - } - if (isset($cccount) && $cccount) - { - $databaseoutput .= "\n"; - } - else - { - if (isset($postgid) && $postgid != "") - { - - $array_result=checkMovequestionConstraintsForConditions(sanitize_int($postsid),sanitize_int($postqid), sanitize_int($postgid)); - // If there is no blocking conditions that could prevent this move - if (is_null($array_result['notAbove']) && is_null($array_result['notBelow'])) - { - - $questlangs = GetAdditionalLanguagesFromSurveyID($postsid); - $baselang = GetBaseLanguageFromSurveyID($postsid); - array_push($questlangs,$baselang); - if ($filterxsshtml) - { - require_once("../classes/inputfilter/class.inputfilter_clean.php"); - $myFilter = new InputFilter('','',1,1,1); - $_POST['title']=$myFilter->process($_POST['title']); - } - else - { - $_POST['title'] = html_entity_decode_php4($_POST['title'], ENT_QUOTES, "UTF-8"); - } - - // Fix bug with FCKEditor saving strange BR types - $_POST['title']=str_replace('
      ','',$_POST['title']); - if ($_POST['title'] == "
      ") - { - $_POST['title'] = ''; - } - - foreach ($questlangs as $qlang) - { - if ($filterxsshtml) - { - $_POST['question_'.$qlang]=$myFilter->process($_POST['question_'.$qlang]); - $_POST['help_'.$qlang]=$myFilter->process($_POST['help_'.$qlang]); - } - else - { - $_POST['question_'.$qlang] = html_entity_decode_php4($_POST['question_'.$qlang], ENT_QUOTES, "UTF-8"); - $_POST['help_'.$qlang] = html_entity_decode_php4($_POST['help_'.$qlang], ENT_QUOTES, "UTF-8"); - } - // Fix bug with FCKEditor saving strange BR types - $_POST['question_'.$qlang]=str_replace('
      ','',$_POST['question_'.$qlang]); - $_POST['help_'.$qlang]=str_replace('
      ','',$_POST['help_'.$qlang]); - if ($_POST['question_'.$qlang] == "
      ") - { - $_POST['question_'.$qlang] = ''; - } - if ($_POST['help_'.$qlang] == "
      ") - { - $_POST['help_'.$qlang] = ''; - } - - //$_POST = array_map('db_quote', $_POST); - - if (isset($qlang) && $qlang != "") - { // ToDo: Sanitize the POST variables ! - $uqquery = "UPDATE ".db_table_name('questions') - . "SET type='".db_quote($_POST['type'])."', title='".db_quote($_POST['title'])."', " - . "question='".db_quote($_POST['question_'.$qlang])."', preg='".db_quote($_POST['preg'])."', help='".db_quote($_POST['help_'.$qlang])."', " - . "gid='".db_quote($postgid)."', other='".db_quote($_POST['other'])."', " - . "mandatory='".db_quote($_POST['mandatory'])."'"; - if ($oldgid!=$postgid) - { - if ( getGroupOrder(returnglobal('sid'),$oldgid) > getGroupOrder(returnglobal('sid'),returnglobal('gid')) ) - { - // Moving question to a 'upper' group - // insert question at the end of the destination group - // this prevent breaking conditions if the target qid is in the dest group - $insertorder = getMaxquestionorder($postgid) + 1; - $uqquery .=', question_order='.$insertorder.' '; - } - else - { - // Moving question to a 'lower' group - // insert question at the beginning of the destination group - shiftorderQuestions($postsid,$postgid,1); // makes 1 spare room for new question at top of dest group - $uqquery .=', question_order=0 '; - } - } - if (isset($_POST['lid']) && trim($_POST['lid'])!="") - { - $uqquery.=", lid='".db_quote($_POST['lid'])."' "; - } - if (isset($_POST['lid1']) && trim($_POST['lid1'])!="") - { - $uqquery.=", lid1='".db_quote($_POST['lid1'])."' "; - } - - $uqquery.= "WHERE sid='".db_quote($postsid)."' AND qid='".db_quote($postqid)."' AND language='{$qlang}'"; - $uqresult = $connect->Execute($uqquery) or safe_die ("Error Update Question: ".$uqquery."
      ".$connect->ErrorMsg()); - if (!$uqresult) - { - $databaseoutput .= "\n"; - } - } - } - // if the group has changed then fix the sortorder of old and new group - if ($oldgid!=$postgid) - { - fixsortorderQuestions(0,$oldgid); - fixsortorderQuestions(0,$postgid); - - // If some questions have conditions set on this question's answers - // then change the cfieldname accordingly - fixmovedquestionConditions($postqid, $oldgid, $postgid); - } - if ($keepanswers == "0") - { - $query = "DELETE FROM ".db_table_name('answers')." WHERE qid=".db_quote($postqid); - $result = $connect->Execute($query) or safe_die("Error: ".$connect->ErrorMsg()); - if (!$result) - { - $databaseoutput .= "\n"; - } - } - } - else - { - // There are conditions constraints: alert the user - $errormsg=""; - if (!is_null($array_result['notAbove'])) - { - $errormsg.=$clang->gT("This question relies on other question's answers and can't be moved above groupId:","js") - . " " . $array_result['notAbove'][0][0] . " " . $clang->gT("in position","js")." ".$array_result['notAbove'][0][1]."\\n" - . $clang->gT("See conditions:")."\\n"; - - foreach ($array_result['notAbove'] as $notAboveCond) - { - $errormsg.="- cid:". $notAboveCond[3]."\\n"; - } - - } - if (!is_null($array_result['notBelow'])) - { - $errormsg.=$clang->gT("Some questions rely on this question's answers. You can't move this question below groupId:","js") - . " " . $array_result['notBelow'][0][0] . " " . $clang->gT("in position","js")." ".$array_result['notBelow'][0][1]."\\n" - . $clang->gT("See conditions:")."\\n"; - - foreach ($array_result['notBelow'] as $notBelowCond) - { - $errormsg.="- cid:". $notBelowCond[3]."\\n"; - } - } - - $databaseoutput .= "\n"; - $gid= $oldgid; // group move impossible ==> keep display on oldgid - } - } - else - { - $databaseoutput .= "\n"; - } - } - } - - elseif ($action == "copynewquestion" && ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $actsurrows['define_questions'])) - { - - if (!$_POST['title']) - { - $databaseoutput .= "\n"; - } - else - { - $questlangs = GetAdditionalLanguagesFromSurveyID($postsid); - $baselang = GetBaseLanguageFromSurveyID($postsid); - - if (!isset($_POST['lid']) || $_POST['lid']=='') {$_POST['lid']=0;} - if (!isset($_POST['lid1']) || $_POST['lid1']=='') {$_POST['lid1']=0;} - //Get maximum order from the question group - $max=get_max_question_order($postgid)+1 ; - // Insert the base language of the question - if ($filterxsshtml) - { - require_once("../classes/inputfilter/class.inputfilter_clean.php"); - $myFilter = new InputFilter('','',1,1,1); - // Prevent XSS attacks - $_POST['title']=$myFilter->process($_POST['title']); - $_POST['question_'.$baselang]=$myFilter->process($_POST['question_'.$baselang]); - $_POST['help_'.$baselang]=$myFilter->process($_POST['help_'.$baselang]); - } - else - { - $_POST['title'] = html_entity_decode_php4($_POST['title'], ENT_QUOTES, "UTF-8"); - $_POST['question_'.$baselang] = html_entity_decode_php4($_POST['question_'.$baselang], ENT_QUOTES, "UTF-8"); - $_POST['help_'.$baselang] = html_entity_decode_php4($_POST['help_'.$baselang], ENT_QUOTES, "UTF-8"); - } - - - // Fix bug with FCKEditor saving strange BR types - $_POST['title']=str_replace('
      ','',$_POST['title']); - $_POST['question_'.$baselang]=str_replace('
      ','',$_POST['question_'.$baselang]); - $_POST['help_'.$baselang]=str_replace('
      ','',$_POST['help_'.$baselang]); - if ($_POST['title']== "
      ") - { - $_POST['title'] = ''; - } - if ($_POST['question_'.$baselang] == "
      ") - { - $_POST['question_'.$baselang] = ''; - } - if ($_POST['help_'.$baselang] == "
      ") - { - $_POST['help_'.$baselang] = ''; - } - - $_POST = array_map('db_quote', $_POST); - $query = "INSERT INTO {$dbprefix}questions (sid, gid, type, title, question, help, other, mandatory, lid, lid1, question_order, language) - VALUES ({$postsid}, {$postgid}, '{$_POST['type']}', '{$_POST['title']}', '".$_POST['question_'.$baselang]."', '".$_POST['help_'.$baselang]."', '{$_POST['other']}', '{$_POST['mandatory']}', '{$_POST['lid']}', '{$_POST['lid1']}',$max,".db_quoteall($baselang).")"; - $result = $connect->Execute($query) or safe_die($connect->ErrorMsg()); - $newqid = $connect->Insert_ID("{$dbprefix}questions","qid"); - if (!$result) - { - $databaseoutput .= "\n"; - - } - - foreach ($questlangs as $qlanguage) - { - if ($filterxsshtml) - { - $_POST['question_'.$qlanguage]=$myFilter->process($_POST['question_'.$qlanguage]); - $_POST['help_'.$qlanguage]=$myFilter->process($_POST['help_'.$qlanguage]); - } - else - { - $_POST['question_'.$qlanguage] = html_entity_decode_php4($_POST['question_'.$qlanguage], ENT_QUOTES, "UTF-8"); - $_POST['help_'.$qlanguage] = html_entity_decode_php4($_POST['help_'.$qlanguage], ENT_QUOTES, "UTF-8"); - } - - // Fix bug with FCKEditor saving strange BR types - $_POST['question_'.$qlanguage]=str_replace('
      ','',$_POST['question_'.$qlanguage]); - $_POST['help_'.$qlanguage]=str_replace('
      ','',$_POST['help_'.$qlanguage]); - if ($_POST['question_'.$qlanguage] == "
      ") - { - $_POST['question_'.$qlanguage] = ''; - } - if ($_POST['question_'.$qlanguage] == "
      ") - { - $_POST['question_'.$qlanguage] = ''; - } - - if ($databasetype=='odbc_mssql') {@$connect->Execute("SET IDENTITY_INSERT ".db_table_name('questions')." ON");} - $query = "INSERT INTO {$dbprefix}questions (qid, sid, gid, type, title, question, help, other, mandatory, lid, lid1, question_order, language) - VALUES ($newqid,{$postsid}, {$postgid}, '{$_POST['type']}', '{$_POST['title']}', '".$_POST['question_'.$qlanguage]."', '".$_POST['help_'.$qlanguage]."', '{$_POST['other']}', '{$_POST['mandatory']}', '{$_POST['lid']}', '{$_POST['lid1']}', $max,".db_quoteall($qlanguage).")"; - $result = $connect->Execute($query) or safe_die($connect->ErrorMsg()); - if ($databasetype=='odbc_mssql') {@$connect->Execute("SET IDENTITY_INSERT ".db_table_name('questions')." OFF");} - } - if (!$result) - { - $databaseoutput .= "\n"; - - } - if (returnglobal('copyanswers') == "Y") - { - $q1 = "SELECT * FROM {$dbprefix}answers WHERE qid=" - . returnglobal('oldqid') - . " ORDER BY code"; - $r1 = db_execute_assoc($q1); - while ($qr1 = $r1->FetchRow()) - { - if ($filterxsshtml) - { - require_once("../classes/inputfilter/class.inputfilter_clean.php"); - $myFilter = new InputFilter('','',1,1,1); - $qr1['answer']=$myFilter->process($qr1['answer']); - } - else - { - $qr1['answer'] = html_entity_decode_php4($qr1['answer'], ENT_QUOTES, "UTF-8"); - } - - - // Fix bug with FCKEditor saving strange BR types - $qr1['answer']=str_replace('
      ','',$qr1['answer']); - if ($qr1['answer'] == "
      ") - { - $qr1['answer'] = ''; - } - - $qr1 = array_map('db_quote', $qr1); - $i1 = "INSERT INTO {$dbprefix}answers (qid, code, answer, default_value, sortorder, language) " - . "VALUES ('$newqid', '{$qr1['code']}', " - . "'{$qr1['answer']}', '{$qr1['default_value']}', " - . "'{$qr1['sortorder']}', '{$qr1['language']}')"; - $ir1 = $connect->Execute($i1); - } - } - if (returnglobal('copyattributes') == "Y") - { - $q1 = "SELECT * FROM {$dbprefix}question_attributes - WHERE qid=".returnglobal('oldqid')." - ORDER BY qaid"; - $r1 = db_execute_assoc($q1); - while($qr1 = $r1->FetchRow()) - { - $qr1 = array_map('db_quote', $qr1); - $i1 = "INSERT INTO {$dbprefix}question_attributes - (qid, attribute, value) - VALUES ('$newqid', - '{$qr1['attribute']}', - '{$qr1['value']}')"; - $ir1 = $connect->Execute($i1); - } // while - } - } - } - elseif ($action == "delquestion" && ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $actsurrows['define_questions'])) - { - if (!isset($qid)) {$qid=returnglobal('qid');} - //check if any other questions have conditions which rely on this question. Don't delete if there are. - $ccquery = "SELECT * FROM {$dbprefix}conditions WHERE cqid=$qid"; - $ccresult = db_execute_assoc($ccquery) or safe_die ("Couldn't get list of cqids for this question
      ".$ccquery."
      ".$connect->ErrorMsg()); - $cccount=$ccresult->RecordCount(); - while ($ccr=$ccresult->FetchRow()) {$qidarray[]=$ccr['qid'];} - if (isset($qidarray)) {$qidlist=implode(", ", $qidarray);} - if ($cccount) //there are conditions dependant on this question - { - $databaseoutput .= "\n"; - } - else - { - $result = db_execute_assoc("SELECT gid FROM ".db_table_name('questions')." WHERE qid='{$qid}'"); - $row=$result->FetchRow(); - $gid = $row['gid']; - //see if there are any conditions/attributes/answers for this question, and delete them now as well - $cquery = "DELETE FROM {$dbprefix}conditions WHERE qid=$qid"; - $cresult = $connect->Execute($cquery); - $query = "DELETE FROM {$dbprefix}question_attributes WHERE qid=$qid"; - $result = $connect->Execute($query); - $cquery = "DELETE FROM {$dbprefix}answers WHERE qid=$qid"; - $cresult = $connect->Execute($cquery); - $query = "DELETE FROM {$dbprefix}questions WHERE qid=$qid"; - $result = $connect->Execute($query); - fixsortorderQuestions(0,$gid); - if ($result) - { - $qid=""; - $postqid=""; - $_GET['qid']=""; - } - else - { - $databaseoutput .= "\n"; - } - } - } - - elseif ($action == "delquestionall" && ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $actsurrows['define_questions'])) - { - if (!isset($qid)) {$qid=returnglobal('qid');} - //check if any other questions have conditions which rely on this question. Don't delete if there are. - $ccquery = "SELECT * FROM {$dbprefix}conditions WHERE cqid={$_GET['qid']}"; - $ccresult = db_execute_assoc($ccquery) or safe_die ("Couldn't get list of cqids for this question
      ".$ccquery."
      ".$connect->ErrorMsg()); - $cccount=$ccresult->RecordCount(); - while ($ccr=$ccresult->FetchRow()) {$qidarray[]=$ccr['qid'];} - if (isset($qidarray) && $qidarray) {$qidlist=implode(", ", $qidarray);} - if ($cccount) //there are conditions dependant on this question - { - $databaseoutput .= "\n"; - } - else - { - //First delete all the answers - if (!isset($total)) {$total=0;} - $query = "DELETE FROM {$dbprefix}answers WHERE qid=$qid"; - if ($result=$connect->Execute($query)) {$total++;} - $query = "DELETE FROM {$dbprefix}conditions WHERE qid=$qid"; - if ($result=$connect->Execute($query)) {$total++;} - $query = "DELETE FROM {$dbprefix}questions WHERE qid=$qid"; - if ($result=$connect->Execute($query)) {$total++;} - } - if ($total==3) - { - $qid=""; - $postqid=""; - $_GET['qid']=""; - } - else - { - $databaseoutput .= "\n"; - } - } - - elseif ($action == "modanswer" && ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $actsurrows['define_questions'])) - { - - if (isset($_POST['sortorder'])) - { - $postsortorder=sanitize_int($_POST['sortorder']); - } - switch($_POST['method']) - { - // Add a new answer button - case $clang->gT("Add new Answer", "unescaped"): - if (isset($_POST['insertcode']) && $_POST['insertcode']!='' && $_POST['insertcode'] != "0") - { - //$_POST = array_map('db_quote', $_POST);//Removed: qstr is used in SQL below - $_POST['insertcode']=sanitize_paranoid_string($_POST['insertcode']); - $query = "select max(sortorder) as maxorder from ".db_table_name('answers')." where qid='$qid'"; - $result = $connect->Execute($query); - $newsortorder=sprintf("%05d", $result->fields['maxorder']+1); - $anslangs = GetAdditionalLanguagesFromSurveyID($surveyid); - $baselang = GetBaseLanguageFromSurveyID($surveyid); - $query = "select * from ".db_table_name('answers')." where code=".$connect->qstr($_POST['insertcode'])." and language='$baselang' and qid={$postqid}"; - $result = $connect->Execute($query); - - if (isset($result) && $result->RecordCount()>0) - { - $databaseoutput .= "\n"; - } - else - { - - - if ($filterxsshtml) - { - require_once("../classes/inputfilter/class.inputfilter_clean.php"); - $myFilter = new InputFilter('','',1,1,1); - $_POST['insertanswer']=$myFilter->process($_POST['insertanswer']); - } - else - { - $_POST['insertanswer'] = html_entity_decode_php4($_POST['insertanswer'], ENT_QUOTES, "UTF-8"); - } - - // Fix bug with FCKEditor saving strange BR types - $_POST['insertanswer']=str_replace('
      ','',$_POST['insertanswer']); - if ($_POST['insertanswer'] == "
      ") - { - $_POST['insertanswer'] = ''; - } - - // Add new Answer for Base Language Question - $query = "INSERT INTO ".db_table_name('answers')." (qid, code, answer, sortorder, default_value,language) VALUES ('{$postqid}', ".$connect->qstr($_POST['insertcode']).", ".$connect->qstr($_POST['insertanswer']).", '{$newsortorder}', 'N','$baselang')"; - if (!$result = $connect->Execute($query)) - { - $databaseoutput .= "\n"; - } - // Added by lemeur for AutoSaveAll - $_POST['code_'.($newsortorder+0)] = $_POST['insertcode']; - $_POST['previouscode_'.($newsortorder+0)] = $_POST['insertcode']; - $_POST['codeids'] = $_POST['codeids'] . " ".($newsortorder+0); - $_POST['answer_'.$baselang.'_'.($newsortorder+0)] = $_POST['insertanswer']; - $_POST['sortorderids'] = $_POST['sortorderids'] . " ".$baselang."_".($newsortorder+0); - // End lemeur AutoSaveAll - // Last code was successfully inserted - found out the next incrementing code and remember it - $_SESSION['nextanswercode']=getNextCode($_POST['insertcode']); - //Now check if this new code doesn't exist. For now then there is no code inserted. - $query = "select * from ".db_table_name('answers')." where code=".$connect->qstr($_SESSION['nextanswercode'])." and language='$baselang' and qid={$postqid}"; - $result = $connect->Execute($query); - if ($result->RecordCount()>0) unset($_SESSION['nextanswercode']); - - foreach ($anslangs as $anslang) - { - if(!isset($_POST['default'])) $_POST['default'] = ""; - $query = "INSERT INTO ".db_table_name('answers')." (qid, code, answer, sortorder, default_value,language) VALUES ({$postqid}, ".$connect->qstr($_POST['insertcode']).",".$connect->qstr($_POST['insertanswer']).", '{$newsortorder}', 'N','$anslang')"; - if (!$result = $connect->Execute($query)) - { - $databaseoutput .= "\n"; - } - // Added by lemeur for AutoSaveAll - $_POST['answer_'.$anslang.'_'.($newsortorder+0)] = $_POST['insertanswer']; - $_POST['sortorderids'] = $_POST['sortorderids'] . " ".$anslang."_".($newsortorder+0); - // End lemeur AutoSaveAll - } - } - } else { - $databaseoutput .= "\n"; - break; // let's break because in this case we do not want an AutoSaveAll - } - //break; // Commented by lemeur for AutoSaveAll - // Save all answers with one button - case $clang->gT("Save All", "unescaped"): - //Determine autoids by evaluating the hidden field - $sortorderids=explode(' ', trim($_POST['sortorderids'])); - natsort($sortorderids); // // Added by lemeur for AutoSaveAll - $codeids=explode(' ', trim($_POST['codeids'])); - $count=0; - $invalidCode = 0; - $duplicateCode = 0; - - $testarray = array(); - - for ($i=0; $i$value){ - if($value>=2){ - $dupanswers[]=$key; - } - } - - require_once("../classes/inputfilter/class.inputfilter_clean.php"); - $myFilter = new InputFilter('','',1,1,1); - - //First delete all answers - $query = "delete from ".db_table_name('answers')." where qid=".$connect->qstr($qid); - $result = $connect->Execute($query); - - foreach ($sortorderids as $sortorderid) - { - $defaultanswerset='N'; - $langid=substr($sortorderid,0,strrpos($sortorderid,'_')); - $orderid=substr($sortorderid,strrpos($sortorderid,'_')+1,20); - if (isset($_POST['default_answer']) && $_POST['default_answer']==$orderid) - { - $defaultanswerset='Y'; - } - if ($_POST['code_'.$codeids[$count]] != "0" && trim($_POST['code_'.$codeids[$count]]) != "" && !in_array($_POST['code_'.$codeids[$count]],$dupanswers)) - { - //Sanitize input, strip XSS - if ($filterxsshtml) - { - $_POST['answer_'.$sortorderid]=$myFilter->process($_POST['answer_'.$sortorderid]); - } - else - { - $_POST['answer_'.$sortorderid] = html_entity_decode_php4($_POST['answer_'.$sortorderid], ENT_QUOTES, "UTF-8"); - } - - // Fix bug with FCKEditor saving strange BR types - $_POST['answer_'.$sortorderid]=str_replace('
      ','',$_POST['answer_'.$sortorderid]); - if ($_POST['answer_'.$sortorderid] == "
      ") - { - $_POST['answer_'.$sortorderid] = ''; - } - - $_POST['code_'.$codeids[$count]]=sanitize_paranoid_string($_POST['code_'.$codeids[$count]]); - // Now we insert the answers - $query = "INSERT INTO ".db_table_name('answers')." (code,answer,qid,sortorder,language,default_value) - VALUES (".$connect->qstr($_POST['code_'.$codeids[$count]]).", ". - $connect->qstr($_POST['answer_'.$sortorderid]).", ". - $connect->qstr($qid).", ". - $connect->qstr($orderid).", ". - $connect->qstr($langid).", ". - $connect->qstr($defaultanswerset).")"; - if (!$result = $connect->Execute($query)) - { - $databaseoutput .= "\n"; - } - //if ($oldcode != false) - if ($_POST['previouscode_'.$codeids[$count]] != $_POST['code_'.$codeids[$count]]) - { - // Update the Answer code in conditions (updates if row exists right) - $query = "UPDATE ".db_table_name('conditions')." SET value = ".$connect->qstr($_POST['code_'.$codeids[$count]])." where cqid='$qid' and value=".$connect->qstr($_POST['previouscode_'.$codeids[$count]]); - $result = $connect->Execute($query); - // also update references like @sidXgidXqidAid@ - $query = "UPDATE ".db_table_name('conditions')." SET value = '@".$surveyid."X".$gid."X".$qid.db_quote($_POST['code_'.$codeids[$count]])."@' where cqid='$qid' and value='@".$surveyid."X".$gid."X".$qid.db_quote($_POST['previouscode_'.$codeids[$count]])."@'"; - $result = $connect->Execute($query); - } - } else { - if ($_POST['code_'.$codeids[$count]] == "0" || trim($_POST['code_'.$codeids[$count]]) == "") $invalidCode = 1; - if (in_array($_POST['code_'.$codeids[$count]],$dupanswers)) $duplicateCode = 1; - } - $count++; - if ($count>count($codeids)-1) {$count=0;} - } - if ($invalidCode == 1) $databaseoutput .= "\n"; - if ($duplicateCode == 1) $databaseoutput .= "\n"; - break; - - // Pressing the Up button - case $clang->gT("Up", "unescaped"): - $newsortorder=$postsortorder-1; - $oldsortorder=$postsortorder; - $cdquery = "UPDATE ".db_table_name('answers')." SET sortorder=-1 WHERE qid=$qid AND sortorder='$newsortorder'"; - $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); - $cdquery = "UPDATE ".db_table_name('answers')." SET sortorder=$newsortorder WHERE qid=$qid AND sortorder=$oldsortorder"; - $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); - $cdquery = "UPDATE ".db_table_name('answers')." SET sortorder='$oldsortorder' WHERE qid=$qid AND sortorder=-1"; - $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); - break; - - // Pressing the Down button - case $clang->gT("Dn", "unescaped"): - $newsortorder=$postsortorder+1; - $oldsortorder=$postsortorder; - $cdquery = "UPDATE ".db_table_name('answers')." SET sortorder=-1 WHERE qid=$qid AND sortorder='$newsortorder'"; - $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); - $cdquery = "UPDATE ".db_table_name('answers')." SET sortorder='$newsortorder' WHERE qid=$qid AND sortorder=$oldsortorder"; - $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); - $cdquery = "UPDATE ".db_table_name('answers')." SET sortorder=$oldsortorder WHERE qid=$qid AND sortorder=-1"; - $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); - break; - - // Delete Button - case $clang->gT("Del", "unescaped"): - $query = "DELETE FROM ".db_table_name('answers')." WHERE qid={$qid} AND sortorder='{$postsortorder}'"; - if (!$result = $connect->Execute($query)) - { - $databaseoutput .= "\n"; - } - fixsortorderAnswers($qid); - break; - - // Default Button - case $clang->gT("Default", "unescaped"): - $query = "SELECT default_value from ".db_table_name('answers')." where qid={$qid} AND sortorder='{$postsortorder}' GROUP BY default_value"; - $result = db_execute_assoc($query); - $row = $result->FetchRow(); - if ($row['default_value'] == "Y") - { - $query = "UPDATE ".db_table_name('answers')." SET default_value='N' WHERE qid={$qid} AND sortorder='{$postsortorder}'"; - if (!$result = $connect->Execute($query)) - { - $databaseoutput .= "\n"; - } - } else { - $query = "SELECT type from ".db_table_name('questions')." where qid={$qid} GROUP BY type"; - $result = db_execute_assoc($query); - $row = $result->FetchRow(); - if ($row['type'] == "O" || $row['type'] == "L" || $row['type'] == "!") - { // SINGLE CHOICE QUESTION, SET ALL RECORDS TO N, THEN WE SET ONE TO Y - $query = "UPDATE ".db_table_name('answers')." SET default_value='N' WHERE qid={$qid}"; - $result = $connect->Execute($query); - } - $query = "UPDATE ".db_table_name('answers')." SET default_value='Y' WHERE qid={$qid} AND sortorder='{$postsortorder}'"; - if (!$result = $connect->Execute($query)) - { - $databaseoutput .= "\n"; - } - } - break; - } - } - - elseif ($action == "updatesurvey" && ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $actsurrows['edit_survey_property'])) - { - if ($_POST['url'] == "http://") {$_POST['url']="";} - - if (trim($_POST['expires'])=="") - { - $_POST['expires']='1980-01-01'; - } - CleanLanguagesFromSurvey($postsid,$_POST['languageids']); - FixLanguageConsistency($postsid,$_POST['languageids']); - - if($_SESSION['USER_RIGHT_SUPERADMIN'] != 1 && $_SESSION['USER_RIGHT_MANAGE_TEMPLATE'] != 1 && !hasTemplateManageRights($_SESSION['loginID'], $_POST['template'])) $_POST['template'] = "default"; - - $_POST = array_map('db_quote', $_POST); - $usquery = "UPDATE {$dbprefix}surveys \n" - . "SET admin='{$_POST['admin']}', useexpiry='{$_POST['useexpiry']}',\n" - . "expires='{$_POST['expires']}', adminemail='{$_POST['adminemail']}',\n" - . "bounce_email='{$_POST['bounce_email']}',\n" - . "private='{$_POST['private']}', faxto='{$_POST['faxto']}',\n" - . "format='{$_POST['format']}', template='{$_POST['template']}',\n" - . "url='{$_POST['url']}', \n" - . "language='{$_POST['language']}', additional_languages='{$_POST['languageids']}',\n" - . "datestamp='{$_POST['datestamp']}', ipaddr='{$_POST['ipaddr']}', refurl='{$_POST['refurl']}',\n" - . "usecookie='{$_POST['usecookie']}', notification='{$_POST['notification']}',\n" - . "allowregister='{$_POST['allowregister']}', attribute1='{$_POST['attribute1']}',\n" - . "attribute2='{$_POST['attribute2']}', allowsave='{$_POST['allowsave']}',\n" - . "printanswers='{$_POST['printanswers']}',\n" - . "autoredirect='{$_POST['autoredirect']}', allowprev='{$_POST['allowprev']}',\n" - . "listpublic='{$_POST['public']}', htmlemail='{$_POST['htmlemail']}',\n" - . "tokenanswerspersistence='{$_POST['tokenanswerspersistence']}', usecaptcha='{$_POST['usecaptcha']}'\n" - . "WHERE sid={$postsid}"; - - $usresult = $connect->Execute($usquery) or safe_die("Error updating
      ".$usquery."

      ".$connect->ErrorMsg()); - $sqlstring =''; - foreach (GetAdditionalLanguagesFromSurveyID($surveyid) as $langname) - { - if ($langname) - { - $sqlstring .= "and surveyls_language <> '".$langname."' "; - } - } - // Add base language too - $sqlstring .= "and surveyls_language <> '".GetBaseLanguageFromSurveyID($surveyid)."' "; - - $usquery = "Delete from ".db_table_name('surveys_languagesettings')." where surveyls_survey_id={$postsid} ".$sqlstring; - $usresult = $connect->Execute($usquery) or safe_die("Error deleting obsolete surveysettings
      ".$usquery."

      ".$connect->ErrorMsg()); - - foreach (GetAdditionalLanguagesFromSurveyID($surveyid) as $langname) - { - if ($langname) - { - $usquery = "select * from ".db_table_name('surveys_languagesettings')." where surveyls_survey_id={$postsid} and surveyls_language='".$langname."'"; - $usresult = $connect->Execute($usquery) or safe_die("Error deleting obsolete surveysettings
      ".$usquery."

      ".$connect->ErrorMsg()); - if ($usresult->RecordCount()==0) - { - - if (getEmailFormat($surveyid) == "html") - { - $ishtml=true; - } - else - { - $ishtml=false; - } - - $bplang = new limesurvey_lang($langname); - $usquery = "INSERT INTO ".db_table_name('surveys_languagesettings') - ." (surveyls_survey_id, surveyls_language, surveyls_title, " - ." surveyls_email_invite_subj, surveyls_email_invite, " - ." surveyls_email_remind_subj, surveyls_email_remind, " - ." surveyls_email_confirm_subj, surveyls_email_confirm, " - ." surveyls_email_register_subj, surveyls_email_register) " - ." VALUES ({$postsid}, '".$langname."', ''," - .$connect->qstr($bplang->gT("Invitation to participate in survey",'unescaped'))."," - .$connect->qstr(conditional2_nl2br($bplang->gT("Dear {FIRSTNAME},\n\nYou have been invited to participate in a survey.\n\nThe survey is titled:\n\"{SURVEYNAME}\"\n\n\"{SURVEYDESCRIPTION}\"\n\nTo participate, please click on the link below.\n\nSincerely,\n\n{ADMINNAME} ({ADMINEMAIL})\n\n----------------------------------------------\nClick here to do the survey:\n{SURVEYURL}",'unescaped'),$ishtml))."," - .$connect->qstr($bplang->gT("Reminder to participate in survey",'unescaped'))."," - .$connect->qstr(conditional2_nl2br($bplang->gT("Dear {FIRSTNAME},\n\nRecently we invited you to participate in a survey.\n\nWe note that you have not yet completed the survey, and wish to remind you that the survey is still available should you wish to take part.\n\nThe survey is titled:\n\"{SURVEYNAME}\"\n\n\"{SURVEYDESCRIPTION}\"\n\nTo participate, please click on the link below.\n\nSincerely,\n\n{ADMINNAME} ({ADMINEMAIL})\n\n----------------------------------------------\nClick here to do the survey:\n{SURVEYURL}",'unescaped'),$ishtml))."," - .$connect->qstr($bplang->gT("Confirmation of completed survey",'unescaped'))."," - .$connect->qstr(conditional2_nl2br($bplang->gT("Dear {FIRSTNAME},\n\nThis email is to confirm that you have completed the survey titled {SURVEYNAME} and your response has been saved. Thank you for participating.\n\nIf you have any further questions about this email, please contact {ADMINNAME} on {ADMINEMAIL}.\n\nSincerely,\n\n{ADMINNAME}",'unescaped'),$ishtml))."," - .$connect->qstr($bplang->gT("Survey Registration Confirmation",'unescaped'))."," - .$connect->qstr(conditional2_nl2br($bplang->gT("Dear {FIRSTNAME},\n\nYou, or someone using your email address, have registered to participate in an online survey titled {SURVEYNAME}.\n\nTo complete this survey, click on the following URL:\n\n{SURVEYURL}\n\nIf you have any questions about this survey, or if you did not register to participate and believe this email is in error, please contact {ADMINNAME} at {ADMINEMAIL}.",'unescaped'),$ishtml)) - .")"; - unset($bplang); - $usresult = $connect->Execute($usquery) or safe_die("Error deleting obsolete surveysettings
      ".$usquery."

      ".$connect->ErrorMsg()); - } - } - } - - - - if ($usresult) - { - $surveyselect = getsurveylist(); - } - else - { - $databaseoutput .= "\n"; - } - } - - elseif ($action == "delsurvey" && ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $actsurrows['delete_survey'])) //can only happen if there are no groups, no questions, no answers etc. - { - $query = "DELETE FROM {$dbprefix}surveys WHERE sid=$surveyid"; - $result = $connect->Execute($query); - if ($result) - { - $surveyid = ""; - $surveyselect = getsurveylist(); - } - else - { - $databaseoutput .= "\n"; - - } - } - - - // Save the 2nd page from the survey-properties - elseif ($action == "updatesurvey2" && ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $actsurrows['edit_survey_property'])) - { - $languagelist = GetAdditionalLanguagesFromSurveyID($surveyid); - $languagelist[]=GetBaseLanguageFromSurveyID($surveyid); - require_once("../classes/inputfilter/class.inputfilter_clean.php"); - $myFilter = new InputFilter('','',1,1,1); - - foreach ($languagelist as $langname) - { - if ($langname) - { - // Clean XSS attacks - if ($filterxsshtml) - { - $_POST['short_title_'.$langname]=$myFilter->process($_POST['short_title_'.$langname]); - $_POST['description_'.$langname]=$myFilter->process($_POST['description_'.$langname]); - $_POST['welcome_'.$langname]=$myFilter->process($_POST['welcome_'.$langname]); - $_POST['urldescrip_'.$langname]=$myFilter->process($_POST['urldescrip_'.$langname]); - } - else - { - $_POST['short_title_'.$langname] = html_entity_decode_php4($_POST['short_title_'.$langname], ENT_QUOTES, "UTF-8"); - $_POST['description_'.$langname] = html_entity_decode_php4($_POST['description_'.$langname], ENT_QUOTES, "UTF-8"); - $_POST['welcome_'.$langname] = html_entity_decode_php4($_POST['welcome_'.$langname], ENT_QUOTES, "UTF-8"); - $_POST['urldescrip_'.$langname] = html_entity_decode_php4($_POST['urldescrip_'.$langname], ENT_QUOTES, "UTF-8"); - } - - // Fix bug with FCKEditor saving strange BR types - $_POST['short_title_'.$langname]=str_replace('
      ','',$_POST['short_title_'.$langname]); - $_POST['description_'.$langname]=str_replace('
      ','',$_POST['description_'.$langname]); - $_POST['welcome_'.$langname]=str_replace('
      ','',$_POST['welcome_'.$langname]); - $_POST['urldescrip_'.$langname]=str_replace('
      ','',$_POST['urldescrip_'.$langname]); - if ($_POST['short_title_'.$langname] == "
      ") - { - $_POST['short_title_'.$langname] = ''; - } - if ( $_POST['description_'.$langname] == "
      ") - { - $_POST['description_'.$langname] = ''; - } - if ($_POST['welcome_'.$langname] == "
      ") - { - $_POST['welcome_'.$langname] = ''; - } - if ($_POST['urldescrip_'.$langname] == "
      ") - { - $_POST['urldescrip_'.$langname] = ''; - } - - $usquery = "UPDATE ".db_table_name('surveys_languagesettings')." \n" - . "SET surveyls_title='".db_quote($_POST['short_title_'.$langname])."', surveyls_description='".db_quote($_POST['description_'.$langname])."',\n" - . "surveyls_welcometext='".db_quote($_POST['welcome_'.$langname])."',\n" - . "surveyls_urldescription='".db_quote($_POST['urldescrip_'.$langname])."'\n" - . "WHERE surveyls_survey_id=".db_quote($postsid)." and surveyls_language='".$langname."'"; - $usresult = $connect->Execute($usquery) or safe_die("Error updating
      ".$usquery."

      ".$connect->ErrorMsg()); - } - } - } - -} - - - - -elseif ($action == "insertnewsurvey" && $_SESSION['USER_RIGHT_CREATE_SURVEY']) -{ - if ($_POST['url'] == "http://") {$_POST['url']="";} - if (!$_POST['surveyls_title']) - { - $databaseoutput .= "\n"; - } else - { - if (trim($_POST['expires'])=="") - { - $_POST['expires']='1980-01-01'; - } - - // Get random ids until one is found that is not used - do - { - $surveyid = getRandomID(); - $isquery = "SELECT sid FROM ".db_table_name('surveys')." WHERE sid=$surveyid"; - $isresult = db_execute_assoc($isquery); - } - while ($isresult->RecordCount()>0); - - if (!isset($_POST['template'])) {$_POST['template']='default';} - if($_SESSION['USER_RIGHT_SUPERADMIN'] != 1 && $_SESSION['USER_RIGHT_MANAGE_TEMPLATE'] != 1 && !hasTemplateManageRights($_SESSION['loginID'], $_POST['template'])) $_POST['template'] = "default"; - - $_POST = array_map('db_quote', $_POST); - - $isquery = "INSERT INTO {$dbprefix}surveys\n" - . "(sid, owner_id, admin, active, useexpiry, expires, " - . "adminemail, bounce_email, private, faxto, format, template, url, " - . "language, datestamp, ipaddr, refurl, usecookie, notification, allowregister, attribute1, attribute2, " - . "allowsave, autoredirect, allowprev, printanswers, datecreated, listpublic,htmlemail,tokenanswerspersistence,usecaptcha)\n" - . "VALUES ($surveyid, {$_SESSION['loginID']},\n" - . "'{$_POST['admin']}', 'N', \n" - . "'{$_POST['useexpiry']}','{$_POST['expires']}', '{$_POST['adminemail']}', '{$_POST['bounce_email']}', '{$_POST['private']}',\n" - . "'{$_POST['faxto']}', '{$_POST['format']}', '{$_POST['template']}', '{$_POST['url']}',\n" - . "'{$_POST['language']}', '{$_POST['datestamp']}', '{$_POST['ipaddr']}', '{$_POST['refurl']}',\n" - . "'{$_POST['usecookie']}', '{$_POST['notification']}', '{$_POST['allowregister']}',\n" - . "'{$_POST['attribute1']}', '{$_POST['attribute2']}', \n" - . "'{$_POST['allowsave']}', '{$_POST['autoredirect']}', \n" - . "'{$_POST['allowprev']}', '{$_POST['printanswers']}', \n'" - . date("Y-m-d")."', '{$_POST['public']}', '{$_POST['htmlemail']}', '{$_POST['tokenanswerspersistence']}', '{$_POST['usecaptcha']}')"; - - $isresult = $connect->Execute($isquery); - - // insert base language into surveys_language_settings - if ($filterxsshtml) - { - require_once("../classes/inputfilter/class.inputfilter_clean.php"); - $myFilter = new InputFilter('','',1,1,1); - - $_POST['surveyls_title']=$myFilter->process($_POST['surveyls_title']); - $_POST['description']=$myFilter->process($_POST['description']); - $_POST['welcome']=$myFilter->process($_POST['welcome']); - $_POST['urldescrip']=$myFilter->process($_POST['urldescrip']); - } - else - { - $_POST['surveyls_title'] = html_entity_decode_php4($_POST['surveyls_title'], ENT_QUOTES, "UTF-8"); - $_POST['description'] = html_entity_decode_php4($_POST['description'], ENT_QUOTES, "UTF-8"); - $_POST['welcome'] = html_entity_decode_php4($_POST['welcome'], ENT_QUOTES, "UTF-8"); - $_POST['urldescrip'] = html_entity_decode_php4($_POST['urldescrip'], ENT_QUOTES, "UTF-8"); - } - - // Fix bug with FCKEditor saving strange BR types - $_POST['surveyls_title']=str_replace('
      ','',$_POST['surveyls_title']); - $_POST['description']=str_replace('
      ','',$_POST['description']); - $_POST['welcome']=str_replace('
      ','',$_POST['welcome']); - $_POST['urldescrip']=str_replace('
      ','',$_POST['urldescrip']); - if ($_POST['surveyls_title'] == "
      ") - { - $_POST['surveyls_title'] = ''; - } - if ($_POST['description'] == "
      ") - { - $_POST['description'] = ''; - } - if ($_POST['welcome'] = "
      ") - { - $_POST['welcome'] = ''; - } - if ($_POST['urldescrip'] == "
      ") - { - $_POST['urldescrip'] = ''; - } - - // Prepare default emailsettings - if ($_POST['htmlemail'] == "Y") - { - $ishtml=true; - } - else - { - $ishtml=false; - } - $bplang = new limesurvey_lang($_POST['language']); - - $isquery = "INSERT INTO ".db_table_name('surveys_languagesettings') - . "(surveyls_survey_id, surveyls_language, surveyls_title, surveyls_description, surveyls_welcometext, surveyls_urldescription," - ." surveyls_email_invite_subj, surveyls_email_invite, " - ." surveyls_email_remind_subj, surveyls_email_remind, " - ." surveyls_email_confirm_subj, surveyls_email_confirm, " - ." surveyls_email_register_subj, surveyls_email_register) " - . "VALUES ($surveyid, '{$_POST['language']}', '{$_POST['surveyls_title']}', '{$_POST['description']}',\n" - . "'".str_replace("\n", "
      ", $_POST['welcome'])."',\n" - . "'{$_POST['urldescrip']}', " - .$connect->qstr($bplang->gT("Invitation to participate in survey",'unescaped'))."," - .$connect->qstr(conditional2_nl2br($bplang->gT("Dear {FIRSTNAME},\n\nYou have been invited to participate in a survey.\n\nThe survey is titled:\n\"{SURVEYNAME}\"\n\n\"{SURVEYDESCRIPTION}\"\n\nTo participate, please click on the link below.\n\nSincerely,\n\n{ADMINNAME} ({ADMINEMAIL})\n\n----------------------------------------------\nClick here to do the survey:\n{SURVEYURL}",'unescaped'),$ishtml))."," - .$connect->qstr($bplang->gT("Reminder to participate in survey",'unescaped'))."," - .$connect->qstr(conditional2_nl2br($bplang->gT("Dear {FIRSTNAME},\n\nRecently we invited you to participate in a survey.\n\nWe note that you have not yet completed the survey, and wish to remind you that the survey is still available should you wish to take part.\n\nThe survey is titled:\n\"{SURVEYNAME}\"\n\n\"{SURVEYDESCRIPTION}\"\n\nTo participate, please click on the link below.\n\nSincerely,\n\n{ADMINNAME} ({ADMINEMAIL})\n\n----------------------------------------------\nClick here to do the survey:\n{SURVEYURL}",'unescaped'),$ishtml))."," - .$connect->qstr($bplang->gT("Confirmation of completed survey",'unescaped'))."," - .$connect->qstr(conditional2_nl2br($bplang->gT("Dear {FIRSTNAME},\n\nThis email is to confirm that you have completed the survey titled {SURVEYNAME} and your response has been saved. Thank you for participating.\n\nIf you have any further questions about this email, please contact {ADMINNAME} on {ADMINEMAIL}.\n\nSincerely,\n\n{ADMINNAME}",'unescaped'),$ishtml))."," - .$connect->qstr($bplang->gT("Survey Registration Confirmation",'unescaped'))."," - .$connect->qstr(conditional2_nl2br($bplang->gT("Dear {FIRSTNAME},\n\nYou, or someone using your email address, have registered to participate in an online survey titled {SURVEYNAME}.\n\nTo complete this survey, click on the following URL:\n\n{SURVEYURL}\n\nIf you have any questions about this survey, or if you did not register to participate and believe this email is in error, please contact {ADMINNAME} at {ADMINEMAIL}.",'unescaped'),$ishtml)) - .")"; - - $isresult = $connect->Execute($isquery); - unset($bplang); - - // Insert into survey_rights - $isrquery = "INSERT INTO {$dbprefix}surveys_rights VALUES($surveyid,". $_SESSION['loginID'].",1,1,1,1,1,1)"; //inserts survey rights for owner - $isrresult = $connect->Execute($isrquery) or safe_die ($isrquery."
      ".$connect->ErrorMsg()); //ADDED by Moses - if ($isresult) - { - $surveyselect = getsurveylist(); - } - else - { - $errormsg=$clang->gT("Survey could not be created","js")." - ".$connect->ErrorMsg(); - $databaseoutput .= "\n"; - $databaseoutput .= htmlspecialchars($isquery); - } - } -} - -else -{ - - include("access_denied.php"); -} - - -?> +RenameTableSQL($oldtable, $newtable); + return $result[0]; +} + + +/* +* Gets the maximum question_order field value for a group +* @gid: The id of the group +*/ + +/** +* Gets the maximum question_order field value for a group +* +* @param mixed $gid +* @return mixed +*/ +function get_max_question_order($gid) +{ + global $connect ; + global $dbprefix ; + $query="SELECT MAX(question_order) as maxorder FROM {$dbprefix}questions where gid=".$gid ; + // echo $query; + $result = db_execute_assoc($query); + $gv = $result->FetchRow(); + return $gv['maxorder']; +} + +$databaseoutput =''; + +if(isset($surveyid)) +{ + $actsurquery = "SELECT define_questions, edit_survey_property, delete_survey FROM {$dbprefix}surveys_rights WHERE sid=$surveyid AND uid = ".$_SESSION['loginID']; //Getting rights for this survey + $actsurresult = db_execute_assoc($actsurquery); + $actsurrows = $actsurresult->FetchRow(); + + if ($action == "delattribute" && ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $actsurrows['define_questions'])) + { + $query = "DELETE FROM ".db_table_name('question_attributes')." + WHERE qaid={$postqaid} AND qid={$postqid}"; + $result=$connect->Execute($query) or safe_die("Couldn't delete attribute
      ".$query."
      ".$connect->ErrorMsg()); + } + elseif ($action == "addattribute" && ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $actsurrows['define_questions'])) + { + if (isset($_POST['attribute_value']) && (!empty($_POST['attribute_value']) || $_POST['attribute_value'] == "0")) + { + if ($_POST['attribute_name']=='dropdown_separators' || $_POST['attribute_name']=='dualscale_headerA' || $_POST['attribute_name']=='dualscale_headerB' || + $_POST['attribute_name']=='dropdown_prepostfix' || $_POST['attribute_name']=='prefix' || $_POST['attribute_name']=='suffix') + { + if ($filterxsshtml) + { + require_once("../classes/inputfilter/class.inputfilter_clean.php"); + $myFilter = new InputFilter('','',1,1,1); + $_POST['attribute_value']=$myFilter->process($_POST['attribute_value']); + } + else + { + $_POST['attribute_value'] = html_entity_decode($_POST['attribute_value'], ENT_QUOTES, "UTF-8"); + } + } + + $_POST = array_map('db_quote', $_POST); + $query = "INSERT INTO ".db_table_name('question_attributes')." + (qid, attribute, value) + VALUES ('{$postqid}', '{$_POST['attribute_name']}', '{$_POST['attribute_value']}')"; + $result = $connect->Execute($query) or safe_die("Error
      ".$query."
      ".$connect->ErrorMsg()); + } + } + elseif ($action == "editattribute" && ( $_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $actsurrows['define_questions'])) + { + if (isset($_POST['attribute_value']) && (!empty($_POST['attribute_value']) || $_POST['attribute_value'] == "0")) + { + $query = "UPDATE ".db_table_name('question_attributes')." + SET value='{$_POST['attribute_value']}' WHERE qaid=".$postqaid." AND qid=".returnglobal('qid'); + $result = $connect->Execute($query) or safe_die("Error
      ".$query."
      ".$connect->ErrorMsg()); + } + } + elseif ($action == "insertnewgroup" && ( $_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $actsurrows['define_questions'])) + { + $grplangs = GetAdditionalLanguagesFromSurveyID($postsid); + $baselang = GetBaseLanguageFromSurveyID($postsid); + $grplangs[] = $baselang; + $errorstring = ''; + foreach ($grplangs as $grouplang) + { + if (!$_POST['group_name_'.$grouplang]) { $errorstring.= GetLanguageNameFromCode($grouplang,false)."\\n";} + } + if ($errorstring!='') + { + $databaseoutput .= "\n"; + } + + else + { + $first=true; + require_once("../classes/inputfilter/class.inputfilter_clean.php"); + $myFilter = new InputFilter('','',1,1,1); + + foreach ($grplangs as $grouplang) + { + //Clean XSS + if ($filterxsshtml) + { + $_POST['group_name_'.$grouplang]=$myFilter->process($_POST['group_name_'.$grouplang]); + $_POST['description_'.$grouplang]=$myFilter->process($_POST['description_'.$grouplang]); + } + else + { + $_POST['group_name_'.$grouplang] = html_entity_decode($_POST['group_name_'.$grouplang], ENT_QUOTES, "UTF-8"); + $_POST['description_'.$grouplang] = html_entity_decode($_POST['description_'.$grouplang], ENT_QUOTES, "UTF-8"); + } + + // Fix bug with FCKEditor saving strange BR types + $_POST['group_name_'.$grouplang]=fix_FCKeditor_text($_POST['group_name_'.$grouplang]); + $_POST['description_'.$grouplang]=fix_FCKeditor_text($_POST['description_'.$grouplang]); + + //$_POST = array_map('db_quote', $_POST); + + if ($first) + { + $query = "INSERT INTO ".db_table_name('groups')." (sid, group_name, description,group_order,language) VALUES ('".db_quote($postsid)."', '".db_quote($_POST['group_name_'.$grouplang])."', '".db_quote($_POST['description_'.$grouplang])."',".getMaxgrouporder(returnglobal('sid')).",'{$grouplang}')"; + $result = $connect->Execute($query); + $groupid=$connect->Insert_Id(db_table_name_nq('groups'),"gid"); + $first=false; + } + else{ + $query = "INSERT INTO ".db_table_name('groups')." (gid, sid, group_name, description,group_order,language) VALUES ('{$groupid}','".db_quote($postsid)."', '".db_quote($_POST['group_name_'.$grouplang])."', '".db_quote($_POST['description_'.$grouplang])."',".getMaxgrouporder(returnglobal('sid')).",'{$grouplang}')"; + if ($connect->databaseType == 'odbc_mssql' || $connect->databaseType == 'odbtp' || $connect->databaseType == 'mssql_n') $query = 'SET IDENTITY_INSERT '.db_table_name('groups')." ON; " . $query . 'SET IDENTITY_INSERT '.db_table_name('groups')." OFF;"; + $result = $connect->Execute($query) or safe_die("Error
      ".$query."
      ".$connect->ErrorMsg()); + } + if (!$result) + { + $databaseoutput .= $clang->gT("Error: The database reported the following error:")."
      \n"; + $databaseoutput .= "" . htmlspecialchars($connect->ErrorMsg()) . "\n"; + $databaseoutput .= "
      ".htmlspecialchars($query)."
      \n"; + $databaseoutput .= "\n"; + exit; + } + } + // This line sets the newly inserted group as the new group + if (isset($groupid)){$gid=$groupid;} + + } + } + + elseif ($action == "updategroup" && ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $actsurrows['define_questions'])) + { + $grplangs = GetAdditionalLanguagesFromSurveyID($postsid); + $baselang = GetBaseLanguageFromSurveyID($postsid); + array_push($grplangs,$baselang); + require_once("../classes/inputfilter/class.inputfilter_clean.php"); + $myFilter = new InputFilter('','',1,1,1); + foreach ($grplangs as $grplang) + { + if (isset($grplang) && $grplang != "") + { + if ($filterxsshtml) + { + $_POST['group_name_'.$grplang]=$myFilter->process($_POST['group_name_'.$grplang]); + $_POST['description_'.$grplang]=$myFilter->process($_POST['description_'.$grplang]); + } + else + { + $_POST['group_name_'.$grplang] = html_entity_decode($_POST['group_name_'.$grplang], ENT_QUOTES, "UTF-8"); + $_POST['description_'.$grplang] = html_entity_decode($_POST['description_'.$grplang], ENT_QUOTES, "UTF-8"); + } + + // Fix bug with FCKEditor saving strange BR types + $_POST['group_name_'.$grplang]=fix_FCKeditor_text($_POST['group_name_'.$grplang]); + $_POST['description_'.$grplang]=fix_FCKeditor_text($_POST['description_'.$grplang]); + + // don't use array_map db_quote on POST + // since this is iterated for each language + //$_POST = array_map('db_quote', $_POST); + $ugquery = "UPDATE ".db_table_name('groups')." SET group_name='".db_quote($_POST['group_name_'.$grplang])."', description='".db_quote($_POST['description_'.$grplang])."' WHERE sid=".db_quote($postsid)." AND gid=".db_quote($postgid)." AND language='{$grplang}'"; + $ugresult = $connect->Execute($ugquery); + if ($ugresult) + { + $groupsummary = getgrouplist($postgid); + } + else + { + $databaseoutput .= "\n"; + } + } + } + + } + + elseif ($action == "delgroupnone" && ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $actsurrows['define_questions'])) + { + if (!isset($gid)) $gid=returnglobal('gid'); + + $query = "DELETE FROM ".db_table_name('assessments')." WHERE sid=$surveyid AND gid=$gid"; + $result = $connect->Execute($query) or safe_die($connect->ErrorMsg()) ; + + $query = "DELETE FROM ".db_table_name('groups')." WHERE sid=$surveyid AND gid=$gid"; + $result = $connect->Execute($query) or safe_die($connect->ErrorMsg()) ; + + if ($result) + { + $gid = ""; + $groupselect = getgrouplist($gid); + fixsortorderGroups(); + } + else + { + $databaseoutput .= "\n"; + } + } + + elseif ($action == "delgroup" && ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $actsurrows['define_questions'])) + { + if (!isset($gid)) $gid=returnglobal('gid'); + $query = "SELECT qid FROM ".db_table_name('groups').", ".db_table_name('questions')." WHERE ".db_table_name('groups').".gid=".db_table_name('questions').".gid AND ".db_table_name('groups').".gid=$gid"; + if ($result = db_execute_assoc($query)) + { + if (!isset($total)) $total=0; + $qtodel=$result->RecordCount(); + while ($row=$result->FetchRow()) + { + $dquery = "DELETE FROM ".db_table_name('conditions')." WHERE qid={$row['qid']}"; + if ($dresult=$connect->Execute($dquery)) {$total++;} + $dquery = "DELETE FROM ".db_table_name('answers')." WHERE qid={$row['qid']}"; + if ($dresult=$connect->Execute($dquery)) {$total++;} + $dquery = "DELETE FROM ".db_table_name('question_attributes')." WHERE qid={$row['qid']}"; + if ($dresult=$connect->Execute($dquery)) {$total++;} + $dquery = "DELETE FROM ".db_table_name('questions')." WHERE qid={$row['qid']}"; + if ($dresult=$connect->Execute($dquery)) {$total++;} + } + if ($total != $qtodel*4) + { + $databaseoutput .= "\n"; + } + } + $query = "DELETE FROM ".db_table_name('assessments')." WHERE sid=$surveyid AND gid=$gid"; + $result = $connect->Execute($query) or safe_die($connect->ErrorMsg()) ; + + $query = "DELETE FROM ".db_table_name('groups')." WHERE sid=$surveyid AND gid=$gid"; + $result = $connect->Execute($query) or safe_die($connect->ErrorMsg()) ; + if ($result) + { + $gid = ""; + $groupselect = getgrouplist($gid); + fixsortorderGroups(); + } + else + { + $databaseoutput .= "\n"; + } + } + + elseif ($action == "insertnewquestion" && ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $actsurrows['define_questions'])) + { + $baselang = GetBaseLanguageFromSurveyID($postsid); + if (strlen($_POST['title']) < 1) + { + $databaseoutput .= "\n"; + } + else + { + if (!isset($_POST['lid']) || $_POST['lid'] == '') {$_POST['lid']="0";} + if (!isset($_POST['lid1']) || $_POST['lid1'] == '') {$_POST['lid1']="0";} + if(!empty($_POST['questionposition']) || $_POST['questionposition'] == '0') + { + //Bug Fix: remove +1 -> $question_order=(sanitize_int($_POST['questionposition'])+1); + $question_order=(sanitize_int($_POST['questionposition'])); + //Need to renumber all questions on or after this + $cdquery = "UPDATE ".db_table_name('questions')." SET question_order=question_order+1 WHERE gid=".$postgid." AND question_order >= ".$question_order; + $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); + } else { + $question_order=(getMaxquestionorder($postgid)); + $question_order++; + } + + if ($filterxsshtml) + { + require_once("../classes/inputfilter/class.inputfilter_clean.php"); + $myFilter = new InputFilter('','',1,1,1); + $_POST['title']=$myFilter->process($_POST['title']); + $_POST['question_'.$baselang]=$myFilter->process($_POST['question_'.$baselang]); + $_POST['help_'.$baselang]=$myFilter->process($_POST['help_'.$baselang]); + } + else + { + $_POST['title'] = html_entity_decode($_POST['title'], ENT_QUOTES, "UTF-8"); + $_POST['question_'.$baselang] = html_entity_decode($_POST['question_'.$baselang], ENT_QUOTES, "UTF-8"); + $_POST['help_'.$baselang] = html_entity_decode($_POST['help_'.$baselang], ENT_QUOTES, "UTF-8"); + } + + // Fix bug with FCKEditor saving strange BR types + $_POST['title']=fix_FCKeditor_text($_POST['title']); + $_POST['question_'.$baselang]=fix_FCKeditor_text($_POST['question_'.$baselang]); + $_POST['help_'.$baselang]=fix_FCKeditor_text($_POST['help_'.$baselang]); + + $_POST = array_map('db_quote', $_POST); + $query = "INSERT INTO ".db_table_name('questions')." (sid, gid, type, title, question, preg, help, other, mandatory, lid, lid1, question_order, language)" + ." VALUES ('{$postsid}', '{$postgid}', '{$_POST['type']}', '{$_POST['title']}'," + ." '{$_POST['question_'.$baselang]}', '{$_POST['preg']}', '{$_POST['help_'.$baselang]}', '{$_POST['other']}', '{$_POST['mandatory']}', '{$_POST['lid']}', '{$_POST['lid1']}',$question_order,'{$baselang}')"; + $result = $connect->Execute($query); + // Get the last inserted questionid for other languages + $qid=$connect->Insert_ID(db_table_name_nq('questions'),"qid"); + + // Add other languages + if ($result) + { + $addlangs = GetAdditionalLanguagesFromSurveyID($postsid); + foreach ($addlangs as $alang) + { + if ($alang != "") + { + $query = "INSERT INTO ".db_table_name('questions')." (qid, sid, gid, type, title, question, preg, help, other, mandatory, lid, lid1, question_order, language)" + ." VALUES ('$qid','{$postsid}', '{$postgid}', '{$_POST['type']}', '{$_POST['title']}'," + ." '{$_POST['question_'.$alang]}', '{$_POST['preg']}', '{$_POST['help_'.$alang]}', '{$_POST['other']}', '{$_POST['mandatory']}', '{$_POST['lid']}', '{$_POST['lid1']}',$question_order,'{$alang}')"; + if ($connect->databaseType == 'odbc_mssql' || $connect->databaseType == 'odbtp' || $connect->databaseType == 'mssql_n') $query = "SET IDENTITY_INSERT ".db_table_name('questions')." ON; " . $query . "SET IDENTITY_INSERT ".db_table_name('questions')." OFF;"; + $result2 = $connect->Execute($query); + if (!$result2) + { + $databaseoutput .= "\n"; + + } + } + } + } + + + if (!$result) + { + $databaseoutput .= "\n"; + + } + if (isset($_POST['attribute_value']) && $_POST['attribute_value']) + { + $query = "INSERT INTO ".db_table_name('question_attributes')." + (qid, attribute, value) + VALUES + ($qid, '".$_POST['attribute_name']."', '".$_POST['attribute_value']."')"; + $result = $connect->Execute($query); + } + fixsortorderQuestions($postgid, $surveyid); + } + } + elseif ($action == "renumberquestions" && ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $actsurrows['define_questions'])) + { + //Automatically renumbers the "question codes" so that they follow + //a methodical numbering method + $question_number=1; + $group_number=0; + $gselect="SELECT a.qid, a.gid\n" + ."FROM ".db_table_name('questions')." as a, ".db_table_name('groups')."\n" + ."WHERE a.gid=".db_table_name('groups').".gid\n" + ."AND a.sid=$surveyid\n" + ."GROUP BY a.gid, a.qid, ".db_table_name('groups').".group_order, question_order\n" + ."ORDER BY ".db_table_name('groups').".group_order, question_order"; + $gresult=db_execute_assoc($gselect) or safe_die ("Error: ".$connect->ErrorMsg()); + $grows = array(); //Create an empty array in case FetchRow does not return any rows + while ($grow = $gresult->FetchRow()) {$grows[] = $grow;} // Get table output into array + foreach($grows as $grow) + { + //Go through all the questions + if ((isset($_POST['style']) && $_POST['style']=="bygroup") && (!isset($group_number) || $group_number != $grow['gid'])) + { //If we're doing this by group, restart the numbering when the group number changes + $question_number=1; + $group_number++; + } + $usql="UPDATE ".db_table_name('questions')."\n" + ."SET title='".str_pad($question_number, 4, "0", STR_PAD_LEFT)."'\n" + ."WHERE qid=".$grow['qid']; + //$databaseoutput .= "[$sql]"; + $uresult=$connect->Execute($usql) or safe_die("Error: ".$connect->ErrorMsg()); + $question_number++; + $group_number=$grow['gid']; + } + } + + elseif ($action == "updatequestion" && ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $actsurrows['define_questions'])) + { + $cqquery = "SELECT type, gid FROM ".db_table_name('questions')." WHERE qid={$postqid}"; + $cqresult=db_execute_assoc($cqquery) or safe_die ("Couldn't get question type to check for change
      ".$cqquery."
      ".$connect->ErrorMsg()); + $cqr=$cqresult->FetchRow(); + $oldtype=$cqr['type']; + $oldgid=$cqr['gid']; + + // Remove invalid question attributes on saving + $qattributes=questionAttributes(); + $attsql="delete from ".db_table_name('question_attributes')." where qid='{$postqid}' and "; + if (isset($qattributes[$_POST['type']])){ + $validAttributes=$qattributes[$_POST['type']]; + foreach ($validAttributes as $validAttribute) + { + $attsql.='attribute<>'.db_quoteall($validAttribute['name'])." and "; + } + } + $attsql.='1=1'; + db_execute_assoc($attsql) or safe_die ("Couldn't delete obsolete question attributes
      ".$attsql."
      ".$connect->ErrorMsg()); + + $keepanswers = "1"; // Generally we try to keep answers if the question type has changed + + // These are the questions types that have no answers and therefore we delete the answer in that case + if (($_POST['type']== "5") || ($_POST['type']== "D") || ($_POST['type']== "G") || + ($_POST['type']== "I") || ($_POST['type']== "N") || ($_POST['type']== "S") || + ($_POST['type']== "T") || ($_POST['type']== "U") || ($_POST['type']== "X") || + ($_POST['type']=="Y")) + { + $keepanswers = "0"; + } + + // These are the questions types that use labelsets and + // therefore we set the label set of all other question types to 0 + if (($_POST['type']!= "F") && ($_POST['type']!= "H") && ($_POST['type']!= "W") && + ($_POST['type']!= "Z") && ($_POST['type']!= "1") && ($_POST['type']!= ":") && + ($_POST['type']!= ";")) + { + $_POST['lid']=0; + } + + // These are the questions types that have the other option therefore we set everything else to 'No Other' + if (($_POST['type']!= "L") && ($_POST['type']!= "!") && ($_POST['type']!= "P") && ($_POST['type']!="M") && ($_POST['type'] != "W") && ($_POST['type'] != "Z")) + { + $_POST['other']='N'; + } + + // These are the questions types that have no validation - so zap it accordingly + + if ($_POST['type']== "!" || $_POST['type']== "L" || $_POST['type']== "M" || $_POST['type']== "P" || $_POST['type']== "W" || + $_POST['type']== "Z" || $_POST['type']== "F" || $_POST['type']== "H" || $_POST['type']== ":" || $_POST['type']== ";" || + $_POST['type']== "X" || $_POST['type']== "") + { + $_POST['preg']=''; + } + + + + if ($oldtype != $_POST['type']) + { + //Make sure there are no conditions based on this question, since we are changing the type + $ccquery = "SELECT * FROM ".db_table_name('conditions')." WHERE cqid={$postqid}"; + $ccresult = db_execute_assoc($ccquery) or safe_die ("Couldn't get list of cqids for this question
      ".$ccquery."
      ".$connect->ErrorMsg()); + $cccount=$ccresult->RecordCount(); + while ($ccr=$ccresult->FetchRow()) {$qidarray[]=$ccr['qid'];} + if (isset($qidarray) && $qidarray) {$qidlist=implode(", ", $qidarray);} + } + if (isset($cccount) && $cccount) + { + $databaseoutput .= "\n"; + } + else + { + if (isset($postgid) && $postgid != "") + { + + $array_result=checkMovequestionConstraintsForConditions(sanitize_int($postsid),sanitize_int($postqid), sanitize_int($postgid)); + // If there is no blocking conditions that could prevent this move + if (is_null($array_result['notAbove']) && is_null($array_result['notBelow'])) + { + + $questlangs = GetAdditionalLanguagesFromSurveyID($postsid); + $baselang = GetBaseLanguageFromSurveyID($postsid); + array_push($questlangs,$baselang); + if ($filterxsshtml) + { + require_once("../classes/inputfilter/class.inputfilter_clean.php"); + $myFilter = new InputFilter('','',1,1,1); + $_POST['title']=$myFilter->process($_POST['title']); + } + else + { + $_POST['title'] = html_entity_decode($_POST['title'], ENT_QUOTES, "UTF-8"); + } + + // Fix bug with FCKEditor saving strange BR types + $_POST['title']=fix_FCKeditor_text($_POST['title']); + + foreach ($questlangs as $qlang) + { + if ($filterxsshtml) + { + $_POST['question_'.$qlang]=$myFilter->process($_POST['question_'.$qlang]); + $_POST['help_'.$qlang]=$myFilter->process($_POST['help_'.$qlang]); + } + else + { + $_POST['question_'.$qlang] = html_entity_decode($_POST['question_'.$qlang], ENT_QUOTES, "UTF-8"); + $_POST['help_'.$qlang] = html_entity_decode($_POST['help_'.$qlang], ENT_QUOTES, "UTF-8"); + } + // Fix bug with FCKEditor saving strange BR types + $_POST['question_'.$qlang]=fix_FCKeditor_text($_POST['question_'.$qlang]); + $_POST['help_'.$qlang]=fix_FCKeditor_text($_POST['help_'.$qlang]); + + if (isset($qlang) && $qlang != "") + { // ToDo: Sanitize the POST variables ! + $uqquery = "UPDATE ".db_table_name('questions') + . "SET type='".db_quote($_POST['type'])."', title='".db_quote($_POST['title'])."', " + . "question='".db_quote($_POST['question_'.$qlang])."', preg='".db_quote($_POST['preg'])."', help='".db_quote($_POST['help_'.$qlang])."', " + . "gid='".db_quote($postgid)."', other='".db_quote($_POST['other'])."', " + . "mandatory='".db_quote($_POST['mandatory'])."'"; + if ($oldgid!=$postgid) + { + if ( getGroupOrder(returnglobal('sid'),$oldgid) > getGroupOrder(returnglobal('sid'),returnglobal('gid')) ) + { + // Moving question to a 'upper' group + // insert question at the end of the destination group + // this prevent breaking conditions if the target qid is in the dest group + $insertorder = getMaxquestionorder($postgid) + 1; + $uqquery .=', question_order='.$insertorder.' '; + } + else + { + // Moving question to a 'lower' group + // insert question at the beginning of the destination group + shiftorderQuestions($postsid,$postgid,1); // makes 1 spare room for new question at top of dest group + $uqquery .=', question_order=0 '; + } + } + if (isset($_POST['lid']) && trim($_POST['lid'])!="") + { + $uqquery.=", lid='".db_quote($_POST['lid'])."' "; + } + if (isset($_POST['lid1']) && trim($_POST['lid1'])!="") + { + $uqquery.=", lid1='".db_quote($_POST['lid1'])."' "; + } + + $uqquery.= "WHERE sid='".db_quote($postsid)."' AND qid='".db_quote($postqid)."' AND language='{$qlang}'"; + $uqresult = $connect->Execute($uqquery) or safe_die ("Error Update Question: ".$uqquery."
      ".$connect->ErrorMsg()); + if (!$uqresult) + { + $databaseoutput .= "\n"; + } + } + } + // if the group has changed then fix the sortorder of old and new group + if ($oldgid!=$postgid) + { + fixsortorderQuestions($oldgid, $surveyid); + fixsortorderQuestions($postgid, $surveyid); + + // If some questions have conditions set on this question's answers + // then change the cfieldname accordingly + fixmovedquestionConditions($postqid, $oldgid, $postgid); + } + if ($keepanswers == "0") + { + $query = "DELETE FROM ".db_table_name('answers')." WHERE qid=".db_quote($postqid); + $result = $connect->Execute($query) or safe_die("Error: ".$connect->ErrorMsg()); + if (!$result) + { + $databaseoutput .= "\n"; + } + } + } + else + { + // There are conditions constraints: alert the user + $errormsg=""; + if (!is_null($array_result['notAbove'])) + { + $errormsg.=$clang->gT("This question relies on other question's answers and can't be moved above groupId:","js") + . " " . $array_result['notAbove'][0][0] . " " . $clang->gT("in position","js")." ".$array_result['notAbove'][0][1]."\\n" + . $clang->gT("See conditions:")."\\n"; + + foreach ($array_result['notAbove'] as $notAboveCond) + { + $errormsg.="- cid:". $notAboveCond[3]."\\n"; + } + + } + if (!is_null($array_result['notBelow'])) + { + $errormsg.=$clang->gT("Some questions rely on this question's answers. You can't move this question below groupId:","js") + . " " . $array_result['notBelow'][0][0] . " " . $clang->gT("in position","js")." ".$array_result['notBelow'][0][1]."\\n" + . $clang->gT("See conditions:")."\\n"; + + foreach ($array_result['notBelow'] as $notBelowCond) + { + $errormsg.="- cid:". $notBelowCond[3]."\\n"; + } + } + + $databaseoutput .= "\n"; + $gid= $oldgid; // group move impossible ==> keep display on oldgid + } + } + else + { + $databaseoutput .= "\n"; + } + } + } + + elseif ($action == "copynewquestion" && ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $actsurrows['define_questions'])) + { + + if (!$_POST['title']) + { + $databaseoutput .= "\n"; + } + else + { + $questlangs = GetAdditionalLanguagesFromSurveyID($postsid); + $baselang = GetBaseLanguageFromSurveyID($postsid); + + if (!isset($_POST['lid']) || $_POST['lid']=='') {$_POST['lid']=0;} + if (!isset($_POST['lid1']) || $_POST['lid1']=='') {$_POST['lid1']=0;} + //Get maximum order from the question group + $max=get_max_question_order($postgid)+1 ; + // Insert the base language of the question + if ($filterxsshtml) + { + require_once("../classes/inputfilter/class.inputfilter_clean.php"); + $myFilter = new InputFilter('','',1,1,1); + // Prevent XSS attacks + $_POST['title']=$myFilter->process($_POST['title']); + $_POST['question_'.$baselang]=$myFilter->process($_POST['question_'.$baselang]); + $_POST['help_'.$baselang]=$myFilter->process($_POST['help_'.$baselang]); + } + else + { + $_POST['title'] = html_entity_decode($_POST['title'], ENT_QUOTES, "UTF-8"); + $_POST['question_'.$baselang] = html_entity_decode($_POST['question_'.$baselang], ENT_QUOTES, "UTF-8"); + $_POST['help_'.$baselang] = html_entity_decode($_POST['help_'.$baselang], ENT_QUOTES, "UTF-8"); + } + + + // Fix bug with FCKEditor saving strange BR types + $_POST['title']=fix_FCKeditor_text($_POST['title']); + $_POST['question_'.$baselang]=fix_FCKeditor_text($_POST['question_'.$baselang]); + $_POST['help_'.$baselang]=fix_FCKeditor_text($_POST['help_'.$baselang]); + $_POST = array_map('db_quote', $_POST); + $query = "INSERT INTO {$dbprefix}questions (sid, gid, type, title, question, preg, help, other, mandatory, lid, lid1, question_order, language) + VALUES ({$postsid}, {$postgid}, '{$_POST['type']}', '{$_POST['title']}', '".$_POST['question_'.$baselang]."', '{$_POST['preg']}', '".$_POST['help_'.$baselang]."', '{$_POST['other']}', '{$_POST['mandatory']}', '{$_POST['lid']}', '{$_POST['lid1']}',$max,".db_quoteall($baselang).")"; + $result = $connect->Execute($query) or safe_die($connect->ErrorMsg()); + $newqid = $connect->Insert_ID("{$dbprefix}questions","qid"); + if (!$result) + { + $databaseoutput .= "\n"; + + } + + foreach ($questlangs as $qlanguage) + { + if ($filterxsshtml) + { + $_POST['question_'.$qlanguage]=$myFilter->process($_POST['question_'.$qlanguage]); + $_POST['help_'.$qlanguage]=$myFilter->process($_POST['help_'.$qlanguage]); + } + else + { + $_POST['question_'.$qlanguage] = html_entity_decode($_POST['question_'.$qlanguage], ENT_QUOTES, "UTF-8"); + $_POST['help_'.$qlanguage] = html_entity_decode($_POST['help_'.$qlanguage], ENT_QUOTES, "UTF-8"); + } + + // Fix bug with FCKEditor saving strange BR types + $_POST['question_'.$qlanguage]=fix_FCKeditor_text($_POST['question_'.$qlanguage]); + $_POST['help_'.$qlanguage]=fix_FCKeditor_text($_POST['help_'.$qlanguage]); + + if ($connect->databaseType == 'odbc_mssql' || $connect->databaseType == 'odbtp' || $connect->databaseType == 'mssql_n') {@$connect->Execute('SET IDENTITY_INSERT '.db_table_name('questions')." ON");} + $query = "INSERT INTO {$dbprefix}questions (qid, sid, gid, type, title, question, help, other, mandatory, lid, lid1, question_order, language) + VALUES ($newqid,{$postsid}, {$postgid}, '{$_POST['type']}', '{$_POST['title']}', '".$_POST['question_'.$qlanguage]."', '".$_POST['help_'.$qlanguage]."', '{$_POST['other']}', '{$_POST['mandatory']}', '{$_POST['lid']}', '{$_POST['lid1']}', $max,".db_quoteall($qlanguage).")"; + $result = $connect->Execute($query) or safe_die($connect->ErrorMsg()); + if ($connect->databaseType == 'odbc_mssql' || $connect->databaseType == 'odbtp' || $connect->databaseType == 'mssql_n') {@$connect->Execute('SET IDENTITY_INSERT '.db_table_name('questions')." OFF");} + } + if (!$result) + { + $databaseoutput .= "\n"; + + } + if (returnglobal('copyanswers') == "Y") + { + $q1 = "SELECT * FROM {$dbprefix}answers WHERE qid=" + . returnglobal('oldqid') + . " ORDER BY code"; + $r1 = db_execute_assoc($q1); + while ($qr1 = $r1->FetchRow()) + { + if ($filterxsshtml) + { + require_once("../classes/inputfilter/class.inputfilter_clean.php"); + $myFilter = new InputFilter('','',1,1,1); + $qr1['answer']=$myFilter->process($qr1['answer']); + } + else + { + $qr1['answer'] = html_entity_decode($qr1['answer'], ENT_QUOTES, "UTF-8"); + } + + + // Fix bug with FCKEditor saving strange BR types + $qr1['answer']=fix_FCKeditor_text($qr1['answer']); + + $qr1 = array_map('db_quote', $qr1); + $i1 = "INSERT INTO {$dbprefix}answers (qid, code, answer, default_value, sortorder, language) " + . "VALUES ('$newqid', '{$qr1['code']}', " + . "'{$qr1['answer']}', '{$qr1['default_value']}', " + . "'{$qr1['sortorder']}', '{$qr1['language']}')"; + $ir1 = $connect->Execute($i1); + } + } + if (returnglobal('copyattributes') == "Y") + { + $q1 = "SELECT * FROM {$dbprefix}question_attributes + WHERE qid=".returnglobal('oldqid')." + ORDER BY qaid"; + $r1 = db_execute_assoc($q1); + while($qr1 = $r1->FetchRow()) + { + $qr1 = array_map('db_quote', $qr1); + $i1 = "INSERT INTO {$dbprefix}question_attributes + (qid, attribute, value) + VALUES ('$newqid', + '{$qr1['attribute']}', + '{$qr1['value']}')"; + $ir1 = $connect->Execute($i1); + } // while + } + fixsortorderQuestions($postgid, $surveyid); + } + } + elseif ($action == "delquestion" && ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $actsurrows['define_questions'])) + { + if (!isset($qid)) {$qid=returnglobal('qid');} + //check if any other questions have conditions which rely on this question. Don't delete if there are. + $ccquery = "SELECT * FROM {$dbprefix}conditions WHERE cqid=$qid"; + $ccresult = db_execute_assoc($ccquery) or safe_die ("Couldn't get list of cqids for this question
      ".$ccquery."
      ".$connect->ErrorMsg()); + $cccount=$ccresult->RecordCount(); + while ($ccr=$ccresult->FetchRow()) {$qidarray[]=$ccr['qid'];} + if (isset($qidarray)) {$qidlist=implode(", ", $qidarray);} + if ($cccount) //there are conditions dependant on this question + { + $databaseoutput .= "\n"; + } + else + { + $result = db_execute_assoc("SELECT gid FROM ".db_table_name('questions')." WHERE qid='{$qid}'"); + $row=$result->FetchRow(); + $gid = $row['gid']; + //see if there are any conditions/attributes/answers for this question, and delete them now as well + $cquery = "DELETE FROM {$dbprefix}conditions WHERE qid=$qid"; + $cresult = $connect->Execute($cquery); + $query = "DELETE FROM {$dbprefix}question_attributes WHERE qid=$qid"; + $result = $connect->Execute($query); + $cquery = "DELETE FROM {$dbprefix}answers WHERE qid=$qid"; + $cresult = $connect->Execute($cquery); + $query = "DELETE FROM {$dbprefix}questions WHERE qid=$qid"; + $result = $connect->Execute($query); + fixsortorderQuestions($gid, $surveyid); + if ($result) + { + $qid=""; + $postqid=""; + $_GET['qid']=""; + } + else + { + $databaseoutput .= "\n"; + } + } + } + + elseif ($action == "modanswer" && ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $actsurrows['define_questions'])) + { + + if (isset($_POST['sortorder'])) + { + $postsortorder=sanitize_int($_POST['sortorder']); + } + + switch($_POST['method']) + { + // Add a new answer button + case $clang->gT("Add new Answer", "unescaped"): + if (isset($_POST['insertcode']) && $_POST['insertcode']!='' && $_POST['insertcode'] != "0") + { + //$_POST = array_map('db_quote', $_POST);//Removed: qstr is used in SQL below + $_POST['insertcode']=sanitize_paranoid_string($_POST['insertcode']); + $query = "select max(sortorder) as maxorder from ".db_table_name('answers')." where qid='$qid'"; + $result = $connect->Execute($query); + $newsortorder=sprintf("%05d", $result->fields['maxorder']+1); + $anslangs = GetAdditionalLanguagesFromSurveyID($surveyid); + $baselang = GetBaseLanguageFromSurveyID($surveyid); + $query = "select * from ".db_table_name('answers')." where code=".$connect->qstr($_POST['insertcode'])." and language='$baselang' and qid={$postqid}"; + $result = $connect->Execute($query); + + if (isset($result) && $result->RecordCount()>0) + { + $databaseoutput .= "\n"; + } + else + { + + + if ($filterxsshtml) + { + require_once("../classes/inputfilter/class.inputfilter_clean.php"); + $myFilter = new InputFilter('','',1,1,1); + $_POST['insertanswer']=$myFilter->process($_POST['insertanswer']); + } + else + { + $_POST['insertanswer'] = html_entity_decode($_POST['insertanswer'], ENT_QUOTES, "UTF-8"); + } + + // Fix bug with FCKEditor saving strange BR types + $_POST['insertanswer']=fix_FCKeditor_text($_POST['insertanswer']); + + // Add new Answer for Base Language Question + if (!isset($_POST['insertassessment_value'])) $_POST['insertassessment_value']=0; + else {$_POST['insertassessment_value']=(int) $_POST['insertassessment_value'];} + + $query = "INSERT INTO ".db_table_name('answers')." (qid, code, answer, sortorder, default_value,language, assessment_value) VALUES ('{$postqid}', ".$connect->qstr($_POST['insertcode']).", ".$connect->qstr($_POST['insertanswer']).", '{$newsortorder}', 'N','$baselang',{$_POST['insertassessment_value']})"; + if (!$result = $connect->Execute($query)) + { + $databaseoutput .= "\n"; + } + + // Added by lemeur for AutoSaveAll + $_POST['code_'.($newsortorder+0)] = $_POST['insertcode']; + $_POST['assessment_'.($newsortorder+0)] = $_POST['insertassessment_value']; + $_POST['previouscode_'.($newsortorder+0)] = $_POST['insertcode']; + $_POST['codeids'] = $_POST['codeids'] . " ".($newsortorder+0); + $_POST['answer_'.$baselang.'_'.($newsortorder+0)] = $_POST['insertanswer']; + $_POST['sortorderids'] = $_POST['sortorderids'] . " ".$baselang."_".($newsortorder+0); + // End lemeur AutoSaveAll + + // Last code was successfully inserted - find out the next incrementing code and remember it + $_SESSION['nextanswercode']=getNextCode($_POST['insertcode']); + //Now check if this new code doesn't exist. For now then there is no code inserted. + $query = "select * from ".db_table_name('answers')." where code=".$connect->qstr($_SESSION['nextanswercode'])." and language='$baselang' and qid={$postqid}"; + $result = $connect->Execute($query); + if ($result->RecordCount()>0) unset($_SESSION['nextanswercode']); + + foreach ($anslangs as $anslang) + { + if(!isset($_POST['default'])) $_POST['default'] = ""; + $query = "INSERT INTO ".db_table_name('answers')." (qid, code, answer, sortorder, default_value,language) VALUES ({$postqid}, ".$connect->qstr($_POST['insertcode']).",".$connect->qstr($_POST['insertanswer']).", '{$newsortorder}', 'N','$anslang')"; + if (!$result = $connect->Execute($query)) + { + $databaseoutput .= "\n"; + } + // Added by lemeur for AutoSaveAll + $_POST['answer_'.$anslang.'_'.($newsortorder+0)] = $_POST['insertanswer']; + $_POST['sortorderids'] = $_POST['sortorderids'] . " ".$anslang."_".($newsortorder+0); + // End lemeur AutoSaveAll + } + } + } else { + $databaseoutput .= "\n"; + break; // let's break because in this case we do not want an AutoSaveAll + } + //break; // Commented by lemeur for AutoSaveAll + // Save all answers with one button + case $clang->gT("Save Changes", "unescaped"): + //Determine autoids by evaluating the hidden field + $sortorderids=explode(' ', trim($_POST['sortorderids'])); + natsort($sortorderids); // // Added by lemeur for AutoSaveAll + $codeids=explode(' ', trim($_POST['codeids'])); + $count=0; + $invalidCode = 0; + $duplicateCode = 0; + + $testarray = array(); + + for ($i=0; $i$value){ + if($value>=2){ + $dupanswers[]=$key; + } + } + + require_once("../classes/inputfilter/class.inputfilter_clean.php"); + $myFilter = new InputFilter('','',1,1,1); + + //First delete all answers + $query = "delete from ".db_table_name('answers')." where qid=".$connect->qstr($qid); + $result = $connect->Execute($query); + + foreach ($sortorderids as $sortorderid) + { + $defaultanswerset='N'; + $langid=substr($sortorderid,0,strrpos($sortorderid,'_')); + $orderid=substr($sortorderid,strrpos($sortorderid,'_')+1,20); + if (isset($_POST['default_answer_'.$codeids[$count]]) && $_POST['default_answer_'.$codeids[$count]]=="Y") + { + $defaultanswerset='Y'; + } + if ($_POST['code_'.$codeids[$count]] != "0" && trim($_POST['code_'.$codeids[$count]]) != "" && !in_array($_POST['code_'.$codeids[$count]],$dupanswers)) + { + //Sanitize input, strip XSS + if ($filterxsshtml) + { + $_POST['answer_'.$sortorderid]=$myFilter->process($_POST['answer_'.$sortorderid]); + } + else + { + $_POST['answer_'.$sortorderid] = html_entity_decode($_POST['answer_'.$sortorderid], ENT_QUOTES, "UTF-8"); + } + + // Fix bug with FCKEditor saving strange BR types + $_POST['answer_'.$sortorderid]=fix_FCKeditor_text($_POST['answer_'.$sortorderid]); + + $_POST['code_'.$codeids[$count]]=sanitize_paranoid_string($_POST['code_'.$codeids[$count]]); + // Now we insert the answers + $query = "INSERT INTO ".db_table_name('answers')." (code,answer,qid,sortorder,language,default_value,assessment_value) + VALUES (".$connect->qstr($_POST['code_'.$codeids[$count]]).", ". + $connect->qstr($_POST['answer_'.$sortorderid]).", ". + $connect->qstr($qid).", ". + $connect->qstr($orderid).", ". + $connect->qstr($langid).", ". + $connect->qstr($defaultanswerset).",". + $connect->qstr((int)$_POST['assessment_'.$codeids[$count]]).")"; + if (!$result = $connect->Execute($query)) + { + $databaseoutput .= "\n"; + } + //if ($oldcode != false) + if ($_POST['previouscode_'.$codeids[$count]] != $_POST['code_'.$codeids[$count]]) + { + // Update the Answer code in conditions (updates if row exists right) + $query = "UPDATE ".db_table_name('conditions')." SET value = ".$connect->qstr($_POST['code_'.$codeids[$count]])." where cqid='$qid' and value=".$connect->qstr($_POST['previouscode_'.$codeids[$count]]); + $result = $connect->Execute($query); + // also update references like @sidXgidXqidAid@ + $query = "UPDATE ".db_table_name('conditions')." SET value = '@".$surveyid."X".$gid."X".$qid.db_quote($_POST['code_'.$codeids[$count]])."@' where cqid='$qid' and value='@".$surveyid."X".$gid."X".$qid.db_quote($_POST['previouscode_'.$codeids[$count]])."@'"; + $result = $connect->Execute($query); + } + } else { + if ($_POST['code_'.$codeids[$count]] == "0" || trim($_POST['code_'.$codeids[$count]]) == "") $invalidCode = 1; + if (in_array($_POST['code_'.$codeids[$count]],$dupanswers)) $duplicateCode = 1; + } + $count++; + if ($count>count($codeids)-1) {$count=0;} + } + if ($invalidCode == 1) $databaseoutput .= "\n"; + if ($duplicateCode == 1) $databaseoutput .= "\n"; + break; + + // Pressing the Up button + case $clang->gT("Up", "unescaped"): + $newsortorder=$postsortorder-1; + $oldsortorder=$postsortorder; + $cdquery = "UPDATE ".db_table_name('answers')." SET sortorder=-1 WHERE qid=$qid AND sortorder='$newsortorder'"; + $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); + $cdquery = "UPDATE ".db_table_name('answers')." SET sortorder=$newsortorder WHERE qid=$qid AND sortorder=$oldsortorder"; + $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); + $cdquery = "UPDATE ".db_table_name('answers')." SET sortorder='$oldsortorder' WHERE qid=$qid AND sortorder=-1"; + $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); + break; + + // Pressing the Down button + case $clang->gT("Dn", "unescaped"): + $newsortorder=$postsortorder+1; + $oldsortorder=$postsortorder; + $cdquery = "UPDATE ".db_table_name('answers')." SET sortorder=-1 WHERE qid=$qid AND sortorder='$newsortorder'"; + $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); + $cdquery = "UPDATE ".db_table_name('answers')." SET sortorder='$newsortorder' WHERE qid=$qid AND sortorder=$oldsortorder"; + $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); + $cdquery = "UPDATE ".db_table_name('answers')." SET sortorder=$oldsortorder WHERE qid=$qid AND sortorder=-1"; + $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); + break; + + // Delete Button + case $clang->gT("Del", "unescaped"): + $query = "DELETE FROM ".db_table_name('answers')." WHERE qid={$qid} AND sortorder='{$postsortorder}'"; + if (!$result = $connect->Execute($query)) + { + $databaseoutput .= "\n"; + } + fixsortorderAnswers($qid); + break; + + // Default Button + case $clang->gT("Default", "unescaped"): + $query = "SELECT default_value from ".db_table_name('answers')." where qid={$qid} AND sortorder='{$postsortorder}' GROUP BY default_value"; + $result = db_execute_assoc($query); + $row = $result->FetchRow(); + if ($row['default_value'] == "Y") + { + $query = "UPDATE ".db_table_name('answers')." SET default_value='N' WHERE qid={$qid} AND sortorder='{$postsortorder}'"; + if (!$result = $connect->Execute($query)) + { + $databaseoutput .= "\n"; + } + } else { + $query = "SELECT type from ".db_table_name('questions')." where qid={$qid} GROUP BY type"; + $result = db_execute_assoc($query); + $row = $result->FetchRow(); + if ($row['type'] == "O" || $row['type'] == "L" || $row['type'] == "!") + { // SINGLE CHOICE QUESTION, SET ALL RECORDS TO N, THEN WE SET ONE TO Y + $query = "UPDATE ".db_table_name('answers')." SET default_value='N' WHERE qid={$qid}"; + $result = $connect->Execute($query); + } + $query = "UPDATE ".db_table_name('answers')." SET default_value='Y' WHERE qid={$qid} AND sortorder='{$postsortorder}'"; + if (!$result = $connect->Execute($query)) + { + $databaseoutput .= "\n"; + } + } + break; + } + } + + elseif ($action == "updatesurvey" && ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $actsurrows['edit_survey_property'])) + { + + $formatdata=getDateFormatData($_SESSION['dateformat']); + if (trim($_POST['expires'])=="") + { + $_POST['expires']=null; + } + else + { + $datetimeobj = new Date_Time_Converter($_POST['expires'],$formatdata['phpdate']); + $_POST['expires']=$datetimeobj->convert("Y-m-d H:i:s"); + } + if (trim($_POST['startdate'])=="") + { + $_POST['startdate']=null; + } + else + { + $datetimeobj = new Date_Time_Converter($_POST['startdate'],$formatdata['phpdate']); + $_POST['startdate']=$datetimeobj->convert("Y-m-d H:i:s"); + } + CleanLanguagesFromSurvey($postsid,$_POST['languageids']); + FixLanguageConsistency($postsid,$_POST['languageids']); + + if($_SESSION['USER_RIGHT_SUPERADMIN'] != 1 && $_SESSION['USER_RIGHT_MANAGE_TEMPLATE'] != 1 && !hasTemplateManageRights($_SESSION['loginID'], $_POST['template'])) $_POST['template'] = "default"; + + $sql = "SELECT * FROM ".db_table_name('surveys')." WHERE sid={$postsid}"; + $rs = db_execute_assoc($sql); + $updatearray= array('admin'=>$_POST['admin'], + 'expires'=>$_POST['expires'], + 'adminemail'=>$_POST['adminemail'], + 'startdate'=>$_POST['startdate'], + 'bounce_email'=>$_POST['bounce_email'], + 'usetokens'=>$_POST['usetokens'], + 'private'=>$_POST['private'], + 'faxto'=>$_POST['faxto'], + 'format'=>$_POST['format'], + 'template'=>$_POST['template'], + 'assessments'=>$_POST['assessments'], + 'language'=>$_POST['language'], + 'additional_languages'=>$_POST['languageids'], + 'datestamp'=>$_POST['datestamp'], + 'ipaddr'=>$_POST['ipaddr'], + 'refurl'=>$_POST['refurl'], + 'publicgraphs'=>$_POST['publicgraphs'], + 'usecookie'=>$_POST['usecookie'], + 'notification'=>$_POST['notification'], + 'allowregister'=>$_POST['allowregister'], + 'allowsave'=>$_POST['allowsave'], + 'printanswers'=>$_POST['printanswers'], + 'publicstatistics'=>$_POST['publicstatistics'], + 'autoredirect'=>$_POST['autoredirect'], + 'allowprev'=>$_POST['allowprev'], + 'listpublic'=>$_POST['public'], + 'htmlemail'=>$_POST['htmlemail'], + 'tokenanswerspersistence'=>$_POST['tokenanswerspersistence'], + 'usecaptcha'=>$_POST['usecaptcha'] + ); + + $usquery=$connect->GetUpdateSQL($rs, $updatearray); + if ($usquery) { + $usresult = $connect->Execute($usquery) or safe_die("Error updating
      ".$usquery."

      ".$connect->ErrorMsg()); + } + $sqlstring =''; + foreach (GetAdditionalLanguagesFromSurveyID($surveyid) as $langname) + { + if ($langname) + { + $sqlstring .= "and surveyls_language <> '".$langname."' "; + } + } + // Add base language too + $sqlstring .= "and surveyls_language <> '".GetBaseLanguageFromSurveyID($surveyid)."' "; + + $usquery = "Delete from ".db_table_name('surveys_languagesettings')." where surveyls_survey_id={$postsid} ".$sqlstring; + $usresult = $connect->Execute($usquery) or safe_die("Error deleting obsolete surveysettings
      ".$usquery."

      ".$connect->ErrorMsg()); + + foreach (GetAdditionalLanguagesFromSurveyID($surveyid) as $langname) + { + if ($langname) + { + $usquery = "select * from ".db_table_name('surveys_languagesettings')." where surveyls_survey_id={$postsid} and surveyls_language='".$langname."'"; + $usresult = $connect->Execute($usquery) or safe_die("Error deleting obsolete surveysettings
      ".$usquery."

      ".$connect->ErrorMsg()); + if ($usresult->RecordCount()==0) + { + + if (getEmailFormat($surveyid) == "html") + { + $ishtml=true; + } + else + { + $ishtml=false; + } + + $bplang = new limesurvey_lang($langname); + $languagedetails=getLanguageDetails($langname); + $usquery = "INSERT INTO ".db_table_name('surveys_languagesettings') + ." (surveyls_survey_id, surveyls_language, surveyls_title, " + ." surveyls_email_invite_subj, surveyls_email_invite, " + ." surveyls_email_remind_subj, surveyls_email_remind, " + ." surveyls_email_confirm_subj, surveyls_email_confirm, " + ." surveyls_email_register_subj, surveyls_email_register, " + ." surveyls_dateformat) " + ." VALUES ({$postsid}, '".$langname."', ''," + .$connect->qstr($bplang->gT("Invitation to participate in survey",'unescaped'))."," + .$connect->qstr(conditional2_nl2br($bplang->gT("Dear {FIRSTNAME},\n\nYou have been invited to participate in a survey.\n\nThe survey is titled:\n\"{SURVEYNAME}\"\n\n\"{SURVEYDESCRIPTION}\"\n\nTo participate, please click on the link below.\n\nSincerely,\n\n{ADMINNAME} ({ADMINEMAIL})\n\n----------------------------------------------\nClick here to do the survey:\n{SURVEYURL}",'unescaped'),$ishtml))."," + .$connect->qstr($bplang->gT("Reminder to participate in survey",'unescaped'))."," + .$connect->qstr(conditional2_nl2br($bplang->gT("Dear {FIRSTNAME},\n\nRecently we invited you to participate in a survey.\n\nWe note that you have not yet completed the survey, and wish to remind you that the survey is still available should you wish to take part.\n\nThe survey is titled:\n\"{SURVEYNAME}\"\n\n\"{SURVEYDESCRIPTION}\"\n\nTo participate, please click on the link below.\n\nSincerely,\n\n{ADMINNAME} ({ADMINEMAIL})\n\n----------------------------------------------\nClick here to do the survey:\n{SURVEYURL}",'unescaped'),$ishtml))."," + .$connect->qstr($bplang->gT("Confirmation of completed survey",'unescaped'))."," + .$connect->qstr(conditional2_nl2br($bplang->gT("Dear {FIRSTNAME},\n\nThis email is to confirm that you have completed the survey titled {SURVEYNAME} and your response has been saved. Thank you for participating.\n\nIf you have any further questions about this email, please contact {ADMINNAME} on {ADMINEMAIL}.\n\nSincerely,\n\n{ADMINNAME}",'unescaped'),$ishtml))."," + .$connect->qstr($bplang->gT("Survey Registration Confirmation",'unescaped'))."," + .$connect->qstr(conditional2_nl2br($bplang->gT("Dear {FIRSTNAME},\n\nYou, or someone using your email address, have registered to participate in an online survey titled {SURVEYNAME}.\n\nTo complete this survey, click on the following URL:\n\n{SURVEYURL}\n\nIf you have any questions about this survey, or if you did not register to participate and believe this email is in error, please contact {ADMINNAME} at {ADMINEMAIL}.",'unescaped'),$ishtml))."," + .$languagedetails['dateformat'].")"; + unset($bplang); + $usresult = $connect->Execute($usquery) or safe_die("Error deleting obsolete surveysettings
      ".$usquery."

      ".$connect->ErrorMsg()); + } + } + } + + + + if ($usresult) + { + $surveyselect = getsurveylist(); + } + else + { + $databaseoutput .= "\n"; + } + } + + elseif ($action == "delsurvey" && ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $actsurrows['delete_survey'])) //can only happen if there are no groups, no questions, no answers etc. + { + $query = "DELETE FROM {$dbprefix}surveys WHERE sid=$surveyid"; + $result = $connect->Execute($query); + if ($result) + { + $surveyid = ""; + $surveyselect = getsurveylist(); + } + else + { + $databaseoutput .= "\n"; + + } + } + + + // Save the 2nd page from the survey-properties + elseif ($action == "updatesurvey2" && ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $actsurrows['edit_survey_property'])) + { + $languagelist = GetAdditionalLanguagesFromSurveyID($surveyid); + $languagelist[]=GetBaseLanguageFromSurveyID($surveyid); + require_once("../classes/inputfilter/class.inputfilter_clean.php"); + $myFilter = new InputFilter('','',1,1,1); + + foreach ($languagelist as $langname) + { + if ($langname) + { + + if ($_POST['url_'.$langname] == "http://") {$_POST['url_'.$langname]="";} + + // Clean XSS attacks + if ($filterxsshtml) + { + $_POST['short_title_'.$langname]=$myFilter->process($_POST['short_title_'.$langname]); + $_POST['description_'.$langname]=$myFilter->process($_POST['description_'.$langname]); + $_POST['welcome_'.$langname]=$myFilter->process($_POST['welcome_'.$langname]); + $_POST['endtext_'.$langname]=$myFilter->process($_POST['endtext_'.$langname]); + $_POST['urldescrip_'.$langname]=$myFilter->process($_POST['urldescrip_'.$langname]); + $_POST['url_'.$langname]=$myFilter->process($_POST['url_'.$langname]); + } + else + { + $_POST['short_title_'.$langname] = html_entity_decode($_POST['short_title_'.$langname], ENT_QUOTES, "UTF-8"); + $_POST['description_'.$langname] = html_entity_decode($_POST['description_'.$langname], ENT_QUOTES, "UTF-8"); + $_POST['welcome_'.$langname] = html_entity_decode($_POST['welcome_'.$langname], ENT_QUOTES, "UTF-8"); + $_POST['endtext_'.$langname] = html_entity_decode($_POST['endtext_'.$langname], ENT_QUOTES, "UTF-8"); + $_POST['urldescrip_'.$langname] = html_entity_decode($_POST['urldescrip_'.$langname], ENT_QUOTES, "UTF-8"); + $_POST['url_'.$langname] = html_entity_decode($_POST['url_'.$langname], ENT_QUOTES, "UTF-8"); + } + + // Fix bug with FCKEditor saving strange BR types + $_POST['short_title_'.$langname]=fix_FCKeditor_text($_POST['short_title_'.$langname]); + $_POST['description_'.$langname]=fix_FCKeditor_text($_POST['description_'.$langname]); + $_POST['welcome_'.$langname]=fix_FCKeditor_text($_POST['welcome_'.$langname]); + $_POST['endtext_'.$langname]=fix_FCKeditor_text($_POST['endtext_'.$langname]); + + $usquery = "UPDATE ".db_table_name('surveys_languagesettings')." \n" + . "SET surveyls_title='".db_quote($_POST['short_title_'.$langname])."', surveyls_description='".db_quote($_POST['description_'.$langname])."',\n" + . "surveyls_welcometext='".db_quote($_POST['welcome_'.$langname])."',\n" + . "surveyls_endtext='".db_quote($_POST['endtext_'.$langname])."',\n" + . "surveyls_url='".db_quote($_POST['url_'.$langname])."',\n" + . "surveyls_urldescription='".db_quote($_POST['urldescrip_'.$langname])."',\n" + . "surveyls_dateformat='".db_quote($_POST['dateformat_'.$langname])."'\n" + . "WHERE surveyls_survey_id=".db_quote($postsid)." and surveyls_language='".$langname."'"; + $usresult = $connect->Execute($usquery) or safe_die("Error updating
      ".$usquery."

      ".$connect->ErrorMsg()); + } + } + } + +} + + + + +elseif ($action == "insertnewsurvey" && $_SESSION['USER_RIGHT_CREATE_SURVEY']) +{ + $dateformatdetails=getDateFormatData($_SESSION['dateformat']); + if ($_POST['url'] == "http://") {$_POST['url']="";} + if (!$_POST['surveyls_title']) + { + $databaseoutput .= "\n"; + } else + { + if (trim($_POST['expires'])=="") + { + $_POST['expires']='1980-01-01'; + } + + // Get random ids until one is found that is not used + do + { + $surveyid = getRandomID(); + $isquery = "SELECT sid FROM ".db_table_name('surveys')." WHERE sid=$surveyid"; + $isresult = db_execute_assoc($isquery); + } + while ($isresult->RecordCount()>0); + + if (!isset($_POST['template'])) {$_POST['template']='default';} + if($_SESSION['USER_RIGHT_SUPERADMIN'] != 1 && $_SESSION['USER_RIGHT_MANAGE_TEMPLATE'] != 1 && !hasTemplateManageRights($_SESSION['loginID'], $_POST['template'])) $_POST['template'] = "default"; + + // insert base language into surveys_language_settings + if ($filterxsshtml) + { + require_once("../classes/inputfilter/class.inputfilter_clean.php"); + $myFilter = new InputFilter('','',1,1,1); + + $_POST['surveyls_title']=$myFilter->process($_POST['surveyls_title']); + $_POST['description']=$myFilter->process($_POST['description']); + $_POST['welcome']=$myFilter->process($_POST['welcome']); + $_POST['urldescrip']=$myFilter->process($_POST['urldescrip']); + } + else + { + $_POST['surveyls_title'] = html_entity_decode($_POST['surveyls_title'], ENT_QUOTES, "UTF-8"); + $_POST['description'] = html_entity_decode($_POST['description'], ENT_QUOTES, "UTF-8"); + $_POST['welcome'] = html_entity_decode($_POST['welcome'], ENT_QUOTES, "UTF-8"); + $_POST['urldescrip'] = html_entity_decode($_POST['urldescrip'], ENT_QUOTES, "UTF-8"); + } + + + $_POST['dateformat'] = (int) $_POST['dateformat']; + + + if (trim($_POST['expires'])=='') + { + $_POST['expires']=null; + } + else + { + $datetimeobj = new Date_Time_Converter($_POST['expires'] , "Y-m-d H:i:s"); + $browsedatafield=$datetimeobj->convert($dateformatdetails['phpdate'].' H:i'); + $_POST['expires']=$browsedatafield; + } + + if (trim($_POST['startdate'])=='') + { + $_POST['expires']=null; + } + else + { + $datetimeobj = new Date_Time_Converter($_POST['startdate'] , "Y-m-d H:i:s"); + $browsedatafield=$datetimeobj->convert($dateformatdetails['phpdate'].' H:i'); + $_POST['startdate']=$browsedatafield; + } + + + $insertarray=array( 'sid'=>$surveyid, + 'owner_id'=>$_SESSION['loginID'], + 'admin'=>$_POST['admin'], + 'active'=>'N', + 'expires'=>$_POST['expires'], + 'startdate'=>$_POST['startdate'], + 'adminemail'=>$_POST['adminemail'], + 'bounce_email'=>$_POST['bounce_email'], + 'private'=>$_POST['private'], + 'faxto'=>$_POST['faxto'], + 'format'=>$_POST['format'], + 'template'=>$_POST['template'], + 'language'=>$_POST['language'], + 'datestamp'=>$_POST['datestamp'], + 'ipaddr'=>$_POST['ipaddr'], + 'refurl'=>$_POST['refurl'], + 'usecookie'=>$_POST['usecookie'], + 'notification'=>$_POST['notification'], + 'allowregister'=>$_POST['allowregister'], + 'allowsave'=>$_POST['allowsave'], + 'autoredirect'=>$_POST['autoredirect'], + 'allowprev'=>$_POST['allowprev'], + 'printanswers'=>$_POST['printanswers'], + 'usetokens'=>$_POST['usetokens'], + 'datecreated'=>date("Y-m-d"), + 'public'=>$_POST['public'], + 'htmlemail'=>$_POST['htmlemail'], + 'tokenanswerspersistence'=>$_POST['tokenanswerspersistence'], + 'usecaptcha'=>$_POST['usecaptcha'], + 'publicstatistics'=>$_POST['publicstatistics'], + 'publicgraphs'=>$_POST['publicgraphs'], + 'assessments'=>$_POST['assessments'] + ); + $dbtablename=db_table_name_nq('surveys'); + $isquery = $connect->GetInsertSQL($dbtablename, $insertarray); + $isresult = $connect->Execute($isquery) or safe_die ($isrquery."
      ".$connect->ErrorMsg()); + + + + // Fix bug with FCKEditor saving strange BR types + $_POST['surveyls_title']=fix_FCKeditor_text($_POST['surveyls_title']); + $_POST['description']=fix_FCKeditor_text($_POST['description']); + $_POST['welcome']=fix_FCKeditor_text($_POST['welcome']); + + $bplang = new limesurvey_lang($_POST['language']); + + $insertarray=array( 'surveyls_survey_id'=>$surveyid, + 'surveyls_language'=>$_POST['language'], + 'surveyls_title'=>$_POST['surveyls_title'], + 'surveyls_description'=>$_POST['description'], + 'surveyls_welcometext'=>$_POST['welcome'], + 'surveyls_urldescription'=>$_POST['urldescrip'], + 'surveyls_endtext'=>$_POST['endtext'], + 'surveyls_url'=>$_POST['url'], + 'surveyls_email_invite_subj'=>$bplang->gT("Invitation to participate in survey",'unescaped'), + 'surveyls_email_invite'=>$bplang->gT("Dear {FIRSTNAME},\n\nYou have been invited to participate in a survey.\n\nThe survey is titled:\n\"{SURVEYNAME}\"\n\n\"{SURVEYDESCRIPTION}\"\n\nTo participate, please click on the link below.\n\nSincerely,\n\n{ADMINNAME} ({ADMINEMAIL})\n\n----------------------------------------------\nClick here to do the survey:\n{SURVEYURL}",'unescaped'), + 'surveyls_email_remind_subj'=>$bplang->gT("Reminder to participate in survey",'unescaped'), + 'surveyls_email_remind'=>$bplang->gT("Dear {FIRSTNAME},\n\nRecently we invited you to participate in a survey.\n\nWe note that you have not yet completed the survey, and wish to remind you that the survey is still available should you wish to take part.\n\nThe survey is titled:\n\"{SURVEYNAME}\"\n\n\"{SURVEYDESCRIPTION}\"\n\nTo participate, please click on the link below.\n\nSincerely,\n\n{ADMINNAME} ({ADMINEMAIL})\n\n----------------------------------------------\nClick here to do the survey:\n{SURVEYURL}",'unescaped'), + 'surveyls_email_confirm_subj'=>$bplang->gT("Confirmation of completed survey",'unescaped'), + 'surveyls_email_confirm'=>$bplang->gT("Dear {FIRSTNAME},\n\nThis email is to confirm that you have completed the survey titled {SURVEYNAME} and your response has been saved. Thank you for participating.\n\nIf you have any further questions about this email, please contact {ADMINNAME} on {ADMINEMAIL}.\n\nSincerely,\n\n{ADMINNAME}",'unescaped'), + 'surveyls_email_register_subj'=>$bplang->gT("Survey Registration Confirmation",'unescaped'), + 'surveyls_email_register'=>$bplang->gT("Dear {FIRSTNAME},\n\nYou, or someone using your email address, have registered to participate in an online survey titled {SURVEYNAME}.\n\nTo complete this survey, click on the following URL:\n\n{SURVEYURL}\n\nIf you have any questions about this survey, or if you did not register to participate and believe this email is in error, please contact {ADMINNAME} at {ADMINEMAIL}.",'unescaped'), + 'surveyls_dateformat'=>$_POST['dateformat'] + ); + $dbtablename=db_table_name_nq('surveys_languagesettings'); + $isquery = $connect->GetInsertSQL($dbtablename, $insertarray); + $isresult = $connect->Execute($isquery) or safe_die ($isquery."
      ".$connect->ErrorMsg()); + unset($bplang); + + // Insert into survey_rights + + $isrquery = "INSERT INTO {$dbprefix}surveys_rights VALUES($surveyid,". $_SESSION['loginID'].",1,1,1,1,1,1)"; //inserts survey rights for owner + $isrresult = $connect->Execute($isrquery) or safe_die ($isrquery."
      ".$connect->ErrorMsg()); + if ($isresult) + { + $surveyselect = getsurveylist(); + } + else + { + $errormsg=$clang->gT("Survey could not be created","js")." - ".$connect->ErrorMsg(); + $databaseoutput .= "\n"; + $databaseoutput .= htmlspecialchars($isquery); + } + } +} +elseif ($action == "savepersonalsettings") +{ + $uquery = "UPDATE {$dbprefix}users SET lang='{$_POST['lang']}', dateformat='{$_POST['dateformat']}', htmleditormode= '{$_POST['htmleditormode']}' + WHERE uid={$_SESSION['loginID']}"; + $uresult = $connect->Execute($uquery) or safe_die ($isrquery."
      ".$connect->ErrorMsg()); + $_SESSION['adminlang']=$_POST['lang']; + $_SESSION['htmleditormode']=$_POST['htmleditormode']; + $_SESSION['dateformat']= $_POST['dateformat']; + $databaseoutput.='
      '.$clang->gT('Your personal settings were successfully saved.').'
      '; +} +else +{ + include("access_denied.php"); +} + + +?> diff --git a/include/limesurvey/admin/dataentry.php b/include/limesurvey/admin/dataentry.php index 6fb0dc72..67425590 100644 --- a/include/limesurvey/admin/dataentry.php +++ b/include/limesurvey/admin/dataentry.php @@ -1,2517 +1,3046 @@ -ErrorMsg()); -$actsurrows = $actsurresult->FetchRow(); - -if($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $actsurrows['browse_response']) -{ - - $surveyoptions = browsemenubar(); - if (!$database_exists) - { - //$dataentryoutput .= "\n"; - $dataentryoutput .= "\n" - ."\t\n" - ."\t
      " - .$clang->gT("Data Entry")."
      \n" - ."".$clang->gT("Error")."
      \n" - .$clang->gT("The defined LimeSurvey database does not exist")."
      \n" - .$clang->gT("Either your selected database has not yet been created or there is a problem accessing it.")."

      \n" - ."
      \n" - ."
      \n" - ."\n"; - return; - } - if (!$surveyid && !$subaction) - { - //$dataentryoutput .= "\n"; - $dataentryoutput .= "\n" - ."\t\n" - ."\t
      " - .$clang->gT("Data Entry")."
      \n" - ."".$clang->gT("Error")."
      \n" - .$clang->gT("You have not selected a survey for data-entry.")."

      \n" - ."
      \n" - ."
      \n"; - return; - } - - if ($subaction == "edit" || $subaction == "" || $subaction == "editsaved" || $subaction == "insert") - { - $language = GetBaseLanguageFromSurveyID($surveyid); - } - - if ($subaction == "insert") - { - $thissurvey=getSurveyInfo($surveyid); - $errormsg=""; - $dataentryoutput .= "\n" - ."\t\n" - ."\t\n" - ."
      " - .$clang->gT("Data Entry")."
      \n"; - - $lastanswfortoken=''; // check if a previous answer has been submitted or saved - $rlanguage=''; - if (isset($_POST['token']) && $_POST['token']) - { - $tokencompleted = ""; - $tokentable = db_table_name("tokens_".$surveyid); - $tcquery = "SELECT completed from $tokentable WHERE token='".$_POST['token']."'"; - $tcresult = db_execute_assoc($tcquery); - $tccount = $tcresult->RecordCount(); - while ($tcrow = $tcresult->FetchRow()) - { - $tokencompleted = $tcrow['completed']; - } - - if ($tccount < 1) - { // token doesn't exist in token table - $lastanswfortoken='UnknownToken'; - } - elseif ($thissurvey['private'] == "Y") - { // token exist but survey is anonymous, check completed state - if ($tokencompleted != "" && $tokencompleted != "N") - { // token is not completed - $lastanswfortoken='PrivacyProtected'; - } - } - else - { // token is valid, survey not anonymous, try to get last recorded response id - $aquery = "SELECT id,startlanguage FROM $surveytable WHERE token='".$_POST['token']."'"; - $aresult = db_execute_assoc($aquery); - while ($arow = $aresult->FetchRow()) - { - $lastanswfortoken=$arow['id']; - $rlanguage=$arow['startlanguage']; - } - } - } - - if (bHasSurveyGotTokentable($thissurvey) && (!isset($_POST['token']) || !$_POST['token'])) - {// First Check if the survey uses tokens and if a token has been provided - $errormsg="".$clang->gT("Error").": ".$clang->gT("This is a closed-access survey, so you must supply a valid token. Please contact the administrator for assistance.")."\n"; - } - elseif (bHasSurveyGotTokentable($thissurvey) && $lastanswfortoken == 'UnknownToken') - { - $errormsg="".$clang->gT("Error").": ".$clang->gT("The token you have provided is not valid or has already been used.")."\n"; - } - elseif (bHasSurveyGotTokentable($thissurvey) && $lastanswfortoken != '') - { - $errormsg="".$clang->gT("Error").": ".$clang->gT("There is already a recorded answer for this token")."\n"; - if ($lastanswfortoken != 'PrivacyProtected') - { - $errormsg .= "

      ".$clang->gT("Follow the following link to update it").":\n" - . "gT("Edit this entry", "js")."')\">[id:$lastanswfortoken]"; - } - else - { - $errormsg .= "

      ".$clang->gT("This surveys uses anonymous answers, so you can't update your response.")."\n"; - } - } - else - { - if (isset($_POST['save']) && $_POST['save'] == "on") - { - $saver['identifier']=returnglobal('save_identifier'); - $saver['language']=returnglobal('save_language'); - $saver['password']=returnglobal('save_password'); - $saver['passwordconfirm']=returnglobal('save_confirmpassword'); - $saver['email']=returnglobal('save_email'); - if (!returnglobal('redo')) - { - $password=md5($saver['password']); - } - else - { - $password=$saver['password']; - } - $errormsg=""; - if (!$saver['identifier']) {$errormsg .= $clang->gT("Error").": ".$clang->gT("You must supply a name for this saved session.");} - if (!$saver['password']) {$errormsg .= $clang->gT("Error").": ".$clang->gT("You must supply a password for this saved session.");} - if ($saver['password'] != $saver['passwordconfirm']) {$errormsg .= $clang->gT("Error").": ".$clang->gT("Your passwords do not match.");} - if ($errormsg) - { - $dataentryoutput .= $errormsg; - $dataentryoutput .= $clang->gT("Try again").":
      -
      - - - - - - - - - - - "; - if (isset($_POST['datestamp'])) - { - $dataentryoutput .= "\n"; - } - if (isset($_POST['ipaddr'])) - { - $dataentryoutput .= "\n"; - } - $dataentryoutput .= "
      ".$clang->gT("Identifier:")."
      ".$clang->gT("Password:")."
      ".$clang->gT("Confirm Password:")."
      ".$clang->gT("Email:")." -
      ".$clang->gT("Start Language:")."\n"; - foreach ($_POST as $key=>$val) - { - if (substr($key, 0, 4) != "save" && $key != "action" && $key != "surveytable" && $key !="sid" && $key != "datestamp" && $key !="ipaddr") - { - $dataentryoutput .= "\n"; - } - } - $dataentryoutput .= "
      - - - - -
      \n"; - } elseif (returnglobal('redo')=="yes") - { - //Delete all the existing entries TODO WTF IS REDO? - //$delete="DELETE FROM ".db_table_name("saved")." WHERE scid=".$saver['scid']; - //$result=$connect->Execute($delete) or safe_die("Couldn't delete old record
      $delete
      ".htmlspecialchars($connect->ErrorMsg())); - //$delete="DELETE FROM ".db_table_name("saved_control")." WHERE scid=".$surveytable['scid']; - //$result=$connect->Execute($delete) or safe_die("Couldn't delete old record
      $delete
      ".htmlspecialchars($connect->ErrorMsg())); - } - } - //BUILD THE SQL TO INSERT RESPONSES - $baselang = GetBaseLanguageFromSurveyID($surveyid); - $iquery = "SELECT * FROM ".db_table_name("questions").", ".db_table_name("groups")." WHERE - ".db_table_name("questions").".gid=".db_table_name("groups").".gid AND - ".db_table_name("questions").".language = '{$baselang}' AND ".db_table_name("groups").".language = '{$baselang}' AND - ".db_table_name("questions").".sid=$surveyid ORDER BY ".db_table_name("groups").".group_order, title"; - $iresult = db_execute_assoc($iquery); - $col_name=""; - $insertqr=""; - while ($irow = $iresult->FetchRow()) - { - if ($irow['type'] != "M" && $irow['type'] != "A" && $irow['type'] != "B" && $irow['type'] != "C" && - $irow['type'] != "E" && $irow['type'] != "F" && $irow['type'] != "H" && $irow['type'] != "P" && - $irow['type'] != "O" && $irow['type'] != "R" && $irow['type'] != "Q" && $irow['type'] != "J" && - $irow['type'] != "K" && $irow['type'] != "1" ) - { - $fieldname = "{$irow['sid']}X{$irow['gid']}X{$irow['qid']}"; - if (isset($_POST[$fieldname])) - { - $col_name .= db_quote_id($fieldname).", \n"; - $insertqr .= "'" . auto_escape($_POST[$fieldname]) . "', \n"; - } - } - elseif ($irow['type'] == "O") - { - $fieldname = "{$irow['sid']}X{$irow['gid']}X{$irow['qid']}"; - $fieldname2 = $fieldname . "comment"; - $col_name .= db_quote_id($fieldname).", \n".db_quote_id($fieldname2).", \n"; - $insertqr .= "'" . auto_escape($_POST[$fieldname]) . "', \n'" . auto_escape($_POST[$fieldname2]) . "', \n"; - } - elseif ($irow['type'] == "1") - { - $i2query = "SELECT ".db_table_name("answers").".*, ".db_table_name("questions").".other FROM ".db_table_name("answers").", ".db_table_name("questions")." WHERE - ".db_table_name("answers").".qid=".db_table_name("questions").".qid AND ".db_table_name("questions").".qid={$irow['qid']} AND - ".db_table_name("questions").".language = '{$language}' AND ".db_table_name("answers").".language = '{$language}' AND - ".db_table_name("questions").".sid=$surveyid ORDER BY ".db_table_name("answers").".sortorder, ".db_table_name("answers").".answer"; - - $i2result = $connect->Execute($i2query); - $i2count = $i2result->RecordCount(); - while ($i2answ = $i2result->FetchRow()) - { - // first scale - $fieldname = "{$irow['sid']}X{$irow['gid']}X{$irow['qid']}{$i2answ['code']}#0"; - $col_name .= db_quote_id($fieldname).", \n"; - $insertqr .= "'" . auto_escape($_POST["$fieldname"]) . "', \n"; - // second scale - $fieldname = "{$irow['sid']}X{$irow['gid']}X{$irow['qid']}{$i2answ['code']}#1"; - $col_name .= db_quote_id($fieldname).", \n"; - $insertqr .= "'" . auto_escape($_POST["$fieldname"]) . "', \n"; - } - - } - elseif ($irow['type'] == "R") - { - $i2query = "SELECT ".db_table_name("answers").".*, ".db_table_name("questions").".other FROM ".db_table_name("answers").", ".db_table_name("questions")." WHERE - ".db_table_name("answers").".qid=".db_table_name("questions").".qid AND ".db_table_name("questions").".qid={$irow['qid']} AND - ".db_table_name("questions").".language = '{$language}' AND ".db_table_name("answers").".language = '{$language}' AND - ".db_table_name("questions").".sid=$surveyid ORDER BY ".db_table_name("answers").".sortorder, ".db_table_name("answers").".answer"; - $i2result = $connect->Execute($i2query); - $i2count = $i2result->RecordCount(); - for ($i=1; $i<=$i2count; $i++) - { - $fieldname = "{$irow['sid']}X{$irow['gid']}X{$irow['qid']}$i"; - $col_name .= db_quote_id($fieldname).", \n"; - $insertqr .= "'" . auto_escape($_POST["d$fieldname"]) . "', \n"; - } - } - else - { - $i2query = "SELECT ".db_table_name("answers").".*, ".db_table_name("questions").".other FROM ".db_table_name("answers").", ".db_table_name("questions")." - WHERE ".db_table_name("answers").".qid=".db_table_name("questions").".qid AND - ".db_table_name("questions").".language = '{$language}' AND ".db_table_name("answers").".language = '{$language}' AND - ".db_table_name("questions").".qid={$irow['qid']} - AND ".db_table_name("questions").".sid=$surveyid ORDER BY ".db_table_name("answers").".sortorder, ".db_table_name("answers").".answer"; - $i2result = db_execute_assoc($i2query); - while ($i2row = $i2result->FetchRow()) - { - $otherexists = ""; - if ($i2row['other'] == "Y" and ($irow['type']=="!" or $irow['type']=="L" or $irow['type']=="M" or $irow['type']=="P" or $irow['type'] == "W" or $irow['type'] == "Z")) {$otherexists = "Y";} - $fieldname = "{$irow['sid']}X{$irow['gid']}X{$irow['qid']}{$i2row['code']}"; - if (isset($_POST[$fieldname])) - { - $col_name .= db_quote_id($fieldname).", \n"; - $insertqr .= "'" . auto_escape($_POST[$fieldname]) . "', \n"; - if ($irow['type'] == "P") - { - $fieldname2 = $fieldname."comment"; - $col_name .= db_quote_id($fieldname2).", \n"; - $insertqr .= "'" . auto_escape($_POST[$fieldname2]) . "', \n"; - } - } - } - if (isset($otherexists) && $otherexists == "Y") - { - $fieldname = "{$irow['sid']}X{$irow['gid']}X{$irow['qid']}other"; - $col_name .= db_quote_id($fieldname).", \n"; - $insertqr .= "'" . auto_escape($_POST[$fieldname]) . "', \n"; - } - } - } - - $col_name = substr($col_name, 0, -3); //Strip off the last comma-space - $insertqr = substr($insertqr, 0, -3); //Strip off the last comma-space - - //NOW SHOW SCREEN - if (bHasSurveyGotTokentable($thissurvey) && - isset($_POST['token']) && $_POST['token'] && - $thissurvey['private'] == 'N') //handle tokens if survey needs them - { - $col_name .= ", token\n"; - $insertqr .= ", '{$_POST['token']}'"; - } - if (isset($_POST['datestamp']) && $_POST['datestamp']) //handle datestamp if needed - { - $col_name .= ", datestamp\n"; - $insertqr .= ", '{$_POST['datestamp']}'"; - } - if (isset($_POST['ipaddr']) && $_POST['ipaddr']) //handle datestamp if needed - { - $col_name .= ", ipaddr\n"; - $insertqr .= ", '{$_POST['ipaddr']}'"; - } - if (isset($_POST['language']) && $_POST['language']) // handle language - { - $col_name .= ", startlanguage\n"; - $insertqr .= ", '{$_POST['language']}'"; - } - if (isset($_POST['closerecord'])) // handle Submidate if required - { - if ($thissurvey['private'] =="Y" && $thissurvey['datestamp'] =="N") - { - $col_name .= ", submitdate\n"; - $insertqr .= ", '".date("Y-m-d H:i:s",mktime(0,0,0,1,1,1980))."'"; - } - elseif (isset($_POST['closedate']) && $_POST['closedate'] != '') - { - $col_name .= ", submitdate\n"; - $insertqr .= ", '{$_POST['closedate']}'"; - } - } - // $dataentryoutput .= "\t\t\tInserting data
      \n" - // ."SID: $surveyid, ($surveytable)

      \n"; - $SQL = "INSERT INTO $surveytable - ($col_name) - VALUES - ($insertqr)"; - //$dataentryoutput .= $SQL; //Debugging line - - $iinsert = $connect->Execute($SQL) or safe_die ("Could not insert your data:
      $SQL
      \n" .$connect->ErrorMsg()); - /*if (returnglobal('redo')=="yes") - { - //This submission of data came from a saved session. Must delete the - //saved session now that it has been recorded in the responses table - $dquery = "DELETE FROM ".db_table_name("saved_control")." WHERE scid=".$saver['scid']; - if ($dresult=$connect->Execute($dquery)) - { - $dquery = "DELETE FROM ".db_table_name("saved")." WHERE scid=".$saver['scid']; - $dresult=$connect->Execute($dquery) or safe_die("Couldn't delete saved data
      $dquery
      ".htmlspecialchars($connect->ErrorMsg())); - } - else - { - $dataentryoutput .= "Couldn't delete saved data
      $dquery
      ".htmlspecialchars($connect->ErrorMsg()); - } - }*/ - - if (isset($_POST['closerecord']) && isset($_POST['token']) && $_POST['token'] != '') // submittoken - { - $today = date_shift(date("Y-m-d H:i:s"), "Y-m-d", $timeadjust); - $utquery = "UPDATE {$dbprefix}tokens_$surveyid\n"; - if (bIsTokenCompletedDatestamped($thissurvey)) - { - $utquery .= "SET completed='$today'\n"; - } - else - { - $utquery .= "SET completed='Y'\n"; - } - $utquery .= "WHERE token='{$_POST['token']}'"; - $utresult = $connect->Execute($utquery) or safe_die ("Couldn't update tokens table!
      \n$utquery
      \n".$connect->ErrorMsg()); - } - if (isset($_POST['save']) && $_POST['save'] == "on") - { - $srid = $connect->Insert_ID(); - //CREATE ENTRY INTO "saved_control" - $scdata = array("sid"=>$surveyid, - "srid"=>$srid, - "identifier"=>$saver['identifier'], - "access_code"=>$password, - "email"=>$saver['email'], - "ip"=>$_SERVER['REMOTE_ADDR'], - "refurl"=>getenv("HTTP_REFERER"), - 'saved_thisstep' => 0, - "status"=>"S", - "saved_date"=>date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust)); - - if ($connect->AutoExecute("{$dbprefix}saved_control", $scdata,'INSERT')) - { - $scid = $connect->Insert_ID("{$dbprefix}saved_control","scid"); - - $dataentryoutput .= "".$clang->gT("Your survey responses have been saved successfully. You will be sent a confirmation e-mail. Please make sure to save your password, since we will not be able to retrieve it for you.")."
      \n"; - - $tkquery = "SELECT * FROM ".db_table_name("tokens_$surveyid"); - if ($tkresult = $connect->Execute($tkquery)) //If the query fails, assume no tokens table exists - { - $tokendata = array ( - "firstname"=> $saver['identifier'], - "lastname"=> $saver['identifier'], - "email"=>$saver['email'], - "token"=>randomkey(15), - "language"=>$saver['language'], - "sent"=>date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i", $timeadjust), - "completed"=>"N"); - $connect->AutoExecute(db_table_name("tokens_".$surveyid), $tokendata,'INSERT'); - $dataentryoutput .= "".$clang->gT("A token entry for the saved survey has been created too.")."
      \n"; - - } - - if ($saver['email']) - { - //Send email - if (validate_email($saver['email']) && !returnglobal('redo')) - { - $subject=$clang->gT("Saved Survey Details"); - $message=$clang->gT("Thank you for saving your survey in progress. The following details can be used to return to this survey and continue where you left off. Please keep this e-mail for your reference - we cannot retrieve the password for you."); - $message.="\n\n".$thissurvey['name']."\n\n"; - $message.=$clang->gT("Name").": ".$saver['identifier']."\n"; - $message.=$clang->gT("Password").": ".$saver['password']."\n\n"; - $message.=$clang->gT("Reload your survey by clicking on the following link (or pasting it into your browser):").":\n"; - $message.=$publicurl."/index.php?sid=$surveyid&loadall=reload&scid=".$scid."&lang=".urlencode($saver['language'])."&loadname=".urlencode($saver['identifier'])."&loadpass=".urlencode($saver['password']); - if (isset($tokendata['token'])) {$message.="&token=".$tokendata['token'];} - $from = $thissurvey['adminemail']; - - if (MailTextMessage($message, $subject, $saver['email'], $from, $sitename, false, getBounceEmail($surveyid))) - { - $emailsent="Y"; - $dataentryoutput .= "".$clang->gT("An email has been sent with details about your saved survey")."
      \n"; - } - } - } - - } - else - { - safe_die("Unable to insert record into saved_control table.

      ".$connect->ErrorMsg()); - } - - } - $dataentryoutput .= "\t\t\t".$clang->gT("Success")."
      \n"; - $thisid=$connect->Insert_ID(); - $dataentryoutput .= "\t\t\t".$clang->gT("The entry was assigned the following record id: ")." {$thisid}
      \n"; - } - - $dataentryoutput .= $errormsg; - $dataentryoutput .= "\t\t\t
      [".$clang->gT("Add Another Record")."]
      \n"; - $dataentryoutput .= "[".$clang->gT("Return to Survey Administration")."
      \n"; - if (isset($thisid)) - { - $dataentryoutput .= "\t\t\t[".$clang->gT("View This Record")."]
      \n"; - } - if (isset($_POST['save']) && $_POST['save'] == "on") - { - $dataentryoutput .= "\t\t\t[".$clang->gT("Browse Saved Responses")."]
      \n"; - } - $dataentryoutput .= "\t\t\t[".$clang->gT("Browse Responses")."]
      \n" - ."\t
      \n" - ."\n"; - - } - - elseif ($subaction == "edit" || $subaction == "editsaved") - { - $dataentryoutput .= "\n" - ."\t\n"; - if (isset($surveyheader)) {$dataentryoutput .= $surveyheader;} - $dataentryoutput .= $surveyoptions - ."\n"; - - if (!isset($_GET['language'])) $_GET['language'] = GetBaseLanguageFromSurveyID($surveyid); - - - - - - - //FIRST LETS GET THE NAMES OF THE QUESTIONS AND MATCH THEM TO THE FIELD NAMES FOR THE DATABASE - $fnquery = "SELECT * FROM ".db_table_name("questions").", ".db_table_name("groups").", ".db_table_name("surveys")." WHERE - ".db_table_name("questions").".gid=".db_table_name("groups").".gid AND - ".db_table_name("questions").".language = '{$language}' AND ".db_table_name("groups").".language = '{$language}' AND - ".db_table_name("questions").".sid=".db_table_name("surveys").".sid AND ".db_table_name("questions").".sid='$surveyid'"; - $fnresult = db_execute_assoc($fnquery); - $fncount = $fnresult->RecordCount(); - //$dataentryoutput .= "$fnquery

      \n"; - $fnrows = array(); //Create an empty array in case FetchRow does not return any rows - while ($fnrow = $fnresult->FetchRow()) - { - $fnrows[] = $fnrow; - $private=$fnrow['private']; - $datestamp=$fnrow['datestamp']; - $ipaddr=$fnrow['ipaddr']; - } // Get table output into array - // Perform a case insensitive natural sort on group name then question title of a multidimensional array - usort($fnrows, 'CompareGroupThenTitle'); - // $fnames = (Field Name in Survey Table, Short Title of Question, Question Type, Field Name, Question Code, Predetermined Answers if exist) - $fnames[] = array("id", "id", "id", "id", "id", "id", "id", ""); - - if ($private == "N") //show token info if survey not private - { - $fnames[] = array ("token", $clang->gT("Token ID"), $clang->gT("Token"), "token", "TID", "", ""); - } - if ($datestamp == "Y") - { - $fnames[] = array ("datestamp", $clang->gT("Date Stamp"), $clang->gT("Date Stamp"), "datestamp", "datestamp", "", ""); - } - if ($ipaddr == "Y") - { - $fnames[] = array ("ipaddr", $clang->gT("IP Address"), $clang->gT("IP Address"), "ipaddr", "ipaddr", "", ""); - } - $fcount=0; - foreach ($fnrows as $fnrow) - { - $fcount++; - $field = "{$fnrow['sid']}X{$fnrow['gid']}X{$fnrow['qid']}"; - $ftitle = "Grp{$fnrow['gid']}Qst{$fnrow['title']}"; - $fquestion = $fnrow['question']; - if ($fnrow['type'] == "M" || $fnrow['type'] == "A" || $fnrow['type'] == "B" || $fnrow['type'] == "C" || - $fnrow['type'] == "E" || $fnrow['type'] == "F" || $fnrow['type'] == "H" || $fnrow['type'] == "P" || - $fnrow['type'] == "Q" || $fnrow['type'] == "^" || $fnrow['type'] == "J" || $fnrow['type'] == "K") - { - $fnrquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid={$fnrow['qid']} and language='{$language}' ORDER BY sortorder, answer"; - $fnrresult = db_execute_assoc($fnrquery); - while ($fnrrow = $fnrresult->FetchRow()) - { - $fnames[] = array("$field{$fnrrow['code']}", "$ftitle ({$fnrrow['code']})", "{$fnrow['question']}", "{$fnrow['type']}", "$field", "{$fnrrow['code']}", "{$fnrrow['answer']}", "{$fnrow['qid']}", "{$fnrow['lid']}"); - if ($fnrow['type'] == "P") - { - $fnames[] = array("$field{$fnrrow['code']}"."comment", "$ftitle"."comment", "{$fnrow['question']}(comment)", "{$fnrow['type']}", "$field", "{$fnrrow['code']}", "{$fnrrow['answer']}", "{$fnrow['qid']}", "{$fnrow['lid']}"); - } - } - if ($fnrow['other'] == "Y") - { - $fnames[] = array("$field"."other", "$ftitle"."other", "{$fnrow['question']}(other)", "{$fnrow['type']}", "$field", "{$fnrrow['code']}", "{$fnrrow['answer']}", "{$fnrow['qid']}", "{$fnrow['lid']}"); - if ($fnrow['type'] == "P") - { - $fnames[] = array("$field"."othercomment", "$ftitle"."othercomment", "{$fnrow['question']}(other comment)", "{$fnrow['type']}", "$field", "{$fnrrow['code']}", "{$fnrrow['answer']}", "{$fnrow['qid']}", "{$fnrow['lid']}"); - } - } - - } - elseif ($fnrow['type'] == "R") - { - $fnrquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid={$fnrow['qid']} and language='{$language}' ORDER BY sortorder, answer"; - $fnrresult = $connect->Execute($fnrquery); - $fnrcount = $fnrresult->RecordCount(); - for ($j=1; $j<=$fnrcount; $j++) - { - $fnames[] = array("$field$j", "$ftitle ($j)", "{$fnrow['question']}", "{$fnrow['type']}", "$field", "{$fnrrow['code']}", "$j", "{$fnrow['qid']}", "{$fnrow['lid']}"); - } - } - elseif ($fnrow['type'] == "1") - { - $fnrquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid={$fnrow['qid']} and language='{$language}' ORDER BY sortorder, answer"; - $fnrresult = $connect->Execute($fnrquery); - while ($fnrrow = $fnrresult->FetchRow()) - { - $fnames[] = array("$field{$fnrrow['code']}#0", "$ftitle ({$fnrrow['code']})", "{$fnrow['question']}", "{$fnrow['type']}", "$field", "{$fnrrow['code']}", "{$fnrrow['answer']} (1)", "{$fnrow['qid']}", "{$fnrow['lid']}"); - $fnames[] = array("$field{$fnrrow['code']}#1", "$ftitle ({$fnrrow['code']})", "{$fnrow['question']}", "{$fnrow['type']}", "$field", "{$fnrrow['code']}", "{$fnrrow['answer']} (2)", "{$fnrow['qid']}", "{$fnrow['lid1']}"); - } - } - elseif ($fnrow['type'] == "O") - { - if (!isset($fnrrow)) {$fnrrow=array("code"=>"", "answer"=>"");} - $fnames[] = array("$field", "$ftitle", "{$fnrow['question']}", "{$fnrow['type']}", "$field", "{$fnrrow['code']}", "{$fnrrow['answer']}", "{$fnrow['qid']}", "{$fnrow['lid']}"); - $field2 = $field."comment"; - $ftitle2 = $ftitle."[Comment]"; - $longtitle = "{$fnrow['question']}
      (Comment)"; - $fnames[] = array("$field2", "$ftitle", "{$fnrow['question']}", "{$fnrow['type']}", "$field", "{$fnrrow['code']}", "{$fnrrow['answer']}", "{$fnrow['qid']}", "{$fnrow['lid']}"); - } - else - { - if (!isset($fnrrow)) {$fnrrow=array("code"=>"", "answer"=>"");} - $fnames[] = array("$field", "$ftitle", "{$fnrow['question']}", "{$fnrow['type']}", "$field", "{$fnrrow['code']}", "{$fnrrow['answer']}", "{$fnrow['qid']}", "{$fnrow['lid']}"); - if (($fnrow['type'] == "L" || $fnrow['type'] == "!" || $fnrow['type'] == "Z" || $fnrow['type'] == "W") && $fnrow['other'] =="Y") - { - $fnames[] = array("$field"."other", "$ftitle"."other", "{$fnrow['question']}(other)", "{$fnrow['type']}", "$field", "{$fnrrow['code']}", "{$fnrrow['answer']}", "{$fnrow['qid']}", "{$fnrow['lid']}"); - } - } - } - $nfncount = count($fnames)-1; - - //SHOW INDIVIDUAL RECORD - - if ($subaction == "edit") - { - $idquery = "SELECT * FROM $surveytable WHERE id=$id"; - $idresult = db_execute_assoc($idquery) or safe_die ("Couldn't get individual record
      $idquery
      ".$connect->ErrorMsg()); - while ($idrow = $idresult->FetchRow()) - { - $results[]=$idrow; - } - } - elseif ($subaction == "editsaved") - { - if (isset($_GET['public']) && $_GET['public']=="true") - { - $password=md5($_GET['accesscode']); - } - else - { - $password=$_GET['accesscode']; - } - $svquery = "SELECT * FROM ".db_table_name("saved_control")." - WHERE sid=$surveyid - AND identifier='".$_GET['identifier']."' - AND access_code='".$password."'"; - $svresult=db_execute_assoc($svquery) or safe_die("Error getting save
      $svquery
      ".$connect->ErrorMsg()); - while($svrow=$svresult->FetchRow()) - { - $saver['email']=$svrow['email']; - $saver['scid']=$svrow['scid']; - $saver['ip']=$svrow['ip']; - } - $svquery = "SELECT * FROM ".db_table_name("saved_control")." WHERE scid=".$saver['scid']; - $svresult=db_execute_assoc($svquery) or safe_die("Error getting saved info
      $svquery
      ".$connect->ErrorMsg()); - while($svrow=$svresult->FetchRow()) - { - $responses[$svrow['fieldname']]=$svrow['value']; - } // while - $fieldmap = createFieldMap($surveyid); - foreach($fieldmap as $fm) - { - if (isset($responses[$fm['fieldname']])) - { - $results1[$fm['fieldname']]=$responses[$fm['fieldname']]; - } - else - { - $results1[$fm['fieldname']]=""; - } - } - $results1['id']=""; - $results1['datestamp']=date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust); - $results1['ipaddr']=$saver['ip']; - $results[]=$results1; - } - // $dataentryoutput .= "
      ";print_r($results);$dataentryoutput .= "
      "; - - $dataentryoutput .= "
      \n" - ."\n" - ."\t\n" - ."\t\n" - ."\t\n"; - - foreach ($results as $idrow) - { - //$dataentryoutput .= "
      "; print_r($idrow);$dataentryoutput .= "
      "; - for ($i=0; $i<$nfncount+1; $i++) - { - //$dataentryoutput .= "
      "; print_r($fnames[$i]);$dataentryoutput .= "
      "; - $answer = $idrow[$fnames[$i][0]]; - $question=$fnames[$i][2]; - $dataentryoutput .= "\t\n" - ."\t\t\n" - ."\t\t\n"; - $dataentryoutput .= "\t\n"; - $dataentryoutput .= "\t\n"; - $dataentryoutput .= "
      " - .$clang->gT("Data Entry")."
      " - .$clang->gT("Editing Response")." (ID $id)
      " - ."\n"; - $dataentryoutput .= "\t\t\t{$fnames[$i][2]}\n"; - $dataentryoutput .= "\t\t\n"; - //$dataentryoutput .= "\t\t\t-={$fnames[$i][3]}=-"; //Debugging info - switch ($fnames[$i][3]) - { - case "X": //Boilerplate question - $dataentryoutput .= ""; - break; - case "Q": - case "K": - $dataentryoutput .= "\t\t\t{$fnames[$i][6]} \n"; - break; - case "id": - $dataentryoutput .= "\t\t\t {$idrow[$fnames[$i][0]]} ".$clang->gT("Cannot be modified")."\n"; - break; - case "5": //5 POINT CHOICE radio-buttons - for ($x=1; $x<=5; $x++) - { - $dataentryoutput .= "\t\t\tgT("Please choose")."..\n" - ."\t\t\t\t\n" - ."\t\t\t\t\n" - ."\t\t\t\n"; - break; - case "W": - case "Z": - if (substr($fnames[$i][0], -5) == "other") - { - $dataentryoutput .= "\t\t\t\n"; - } - else - { - $lquery = "SELECT * FROM ".db_table_name("labels") - ." WHERE lid={$fnames[$i][8]} AND ".db_table_name("labels").".language = '{$language}' ORDER BY sortorder, code"; - $lresult = db_execute_assoc($lquery); - $dataentryoutput .= "\t\t\t\n"; - } - break; - case "L": //LIST drop-down - case "!": //List (Radio) - if (substr($fnames[$i][0], -5) == "other") - { - $dataentryoutput .= "\t\t\t\n"; - } - else - { - $lquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid={$fnames[$i][7]} AND ".db_table_name("answers").".language = '{$language}' ORDER BY sortorder, answer"; - $lresult = db_execute_assoc($lquery); - $dataentryoutput .= "\t\t\t\n"; - } - break; - case "O": //LIST WITH COMMENT drop-down/radio-button list + textarea - $lquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid={$fnames[$i][7]} AND ".db_table_name("answers").".language = '{$language}' ORDER BY sortorder, answer"; - $lresult = db_execute_assoc($lquery); - $dataentryoutput .= "\t\t\t\n"; - break; - case "R": //RANKING TYPE QUESTION - $l=$i; - $thisqid=$fnames[$l][7]; - $myfname=substr($fnames[$i][0], 0, -1); - while (isset($fnames[$i][3]) && $fnames[$i][3] == "R") - { - //Let's get all the existing values into an array - if ($idrow[$fnames[$i][0]]) - { - $currentvalues[] = $idrow[$fnames[$i][0]]; - } - $i++; - } - $ansquery = "SELECT * FROM ".db_table_name("answers")." WHERE ".db_table_name("answers").".language = '{$language}' AND qid=$thisqid ORDER BY sortorder, answer"; - $ansresult = db_execute_assoc($ansquery); - $anscount = $ansresult->RecordCount(); - $dataentryoutput .= "\t\t\t\n"; - while ($ansrow = $ansresult->FetchRow()) //Now we're getting the codes and answers - { - $answers[] = array($ansrow['code'], $ansrow['answer']); - } - //now find out how many existing values there are - - $chosen[]=""; //create array - if (!isset($ranklist)) {$ranklist="";} - - if (isset($currentvalues)) - { - $existing = count($currentvalues); - } - else {$existing=0;} - for ($j=1; $j<=$anscount; $j++) //go through each ranking and check for matching answer - { - $k=$j-1; - if (isset($currentvalues) && $currentvalues[$k]) - { - foreach ($answers as $ans) - { - if ($ans[0] == $currentvalues[$k]) - { - $thiscode=$ans[0]; - $thistext=$ans[1]; - } - } - } - $ranklist .= "\t\t\t\t\t\t$j: \n" - . "\t\t\t\t\t\t\n" - . "\t\t\t\t\t\t".$clang->gT("Remove this item")."
      \n\n"; - } - - if (!isset($choicelist)) {$choicelist="";} - $choicelist .= "\t\t\t\t\t\t\n"; - $dataentryoutput .= "\t\t\t\n" - ."\t\t\t\t\n" - ."\t\t\t\t\t\n" - ."\t\t\t\t\t\n" - ."\t\t\t\t\n" - ."\t\t\t
      \n" - ."\t\t\t\t\t\t" - .$clang->gT("Your Choices").":
      \n" - .$choicelist - ."\t\t\t\t\t
      \n" - ."\t\t\t\t\t\t" - .$clang->gT("Your Ranking").":
      \n" - .$ranklist - ."\t\t\t\t\t
      \n" - ."\t\t\t\n" - ."\t\t\t\n"; - $choicelist=""; - $ranklist=""; - unset($answers); - $i--; - break; - - case "M": //MULTIPLE OPTIONS checkbox - $qidattributes=getQuestionAttributes($fnames[$i][7]); - if ($displaycols=arraySearchByKey("display_columns", $qidattributes, "attribute", 1)) - { - $dcols=$displaycols['value']; - } - else - { - $dcols=0; - } - -// while ($fnames[$i][3] == "M" && $question != "" && $question == $fnames[$i][2]) - while ($fnames[$i][3] == "M" && $question == $fnames[$i][2]) - { - $fieldn = substr($fnames[$i][0], 0, strlen($fnames[$i][0])); - //$dataentryoutput .= substr($fnames[$i][0], strlen($fnames[$i][0])-5, 5)."
      \n"; - if (substr($fnames[$i][0], -5) == "other") - { - $dataentryoutput .= "\t\t\t\n"; - } - else - { - $dataentryoutput .= "\t\t\tgT("Please choose")."..\n"; - - foreach ($slangs as $lang) - { - $dataentryoutput.="
      \n"; - $dataentryoutput .= "\t\n"; - $dataentryoutput .= "\t\n"; - $dataentryoutput .= "\t\n"; - $dataentryoutput .= "\t\n"; - $dataentryoutput .= "\t
      \n"; - $dataentryoutput .= "\t\n"; - } - $dataentryoutput .= " "; -} -else -{ - $action = "browse_response"; - include("access_denied.php"); - include("admin.php"); -} - - -function array_in_array($needle, $haystack) -{ - foreach ($haystack as $value) - { - if ($needle == $value) - return true; - } - return false; -} - -?> +ErrorMsg()); +$actsurrows = $actsurresult->FetchRow(); + +if ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $actsurrows['browse_response']) +{ + + $surveyoptions = browsemenubar($clang->gT("Browse Responses")); + if (!$surveyid && !$subaction) + { + //$dataentryoutput .= "\n"; + $dataentryoutput .= "\n" + ."\t\n" + ."\t
      " + .$clang->gT("Data Entry")."
      \n" + ."".$clang->gT("Error")."
      \n" + .$clang->gT("You have not selected a survey for data-entry.")."

      \n" + ."
      \n" + ."
      \n"; + return; + } + + if ($subaction == "edit" || $subaction == "" || $subaction == "editsaved" || $subaction == "insert") + { + $language = GetBaseLanguageFromSurveyID($surveyid); + } + + if ($subaction == "insert") + { + $thissurvey=getSurveyInfo($surveyid); + $errormsg=""; + $dataentryoutput .= "\n" + ."\t\n" + ."\t\n" + ."
      " + .$clang->gT("Data Entry")."
      \n"; + + $lastanswfortoken=''; // check if a previous answer has been submitted or saved + $rlanguage=''; + if (isset($_POST['token']) && $_POST['token']) + { + $tokencompleted = ""; + $tokentable = db_table_name("tokens_".$surveyid); + $tcquery = "SELECT completed from $tokentable WHERE token='".$_POST['token']."'"; + $tcresult = db_execute_assoc($tcquery); + $tccount = $tcresult->RecordCount(); + while ($tcrow = $tcresult->FetchRow()) + { + $tokencompleted = $tcrow['completed']; + } + + if ($tccount < 1) + { // token doesn't exist in token table + $lastanswfortoken='UnknownToken'; + } + elseif ($thissurvey['private'] == "Y") + { // token exist but survey is anonymous, check completed state + if ($tokencompleted != "" && $tokencompleted != "N") + { // token is not completed + $lastanswfortoken='PrivacyProtected'; + } + } + else + { // token is valid, survey not anonymous, try to get last recorded response id + $aquery = "SELECT id,startlanguage FROM $surveytable WHERE token='".$_POST['token']."'"; + $aresult = db_execute_assoc($aquery); + while ($arow = $aresult->FetchRow()) + { + $lastanswfortoken=$arow['id']; + $rlanguage=$arow['startlanguage']; + } + } + } + + if (tokenTableExists($thissurvey['sid']) && (!isset($_POST['token']) || !$_POST['token'])) + {// First Check if the survey uses tokens and if a token has been provided + $errormsg="".$clang->gT("Error").": ".$clang->gT("This is a closed-access survey, so you must supply a valid token. Please contact the administrator for assistance.")."\n"; + } + elseif (tokenTableExists($thissurvey['sid']) && $lastanswfortoken == 'UnknownToken') + { + $errormsg="".$clang->gT("Error").": ".$clang->gT("The token you have provided is not valid or has already been used.")."\n"; + } + elseif (tokenTableExists($thissurvey['sid']) && $lastanswfortoken != '') + { + $errormsg="".$clang->gT("Error").": ".$clang->gT("There is already a recorded answer for this token")."\n"; + if ($lastanswfortoken != 'PrivacyProtected') + { + $errormsg .= "

      ".$clang->gT("Follow the following link to update it").":\n" + . "gT("Edit this entry", "js")."')\">[id:$lastanswfortoken]"; + } + else + { + $errormsg .= "

      ".$clang->gT("This surveys uses anonymous answers, so you can't update your response.")."\n"; + } + } + else + { + if (isset($_POST['save']) && $_POST['save'] == "on") + { + $saver['identifier']=returnglobal('save_identifier'); + $saver['language']=returnglobal('save_language'); + $saver['password']=returnglobal('save_password'); + $saver['passwordconfirm']=returnglobal('save_confirmpassword'); + $saver['email']=returnglobal('save_email'); + if (!returnglobal('redo')) + { + $password=md5($saver['password']); + } + else + { + $password=$saver['password']; + } + $errormsg=""; + if (!$saver['identifier']) {$errormsg .= $clang->gT("Error").": ".$clang->gT("You must supply a name for this saved session.");} + if (!$saver['password']) {$errormsg .= $clang->gT("Error").": ".$clang->gT("You must supply a password for this saved session.");} + if ($saver['password'] != $saver['passwordconfirm']) {$errormsg .= $clang->gT("Error").": ".$clang->gT("Your passwords do not match.");} + if ($errormsg) + { + $dataentryoutput .= $errormsg; + $dataentryoutput .= $clang->gT("Try again").":
      +
      + + + + + + + + + + + "; + if (isset($_POST['datestamp'])) + { + $dataentryoutput .= "\n"; + } + if (isset($_POST['ipaddr'])) + { + $dataentryoutput .= "\n"; + } + $dataentryoutput .= "
      ".$clang->gT("Identifier:")."
      ".$clang->gT("Password:")."
      ".$clang->gT("Confirm Password:")."
      ".$clang->gT("Email:")." +
      ".$clang->gT("Start Language:")."\n"; + foreach ($_POST as $key=>$val) + { + if (substr($key, 0, 4) != "save" && $key != "action" && $key != "surveytable" && $key !="sid" && $key != "datestamp" && $key !="ipaddr") + { + $dataentryoutput .= "\n"; + } + } + $dataentryoutput .= "
      + + + + +
      \n"; + } elseif (returnglobal('redo')=="yes") + { + //Delete all the existing entries TODO WTF IS REDO? + //$delete="DELETE FROM ".db_table_name("saved")." WHERE scid=".$saver['scid']; + //$result=$connect->Execute($delete) or safe_die("Couldn't delete old record
      $delete
      ".htmlspecialchars($connect->ErrorMsg())); + //$delete="DELETE FROM ".db_table_name("saved_control")." WHERE scid=".$surveytable['scid']; + //$result=$connect->Execute($delete) or safe_die("Couldn't delete old record
      $delete
      ".htmlspecialchars($connect->ErrorMsg())); + } + } + //BUILD THE SQL TO INSERT RESPONSES + $baselang = GetBaseLanguageFromSurveyID($surveyid); + $iquery = "SELECT * FROM ".db_table_name("questions").", ".db_table_name("groups")." WHERE + ".db_table_name("questions").".gid=".db_table_name("groups").".gid AND + ".db_table_name("questions").".language = '{$baselang}' AND ".db_table_name("groups").".language = '{$baselang}' AND + ".db_table_name("questions").".sid=$surveyid ORDER BY ".db_table_name("groups").".group_order, title"; + $iresult = db_execute_assoc($iquery); + $col_name=""; + $insertqr=""; + while ($irow = $iresult->FetchRow()) + { + if ($irow['type'] != "M" && $irow['type'] != "A" && $irow['type'] != "B" && $irow['type'] != "C" && + $irow['type'] != "E" && $irow['type'] != "F" && $irow['type'] != "H" && $irow['type'] != "P" && + $irow['type'] != "O" && $irow['type'] != "R" && $irow['type'] != "Q" && $irow['type'] != "J" && + $irow['type'] != "K" && $irow['type'] != ":" && $irow['type'] != "1" && $irow['type'] != ";") + { + $fieldname = "{$irow['sid']}X{$irow['gid']}X{$irow['qid']}"; + if (isset($_POST[$fieldname])) + { + if ($irow['type'] == 'D' && $_POST[$fieldname] == "") + { // can't add '' in Date column + // Do nothing + } + elseif ($irow['type'] == 'N' && $_POST[$fieldname] == "") + { // can't add '' to numerical column + // Do nothing + } + else + { + $col_name .= db_quote_id($fieldname).", \n"; + $insertqr .= "'" . auto_escape($_POST[$fieldname]) . "', \n"; + } + } + // if "!" "L" "W" "Z", and Other ==> add other fieldname + if ($irow['type'] == "!" || $irow['type'] == "L" || + $irow['type'] == "W" || $irow['type'] == "Z") + { + $fieldname2=$fieldname."other"; + if (isset($_POST[$fieldname2]) && isset($_POST[$fieldname]) && $_POST[$fieldname] == '-oth-' && $_POST[$fieldname2]!= "") + { + $col_name .= db_quote_id($fieldname2).", \n"; + $insertqr .= "'" . auto_escape($_POST[$fieldname2]) . "', \n"; + } + } + } + elseif ($irow['type'] == "O") + { + $fieldname = "{$irow['sid']}X{$irow['gid']}X{$irow['qid']}"; + $fieldname2 = $fieldname . "comment"; + $col_name .= db_quote_id($fieldname).", \n".db_quote_id($fieldname2).", \n"; + $insertqr .= "'" . auto_escape($_POST[$fieldname]) . "', \n'" . auto_escape($_POST[$fieldname2]) . "', \n"; + } + elseif ($irow['type'] == "1") + { + $i2query = "SELECT ".db_table_name("answers").".*, ".db_table_name("questions").".other FROM ".db_table_name("answers").", ".db_table_name("questions")." WHERE + ".db_table_name("answers").".qid=".db_table_name("questions").".qid AND ".db_table_name("questions").".qid={$irow['qid']} AND + ".db_table_name("questions").".language = '{$language}' AND ".db_table_name("answers").".language = '{$language}' AND + ".db_table_name("questions").".sid=$surveyid ORDER BY ".db_table_name("answers").".sortorder, ".db_table_name("answers").".answer"; + + $i2result = $connect->Execute($i2query); + $i2count = $i2result->RecordCount(); + while ($i2answ = $i2result->FetchRow()) + { + // first scale + $fieldname = "{$irow['sid']}X{$irow['gid']}X{$irow['qid']}{$i2answ['code']}#0"; + $col_name .= db_quote_id($fieldname).", \n"; + $insertqr .= "'" . auto_escape($_POST["$fieldname"]) . "', \n"; + // second scale + $fieldname = "{$irow['sid']}X{$irow['gid']}X{$irow['qid']}{$i2answ['code']}#1"; + $col_name .= db_quote_id($fieldname).", \n"; + $insertqr .= "'" . auto_escape($_POST["$fieldname"]) . "', \n"; + } + + } + elseif ($irow['type'] == "R") + { + $i2query = "SELECT ".db_table_name("answers").".*, ".db_table_name("questions").".other FROM ".db_table_name("answers").", ".db_table_name("questions")." WHERE + ".db_table_name("answers").".qid=".db_table_name("questions").".qid AND ".db_table_name("questions").".qid={$irow['qid']} AND + ".db_table_name("questions").".language = '{$language}' AND ".db_table_name("answers").".language = '{$language}' AND + ".db_table_name("questions").".sid=$surveyid ORDER BY ".db_table_name("answers").".sortorder, ".db_table_name("answers").".answer"; + $i2result = $connect->Execute($i2query); + $i2count = $i2result->RecordCount(); + for ($i=1; $i<=$i2count; $i++) + { + $fieldname = "{$irow['sid']}X{$irow['gid']}X{$irow['qid']}$i"; + $col_name .= db_quote_id($fieldname).", \n"; + $insertqr .= "'" . auto_escape($_POST["d$fieldname"]) . "', \n"; + } + } + elseif ($irow['type'] == ":" || $irow['type'] == ";") + { + $i2query = "SELECT ".db_table_name("answers").".*, ".db_table_name("questions").".other FROM ".db_table_name("answers").", ".db_table_name("questions")." + WHERE ".db_table_name("answers").".qid=".db_table_name("questions").".qid AND + ".db_table_name("answers").".language='{$language}' AND ".db_table_name("questions").".language='{$language}' AND + ".db_table_name("questions").".qid={$irow['qid']} AND ".db_table_name("questions").".sid=$surveyid + ORDER BY ".db_table_name("answers").".sortorder, ".db_table_name("answers").".answer"; + $i2result = db_execute_assoc($i2query); + $ab2query = "SELECT ".db_table_name('labels').".* + FROM ".db_table_name('questions').", ".db_table_name('labels')." + WHERE sid=$surveyid + AND ".db_table_name('labels').".lid=".db_table_name('questions').".lid + AND ".db_table_name('questions').".language='".$language."' + AND ".db_table_name('labels').".language='".$language."' + AND ".db_table_name('questions').".qid=".$irow['qid']." + ORDER BY ".db_table_name('labels').".sortorder, ".db_table_name('labels').".title"; + $ab2result=db_execute_assoc($ab2query) or die("Couldn't get list of labels in createFieldMap function (case :)
      $ab2query
      ".htmlspecialchars($connection->ErrorMsg())); + while($ab2row=$ab2result->FetchRow()) + { + $lset[]=$ab2row; + } + while ($i2row = $i2result->FetchRow()) + { + foreach($lset as $ls) + { + $fieldname = "{$irow['sid']}X{$irow['gid']}X{$irow['qid']}{$i2row['code']}_{$ls['code']}"; + $col_name .= db_quote_id($fieldname).", \n"; + $insertqr .= "'" . auto_escape($_POST[$fieldname]) . "', \n"; + } + } + unset($lset); + } + else + { + $i2query = "SELECT ".db_table_name("answers").".*, ".db_table_name("questions").".other FROM ".db_table_name("answers").", ".db_table_name("questions")." + WHERE ".db_table_name("answers").".qid=".db_table_name("questions").".qid AND + ".db_table_name("questions").".language = '{$language}' AND ".db_table_name("answers").".language = '{$language}' AND + ".db_table_name("questions").".qid={$irow['qid']} + AND ".db_table_name("questions").".sid=$surveyid ORDER BY ".db_table_name("answers").".sortorder, ".db_table_name("answers").".answer"; + $i2result = db_execute_assoc($i2query); + while ($i2row = $i2result->FetchRow()) + { + $otherexists = ""; + if ($i2row['other'] == "Y" and ($irow['type']=="!" or $irow['type']=="L" or $irow['type']=="M" or $irow['type']=="P" or $irow['type'] == "W" or $irow['type'] == "Z")) {$otherexists = "Y";} + $fieldname = "{$irow['sid']}X{$irow['gid']}X{$irow['qid']}{$i2row['code']}"; + if (isset($_POST[$fieldname])) + { + if ($irow['type'] == 'K' && $_POST[$fieldname] == "") + { // can't add '' in a numerical column + // Do nothing + } + else + { + $col_name .= db_quote_id($fieldname).", \n"; + $insertqr .= "'" . auto_escape($_POST[$fieldname]) . "', \n"; + } + + if ($irow['type'] == "P") + { + $fieldname2 = $fieldname."comment"; + $col_name .= db_quote_id($fieldname2).", \n"; + $insertqr .= "'" . auto_escape($_POST[$fieldname2]) . "', \n"; + } + } + } + if (isset($otherexists) && $otherexists == "Y") + { + $fieldname = "{$irow['sid']}X{$irow['gid']}X{$irow['qid']}other"; + $col_name .= db_quote_id($fieldname).", \n"; + $insertqr .= "'" . auto_escape($_POST[$fieldname]) . "', \n"; + + if ($irow['type']=="P") + { + $fieldname = "{$irow['sid']}X{$irow['gid']}X{$irow['qid']}othercomment"; + $col_name .= db_quote_id($fieldname).", \n"; + $insertqr .= "'" . auto_escape($_POST[$fieldname]) . "', \n"; + } + } + } + } + + $stripCommaColName = false; + if ($col_name == "") + { // if cold_name is empty, set a flag so that we delete the beginning "," + $stripCommaColName = true; + } + $stripCommaInsertqr = false; + if ($insertqr =="") + { // if insertqr is empty, set a flag so that we delete the beginning "," + $stripCommaInsertqr = true; + } + + $col_name = substr($col_name, 0, -3); //Strip off the last comma-space + $insertqr = substr($insertqr, 0, -3); //Strip off the last comma-space + + //NOW SHOW SCREEN + if (tokenTableExists($thissurvey['sid']) && + isset($_POST['token']) && $_POST['token'] && + $thissurvey['private'] == 'N') //handle tokens if survey needs them + { + $col_name .= ", token\n"; + $insertqr .= ", '{$_POST['token']}'"; + } + if (isset($_POST['datestamp']) && $_POST['datestamp']) //handle datestamp if needed + { + $col_name .= ", datestamp\n"; + $insertqr .= ", '{$_POST['datestamp']}'"; + $col_name .= ", startdate\n"; + $insertqr .= ", '{$_POST['datestamp']}'"; + } + if (isset($_POST['ipaddr']) && $_POST['ipaddr']) //handle datestamp if needed + { + $col_name .= ", ipaddr\n"; + $insertqr .= ", '{$_POST['ipaddr']}'"; + } + if (isset($_POST['language']) && $_POST['language']) // handle language + { + $col_name .= ", startlanguage\n"; + $insertqr .= ", '{$_POST['language']}'"; + } + if (isset($_POST['closerecord'])) // handle Submidate if required + { + if ($thissurvey['private'] =="Y" && $thissurvey['datestamp'] =="N") + { + $col_name .= ", submitdate\n"; + $insertqr .= ", '".date("Y-m-d H:i:s",mktime(0,0,0,1,1,1980))."'"; + } + elseif (isset($_POST['closedate']) && $_POST['closedate'] != '') + { + $col_name .= ", submitdate\n"; + $insertqr .= ", '{$_POST['closedate']}'"; + } + } + + if ($stripCommaColName === true) + { + $col_name=substr($col_name, 1); + } + if ($stripCommaInsertqr === true) + { + $insertqr=substr($insertqr, 1); + } + + // $dataentryoutput .= "\tInserting data
      \n" + // ."SID: $surveyid, ($surveytable)

      \n"; + $SQL = "INSERT INTO $surveytable + ($col_name) + VALUES + ($insertqr)"; + //$dataentryoutput .= $SQL; //Debugging line + + $iinsert = $connect->Execute($SQL) or safe_die ("Could not insert your data:
      $SQL
      \n" .$connect->ErrorMsg()); + /*if (returnglobal('redo')=="yes") + { + //This submission of data came from a saved session. Must delete the + //saved session now that it has been recorded in the responses table + $dquery = "DELETE FROM ".db_table_name("saved_control")." WHERE scid=".$saver['scid']; + if ($dresult=$connect->Execute($dquery)) + { + $dquery = "DELETE FROM ".db_table_name("saved")." WHERE scid=".$saver['scid']; + $dresult=$connect->Execute($dquery) or safe_die("Couldn't delete saved data
      $dquery
      ".htmlspecialchars($connect->ErrorMsg())); + } + else + { + $dataentryoutput .= "Couldn't delete saved data
      $dquery
      ".htmlspecialchars($connect->ErrorMsg()); + } + }*/ + + if (isset($_POST['closerecord']) && isset($_POST['token']) && $_POST['token'] != '') // submittoken + { + $today = date_shift(date("Y-m-d H:i:s"), "Y-m-d", $timeadjust); + $utquery = "UPDATE {$dbprefix}tokens_$surveyid\n"; + if (bIsTokenCompletedDatestamped($thissurvey)) + { + $utquery .= "SET completed='$today'\n"; + } + else + { + $utquery .= "SET completed='Y'\n"; + } + $utquery .= "WHERE token='{$_POST['token']}'"; + $utresult = $connect->Execute($utquery) or safe_die ("Couldn't update tokens table!
      \n$utquery
      \n".$connect->ErrorMsg()); + } + if (isset($_POST['save']) && $_POST['save'] == "on") + { + $srid = $connect->Insert_ID(); + //CREATE ENTRY INTO "saved_control" + $scdata = array("sid"=>$surveyid, + "srid"=>$srid, + "identifier"=>$saver['identifier'], + "access_code"=>$password, + "email"=>$saver['email'], + "ip"=>$_SERVER['REMOTE_ADDR'], + "refurl"=>getenv("HTTP_REFERER"), + 'saved_thisstep' => 0, + "status"=>"S", + "saved_date"=>date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust)); + + if ($connect->AutoExecute("{$dbprefix}saved_control", $scdata,'INSERT')) + { + $scid = $connect->Insert_ID("{$dbprefix}saved_control","scid"); + + $dataentryoutput .= "".$clang->gT("Your survey responses have been saved successfully. You will be sent a confirmation e-mail. Please make sure to save your password, since we will not be able to retrieve it for you.")."
      \n"; + + $tkquery = "SELECT * FROM ".db_table_name("tokens_$surveyid"); + if ($tkresult = $connect->Execute($tkquery)) //If the query fails, assume no tokens table exists + { + $tokendata = array ( + "firstname"=> $saver['identifier'], + "lastname"=> $saver['identifier'], + "email"=>$saver['email'], + "token"=>randomkey(15), + "language"=>$saver['language'], + "sent"=>date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i", $timeadjust), + "completed"=>"N"); + $connect->AutoExecute(db_table_name("tokens_".$surveyid), $tokendata,'INSERT'); + $dataentryoutput .= "".$clang->gT("A token entry for the saved survey has been created too.")."
      \n"; + + } + + if ($saver['email']) + { + //Send email + if (validate_email($saver['email']) && !returnglobal('redo')) + { + $subject=$clang->gT("Saved Survey Details"); + $message=$clang->gT("Thank you for saving your survey in progress. The following details can be used to return to this survey and continue where you left off. Please keep this e-mail for your reference - we cannot retrieve the password for you."); + $message.="\n\n".$thissurvey['name']."\n\n"; + $message.=$clang->gT("Name").": ".$saver['identifier']."\n"; + $message.=$clang->gT("Password").": ".$saver['password']."\n\n"; + $message.=$clang->gT("Reload your survey by clicking on the following link (or pasting it into your browser):").":\n"; + $message.=$publicurl."/index.php?sid=$surveyid&loadall=reload&scid=".$scid."&lang=".urlencode($saver['language'])."&loadname=".urlencode($saver['identifier'])."&loadpass=".urlencode($saver['password']); + if (isset($tokendata['token'])) {$message.="&token=".$tokendata['token'];} + $from = $thissurvey['adminemail']; + + if (MailTextMessage($message, $subject, $saver['email'], $from, $sitename, false, getBounceEmail($surveyid))) + { + $emailsent="Y"; + $dataentryoutput .= "".$clang->gT("An email has been sent with details about your saved survey")."
      \n"; + } + } + } + + } + else + { + safe_die("Unable to insert record into saved_control table.

      ".$connect->ErrorMsg()); + } + + } + $dataentryoutput .= "\t".$clang->gT("Success")."
      \n"; + $thisid=$connect->Insert_ID(); + $dataentryoutput .= "\t".$clang->gT("The entry was assigned the following record id: ")." {$thisid}
      \n"; + } + + $dataentryoutput .= $errormsg; + $dataentryoutput .= "\t
      [".$clang->gT("Add Another Record")."]
      \n"; + $dataentryoutput .= "[".$clang->gT("Return to Survey Administration")."]
      \n"; + if (isset($thisid)) + { + $dataentryoutput .= "\t[".$clang->gT("View This Record")."]
      \n"; + } + if (isset($_POST['save']) && $_POST['save'] == "on") + { + $dataentryoutput .= "\t[".$clang->gT("Browse Saved Responses")."]
      \n"; + } + $dataentryoutput .= "\t[".$clang->gT("Browse Responses")."]
      \n" + ."\t
      \n" + ."\n"; + + } + + elseif ($subaction == "edit" || $subaction == "editsaved") + { + $dataentryoutput .= $surveyoptions; + + if (!isset($_GET['language'])) $_GET['language'] = GetBaseLanguageFromSurveyID($surveyid); + + + + + + + //FIRST LETS GET THE NAMES OF THE QUESTIONS AND MATCH THEM TO THE FIELD NAMES FOR THE DATABASE + $fnquery = "SELECT * FROM ".db_table_name("questions").", ".db_table_name("groups").", ".db_table_name("surveys")." WHERE + ".db_table_name("questions").".gid=".db_table_name("groups").".gid AND + ".db_table_name("questions").".language = '{$language}' AND ".db_table_name("groups").".language = '{$language}' AND + ".db_table_name("questions").".sid=".db_table_name("surveys").".sid AND ".db_table_name("questions").".sid='$surveyid'"; + $fnresult = db_execute_assoc($fnquery); + $fncount = $fnresult->RecordCount(); + //$dataentryoutput .= "$fnquery

      \n"; + $fnrows = array(); //Create an empty array in case FetchRow does not return any rows + while ($fnrow = $fnresult->FetchRow()) + { + $fnrows[] = $fnrow; + $private=$fnrow['private']; + $datestamp=$fnrow['datestamp']; + $ipaddr=$fnrow['ipaddr']; + } // Get table output into array + // Perform a case insensitive natural sort on group name then question title of a multidimensional array + usort($fnrows, 'CompareGroupThenTitle'); + // $fnames = (Field Name in Survey Table, Short Title of Question, Question Type, Field Name, Question Code, Predetermined Answers if exist) + $fnames[] = array("id", "id", "id", "id", "id", "id", "id", ""); + $fnames[] = array ("submitdate", $clang->gT("Completed"), $clang->gT("Completed"), "completed", "completed", "", ""); + + if ($private == "N") //show token info if survey not private + { + $fnames[] = array ("token", $clang->gT("Token ID"), $clang->gT("Token"), "token", "TID", "", ""); + } + if ($datestamp == "Y") + { + $fnames[] = array ("datestamp", $clang->gT("Date Stamp"), $clang->gT("Date Stamp"), "datestamp", "datestamp", "", ""); + } + if ($ipaddr == "Y") + { + $fnames[] = array ("ipaddr", $clang->gT("IP Address"), $clang->gT("IP Address"), "ipaddr", "ipaddr", "", ""); + } + $fcount=0; + foreach ($fnrows as $fnrow) + { + $fcount++; + $field = "{$fnrow['sid']}X{$fnrow['gid']}X{$fnrow['qid']}"; + $ftitle = "Grp{$fnrow['gid']}Qst{$fnrow['title']}"; + $fquestion = $fnrow['question']; + if ($fnrow['type'] == "M" || $fnrow['type'] == "A" || $fnrow['type'] == "B" || $fnrow['type'] == "C" || + $fnrow['type'] == "E" || $fnrow['type'] == "F" || $fnrow['type'] == "H" || $fnrow['type'] == "P" || + $fnrow['type'] == "Q" || $fnrow['type'] == "^" || $fnrow['type'] == "J" || $fnrow['type'] == "K") + { + $fnrquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid={$fnrow['qid']} and language='{$language}' ORDER BY sortorder, answer"; + $fnrresult = db_execute_assoc($fnrquery); + while ($fnrrow = $fnrresult->FetchRow()) + { + $fnames[] = array("$field{$fnrrow['code']}", "$ftitle ({$fnrrow['code']})", "{$fnrow['question']}", "{$fnrow['type']}", "$field", "{$fnrrow['code']}", "{$fnrrow['answer']}", "{$fnrow['qid']}", "{$fnrow['lid']}"); + if ($fnrow['type'] == "P") + { + $fnames[] = array("$field{$fnrrow['code']}"."comment", "$ftitle"."comment", "{$fnrow['question']}(comment)", "{$fnrow['type']}", "$field", "{$fnrrow['code']}", "{$fnrrow['answer']}", "{$fnrow['qid']}", "{$fnrow['lid']}"); + } + } + if ($fnrow['other'] == "Y") + { + $fnames[] = array("$field"."other", "$ftitle"."other", "{$fnrow['question']}(other)", "{$fnrow['type']}", "$field", "{$fnrrow['code']}", "{$fnrrow['answer']}", "{$fnrow['qid']}", "{$fnrow['lid']}"); + if ($fnrow['type'] == "P") + { + $fnames[] = array("$field"."othercomment", "$ftitle"."othercomment", "{$fnrow['question']}(other comment)", "{$fnrow['type']}", "$field", "{$fnrrow['code']}", "{$fnrrow['answer']}", "{$fnrow['qid']}", "{$fnrow['lid']}"); + } + } + + } + elseif ($fnrow['type'] == ":" || $fnrow['type'] == ";") + { + $fnrquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid={$fnrow['qid']} and language='{$language}' ORDER BY sortorder, answer"; + $fnrresult = db_execute_assoc($fnrquery); + $fnr2query = "SELECT * + FROM ".db_table_name('labels')." + WHERE lid={$fnrow['lid']} + AND language = '{$language}' + ORDER BY sortorder, title"; + $fnr2result = db_execute_assoc($fnr2query); + while( $fnr2row = $fnr2result->FetchRow()) + { + $lset[]=$fnr2row; + } + while ($fnrrow = $fnrresult->FetchRow()) + { + foreach($lset as $ls) + { + $fnames[] = array("$field{$fnrrow['code']}_{$ls['code']}", "$ftitle ({$fnrrow['code']})", "{$fnrow['question']}", "{$fnrow['type']}", "$field", "{$fnrrow['code']}", "{$fnrrow['answer']}
      {$ls['title']}", "{$fnrow['qid']}", "{$fnrow['lid']}"); + } + } + unset($lset); + } + elseif ($fnrow['type'] == "R") + { + $fnrquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid={$fnrow['qid']} and language='{$language}' ORDER BY sortorder, answer"; + $fnrresult = $connect->Execute($fnrquery); + $fnrcount = $fnrresult->RecordCount(); + for ($j=1; $j<=$fnrcount; $j++) + { + $fnames[] = array("$field$j", "$ftitle ($j)", "{$fnrow['question']}", "{$fnrow['type']}", "$field", "$j", "$j", "{$fnrow['qid']}", "{$fnrow['lid']}"); + } + } + elseif ($fnrow['type'] == "1") + { + $fnrquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid={$fnrow['qid']} and language='{$language}' ORDER BY sortorder, answer"; + $fnrresult = $connect->Execute($fnrquery); + while ($fnrrow = $fnrresult->FetchRow()) + { + $fnames[] = array("$field{$fnrrow['code']}#0", "$ftitle ({$fnrrow['code']})", "{$fnrow['question']}", "{$fnrow['type']}", "$field", "{$fnrrow['code']}", "{$fnrrow['answer']} (1)", "{$fnrow['qid']}", "{$fnrow['lid']}"); + $fnames[] = array("$field{$fnrrow['code']}#1", "$ftitle ({$fnrrow['code']})", "{$fnrow['question']}", "{$fnrow['type']}", "$field", "{$fnrrow['code']}", "{$fnrrow['answer']} (2)", "{$fnrow['qid']}", "{$fnrow['lid1']}"); + } + } + elseif ($fnrow['type'] == "O") + { + if (!isset($fnrrow)) {$fnrrow=array("code"=>"", "answer"=>"");} + $fnames[] = array("$field", "$ftitle", "{$fnrow['question']}", "{$fnrow['type']}", "$field", "{$fnrrow['code']}", "{$fnrrow['answer']}", "{$fnrow['qid']}", "{$fnrow['lid']}"); + $field2 = $field."comment"; + $ftitle2 = $ftitle."[Comment]"; + $longtitle = "{$fnrow['question']}
      (Comment)"; + $fnames[] = array("$field2", "$ftitle", "{$fnrow['question']}", "{$fnrow['type']}", "$field", "{$fnrrow['code']}", "{$fnrrow['answer']}", "{$fnrow['qid']}", "{$fnrow['lid']}"); + } + else + { + if (!isset($fnrrow)) {$fnrrow=array("code"=>"", "answer"=>"");} + $fnames[] = array("$field", "$ftitle", "{$fnrow['question']}", "{$fnrow['type']}", "$field", "{$fnrrow['code']}", "{$fnrrow['answer']}", "{$fnrow['qid']}", "{$fnrow['lid']}"); + if (($fnrow['type'] == "L" || $fnrow['type'] == "!" || $fnrow['type'] == "Z" || $fnrow['type'] == "W") && $fnrow['other'] =="Y") + { + $fnames[] = array("$field"."other", "$ftitle"."other", "{$fnrow['question']}(other)", "{$fnrow['type']}", "$field", "{$fnrrow['code']}", "{$fnrrow['answer']}", "{$fnrow['qid']}", "{$fnrow['lid']}"); + } + } + } + $nfncount = count($fnames)-1; + + //SHOW INDIVIDUAL RECORD + + if ($subaction == "edit") + { + $idquery = "SELECT * FROM $surveytable WHERE id=$id"; + $idresult = db_execute_assoc($idquery) or safe_die ("Couldn't get individual record
      $idquery
      ".$connect->ErrorMsg()); + while ($idrow = $idresult->FetchRow()) + { + $results[]=$idrow; + } + } + elseif ($subaction == "editsaved") + { + if (isset($_GET['public']) && $_GET['public']=="true") + { + $password=md5($_GET['accesscode']); + } + else + { + $password=$_GET['accesscode']; + } + $svquery = "SELECT * FROM ".db_table_name("saved_control")." + WHERE sid=$surveyid + AND identifier='".$_GET['identifier']."' + AND access_code='".$password."'"; + $svresult=db_execute_assoc($svquery) or safe_die("Error getting save
      $svquery
      ".$connect->ErrorMsg()); + while($svrow=$svresult->FetchRow()) + { + $saver['email']=$svrow['email']; + $saver['scid']=$svrow['scid']; + $saver['ip']=$svrow['ip']; + } + $svquery = "SELECT * FROM ".db_table_name("saved_control")." WHERE scid=".$saver['scid']; + $svresult=db_execute_assoc($svquery) or safe_die("Error getting saved info
      $svquery
      ".$connect->ErrorMsg()); + while($svrow=$svresult->FetchRow()) + { + $responses[$svrow['fieldname']]=$svrow['value']; + } // while + $fieldmap = createFieldMap($surveyid); + foreach($fieldmap as $fm) + { + if (isset($responses[$fm['fieldname']])) + { + $results1[$fm['fieldname']]=$responses[$fm['fieldname']]; + } + else + { + $results1[$fm['fieldname']]=""; + } + } + $results1['id']=""; + $results1['datestamp']=date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust); + $results1['ipaddr']=$saver['ip']; + $results[]=$results1; + } + // $dataentryoutput .= "
      ";print_r($results);$dataentryoutput .= "
      "; + + $dataentryoutput .= "
      \n" + ."\n" + ."\t\n" + ."\t\n" + ."\t\n"; + + foreach ($results as $idrow) + { + //$dataentryoutput .= "
      "; print_r($idrow);$dataentryoutput .= "
      "; + for ($i=0; $i<$nfncount+1; $i++) + { + //$dataentryoutput .= "
      "; print_r($fnames[$i]);$dataentryoutput .= "
      "; + $answer = $idrow[$fnames[$i][0]]; + $question=$fnames[$i][2]; + $dataentryoutput .= "\t\n" + ."\t\t\n" + ."\t\t\n"; - $deletesurveyoutput .= "\t\t\n"; - $deletesurveyoutput .= "\t\n"; - $deletesurveyoutput .= "\t\n"; - $deletesurveyoutput .= "\t\t\n"; - $deletesurveyoutput .= "\t\n"; - $deletesurveyoutput .= "\n"; -} - -else //delete the survey -{ - $tablelist = $connect->MetaTables(); - $dict = NewDataDictionary($connect); - - if (in_array("{$dbprefix}survey_$surveyid", $tablelist)) //delete the survey_$surveyid table - { - $dsquery = $dict->DropTableSQL("{$dbprefix}survey_$surveyid"); - //$dict->ExecuteSQLArray($sqlarray); - $dsresult = $dict->ExecuteSQLArray($dsquery) or safe_die ("Couldn't \"$dsquery\" because
      ".$connect->ErrorMsg()); - } - - if (in_array("{$dbprefix}tokens_$surveyid", $tablelist)) //delete the tokens_$surveyid table - { - $dsquery = $dict->DropTableSQL("{$dbprefix}tokens_$surveyid"); - $dsresult = $dict->ExecuteSQLArray($dsquery) or safe_die ("Couldn't \"$dsquery\" because
      ".$connect->ErrorMsg()); - } - - $dsquery = "SELECT qid FROM {$dbprefix}questions WHERE sid=$surveyid"; - $dsresult = db_execute_assoc($dsquery) or safe_die ("Couldn't find matching survey to delete
      $dsquery
      ".$connect->ErrorMsg()); - while ($dsrow = $dsresult->FetchRow()) - { - $asdel = "DELETE FROM {$dbprefix}answers WHERE qid={$dsrow['qid']}"; - $asres = $connect->Execute($asdel); - $cddel = "DELETE FROM {$dbprefix}conditions WHERE qid={$dsrow['qid']}"; - $cdres = $connect->Execute($cddel) or safe_die ("Delete conditions failed
      $cddel
      ".$connect->ErrorMsg()); - $qadel = "DELETE FROM {$dbprefix}question_attributes WHERE qid={$dsrow['qid']}"; - $qares = $connect->Execute($qadel); - } - - $qdel = "DELETE FROM {$dbprefix}questions WHERE sid=$surveyid"; - $qres = $connect->Execute($qdel); - - $scdel = "DELETE FROM {$dbprefix}assessments WHERE sid=$surveyid"; - $scres = $connect->Execute($scdel); - - $gdel = "DELETE FROM {$dbprefix}groups WHERE sid=$surveyid"; - $gres = $connect->Execute($gdel); - - $slsdel = "DELETE FROM {$dbprefix}surveys_languagesettings WHERE surveyls_survey_id=$surveyid"; - $slsres = $connect->Execute($slsdel); - - $srdel = "DELETE FROM {$dbprefix}surveys_rights WHERE sid=$surveyid"; - $srres = $connect->Execute($srdel); - - $srdel = "DELETE FROM {$dbprefix}saved_control WHERE sid=$surveyid"; - $srres = $connect->Execute($srdel); - - $sdel = "DELETE FROM {$dbprefix}surveys WHERE sid=$surveyid"; - $sres = $connect->Execute($sdel); - - - $deletesurveyoutput .= "\t\n"; - $deletesurveyoutput .= "\t\t\n"; - $deletesurveyoutput .= "\t\n"; - $surveyid=false; - -} -$deletesurveyoutput .= "
      " + .$clang->gT("Data Entry")."
      " + .sprintf($clang->gT("Editing response (ID %s)"),$id)."
      " + ."\n"; + $dataentryoutput .= "\t".strip_javascript($question)."\n"; + $dataentryoutput .= "\t\t\n"; + //$dataentryoutput .= "\t-={$fnames[$i][3]}=-"; //Debugging info + switch ($fnames[$i][3]) + { + case "completed": + // First compute the submitdate + if ($private == "Y" && $datestamp == "N") + { + // In case of anonymous answers survey with no datestamp + // then the the answer submutdate gets a conventional timestamp + // 1st Jan 1980 + $mysubmitdate = date("Y-m-d H:i:s",mktime(0,0,0,1,1,1980)); + } + else + { + $mysubmitdate = date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust); + } + $completedate= empty($idrow[$fnames[$i][0]]) ? $mysubmitdate : $idrow[$fnames[$i][0]]; + + $dataentryoutput .= " \n"; + break; + case "X": //Boilerplate question + $dataentryoutput .= ""; + break; + case "Q": + case "K": + $dataentryoutput .= "\t{$fnames[$i][6]} \n"; + break; + case "id": + $dataentryoutput .= "\t {$idrow[$fnames[$i][0]]} ".$clang->gT("Cannot be modified")."\n"; + break; + case "5": //5 POINT CHOICE radio-buttons + for ($x=1; $x<=5; $x++) + { + $dataentryoutput .= "\tconvert($dateformatdetails['phpdate']); + $dataentryoutput .= "\t\n"; + break; + case "G": //GENDER drop-down list + $dataentryoutput .= "\t\n"; + break; + case "W": + case "Z": + if (substr($fnames[$i][0], -5) == "other") + { + $dataentryoutput .= "\t\n"; + } + else + { + $lquery = "SELECT * FROM ".db_table_name("labels") + ." WHERE lid={$fnames[$i][8]} AND ".db_table_name("labels").".language = '{$language}' ORDER BY sortorder, code"; + $lresult = db_execute_assoc($lquery); + $dataentryoutput .= "\t\n"; + } + break; + case "L": //LIST drop-down + case "!": //List (Radio) + $qidattributes=getQuestionAttributes($fnames[$i][7]); + if ($optCategorySeparator = arraySearchByKey('category_separator', $qidattributes, 'attribute', 1)) + { + $optCategorySeparator = $optCategorySeparator['value']; + } + else + { + unset($optCategorySeparator); + } + + if (substr($fnames[$i][0], -5) == "other") + { + $dataentryoutput .= "\t\n"; + } + else + { + $lquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid={$fnames[$i][7]} AND ".db_table_name("answers").".language = '{$language}' ORDER BY sortorder, answer"; + $lresult = db_execute_assoc($lquery); + $dataentryoutput .= "\t\n"; + } + break; + case "O": //LIST WITH COMMENT drop-down/radio-button list + textarea + $lquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid={$fnames[$i][7]} AND ".db_table_name("answers").".language = '{$language}' ORDER BY sortorder, answer"; + $lresult = db_execute_assoc($lquery); + $dataentryoutput .= "\t\n"; + break; + case "R": //RANKING TYPE QUESTION + $l=$i; + $thisqid=$fnames[$l][7]; + $myfname=substr($fnames[$i][0], 0, -1); + while (isset($fnames[$i][3]) && $fnames[$i][3] == "R") + { + //Let's get all the existing values into an array + if ($idrow[$fnames[$i][0]]) + { + $currentvalues[] = $idrow[$fnames[$i][0]]; + } + $i++; + } + $ansquery = "SELECT * FROM ".db_table_name("answers")." WHERE ".db_table_name("answers").".language = '{$language}' AND qid=$thisqid ORDER BY sortorder, answer"; + $ansresult = db_execute_assoc($ansquery); + $anscount = $ansresult->RecordCount(); + $dataentryoutput .= "\t\n"; + while ($ansrow = $ansresult->FetchRow()) //Now we're getting the codes and answers + { + $answers[] = array($ansrow['code'], $ansrow['answer']); + } + //now find out how many existing values there are + + $chosen[]=""; //create array + if (!isset($ranklist)) {$ranklist="";} + + if (isset($currentvalues)) + { + $existing = count($currentvalues); + } + else {$existing=0;} + for ($j=1; $j<=$anscount; $j++) //go through each ranking and check for matching answer + { + $k=$j-1; + if (isset($currentvalues) && isset($currentvalues[$k]) && $currentvalues[$k]) + { + foreach ($answers as $ans) + { + if ($ans[0] == $currentvalues[$k]) + { + $thiscode=$ans[0]; + $thistext=$ans[1]; + } + } + } + $ranklist .= "\t\t$j: \n" + . "\t\t\n" + . "\t\t".$clang->gT("Remove this item")."
      \n\n"; + } + + if (!isset($choicelist)) {$choicelist="";} + $choicelist .= "\t\t\n"; + $dataentryoutput .= "\t\n" + ."\t\t\n" + ."\t\t\t\n" + ."\t\t\t\n" + ."\t\t\n" + ."\t
      \n" + ."\t\t" + .$clang->gT("Your Choices").":
      \n" + .$choicelist + ."\t\t\t
      \n" + ."\t\t" + .$clang->gT("Your Ranking").":
      \n" + .$ranklist + ."\t\t\t
      \n" + ."\t\n" + ."\t\n"; + $choicelist=""; + $ranklist=""; + unset($answers); + $i--; + break; + + case "M": //MULTIPLE OPTIONS checkbox + $qidattributes=getQuestionAttributes($fnames[$i][7]); + if ($displaycols=arraySearchByKey("display_columns", $qidattributes, "attribute", 1)) + { + $dcols=$displaycols['value']; + } + else + { + $dcols=0; + } + +// while ($fnames[$i][3] == "M" && $question != "" && $question == $fnames[$i][2]) + while ($fnames[$i][3] == "M" && $question == $fnames[$i][2]) + { + $fieldn = substr($fnames[$i][0], 0, strlen($fnames[$i][0])); + //$dataentryoutput .= substr($fnames[$i][0], strlen($fnames[$i][0])-5, 5)."
      \n"; + if (substr($fnames[$i][0], -5) == "other") + { + $dataentryoutput .= "\t\n"; + } + else + { + $dataentryoutput .= "\tgT("Please choose")."..\n"; + + foreach ($slangs as $lang) + { + $dataentryoutput.="

      \n"; - $deletesurveyoutput .= "\t\t\t".$clang->gT("Warning")."
      \n"; - $deletesurveyoutput .= "\t\t\t".$clang->gT("You are about to delete this survey")." ($surveyid)

      \n"; - $deletesurveyoutput .= "\t\t\t".$clang->gT("This process will delete this survey, and all related groups, questions answers and conditions.")."

      \n"; - $deletesurveyoutput .= "\t\t\t".$clang->gT("We recommend that before you delete this survey you export the entire survey from the main administration screen.")."\n"; - - if (in_array("{$dbprefix}survey_$surveyid", $tablelist)) - { - $deletesurveyoutput .= "\t\t\t

      \n".$clang->gT("This survey is active and a responses table exists. If you delete this survey, these responses will be deleted. We recommend that you export the responses before deleting this survey.")."

      \n"; - } - - if (in_array("{$dbprefix}tokens_$surveyid", $tablelist)) - { - $deletesurveyoutput .= "\t\t\t".$clang->gT("This survey has an associated tokens table. If you delete this survey this tokens table will be deleted. We recommend that you export or backup these tokens before deleting this survey.")."

      \n"; - } - - $deletesurveyoutput .= "\t\t

      \n"; - $deletesurveyoutput .= "\t\t\t
      \n"; -// $deletesurveyoutput .= "\t\t\t\n"; - $deletesurveyoutput .= "\t\t\t\n"; - $deletesurveyoutput .= "\t\t

      \n"; - $deletesurveyoutput .= "\t\t\t".$clang->gT("This survey has been deleted.")."

      \n"; - $deletesurveyoutput .= "\t\t\t\n"; - $deletesurveyoutput .= "\t\t

       \n"; - - - -?> +\n"; +$deletesurveyoutput .= "\n"; +$deletesurveyoutput .= "\t\n"; + +if (!isset($surveyid) || !$surveyid) +{ + $deletesurveyoutput .= "\t
      ".$clang->gT("Delete Survey")."
      \n"; + $deletesurveyoutput .= "
      ".$clang->gT("Error")."
      \n"; + $deletesurveyoutput .= $clang->gT("You have not selected a survey to delete")."

      \n"; + $deletesurveyoutput .= "\n"; + $deletesurveyoutput .= "
      \n"; + $deletesurveyoutput .= "\n"; + return; +} + +if (!isset($deleteok) || !$deleteok) +{ + $tablelist = $connect->MetaTables(); + + $deletesurveyoutput .= "\t\n"; + $deletesurveyoutput .= "\t\t
      \n"; + $deletesurveyoutput .= "\t\t\t".$clang->gT("Warning")."
      \n"; + $deletesurveyoutput .= "\t\t\t".$clang->gT("You are about to delete this survey")." ($surveyid)

      \n"; + $deletesurveyoutput .= "\t\t\t".$clang->gT("This process will delete this survey, and all related groups, questions answers and conditions.")."

      \n"; + $deletesurveyoutput .= "\t\t\t".$clang->gT("We recommend that before you delete this survey you export the entire survey from the main administration screen.")."\n"; + + if (in_array("{$dbprefix}survey_$surveyid", $tablelist)) + { + $deletesurveyoutput .= "\t\t\t

      \n".$clang->gT("This survey is active and a responses table exists. If you delete this survey, these responses will be deleted. We recommend that you export the responses before deleting this survey.")."

      \n"; + } + + if (in_array("{$dbprefix}tokens_$surveyid", $tablelist)) + { + $deletesurveyoutput .= "\t\t\t".$clang->gT("This survey has an associated tokens table. If you delete this survey this tokens table will be deleted. We recommend that you export or backup these tokens before deleting this survey.")."

      \n"; + } + + $deletesurveyoutput .= "\t\t\n"; + $deletesurveyoutput .= "\t\n"; + $deletesurveyoutput .= "\t\n"; + $deletesurveyoutput .= "\t\t
      \n"; + $deletesurveyoutput .= "\t\t\t
      \n"; +// $deletesurveyoutput .= "\t\t\t\n"; + $deletesurveyoutput .= "\t\t\t\n"; + $deletesurveyoutput .= "\t\t\n"; + $deletesurveyoutput .= "\t\n"; + $deletesurveyoutput .= "\n"; +} + +else //delete the survey +{ + $tablelist = $connect->MetaTables(); + $dict = NewDataDictionary($connect); + + if (in_array("{$dbprefix}survey_$surveyid", $tablelist)) //delete the survey_$surveyid table + { + $dsquery = $dict->DropTableSQL("{$dbprefix}survey_$surveyid"); + //$dict->ExecuteSQLArray($sqlarray); + $dsresult = $dict->ExecuteSQLArray($dsquery) or safe_die ("Couldn't \"$dsquery\" because
      ".$connect->ErrorMsg()); + } + + if (in_array("{$dbprefix}tokens_$surveyid", $tablelist)) //delete the tokens_$surveyid table + { + $dsquery = $dict->DropTableSQL("{$dbprefix}tokens_$surveyid"); + $dsresult = $dict->ExecuteSQLArray($dsquery) or safe_die ("Couldn't \"$dsquery\" because
      ".$connect->ErrorMsg()); + } + + $dsquery = "SELECT qid FROM {$dbprefix}questions WHERE sid=$surveyid"; + $dsresult = db_execute_assoc($dsquery) or safe_die ("Couldn't find matching survey to delete
      $dsquery
      ".$connect->ErrorMsg()); + while ($dsrow = $dsresult->FetchRow()) + { + $asdel = "DELETE FROM {$dbprefix}answers WHERE qid={$dsrow['qid']}"; + $asres = $connect->Execute($asdel); + $cddel = "DELETE FROM {$dbprefix}conditions WHERE qid={$dsrow['qid']}"; + $cdres = $connect->Execute($cddel) or safe_die ("Delete conditions failed
      $cddel
      ".$connect->ErrorMsg()); + $qadel = "DELETE FROM {$dbprefix}question_attributes WHERE qid={$dsrow['qid']}"; + $qares = $connect->Execute($qadel); + } + + $qdel = "DELETE FROM {$dbprefix}questions WHERE sid=$surveyid"; + $qres = $connect->Execute($qdel); + + $scdel = "DELETE FROM {$dbprefix}assessments WHERE sid=$surveyid"; + $scres = $connect->Execute($scdel); + + $gdel = "DELETE FROM {$dbprefix}groups WHERE sid=$surveyid"; + $gres = $connect->Execute($gdel); + + $slsdel = "DELETE FROM {$dbprefix}surveys_languagesettings WHERE surveyls_survey_id=$surveyid"; + $slsres = $connect->Execute($slsdel); + + $srdel = "DELETE FROM {$dbprefix}surveys_rights WHERE sid=$surveyid"; + $srres = $connect->Execute($srdel); + + $srdel = "DELETE FROM {$dbprefix}saved_control WHERE sid=$surveyid"; + $srres = $connect->Execute($srdel); + + $sdel = "DELETE FROM {$dbprefix}surveys WHERE sid=$surveyid"; + $sres = $connect->Execute($sdel); + + $sdel = "DELETE {$dbprefix}quota_languagesettings FROM {$dbprefix}quota_languagesettings, {$dbprefix}quota WHERE {$dbprefix}quota_languagesettings.quotals_quota_id={$dbprefix}quota.id and sid=$surveyid"; + $sres = $connect->Execute($sdel); + + $sdel = "DELETE FROM {$dbprefix}quota WHERE sid=$surveyid"; + $sres = $connect->Execute($sdel); + + $sdel = "DELETE FROM {$dbprefix}quota_members WHERE sid=$surveyid;"; + $sres = $connect->Execute($sdel); + + $deletesurveyoutput .= "\t\n"; + $deletesurveyoutput .= "\t\t
      \n"; + $deletesurveyoutput .= "\t\t\t".$clang->gT("This survey has been deleted.")."

      \n"; + $deletesurveyoutput .= "\t\t\t\n"; + $deletesurveyoutput .= "\t\t
      \n"; + $deletesurveyoutput .= "\t\n"; + $surveyid=false; + +} +$deletesurveyoutput .= "
       \n"; + + + +?> diff --git a/include/limesurvey/admin/dumpdb.php b/include/limesurvey/admin/dumpdb.php index 976818f5..127be6f5 100644 --- a/include/limesurvey/admin/dumpdb.php +++ b/include/limesurvey/admin/dumpdb.php @@ -1,129 +1,137 @@ -MetaTables(); - - $export=""; - $export .="#------------------------------------------"."\n"; - $export .="# LimeSurvey Database Dump of `$databasename`"."\n"; - if ($allowexportalldb==0) { - $export .="# Only prefixed tables with: ". $dbprefix ."\n"; - } - $export .="# Date of Dump: ". date("d-M-Y") ."\n"; - $export .="#------------------------------------------"."\n\n\n"; - - foreach($tables as $table) { - if ($allowexportalldb==0) { - if ($dbprefix==substr($table, 0, strlen($dbprefix))) { - $export .= defdump($table); - $export .= datadump($table); - } - } - else { - $export .= defdump($table); - $export .= datadump($table); - } - } - - $file_name = "LimeSurvey_{$databasename}_dump_".date_shift(date("Y-m-d H:i:s"), "Y-m-d", $timeadjust).".sql"; - Header("Content-type: application/octet-stream"); - Header("Content-Disposition: attachment; filename=$file_name"); - Header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); - echo $export; - exit; -} - else - { - $dumpdboutput= "
      \n" - ."\n" - ."\t\n" - ."\t" - ."
      ".$clang->gT("Export database")."
      ".$clang->gT("The database export is only available for MySQL databases. For other database types please use the according backup mechanism to create a database dump.")."

      "; - return; - } - - - function defdump($tablename) - { - global $connect; - $def = ""; - $def .="#------------------------------------------"."\n"; - $def .="# Table definition for $tablename"."\n"; - $def .="#------------------------------------------"."\n"; - $def .= "DROP TABLE IF EXISTS $tablename;"."\n"."\n"; - $def .= "CREATE TABLE $tablename ("."\n"; - $result = db_execute_assoc("SHOW COLUMNS FROM $tablename") or die("Table $tablename not existing in database"); - while($row = $result->FetchRow()) - { - $def .= " `$row[Field]` $row[Type]"; - if (!is_null($row["Default"])) $def .= " DEFAULT '$row[Default]'"; - if ($row["Null"] != "YES") $def .= " NOT NULL"; - if ($row["Extra"] != "") $def .= " $row[Extra]"; - $def .= ",\n"; - } - $def = ereg_replace(",\n$","", $def); - - $result = db_execute_assoc("SHOW KEYS FROM $tablename"); - while($row = $result->FetchRow()) - { - $kname=$row["Key_name"]; - if(($kname != "PRIMARY") && ($row["Non_unique"] == 0)) $kname="UNIQUE|$kname"; - if(!isset($index[$kname])) $index[$kname] = array(); - $index[$kname][] = $row["Column_name"]; - } - - while(list($x, $columns) = @each($index)) - { - $def .= ",\n"; - if($x == "PRIMARY") $def .= " PRIMARY KEY (" . implode($columns, ", ") . ")"; - else if (substr($x,0,6) == "UNIQUE") $def .= " UNIQUE ".substr($x,7)." (" . implode($columns, ", ") . ")"; - else $def .= " KEY $x (" . implode($columns, ", ") . ")"; - } - $def .= "\n);\n\n\n"; - return (stripslashes($def)); - } - - - function datadump ($table) { - - global $connect; - - $result = "#------------------------------------------"."\n"; - $result .="# Table data for $table"."\n"; - $result .="#------------------------------------------"."\n"; - - $query = db_execute_num("select * from $table"); - $num_fields = $query->FieldCount(); - $numrow = $query->RecordCount(); - - while($row=$query->FetchRow()){ - @set_time_limit(5); - $result .= "INSERT INTO ".$table." VALUES("; - for($j=0; $j<$num_fields; $j++) { - $row[$j] = addslashes($row[$j]); - $row[$j] = ereg_replace("\n","\\n",$row[$j]); - if (isset($row[$j])) $result .= "\"$row[$j]\"" ; else $result .= "\"\""; - if ($j<($num_fields-1)) $result .= ","; - } - $result .= ");\n"; - } // while - return $result . "\n\n\n"; - } - -?> +MetaTables(); + + $export=""; + $export .="#------------------------------------------"."\n"; + $export .="# LimeSurvey Database Dump of `$databasename`"."\n"; + if ($allowexportalldb==0) { + $export .="# Only prefixed tables with: ". $dbprefix ."\n"; + } + $export .="# Date of Dump: ". date("d-M-Y") ."\n"; + $export .="#------------------------------------------"."\n\n\n"; + + foreach($tables as $table) { + if ($allowexportalldb==0) { + if ($dbprefix==substr($table, 0, strlen($dbprefix))) { + $export .= defdump($table); + $export .= datadump($table); + } + } + else { + $export .= defdump($table); + $export .= datadump($table); + } + } + + $file_name = "LimeSurvey_{$databasename}_dump_".date_shift(date("Y-m-d H:i:s"), "Y-m-d", $timeadjust).".sql"; + Header("Content-type: application/octet-stream"); + Header("Content-Disposition: attachment; filename=$file_name"); + Header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); + echo $export; + exit; +} + else + { + $dumpdboutput= "
      \n" + ."\n" + ."\t\n" + ."\t" + ."
      ".$clang->gT("Export database")."
      ".$clang->gT("The database export is only available for MySQL databases. For other database types please use the according backup mechanism to create a database dump.")."

      "; + return; + } + + + function defdump($tablename) + { + global $connect; + $def = ""; + $def .="#------------------------------------------"."\n"; + $def .="# Table definition for $tablename"."\n"; + $def .="#------------------------------------------"."\n"; + $def .= "DROP TABLE IF EXISTS $tablename;"."\n"."\n"; + $def .= "CREATE TABLE $tablename ("."\n"; + $result = db_execute_assoc("SHOW COLUMNS FROM $tablename") or die("Table $tablename not existing in database"); + while($row = $result->FetchRow()) + { + $def .= " `$row[Field]` $row[Type]"; + if (!is_null($row["Default"])) $def .= " DEFAULT '$row[Default]'"; + if ($row["Null"] != "YES") $def .= " NOT NULL"; + if ($row["Extra"] != "") $def .= " $row[Extra]"; + $def .= ",\n"; + } + $def = preg_replace("#,\n$#","", $def); + + $result = db_execute_assoc("SHOW KEYS FROM $tablename"); + while($row = $result->FetchRow()) + { + $kname=$row["Key_name"]; + if(($kname != "PRIMARY") && ($row["Non_unique"] == 0)) $kname="UNIQUE|$kname"; + if(!isset($index[$kname])) $index[$kname] = array(); + $index[$kname][] = $row["Column_name"]; + } + + while(list($x, $columns) = @each($index)) + { + $def .= ",\n"; + if($x == "PRIMARY") $def .= " PRIMARY KEY (" . implode($columns, ", ") . ")"; + else if (substr($x,0,6) == "UNIQUE") $def .= " UNIQUE ".substr($x,7)." (" . implode($columns, ", ") . ")"; + else $def .= " KEY $x (" . implode($columns, ", ") . ")"; + } + $def .= "\n);\n\n\n"; + return (stripslashes($def)); + } + + + function datadump ($table) { + + global $connect; + + $result = "#------------------------------------------"."\n"; + $result .="# Table data for $table"."\n"; + $result .="#------------------------------------------"."\n"; + + $query = db_execute_num("select * from $table"); + $num_fields = $query->FieldCount(); + $numrow = $query->RecordCount(); + + while($row=$query->FetchRow()){ + @set_time_limit(5); + $result .= "INSERT INTO ".$table." VALUES("; + for($j=0; $j<$num_fields; $j++) { + if (isset($row[$j]) && !is_null($row[$j])) + { + $row[$j] = addslashes($row[$j]); + $row[$j] = preg_replace("#\n#","\\n",$row[$j]); + $result .= "\"$row[$j]\""; + } + else + { + $result .= "NULL"; + } + + if ($j<($num_fields-1)) $result .= ","; + } + $result .= ");\n"; + } // while + return $result . "\n\n\n"; + } + +?> diff --git a/include/limesurvey/admin/dumpgroup.php b/include/limesurvey/admin/dumpgroup.php index 81f03bb4..a569b709 100644 --- a/include/limesurvey/admin/dumpgroup.php +++ b/include/limesurvey/admin/dumpgroup.php @@ -1,95 +1,155 @@ -\n"; - echo "\n"; - echo "\t\n"; - echo "\t\n"; - echo "
      ".$clang->gT("Export Question")."
      $setfont\n"; - echo "$setfont
      ".$clang->gT("Error")."
      \n"._EQ_NOGID."
      \n"; - echo "
      \n"; - echo "\t
      \n"; - echo "\n"; - exit; -} - -$fn = "limesurvey_group_$gid.csv"; - -$dumphead = "# LimeSurvey Group Dump\n" - . "# DBVersion $dbversionnumber\n" - . "# This is a dumped group from the LimeSurvey Script\n" - . "# http://www.limesurvey.org/\n" - . "# Do not change this header!\n"; - - -header("Content-Type: application/download"); -header("Content-Disposition: attachment; filename=$fn"); -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: must-revalidate, post-check=0, pre-check=0"); -header("Pragma: cache"); - -//0: Groups Table -$gquery = "SELECT * FROM {$dbprefix}groups WHERE gid=$gid"; -$gdump = BuildCSVFromQuery($gquery); - -//1: Questions Table -$qquery = "SELECT * FROM {$dbprefix}questions WHERE gid=$gid"; -$qdump = BuildCSVFromQuery($qquery); - -//2: Answers table -$aquery = "SELECT DISTINCT {$dbprefix}answers.* FROM {$dbprefix}answers, {$dbprefix}questions WHERE ({$dbprefix}answers.qid={$dbprefix}questions.qid) AND ({$dbprefix}questions.gid=$gid)"; -$adump = BuildCSVFromQuery($aquery); - -//3: Conditions table - THIS CAN ONLY EXPORT CONDITIONS THAT RELATE TO THE SAME GROUP -$cquery = "SELECT DISTINCT {$dbprefix}conditions.* FROM {$dbprefix}conditions, {$dbprefix}questions, {$dbprefix}questions b WHERE ({$dbprefix}conditions.cqid={$dbprefix}questions.qid) AND ({$dbprefix}conditions.qid=b.qid) AND ({$dbprefix}questions.gid=$gid) AND (b.gid=$gid)"; -$cdump = BuildCSVFromQuery($cquery); - -//4: Labelsets Table -$lsquery = "SELECT DISTINCT {$dbprefix}labelsets.* FROM {$dbprefix}labelsets, {$dbprefix}questions WHERE ({$dbprefix}labelsets.lid={$dbprefix}questions.lid) AND (type in ('F', 'H', 'Z', 'W')) AND (gid=$gid)"; -$lsdump = BuildCSVFromQuery($lsquery); - -//5: Labels Table -$lquery = "SELECT {$dbprefix}labels.* FROM {$dbprefix}labels, {$dbprefix}questions WHERE ({$dbprefix}labels.lid={$dbprefix}questions.lid) AND (type in ('F', 'H', 'Z', 'W')) AND (gid=$gid)"; -$ldump = BuildCSVFromQuery($lquery); - -//8: Question Attributes -$query = "SELECT DISTINCT {$dbprefix}question_attributes.* FROM {$dbprefix}question_attributes, {$dbprefix}questions WHERE ({$dbprefix}question_attributes.qid={$dbprefix}questions.qid) AND ({$dbprefix}questions.gid=$gid)"; -$qadump = BuildCSVFromQuery($query); - -// HTTP/1.0 -echo $dumphead, $gdump, $qdump, $adump, $cdump, $lsdump, $ldump, $qadump; -exit; -?> +\n"; + echo "\n"; + echo "\t\n"; + echo "\t\n"; + echo "
      ".$clang->gT("Export Question")."
      $setfont\n"; + echo "$setfont
      ".$clang->gT("Error")."
      \n"._EQ_NOGID."
      \n"; + echo "
      \n"; + echo "\t
      \n"; + echo "\n"; + exit; +} + +$fn = "limesurvey_group_$gid.csv"; + +$dumphead = "# LimeSurvey Group Dump\n" + . "# DBVersion $dbversionnumber\n" + . "# This is a dumped group from the LimeSurvey Script\n" + . "# http://www.limesurvey.org/\n" + . "# Do not change this header!\n"; + + +header("Content-Type: application/download"); +header("Content-Disposition: attachment; filename=$fn"); +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: must-revalidate, post-check=0, pre-check=0"); +header("Pragma: cache"); + +//0: Groups Table +$gquery = "SELECT * + FROM {$dbprefix}groups + WHERE gid=$gid"; +$gdump = BuildCSVFromQuery($gquery); + +//1: Questions Table +$qquery = "SELECT * + FROM {$dbprefix}questions + WHERE gid=$gid"; +$qdump = BuildCSVFromQuery($qquery); + +//2: Answers table +$aquery = "SELECT DISTINCT {$dbprefix}answers.* + FROM {$dbprefix}answers, {$dbprefix}questions + WHERE ({$dbprefix}answers.qid={$dbprefix}questions.qid) + AND ({$dbprefix}questions.gid=$gid)"; +$adump = BuildCSVFromQuery($aquery); + +//3: Conditions table - THIS CAN ONLY EXPORT CONDITIONS THAT RELATE TO THE SAME GROUP +$cquery = "SELECT DISTINCT {$dbprefix}conditions.* + FROM {$dbprefix}conditions, {$dbprefix}questions, {$dbprefix}questions b + WHERE ({$dbprefix}conditions.cqid={$dbprefix}questions.qid) + AND ({$dbprefix}conditions.qid=b.qid) + AND ({$dbprefix}questions.gid=$gid) + AND (b.gid=$gid)"; +$cdump = BuildCSVFromQuery($cquery); + +//4: Labelsets Table +$lsquery = "SELECT DISTINCT {$dbprefix}labelsets.* + FROM {$dbprefix}labelsets, {$dbprefix}questions + WHERE ({$dbprefix}labelsets.lid={$dbprefix}questions.lid) + AND (type in ('F', 'W', 'H', 'Z', '1', ':', ';')) + AND (gid=$gid)"; +$lsdump = BuildCSVFromQuery($lsquery); + +//5: Labelsets1 Table +//This exists specifically to deal with dual-scale questions (or any future question that may have 2 labelsets) +$lsquery = "SELECT DISTINCT {$dbprefix}labelsets.* FROM {$dbprefix}labelsets, {$dbprefix}questions WHERE ({$dbprefix}labelsets.lid={$dbprefix}questions.lid1) AND (type in ('1')) AND (gid=$gid)"; +$ls1dump = BuildCSVFromQuery($lsquery); +$ls1=explode("\n", trim($ls1dump)); + +if(count($ls1)>3) { + //If there is actually some data here, then add just the data (not the headers) into + // $ls1dump - which will be outputted directly after $lsdump + $ls1dump=$ls1[4]; + $ls1dump .= "\n"; +} else { + //If there is no data then make it an empty string. + $ls1dump = ""; +} + +//4a: Labels Table +$lquery = "SELECT {$dbprefix}labels.* FROM {$dbprefix}labels, {$dbprefix}questions WHERE ({$dbprefix}labels.lid={$dbprefix}questions.lid) AND (type in ('F', 'H', 'Z', 'W', '1', ':', ';')) AND (gid=$gid)"; +$ldump = BuildCSVFromQuery($lquery); + +//5a: Labels1 Table +// See explanation for Labelsets1 Table!! These are the actual labels +$lquery = "SELECT {$dbprefix}labels.* FROM {$dbprefix}labels, {$dbprefix}questions WHERE ({$dbprefix}labels.lid={$dbprefix}questions.lid1) AND (type in ('1')) AND (gid=$gid)"; +$l1dump = BuildCSVFromQuery($lquery); +$ld1=explode("\n", trim($l1dump)); + +if(count($ld1)>3) { + //If there is actually some data here, then add just the data (not the headers) into + // $l1dump - which will be outputted directly after $ldump + $l1dump=array(); + foreach($ld1 as $key=>$ld) { + //Put every line, other than the first three into this string + if($key > 3) { + $l1dump[]=$ld; + } + } + $l1dump = implode("\n", $l1dump); + $l1dump .= "\n"; +} else { + //If there is no data then make it an empty string. + $l1dump = ""; +} + + + +//8: Question Attributes +$query = "SELECT DISTINCT {$dbprefix}question_attributes.* + FROM {$dbprefix}question_attributes, {$dbprefix}questions + WHERE ({$dbprefix}question_attributes.qid={$dbprefix}questions.qid) + AND ({$dbprefix}questions.gid=$gid)"; +$qadump = BuildCSVFromQuery($query); + +// HTTP/1.0 +echo $dumphead, $gdump, $qdump, $adump, $cdump, $lsdump, $ls1dump, $ldump, $l1dump, $qadump; +exit; +?> diff --git a/include/limesurvey/admin/dumplabel.php b/include/limesurvey/admin/dumplabel.php index 91a0c238..603b5a08 100644 --- a/include/limesurvey/admin/dumplabel.php +++ b/include/limesurvey/admin/dumplabel.php @@ -1,67 +1,67 @@ -\n"; - echo "\n"; - echo "\t\n"; - echo "\t\n"; - echo "
      ".$clang->gT("Export Label Set")."
      \n"; - echo "
      ".$clang->gT("Error")."
      \n".$clang->gT("No LID has been provided. Cannot dump label set.")."
      \n"; - echo "
      \n"; - echo "\t
      \n"; - echo "\n"; - exit; -} - -$dumphead = "# LimeSurvey Label Set Dump\n" -. "# DBVersion $dbversionnumber\n" -. "# This is a dumped label set from the LimeSurvey Script\n" -. "# http://www.limesurvey.org/\n" -. "# Do not change this header!\n"; - -//1: Questions Table -$qquery = "SELECT * FROM {$dbprefix}labelsets WHERE lid=$lid"; -$qdump = BuildCSVFromQuery($qquery); - -//2: Answers table -$aquery = "SELECT lid, code, title, sortorder, language FROM {$dbprefix}labels WHERE lid=$lid"; -$adump = BuildCSVFromQuery($aquery); - -$fn = "limesurvey_labelset_$lid.csv"; - - -header("Content-Type: application/download"); -header("Content-Disposition: attachment; filename=$fn"); -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"); -header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); -header("Pragma: cache"); // HTTP/1.0 - -echo $dumphead, $qdump, $adump; -exit; - -?> +\n"; + echo "\n"; + echo "\t\n"; + echo "\t\n"; + echo "
      ".$clang->gT("Export Label Set")."
      \n"; + echo "
      ".$clang->gT("Error")."
      \n".$clang->gT("No LID has been provided. Cannot dump label set.")."
      \n"; + echo "
      \n"; + echo "\t
      \n"; + echo "\n"; + exit; +} + +$dumphead = "# LimeSurvey Label Set Dump\n" +. "# DBVersion $dbversionnumber\n" +. "# This is a dumped label set from the LimeSurvey Script\n" +. "# http://www.limesurvey.org/\n" +. "# Do not change this header!\n"; + +//1: Questions Table +$qquery = "SELECT * FROM {$dbprefix}labelsets WHERE lid=$lid"; +$qdump = BuildCSVFromQuery($qquery); + +//2: Answers table +$aquery = "SELECT lid, code, title, sortorder, language, assessment_value FROM {$dbprefix}labels WHERE lid=$lid"; +$adump = BuildCSVFromQuery($aquery); + +$fn = "limesurvey_labelset_$lid.csv"; + + +header("Content-Type: application/download"); +header("Content-Disposition: attachment; filename=$fn"); +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"); +header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); +header("Pragma: cache"); // HTTP/1.0 + +echo $dumphead, $qdump, $adump; +exit; + +?> diff --git a/include/limesurvey/admin/dumpquestion.php b/include/limesurvey/admin/dumpquestion.php index 271ebcb3..5c1cb210 100644 --- a/include/limesurvey/admin/dumpquestion.php +++ b/include/limesurvey/admin/dumpquestion.php @@ -1,118 +1,172 @@ -\n"; - echo "\n"; - echo "\t\n"; - echo "\t\n"; - echo "
      ".$clang->gT("Export Question")."
      \n"; - echo "
      ".$clang->gT("Error")."
      \n".$clang->gT("No QID has been provided. Cannot dump question.")."
      \n"; - echo "
      \n"; - echo "\t
      \n"; - echo "\n"; - exit; -} - -$dumphead = "# LimeSurvey Question Dump\n" - . "# DBVersion $dbversionnumber\n" - . "# This is a dumped question from the LimeSurvey Script\n" - . "# http://www.limesurvey.org/\n" - . "# Do not change this header!\n"; - -function BuildOutput($Query) -{ - global $dbprefix, $connect; - $QueryResult = db_execute_assoc($Query) or safe_die ("ERROR: $QueryResult
      ".$connect->ErrorMsg()); - preg_match('/FROM (\w+)( |,)/i', $Query, $MatchResults); - $TableName = $MatchResults[1];; - if ($dbprefix) - { - $TableName = substr($TableName, strlen($dbprefix), strlen($TableName)); - } - $Output = "\n#\n# " . strtoupper($TableName) . " TABLE\n#\n"; - $HeaderDone = false; $ColumnNames = ""; - while ($Row = $QueryResult->FetchRow()) - { - - if (!$HeaderDone) - { - foreach ($Row as $Key=>$Value) - { - $ColumnNames .= CSVEscape($Key).","; //Add all the column names together - } - $ColumnNames = substr($ColumnNames, 0, -1); //strip off last comma space - $Output .= "$ColumnNames\n"; - $HeaderDone=true; - } - $ColumnValues = ""; - foreach ($Row as $Key=>$Value) - { - $ColumnValues .= CSVEscape(str_replace("\r\n", "\n", $Value)) . ","; - } - $ColumnValues = substr($ColumnValues, 0, -1); //strip off last comma space - $Output .= "$ColumnValues\n"; - } - return $Output; -} - - -//1: Questions Table -$qquery = "SELECT * FROM {$dbprefix}questions WHERE qid=$qid"; -$qdump = BuildCSVFromQuery($qquery); - -//2: Answers table -$aquery = "SELECT {$dbprefix}answers.* FROM {$dbprefix}answers WHERE {$dbprefix}answers.qid = $qid"; -$adump = BuildCSVFromQuery($aquery); - -//3: Labelsets Table -//$lsquery = "SELECT DISTINCT {$dbprefix}labelsets.* FROM {$dbprefix}labelsets, {$dbprefix}questions WHERE {$dbprefix}labelsets.lid={$dbprefix}questions.lid AND type='F' AND qid=$qid"; -$lsquery = "SELECT DISTINCT {$dbprefix}labelsets.* FROM {$dbprefix}labelsets, {$dbprefix}questions WHERE {$dbprefix}labelsets.lid={$dbprefix}questions.lid AND type in ('F', 'H', 'Z', 'W') AND qid=$qid"; -$lsdump = BuildCSVFromQuery($lsquery); - -//4: Labels Table -$lquery = "SELECT DISTINCT {$dbprefix}labels.* FROM {$dbprefix}labels, {$dbprefix}questions WHERE {$dbprefix}labels.lid={$dbprefix}questions.lid AND type in ('F', 'H', 'Z', 'W') AND qid=$qid"; -$ldump = BuildCSVFromQuery($lquery); - -//5: Question Attributes -$query = "SELECT {$dbprefix}question_attributes.* FROM {$dbprefix}question_attributes WHERE {$dbprefix}question_attributes.qid=$qid"; -$qadump = BuildCSVFromQuery($query); -$fn = "limesurvey_question_$qid.csv"; - -header("Content-Type: application/download"); -header("Content-Disposition: attachment; filename=$fn"); -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"); -header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); -header("Pragma: cache"); // HTTP/1.0 -echo $dumphead, $qdump, $adump, $lsdump, $ldump, $qadump; -exit; -?> +\n"; + echo "\n"; + echo "\t\n"; + echo "\t\n"; + echo "
      ".$clang->gT("Export Question")."
      \n"; + echo "
      ".$clang->gT("Error")."
      \n".$clang->gT("No QID has been provided. Cannot dump question.")."
      \n"; + echo "
      \n"; + echo "\t
      \n"; + echo "\n"; + exit; +} + +$dumphead = "# LimeSurvey Question Dump\n" + . "# DBVersion $dbversionnumber\n" + . "# This is a dumped question from the LimeSurvey Script\n" + . "# http://www.limesurvey.org/\n" + . "# Do not change this header!\n"; + +function BuildOutput($Query) +{ + global $dbprefix, $connect; + $QueryResult = db_execute_assoc($Query) or safe_die ("ERROR: $QueryResult
      ".$connect->ErrorMsg()); + preg_match('/FROM (\w+)( |,)/i', $Query, $MatchResults); + $TableName = $MatchResults[1];; + if ($dbprefix) + { + $TableName = substr($TableName, strlen($dbprefix), strlen($TableName)); + } + $Output = "\n#\n# " . strtoupper($TableName) . " TABLE\n#\n"; + $HeaderDone = false; $ColumnNames = ""; + while ($Row = $QueryResult->FetchRow()) + { + + if (!$HeaderDone) + { + foreach ($Row as $Key=>$Value) + { + $ColumnNames .= CSVEscape($Key).","; //Add all the column names together + } + $ColumnNames = substr($ColumnNames, 0, -1); //strip off last comma space + $Output .= "$ColumnNames\n"; + $HeaderDone=true; + } + $ColumnValues = ""; + foreach ($Row as $Key=>$Value) + { + $ColumnValues .= CSVEscape(str_replace("\r\n", "\n", $Value)) . ","; + } + $ColumnValues = substr($ColumnValues, 0, -1); //strip off last comma space + $Output .= "$ColumnValues\n"; + } + return $Output; +} + + +//1: Questions Table +$qquery = "SELECT * + FROM {$dbprefix}questions + WHERE qid=$qid"; +$qdump = BuildCSVFromQuery($qquery); + +//2: Answers table +$aquery = "SELECT {$dbprefix}answers.* + FROM {$dbprefix}answers + WHERE {$dbprefix}answers.qid = $qid"; +$adump = BuildCSVFromQuery($aquery); + +//3: Labelsets Table +//$lsquery = "SELECT DISTINCT {$dbprefix}labelsets.* FROM {$dbprefix}labelsets, {$dbprefix}questions WHERE {$dbprefix}labelsets.lid={$dbprefix}questions.lid AND type='F' AND qid=$qid"; +$lsquery = "SELECT DISTINCT {$dbprefix}labelsets.* + FROM {$dbprefix}labelsets, {$dbprefix}questions + WHERE {$dbprefix}labelsets.lid={$dbprefix}questions.lid + AND type in ('F', 'W', 'H', 'Z', '1', ':', ';') + AND qid=$qid"; +$lsdump = BuildCSVFromQuery($lsquery); + +//4: Labels Table +$lquery = "SELECT DISTINCT {$dbprefix}labels.* + FROM {$dbprefix}labels, {$dbprefix}questions + WHERE {$dbprefix}labels.lid={$dbprefix}questions.lid + AND type in ('F', 'W', 'H', 'Z', '1', ':', ';') + AND qid=$qid"; +$ldump = BuildCSVFromQuery($lquery); + +//4: Labelsets1 Table +//This exists specifically to deal with dual-scale questions (or any future question that may have 2 labelsets) +$lsquery = "SELECT DISTINCT {$dbprefix}labelsets.* FROM {$dbprefix}labelsets, {$dbprefix}questions WHERE {$dbprefix}labelsets.lid={$dbprefix}questions.lid1 AND type in ('1') AND qid=$qid"; +$ls1dump = BuildCSVFromQuery($lsquery); +$ls1=explode("\n", trim($ls1dump)); + +if(count($ls1)>3) { + //If there is actually some data here, then add just the data (not the headers) into + // $ls1dump - which will be outputted directly after $lsdump + $ls1dump=$ls1[4]; + $ls1dump .= "\n"; +} else { + //If there is no data then make it an empty string. + $ls1dump = ""; +} +//4a: Labels1 Table +// See explanation for Labelsets1 Table!! These are the actual labels +$lquery = "SELECT DISTINCT {$dbprefix}labels.* FROM {$dbprefix}labels, {$dbprefix}questions WHERE {$dbprefix}labels.lid={$dbprefix}questions.lid1 AND type in ('1') AND qid=$qid"; +$l1dump = BuildCSVFromQuery($lquery); +$ld1=explode("\n", trim($l1dump)); + +if(count($ld1)>3) { + //If there is actually some data here, then add just the data (not the headers) into + // $l1dump - which will be outputted directly after $ldump + $l1dump=array(); + foreach($ld1 as $key=>$ld) { + //Put every line, other than the first three into this string + if($key > 3) { + $l1dump[]=$ld; + } + } + $l1dump = implode("\n", $l1dump); + $l1dump .= "\n"; +} else { + //If there is no data then make it an empty string. + $l1dump = ""; +} + + +//5: Question Attributes +$query = "SELECT {$dbprefix}question_attributes.* + FROM {$dbprefix}question_attributes + WHERE {$dbprefix}question_attributes.qid=$qid"; +$qadump = BuildCSVFromQuery($query); +$fn = "limesurvey_question_$qid.csv"; + + +header("Content-Type: application/download"); +header("Content-Disposition: attachment; filename=$fn"); +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"); +header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); +header("Pragma: cache"); // HTTP/1.0 +echo $dumphead, $qdump, $adump, $lsdump, $ls1dump, $ldump, $l1dump, $qadump; +exit; +?> diff --git a/include/limesurvey/admin/export_data_functions.php b/include/limesurvey/admin/export_data_functions.php new file mode 100644 index 00000000..32c18090 --- /dev/null +++ b/include/limesurvey/admin/export_data_functions.php @@ -0,0 +1,457 @@ +$query
      ".$connect->ErrorMsg()); //Checked + $num_fields = $result->FieldCount(); + + while ($row = $result->FetchRow()) { + $fieldno = 0; + while ($fieldno < $num_fields) + { + if ($fields[$fieldno]['SPSStype']=='DATETIME23.2'){ + #convert mysql datestamp (yyyy-mm-dd hh:mm:ss) to SPSS datetime (dd-mmm-yyyy hh:mm:ss) format + if (isset($row[$fieldno])) + { + list( $year, $month, $day, $hour, $minute, $second ) = split( '([^0-9])', $row[$fieldno] ); + if ($year != '' && (int)$year >= 1970) + { + echo "'".date('d-m-Y H:i:s', mktime( $hour, $minute, $second, $month, $day, $year ) )."'"; + } else + { + echo ($na); + } + } else + { + echo ($na); + } + } else if ($fields[$fieldno]['LStype'] == 'Y') + { + if ($row[$fieldno] == 'Y') // Yes/No Question Type + { + echo( "'1'"); + } else if ($row[$fieldno] == 'N'){ + echo( "'2'"); + } else { + echo($na); + } + } else if ($fields[$fieldno]['LStype'] == 'G') //Gender + { + if ($row[$fieldno] == 'F') + { + echo( "'1'"); + } else if ($row[$fieldno] == 'M'){ + echo( "'2'"); + } else { + echo($na); + } + } else if ($fields[$fieldno]['LStype'] == 'C') //Yes/No/Uncertain + { + if ($row[$fieldno] == 'Y') + { + echo( "'1'"); + } else if ($row[$fieldno] == 'N'){ + echo( "'2'"); + } else if ($row[$fieldno] == 'U'){ + echo( "'3'"); + } else { + echo($na); + } + } else if ($fields[$fieldno]['LStype'] == 'E') //Increase / Same / Decrease + { + if ($row[$fieldno] == 'I') + { + echo( "'1'"); + } else if ($row[$fieldno] == 'S'){ + echo( "'2'"); + } else if ($row[$fieldno] == 'D'){ + echo( "'3'"); + } else { + echo($na); + } + } elseif (($fields[$fieldno]['LStype'] == 'P' || $fields[$fieldno]['LStype'] == 'M') && (substr($fields[$fieldno]['code'],-7) != 'comment' && substr($fields[$fieldno]['code'],-5) != 'other')) + { + if ($row[$fieldno] == 'Y') + { + echo("'1'"); + } else + { + echo("'0'"); + } + } elseif (!$fields[$fieldno]['hide']) { + $strTmp=mb_substr(strip_tags_full($row[$fieldno]), 0, $length_data); + if (trim($strTmp) != ''){ + $strTemp=str_replace(array("'","\n","\r"),array("''",' ',' '),trim($strTmp)); + /* + * Temp quick fix for replacing decimal dots with comma's + if (my_is_numeric($strTemp)) { + $strTemp = str_replace('.',',',$strTemp); + } + */ + echo "'$strTemp'"; + } + else + { + echo $na; + } + } + $fieldno++; + if ($fieldno<$num_fields && !$fields[$fieldno]['hide']) echo ','; + } + echo "\n"; + } +} + +/** + * Check it the gives field has a labelset and return it as an array if true + * + * @param $field array field from spss_fieldmap + * @return array or false + */ +function spss_getvalues ($field = array()) { + global $surveyid, $dbprefix, $connect, $clang, $language, $length_vallabel; + + if (!isset($field['LStype']) || empty($field['LStype'])) return false; + $answers=array(); + if (strpos("!LOR",$field['LStype']) !== false) { + if (substr($field['code'],-5) == 'other' || substr($field['code'],-7) == 'comment') { + //We have a comment field, so free text + } else { + $query = "SELECT {$dbprefix}answers.code, {$dbprefix}answers.answer, + {$dbprefix}questions.type FROM {$dbprefix}answers, {$dbprefix}questions WHERE + {$dbprefix}answers.qid = '".$field["qid"]."' and {$dbprefix}questions.language='".$language."' and {$dbprefix}answers.language='".$language."' + and {$dbprefix}questions.qid='".$field['qid']."' ORDER BY sortorder ASC"; + $result=db_execute_assoc($query) or safe_die("Couldn't lookup value labels
      $query
      ".$connect->ErrorMsg()); //Checked + $num_results = $result->RecordCount(); + if ($num_results > 0) + { + $displayvaluelabel = 0; + # Build array that has to be returned + for ($i=0; $i < $num_results; $i++) + { + $row = $result->FetchRow(); + $answers[] = array('code'=>$row['code'], 'value'=>strip_tags_full(mb_substr($row["answer"],0,$length_vallabel))); + } + } + } + } elseif (strpos("FWZWH1",$field['LStype']) !== false) { + $query = "SELECT {$dbprefix}questions.lid, {$dbprefix}labels.code, {$dbprefix}labels.title from + {$dbprefix}questions, {$dbprefix}labels WHERE {$dbprefix}labels.language='".$language."' and + {$dbprefix}questions.language='".$language."' and + {$dbprefix}questions.qid ='".$field["qid"]."' and {$dbprefix}questions.lid={$dbprefix}labels.lid ORDER BY sortorder ASC"; + $result=db_execute_assoc($query) or safe_die("Couldn't get labels
      $query
      ".$connect->ErrorMsg()); //Checked + $num_results = $result->RecordCount(); + if ($num_results > 0) + { + for ($i=0; $i < $num_results; $i++) + { + $row = $result->FetchRow(); + $answers[] = array('code'=>$row['code'], 'value'=>strip_tags_full(mb_substr($row["title"],0,$length_vallabel))); + } + } + } elseif ($field['LStype'] == ':') { + $displayvaluelabel = 0; + //Get the labels that could apply! + $qidattributes=getQuestionAttributes($field["qid"]); + if ($maxvalue=arraySearchByKey("multiflexible_max", $qidattributes, "attribute", 1)) { + $maxvalue=$maxvalue['value']; + } else { + $maxvalue=10; + } + if ($minvalue=arraySearchByKey("multiflexible_min", $qidattributes, "attribute", 1)) { + $minvalue=$minvalue['value']; + } else { + $minvalue=1; + } + if ($stepvalue=arraySearchByKey("multiflexible_step", $qidattributes, "attribute", 1)) { + $stepvalue=$stepvalue['value']; + } else { + $stepvalue=1; + } + if (arraySearchByKey("multiflexible_checkbox", $qidattributes, "attribute", 1)) { + $minvalue=0; + $maxvalue=1; + $stepvalue=1; + } + for ($i=$minvalue; $i<=$maxvalue; $i+=$stepvalue) + { + $answers[] = array('code'=>$i, 'value'=>$i); + } + } elseif ($field['LStype'] == 'M' && substr($field['code'],-5) != 'other' && $field['size'] > 0) + { + $answers[] = array('code'=>1, 'value'=>$clang->gT('Yes')); + $answers[] = array('code'=>0, 'value'=>$clang->gT('Not Selected')); + } elseif ($field['LStype'] == "P" && substr($field['code'],-5) != 'other' && substr($field['code'],-7) != 'comment') + { + $answers[] = array('code'=>1, 'value'=>$clang->gT('Yes')); + $answers[] = array('code'=>0, 'value'=>$clang->gT('Not Selected')); + } elseif ($field['LStype'] == "G" && $field['size'] > 0) + { + $answers[] = array('code'=>1, 'value'=>$clang->gT('Female')); + $answers[] = array('code'=>2, 'value'=>$clang->gT('Male')); + } elseif ($field['LStype'] == "Y" && $field['size'] > 0) + { + $answers[] = array('code'=>1, 'value'=>$clang->gT('Yes')); + $answers[] = array('code'=>2, 'value'=>$clang->gT('No')); + } elseif ($field['LStype'] == "C" && $field['size'] > 0) + { + $answers[] = array('code'=>1, 'value'=>$clang->gT('Yes')); + $answers[] = array('code'=>2, 'value'=>$clang->gT('No')); + $answers[] = array('code'=>3, 'value'=>$clang->gT('Uncertain')); + } elseif ($field['LStype'] == "E" && $field['size'] > 0) + { + $answers[] = array('code'=>1, 'value'=>$clang->gT('Increase')); + $answers[] = array('code'=>2, 'value'=>$clang->gT('Same')); + $answers[] = array('code'=>3, 'value'=>$clang->gT('Decrease')); + } + if (count($answers)>0) { + //check the max width of the answers + $size = 0; + $spssType = 'F'; //Try if we can use num and use alpha as fallback + $size = 1; + foreach ($answers as $answer) { + $len = mb_strlen($answer['code']); + if ($len>$size) $size = $len; + if ($spssType =='F' && (my_is_numeric($answer['code'])===false || $size>16)) $spssType='A'; + } + $answers['size'] = $size; + $answers['SPSStype'] = $spssType; + return $answers; + + } else { + return false; + } +} + +/** + * Creates a fieldmap with all information necessary to output the fields + * + * @param $prefix string prefix for the variable ID + * @return array + */ +function spss_fieldmap($prefix = 'V') { + global $surveyid, $dbprefix, $typeMap, $connect, $clang; + global $surveyprivate, $tokensexist, $language; + + $fieldmap = createFieldMap($surveyid, 'full'); //Create a FULL fieldmap + + #See if tokens are being used + $tokensexist = tokenTableExists($surveyid); + + #Lookup the names of the attributes + $query="SELECT sid, private, language FROM {$dbprefix}surveys WHERE sid=$surveyid"; + $result=db_execute_assoc($query) or safe_die("Couldn't count fields
      $query
      ".$connect->ErrorMsg()); //Checked + $num_results = $result->RecordCount(); + $num_fields = $num_results; + # Build array that has to be returned + for ($i=0; $i < $num_results; $i++) { + $row = $result->FetchRow(); + $surveyprivate=$row['private']; + $language=$row['language']; + } + + $fieldno=0; + + $fields=array(); + if (isset($tokensexist) && $tokensexist == true && $surveyprivate == 'N') { + $tokenattributes=GetTokenFieldsAndNames($surveyid,false); + foreach ($tokenattributes as $attributefield=>$attributedescription) + { + //Drop the token field, since it is in the survey too + if($attributefield!='token') { + $fieldno++; + $fields[] = array('id'=>"$prefix$fieldno",'name'=>mb_substr($attributefield, 0, 8), + 'qid'=>0,'code'=>'','SPSStype'=>'A','LStype'=>'Undef', + 'VariableLabel'=>$attributedescription,'sql_name'=>$attributefield,'size'=>'100', + 'title'=>$attributefield,'hide'=>0); + } + } + } + + $tempArray = array(); + $fieldnames = array_values($connect->MetaColumnNames("{$dbprefix}survey_$surveyid", true)); + $num_results = count($fieldnames); + $num_fields = $num_results; + $diff = 0; + $noQID = Array('id', 'token', 'datestamp', 'submitdate', 'startdate', 'startlanguage', 'ipaddr', 'refurl'); + # Build array that has to be returned + for ($i=0; $i < $num_results; $i++) { + #Conditions for SPSS fields: + # - Length may not be longer than 8 characters + # - Name may not begin with a digit + $fieldname = $fieldnames[$i]; + $fieldtype = ''; + $ftype=''; + $val_size = 1; + $hide = 0; + $export_scale = ''; + $code=''; + + #Determine field type + if ($fieldname=='submitdate' || $fieldname=='startdate' || $fieldname == 'datestamp') { + $fieldtype = 'DATETIME23.2'; + } elseif ($fieldname=='startlanguage') { + $fieldtype = 'A'; + $val_size = 19; + } elseif ($fieldname=='token') { + $fieldtype = 'A'; + $val_size = 16; + } elseif ($fieldname=='id') { + $fieldtype = 'F'; + $val_size = 7; //Arbitrarilty restrict to 9,999,999 (7 digits) responses/survey + } elseif ($fieldname == 'ipaddr') { + $fieldtype = 'A'; + $val_size = '15'; + } elseif ($fieldname == 'refurl') { + $fieldtype = 'A'; + $val_size = 255; + } + + #Get qid (question id) + if (in_array($fieldname, $noQID) || substr($fieldname,0,10)=='attribute_'){ + $qid = 0; + $varlabel = $fieldname; + $ftitle = $fieldname; + } else{ + //GET FIELD DATA + $fielddata=arraySearchByKey($fieldname, $fieldmap, 'fieldname', 1); + if (count($fielddata)==0) { + //Field in database but no longer in survey... how is this possible? + //@TODO: think of a fix. + } else { + $qid=$fielddata['qid']; + $ftype=$fielddata['type']; + $fsid=$fielddata['sid']; + $fgid=$fielddata['gid']; + $code=mb_substr($fielddata['fieldname'],strlen($fsid."X".$fgid."X".$qid)); + $varlabel=$fielddata['question']; + $ftitle=$fielddata['title']; + if (!is_null($code) && $code<>"" ) $ftitle .= "_$code"; + if (isset($typeMap[$ftype]['size'])) $val_size = $typeMap[$ftype]['size']; + if($fieldtype == '') $fieldtype = $typeMap[$ftype]['SPSStype']; + if (isset($typeMap[$ftype]['hide'])) { + $hide = $typeMap[$ftype]['hide']; + $diff++; + } + //Get default scale for this type + if (isset($typeMap[$ftype]['Scale'])) $export_scale = $typeMap[$ftype]['Scale']; + //But allow override + $aQuestionAttribs = getQAttributes($qid); + if (isset($aQuestionAttribs['scale_export'])) $export_scale = $aQuestionAttribs['scale_export']; + } + + } + $fieldno++; + $fid = $fieldno - $diff; + $lsLong = isset($typeMap[$ftype]["name"])?$typeMap[$ftype]["name"]:$ftype; + $tempArray = array('id'=>"$prefix$fid",'name'=>mb_substr($fieldname, 0, 8), + 'qid'=>$qid,'code'=>$code,'SPSStype'=>$fieldtype,'LStype'=>$ftype,"LSlong"=>$lsLong, + 'ValueLabels'=>'','VariableLabel'=>$varlabel,"sql_name"=>$fieldname,"size"=>$val_size, + 'title'=>$ftitle,'hide'=>$hide,'scale'=>$export_scale); + //Now check if we have to retrieve value labels + $answers = spss_getvalues($tempArray); + if (is_array($answers)) { + //Ok we have answers + if (isset($answers['size'])) { + $tempArray['size'] = $answers['size']; + unset($answers['size']); + } + if (isset($answers['SPSStype'])) { + $tempArray['SPSStype'] = $answers['SPSStype']; + unset($answers['SPSStype']); + } + $tempArray['answers'] = $answers; + } + $fields[] = $tempArray; + } + return $fields; +} + +/** + * Creates a query string with all fields for the export + * + * @return string + */ +function spss_getquery() { + global $surveyprivate, $dbprefix, $surveyid, $tokensexist; + + #See if tokens are being used + if (isset($tokensexist) && $tokensexist == true && $surveyprivate == 'N') { + $query="SELECT "; + $tokenattributes=GetTokenFieldsAndNames($surveyid,false); + foreach ($tokenattributes as $attributefield=>$attributedescription) { + //Drop the token field, since it is in the survey too + if($attributefield!='token') { + $query .= "{$dbprefix}tokens_$surveyid.$attributefield, "; + } + } + $query .= "{$dbprefix}survey_$surveyid.* + FROM {$dbprefix}survey_$surveyid + LEFT JOIN {$dbprefix}tokens_$surveyid ON {$dbprefix}survey_$surveyid.token = {$dbprefix}tokens_$surveyid.token"; + } else { + $query = "SELECT * + FROM {$dbprefix}survey_$surveyid"; + } + switch (incompleteAnsFilterstate()) { + case 'inc': + //Inclomplete answers only + $query .= ' WHERE submitdate is null '; + break; + case 'filter': + //Inclomplete answers only + $query .= ' WHERE submitdate is not null '; + break; + } + return $query; +} +?> \ No newline at end of file diff --git a/include/limesurvey/admin/export_data_r.php b/include/limesurvey/admin/export_data_r.php new file mode 100644 index 00000000..bc1da40f --- /dev/null +++ b/include/limesurvey/admin/export_data_r.php @@ -0,0 +1,244 @@ +Array('name'=>'5 Point Choice','size'=>1,'SPSStype'=>'F','Scale'=>3), +'B'=>Array('name'=>'Array (10 Point Choice)','size'=>1,'SPSStype'=>'F','Scale'=>3), +'A'=>Array('name'=>'Array (5 Point Choice)','size'=>1,'SPSStype'=>'F','Scale'=>3), +'F'=>Array('name'=>'Array (Flexible Labels)','size'=>1,'SPSStype'=>'F'), +'1'=>Array('name'=>'Array (Flexible Labels) Dual Scale','size'=>1,'SPSStype'=>'F'), +'H'=>Array('name'=>'Array (Flexible Labels) by Column','size'=>1,'SPSStype'=>'F'), +'E'=>Array('name'=>'Array (Increase, Same, Decrease)','size'=>1,'SPSStype'=>'F','Scale'=>2), +'C'=>Array('name'=>'Array (Yes/No/Uncertain)','size'=>1,'SPSStype'=>'F'), +'X'=>Array('name'=>'Boilerplate Question','size'=>1,'SPSStype'=>'A','hide'=>1), +'D'=>Array('name'=>'Date','size'=>10,'SPSStype'=>'SDATE'), +'G'=>Array('name'=>'Gender','size'=>1,'SPSStype'=>'F'), +'U'=>Array('name'=>'Huge Free Text','size'=>1,'SPSStype'=>'A'), +'I'=>Array('name'=>'Language Switch','size'=>1,'SPSStype'=>'A'), +'!'=>Array('name'=>'List (Dropdown)','size'=>1,'SPSStype'=>'F'), +'W'=>Array('name'=>'List (Flexible Labels) (Dropdown)','size'=>1,'SPSStype'=>'F'), +'Z'=>Array('name'=>'List (Flexible Labels) (Radio)','size'=>1,'SPSStype'=>'F'), +'L'=>Array('name'=>'List (Radio)','size'=>1,'SPSStype'=>'F'), +'O'=>Array('name'=>'List With Comment','size'=>1,'SPSStype'=>'F'), +'T'=>Array('name'=>'Long free text','size'=>1,'SPSStype'=>'A'), +'K'=>Array('name'=>'Multiple Numerical Input','size'=>1,'SPSStype'=>'F'), +'M'=>Array('name'=>'Multiple Options','size'=>1,'SPSStype'=>'F'), +'P'=>Array('name'=>'Multiple Options With Comments','size'=>1,'SPSStype'=>'F'), +'Q'=>Array('name'=>'Multiple Short Text','size'=>1,'SPSStype'=>'F'), +'N'=>Array('name'=>'Numerical Input','size'=>3,'SPSStype'=>'F','Scale'=>3), +'R'=>Array('name'=>'Ranking','size'=>1,'SPSStype'=>'F'), +'S'=>Array('name'=>'Short free text','size'=>1,'SPSStype'=>'F'), +'Y'=>Array('name'=>'Yes/No','size'=>1,'SPSStype'=>'F'), +':'=>Array('name'=>'Multi flexi numbers','size'=>1,'SPSStype'=>'F','Scale'=>3), +';'=>Array('name'=>'Multi flexi text','size'=>1,'SPSStype'=>'A'), +); + +if (!isset($surveyid)) {$surveyid=returnglobal('sid');} + +if (!isset($subaction)) +{ + $exportroutput = browsemenubar($clang->gT('Export results')); + $exportroutput .= "
      \n"; + $exportroutput .= "
      ".$clang->gT("Export result data to R")."
      \n"; + $exportroutput .= "


      \n" + ."

      ".$clang->gT("Instructions for the impatient")."

      " + ."
        " + ."
      1. ".$clang->gT("Download the data and the syntax file.")."
      2. " + ."
      3. ".$clang->gT("Save both of them on the R working directory (use getwd() and setwd() on the R command window to get and set it)").".
      4. " + ."
      5. ".$clang->gT("digit: source(\"Surveydata_syntax.R\", encoding = \"UTF-8\") on the R command window")."
      6. " + ."

      " + .$clang->gT("Your data should be imported now, the data.frame is named \"data\", the variable.labels are attributes of data (\"attributes(data)\$variable.labels\"), like for foreign:read.spss.") + ."\n" + + . "\n" + + . "\n" + . "\n" + . "
      "; +} else { + // Get Base Language: + + $language = GetBaseLanguageFromSurveyID($surveyid); + $clang = new limesurvey_lang($language); + require_once ("export_data_functions.php"); +} + + + +if ($subaction=='dldata') { + header("Content-Type: application/download; charset=utf-8"); + header("Content-Disposition: attachment; filename=survey_".$surveyid."_data_file.csv"); + header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); + header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); + header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); + header('Pragma: no-cache'); + + sendcacheheaders(); + + $na = "\"\""; + spss_export_data($na); + + exit; +} + + +if ($subaction=='dlstructure') { + header("Content-Type: application/download; charset=utf-8"); + header("Content-Disposition: attachment; filename=Surveydata_syntax.R"); + header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); + header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); + header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); + header('Pragma: no-cache'); + + sendcacheheaders(); + + // Build array that has to be returned + $fields = spss_fieldmap(); + + //Now get the query string with all fields to export + $query = spss_getquery(); + + $result=db_execute_num($query) or safe_die("Couldn't get results
      $query
      ".$connect->ErrorMsg()); //Checked + $num_fields = $result->FieldCount(); + + //Now we check if we need to adjust the size of the field or the type of the field + while ($row = $result->FetchRow()) { + $fieldno = 0; + while ($fieldno < $num_fields) + { + //Performance improvement, don't recheck fields that have valuelabels + if (!isset($fields[$fieldno]['answers'])) { + $strTmp=mb_substr(strip_tags_full($row[$fieldno]), 0, $length_data); + $len = mb_strlen($strTmp); + if($len > $fields[$fieldno]['size']) $fields[$fieldno]['size'] = $len; + + if (trim($strTmp) != ''){ + if ($fields[$fieldno]['SPSStype']=='F' && (my_is_numeric($strTmp)===false || $fields[$fieldno]['size']>16)) + { + $fields[$fieldno]['SPSStype']='A'; + } + } + } + $fieldno++; + } + } + + /** + * End of DATA print out + * + * Now $fields contains accurate length data, and the DATA LIST can be rendered -- then the contents of the temp file can + * be sent to the client. + */ + echo $headerComment; + echo "data=read.table(\"survey_".$surveyid."_data_file.csv\", sep=\",\", quote = \"'\", na.strings=\"\")\n names(data)=paste(\"V\",1:dim(data)[2],sep=\"\")\n"; + foreach ($fields as $field){ + if($field['SPSStype'] == 'DATETIME23.2') $field['size']=''; + if($field['LStype'] == 'N' || $field['LStype']=='K') { + $field['size'].='.'.($field['size']-1); + } + switch ($field['SPSStype']) { + case 'F': + $type="numeric"; + break; + case 'A': + $type="character"; + break; + case 'DATETIME23.2': + case 'SDATE': + $type="character"; + //@TODO set $type to format for date + break; + + } + if (!$field['hide']) echo " data[,which(names(data)==\"" . $field['id'] . "\")]=as.$type(data[,which(names(data)==\"" . $field['id'] . "\")])\n"; + } + + //Create the variable labels: + echo "#Define Variable Properties.\n"; + foreach ($fields as $field) { + if (!$field['hide']) echo 'attributes(data)$variable.labels[which(names(data)=="' . $field['id'] . '")]="' . addslashes(strip_tags_full(mb_substr($field['VariableLabel'],0,$length_varlabel))) . '"' . "\n"; + } + + // Create our Value Labels! + echo "#Define Value labels.\n"; + foreach ($fields as $field) { + if (isset($field['answers'])) { + $answers = $field['answers']; + //print out the value labels! + // data$V14=factor(data$V14,levels=c(1,2,3),labels=c("Yes","No","Uncertain")) + echo 'data$' . $field["id"] . '=factor(data$' . $field["id"] . ',levels=c('; + $str=""; + foreach ($answers as $answer) { + if ($field['SPSStype']=="F" && my_is_numeric($answer['code'])) { + $str .= ",{$answer['code']}"; + } else { + $str .= ",\"{$answer['code']}\""; + } + } + $str = mb_substr($str,1); + echo $str . '),labels=c('; + $str=""; + foreach ($answers as $answer) { + $str .= ",\"{$answer['value']}\""; + } + $str = mb_substr($str,1); + if($field['scale']!=='' && $field['scale'] == 2 ) { + $scale = ",ordered=TRUE"; + } else { + $scale = ""; + } + echo "$str)$scale)\n"; + } + } + + //Rename the Variables (in case somethings goes wrong, we still have the OLD values + $errors = ""; + echo "v.names=c("; + foreach ($fields as $field){ + if (isset($field['sql_name'])) { + $ftitle = $field['title']; + if (!preg_match ("/^([a-z]|[A-Z])+.*$/", $ftitle)) { + $ftitle = "q_" . $ftitle; + } + $ftitle = str_replace(array("-",":",";","!"), array("_hyph_","_dd_","_dc_","_excl_"), $ftitle); + if (!$field['hide']) { + if ($ftitle != $field['title']) $errors .= "# Variable name was incorrect and was changed from {$field['title']} to $ftitle .\n"; + echo "\"". $ftitle . "\","; + } + } + } + echo "NA); names(data)= v.names[-length(v.names)]\nprint(str(data))\n"; + echo $errors; + exit; +} +?> \ No newline at end of file diff --git a/include/limesurvey/admin/export_data_spss.php b/include/limesurvey/admin/export_data_spss.php new file mode 100644 index 00000000..1b5b8863 --- /dev/null +++ b/include/limesurvey/admin/export_data_spss.php @@ -0,0 +1,241 @@ +Array('name'=>'5 Point Choice','size'=>1,'SPSStype'=>'F','Scale'=>3), +'B'=>Array('name'=>'Array (10 Point Choice)','size'=>1,'SPSStype'=>'F','Scale'=>3), +'A'=>Array('name'=>'Array (5 Point Choice)','size'=>1,'SPSStype'=>'F','Scale'=>3), +'F'=>Array('name'=>'Array (Flexible Labels)','size'=>1,'SPSStype'=>'F'), +'1'=>Array('name'=>'Array (Flexible Labels) Dual Scale','size'=>1,'SPSStype'=>'F'), +'H'=>Array('name'=>'Array (Flexible Labels) by Column','size'=>1,'SPSStype'=>'F'), +'E'=>Array('name'=>'Array (Increase, Same, Decrease)','size'=>1,'SPSStype'=>'F','Scale'=>2), +'C'=>Array('name'=>'Array (Yes/No/Uncertain)','size'=>1,'SPSStype'=>'F'), +'X'=>Array('name'=>'Boilerplate Question','size'=>1,'SPSStype'=>'A','hide'=>1), +'D'=>Array('name'=>'Date','size'=>10,'SPSStype'=>'SDATE'), +'G'=>Array('name'=>'Gender','size'=>1,'SPSStype'=>'F'), +'U'=>Array('name'=>'Huge Free Text','size'=>1,'SPSStype'=>'A'), +'I'=>Array('name'=>'Language Switch','size'=>1,'SPSStype'=>'A'), +'!'=>Array('name'=>'List (Dropdown)','size'=>1,'SPSStype'=>'F'), +'W'=>Array('name'=>'List (Flexible Labels) (Dropdown)','size'=>1,'SPSStype'=>'F'), +'Z'=>Array('name'=>'List (Flexible Labels) (Radio)','size'=>1,'SPSStype'=>'F'), +'L'=>Array('name'=>'List (Radio)','size'=>1,'SPSStype'=>'F'), +'O'=>Array('name'=>'List With Comment','size'=>1,'SPSStype'=>'F'), +'T'=>Array('name'=>'Long free text','size'=>1,'SPSStype'=>'A'), +'K'=>Array('name'=>'Multiple Numerical Input','size'=>1,'SPSStype'=>'F'), +'M'=>Array('name'=>'Multiple Options','size'=>1,'SPSStype'=>'F'), +'P'=>Array('name'=>'Multiple Options With Comments','size'=>1,'SPSStype'=>'F'), +'Q'=>Array('name'=>'Multiple Short Text','size'=>1,'SPSStype'=>'F'), +'N'=>Array('name'=>'Numerical Input','size'=>3,'SPSStype'=>'F','Scale'=>3), +'R'=>Array('name'=>'Ranking','size'=>1,'SPSStype'=>'F'), +'S'=>Array('name'=>'Short free text','size'=>1,'SPSStype'=>'F'), +'Y'=>Array('name'=>'Yes/No','size'=>1,'SPSStype'=>'F'), +':'=>Array('name'=>'Multi flexi numbers','size'=>1,'SPSStype'=>'F','Scale'=>3), +';'=>Array('name'=>'Multi flexi text','size'=>1,'SPSStype'=>'A'), +); + +if (!isset($surveyid)) {$surveyid=returnglobal('sid');} + +if (!isset($subaction)) +{ + $exportspssoutput = browsemenubar($clang->gT('Export results')); + $exportspssoutput .= "
      \n"; + $exportspssoutput .= "
      ".$clang->gT("Export result data to SPSS")."
      \n"; + $exportspssoutput .= "


      \n" + ."

      ".$clang->gT("Instructions for the impatient")."

      " + ."
        " + ."
      1. ".$clang->gT("Download the data and the syntax file.")."
      2. " + ."
      3. ".$clang->gT("Open the syntax file in SPSS in Unicode mode").".
      4. " + ."
      5. ".$clang->gT("Edit the 4th line and complete the filename with a full path to the downloaded data file.")."
      6. " + ."
      7. ".$clang->gT("Choose 'Run/All' from the menu to run the import.")."
      8. " + ."

      " + .$clang->gT("Your data should be imported now.") + ."\n" - ."\t" - ."
      "; +} else { + // Get Base Language: + + $language = GetBaseLanguageFromSurveyID($surveyid); + $clang = new limesurvey_lang($language); + require_once ("export_data_functions.php"); +} + + + +if ($subaction=='dldata') { + header("Content-Type: application/download; charset=utf-8"); + header("Content-Disposition: attachment; filename=survey_".$surveyid."_SPSS_data_file.dat"); + header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); + header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); + header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); + header('Pragma: no-cache'); + + sendcacheheaders(); + + $na = ""; + spss_export_data($na); + + exit; +} + + +if ($subaction=='dlstructure') { + header("Content-Type: application/download; charset=utf-8"); + header("Content-Disposition: attachment; filename=survey_".$surveyid."_SPSS_syntax_file.sps"); + header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); + header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); + header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); + header('Pragma: no-cache'); + + sendcacheheaders(); + + // Build array that has to be returned + $fields = spss_fieldmap(); + + //Now get the query string with all fields to export + $query = spss_getquery(); + + $result=db_execute_num($query) or safe_die("Couldn't get results
      $query
      ".$connect->ErrorMsg()); //Checked + $num_fields = $result->FieldCount(); + + //Now we check if we need to adjust the size of the field or the type of the field + while ($row = $result->FetchRow()) { + $fieldno = 0; + while ($fieldno < $num_fields) + { + //Performance improvement, don't recheck fields that have valuelabels + if (!isset($fields[$fieldno]['answers'])) { + $strTmp=mb_substr(strip_tags_full($row[$fieldno]), 0, $length_data); + $len = mb_strlen($strTmp); + if($len > $fields[$fieldno]['size']) $fields[$fieldno]['size'] = $len; + + if (trim($strTmp) != ''){ + if ($fields[$fieldno]['SPSStype']=='F' && (my_is_numeric($strTmp)===false || $fields[$fieldno]['size']>16)) + { + $fields[$fieldno]['SPSStype']='A'; + } + } + } + $fieldno++; + } + } + + /** + * End of DATA print out + * + * Now $fields contains accurate length data, and the DATA LIST can be rendered -- then the contents of the temp file can + * be sent to the client. + */ + echo $headerComment; + echo "SET UNICODE=ON.\n" + ."GET DATA\n" + ."/TYPE=TXT\n" + ."/FILE='survey_".$surveyid."_SPSS_data_file.dat'\n" + ."/DELCASE=LINE\n" + ."/DELIMITERS=\",\"\n" + ."/QUALIFIER=\"'\"\n" + ."/ARRANGEMENT=DELIMITED\n" + ."/FIRSTCASE=1\n" + ."/IMPORTCASE=ALL\n" + ."/VARIABLES="; + foreach ($fields as $field){ + if($field['SPSStype'] == 'DATETIME23.2') $field['size']=''; + if($field['SPSStype']=='F' && ($field['LStype'] == 'N' || $field['LStype']=='K')) { + $field['size'].='.'.($field['size']-1); + } + if (!$field['hide']) echo "\n {$field['id']} {$field['SPSStype']}{$field['size']}"; + } + echo ".\nCACHE.\n" + ."EXECUTE.\n"; + + //Create the variable labels: + echo "*Define Variable Properties.\n"; + foreach ($fields as $field) { + if (!$field['hide']) echo "VARIABLE LABELS " . $field['id'] . " \"" . addslashes(strip_tags_full(mb_substr($field['VariableLabel'],0,$length_varlabel))) . "\".\n"; + } + + // Create our Value Labels! + echo "*Define Value labels.\n"; + foreach ($fields as $field) { + if (isset($field['answers'])) { + $answers = $field['answers']; + //print out the value labels! + echo "VALUE LABELS {$field['id']}\n"; + $i=0; + foreach ($answers as $answer) { + $i++; + if ($field['SPSStype']=="F" && my_is_numeric($answer['code'])) { + $str = "{$answer['code']}"; + } else { + $str = "\"{$answer['code']}\""; + } + if ($i < count($answers)) { + echo " $str \"{$answer['value']}\"\n"; + } else { + echo " $str \"{$answer['value']}\".\n"; + } + } + } + } + + foreach ($fields as $field){ + if($field['scale']!=='') { + switch ($field['scale']) { + case 2: + echo "VARIABLE LEVEL {$field['id']}(ORDINAL).\n"; + break; + case 3: + echo "VARIABLE LEVEL {$field['id']}(SCALE).\n"; + } + } + } + + //Rename the Variables (in case somethings goes wrong, we still have the OLD values + foreach ($fields as $field){ + if (isset($field['sql_name']) && $field['hide']===0) { + $ftitle = $field['title']; + if (!preg_match ("/^([a-z]|[A-Z])+.*$/", $ftitle)) { + $ftitle = "q_" . $ftitle; + } + $ftitle = str_replace(array(" ","-",":",";","!","/","\\"), array("_","_hyph_","_dd_","_dc_","_excl_","_fs_","_bs_"), $ftitle); + if ($ftitle != $field['title']) echo "* Variable name was incorrect and was changed from {$field['title']} to $ftitle .\n"; + echo "RENAME VARIABLE ( " . $field['id'] . " = " . $ftitle . " ).\n"; + } + } + exit; +} +?> \ No newline at end of file diff --git a/include/limesurvey/admin/export_resources_zip.php b/include/limesurvey/admin/export_resources_zip.php index 3b16fb3b..8df9b968 100644 --- a/include/limesurvey/admin/export_resources_zip.php +++ b/include/limesurvey/admin/export_resources_zip.php @@ -10,7 +10,7 @@ * other free or open source software licenses. * See COPYRIGHT.php for copyright notices and details. * -* $Id: templates.php 3685 2007-11-22 04:53:18Z jcleeland $ +* $Id: export_resources_zip.php 6853 2009-05-15 12:51:09Z c_schmitz $ */ diff --git a/include/limesurvey/admin/export_structure_csv.php b/include/limesurvey/admin/export_structure_csv.php index 49947fc6..a45fc7c6 100644 --- a/include/limesurvey/admin/export_structure_csv.php +++ b/include/limesurvey/admin/export_structure_csv.php @@ -1,122 +1,163 @@ -\n" - ."\n" - ."\t\n" - ."\t\n" - ."
      " - .$clang->gT("Export Survey")."
      \n" - ."
      " - .$clang->gT("Error")."
      \n" - .$clang->gT("No SID has been provided. Cannot dump survey")."
      \n" - ."
      \n" - ."\t
      \n" - ."\n"; - exit; -} - -$dumphead = "# LimeSurvey Survey Dump\n" - . "# DBVersion $dbversionnumber\n" - . "# This is a dumped survey from the LimeSurvey Script\n" - . "# http://www.limesurvey.org/\n" - . "# Do not change this header!\n"; - -//1: Surveys table -$squery = "SELECT * FROM {$dbprefix}surveys WHERE sid=$surveyid"; -$sdump = BuildCSVFromQuery($squery); - -//2: Surveys Languagsettings table -$slsquery = "SELECT * FROM {$dbprefix}surveys_languagesettings WHERE surveyls_survey_id=$surveyid"; -$slsdump = BuildCSVFromQuery($slsquery); - -//3: Groups Table -$gquery = "SELECT * FROM {$dbprefix}groups WHERE sid=$surveyid order by gid"; -$gdump = BuildCSVFromQuery($gquery); - -//4: Questions Table -$qquery = "SELECT * FROM {$dbprefix}questions WHERE sid=$surveyid order by qid"; -$qdump = BuildCSVFromQuery($qquery); - -//5: Answers table -$aquery = "SELECT {$dbprefix}answers.* FROM {$dbprefix}answers, {$dbprefix}questions WHERE {$dbprefix}answers.language={$dbprefix}questions.language AND {$dbprefix}answers.qid={$dbprefix}questions.qid AND {$dbprefix}questions.sid=$surveyid"; -$adump = BuildCSVFromQuery($aquery); - -//6: Conditions table -$cquery = "SELECT DISTINCT {$dbprefix}conditions.* FROM {$dbprefix}conditions, {$dbprefix}questions WHERE {$dbprefix}conditions.qid={$dbprefix}questions.qid AND {$dbprefix}questions.sid=$surveyid"; -$cdump = BuildCSVFromQuery($cquery); - -//7: Label Sets -$lsquery = "SELECT DISTINCT {$dbprefix}labelsets.lid, label_name, {$dbprefix}labelsets.languages FROM {$dbprefix}labelsets, {$dbprefix}questions WHERE ({$dbprefix}labelsets.lid={$dbprefix}questions.lid or {$dbprefix}labelsets.lid={$dbprefix}questions.lid1) AND type IN ('F', 'H', 'W', 'Z', '1') AND sid=$surveyid"; -$lsdump = BuildCSVFromQuery($lsquery); - -//8: Labels -$lquery = "SELECT {$dbprefix}labels.lid, {$dbprefix}labels.code, {$dbprefix}labels.title, {$dbprefix}labels.sortorder,{$dbprefix}labels.language FROM {$dbprefix}labels, {$dbprefix}questions WHERE ({$dbprefix}labels.lid={$dbprefix}questions.lid or {$dbprefix}labels.lid={$dbprefix}questions.lid1) AND type in ('F', 'W', 'H', 'Z', '1') AND sid=$surveyid group by {$dbprefix}labels.lid, {$dbprefix}labels.code, {$dbprefix}labels.title, {$dbprefix}labels.sortorder,{$dbprefix}labels.language"; -$ldump = BuildCSVFromQuery($lquery); - -//9: Question Attributes -$query = "SELECT DISTINCT {$dbprefix}question_attributes.* FROM {$dbprefix}question_attributes, {$dbprefix}questions WHERE {$dbprefix}question_attributes.qid={$dbprefix}questions.qid AND {$dbprefix}questions.sid=$surveyid"; -$qadump = BuildCSVFromQuery($query); - -//10: Assessments; -$query = "SELECT {$dbprefix}assessments.* FROM {$dbprefix}assessments WHERE {$dbprefix}assessments.sid=$surveyid"; -$asdump = BuildCSVFromQuery($query); - -//11: Quota; -$query = "SELECT {$dbprefix}quota.* FROM {$dbprefix}quota WHERE {$dbprefix}quota.sid=$surveyid"; -$quotadump = BuildCSVFromQuery($query); - -//12: Quota Members; -$query = "SELECT {$dbprefix}quota_members.* FROM {$dbprefix}quota_members WHERE {$dbprefix}quota_members.sid=$surveyid"; -$quotamemdump = BuildCSVFromQuery($query); - -$fn = "limesurvey_survey_$surveyid.csv"; - -header("Content-Type: application/download"); -header("Content-Disposition: attachment; filename=$fn"); -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"); -header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); -header("Pragma: cache"); // HTTP/1.0 - -echo $dumphead, $sdump, $gdump, $qdump, $adump, $cdump, $lsdump, $ldump, $qadump, $asdump, $slsdump, $quotadump, $quotamemdump."\n"; -exit; -?> +\n" + ."\n" + ."\t\n" + ."\t\n" + ."
      " + .$clang->gT("Export Survey")."
      \n" + ."
      " + .$clang->gT("Error")."
      \n" + .$clang->gT("No SID has been provided. Cannot dump survey")."
      \n" + ."
      \n" + ."\t
      \n" + ."\n"; + exit; +} + +$dumphead = "# LimeSurvey Survey Dump\n" + . "# DBVersion $dbversionnumber\n" + . "# This is a dumped survey from the LimeSurvey Script\n" + . "# http://www.limesurvey.org/\n" + . "# Do not change this header!\n"; + +//1: Surveys table +$squery = "SELECT * + FROM {$dbprefix}surveys + WHERE sid=$surveyid"; +$sdump = BuildCSVFromQuery($squery); + +//2: Surveys Languagsettings table +$slsquery = "SELECT * + FROM {$dbprefix}surveys_languagesettings + WHERE surveyls_survey_id=$surveyid"; +$slsdump = BuildCSVFromQuery($slsquery); + +//3: Groups Table +$gquery = "SELECT * + FROM {$dbprefix}groups + WHERE sid=$surveyid + ORDER BY gid"; +$gdump = BuildCSVFromQuery($gquery); + +//4: Questions Table +$qquery = "SELECT * + FROM {$dbprefix}questions + WHERE sid=$surveyid + ORDER BY qid"; +$qdump = BuildCSVFromQuery($qquery); + +//5: Answers table +$aquery = "SELECT {$dbprefix}answers.* + FROM {$dbprefix}answers, {$dbprefix}questions + WHERE {$dbprefix}answers.language={$dbprefix}questions.language + AND {$dbprefix}answers.qid={$dbprefix}questions.qid + AND {$dbprefix}questions.sid=$surveyid"; +$adump = BuildCSVFromQuery($aquery); + +//6: Conditions table +$cquery = "SELECT DISTINCT {$dbprefix}conditions.* + FROM {$dbprefix}conditions, {$dbprefix}questions + WHERE {$dbprefix}conditions.qid={$dbprefix}questions.qid + AND {$dbprefix}questions.sid=$surveyid"; +$cdump = BuildCSVFromQuery($cquery); + +//7: Label Sets +$lsquery = "SELECT DISTINCT {$dbprefix}labelsets.lid, label_name, {$dbprefix}labelsets.languages + FROM {$dbprefix}labelsets, {$dbprefix}questions + WHERE ({$dbprefix}labelsets.lid={$dbprefix}questions.lid or {$dbprefix}labelsets.lid={$dbprefix}questions.lid1) + AND type IN ('F', 'H', 'W', 'Z', '1', ':', ';') + AND sid=$surveyid"; +$lsdump = BuildCSVFromQuery($lsquery); + +//8: Labels +$lquery = "SELECT {$dbprefix}labels.lid, {$dbprefix}labels.code, {$dbprefix}labels.title, {$dbprefix}labels.sortorder,{$dbprefix}labels.language,{$dbprefix}labels.assessment_value + FROM {$dbprefix}labels, {$dbprefix}questions + WHERE ({$dbprefix}labels.lid={$dbprefix}questions.lid or {$dbprefix}labels.lid={$dbprefix}questions.lid1) + AND type in ('F', 'W', 'H', 'Z', '1', ':', ';') + AND sid=$surveyid + GROUP BY {$dbprefix}labels.lid, {$dbprefix}labels.code, {$dbprefix}labels.title, {$dbprefix}labels.sortorder,{$dbprefix}labels.language,{$dbprefix}labels.assessment_value"; +$ldump = BuildCSVFromQuery($lquery); + +//9: Question Attributes +$query = "SELECT {$dbprefix}question_attributes.qaid, {$dbprefix}question_attributes.qid, {$dbprefix}question_attributes.attribute, {$dbprefix}question_attributes.value + FROM {$dbprefix}question_attributes + WHERE {$dbprefix}question_attributes.qid in (select qid from {$dbprefix}questions where sid=$surveyid group by qid)"; +$qadump = BuildCSVFromQuery($query); + +//10: Assessments; +$query = "SELECT {$dbprefix}assessments.* + FROM {$dbprefix}assessments + WHERE {$dbprefix}assessments.sid=$surveyid"; +$asdump = BuildCSVFromQuery($query); + +//11: Quota; +$query = "SELECT {$dbprefix}quota.* + FROM {$dbprefix}quota + WHERE {$dbprefix}quota.sid=$surveyid"; +$quotadump = BuildCSVFromQuery($query); + +//12: Quota Members; +$query = "SELECT {$dbprefix}quota_members.* + FROM {$dbprefix}quota_members + WHERE {$dbprefix}quota_members.sid=$surveyid"; +$quotamemdump = BuildCSVFromQuery($query); + +//13: Quota languagesettings +$query = "SELECT {$dbprefix}quota_languagesettings.* + FROM {$dbprefix}quota_languagesettings, {$dbprefix}quota + WHERE {$dbprefix}quota.id = {$dbprefix}quota_languagesettings.quotals_quota_id + AND {$dbprefix}quota.sid=$surveyid"; +$quotalsdump = BuildCSVFromQuery($query); + +$fn = "limesurvey_survey_$surveyid.csv"; + +header("Content-Type: application/download"); +header("Content-Disposition: attachment; filename=$fn"); +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"); +header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); +header("Pragma: cache"); // HTTP/1.0 + +echo $dumphead, $sdump, $gdump, $qdump, $adump, $cdump, $lsdump, $ldump, $qadump, $asdump, $slsdump, $quotadump, $quotamemdump, $quotalsdump."\n"; +exit; +?> diff --git a/include/limesurvey/admin/export_structure_lsrc.php b/include/limesurvey/admin/export_structure_lsrc.php new file mode 100644 index 00000000..e0a3588a --- /dev/null +++ b/include/limesurvey/admin/export_structure_lsrc.php @@ -0,0 +1,170 @@ +\n" + ."\n" + ."\t\n" + ."\t\n" + ."
      " + .$clang->gT("Export Survey")."
      \n" + ."
      " + .$clang->gT("Error")."
      \n" + .$clang->gT("No SID has been provided. Cannot dump survey")."
      \n" + ."
      \n" + ."\t
      \n" + ."\n"; + exit; +} + +$dumphead = "# LimeSurvey Survey Dump\n" + . "# DBVersion $dbversionnumber\n" + . "# This is a dumped survey from the LimeSurvey Script\n" + . "# http://www.limesurvey.org/\n" + . "# Do not change this header!\n"; + +//1: Surveys table +$squery = "SELECT * + FROM {$dbprefix}surveys + WHERE sid=$surveyid"; +$sdump = BuildCSVFromQuery($squery); + +//2: Surveys Languagsettings table +$slsquery = "SELECT * + FROM {$dbprefix}surveys_languagesettings + WHERE surveyls_survey_id=$surveyid"; +$slsdump = BuildCSVFromQuery($slsquery); + +//3: Groups Table +$gquery = "SELECT * + FROM {$dbprefix}groups + WHERE sid=$surveyid + ORDER BY gid"; +$gdump = BuildCSVFromQuery($gquery); + +//4: Questions Table +$qquery = "SELECT * + FROM {$dbprefix}questions + WHERE sid=$surveyid + ORDER BY qid"; +$qdump = BuildCSVFromQuery($qquery); + +//5: Answers table +$aquery = "SELECT {$dbprefix}answers.* + FROM {$dbprefix}answers, {$dbprefix}questions + WHERE {$dbprefix}answers.language={$dbprefix}questions.language + AND {$dbprefix}answers.qid={$dbprefix}questions.qid + AND {$dbprefix}questions.sid=$surveyid"; +$adump = BuildCSVFromQuery($aquery); + +//6: Conditions table +$cquery = "SELECT DISTINCT {$dbprefix}conditions.* + FROM {$dbprefix}conditions, {$dbprefix}questions + WHERE {$dbprefix}conditions.qid={$dbprefix}questions.qid + AND {$dbprefix}questions.sid=$surveyid"; +$cdump = BuildCSVFromQuery($cquery); + +//7: Label Sets +$lsquery = "SELECT DISTINCT {$dbprefix}labelsets.lid, label_name, {$dbprefix}labelsets.languages + FROM {$dbprefix}labelsets, {$dbprefix}questions + WHERE ({$dbprefix}labelsets.lid={$dbprefix}questions.lid or {$dbprefix}labelsets.lid={$dbprefix}questions.lid1) + AND type IN ('F', 'H', 'W', 'Z', '1', ':', ';') + AND sid=$surveyid"; +$lsdump = BuildCSVFromQuery($lsquery); + +//8: Labels +$lquery = "SELECT {$dbprefix}labels.lid, {$dbprefix}labels.code, {$dbprefix}labels.title, {$dbprefix}labels.sortorder,{$dbprefix}labels.language + FROM {$dbprefix}labels, {$dbprefix}questions + WHERE ({$dbprefix}labels.lid={$dbprefix}questions.lid or {$dbprefix}labels.lid={$dbprefix}questions.lid1) + AND type in ('F', 'W', 'H', 'Z', '1', ':', ';') + AND sid=$surveyid + GROUP BY {$dbprefix}labels.lid, {$dbprefix}labels.code, {$dbprefix}labels.title, {$dbprefix}labels.sortorder,{$dbprefix}labels.language"; +$ldump = BuildCSVFromQuery($lquery); + +//9: Question Attributes +$query = "SELECT DISTINCT {$dbprefix}question_attributes.* + FROM {$dbprefix}question_attributes, {$dbprefix}questions + WHERE {$dbprefix}question_attributes.qid={$dbprefix}questions.qid + AND {$dbprefix}questions.sid=$surveyid"; +$qadump = BuildCSVFromQuery($query); + +//10: Assessments; +$query = "SELECT {$dbprefix}assessments.* + FROM {$dbprefix}assessments + WHERE {$dbprefix}assessments.sid=$surveyid"; +$asdump = BuildCSVFromQuery($query); + +//11: Quota; +$query = "SELECT {$dbprefix}quota.* + FROM {$dbprefix}quota + WHERE {$dbprefix}quota.sid=$surveyid"; +$quotadump = BuildCSVFromQuery($query); + +//12: Quota Members; +$query = "SELECT {$dbprefix}quota_members.* + FROM {$dbprefix}quota_members + WHERE {$dbprefix}quota_members.sid=$surveyid"; +$quotamemdump = BuildCSVFromQuery($query); + +$fn = "limesurvey_survey_$surveyid.csv"; + +//header("Content-Type: application/download"); +//header("Content-Disposition: attachment; filename=$fn"); +//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"); +//header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); +//header("Pragma: cache"); // HTTP/1.0 + +include("../config.php"); +include("remotecontrol/lsrc.config.php"); + +$lsrcString = $dumphead. $sdump. $gdump. $qdump. $adump. $cdump. $lsdump. $ldump. $qadump. $asdump. $slsdump. $quotadump. $quotamemdump."\n"; + +//Select title as Filename and save +$surveyTitleSql = "SELECT surveyls_title + FROM {$dbprefix}surveys_languagesettings + WHERE surveyls_survey_id=$surveyid"; +$surveyTitleRs = db_execute_assoc($surveyTitleSql); +$surveyTitle = $surveyTitleRs->FetchRow(); +file_put_contents("remotecontrol/".$coreDir.$surveyTitle['surveyls_title'].".csv",$lsrcString); + +header("Location: $scriptname?sid=$surveyid"); +exit; +?> diff --git a/include/limesurvey/admin/export_structure_quexml.php b/include/limesurvey/admin/export_structure_quexml.php index 3378aed8..f83c5f77 100644 --- a/include/limesurvey/admin/export_structure_quexml.php +++ b/include/limesurvey/admin/export_structure_quexml.php @@ -416,7 +416,7 @@ while ($Row = $QueryResult->FetchRow()) $question->append_child($response); break; case "S": //SHORT FREE TEXT - $response->append_child(create_free("text",get_length($qid,"maximum_chars","240"),"")); + $response->append_child(create_free("text",get_length($qid,"text_input_width","240"),"")); $question->append_child($response); break; case "T": //LONG FREE TEXT @@ -502,7 +502,8 @@ while ($Row = $QueryResult->FetchRow()) $response->set_attribute("varName",'datecomp'); $response->append_child(create_free("text",16,"")); $question->append_child($response); - + + $questionnaire->append_child($section); } diff --git a/include/limesurvey/admin/exportresults.php b/include/limesurvey/admin/exportresults.php index bdfafb5d..2493bd24 100644 --- a/include/limesurvey/admin/exportresults.php +++ b/include/limesurvey/admin/exportresults.php @@ -1,1305 +1,1485 @@ -FetchRow(); - -if ($sumrows5['export'] != "1" && $_SESSION['USER_RIGHT_SUPERADMIN'] != 1) -{ - exit; -} - -include_once("login_check.php"); -include_once(dirname(__FILE__)."/classes/pear/Spreadsheet/Excel/Writer.php"); -include_once(dirname(__FILE__)."/classes/tcpdf/extensiontcpdf.php"); - -$surveybaselang=GetBaseLanguageFromSurveyID($surveyid); -$exportoutput=""; - -if (!$style) -{ - // Get info about the survey - $thissurvey=getSurveyInfo($surveyid); - - // First add the standard fields - $excesscols[]="id"; - $excesscols[]='completed'; - if ($thissurvey["datestamp"]=='Y') {$excesscols[]='datestamp';} - if ($thissurvey["ipaddr"]=='Y') {$excesscols[]='ipaddr';} - if ($thissurvey["refurl"]=='Y') {$excesscols[]='refurl';} - - //FIND OUT HOW MANY FIELDS WILL BE NEEDED - FOR 255 COLUMN LIMIT - $query=" SELECT other, q.type, q.gid, q.qid, q.lid, q.lid1 FROM {$dbprefix}questions as q, {$dbprefix}groups as g " - ." where q.gid=g.gid and g.sid=$surveyid and g.language='$surveybaselang' and q.language='$surveybaselang'" - ." order by group_order, question_order"; - - $result=db_execute_assoc($query) or safe_die("Couldn't count fields
      $query
      ".$connect->ErrorMsg()); - while ($rows = $result->FetchRow()) - { - if (($rows['type']=='A') || ($rows['type']=='B')||($rows['type']=='C')||($rows['type']=='M')||($rows['type']=='P')||($rows['type']=='Q')||($rows['type'] == "K") ||($rows['type']=='E')||($rows['type']=='F')||($rows['type']=='H')) - { - $detailquery="select code from {$dbprefix}answers where qid=".$rows['qid']." and language='$surveybaselang' order by sortorder,code"; - $detailresult=db_execute_assoc($detailquery) or safe_die("Couldn't find detailfields
      $detailquery
      ".$connect->ErrorMsg()); - while ($detailrows = $detailresult->FetchRow()) - { - $excesscols[]=$surveyid.'X'.$rows['gid']."X".$rows['qid'].$detailrows['code']; - if ($rows['type']=='P') - { - $excesscols[]=$surveyid.'X'.$rows['gid']."X".$rows['qid'].$detailrows['code']."comment"; - } - } - } - elseif ($rows['type']=='R') - { - $detailquery="select code from {$dbprefix}answers where qid=".$rows['qid']." and language='$surveybaselang' order by sortorder,code"; - $detailresult=db_execute_assoc($detailquery) or safe_die("Couldn't find detailfields
      $detailquery
      ".$connect->ErrorMsg()); - $i=1; - while ($detailrows = $detailresult->FetchRow()) - { - $excesscols[]=$surveyid.'X'.$rows['gid']."X".$rows['qid'].$i; - $i++; - } - } - elseif ($rows['type']=='1') - { - // $detailquery="select code from {$dbprefix}answers where qid=".$rows['qid']." and language='$surveybaselang' order by sortorder,code"; - $detailquery="select a.code, l.lid from {$dbprefix}answers as a, {$dbprefix}labels as l where qid=".$rows['qid']." AND (l.lid =".$rows['lid'].") and a.language='$surveybaselang' group by a.code order by a.code "; - $detailresult=db_execute_assoc($detailquery) or safe_die("Couldn't find detailfields
      $detailquery
      ".$connect->ErrorMsg()); - $i=0; - while ($detailrows = $detailresult->FetchRow()) - { - // $excesscols[]=$surveyid.'X'.$rows['gid']."X".$rows['qid'].$rows['code'].$detailrows['code']."#".$i; - $excesscols[]=$surveyid.'X'.$rows['gid']."X".$rows['qid'].$detailrows['code']."#0"; - $i++; - } - // second scale - $detailquery="select a.code, l.lid from {$dbprefix}answers as a, {$dbprefix}labels as l where qid=".$rows['qid']." AND (l.lid =".$rows['lid1'].") and a.language='$surveybaselang' group by a.code order by a.code "; - $detailresult=db_execute_assoc($detailquery) or safe_die("Couldn't find detailfields
      $detailquery
      ".$connect->ErrorMsg()); - $i=0; - while ($detailrows = $detailresult->FetchRow()) - { - // $excesscols[]=$surveyid.'X'.$rows['gid']."X".$rows['qid'].$rows['code'].$detailrows['code']."#".$i; - $excesscols[]=$surveyid.'X'.$rows['gid']."X".$rows['qid'].$detailrows['code']."#1"; - $i++; - } - - } - else - { - $excesscols[]=$surveyid.'X'.$rows['gid']."X".$rows['qid']; - } - if ($rows['other']=="Y" && ($rows['type']=='M' || $rows['type']=='!'|| $rows['type']=='L' || $rows['type']=='P' || $rows['type'] == "Z" || $rows['type'] == "W")) - { - $excesscols[]=$surveyid.'X'.$rows['gid']."X".$rows['qid']."other"; - } - if ($rows['other']=="Y" && ($rows['type']=='P' )) - { - $excesscols[]=$surveyid.'X'.$rows['gid']."X".$rows['qid']."othercomment"; - } - if ($rows['type']=='O' ) - { - $excesscols[]=$surveyid.'X'.$rows['gid']."X".$rows['qid']."comment"; - } - - } - - - - $afieldcount = count($excesscols); - $exportoutput .= "\n" - ."\t\n"; - $exportoutput .= browsemenubar(); - $exportoutput .= "\n"; - $exportoutput .= "
      \n" - ."
      \n" - ."" - .""; - $query="SELECT private FROM {$dbprefix}surveys WHERE sid=$surveyid"; //Find out if tokens are used - $result=db_execute_assoc($query) or safe_die("Couldn't get privacy data
      $query
      ".$connect->ErrorMsg()); - while ($rows = $result->FetchRow()) {$surveyprivate=$rows['private'];} - if ($surveyprivate == "N") - { - $query=db_select_tables_like("{$dbprefix}tokens_$surveyid"); //SEE IF THERE IS AN ASSOCIATED TOKENS TABLE - $result=$connect->Execute($query) or safe_die("Couldn't get table list
      $query
      ".$connect->ErrorMsg()); - $tablecount=$result->RecordCount(); - } - $exportoutput .= "\n"; - if (isset($tablecount) && $tablecount > 0) //Do second column - { - //OPTIONAL EXTRAS (FROM TOKENS TABLE) - if ($tablecount > 0) - { - $exportoutput .= ""; - } - } - $exportoutput .= "\n" - ."
      \n" - ."\n" - ."\t\n" - ."\t\n" - ."\t\n" - ."\t\t\n" - ."\t\n" - ."\t\n" - ."\t\n" - ."\t\t\n" - ."\t\n" - ."\t\n" - ."\t\n" - ."\t\t\n" - ."\t\n" - ."\t\n" - ."\t\n" - ."\t\t\n" - ."\t\n" - ."\t\n" - ."\t\t\n" - ."\t\n" - ."
      " - ."" - .$clang->gT("Export Responses"); - if (isset($_POST['sql'])) {$exportoutput .= " - ".$clang->gT("Filtered from Statistics Script");} - if (returnglobal('id')<>'') {$exportoutput .= " - ".$clang->gT("Single Response");} - - if (incompleteAnsFilterstate() === true) - { - $selecthide="selected='selected'"; - $selectshow=""; - } - else - { - $selecthide=""; - $selectshow="selected='selected'"; - } - - $exportoutput .= " ($afieldcount ".$clang->gT("Columns").")
      " - .$clang->gT("Questions")."
      \n" - ."\t\t\t" - ."
      \n" - ."\t\t\t" - ."
      \n" - ."\t\t\t" - ."
      \n" - ."\t\t\t  ".$clang->gT("Filter incomplete answers")." \n" - ."\t\t
      " - .$clang->gT("Answers")."
      \n" - ."\t\t\t" - ."
      \n" - ."\t\t\t" - ."\n" - ."\t\t
      " - .$clang->gT("Format")."
      \n" - ."\t\t\t" - ."
      \n" - ."\t\t\t" - ."
      \n" - ."\t\t\t" - ."
      \n"; - if(isset($usepdfexport) && $usepdfexport == 1) - { - $exportoutput .= "\t\t\t" - ."\n"; - } - $exportoutput .="\t\t
      \n" - ."\t\t\t\n" - ."\t\t\t\n" - ."\t\t
      \n"; - if (isset($_POST['sql'])) - { - $exportoutput .= "\t\n"; - } - if (returnglobal('id')<>'') - { - $exportoutput .= "\t\n"; - } - $exportoutput .= "
      \n" - ."
      \n" - ."" - ."\t\n" - ."\t\t\n" - ."\t\n" - ."\t\n" - ."\t\t\n" - ."\t\n" - ."\t\n" - ."\t\t\n" - ."\t\n" - ."
      " - .$clang->gT("Column Control")."\n" - ."\t\t
      \n" - ."\t\t\t".$clang->gT("Choose Columns").":\n" - ."\t\t"; - if ($afieldcount > 255) - { - $exportoutput .= "\t\t\t".$clang->gT("Help").""; - } - else - { - $exportoutput .= "\t\t\t".$clang->gT("Help").""; - } - $exportoutput .= "\t\t
      \n" - ."\t\t\t
      \n" - ."
      \n" - ."" - ."\t\n" - ."\t\t\n" - ."\t\n" - ."\t\n" - ."\t\t\n" - ."\t\n" - ."\t\n" - ."\t\t\n" - ."\t\n" - ."
      " - .$clang->gT("Token Control")."\n" - ."\t\t
      \n" - .$clang->gT("Choose Token Fields").":" - ."\t\t
      " - ."".$clang->gT("Help")."

      \n" - ."" - ."
      \n" - ."" - ."
      \n" - ."" - ."
      \n" - ."" - ."
      \n"; - $query = "SELECT * FROM {$dbprefix}tokens_$surveyid"; //SEE IF TOKENS TABLE HAS ATTRIBUTE FIELDS - $result = db_select_limit_assoc($query, 1) or safe_die ($query."
      ".$connect->ErrorMsg()); - $rowcount = $result->FieldCount(); - if ($rowcount > 7) - { - $exportoutput .= "" - ."
      \n" - ."" - ."
      \n"; - } - $exportoutput .= "\t\t
      " - ."

      \n" - ."\t
      \n"; - return; -} - -//HERE WE EXPORT THE ACTUAL RESULTS - -//sendcacheheaders(); // sending "cache headers" before this permit us to send something else than a "text/html" content-type -switch ( $_POST["type"] ) { // this is a step to register_globals = false ;c) - case "doc": - header("Content-Disposition: attachment; filename=results-survey".$surveyid.".doc"); - header("Content-type: application/vnd.ms-word"); - $separator="\t"; - break; - case "xls": - - $workbook = new Spreadsheet_Excel_Writer(); - $workbook->setVersion(8); - // Inform the module that our data will arrive as UTF-8. - // Set the temporary directory to avoid PHP error messages due to open_basedir restrictions and calls to tempnam("", ...) - if (!empty($tempdir)) { - $workbook->setTempDir($tempdir); - } - $workbook->send('results-survey'.$surveyid.'.xls'); - // Creating the first worksheet - $sheet =& $workbook->addWorksheet('Survey Results'); - $sheet->setInputEncoding('utf-8'); - $separator="~|"; - break; - case "csv": - header("Content-Disposition: attachment; filename=results-survey".$surveyid.".csv"); - header("Content-type: text/comma-separated-values; charset=UTF-8"); - $separator=","; - break; - case "pdf": - $pdf = new PDF('P','mm','A4'); - $pdf->SetFont($pdfdefaultfont,'',$pdffontsize); - $pdf->AddPage(); - $pdf->intopdf("PDF Export ".date("Y.m.d-H:i",time())); - $query="SELECT * FROM {$dbprefix}surveys_languagesettings WHERE surveyls_survey_id=".$surveyid; - $result=db_execute_assoc($query) or safe_die("Couldn't get privacy data
      $query
      ".$connect->ErrorMsg()); - while ($row = $result->FetchRow()) - { - $pdf->intopdf($clang->gT("General information in language: ").getLanguageNameFromCode($row['surveyls_language']),'B'); - $pdf->ln(); - $pdf->titleintopdf($row['surveyls_title'],$row['surveyls_description']); - $surveyname=$row['surveyls_title']; - } - $pdf->AddPage(); - $separator="\t"; - break; - default: - header("Content-Disposition: attachment; filename=results-survey".$surveyid.".csv"); - header("Content-type: text/comma-separated-values; charset=UTF-8"); - $separator=","; - break; -} -Header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); - -// Export Language is set by default to surveybaselang -// * the explang language code is used in SQL queries -// * the alang object is used to translate headers and hardcoded answers -// In the future it might be possible to 'post' the 'export language' from -// the exportresults form -$explang = $surveybaselang; -$elang=new limesurvey_lang($explang); - -//STEP 1: First line is column headings - -$fieldmap=createFieldMap($surveyid); - -// We make the fieldmap alot more accesible by using the SGQA identifier as key -// so we do not need ArraySearchByKey later -foreach ($fieldmap as $fieldentry) -{ - $outmap[]=$fieldentry['fieldname']; - $outmap[$fieldentry['fieldname']]['type']= $fieldentry['type']; - $outmap[$fieldentry['fieldname']]['sid']= $fieldentry['sid']; - $outmap[$fieldentry['fieldname']]['gid']= $fieldentry['gid']; - $outmap[$fieldentry['fieldname']]['qid']= $fieldentry['qid']; - $outmap[$fieldentry['fieldname']]['aid']= $fieldentry['aid']; - if (isset($fieldentry['lid1'])) {$outmap[$fieldentry['fieldname']]['lid1']= $fieldentry['lid1'];} - if ($fieldentry['qid']!='') - { - $qq = "SELECT lid, other FROM {$dbprefix}questions WHERE qid={$fieldentry['qid']} and language='$surveybaselang'"; - $qr = db_execute_assoc($qq) or safe_die("Error selecting type and lid from questions table.
      ".$qq."
      ".$connect->ErrorMsg()); - while ($qrow = $qr->FetchRow()) - { - $outmap[$fieldentry['fieldname']]['lid']=$qrow['lid']; - $outmap[$fieldentry['fieldname']]['other']=$qrow['other']; - } - } - -} -//Get the fieldnames from the survey table for column headings -$surveytable = "{$dbprefix}survey_$surveyid"; -if (isset($_POST['colselect'])) -{ - $selectfields=""; - foreach($_POST['colselect'] as $cs) - { - if ($cs != 'completed') - { - $selectfields.= db_quote_id($cs).", "; - } - else - { - $selectfields.= "CASE WHEN $surveytable.submitdate IS NULL THEN 'N' ELSE 'Y' END AS completed, "; - } - } - $selectfields = mb_substr($selectfields, 0, strlen($selectfields)-2); -} -else -{ - $selectfields="$surveytable.*, CASE WHEN $surveytable.submitdate IS NULL THEN 'N' ELSE 'Y' END AS completed"; -} - -$dquery = "SELECT $selectfields"; -if (isset($_POST['first_name']) && $_POST['first_name']=="on") -{ - $dquery .= ", {$dbprefix}tokens_$surveyid.firstname"; -} -if (isset($_POST['last_name']) && $_POST['last_name']=="on") -{ - $dquery .= ", {$dbprefix}tokens_$surveyid.lastname"; -} -if (isset($_POST['email_address']) && $_POST['email_address']=="on") -{ - $dquery .= ", {$dbprefix}tokens_$surveyid.email"; -} -if (isset($_POST['token']) && $_POST['token']=="on") -{ - $dquery .= ", {$dbprefix}tokens_$surveyid.token"; -} -if (isset($_POST['attribute_1']) && $_POST['attribute_1']=="on") -{ - $dquery .= ", {$dbprefix}tokens_$surveyid.attribute_1"; -} -if (isset($_POST['attribute_2']) && $_POST['attribute_2']=="on") -{ - $dquery .= ", {$dbprefix}tokens_$surveyid.attribute_2"; -} -$dquery .= " FROM $surveytable"; -if ((isset($_POST['first_name']) && $_POST['first_name']=="on") || (isset($_POST['token']) && $_POST['token']=="on") || (isset($_POST['last_name']) && $_POST['last_name']=="on") || (isset($_POST['attribute_1']) && $_POST['attribute_1']=="on") || (isset($_POST['attribute_2']) && $_POST['attribute_2']=="on") || (isset($_POST['email_address']) && $_POST['email_address']=="on")) -{ - $dquery .= "" - . " LEFT OUTER JOIN {$dbprefix}tokens_$surveyid" - . " ON $surveytable.token = {$dbprefix}tokens_$surveyid.token"; -} -if (incompleteAnsFilterstate() === true) -{ - $dquery .= " WHERE $surveytable.submitdate is not null "; -} -$dquery .=" ORDER BY id"; - -$dresult = db_select_limit_assoc($dquery, 1) or safe_die($clang->gT("Error")." getting results
      $dquery
      ".$connect->ErrorMsg()); -$fieldcount = $dresult->FieldCount(); -$firstline=""; -$faid=""; -for ($i=0; $i<$fieldcount; $i++) -{ - //Iterate through column names and output headings - $field=$dresult->FetchField($i); - $fieldinfo=$field->name; - - if ($fieldinfo == "lastname") - { - if ($type == "csv") {$firstline .= "\"".$elang->gT("Last Name")."\"$separator";} - else {$firstline .= $elang->gT("Last Name")."$separator";} - } - elseif ($fieldinfo == "firstname") - { - if ($type == "csv") {$firstline .= "\"".$elang->gT("First Name")."\"$separator";} - else {$firstline .= $elang->gT("First Name")."$separator";} - } - elseif ($fieldinfo == "email") - { - if ($type == "csv") {$firstline .= "\"".$elang->gT("Email Address")."\"$separator";} - else {$firstline .= $elang->gT("Email Address")."$separator";} - } - elseif ($fieldinfo == "token") - { - if ($type == "csv") {$firstline .= "\"".$elang->gT("Token")."\"$separator";} - else {$firstline .= $elang->gT("Token")."$separator";} - } - elseif ($fieldinfo == "attribute_1") - { - if ($type == "csv") {$firstline .= "\"attr1\"$separator";} - else {$firstline .= $elang->gT("Attribute 1")."$separator";} - } - elseif ($fieldinfo == "attribute_2") - { - if ($type == "csv") {$firstline .= "\"attr2\"$separator";} - else {$firstline .= $elang->gT("Attribute 2")."$separator";} - } - elseif ($fieldinfo == "id") - { - if ($type == "csv") {$firstline .= "\"id\"$separator";} - else {$firstline .= "id$separator";} - } - elseif ($fieldinfo == "datestamp") - { - if ($type == "csv") {$firstline .= "\"".$elang->gT("Time Submitted")."\"$separator";} - else {$firstline .= $elang->gT("Time Submitted")."$separator";} - } - elseif ($fieldinfo == "completed") - { - if ($type == "csv") {$firstline .= "\"".$elang->gT("Completed")."\"$separator";} - else {$firstline .= $elang->gT("Completed")."$separator";} - } - elseif ($fieldinfo == "ipaddr") - { - if ($type == "csv") {$firstline .= "\"".$elang->gT("IP-Address")."\"$separator";} - else {$firstline .= $elang->gT("IP-Address")."$separator";} - } - elseif ($fieldinfo == "refurl") - { - if ($type == "csv") {$firstline .= "\"".$elang->gT("Referring URL")."\"$separator";} - else {$firstline .= $elang->gT("Referring URL")."$separator";} - } - else - { - //Data fields! - //$fielddata=arraySearchByKey($fieldinfo, $fieldmap, "fieldname", 1); - $fielddata=$outmap[$fieldinfo]; - - $fqid=$fielddata['qid']; - $ftype=$fielddata['type']; - $fsid=$fielddata['sid']; - $fgid=$fielddata['gid']; - $faid=$fielddata['aid']; - - if ($style == "abrev") - { - $qq = "SELECT question FROM {$dbprefix}questions WHERE qid=$fqid and language='$explang'"; - $qr = db_execute_assoc($qq); - while ($qrow=$qr->FetchRow()) - {$qname=$qrow['question'];} - $qname=strip_tags_full($qname); - $qname=mb_substr($qname, 0, 15).".."; - $firstline = str_replace("\n", "", $firstline); - $firstline = str_replace("\r", "", $firstline); - if ($type == "csv") {$firstline .= "\"$qname";} - else {$firstline .= "$qname";} - if (isset($faid)) {$firstline .= " [{$faid}]"; $faid="";} - if ($type == "csv") {$firstline .= "\"";} - $firstline .= "$separator"; - } - else - { - $qq = "SELECT question, type, other, title FROM {$dbprefix}questions WHERE qid=$fqid AND language='$explang' ORDER BY gid, title"; //get the question - $qr = db_execute_assoc($qq) or safe_die ("ERROR:
      ".$qq."
      ".$connect->ErrorMsg()); - while ($qrow=$qr->FetchRow()) - { - if ($style == "headcodes"){$fquest=$qrow['title'];} - else {$fquest=$qrow['question'];} - } - switch ($ftype) - { - case "R": //RANKING TYPE - $fquest .= " [".$elang->gT("Ranking")." $faid]"; - break; - case "L": - case "!": - case "W": - case "Z": - if ($faid == "other") { - $fquest .= " [".$elang->gT("Other")."]"; - } - break; - case "O": //DROPDOWN LIST WITH COMMENT - if ($faid == "comment") - { - $fquest .= " - Comment"; - } - break; - case "M": //multioption - if ($faid == "other") - { - $fquest .= " [".$elang->gT("Other")."]"; - } - else - { - if ($answers == "short") { - $fquest .= " [$faid]"; //Show only the code - } - else - { - $lq = "SELECT * FROM {$dbprefix}answers WHERE qid=$fqid AND code = '$faid' AND language = '$explang'"; - $lr = db_execute_assoc($lq); - while ($lrow = $lr->FetchRow()) - { - $fquest .= " [".strip_tags_full($lrow['answer'])."]"; - } - } - } - break; - case "P": //multioption with comment - if (mb_substr($faid, -7, 7) == "comment") - { - $faid=mb_substr($faid, 0, -7); - $comment=true; - } - if ($faid == "other") - { - $fquest .= " [".$elang->gT("Other")."]"; - } - else - { - if ($answers == "short") { - $fquest .= " [$faid]"; //Show only the code - } - else - { - $lq = "SELECT * FROM {$dbprefix}answers WHERE qid=$fqid AND code = '$faid' AND language = '$explang'"; - $lr = db_execute_assoc($lq); - while ($lrow = $lr->FetchRow()) - { - $fquest .= " [".strip_tags_full($lrow['answer'])."]"; - } - } - } - if (isset($comment) && $comment == true) {$fquest .= " - comment"; $comment=false;} - break; - case "A": - case "B": - case "C": - case "E": - case "F": - case "H": - case "K": - case "Q": - case "^": - if ($answers == "short") { - $fquest .= " [$faid]"; - } - else - { - $lq = "SELECT * FROM {$dbprefix}answers WHERE qid=$fqid AND code= '$faid' AND language = '$explang'"; - $lr = db_execute_assoc($lq); - while ($lrow=$lr->FetchRow()) - { - $fquest .= " [".strip_tags_full($lrow['answer'])."]"; - } - } - break; - case "1": // multi scale Headline - $flid=$fielddata['lid']; - $flid1=$fielddata['lid1']; - if (substr($fieldinfo,-1) == '0') - { - $strlabel = "1"; - $lq = "select a.*, l.* from {$dbprefix}answers as a, {$dbprefix}labels as l where a.code='$faid' and qid=$fqid AND l.lid = $flid AND a.language='$surveybaselang' group by l.lid"; - } - else - { - $strlabel = "2"; - $lq = "select a.*, l.* from {$dbprefix}answers as a, {$dbprefix}labels as l where a.code='$faid' and qid=$fqid AND l.lid = $flid1 AND a.language='$surveybaselang' group by l.lid"; - } - $lr = db_execute_assoc($lq); - $j=0; - while ($lrow=$lr->FetchRow()) - { - $fquest .= " [".strip_tags_full($lrow['answer'])."][".strip_tags_full($strlabel).". label]"; - $j++; - } - - break; - - } - $fquest=strip_tags_full($fquest); - - $fquest = str_replace("\n", " ", $fquest); - $fquest = str_replace("\r", "", $fquest); - if ($type == "csv") - { - $firstline .="\"$fquest\"$separator"; - } - else - { - $firstline .= "$fquest $separator"; - } - } - } -} -if ($type == "csv") { $firstline = mb_substr(trim($firstline),0,strlen($firstline)-1);} -else -{ - $firstline = trim($firstline); -} - -$firstline .= "\n"; - -if ($type == "doc" || $type == "pdf") -{ - $flarray=explode($separator, $firstline); - -} -else -if ($type == "xls") -{ - //var_dump ($firstline); - $flarray=explode($separator, $firstline); - $fli=0; - foreach ($flarray as $fl) - { - $sheet->write(0,$fli,$fl); - $fli++; - } - //print_r($fieldmap); -} -else -{ - $exportoutput .= $firstline; //Sending the header row -} - - -//Now dump the data -if ((isset($_POST['first_name']) && $_POST['first_name']=="on") || (isset($_POST['token']) && $_POST['token']=="on") || (isset($_POST['last_name']) && $_POST['last_name']=="on") || (isset($_POST['attribute_1']) && $_POST['attribute_1']=="on") || (isset($_POST['attribute_2']) && $_POST['attribute_2'] == "on") || (isset($_POST['email_address']) && $_POST['email_address'] == "on")) -{ - $dquery = "SELECT $selectfields"; - if (isset($_POST['first_name']) && $_POST['first_name']=="on") - { - $dquery .= ", {$dbprefix}tokens_$surveyid.firstname"; - } - if (isset($_POST['last_name']) && $_POST['last_name']=="on") - { - $dquery .= ", {$dbprefix}tokens_$surveyid.lastname"; - } - if (isset($_POST['email_address']) && $_POST['email_address']=="on") - { - $dquery .= ", {$dbprefix}tokens_$surveyid.email"; - } - if (isset($_POST['token']) && $_POST['token']=="on") - { - $dquery .= ", {$dbprefix}tokens_$surveyid.token"; - } - if (isset($_POST['attribute_1']) && $_POST['attribute_1']=="on") - { - $dquery .= ", {$dbprefix}tokens_$surveyid.attribute_1"; - } - if (isset($_POST['attribute_2']) && $_POST['attribute_2']=="on") - { - $dquery .= ", {$dbprefix}tokens_$surveyid.attribute_2"; - } - $dquery .= " FROM $surveytable " - . "LEFT OUTER JOIN {$dbprefix}tokens_$surveyid " - . "ON $surveytable.token={$dbprefix}tokens_$surveyid.token "; - if (incompleteAnsFilterstate() === true) - { - $dquery .= " WHERE $surveytable.submitdate is not null "; - } -} -else // this applies for exporting everything -{ - $dquery = "SELECT $selectfields FROM $surveytable "; - - if (incompleteAnsFilterstate() === true) - { - $dquery .= " WHERE $surveytable.submitdate is not null "; - } -} - -if (isset($_POST['sql'])) //this applies if export has been called from the statistics package -{ - if ($_POST['sql'] != "NULL") - { - if (incompleteAnsFilterstate() === true) {$dquery .= " AND ".stripcslashes($_POST['sql'])." ";} - else {$dquery .= "WHERE ".stripcslashes($_POST['sql'])." ";} - } -} -if (isset($_POST['answerid']) && $_POST['answerid'] != "NULL") //this applies if export has been called from single answer view -{ - if (incompleteAnsFilterstate() === true) {$dquery .= " AND $surveytable.id=".stripcslashes($_POST['answerid'])." ";} - else {$dquery .= "WHERE $surveytable.id=".stripcslashes($_POST['answerid'])." ";} -} - - -$dquery .= "ORDER BY $surveytable.id"; -if ($answers == "short") //Nice and easy. Just dump the data straight -{ - $dresult = db_execute_assoc($dquery); - $rowcounter=0; - while ($drow = $dresult->FetchRow()) - { - $rowcounter++; - if ($type == "csv") - { - $exportoutput .= "\"".implode("\"$separator\"", str_replace("\"", "\"\"", str_replace("\r\n", " ", $drow))) . "\"\n"; //create dump from each row - } - elseif ($type == "xls") - { - $colcounter=0; - foreach ($drow as $rowfield) - { - $rowfield=str_replace("?","-",$rowfield); - $sheet->write($rowcounter,$colcounter,mb_convert_encoding($rowfield, "ISO-8859-1", "UTF-8")); - $colcounter++; - } - } - else if($type == "pdf") - { - $pdf->titleintopdf($clang->gT("New Record")); - foreach ($drow as $rowfield) - { - $rowfield=str_replace("?","-",$rowfield); - $pdfstring .=mb_convert_encoding($rowfield, "ISO-8859-1", "UTF-8")." | "; - } - $pdf->intopdf($pdfstring); - } - else - { - $exportoutput .= implode($separator, str_replace("\r\n", " ", $drow)) . "\n"; //create dump from each row - } - } -} -elseif ($answers == "long") //vollständige Antworten gewählt -{ -// echo $dquery; - $labelscache=array(); - $dresult = db_execute_num($dquery) or safe_die("ERROR: $dquery -".$connect->ErrorMsg()); - $fieldcount = $dresult->FieldCount(); - $rowcounter=0; - - while ($drow = $dresult->FetchRow()) - { - $rowcounter++; - if ($type == "pdf") - { - //$pdf->Write (5,$exportoutput); - if($rowcounter != 1) - { - $pdf->AddPage(); - } - $pdf->Cell(0,10,$elang->gT('NEW RECORD')." ".$rowcounter,1,1); - } - - if ($type == "doc") - { - $exportoutput .= "\n\n\n".$elang->gT('NEW RECORD')."\n"; - } - for ($i=0; $i<$fieldcount; $i++) //For each field, work out the QID - { - $fqid=0; // By default fqid is set to zero - $field=$dresult->FetchField($i); - $fieldinfo=$field->name; - if ($fieldinfo != "startlanguage" && $fieldinfo != "id" && $fieldinfo != "datestamp" && $fieldinfo != "ipaddr" && $fieldinfo != "refurl" && $fieldinfo != "token" && $fieldinfo != "firstname" && $fieldinfo != "lastname" && $fieldinfo != "email" && $fieldinfo != "attribute_1" && $fieldinfo != "attribute_2" && $fieldinfo != "completed") - { -// $fielddata=arraySearchByKey($fieldinfo, $fieldmap, "fieldname", 1); - $fielddata=$outmap[$fieldinfo]; - $fqid=$fielddata['qid']; - $ftype=$fielddata['type']; - $fsid=$fielddata['sid']; - $fgid=$fielddata['gid']; - $faid=$fielddata['aid']; - $flid=$fielddata['lid']; - if (isset($fielddata['lid1'])) {$flid1=$fielddata['lid1'];} - - $fother=$fielddata['other']; - if ($type == "doc" || $type == "pdf") - { - $ftitle=$flarray[$i]; - } - } - else - { - $fsid=""; $fgid=""; - if ($type == "doc" || $type == "pdf") - { - switch($fieldinfo) - { - case "datestamp": - $ftitle=$elang->gT("Time Submitted").":"; - break; - case "ipaddr": - $ftitle=$elang->gT("IP Address").":"; - break; - case "completed": - $ftitle=$elang->gT("Completed").":"; - break; - case "refurl": - $ftitle=$elang->gT("Referring URL").":"; - break; - case "firstname": - $ftitle=$elang->gT("First Name").":"; - break; - case "lastname": - $ftitle=$elang->gT("Last Name").":"; - break; - case "email": - $ftitle=$elang->gT("Email").":"; - break; - case "id": - $ftitle=$elang->gT("ID").":"; - break; - case "token": - $ftitle=$elang->gT("Token").":"; - break; - case "tid": - $ftitle=$elang->gT("Token ID").":"; - break; - case "attribute_1": - $ftitle=$elang->gT("Attribute 1").":"; - break; - case "attribute_2": - $ftitle=$elang->gT("Attribute 2").":"; - break; - case "startlanguage": - $ftitle=$elang->gT("Language").":"; - break; - default: - $fielddata=$outmap[$fieldinfo]; -// $fielddata=arraySearchByKey($fieldinfo, $fieldmap, "fieldname", 1); - if (isset($fielddata['title']) && !isset($ftitle)) {$ftitle=$fielddata['title'].":";} - } // switch - } - } - if ($fqid == 0) - { - $ftype = "-"; // This is set if it not a normal answer field, but something like tokenID, First Name etc - } - if ($type == "csv") {$exportoutput .= "\"";} - if ($type == "doc") {$exportoutput .= "\n$ftitle\n\t";} - if ($type == "pdf"){ $pdf->intopdf($ftitle);} - switch ($ftype) - { - case "-": //JASONS SPECIAL TYPE - $exportoutput .= $drow[$i]; - if($type == "pdf"){$pdf->intopdf($drow[$i]);} - break; - case "R": //RANKING TYPE - $lq = "SELECT * FROM {$dbprefix}answers WHERE qid=$fqid AND language='$explang' AND code = ?"; - $lr = db_execute_assoc($lq, array($drow[$i])); - while ($lrow = $lr->FetchRow()) - { - $exportoutput .= strip_tags_full($lrow['answer']); - if($type == "pdf"){$pdf->intopdf(strip_tags_full($lrow['answer']));} - } - break; - case "1": - if (substr($fieldinfo,-1) == 0) - { - $lq = "select a.*, l.*, l.code as lcode from {$dbprefix}answers as a, {$dbprefix}labels as l where qid=$fqid AND l.lid =$flid AND a.language='$explang' AND l.code = ? group by l.lid"; - } - else - { - $lq = "select a.*, l.*, l.code as lcode from {$dbprefix}answers as a, {$dbprefix}labels as l where qid=$fqid AND l.lid =$flid1 AND a.language='$explang' AND l.code = ? group by l.lid"; - } - $lr = db_execute_assoc($lq, array($drow[$i])) or safe_die($lq."
      ERROR:
      ".$connect->ErrorMsg()); - while ($lrow = $lr->FetchRow()) - { - $exportoutput .= strip_tags_full($lrow['lcode']); - if($type == "pdf"){$pdf->intopdf(strip_tags_full($lrow['lcode']));} - } - break; - case "L": //DROPDOWN LIST - case "!": - if (mb_substr($fieldinfo, -5, 5) == "other") - { - $exportoutput .= strip_tags_full($drow[$i]); - if($type == "pdf"){$pdf->intopdf($drow[$i]);} - } - else - { - if ($drow[$i] == "-oth-") - { - $exportoutput .= $elang->gT("Other"); - if($type == "pdf"){$pdf->intopdf($elang->gT("Other"));} - } - else - { - $lq = "SELECT * FROM {$dbprefix}answers WHERE qid=$fqid AND language='$explang' AND code = ?"; - $lr = db_execute_assoc($lq, array($drow[$i])) or safe_die($lq."
      ERROR:
      ".$connect->ErrorMsg()); - while ($lrow = $lr->FetchRow()) - { - //if ($lrow['code'] == $drow[$i]) {$exportoutput .= $lrow['answer'];} - if ($type == "csv") - { - $exportoutput .= str_replace("\"", "\"\"", strip_tags_full($lrow['answer'])); - if($type == "pdf"){$pdf->intopdf(str_replace("\"", "\"\"", strip_tags_full($lrow['answer'])));} - } - else - { - $exportoutput .= strip_tags_full($lrow['answer']); - if($type == "pdf"){$pdf->intopdf(strip_tags_full($lrow['answer']));} - } - - } - } - } - break; - case "W": - case "Z": - if (mb_substr($fieldinfo, -5, 5) == "other") - { - $exportoutput .= strip_tags_full($drow[$i]); - if($type == "pdf"){$pdf->intopdf($drow[$i]);} - } - else - { - if ($drow[$i] == "-oth-") - { - $exportoutput .= $elang->gT("Other"); - if($type == "pdf"){$pdf->intopdf($elang->gT("Other"));} - } - else - { - $fquery = "SELECT * FROM {$dbprefix}labels WHERE lid=$flid AND language='$explang' AND code='$drow[$i]'"; - $fresult = db_execute_assoc($fquery) or safe_die("ERROR:".$fquery."
      ".$qq."
      ".$connect->ErrorMsg()); - while ($frow = $fresult->FetchRow()) - { - $exportoutput .= strip_tags_full($frow['title']); - if($type == "pdf"){$pdf->intopdf($frow['title']);} - } - } - } - break; - case "O": //DROPDOWN LIST WITH COMMENT - $lq = "SELECT * FROM {$dbprefix}answers WHERE qid=$fqid AND language='$explang' ORDER BY answer"; - $lr = db_execute_assoc($lq) or safe_die ("Could do it
      $lq
      ".$connect->ErrorMsg()); - $found = ""; - while ($lrow = $lr->FetchRow()) - { - if ($lrow['code'] == $drow[$i]) - { - $exportoutput .= strip_tags_full($lrow['answer']); - $found = "Y"; - if($type == "pdf"){$pdf->intopdf(strip_tags_full($lrow['answer']));} - } - } -// if ($found != "Y") {if ($type == "csv" || $type == "pdf") {$exportoutput .= str_replace("\"", "\"\"", $drow[$i]);} else {$exportoutput .= str_replace("\r\n", " ", $drow[$i]);}} - break; - case "Y": //YES\NO - switch($drow[$i]) - { - case "Y": - $exportoutput .= $elang->gT("Yes"); - if($type == "pdf"){$pdf->intopdf($elang->gT("Yes"));} - break; - case "N": - $exportoutput .= $elang->gT("No"); - if($type == "pdf"){$pdf->intopdf($elang->gT("No"));} - break; - default: - $exportoutput .= $elang->gT("N/A"); - if($type == "pdf"){$pdf->intopdf($elang->gT("N/A"));} - break; - } - break; - case "G": //GENDER - switch($drow[$i]) - { - case "M": - $exportoutput .= $elang->gT("Male"); - if($type == "pdf"){$pdf->intopdf($elang->gT("Male"));} - break; - case "F": - $exportoutput .= $elang->gT("Female"); - if($type == "pdf"){$pdf->intopdf($elang->gT("Female"));} - break; - default: - $exportoutput .= $elang->gT("N/A"); - if($type == "pdf"){$pdf->intopdf($elang->gT("N/A"));} - break; - } - break; - case "M": //multioption - case "P": - if (mb_substr($fieldinfo, -5, 5) == "other") - { - $exportoutput .= strip_tags_full($drow[$i]); - if($type == "pdf"){$pdf->intopdf($drow[$i]);} - } - elseif (mb_substr($fieldinfo, -7, 7) == "comment") - { - $exportoutput .= strip_tags_full($drow[$i]); - if($type == "pdf"){$pdf->intopdf($drow[$i]);} - } - else - { - switch($drow[$i]) - { - case "Y": - $exportoutput .= $elang->gT("Yes"); - if($type == "pdf"){$pdf->intopdf($elang->gT("Yes"));} - break; - case "N": - $exportoutput .= $elang->gT("No"); - if($type == "pdf"){$pdf->intopdf($elang->gT("No"));} - break; - case "": - $exportoutput .= $elang->gT("No"); - if($type == "pdf"){$pdf->intopdf($elang->gT("No"));} - break; - default: - $exportoutput .= $drow[$i]; - if($type == "pdf"){$pdf->intopdf($drow[$i]);} - break; - } - } - break; - case "C": - switch($drow[$i]) - { - case "Y": - $exportoutput .= $elang->gT("Yes"); - if($type == "pdf"){$pdf->intopdf($elang->gT("Yes")); } - break; - case "N": - $exportoutput .= $elang->gT("No"); - if($type == "pdf"){$pdf->intopdf($elang->gT("No")); } - break; - case "U": - $exportoutput .= $elang->gT("Uncertain"); - if($type == "pdf"){$pdf->intopdf($elang->gT("Uncertain"));} - break; - } - case "E": - switch($drow[$i]) - { - case "I": - $exportoutput .= $elang->gT("Increase"); - if($type == "pdf"){$pdf->intopdf($elang->gT("Increase"));} - break; - case "S": - $exportoutput .= $elang->gT("Same"); - if($type == "pdf"){$pdf->intopdf($elang->gT("Same"));} - break; - case "D": - $exportoutput .= $elang->gT("Decrease"); - if($type == "pdf"){$pdf->intopdf($elang->gT("Decrease"));} - break; - } - break; - case "F": - case "H": - if (!isset($labelscache[$flid.'|'.$explang.'|'.$drow[$i]])) - { - $fquery = "SELECT * FROM {$dbprefix}labels WHERE lid=$flid AND language='$explang' AND code='$drow[$i]'"; - $fresult = db_execute_assoc($fquery) or safe_die("ERROR:".$fquery."\n".$qq."\n".$connect->ErrorMsg()); - if ($fresult) - { - $frow=$fresult->FetchRow(); - if($type == "pdf"){$pdf->intopdf(strip_tags_full($frow['title']));} - $exportoutput .= strip_tags_full($frow['title']); - $labelscache[$flid.'|'.$explang.'|'.$drow[$i]]=strip_tags_full($frow['title']); - } - } - else - { - $exportoutput .=$labelscache[$flid.'|'.$explang.'|'.$drow[$i]]; - if($type == "pdf"){$pdf->intopdf($labelscache[$flid.'|'.$explang.'|'.$drow[$i]]);} - } - break; - case "1": //dual scale - $flid=$fielddata['lid']; - $flid1=$fielddata['lid1']; - if (substr($fieldinfo,-1) == '0') - { - $strlabel = "1"; - $lq = "select title from {$dbprefix}labels as l where l.lid = $flid AND l.language='$surveybaselang'"; - } - else - { - $strlabel = "2"; - $lq = "select title from {$dbprefix}labels as l where l.lid = $flid1 AND l.language='$surveybaselang'"; - } - $lr = db_execute_assoc($lq); - while ($lrow=$lr->FetchRow()) - { - $fquest .= " [".strip_tags_full($lrow['title'])."][".strip_tags_full($strlabel).". label]"; - } - - break; - - default: $tempresult=$dresult->FetchField($i); - if ($tempresult->name == "token") - { - $tokenquery = "SELECT firstname, lastname FROM {$dbprefix}tokens_$surveyid WHERE token='$drow[$i]'"; - if ($tokenresult = db_execute_assoc($tokenquery)) //or safe_die ("Couldn't get token info
      $tokenquery
      ".$connect->ErrorMsg()); - while ($tokenrow=$tokenresult->FetchRow()) - { - $exportoutput .= "{$tokenrow['lastname']}, {$tokenrow['firstname']}"; - if($type == "pdf"){$pdf->intopdf($tokenrow['lastname']." , ".$tokenrow['firstname']);} - } - else - { - $exportoutput .= $elang->gT("Tokens problem - token table missing"); - if($type == "pdf"){$pdf->intopdf($elang->gT("Tokens problem - token table missing"));} - } - } - else - { - if ($type == "csv") - {$exportoutput .= str_replace("\r\n", "\n", str_replace("\"", "\"\"", strip_tags_full($drow[$i])));} - else if ($type == "pdf") - {$pdf->intopdf(str_replace("\r\n", " ", strip_tags_full($drow[$i])));} - else - {$exportoutput .= str_replace("\r\n", " ", $drow[$i]);} - } - } - if ($type == "csv") {$exportoutput .= "\"";} - $exportoutput .= "$separator"; - $ftype = ""; - } - - IF ($type=='xls') - { - $rowarray=explode($separator, $exportoutput); - $fli=0; - foreach ($rowarray as $row) - { - $sheet->write($rowcounter,$fli,$row); - $fli++; - } - $exportoutput=''; - } - else {$exportoutput .= "\n";} - }} -if ($type=='xls') -{ - $workbook->close(); -} -else if($type=='pdf') -{ - $pdf->Output($clang->gT($surveyname)." ".$surveyid.".pdf","D"); -} -else -{ - echo $exportoutput; -} -exit; - - -function strip_tags_full($string) { - $string=html_entity_decode_php4($string, ENT_QUOTES, "UTF-8"); - mb_regex_encoding('utf-8'); - $pattern = array('\r', '\n', '-oth-'); - for ($i=0; $i +FetchRow(); + +if ($sumrows5['export'] != "1" && $_SESSION['USER_RIGHT_SUPERADMIN'] != 1) +{ + exit; +} + +include_once("login_check.php"); +include_once(dirname(__FILE__)."/classes/pear/Spreadsheet/Excel/Writer.php"); +include_once(dirname(__FILE__)."/classes/tcpdf/extensiontcpdf.php"); + +$surveybaselang=GetBaseLanguageFromSurveyID($surveyid); +$exportoutput=""; + +// Get info about the survey +$thissurvey=getSurveyInfo($surveyid); + +if (!$exportstyle) +{ + // First add the standard fields + $excesscols[]="id"; + $excesscols[]='completed'; + if ($thissurvey["datestamp"]=='Y') {$excesscols[]='datestamp';} + if ($thissurvey["datestamp"]=='Y') {$excesscols[]='startdate';} + if ($thissurvey["ipaddr"]=='Y') {$excesscols[]='ipaddr';} + if ($thissurvey["refurl"]=='Y') {$excesscols[]='refurl';} + + //FIND OUT HOW MANY FIELDS WILL BE NEEDED - FOR 255 COLUMN LIMIT + $query=" SELECT other, q.type, q.gid, q.qid, q.lid, q.lid1 FROM {$dbprefix}questions as q, {$dbprefix}groups as g " + ." where q.gid=g.gid and g.sid=$surveyid and g.language='$surveybaselang' and q.language='$surveybaselang'" + ." order by group_order, question_order"; + + $result=db_execute_assoc($query) or safe_die("Couldn't count fields
      $query
      ".$connect->ErrorMsg()); + while ($rows = $result->FetchRow()) + { + if (($rows['type']=='A') || ($rows['type']=='B')||($rows['type']=='C')||($rows['type']=='M')||($rows['type']=='P')||($rows['type']=='Q')||($rows['type'] == "K") ||($rows['type']=='E')||($rows['type']=='F')||($rows['type']=='H')) + { + $detailquery="select code from {$dbprefix}answers where qid=".$rows['qid']." and language='$surveybaselang' order by sortorder,code"; + $detailresult=db_execute_assoc($detailquery) or safe_die("Couldn't find detailfields
      $detailquery
      ".$connect->ErrorMsg()); + while ($detailrows = $detailresult->FetchRow()) + { + $excesscols[]=$surveyid.'X'.$rows['gid']."X".$rows['qid'].$detailrows['code']; + if ($rows['type']=='P') + { + $excesscols[]=$surveyid.'X'.$rows['gid']."X".$rows['qid'].$detailrows['code']."comment"; + } + } + } + elseif ($rows['type']==":" || $rows['type'] == ";") + { + $detailquery="select code from {$dbprefix}answers where qid=".$rows['qid']." and language='$surveybaselang' order by sortorder,code"; + $detailresult=db_execute_assoc($detailquery) or die("Couldn't find detailfields
      $detailquery
      ".htmlspecialchars($connect->ErrorMsg())); + while ($detailrows = $detailresult->FetchRow()) + { + $detailquery2="SELECT * + FROM {$dbprefix}labels + WHERE lid=".$rows['lid']." + AND language='$surveybaselang' + ORDER BY sortorder, title"; + $detailresult2=db_execute_assoc($detailquery2) or die("Couldn't find labels
      $detailquery2
      ".htmlspecialchars($connect->ErrorMsg())); + while ($dr2 = $detailresult2->FetchRow()) + { + $excesscols[]=$surveyid.'X'.$rows['gid']."X".$rows['qid'].$detailrows['code']."_".$dr2['code']; + } + } + } + elseif ($rows['type']=='R') + { + $detailquery="select code from {$dbprefix}answers where qid=".$rows['qid']." and language='$surveybaselang' order by sortorder,code"; + $detailresult=db_execute_assoc($detailquery) or safe_die("Couldn't find detailfields
      $detailquery
      ".$connect->ErrorMsg()); + $i=1; + while ($detailrows = $detailresult->FetchRow()) + { + $excesscols[]=$surveyid.'X'.$rows['gid']."X".$rows['qid'].$i; + $i++; + } + } + elseif ($rows['type']=='1') + { + // $detailquery="select code from {$dbprefix}answers where qid=".$rows['qid']." and language='$surveybaselang' order by sortorder,code"; + $detailquery="select a.code, l.lid from {$dbprefix}answers as a, {$dbprefix}labels as l where qid=".$rows['qid']." AND (l.lid =".$rows['lid'].") and a.language='$surveybaselang' group by a.code, l.lid order by a.code "; + $detailresult=db_execute_assoc($detailquery) or safe_die("Couldn't find detailfields
      $detailquery
      ".$connect->ErrorMsg()); + $i=0; + while ($detailrows = $detailresult->FetchRow()) + { + // $excesscols[]=$surveyid.'X'.$rows['gid']."X".$rows['qid'].$rows['code'].$detailrows['code']."#".$i; + $excesscols[]=$surveyid.'X'.$rows['gid']."X".$rows['qid'].$detailrows['code']."#0"; + $i++; + } + // second scale + $detailquery="select a.code, l.lid from {$dbprefix}answers as a, {$dbprefix}labels as l where qid=".$rows['qid']." AND (l.lid =".$rows['lid1'].") and a.language='$surveybaselang' group by a.code, l.lid order by a.code "; + $detailresult=db_execute_assoc($detailquery) or safe_die("Couldn't find detailfields
      $detailquery
      ".$connect->ErrorMsg()); + $i=0; + while ($detailrows = $detailresult->FetchRow()) + { + // $excesscols[]=$surveyid.'X'.$rows['gid']."X".$rows['qid'].$rows['code'].$detailrows['code']."#".$i; + $excesscols[]=$surveyid.'X'.$rows['gid']."X".$rows['qid'].$detailrows['code']."#1"; + $i++; + } + + } + else + { + $excesscols[]=$surveyid.'X'.$rows['gid']."X".$rows['qid']; + } + if ($rows['other']=="Y" && ($rows['type']=='M' || $rows['type']=='!'|| $rows['type']=='L' || $rows['type']=='P' || $rows['type'] == "Z" || $rows['type'] == "W")) + { + $excesscols[]=$surveyid.'X'.$rows['gid']."X".$rows['qid']."other"; + } + if ($rows['other']=="Y" && ($rows['type']=='P' )) + { + $excesscols[]=$surveyid.'X'.$rows['gid']."X".$rows['qid']."othercomment"; + } + if ($rows['type']=='O' ) + { + $excesscols[]=$surveyid.'X'.$rows['gid']."X".$rows['qid']."comment"; + } + + } + + + + $afieldcount = count($excesscols); + $exportoutput .= browsemenubar($clang->gT("Export Results")); + $exportoutput .= "
      \n" + ."
      \n" + ."" + .""; + + // Find out if survey results are anonymous + if ($thissurvey['private'] == "N") + { + $query=db_select_tables_like("{$dbprefix}tokens_$surveyid"); //SEE IF THERE IS AN ASSOCIATED TOKENS TABLE + $result=$connect->Execute($query) or safe_die("Couldn't get table list
      $query
      ".$connect->ErrorMsg()); + $tablecount=$result->RecordCount(); + } + $exportoutput .= "\n"; + if (isset($tablecount) && $tablecount > 0) //Do second column + { + //OPTIONAL EXTRAS (FROM TOKENS TABLE) + if ($tablecount > 0) + { + $exportoutput .= ""; + } + } + $exportoutput .= "\n" + ."
      \n" + ."\n" + ."\t\n" + ."\t\n" + ."\t\n" + ."\t\t\n" + ."\t\n" + ."\t\n" + ."\t\n" + ."\t\t\n" + ."\t\n" + ."\t\n" + ."\t\n" + ."\t\t\n" + ."\t\n" + ."\t\n" + ."\t\n" + ."\t\t\n" + ."\t\n" + ."\t\n" + ."\t\t\n" + ."\t\n" + ."
      " + ."" + .$clang->gT("Export responses"); + if (isset($_POST['sql'])) {$exportoutput .= " - ".$clang->gT("Filtered from statistics script");} + if (returnglobal('id')<>'') {$exportoutput .= " - ".$clang->gT("Single response");} + + if (incompleteAnsFilterstate() == "filter") + { + $selecthide="selected='selected'"; + $selectshow=""; + $selectinc=""; + } + elseif (incompleteAnsFilterstate() == "inc") + { + $selecthide=""; + $selectshow=""; + $selectinc="selected='selected'"; + } + else + { + $selecthide=""; + $selectshow="selected='selected'"; + $selectinc=""; + } + + $exportoutput .= " ($afieldcount ".$clang->gT("Columns").")
      " + .$clang->gT("Questions")."
      \n" + ."\t\t\t" + ."
      \n" + ."\t\t\t" + ."
      \n" + ."\t\t\t" + ."
      \n" + + ."\t\t\t" + ."
      " + + ."\t\t\t  ".$clang->gT("Include")." \n" + ."\t\t
      " + .$clang->gT("Answers")."
      \n" + ."\t\t\t" + .""; + + $exportoutput .= "
      \n" + ."\t\t\t" + .""; + $exportoutput .= "
      \n" + ."\t\t\t" + .""; + + $exportoutput .= "
      \n" + ."\t\t\t" + ."\n" + ."\t\t
      " + .$clang->gT("Format")."
      \n" + ."\t\t\t" + ."
      \n" + ."\t\t\t" + ."
      \n" + ."\t\t\t" + ."
      \n"; + if(isset($usepdfexport) && $usepdfexport == 1) + { + $exportoutput .= "\t\t\t" + ."\n"; + } + + + //get max number of datasets + $max_datasets = 0; + + $max_datasets_query = "SELECT COUNT(id) FROM {$dbprefix}survey_$surveyid"; + $max_datasets_result = db_execute_num($max_datasets_query); + + while($max = $max_datasets_result -> FetchRow()) + { + $max_datasets = $max[0]; + } + + // form fields to limit export from X to Y + $exportoutput .= "
      ".$clang->gT("from")." "; + $exportoutput .= " ".$clang->gT("to")." "; + + + $exportoutput .="\t\t
      \n" + ."\t\t\t\n" + ."\t\t\t\n" + ."\t\t
      \n"; + if (isset($_POST['sql'])) + { + $exportoutput .= "\t\n"; + } + if (returnglobal('id')<>'') + { + $exportoutput .= "\t\n"; + } + $exportoutput .= "
      \n" + ."
      \n" + ."" + ."\t\n" + ."\t\t\n" + ."\t\n" + ."\t\n" + ."\t\t\n" + ."\t\n" + ."\t\n" + ."\t\t\n" + ."\t\n" + ."
      " + .$clang->gT("Column Control")."\n" + ."\t\t
      \n" + ."\t\t\t".$clang->gT("Choose Columns").":\n" + ."\t\t"; + if ($afieldcount > 255) + { + $exportoutput .= "\t\t\t".$clang->gT("Help").""; + } + else + { + $exportoutput .= "\t\t\t".$clang->gT("Help").""; + } + $exportoutput .= "\t\t
      \n" + ."\t\t\t
      \n" + ."
      \n" + ."" + ."\t\n" + ."\t\t\n" + ."\t\n" + ."\t\n" + ."\t\t\n" + ."\t\n" + ."\t\n" + ."\t\t\n" + ."\t\n" + ."
      " + .$clang->gT("Token Control")."\n" + ."\t\t
      \n" + .$clang->gT("Choose Token Fields").":" + ."\t\t
      " + ."".$clang->gT("Help")."

      \n" + ."" + ."
      \n" + ."" + ."
      \n" + ."" + ."
      \n" + ."" + ."
      \n"; + + $attrfieldnames=GetTokenFieldsAndNames($surveyid,true); + foreach ($attrfieldnames as $attr_name=>$attr_desc) + { + $exportoutput .= "" + ."
      \n"; + } + $exportoutput .= "\t\t
      " + ."

      \n" + ."\t
      \n"; + return; +} + + + + + +// ====================================================================== +// Actual export routines start here ! +// ====================================================================== + +$tokenTableExists=tokenTableExists($surveyid); + +if ($tokenTableExists) +{ + $attributeFieldAndNames=GetTokenFieldsAndNames($surveyid,true); + $attributeFields=array_keys($attributeFieldAndNames); +} + +//sendcacheheaders(); // sending "cache headers" before this permit us to send something else than a "text/html" content-type +switch ( $_POST["type"] ) { // this is a step to register_globals = false ;c) + case "doc": + header("Content-Disposition: attachment; filename=results-survey".$surveyid.".doc"); + header("Content-type: application/vnd.ms-word"); + $separator="\t"; + break; + case "xls": + + $workbook = new Spreadsheet_Excel_Writer(); + $workbook->setVersion(8); + // Inform the module that our data will arrive as UTF-8. + // Set the temporary directory to avoid PHP error messages due to open_basedir restrictions and calls to tempnam("", ...) + if (!empty($tempdir)) { + $workbook->setTempDir($tempdir); + } + $workbook->send('results-survey'.$surveyid.'.xls'); + // Creating the first worksheet + + $query="SELECT * FROM {$dbprefix}surveys_languagesettings WHERE surveyls_survey_id=".$surveyid; + $result=db_execute_assoc($query) or safe_die("Couldn't get privacy data
      $query
      ".$connect->ErrorMsg()); + $row = $result->FetchRow(); + + $sheet =& $workbook->addWorksheet(utf8_decode($row['surveyls_title'])); + $sheet->setInputEncoding('utf-8'); + $separator="~|"; + break; + case "csv": + header("Content-Disposition: attachment; filename=results-survey".$surveyid.".csv"); + header("Content-type: text/comma-separated-values; charset=UTF-8"); + $separator=","; + break; + case "pdf": + $pdf = new PDF($pdforientation,'mm','A4'); + $pdf->SetFont($pdfdefaultfont,'',$pdffontsize); + $pdf->AddPage(); + $pdf->intopdf("PDF Export ".date("Y.m.d-H:i",time())); + $query="SELECT * FROM {$dbprefix}surveys_languagesettings WHERE surveyls_survey_id=".$surveyid; + $result=db_execute_assoc($query) or safe_die("Couldn't get privacy data
      $query
      ".$connect->ErrorMsg()); + while ($row = $result->FetchRow()) + { + $pdf->intopdf($clang->gT("General information in language: ").getLanguageNameFromCode($row['surveyls_language']),'B'); + $pdf->ln(); + $pdf->titleintopdf($row['surveyls_title'],$row['surveyls_description']); + $surveyname=$row['surveyls_title']; + } + $pdf->AddPage(); + $separator="\t"; + break; + default: + header("Content-Disposition: attachment; filename=results-survey".$surveyid.".csv"); + header("Content-type: text/comma-separated-values; charset=UTF-8"); + $separator=","; + break; +} +Header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); + +// Export Language is set by default to surveybaselang +// * the explang language code is used in SQL queries +// * the alang object is used to translate headers and hardcoded answers +// In the future it might be possible to 'post' the 'export language' from +// the exportresults form +$explang = $surveybaselang; +$elang=new limesurvey_lang($explang); + +//STEP 1: First line is column headings + +$fieldmap=createFieldMap($surveyid); + +// We make the fieldmap alot more accesible by using the SGQA identifier as key +// so we do not need ArraySearchByKey later +foreach ($fieldmap as $fieldentry) +{ + $outmap[]=$fieldentry['fieldname']; + $outmap[$fieldentry['fieldname']]['type']= $fieldentry['type']; + $outmap[$fieldentry['fieldname']]['sid']= $fieldentry['sid']; + $outmap[$fieldentry['fieldname']]['gid']= $fieldentry['gid']; + $outmap[$fieldentry['fieldname']]['qid']= $fieldentry['qid']; + $outmap[$fieldentry['fieldname']]['aid']= $fieldentry['aid']; + if (isset($fieldentry['lid1'])) {$outmap[$fieldentry['fieldname']]['lid1']= $fieldentry['lid1'];} + if ($fieldentry['qid']!='') + { + $qq = "SELECT lid, other FROM {$dbprefix}questions WHERE qid={$fieldentry['qid']} and language='$surveybaselang'"; + $qr = db_execute_assoc($qq) or safe_die("Error selecting type and lid from questions table.
      ".$qq."
      ".$connect->ErrorMsg()); + while ($qrow = $qr->FetchRow()) + { + $outmap[$fieldentry['fieldname']]['lid']=$qrow['lid']; + $outmap[$fieldentry['fieldname']]['other']=$qrow['other']; + } + } + +} +//Get the fieldnames from the survey table for column headings +$surveytable = "{$dbprefix}survey_$surveyid"; +if (isset($_POST['colselect'])) +{ + $selectfields=""; + foreach($_POST['colselect'] as $cs) + { + if ($cs != 'completed') + { + $selectfields.= db_quote_id($cs).", "; + } + else + { + $selectfields.= "CASE WHEN $surveytable.submitdate IS NULL THEN 'N' ELSE 'Y' END AS completed, "; + } + } + $selectfields = mb_substr($selectfields, 0, strlen($selectfields)-2); +} +else +{ + $selectfields="$surveytable.*, CASE WHEN $surveytable.submitdate IS NULL THEN 'N' ELSE 'Y' END AS completed"; +} + +$dquery = "SELECT $selectfields"; +if (isset($_POST['first_name']) && $_POST['first_name']=="on") +{ + $dquery .= ", {$dbprefix}tokens_$surveyid.firstname"; +} +if (isset($_POST['last_name']) && $_POST['last_name']=="on") +{ + $dquery .= ", {$dbprefix}tokens_$surveyid.lastname"; +} +if (isset($_POST['email_address']) && $_POST['email_address']=="on") +{ + $dquery .= ", {$dbprefix}tokens_$surveyid.email"; +} + +if ($tokenTableExists && $thissurvey['private']=='N') +{ + if (isset($_POST['token']) && $_POST['token']=="on") + { + $dquery .= ", {$dbprefix}tokens_$surveyid.token"; + } + + foreach ($attributeFields as $attr_name) + { + if (isset($_POST[$attr_name]) && $_POST[$attr_name]=="on") + { + $dquery .= ", {$dbprefix}tokens_$surveyid.$attr_name"; + } + } +} +$dquery .= " FROM $surveytable"; + +if ($tokenTableExists && $thissurvey['private']=='N') +{ + $dquery .= " LEFT OUTER JOIN {$dbprefix}tokens_$surveyid" + . " ON $surveytable.token = {$dbprefix}tokens_$surveyid.token"; +} +if (incompleteAnsFilterstate() == "filter") +{ + $dquery .= " WHERE $surveytable.submitdate is not null "; +} elseif (incompleteAnsFilterstate() == "inc") +{ + $dquery .= " WHERE $surveytable.submitdate is null "; +} + +$dquery .=" ORDER BY id "; + +$dresult = db_select_limit_assoc($dquery, 1) or safe_die($clang->gT("Error")." getting results
      $dquery
      ".$connect->ErrorMsg()); +$fieldcount = $dresult->FieldCount(); +$firstline=""; +$faid=""; +for ($i=0; $i<$fieldcount; $i++) +{ + //Iterate through column names and output headings + $field=$dresult->FetchField($i); + $fieldinfo=$field->name; + + if ($fieldinfo == "lastname") + { + if ($type == "csv") {$firstline .= "\"".$elang->gT("Last Name")."\"$separator";} + else {$firstline .= $elang->gT("Last Name")."$separator";} + } + elseif ($fieldinfo == "firstname") + { + if ($type == "csv") {$firstline .= "\"".$elang->gT("First Name")."\"$separator";} + else {$firstline .= $elang->gT("First Name")."$separator";} + } + elseif ($fieldinfo == "email") + { + if ($type == "csv") {$firstline .= "\"".$elang->gT("Email Address")."\"$separator";} + else {$firstline .= $elang->gT("Email Address")."$separator";} + } + elseif ($fieldinfo == "token") + { + if ($type == "csv") {$firstline .= "\"".$elang->gT("Token")."\"$separator";} + else {$firstline .= $elang->gT("Token")."$separator";} + } + elseif (substr($fieldinfo,0,10)=="attribute_") + { + if ($type == "csv") {$firstline .= CSVEscape($fieldinfo)."$separator";} + else {$firstline .= $attributeFieldAndNames[$fieldinfo]."$separator";} + } + elseif ($fieldinfo == "id") + { + if ($type == "csv") {$firstline .= "\"id\"$separator";} + else {$firstline .= "id$separator";} + } + elseif ($fieldinfo == "datestamp") + { + if ($type == "csv") {$firstline .= "\"".$elang->gT("Date Last Action")."\"$separator";} + else {$firstline .= $elang->gT("Date Last Action")."$separator";} + } + elseif ($fieldinfo == "startdate") + { + if ($type == "csv") {$firstline .= "\"".$elang->gT("Date Started")."\"$separator";} + else {$firstline .= $elang->gT("Date Started")."$separator";} + } + elseif ($fieldinfo == "completed") + { + if ($type == "csv") {$firstline .= "\"".$elang->gT("Completed")."\"$separator";} + else {$firstline .= $elang->gT("Completed")."$separator";} + } + elseif ($fieldinfo == "ipaddr") + { + if ($type == "csv") {$firstline .= "\"".$elang->gT("IP-Address")."\"$separator";} + else {$firstline .= $elang->gT("IP-Address")."$separator";} + } + elseif ($fieldinfo == "refurl") + { + if ($type == "csv") {$firstline .= "\"".$elang->gT("Referring URL")."\"$separator";} + else {$firstline .= $elang->gT("Referring URL")."$separator";} + } + else + { + //Data fields! + //$fielddata=arraySearchByKey($fieldinfo, $fieldmap, "fieldname", 1); + $fielddata=$outmap[$fieldinfo]; + + $fqid=$fielddata['qid']; + $ftype=$fielddata['type']; + $fsid=$fielddata['sid']; + $fgid=$fielddata['gid']; + $faid=$fielddata['aid']; + if ($exportstyle == "abrev") + { + $qq = "SELECT question FROM {$dbprefix}questions WHERE qid=$fqid and language='$explang'"; + $qr = db_execute_assoc($qq); + while ($qrow=$qr->FetchRow()) + {$qname=$qrow['question'];} + $qname=strip_tags_full($qname); + $qname=mb_substr($qname, 0, 15).".."; + $firstline = str_replace("\n", "", $firstline); + $firstline = str_replace("\r", "", $firstline); + if ($type == "csv") {$firstline .= "\"$qname";} + else {$firstline .= "$qname";} + if (isset($faid)) {$firstline .= " [{$faid}]"; $faid="";} + if ($ftype == ":" || $ftype == ";") + { + + } + if ($type == "csv") {$firstline .= "\"";} + $firstline .= "$separator"; + } + else //headcode or full answer + { + $qq = "SELECT question, type, other, title FROM {$dbprefix}questions WHERE qid=$fqid AND language='$explang' ORDER BY gid, title"; //get the question + $qr = db_execute_assoc($qq) or safe_die ("ERROR:
      ".$qq."
      ".$connect->ErrorMsg()); + while ($qrow=$qr->FetchRow()) + { + if ($exportstyle == "headcodes"){$fquest=$qrow['title'];} + else {$fquest=$qrow['question'];} + } + switch ($ftype) + { + case "R": //RANKING TYPE + $fquest .= " [".$elang->gT("Ranking")." $faid]"; + break; + case "L": + case "!": + case "W": + case "Z": + if ($faid == "other") { + $fquest .= " [".$elang->gT("Other")."]"; + } + break; + case "O": //DROPDOWN LIST WITH COMMENT + if ($faid == "comment") + { + $fquest .= " - Comment"; + } + break; + case "M": //multioption + if ($faid == "other") + { + $fquest .= " [".$elang->gT("Other")."]"; + } + else + { + if ($answers == "short") { + $fquest .= " [$faid]"; //Show only the code + } + else + { + $lq = "SELECT * FROM {$dbprefix}answers WHERE qid=$fqid AND code = '$faid' AND language = '$explang'"; + $lr = db_execute_assoc($lq); + while ($lrow = $lr->FetchRow()) + { + $fquest .= " [".strip_tags_full($lrow['answer'])."]"; + } + } + } + break; + case "P": //multioption with comment + if (mb_substr($faid, -7, 7) == "comment") + { + $faid=mb_substr($faid, 0, -7); + $comment=true; + } + if ($faid == "other") + { + $fquest .= " [".$elang->gT("Other")."]"; + } + else + { + if ($answers == "short") { + $fquest .= " [$faid]"; //Show only the code + } + else + { + $lq = "SELECT * FROM {$dbprefix}answers WHERE qid=$fqid AND code = '$faid' AND language = '$explang'"; + $lr = db_execute_assoc($lq); + while ($lrow = $lr->FetchRow()) + { + $fquest .= " [".strip_tags_full($lrow['answer'])."]"; + } + } + } + if (isset($comment) && $comment == true) {$fquest .= " - comment"; $comment=false;} + break; + case "A": + case "B": + case "C": + case "E": + case "F": + case "H": + case "K": + case "Q": + case "^": + if ($answers == "short") { + $fquest .= " [$faid]"; + } + else + { + $lq = "SELECT * FROM {$dbprefix}answers WHERE qid=$fqid AND code= '$faid' AND language = '$explang'"; + $lr = db_execute_assoc($lq); + while ($lrow=$lr->FetchRow()) + { + $fquest .= " [".strip_tags_full($lrow['answer'])."]"; + } + } + break; + case ":": + case ";": + list($faid, $fcode) = explode("_", $faid); + if ($answers == "short") { + $fquest .= " [$faid] [$fcode]"; + } else { + $lq1="SELECT lid FROM {$dbprefix}questions WHERE qid=$fqid"; + $lr1=db_execute_assoc($lq1); + while($lrow1=$lr1->FetchRow()) { + $flid = $lrow1['lid']; + } + $lq = "SELECT * FROM {$dbprefix}answers WHERE qid=$fqid AND code= '$faid' AND language = '$explang'"; + $lr = db_execute_assoc($lq); + while ($lrow=$lr->FetchRow()) + { + $lq2 = "SELECT * FROM {$dbprefix}labels WHERE lid=$flid AND code='$fcode' AND language = '$explang'"; + $lr2 = db_execute_assoc($lq2); + while ($lrow2=$lr2->FetchRow()) + { + $fquest .= " [".$lrow['answer']."] [".$lrow2['title']."]"; + } + } + } + break; + case "1": // multi scale Headline + $flid=$fielddata['lid']; + $flid1=$fielddata['lid1']; + if (mb_substr($fieldinfo,-1) == '0') + { //TIBO + $strlabel = "1"; + $lq = "select a.*, l.*, t.label_name as labeltitle from {$dbprefix}answers as a, {$dbprefix}labels as l, {$dbprefix}labelsets as t where a.code='$faid' and qid=$fqid AND l.lid = $flid AND a.language='$surveybaselang' AND t.lid=$flid group by l.lid"; + } + else + { + $strlabel = "2"; + $lq = "select a.*, l.*, t.label_name as labeltitle from {$dbprefix}answers as a, {$dbprefix}labels as l, {$dbprefix}labelsets as t where a.code='$faid' and qid=$fqid AND l.lid = $flid1 AND a.language='$surveybaselang' AND t.lid=$flid1 group by l.lid"; + } + $lr = db_execute_assoc($lq); + $j=0; + while ($lrow=$lr->FetchRow()) + { + $strlabel = $strlabel."-".$lrow['labeltitle']; + $fquest .= " [".strip_tags_full($lrow['answer'])."][".strip_tags_full($strlabel)."]"; + $j++; + } + + break; + + } + $fquest=strip_tags_full($fquest); + + $fquest = str_replace("\n", " ", $fquest); + $fquest = str_replace("\r", "", $fquest); + if ($type == "csv") + { + $firstline .="\"$fquest\"$separator"; + } + else + { + $firstline .= "$fquest $separator"; + } + } + if($convertspacetous == "Y") + { + $firstline=str_replace(" ", "_", $firstline); + } + } +} +if ($type == "csv") { $firstline = mb_substr(trim($firstline),0,strlen($firstline)-1);} +else +{ + $firstline = trim($firstline); +} + +$firstline .= "\n"; + +if ($type == "doc" || $type == "pdf") +{ + $flarray=explode($separator, $firstline); + +} +else +if ($type == "xls") +{ + //var_dump ($firstline); + $flarray=explode($separator, $firstline); + $fli=0; + foreach ($flarray as $fl) + { + $sheet->write(0,$fli,$fl); + $fli++; + } + //print_r($fieldmap); +} +else +{ + $exportoutput .= $firstline; //Sending the header row +} + + +//calculate interval because the second argument at SQL "limit" +//is the number of records not the ending point +$from_record = sanitize_int($_POST['export_from']) - 1; +$limit_interval = sanitize_int($_POST['export_to']) - sanitize_int($_POST['export_from']) + 1; +$attributefieldAndNames=array(); + +//Now dump the data +if ($tokenTableExists && $thissurvey['private']=='N') +{ + $dquery = "SELECT $selectfields"; + if (isset($_POST['first_name']) && $_POST['first_name']=="on") + { + $dquery .= ", {$dbprefix}tokens_$surveyid.firstname"; + } + if (isset($_POST['last_name']) && $_POST['last_name']=="on") + { + $dquery .= ", {$dbprefix}tokens_$surveyid.lastname"; + } + if (isset($_POST['email_address']) && $_POST['email_address']=="on") + { + $dquery .= ", {$dbprefix}tokens_$surveyid.email"; + } + if (isset($_POST['token']) && $_POST['token']=="on") + { + $dquery .= ", {$dbprefix}tokens_$surveyid.token"; + } + foreach ($attributeFields as $attributefield) + { + if (isset($_POST[$attributefield]) && $_POST[$attributefield]=="on") + { + $dquery .= ", {$dbprefix}tokens_$surveyid.$attributefield"; + } + } + $dquery .= " FROM $surveytable " + . "LEFT OUTER JOIN {$dbprefix}tokens_$surveyid " + . "ON $surveytable.token={$dbprefix}tokens_$surveyid.token "; + if (incompleteAnsFilterstate() == "filter") + { + $dquery .= " WHERE $surveytable.submitdate is not null "; + } elseif (incompleteAnsFilterstate() == "inc") + { + $dquery .= " WHERE $surveytable.submitdate is null "; + } +} +else // this applies for exporting everything +{ + $dquery = "SELECT $selectfields FROM $surveytable "; + + if (incompleteAnsFilterstate() == "filter") + { + $dquery .= " WHERE $surveytable.submitdate is not null "; + } elseif (incompleteAnsFilterstate() == "inc") + { + $dquery .= " WHERE $surveytable.submitdate is null "; + } +} + +if (isset($_POST['sql'])) //this applies if export has been called from the statistics package +{ + if ($_POST['sql'] != "NULL") + { + if (incompleteAnsFilterstate() == "filter" || incompleteAnsFilterstate() == "inc") {$dquery .= " AND ".stripcslashes($_POST['sql'])." ";} + else {$dquery .= "WHERE ".stripcslashes($_POST['sql'])." ";} + } +} +if (isset($_POST['answerid']) && $_POST['answerid'] != "NULL") //this applies if export has been called from single answer view +{ + if (incompleteAnsFilterstate() == "filter" || incompleteAnsFilterstate() == "inc") {$dquery .= " AND $surveytable.id=".stripcslashes($_POST['answerid'])." ";} + else {$dquery .= "WHERE $surveytable.id=".stripcslashes($_POST['answerid'])." ";} +} + + +$dquery .= "ORDER BY $surveytable.id"; +if ($answers == "short") //Nice and easy. Just dump the data straight +{ + //$dresult = db_execute_assoc($dquery); + $dresult = db_select_limit_assoc($dquery, $limit_interval, $from_record); + $rowcounter=0; + while ($drow = $dresult->FetchRow()) + { + $drow=array_map('strip_tags_full',$drow); + if($convertyto1 == "Y") + //Converts "Y" to "1" in export + { + $convertyto=returnglobal('convertyto'); + foreach($drow as $key=>$dr) { + $fielddata=arraySearchByKey($key, $fieldmap, "fieldname", 1); + if(isset($fielddata['type']) && + ($fielddata['type'] == "M" || + $fielddata['type'] == "P" || + $fielddata['type'] == "Y") + ) + { + if($dr == "Y") {$dr = $convertyto;} + } + $line[$key]=$dr; + } + $drow=$line; + } + if($convertnto2 == "Y") + //Converts "N" to "2" in export + { + $convertnto=returnglobal('convertnto'); + foreach($drow as $key=>$dr) { + $fielddata=arraySearchByKey($key, $fieldmap, "fieldname", 1); + if(isset($fielddata['type']) && + ($fielddata['type'] == "M" || + $fielddata['type'] == "P" || + $fielddata['type'] == "Y") + ) + { + if($dr == "N") {$dr = $convertnto;} + } + $line[$key]=$dr; + } + $drow=$line; + } + $rowcounter++; + if ($type == "csv") + { + $exportoutput .= "\"".implode("\"$separator\"", str_replace("\"", "\"\"", str_replace("\r\n", " ", $drow))) . "\"\n"; //create dump from each row + } + elseif ($type == "xls") + { + $colcounter=0; + foreach ($drow as $rowfield) + { + $rowfield=str_replace("?","-",$rowfield); + $sheet->write($rowcounter,$colcounter,$rowfield); + $colcounter++; + } + } + else if($type == "pdf") + { + $pdf->titleintopdf($clang->gT("New Record")); + foreach ($drow as $rowfield) + { + $rowfield=str_replace("?","-",$rowfield); + $pdfstring .=$rowfield." | "; + } + $pdf->intopdf($pdfstring); + } + else + { + $exportoutput .= implode($separator, str_replace("\r\n", " ", $drow)) . "\n"; //create dump from each row + } + } +} +elseif ($answers == "long") //chose complete answers +{ + + $labelscache=array(); + //$dresult = db_execute_num($dquery) or safe_die("ERROR: $dquery -".$connect->ErrorMsg()); + $dresult = db_select_limit_num($dquery, $limit_interval, $from_record); + $fieldcount = $dresult->FieldCount(); + $rowcounter=0; + + while ($drow = $dresult->FetchRow()) + { + $rowcounter++; + if ($type == "pdf") + { + //$pdf->Write (5,$exportoutput); + if($rowcounter != 1) + { + $pdf->AddPage(); + } + $pdf->Cell(0,10,$elang->gT('NEW RECORD')." ".$rowcounter,1,1); + } + + if ($type == "doc") + { + $exportoutput .= "\n\n\n".$elang->gT('NEW RECORD')."\n"; + } + for ($i=0; $i<$fieldcount; $i++) //For each field, work out the QID + { + $fqid=0; // By default fqid is set to zero + $field=$dresult->FetchField($i); + $fieldinfo=$field->name; + if ($fieldinfo != "startlanguage" && $fieldinfo != "id" && $fieldinfo != "datestamp" && $fieldinfo != "startdate" && $fieldinfo != "ipaddr" && $fieldinfo != "refurl" && $fieldinfo != "token" && $fieldinfo != "firstname" && $fieldinfo != "lastname" && $fieldinfo != "email" && (substr($fieldinfo,0,10)!="attribute_") && $fieldinfo != "completed") + { + // $fielddata=arraySearchByKey($fieldinfo, $fieldmap, "fieldname", 1); + $fielddata=$outmap[$fieldinfo]; + $fqid=$fielddata['qid']; + $ftype=$fielddata['type']; + $fsid=$fielddata['sid']; + $fgid=$fielddata['gid']; + $faid=$fielddata['aid']; + $flid=$fielddata['lid']; + if (isset($fielddata['lid1'])) {$flid1=$fielddata['lid1'];} + + $fother=$fielddata['other']; + if ($type == "doc" || $type == "pdf") + { + $ftitle=$flarray[$i]; + } + } + else + { + $fsid=""; $fgid=""; + if ($type == "doc" || $type == "pdf") + { + switch($fieldinfo) + { + case "datestamp": + $ftitle=$elang->gT("Date Last Action").":"; + break; + case "startdate": + $ftitle=$elang->gT("Date Started").":"; + break; + case "ipaddr": + $ftitle=$elang->gT("IP Address").":"; + break; + case "completed": + $ftitle=$elang->gT("Completed").":"; + break; + case "refurl": + $ftitle=$elang->gT("Referring URL").":"; + break; + case "firstname": + $ftitle=$elang->gT("First Name").":"; + break; + case "lastname": + $ftitle=$elang->gT("Last Name").":"; + break; + case "email": + $ftitle=$elang->gT("Email").":"; + break; + case "id": + $ftitle=$elang->gT("ID").":"; + break; + case "token": + $ftitle=$elang->gT("Token").":"; + break; + case "tid": + $ftitle=$elang->gT("Token ID").":"; + break; + case "startlanguage": + $ftitle=$elang->gT("Language").":"; + break; + default: + if (substr($fieldinfo,0,10)=='attribute_') + { + $ftitle=$attributeFieldAndNames[$fieldinfo]; + } + else + { + $fielddata=$outmap[$fieldinfo]; + if (isset($fielddata['title']) && !isset($ftitle)) {$ftitle=$fielddata['title'].":";} + } + } // switch + } + } + if ($fqid == 0) + { + $ftype = "-"; // This is set if it not a normal answer field, but something like tokenID, First Name etc + } + if ($type == "csv") {$exportoutput .= "\"";} + if ($type == "doc") {$exportoutput .= "\n$ftitle\n\t";} + if ($type == "pdf"){ $pdf->intopdf($ftitle);} + switch ($ftype) + { + case "-": //SPECIAL Placeholder TYPE + $exportoutput .= $drow[$i]; + if($type == "pdf"){$pdf->intopdf($drow[$i]);} + break; + case "R": //RANKING TYPE + $lq = "SELECT * FROM {$dbprefix}answers WHERE qid=$fqid AND language='$explang' AND code = ?"; + $lr = db_execute_assoc($lq, array($drow[$i])); + while ($lrow = $lr->FetchRow()) + { + $exportoutput .= strip_tags_full($lrow['answer']); + if($type == "pdf"){$pdf->intopdf(strip_tags_full($lrow['answer']));} + } + break; + case "1": + if (mb_substr($fieldinfo,-1) == 0) + { + $lq = "select a.*, l.*, l.code as lcode, l.title as ltitle from {$dbprefix}answers as a, {$dbprefix}labels as l where qid=$fqid AND l.lid =$flid AND a.language='$explang' AND l.code = ? group by l.lid"; + } + else + { + $lq = "select a.*, l.*, l.code as lcode, l.title as ltitle from {$dbprefix}answers as a, {$dbprefix}labels as l where qid=$fqid AND l.lid =$flid1 AND a.language='$explang' AND l.code = ? group by l.lid"; + } + $lr = db_execute_assoc($lq, array($drow[$i])) or safe_die($lq."
      ERROR:
      ".$connect->ErrorMsg()); + while ($lrow = $lr->FetchRow()) + { + $exportoutput .= strip_tags_full($lrow['ltitle']); + if($type == "pdf"){$pdf->intopdf(strip_tags_full($lrow['ltitle']));} + } + break; + case "L": //DROPDOWN LIST + case "!": + if (mb_substr($fieldinfo, -5, 5) == "other") + { + $exportoutput .= strip_tags_full($drow[$i]); + if($type == "pdf"){$pdf->intopdf($drow[$i]);} + } + else + { + if ($drow[$i] == "-oth-") + { + $exportoutput .= $elang->gT("Other"); + if($type == "pdf"){$pdf->intopdf($elang->gT("Other"));} + } + else + { + $lq = "SELECT * FROM {$dbprefix}answers WHERE qid=$fqid AND language='$explang' AND code = ?"; + $lr = db_execute_assoc($lq, array($drow[$i])) or safe_die($lq."
      ERROR:
      ".$connect->ErrorMsg()); + while ($lrow = $lr->FetchRow()) + { + //if ($lrow['code'] == $drow[$i]) {$exportoutput .= $lrow['answer'];} + if ($type == "csv") + { + $exportoutput .= str_replace("\"", "\"\"", strip_tags_full($lrow['answer'])); + if($type == "pdf"){$pdf->intopdf(str_replace("\"", "\"\"", strip_tags_full($lrow['answer'])));} + } + else + { + $exportoutput .= strip_tags_full($lrow['answer']); + if($type == "pdf"){$pdf->intopdf(strip_tags_full($lrow['answer']));} + } + + } + } + } + break; + case "W": + case "Z": + if (mb_substr($fieldinfo, -5, 5) == "other") + { + $exportoutput .= strip_tags_full($drow[$i]); + if($type == "pdf"){$pdf->intopdf($drow[$i]);} + } + else + { + if ($drow[$i] == "-oth-") + { + $exportoutput .= $elang->gT("Other"); + if($type == "pdf"){$pdf->intopdf($elang->gT("Other"));} + } + else + { + $fquery = "SELECT * FROM {$dbprefix}labels WHERE lid=$flid AND language='$explang' AND code='$drow[$i]'"; + $fresult = db_execute_assoc($fquery) or safe_die("ERROR:".$fquery."
      ".$qq."
      ".$connect->ErrorMsg()); + while ($frow = $fresult->FetchRow()) + { + $exportoutput .= strip_tags_full($frow['title']); + if($type == "pdf"){$pdf->intopdf($frow['title']);} + } + } + } + break; + case "O": //DROPDOWN LIST WITH COMMENT + $lq = "SELECT * FROM {$dbprefix}answers WHERE qid=$fqid AND language='$explang' ORDER BY answer"; + $lr = db_execute_assoc($lq) or safe_die ("Could do it
      $lq
      ".$connect->ErrorMsg()); + $found = ""; + while ($lrow = $lr->FetchRow()) + { + if ($lrow['code'] == $drow[$i]) + { + $exportoutput .= strip_tags_full($lrow['answer']); + $found = "Y"; + if($type == "pdf"){$pdf->intopdf(strip_tags_full($lrow['answer']));} + } + } + //This following section exports the comment field + if ($found != "Y") + { + if ($type == "csv") + {$exportoutput .= str_replace("\r\n", "\n", str_replace("\"", "\"\"", strip_tags_full($drow[$i])));} + else if ($type == "pdf") + {$pdf->intopdf(str_replace("\r\n", " ", strip_tags_full($drow[$i])));} + else + {$exportoutput .= str_replace("\r\n", " ", $drow[$i]);} + } + break; + case "Y": //YES\NO + switch($drow[$i]) + { + case "Y": + $exportoutput .= $elang->gT("Yes"); + if($type == "pdf"){$pdf->intopdf($elang->gT("Yes"));} + break; + case "N": + $exportoutput .= $elang->gT("No"); + if($type == "pdf"){$pdf->intopdf($elang->gT("No"));} + break; + default: + $exportoutput .= $elang->gT("N/A"); + if($type == "pdf"){$pdf->intopdf($elang->gT("N/A"));} + break; + } + break; + case "G": //GENDER + switch($drow[$i]) + { + case "M": + $exportoutput .= $elang->gT("Male"); + if($type == "pdf"){$pdf->intopdf($elang->gT("Male"));} + break; + case "F": + $exportoutput .= $elang->gT("Female"); + if($type == "pdf"){$pdf->intopdf($elang->gT("Female"));} + break; + default: + $exportoutput .= $elang->gT("N/A"); + if($type == "pdf"){$pdf->intopdf($elang->gT("N/A"));} + break; + } + break; + case "M": //multioption + case "P": + if (mb_substr($fieldinfo, -5, 5) == "other") + { + $exportoutput .= strip_tags_full($drow[$i]); + if($type == "pdf"){$pdf->intopdf($drow[$i]);} + } + elseif (mb_substr($fieldinfo, -7, 7) == "comment") + { + $exportoutput .= strip_tags_full($drow[$i]); + if($type == "pdf"){$pdf->intopdf($drow[$i]);} + } + else + { + switch($drow[$i]) + { + case "Y": + $exportoutput .= $elang->gT("Yes"); + if($type == "pdf"){$pdf->intopdf($elang->gT("Yes"));} + break; + case "N": + $exportoutput .= $elang->gT("No"); + if($type == "pdf"){$pdf->intopdf($elang->gT("No"));} + break; + case "": + $exportoutput .= $elang->gT("No"); + if($type == "pdf"){$pdf->intopdf($elang->gT("No"));} + break; + default: + $exportoutput .= $drow[$i]; + if($type == "pdf"){$pdf->intopdf($drow[$i]);} + break; + } + } + break; + case "C": + switch($drow[$i]) + { + case "Y": + $exportoutput .= $elang->gT("Yes"); + if($type == "pdf"){$pdf->intopdf($elang->gT("Yes")); } + break; + case "N": + $exportoutput .= $elang->gT("No"); + if($type == "pdf"){$pdf->intopdf($elang->gT("No")); } + break; + case "U": + $exportoutput .= $elang->gT("Uncertain"); + if($type == "pdf"){$pdf->intopdf($elang->gT("Uncertain"));} + break; + } + case "E": + switch($drow[$i]) + { + case "I": + $exportoutput .= $elang->gT("Increase"); + if($type == "pdf"){$pdf->intopdf($elang->gT("Increase"));} + break; + case "S": + $exportoutput .= $elang->gT("Same"); + if($type == "pdf"){$pdf->intopdf($elang->gT("Same"));} + break; + case "D": + $exportoutput .= $elang->gT("Decrease"); + if($type == "pdf"){$pdf->intopdf($elang->gT("Decrease"));} + break; + } + break; + case "F": + case "H": + if (!isset($labelscache[$flid.'|'.$explang.'|'.$drow[$i]])) + { + $fquery = "SELECT * FROM {$dbprefix}labels WHERE lid=$flid AND language='$explang' AND code='$drow[$i]'"; + $fresult = db_execute_assoc($fquery) or safe_die("ERROR:".$fquery."\n".$qq."\n".$connect->ErrorMsg()); + if ($fresult) + { + $frow=$fresult->FetchRow(); + if($type == "pdf"){$pdf->intopdf(strip_tags_full($frow['title']));} + $exportoutput .= strip_tags_full($frow['title']); + $labelscache[$flid.'|'.$explang.'|'.$drow[$i]]=strip_tags_full($frow['title']); + } + } + else + { + $exportoutput .=$labelscache[$flid.'|'.$explang.'|'.$drow[$i]]; + if($type == "pdf"){$pdf->intopdf($labelscache[$flid.'|'.$explang.'|'.$drow[$i]]);} + } + break; + case "1": //dual scale + $flid=$fielddata['lid']; + $flid1=$fielddata['lid1']; + if (mb_substr($fieldinfo,-1) == '0') + { + $strlabel = "1"; + $lq = "select title from {$dbprefix}labels as l where l.lid = $flid AND l.language='$surveybaselang'"; + } + else + { + $strlabel = "2"; + $lq = "select title from {$dbprefix}labels as l where l.lid = $flid1 AND l.language='$surveybaselang'"; + } + $lr = db_execute_assoc($lq); + while ($lrow=$lr->FetchRow()) + { + $fquest .= " [".strip_tags_full($lrow['title'])."][".strip_tags_full($strlabel).". label]"; + } + + break; + + default: $tempresult=$dresult->FetchField($i); + if ($tempresult->name == "token") + { + $tokenquery = "SELECT firstname, lastname FROM {$dbprefix}tokens_$surveyid WHERE token='$drow[$i]'"; + if ($tokenresult = db_execute_assoc($tokenquery)) //or safe_die ("Couldn't get token info
      $tokenquery
      ".$connect->ErrorMsg()); + while ($tokenrow=$tokenresult->FetchRow()) + { + $exportoutput .= "{$tokenrow['lastname']}, {$tokenrow['firstname']}"; + if($type == "pdf"){$pdf->intopdf($tokenrow['lastname']." , ".$tokenrow['firstname']);} + } + else + { + $exportoutput .= $elang->gT("Tokens problem - token table missing"); + if($type == "pdf"){$pdf->intopdf($elang->gT("Tokens problem - token table missing"));} + } + } + else + { + if ($type == "csv") + {$exportoutput .= str_replace("\r\n", "\n", str_replace("\"", "\"\"", strip_tags_full($drow[$i])));} + else if ($type == "pdf") + {$pdf->intopdf(str_replace("\r\n", " ", strip_tags_full($drow[$i])));} + else + {$exportoutput .= str_replace("\r\n", " ", $drow[$i]);} + } + } + if ($type == "csv") {$exportoutput .= "\"";} + $exportoutput .= "$separator"; + $ftype = ""; + } + $exportoutput=mb_substr($exportoutput,0,-(strlen($separator))); + IF ($type=='xls') + { + $rowarray=explode($separator, $exportoutput); + $fli=0; + foreach ($rowarray as $row) + { + $sheet->write($rowcounter,$fli,$row); + $fli++; + } + $exportoutput=''; + } + else {$exportoutput .= "\n";} + } +} + if ($type=='xls') + { + $workbook->close(); + } + else if($type=='pdf') + { + $pdf->Output($clang->gT($surveyname)." ".$surveyid.".pdf","D"); + } + else + { + echo $exportoutput; + } + exit; + + + function strip_tags_full($string) { + $string=html_entity_decode($string, ENT_QUOTES, "UTF-8"); + mb_regex_encoding('utf-8'); + $pattern = array('\r', '\n', '-oth-'); + for ($i=0; $i diff --git a/include/limesurvey/admin/fck_LimeReplacementFields.php b/include/limesurvey/admin/fck_LimeReplacementFields.php index 3e6bf0b0..d69b0d91 100644 --- a/include/limesurvey/admin/fck_LimeReplacementFields.php +++ b/include/limesurvey/admin/fck_LimeReplacementFields.php @@ -10,7 +10,7 @@ * other free or open source software licenses. * See COPYRIGHT.php for copyright notices and details. * -* $Id: conditions.php 3736 2007-11-30 16:13:55Z lemeur $ +* $Id: fck_LimeReplacementFields.php 7161 2009-06-22 19:13:21Z lemeur $ */ include_once("login_check.php"); @@ -32,19 +32,30 @@ $InsertansUnsupportedtypes=Array(); // Currently all question types are supporte $replFields=Array(); $isInstertansEnabled=false; -$limereplacementoutput="" - . "\n" + . "\t\t\n" + . "\t\t\n"; + . "}\n"; +**/ + +$limereplacementoutput .= "" + . "\t\t\tfunction LoadSelected()\n" + . "\t\t\t{\n" + . "\t\t\t\tif ( !eSelected )\n" + . "\t\t\t\t\treturn ;\n" + . "\t\t\t\tif ( eSelected.tagName == 'SPAN' && eSelected._fckLimeReplacementFields )\n" + . "\t\t\t\t\t document.getElementById('cquestions').value = eSelected._fckLimeReplacementFields ;\n" + . "\t\t\t\telse\n" + . "\t\t\t\t\teSelected == null ;\n" + . "\t\t\t}\n"; -$limereplacementoutput .= "
      "; +$limereplacementoutput .= "" + . "\t\t\tfunction Ok()\n" + . "\t\t\t{\n" + . "\t\t\t\tvar sValue = document.getElementById('cquestions').value ;\n" + + . "\t\t\t\tFCKLimeReplacementFieldss.Add( sValue ) ;\n" + . "\t\t\t\treturn true ;\n" + . "\t\t\t}\n"; + +$limereplacementoutput .= "" + . "\t\t\t\n" + . "\t\t\n"; + +$limereplacementoutput .= "\t\n" + . "\t\t\n" + . "\t\t\t\n" + . "\t\t\t\t\n"; + $limereplacementoutput .= "\t\t\t\n" + . "\t\t\t\t\n" + . "\t\t\t\n"; break; case 'G': - $limereplacementoutput .= "\n"; + $limereplacementoutput .= "\t\t\t\n" + . "\t\t\t\t\n" + . "\t\t\t\n"; break; } } -$limereplacementoutput .= "
      \n"; switch ($fieldtype) { case 'survey-desc': case 'survey-welc': + case 'survey-endtext': $replFields[]=array('TOKEN:FIRSTNAME',$clang->gT("Firstname from token")); $replFields[]=array('TOKEN:LASTNAME',$clang->gT("Lastname from token")); $replFields[]=array('TOKEN:EMAIL',$clang->gT("Email from the token")); - $replFields[]=array('TOKEN:ATTRIBUTE_1',$clang->gT("Attribute_1 from token")); - $replFields[]=array('TOKEN:ATTRIBUTE_2',$clang->gT("Attribute_2 from token")); + $attributes=GetTokenFieldsAndNames($surveyid,true); + foreach ($attributes as $attributefield=>$attributedescription) + { + $replFields[]=array('TOKEN:'.strtoupper($attributefield), sprintf($clang->gT("Token attribute: %s"),$attributedescription)); + } + $replFields[]=array('EXPIRY',$clang->gT("Survey expiration date (YYYY-MM-DD)")); + $replFields[]=array('EXPIRY-DMY',$clang->gT("Survey expiration date (DD-MM-YYYY)")); + $replFields[]=array('EXPIRY-MDY',$clang->gT("Survey expiration date (MM-DD-YYYY)")); break; case 'email-inv': @@ -99,11 +141,17 @@ switch ($fieldtype) $replFields[]=array('LASTNAME',$clang->gT("Lastname from token")); $replFields[]=array('SURVEYNAME',$clang->gT("Name of the survey")); $replFields[]=array('SURVEYDESCRIPTION',$clang->gT("Description of the survey")); - $replFields[]=array('ATTRIBUTE_1',$clang->gT("Attribute_1 from token")); - $replFields[]=array('ATTRIBUTE_2',$clang->gT("Attribute_2 from token")); + $attributes=GetTokenFieldsAndNames($surveyid,true); + foreach ($attributes as $attributefield=>$attributedescription) + { + $replFields[]=array(strtoupper($attributefield), sprintf($clang->gT("Token attribute: %s"),$attributedescription)); + } $replFields[]=array('ADMINNAME',$clang->gT("Name of the survey administrator")); $replFields[]=array('ADMINEMAIL',$clang->gT("Email address of the survey administrator")); $replFields[]=array('SURVEYURL',$clang->gT("URL of the survey")); + $replFields[]=array('EXPIRY',$clang->gT("Survey expiration date (YYYY-MM-DD)")); + $replFields[]=array('EXPIRY-DMY',$clang->gT("Survey expiration date (DD-MM-YYYY)")); + $replFields[]=array('EXPIRY-MDY',$clang->gT("Survey expiration date (MM-DD-YYYY)")); break; case 'group-desc': @@ -112,10 +160,21 @@ switch ($fieldtype) $replFields[]=array('TOKEN:FIRSTNAME',$clang->gT("Firstname from token")); $replFields[]=array('TOKEN:LASTNAME',$clang->gT("Lastname from token")); $replFields[]=array('TOKEN:EMAIL',$clang->gT("Email from the token")); - $replFields[]=array('TOKEN:ATTRIBUTE_1',$clang->gT("Attribute_1 from token")); - $replFields[]=array('TOKEN:ATTRIBUTE_2',$clang->gT("Attribute_2 from token")); + $attributes=GetTokenFieldsAndNames($surveyid,true); + foreach ($attributes as $attributefield=>$attributedescription) + { + $replFields[]=array('TOKEN:'.strtoupper($attributefield), sprintf($clang->gT("Token attribute: %s"),$attributedescription)); + } + $replFields[]=array('EXPIRY',$clang->gT("Survey expiration date (YYYY-MM-DD)")); + $replFields[]=array('EXPIRY-DMY',$clang->gT("Survey expiration date (DD-MM-YYYY)")); + $replFields[]=array('EXPIRY-MDY',$clang->gT("Survey expiration date (MM-DD-YYYY)")); + case 'editanswer': $isInstertansEnabled=true; break; + case 'assessment-text': + $replFields[]=array('TOTAL',$clang->gT("Overall assessment score")); + $replFields[]=array('PERC',$clang->gT("Assessment group score")); + break; } @@ -178,6 +237,7 @@ if ($isInstertansEnabled===true) } break; + case 'editanswer': case 'copyquestion': case 'editquestion': if (empty($gid)) {die("No GID provided.");} @@ -314,6 +374,40 @@ if ($isInstertansEnabled===true) } //while } //if A,B,C,E,F,H + elseif ($rows['type'] == ":" || $rows['type'] == ";") // Multiflexi + { + //Get the LIDs + $fquery = "SELECT * " + ."FROM {$dbprefix}labels " + ."WHERE lid={$rows['lid']} " + ."AND language='".GetBaseLanguageFromSurveyID($surveyid)."' " + ."ORDER BY sortorder, code "; + $fresult = db_execute_assoc($fquery); + while ($frow=$fresult->FetchRow()) + { + $lids[$frow['code']]=$frow['title']; + } + //Now cycle through the answers + $aquery="SELECT * " + ."FROM {$dbprefix}answers " + ."WHERE qid={$rows['qid']} " + ."AND {$dbprefix}answers.language='".GetBaseLanguageFromSurveyID($surveyid)."' " + ."ORDER BY sortorder, " + ."answer"; + $aresult=db_execute_assoc($aquery) or safe_die ("Couldn't get answers to Array questions
      $aquery
      ".$connect->ErrorMsg()); + + while ($arows = $aresult->FetchRow()) + { + $shortanswer = strip_tags($arows['answer']); + + $shortanswer .= " [{$arows['code']}]"; + foreach($lids as $key=>$val) + { + $cquestions[]=array("$shortquestion [$shortanswer [$val]] ", $rows['qid'], $rows['type'], $rows['sid'].$X.$rows['gid'].$X.$rows['qid'].$arows['code']."_".$key,$rows['previouspage']); + } + } + + } //TIBO elseif ($rows['type'] == "R") //Answer Ranking { $aquery="SELECT * " @@ -396,30 +490,33 @@ if ($isInstertansEnabled===true) if (count($replFields) > 0 || isset($cquestions) ) { - $limereplacementoutput .= "\t\t\t\n"; + $noselection = false; } else { - $limereplacementoutput = $clang->gT("No replacement variable available for this field"); - echo $limereplacementoutput; - return; + $limereplacementoutput .= $clang->gT("No replacement variable available for this field"); + //echo $limereplacementoutput; + //return; + $noselection = true; + } if (count($replFields) > 0) { - $limereplacementoutput .= "\t\t\t\t\n"; + $limereplacementoutput .= "\t\t\t\t\t\t\n"; foreach ($replFields as $stdfield) { - $limereplacementoutput .= "\t\t\t\t\n"; + $limereplacementoutput .= "\t\t\t\t\t\t\n"; } if (isset($cquestions)) { - $limereplacementoutput .= "\t\t\t\t\n"; + $limereplacementoutput .= "\t\t\t\t\t\t\n"; foreach ($cquestions as $cqn) { $isDisabled=""; @@ -432,36 +529,53 @@ if (isset($cquestions)) $isDisabled=" disabled='disabled'"; } - $limereplacementoutput .= "\t\t\t\t
      \n"; - $limereplacementoutput .= "
      ".$clang->gT("Some Question have been disabled").""; - $limereplacementoutput .= "
      ".sprintf($clang->gT("Survey Format is %s:"), $clang->gT("All in one"))."
      ".$clang->gT("Only Previous pages answers are available")."
      "; - $limereplacementoutput .= "
      \n"; + $limereplacementoutput .= "\t\t\t\t\t
      \n" + . "\t\t\t\t\t".$clang->gT("Some Question have been disabled")."\n"; + $limereplacementoutput .= "\t\t\t\t\t
      \n" + . "\t\t\t\t\t".sprintf($clang->gT("Survey Format is %s:"), $clang->gT("All in one")) + . "\t\t\t\t\t
      \n" + . "\t\t\t\t\t".$clang->gT("Only Previous pages answers are available")."\n" + . "\t\t\t\t\t
      \n"; + $limereplacementoutput .= "\t\t\t\t
      \n"; - $limereplacementoutput .= "
      ".$clang->gT("Some Question have been disabled").""; - $limereplacementoutput .= "
      ".sprintf($clang->gT("Survey mode is set to %s:"), $clang->gT("Group by Group"))."
      ".$clang->gT("Only Previous pages answers are available")."
      "; $limereplacementoutput .= "
      \n"; + $limereplacementoutput .= "\t\t\t\t\t
      ".$clang->gT("Some Question have been disabled").""; + $limereplacementoutput .= "
      ".sprintf($clang->gT("Survey mode is set to %s:"), $clang->gT("Group by Group"))."
      ".$clang->gT("Only Previous pages answers are available")."
      "; + $limereplacementoutput .= "\t\t\t\t
      \n"; +$limereplacementoutput .= "\t\t
      \n" + . "\t\n" + . ""; echo $limereplacementoutput; - +exit; ?> diff --git a/include/limesurvey/admin/grouphandling.php b/include/limesurvey/admin/grouphandling.php index 1a6f89df..ae96563f 100644 --- a/include/limesurvey/admin/grouphandling.php +++ b/include/limesurvey/admin/grouphandling.php @@ -1,175 +1,182 @@ -
      \n\t\t".$clang->gT("Add Group")."
      \n"; - - -// $newgroupoutput .="\n\t\n" + ."\t" + ."
      \n" - $newgroupoutput .= "
      "; - $newgroupoutput .="\n" - . '
      '; - foreach ($grplangs as $grouplang) - { - $newgroupoutput .= '

      '.GetLanguageNameFromCode($grouplang,false); - if ($grouplang==$baselang) {$newgroupoutput .= '('.$clang->gT("Base Language").')';} - $newgroupoutput .= "

      " - . "" - . "\t\t\n" - . "\t\t\n" - . "\t\n" - . "\t\t\n" - . "
      ".$clang->gT("Title").": ".$clang->gT("Required")."
      ".$clang->gT("Description:")."" - . getEditor("group-desc","description_".$grouplang, "[".$clang->gT("Description:", "js")."](".$grouplang.")",$surveyid,'','',$action) - ."
      "; - $newgroupoutput.= "\t
      \n" - . "\t
      \n" - . "\n"; - $newgroupoutput.= "
      \n"; - - } - - $newgroupoutput.= "" - . "\t\n" - . "\t\n" - . "\n"; - - - // Import TAB - $newgroupoutput .= '

      '.$clang->gT("Import Group")."

      \n"; - $newgroupoutput.= "" - . "
      \n" - . "\n" - . "\t\t" - . "\t\n" - . "\t\t\n" - . "\t\t\n" - . "\t\t\t\t\n" - . "\t\t\n" - . "\t\n
      ".$clang->gT("Select CSV File:")."
      ".$clang->gT("Convert Resources links ?")."
      \n" - . "\t\n" - . "\t\n" - . "\t
      \n"; - - // End Import TABS - $newgroupoutput.= "
      "; - - // End of TABS - $newgroupoutput.= "
      "; - - $newgroupoutput.= "" - ."\n"; -} - - -if ($action == "editgroup") -{ - $grplangs = GetAdditionalLanguagesFromSurveyID($surveyid); - $baselang = GetBaseLanguageFromSurveyID($surveyid); - - $grplangs[] = $baselang; - $grplangs = array_flip($grplangs); - - $egquery = "SELECT * FROM ".db_table_name('groups')." WHERE sid=$surveyid AND gid=$gid"; - $egresult = db_execute_assoc($egquery); - while ($esrow = $egresult->FetchRow()) - { - if(!array_key_exists($esrow['language'], $grplangs)) // Language Exists, BUT ITS NOT ON THE SURVEY ANYMORE. - { - $egquery = "DELETE FROM ".db_table_name('groups')." WHERE sid='{$surveyid}' AND gid='{$gid}' AND language='".$esrow['language']."'"; - $egresultD = $connect->Execute($egquery); - } else { - $grplangs[$esrow['language']] = 99; - } - if ($esrow['language'] == $baselang) $basesettings = array('group_name' => $esrow['group_name'],'description' => $esrow['description'],'group_order' => $esrow['group_order']); - - } - - while (list($key,$value) = each($grplangs)) - { - if ($value != 99) - { - $egquery = "INSERT INTO ".db_table_name('groups')." (gid, sid, group_name, description,group_order,language) VALUES ('{$gid}', '{$surveyid}', '{$basesettings['group_name']}', '{$basesettings['description']}','{$basesettings['group_order']}', '{$key}')"; - $egresult = $connect->Execute($egquery); - } - } - - $egquery = "SELECT * FROM ".db_table_name('groups')." WHERE sid=$surveyid AND gid=$gid AND language='$baselang'"; - $egresult = db_execute_assoc($egquery); - $editgroup = PrepareEditorScript(); - $editgroup .= "\n\t
      " - . "\t\t".$clang->gT("Edit Group")."
      \n" - . "
      \n" - . '
      '; - - $esrow = $egresult->FetchRow(); - $editgroup .= '

      '.getLanguageNameFromCode($esrow['language'],false); - $editgroup .= '('.$clang->gT("Base Language").')'; - $esrow = array_map('htmlspecialchars', $esrow); - $editgroup .= '

      '; - $editgroup .= "\t
      ".$clang->gT("Title").":\n" - . "\t\t\n" - . "\t
      \n" - . "\t
      ".$clang->gT("Description:")."\n" - . "\t\t\n" - . getEditor("group-desc","description_".$esrow['language'], "[".$clang->gT("Description:", "js")."](".$esrow['language'].")",$surveyid,$gid,'',$action) - . "\t
      "; // THis empty div class is needed for forcing the tabpage border under the button - - - $egquery = "SELECT * FROM ".db_table_name('groups')." WHERE sid=$surveyid AND gid=$gid AND language!='$baselang'"; - $egresult = db_execute_assoc($egquery); - while ($esrow = $egresult->FetchRow()) - { - $editgroup .= '

      '.getLanguageNameFromCode($esrow['language'],false); - $esrow = array_map('htmlspecialchars', $esrow); - $editgroup .= '

      '; - $editgroup .= "\t
      ".$clang->gT("Title").":\n" - . "\t\t\n" - . "\t
      \n" - . "\t
      ".$clang->gT("Description:")."\n" - . "\t\t\n" - . getEditor("group-desc","description_".$esrow['language'], "[".$clang->gT("Description:", "js")."](".$esrow['language'].")",$surveyid,$gid,'',$action) - . "\t
      "; // THis empty div class is needed for forcing the tabpage border under the button - } - $editgroup .= '
      '; - $editgroup .= "\t

      \n" - . "\t\n" - . "\t\n" - . "\t\n" - . "\t\n" - . "\t

      \n" - . "
      \n"; -} - - -?> +
      \n\t\t".$clang->gT("Add Group")."
      \n"; + + +// $newgroupoutput .="\n\t\n" - - . "\t\t\t\t\t\n" - - . "\t\t\n" - . "\t\n" - . "\t
      \n" + $newgroupoutput .="\n" + . '
      '; + $newgroupoutput .= "
      gT("Error: You have to enter a group title for each language.",'js')."'); return false;}\" "; + + foreach ($grplangs as $grouplang) + { + $newgroupoutput .= '

      '.GetLanguageNameFromCode($grouplang,false); + if ($grouplang==$baselang) {$newgroupoutput .= '('.$clang->gT("Base Language").')';} + $newgroupoutput .= "

      " + . "" + . "\t\t\n" + . "\t\t\n" + . "\t\n" + . "\t\t\n" + . "
      ".$clang->gT("Title").": ".$clang->gT("Required")."
      ".$clang->gT("Description:")."" + . getEditor("group-desc","description_".$grouplang, "[".$clang->gT("Description:", "js")."](".$grouplang.")",$surveyid,'','',$action) + ."
      "; + $newgroupoutput.= "\t
      \n" + . "\t
      \n" + . "\n"; + $newgroupoutput.= "
      \n"; + + } + + $newgroupoutput.= "" + . "\t\n" + . "\t\n" + . "
      \n"; + + + // Import TAB + $newgroupoutput .= '

      '.$clang->gT("Import Group")."

      \n"; + $newgroupoutput.= "" + . "
      \n" + . "\n" + . "\t\t" + . "\t\n" + . "\t\t\n" + . "\t\t\n" + . "\t\t\t\t\n" + . "\t\t\n" + . "\t\n
      ".$clang->gT("Select CSV File:")."
      ".$clang->gT("Convert resources links?")."
      \n" + . "\t\n" + . "\t\n" + . "\t
      \n"; + + // End Import TABS + $newgroupoutput.= "
      "; + + // End of TABS + $newgroupoutput.= "
      "; + + $newgroupoutput.= "" + ."\n"; +} + + +if ($action == "editgroup") +{ + $grplangs = GetAdditionalLanguagesFromSurveyID($surveyid); + $baselang = GetBaseLanguageFromSurveyID($surveyid); + + $grplangs[] = $baselang; + $grplangs = array_flip($grplangs); + + $egquery = "SELECT * FROM ".db_table_name('groups')." WHERE sid=$surveyid AND gid=$gid"; + $egresult = db_execute_assoc($egquery); + while ($esrow = $egresult->FetchRow()) + { + if(!array_key_exists($esrow['language'], $grplangs)) // Language Exists, BUT ITS NOT ON THE SURVEY ANYMORE. + { + $egquery = "DELETE FROM ".db_table_name('groups')." WHERE sid='{$surveyid}' AND gid='{$gid}' AND language='".$esrow['language']."'"; + $egresultD = $connect->Execute($egquery); + } else { + $grplangs[$esrow['language']] = 99; + } + if ($esrow['language'] == $baselang) $basesettings = array('group_name' => $esrow['group_name'],'description' => $esrow['description'],'group_order' => $esrow['group_order']); + + } + + while (list($key,$value) = each($grplangs)) + { + if ($value != 99) + { + $egquery = "INSERT INTO ".db_table_name('groups')." (gid, sid, group_name, description,group_order,language) VALUES ('{$gid}', '{$surveyid}', '{$basesettings['group_name']}', '{$basesettings['description']}','{$basesettings['group_order']}', '{$key}')"; + $egresult = $connect->Execute($egquery); + } + } + + $egquery = "SELECT * FROM ".db_table_name('groups')." WHERE sid=$surveyid AND gid=$gid AND language='$baselang'"; + $egresult = db_execute_assoc($egquery); + $editgroup = PrepareEditorScript(); + $editgroup .= "\n\t
      " + . "\t\t".$clang->gT("Edit Group")."
      \n" + . "
      \n" + . '
      '; + + $esrow = $egresult->FetchRow(); + $editgroup .= '

      '.getLanguageNameFromCode($esrow['language'],false); + $editgroup .= '('.$clang->gT("Base Language").')'; + $esrow = array_map('htmlspecialchars', $esrow); + $editgroup .= '

      '; + $editgroup .= "\t
      ".$clang->gT("Title").":\n" + . "\t\t\n" + . "\t
      \n" + . "\t
      ".$clang->gT("Description:")."\n" + . "\t\t\n" + . getEditor("group-desc","description_".$esrow['language'], "[".$clang->gT("Description:", "js")."](".$esrow['language'].")",$surveyid,$gid,'',$action) + . "\t
      "; // THis empty div class is needed for forcing the tabpage border under the button + + + $egquery = "SELECT * FROM ".db_table_name('groups')." WHERE sid=$surveyid AND gid=$gid AND language!='$baselang'"; + $egresult = db_execute_assoc($egquery); + while ($esrow = $egresult->FetchRow()) + { + $editgroup .= '

      '.getLanguageNameFromCode($esrow['language'],false); + $esrow = array_map('htmlspecialchars', $esrow); + $editgroup .= '

      '; + $editgroup .= "\t
      ".$clang->gT("Title").":\n" + . "\t\t\n" + . "\t
      \n" + . "\t
      ".$clang->gT("Description:")."\n" + . "\t\t\n" + . getEditor("group-desc","description_".$esrow['language'], "[".$clang->gT("Description:", "js")."](".$esrow['language'].")",$surveyid,$gid,'',$action) + . "\t
      "; // THis empty div class is needed for forcing the tabpage border under the button + } + $editgroup .= '
      '; + $editgroup .= "\t

      \n" + . "\t\n" + . "\t\n" + . "\t\n" + . "\t\n" + . "\t

      \n" + . "
      \n"; +} + + +?> diff --git a/include/limesurvey/admin/html.php b/include/limesurvey/admin/html.php index 34c275b1..77a6fb6b 100644 --- a/include/limesurvey/admin/html.php +++ b/include/limesurvey/admin/html.php @@ -1,3238 +1,3621 @@ -ErrorMsg()); //Checked - - if($result->RecordCount() > 0) { - $listsurveys= "
      - - - - - - - - - - - - "; - $gbc = "evenrow"; - - while($rows = $result->FetchRow()) - { - $sidsecurityQ = "SELECT b.* FROM {$dbprefix}surveys AS a INNER JOIN {$dbprefix}surveys_rights AS b ON a.sid = b.sid WHERE a.sid='{$rows['sid']}' AND b.uid = ".$_SESSION['loginID']; //Getting rights for this survey and user - $sidsecurityR = db_execute_assoc($sidsecurityQ); //Checked - $sidsecurity = $sidsecurityR->FetchRow(); - - if($rows['private']=="Y") - { - $privacy=$clang->gT("Anonymous") ; - } - else $privacy =$clang->gT("Not Anonymous") ; - - - if (bHasSurveyGotTokentable(null,$rows['sid'])) - { - $visibility = $clang->gT("Closed-access"); - } - else - { - $visibility = $clang->gT("Open-access"); - } - - if($rows['active']=="Y") - { - if ($rows['useexpiry']=='Y' && $rows['expires'] < date_shift(date("Y-m-d H:i:s"), "Y-m-d", $timeadjust)) - { - $status=$clang->gT("Expired") ; - } else { - $status=$clang->gT("Active") ; - } - // Complete Survey Responses - added by DLR - $gnquery = "SELECT count(id) FROM ".db_table_name("survey_".$rows['sid'])." WHERE submitdate IS NULL"; - $gnresult = db_execute_num($gnquery); //Checked - while ($gnrow = $gnresult->FetchRow()) - { - $partial_responses=$gnrow[0]; - } - $gnquery = "SELECT count(id) FROM ".db_table_name("survey_".$rows['sid']); - $gnresult = db_execute_num($gnquery); //Checked - while ($gnrow = $gnresult->FetchRow()) - { - $responses=$gnrow[0]; - } - - } - else $status =$clang->gT("Inactive") ; - - $datecreated=$rows['datecreated'] ; - - if (in_array($rows['owner_id'],getuserlist('onlyuidarray'))) - { - $ownername=$rows['users_name'] ; - } - else - { - $ownername="---"; - } - - $questionsCount = 0; - $questionsCountQuery = "SELECT * FROM ".db_table_name('questions')." WHERE sid={$rows['sid']} AND language='".$rows['language']."'"; //Getting a count of questions for this survey - $questionsCountResult = $connect->Execute($questionsCountQuery); //Checked - $questionsCount = $questionsCountResult->RecordCount(); - - if ($gbc == "oddrow") {$gbc = "evenrow";} - else {$gbc = "oddrow";} - $listsurveys.=""; - - if ($rows['active']=="Y") - { - if ($rows['useexpiry']=='Y' && $rows['expires'] < date_shift(date("Y-m-d H:i:s"), "Y-m-d", $timeadjust)) - { - $listsurveys .= "\n"; - } else - { - $listsurveys .= "\n"; - } - } - } else { - if ( ($_SESSION['USER_RIGHT_SUPERADMIN'] ==1 || $sidsecurity['activate_survey']) && $questionsCount > 0) - { - $listsurveys .= "\n" ; - } else - { - $listsurveys .= "\n"; - } - } - - $listsurveys.="". - "". - "". - "" . - "" . - ""; - - if ($rows['active']=="Y") - { - $complete = $responses - $partial_responses; - $listsurveys .= ""; - $listsurveys .= ""; - $listsurveys .= ""; - }else{ - $listsurveys .= ""; - $listsurveys .= ""; - $listsurveys .= ""; - } - $listsurveys .= "" ; - } - - $listsurveys.=" - ". - ""; - $listsurveys.="
       ".$clang->gT("Survey")."".$clang->gT("Date Created")."".$clang->gT("Owner")."".$clang->gT("Access")."".$clang->gT("Answer Privacy")."".$clang->gT("Status")."".$clang->gT("Full Responses")."".$clang->gT("Partial Responses")."".$clang->gT("Total Responses")."
      gT("This survey is active but expired", "js")."');return false\" />\n"; - } - else - { - if ($_SESSION['USER_RIGHT_SUPERADMIN'] ==1 || $sidsecurity['activate_survey']) - { - $listsurveys .= "gTview("De-activate this Survey")."\" " - . "onmouseover=\"showTooltip(event,'".$clang->gT("De-activate this Survey", "js")."');return false\">" - . "gTview("This survey is currently active")."\"" - . "onmouseover=\"showTooltip(event,'".$clang->gT("This survey is currently active", "js")."');return false\" />gTview("Activate this Survey")."\"" - . "onmouseover=\"showTooltip(event,'".$clang->gT("Activate this Survey", "js")."');return false\">" . - "".$clang->gT("Activate this Survey")."".$clang->gT("This survey is not currently active")."gT("This survey is not currently active", "js")."');return false\" />".$rows['surveyls_title']."".$datecreated."".$ownername."".$visibility."".$privacy."".$status."".$complete."".$partial_responses."".$responses."   
       

      " ; - } - else $listsurveys="
      ".$clang->gT("No Surveys available - please create one.")."

      " ; -} - -if ($action == "checksettings" || $action == "changelang" || $action=="changehtmleditormode") -{ - //GET NUMBER OF SURVEYS - $query = "SELECT sid FROM ".db_table_name('surveys'); - $result = $connect->Execute($query); //Checked - $surveycount=$result->RecordCount(); - $query = "SELECT sid FROM ".db_table_name('surveys')." WHERE active='Y'"; - $result = $connect->Execute($query); //Checked - $activesurveycount=$result->RecordCount(); - $query = "SELECT users_name FROM ".db_table_name('users'); - $result = $connect->Execute($query); //Checked - $usercount = $result->RecordCount(); - - // prepare data for the htmleditormode preference - $edmod1=''; - $edmod2=''; - $edmod3=''; - $edmod4=''; - switch ($_SESSION['htmleditormode']) - { - case 'none': - $edmod2="selected='selected'"; - break; - case 'inline': - $edmod3="selected='selected'"; - break; - case 'popup': - $edmod4="selected='selected'"; - break; - default: - $edmod1="selected='selected'"; - break; - } - - $tablelist = $connect->MetaTables(); - foreach ($tablelist as $table) - { - $stlength=strlen($dbprefix).strlen("old"); - if (substr($table, 0, $stlength+strlen("_tokens")) == $dbprefix."old_tokens") - { - $oldtokenlist[]=$table; - } - elseif (substr($table, 0, strlen($dbprefix) + strlen("tokens")) == $dbprefix."tokens") - { - $tokenlist[]=$table; - } - elseif (substr($table, 0, $stlength) == $dbprefix."old") - { - $oldresultslist[]=$table; - } - } - if(isset($oldresultslist) && is_array($oldresultslist)) - {$deactivatedsurveys=count($oldresultslist);} else {$deactivatedsurveys=0;} - if(isset($oldtokenlist) && is_array($oldtokenlist)) - {$deactivatedtokens=count($oldtokenlist);} else {$deactivatedtokens=0;} - if(isset($tokenlist) && is_array($tokenlist)) - {$activetokens=count($tokenlist);} else {$activetokens=0;} - $cssummary = "
      \n" - . "
      " - . "\n" - . "\t\n" - . "\t\t\n" - . "\t\n"; - // Database name & default language - $cssummary .= "\t\n" - . "\t\t\n" - . "\t\n" - . "\t\n" - . "\t\t\n" - . "\t\n"; - // Current language - $cssummary .= "\t\n" - . "\t\t\n" - . "\t\n"; - // Current htmleditormode - $cssummary .= "\t\n" - . "\t\t\n" - . "\t\n"; - // Other infos - $cssummary .= "\t\n" - . "\t\t\n" - . "\t\n" - . "\t\n" - . "\t\t\n" - . "\t\n" - . "\t\n" - . "\t\t\n" - . "\t\n" - . "\t\n" - . "\t\t\n" - . "\t\n" - . "\t\n" - . "\t\t\n" - . "\t\n" - . "\t\n" - . "\t\t\n" - . "\t\n" - . "
      \n" - . "\t\t\t".$clang->gT("LimeSurvey System Summary")."\n" - . "\t\t
      \n" - . "\t\t\t".$clang->gT("Database Name").":\n" - . "\t\t\n" - . "\t\t\t$databasename\n" - . "\t\t
      \n" - . "\t\t\t".$clang->gT("Default Language").":\n" - . "\t\t\n" - . "\t\t\t".getLanguageNameFromCode($defaultlang)."\n" - . "\t\t
      \n" - . "\t\t\t".$clang->gT("Current Language").":\n" - . "\t\t\n" - . "\t\t\t\n" - . "\t\t\t\n" - . "\t\t
      \n" - . "\t\t\t".$clang->gT("Preferred HTML editor mode").":\n" - . "\t\t\n" - . "\t\t\t\n" - . "" - . "\t\t
      \n" - . "\t\t\t".$clang->gT("Users").":\n" - . "\t\t\n" - . "\t\t\t$usercount\n" - . "\t\t
      \n" - . "\t\t\t".$clang->gT("Surveys").":\n" - . "\t\t\n" - . "\t\t\t$surveycount\n" - . "\t\t
      \n" - . "\t\t\t".$clang->gT("Active Surveys").":\n" - . "\t\t\n" - . "\t\t\t$activesurveycount\n" - . "\t\t
      \n" - . "\t\t\t".$clang->gT("De-activated Surveys").":\n" - . "\t\t\n" - . "\t\t\t$deactivatedsurveys\n" - . "\t\t
      \n" - . "\t\t\t".$clang->gT("Active Token Tables").":\n" - . "\t\t\n" - . "\t\t\t$activetokens\n" - . "\t\t
      \n" - . "\t\t\t".$clang->gT("De-activated Token Tables").":\n" - . "\t\t\n" - . "\t\t\t$deactivatedtokens\n" - . "\t\t
      \n" - . "
      \n"; - - if ($_SESSION['USER_RIGHT_CONFIGURATOR'] == 1) - { - $cssummary .= "
      "; - } -} - -if ($surveyid) -{ - $query = "SELECT * FROM ".db_table_name('surveys_rights')." WHERE sid = {$surveyid} AND uid = ".$_SESSION['loginID']; - $result = $connect->SelectLimit($query, 1); - if($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $result->RecordCount() > 0) - { - $baselang = GetBaseLanguageFromSurveyID($surveyid); - $sumquery5 = "SELECT b.* FROM {$dbprefix}surveys AS a INNER JOIN {$dbprefix}surveys_rights AS b ON a.sid = b.sid WHERE a.sid=$surveyid AND b.uid = ".$_SESSION['loginID']; //Getting rights for this survey and user - $sumresult5 = db_execute_assoc($sumquery5); //Checked - $sumrows5 = $sumresult5->FetchRow(); - $sumquery3 = "SELECT * FROM ".db_table_name('questions')." WHERE sid=$surveyid AND language='".$baselang."'"; //Getting a count of questions for this survey - $sumresult3 = $connect->Execute($sumquery3); //Checked - $sumcount3 = $sumresult3->RecordCount(); - $sumquery6 = "SELECT * FROM ".db_table_name('conditions')." as c, ".db_table_name('questions')."as q WHERE c.qid = q.qid AND q.sid=$surveyid"; //Getting a count of conditions for this survey - $sumresult6 = $connect->Execute($sumquery6) or die("Can't coun't conditions"); //Checked - $sumcount6 = $sumresult6->RecordCount(); - $sumquery2 = "SELECT * FROM ".db_table_name('groups')." WHERE sid=$surveyid AND language='".$baselang."'"; //Getting a count of groups for this survey - $sumresult2 = $connect->Execute($sumquery2); //Checked - $sumcount2 = $sumresult2->RecordCount(); - $sumquery1 = "SELECT * FROM ".db_table_name('surveys')." inner join ".db_table_name('surveys_languagesettings')." on (surveyls_survey_id=sid and surveyls_language=language) WHERE sid=$surveyid"; //Getting data for this survey - $sumresult1 = db_select_limit_assoc($sumquery1, 1); //Checked - - // Output starts here... - $surveysummary = "\n"; - - $s1row = $sumresult1->FetchRow(); - - $s1row = array_map('strip_tags', $s1row); - //$s1row = array_map('htmlspecialchars', $s1row); - $activated = $s1row['active']; - //BUTTON BAR - $surveysummary .= "\t\n" - . "\t\t\n" - . "\t\n"; - - //SURVEY SUMMARY - if ($gid || $qid || $action=="deactivate"|| $action=="activate" || $action=="surveysecurity" - || $action=="surveyrights" || $action=="addsurveysecurity" || $action=="addusergroupsurveysecurity" - || $action=="setsurveysecurity" || $action=="setusergroupsurveysecurity" || $action=="delsurveysecurity" - || $action=="editsurvey" || $action=="addgroup" || $action=="importgroup" - || $action=="ordergroups" || $action=="updatesurvey" || $action=="deletesurvey" || $action=="resetsurveylogic" - || $action=="importsurvresources" - || $action=="exportstructure" || $action=="quotas" ) {$showstyle="style='display: none'";} - if (!isset($showstyle)) {$showstyle="";} - $additionnalLanguagesArray = GetAdditionalLanguagesFromSurveyID($surveyid); - $surveysummary .= "\t
      \n" - . "\t\t\t\n" - . "\t\t\t\t\n" - . "\t\t\t\t\n" - . "\t\t\t\t" - . "\n" - . "\t\t\t\n" - . "\t\t
      \n" - . "\t\n"; - $surveysummary2 = ""; - if ($s1row['private'] != "N") {$surveysummary2 .= $clang->gT("Answers to this survey are anonymized.")."
      \n";} - else {$surveysummary2 .= $clang->gT("This survey is NOT anonymous.")."
      \n";} - if ($s1row['format'] == "S") {$surveysummary2 .= $clang->gT("It is presented question by question.")."
      \n";} - elseif ($s1row['format'] == "G") {$surveysummary2 .= $clang->gT("It is presented group by group.")."
      \n";} - else {$surveysummary2 .= $clang->gT("It is presented on one single page.")."
      \n";} - if ($s1row['datestamp'] == "Y") {$surveysummary2 .= $clang->gT("Responses will be date stamped")."
      \n";} - if ($s1row['ipaddr'] == "Y") {$surveysummary2 .= $clang->gT("IP Addresses will be logged")."
      \n";} - if ($s1row['refurl'] == "Y") {$surveysummary2 .= $clang->gT("Referer-URL will be saved")."
      \n";} - if ($s1row['usecookie'] == "Y") {$surveysummary2 .= $clang->gT("It uses cookies for access control.")."
      \n";} - if ($s1row['allowregister'] == "Y") {$surveysummary2 .= $clang->gT("If tokens are used, the public may register for this survey")."
      \n";} - if ($s1row['allowsave'] == "Y") {$surveysummary2 .= $clang->gT("Participants can save partially finished surveys")."
      \n";} - switch ($s1row['notification']) - { - case 0: - $surveysummary2 .= $clang->gT("No email notification")."
      \n"; - break; - case 1: - $surveysummary2 .= $clang->gT("Basic email notification")."
      \n"; - break; - case 2: - $surveysummary2 .= $clang->gT("Detailed email notification with result codes")."
      \n"; - break; - } - - if($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $sumrows5['edit_survey_property']) - { - $surveysummary2 .= $clang->gT("Regenerate Question Codes:") -// . " [gT("Are you sure you want regenerate the question codes?","js")."')) {".get2post("$scriptname?action=renumberquestions&sid=$surveyid&style=straight")."}\" " - . ">".$clang->gT("Straight")."] " -// . "[gT("Are you sure you want regenerate the question codes?","js")."')) {".get2post("$scriptname?action=renumberquestions&sid=$surveyid&style=bygroup")."}\" " - . ">".$clang->gT("By Group")."]"; - $surveysummary2 .= "\n"; - } - $surveysummary .= "\t" - . "\n"; - $tmp_url = $GLOBALS['publicurl'] . '/index.php?sid=' . $s1row['sid']; - $surveysummary .= "\t\t\n" - . "\t\n\t\t\n" - . "\t\n" - . "\t\t\n" - . "\t\t\n" - . "\t\n" - . "\t\t\n" - . "\t\n\t\t\n" - . "\t\n"; - if ($s1row['useexpiry']== "Y") - { - $expdate=$s1row['expires']; - } - else - { - $expdate="-"; - } - $surveysummary .= "\t\n" - . "\t\n" - . "\t\t\n" - - . "\t\n"; - if (!$s1row['language']) {$language=getLanguageNameFromCode($currentadminlang);} else {$language=getLanguageNameFromCode($s1row['language']);} - $surveysummary .= "\t\n"; - - // get the rowspan of the Additionnal languages row - // is at least 1 even if no additionnal language is present - $additionnalLanguagesCount = count($additionnalLanguagesArray); - if ($additionnalLanguagesCount == 0) $additionnalLanguagesCount = 1; - $surveysummary .= "\t\n"; - - $first=true; - foreach ($additionnalLanguagesArray as $langname) - { - if ($langname) - { - if (!$first) {$surveysummary .= "\t\t\t";} - $first=false; - $surveysummary .= "\n"; - } - } - if ($first) $surveysummary .= "\t"; - - if ($s1row['surveyls_urldescription']==""){$s1row['surveyls_urldescription']=$s1row['url'];} - $surveysummary .= "\t\n" - . "\t\t\n"; - $surveysummary .= "\t\n"; - $surveysummary .= "\t\n"; - - if ($activated == "Y") - { - $surveysummary .= "\t\n"; - } - $surveysummary .= "\t
      " - . "".$clang->gT("Title").":{$s1row['surveyls_title']} " - . "(ID {$s1row['sid']})
      " - . $clang->gT("Survey URL") ." (".getLanguageNameFromCode($s1row['language'],false)."): $tmp_url&lang=".$s1row['language'].""; - foreach ($additionnalLanguagesArray as $langname) - { - $surveysummary .= " ".getLanguageNameFromCode($langname,false)." ".$clang->gT("Flag").""; - } - - - $surveysummary .= "
      " - . $clang->gT("Description:").""; - if (trim($s1row['surveyls_description'])!='') {$surveysummary .= " {$s1row['surveyls_description']}";} - $surveysummary .= "
      " - . $clang->gT("Welcome:")." {$s1row['surveyls_welcometext']}
      " - . $clang->gT("Administrator:")." {$s1row['admin']} ({$s1row['adminemail']})
      " - . $clang->gT("Fax To:").""; - if (trim($s1row['faxto'])!='') {$surveysummary .= " {$s1row['faxto']}";} - $surveysummary .= "
      " - . $clang->gT("Expiry Date:")."$expdate
      " - . $clang->gT("Template:")." {$s1row['template']}
      " - . $clang->gT("Base Language:")."$language
      " - . $clang->gT("Additional Languages").":
      ".getLanguageNameFromCode($langname)."
      " - . $clang->gT("Exit Link").":"; - if ($s1row['url']!="") {$surveysummary .=" {$s1row['surveyls_urldescription']}";} - $surveysummary .="
      " - . $clang->gT("Number of questions/groups").":$sumcount3/$sumcount2
      " - . $clang->gT("Survey currently active").":"; - if ($activated == "N") - { - $surveysummary .= $clang->gT("No"); - } - else - { - $surveysummary .= $clang->gT("Yes"); - } - $surveysummary .="
      " - . $clang->gT("Survey table name").":".$dbprefix."survey_$surveyid
      " - . $clang->gT("Hints").":\n"; - - if ($activated == "N" && $sumcount3 == 0) - { - $surveysummary .= $clang->gT("Survey cannot be activated yet.")."
      \n"; - if ($sumcount2 == 0 && ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $sumrows5['define_questions'])) - { - $surveysummary .= "\t[".$clang->gT("You need to add groups")."]
      "; - } - if ($sumcount3 == 0 && ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 ||$sumrows5['define_questions'])) - { - $surveysummary .= "\t[".$clang->gT("You need to add questions")."]
      "; - } - } - $surveysummary .= $surveysummary2 - . "
      \n"; - } - else - { - include("access_denied.php"); - } -} - - -if ($surveyid && $gid ) // Show the group toolbar -{ - // TODO: check that surveyid and thus baselang are always set here - $sumquery4 = "SELECT * FROM ".db_table_name('questions')." WHERE sid=$surveyid AND - gid=$gid AND language='".$baselang."'"; //Getting a count of questions for this survey - $sumresult4 = $connect->Execute($sumquery4); //Checked - $sumcount4 = $sumresult4->RecordCount(); - $grpquery ="SELECT * FROM ".db_table_name('groups')." WHERE gid=$gid AND - language='".$baselang."' ORDER BY ".db_table_name('groups').".group_order"; - $grpresult = db_execute_assoc($grpquery); //Checked - - // Check if other questions/groups are dependent upon this group - $condarray=GetGroupDepsForConditions($surveyid,"all",$gid,"by-targgid"); - - $groupsummary = "\n"; - while ($grow = $grpresult->FetchRow()) - { - $grow = array_map('strip_tags', $grow); - //$grow = array_map('htmlspecialchars', $grow); - $groupsummary .= "\t\n" - . "\t\t\n" - . "\t\n"; - if ($qid || $action=='editgroup'|| $action=='addquestion') {$gshowstyle="style='display: none'";} - else {$gshowstyle="";} - - $groupsummary .= "\t
      \n" - . "\t\t\t\n" - . "\t\t\t\t\n" - . "\t\t\t\t\n" - . "\t\t\t\t\t\n" - . "\t\t\t\t\t\n" - . "\t\t\t\n" - . "\t\t
      \n" - . "\t\n" - . "\t\n\t\n"; - - if (!is_null($condarray)) - { - $groupsummary .= "\t\n" - . "\t"; - } - } - $groupsummary .= "\n
      " - . $clang->gT("Title").":" - . "{$grow['group_name']} ({$grow['gid']})
      " - . $clang->gT("Description:").""; - if (trim($grow['description'])!='') {$groupsummary .=$grow['description'];} - $groupsummary .= "
      " - . $clang->gT("Questions with conditions to this group").":"; - foreach ($condarray[$gid] as $depgid => $deprow) - { - foreach ($deprow['conditions'] as $depqid => $depcid) - { - //$groupsummary .= "[QID: ".$depqid."]"; - $listcid=implode("-",$depcid); - $groupsummary .= " [QID: ".$depqid."]"; - } - } - $groupsummary .= "\t
      \n"; -} - -if ($surveyid && $gid && $qid) // Show the question toolbar -{ - // TODO: check that surveyid is set and that so is $baselang - //Show Question Details - $qrq = "SELECT * FROM ".db_table_name('answers')." WHERE qid=$qid AND language='".$baselang."' ORDER BY sortorder, answer"; - $qrr = $connect->Execute($qrq); //Checked - $qct = $qrr->RecordCount(); - $qrquery = "SELECT * FROM ".db_table_name('questions')." WHERE gid=$gid AND sid=$surveyid AND qid=$qid AND language='".$baselang."'"; - $qrresult = db_execute_assoc($qrquery) or safe_die($qrquery."
      ".$connect->ErrorMsg()); //Checked - $questionsummary = "\n"; - - // Check if other questions in the Survey are dependent upon this question - $condarray=GetQuestDepsForConditions($surveyid,"all","all",$qid,"by-targqid","outsidegroup"); - - while ($qrrow = $qrresult->FetchRow()) - { - $qrrow = array_map('strip_tags', $qrrow); - //$qrrow = array_map('htmlspecialchars', $qrrow); - $questionsummary .= "\t\n" - . "\t\t\n" - . "\t\n"; - if (returnglobal('viewanswer') || $action =="editquestion" || $action =="copyquestion") {$qshowstyle = "style='display: none'";} - else {$qshowstyle = "";} - $questionsummary .= "\t
      \n" - . "\t\t\t\n" - . "\t\t\t\t\n" - . "\t\t\t\t\n" - . "\t\t\t\t\t\n" - . "\t\t\t\t\t\n" - . "\t\t\t\n" - . "\t\t
      \n" - . "\t\n" - . "\t\n\t\n" - . "\t\n\t\n"; - if ($qrrow['preg']) - { - $questionsummary .= "\t\n\t\n"; - } - $qtypes = getqtypelist("", "array"); //qtypes = array(type code=>type description) - $questionsummary .= "\t\n\t\n"; - if ($qct == 0 && ($qrrow['type'] == "O" || $qrrow['type'] == "L" || $qrrow['type'] == "!" || $qrrow['type'] == "M" || $qrrow['type'] == "Q" || $qrrow['type'] == "K" || $qrrow['type'] == "A" || $qrrow['type'] == "B" || $qrrow['type'] == "C" || $qrrow['type'] == "E" || $qrrow['type'] == "P" || $qrrow['type'] == "R" || $qrrow['type'] == "F" || $qrrow['type'] == "1" ||$qrrow['type'] == "H")) - { - $questionsummary .= "\t\t\n"; - } - - // For Labelset Questions show the label set and warn if there is no label set configured - if (($qrrow['type'] == "1" || $qrrow['type'] == "F" || $qrrow['type'] == "H" || $qrrow['type'] == "W" || $qrrow['type'] == "Z")) - { - $questionsummary .= "\t\t"; - if (!$qrrow['lid']) - { - $questionsummary .= ""; - - if ($qrrow['type'] == "1") // Second labelset for "multi scale" - { - $questionsummary .= ""; - if (!$qrrow['lid1']) - { - $questionsummary .= ""; - } - } - - - if ($qrrow['type'] == "M" or $qrrow['type'] == "P") - { - $questionsummary .= "\t" - . "\n" - . "\t\n"; - } - if (isset($qrrow['mandatory']) and ($qrrow['type'] != "X")) - { - $questionsummary .= "\t" - . "\n" - . "\t\n"; - } - if (!is_null($condarray)) - { - $questionsummary .= "\t" - . "\n"; - } - $qid_attributes=getQuestionAttributes($qid); - $questionsummary .= "
      " - . $clang->gT("Code:")."{$qrrow['title']}"; - if ($qrrow['type'] != "X") - { - if ($qrrow['mandatory'] == "Y") {$questionsummary .= ": (".$clang->gT("Mandatory Question").")";} - else {$questionsummary .= ": (".$clang->gT("Optional Question").")";} - } - $questionsummary .= "
      " - . $clang->gT("Question:")."".strip_tags($qrrow['question'])."
      " - . $clang->gT("Help:").""; - if (trim($qrrow['help'])!=''){$questionsummary .= strip_tags($qrrow['help']);} - $questionsummary .= "
      " - . $clang->gT("Validation:")."{$qrrow['preg']}" - . "
      " - .$clang->gT("Type:")."{$qtypes[$qrrow['type']]}"; - $questionsummary .="
      " - . "" - . $clang->gT("Warning").": ". $clang->gT("You need to add answers to this question")." " - . "
      ". $clang->gT("Label Set").":" - . $clang->gT("Warning")." - ".$clang->gT("You need to choose a label set for this question!")."\n"; - } - else - // If label set ID is configured show the labelset name and ID - { - - $labelsetname=$connect->GetOne("SELECT label_name FROM ".db_table_name('labelsets')." WHERE lid = ".$qrrow['lid']); - $questionsummary .= "".$labelsetname." (LID: {$qrrow['lid']}) "; - } - // If the user has the right to edit the label sets show the icon for the label set administration - if ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $sumrows5['define_questions']) - { - $questionsummary .= "\n"; - } - $questionsummary .= "
      ". $clang->gT("Second Label Set").":" - . $clang->gT("Warning")." - ".$clang->gT("You need to choose a second label set for this question!")."\n"; - } - else - // If label set ID is configured show the labelset name and ID - { - - $labelsetname=$connect->GetOne("SELECT label_name FROM ".db_table_name('labelsets')." WHERE lid = ".$qrrow['lid1']); - $questionsummary .= "".$labelsetname." (LID: {$qrrow['lid1']}) "; - } - - // If the user has the right to edit the second label sets show the icon for the label set administration - if ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $sumrows5['define_questions']) - { - $questionsummary .= "\n"; - } - $questionsummary .= "
      " - . $clang->gT("Other:").""; - $questionsummary .= ($qrrow['other'] == "Y") ? ($clang->gT("Yes")) : ($clang->gT("No")) ; - $questionsummary .= "
      " - . $clang->gT("Mandatory:").""; - $questionsummary .= ($qrrow['mandatory'] == "Y") ? ($clang->gT("Yes")) : ($clang->gT("No")) ; - $questionsummary .= "
      " - . $clang->gT("Other questions having conditions on this question:") - . "\t\n"; - foreach ($condarray[$qid] as $depqid => $depcid) - { - $listcid=implode("-",$depcid); - $questionsummary .= " [QID: ".$depqid."]"; - } - $questionsummary .= "
      "; - } - $questionsummary .= "
      "; -} - -if (returnglobal('viewanswer')) -{ - $_SESSION['FileManagerContext']="edit:answer:$surveyid"; - // Get languages select on survey. - $anslangs = GetAdditionalLanguagesFromSurveyID($surveyid); - $baselang = GetBaseLanguageFromSurveyID($surveyid); - - // check that there are answers for every language supported by the survey - foreach ($anslangs as $language) - { - $qquery = "SELECT count(*) as num_ans FROM ".db_table_name('answers')." WHERE qid=$qid AND language='".$language."'"; - $qresult = db_execute_assoc($qquery); //Checked - $qrow = $qresult->FetchRow(); - if ($qrow["num_ans"] == 0) // means that no record for the language exists in the answers table - { - $qquery = "INSERT INTO ".db_table_name('answers')." (SELECT `qid`,`code`,`answer`,`default_value`,`sortorder`, '".$language."' FROM ".db_table_name('answers')." WHERE qid=$qid AND language='".$baselang."')"; - $connect->Execute($qquery); //Checked - } - } - - array_unshift($anslangs,$baselang); // makes an array with ALL the languages supported by the survey -> $anslangs - - //delete the answers in languages not supported by the survey - $qquery = "SELECT DISTINCT language FROM ".db_table_name('answers')." WHERE (qid = $qid) AND (language NOT IN ('".implode("','",$anslangs)."'))"; - $qresult = db_execute_assoc($qquery); //Checked - while ($qrow = $qresult->FetchRow()) - { - $qquery = "DELETE FROM ".db_table_name('answers')." WHERE (qid = $qid) AND (language = '".$qrow["language"]."')"; - $connect->Execute($qquery); //Checked - } - - - // Check sort order for answers - $qquery = "SELECT type FROM ".db_table_name('questions')." WHERE qid=$qid AND language='".$baselang."'"; - $qresult = db_execute_assoc($qquery); //Checked - while ($qrow=$qresult->FetchRow()) {$qtype=$qrow['type'];} - if (!isset($_POST['ansaction'])) - { - //check if any nulls exist. If they do, redo the sortorders - $caquery="SELECT * FROM ".db_table_name('answers')." WHERE qid=$qid AND sortorder is null AND language='".$baselang."'"; - $caresult=$connect->Execute($caquery); //Checked - $cacount=$caresult->RecordCount(); - if ($cacount) - { - fixsortorderAnswers($qid); // !!Adjust this!! - } - } - - // Print Key Control JavaScript - $vasummary = PrepareEditorScript("editanswer"); - - $query = "SELECT sortorder FROM ".db_table_name('answers')." WHERE qid='{$qid}' AND language='".GetBaseLanguageFromSurveyID($surveyid)."' ORDER BY sortorder desc"; - $result = db_execute_assoc($query) or safe_die($connect->ErrorMsg()); //Checked - $anscount = $result->RecordCount(); - $row=$result->FetchRow(); - $maxsortorder=$row['sortorder']+1; - $vasummary .= "\t\n" - ."\n" - ."\t\n" - ."\n" - ."\t
      \n" - .$clang->gT("Edit Answers") - ."\t
      gT("Error: You are trying to use duplicate answer codes.",'js')."');\">\n" - . "\t\n" - . "\t\n" - . "\t\n" - . "\t\n" - . "\n" - . "\t\n"; - $vasummary .= "
      "; - $first=true; - $sortorderids=''; - $codeids=''; - - $vasummary .= "\t
      \n"; - - foreach ($anslangs as $anslang) - { - $position=0; - $query = "SELECT * FROM ".db_table_name('answers')." WHERE qid='{$qid}' AND language='{$anslang}' ORDER BY sortorder, code"; - $result = db_execute_assoc($query) or safe_die($connect->ErrorMsg()); //Checked - $anscount = $result->RecordCount(); - $vasummary .= "
      " - ."

      ".getLanguageNameFromCode($anslang, false); - if ($anslang==GetBaseLanguageFromSurveyID($surveyid)) {$vasummary .= '('.$clang->gT("Base Language").')';} - - $vasummary .= "

      \t\n" - ."" - ."\n" - ."\t\n" - ."\t\n" - ."\t\n" - ."\t\n" - ."" - .""; - while ($row=$result->FetchRow()) - { - $row['code'] = htmlspecialchars($row['code']); - $row['answer']=htmlspecialchars($row['answer']); - - $sortorderids=$sortorderids.' '.$row['language'].'_'.$row['sortorder']; - if ($first) {$codeids=$codeids.' '.$row['sortorder'];} - - $vasummary .= "\n" - ."\t\n" - ."\t\n" - ."\t\n"; - $position++; - } - ++$anscount; - if ($anscount > 0) - { - $vasummary .= "\t\n"; - } - $position=sprintf("%05d", $position); - if ($activated != 'Y' || (($activated == 'Y') && (($qtype=='O' ) || ($qtype=='L' ) ||($qtype=='!' )))) - { - - if ($first==true) - { - $vasummary .= "\n" - ."\t\n" - ."\t\n" - ."\t\n" - ."\n"; - } - } - else - { - $vasummary .= "\n" - ."\t\n" - ."\n"; - } - $first=false; - $vasummary .= "
      \n" - .$clang->gT("Code") - ."\t\n" - .$clang->gT("Answer") - ."\t\n" - .$clang->gT("Action") - ."\t\n" - .$clang->gT("Order") - ."\t"; - - - - $vasummary .= "
      \n"; - if ($row['default_value'] == 'Y') - { - $vasummary .= "".$clang->gT("Default")."" - ."\t"; - } - - if (($activated != 'Y' && $first) || ($activated == 'Y' && $first && (($qtype=='O') || ($qtype=='L') || ($qtype=='!') ))) - { - $vasummary .= "\t"; - $vasummary .= "\t"; - } - elseif (($activated != 'N' && $first) ) // If survey is activated and its not one of the above question types who allows modfying answers on active survey - { - $vasummary .= "\t{$row['code']}"; - $vasummary .= "\t"; - - } - else - { - $vasummary .= "\t{$row['code']}"; - - } - - $vasummary .= "\t\n" - ."\t\n" - . getEditor("editanswer","answer_".$row['language']."_".$row['sortorder'], "[".$clang->gT("Answer:", "js")."](".$row['language'].")",'','','','editanswer') - ."\t\n"; - - // Deactivate delete button for active surveys - if ($activated != 'Y' || ($activated == 'Y' && (($qtype=='O' ) || ($qtype=='L' ) ||($qtype=='!' )))) - { - $vasummary .= "\t\n"; - } - else - { - $vasummary .= "\t\n"; - } - - // Don't show Default Button for array question types - if ($qtype != "A" && $qtype != "B" && $qtype != "C" && $qtype != "E" && $qtype != "F" && $qtype != "H" && $qtype != "R" && $qtype != "Q" && $qtype != "1") $vasummary .= "\t\n"; - $vasummary .= "\t\n"; - if ($position > 0) - { - $vasummary .= "\t\n"; - }; - if ($position < $anscount-1) - { - // Fill the sortorder hiddenfield so we now what field is moved down - $vasummary .= "\t\n"; - } - $vasummary .= "\t
      " - ."\n" - ."

      " - ."".$clang->gT("New Answer").": "; - if (!isset($_SESSION['nextanswercode'])) $_SESSION['nextanswercode']=''; - $vasummary .= "\t"; - unset($_SESSION['nextanswercode']); - - - $first=false; - $vasummary .= "\t\n" - ."\t\n" - . getEditor("addanswer","insertanswer", "[".$clang->gT("Answer:", "js")."]",'','','',$action) - ."\t\n" - ."\t\n" - ."\t\n" - ."\t\n" - ."\n" - ."\t
      \n" - ."" - .$clang->gT("Warning").": ".$clang->gT("You cannot add answers or edit answer codes for this question type because the survey is active.")."\n" - ."\t
      \n"; - $vasummary .= "\n"; - $vasummary .= "\n"; - $vasummary .= "
      "; - } - $vasummary .= "
      "; - - -} - -// ************************************************* -// Survey Rights Start **************************** -// ************************************************* - -if($action == "addsurveysecurity") -{ - $addsummary = "
      ".$clang->gT("Add User")."
      \n"; - - $query = "SELECT sid, owner_id FROM ".db_table_name('surveys')." WHERE sid = {$surveyid} AND owner_id = ".$_SESSION['loginID']." AND owner_id != ".$postuserid; - $result = db_execute_assoc($query); //Checked - if( ($result->RecordCount() > 0 && in_array($postuserid,getuserlist('onlyuidarray'))) || - $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) - { - if($postuserid > 0){ - - $isrquery = "INSERT INTO {$dbprefix}surveys_rights VALUES($surveyid,". $postuserid.",0,0,0,0,0,0)"; - $isrresult = $connect->Execute($isrquery); //Checked - - if($isrresult) - { - $addsummary .= "
      ".$clang->gT("User added.")."
      \n"; - $addsummary .= "
      " - ."" - ."" - ."" - ."
      \n"; - } - else - { - // Username already exists. - $addsummary .= "
      ".$clang->gT("Failed to add User.")."
      \n" . " " . $clang->gT("Username already exists.")."
      \n"; - } - $addsummary .= "
      ".$clang->gT("Continue")."
       \n"; - } - else - { - $addsummary .= "
      ".$clang->gT("Failed to add User.")."
      \n" . " " . $clang->gT("No Username selected.")."
      \n"; - $addsummary .= "
      ".$clang->gT("Continue")."
       \n"; - } - } - else - { - include("access_denied.php"); - } -} - - -if($action == "addusergroupsurveysecurity") -{ - $addsummary = "
      ".$clang->gT("Add User Group")."
      \n"; - - $query = "SELECT sid, owner_id FROM ".db_table_name('surveys')." WHERE sid = {$surveyid} AND owner_id = ".$_SESSION['loginID']; - $result = db_execute_assoc($query); //Checked - if( ($result->RecordCount() > 0 && in_array($postusergroupid,getsurveyusergrouplist('simpleugidarray')) ) || - $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) - { - if($postusergroupid > 0){ - $query2 = "SELECT b.uid FROM (SELECT uid FROM ".db_table_name('surveys_rights')." WHERE sid = {$surveyid}) AS c RIGHT JOIN ".db_table_name('user_in_groups')." AS b ON b.uid = c.uid WHERE c.uid IS NULL AND b.ugid = {$postusergroupid}"; - $result2 = db_execute_assoc($query2); //Checked - if($result2->RecordCount() > 0) - { - while ($row2 = $result2->FetchRow()) - { - $uid_arr[] = $row2['uid']; - $values[] = "($surveyid, {$row2['uid']},0,0,0,0,0,0)"; - } - $values_implode = implode(",", $values); - - $isrquery = "INSERT INTO {$dbprefix}surveys_rights VALUES ".$values_implode; - $isrresult = $connect->Execute($isrquery); //Checked - - if($isrresult) - { - $addsummary .= "
      ".$clang->gT("User Group added.")."
      \n"; - $_SESSION['uids'] = $uid_arr; - $addsummary .= "
      " - ."" - ."" - ."" - ."
      \n"; - } - } - else - { - // no user to add - $addsummary .= "
      ".$clang->gT("Failed to add User Group.")."
      \n"; - } - $addsummary .= "
      ".$clang->gT("Continue")."
       \n"; - } - else - { - $addsummary .= "
      ".$clang->gT("Failed to add User.")."
      \n" . " " . $clang->gT("No Username selected.")."
      \n"; - $addsummary .= "
      ".$clang->gT("Continue")."
       \n"; - } - } - else - { - include("access_denied.php"); - } -} - -if($action == "delsurveysecurity"){ - { - $addsummary = "
      ".$clang->gT("Deleting User")."
      \n"; - - $query = "SELECT sid, owner_id FROM ".db_table_name('surveys')." WHERE sid = {$surveyid} AND owner_id = ".$_SESSION['loginID']." AND owner_id != ".$postuserid; - $result = db_execute_assoc($query); //Checked - if($result->RecordCount() > 0 || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) - { - if (isset($postuserid)) - { - $dquery="DELETE FROM {$dbprefix}surveys_rights WHERE uid={$postuserid} AND sid={$surveyid}"; // added by Dennis - $dresult=$connect->Execute($dquery); //Checked - - $addsummary .= "
      ".$clang->gT("Username").": ".sanitize_xss_string($_POST['user'])."
      \n"; - } - else - { - $addsummary .= "
      ".$clang->gT("Could not delete user. User was not supplied.")."
      \n"; - } - } - else - { - include("access_denied.php"); - } - $addsummary .= "

      ".$clang->gT("Continue")."
       \n"; - } -} - -if($action == "setsurveysecurity") -{ - $query = "SELECT sid, owner_id FROM ".db_table_name('surveys')." WHERE sid = {$surveyid} AND owner_id = ".$_SESSION['loginID']." AND owner_id != ".$postuserid; - $result = db_execute_assoc($query); //Checked - if($result->RecordCount() > 0 || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) - { - $query2 = "SELECT uid, edit_survey_property, define_questions, browse_response, export, delete_survey, activate_survey FROM ".db_table_name('surveys_rights')." WHERE sid = {$surveyid} AND uid = ".$postuserid; - $result2 = db_execute_assoc($query2); //Checked - - if($result2->RecordCount() > 0) - { - $resul2row = $result2->FetchRow(); - - $usersummary = "\n\t\n"; - - $usersummary .= "\t\t\n" - . "\t\t\n" - . "\t\t\n" - . "\t\t\n" - . "\t\t\n" - . "\t\t\n" - . "\t\t\n" - . "\n"; - - //content - $usersummary .= "\t\t" - ."" - . "
      \n" - . "\t\t".$clang->gT("Set Survey Rights")."
      ".$clang->gT("Edit Survey Properties")."".$clang->gT("Define Questions")."".$clang->gT("Browse Responses")."".$clang->gT("Export")."".$clang->gT("Delete Survey")."".$clang->gT("Activate Survey")."
      " - ."" - ."
      \n"; - } - } - else - { - include("access_denied.php"); - } -} - - -if($action == "setusergroupsurveysecurity") -{ - $query = "SELECT sid, owner_id FROM ".db_table_name('surveys')." WHERE sid = {$surveyid} AND owner_id = ".$_SESSION['loginID'];//." AND owner_id != ".$postuserid; - $result = db_execute_assoc($query); //Checked - if($result->RecordCount() > 0 || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) - { - $usersummary = "\n\t\n"; - - $usersummary .= "\t\t\n" - . "\t\t\n" - . "\t\t\n" - . "\t\t\n" - . "\t\t\n" - . "\t\t\n" - . "\t\t\n" - . "\n"; - - //content - $usersummary .= "\t\t" - ."" - . "
      \n" - . "\t\t".$clang->gT("Set Survey Rights")."
      ".$clang->gT("Edit Survey Property")."".$clang->gT("Define Questions")."".$clang->gT("Browse Response")."".$clang->gT("Export")."".$clang->gT("Delete Survey")."".$clang->gT("Activate Survey")."
      " - ."" - ."
      \n"; - } - else - { - include("access_denied.php"); - } -} - -// This is the action to export the structure of a complete survey -if($action == "exportstructure") -{ - if($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $sumrows5['export']) - { - $xml_module_available=function_exists("domxml_new_doc"); - - $exportstructure = "
      \n" - ."\n\t\n" - ."\t\n" - ."\t\t\n" - ."\t\n" - ."\t\n" - ."\t\n" - ."\t\t\n" - ."\t\n" - ."\t
      " - .$clang->gT("Export Survey Structure")."\n
      \n" - ."\t\t\t
      " - ."
      \n" - ."\t\t\t" - .$clang->gT("queXML Survey XML Format (*.xml)")." "; - if (!$xml_module_available) - { - $exportstructure.= "".$clang->gT("(XML module only in PHP 4 available)").""; - } - - $exportstructure.="\n" - ."\t\t
       
      \n" - ."\t\t\t\n" - ."\t\t\t\n" - ."\t\t\t\n" - ."\t\t

      \n"; - } -} - - -if($action == "surveysecurity") -{ - $query = "SELECT sid FROM ".db_table_name('surveys')." WHERE sid = {$surveyid} AND owner_id = ".$_SESSION['loginID']; - $result = db_execute_assoc($query); //Checked - if($result->RecordCount() > 0 || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) - { - $query2 = "SELECT a.uid, b.users_name FROM ".db_table_name('surveys_rights')." AS a INNER JOIN ".db_table_name('users')." AS b ON a.uid = b.uid WHERE a.sid = {$surveyid} AND b.uid != ".$_SESSION['loginID'] ." ORDER BY b.users_name"; - $result2 = db_execute_assoc($query2); //Checked - $surveysecurity = "\n\t\n" - . "\t\n" - . "\t\t\n" - . "\t\t\n" - . "\t\t\n" - . "\t\n"; - - if (isset($usercontrolSameGroupPolicy) && - $usercontrolSameGroupPolicy === true) - { - $authorizedGroupsList=getusergrouplist('simplegidarray'); - } - - if($result2->RecordCount() > 0) - { - // output users - $row = 0; - while ($resul2row = $result2->FetchRow()) - { - $query3 = "SELECT a.ugid FROM ".db_table_name('user_in_groups')." AS a RIGHT OUTER JOIN ".db_table_name('users')." AS b ON a.uid = b.uid WHERE b.uid = ".$resul2row['uid']; - $result3 = db_execute_assoc($query3); //Checked - while ($resul3row = $result3->FetchRow()) - { - if (!isset($usercontrolSameGroupPolicy) || - $usercontrolSameGroupPolicy === false || - in_array($resul3row['ugid'],$authorizedGroupsList)) - { - $group_ids[] = $resul3row['ugid']; - } - } - - if(isset($group_ids) && $group_ids[0] != NULL) - { - $group_ids_query = implode(" OR ugid=", $group_ids); - unset($group_ids); - - $query4 = "SELECT name FROM ".db_table_name('user_groups')." WHERE ugid = ".$group_ids_query; - $result4 = db_execute_assoc($query4); //Checked - - while ($resul4row = $result4->FetchRow()) - { - $group_names[] = $resul4row['name']; - } - if(count($group_names) > 0) - $group_names_query = implode(", ", $group_names); - } -// else {break;} //TODO Commented by lemeur - if(($row % 2) == 0) - $surveysecurity .= "\t\n"; - else - $surveysecurity .= "\t\n"; - - $surveysecurity .= "\t\n" - . "\t\t\n" - . "\t\n"; - $row++; - } - } - $surveysecurity .= "\t\t\n" - . "\t\t\n" - - . "\t\t\t\t\t\n" - - . "\t\t\n" - . "\t\n"; - //. "\t
      \n" - . "\t\t".$clang->gT("Survey Security")."
      ".$clang->gT("Username")."".$clang->gT("User Group")."".$clang->gT("Action")."
      {$resul2row['users_name']}\n" - . "\t"; - - if(isset($group_names) > 0) - { - $surveysecurity .= $group_names_query; - } - else - { - $surveysecurity .= "---"; - } - unset($group_names); - - $surveysecurity .= "\n"; - - $surveysecurity .= "" - ."" - ."" - ."" - ."" - .""; - - $surveysecurity .= "
      " - ."" - ."" - ."" - ."" - ."
      \n"; - - $surveysecurity .= "\t\t
      " - . "\t\t\t\t\t".$clang->gT("User").": \n" - . "\t\t\t\t" - . "
      \n"; - - $surveysecurity .= "\t\t
      \n" - . "\t\t
      " - . "\t\t\t\t\t".$clang->gT("Groups").": \n" - . "\t\t\t\t" - . "
      \n"; - } - else - { - include("access_denied.php"); - } -} - -elseif ($action == "surveyrights") -{ - $addsummary = "
      ".$clang->gT("Set Survey Rights")."
      \n"; - - if(isset($postuserid)){ - $query = "SELECT sid, owner_id FROM ".db_table_name('surveys')." WHERE sid = {$surveyid} "; - if ($_SESSION['USER_RIGHT_SUPERADMIN'] != 1) - { - $query.=" AND owner_id != ".$postuserid." AND owner_id = ".$_SESSION['loginID']; - } - } - else{ - $query = "SELECT sid, owner_id FROM ".db_table_name('surveys')." WHERE sid = {$surveyid} AND owner_id = ".$_SESSION['loginID']; - } - $result = db_execute_assoc($query); //Checked - if($result->RecordCount() > 0) - { - $rights = array(); - - if(isset($_POST['edit_survey_property']))$rights['edit_survey_property']=1; else $rights['edit_survey_property']=0; - if(isset($_POST['define_questions']))$rights['define_questions']=1; else $rights['define_questions']=0; - if(isset($_POST['browse_response']))$rights['browse_response']=1; else $rights['browse_response']=0; - if(isset($_POST['export']))$rights['export']=1; else $rights['export']=0; - if(isset($_POST['delete_survey']))$rights['delete_survey']=1; else $rights['delete_survey']=0; - if(isset($_POST['activate_survey']))$rights['activate_survey']=1; else $rights['activate_survey']=0; - - if(isset($postuserid)){ - $uids[] = $postuserid; - } - else{ - $uids = $_SESSION['uids']; - unset($_SESSION['uids']); - } - if(setsurveyrights($uids, $rights)) - { - $addsummary .= "
      ".$clang->gT("Update survey rights successful.")."
      \n"; - } - else - { - $addsummary .= "
      ".$clang->gT("Failed to update survey rights!")."
      \n"; - } - $addsummary .= "

      ".$clang->gT("Continue")."
       \n"; - } - else - { - include("access_denied.php"); - } -} - -// ************************************************* -// Survey Rights End **************************** -// ************************************************* - - -// Editing the survey -if ($action == "editsurvey") -{ - if($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $sumrows5['edit_survey_property']) - { - $esquery = "SELECT * FROM {$dbprefix}surveys WHERE sid=$surveyid"; - $esresult = db_execute_assoc($esquery); //Checked - while ($esrow = $esresult->FetchRow()) - { - $esrow = array_map('htmlspecialchars', $esrow); - $editsurvey = include2var('./scripts/addremove.js'); - $editsurvey .= "
      \n"; - - // header - $editsurvey .= "\n\t
      " - . "\t\t".$clang->gT("Edit Survey - Step 1 of 2")."
      \n"; - - - // beginning TABs section - $editsurvey .= "\t
      \n"; - // General & Contact TAB - $editsurvey .= "\t

      ".$clang->gT("General")."

      \n"; - - // Base Language - $editsurvey .= "\t
      ".$clang->gT("Base Language:")."\n" - . "\t\t\n".GetLanguageNameFromCode($esrow['language']) - . "\t\t\t
      \n" - - // Additional languages listbox - . "\t
      ".$clang->gT("Additional Languages").":\n" - . "\t\t" - . "\n" - - // Available languages listbox - . "\t\t" - . "
      gT("Add")."\" onclick=\"DoAdd()\" id=\"AddBtn\" />
      gT("Remove")." >>\" onclick=\"DoRemove(0,'')\" id=\"RemoveBtn\" />
      \n"; - - $editsurvey .= ""; - - - // Administrator... - $editsurvey .= "" - . "\t
      ".$clang->gT("Administrator:")."\n" - . "\t\t
      \n" - . "\t
      ".$clang->gT("Admin Email:")."\n" - . "\t\t
      \n" - . "\t
      ".$clang->gT("Bounce Email:")."\n" - . "\t\t
      \n" - . "\t
      ".$clang->gT("Fax To:")."\n" - . "\t\t
      \n"; - - // End General TAB - // Create Survey Button TIBO -// $editsurvey .= "
      \n"; - $editsurvey .= "\t
      \n"; - - // Presentation and navigation TAB - $editsurvey .= "\t

      ".$clang->gT("Presentation & Navigation")."

      \n"; - - //Format - $editsurvey .= "\t
      ".$clang->gT("Format:")."\n" - . "\t\t\n" - . "\t
      \n"; - - //TEMPLATES - $editsurvey .= "\t
      ".$clang->gT("Template:")."\n" - . "\t\t\n" - . "\t\t\t\n" - . "\t\t\n" - . "\t\t\n" - . "\t
      \n"; - - //ALLOW PREV - $editsurvey .= "\t
      ".$clang->gT("Show [<< Prev] button")."\n" - . "\t\t\n" - . "\t
      \n"; - - //Result printing - $editsurvey .= "\t
      ".$clang->gT("Participiants may print answers?")."\n" - . "\t\t\n" - . "\t
      \n"; - - //Public Surveys - $editsurvey .= "\t
      ".$clang->gT("List survey publicly:")."\n" - . "\t\t\n" - . "\t
      \n"; - - - // End URL block - $editsurvey .= "" - . "\t
      ".$clang->gT("End URL:")."\n" - . "\t\t
      \n" - . "\t
      ".$clang->gT("Automatically load URL when survey complete?")."\n" - . "\t\t
      "; - - - // End Presention and navigation TAB - // Create Survey Button TIBO -// $editsurvey .= "
      \n"; - $editsurvey .= "\t
      \n"; - - // Publication and access control TAB - $editsurvey .= "\t

      ".$clang->gT("Publication & Access control")."

      \n"; - - - // Expiration - $editsurvey .= "" - . "\t
      ".$clang->gT("Expires?")."\n" - . "\t\t\t
      " - . "
      ".$clang->gT("Expiry Date:")."\n" - . "\t\t
      \n"; - - //COOKIES - $editsurvey .= "\t
      ".$clang->gT("Use Cookies?")."\n" - . "\t\t\n" - . "\t
      \n"; - - // Auto registration - $editsurvey .= "\t
      ".$clang->gT("Allow public registration?")."\n" - . "\t\t\n\t
      \n"; - - // Use Captcha - $editsurvey .= "\t
      ".$clang->gT("Use CAPTCHA for").":\n" - . "\t\t(".$clang->gT("Attribute 1").")
      " - . "(".$clang->gT("Attribute 2").")
      \n\t
      \n"; - - // Email format - $editsurvey .= "\t
      ".$clang->gT("Use HTML format for token emails?")."\n" - . "\t\t\n\t
      \n"; - - // End Publication and access control TAB - // Create Survey Button TIBO -// $editsurvey .= "
      \n"; - $editsurvey .= "\t
      \n"; - - // Notification and Data management TAB - $editsurvey .= "\t

      ".$clang->gT("Notification & Data Management")."

      \n"; - - - //NOTIFICATION - $editsurvey .= "\t
      ".$clang->gT("Admin Notification:")."\n" - . "\t\t\n" - . "\t
      \n"; - - - //ANONYMOUS - $editsurvey .= "\t
      ".$clang->gT("Anonymous answers?")."\n"; - // warning message if anonymous + tokens used - $editsurvey .= "\n" - . "\t\n"; - - if ($esrow['active'] == "Y") - { - $editsurvey .= "\t\t\n\t\t\t"; - if ($esrow['private'] == "N") {$editsurvey .= " ".$clang->gT("This survey is NOT anonymous.");} - else {$editsurvey .= $clang->gT("Answers to this survey are anonymized.");} - $editsurvey .= " (".$clang->gT("Cannot be changed").")\n" - . "\t\t\n"; - $editsurvey .= "\n"; - } - else - { - $editsurvey .= "\t\t\n\t\t\n"; - } - $editsurvey .= "
      \n"; - - // date stamp - $editsurvey .= "\t
      ".$clang->gT("Date Stamp?")."\n"; - if ($esrow['active'] == "Y") - { - $editsurvey .= "\t\t\n\t\t\t"; - if ($esrow['datestamp'] != "Y") {$editsurvey .= " ".$clang->gT("Responses will not be date stamped.");} - else {$editsurvey .= $clang->gT("Responses will be date stamped.");} - $editsurvey .= " (".$clang->gT("Cannot be changed").")\n" - . "\t\t\n"; - $editsurvey .= "\n"; - } - else - { - $editsurvey .= "\t\t\n\t\t\n"; - } - $editsurvey .= "
      \n"; - - // Ip Addr - $editsurvey .= "\t
      ".$clang->gT("Save IP Address?")."\n"; - - if ($esrow['active'] == "Y") - { - $editsurvey .= "\t\t\n\t\t\t"; - if ($esrow['ipaddr'] != "Y") {$editsurvey .= " ".$clang->gT("Responses will not have the IP address logged.");} - else {$editsurvey .= $clang->gT("Responses will have the IP address logged");} - $editsurvey .= " (".$clang->gT("Cannot be changed").")\n" - . "\t\t\n"; - $editsurvey .= "\n"; - } - else - { - $editsurvey .= "\t\t\n\t\t\n"; - } - - $editsurvey .= "\t
      \n"; - - // begin REF URL Block - $editsurvey .= "\t
      ".$clang->gT("Save Referring URL?")."\n"; - - if ($esrow['active'] == "Y") - { - $editsurvey .= "\t\t\n\t\t\t"; - if ($esrow['refurl'] != "Y") {$editsurvey .= " ".$clang->gT("Responses will not have their referring URL logged.");} - else {$editsurvey .= $clang->gT("Responses will have their referring URL logged.");} - $editsurvey .= " (".$clang->gT("Cannot be changed").")\n" - . "\t\t\n"; - $editsurvey .= "\n"; - } - else - { - $editsurvey .= "\t\t\n\t\t\n"; - } - $editsurvey .= "\t
      \n"; - // BENBUN - END REF URL Block - - // Token answers persistence - $editsurvey .= "\t
      ".$clang->gT("Enable Token-based answers persistence?")."\n" - . "\t\t\n\t
      \n"; - - // End Notification and Data management TAB - // Create Survey Button -// $editsurvey .= "
      \n"; - $editsurvey .= "\t
      \n"; - - // Ending First TABs Form - $editsurvey .= "" - . "\t\n" - . "\t\n" - . "\t\n" - . "\t\n" - ."\t"; - - - // TAB Uploaded Resources Management - - $ZIPimportAction = " onclick='if (validatefilename(this.form,\"".$clang->gT('Please select a file to import!','js')."\")) {this.form.submit();}'"; - if (!function_exists("zip_open")) - { - $ZIPimportAction = " onclick='alert(\"".$clang->gT("zip library not supported by PHP, Import ZIP Disabled","js")."\");'"; - } - - $disabledIfNoResources = ''; - if (hasResources($surveyid,'survey') === false) - { - $disabledIfNoResources = " disabled='disabled'"; - } - - $editsurvey .= "\t

      ".$clang->gT("Uploaded Resources Management")."

      \n" - . "\t
      \n" - . "\t\n" - . "\t\n" - . "\t\n" - . "\t" - . "\t\t\n" - . "\t\t\n" - . "\t\t \n" - . "\t\t\n" - . "\t\t\n" - . "\t\t\n" - . "\t
      \n" - . "\t\tgT("Browse Uploaded Resources")."\" $disabledIfNoResources>
      gT("Export Resources As ZIP Archive")."\" $disabledIfNoResources>
      ".$clang->gT("Select ZIP File:")."
      \n"; - - // End TAB Uploaded Resources Management - $editsurvey .= "\t
      \n"; - - // End TAB pane - $editsurvey .= "\t
      \n"; - - - // The external button to sumbit Survey edit changes - $editsurvey .= "\t\n" - . "
      \n" - . "\t
      \n"; - - // Here we do the setup the date javascript - $editsurvey .= "\n"; - } - - } - else - { - include("access_denied.php"); - } - -} - - -if ($action == "updatesurvey") // Edit survey step 2 - editing language dependent settings -{ - if($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $sumrows5['edit_survey_property']) - { - - $grplangs = GetAdditionalLanguagesFromSurveyID($surveyid); - $baselang = GetBaseLanguageFromSurveyID($surveyid); - array_unshift($grplangs,$baselang); - - $editsurvey = PrepareEditorScript(); - - - $editsurvey .="\n" - . "\n\t
      " - . "\t\t".$clang->gT("Edit Survey - Step 2 of 2")."
      \n"; - $editsurvey .= "
      \n" - . '
      '; - foreach ($grplangs as $grouplang) - { - // this one is created to get the right default texts fo each language - $bplang = new limesurvey_lang($grouplang); - $esquery = "SELECT * FROM ".db_table_name("surveys_languagesettings")." WHERE surveyls_survey_id=$surveyid and surveyls_language='$grouplang'"; - $esresult = db_execute_assoc($esquery); //Checked - $esrow = $esresult->FetchRow(); - $editsurvey .= '

      '.getLanguageNameFromCode($esrow['surveyls_language'],false); - if ($esrow['surveyls_language']==GetBaseLanguageFromSurveyID($surveyid)) {$editsurvey .= '('.$clang->gT("Base Language").')';} - $editsurvey .= '

      '; - $esrow = array_map('htmlspecialchars', $esrow); - $editsurvey .= "\t\t
      ".$clang->gT("Title").":\n" - . "\t\t\n" - . "\t
      ".$clang->gT("Description:")."\n" - . "\t\t\n" - . getEditor("survey-desc","description_".$esrow['surveyls_language'], "[".$clang->gT("Description:", "js")."](".$esrow['surveyls_language'].")",'','','',$action) - . "\n" - . "\t
      ".$clang->gT("Welcome:")."\n" - . "\t\t\n" - . getEditor("survey-welc","welcome_".$esrow['surveyls_language'], "[".$clang->gT("Welcome:", "js")."](".$esrow['surveyls_language'].")",'','','',$action) - . "
      \n" - . "\t
      ".$clang->gT("URL Description:")."\n" - . "\t\t\n" - . "\t
      "; - } - $editsurvey .= '
      '; - $editsurvey .= "\t

      \n" - . "\t\n" - . "\t\n" - . "\t\n" - . "\t

      \n" - . "
      \n"; - - } - else - { - include("access_denied.php"); - } - -} - -if($action == "quotas") -{ - include("quota.php"); -} - -// Show the screen to order groups - -if ($action == "ordergroups") -{ - if($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $sumrows5['edit_survey_property']) - { - // Check if one of the up/down buttons have been clicked - if (isset($_POST['groupordermethod']) && isset($_POST['sortorder'])) - { - $postsortorder=sanitize_int($_POST['sortorder']); - switch($_POST['groupordermethod']) - { - // Pressing the Up button - case $clang->gT("Up", "unescaped"): - $newsortorder=$postsortorder-1; - $oldsortorder=$postsortorder; - $cdquery = "UPDATE ".db_table_name('groups')." SET group_order=-1 WHERE sid=$surveyid AND group_order=$newsortorder"; - $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); //Checked - $cdquery = "UPDATE ".db_table_name('groups')." SET group_order=$newsortorder WHERE sid=$surveyid AND group_order=$oldsortorder"; - $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); //Checked - $cdquery = "UPDATE ".db_table_name('groups')." SET group_order='$oldsortorder' WHERE sid=$surveyid AND group_order=-1"; - $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); //Checked - break; - - // Pressing the Down button - case $clang->gT("Dn", "unescaped"): - $newsortorder=$postsortorder+1; - $oldsortorder=$postsortorder; - $cdquery = "UPDATE ".db_table_name('groups')." SET group_order=-1 WHERE sid=$surveyid AND group_order=$newsortorder"; - $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg());//Checked - $cdquery = "UPDATE ".db_table_name('groups')." SET group_order='$newsortorder' WHERE sid=$surveyid AND group_order=$oldsortorder"; - $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg());//Checked - $cdquery = "UPDATE ".db_table_name('groups')." SET group_order=$oldsortorder WHERE sid=$surveyid AND group_order=-1"; - $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg());//Checked - break; - } - } - - $ordergroups = "\n\t" - . "
      " - . "\t\t".$clang->gT("Change Group Order")."
      \n"; - - // Get groups dependencies regarding conditions - // => Get an array of groups containing questions with conditions outside the group - // $groupdepsarray[dependent-gid][target-gid]['conditions'][qid-having-conditions]=Array(cids...) - $groupdepsarray = GetGroupDepsForConditions($surveyid); - if (!is_null($groupdepsarray)) - { - $ordergroups .= "
      • ".$clang->gT("Warning").": ".$clang->gT("Current survey has questions with conditions outside their own group")."

        ".$clang->gT("Re-ordering groups is restricted to ensure that questions on which conditions are based aren't reordered after questions having the conditions set")."

        ".$clang->gT("The following groups are concerned").":
          \n"; - foreach ($groupdepsarray as $depgid => $depgrouprow) - { - foreach($depgrouprow as $targgid => $targrow) - { - $ordergroups .= "
        • ".sprintf($clang->gT("Group %s depends on group %s, see the marked conditions on:"), "".$targrow['depgpname']."", "".$targrow['targetgpname']." "); - foreach($targrow['conditions'] as $depqid => $depqrow) - { - $listcid=implode("-",$depqrow); - $ordergroups .= " [".$clang->gT("QID").": ".$depqid."]"; - } - $ordergroups .= "
        • \n"; - } - } - $ordergroups .= "
      "; - } - - $ordergroups .= "
        "; - //Get the groups from this survey - $s_lang = GetBaseLanguageFromSurveyID($surveyid); - $ogquery = "SELECT * FROM {$dbprefix}groups WHERE sid='{$surveyid}' AND language='{$s_lang}' order by group_order,group_name" ; - $ogresult = db_execute_assoc($ogquery) or safe_die($connect->ErrorMsg());//Checked - - $ogarray = $ogresult->GetArray(); - $groupcount = count($ogarray); - for($i=0; $i < $groupcount ; $i++) - { - $downdisabled = ""; - $updisabled = ""; - if ( !is_null($groupdepsarray) && $i < $groupcount-1 && - array_key_exists($ogarray[$i+1]['gid'],$groupdepsarray) && - array_key_exists($ogarray[$i]['gid'],$groupdepsarray[$ogarray[$i+1]['gid']]) ) - { - $downdisabled = "disabled=\"true\" class=\"disabledbtn\""; - } - if ( !is_null($groupdepsarray) && $i !=0 && - array_key_exists($ogarray[$i]['gid'],$groupdepsarray) && - array_key_exists($ogarray[$i-1]['gid'],$groupdepsarray[$ogarray[$i]['gid']]) ) - { - $updisabled = "disabled=\"true\" class=\"disabledbtn\""; - } - - $ordergroups.="
      • \n" ; - $ordergroups.= "\t\n"; - - if ($i < $groupcount-1) - { - // Fill the hidden field 'sortorder' so we know what field is moved down - $ordergroups.= "\t\n"; - } - $ordergroups.=$ogarray[$i]['group_name']."
      • \n" ; - - } - - $ordergroups.="
      \n" - . "\t" - . "\t" - . "
      " ; - $ordergroups .="
      " ; - } - else - { - include("access_denied.php"); - } -} - - -if ($action == "newsurvey") -{ - if($_SESSION['USER_RIGHT_CREATE_SURVEY']) - { - $newsurvey = PrepareEditorScript(); - $newsurvey .= "
      gT("Error: You have to enter a title for this survey.",'js')."');\" >\n"; - - // header - $newsurvey .= "\n\t
      " - . "\t\t".$clang->gT("Create or Import Survey")."
      \n"; - - // begin Tabs section - $newsurvey .= "\t
      \n"; - - // General and Contact TAB - $newsurvey .= "\t

      ".$clang->gT("General")."

      \n"; -// could be used to add a header -// $newsurvey .= "\n\t
      " -// . "\t\t".$clang->gT("Create Survey")."
      \n"; - - // * Survey Language - $newsurvey .= "\t
      ".$clang->gT("Base Language:")."\n" - . "\t\t ".$clang->gT("This setting cannot be changed later!")."\n" - . "\t
      \n"; - - $newsurvey .= "" - . "\t\t
      ".$clang->gT("Title").":\n" - . "\t\t ".$clang->gT("(This field is mandatory.)")."
      \n" - . "\t
      ".$clang->gT("Description:")."\n" - . "\t\t" - . getEditor("survey-desc","description", "[".$clang->gT("Description:", "js")."]",'','','',$action) - . "
      \n" - . "\t
      ".$clang->gT("Welcome:")."\n" - . "\t\t" - . getEditor("survey-welc","welcome", "[".$clang->gT("Welcome:", "js")."]",'','','',$action) - . "
      \n" - . "\t
      ".$clang->gT("Administrator:")."\n" - . "\t\t
      \n" - . "\t
      ".$clang->gT("Admin Email:")."\n" - . "\t\t
      \n" - . "\t
      ".$clang->gT("Bounce Email:")."\n" - . "\t\t
      \n"; - $newsurvey .= "\t
      ".$clang->gT("Fax To:")."\n" - . "\t\t
      \n"; - - - // End General TAB - // Create Survey Button TIBO - $newsurvey .= "
      \n"; - - $newsurvey .= "\t
      \n"; - - // Presentation and navigation TAB - $newsurvey .= "\t

      ".$clang->gT("Presentation & Navigation")."

      \n"; - - - $newsurvey .= "\t
      ".$clang->gT("Format:")."\n" - . "\t\t\n" - . "\t
      \n"; - $newsurvey .= "\t
      ".$clang->gT("Template:")."\n" - . "\t\t\n" - . "\t\t\t\n" - . "\t\t\n" - . "\t\t\n" - . "\t
      \n"; - //ALLOW PREV - $newsurvey .= "\t
      ".$clang->gT("Show [<< Prev] button")."\n" - . "\t\t\n" - . "\t
      \n"; - - //Result printing - $newsurvey .= "\t
      ".$clang->gT("Participiants may print answers?")."\n" - . "\t\t\n" - . "\t
      \n"; - - //Public Surveys - $newsurvey .= "\t
      ".$clang->gT("List survey publicly:")."\n" - . "\t\t\n" - . "\t
      \n"; - - - // End URL - $newsurvey .= "" - . "\t
      ".$clang->gT("End URL:")."\n" - . "\t\t".$clang->gT("URL Description:")."\n" - . "\t\t".$clang->gT("Automatically load URL when survey complete?")."\n" - . "\t\t
      "; - - // End Presention and navigation TAB - // Create Survey Button TIBO - $newsurvey .= "
      \n"; - $newsurvey .= "\t
      \n"; - - // Publication and access control TAB - $newsurvey .= "\t

      ".$clang->gT("Publication & Access control")."

      \n"; - - // Expiration - $newsurvey .= "\t
      ".$clang->gT("Expires?")."\n" - . "\t\t\t
      \n" - . "
      ".$clang->gT("Expiry Date:")."\n" - . "\t\t" - . " ".$clang->gT("Date Format").": YYYY-MM-DD
      \n"; - - //COOKIES - $newsurvey .= "\t
      ".$clang->gT("Use Cookies?")."\n" - . "\t\t\n" - . "\t
      \n"; - - // Public registration - $newsurvey .= "\t
      ".$clang->gT("Allow public registration?")."\n" - . "\t\t\n\t
      \n"; - - // Use Captcha - $newsurvey .= "\t
      ".$clang->gT("Use CAPTCHA for").":\n" - . "\t\t\n\t
      \n"; - - // Token attributes names - $newsurvey .= "\t
      ".$clang->gT("Token Attribute Names:")."\n" - . "\t\t(".$clang->gT("Attribute 1").")
      " - . "(".$clang->gT("Attribute 2").")
      \n\t
      \n"; - - // Email format - $newsurvey .= "\t
      ".$clang->gT("Use HTML format for token emails?")."\n" - . "\t\t\n\t
      \n"; - - // End Publication and access control TAB - // Create Survey Button TIBO - $newsurvey .= "
      \n"; - $newsurvey .= "\t
      \n"; - - // Notification and Data management TAB - $newsurvey .= "\t

      ".$clang->gT("Notification & Data Management")."

      \n"; - - //NOTIFICATIONS - $newsurvey .= "\t
      ".$clang->gT("Admin Notification:")."\n" - . "\t\t\n" - . "\t
      \n"; - - - // ANONYMOUS - $newsurvey .= "\t
      ".$clang->gT("Anonymous answers?")."\n"; - // warning message if anonymous + datestamped anwsers - $newsurvey .= "\n" - . "\t\n"; - $newsurvey .= "\t\t\n\t
      \n"; - - // Datestamp - $newsurvey .= "\t
      ".$clang->gT("Date Stamp?")."\n" - . "\t\t\n\t
      \n"; - - // IP Address - $newsurvey .= "\t
      ".$clang->gT("Save IP Address?")."\n" - . "\t\t\n\t
      \n"; - - // Referring URL - $newsurvey .= "\t
      ".$clang->gT("Save Referring URL?")."\n" - . "\t\t\n\t
      \n"; - - // Token answers persistence - $newsurvey .= "\t
      ".$clang->gT("Enable Token-based answers persistence?")."\n" - . "\t\t\n\t
      \n"; - - // end of addnewsurvey form - $newsurvey .= "" -// . "\t
      \n" -// . "\t\n" - . "\t\n" - . "\n"; - - // End Notification and Data management TAB - // Create Survey Button - $newsurvey .= "
      \n"; - $newsurvey .= "\t
      \n"; - - // Import TAB - $newsurvey .= "\t

      ".$clang->gT("Import Survey")."

      \n"; - - // Import Survey - $newsurvey .= "
      \n" - . "\n" -// . "\n" - . "\t\t\t\n" - . "\t\t\n" - . "\t\t\t\t\n" - . "\t\t\n" - . "\t\n" - . "\t\n" -// . "" // end tab -// . "" // end tab-pane - . "
      \n" -// . "\t\t".$clang->gT("Import Survey")."
      ".$clang->gT("Select CSV/SQL File:")."
      \n" - . "\t
      \n"; -// . "\n"; - - // End Import TAB - $newsurvey .= "\t
      \n"; - - // End TAB pane - $newsurvey .= "\t
      \n"; - - // Here we do setup the date javascript - $newsurvey .= "\n"; - } - else - { - include("access_denied.php"); - } -} - - -function replacenewline ($texttoreplace) -{ - $texttoreplace = str_replace( "\n", '
      ', $texttoreplace); - // $texttoreplace = htmlentities( $texttoreplace, ENT_QUOTES, UTF-8); - $new_str = ''; - - for($i = 0; $i < strlen($texttoreplace); $i++) { - $new_str .= '\x' . dechex(ord(substr($texttoreplace, $i, 1))); - } - - return $new_str; -} -/* -function questionjavascript($type, $qattributes) - { - $newquestion = "\n"; - -} */ -?> +ErrorMsg()); //Checked + + if($result->RecordCount() > 0) { + $listsurveys= "
      + + + + + + + + + + + + "; + $gbc = "evenrow"; + $dateformatdetails=getDateFormatData($_SESSION['dateformat']); + + while($rows = $result->FetchRow()) + { + $sidsecurityQ = "SELECT b.* FROM {$dbprefix}surveys AS a INNER JOIN {$dbprefix}surveys_rights AS b ON a.sid = b.sid WHERE a.sid='{$rows['sid']}' AND b.uid = ".$_SESSION['loginID']; //Getting rights for this survey and user + $sidsecurityR = db_execute_assoc($sidsecurityQ); //Checked + $sidsecurity = $sidsecurityR->FetchRow(); + + if($rows['private']=="Y") + { + $privacy=$clang->gT("Yes") ; + } + else $privacy =$clang->gT("No") ; + + + if (tokenTableExists($rows['sid'])) + { + $visibility = $clang->gT("Closed-access"); + } + else + { + $visibility = $clang->gT("Open-access"); + } + + if($rows['active']=="Y") + { + if ($rows['expires']!='' && $rows['expires'] < date_shift(date("Y-m-d H:i:s"), "Y-m-d", $timeadjust)) + { + $status=$clang->gT("Expired") ; + } + elseif ($rows['startdate']!='' && $rows['startdate'] > date_shift(date("Y-m-d H:i:s"), "Y-m-d", $timeadjust)) + { + $status=$clang->gT("Not yet active") ; + } + else { + $status=$clang->gT("Active") ; + } + // Complete Survey Responses - added by DLR + $gnquery = "SELECT count(id) FROM ".db_table_name("survey_".$rows['sid'])." WHERE submitdate IS NULL"; + $gnresult = db_execute_num($gnquery); //Checked + while ($gnrow = $gnresult->FetchRow()) + { + $partial_responses=$gnrow[0]; + } + $gnquery = "SELECT count(id) FROM ".db_table_name("survey_".$rows['sid']); + $gnresult = db_execute_num($gnquery); //Checked + while ($gnrow = $gnresult->FetchRow()) + { + $responses=$gnrow[0]; + } + + } + else $status =$clang->gT("Inactive") ; + + + $datetimeobj = new Date_Time_Converter($rows['datecreated'] , "Y-m-d H:i:s"); + $datecreated=$datetimeobj->convert($dateformatdetails['phpdate']); + + if (in_array($rows['owner_id'],getuserlist('onlyuidarray'))) + { + $ownername=$rows['users_name'] ; + } + else + { + $ownername="---"; + } + + $questionsCount = 0; + $questionsCountQuery = "SELECT * FROM ".db_table_name('questions')." WHERE sid={$rows['sid']} AND language='".$rows['language']."'"; //Getting a count of questions for this survey + $questionsCountResult = $connect->Execute($questionsCountQuery); //Checked + $questionsCount = $questionsCountResult->RecordCount(); + + if ($gbc == "oddrow") {$gbc = "evenrow";} + else {$gbc = "oddrow";} + $listsurveys.=""; + + if ($rows['active']=="Y") + { + if ($rows['expires']!='' && $rows['expires'] < date_shift(date("Y-m-d H:i:s"), "Y-m-d", $timeadjust)) + { + $listsurveys .= "\n"; + } else + { + $listsurveys .= "\n"; + } + } + } else { + if ( ($_SESSION['USER_RIGHT_SUPERADMIN'] ==1 || $sidsecurity['activate_survey']) && $questionsCount > 0) + { + $listsurveys .= "\n" ; + } else + { + $listsurveys .= "\n"; + } + } + + $listsurveys.="". + "". + "". + "" . + "" . + ""; + + if ($rows['active']=="Y") + { + $complete = $responses - $partial_responses; + $listsurveys .= ""; + $listsurveys .= ""; + $listsurveys .= ""; + }else{ + $listsurveys .= ""; + $listsurveys .= ""; + $listsurveys .= ""; + } + $listsurveys .= "" ; + } + + $listsurveys.=" + ". + ""; + $listsurveys.="
      ".$clang->gT("Status")."".$clang->gT("Survey")."".$clang->gT("Date Created")."".$clang->gT("Owner") ."".$clang->gT("Access")."".$clang->gT("Anonymous answers")."".$clang->gT("Status")."".$clang->gT("Full Responses")."".$clang->gT("Partial Responses")."".$clang->gT("Total Responses")."
      gT("This survey is active but expired", "js")."');return false\" />\n"; + } + else + { + if ($_SESSION['USER_RIGHT_SUPERADMIN'] ==1 || $sidsecurity['activate_survey']) + { + $listsurveys .= "gTview("De-activate this Survey")."\" " + . "onmouseover=\"showTooltip(event,'".$clang->gT("De-activate this Survey", "js")."');return false\">" + . "gTview("This survey is currently active")."\"" + . "onmouseover=\"showTooltip(event,'".$clang->gT("This survey is currently active", "js")."');return false\" />gTview("Activate this Survey")."\"" + . "onmouseover=\"showTooltip(event,'".$clang->gT("Activate this Survey", "js")."');return false\">" . + "".$clang->gT("Activate this Survey")."".$clang->gT("This survey is not currently active")."gT("This survey is not currently active", "js")."');return false\" />".$rows['surveyls_title']."".$datecreated."".$ownername."".$visibility."".$privacy."".$status."".$complete."".$partial_responses."".$responses."   
       

      " ; + } + else $listsurveys="
      ".$clang->gT("No Surveys available - please create one.")."

      " ; +} + +if ($action == "personalsettings") +{ + + // prepare data for the htmleditormode preference + $edmod1=''; + $edmod2=''; + $edmod3=''; + $edmod4=''; + switch ($_SESSION['htmleditormode']) + { + case 'none': + $edmod2="selected='selected'"; + break; + case 'inline': + $edmod3="selected='selected'"; + break; + case 'popup': + $edmod4="selected='selected'"; + break; + default: + $edmod1="selected='selected'"; + break; + } + + $cssummary = "
      " + . "".$clang->gT("Your personal settings")."\n" + . "
      \n" + . "
      \n" + . "
      " + . "
        \n"; + + // Current language + $cssummary .= "
      • \n" + . "\n" + . "\n" + . "
      • \n"; + + // Current htmleditormode + $cssummary .= "
      • \n" + . "\n" + . "\n" + . "
      • \n"; + + // Date format + $cssummary .= "
      • \n" + . "\n" + . "\n" + . "
      • \n" + . "
      \n" + . "
      "; +} + + +if ($action == "checksettings" || $action == "changelang" || $action=="changehtmleditormode") +{ + //GET NUMBER OF SURVEYS + $query = "SELECT sid FROM ".db_table_name('surveys'); + $result = $connect->Execute($query); //Checked + $surveycount=$result->RecordCount(); + $query = "SELECT sid FROM ".db_table_name('surveys')." WHERE active='Y'"; + $result = $connect->Execute($query); //Checked + $activesurveycount=$result->RecordCount(); + $query = "SELECT users_name FROM ".db_table_name('users'); + $result = $connect->Execute($query); //Checked + $usercount = $result->RecordCount(); + + // prepare data for the htmleditormode preference + $edmod1=''; + $edmod2=''; + $edmod3=''; + $edmod4=''; + switch ($_SESSION['htmleditormode']) + { + case 'none': + $edmod2="selected='selected'"; + break; + case 'inline': + $edmod3="selected='selected'"; + break; + case 'popup': + $edmod4="selected='selected'"; + break; + default: + $edmod1="selected='selected'"; + break; + } + + $tablelist = $connect->MetaTables(); + foreach ($tablelist as $table) + { + $stlength=strlen($dbprefix).strlen("old"); + if (substr($table, 0, $stlength+strlen("_tokens")) == $dbprefix."old_tokens") + { + $oldtokenlist[]=$table; + } + elseif (substr($table, 0, strlen($dbprefix) + strlen("tokens")) == $dbprefix."tokens") + { + $tokenlist[]=$table; + } + elseif (substr($table, 0, $stlength) == $dbprefix."old") + { + $oldresultslist[]=$table; + } + } + if(isset($oldresultslist) && is_array($oldresultslist)) + {$deactivatedsurveys=count($oldresultslist);} else {$deactivatedsurveys=0;} + if(isset($oldtokenlist) && is_array($oldtokenlist)) + {$deactivatedtokens=count($oldtokenlist);} else {$deactivatedtokens=0;} + if(isset($tokenlist) && is_array($tokenlist)) + {$activetokens=count($tokenlist);} else {$activetokens=0;} + $cssummary = "
      " + . "\n" + . "\n" + . "\n" + . "\n"; + // Database name & default language + $cssummary .= "\n" + . "\n" + . "\n" + . "\n" + . "\n" + . "\n"; + // Other infos + $cssummary .= "\n" + . "\n" + . "\n" + . "\n" + . "\n" + . "\n" + . "\n" + . "\n" + . "\n" + . "\n" + . "\n" + . "\n" + . "\n" + . "\n" + . "\n" + . "\n" + . "\n" + . "\n" + . "
      \n" + . "".$clang->gT("LimeSurvey System Summary")."\n" + . "
      \n" + . "".$clang->gT("Database Name").":\n" + . "\n" + . "$databasename\n" + . "
      \n" + . "".$clang->gT("Default Language").":\n" + . "\n" + . "".getLanguageNameFromCode($defaultlang)."\n" + . "
      \n" + . "".$clang->gT("Users").":\n" + . "\n" + . "$usercount\n" + . "
      \n" + . "".$clang->gT("Surveys").":\n" + . "\n" + . "$surveycount\n" + . "
      \n" + . "".$clang->gT("Active Surveys").":\n" + . "\n" + . "$activesurveycount\n" + . "
      \n" + . "".$clang->gT("De-activated Surveys").":\n" + . "\n" + . "$deactivatedsurveys\n" + . "
      \n" + . "".$clang->gT("Active Token Tables").":\n" + . "\n" + . "$activetokens\n" + . "
      \n" + . "".$clang->gT("De-activated Token Tables").":\n" + . "\n" + . "$deactivatedtokens\n" + . "

      \n"; + + if ($_SESSION['USER_RIGHT_CONFIGURATOR'] == 1) + { + $cssummary .= "
      "; + } +} + + + + +if ($surveyid) +{ + $query = "SELECT * FROM ".db_table_name('surveys_rights')." WHERE sid = {$surveyid} AND uid = ".$_SESSION['loginID']; + $result = $connect->SelectLimit($query, 1); + if($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $result->RecordCount() > 0) + { + $baselang = GetBaseLanguageFromSurveyID($surveyid); + $sumquery5 = "SELECT b.* FROM {$dbprefix}surveys AS a INNER JOIN {$dbprefix}surveys_rights AS b ON a.sid = b.sid WHERE a.sid=$surveyid AND b.uid = ".$_SESSION['loginID']; //Getting rights for this survey and user + $sumresult5 = db_execute_assoc($sumquery5); //Checked + $sumrows5 = $sumresult5->FetchRow(); + $sumquery3 = "SELECT * FROM ".db_table_name('questions')." WHERE sid=$surveyid AND language='".$baselang."'"; //Getting a count of questions for this survey + $sumresult3 = $connect->Execute($sumquery3); //Checked + $sumcount3 = $sumresult3->RecordCount(); + $sumquery6 = "SELECT * FROM ".db_table_name('conditions')." as c, ".db_table_name('questions')."as q WHERE c.qid = q.qid AND q.sid=$surveyid"; //Getting a count of conditions for this survey + $sumresult6 = $connect->Execute($sumquery6) or die("Can't coun't conditions"); //Checked + $sumcount6 = $sumresult6->RecordCount(); + $sumquery2 = "SELECT * FROM ".db_table_name('groups')." WHERE sid=$surveyid AND language='".$baselang."'"; //Getting a count of groups for this survey + $sumresult2 = $connect->Execute($sumquery2); //Checked + $sumcount2 = $sumresult2->RecordCount(); + $sumquery1 = "SELECT * FROM ".db_table_name('surveys')." inner join ".db_table_name('surveys_languagesettings')." on (surveyls_survey_id=sid and surveyls_language=language) WHERE sid=$surveyid"; //Getting data for this survey + $sumresult1 = db_select_limit_assoc($sumquery1, 1); //Checked + + // Output starts here... + $surveysummary = ""; + + $surveyinfo = $sumresult1->FetchRow(); + + $surveyinfo = array_map('strip_tags', $surveyinfo); + //$surveyinfo = array_map('htmlspecialchars', $surveyinfo); + $activated = $surveyinfo['active']; + //BUTTON BAR + $surveysummary .= "" //"
      \n" + . "\n"; + $surveysummary .= "

       

      "; //CSS Firefox 2 transition fix + + + //SURVEY SUMMARY + if ($gid || $qid || $action=="deactivate"|| $action=="activate" || $action=="surveysecurity" + || $action=="surveyrights" || $action=="addsurveysecurity" || $action=="addusergroupsurveysecurity" + || $action=="setsurveysecurity" || $action=="setusergroupsurveysecurity" || $action=="delsurveysecurity" + || $action=="editsurvey" || $action=="addgroup" || $action=="importgroup" + || $action=="ordergroups" || $action=="updatesurvey" || $action=="deletesurvey" || $action=="resetsurveylogic" + || $action=="importsurvresources" + || $action=="exportstructure" || $action=="quotas" ) {$showstyle="style='display: none'";} + if (!isset($showstyle)) {$showstyle="";} + $additionnalLanguagesArray = GetAdditionalLanguagesFromSurveyID($surveyid); + $surveysummary .= "\n" + . "\n"; + $surveysummary2 = ""; + if ($surveyinfo['private'] != "N") {$surveysummary2 .= $clang->gT("Answers to this survey are anonymized.")."
      \n";} + else {$surveysummary2 .= $clang->gT("This survey is NOT anonymous.")."
      \n";} + if ($surveyinfo['format'] == "S") {$surveysummary2 .= $clang->gT("It is presented question by question.")."
      \n";} + elseif ($surveyinfo['format'] == "G") {$surveysummary2 .= $clang->gT("It is presented group by group.")."
      \n";} + else {$surveysummary2 .= $clang->gT("It is presented on one single page.")."
      \n";} + if ($surveyinfo['datestamp'] == "Y") {$surveysummary2 .= $clang->gT("Responses will be date stamped")."
      \n";} + if ($surveyinfo['ipaddr'] == "Y") {$surveysummary2 .= $clang->gT("IP Addresses will be logged")."
      \n";} + if ($surveyinfo['refurl'] == "Y") {$surveysummary2 .= $clang->gT("Referer-URL will be saved")."
      \n";} + if ($surveyinfo['usecookie'] == "Y") {$surveysummary2 .= $clang->gT("It uses cookies for access control.")."
      \n";} + if ($surveyinfo['allowregister'] == "Y") {$surveysummary2 .= $clang->gT("If tokens are used, the public may register for this survey")."
      \n";} + if ($surveyinfo['allowsave'] == "Y") {$surveysummary2 .= $clang->gT("Participants can save partially finished surveys")."
      \n";} + switch ($surveyinfo['notification']) + { + case 0: + $surveysummary2 .= $clang->gT("No email notification")."
      \n"; + break; + case 1: + $surveysummary2 .= $clang->gT("Basic email notification")."
      \n"; + break; + case 2: + $surveysummary2 .= $clang->gT("Detailed email notification with result codes")."
      \n"; + break; + } + + if($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $sumrows5['edit_survey_property']) + { + $surveysummary2 .= $clang->gT("Regenerate Question Codes:") +// . " [gT("Are you sure you want regenerate the question codes?","js")."')) {".get2post("$scriptname?action=renumberquestions&sid=$surveyid&style=straight")."}\" " + . ">".$clang->gT("Straight")."] " +// . "[gT("Are you sure you want regenerate the question codes?","js")."')) {".get2post("$scriptname?action=renumberquestions&sid=$surveyid&style=bygroup")."}\" " + . ">".$clang->gT("By Group")."]"; + $surveysummary2 .= "\n"; + } + $surveysummary .= "" + . "\n"; + if ( $modrewrite ) { + $tmp_url = $GLOBALS['publicurl'] . '/' . $surveyinfo['sid']; + $surveysummary .= "\n" + . "\n\n" + . "\n" + . "\n" + . "\n" + . "\n" + . "\n" + . "\n\n" + . "\n"; + $dateformatdetails=getDateFormatData($_SESSION['dateformat']); + if (trim($surveyinfo['startdate'])!= '') + { + $datetimeobj = new Date_Time_Converter($surveyinfo['startdate'] , "Y-m-d H:i:s"); + $startdate=$datetimeobj->convert($dateformatdetails['phpdate']); + } + else + { + $startdate="-"; + } + $surveysummary .= "\n" + . "\n"; + if (trim($surveyinfo['expires'])!= '') + { + $datetimeobj = new Date_Time_Converter($surveyinfo['expires'] , "Y-m-d H:i:s"); + $expdate=$datetimeobj->convert($dateformatdetails['phpdate']); + } + else + { + $expdate="-"; + } + $surveysummary .= "\n" + . "\n" + . "\n" + + . "\n"; + if (!$surveyinfo['language']) {$language=getLanguageNameFromCode($currentadminlang);} else {$language=getLanguageNameFromCode($surveyinfo['language']);} + $surveysummary .= "\n"; + + // get the rowspan of the Additionnal languages row + // is at least 1 even if no additionnal language is present + $additionnalLanguagesCount = count($additionnalLanguagesArray); + if ($additionnalLanguagesCount == 0) $additionnalLanguagesCount = 1; + $surveysummary .= "\n"; + + $first=true; + foreach ($additionnalLanguagesArray as $langname) + { + if ($langname) + { + if (!$first) {$surveysummary .= "";} + $first=false; + $surveysummary .= "\n"; + } + } + if ($first) $surveysummary .= ""; + + if ($surveyinfo['surveyls_urldescription']==""){$surveyinfo['surveyls_urldescription']=$surveyinfo['surveyls_url'];} + $surveysummary .= "\n" + . "\n"; + $surveysummary .= "\n"; + $surveysummary .= "\n"; + + if ($activated == "Y") + { + $surveysummary .= "\n"; + } + $surveysummary .= "
      " + . "".$clang->gT("Title").":{$surveyinfo['surveyls_title']} " + . "(".$clang->gT("ID")." {$surveyinfo['sid']})
      " + . $clang->gT("Survey URL") ." (".getLanguageNameFromCode($surveyinfo['language'],false)."): $tmp_url/lang-".$surveyinfo['language'].""; + foreach ($additionnalLanguagesArray as $langname) + { + $surveysummary .= " ".getLanguageNameFromCode($langname,false)." ".$clang->gT("Flag").""; + } + } else { + $tmp_url = $GLOBALS['publicurl'] . '/index.php?sid=' . $surveyinfo['sid']; + $surveysummary .= " $tmp_url&lang=".$surveyinfo['language'].""; + foreach ($additionnalLanguagesArray as $langname) + { + $surveysummary .= " ".getLanguageNameFromCode($langname,false)." ".$clang->gT("Flag").""; + } + } + + $surveysummary .= "
      " + . $clang->gT("Description:").""; + if (trim($surveyinfo['surveyls_description'])!='') {$surveysummary .= " {$surveyinfo['surveyls_description']}";} + $surveysummary .= "
      " + . $clang->gT("Welcome:")." {$surveyinfo['surveyls_welcometext']}
      " + . $clang->gT("Administrator:")." {$surveyinfo['admin']} ({$surveyinfo['adminemail']})
      " + . $clang->gT("Fax To:").""; + if (trim($surveyinfo['faxto'])!='') {$surveysummary .= " {$surveyinfo['faxto']}";} + $surveysummary .= "
      " + . $clang->gT("Start date:")."$startdate
      " + . $clang->gT("Expiry Date:")."$expdate
      " + . $clang->gT("Template:")." {$surveyinfo['template']}
      " + . $clang->gT("Base Language:")."$language
      " + . $clang->gT("Additional Languages").":
       ".getLanguageNameFromCode($langname)."
      " + . $clang->gT("Exit Link").":"; + if ($surveyinfo['surveyls_url']!="") {$surveysummary .=" {$surveyinfo['surveyls_urldescription']}";} + $surveysummary .="
      " + . $clang->gT("Number of questions/groups").":$sumcount3/$sumcount2
      " + . $clang->gT("Survey currently active").":"; + if ($activated == "N") + { + $surveysummary .= $clang->gT("No"); + } + else + { + $surveysummary .= $clang->gT("Yes"); + } + $surveysummary .="
      " + . $clang->gT("Survey table name").":".$dbprefix."survey_$surveyid
      " + . $clang->gT("Hints").":\n"; + + if ($activated == "N" && $sumcount3 == 0) + { + $surveysummary .= $clang->gT("Survey cannot be activated yet.")."
      \n"; + if ($sumcount2 == 0 && ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $sumrows5['define_questions'])) + { + $surveysummary .= "[".$clang->gT("You need to add groups")."]
      "; + } + if ($sumcount3 == 0 && ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 ||$sumrows5['define_questions'])) + { + $surveysummary .= "[".$clang->gT("You need to add questions")."]
      "; + } + } + $surveysummary .= $surveysummary2 + . "
      \n"; + } + else + { + include("access_denied.php"); + } +} + + +if ($surveyid && $gid ) // Show the group toolbar +{ + // TODO: check that surveyid and thus baselang are always set here + $sumquery4 = "SELECT * FROM ".db_table_name('questions')." WHERE sid=$surveyid AND + gid=$gid AND language='".$baselang."'"; //Getting a count of questions for this survey + $sumresult4 = $connect->Execute($sumquery4); //Checked + $sumcount4 = $sumresult4->RecordCount(); + $grpquery ="SELECT * FROM ".db_table_name('groups')." WHERE gid=$gid AND + language='".$baselang."' ORDER BY ".db_table_name('groups').".group_order"; + $grpresult = db_execute_assoc($grpquery); //Checked + + // Check if other questions/groups are dependent upon this group + $condarray=GetGroupDepsForConditions($surveyid,"all",$gid,"by-targgid"); + + $groupsummary = "\n"; + $groupsummary .= "

       

      "; //CSS Firefox 2 transition fix + + if ($qid || $action=='editgroup'|| $action=='addquestion') {$gshowstyle="style='display: none'";} + else {$gshowstyle="";} + + $groupsummary .= "\n" + . "\n" + . "\n\n"; + + if (!is_null($condarray)) + { + $groupsummary .= "\n" + . ""; + } + } + $groupsummary .= "\n
      " + . $clang->gT("Title").":" + . "{$grow['group_name']} ({$grow['gid']})
      " + . $clang->gT("Description:").""; + if (trim($grow['description'])!='') {$groupsummary .=$grow['description'];} + $groupsummary .= "
      " + . $clang->gT("Questions with conditions to this group").":"; + foreach ($condarray[$gid] as $depgid => $deprow) + { + foreach ($deprow['conditions'] as $depqid => $depcid) + { + //$groupsummary .= "[QID: ".$depqid."]"; + $listcid=implode("-",$depcid); + $groupsummary .= " [QID: ".$depqid."]"; + } + } + $groupsummary .= "
      \n"; +} + +if ($surveyid && $gid && $qid) // Show the question toolbar +{ + // TODO: check that surveyid is set and that so is $baselang + //Show Question Details + $qrq = "SELECT * FROM ".db_table_name('answers')." WHERE qid=$qid AND language='".$baselang."' ORDER BY sortorder, answer"; + $qrr = $connect->Execute($qrq); //Checked + $qct = $qrr->RecordCount(); + $qrquery = "SELECT * FROM ".db_table_name('questions')." WHERE gid=$gid AND sid=$surveyid AND qid=$qid AND language='".$baselang."'"; + $qrresult = db_execute_assoc($qrquery) or safe_die($qrquery."
      ".$connect->ErrorMsg()); //Checked + $questionsummary = "\n"; + $questionsummary .= "

       

      "; //CSS Firefox 2 transition fix + + if (returnglobal('viewanswer') || $action =="editquestion" || $action =="copyquestion") {$qshowstyle = "style='display: none'";} + else {$qshowstyle = "";} + $questionsummary .= "\n" + . "\n" + . "\n\n" + . "\n\n"; + if ($qrrow['preg']) + { + $questionsummary .= "\n\n"; + } + $qtypes = getqtypelist("", "array"); //qtypes = array(type code=>type description) + $questionsummary .= "\n\n"; + if ($qct == 0 && ($qrrow['type'] == "O" || $qrrow['type'] == "L" + || $qrrow['type'] == "!" || $qrrow['type'] == "M" + || $qrrow['type'] == "Q" || $qrrow['type'] == "K" + || $qrrow['type'] == "A" || $qrrow['type'] == "B" + || $qrrow['type'] == "C" || $qrrow['type'] == "E" + || $qrrow['type'] == "P" || $qrrow['type'] == "R" + || $qrrow['type'] == "F" || $qrrow['type'] == "1" + || $qrrow['type'] == "H" || $qrrow['type'] == ":" + || $qrrow['type'] == ";")) + { + $questionsummary .= "\n"; + } + + // For Labelset Questions show the label set and warn if there is no label set configured + if (($qrrow['type'] == "1" || $qrrow['type'] == "F" || $qrrow['type'] == "H" || + $qrrow['type'] == "W" || $qrrow['type'] == "Z" || $qrrow['type'] == ":" || + $qrrow['type'] == ";" )) + { + $questionsummary .= ""; + if (!$qrrow['lid']) + { + $questionsummary .= ""; + + if ($qrrow['type'] == "1") // Second labelset for "multi scale" + { + $questionsummary .= ""; + if (!$qrrow['lid1']) + { + $questionsummary .= ""; + } + } + + + if ($qrrow['type'] == "M" or $qrrow['type'] == "P") + { + $questionsummary .= "" + . "\n" + . "\n"; + } + if (isset($qrrow['mandatory']) and ($qrrow['type'] != "X")) + { + $questionsummary .= "" + . "\n" + . "\n"; + } + if (!is_null($condarray)) + { + $questionsummary .= "" + . "\n"; + } + $qid_attributes=getQuestionAttributes($qid); + $questionsummary .= "
      " + . $clang->gT("Code:")."{$qrrow['title']}"; + if ($qrrow['type'] != "X") + { + if ($qrrow['mandatory'] == "Y") {$questionsummary .= ": (".$clang->gT("Mandatory Question").")";} + else {$questionsummary .= ": (".$clang->gT("Optional Question").")";} + } + $questionsummary .= "
      " + . $clang->gT("Question:")."".strip_tags($qrrow['question'])."
      " + . $clang->gT("Help:").""; + if (trim($qrrow['help'])!=''){$questionsummary .= strip_tags($qrrow['help']);} + $questionsummary .= "
      " + . $clang->gT("Validation:")."{$qrrow['preg']}" + . "
      " + .$clang->gT("Type:")."{$qtypes[$qrrow['type']]}"; + $questionsummary .="
      " + . "" + . $clang->gT("Warning").": ". $clang->gT("You need to add answers to this question")." " + . "
      ". $clang->gT("Label Set").":" + . $clang->gT("Warning")." - ".$clang->gT("You need to choose a label set for this question!")."\n"; + } + else + // If label set ID is configured show the labelset name and ID + { + + $labelsetname=$connect->GetOne("SELECT label_name FROM ".db_table_name('labelsets')." WHERE lid = ".$qrrow['lid']); + $questionsummary .= "".$labelsetname." (LID: {$qrrow['lid']}) "; + } + // If the user has the right to edit the label sets show the icon for the label set administration + if ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $sumrows5['define_questions']) + { + $questionsummary .= "\n"; + } + $questionsummary .= "
      ". $clang->gT("Second Label Set").":" + . $clang->gT("Warning")." - ".$clang->gT("You need to choose a second label set for this question!")."\n"; + } + else + // If label set ID is configured show the labelset name and ID + { + + $labelsetname=$connect->GetOne("SELECT label_name FROM ".db_table_name('labelsets')." WHERE lid = ".$qrrow['lid1']); + $questionsummary .= "".$labelsetname." (LID: {$qrrow['lid1']}) "; + } + + // If the user has the right to edit the second label sets show the icon for the label set administration + if ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $sumrows5['define_questions']) + { + $questionsummary .= "\n"; + } + $questionsummary .= "
      " + . $clang->gT("Option 'Other':").""; + $questionsummary .= ($qrrow['other'] == "Y") ? ($clang->gT("Yes")) : ($clang->gT("No")) ; + $questionsummary .= "
      " + . $clang->gT("Mandatory:").""; + $questionsummary .= ($qrrow['mandatory'] == "Y") ? ($clang->gT("Yes")) : ($clang->gT("No")) ; + $questionsummary .= "
      " + . $clang->gT("Other questions having conditions on this question:") + . "\n"; + foreach ($condarray[$qid] as $depqid => $depcid) + { + $listcid=implode("-",$depcid); + $questionsummary .= " [QID: ".$depqid."]"; + } + $questionsummary .= "
      "; + } +} + +if (returnglobal('viewanswer')) +{ + $_SESSION['FileManagerContext']="edit:answer:$surveyid"; + // Get languages select on survey. + $anslangs = GetAdditionalLanguagesFromSurveyID($surveyid); + $baselang = GetBaseLanguageFromSurveyID($surveyid); + + // check that there are answers for every language supported by the survey + foreach ($anslangs as $language) + { + $qquery = "SELECT count(*) as num_ans FROM ".db_table_name('answers')." WHERE qid=$qid AND language='".$language."'"; + $qresult = db_execute_assoc($qquery); //Checked + $qrow = $qresult->FetchRow(); + if ($qrow["num_ans"] == 0) // means that no record for the language exists in the answers table + { + $qquery = "INSERT INTO ".db_table_name('answers')." (SELECT `qid`,`code`,`answer`,`default_value`,`sortorder`, '".$language."' FROM ".db_table_name('answers')." WHERE qid=$qid AND language='".$baselang."')"; + $connect->Execute($qquery); //Checked + } + } + + array_unshift($anslangs,$baselang); // makes an array with ALL the languages supported by the survey -> $anslangs + + //delete the answers in languages not supported by the survey + $qquery = "SELECT DISTINCT language FROM ".db_table_name('answers')." WHERE (qid = $qid) AND (language NOT IN ('".implode("','",$anslangs)."'))"; + $qresult = db_execute_assoc($qquery); //Checked + while ($qrow = $qresult->FetchRow()) + { + $qquery = "DELETE FROM ".db_table_name('answers')." WHERE (qid = $qid) AND (language = '".$qrow["language"]."')"; + $connect->Execute($qquery); //Checked + } + + + // Check sort order for answers + $qquery = "SELECT type FROM ".db_table_name('questions')." WHERE qid=$qid AND language='".$baselang."'"; + $qresult = db_execute_assoc($qquery); //Checked + while ($qrow=$qresult->FetchRow()) {$qtype=$qrow['type'];} + if (!isset($_POST['ansaction'])) + { + //check if any nulls exist. If they do, redo the sortorders + $caquery="SELECT * FROM ".db_table_name('answers')." WHERE qid=$qid AND sortorder is null AND language='".$baselang."'"; + $caresult=$connect->Execute($caquery); //Checked + $cacount=$caresult->RecordCount(); + if ($cacount) + { + fixsortorderAnswers($qid); // !!Adjust this!! + } + } + + // Print Key Control JavaScript + $vasummary = PrepareEditorScript("editanswer"); + + $query = "SELECT sortorder FROM ".db_table_name('answers')." WHERE qid='{$qid}' AND language='".GetBaseLanguageFromSurveyID($surveyid)."' ORDER BY sortorder desc"; + $result = db_execute_assoc($query) or safe_die($connect->ErrorMsg()); //Checked + $anscount = $result->RecordCount(); + $row=$result->FetchRow(); + $maxsortorder=$row['sortorder']+1; + $vasummary .= "\n" + ."\n" + ."\n" + ."\n" + ."
      \n" + .$clang->gT("Edit Answers") + ."
      gT("Error: You are trying to use duplicate answer codes.",'js')."');\">\n" + . "\n" + . "\n" + . "\n" + . "\n" + . "\n" + . "\n"; + $vasummary .= "
      "; + $first=true; + $sortorderids=''; + $codeids=''; + + $vasummary .= "
      \n"; + + // the following line decides if the assessment input fields are visible or not + // for some question types the assessment values is set in the label set instead of the answers + $assessmentvisible=($surveyinfo['assessments']=='Y' && !in_array($qtype,array('A','B','C','E','F','K','R','Z',':'))); + + foreach ($anslangs as $anslang) + { + $position=0; + $query = "SELECT * FROM ".db_table_name('answers')." WHERE qid='{$qid}' AND language='{$anslang}' ORDER BY sortorder, code"; + $result = db_execute_assoc($query) or safe_die($connect->ErrorMsg()); //Checked + $anscount = $result->RecordCount(); + $vasummary .= "
      " + ."

      ".getLanguageNameFromCode($anslang, false); + if ($anslang==GetBaseLanguageFromSurveyID($surveyid)) {$vasummary .= '('.$clang->gT("Base Language").')';} + + $vasummary .= "

      \n" + ."" + ."\n" + ."\n"; + if ($assessmentvisible) + { + $vasummary .="\n" + ."\n" + ."\n" + ."" + .""; + $alternate=false; + while ($row=$result->FetchRow()) + { + $row['code'] = htmlspecialchars($row['code']); + $row['answer']=htmlspecialchars($row['answer']); + + $sortorderids=$sortorderids.' '.$row['language'].'_'.$row['sortorder']; + if ($first) {$codeids=$codeids.' '.$row['sortorder'];} + + $vasummary .= "gT("Default")."" + .""; + } + + if (($activated != 'Y' && $first) || ($activated == 'Y' && $first && (($qtype=='O') || ($qtype=='L') || ($qtype=='!') ))) + { + $vasummary .= ""; + $vasummary .= ""; + } + elseif (($activated != 'N' && $first) ) // If survey is activated and its not one of the above question types who allows modfying answers on active survey + { + $vasummary .= "{$row['code']}"; + $vasummary .= ""; + + } + else + { + $vasummary .= "{$row['code']}"; + + } + + $vasummary .= "\n" + .""; + } + elseif ( $first) + { + $vasummary .= " style='display:none;'>"; + } + elseif ($assessmentvisible) + { + $vasummary .= '>'.$row['assessment_value']; + } + else + { + $vasummary .= " style='display:none;'>"; + } + + $vasummary .= "\n" + ."\n" + ."\n"; + $position++; + } + ++$anscount; + if ($anscount > 0) + { + $vasummary .= "\n"; + } + $position=sprintf("%05d", $position); + if ($activated != 'Y' || (($activated == 'Y') && (($qtype=='O' ) || ($qtype=='L' ) ||($qtype=='!' )))) + { + + if ($first==true) + { + $vasummary .= "" + .""; + } + else + { + $vasummary .= " style='display:none;'>"; + } + $vasummary .="\n" + ."\n" + ."\n" + ."\n" + ."\n"; + } + } + else + { + $vasummary .= "\n" + ."\n" + ."\n"; + } + $first=false; + $vasummary .= "
      \n" + .$clang->gT("Code") + ."".$clang->gT("Assessment value"); + } + else + { + $vasummary .=""; + } + $vasummary .="\n" + .$clang->gT("Answer") + ."\n" + .$clang->gT("Action") + ."\n" + .$clang->gT("Order"); + + $vasummary .= "
      \n" + ."\n" + . getEditor("editanswer","answer_".$row['language']."_".$row['sortorder'], "[".$clang->gT("Answer:", "js")."](".$row['language'].")",$surveyid,$gid,$qid,'editanswer') + ."\n"; + + // Deactivate delete button for active surveys + if ($activated != 'Y' || ($activated == 'Y' && (($qtype=='O' ) || ($qtype=='L' ) ||($qtype=='!' )))) + { + $vasummary .= "\n"; + } + else + { + $vasummary .= "\n"; + } + + // Don't show Default Button for array question types + if ($qtype != "A" && $qtype != "B" && $qtype != "C" && $qtype != "E" && $qtype != "F" && $qtype != "H" && $qtype != "R" && $qtype != "Q" && $qtype != "1" && $qtype != ":" && $qtype != ";") $vasummary .= "\n"; + $vasummary .= "\n"; + if ($position > 0) + { + $vasummary .= "\n"; + }; + if ($position < $anscount-1) + { + // Fill the sortorder hiddenfield so we now what field is moved down + $vasummary .= "\n"; + } + $vasummary .= "
      " + ."\n" + ."

      " + ."".$clang->gT("New Answer").": "; + if (!isset($_SESSION['nextanswercode'])) $_SESSION['nextanswercode']=''; + $vasummary .= ""; + unset($_SESSION['nextanswercode']); + + + $first=false; + $vasummary .= "\n" + ."\n" + . getEditor("addanswer","insertanswer", "[".$clang->gT("Answer:", "js")."]",'','','',$action) + ."\n" + ."\n" + ."\n" + ."\n" + ."\n" + ."
      \n" + ."" + .$clang->gT("Warning").": ".$clang->gT("You cannot add answers or edit answer codes for this question type because the survey is active.")."\n" + ."
      \n"; + $vasummary .= "\n"; + $vasummary .= "\n"; + $vasummary .= "
      "; + } + $vasummary .= "
      "; + + +} + +// ************************************************* +// Survey Rights Start **************************** +// ************************************************* + +if($action == "addsurveysecurity") +{ + $addsummary = "
      ".$clang->gT("Add User")."
      \n"; + + $query = "SELECT sid, owner_id FROM ".db_table_name('surveys')." WHERE sid = {$surveyid} AND owner_id = ".$_SESSION['loginID']." AND owner_id != ".$postuserid; + $result = db_execute_assoc($query); //Checked + if( ($result->RecordCount() > 0 && in_array($postuserid,getuserlist('onlyuidarray'))) || + $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) + { + if($postuserid > 0){ + + $isrquery = "INSERT INTO {$dbprefix}surveys_rights VALUES($surveyid,". $postuserid.",0,0,0,0,0,0)"; + $isrresult = $connect->Execute($isrquery); //Checked + + if($isrresult) + { + $addsummary .= "
      ".$clang->gT("User added.")."
      \n"; + $addsummary .= "
      " + ."" + ."" + ."" + ."
      \n"; + } + else + { + // Username already exists. + $addsummary .= "
      ".$clang->gT("Failed to add User.")."
      \n" . " " . $clang->gT("Username already exists.")."
      \n"; + } + $addsummary .= "
      ".$clang->gT("Continue")."
       \n"; + } + else + { + $addsummary .= "
      ".$clang->gT("Failed to add User.")."
      \n" . " " . $clang->gT("No Username selected.")."
      \n"; + $addsummary .= "
      ".$clang->gT("Continue")."
       \n"; + } + } + else + { + include("access_denied.php"); + } +} + + +if($action == "addusergroupsurveysecurity") +{ + $addsummary = "
      ".$clang->gT("Add User Group")."
      \n"; + + $query = "SELECT sid, owner_id FROM ".db_table_name('surveys')." WHERE sid = {$surveyid} AND owner_id = ".$_SESSION['loginID']; + $result = db_execute_assoc($query); //Checked + if( ($result->RecordCount() > 0 && in_array($postusergroupid,getsurveyusergrouplist('simpleugidarray')) ) || + $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) + { + if($postusergroupid > 0){ + $query2 = "SELECT b.uid FROM (SELECT uid FROM ".db_table_name('surveys_rights')." WHERE sid = {$surveyid}) AS c RIGHT JOIN ".db_table_name('user_in_groups')." AS b ON b.uid = c.uid WHERE c.uid IS NULL AND b.ugid = {$postusergroupid}"; + $result2 = db_execute_assoc($query2); //Checked + if($result2->RecordCount() > 0) + { + while ($row2 = $result2->FetchRow()) + { + $uid_arr[] = $row2['uid']; + $values[] = "($surveyid, {$row2['uid']},0,0,0,0,0,0)"; + } + $values_implode = implode(",", $values); + + $isrquery = "INSERT INTO {$dbprefix}surveys_rights VALUES ".$values_implode; + $isrresult = $connect->Execute($isrquery); //Checked + + if($isrresult) + { + $addsummary .= "
      ".$clang->gT("User Group added.")."
      \n"; + $_SESSION['uids'] = $uid_arr; + $addsummary .= "
      " + ."" + ."" + ."" + ."
      \n"; + } + } + else + { + // no user to add + $addsummary .= "
      ".$clang->gT("Failed to add User Group.")."
      \n"; + } + $addsummary .= "
      ".$clang->gT("Continue")."
       \n"; + } + else + { + $addsummary .= "
      ".$clang->gT("Failed to add User.")."
      \n" . " " . $clang->gT("No Username selected.")."
      \n"; + $addsummary .= "
      ".$clang->gT("Continue")."
       \n"; + } + } + else + { + include("access_denied.php"); + } +} + +if($action == "delsurveysecurity"){ + { + $addsummary = "
      ".$clang->gT("Deleting User")."
      \n"; + + $query = "SELECT sid, owner_id FROM ".db_table_name('surveys')." WHERE sid = {$surveyid} AND owner_id = ".$_SESSION['loginID']." AND owner_id != ".$postuserid; + $result = db_execute_assoc($query); //Checked + if($result->RecordCount() > 0 || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) + { + if (isset($postuserid)) + { + $dquery="DELETE FROM {$dbprefix}surveys_rights WHERE uid={$postuserid} AND sid={$surveyid}"; // added by Dennis + $dresult=$connect->Execute($dquery); //Checked + + $addsummary .= "
      ".$clang->gT("Username").": ".sanitize_xss_string($_POST['user'])."
      \n"; + } + else + { + $addsummary .= "
      ".$clang->gT("Could not delete user. User was not supplied.")."
      \n"; + } + } + else + { + include("access_denied.php"); + } + $addsummary .= "

      ".$clang->gT("Continue")."
       \n"; + } +} + +if($action == "setsurveysecurity") +{ + $query = "SELECT sid, owner_id FROM ".db_table_name('surveys')." WHERE sid = {$surveyid} AND owner_id = ".$_SESSION['loginID']." AND owner_id != ".$postuserid; + $result = db_execute_assoc($query); //Checked + if($result->RecordCount() > 0 || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) + { + $query2 = "SELECT uid, edit_survey_property, define_questions, browse_response, export, delete_survey, activate_survey FROM ".db_table_name('surveys_rights')." WHERE sid = {$surveyid} AND uid = ".$postuserid; + $result2 = db_execute_assoc($query2); //Checked + + if($result2->RecordCount() > 0) + { + $resul2row = $result2->FetchRow(); + + $usersummary = "\n\n"; + + $usersummary .= "\n" + . "\n" + . "\n" + . "\n" + . "\n" + . "\n" + . "\n" + . "\n"; + + //content + $usersummary .= "" + ."" + . "
      \n" + . "".$clang->gT("Set Survey Rights")."
      ".$clang->gT("Edit Survey Properties")."".$clang->gT("Define Questions")."".$clang->gT("Browse Responses")."".$clang->gT("Export")."".$clang->gT("Delete Survey")."".$clang->gT("Activate Survey")."
      " + ."" + ."
      \n"; + } + } + else + { + include("access_denied.php"); + } +} + + +if($action == "setusergroupsurveysecurity") +{ + $query = "SELECT sid, owner_id FROM ".db_table_name('surveys')." WHERE sid = {$surveyid} AND owner_id = ".$_SESSION['loginID'];//." AND owner_id != ".$postuserid; + $result = db_execute_assoc($query); //Checked + if($result->RecordCount() > 0 || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) + { + $usersummary = "\n\n"; + + $usersummary .= "\n" + . "\n" + . "\n" + . "\n" + . "\n" + . "\n" + . "\n" + . "\n"; + + //content + $usersummary .= "" + ."" + . "
      \n" + . "".$clang->gT("Set Survey Rights")."
      ".$clang->gT("Edit Survey Property")."".$clang->gT("Define Questions")."".$clang->gT("Browse Response")."".$clang->gT("Export")."".$clang->gT("Delete Survey")."".$clang->gT("Activate Survey")."
      " + ."" + ."
      \n"; + } + else + { + include("access_denied.php"); + } +} + +// This is the action to export the structure of a complete survey +if($action == "exportstructure") +{ + if($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $sumrows5['export']) + { + $exportstructure = "
      \n" + ."\n\n" + ."\n" + ."\n" + ."\n" + ."\n" + ."\n" + ."\n" + ."\n"; + $exportstructure.="
      " + .$clang->gT("Export Survey Structure")."\n
      \n"; + $exportstructure.="
      " + ."
      \n"; + + $exportstructure.="" + ."\n"; + + // XXX + include("../config.php"); + + //echo $export4lsrc; + if($export4lsrc) + { + $exportstructure.="
      " + ."\n"; + } + + $exportstructure.="
       
      \n" + ."\n" + ."\n" + ."\n" + ."

      \n"; + } +} + + +if($action == "surveysecurity") +{ + $query = "SELECT sid FROM ".db_table_name('surveys')." WHERE sid = {$surveyid} AND owner_id = ".$_SESSION['loginID']; + $result = db_execute_assoc($query); //Checked + if($result->RecordCount() > 0 || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) + { + $query2 = "SELECT a.uid, b.users_name FROM ".db_table_name('surveys_rights')." AS a INNER JOIN ".db_table_name('users')." AS b ON a.uid = b.uid WHERE a.sid = {$surveyid} AND b.uid != ".$_SESSION['loginID'] ." ORDER BY b.users_name"; + $result2 = db_execute_assoc($query2); //Checked + $surveysecurity = "\n\n" + . "\n" + . "\n" + . "\n" + . "\n" + . "\n"; + + if (isset($usercontrolSameGroupPolicy) && + $usercontrolSameGroupPolicy == true) + { + $authorizedGroupsList=getusergrouplist('simplegidarray'); + } + + if($result2->RecordCount() > 0) + { + // output users + $row = 0; + while ($resul2row = $result2->FetchRow()) + { + $query3 = "SELECT a.ugid FROM ".db_table_name('user_in_groups')." AS a RIGHT OUTER JOIN ".db_table_name('users')." AS b ON a.uid = b.uid WHERE b.uid = ".$resul2row['uid']; + $result3 = db_execute_assoc($query3); //Checked + while ($resul3row = $result3->FetchRow()) + { + if (!isset($usercontrolSameGroupPolicy) || + $usercontrolSameGroupPolicy == false || + in_array($resul3row['ugid'],$authorizedGroupsList)) + { + $group_ids[] = $resul3row['ugid']; + } + } + + if(isset($group_ids) && $group_ids[0] != NULL) + { + $group_ids_query = implode(" OR ugid=", $group_ids); + unset($group_ids); + + $query4 = "SELECT name FROM ".db_table_name('user_groups')." WHERE ugid = ".$group_ids_query; + $result4 = db_execute_assoc($query4); //Checked + + while ($resul4row = $result4->FetchRow()) + { + $group_names[] = $resul4row['name']; + } + if(count($group_names) > 0) + $group_names_query = implode(", ", $group_names); + } +// else {break;} //TODO Commented by lemeur + if(($row % 2) == 0) + $surveysecurity .= "\n"; + else + $surveysecurity .= "\n"; + + $surveysecurity .= "\n" + . "\n" + . "\n"; + $row++; + } + } + $surveysecurity .= "\n" + . "\n" + + . "\n" + + . "\n" + . "\n"; + //. "
      \n" + . "".$clang->gT("Survey Security")."
      ".$clang->gT("Username")."".$clang->gT("User Group")."".$clang->gT("Action")."
      {$resul2row['users_name']}\n" + . ""; + + if(isset($group_names) > 0) + { + $surveysecurity .= $group_names_query; + } + else + { + $surveysecurity .= "---"; + } + unset($group_names); + + $surveysecurity .= "\n"; + + $surveysecurity .= "" + ."" + ."" + ."" + ."" + .""; + + $surveysecurity .= "
      " + ."" + ."" + ."" + ."" + ."
      \n"; + + $surveysecurity .= "
      " + . "".$clang->gT("User").": \n" + . "gT("Please select a user first","js")."'); return false;}\"/>" + . "
      \n"; + + $surveysecurity .= "
      \n" + . "
      " + . "".$clang->gT("Groups").": \n" + . "gT("Please select a user group first","js")."'); return false;}\" />" + . "
      \n"; + } + else + { + include("access_denied.php"); + } +} + +elseif ($action == "surveyrights") +{ + $addsummary = "
      ".$clang->gT("Set Survey Rights")."
      \n"; + + if(isset($postuserid)){ + $query = "SELECT sid, owner_id FROM ".db_table_name('surveys')." WHERE sid = {$surveyid} "; + if ($_SESSION['USER_RIGHT_SUPERADMIN'] != 1) + { + $query.=" AND owner_id != ".$postuserid." AND owner_id = ".$_SESSION['loginID']; + } + } + else{ + $query = "SELECT sid, owner_id FROM ".db_table_name('surveys')." WHERE sid = {$surveyid} AND owner_id = ".$_SESSION['loginID']; + } + $result = db_execute_assoc($query); //Checked + if($result->RecordCount() > 0) + { + $rights = array(); + + if(isset($_POST['edit_survey_property']))$rights['edit_survey_property']=1; else $rights['edit_survey_property']=0; + if(isset($_POST['define_questions']))$rights['define_questions']=1; else $rights['define_questions']=0; + if(isset($_POST['browse_response']))$rights['browse_response']=1; else $rights['browse_response']=0; + if(isset($_POST['export']))$rights['export']=1; else $rights['export']=0; + if(isset($_POST['delete_survey']))$rights['delete_survey']=1; else $rights['delete_survey']=0; + if(isset($_POST['activate_survey']))$rights['activate_survey']=1; else $rights['activate_survey']=0; + + if(isset($postuserid)){ + $uids[] = $postuserid; + } + else{ + $uids = $_SESSION['uids']; + unset($_SESSION['uids']); + } + if(setsurveyrights($uids, $rights)) + { + $addsummary .= "
      ".$clang->gT("Update survey rights successful.")."
      \n"; + } + else + { + $addsummary .= "
      ".$clang->gT("Failed to update survey rights!")."
      \n"; + } + $addsummary .= "

      ".$clang->gT("Continue")."
       \n"; + } + else + { + include("access_denied.php"); + } +} + +// ************************************************* +// Survey Rights End **************************** +// ************************************************* + + +// Editing the survey +if ($action == "editsurvey") +{ + if($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $sumrows5['edit_survey_property']) + { + $esquery = "SELECT * FROM {$dbprefix}surveys WHERE sid=$surveyid"; + $esresult = db_execute_assoc($esquery); //Checked + while ($esrow = $esresult->FetchRow()) + { + $esrow = array_map('htmlspecialchars', $esrow); + + $editsurvey = "
      \n"; + + // header + $editsurvey .= "\n
      " + . "".$clang->gT("Edit survey settings - Step 1 of 2")."
      \n"; + + + // beginning TABs section + $editsurvey .= "
      \n"; + // General & Contact TAB + $editsurvey .= "

      ".$clang->gT("General")."

      \n"; + + // Base Language + $editsurvey .= "
      ".$clang->gT("Base Language:")."\n" + . "\n".GetLanguageNameFromCode($esrow['language']) + . "
      \n" + + // Additional languages listbox + . "
      ".$clang->gT("Additional Languages").":\n" + . "" + . "\n" + + // Available languages listbox + . "" + . "
      gT("Add")."\" onclick=\"DoAdd()\" id=\"AddBtn\" />
      gT("Remove")." >>\" onclick=\"DoRemove(0,'')\" id=\"RemoveBtn\" />
      \n"; + + $editsurvey .= ""; + + + // Administrator... + $editsurvey .= "" + . "
      ".$clang->gT("Administrator:")."\n" + . "
      \n" + . "
      ".$clang->gT("Admin Email:")."\n" + . "
      \n" + . "
      ".$clang->gT("Bounce Email:")."\n" + . "
      \n" + . "
      ".$clang->gT("Fax To:")."\n" + . "
      \n"; + + // End General TAB + // Create Survey Button +// $editsurvey .= "
      \n"; + $editsurvey .= "
      \n"; + + // Presentation and navigation TAB + $editsurvey .= "

      ".$clang->gT("Presentation & Navigation")."

      \n"; + + //Format + $editsurvey .= "
      ".$clang->gT("Format:")."\n" + . "\n" + . "
      \n"; + + //TEMPLATES + $editsurvey .= "
      ".$clang->gT("Template:")."\n" + . "\n" + . "\n" + . "\n" + . "\n" + . "
      \n"; + + //Show Prev Button + $editsurvey .= "
      ".$clang->gT("Show [<< Prev] button")."\n" + . "\n" + . "
      \n"; + + //Result printing + $editsurvey .= "
      ".$clang->gT("Participants may print answers?")."\n" + . "\n" + . "
      \n"; + + //Public statistics + $editsurvey .= "
      ".$clang->gT("Public statistics?")."\n" + . "\n" + . "
      \n"; + + //Public statistics + $editsurvey .= "
      ".$clang->gT("Show graphs in public statistics?")."\n" + . "\n" + . "
      \n"; + + //Public Surveys + $editsurvey .= "
      ".$clang->gT("List survey publicly:")."\n" + . "\n" + . "
      \n"; + + + // End URL block + $editsurvey .= "
      ".$clang->gT("Automatically load URL when survey complete?")."\n" + . "
      "; + + + // End Presention and navigation TAB + // Create Survey Button +// $editsurvey .= "
      \n"; + $editsurvey .= "
      \n"; + + // Publication and access control TAB + $editsurvey .= "

      ".$clang->gT("Publication & Access control")."

      \n"; + + + + // Token access + $editsurvey .= "
      ".$clang->gT("Only users with tokens may enter the survey?")."\n" + . "\n
      \n"; + + // Self registration + $editsurvey .= "
      ".$clang->gT("Allow public registration?")."\n" + . "\n
      \n"; + + + + // Start date + $dateformatdetails=getDateFormatData($_SESSION['dateformat']); + $startdate=''; + if (trim($esrow['startdate'])!= '') + { + $datetimeobj = new Date_Time_Converter($esrow['startdate'] , "Y-m-d H:i:s"); + $startdate=$datetimeobj->convert($dateformatdetails['phpdate']); + } + + $editsurvey .= "
      \n" + . "
      \n"; + + // Expiration date + $expires=''; + if (trim($esrow['expires'])!= '') + { + $datetimeobj = new Date_Time_Converter($esrow['expires'] , "Y-m-d H:i:s"); + $expires=$datetimeobj->convert($dateformatdetails['phpdate']); + } + $editsurvey .="
      ".$clang->gT("Expiry Date:")."\n" + . "
      \n"; + //COOKIES + $editsurvey .= "
      ".$clang->gT("Set cookie to prevent repeated participation?")."\n" + . "\n" + . "
      \n"; + + + // Use Captcha + $editsurvey .= "
      ".$clang->gT("Use CAPTCHA for").":\n" + . "gT("If you switch email mode, you'll have to review your email templates to fit the new format","js")."');\">\n" + . "\n" + . "\n" + . "\n
      \n"; + + // End Publication and access control TAB + // Create Survey Button +// $editsurvey .= "
      \n"; + $editsurvey .= "
      \n"; + + // Notification and Data management TAB + $editsurvey .= "

      ".$clang->gT("Notification & Data Management")."

      \n"; + + + //NOTIFICATION + $editsurvey .= "
      ".$clang->gT("Admin Notification:")."\n" + . "\n" + . "
      \n"; + + + //ANONYMOUS + $editsurvey .= "
      ".$clang->gT("Anonymous answers?")."\n"; + // warning message if anonymous + tokens used + $editsurvey .= "\n" + . "\n"; + + if ($esrow['active'] == "Y") + { + $editsurvey .= "\n"; + if ($esrow['private'] == "N") {$editsurvey .= " ".$clang->gT("This survey is NOT anonymous.");} + else {$editsurvey .= $clang->gT("Answers to this survey are anonymized.");} + $editsurvey .= " (".$clang->gT("Cannot be changed").")\n" + . "\n"; + $editsurvey .= "\n"; + } + else + { + $editsurvey .= "\n\n"; + } + $editsurvey .= "
      \n"; + + // date stamp + $editsurvey .= "
      ".$clang->gT("Date Stamp?")."\n"; + if ($esrow['active'] == "Y") + { + $editsurvey .= "\n"; + if ($esrow['datestamp'] != "Y") {$editsurvey .= " ".$clang->gT("Responses will not be date stamped.");} + else {$editsurvey .= $clang->gT("Responses will be date stamped.");} + $editsurvey .= " (".$clang->gT("Cannot be changed").")\n" + . "\n"; + $editsurvey .= "\n"; + } + else + { + $editsurvey .= "\n\n"; + } + $editsurvey .= "
      \n"; + + // Ip Addr + $editsurvey .= "
      ".$clang->gT("Save IP Address?")."\n"; + + if ($esrow['active'] == "Y") + { + $editsurvey .= "\n"; + if ($esrow['ipaddr'] != "Y") {$editsurvey .= " ".$clang->gT("Responses will not have the IP address logged.");} + else {$editsurvey .= $clang->gT("Responses will have the IP address logged");} + $editsurvey .= " (".$clang->gT("Cannot be changed").")\n" + . "\n"; + $editsurvey .= "\n"; + } + else + { + $editsurvey .= "\n\n"; + } + + $editsurvey .= "
      \n"; + + // begin REF URL Block + $editsurvey .= "
      ".$clang->gT("Save Referring URL?")."\n"; + + if ($esrow['active'] == "Y") + { + $editsurvey .= "\n"; + if ($esrow['refurl'] != "Y") {$editsurvey .= " ".$clang->gT("Responses will not have their referring URL logged.");} + else {$editsurvey .= $clang->gT("Responses will have their referring URL logged.");} + $editsurvey .= " (".$clang->gT("Cannot be changed").")\n" + . "\n"; + $editsurvey .= "\n"; + } + else + { + $editsurvey .= "\n\n"; + } + $editsurvey .= "
      \n"; + // BENBUN - END REF URL Block + + // Token answers persistence + $editsurvey .= "
      ".$clang->gT("Enable token-based answers persistence?")."\n" + . "\n
      \n"; + + // Enable assessments + $editsurvey .= "
      ".$clang->gT("Enable assessment mode?")."\n" + . "\n
      \n"; + + + + // End Notification and Data management TAB + $editsurvey .= "
      \n"; + + // Ending First TABs Form + $editsurvey .= "" + . "\n" + . "\n" + . "\n" + . "\n" + .""; + + + // TAB Uploaded Resources Management + + $ZIPimportAction = " onclick='if (validatefilename(this.form,\"".$clang->gT('Please select a file to import!','js')."\")) {this.form.submit();}'"; + if (!function_exists("zip_open")) + { + $ZIPimportAction = " onclick='alert(\"".$clang->gT("zip library not supported by PHP, Import ZIP Disabled","js")."\");'"; + } + + $disabledIfNoResources = ''; + if (hasResources($surveyid,'survey') === false) + { + $disabledIfNoResources = " disabled='disabled'"; + } + + $editsurvey .= "

      ".$clang->gT("Uploaded Resources Management")."

      \n" + . "
      \n" + . "\n" + . "\n" + . "\n" + . "" + . "\n" + . "\n" + . "\n" + . "\n" + . "\n" + . "\n" + . "
      \n" + . "gT("Browse Uploaded Resources")."\" $disabledIfNoResources />
      gT("Export Resources As ZIP Archive")."\" $disabledIfNoResources />
       
      ".$clang->gT("Select ZIP File:")."
      \n"; + + // End TAB Uploaded Resources Management + $editsurvey .= "
      \n"; + + // End TAB pane + $editsurvey .= "
      \n"; + + + // The external button to sumbit Survey edit changes + $editsurvey .= "\n" + . "
      \n" + . "
      \n"; + } + + } + else + { + include("access_denied.php"); + } + +} + + +if ($action == "updatesurvey") // Edit survey step 2 - editing language dependent settings +{ + if($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $sumrows5['edit_survey_property']) + { + + $grplangs = GetAdditionalLanguagesFromSurveyID($surveyid); + $baselang = GetBaseLanguageFromSurveyID($surveyid); + array_unshift($grplangs,$baselang); + + $editsurvey = PrepareEditorScript(); + + + $editsurvey .="\n" + . "\n
      " + . "".$clang->gT("Edit survey settings - Step 2 of 2")."
      \n"; + $editsurvey .= "
      \n" + . '
      '; + foreach ($grplangs as $grouplang) + { + // this one is created to get the right default texts fo each language + $bplang = new limesurvey_lang($grouplang); + $esquery = "SELECT * FROM ".db_table_name("surveys_languagesettings")." WHERE surveyls_survey_id=$surveyid and surveyls_language='$grouplang'"; + $esresult = db_execute_assoc($esquery); //Checked + $esrow = $esresult->FetchRow(); + $editsurvey .= '

      '.getLanguageNameFromCode($esrow['surveyls_language'],false); + if ($esrow['surveyls_language']==GetBaseLanguageFromSurveyID($surveyid)) {$editsurvey .= '('.$clang->gT("Base Language").')';} + $editsurvey .= '

      '; + $esrow = array_map('htmlspecialchars', $esrow); + $editsurvey .= "
      ".$clang->gT("Title").":\n" + . "\n" + . "
      ".$clang->gT("Description:")."\n" + . "\n" + . getEditor("survey-desc","description_".$esrow['surveyls_language'], "[".$clang->gT("Description:", "js")."](".$esrow['surveyls_language'].")",'','','',$action) + . "\n" + . "
      " + . "
      ".$clang->gT("Welcome message:")."\n" + . "\n" + . getEditor("survey-welc","welcome_".$esrow['surveyls_language'], "[".$clang->gT("Welcome:", "js")."](".$esrow['surveyls_language'].")",'','','',$action) + . "
      \n" + . "
      ".$clang->gT("End message:")."\n" + . "\n" + . getEditor("survey-endtext","endtext_".$esrow['surveyls_language'], "[".$clang->gT("End message:", "js")."](".$esrow['surveyls_language'].")",'','','',$action) + . "
      \n" + . "
      ".$clang->gT("End URL:")."\n" + . "\n" + . "
      " + . "
      ".$clang->gT("URL description:")."\n" + . "\n" + . "
      " + . "
      ".$clang->gT("Date format:")."\n" + . "
      " + . "
      "; + } + $editsurvey .= '
      '; + $editsurvey .= "

      \n" + . "\n" + . "\n" + . "\n" + . "

      \n" + . "
      \n"; + + } + else + { + include("access_denied.php"); + } + +} + +if($action == "quotas") +{ + include("quota.php"); +} + +// Show the screen to order groups + +if ($action == "ordergroups") +{ + if($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $sumrows5['edit_survey_property']) + { + // Check if one of the up/down buttons have been clicked + if (isset($_POST['groupordermethod']) && isset($_POST['sortorder'])) + { + $postsortorder=sanitize_int($_POST['sortorder']); + switch($_POST['groupordermethod']) + { + // Pressing the Up button + case $clang->gT("Up", "unescaped"): + $newsortorder=$postsortorder-1; + $oldsortorder=$postsortorder; + $cdquery = "UPDATE ".db_table_name('groups')." SET group_order=-1 WHERE sid=$surveyid AND group_order=$newsortorder"; + $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); //Checked + $cdquery = "UPDATE ".db_table_name('groups')." SET group_order=$newsortorder WHERE sid=$surveyid AND group_order=$oldsortorder"; + $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); //Checked + $cdquery = "UPDATE ".db_table_name('groups')." SET group_order='$oldsortorder' WHERE sid=$surveyid AND group_order=-1"; + $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); //Checked + break; + + // Pressing the Down button + case $clang->gT("Dn", "unescaped"): + $newsortorder=$postsortorder+1; + $oldsortorder=$postsortorder; + $cdquery = "UPDATE ".db_table_name('groups')." SET group_order=-1 WHERE sid=$surveyid AND group_order=$newsortorder"; + $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg());//Checked + $cdquery = "UPDATE ".db_table_name('groups')." SET group_order='$newsortorder' WHERE sid=$surveyid AND group_order=$oldsortorder"; + $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg());//Checked + $cdquery = "UPDATE ".db_table_name('groups')." SET group_order=$oldsortorder WHERE sid=$surveyid AND group_order=-1"; + $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg());//Checked + break; + } + } + // Move the question to specific position + if ((!empty($_POST['groupmovefrom']) || (isset($_POST['groupmovefrom']) && $_POST['groupmovefrom'] == '0')) && (!empty($_POST['groupmoveto']) || (isset($_POST['groupmoveto']) && $_POST['groupmoveto'] == '0'))) + { + $newpos=$_POST['groupmoveto']; + $oldpos=$_POST['groupmovefrom']; + if($newpos > $oldpos) + { + //Move the group we're changing out of the way + $cdquery = "UPDATE ".db_table_name('groups')." SET group_order=-1 WHERE sid=$surveyid AND group_order=$oldpos"; + $cdresult=$connect->Execute($cdquery) or safe_die($cdquery."
      ".$connect->ErrorMsg()); + //Move all question_orders that are less than the newpos down one + $cdquery = "UPDATE ".db_table_name('groups')." SET group_order=group_order-1 WHERE sid=$surveyid AND group_order > 0 AND group_order <= $newpos"; + $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); + //Renumber the question we're changing + $cdquery = "UPDATE ".db_table_name('groups')." SET group_order=$newpos WHERE sid=$surveyid AND group_order=-1"; + $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); + } + if(($newpos+1) < $oldpos) + { + //echo "Newpos $newpos, Oldpos $oldpos"; + //Move the question we're changing out of the way + $cdquery = "UPDATE ".db_table_name('groups')." SET group_order=-1 WHERE sid=$surveyid AND group_order=$oldpos"; + $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); + //Move all question_orders that are later than the newpos up one + $cdquery = "UPDATE ".db_table_name('groups')." SET group_order=group_order+1 WHERE sid=$surveyid AND group_order > ".$newpos." AND group_order <= $oldpos"; + $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); + //Renumber the question we're changing + $cdquery = "UPDATE ".db_table_name('groups')." SET group_order=".($newpos+1)." WHERE sid=$surveyid AND group_order=-1"; + $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); + } + } + + $ordergroups = "\n" + . "
      " + . "".$clang->gT("Change Group Order")."
      \n"; + + // Get groups dependencies regarding conditions + // => Get an array of groups containing questions with conditions outside the group + // $groupdepsarray[dependent-gid][target-gid]['conditions'][qid-having-conditions]=Array(cids...) + $groupdepsarray = GetGroupDepsForConditions($surveyid); + $nicegroupdeps=array(); + if (!is_null($groupdepsarray)) + { + $ordergroups .= "
      • ".$clang->gT("Warning").": ".$clang->gT("Current survey has questions with conditions outside their own group")."

        ".$clang->gT("Re-ordering groups is restricted to ensure that questions on which conditions are based aren't reordered after questions having the conditions set")."


        ".$clang->gT("The following groups are concerned").":
          \n"; + foreach ($groupdepsarray as $depgid => $depgrouprow) + { + foreach($depgrouprow as $targgid => $targrow) + { + $ordergroups .= "
        • ".sprintf($clang->gT("Group %s depends on group %s, see the marked conditions on:"), "".$targrow['depgpname']."", "".$targrow['targetgpname']." "); + $nicegroupdeps[$depgid]=$targgid; + foreach($targrow['conditions'] as $depqid => $depqrow) + { + $listcid=implode("-",$depqrow); + $ordergroups .= " [".$clang->gT("QID").": ".$depqid."]"; + } + $ordergroups .= "
        • \n"; + } + } + $ordergroups .= "
      "; + } + + $ordergroups .= "
        "; + //Get the groups from this survey + $s_lang = GetBaseLanguageFromSurveyID($surveyid); + $ogquery = "SELECT * FROM {$dbprefix}groups WHERE sid='{$surveyid}' AND language='{$s_lang}' order by group_order,group_name" ; + $ogresult = db_execute_assoc($ogquery) or safe_die($connect->ErrorMsg());//Checked + + $ogarray = $ogresult->GetArray(); + //FIX BROKEN ORDER + //Check if all group_order numbers are consecutive + $consecutive=true; + $lastnumber=-1; + foreach($ogarray as $group) + { + if(($group['group_order']-1) != $lastnumber) + { + $consecutive=false; + } + $lastnumber=$group['group_order']; + } + //Fix bad ordering + if($ogarray[0]['group_order'] > 0 || !$consecutive) + { + $i=0; + foreach($ogarray as $group) + { + $fixorderq = "UPDATE ".db_table_name('groups')." SET group_order=$i WHERE sid=$surveyid AND group_order = ".$group['group_order']; + $foresult = db_execute_assoc($fixorderq) or safe_die($connect->ErrorMsg()); + $ogarray[$i]['group_order']=$i; + $i++; + } + } + //END FIX BROKEN ORDER + $miniogarray=$ogarray; + $groupcount = count($ogarray); + for($i=0; $i < $groupcount ; $i++) + { + $downdisabled = ""; + $updisabled = ""; + if ( !is_null($groupdepsarray) && $i < $groupcount-1 && + array_key_exists($ogarray[$i+1]['gid'],$groupdepsarray) && + array_key_exists($ogarray[$i]['gid'],$groupdepsarray[$ogarray[$i+1]['gid']]) ) + { + $downdisabled = "disabled=\"true\" class=\"disabledbtn\""; + } + if ( !is_null($groupdepsarray) && $i !=0 && + array_key_exists($ogarray[$i]['gid'],$groupdepsarray) && + array_key_exists($ogarray[$i-1]['gid'],$groupdepsarray[$ogarray[$i]['gid']]) ) + { + $updisabled = "disabled=\"true\" class=\"disabledbtn\""; + } + + $ordergroups.="
      • \n" ; + + // DROP DOWN LIST // + //Move to location + //$ordergroups.="
      • \n" ; + $ordergroups.="\t\n"; + + // BUTTONS // + $ordergroups.= "\n"; + + if ($i < $groupcount-1) + { + // Fill the hidden field 'sortorder' so we know what field is moved down + $ordergroups.= "\n"; + } + $ordergroups.=$ogarray[$i]['group_name']."
      • \n" ; + + } + + $ordergroups.="
      \n" + . "\n" + . "\n" + . "" + . "" + . "
      " ; + $ordergroups .="
      " ; + } + else + { + include("access_denied.php"); + } +} + + +if ($action == "newsurvey") +{ + if($_SESSION['USER_RIGHT_CREATE_SURVEY']) + { + $dateformatdetails=getDateFormatData($_SESSION['dateformat']); + + $newsurvey = PrepareEditorScript(); + + // header + $newsurvey .= "\n
      " + . "".$clang->gT("Create or Import Survey")."
      \n"; + + // begin Tabs section + $newsurvey .= "
      \n"; + $newsurvey .= "
      gT("Error: You have to enter a title for this survey.",'js')."');\" >\n"; + + // General and Contact TAB + $newsurvey .= "

      ".$clang->gT("General")."

      \n"; + + // * Survey Language + $newsurvey .= "
      ".$clang->gT("Base Language:")."\n" + . " ".$clang->gT("This setting cannot be changed later!")."\n" + . "
      \n"; + + $newsurvey .= "" + . "
      ".$clang->gT("Title").":\n" + . " ".$clang->gT("(This field is mandatory.)")."
      \n" + . "
      ".$clang->gT("Description:")."\n" + . "" + . getEditor("survey-desc","description", "[".$clang->gT("Description:", "js")."]",'','','',$action) + . "
      \n" + . "
      ".$clang->gT("Welcome message:")."\n" + . "" + . getEditor("survey-welc","welcome", "[".$clang->gT("Welcome message:", "js")."]",'','','',$action) + . "
      \n" + . "
      ".$clang->gT("End message:")."\n" + . "" + . getEditor("survey-endtext","endtext", "[".$clang->gT("End message:", "js")."]",'','','',$action) + . "
      \n" + . "
      ".$clang->gT("Administrator:")."\n" + . "
      \n" + . "
      ".$clang->gT("Admin Email:")."\n" + . "
      \n" + . "
      ".$clang->gT("Bounce Email:")."\n" + . "
      \n"; + $newsurvey .= "
      ".$clang->gT("Fax To:")."\n" + . "
      \n"; + + // End General TAB + // Create Survey Button + $newsurvey .= "
      gT("Error: You have to enter a title for this survey.",'js')."')) { document.getElementById('addnewsurvey').submit(); }; return false;\" value='".$clang->gT("Create Survey")."' />
      \n"; + + $newsurvey .= "
      \n"; + + // Presentation and navigation TAB + $newsurvey .= "

      ".$clang->gT("Presentation & Navigation")."

      \n"; + + + $newsurvey .= "
      ".$clang->gT("Format:")."\n" + . "\n" + . "
      \n"; + $newsurvey .= "
      ".$clang->gT("Template:")."\n" + . "\n" + . "\n" + . "\n" + . "\n" + . "
      \n"; + //ALLOW PREV + $newsurvey .= "
      ".$clang->gT("Show [<< Prev] button")."\n" + . "\n" + . "
      \n"; + + //Result printing + $newsurvey .= "
      ".$clang->gT("Participants may print answers?")."\n" + . "\n" + . "
      \n"; + + //Public statistics + $newsurvey .= "
      ".$clang->gT("Public statistics?")."\n" + . "\n" + . "
      \n"; + + //Public statistics graphs + $newsurvey .= "
      ".$clang->gT("Show graphs in public statistics?")."\n" + . "\n" + . "
      \n"; + + + //List survey publicly + $newsurvey .= "
      ".$clang->gT("List survey publicly:")."\n" + . "\n" + . "
      \n"; + + + // End URL + $newsurvey .= "" + . "
      ".$clang->gT("End URL:")."\n" + . "".$clang->gT("URL description:")."\n" + . "".$clang->gT("Automatically load URL when survey complete?")."\n" + . "
      " + + //Default date format + . "
      ".$clang->gT("Date format:")."\n" + . "
      "; + + + // End Presention and navigation TAB + // Create Survey Button + $newsurvey .= "
      gT("Error: You have to enter a title for this survey.",'js')."')) { document.getElementById('addnewsurvey').submit(); }; return false;\" value='".$clang->gT("Create Survey")."' />
      \n"; + $newsurvey .= "
      \n"; + + // Publication and access control TAB + $newsurvey .= "

      ".$clang->gT("Publication & Access control")."

      \n"; + + + // Use tokens + $newsurvey .= "
      ".$clang->gT("Only users with tokens may enter the survey?")."\n" + . "\n
      \n"; + + // Public registration + $newsurvey .= "
      ".$clang->gT("Allow public registration?")."\n" + . "\n
      \n"; + + // Timed Start + $newsurvey .= "
      ".$clang->gT("Start date:")."\n" + . "" + . " ".sprintf($clang->gT("Date format: %s"), $dateformatdetails['dateformat'])."
      \n"; + + // Expiration + $newsurvey .= "
      ".$clang->gT("Expiry Date:")."\n" + . "" + . " ".sprintf($clang->gT("Date format: %s"), $dateformatdetails['dateformat'])."
      \n"; + + //COOKIES + $newsurvey .= "
      ".$clang->gT("Set cookie to prevent repeated participation?")."\n" + . "\n" + . "
      \n"; + + + // Use Captcha + $newsurvey .= "
      ".$clang->gT("Use CAPTCHA for").":\n" + . "\n
      \n"; + + // Email format + $newsurvey .= "
      ".$clang->gT("Use HTML format for token emails?")."\n" + . "\n
      \n"; + + // End Publication and access control TAB + // Create Survey Button + $newsurvey .= "
      gT("Error: You have to enter a title for this survey.",'js')."')) { document.getElementById('addnewsurvey').submit(); }; return false;\" value='".$clang->gT("Create Survey")."' />
      \n"; + $newsurvey .= "
      \n"; + + // Notification and Data management TAB + $newsurvey .= "

      ".$clang->gT("Notification & Data Management")."

      \n"; + + //NOTIFICATIONS + $newsurvey .= "
      ".$clang->gT("Admin Notification:")."\n" + . "\n" + . "
      \n"; + + + // ANONYMOUS + $newsurvey .= "
      ".$clang->gT("Anonymous answers?")."\n"; + // warning message if anonymous + datestamped anwsers + $newsurvey .= "\n" + . "\n"; + $newsurvey .= "\n
      \n"; + + // Datestamp + $newsurvey .= "
      ".$clang->gT("Date Stamp?")."\n" + . "\n
      \n"; + + // IP Address + $newsurvey .= "
      ".$clang->gT("Save IP Address?")."\n" + . "\n
      \n"; + + // Referring URL + $newsurvey .= "
      ".$clang->gT("Save Referring URL?")."\n" + . "\n
      \n"; + + // Token answers persistence + $newsurvey .= "
      ".$clang->gT("Enable token-based answers persistence?")."\n" + . "\n
      \n"; + + // enable assessment mote + $newsurvey .= "
      ".$clang->gT("Enable assessment mode?")."\n" + . "\n
      \n"; + + + // end of addnewsurvey form + $newsurvey .= "\n"; + + // End Notification and Data management TAB + // Create Survey Button + $newsurvey .= "
      gT("Error: You have to enter a title for this survey.",'js')."')) { document.getElementById('addnewsurvey').submit(); }; return false;\" value='".$clang->gT("Create Survey")."' />
      \n"; + $newsurvey .= "
      \n"; + $newsurvey .= "
      \n"; + + // Import TAB + $newsurvey .= "

      ".$clang->gT("Import Survey")."

      \n"; + + // Import Survey + $newsurvey .= "
      \n" + . "\n" +// . "\n" + . "\n" + . "\n" + . "\n" + . "\n" + . "\n" + . "\n" +// . "" // end tab +// . "" // end tab-pane + . "
      \n" +// . "".$clang->gT("Import Survey")."
      ".$clang->gT("Select CSV/SQL File:")."
      \n" + . "
      \n"; +// . "\n"; + + // End Import TAB + $newsurvey .= "
      \n"; + + // End TAB pane + $newsurvey .= "
      \n"; + + } + else + { + include("access_denied.php"); + } +} + + +function replacenewline ($texttoreplace) +{ + $texttoreplace = str_replace( "\n", '
      ', $texttoreplace); + // $texttoreplace = htmlentities( $texttoreplace, ENT_QUOTES, UTF-8); + $new_str = ''; + + for($i = 0; $i < strlen($texttoreplace); $i++) { + $new_str .= '\x' . dechex(ord(substr($texttoreplace, $i, 1))); + } + + return $new_str; +} +/* +function questionjavascript($type, $qattributes) + { + $newquestion = "\n"; + +} */ +?> diff --git a/include/limesurvey/admin/htmleditor-functions.php b/include/limesurvey/admin/htmleditor-functions.php index e3926587..8e40623f 100644 --- a/include/limesurvey/admin/htmleditor-functions.php +++ b/include/limesurvey/admin/htmleditor-functions.php @@ -1,286 +1,295 @@ -\n" - . "\n"; - - return $script; -} - -function PrepareEditorInlineScript() -{ - global $homeurl, $fckeditordir; - $script ="\n" - . "\n"; -/*** Commented because of inconsistencies - $script .= "" - . "\n"; -***/ - return $script; -} - -function PrepareEditorScript($fieldtype=null) -{ - global $defaulthtmleditormode; - - if (isset($_SESSION['htmleditormode']) && - $_SESSION['htmleditormode'] == 'none') - { - return "\n"; - } - - if (!isset($_SESSION['htmleditormode']) || - ($_SESSION['htmleditormode'] != 'inline' && - $_SESSION['htmleditormode'] != 'popup') ) - { - $htmleditormode = $defaulthtmleditormode; - } - else - { - $htmleditormode = $_SESSION['htmleditormode']; - } - - if ($htmleditormode == 'popup' || - $fieldtype == 'editanswer' || - $fieldtype == 'addanswer' || - $fieldtype == 'editlabel' || - $fieldtype == 'addlabel') - { - return PrepareEditorPopupScript(); - } - elseif ($htmleditormode == 'inline') - { - return PrepareEditorInlineScript(); - } - else - { - return ''; - } -} - -function getEditor($fieldtype,$fieldname,$fieldtext, $surveyID=null,$gID=null,$qID=null,$action=null) -{ - global $defaulthtmleditormode; - - if (isset($_SESSION['htmleditormode']) && - $_SESSION['htmleditormode'] == 'none') - { - return ''; - } - - - if (!isset($_SESSION['htmleditormode']) || - ($_SESSION['htmleditormode'] != 'inline' && - $_SESSION['htmleditormode'] != 'popup') ) - { - $htmleditormode = $defaulthtmleditormode; - } - else - { - $htmleditormode = $_SESSION['htmleditormode']; - } - - if ( ($fieldtype == 'email-inv' || - $fieldtype == 'email-reg' || - $fieldtype == 'email-conf' || - $fieldtype == 'email-rem' ) && - getEmailFormat($surveyID) != 'html') - { - return ''; - } - - if ($htmleditormode == 'popup' || - $fieldtype == 'editanswer' || - $fieldtype == 'addanswer' || - $fieldtype == 'editlabel' || - $fieldtype == 'addlabel') - { - return getPopupEditor($fieldtype,$fieldname,$fieldtext, $surveyID,$gID,$qID,$action); - } - elseif ($htmleditormode == 'inline') - { - return getInlineEditor($fieldtype,$fieldname,$fieldtext, $surveyID,$gID,$qID,$action); - } - else - { - return ''; - } -} - -function getPopupEditor($fieldtype,$fieldname,$fieldtext, $surveyID=null,$gID=null,$qID=null,$action=null) -{ - global $clang, $imagefiles, $homeurl; - - $htmlcode = ''; - $imgopts = ''; - $toolbarname = 'Basic'; - - if ($fieldtype == 'editanswer' || - $fieldtype == 'addanswer' || - $fieldtype == 'editlabel' || - $fieldtype == 'addlabel') - { - $imgopts = "width='14px' height='14px'"; - } - - $htmlcode .= "" - . "gTview("Start HTML Editor in a Popup Window")."\">\"".$clang-gT("Start HTML Editor in a Popup Window")."\" id='".$fieldname."_popupctrlena' name='".$fieldname."_popupctrlena' border='0' src='".$imagefiles."/edithtmlpopup.png' $imgopts />\"".$clang-gT("Give focus to the HTML Editor Popup Window")."\" id='".$fieldname."_popupctrldis' name='".$fieldname."_popupctrldis' border='0' src='".$imagefiles."/edithtmlpopup_disabled.png' style='display: none' $imgopts align='top'/>"; - - return $htmlcode; -} - -function getInlineEditor($fieldtype,$fieldname,$fieldtext, $surveyID=null,$gID=null,$qID=null,$action=null) -{ - global $clang, $imagefiles, $homeurl, $rooturl, $fckeditordir; - - $htmlcode = ''; - $imgopts = ''; - $toolbarname = 'Basic'; - $toolbaroption=""; - $htmlformatoption=""; - - if ($fieldtype == 'editanswer' || - $fieldtype == 'addanswer' || - $fieldtype == 'editlabel' || - $fieldtype == 'addlabel') - { - $toolbarname = 'LimeSurveyToolbarfull'; - $toolbaroption="oFCKeditor_$fieldname.Config[\"ToolbarLocation\"]=\"Out:xToolbar\";\n" - . "oFCKeditor_$fieldname.Config[\"ToolbarStartExpanded\"]=true;\n" - . "oFCKeditor_$fieldname.Config[\"ToolbarCanCollapse\"]=false;\n" - . "oFCKeditor_$fieldname.Height = \"50\"\n"; - } - - if ( $fieldtype == 'email-inv' || - $fieldtype == 'email-reg' || - $fieldtype == 'email-conf' || - $fieldtype == 'email-rem' ) - { - $htmlformatoption = "oFCKeditor_$fieldname.Config[\"FullPage\"]=true;\n"; - } - - $htmlcode .= "" - . "'; - - return $htmlcode; -} - -?> +\n" + . "\n"; + + return $script; +} + +function PrepareEditorInlineScript() +{ + global $homeurl, $fckeditordir; + $script ="\n" + . "\n"; +/*** Commented because of inconsistencies + $script .= "" + . "\n"; +***/ + return $script; +} + +function PrepareEditorScript($fieldtype=null) +{ + global $defaulthtmleditormode; + + if (isset($_SESSION['htmleditormode']) && + $_SESSION['htmleditormode'] == 'none') + { + return "\n"; + } + + if (!isset($_SESSION['htmleditormode']) || + ($_SESSION['htmleditormode'] != 'inline' && + $_SESSION['htmleditormode'] != 'popup') ) + { + $htmleditormode = $defaulthtmleditormode; + } + else + { + $htmleditormode = $_SESSION['htmleditormode']; + } + + if ($htmleditormode == 'popup' || + $fieldtype == 'editanswer' || + $fieldtype == 'addanswer' || + $fieldtype == 'editlabel' || + $fieldtype == 'addlabel') + { + return PrepareEditorPopupScript(); + } + elseif ($htmleditormode == 'inline') + { + return PrepareEditorInlineScript(); + } + else + { + return ''; + } +} + +function getEditor($fieldtype,$fieldname,$fieldtext, $surveyID=null,$gID=null,$qID=null,$action=null) +{ + global $defaulthtmleditormode; + + if (isset($_SESSION['htmleditormode']) && + $_SESSION['htmleditormode'] == 'none') + { + return ''; + } + + + if (!isset($_SESSION['htmleditormode']) || + ($_SESSION['htmleditormode'] != 'inline' && + $_SESSION['htmleditormode'] != 'popup') ) + { + $htmleditormode = $defaulthtmleditormode; + } + else + { + $htmleditormode = $_SESSION['htmleditormode']; + } + + if ( ($fieldtype == 'email-inv' || + $fieldtype == 'email-reg' || + $fieldtype == 'email-conf' || + $fieldtype == 'email-rem' ) && + getEmailFormat($surveyID) != 'html') + { + return ''; + } + + if ($htmleditormode == 'popup' || + $fieldtype == 'editanswer' || + $fieldtype == 'addanswer' || + $fieldtype == 'editlabel' || + $fieldtype == 'addlabel') + { + return getPopupEditor($fieldtype,$fieldname,$fieldtext, $surveyID,$gID,$qID,$action); + } + elseif ($htmleditormode == 'inline') + { + return getInlineEditor($fieldtype,$fieldname,$fieldtext, $surveyID,$gID,$qID,$action); + } + else + { + return ''; + } +} + +function getPopupEditor($fieldtype,$fieldname,$fieldtext, $surveyID=null,$gID=null,$qID=null,$action=null) +{ + global $clang, $imagefiles, $homeurl; + + $htmlcode = ''; + $imgopts = ''; + $toolbarname = 'Basic'; + + if ($fieldtype == 'editanswer' || + $fieldtype == 'addanswer' || + $fieldtype == 'editlabel' || + $fieldtype == 'addlabel') + { + $imgopts = "width='14' height='14'"; + } + + $htmlcode .= "" + . "gTview("Start HTML Editor in a Popup Window")."\">\"".$clang-gT("Start HTML Editor in a Popup Window")."\" id='".$fieldname."_popupctrlena' name='".$fieldname."_popupctrlena' border='0' src='".$imagefiles."/edithtmlpopup.png' $imgopts />\"".$clang-gT("Give focus to the HTML Editor Popup Window")."\" id='".$fieldname."_popupctrldis' name='".$fieldname."_popupctrldis' border='0' src='".$imagefiles."/edithtmlpopup_disabled.png' style='display: none' $imgopts align='top'/>"; + + return $htmlcode; +} + +function getInlineEditor($fieldtype,$fieldname,$fieldtext, $surveyID=null,$gID=null,$qID=null,$action=null) +{ + global $clang, $imagefiles, $homeurl, $rooturl, $fckeditordir, $fckeditexpandtoolbar; + + $htmlcode = ''; + $imgopts = ''; + $toolbarname = 'Basic'; + $toolbaroption=""; + $htmlformatoption=""; + $oFCKeditorVarName = "oFCKeditor_".str_replace("-","_",$fieldname); + + if ($fieldtype == 'editanswer' || + $fieldtype == 'addanswer' || + $fieldtype == 'editlabel' || + $fieldtype == 'addlabel') + { + $toolbarname = 'LimeSurveyToolbarfull'; + $toolbaroption="$oFCKeditorVarName.Config[\"ToolbarLocation\"]=\"Out:xToolbar\";\n" + . "$oFCKeditorVarName.Config[\"ToolbarStartExpanded\"]=true;\n" + . "$oFCKeditorVarName.Config[\"ToolbarCanCollapse\"]=false;\n" + . "$oFCKeditorVarName.Height = \"50\"\n"; + } + else + { + if (!isset($fckeditexpandtoolbar) || $fckeditexpandtoolbar == true) + { + $toolbaroption .= "$oFCKeditorVarName.Config[\"ToolbarStartExpanded\"]=true;\n"; + } + } + + if ( $fieldtype == 'email-inv' || + $fieldtype == 'email-reg' || + $fieldtype == 'email-conf' || + $fieldtype == 'email-rem' ) + { + $htmlformatoption = "$oFCKeditorVarName.Config[\"FullPage\"]=true;\n"; + } + + + $htmlcode .= "" + . "'; + + return $htmlcode; +} + +?> diff --git a/include/limesurvey/admin/htmleditor-popup.php b/include/limesurvey/admin/htmleditor-popup.php index 1bffabcb..0f8807df 100644 --- a/include/limesurvey/admin/htmleditor-popup.php +++ b/include/limesurvey/admin/htmleditor-popup.php @@ -1,197 +1,197 @@ - - - - LimeSurvey '.$clang->gT("HTML Editor").' - - -' - - . ' - -
      - LimeSurvey '.$clang->gT("HTML Editor").' -
      -
      - -
      -
      - -
      - - -
      - - '; -} -else { - $fieldname=$_GET['fieldname']; - $fieldtext=$_GET['fieldtext']; - $controlidena=$_GET['fieldname'].'_popupctrlena'; - $controliddis=$_GET['fieldname'].'_popupctrldis'; - - $sid=sanitize_int($_GET['sid']); - $gid=sanitize_int($_GET['gid']); - $qid=sanitize_int($_GET['qid']); - $fieldtype=preg_replace("/[^_.a-zA-Z0-9-]/", "",$_GET['fieldtype']); - $action=preg_replace("/[^_.a-zA-Z0-9-]/", "",$_GET['action']); - - $toolbarname='LimeSurveyToolbarfullPopup'; - $htmlformatoption=''; - - if ( $fieldtype == 'email-inv' || - $fieldtype == 'email-reg' || - $fieldtype == 'email-conf' || - $fieldtype == 'email-rem' ) - { - $htmlformatoption = "oFCKeditor.Config[\"FullPage\"]=true;"; - } - - $output = ' - - - - '.$clang->gT("Editing").' '.$fieldtext.' - - - - '; - - - $output .= " - -
      - - - -
      "; - - //$output .= ""; - $output .= " - - "; -} - -echo $output; -?> + + + + LimeSurvey '.$clang->gT("HTML Editor").' + + +' + + . ' + +
      + LimeSurvey '.$clang->gT("HTML Editor").' +
      +
      + +
      +
      + +
      + + +
      + + '; +} +else { + $fieldname=$_GET['fieldname']; + $fieldtext=$_GET['fieldtext']; + $controlidena=$_GET['fieldname'].'_popupctrlena'; + $controliddis=$_GET['fieldname'].'_popupctrldis'; + + $sid=sanitize_int($_GET['sid']); + $gid=sanitize_int($_GET['gid']); + $qid=sanitize_int($_GET['qid']); + $fieldtype=preg_replace("/[^_.a-zA-Z0-9-]/", "",$_GET['fieldtype']); + $action=preg_replace("/[^_.a-zA-Z0-9-]/", "",$_GET['action']); + + $toolbarname='LimeSurveyToolbarfullPopup'; + $htmlformatoption=''; + + if ( $fieldtype == 'email-inv' || + $fieldtype == 'email-reg' || + $fieldtype == 'email-conf' || + $fieldtype == 'email-rem' ) + { + $htmlformatoption = "oFCKeditor.Config[\"FullPage\"]=true;"; + } + + $output = ' + + + + '.$clang->gT("Editing").' '.$fieldtext.' + + + + '; + + + $output .= " + +
      + + + +
      "; + + //$output .= ""; + $output .= " + + "; +} + +echo $output; +?> diff --git a/include/limesurvey/admin/http_importsurvey.php b/include/limesurvey/admin/http_importsurvey.php index 9c1a2400..80fb4bab 100644 --- a/include/limesurvey/admin/http_importsurvey.php +++ b/include/limesurvey/admin/http_importsurvey.php @@ -1,47 +1,47 @@ -
      \n"; -$importsurvey .= "\n"; -$importsurvey .= "\t\n"; -$importsurvey .= "\t
      " -.$clang->gT("Import Survey")."
      \n"; - -$the_full_file_path = $tempdir . "/" . $_FILES['the_file']['name']; - -if (!@move_uploaded_file($_FILES['the_file']['tmp_name'], $the_full_file_path)) -{ - $importsurvey .= "".$clang->gT("Error")."
      \n"; - $importsurvey .= sprintf ($clang->gT("An error occurred uploading your file. This may be caused by incorrect permissions in your %s folder."),$tempdir)."

      \n"; - $importsurvey .= "
      \n"; - return; -} - -// IF WE GOT THIS FAR, THEN THE FILE HAS BEEN UPLOADED SUCCESFULLY - -$importsurvey .= "".$clang->gT("Success")."!
      \n"; -$importsurvey .= $clang->gT("File upload succeeded.")."

      \n"; -$importsurvey .= $clang->gT("Reading file..")."
      \n"; - -$importingfrom = "http"; // "http" for the web version and "cmdline" for the command line version -include("importsurvey.php"); - -?> +
      \n"; +$importsurvey .= "\n"; +$importsurvey .= "\t\n"; +$importsurvey .= "\t
      " +.$clang->gT("Import Survey")."
      \n"; + +$the_full_file_path = $tempdir . "/" . $_FILES['the_file']['name']; + +if (!@move_uploaded_file($_FILES['the_file']['tmp_name'], $the_full_file_path)) +{ + $importsurvey .= "".$clang->gT("Error")."
      \n"; + $importsurvey .= sprintf ($clang->gT("An error occurred uploading your file. This may be caused by incorrect permissions in your %s folder."),$tempdir)."

      \n"; + $importsurvey .= "
      \n"; + return; +} + +// IF WE GOT THIS FAR, THEN THE FILE HAS BEEN UPLOADED SUCCESFULLY + +$importsurvey .= "".$clang->gT("Success")."!
      \n"; +$importsurvey .= $clang->gT("File upload succeeded.")."

      \n"; +$importsurvey .= $clang->gT("Reading file..")."
      \n"; + +$importingfrom = "http"; // "http" for the web version and "cmdline" for the command line version +include("importsurvey.php"); + +?> diff --git a/include/limesurvey/admin/import_resources_zip.php b/include/limesurvey/admin/import_resources_zip.php index fc3cdd01..fbbf502c 100644 --- a/include/limesurvey/admin/import_resources_zip.php +++ b/include/limesurvey/admin/import_resources_zip.php @@ -10,7 +10,7 @@ * other free or open source software licenses. * See COPYRIGHT.php for copyright notices and details. * -* $Id: import_resources_zip.php 3685 2007-11-22 04:53:18Z jcleeland $ +* $Id: import_resources_zip.php 6864 2009-05-17 22:33:37Z c_schmitz $ */ @@ -26,7 +26,16 @@ if (!isset($lid)) returnglobal('lid'); } + + if ($action == "importsurvresources" && $surveyid) { + if ($demoModeOnly === true) + { + $importsurvresourcesoutput = "".$clang->gT("Error")."
      \n"; + $importsurvresourcesoutput .= $clang->gT("Demo Mode Only: Uploading file is disabled in this system.")."

      \n"; + $importsurvresourcesoutput .= " 
       
      \n"; + return; + } require("classes/phpzip/phpzip.inc.php"); $zipfile=$_FILES['the_file']['tmp_name']; $z = new PHPZip(); @@ -197,6 +206,15 @@ if ($action == "importsurvresources" && $surveyid) { if ($action == "importlabelresources" && $lid) { + if ($demoModeOnly === true) + { + $importlabelresourcesoutput .= "".$clang->gT("Error")."
      \n"; + $importlabelresourcesoutput .= sprintf ($clang->gT("Demo Mode Only: Uploading file is disabled in this system."),$basedestdir)."

      \n"; + $importlabelresourcesoutput .= "\n"; + $importlabelresourcesoutput .= "

       \n"; + return; + } + require("classes/phpzip/phpzip.inc.php"); //$the_full_file_path = $tempdir . "/" . $_FILES['the_file']['name']; $zipfile=$_FILES['the_file']['tmp_name']; @@ -363,6 +381,187 @@ if ($action == "importlabelresources" && $lid) +if ($action == "templateupload") +{ + if ($demoModeOnly === true) + { + $importtemplateresourcesoutput .= "".$clang->gT("Error")."
      \n"; + $importtemplateoutput .= sprintf ($clang->gT("Demo mode: Uploading templates is disabled."),$basedestdir)."

      \n"; + $importtemplateoutput .= "

       \n"; + return; + } + + require("classes/phpzip/phpzip.inc.php"); + //$the_full_file_path = $tempdir . "/" . $_FILES['the_file']['name']; + $zipfile=$_FILES['the_file']['tmp_name']; + $z = new PHPZip(); + // Create temporary directory + // If dangerous content is unzipped + // then no one will know the path + $extractdir=tempdir($tempdir); + $basedestdir = $templaterootdir; + $newdir=str_replace('.','',strip_ext(sanitize_paranoid_string($_FILES['the_file']['name']))); + $destdir=$basedestdir.'/'.$newdir.'/'; + + $importtemplateoutput = "
      \n"; + $importtemplateoutput .= "\n"; + $importtemplateoutput .= "\t\n"; + $importtemplateoutput .= "\t
      ".$clang->gT("Import Label Set")."
      \n"; + + if (!is_writeable($basedestdir)) + { + $importtemplateoutput .= "".$clang->gT("Error")."
      \n"; + $importtemplateoutput .= sprintf ($clang->gT("Incorrect permissions in your %s folder."),$basedestdir)."

      \n"; + $importtemplateoutput .= "

       \n"; + return; + } + + if (!is_dir($destdir)) + { + mkdir($destdir); + } + else + { + $importtemplateoutput .= "".$clang->gT("Error")."
      \n"; + $importtemplateoutput .= sprintf ($clang->gT("Template '%s' does already exist."),$newdir)."

      \n"; + $importtemplateoutput .= "
       \n"; + return; + } + + $aImportedFilesInfo=array(); + $aErrorFilesInfo=array(); + + + if (is_file($zipfile)) + { + $importtemplateoutput .= "".$clang->gT("Success")."
      \n"; + $importtemplateoutput .= $clang->gT("File upload succeeded.")."

      \n"; + $importtemplateoutput .= $clang->gT("Reading file..")."
      \n"; + + if ($z->extract($extractdir,$zipfile) != 'OK') + { + $importtemplateoutput .= "".$clang->gT("Error")."
      \n"; + $importtemplateoutput .= $clang->gT("This file is not a valid ZIP file archive. Import failed.")."

      \n"; + $importtemplateoutput .= "
       \n"; + return; + } + + $ErrorListHeader = ""; + $ImportListHeader = ""; + + // now read tempdir and copy authorized files only + $dh = opendir($extractdir); + while($direntry = readdir($dh)) + { + if (($direntry!=".")&&($direntry!="..")) + { + if (is_file($extractdir."/".$direntry)) + { // is a file + $extfile = substr(strrchr($direntry, '.'),1); + if (!(stripos(','.$allowedresourcesuploads.',',','.$extfile.',') === false)) + { //Extension allowed + if (!copy($extractdir."/".$direntry, $destdir.$direntry)) + { + $aErrorFilesInfo[]=Array( + "filename" => $direntry, + "status" => $clang->gT("Copy failed") + ); + unlink($extractdir."/".$direntry); + + } + else + { + $aImportedFilesInfo[]=Array( + "filename" => $direntry, + "status" => $clang->gT("OK") + ); + unlink($extractdir."/".$direntry); + } + } + + else + { // Extension forbidden + $aErrorFilesInfo[]=Array( + "filename" => $direntry, + "status" => $clang->gT("Error")." (".$clang->gT("Forbidden Extension").")" + ); + unlink($extractdir."/".$direntry); + } + } // end if is_file + } // end if ! . or .. + } // end while read dir + + + //Delete the temporary file + unlink($zipfile); + closedir($dh); + //Delete temporary folder + rmdir($extractdir); + + // display summary + $okfiles = 0; + $errfiles= 0; + if (count($aErrorFilesInfo)==0 && count($aImportedFilesInfo)>0) + { + $status=$clang->gT("Success"); + $color='green'; + $okfiles = count($aImportedFilesInfo); + $ImportListHeader .= "
      ".$clang->gT("Imported Files List").":
      \n"; + } + elseif (count($aErrorFilesInfo)==0 && count($aImportedFilesInfo)==0) + { + $importtemplateoutput .= "".$clang->gT("Error")."
      \n"; + $importtemplateoutput .= $clang->gT("This ZIP archive contains no valid template files. Import failed.")."

      \n"; + $importtemplateoutput .= $clang->gT("Remember that we do not support subdirectories in ZIP archives.")."

      \n"; + $importtemplateoutput .= "
       \n"; + return; + + } + elseif (count($aErrorFilesInfo)>0 && count($aImportedFilesInfo)>0) + { + $status=$clang->gT("Partial"); + $color='orange'; + $okfiles = count($aImportedFilesInfo); + $errfiles = count($aErrorFilesInfo); + $ErrorListHeader .= "
      ".$clang->gT("Error Files List").":
      \n"; + $ImportListHeader .= "
      ".$clang->gT("Imported Files List").":
      \n"; + } + else + { + $status=$clang->gT("Error"); + $color='red'; + $errfiles = count($aErrorFilesInfo); + $ErrorListHeader .= "
      ".$clang->gT("Error Files List").":
      \n"; + } + + $importtemplateoutput .= "".$clang->gT("Imported template files for")." $lid
      \n"; + $importtemplateoutput .= "
      \n".$status."
      \n"; + $importtemplateoutput .= "".$clang->gT("Resources Import Summary")."
      \n"; + $importtemplateoutput .= "".$clang->gT("Total Imported files").": $okfiles
      \n"; + $importtemplateoutput .= "".$clang->gT("Total Errors").": $errfiles
      \n"; + $importtemplateoutput .= $ImportListHeader; + foreach ($aImportedFilesInfo as $entry) + { + $importtemplateoutput .= "\t
    1. ".$clang->gT("File").": ".$entry["filename"]."
    2. \n"; + } + $importtemplateoutput .= "\t

      \n"; + $importtemplateoutput .= $ErrorListHeader; + foreach ($aErrorFilesInfo as $entry) + { + $importtemplateoutput .= "\t
    3. ".$clang->gT("File").": ".$entry['filename']." (".$entry['status'].")
    4. \n"; + } + } + else + { + $importtemplateoutput .= "".$clang->gT("Error")."
      \n"; + $importtemplateoutput .= sprintf ($clang->gT("An error occurred uploading your file. This may be caused by incorrect permissions in your %s folder."),$basedestdir)."

      \n"; + $importtemplateoutput .= "
       \n"; + return; + } + $importtemplateoutput .= "\n"; +} + + //--------------------- // Comes from http://fr2.php.net/tempnam function tempdir($dir, $prefix='', $mode=0700) @@ -377,4 +576,20 @@ if ($action == "importlabelresources" && $lid) return $path; } + /** + * Strips file extension + * + * @param string $name + * @return string + */ + function strip_ext($name) + { + $ext = strrchr($name, '.'); + if($ext !== false) + { + $name = substr($name, 0, -strlen($ext)); + } + return $name; + } + ?> diff --git a/include/limesurvey/admin/importgroup.php b/include/limesurvey/admin/importgroup.php index 98bf34f8..d540e0fb 100644 --- a/include/limesurvey/admin/importgroup.php +++ b/include/limesurvey/admin/importgroup.php @@ -1,680 +1,709 @@ -
      \n"; -$importgroup .= "\n"; -$importgroup .= "\t\n"; -$importgroup .= "\t
      ".$clang->gT("Import Group")."
      \n"; - -$the_full_file_path = $tempdir . "/" . $_FILES['the_file']['name']; - -if (!@move_uploaded_file($_FILES['the_file']['tmp_name'], $the_full_file_path)) -{ - $importgroup .= "".$clang->gT("Error")."
      \n"; - $importgroup .= sprintf ($clang->gT("An error occurred uploading your file. This may be caused by incorrect permissions in your %s folder."),$tempdir)."

      \n"; - $importgroup .= "\n"; - $importgroup .= "
      \n"; - return; -} - -// validate that we have a SID -if (!returnglobal('sid')) -{ - $importquestion .= $clang->gT("No SID (Survey) has been provided. Cannot import group.")."

      \n" - ."\n" - ."
      \n"; - unlink($the_full_file_path); - return; -} -else -{ - $newsid = returnglobal('sid'); -} - - -// IF WE GOT THIS FAR, THEN THE FILE HAS BEEN UPLOADED SUCCESFULLY - -$importgroup .= "".$clang->gT("Success")."
      \n"; -$importgroup .= $clang->gT("File upload succeeded.")."

      \n"; -$importgroup .= $clang->gT("Reading file...")."
      \n"; -$handle = fopen($the_full_file_path, "r"); -while (!feof($handle)) -{ - $buffer = fgets($handle); - $bigarray[] = $buffer; -} -fclose($handle); - -if (substr($bigarray[0], 0, 23) != "# LimeSurvey Group Dump" && substr($bigarray[0], 0, 24) != "# PHPSurveyor Group Dump") -{ - $importgroup .= "".$clang->gT("Error")."
      \n"; - $importgroup .= $clang->gT("This file is not a LimeSurvey group file. Import failed.")."

      \n"; - $importgroup .= "\n"; - $importgroup .= "\n"; - unlink($the_full_file_path); - return; -} - -for ($i=0; $i<9; $i++) -{ - unset($bigarray[$i]); -} -$bigarray = array_values($bigarray); - -//GROUPS -if (array_search("# QUESTIONS TABLE\n", $bigarray)) -{ - $stoppoint = array_search("# QUESTIONS TABLE\n", $bigarray); -} -elseif (array_search("# QUESTIONS TABLE\r\n", $bigarray)) -{ - $stoppoint = array_search("# QUESTIONS TABLE\r\n", $bigarray); -} -else -{ - $stoppoint = count($bigarray)-1; -} -for ($i=0; $i<=$stoppoint+1; $i++) -{ - if ($i<$stoppoint-2) {$grouparray[] = $bigarray[$i];} - unset($bigarray[$i]); -} -$bigarray = array_values($bigarray); - -//QUESTIONS -if (array_search("# ANSWERS TABLE\n", $bigarray)) -{ - $stoppoint = array_search("# ANSWERS TABLE\n", $bigarray); -} -elseif (array_search("# ANSWERS TABLE\r\n", $bigarray)) -{ - $stoppoint = array_search("# ANSWERS TABLE\r\n", $bigarray); -} -else -{ - $stoppoint = count($bigarray)-1; -} -for ($i=0; $i<=$stoppoint+1; $i++) -{ - if ($i<$stoppoint-2) {$questionarray[] = $bigarray[$i];} - unset($bigarray[$i]); -} -$bigarray = array_values($bigarray); - -//ANSWERS -if (array_search("# CONDITIONS TABLE\n", $bigarray)) -{ - $stoppoint = array_search("# CONDITIONS TABLE\n", $bigarray); -} -elseif (array_search("# CONDITIONS TABLE\r\n", $bigarray)) -{ - $stoppoint = array_search("# CONDITIONS TABLE\r\n", $bigarray); -} -else -{ - $stoppoint = count($bigarray)-1; -} -for ($i=0; $i<=$stoppoint+1; $i++) -{ - if ($i<$stoppoint-2) {$answerarray[] = $bigarray[$i];} - unset($bigarray[$i]); -} -$bigarray = array_values($bigarray); - -//CONDITIONS -if (array_search("# LABELSETS TABLE\n", $bigarray)) -{ - $stoppoint = array_search("# LABELSETS TABLE\n", $bigarray); -} -elseif (array_search("# LABELSETS TABLE\r\n", $bigarray)) -{ - $stoppoint = array_search("# LABELSETS TABLE\r\n", $bigarray); -} -else -{ - $stoppoint = count($bigarray); -} -for ($i=0; $i<=$stoppoint+1; $i++) -{ - if ($i<$stoppoint-2) {$conditionsarray[] = $bigarray[$i];} - unset($bigarray[$i]); -} -$bigarray = array_values($bigarray); - -//LABELSETS -if (array_search("# LABELS TABLE\n", $bigarray)) -{ - $stoppoint = array_search("# LABELS TABLE\n", $bigarray); -} -elseif (array_search("# LABELS TABLE\r\n", $bigarray)) -{ - $stoppoint = array_search("# LABELS TABLE\r\n", $bigarray); -} -else -{ - $stoppoint = count($bigarray)-1; -} -for ($i=0; $i<=$stoppoint+1; $i++) -{ - if ($i<$stoppoint-2) {$labelsetsarray[] = $bigarray[$i];} - unset($bigarray[$i]); -} -$bigarray = array_values($bigarray); - -//LABELS -if (array_search("# QUESTION_ATTRIBUTES TABLE\n", $bigarray)) -{ - $stoppoint = array_search("# QUESTION_ATTRIBUTES TABLE\n", $bigarray); -} -elseif (array_search("# QUESTION_ATTRIBUTES TABLE\r\n", $bigarray)) -{ - $stoppoint = array_search("# QUESTION_ATTRIBUTES TABLE\r\n", $bigarray); -} -else -{ - $stoppoint = count($bigarray)-1; -} -for ($i=0; $i<=$stoppoint+1; $i++) -{ - if ($i<$stoppoint-2) {$labelsarray[] = $bigarray[$i];} - unset($bigarray[$i]); -} -$bigarray = array_values($bigarray); - -//LAST LOT (now question_attributes) -if (!isset($noconditions) || $noconditions != "Y") -{ - // stoppoint is the last line number - // this is an empty line after the QA CSV lines - $stoppoint = count($bigarray)-1; - for ($i=0; $i<=$stoppoint+1; $i++) - { - if ($i<=$stoppoint-1) {$question_attributesarray[] = $bigarray[$i];} - unset($bigarray[$i]); - } -} -$bigarray = array_values($bigarray); - -$countgroups=0; -if (isset($questionarray)) - { - $questionfieldnames=convertCSVRowToArray($questionarray[0],',','"'); - unset($questionarray[0]); - $countquestions = 0; - } - -if (isset($answerarray)) - { - $answerfieldnames=convertCSVRowToArray($answerarray[0],',','"'); - unset($answerarray[0]); - $countanswers = 0; - } - -$countconditions = 0; -$countlabelsets=0; -$countlabels=0; -$countquestion_attributes = 0; -$countanswers = 0; - - -// first check that imported group, questions and labels support the -// current survey's baselang -$langcode = GetBaseLanguageFromSurveyID($newsid); -if (isset($grouparray)) -{ - $groupfieldnames = convertCSVRowToArray($grouparray[0],',','"'); - $langfieldnum = array_search("language", $groupfieldnames); - $gidfieldnum = array_search("gid", $groupfieldnames); - $groupssupportbaselang = bDoesImportarraySupportsLanguage($grouparray,Array($gidfieldnum),$langfieldnum,$langcode,true); - if (!$groupssupportbaselang) - { - $importgroup .= "".$clang->gT("Error")."
      \n"; - $importgroup .= $clang->gT("You can't import a group which doesn't support the current survey's base language.")."

      \n"; - $importgroup .= "\n"; - $importgroup .= "\n"; - unlink($the_full_file_path); - return; - } -} - -if (isset($questionarray)) -{ - $langfieldnum = array_search("language", $questionfieldnames); - $qidfieldnum = array_search("qid", $questionfieldnames); - $questionssupportbaselang = bDoesImportarraySupportsLanguage($questionarray,Array($qidfieldnum), $langfieldnum,$langcode,false); - if (!$questionssupportbaselang) - { - $importgroup .= "".$clang->gT("Error")."
      \n"; - $importgroup .= $clang->gT("You can't import a question which doesn't support the current survey's base language.")."

      \n"; - $importgroup .= "\n"; - $importgroup .= "\n"; - unlink($the_full_file_path); - return; - } -} - - -if (isset($labelsetsarray)) -{ - $labelsetfieldname = convertCSVRowToArray($labelsetsarray[0],',','"'); - $langfieldnum = array_search("languages", $labelsetfieldname); - $lidfilednum = array_search("lid", $labelsetfieldname); - $labelsetssupportbaselang = bDoesImportarraySupportsLanguage($labelsetsarray,Array($lidfilednum),$langfieldnum,$langcode,true); - if (!$labelsetssupportbaselang) - { - $importquestion .= "".$clang->gT("Error")."
      \n" - .$clang->gT("You can't import label sets which don't support the current survey's base language")."

      \n" - ."\n"; - unlink($the_full_file_path); - return; - } -} - -$newlids = array(); // this array will have the "new lid" for the label sets, the key will be the "old lid" - -//DO ANY LABELSETS FIRST, SO WE CAN KNOW WHAT THEIR NEW LID IS FOR THE QUESTIONS -if (isset($labelsetsarray) && $labelsetsarray) { - $csarray=buildLabelSetCheckSumArray(); // build checksums over all existing labelsets - $count=0; - foreach ($labelsetsarray as $lsa) { - $fieldorders =convertCSVRowToArray($labelsetsarray[0],',','"'); - $fieldcontents=convertCSVRowToArray($lsa,',','"'); - if ($count==0) {$count++; continue;} - - $countlabelsets++; - - $labelsetrowdata=array_combine($fieldorders,$fieldcontents); - - // Save old labelid - $oldlid=$labelsetrowdata['lid']; - // set the new language - unset($labelsetrowdata['lid']); - $newvalues=array_values($labelsetrowdata); - $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly - $lsainsert = "INSERT INTO {$dbprefix}labelsets (".implode(',',array_keys($labelsetrowdata)).") VALUES (".implode(',',$newvalues).")"; //handle db prefix - $lsiresult=$connect->Execute($lsainsert); - - // Get the new insert id for the labels inside this labelset - $newlid=$connect->Insert_ID("{$dbprefix}labelsets",'lid'); - - if ($labelsarray) { - $count=0; - foreach ($labelsarray as $la) { - $lfieldorders =convertCSVRowToArray($labelsarray[0],',','"'); - $lfieldcontents=convertCSVRowToArray($la,',','"'); - if ($count==0) {$count++; continue;} - - // Combine into one array with keys and values since its easier to handle - $labelrowdata=array_combine($lfieldorders,$lfieldcontents); - $labellid=$labelrowdata['lid']; - if ($labellid == $oldlid) { - $labelrowdata['lid']=$newlid; - - // translate internal links - $labelrowdata['title']=translink('label', $oldlid, $newlid, $labelrowdata['title']); - - $newvalues=array_values($labelrowdata); - $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly - $lainsert = "INSERT INTO {$dbprefix}labels (".implode(',',array_keys($labelrowdata)).") VALUES (".implode(',',$newvalues).")"; //handle db prefix - $liresult=$connect->Execute($lainsert); - $countlabels++; - } - } - } - - //CHECK FOR DUPLICATE LABELSETS - $thisset=""; - $query2 = "SELECT code, title, sortorder, language - FROM {$dbprefix}labels - WHERE lid=".$newlid." - ORDER BY language, sortorder, code"; - $result2 = db_execute_num($query2) or safe_die("Died querying labelset $lid
      $query2
      ".$connect->ErrorMsg()); - while($row2=$result2->FetchRow()) - { - $thisset .= implode('.', $row2); - } // while - $newcs=dechex(crc32($thisset)*1); - unset($lsmatch); - if (isset($csarray)) - { - foreach($csarray as $key=>$val) - { - if ($val == $newcs) - { - $lsmatch=$key; - } - } - } - if (isset($lsmatch)) - { - //There is a matching labelset. So, we will delete this one and refer - //to the matched one. - $query = "DELETE FROM {$dbprefix}labels WHERE lid=$newlid"; - $result=$connect->Execute($query) or safe_die("Couldn't delete labels
      $query
      ".$connect->ErrorMsg()); - $query = "DELETE FROM {$dbprefix}labelsets WHERE lid=$newlid"; - $result=$connect->Execute($query) or safe_die("Couldn't delete labelset
      $query
      ".$connect->ErrorMsg()); - $newlid=$lsmatch; - } - else - { - //There isn't a matching labelset, add this checksum to the $csarray array - $csarray[$newlid]=$newcs; - } - //END CHECK FOR DUPLICATES - $labelreplacements[]=array($oldlid, $newlid); - $newlids[$oldlid] = $newlid; - } -} - -//these arrays will aloud to insert correctly groups an questions multi languague survey imports correctly, and will eliminate the need to "searh" the imported data -//$newgids = array(); // this array will have the "new gid" for the groups, the kwy will be the "old gid" <-- not needed when importing groups -$newqids = array(); // this array will have the "new qid" for the questions, the kwy will be the "old qid" - -// DO GROUPS, QUESTIONS FOR GROUPS, THEN ANSWERS FOR QUESTIONS IN A __NOT__ NESTED FORMAT! -if (isset($grouparray) && $grouparray) -{ - $surveylanguages=GetAdditionalLanguagesFromSurveyID($surveyid); - $surveylanguages[]=GetBaseLanguageFromSurveyID($surveyid); - - // do GROUPS - $gafieldorders=convertCSVRowToArray($grouparray[0],',','"'); - unset($grouparray[0]); - $newgid = 0; - $group_order = 0; // just to initialize this variable - foreach ($grouparray as $ga) - { - //GET ORDER OF FIELDS - $gacfieldcontents=convertCSVRowToArray($ga,',','"'); - $grouprowdata=array_combine($gafieldorders,$gacfieldcontents); - - // Skip not supported languages - if (!in_array($grouprowdata['language'],$surveylanguages)) - { - $skippedlanguages[]=$grouprowdata['language']; // this is for the message in the end. - continue; - } - - // replace the sid - $oldsid=$grouprowdata['sid']; - $grouprowdata['sid']=$newsid; - - // replace the gid or remove it if needed (it also will calculate the group order if is a new group) - $oldgid=$grouprowdata['gid']; - if ($newgid == 0) - { - unset($grouprowdata['gid']); - - // find the maximum group order and use this grouporder+1 to assign it to the new group - $qmaxgo = "select max(group_order) as maxgo from ".db_table_name('groups')." where sid=$newsid"; - $gres = db_execute_assoc($qmaxgo) or safe_die ($clang->gT("Error")." Failed to find out maximum group order value
      \n$qmaxqo
      \n".$connect->ErrorMsg()); - $grow=$gres->FetchRow(); - $group_order = $grow['maxgo']+1; - } - else - $grouprowdata['gid'] = $newgid; - - $grouprowdata["group_order"]= $group_order; - - // Everything set - now insert it - $grouprowdata=array_map('convertCsvreturn2return', $grouprowdata); - - - // translate internal links - $grouprowdata['group_name']=translink('survey', $oldsid, $newsid, $grouprowdata['group_name']); - $grouprowdata['description']=translink('survey', $oldsid, $newsid, $grouprowdata['description']); - - $newvalues=array_values($grouprowdata); - $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly - $ginsert = "insert INTO {$dbprefix}groups (".implode(',',array_keys($grouprowdata)).") VALUES (".implode(',',$newvalues).")"; - $gres = $connect->Execute($ginsert) or safe_die($clang->gT("Error").": Failed to insert group
      \n$ginsert
      \n".$connect->ErrorMsg()); - - //GET NEW GID .... if is not done before and we count a group if a new gid is required - if ($newgid == 0) - { - $newgid = $connect->Insert_ID("{$dbprefix}groups",'gid'); - $countgroups++; - } - } - // GROUPS is DONE - - // do QUESTIONS - if (isset($questionarray) && $questionarray) - { - foreach ($questionarray as $qa) - { - $qacfieldcontents=convertCSVRowToArray($qa,',','"'); - $questionrowdata=array_combine($questionfieldnames,$qacfieldcontents); - - // Skip not supported languages - if (!in_array($questionrowdata['language'],$surveylanguages)) - continue; - - // replace the sid - $questionrowdata["sid"] = $newsid; - - // replace the gid (if the gid is not in the oldgid it means there is a problem with the exported record, so skip it) - if ($questionrowdata['gid'] == $oldgid) - $questionrowdata['gid'] = $newgid; - else - continue; // a problem with this question record -> don't consider - - // replace the qid or remove it if needed - $oldqid = $questionrowdata['qid']; - if (isset($newqids[$oldqid])) - $questionrowdata['qid'] = $newqids[$oldqid]; - else - unset($questionrowdata['qid']); - - // replace the lid for the new one (if there is no new lid in the $newlids array it mean that was not imported -> error, skip this record) - if (in_array($questionrowdata["type"], array("F","H","W","Z"))) // only fot the questions that uses a label set. - if (isset($newlids[$questionrowdata["lid"]])) - $questionrowdata["lid"] = $newlids[$questionrowdata["lid"]]; - else - continue; // a problem with this question record -> don't consider - -// $other = $questionrowdata["other"]; //Get 'other' field value -// $oldlid = $questionrowdata['lid']; - - // Everything set - now insert it - $questionrowdata=array_map('convertCsvreturn2return', $questionrowdata); - - // translate internal links - $questionrowdata['title']=translink('survey', $oldsid, $newsid, $questionrowdata['title']); - $questionrowdata['question']=translink('survey', $oldsid, $newsid, $questionrowdata['question']); - $questionrowdata['help']=translink('survey', $oldsid, $newsid, $questionrowdata['help']); - - $newvalues=array_values($questionrowdata); - $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly - $qinsert = "insert INTO {$dbprefix}questions (".implode(',',array_keys($questionrowdata)).") VALUES (".implode(',',$newvalues).")"; - $qres = $connect->Execute($qinsert) or safe_die ($clang->gT("Error")."Failed to insert question
      \n$qinsert
      \n".$connect->ErrorMsg()); - - //GET NEW QID .... if is not done before and we count a question if a new qid is required - if (!isset($newqids[$oldqid])) - { - $newqids[$oldqid] = $connect->Insert_ID("{$dbprefix}questions",'qid'); - $countquestions++; - } - } - } - // QESTIONS is DONE - - // do ANSWERS - if (isset($answerarray) && $answerarray) - { - foreach ($answerarray as $aa) - { - $aacfieldcontents=convertCSVRowToArray($aa,',','"'); - $answerrowdata=array_combine($answerfieldnames,$aacfieldcontents); - - // Skip not supported languages - if (!in_array($answerrowdata['language'],$surveylanguages)) - continue; - - // replace the qid for the new one (if there is no new qid in the $newqids array it mean that this answer is orphan -> error, skip this record) - if (isset($newqids[$answerrowdata["qid"]])) - $answerrowdata["qid"] = $newqids[$answerrowdata["qid"]]; - else - continue; // a problem with this answer record -> don't consider - - // Everything set - now insert it - $answerrowdata = array_map('convertCsvreturn2return', $answerrowdata); - - // translate internal links - $answerrowdata['answer']=translink('survey', $oldsid, $newsid, $answerrowdata['answer']); - - $newvalues=array_values($answerrowdata); - $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly - $ainsert = "insert INTO {$dbprefix}answers (".implode(',',array_keys($answerrowdata)).") VALUES (".implode(',',$newvalues).")"; - $ares = $connect->Execute($ainsert) or safe_die ($clang->gT("Error")."Failed to insert answer
      \n$ainsert
      \n".$connect->ErrorMsg()); - $countanswers++; - } - } - // ANSWERS is DONE - - // Fix Group sortorder - fixsortorderGroups(); - //... and for the questions inside the groups - // get all group ids and fix questions inside each group - $gquery = "SELECT gid FROM {$dbprefix}groups where sid=$newsid group by gid ORDER BY gid"; //Get last question added (finds new qid) - $gres = db_execute_assoc($gquery); - while ($grow = $gres->FetchRow()) - { - fixsortorderQuestions(0,$grow['gid']); - } - } - - // do ATTRIBUTES - if (isset($question_attributesarray) && $question_attributesarray) - { - $fieldorders =convertCSVRowToArray($question_attributesarray[0],',','"'); - unset($question_attributesarray[0]); - foreach ($question_attributesarray as $qar) { - $fieldcontents=convertCSVRowToArray($qar,',','"'); - $qarowdata=array_combine($fieldorders,$fieldcontents); - - // replace the qid for the new one (if there is no new qid in the $newqids array it mean that this attribute is orphan -> error, skip this record) - if (isset($newqids[$qarowdata["qid"]])) - $qarowdata["qid"] = $newqids[$qarowdata["qid"]]; - else - continue; // a problem with this answer record -> don't consider - - unset($qarowdata["qaid"]); - - // Everything set - now insert it - $newvalues=array_values($qarowdata); - $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly - $qainsert = "insert INTO {$dbprefix}question_attributes (".implode(',',array_keys($qarowdata)).") VALUES (".implode(',',$newvalues).")"; - $result=$connect->Execute($qainsert) or safe_die ("Couldn't insert question_attribute
      $qainsert
      ".$connect->ErrorMsg()); - $countquestion_attributes++; - } - } - // ATTRIBUTES is DONE - - // do CONDITIONS - if (isset($conditionsarray) && $conditionsarray) - { - $fieldorders=convertCSVRowToArray($conditionsarray[0],',','"'); - unset($conditionsarray[0]); - foreach ($conditionsarray as $car) { - $fieldcontents=convertCSVRowToArray($car,',','"'); - $conditionrowdata=array_combine($fieldorders,$fieldcontents); - - $oldqid = $conditionrowdata["qid"]; - $oldcqid = $conditionrowdata["cqid"]; - - // replace the qid for the new one (if there is no new qid in the $newqids array it mean that this condition is orphan -> error, skip this record) - if (isset($newqids[$oldqid])) - $conditionrowdata["qid"] = $newqids[$oldqid]; - else - continue; // a problem with this answer record -> don't consider - - // replace the cqid for the new one (if there is no new qid in the $newqids array it mean that this condition is orphan -> error, skip this record) - if (isset($newqids[$oldcqid])) - $conditionrowdata["cqid"] = $newqids[$oldcqid]; - else - continue; // a problem with this answer record -> don't consider - - list($oldcsid, $oldcgid, $oldqidanscode) = explode("X",$conditionrowdata["cfieldname"],3); - - if ($oldcgid != $oldgid) // this means that the condition is in another group (so it should not have to be been exported -> skip it - continue; - - unset($conditionrowdata["cid"]); - - // recreate the cfieldname with the new IDs - $newcfieldname = $newsid . "X" . $newgid . "X" . $conditionrowdata["cqid"] .substr($oldqidanscode,strlen($oldcgid)); - - $conditionrowdata["cfieldname"] = $newcfieldname; - if (!isset($conditionrowdata["method"]) || trim($conditionrowdata["method"])=='') - { - $conditionrowdata["method"]='=='; - } - $newvalues=array_values($conditionrowdata); - $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly - $conditioninsert = "insert INTO {$dbprefix}conditions (".implode(',',array_keys($conditionrowdata)).") VALUES (".implode(',',$newvalues).")"; - $result=$connect->Execute($conditioninsert) or safe_die ("Couldn't insert condition
      $conditioninsert
      ".$connect->ErrorMsg()); - $countconditions++; - } - } - // CONDITIONS is DONE - - -if (isset($skippedlanguages)) -{ - $importgroup.=''.$clang->gT("Import partially successful.")."

      "; - $importgroup.=$clang->gT("The following languages in this group were not imported since the survey does not contain such a language: ")."
      "; - foreach ($skippedlanguages as $sl) - { - $importgroup.= getLanguageNameFromCode($grouprowdata['language'], false).'
      '; - } - $importgroup.='
      '; -} -else -{ - $importgroup .= "
      \n".$clang->gT("Success")."
      \n"; -} -$importgroup .="".$clang->gT("Group Import Summary")."
      \n" -."
        \n\t
      • ".$clang->gT("Groups").": "; -if (isset($countgroups)) {$importgroup .= $countgroups;} -$importgroup .= "
      • \n" - ."\t
      • ".$clang->gT("Questions").": "; -if (isset($countquestions)) {$importgroup .= $countquestions;} -$importgroup .= "
      • \n" - ."\t
      • ".$clang->gT("Answers").": "; -if (isset($countanswers)) {$importgroup .= $countanswers;} -$importgroup .= "
      • \n" - ."\t
      • ".$clang->gT("Conditions").": "; -if (isset($countconditions)) {$importgroup .= $countconditions;} -$importgroup .= "
      • \n" -."\t
      • ".$clang->gT("Label Set").": "; -if (isset($countlabelsets)) {$importgroup .= $countlabelsets;} -$importgroup .= " (".$clang->gT("Labels").": "; -if (isset($countlabels)) {$importgroup .= $countlabels;} -$importgroup .= ")
      • \n"; -$importgroup .= "\t
      • ".$clang->gT("Question Attributes: "); -$importgroup .= $countquestion_attributes; -$importgroup .= "
      • \n
      \n"; -$importgroup .= "".$clang->gT("Import of group is completed.")."
       \n" -."
       \n"; - - -unlink($the_full_file_path); - -?> +
      \n"; +$importgroup .= "\n"; +$importgroup .= "\t\n"; +$importgroup .= "\t
      ".$clang->gT("Import Group")."
      \n"; + +$the_full_file_path = $tempdir . "/" . $_FILES['the_file']['name']; + +if (!@move_uploaded_file($_FILES['the_file']['tmp_name'], $the_full_file_path)) +{ + $importgroup .= "".$clang->gT("Error")."
      \n"; + $importgroup .= sprintf ($clang->gT("An error occurred uploading your file. This may be caused by incorrect permissions in your %s folder."),$tempdir)."

      \n"; + $importgroup .= "\n"; + $importgroup .= "
      \n"; + return; +} + +// validate that we have a SID +if (!returnglobal('sid')) +{ + $importquestion .= $clang->gT("No SID (Survey) has been provided. Cannot import group.")."

      \n" + ."\n" + ."
      \n"; + unlink($the_full_file_path); + return; +} +else +{ + $newsid = returnglobal('sid'); +} + + +// IF WE GOT THIS FAR, THEN THE FILE HAS BEEN UPLOADED SUCCESFULLY + +$importgroup .= "".$clang->gT("Success")."
      \n"; +$importgroup .= $clang->gT("File upload succeeded.")."

      \n"; +$importgroup .= $clang->gT("Reading file...")."
      \n"; +$handle = fopen($the_full_file_path, "r"); +while (!feof($handle)) +{ + $buffer = fgets($handle); + $bigarray[] = $buffer; +} +fclose($handle); + +if (substr($bigarray[0], 0, 23) != "# LimeSurvey Group Dump" && substr($bigarray[0], 0, 24) != "# PHPSurveyor Group Dump") +{ + $importgroup .= "".$clang->gT("Error")."
      \n"; + $importgroup .= $clang->gT("This file is not a LimeSurvey group file. Import failed.")."

      \n"; + $importgroup .= "\n"; + $importgroup .= "\n"; + unlink($the_full_file_path); + return; +} +else +{ + $importversion=(int)trim(substr($bigarray[1],12)); +} + +for ($i=0; $i<9; $i++) +{ + unset($bigarray[$i]); +} +$bigarray = array_values($bigarray); + +//GROUPS +if (array_search("# QUESTIONS TABLE\n", $bigarray)) +{ + $stoppoint = array_search("# QUESTIONS TABLE\n", $bigarray); +} +elseif (array_search("# QUESTIONS TABLE\r\n", $bigarray)) +{ + $stoppoint = array_search("# QUESTIONS TABLE\r\n", $bigarray); +} +else +{ + $stoppoint = count($bigarray)-1; +} +for ($i=0; $i<=$stoppoint+1; $i++) +{ + if ($i<$stoppoint-2) {$grouparray[] = $bigarray[$i];} + unset($bigarray[$i]); +} +$bigarray = array_values($bigarray); + +//QUESTIONS +if (array_search("# ANSWERS TABLE\n", $bigarray)) +{ + $stoppoint = array_search("# ANSWERS TABLE\n", $bigarray); +} +elseif (array_search("# ANSWERS TABLE\r\n", $bigarray)) +{ + $stoppoint = array_search("# ANSWERS TABLE\r\n", $bigarray); +} +else +{ + $stoppoint = count($bigarray)-1; +} +for ($i=0; $i<=$stoppoint+1; $i++) +{ + if ($i<$stoppoint-2) {$questionarray[] = $bigarray[$i];} + unset($bigarray[$i]); +} +$bigarray = array_values($bigarray); + +//ANSWERS +if (array_search("# CONDITIONS TABLE\n", $bigarray)) +{ + $stoppoint = array_search("# CONDITIONS TABLE\n", $bigarray); +} +elseif (array_search("# CONDITIONS TABLE\r\n", $bigarray)) +{ + $stoppoint = array_search("# CONDITIONS TABLE\r\n", $bigarray); +} +else +{ + $stoppoint = count($bigarray)-1; +} +for ($i=0; $i<=$stoppoint+1; $i++) +{ + if ($i<$stoppoint-2) {$answerarray[] = $bigarray[$i];} + unset($bigarray[$i]); +} +$bigarray = array_values($bigarray); + +//CONDITIONS +if (array_search("# LABELSETS TABLE\n", $bigarray)) +{ + $stoppoint = array_search("# LABELSETS TABLE\n", $bigarray); +} +elseif (array_search("# LABELSETS TABLE\r\n", $bigarray)) +{ + $stoppoint = array_search("# LABELSETS TABLE\r\n", $bigarray); +} +else +{ + $stoppoint = count($bigarray); +} +for ($i=0; $i<=$stoppoint+1; $i++) +{ + if ($i<$stoppoint-2) {$conditionsarray[] = $bigarray[$i];} + unset($bigarray[$i]); +} +$bigarray = array_values($bigarray); + +//LABELSETS +if (array_search("# LABELS TABLE\n", $bigarray)) +{ + $stoppoint = array_search("# LABELS TABLE\n", $bigarray); +} +elseif (array_search("# LABELS TABLE\r\n", $bigarray)) +{ + $stoppoint = array_search("# LABELS TABLE\r\n", $bigarray); +} +else +{ + $stoppoint = count($bigarray)-1; +} +for ($i=0; $i<=$stoppoint+1; $i++) +{ + if ($i<$stoppoint-2) {$labelsetsarray[] = $bigarray[$i];} + unset($bigarray[$i]); +} +$bigarray = array_values($bigarray); + +//LABELS +if (array_search("# QUESTION_ATTRIBUTES TABLE\n", $bigarray)) +{ + $stoppoint = array_search("# QUESTION_ATTRIBUTES TABLE\n", $bigarray); +} +elseif (array_search("# QUESTION_ATTRIBUTES TABLE\r\n", $bigarray)) +{ + $stoppoint = array_search("# QUESTION_ATTRIBUTES TABLE\r\n", $bigarray); +} +else +{ + $stoppoint = count($bigarray)-1; +} +for ($i=0; $i<=$stoppoint+1; $i++) +{ + if ($i<$stoppoint-2) {$labelsarray[] = $bigarray[$i];} + unset($bigarray[$i]); +} +$bigarray = array_values($bigarray); + +//LAST LOT (now question_attributes) +if (!isset($noconditions) || $noconditions != "Y") +{ + // stoppoint is the last line number + // this is an empty line after the QA CSV lines + $stoppoint = count($bigarray)-1; + for ($i=0; $i<=$stoppoint+1; $i++) + { + if ($i<=$stoppoint-1) {$question_attributesarray[] = $bigarray[$i];} + unset($bigarray[$i]); + } +} +$bigarray = array_values($bigarray); + +$countgroups=0; +if (isset($questionarray)) + { + $questionfieldnames=convertCSVRowToArray($questionarray[0],',','"'); + unset($questionarray[0]); + $countquestions = 0; + } + +if (isset($answerarray)) + { + $answerfieldnames=convertCSVRowToArray($answerarray[0],',','"'); + unset($answerarray[0]); + $countanswers = 0; + } + +$countconditions = 0; +$countlabelsets=0; +$countlabels=0; +$countquestion_attributes = 0; +$countanswers = 0; + + +// first check that imported group, questions and labels support the +// current survey's baselang +$langcode = GetBaseLanguageFromSurveyID($newsid); +if (isset($grouparray)) +{ + $groupfieldnames = convertCSVRowToArray($grouparray[0],',','"'); + $langfieldnum = array_search("language", $groupfieldnames); + $gidfieldnum = array_search("gid", $groupfieldnames); + $groupssupportbaselang = bDoesImportarraySupportsLanguage($grouparray,Array($gidfieldnum),$langfieldnum,$langcode,true); + if (!$groupssupportbaselang) + { + $importgroup .= "".$clang->gT("Error")."
      \n"; + $importgroup .= $clang->gT("You can't import a group which doesn't support the current survey's base language.")."

      \n"; + $importgroup .= "\n"; + $importgroup .= "\n"; + unlink($the_full_file_path); + return; + } +} + +if (isset($questionarray)) +{ + $langfieldnum = array_search("language", $questionfieldnames); + $qidfieldnum = array_search("qid", $questionfieldnames); + $questionssupportbaselang = bDoesImportarraySupportsLanguage($questionarray,Array($qidfieldnum), $langfieldnum,$langcode,false); + if (!$questionssupportbaselang) + { + $importgroup .= "".$clang->gT("Error")."
      \n"; + $importgroup .= $clang->gT("You can't import a question which doesn't support the current survey's base language.")."

      \n"; + $importgroup .= "\n"; + $importgroup .= "\n"; + unlink($the_full_file_path); + return; + } +} + + +if (isset($labelsetsarray)) +{ + $labelsetfieldname = convertCSVRowToArray($labelsetsarray[0],',','"'); + $langfieldnum = array_search("languages", $labelsetfieldname); + $lidfilednum = array_search("lid", $labelsetfieldname); + $labelsetssupportbaselang = bDoesImportarraySupportsLanguage($labelsetsarray,Array($lidfilednum),$langfieldnum,$langcode,true); + if (!$labelsetssupportbaselang) + { + $importquestion .= "".$clang->gT("Error")."
      \n" + .$clang->gT("You can't import label sets which don't support the current survey's base language")."

      \n" + ."\n"; + unlink($the_full_file_path); + return; + } +} + +$newlids = array(); // this array will have the "new lid" for the label sets, the key will be the "old lid" + +//DO ANY LABELSETS FIRST, SO WE CAN KNOW WHAT THEIR NEW LID IS FOR THE QUESTIONS +if (isset($labelsetsarray) && $labelsetsarray) { + $csarray=buildLabelSetCheckSumArray(); // build checksums over all existing labelsets + $count=0; + foreach ($labelsetsarray as $lsa) { + $fieldorders =convertCSVRowToArray($labelsetsarray[0],',','"'); + $fieldcontents=convertCSVRowToArray($lsa,',','"'); + if ($count==0) {$count++; continue;} + + $countlabelsets++; + + $labelsetrowdata=array_combine($fieldorders,$fieldcontents); + + // Save old labelid + $oldlid=$labelsetrowdata['lid']; + // set the new language + unset($labelsetrowdata['lid']); + $newvalues=array_values($labelsetrowdata); + $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly + $lsainsert = "INSERT INTO {$dbprefix}labelsets (".implode(',',array_keys($labelsetrowdata)).") VALUES (".implode(',',$newvalues).")"; //handle db prefix + $lsiresult=$connect->Execute($lsainsert); + + // Get the new insert id for the labels inside this labelset + $newlid=$connect->Insert_ID("{$dbprefix}labelsets",'lid'); + + if ($labelsarray) { + $count=0; + foreach ($labelsarray as $la) { + $lfieldorders =convertCSVRowToArray($labelsarray[0],',','"'); + $lfieldcontents=convertCSVRowToArray($la,',','"'); + if ($count==0) {$count++; continue;} + + // Combine into one array with keys and values since its easier to handle + $labelrowdata=array_combine($lfieldorders,$lfieldcontents); + $labellid=$labelrowdata['lid']; + if ($importversion<=132) + { + $labelrowdata["assessment_value"]=(int)$labelrowdata["code"]; + } + if ($labellid == $oldlid) { + $labelrowdata['lid']=$newlid; + + // translate internal links + $labelrowdata['title']=translink('label', $oldlid, $newlid, $labelrowdata['title']); + + $newvalues=array_values($labelrowdata); + $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly + $lainsert = "INSERT INTO {$dbprefix}labels (".implode(',',array_keys($labelrowdata)).") VALUES (".implode(',',$newvalues).")"; //handle db prefix + $liresult=$connect->Execute($lainsert); + $countlabels++; + } + } + } + + //CHECK FOR DUPLICATE LABELSETS + $thisset=""; + $query2 = "SELECT code, title, sortorder, language, assessment_value + FROM {$dbprefix}labels + WHERE lid=".$newlid." + ORDER BY language, sortorder, code"; + $result2 = db_execute_num($query2) or safe_die("Died querying labelset $lid
      $query2
      ".$connect->ErrorMsg()); + while($row2=$result2->FetchRow()) + { + $thisset .= implode('.', $row2); + } // while + $newcs=dechex(crc32($thisset)*1); + unset($lsmatch); + if (isset($csarray)) + { + foreach($csarray as $key=>$val) + { + if ($val == $newcs) + { + $lsmatch=$key; + } + } + } + if (isset($lsmatch)) + { + //There is a matching labelset. So, we will delete this one and refer + //to the matched one. + $query = "DELETE FROM {$dbprefix}labels WHERE lid=$newlid"; + $result=$connect->Execute($query) or safe_die("Couldn't delete labels
      $query
      ".$connect->ErrorMsg()); + $query = "DELETE FROM {$dbprefix}labelsets WHERE lid=$newlid"; + $result=$connect->Execute($query) or safe_die("Couldn't delete labelset
      $query
      ".$connect->ErrorMsg()); + $newlid=$lsmatch; + } + else + { + //There isn't a matching labelset, add this checksum to the $csarray array + $csarray[$newlid]=$newcs; + } + //END CHECK FOR DUPLICATES + $labelreplacements[]=array($oldlid, $newlid); + $newlids[$oldlid] = $newlid; + } +} + +//these arrays will aloud to insert correctly groups an questions multi languague survey imports correctly, and will eliminate the need to "searh" the imported data +//$newgids = array(); // this array will have the "new gid" for the groups, the kwy will be the "old gid" <-- not needed when importing groups +$newqids = array(); // this array will have the "new qid" for the questions, the kwy will be the "old qid" + +// DO GROUPS, QUESTIONS FOR GROUPS, THEN ANSWERS FOR QUESTIONS IN A __NOT__ NESTED FORMAT! +if (isset($grouparray) && $grouparray) +{ + $surveylanguages=GetAdditionalLanguagesFromSurveyID($surveyid); + $surveylanguages[]=GetBaseLanguageFromSurveyID($surveyid); + + // do GROUPS + $gafieldorders=convertCSVRowToArray($grouparray[0],',','"'); + unset($grouparray[0]); + $newgid = 0; + $group_order = 0; // just to initialize this variable + foreach ($grouparray as $ga) + { + //GET ORDER OF FIELDS + $gacfieldcontents=convertCSVRowToArray($ga,',','"'); + $grouprowdata=array_combine($gafieldorders,$gacfieldcontents); + + // Skip not supported languages + if (!in_array($grouprowdata['language'],$surveylanguages)) + { + $skippedlanguages[]=$grouprowdata['language']; // this is for the message in the end. + continue; + } + + // replace the sid + $oldsid=$grouprowdata['sid']; + $grouprowdata['sid']=$newsid; + + // replace the gid or remove it if needed (it also will calculate the group order if is a new group) + $oldgid=$grouprowdata['gid']; + if ($newgid == 0) + { + unset($grouprowdata['gid']); + + // find the maximum group order and use this grouporder+1 to assign it to the new group + $qmaxgo = "select max(group_order) as maxgo from ".db_table_name('groups')." where sid=$newsid"; + $gres = db_execute_assoc($qmaxgo) or safe_die ($clang->gT("Error")." Failed to find out maximum group order value
      \n$qmaxqo
      \n".$connect->ErrorMsg()); + $grow=$gres->FetchRow(); + $group_order = $grow['maxgo']+1; + } + else + $grouprowdata['gid'] = $newgid; + + $grouprowdata["group_order"]= $group_order; + + // Everything set - now insert it + $grouprowdata=array_map('convertCsvreturn2return', $grouprowdata); + + + // translate internal links + $grouprowdata['group_name']=translink('survey', $oldsid, $newsid, $grouprowdata['group_name']); + $grouprowdata['description']=translink('survey', $oldsid, $newsid, $grouprowdata['description']); + + $newvalues=array_values($grouprowdata); + $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly + $ginsert = "insert INTO {$dbprefix}groups (".implode(',',array_keys($grouprowdata)).") VALUES (".implode(',',$newvalues).")"; + $gres = $connect->Execute($ginsert) or safe_die($clang->gT("Error").": Failed to insert group
      \n$ginsert
      \n".$connect->ErrorMsg()); + + //GET NEW GID .... if is not done before and we count a group if a new gid is required + if ($newgid == 0) + { + $newgid = $connect->Insert_ID("{$dbprefix}groups",'gid'); + $countgroups++; + } + } + // GROUPS is DONE + + // do QUESTIONS + if (isset($questionarray) && $questionarray) + { + foreach ($questionarray as $qa) + { + $qacfieldcontents=convertCSVRowToArray($qa,',','"'); + $questionrowdata=array_combine($questionfieldnames,$qacfieldcontents); + + // Skip not supported languages + if (!in_array($questionrowdata['language'],$surveylanguages)) + continue; + + // replace the sid + $questionrowdata["sid"] = $newsid; + + // replace the gid (if the gid is not in the oldgid it means there is a problem with the exported record, so skip it) + if ($questionrowdata['gid'] == $oldgid) + $questionrowdata['gid'] = $newgid; + else + continue; // a problem with this question record -> don't consider + + // replace the qid or remove it if needed + $oldqid = $questionrowdata['qid']; + if (isset($newqids[$oldqid])) + $questionrowdata['qid'] = $newqids[$oldqid]; + else + unset($questionrowdata['qid']); + + // replace the lid for the new one (if there is no new lid in the $newlids array it mean that was not imported -> error, skip this record) + if (in_array($questionrowdata["type"], array("F","H","W","Z", "1", ":", ";"))) // only fot the questions that uses a label set. + if (isset($newlids[$questionrowdata["lid"]])) + { + $questionrowdata["lid"] = $newlids[$questionrowdata["lid"]]; + if(isset($newlids[$questionrowdata["lid1"]])) + { + $questionrowdata["lid1"] = $newlids[$questionrowdata["lid1"]]; + } + } + else + { + continue; // a problem with this question record -> don't consider + } +// $other = $questionrowdata["other"]; //Get 'other' field value +// $oldlid = $questionrowdata['lid']; + + // Everything set - now insert it + $questionrowdata=array_map('convertCsvreturn2return', $questionrowdata); + + // translate internal links + $questionrowdata['title']=translink('survey', $oldsid, $newsid, $questionrowdata['title']); + $questionrowdata['question']=translink('survey', $oldsid, $newsid, $questionrowdata['question']); + $questionrowdata['help']=translink('survey', $oldsid, $newsid, $questionrowdata['help']); + + $newvalues=array_values($questionrowdata); + $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly + $qinsert = "insert INTO {$dbprefix}questions (".implode(',',array_keys($questionrowdata)).") VALUES (".implode(',',$newvalues).")"; + $qres = $connect->Execute($qinsert) or safe_die ($clang->gT("Error")."Failed to insert question
      \n$qinsert
      \n".$connect->ErrorMsg()); + + //GET NEW QID .... if is not done before and we count a question if a new qid is required + if (!isset($newqids[$oldqid])) + { + $newqids[$oldqid] = $connect->Insert_ID("{$dbprefix}questions",'qid'); + $countquestions++; + } + } + } + // QESTIONS is DONE + + // do ANSWERS + if (isset($answerarray) && $answerarray) + { + foreach ($answerarray as $aa) + { + $aacfieldcontents=convertCSVRowToArray($aa,',','"'); + $answerrowdata=array_combine($answerfieldnames,$aacfieldcontents); + + // Skip not supported languages + if (!in_array($answerrowdata['language'],$surveylanguages)) + continue; + + // replace the qid for the new one (if there is no new qid in the $newqids array it mean that this answer is orphan -> error, skip this record) + if (isset($newqids[$answerrowdata["qid"]])) + $answerrowdata["qid"] = $newqids[$answerrowdata["qid"]]; + else + continue; // a problem with this answer record -> don't consider + + if ($importversion<=132) + { + $answerrowdata["assessment_value"]=(int)$answerrowdata["code"]; + } + + + // Everything set - now insert it + $answerrowdata = array_map('convertCsvreturn2return', $answerrowdata); + + // translate internal links + $answerrowdata['answer']=translink('survey', $oldsid, $newsid, $answerrowdata['answer']); + + $newvalues=array_values($answerrowdata); + $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly + $ainsert = "insert INTO {$dbprefix}answers (".implode(',',array_keys($answerrowdata)).") VALUES (".implode(',',$newvalues).")"; + $ares = $connect->Execute($ainsert) or safe_die ($clang->gT("Error")."Failed to insert answer
      \n$ainsert
      \n".$connect->ErrorMsg()); + $countanswers++; + } + } + // ANSWERS is DONE + + // Fix Group sortorder + fixsortorderGroups(); + //... and for the questions inside the groups + // get all group ids and fix questions inside each group + $gquery = "SELECT gid FROM {$dbprefix}groups where sid=$newsid group by gid ORDER BY gid"; //Get last question added (finds new qid) + $gres = db_execute_assoc($gquery); + while ($grow = $gres->FetchRow()) + { + fixsortorderQuestions($grow['gid'], $surveyid); + } + } + + // do ATTRIBUTES + if (isset($question_attributesarray) && $question_attributesarray) + { + $fieldorders =convertCSVRowToArray($question_attributesarray[0],',','"'); + unset($question_attributesarray[0]); + foreach ($question_attributesarray as $qar) { + $fieldcontents=convertCSVRowToArray($qar,',','"'); + $qarowdata=array_combine($fieldorders,$fieldcontents); + + // replace the qid for the new one (if there is no new qid in the $newqids array it mean that this attribute is orphan -> error, skip this record) + if (isset($newqids[$qarowdata["qid"]])) + $qarowdata["qid"] = $newqids[$qarowdata["qid"]]; + else + continue; // a problem with this answer record -> don't consider + + unset($qarowdata["qaid"]); + + // Everything set - now insert it + $newvalues=array_values($qarowdata); + $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly + $qainsert = "insert INTO {$dbprefix}question_attributes (".implode(',',array_keys($qarowdata)).") VALUES (".implode(',',$newvalues).")"; + $result=$connect->Execute($qainsert) or safe_die ("Couldn't insert question_attribute
      $qainsert
      ".$connect->ErrorMsg()); + $countquestion_attributes++; + } + } + // ATTRIBUTES is DONE + + // do CONDITIONS + if (isset($conditionsarray) && $conditionsarray) + { + $fieldorders=convertCSVRowToArray($conditionsarray[0],',','"'); + unset($conditionsarray[0]); + foreach ($conditionsarray as $car) { + $fieldcontents=convertCSVRowToArray($car,',','"'); + $conditionrowdata=array_combine($fieldorders,$fieldcontents); + + $oldqid = $conditionrowdata["qid"]; + $oldcqid = $conditionrowdata["cqid"]; + + // replace the qid for the new one (if there is no new qid in the $newqids array it mean that this condition is orphan -> error, skip this record) + if (isset($newqids[$oldqid])) + $conditionrowdata["qid"] = $newqids[$oldqid]; + else + continue; // a problem with this answer record -> don't consider + + // replace the cqid for the new one (if there is no new qid in the $newqids array it mean that this condition is orphan -> error, skip this record) + if (isset($newqids[$oldcqid])) + $conditionrowdata["cqid"] = $newqids[$oldcqid]; + else + continue; // a problem with this answer record -> don't consider + + list($oldcsid, $oldcgid, $oldqidanscode) = explode("X",$conditionrowdata["cfieldname"],3); + + if ($oldcgid != $oldgid) // this means that the condition is in another group (so it should not have to be been exported -> skip it + continue; + + unset($conditionrowdata["cid"]); + + // recreate the cfieldname with the new IDs + if (preg_match("/^\+/",$oldcsid)) + { + $newcfieldname = '+'.$newsid . "X" . $newgid . "X" . $conditionrowdata["cqid"] .substr($oldqidanscode,strlen($oldqid)); + } + else + { + $newcfieldname = $newsid . "X" . $newgid . "X" . $conditionrowdata["cqid"] .substr($oldqidanscode,strlen($oldqid)); + } + + $conditionrowdata["cfieldname"] = $newcfieldname; + if (!isset($conditionrowdata["method"]) || trim($conditionrowdata["method"])=='') + { + $conditionrowdata["method"]='=='; + } + $newvalues=array_values($conditionrowdata); + $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly + $conditioninsert = "insert INTO {$dbprefix}conditions (".implode(',',array_keys($conditionrowdata)).") VALUES (".implode(',',$newvalues).")"; + $result=$connect->Execute($conditioninsert) or safe_die ("Couldn't insert condition
      $conditioninsert
      ".$connect->ErrorMsg()); + $countconditions++; + } + } + // CONDITIONS is DONE + + +if (isset($skippedlanguages)) +{ + $importgroup.=''.$clang->gT("Import partially successful.")."

      "; + $importgroup.=$clang->gT("The following languages in this group were not imported since the survey does not contain such a language: ")."
      "; + foreach ($skippedlanguages as $sl) + { + $importgroup.= getLanguageNameFromCode($grouprowdata['language'], false).'
      '; + } + $importgroup.='
      '; +} +else +{ + $importgroup .= "
      \n".$clang->gT("Success")."
      \n"; +} +$importgroup .="".$clang->gT("Group Import Summary")."
      \n" +."
        \n\t
      • ".$clang->gT("Groups:"); +if (isset($countgroups)) {$importgroup .= $countgroups;} +$importgroup .= "
      • \n" + ."\t
      • ".$clang->gT("Questions").": "; +if (isset($countquestions)) {$importgroup .= $countquestions;} +$importgroup .= "
      • \n" + ."\t
      • ".$clang->gT("Answers").": "; +if (isset($countanswers)) {$importgroup .= $countanswers;} +$importgroup .= "
      • \n" + ."\t
      • ".$clang->gT("Conditions").": "; +if (isset($countconditions)) {$importgroup .= $countconditions;} +$importgroup .= "
      • \n" +."\t
      • ".$clang->gT("Label Set").": "; +if (isset($countlabelsets)) {$importgroup .= $countlabelsets;} +$importgroup .= " (".$clang->gT("Labels").": "; +if (isset($countlabels)) {$importgroup .= $countlabels;} +$importgroup .= ")
      • \n"; +$importgroup .= "\t
      • ".$clang->gT("Question Attributes: "); +$importgroup .= $countquestion_attributes; +$importgroup .= "
      • \n
      \n"; +$importgroup .= "".$clang->gT("Import of group is completed.")."
       \n"; +$importgroup .= "".$clang->gT("Go to group")."
      \n"; +$importgroup .= "
       \n"; + + +unlink($the_full_file_path); + +?> diff --git a/include/limesurvey/admin/importlabel.php b/include/limesurvey/admin/importlabel.php index fa9b7486..4b5eb081 100644 --- a/include/limesurvey/admin/importlabel.php +++ b/include/limesurvey/admin/importlabel.php @@ -1,219 +1,223 @@ -\n"; -$importlabeloutput .= "\n"; -$importlabeloutput .= "\t\n"; -$importlabeloutput .= "\t
      ".$clang->gT("Import Label Set")."
      \n"; - -$the_full_file_path = $tempdir . "/" . $_FILES['the_file']['name']; - -if (!@move_uploaded_file($_FILES['the_file']['tmp_name'], $the_full_file_path)) -{ - $importlabeloutput .= "".$clang->gT("Error")."
      \n"; - $importlabeloutput .= sprintf ($clang->gT("An error occurred uploading your file. This may be caused by incorrect permissions in your %s folder."),$tempdir)."

      \n"; - $importlabeloutput .= "\n"; - $importlabeloutput .= "

       \n"; - return; -} - -// IF WE GOT THIS FAR, THEN THE FILE HAS BEEN UPLOADED SUCCESFULLY - -$csarray=buildLabelSetCheckSumArray(); -//$csarray is now a keyed array with the Checksum of each of the label sets, and the lid as the key - -$importlabeloutput .= "".$clang->gT("Success")."
      \n"; -$importlabeloutput .= $clang->gT("File upload succeeded.")."

      \n"; -$importlabeloutput .= $clang->gT("Reading file..")."
      \n"; -$handle = fopen($the_full_file_path, "r"); -while (!feof($handle)) -{ - $buffer = fgets($handle, 10240); //To allow for very long survey welcomes (up to 10k) - $bigarray[] = $buffer; -} -fclose($handle); -if (substr($bigarray[0], 0, 27) != "# LimeSurvey Label Set Dump" && substr($bigarray[0], 0, 28) != "# PHPSurveyor Label Set Dump") -{ - $importlabeloutput .= "".$clang->gT("Error")."
      \n"; - $importlabeloutput .= $clang->gT("This file is not a LimeSurvey label set file. Import failed.")."

      \n"; - $importlabeloutput .= "\n"; - $importlabeloutput .= "\n"; - $importlabeloutput .= "\n\n"; - unlink($the_full_file_path); - return; -} - -for ($i=0; $i<9; $i++) //skipping the first lines that are not needed -{ - unset($bigarray[$i]); -} -$bigarray = array_values($bigarray); - -//LABEL SETS -if (array_search("# LABELS TABLE\n", $bigarray)) -{ - $stoppoint = array_search("# LABELS TABLE\n", $bigarray); -} -elseif (array_search("# LABELS TABLE\r\n", $bigarray)) -{ - $stoppoint = array_search("# LABELS TABLE\r\n", $bigarray); -} -else -{ - $stoppoint = count($bigarray)-1; -} -for ($i=0; $i<=$stoppoint+1; $i++) -{ - if ($i<$stoppoint-2) {$labelsetsarray[] = $bigarray[$i];} - unset($bigarray[$i]); -} -$bigarray = array_values($bigarray); - - -//LABELS -$stoppoint = count($bigarray)-1; - -for ($i=0; $i<$stoppoint; $i++) -{ - // do not import empty lines - if (trim($bigarray[$i])!='') - { - $labelsarray[] = $bigarray[$i]; - } - unset($bigarray[$i]); -} - - - -$countlabelsets = count($labelsetsarray)-1; -$countlabels = count($labelsarray)-1; - - -if (isset($labelsetsarray) && $labelsetsarray) { - $csarray=buildLabelSetCheckSumArray(); // build checksums over all existing labelsets - $count=0; - foreach ($labelsetsarray as $lsa) { - $fieldorders =convertCSVRowToArray($labelsetsarray[0],',','"'); - $fieldcontents=convertCSVRowToArray($lsa,',','"'); - if ($count==0) {$count++; continue;} - - $labelsetrowdata=array_combine($fieldorders,$fieldcontents); - - // Save old labelid - $oldlid=$labelsetrowdata['lid']; - // set the new language - - unset($labelsetrowdata['lid']); - - $countlang=count(explode(' ',trim($labelsetrowdata['languages']))); - $newvalues=array_values($labelsetrowdata); - $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly - $lsainsert = "insert INTO {$dbprefix}labelsets (".implode(',',array_keys($labelsetrowdata)).") VALUES (".implode(',',$newvalues).")"; //handle db prefix - $lsiresult=$connect->Execute($lsainsert); - - // Get the new insert id for the labels inside this labelset - $newlid=$connect->Insert_ID("{$dbprefix}labelsets",'lid'); - - if ($labelsarray) { - $count=0; - $lfieldorders =convertCSVRowToArray($labelsarray[0],',','"'); - unset($labelsarray[0]); - foreach ($labelsarray as $la) { - - $lfieldcontents=convertCSVRowToArray($la,',','"'); - // Combine into one array with keys and values since its easier to handle - $labelrowdata=array_combine($lfieldorders,$lfieldcontents); - $labellid=$labelrowdata['lid']; - - if ($labellid == $oldlid) { - $labelrowdata['lid']=$newlid; - - // translate internal links - $labelrowdata['title']=translink('label', $oldlid, $newlid, $labelrowdata['title']); - - $newvalues=array_values($labelrowdata); - $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly - $lainsert = "insert INTO {$dbprefix}labels (".implode(',',array_keys($labelrowdata)).") VALUES (".implode(',',$newvalues).")"; //handle db prefix - $liresult=$connect->Execute($lainsert); - } - } - } - - //CHECK FOR DUPLICATE LABELSETS - $thisset=""; - $query2 = "SELECT code, title, sortorder, language - FROM ".db_table_name('labels')." - WHERE lid=".$newlid." - ORDER BY sortorder, code"; - $result2 = db_execute_num($query2) or safe_die("Died querying labelset $lid
      $query2
      ".$connect->ErrorMsg()); - while($row2=$result2->FetchRow()) - { - $thisset .= implode('.', $row2); - } // while - $newcs=dechex(crc32($thisset)*1); - unset($lsmatch); - - if (isset($csarray)) - { - foreach($csarray as $key=>$val) - { -// echo $val."-".$newcs."
      "; For debug purposes - if ($val == $newcs) - { - $lsmatch=$key; - } - } - } - if (isset($lsmatch)) - { - //There is a matching labelset. So, we will delete this one and refer - //to the matched one. - $query = "DELETE FROM {$dbprefix}labels WHERE lid=$newlid"; - $result=$connect->Execute($query) or safe_die("Couldn't delete labels
      $query
      ".$connect->ErrorMsg()); - $query = "DELETE FROM {$dbprefix}labelsets WHERE lid=$newlid"; - $result=$connect->Execute($query) or safe_die("Couldn't delete labelset
      $query
      ".$connect->ErrorMsg()); - $newlid=$lsmatch; - $importlabeloutput.="

      ".$clang->gT("There was a duplicate labelset, so this set was not imported. The duplicate will be used instead.")."\n"; - $importlabeloutput .= "Existing LID: $newlid


      \n"; - - } - else - { - $importlabeloutput .= "LID: $newlid
      \n"; - $importlabeloutput .= "
      \n".$clang->gT("Success")."
      \n"; - $importlabeloutput .= "".$clang->gT("Label Set Import Summary")."
      \n"; - $importlabeloutput .= "\t
    5. ".$clang->gT("Label Sets").": $countlabelsets
    6. \n"; - $importlabeloutput .= "\t
    7. ".$clang->gT("Labels").": $countlabels
    8. \n"; - $importlabeloutput .= "\t
    9. ".$clang->gT("Languages").": $countlang

    10. \n"; - } - //END CHECK FOR DUPLICATES - } -} - - -$importlabeloutput .= "".$clang->gT("Import of Label Set is completed.")."
      \n"; -$importlabeloutput .= "\n"; - -$importlabeloutput .= "\n"; -unlink($the_full_file_path); - - - -?> +\n"; +$importlabeloutput .= "\n"; +$importlabeloutput .= "\t\n"; +$importlabeloutput .= "\t
      ".$clang->gT("Import Label Set")."
      \n"; + +$the_full_file_path = $tempdir . "/" . $_FILES['the_file']['name']; + +if (!@move_uploaded_file($_FILES['the_file']['tmp_name'], $the_full_file_path)) +{ + $importlabeloutput .= "".$clang->gT("Error")."
      \n"; + $importlabeloutput .= sprintf ($clang->gT("An error occurred uploading your file. This may be caused by incorrect permissions in your %s folder."),$tempdir)."

      \n"; + $importlabeloutput .= "\n"; + $importlabeloutput .= "

       \n"; + return; +} + +// IF WE GOT THIS FAR, THEN THE FILE HAS BEEN UPLOADED SUCCESFULLY + +$csarray=buildLabelSetCheckSumArray(); +//$csarray is now a keyed array with the Checksum of each of the label sets, and the lid as the key + +$importlabeloutput .= "".$clang->gT("Success")."
      \n"; +$importlabeloutput .= $clang->gT("File upload succeeded.")."

      \n"; +$importlabeloutput .= $clang->gT("Reading file..")."
      \n"; +$handle = fopen($the_full_file_path, "r"); +while (!feof($handle)) +{ + $buffer = fgets($handle, 10240); //To allow for very long survey welcomes (up to 10k) + $bigarray[] = $buffer; +} +fclose($handle); +if (substr($bigarray[0], 0, 27) != "# LimeSurvey Label Set Dump" && substr($bigarray[0], 0, 28) != "# PHPSurveyor Label Set Dump") +{ + $importlabeloutput .= "".$clang->gT("Error")."
      \n"; + $importlabeloutput .= $clang->gT("This file is not a LimeSurvey label set file. Import failed.")."

      \n"; + $importlabeloutput .= "\n"; + $importlabeloutput .= "\n"; + $importlabeloutput .= "\n\n"; + unlink($the_full_file_path); + return; +} + +for ($i=0; $i<9; $i++) //skipping the first lines that are not needed +{ + unset($bigarray[$i]); +} +$bigarray = array_values($bigarray); + +//LABEL SETS +if (array_search("# LABELS TABLE\n", $bigarray)) +{ + $stoppoint = array_search("# LABELS TABLE\n", $bigarray); +} +elseif (array_search("# LABELS TABLE\r\n", $bigarray)) +{ + $stoppoint = array_search("# LABELS TABLE\r\n", $bigarray); +} +else +{ + $stoppoint = count($bigarray)-1; +} +for ($i=0; $i<=$stoppoint+1; $i++) +{ + if ($i<$stoppoint-2) {$labelsetsarray[] = $bigarray[$i];} + unset($bigarray[$i]); +} +$bigarray = array_values($bigarray); + + +//LABELS +$stoppoint = count($bigarray)-1; + +for ($i=0; $i<$stoppoint; $i++) +{ + // do not import empty lines + if (trim($bigarray[$i])!='') + { + $labelsarray[] = $bigarray[$i]; + } + unset($bigarray[$i]); +} + + + +$countlabelsets = count($labelsetsarray)-1; +$countlabels = count($labelsarray)-1; + + +if (isset($labelsetsarray) && $labelsetsarray) { + $csarray=buildLabelSetCheckSumArray(); // build checksums over all existing labelsets + $count=0; + foreach ($labelsetsarray as $lsa) { + $fieldorders =convertCSVRowToArray($labelsetsarray[0],',','"'); + $fieldcontents=convertCSVRowToArray($lsa,',','"'); + if ($count==0) {$count++; continue;} + + $labelsetrowdata=array_combine($fieldorders,$fieldcontents); + + // Save old labelid + $oldlid=$labelsetrowdata['lid']; + // set the new language + + unset($labelsetrowdata['lid']); + + $countlang=count(explode(' ',trim($labelsetrowdata['languages']))); + $newvalues=array_values($labelsetrowdata); + $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly + $lsainsert = "insert INTO {$dbprefix}labelsets (".implode(',',array_keys($labelsetrowdata)).") VALUES (".implode(',',$newvalues).")"; //handle db prefix + $lsiresult=$connect->Execute($lsainsert); + + // Get the new insert id for the labels inside this labelset + $newlid=$connect->Insert_ID("{$dbprefix}labelsets",'lid'); + + if ($labelsarray) { + $count=0; + $lfieldorders =convertCSVRowToArray($labelsarray[0],',','"'); + unset($labelsarray[0]); + foreach ($labelsarray as $la) { + + $lfieldcontents=convertCSVRowToArray($la,',','"'); + // Combine into one array with keys and values since its easier to handle + $labelrowdata=array_combine($lfieldorders,$lfieldcontents); + $labellid=$labelrowdata['lid']; + + if ($labellid == $oldlid) { + $labelrowdata['lid']=$newlid; + + // translate internal links + $labelrowdata['title']=translink('label', $oldlid, $newlid, $labelrowdata['title']); + if (!isset($labelrowdata["assessment_value"])) + { + $labelrowdata["assessment_value"]=(int)$labelrowdata["code"]; + } + + $newvalues=array_values($labelrowdata); + $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly + $lainsert = "insert INTO {$dbprefix}labels (".implode(',',array_keys($labelrowdata)).") VALUES (".implode(',',$newvalues).")"; //handle db prefix + $liresult=$connect->Execute($lainsert); + } + } + } + + //CHECK FOR DUPLICATE LABELSETS + $thisset=""; + $query2 = "SELECT code, title, sortorder, language, assessment_value + FROM ".db_table_name('labels')." + WHERE lid=".$newlid." + ORDER BY sortorder, code"; + $result2 = db_execute_num($query2) or safe_die("Died querying labelset $lid
      $query2
      ".$connect->ErrorMsg()); + while($row2=$result2->FetchRow()) + { + $thisset .= implode('.', $row2); + } // while + $newcs=dechex(crc32($thisset)*1); + unset($lsmatch); + + if (isset($csarray)) + { + foreach($csarray as $key=>$val) + { +// echo $val."-".$newcs."
      "; For debug purposes + if ($val == $newcs) + { + $lsmatch=$key; + } + } + } + if (isset($lsmatch)) + { + //There is a matching labelset. So, we will delete this one and refer + //to the matched one. + $query = "DELETE FROM {$dbprefix}labels WHERE lid=$newlid"; + $result=$connect->Execute($query) or safe_die("Couldn't delete labels
      $query
      ".$connect->ErrorMsg()); + $query = "DELETE FROM {$dbprefix}labelsets WHERE lid=$newlid"; + $result=$connect->Execute($query) or safe_die("Couldn't delete labelset
      $query
      ".$connect->ErrorMsg()); + $newlid=$lsmatch; + $importlabeloutput.="

      ".$clang->gT("There was a duplicate labelset, so this set was not imported. The duplicate will be used instead.")."\n"; + $importlabeloutput .= "Existing LID: $newlid


      \n"; + + } + else + { + $importlabeloutput .= "LID: $newlid
      \n"; + $importlabeloutput .= "
      \n".$clang->gT("Success")."
      \n"; + $importlabeloutput .= "".$clang->gT("Label Set Import Summary")."
      \n"; + $importlabeloutput .= "\t
    11. ".$clang->gT("Label Sets").": $countlabelsets
    12. \n"; + $importlabeloutput .= "\t
    13. ".$clang->gT("Labels").": $countlabels
    14. \n"; + $importlabeloutput .= "\t
    15. ".$clang->gT("Languages").": $countlang

    16. \n"; + } + //END CHECK FOR DUPLICATES + } +} + + +$importlabeloutput .= "".$clang->gT("Import of Label Set is completed.")."
      \n"; +$importlabeloutput .= "\n"; + +$importlabeloutput .= "\n"; +unlink($the_full_file_path); + + + +?> diff --git a/include/limesurvey/admin/importoldresponses.php b/include/limesurvey/admin/importoldresponses.php index 08c9e95f..264932dc 100644 --- a/include/limesurvey/admin/importoldresponses.php +++ b/include/limesurvey/admin/importoldresponses.php @@ -1,138 +1,269 @@ -$query
      ".$connect->ErrorMsg()); - $optionElements = ''; - while ($row = $result->FetchRow()) - { - $optionElements .= "\t\t\t\n"; - } - - $importoldresponsesoutput = ""; - $importoldresponsesoutput .= "\n" - ."\t\n"; - //Get the menubar - $importoldresponsesoutput .= browsemenubar(); - $importoldresponsesoutput .= "\n"; - $importoldresponsesoutput .= "
      - - - - - - - - - - - - - - - - -
      ".$clang->gT("Import responses from an old (deactivated) survey table into an active survey")."
      ".$clang->gT("Target Survey ID")." $surveyid
      - ".$clang->gT("Source table").": - - -
      -   - -

       "; -} -elseif (isset($surveyid) && $surveyid && isset($oldtable)) -{ - - // options (UI not implemented) - - $dontimportfields = array( - 'id' //,'otherfield' - ); - $presetfields = array( // quote all strings so we can allow NULL - //'4X13X951'=>"'Y'" - //'id' => "NULL" - ); - $importidrange = false; //array('first'=>3,'last'=>10); - - $activetable = "{$dbprefix}survey_$surveyid"; - - // fields we can import - $importablefields = array(); - $query = "SHOW COLUMNS FROM {$activetable}"; - $result = db_execute_assoc($query) or safe_die("Error:
      $query
      ".$connect->ErrorMsg()); - while ($row = $result->FetchRow()) - { - if (!in_array($row['Field'],$dontimportfields)) - { - $importablefields[] = $row['Field']; - } - } - - // fields we can supply - $availablefields = array(); - $query = "SHOW COLUMNS FROM {$oldtable}"; - $result = db_execute_assoc($query) or safe_die("Error:
      $query
      ".$connect->ErrorMsg()); - while ($row = $result->FetchRow()) - { - $availablefields[] = $row['Field']; - } - foreach ($presetfields as $field => $value) - { - if (!in_array($field,$availablefields)) - { - $availablefields[] = $field; - } - } - - $fieldstoimport = array_intersect($importablefields,$availablefields); - - // data sources for each field (field of oldtable or preset value) - $sourcefields = array(); - foreach ($fieldstoimport as $field) - { - $sourcefields[] = array_key_exists($field,$presetfields)? - $presetfields[$field] - : ($oldtable.'.'.$field); - } - - $query = "INSERT INTO {$activetable} (\n\t".join("\t, ",$fieldstoimport)."\n) " - ."SELECT\n\t".join("\t,",$sourcefields)."\n" - ."FROM {$oldtable}"; - if (is_array($importidrange)) - { - $query .= " WHERE {$oldtable}.id >= {$importidrange['first']} " - ." AND {$oldtable}.id <= {$importidrange['last']}"; - } - - $result = $connect->Execute($query) or safe_die("Error:
      $query
      ".$connect->ErrorMsg()); - - header("Location: $scriptname?action=browse&sid=$surveyid"); -} - -?> +$query
      ".$connect->ErrorMsg()); + $optionElements = ''; + $queryCheckColumnsActive = "SELECT * FROM {$dbprefix}survey_{$surveyid} "; + $resultActive = db_execute_num($queryCheckColumnsActive) or safe_die("Error:
      $query
      ".$connect->ErrorMsg()); + $countActive = $resultActive->FieldCount(); + + while ($row = $result->FetchRow()) + { + $queryCheckColumnsOld = "SELECT * FROM {$row[0]} "; + + $resultOld = db_execute_num($queryCheckColumnsOld) or safe_die("Error:
      $query
      ".$connect->ErrorMsg()); + + if($countActive== $resultOld->FieldCount()) + { + $optionElements .= "\t\t\t\n"; + } + } + + //Get the menubar + $importoldresponsesoutput = browsemenubar($clang->gT("Quick Statistics")); + $importoldresponsesoutput .= "
      +
      + ".$clang->gT("Import responses from an deactivated survey table")." +
      +
      +
        +
      • + $surveyid +
      • +
      • + + +
      • +
      +   +

      +
      ".$clang->gT("Warning: You can import all old responses with the same amount of columns as in your active survey. YOU have to make sure, that this responses corresponds to the questions in your active survey.")."
      +
      +
  • +
    "; +} +elseif (isset($surveyid) && $surveyid && isset($oldtable)) +{ + /* + * TODO: + * - mysql fit machen + * -- quotes für mysql beachten --> ` + * - warnmeldung mehrsprachig + * - testen + */ +// if($databasetype=="postgres") +// { + $activetable = "{$dbprefix}survey_$surveyid"; + + //Fields we don't want to import + $dontimportfields = array( + 'id' //,'otherfield' + ); + + // fields we can import + $importablefields = array(); + if($databasetype=="postgres") + { + $query = "SELECT column_name as field FROM information_schema.columns WHERE table_name = '{$activetable}' "; + } + else + { + $query = "SHOW COLUMNS FROM {$activetable}"; + } + + $result = db_execute_assoc($query) or safe_die("Error:
    $query
    ".$connect->ErrorMsg()); + + while ($row = $result->FetchRow()) + { + if($databasetype=="postgres") + { + if (!in_array($row['field'],$dontimportfields)) + { + $importablefields[] = $row['field']; + } + } + else + { + if (!in_array($row['Field'],$dontimportfields)) + { + $importablefields[] = $row['Field']; + } + } + } + foreach ($importablefields as $field => $value) + { + $fields2insert[]=($databasetype=="postgres") ? "\"".$value."\"" : "`".$value."`"; +// if($databasetype=="postgres") { $fields2insert[] = "\"".$value."\""; } + } + + //fields we can supply //fields in the old database + $availablefields = array(); + + if($databasetype=="postgres") + { + $query = "SELECT column_name as field FROM information_schema.columns WHERE table_name = '{$oldtable}' "; + } + else + { + $query = "SHOW COLUMNS FROM {$oldtable}"; + } + $result = db_execute_assoc($query) or safe_die("Error:
    $query
    ".$connect->ErrorMsg()); + + while ($row = $result->FetchRow()) + { + if($databasetype=="postgres") + { + if (!in_array($row['field'],$dontimportfields)) + { + $availablefields[] = $row['field']; + } + } + else + { + if (!in_array($row['Field'],$dontimportfields)) + { + $availablefields[] = $row['Field']; + } + } + + } + + foreach ($availablefields as $field => $value) + { + if($databasetype=="postgres") + { + $fields2import[] = "\"".$value."\""; + } + else + { + $fields2import[] = '`'.$value.'`'; + } + } + + $queryOldValues = "SELECT ".implode(", ",$fields2import)." " + . "FROM {$oldtable} "; + $resultOldValues = db_execute_assoc($queryOldValues) or safe_die("Error:
    $queryOldValues
    ".$connect->ErrorMsg()); + + while ($row = $resultOldValues->FetchRow()) + { + $values2import = array(); + foreach($row as $fieldName => $fieldValue) + { + if( $fieldValue=="") + { + $values2import[] = "NULL"; + } + else + { + if(!is_numeric($fieldValue)) + $values2import[] = "'".db_quote($fieldValue)."'"; + else + $values2import[] = "".$fieldValue.""; + } + } + + $insertOldValues = "INSERT INTO {$activetable} ( ".implode(", ",$fields2insert).") " + . "VALUES( ".implode(", ",$values2import)."); "; + $result = $connect->Execute($insertOldValues) or safe_die("Error:
    $insertOldValues
    ".$connect->ErrorMsg()); + } + +// } +// else +// { +// // options (UI not implemented) +// +// $dontimportfields = array( +// 'id' //,'otherfield' +// ); +// $presetfields = array( // quote all strings so we can allow NULL +// //'4X13X951'=>"'Y'" +// //'id' => "NULL" +// ); +// $importidrange = false; //array('first'=>3,'last'=>10); +// +// $activetable = "{$dbprefix}survey_$surveyid"; +// +// // fields we can import +// $importablefields = array(); +// $query = "SHOW COLUMNS FROM {$activetable}"; +// $result = db_execute_assoc($query) or safe_die("Error:
    $query
    ".$connect->ErrorMsg()); +// while ($row = $result->FetchRow()) +// { +// if (!in_array($row['Field'],$dontimportfields)) +// { +// $importablefields[] = $row['Field']; +// } +// } +// +// // fields we can supply +// $availablefields = array(); +// $query = "SHOW COLUMNS FROM {$oldtable}"; +// $result = db_execute_assoc($query) or safe_die("Error:
    $query
    ".$connect->ErrorMsg()); +// while ($row = $result->FetchRow()) +// { +// $availablefields[] = $row['Field']; +// } +// foreach ($presetfields as $field => $value) +// { +// if (!in_array($field,$availablefields)) +// { +// $availablefields[] = $field; +// } +// } +// +// $fieldstoimport = array_intersect($importablefields,$availablefields); +// +// // data sources for each field (field of oldtable or preset value) +// $sourcefields = array(); +// foreach ($fieldstoimport as $field) +// { +// $sourcefields[] = array_key_exists($field,$presetfields)? +// $presetfields[$field] +// : ($oldtable.'.`'.$field.'`'); +// $fieldstoimport2[] = '`'.$field.'`'; +// } +// +// $query = "INSERT INTO {$activetable} (\n\t".join("\t, ",$fieldstoimport2)."\n) " +// ."SELECT\n\t".join("\t,",$sourcefields)."\n" +// ."FROM {$oldtable}"; +// if (is_array($importidrange)) +// { +// $query .= " WHERE {$oldtable}.id >= {$importidrange['first']} " +// ." AND {$oldtable}.id <= {$importidrange['last']}"; +// } +// +// $result = $connect->Execute($query) or safe_die("Error:
    $query
    ".$connect->ErrorMsg()); +// } + header("Location: $scriptname?action=browse&sid=$surveyid"); +} + +?> diff --git a/include/limesurvey/admin/importquestion.php b/include/limesurvey/admin/importquestion.php index 74d1410c..e0cf2e8e 100644 --- a/include/limesurvey/admin/importquestion.php +++ b/include/limesurvey/admin/importquestion.php @@ -1,519 +1,527 @@ -
    \n" -."\n" -."\t\n" -."\t
    " -.$clang->gT("Import Question")."
    \n"; - -$the_full_file_path = $tempdir . "/" . $_FILES['the_file']['name']; - -if (!@move_uploaded_file($_FILES['the_file']['tmp_name'], $the_full_file_path)) -{ - $importquestion .= "".$clang->gT("Error")."
    \n"; - $importquestion .= sprintf ($clang->gT("An error occurred uploading your file. This may be caused by incorrect permissions in your %s folder."),$tempdir)."

    \n" - ."\n" - ."
    \n"; - unlink($the_full_file_path); - return; -} - -// validate that we have a SID and GID -if (!returnglobal('sid')) -{ - $importquestion .= $clang->gT("No SID (Survey) has been provided. Cannot import question.")."

    \n" - ."\n" - ."
    \n"; - unlink($the_full_file_path); - return; -} -else -{ - $postsid=returnglobal('sid'); -} - -if (!returnglobal('gid')) -{ - $importquestion .= $clang->gT("No GID (Group) has been provided. Cannot import question")."

    \n" - ."\n"; - unlink($the_full_file_path); - return; -} -else -{ - $postgid=returnglobal('gid'); -} - -// IF WE GOT THIS FAR, THEN THE FILE HAS BEEN UPLOADED SUCCESFULLY -$importquestion .= "".$clang->gT("Success")."
    \n" -.$clang->gT("File upload succeeded.")."

    \n" -.$clang->gT("Reading file..")."\n"; -$handle = fopen($the_full_file_path, "r"); -while (!feof($handle)) -{ - $buffer = fgets($handle, 10240); //To allow for very long survey welcomes (up to 10k) - $bigarray[] = $buffer; -} -fclose($handle); - -// Now we try to determine the dataformat of the survey file. -if ((substr($bigarray[1], 0, 24) == "# SURVEYOR QUESTION DUMP")&& (substr($bigarray[4], 0, 29) == "# http://www.phpsurveyor.org/")) -{ - $importversion = 100; // version 1.0 file -} -elseif - ((substr($bigarray[1], 0, 24) == "# SURVEYOR QUESTION DUMP")&& (substr($bigarray[4], 0, 37) == "# http://phpsurveyor.sourceforge.net/")) -{ - $importversion = 99; // Version 0.99 file or older - carries a different URL -} -elseif - (substr($bigarray[0], 0, 26) == "# LimeSurvey Question Dump" || substr($bigarray[0], 0, 27) == "# PHPSurveyor Question Dump") - { // Wow.. this seems to be a >1.0 version file - these files carry the version information to read in line two - $importversion=substr($bigarray[1], 12, 3); - } -else // unknown file - show error message - { - $importquestion .= "".$clang->gT("Error")."
    \n"; - $importquestion .= $clang->gT("This file is not a LimeSurvey question file. Import failed.")."

    \n"; - $importquestion .= "
    \n"; - $importquestion .= "\n\n"; - unlink($the_full_file_path); - return; - } - -if ($importversion != $dbversionnumber) -{ - $importquestion .= "".$clang->gT("Error")."
    \n"; - $importquestion .= $clang->gT("Sorry, importing questions is limited to the same version. Import failed.")."

    \n"; - $importquestion .= "
    \n"; - $importquestion .= "\n\n"; - unlink($the_full_file_path); - return; -} - -for ($i=0; $i<9; $i++) //skipping the first lines that are not needed -{ - unset($bigarray[$i]); -} -$bigarray = array_values($bigarray); - -//QUESTIONS -if (array_search("# ANSWERS TABLE\n", $bigarray)) -{ - $stoppoint = array_search("# ANSWERS TABLE\n", $bigarray); -} -elseif (array_search("# ANSWERS TABLE\r\n", $bigarray)) -{ - $stoppoint = array_search("# ANSWERS TABLE\r\n", $bigarray); -} -else -{ - $stoppoint = count($bigarray)-1; -} -for ($i=0; $i<=$stoppoint+1; $i++) -{ - if ($i<$stoppoint-2) {$questionarray[] = $bigarray[$i];} - unset($bigarray[$i]); -} -$bigarray = array_values($bigarray); - -//ANSWERS -if (array_search("# LABELSETS TABLE\n", $bigarray)) -{ - $stoppoint = array_search("# LABELSETS TABLE\n", $bigarray); -} -elseif (array_search("# LABELSETS TABLE\r\n", $bigarray)) -{ - $stoppoint = array_search("# LABELSETS TABLE\r\n", $bigarray); -} -else -{ - $stoppoint = count($bigarray)-1; -} -for ($i=0; $i<=$stoppoint+1; $i++) -{ - if ($i<$stoppoint-2) {$answerarray[] = str_replace("`default`", "`default_value`", $bigarray[$i]);} - unset($bigarray[$i]); -} -$bigarray = array_values($bigarray); - -//LABELSETS -if (array_search("# LABELS TABLE\n", $bigarray)) -{ - $stoppoint = array_search("# LABELS TABLE\n", $bigarray); -} -elseif (array_search("# LABELS TABLE\r\n", $bigarray)) -{ - $stoppoint = array_search("# LABELS TABLE\r\n", $bigarray); -} -else -{ - $stoppoint = count($bigarray)-1; -} -for ($i=0; $i<=$stoppoint+1; $i++) -{ - if ($i<$stoppoint-2) {$labelsetsarray[] = $bigarray[$i];} - unset($bigarray[$i]); -} -$bigarray = array_values($bigarray); - -//LABELS -if (array_search("# QUESTION_ATTRIBUTES TABLE\n", $bigarray)) -{ - $stoppoint = array_search("# QUESTION_ATTRIBUTES TABLE\n", $bigarray); -} -elseif (array_search("# QUESTION_ATTRIBUTES TABLE\r\n", $bigarray)) -{ - $stoppoint = array_search("# QUESTION_ATTRIBUTES TABLE\r\n", $bigarray); -} -else -{ - $stoppoint = count($bigarray)-1; -} -for ($i=0; $i<=$stoppoint+1; $i++) -{ - if ($i<$stoppoint-2) {$labelsarray[] = $bigarray[$i];} - unset($bigarray[$i]); -} -$bigarray = array_values($bigarray); - -//Question_attributes -if (!isset($noconditions) || $noconditions != "Y") -{ - $stoppoint = count($bigarray); - for ($i=0; $i<=$stoppoint+1; $i++) - { - if ($i<$stoppoint-1) {$question_attributesarray[] = $bigarray[$i];} - unset($bigarray[$i]); - } -} -$bigarray = array_values($bigarray); - -if (isset($questionarray)) {$countquestions = count($questionarray)-1;} else {$countquestions=0;} -if (isset($answerarray)) - { - $answerfieldnames=convertCSVRowToArray($answerarray[0],',','"'); - unset($answerarray[0]); - $countanswers = count($answerarray); - } - else {$countanswers=0;} -if (isset($labelsetsarray)) {$countlabelsets = count($labelsetsarray)-1;} else {$countlabelsets=0;} -if (isset($labelsarray)) {$countlabels = count($labelsarray)-1;} else {$countlabels=0;} -if (isset($question_attributesarray)) {$countquestion_attributes = count($question_attributesarray)-1;} else {$countquestion_attributes=0;} - -$languagesSupported = array(); // this array will keep all the languages supported for the survey - -// Let's check that imported objects support at least the survey's baselang -$langcode = GetBaseLanguageFromSurveyID($postsid); - -$languagesSupported[$langcode] = 1; // adds the base language to the list of supported languages - -if ($countquestions > 0) -{ - $questionfieldnames = convertCSVRowToArray($questionarray[0],',','"'); - $langfieldnum = array_search("language", $questionfieldnames); - $qidfieldnum = array_search("qid", $questionfieldnames); - $questionssupportbaselang = bDoesImportarraySupportsLanguage($questionarray,Array($qidfieldnum), $langfieldnum,$langcode,true); - if (!$questionssupportbaselang) - { - $importquestion .= "".$clang->gT("Error")."
    \n" - .$clang->gT("You can't import a question which doesn't support the current survey's base language")."

    \n" - ."\n"; - unlink($the_full_file_path); - return; - } -} - -foreach (GetAdditionalLanguagesFromSurveyID($postsid) as $language) -{ - $languagesSupported[$language] = 1; -} - -// Let's assume that if the questions do support tye baselang -// Then the answers do support it as well. -// ==> So the following section is commented for now -//if ($countanswers > 0) -//{ -// $langfieldnum = array_search("language", $answerfieldnames); -// $answercodefilednum1 = array_search("qid", $answerfieldnames); -// $answercodefilednum2 = array_search("code", $answerfieldnames); -// $answercodekeysarr = Array($answercodefilednum1,$answercodefilednum2); -// $answerssupportbaselang = bDoesImportarraySupportsLanguage($answerarray,$answercodekeysarr,$langfieldnum,$langcode); -// if (!$answerssupportbaselang) -// { -// $importquestion .= "".$clang->gT("Error")."
    \n" -// .$clang->gT("You can't import answers which don't support current survey's base language")."

    \n" -// ."\n"; -// return; -// } -// -//} - -if ($countlabelsets > 0) -{ - $labelsetfieldname = convertCSVRowToArray($labelsetsarray[0],',','"'); - $langfieldnum = array_search("languages", $labelsetfieldname); - $lidfilednum = array_search("lid", $labelsetfieldname); - $labelsetssupportbaselang = bDoesImportarraySupportsLanguage($labelsetsarray,Array($lidfilednum),$langfieldnum,$langcode,true); - if (!$labelsetssupportbaselang) - { - $importquestion .= "".$clang->gT("Error")."
    \n" - .$clang->gT("You can't import label sets which don't support the current survey's base language")."

    \n" - ."\n"; - unlink($the_full_file_path); - return; - } -} -// I assume that if a labelset supports the survey's baselang, -// then it's labels do support it as well - -// GET SURVEY AND GROUP DETAILS -$surveyid=$postsid; -$gid=$postgid; -$newsid=$surveyid; -$newgid=$gid; - -//DO ANY LABELSETS FIRST, SO WE CAN KNOW WHAT THEIR NEW LID IS FOR THE QUESTIONS -if (isset($labelsetsarray) && $labelsetsarray) { - $csarray=buildLabelSetCheckSumArray(); // build checksums over all existing labelsets - $count=0; - foreach ($labelsetsarray as $lsa) { - $fieldorders =convertCSVRowToArray($labelsetsarray[0],',','"'); - $fieldcontents=convertCSVRowToArray($lsa,',','"'); - if ($count==0) {$count++; continue;} - - $labelsetrowdata=array_combine($fieldorders,$fieldcontents); - - // Save old labelid - $oldlid=$labelsetrowdata['lid']; - // set the new language - unset($labelsetrowdata['lid']); - $newvalues=array_values($labelsetrowdata); - $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly - $lsainsert = "INSERT INTO {$dbprefix}labelsets (".implode(',',array_keys($labelsetrowdata)).") VALUES (".implode(',',$newvalues).")"; //handle db prefix - $lsiresult=$connect->Execute($lsainsert); - - // Get the new insert id for the labels inside this labelset - $newlid=$connect->Insert_ID("{$dbprefix}labelsets","lid"); - - if ($labelsarray) { - $count=0; - foreach ($labelsarray as $la) { - $lfieldorders =convertCSVRowToArray($labelsarray[0],',','"'); - $lfieldcontents=convertCSVRowToArray($la,',','"'); - if ($count==0) {$count++; continue;} - - // Combine into one array with keys and values since its easier to handle - $labelrowdata=array_combine($lfieldorders,$lfieldcontents); - $labellid=$labelrowdata['lid']; - if ($labellid == $oldlid) { - $labelrowdata['lid']=$newlid; - - // translate internal links - $labelrowdata['title']=translink('label', $oldlid, $newlid, $labelrowdata['title']); - - $newvalues=array_values($labelrowdata); - $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly - $lainsert = "INSERT INTO {$dbprefix}labels (".implode(',',array_keys($labelrowdata)).") VALUES (".implode(',',$newvalues).")"; //handle db prefix - $liresult=$connect->Execute($lainsert); - } - } - } - - //CHECK FOR DUPLICATE LABELSETS - $thisset=""; - $query2 = "SELECT code, title, sortorder, language - FROM {$dbprefix}labels - WHERE lid=".$newlid." - ORDER BY language, sortorder, code"; - $result2 = db_execute_num($query2) or safe_die("Died querying labelset $lid
    $query2
    ".$connect->ErrorMsg()); - while($row2=$result2->FetchRow()) - { - $thisset .= implode('.', $row2); - } // while - $newcs=dechex(crc32($thisset)*1); - unset($lsmatch); - if (isset($csarray)) - { - foreach($csarray as $key=>$val) - { - if ($val == $newcs) - { - $lsmatch=$key; - } - } - } - if (isset($lsmatch)) - { - //There is a matching labelset. So, we will delete this one and refer - //to the matched one. - $query = "DELETE FROM {$dbprefix}labels WHERE lid=$newlid"; - $result=$connect->Execute($query) or safe_die("Couldn't delete labels
    $query
    ".$connect->ErrorMsg()); - $query = "DELETE FROM {$dbprefix}labelsets WHERE lid=$newlid"; - $result=$connect->Execute($query) or safe_die("Couldn't delete labelset
    $query
    ".$connect->ErrorMsg()); - $newlid=$lsmatch; - } - else - { - //There isn't a matching labelset, add this checksum to the $csarray array - $csarray[$newlid]=$newcs; - } - //END CHECK FOR DUPLICATES - $labelreplacements[]=array($oldlid, $newlid); - } -} - - - -// QUESTIONS, THEN ANSWERS FOR QUESTIONS IN A NESTED FORMAT! -if (isset($questionarray) && $questionarray) { - $qafieldorders=convertCSVRowToArray($questionarray[0],',','"'); - unset($questionarray[0]); - - //Assuming we will only import one question at a time we will now find out the maximum question order in this group - //and save it for later - $qmaxqo = "SELECT MAX(question_order) AS maxqo FROM ".db_table_name('questions')." WHERE sid=$newsid AND gid=$newgid"; - $qres = db_execute_assoc($qmaxqo) or safe_die ($clang->gT("Error").": Failed to find out maximum question order value
    \n$qmaxqo
    \n".$connect->ErrorMsg()); - $qrow=$qres->FetchRow(); - $newquestionorder=$qrow['maxqo']+1; - - foreach ($questionarray as $qa) { - $qacfieldcontents=convertCSVRowToArray($qa,',','"'); - $newfieldcontents=$qacfieldcontents; - $questionrowdata=array_combine($qafieldorders,$qacfieldcontents); - if (isset($languagesSupported[$questionrowdata["language"]])) - { - $oldqid = $questionrowdata['qid']; - $oldsid = $questionrowdata['sid']; - $oldgid = $questionrowdata['gid']; - - // Remove qid field if there is no newqid; and set it to newqid if it's set - if (!isset($newqid)) - unset($questionrowdata['qid']); - else - $questionrowdata['qid'] = $newqid; - - $questionrowdata["sid"] = $newsid; - $questionrowdata["gid"] = $newgid; - $questionrowdata["question_order"] = $newquestionorder; - - - // Now we will fix up the label id - $type = $questionrowdata["type"]; //Get the type - if ($type == "F" || $type == "H" || $type == "W" || $type == "Z") - {//IF this is a flexible label array, update the lid entry - if (isset($labelreplacements)) { - foreach ($labelreplacements as $lrp) { - if ($lrp[0] == $questionrowdata["lid"]) { - $questionrowdata["lid"]=$lrp[1]; - } - } - } - } - $other = $questionrowdata["other"]; //Get 'other' field value - $oldlid = $questionrowdata["lid"]; - $questionrowdata=array_map('convertCsvreturn2return', $questionrowdata); - - // translate internal links - $questionrowdata['title']=translink('survey', $oldsid, $newsid, $questionrowdata['title']); - $questionrowdata['question']=translink('survey', $oldsid, $newsid, $questionrowdata['question']); - $questionrowdata['help']=translink('survey', $oldsid, $newsid, $questionrowdata['help']); - - $newvalues=array_values($questionrowdata); - $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly - $qinsert = "INSERT INTO {$dbprefix}questions (".implode(',',array_keys($questionrowdata)).") VALUES (".implode(',',$newvalues).")"; - $qres = $connect->Execute($qinsert) or safe_die ($clang->gT("Error").": Failed to insert question
    \n$qinsert
    \n".$connect->ErrorMsg()); - - // set the newqid only if is not set - if (!isset($newqid)) - $newqid=$connect->Insert_ID("{$dbprefix}questions","qid"); - } - } - - //NOW DO ANSWERS FOR THIS QID - Is called just once and only if there was a question - if (isset($answerarray) && $answerarray) { - foreach ($answerarray as $aa) { - $answerfieldcontents=convertCSVRowToArray($aa,',','"'); - $answerrowdata=array_combine($answerfieldnames,$answerfieldcontents); - if (isset($languagesSupported[$answerrowdata["language"]])) - { - $code=$answerrowdata["code"]; - $thisqid=$answerrowdata["qid"]; - $answerrowdata["qid"]=$newqid; - - // translate internal links - $answerrowdata['answer']=translink('survey', $oldsid, $newsid, $answerrowdata['answer']); - - $newvalues=array_values($answerrowdata); - $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly - $ainsert = "INSERT INTO {$dbprefix}answers (".implode(',',array_keys($answerrowdata)).") VALUES (".implode(',',$newvalues).")"; - $ares = $connect->Execute($ainsert) or safe_die ($clang->gT("Error").": Failed to insert answer
    \n$ainsert
    \n".$connect->ErrorMsg()); - } - } - } - - // Finally the question attributes - Is called just once and only if there was a question - if (isset($question_attributesarray) && $question_attributesarray) {//ONLY DO THIS IF THERE ARE QUESTION_ATTRIBUES - $fieldorders =convertCSVRowToArray($question_attributesarray[0],',','"'); - unset($question_attributesarray[0]); - foreach ($question_attributesarray as $qar) { - $fieldcontents=convertCSVRowToArray($qar,',','"'); - $qarowdata=array_combine($fieldorders,$fieldcontents); - $qarowdata["qid"]=$newqid; - unset($qarowdata["qaid"]); - - $newvalues=array_values($qarowdata); - $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly - $qainsert = "INSERT INTO {$dbprefix}question_attributes (".implode(',',array_keys($qarowdata)).") VALUES (".implode(',',$newvalues).")"; - $result=$connect->Execute($qainsert) or safe_die ("Couldn't insert question_attribute
    $qainsert
    ".$connect->ErrorMsg()); - } - } - -} - - -$importquestion .= "".$clang->gT("Success")."

    \n" -."".$clang->gT("Question Import Summary")."
    \n" -."\t
  • ".$clang->gT("Questions").": "; -if (isset($countquestions)) {$importquestion .= $countquestions;} -$importquestion .= "
  • \n" -."\t
  • ".$clang->gT("Answers").": "; -if (isset($countanswers)) {$importquestion .= $countanswers;} -$importquestion .= "
  • \n" -."\t
  • ".$clang->gT("Label Sets").": "; -if (isset($countlabelsets)) {$importquestion .= $countlabelsets;} -$importquestion .= " ("; -if (isset($countlabels)) {$importquestion .= $countlabels;} -$importquestion .= ")
  • \n"; -$importquestion .= "\t
  • ".$clang->gT("Question Attributes:"); -if (isset($countquestion_attributes)) {$importquestion .= $countquestion_attributes;} -$importquestion .= "

  • \n"; - -$importquestion .= "".$clang->gT("Question import is complete.")."
     \n" -."
    \n"; - - -unlink($the_full_file_path); - - -?> +
    \n" +."\n" +."\t\n" +."\t
    " +.$clang->gT("Import Question")."
    \n"; + +$the_full_file_path = $tempdir . "/" . $_FILES['the_file']['name']; + +if (!@move_uploaded_file($_FILES['the_file']['tmp_name'], $the_full_file_path)) +{ + $importquestion .= "".$clang->gT("Error")."
    \n"; + $importquestion .= sprintf ($clang->gT("An error occurred uploading your file. This may be caused by incorrect permissions in your %s folder."),$tempdir)."

    \n" + ."\n" + ."
    \n"; + unlink($the_full_file_path); + return; +} + +// validate that we have a SID and GID +if (!returnglobal('sid')) +{ + $importquestion .= $clang->gT("No SID (Survey) has been provided. Cannot import question.")."

    \n" + ."\n" + ."
    \n"; + unlink($the_full_file_path); + return; +} +else +{ + $postsid=returnglobal('sid'); +} + +if (!returnglobal('gid')) +{ + $importquestion .= $clang->gT("No GID (Group) has been provided. Cannot import question")."

    \n" + ."\n"; + unlink($the_full_file_path); + return; +} +else +{ + $postgid=returnglobal('gid'); +} + +// IF WE GOT THIS FAR, THEN THE FILE HAS BEEN UPLOADED SUCCESFULLY +$importquestion .= "".$clang->gT("Success")."
    \n" +.$clang->gT("File upload succeeded.")."

    \n" +.$clang->gT("Reading file..")."\n"; +$handle = fopen($the_full_file_path, "r"); +while (!feof($handle)) +{ + $buffer = fgets($handle, 10240); //To allow for very long survey welcomes (up to 10k) + $bigarray[] = $buffer; +} +fclose($handle); + +// Now we try to determine the dataformat of the survey file. +if ((substr($bigarray[1], 0, 24) == "# SURVEYOR QUESTION DUMP")&& (substr($bigarray[4], 0, 29) == "# http://www.phpsurveyor.org/")) +{ + $importversion = 100; // version 1.0 file +} +elseif + ((substr($bigarray[1], 0, 24) == "# SURVEYOR QUESTION DUMP")&& (substr($bigarray[4], 0, 37) == "# http://phpsurveyor.sourceforge.net/")) +{ + $importversion = 99; // Version 0.99 file or older - carries a different URL +} +elseif + (substr($bigarray[0], 0, 26) == "# LimeSurvey Question Dump" || substr($bigarray[0], 0, 27) == "# PHPSurveyor Question Dump") + { // Wow.. this seems to be a >1.0 version file - these files carry the version information to read in line two + $importversion=substr($bigarray[1], 12, 3); + } +else // unknown file - show error message + { + $importquestion .= "".$clang->gT("Error")."
    \n"; + $importquestion .= $clang->gT("This file is not a LimeSurvey question file. Import failed.")."

    \n"; + $importquestion .= "\n"; + $importquestion .= "\n\n"; + unlink($the_full_file_path); + return; + } + +for ($i=0; $i<9; $i++) //skipping the first lines that are not needed +{ + unset($bigarray[$i]); +} +$bigarray = array_values($bigarray); + +//QUESTIONS +if (array_search("# ANSWERS TABLE\n", $bigarray)) +{ + $stoppoint = array_search("# ANSWERS TABLE\n", $bigarray); +} +elseif (array_search("# ANSWERS TABLE\r\n", $bigarray)) +{ + $stoppoint = array_search("# ANSWERS TABLE\r\n", $bigarray); +} +else +{ + $stoppoint = count($bigarray)-1; +} +for ($i=0; $i<=$stoppoint+1; $i++) +{ + if ($i<$stoppoint-2) {$questionarray[] = $bigarray[$i];} + unset($bigarray[$i]); +} +$bigarray = array_values($bigarray); + +//ANSWERS +if (array_search("# LABELSETS TABLE\n", $bigarray)) +{ + $stoppoint = array_search("# LABELSETS TABLE\n", $bigarray); +} +elseif (array_search("# LABELSETS TABLE\r\n", $bigarray)) +{ + $stoppoint = array_search("# LABELSETS TABLE\r\n", $bigarray); +} +else +{ + $stoppoint = count($bigarray)-1; +} +for ($i=0; $i<=$stoppoint+1; $i++) +{ + if ($i<$stoppoint-2) {$answerarray[] = str_replace("`default`", "`default_value`", $bigarray[$i]);} + unset($bigarray[$i]); +} +$bigarray = array_values($bigarray); + +//LABELSETS +if (array_search("# LABELS TABLE\n", $bigarray)) +{ + $stoppoint = array_search("# LABELS TABLE\n", $bigarray); +} +elseif (array_search("# LABELS TABLE\r\n", $bigarray)) +{ + $stoppoint = array_search("# LABELS TABLE\r\n", $bigarray); +} +else +{ + $stoppoint = count($bigarray)-1; +} +for ($i=0; $i<=$stoppoint+1; $i++) +{ + if ($i<$stoppoint-2) {$labelsetsarray[] = $bigarray[$i];} + unset($bigarray[$i]); +} +$bigarray = array_values($bigarray); + +//LABELS +if (array_search("# QUESTION_ATTRIBUTES TABLE\n", $bigarray)) +{ + $stoppoint = array_search("# QUESTION_ATTRIBUTES TABLE\n", $bigarray); +} +elseif (array_search("# QUESTION_ATTRIBUTES TABLE\r\n", $bigarray)) +{ + $stoppoint = array_search("# QUESTION_ATTRIBUTES TABLE\r\n", $bigarray); +} +else +{ + $stoppoint = count($bigarray)-1; +} +for ($i=0; $i<=$stoppoint+1; $i++) +{ + if ($i<$stoppoint-2) {$labelsarray[] = $bigarray[$i];} + unset($bigarray[$i]); +} +$bigarray = array_values($bigarray); + +//Question_attributes +if (!isset($noconditions) || $noconditions != "Y") +{ + $stoppoint = count($bigarray); + for ($i=0; $i<=$stoppoint+1; $i++) + { + if ($i<$stoppoint-1) {$question_attributesarray[] = $bigarray[$i];} + unset($bigarray[$i]); + } +} +$bigarray = array_values($bigarray); + +if (isset($questionarray)) {$countquestions = count($questionarray)-1;} else {$countquestions=0;} +if (isset($answerarray)) + { + $answerfieldnames=convertCSVRowToArray($answerarray[0],',','"'); + unset($answerarray[0]); + $countanswers = count($answerarray); + } + else {$countanswers=0;} +if (isset($labelsetsarray)) {$countlabelsets = count($labelsetsarray)-1;} else {$countlabelsets=0;} +if (isset($labelsarray)) {$countlabels = count($labelsarray)-1;} else {$countlabels=0;} +if (isset($question_attributesarray)) {$countquestion_attributes = count($question_attributesarray)-1;} else {$countquestion_attributes=0;} + +$languagesSupported = array(); // this array will keep all the languages supported for the survey + +// Let's check that imported objects support at least the survey's baselang +$langcode = GetBaseLanguageFromSurveyID($postsid); + +$languagesSupported[$langcode] = 1; // adds the base language to the list of supported languages + +if ($countquestions > 0) +{ + $questionfieldnames = convertCSVRowToArray($questionarray[0],',','"'); + $langfieldnum = array_search("language", $questionfieldnames); + $qidfieldnum = array_search("qid", $questionfieldnames); + $questionssupportbaselang = bDoesImportarraySupportsLanguage($questionarray,Array($qidfieldnum), $langfieldnum,$langcode,true); + if (!$questionssupportbaselang) + { + $importquestion .= "".$clang->gT("Error")."
    \n" + .$clang->gT("You can't import a question which doesn't support the current survey's base language")."

    \n" + ."\n"; + unlink($the_full_file_path); + return; + } +} + +foreach (GetAdditionalLanguagesFromSurveyID($postsid) as $language) +{ + $languagesSupported[$language] = 1; +} + +// Let's assume that if the questions do support tye baselang +// Then the answers do support it as well. +// ==> So the following section is commented for now +//if ($countanswers > 0) +//{ +// $langfieldnum = array_search("language", $answerfieldnames); +// $answercodefilednum1 = array_search("qid", $answerfieldnames); +// $answercodefilednum2 = array_search("code", $answerfieldnames); +// $answercodekeysarr = Array($answercodefilednum1,$answercodefilednum2); +// $answerssupportbaselang = bDoesImportarraySupportsLanguage($answerarray,$answercodekeysarr,$langfieldnum,$langcode); +// if (!$answerssupportbaselang) +// { +// $importquestion .= "".$clang->gT("Error")."
    \n" +// .$clang->gT("You can't import answers which don't support current survey's base language")."

    \n" +// ."\n"; +// return; +// } +// +//} + +if ($countlabelsets > 0) +{ + $labelsetfieldname = convertCSVRowToArray($labelsetsarray[0],',','"'); + $langfieldnum = array_search("languages", $labelsetfieldname); + $lidfilednum = array_search("lid", $labelsetfieldname); + $labelsetssupportbaselang = bDoesImportarraySupportsLanguage($labelsetsarray,Array($lidfilednum),$langfieldnum,$langcode,true); + if (!$labelsetssupportbaselang) + { + $importquestion .= "".$clang->gT("Error")."
    \n" + .$clang->gT("You can't import label sets which don't support the current survey's base language")."

    \n" + ."\n"; + unlink($the_full_file_path); + return; + } +} +// I assume that if a labelset supports the survey's baselang, +// then it's labels do support it as well + +// GET SURVEY AND GROUP DETAILS +$surveyid=$postsid; +$gid=$postgid; +$newsid=$surveyid; +$newgid=$gid; + +//DO ANY LABELSETS FIRST, SO WE CAN KNOW WHAT THEIR NEW LID IS FOR THE QUESTIONS +if (isset($labelsetsarray) && $labelsetsarray) { + $csarray=buildLabelSetCheckSumArray(); // build checksums over all existing labelsets + $count=0; + foreach ($labelsetsarray as $lsa) { + $fieldorders =convertCSVRowToArray($labelsetsarray[0],',','"'); + $fieldcontents=convertCSVRowToArray($lsa,',','"'); + if ($count==0) {$count++; continue;} + + $labelsetrowdata=array_combine($fieldorders,$fieldcontents); + + // Save old labelid + $oldlid=$labelsetrowdata['lid']; + // set the new language + unset($labelsetrowdata['lid']); + $newvalues=array_values($labelsetrowdata); + $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly + $lsainsert = "INSERT INTO {$dbprefix}labelsets (".implode(',',array_keys($labelsetrowdata)).") VALUES (".implode(',',$newvalues).")"; //handle db prefix + $lsiresult=$connect->Execute($lsainsert); + + // Get the new insert id for the labels inside this labelset + $newlid=$connect->Insert_ID("{$dbprefix}labelsets","lid"); + + if ($labelsarray) { + $count=0; + foreach ($labelsarray as $la) { + $lfieldorders =convertCSVRowToArray($labelsarray[0],',','"'); + $lfieldcontents=convertCSVRowToArray($la,',','"'); + if ($count==0) {$count++; continue;} + + // Combine into one array with keys and values since its easier to handle + $labelrowdata=array_combine($lfieldorders,$lfieldcontents); + $labellid=$labelrowdata['lid']; + if ($importversion<=132) + { + $labelrowdata["assessment_value"]=(int)$labelrowdata["code"]; + } + + if ($labellid == $oldlid) { + $labelrowdata['lid']=$newlid; + + // translate internal links + $labelrowdata['title']=translink('label', $oldlid, $newlid, $labelrowdata['title']); + + $newvalues=array_values($labelrowdata); + $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly + $lainsert = "INSERT INTO {$dbprefix}labels (".implode(',',array_keys($labelrowdata)).") VALUES (".implode(',',$newvalues).")"; //handle db prefix + $liresult=$connect->Execute($lainsert); + } + } + } + + //CHECK FOR DUPLICATE LABELSETS + $thisset=""; + $query2 = "SELECT code, title, sortorder, language, assessment_value + FROM {$dbprefix}labels + WHERE lid=".$newlid." + ORDER BY language, sortorder, code"; + $result2 = db_execute_num($query2) or safe_die("Died querying labelset $lid
    $query2
    ".$connect->ErrorMsg()); + while($row2=$result2->FetchRow()) + { + $thisset .= implode('.', $row2); + } // while + $newcs=dechex(crc32($thisset)*1); + unset($lsmatch); + if (isset($csarray)) + { + foreach($csarray as $key=>$val) + { + if ($val == $newcs) + { + $lsmatch=$key; + } + } + } + if (isset($lsmatch)) + { + //There is a matching labelset. So, we will delete this one and refer + //to the matched one. + $query = "DELETE FROM {$dbprefix}labels WHERE lid=$newlid"; + $result=$connect->Execute($query) or safe_die("Couldn't delete labels
    $query
    ".$connect->ErrorMsg()); + $query = "DELETE FROM {$dbprefix}labelsets WHERE lid=$newlid"; + $result=$connect->Execute($query) or safe_die("Couldn't delete labelset
    $query
    ".$connect->ErrorMsg()); + $newlid=$lsmatch; + } + else + { + //There isn't a matching labelset, add this checksum to the $csarray array + $csarray[$newlid]=$newcs; + } + //END CHECK FOR DUPLICATES + $labelreplacements[]=array($oldlid, $newlid); + } +} + + + +// QUESTIONS, THEN ANSWERS FOR QUESTIONS IN A NESTED FORMAT! +if (isset($questionarray) && $questionarray) { + $qafieldorders=convertCSVRowToArray($questionarray[0],',','"'); + unset($questionarray[0]); + + //Assuming we will only import one question at a time we will now find out the maximum question order in this group + //and save it for later + $qmaxqo = "SELECT MAX(question_order) AS maxqo FROM ".db_table_name('questions')." WHERE sid=$newsid AND gid=$newgid"; + $qres = db_execute_assoc($qmaxqo) or safe_die ($clang->gT("Error").": Failed to find out maximum question order value
    \n$qmaxqo
    \n".$connect->ErrorMsg()); + $qrow=$qres->FetchRow(); + $newquestionorder=$qrow['maxqo']+1; + + foreach ($questionarray as $qa) { + $qacfieldcontents=convertCSVRowToArray($qa,',','"'); + $newfieldcontents=$qacfieldcontents; + $questionrowdata=array_combine($qafieldorders,$qacfieldcontents); + if (isset($languagesSupported[$questionrowdata["language"]])) + { + $oldqid = $questionrowdata['qid']; + $oldsid = $questionrowdata['sid']; + $oldgid = $questionrowdata['gid']; + + // Remove qid field if there is no newqid; and set it to newqid if it's set + if (!isset($newqid)) + unset($questionrowdata['qid']); + else + $questionrowdata['qid'] = $newqid; + + $questionrowdata["sid"] = $newsid; + $questionrowdata["gid"] = $newgid; + $questionrowdata["question_order"] = $newquestionorder; + + + // Now we will fix up the label id + $type = $questionrowdata["type"]; //Get the type + if ($type == "F" || $type == "H" || $type == "W" || + $type == "Z" || $type == "1" || $type == ":" || + $type == ";" ) + {//IF this is a flexible label array, update the lid entry + if (isset($labelreplacements)) { + foreach ($labelreplacements as $lrp) { + if ($lrp[0] == $questionrowdata["lid"]) { + $questionrowdata["lid"]=$lrp[1]; + } + if ($lrp[0] == $questionrowdata["lid1"]) { + $questionrowdata["lid1"]=$lrp[1]; + } + } + } + } + $other = $questionrowdata["other"]; //Get 'other' field value + $oldlid = $questionrowdata["lid"]; + $questionrowdata=array_map('convertCsvreturn2return', $questionrowdata); + + // translate internal links + $questionrowdata['title']=translink('survey', $oldsid, $newsid, $questionrowdata['title']); + $questionrowdata['question']=translink('survey', $oldsid, $newsid, $questionrowdata['question']); + $questionrowdata['help']=translink('survey', $oldsid, $newsid, $questionrowdata['help']); + + $newvalues=array_values($questionrowdata); + $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly + $qinsert = "INSERT INTO {$dbprefix}questions (".implode(',',array_keys($questionrowdata)).") VALUES (".implode(',',$newvalues).")"; + $qres = $connect->Execute($qinsert) or safe_die ($clang->gT("Error").": Failed to insert question
    \n$qinsert
    \n".$connect->ErrorMsg()); + + // set the newqid only if is not set + if (!isset($newqid)) + $newqid=$connect->Insert_ID("{$dbprefix}questions","qid"); + } + } + + //NOW DO ANSWERS FOR THIS QID - Is called just once and only if there was a question + if (isset($answerarray) && $answerarray) { + foreach ($answerarray as $aa) { + $answerfieldcontents=convertCSVRowToArray($aa,',','"'); + $answerrowdata=array_combine($answerfieldnames,$answerfieldcontents); + if ($answerrowdata===false) + { + $importquestion.='
    '.$clang->gT("Faulty line in import - fields and data don't match").":".implode(',',$answerfieldcontents); + } + if (isset($languagesSupported[$answerrowdata["language"]])) + { + $code=$answerrowdata["code"]; + $thisqid=$answerrowdata["qid"]; + $answerrowdata["qid"]=$newqid; + + // translate internal links + $answerrowdata['answer']=translink('survey', $oldsid, $newsid, $answerrowdata['answer']); + if ($importversion<=132) + { + $answerrowdata["assessment_value"]=(int)$answerrowdata["code"]; + } + $newvalues=array_values($answerrowdata); + $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly + $ainsert = "INSERT INTO {$dbprefix}answers (".implode(',',array_keys($answerrowdata)).") VALUES (".implode(',',$newvalues).")"; + $ares = $connect->Execute($ainsert) or safe_die ($clang->gT("Error").": Failed to insert answer
    \n$ainsert
    \n".$connect->ErrorMsg()); + } + } + } + + // Finally the question attributes - Is called just once and only if there was a question + if (isset($question_attributesarray) && $question_attributesarray) {//ONLY DO THIS IF THERE ARE QUESTION_ATTRIBUES + $fieldorders =convertCSVRowToArray($question_attributesarray[0],',','"'); + unset($question_attributesarray[0]); + foreach ($question_attributesarray as $qar) { + $fieldcontents=convertCSVRowToArray($qar,',','"'); + $qarowdata=array_combine($fieldorders,$fieldcontents); + $qarowdata["qid"]=$newqid; + unset($qarowdata["qaid"]); + + $newvalues=array_values($qarowdata); + $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly + $qainsert = "INSERT INTO {$dbprefix}question_attributes (".implode(',',array_keys($qarowdata)).") VALUES (".implode(',',$newvalues).")"; + $result=$connect->Execute($qainsert) or safe_die ("Couldn't insert question_attribute
    $qainsert
    ".$connect->ErrorMsg()); + } + } + +} + + +$importquestion .= "".$clang->gT("Success")."

    \n" +."".$clang->gT("Question Import Summary")."
    \n" +."\t
  • ".$clang->gT("Questions").": "; +if (isset($countquestions)) {$importquestion .= $countquestions;} +$importquestion .= "
  • \n" +."\t
  • ".$clang->gT("Answers").": "; +if (isset($countanswers)) {$importquestion .= $countanswers;} +$importquestion .= "
  • \n" +."\t
  • ".$clang->gT("Label Sets").": "; +if (isset($countlabelsets)) {$importquestion .= $countlabelsets;} +$importquestion .= " ("; +if (isset($countlabels)) {$importquestion .= $countlabels;} +$importquestion .= ")
  • \n"; +$importquestion .= "\t
  • ".$clang->gT("Question Attributes:"); +if (isset($countquestion_attributes)) {$importquestion .= $countquestion_attributes;} +$importquestion .= "

  • \n"; + +$importquestion .= "".$clang->gT("Question import is complete.")."
     \n"; +$importquestion .= "".$clang->gT("Go to question")."
    \n"; +$importquestion .= "
    \n"; + + +unlink($the_full_file_path); + + +?> diff --git a/include/limesurvey/admin/importsurvey.php b/include/limesurvey/admin/importsurvey.php index 69b46388..8f41d51e 100644 --- a/include/limesurvey/admin/importsurvey.php +++ b/include/limesurvey/admin/importsurvey.php @@ -1,1265 +1,1423 @@ -1.0 version file - these files carry the version information to read in line two - $importversion=substr($bigarray[1], 12, 3); - } -else // unknown file - show error message - { - if ($importingfrom == "http") - { - $importsurvey .= "".$clang->gT("Error")."
    \n"; - $importsurvey .= $clang->gT("This file is not a LimeSurvey survey file. Import failed.")."

    \n"; - $importsurvey .= "\n"; - $importsurvey .= "\n\n"; - unlink($the_full_file_path); - return; - } - else - { - echo $clang->gT("This file is not a LimeSurvey survey file. Import failed.")."\n"; - return; - } - } - - -// okay.. now lets drop the first 9 lines and get to the data -// This works for all versions -for ($i=0; $i<9; $i++) -{ - unset($bigarray[$i]); -} -$bigarray = array_values($bigarray); - - - -//SURVEYS -if (array_search("# GROUPS TABLE\n", $bigarray)) -{ - $stoppoint = array_search("# GROUPS TABLE\n", $bigarray); -} -elseif (array_search("# GROUPS TABLE\r\n", $bigarray)) -{ - $stoppoint = array_search("# GROUPS TABLE\r\n", $bigarray); -} -for ($i=0; $i<=$stoppoint+1; $i++) -{ - if ($i<$stoppoint-2) {$surveyarray[] = $bigarray[$i];} - unset($bigarray[$i]); -} -$bigarray = array_values($bigarray); - -//GROUPS -if (array_search("# QUESTIONS TABLE\n", $bigarray)) -{ - $stoppoint = array_search("# QUESTIONS TABLE\n", $bigarray); -} -elseif (array_search("# QUESTIONS TABLE\r\n", $bigarray)) -{ - $stoppoint = array_search("# QUESTIONS TABLE\r\n", $bigarray); -} -else -{ - $stoppoint = count($bigarray)-1; -} -for ($i=0; $i<=$stoppoint+1; $i++) -{ - if ($i<$stoppoint-2) {$grouparray[] = $bigarray[$i];} - unset($bigarray[$i]); -} -$bigarray = array_values($bigarray); - -//QUESTIONS -if (array_search("# ANSWERS TABLE\n", $bigarray)) -{ - $stoppoint = array_search("# ANSWERS TABLE\n", $bigarray); -} -elseif (array_search("# ANSWERS TABLE\r\n", $bigarray)) -{ - $stoppoint = array_search("# ANSWERS TABLE\r\n", $bigarray); -} -else -{ - $stoppoint = count($bigarray)-1; -} -for ($i=0; $i<=$stoppoint+1; $i++) -{ - if ($i<$stoppoint-2) - { - $questionarray[] = $bigarray[$i]; - } - unset($bigarray[$i]); -} -$bigarray = array_values($bigarray); - -//ANSWERS -if (array_search("# CONDITIONS TABLE\n", $bigarray)) -{ - $stoppoint = array_search("# CONDITIONS TABLE\n", $bigarray); -} -elseif (array_search("# CONDITIONS TABLE\r\n", $bigarray)) -{ - $stoppoint = array_search("# CONDITIONS TABLE\r\n", $bigarray); -} -else -{ - $stoppoint = count($bigarray)-1; -} -for ($i=0; $i<=$stoppoint+1; $i++) -{ - if ($i<$stoppoint-2) - { - $answerarray[] = str_replace("`default`", "`default_value`", $bigarray[$i]); - } - unset($bigarray[$i]); -} -$bigarray = array_values($bigarray); - -//CONDITIONS -if (array_search("# LABELSETS TABLE\n", $bigarray)) -{ - $stoppoint = array_search("# LABELSETS TABLE\n", $bigarray); -} -elseif (array_search("# LABELSETS TABLE\r\n", $bigarray)) -{ - $stoppoint = array_search("# LABELSETS TABLE\r\n", $bigarray); -} -else -{ //There is no labelsets information, so presumably this is a pre-0.98rc3 survey. - $stoppoint = count($bigarray); -} -for ($i=0; $i<=$stoppoint+1; $i++) -{ - if ($i<$stoppoint-2) {$conditionsarray[] = $bigarray[$i];} - unset($bigarray[$i]); -} -$bigarray = array_values($bigarray); - -//LABELSETS -if (array_search("# LABELS TABLE\n", $bigarray)) -{ - $stoppoint = array_search("# LABELS TABLE\n", $bigarray); -} -elseif (array_search("# LABELS TABLE\r\n", $bigarray)) -{ - $stoppoint = array_search("# LABELS TABLE\r\n", $bigarray); -} -else -{ - $stoppoint = count($bigarray)-1; -} -for ($i=0; $i<=$stoppoint+1; $i++) -{ - if ($i<$stoppoint-2) {$labelsetsarray[] = $bigarray[$i];} - unset($bigarray[$i]); -} -$bigarray = array_values($bigarray); - -//LABELS -if (array_search("# QUESTION_ATTRIBUTES TABLE\n", $bigarray)) -{ - $stoppoint = array_search("# QUESTION_ATTRIBUTES TABLE\n", $bigarray); -} -elseif (array_search("# QUESTION_ATTRIBUTES TABLE\r\n", $bigarray)) -{ - $stoppoint = array_search("# QUESTION_ATTRIBUTES TABLE\r\n", $bigarray); -} -else -{ - $stoppoint = count($bigarray)-1; -} - -for ($i=0; $i<=$stoppoint+1; $i++) -{ - if ($i<$stoppoint-2) {$labelsarray[] = $bigarray[$i];} - unset($bigarray[$i]); -} -$bigarray = array_values($bigarray); - -//QUESTION_ATTRIBUTES -if (array_search("# ASSESSMENTS TABLE\n", $bigarray)) -{ - $stoppoint = array_search("# ASSESSMENTS TABLE\n", $bigarray); -} -elseif (array_search("# ASSESSMENTS TABLE\r\n", $bigarray)) -{ - $stoppoint = array_search("# ASSESSMENTS TABLE\r\n", $bigarray); -} -else -{ - $stoppoint = count($bigarray)-1; -} -for ($i=0; $i<=$stoppoint+1; $i++) -{ - if ($i<$stoppoint-2) {$question_attributesarray[] = $bigarray[$i];} - unset($bigarray[$i]); -} -$bigarray = array_values($bigarray); - - -//ASSESSMENTS -if (array_search("# SURVEYS_LANGUAGESETTINGS TABLE\n", $bigarray)) -{ - $stoppoint = array_search("# SURVEYS_LANGUAGESETTINGS TABLE\n", $bigarray); -} -elseif (array_search("# SURVEYS_LANGUAGESETTINGS TABLE\r\n", $bigarray)) -{ - $stoppoint = array_search("# SURVEYS_LANGUAGESETTINGS TABLE\r\n", $bigarray); -} -else -{ - $stoppoint = count($bigarray)-1; -} -for ($i=0; $i<=$stoppoint+1; $i++) -{ -// if ($i<$stoppoint-2 || $i==count($bigarray)-1) - if ($i<$stoppoint-2) - { - $assessmentsarray[] = $bigarray[$i]; - } - unset($bigarray[$i]); -} -$bigarray = array_values($bigarray); - -//LANGAUGE SETTINGS -if (array_search("# QUOTA TABLE\n", $bigarray)) -{ - $stoppoint = array_search("# QUOTA TABLE\n", $bigarray); -} -elseif (array_search("# QUOTA TABLE\r\n", $bigarray)) -{ - $stoppoint = array_search("# QUOTA TABLE\r\n", $bigarray); -} -else -{ - $stoppoint = count($bigarray)-1; -} -for ($i=0; $i<=$stoppoint+1; $i++) -{ -// if ($i<$stoppoint-2 || $i==count($bigarray)-1) - //$bigarray[$i]= trim($bigarray[$i]); - if (isset($bigarray[$i]) && (trim($bigarray[$i])!='')) - { - if (strpos($bigarray[$i],"#")===0) - { - unset($bigarray[$i]); - unset($bigarray[$i+1]); - unset($bigarray[$i+2]); - break ; - } - else - { - $surveylsarray[] = $bigarray[$i]; - } - } - unset($bigarray[$i]); -} -$bigarray = array_values($bigarray); - -//QUOTA -if (array_search("# QUOTA_MEMBERS TABLE\n", $bigarray)) -{ - $stoppoint = array_search("# QUOTA_MEMBERS TABLE\n", $bigarray); -} -elseif (array_search("# QUOTA_MEMBERS TABLE\r\n", $bigarray)) -{ - $stoppoint = array_search("# QUOTA_MEMBERS TABLE\r\n", $bigarray); -} -else -{ - $stoppoint = count($bigarray)-1; -} -for ($i=0; $i<=$stoppoint+1; $i++) -{ -// if ($i<$stoppoint-2 || $i==count($bigarray)-1) - if ($i<$stoppoint-2) - { - $quotaarray[] = $bigarray[$i]; - } - unset($bigarray[$i]); -} -$bigarray = array_values($bigarray); - -//Survey Language Settings -$stoppoint = count($bigarray)-1; -for ($i=0; $i<$stoppoint-1; $i++) -{ - if ($i<=$stoppoint) {$quotamembersarray[] = $bigarray[$i];} - unset($bigarray[$i]); -} -$bigarray = array_values($bigarray); - -if (isset($surveyarray)) {$countsurveys = count($surveyarray);} else {$countsurveys = 0;} -if (isset($surveylsarray)) {$countlanguages = count($surveylsarray)-1;} else {$countlanguages = 1;} -if (isset($grouparray)) {$countgroups = count($grouparray);} else {$countgroups = 0;} -if (isset($questionarray)) {$countquestions = count($questionarray);} else {$countquestions=0;} -if (isset($answerarray)) {$countanswers = count($answerarray);} else {$countanswers=0;} -if (isset($conditionsarray)) {$countconditions = count($conditionsarray);} else {$countconditions=0;} -if (isset($labelsetsarray)) {$countlabelsets = count($labelsetsarray);} else {$countlabelsets=0;} -if (isset($question_attributesarray)) {$countquestion_attributes = count($question_attributesarray);} else {$countquestion_attributes=0;} -if (isset($assessmentsarray)) {$countassessments=count($assessmentsarray);} else {$countassessments=0;} -if (isset($quotaarray)) {$countquota=count($quotaarray);} else {$countquota=0;} - -// CREATE SURVEY - -if ($importversion>=111) -{ - if ($countsurveys>0){$countsurveys--;}; - if ($countanswers>0){$countanswers=($countanswers-1)/$countlanguages;}; - if ($countgroups>0){$countgroups=($countgroups-1)/$countlanguages;}; - if ($countquestions>0){$countquestions=($countquestions-1)/$countlanguages;}; - if ($countassessments>0){$countassessments--;}; - if ($countconditions>0){$countconditions--;}; - if ($countlabelsets>0){$countlabelsets--;}; - if ($countquestion_attributes>0){$countquestion_attributes--;}; - if ($countquota>0){$countquota--;}; - $sfieldorders =convertCSVRowToArray($surveyarray[0],',','"'); - $sfieldcontents=convertCSVRowToArray($surveyarray[1],',','"'); -} -else - { - $sfieldorders=convertToArray($surveyarray[0], "`, `", "(`", "`)"); - $sfieldcontents=convertToArray($surveyarray[0], "', '", "('", "')"); - } -$surveyrowdata=array_combine($sfieldorders,$sfieldcontents); -$surveyid=$surveyrowdata["sid"]; - - -if (!$surveyid) -{ - if ($importingfrom == "http") - { - $importsurvey .= "
    ".$clang->gT("Error")."
    \n"; - $importsurvey .= $clang->gT("Import of this survey file failed")."
    \n"; - $importsurvey .= $clang->gT("File does not contain LimeSurvey data in the correct format.")."
    \n"; //Couldn't find the SID - cannot continue - $importsurvey .= "\n"; - $importsurvey .= "\n\n"; - unlink($the_full_file_path); //Delete the uploaded file - return; - } - else - { - echo $clang->gT("Import of this survey file failed")."\n".$clang->gT("File does not contain LimeSurvey data in the correct format.")."\n"; - return; - } -} - -// Use the existing surveyid if it does not already exists -// This allows the URL links to the survey to keep working because the sid did not change - $newsid = $surveyid; - $isquery = "SELECT sid FROM {$dbprefix}surveys WHERE sid=$newsid"; - $isresult = db_execute_assoc($isquery); - if ($isresult->RecordCount()>0) - { - // Get new random ids until one is found that is not used - do - { - $newsid = getRandomID(); - $isquery = "SELECT sid FROM {$dbprefix}surveys WHERE sid=$newsid"; - $isresult = db_execute_assoc($isquery); - } - while ($isresult->RecordCount()>0); - } - - -$insert=$surveyarray[0]; -if ($importversion>=111) -{ - $sfieldorders =convertCSVRowToArray($surveyarray[0],',','"'); - $sfieldcontents=convertCSVRowToArray($surveyarray[1],',','"'); -} -else - { - $sfieldorders=convertToArray($surveyarray[0], "`, `", "(`", "`)"); - $sfieldcontents=convertToArray($surveyarray[0], "', '", "('", "')"); - } -$surveyrowdata=array_combine($sfieldorders,$sfieldcontents); -// Set new owner ID -$surveyrowdata['owner_id']=$_SESSION['loginID']; -// Set new survey ID -$surveyrowdata['sid']=$newsid; -$surveyrowdata['active']='N'; - - -if ($importversion<=100) -// find the old language field and replace its contents with the new language shortcuts - { - $oldlanguage=$surveyrowdata['language']; - $newlanguage='en'; //Default - switch ($oldlanguage) - { - case "bulgarian": - $newlanguage='bg'; - break; - case "chinese-simplified": - $newlanguage='zh-Hans'; - break; - case "chinese-traditional": - $newlanguage='zh-Hant-HK'; - break; - case "croatian": - $newlanguage='hr'; - break; - case "danish": - $newlanguage='da'; - break; - case "dutch": - $newlanguage='nl'; - break; - case "english": - $newlanguage='en'; - break; - case "french": - $newlanguage='fr'; - break; - case "german-informal": - $newlanguage='de-informal'; - break; - case "german": - $newlanguage='de'; - break; - case "greek": - $newlanguage='el'; - break; - case "hungarian": - $newlanguage='hu'; - break; - case "italian": - $newlanguage='it'; - break; - case "japanese": - $newlanguage='ja'; - break; - case "lithuanian": - $newlanguage='lt'; - break; - case "norwegian": - $newlanguage='nb'; - break; - case "portuguese": - $newlanguage='pt'; - break; - case "romanian": - $newlanguage='ro'; - break; - case "russian": - $newlanguage='ru'; - break; - case "slovenian": - $newlanguage='sl'; - break; - case "spanish": - $newlanguage='es'; - break; - case "swedish": - $newlanguage='sv'; - break; - } - - $surveyrowdata['language']=$newlanguage; - - // copy the survey row data - - // now prepare the languagesettings table and drop according values from the survey array - $surveylsrowdata=array(); - $surveylsrowdata['surveyls_survey_id']=$newsid; - $surveylsrowdata['surveyls_language']=$newlanguage; - $surveylsrowdata['surveyls_title']=$surveyrowdata['short_title']; - $surveylsrowdata['surveyls_description']=$surveyrowdata['description']; - $surveylsrowdata['surveyls_welcometext']=$surveyrowdata['welcome']; - $surveylsrowdata['surveyls_urldescription']=$surveyrowdata['urldescrip']; - $surveylsrowdata['surveyls_email_invite_subj']=$surveyrowdata['email_invite_subj']; - $surveylsrowdata['surveyls_email_invite']=$surveyrowdata['email_invite']; - $surveylsrowdata['surveyls_email_remind_subj']=$surveyrowdata['email_remind_subj']; - $surveylsrowdata['surveyls_email_remind']=$surveyrowdata['email_remind']; - $surveylsrowdata['surveyls_email_register_subj']=$surveyrowdata['email_register_subj']; - $surveylsrowdata['surveyls_email_register']=$surveyrowdata['email_register']; - $surveylsrowdata['surveyls_email_confirm_subj']=$surveyrowdata['email_confirm_subj']; - $surveylsrowdata['surveyls_email_confirm']=$surveyrowdata['email_confirm']; - unset($surveyrowdata['short_title']); - unset($surveyrowdata['description']); - unset($surveyrowdata['welcome']); - unset($surveyrowdata['urldescrip']); - unset($surveyrowdata['email_invite_subj']); - unset($surveyrowdata['email_invite']); - unset($surveyrowdata['email_remind_subj']); - unset($surveyrowdata['email_remind']); - unset($surveyrowdata['email_register_subj']); - unset($surveyrowdata['email_register']); - unset($surveyrowdata['email_confirm_subj']); - unset($surveyrowdata['email_confirm']); - - - // translate internal links - $surveylsrowdata['surveyls_title']=translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_title']); - $surveylsrowdata['surveyls_description']=translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_description']); - $surveylsrowdata['surveyls_welcometext']=translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_welcometext']); - $surveylsrowdata['surveyls_urldescription']=translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_urldescription']); - $surveylsrowdata['surveyls_email_invite']=translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_email_invite']); - $surveylsrowdata['surveyls_email_remind']=translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_email_remind']); - $surveylsrowdata['surveyls_email_register']=translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_email_register']); - $surveylsrowdata['surveyls_email_confirm']=translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_email_confirm']); - - - - // import the survey language-specific settings - $values=array_values($surveylsrowdata); - $values=array_map(array(&$connect, "qstr"),$values); // quote everything accordingly - $insert = "insert INTO {$dbprefix}surveys_languagesettings (".implode(',',array_keys($surveylsrowdata)).") VALUES (".implode(',',$values).")"; //handle db prefix - $iresult = $connect->Execute($insert) or safe_die("
    ".$clang->gT("Import of this survey file failed")."
    \n[$insert]
    {$surveyarray[0]}

    \n" . $connect->ErrorMsg()); - - - - } - - - -if (isset($surveyrowdata['datecreated'])) {$surveyrowdata['datecreated']=$connect->BindTimeStamp($surveyrowdata['datecreated']);} -unset($surveyrowdata['expires']); -$surveyrowdata['bounce_email']=$surveyrowdata['adminemail']; -if (!isset($surveyrowdata['datecreated']) || $surveyrowdata['datecreated']=='' || $surveyrowdata['datecreated']=='null') {$surveyrowdata['datecreated']=$connect->BindTimeStamp(date_shift(date("Y-m-d H:i:s"), "Y-m-d", $timeadjust));} - -$values=array_values($surveyrowdata); -$values=array_map(array(&$connect, "qstr"),$values); // quote everything accordingly -$insert = "INSERT INTO {$dbprefix}surveys (".implode(',',array_keys($surveyrowdata)).") VALUES (".implode(',',$values).")"; //handle db prefix -$iresult = $connect->Execute($insert) or safe_die("
    ".$clang->gT("Import of this survey file failed")."
    \n[$insert]
    {$surveyarray[0]}

    \n" . $connect->ErrorMsg()); - -$oldsid=$surveyid; - -// Now import the survey language settings -if ($importversion>=111) -{ - $fieldorders=convertCSVRowToArray($surveylsarray[0],',','"'); - unset($surveylsarray[0]); - foreach ($surveylsarray as $slsrow) { - $fieldcontents=convertCSVRowToArray($slsrow,',','"'); - $surveylsrowdata=array_combine($fieldorders,$fieldcontents); - // convert back the '\'.'n' cahr from the CSV file to true return char "\n" - $surveylsrowdata=array_map('convertCsvreturn2return', $surveylsrowdata); - // Convert the \n return char from welcometext to
    - - // translate internal links - $surveylsrowdata['surveyls_title']=translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_title']); - $surveylsrowdata['surveyls_description']=translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_description']); - $surveylsrowdata['surveyls_welcometext']=translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_welcometext']); - $surveylsrowdata['surveyls_urldescription']=translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_urldescription']); - $surveylsrowdata['surveyls_email_invite']=translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_email_invite']); - $surveylsrowdata['surveyls_email_remind']=translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_email_remind']); - $surveylsrowdata['surveyls_email_register']=translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_email_register']); - $surveylsrowdata['surveyls_email_confirm']=translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_email_confirm']); - - $surveylsrowdata['surveyls_survey_id']=$newsid; - $newvalues=array_values($surveylsrowdata); - $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly - $lsainsert = "INSERT INTO {$dbprefix}surveys_languagesettings (".implode(',',array_keys($surveylsrowdata)).") VALUES (".implode(',',$newvalues).")"; //handle db prefix - $lsiresult=$connect->Execute($lsainsert) or safe_die("
    ".$clang->gT("Import of this survey file failed")."
    \n[$lsainsert]
    \n" . $connect->ErrorMsg() ); - } - -} - - -// DO SURVEY_RIGHTS -$isrquery = "INSERT INTO {$dbprefix}surveys_rights VALUES($newsid,".$_SESSION['loginID'].",1,1,1,1,1,1)"; -@$isrresult = $connect->Execute($isrquery); -$deniedcountlabelsets =0; - - -//DO ANY LABELSETS FIRST, SO WE CAN KNOW WHAT THEIR NEW LID IS FOR THE QUESTIONS -if (isset($labelsetsarray) && $labelsetsarray) { - $csarray=buildLabelSetCheckSumArray(); // build checksums over all existing labelsets - $count=0; - foreach ($labelsetsarray as $lsa) { - - if ($importversion>=111) - { - $fieldorders =convertCSVRowToArray($labelsetsarray[0],',','"'); - $fieldcontents=convertCSVRowToArray($lsa,',','"'); - if ($count==0) {$count++; continue;} - } - else - { - $fieldorders=convertToArray($lsa, "`, `", "(`", "`)"); - $fieldcontents=convertToArray($lsa, "', '", "('", "')"); - } - $labelsetrowdata=array_combine($fieldorders,$fieldcontents); - - // Save old labelid - $oldlid=$labelsetrowdata['lid']; - // set the new language - if ($importversion<=100) - { - $labelsetrowdata['languages']=$newlanguage; - } - unset($labelsetrowdata['lid']); - $newvalues=array_values($labelsetrowdata); - $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly - $lsainsert = "insert INTO {$dbprefix}labelsets (".implode(',',array_keys($labelsetrowdata)).") VALUES (".implode(',',$newvalues).")"; //handle db prefix - $lsiresult=$connect->Execute($lsainsert); - - // Get the new insert id for the labels inside this labelset - $newlid=$connect->Insert_ID("{$dbprefix}labelsets","lid"); - -// $importsurvey .= "OLDLID: $oldlid NEWLID: $newlid"; -// For debugging label import - - if ($labelsarray) { - $count=0; - foreach ($labelsarray as $la) { - if ($importversion>=111) - { - $lfieldorders =convertCSVRowToArray($labelsarray[0],',','"'); - $lfieldcontents=convertCSVRowToArray($la,',','"'); - if ($count==0) {$count++; continue;} - } - else - { - //Get field names into array - $lfieldorders=convertToArray($la, "`, `", "(`", "`)"); - //Get field values into array - $lfieldcontents=convertToArray($la, "', '", "('", "')"); - } - // Combine into one array with keys and values since its easier to handle - $labelrowdata=array_combine($lfieldorders,$lfieldcontents); - $labellid=$labelrowdata['lid']; - if ($importversion<=100) - { - $labelrowdata['language']=$newlanguage; - } - if ($labellid == $oldlid) { - $labelrowdata['lid']=$newlid; - - // translate internal links - $labelrowdata['title']=translink('label', $oldlid, $newlid, $labelrowdata['title']); - - $newvalues=array_values($labelrowdata); - $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly - $lainsert = "insert INTO {$dbprefix}labels (".implode(',',array_keys($labelrowdata)).") VALUES (".implode(',',$newvalues).")"; //handle db prefix - $liresult=$connect->Execute($lainsert); - - } - } - } - - //CHECK FOR DUPLICATE LABELSETS - $thisset=""; - - /* - $query2 = "SELECT code, title, sortorder, language - FROM {$dbprefix}labels - WHERE lid=".$newlid." - ORDER BY language, sortorder, code"; - $result2 = db_execute_num($query2) or safe_die("Died querying labelset $lid
    $query2
    ".$connect->ErrorMsg()); - while($row2=$result2->FetchRow()) - { - $thisset .= implode('.', $row2); - } // while - $newcs=dechex(crc32($thisset)*1); - unset($lsmatch); - if (isset($csarray)) - { - foreach($csarray as $key=>$val) - { - if ($val == $newcs) - { - $lsmatch=$key; - } - } - } - if (isset($lsmatch) || ($_SESSION['USER_RIGHT_MANAGE_LABEL'] != 1)) - { - //There is a matching labelset or the user is not allowed to edit labels - - // So, we will delete this one and refer to the matched one. - $query = "DELETE FROM {$dbprefix}labels WHERE lid=$newlid"; - $result=$connect->Execute($query) or safe_die("Couldn't delete labels
    $query
    ".$connect->ErrorMsg()); - $query = "DELETE FROM {$dbprefix}labelsets WHERE lid=$newlid"; - $result=$connect->Execute($query) or safe_die("Couldn't delete labelset
    $query
    ".$connect->ErrorMsg()); - if (isset($lsmatch)) {$newlid=$lsmatch;} - else {++$deniedcountlabelsets;--$countlabelsets;} - } - else - { - //There isn't a matching labelset, add this checksum to the $csarray array - $csarray[$newlid]=$newcs; - } - //END CHECK FOR DUPLICATES - */ - - $labelreplacements[]=array($oldlid, $newlid); - } -} - -$importwarning = ""; // used to save the warnings while processing questions -$qtypes = getqtypelist("" ,"array"); - -// DO GROUPS, QUESTIONS FOR GROUPS, THEN ANSWERS FOR QUESTIONS IN A NESTED FORMAT! -if (isset($grouparray) && $grouparray) { - $count=0; - $currentgid=''; - foreach ($grouparray as $ga) { - if ($importversion>=111) - { - $gafieldorders =convertCSVRowToArray($grouparray[0],',','"'); - $gacfieldcontents=convertCSVRowToArray($ga,',','"'); - if ($count==0) {$count++; continue;} - } - else - { - //Get field names into array - $gafieldorders=convertToArray($ga, "`, `", "(`", "`)"); - //Get field values into array - $gacfieldcontents=convertToArray($ga, "', '", "('", "')"); - } - $grouprowdata=array_combine($gafieldorders,$gacfieldcontents); - // remember group id - if ($currentgid=='' || ($currentgid!=$grouprowdata['gid'])) {$currentgid=$grouprowdata['gid'];$newgroup=true;} - else - if ($currentgid==$grouprowdata['gid']) {$newgroup=false;} - $gid=$grouprowdata['gid']; - $gsid=$grouprowdata['sid']; - //Now an additional integrity check if there are any groups not belonging into this survey - if ($gsid != $surveyid) - { - if ($importingfrom == "http") - { - $importsurvey .= "
    \n".$clang->gT("Error")."" - ."
    \n".$clang->gT("A group in the CSV/SQL file is not part of the same survey. The import of the survey was stopped.")."

    \n"; - } - else - { - echo $clang->gT("Error").": A group in the CSV/SQL file is not part of the same Survey. The import of the survey was stopped.\n"; - } - return; - } - //remove the old group id - if ($newgroup) {unset($grouprowdata['gid']);} - else {$grouprowdata['gid']=$newgid;} - //replace old surveyid by new surveyid - $grouprowdata['sid']=$newsid; - // Version <=100 dont have a language field yet so we set it now - if ($importversion<=100) - { - $grouprowdata['language']=$newlanguage; - } - $oldgid=$gid; // save it for later - $grouprowdata=array_map('convertCsvreturn2return', $grouprowdata); - - // translate internal links - $grouprowdata['group_name']=translink('survey', $surveyid, $newsid, $grouprowdata['group_name']); - $grouprowdata['description']=translink('survey', $surveyid, $newsid, $grouprowdata['description']); - - $newvalues=array_values($grouprowdata); - - $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly - $ginsert = "insert INTO {$dbprefix}groups (".implode(',',array_keys($grouprowdata)).") VALUES (".implode(',',$newvalues).")"; - $gres = $connect->Execute($ginsert) or safe_die($clang->gT("Error").": Failed to insert group
    \n$ginsert
    \n".$connect->ErrorMsg()); - //GET NEW GID - if ($newgroup) {$newgid=$connect->Insert_ID("{$dbprefix}groups","gid");} - - //NOW DO NESTED QUESTIONS FOR THIS GID - - if (isset($questionarray) && $questionarray && $newgroup) { - $count=0; - $currentqid=''; - foreach ($questionarray as $qa) { - if ($importversion>=111) - { - $qafieldorders =convertCSVRowToArray($questionarray[0],',','"'); - $qacfieldcontents=convertCSVRowToArray($qa,',','"'); - if ($count==0) {$count++; continue;} - } - else - { - $qafieldorders=convertToArray($qa, "`, `", "(`", "`)"); - $qacfieldcontents=convertToArray($qa, "', '", "('", "')"); - } - $questionrowdata=array_combine($qafieldorders,$qacfieldcontents); - $questionrowdata=array_map('convertCsvreturn2return', $questionrowdata); - - if ($currentqid=='' || ($currentqid!=$questionrowdata['qid'])) {$currentqid=$questionrowdata['qid'];$newquestion=true;} - else - if ($currentqid==$questionrowdata['qid']) {$newquestion=false;} - - if (!array_key_exists($questionrowdata["type"], $qtypes)) - { - $questionrowdata["type"] = strtoupper($questionrowdata["type"]); - if (!array_key_exists($questionrowdata["type"], $qtypes)) - { - $importwarning .= "
  • " . $clang->gT("Question") . " \"{$questionrowdata["title"]} - {$questionrowdata["question"]}\" " . $clang->gT("was NOT imported because the question type is unknown.") . "
  • "; - $countquestions--; - continue; - } - else // the upper case worked well $qtypes[$questionrowdata["type"]] - { - $importwarning .= "
  • " . $clang->gT("Question") . " \"{$questionrowdata["title"]} - {$questionrowdata["question"]}\" " . sprintf($clang->gT("was imported but the type was set to '%s' because it is the most similiar one."),$qtypes[$questionrowdata["type"]]) . "
  • "; - } - } - - - $thisgid=$questionrowdata['gid']; - if ($thisgid == $gid) { - $qid = $questionrowdata['qid']; - // Remove qid field - if ($newquestion) {unset($questionrowdata['qid']);} - else {$questionrowdata['qid']=$newqid;} - - $questionrowdata["sid"] = $newsid; - $questionrowdata["gid"] = $newgid; - // Version <=100 doesn't have a language field yet so we set it now - if ($importversion<=100) - { - $questionrowdata['language']=$newlanguage; - } - $oldqid=$qid; - if (!isset($questionrowdata["lid1"])) - { - $questionrowdata["lid1"]=0; - } - // Now we will fix up the label id - $type = $questionrowdata["type"]; //Get the type - if ($type == "F" || $type == "H" || $type == "W" || $type == "Z" || $type == "1") - {//IF this is a flexible label array, update the lid entry - if (isset($labelreplacements)) { - foreach ($labelreplacements as $lrp) { - if ($lrp[0] == $questionrowdata["lid"]) - { - $questionrowdata["lid"]=$lrp[1]; - } - if ($lrp[0] == $questionrowdata["lid1"]) - { - $questionrowdata["lid1"]=$lrp[1]; - } - } - } - } - if (!isset($questionrowdata["question_order"]) || $questionrowdata["question_order"]=='') {$questionrowdata["question_order"]=0;} - $other = $questionrowdata["other"]; //Get 'other' field value - - // translate internal links - $questionrowdata['title']=translink('survey', $surveyid, $newsid, $questionrowdata['title']); - $questionrowdata['question']=translink('survey', $surveyid, $newsid, $questionrowdata['question']); - $questionrowdata['help']=translink('survey', $surveyid, $newsid, $questionrowdata['help']); - - $newvalues=array_values($questionrowdata); - $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly - $qinsert = "insert INTO {$dbprefix}questions (".implode(',',array_keys($questionrowdata)).") VALUES (".implode(',',$newvalues).")"; - $qres = $connect->Execute($qinsert) or safe_die ($clang->gT("Error").": Failed to insert question
    \n$qinsert
    \n".$connect->ErrorMsg()); - if ($newquestion) - { - $newqid=$connect->Insert_ID("{$dbprefix}questions","qid"); - } - - $newrank=0; - $substitutions[]=array($oldsid, $oldgid, $oldqid, $newsid, $newgid, $newqid); - - //NOW DO NESTED ANSWERS FOR THIS QID - if (isset($answerarray) && $answerarray && $newquestion) { - $count=0; - foreach ($answerarray as $aa) { - if ($importversion>=111) - { - $aafieldorders =convertCSVRowToArray($answerarray[0],',','"'); - $aacfieldcontents=convertCSVRowToArray($aa,',','"'); - if ($count==0) {$count++; continue;} - } - else - { - $aafieldorders=convertToArray($aa, "`, `", "(`", "`)"); - $aacfieldcontents=convertToArray($aa, "', '", "('", "')"); - } - $answerrowdata=array_combine($aafieldorders,$aacfieldcontents); - $code=$answerrowdata["code"]; - $thisqid=$answerrowdata["qid"]; - if ($thisqid == $qid) - { - $answerrowdata["qid"]=$newqid; - // Version <=100 doesn't have a language field yet so we set it now - if ($importversion<=100) - { - $answerrowdata['language']=$newlanguage; - } - - // translate internal links - $answerrowdata['answer']=translink('survey', $surveyid, $newsid, $answerrowdata['answer']); - - $newvalues=array_values($answerrowdata); - $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly - $ainsert = "insert INTO {$dbprefix}answers (".implode(',',array_keys($answerrowdata)).") VALUES (".implode(',',$newvalues).")"; - $ares = $connect->Execute($ainsert) or safe_die ($clang->gT("Error").": Failed to insert answer
    \n$ainsert
    \n".$connect->ErrorMsg()); - - if ($type == "M" || $type == "P") { - $fieldnames[]=array("oldcfieldname"=>$oldsid."X".$oldgid."X".$oldqid, - "newcfieldname"=>$newsid."X".$newgid."X".$newqid, - "oldfieldname"=>$oldsid."X".$oldgid."X".$oldqid.$code, - "newfieldname"=>$newsid."X".$newgid."X".$newqid.$code); - if ($type == "P") { - $fieldnames[]=array("oldcfieldname"=>$oldsid."X".$oldgid."X".$oldqid."comment", - "newcfieldname"=>$newsid."X".$newgid."X".$newqid.$code."comment", - "oldfieldname"=>$oldsid."X".$oldgid."X".$oldqid.$code."comment", - "newfieldname"=>$newsid."X".$newgid."X".$newqid.$code."comment"); - } - } - elseif ($type == "A" || $type == "B" || $type == "C" || $type == "F" || $type == "H" || $type == "E" || $type == "Q" || $type == "K" || $type == "1") { - $fieldnames[]=array("oldcfieldname"=>$oldsid."X".$oldgid."X".$oldqid.$code, - "newcfieldname"=>$newsid."X".$newgid."X".$newqid.$code, - "oldfieldname"=>$oldsid."X".$oldgid."X".$oldqid.$code, - "newfieldname"=>$newsid."X".$newgid."X".$newqid.$code); - } - elseif ($type == "R") { - $newrank++; - } - } - } - if (($type == "A" || $type == "B" || $type == "C" || $type == "M" || $type == "P" || $type == "L") && ($other == "Y")) { - $fieldnames[]=array("oldcfieldname"=>$oldsid."X".$oldgid."X".$oldqid."other", - "newcfieldname"=>$newsid."X".$newgid."X".$newqid."other", - "oldfieldname"=>$oldsid."X".$oldgid."X".$oldqid."other", - "newfieldname"=>$newsid."X".$newgid."X".$newqid."other"); - if ($type == "P") { - $fieldnames[]=array("oldcfieldname"=>$oldsid."X".$oldgid."X".$oldqid."othercomment", - "newcfieldname"=>$newsid."X".$newgid."X".$newqid."othercomment", - "oldfieldname"=>$oldsid."X".$oldgid."X".$oldqid."othercomment", - "newfieldname"=>$newsid."X".$newgid."X".$newqid."othercomment"); - } - } - if ($type == "R" && $newrank >0) { - for ($i=1; $i<=$newrank; $i++) { - $fieldnames[]=array("oldcfieldname"=>$oldsid."X".$oldgid."X".$oldqid.$i, - "newcfieldname"=>$newsid."X".$newgid."X".$newqid.$i, - "oldfieldname"=>$oldsid."X".$oldgid."X".$oldqid.$i, - "newfieldname"=>$newsid."X".$newgid."X".$newqid.$i); - } - } - if ($type != "A" && $type != "B" && $type != "C" && $type != "R" && $type != "M" && $type != "P") { - $fieldnames[]=array("oldcfieldname"=>$oldsid."X".$oldgid."X".$oldqid, - "newcfieldname"=>$newsid."X".$newgid."X".$newqid, - "oldfieldname"=>$oldsid."X".$oldgid."X".$oldqid, - "newfieldname"=>$newsid."X".$newgid."X".$newqid); - if ($type == "O") { - $fieldnames[]=array("oldcfieldname"=>$oldsid."X".$oldgid."X".$oldqid."comment", - "newcfieldname"=>$newsid."X".$newgid."X".$newqid."comment", - "oldfieldname"=>$oldsid."X".$oldgid."X".$oldqid."comment", - "newfieldname"=>$newsid."X".$newgid."X".$newqid."comment"); - } - } - } else { - $fieldnames[]=array("oldcfieldname"=>$oldsid."X".$oldgid."X".$oldqid, - "newcfieldname"=>$newsid."X".$newgid."X".$newqid, - "oldfieldname"=>$oldsid."X".$oldgid."X".$oldqid, - "newfieldname"=>$newsid."X".$newgid."X".$newqid); - } - } - } - } - } -} - - // Fix sortorder of the groups - if users removed groups manually from the csv file there would be gaps - fixsortorderGroups(); - //... and for the questions inside the groups - // get all group ids and fix questions inside each group - $gquery = "SELECT gid FROM {$dbprefix}groups where sid=$newsid group by gid ORDER BY gid"; //Get last question added (finds new qid) - $gres = db_execute_assoc($gquery); - while ($grow = $gres->FetchRow()) - { - fixsortorderQuestions(0,$grow['gid']); - } - - //We've built two arrays along the way - one containing the old SID, GID and QIDs - and their NEW equivalents -//and one containing the old 'extended fieldname' and its new equivalent. These are needed to import conditions and question_attributes. -if (isset($question_attributesarray) && $question_attributesarray) {//ONLY DO THIS IF THERE ARE QUESTION_ATTRIBUES - $count=0; - foreach ($question_attributesarray as $qar) { - if ($importversion>=111) - { - $fieldorders =convertCSVRowToArray($question_attributesarray[0],',','"'); - $fieldcontents=convertCSVRowToArray($qar,',','"'); - if ($count==0) {$count++; continue;} - } - else - { - $fieldorders=convertToArray($qar, "`, `", "(`", "`)"); - $fieldcontents=convertToArray($qar, "', '", "('", "')"); - } - $qarowdata=array_combine($fieldorders,$fieldcontents); - $newqid=""; - $oldqid=$qarowdata['qid']; - foreach ($substitutions as $subs) { - if ($oldqid==$subs[2]) {$newqid=$subs[5];} - } - - $qarowdata["qid"]=$newqid; - unset($qarowdata["qaid"]); - - $newvalues=array_values($qarowdata); - $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly - $qainsert = "insert INTO {$dbprefix}question_attributes (".implode(',',array_keys($qarowdata)).") VALUES (".implode(',',$newvalues).")"; - $result=$connect->Execute($qainsert) or safe_die ("Couldn't insert question_attribute
    $qainsert
    ".$connect->ErrorMsg()); - } -} - -if (isset($assessmentsarray) && $assessmentsarray) {//ONLY DO THIS IF THERE ARE QUESTION_ATTRIBUES - $count=0; - foreach ($assessmentsarray as $qar) { - if ($importversion>=111) - { - $fieldorders =convertCSVRowToArray($assessmentsarray[0],',','"'); - $fieldcontents=convertCSVRowToArray($qar,',','"'); - if ($count==0) {$count++; continue;} - } - else - { - $fieldorders=convertToArray($qar, "`, `", "(`", "`)"); - $fieldcontents=convertToArray($qar, "', '", "('", "')"); - } - $asrowdata=array_combine($fieldorders,$fieldcontents); - $oldsid=$asrowdata["sid"]; - $oldgid=$asrowdata["gid"]; - foreach ($substitutions as $subs) { - if ($oldsid==$subs[0]) {$newsid=$subs[3];} - if ($oldgid==$subs[1]) {$newgid=$subs[4];} - } - - $asrowdata["sid"]=$newsid; - $asrowdata["gid"]=$newgid; - unset($asrowdata["id"]); - - - $newvalues=array_values($asrowdata); - $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly - $asinsert = "insert INTO {$dbprefix}assessments (".implode(',',array_keys($asrowdata)).") VALUES (".implode(',',$newvalues).")"; - $result=$connect->Execute($asinsert) or safe_die ("Couldn't insert assessment
    $asinsert
    ".$connect->ErrorMsg()); - - unset($newgid); - } -} - -if (isset($quotaarray) && $quotaarray) {//ONLY DO THIS IF THERE ARE QUOTAS - $count=0; - foreach ($quotaarray as $qar) { - - $fieldorders=convertCSVRowToArray($quotaarray[0],',','"'); - $fieldcontents=convertCSVRowToArray($qar,',','"'); - if ($count==0) {$count++; continue;} - - $asrowdata=array_combine($fieldorders,$fieldcontents); - - $oldsid=$asrowdata["sid"]; - foreach ($substitutions as $subs) { - if ($oldsid==$subs[0]) {$newsid=$subs[3];} - } - - $asrowdata["sid"]=$newsid; - $oldid = $asrowdata["id"]; - unset($asrowdata["id"]); - - $newvalues=array_values($asrowdata); - $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly - - $asinsert = "insert INTO {$dbprefix}quota (".implode(',',array_keys($asrowdata)).") VALUES (".implode(',',$newvalues).")"; - $result=$connect->Execute($asinsert) or safe_die ("Couldn't insert quota
    $asinsert
    ".$connect->ErrorMsg()); - $quotaids[] = array($oldid,$connect->Insert_ID(db_table_name_nq('quota'),"id")); - - } -} - -if (isset($quotamembersarray) && $quotamembersarray) {//ONLY DO THIS IF THERE ARE QUOTAS - $count=0; - foreach ($quotamembersarray as $qar) { - - $fieldorders =convertCSVRowToArray($quotamembersarray[0],',','"'); - $fieldcontents=convertCSVRowToArray($qar,',','"'); - if ($count==0) {$count++; continue;} - - $asrowdata=array_combine($fieldorders,$fieldcontents); - - $oldsid=$asrowdata["sid"]; - $newqid=""; - $newquotaid=""; - $oldqid=$asrowdata['qid']; - $oldquotaid=$asrowdata['quota_id']; - - foreach ($substitutions as $subs) { - if ($oldsid==$subs[0]) {$newsid=$subs[3];} - if ($oldqid==$subs[2]) {$newqid=$subs[5];} - } - - foreach ($quotaids as $quotaid) { - if ($oldquotaid==$quotaid[0]) {$newquotaid=$quotaid[1];} - } - - $asrowdata["sid"]=$newsid; - $asrowdata["qid"]=$newqid; - $asrowdata["quota_id"]=$newquotaid; - unset($asrowdata["id"]); - - $newvalues=array_values($asrowdata); - $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly - - $asinsert = "insert INTO {$dbprefix}quota_members (".implode(',',array_keys($asrowdata)).") VALUES (".implode(',',$newvalues).")"; - $result=$connect->Execute($asinsert) or safe_die ("Couldn't insert quota
    $asinsert
    ".$connect->ErrorMsg()); - - } -} - -if (isset($conditionsarray) && $conditionsarray) {//ONLY DO THIS IF THERE ARE CONDITIONS! - $count='0'; - foreach ($conditionsarray as $car) { - if ($importversion>=111) - { - $fieldorders =convertCSVRowToArray($conditionsarray[0],',','"'); - $fieldcontents=convertCSVRowToArray($car,',','"'); - if ($count==0) {$count++; continue;} - } - else - { - $fieldorders=convertToArray($car, "`, `", "(`", "`)"); - $fieldcontents=convertToArray($car, "', '", "('", "')"); - } - $conditionrowdata=array_combine($fieldorders,$fieldcontents); - - $oldcid=$conditionrowdata["cid"]; - $oldqid=$conditionrowdata["qid"]; - $oldcfieldname=$conditionrowdata["cfieldname"]; - $oldcqid=$conditionrowdata["cqid"]; - $thisvalue=$conditionrowdata["value"]; - - foreach ($substitutions as $subs) { - if ($oldqid==$subs[2]) {$newqid=$subs[5];} - if ($oldcqid==$subs[2]) {$newcqid=$subs[5];} - } - foreach($fieldnames as $fns) { - //if the $fns['oldcfieldname'] is not the same as $fns['oldfieldname'] then this is a multiple type question - if ($fns['oldcfieldname'] == $fns['oldfieldname']) { //The normal method - non multiples - if ($oldcfieldname==$fns['oldcfieldname']) { - $newcfieldname=$fns['newcfieldname']; - } - } else { - if ($oldcfieldname == $fns['oldcfieldname'] && $oldcfieldname.$thisvalue == $fns['oldfieldname']) { - $newcfieldname=$fns['newcfieldname']; - } - } - } - if (!isset($newcfieldname)) {$newcfieldname="";} - unset($conditionrowdata["cid"]); - $conditionrowdata["qid"]=$newqid; - $conditionrowdata["cfieldname"]=$newcfieldname; - - if (isset($newcqid)) { - $conditionrowdata["cqid"]=$newcqid; - if (!isset($conditionrowdata["method"]) || trim($conditionrowdata["method"])=='') - { - $conditionrowdata["method"]='=='; - } - $newvalues=array_values($conditionrowdata); - $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly - $conditioninsert = "insert INTO {$dbprefix}conditions (".implode(',',array_keys($conditionrowdata)).") VALUES (".implode(',',$newvalues).")"; - $result=$connect->Execute($conditioninsert) or safe_die ("Couldn't insert condition
    $conditioninsert
    ".$connect->ErrorMsg()); - } else { - $importsurvey .= "Condition for $oldqid skipped ($oldcqid does not exist)
    "; - if ($importingfrom != "http") echo "Condition for $oldqid skipped ($oldcqid does not exist)\n"; - } - unset($newcqid); - } -} - -// Translate INSERTANS codes -if (isset($fieldnames)) -{ - transInsertAns($newsid,$oldsid,$fieldnames); -} - - - - -if ($importingfrom == "http") -{ - $importsurvey .= "
    \n".$clang->gT("Success")."

    \n"; - $importsurvey .= "".$clang->gT("Survey Import Summary")."
    \n"; - $importsurvey .= "
      \n\t
    • ".$clang->gT("Surveys").": $countsurveys
    • \n"; - if ($importversion>=111) - { - $importsurvey .= "\t
    • ".$clang->gT("Languages").": $countlanguages
    • \n"; - } - $importsurvey .= "\t
    • ".$clang->gT("Groups").": $countgroups
    • \n"; - $importsurvey .= "\t
    • ".$clang->gT("Questions").": $countquestions
    • \n"; - $importsurvey .= "\t
    • ".$clang->gT("Answers").": $countanswers
    • \n"; - $importsurvey .= "\t
    • ".$clang->gT("Conditions").": $countconditions
    • \n"; - $importsurvey .= "\t
    • ".$clang->gT("Label Sets").": $countlabelsets
    • \n"; - if ($deniedcountlabelsets>0) - { - $importsurvey .= "\t
    • ".$clang->gT("Not imported Label Sets").": $deniedcountlabelsets ".$clang->gT("(Label Sets were not imported since you do not have the permission to create new label sets.)")."
    • \n"; - } - $importsurvey .= "\t
    • ".$clang->gT("Question Attributes").": $countquestion_attributes
    • \n"; - $importsurvey .= "\t
    • ".$clang->gT("Assessments").": $countassessments
    • \n"; - $importsurvey .= "\t
    • ".$clang->gT("Quotas").": $countquota
    • \n
    \n"; - - $importsurvey .= "".$clang->gT("Import of Survey is completed.")."
    \n"; - if ($importwarning != "") $importsurvey .= "
    ".$clang->gT("Warnings").":
      " . $importwarning . "

    \n"; - $importsurvey .= "
    \n"; - unlink($the_full_file_path); - unset ($surveyid); // Crazy but necessary because else the html script will search for user rights -} -else -{ - echo "\n".$clang->gT("Success")."\n\n"; - echo $clang->gT("Survey Import Summary")."\n"; - echo $clang->gT("Surveys").": $countsurveys\n"; - if ($importversion>=111) - { - echo $clang->gT("Languages").": $countlanguages\n"; - } - echo $clang->gT("Groups").": $countgroups\n"; - echo $clang->gT("Questions").": $countquestions\n"; - echo $clang->gT("Answers").": $countanswers\n"; - echo $clang->gT("Conditions").": $countconditions\n"; - echo $clang->gT("Label Sets").": $countlabelsets\n"; - if ($deniedcountlabelsets>0) echo $clang->gT("Not imported Label Sets").": $deniedcountlabelsets (".$clang->gT("(Label Sets were not imported since you do not have the permission to create new label sets.)"); - echo $clang->gT("Question Attributes").": $countquestion_attributes\n"; - echo $clang->gT("Assessments").": $countassessments\n\n"; - - echo $clang->gT("Import of Survey is completed.")."\n"; - if ($importwarning != "") echo "\n".$clang->gT("Warnings").":\n" . $importwarning . "\n"; - $surveyid=$newsid; - -} - -?> +1.0 version file - these files carry the version information to read in line two + $importversion=substr($bigarray[1], 12, 3); + } +else // unknown file - show error message + { + if ($importingfrom == "http") + { + $importsurvey .= "".$clang->gT("Error")."
    \n"; + $importsurvey .= $clang->gT("This file is not a LimeSurvey survey file. Import failed.")."

    \n"; + $importsurvey .= "\n"; + $importsurvey .= "\n\n"; + unlink($the_full_file_path); + return; + } + else + { + echo $clang->gT("This file is not a LimeSurvey survey file. Import failed.")."\n"; + return; + } + } + + +// okay.. now lets drop the first 9 lines and get to the data +// This works for all versions +for ($i=0; $i<9; $i++) +{ + unset($bigarray[$i]); +} +$bigarray = array_values($bigarray); + + + +//SURVEYS +if (array_search("# GROUPS TABLE\n", $bigarray)) +{ + $stoppoint = array_search("# GROUPS TABLE\n", $bigarray); +} +elseif (array_search("# GROUPS TABLE\r\n", $bigarray)) +{ + $stoppoint = array_search("# GROUPS TABLE\r\n", $bigarray); +} +for ($i=0; $i<=$stoppoint+1; $i++) +{ + if ($i<$stoppoint-2) {$surveyarray[] = $bigarray[$i];} + unset($bigarray[$i]); +} +$bigarray = array_values($bigarray); + +//GROUPS +if (array_search("# QUESTIONS TABLE\n", $bigarray)) +{ + $stoppoint = array_search("# QUESTIONS TABLE\n", $bigarray); +} +elseif (array_search("# QUESTIONS TABLE\r\n", $bigarray)) +{ + $stoppoint = array_search("# QUESTIONS TABLE\r\n", $bigarray); +} +else +{ + $stoppoint = count($bigarray)-1; +} +for ($i=0; $i<=$stoppoint+1; $i++) +{ + if ($i<$stoppoint-2) {$grouparray[] = $bigarray[$i];} + unset($bigarray[$i]); +} +$bigarray = array_values($bigarray); + +//QUESTIONS +if (array_search("# ANSWERS TABLE\n", $bigarray)) +{ + $stoppoint = array_search("# ANSWERS TABLE\n", $bigarray); +} +elseif (array_search("# ANSWERS TABLE\r\n", $bigarray)) +{ + $stoppoint = array_search("# ANSWERS TABLE\r\n", $bigarray); +} +else +{ + $stoppoint = count($bigarray)-1; +} +for ($i=0; $i<=$stoppoint+1; $i++) +{ + if ($i<$stoppoint-2) + { + $questionarray[] = $bigarray[$i]; + } + unset($bigarray[$i]); +} +$bigarray = array_values($bigarray); + +//ANSWERS +if (array_search("# CONDITIONS TABLE\n", $bigarray)) +{ + $stoppoint = array_search("# CONDITIONS TABLE\n", $bigarray); +} +elseif (array_search("# CONDITIONS TABLE\r\n", $bigarray)) +{ + $stoppoint = array_search("# CONDITIONS TABLE\r\n", $bigarray); +} +else +{ + $stoppoint = count($bigarray)-1; +} +for ($i=0; $i<=$stoppoint+1; $i++) +{ + if ($i<$stoppoint-2) + { + $answerarray[] = str_replace("`default`", "`default_value`", $bigarray[$i]); + } + unset($bigarray[$i]); +} +$bigarray = array_values($bigarray); + +//CONDITIONS +if (array_search("# LABELSETS TABLE\n", $bigarray)) +{ + $stoppoint = array_search("# LABELSETS TABLE\n", $bigarray); +} +elseif (array_search("# LABELSETS TABLE\r\n", $bigarray)) +{ + $stoppoint = array_search("# LABELSETS TABLE\r\n", $bigarray); +} +else +{ //There is no labelsets information, so presumably this is a pre-0.98rc3 survey. + $stoppoint = count($bigarray); +} +for ($i=0; $i<=$stoppoint+1; $i++) +{ + if ($i<$stoppoint-2) {$conditionsarray[] = $bigarray[$i];} + unset($bigarray[$i]); +} +$bigarray = array_values($bigarray); + +//LABELSETS +if (array_search("# LABELS TABLE\n", $bigarray)) +{ + $stoppoint = array_search("# LABELS TABLE\n", $bigarray); +} +elseif (array_search("# LABELS TABLE\r\n", $bigarray)) +{ + $stoppoint = array_search("# LABELS TABLE\r\n", $bigarray); +} +else +{ + $stoppoint = count($bigarray)-1; +} +for ($i=0; $i<=$stoppoint+1; $i++) +{ + if ($i<$stoppoint-2) {$labelsetsarray[] = $bigarray[$i];} + unset($bigarray[$i]); +} +$bigarray = array_values($bigarray); + +//LABELS +if (array_search("# QUESTION_ATTRIBUTES TABLE\n", $bigarray)) +{ + $stoppoint = array_search("# QUESTION_ATTRIBUTES TABLE\n", $bigarray); +} +elseif (array_search("# QUESTION_ATTRIBUTES TABLE\r\n", $bigarray)) +{ + $stoppoint = array_search("# QUESTION_ATTRIBUTES TABLE\r\n", $bigarray); +} +else +{ + $stoppoint = count($bigarray)-1; +} + +for ($i=0; $i<=$stoppoint+1; $i++) +{ + if ($i<$stoppoint-2) {$labelsarray[] = $bigarray[$i];} + unset($bigarray[$i]); +} +$bigarray = array_values($bigarray); + +//QUESTION_ATTRIBUTES +if (array_search("# ASSESSMENTS TABLE\n", $bigarray)) +{ + $stoppoint = array_search("# ASSESSMENTS TABLE\n", $bigarray); +} +elseif (array_search("# ASSESSMENTS TABLE\r\n", $bigarray)) +{ + $stoppoint = array_search("# ASSESSMENTS TABLE\r\n", $bigarray); +} +else +{ + $stoppoint = count($bigarray)-1; +} +for ($i=0; $i<=$stoppoint+1; $i++) +{ + if ($i<$stoppoint-2) {$question_attributesarray[] = $bigarray[$i];} + unset($bigarray[$i]); +} +$bigarray = array_values($bigarray); + + +//ASSESSMENTS +if (array_search("# SURVEYS_LANGUAGESETTINGS TABLE\n", $bigarray)) +{ + $stoppoint = array_search("# SURVEYS_LANGUAGESETTINGS TABLE\n", $bigarray); +} +elseif (array_search("# SURVEYS_LANGUAGESETTINGS TABLE\r\n", $bigarray)) +{ + $stoppoint = array_search("# SURVEYS_LANGUAGESETTINGS TABLE\r\n", $bigarray); +} +else +{ + $stoppoint = count($bigarray)-1; +} +for ($i=0; $i<=$stoppoint+1; $i++) +{ +// if ($i<$stoppoint-2 || $i==count($bigarray)-1) + if ($i<$stoppoint-2) + { + $assessmentsarray[] = $bigarray[$i]; + } + unset($bigarray[$i]); +} +$bigarray = array_values($bigarray); + +//LANGAUGE SETTINGS +if (array_search("# QUOTA TABLE\n", $bigarray)) +{ + $stoppoint = array_search("# QUOTA TABLE\n", $bigarray); +} +elseif (array_search("# QUOTA TABLE\r\n", $bigarray)) +{ + $stoppoint = array_search("# QUOTA TABLE\r\n", $bigarray); +} +else +{ + $stoppoint = count($bigarray)-1; +} +for ($i=0; $i<=$stoppoint+1; $i++) +{ +// if ($i<$stoppoint-2 || $i==count($bigarray)-1) + //$bigarray[$i]= trim($bigarray[$i]); + if (isset($bigarray[$i]) && (trim($bigarray[$i])!='')) + { + if (strpos($bigarray[$i],"#")===0) + { + unset($bigarray[$i]); + unset($bigarray[$i+1]); + unset($bigarray[$i+2]); + break ; + } + else + { + $surveylsarray[] = $bigarray[$i]; + } + } + unset($bigarray[$i]); +} +$bigarray = array_values($bigarray); + +//QUOTA +if (array_search("# QUOTA_MEMBERS TABLE\n", $bigarray)) +{ + $stoppoint = array_search("# QUOTA_MEMBERS TABLE\n", $bigarray); +} +elseif (array_search("# QUOTA_MEMBERS TABLE\r\n", $bigarray)) +{ + $stoppoint = array_search("# QUOTA_MEMBERS TABLE\r\n", $bigarray); +} +else +{ + $stoppoint = count($bigarray)-1; +} +for ($i=0; $i<=$stoppoint+1; $i++) +{ +// if ($i<$stoppoint-2 || $i==count($bigarray)-1) + if ($i<$stoppoint-2) + { + $quotaarray[] = $bigarray[$i]; + } + unset($bigarray[$i]); +} +$bigarray = array_values($bigarray); + +//QUOTA MEMBERS +if (array_search("# QUOTA_LANGUAGESETTINGS TABLE\n", $bigarray)) +{ + $stoppoint = array_search("# QUOTA_LANGUAGESETTINGS TABLE\n", $bigarray); +} +elseif (array_search("# QUOTA_LANGUAGESETTINGS TABLE\r\n", $bigarray)) +{ + $stoppoint = array_search("# QUOTA_LANGUAGESETTINGS TABLE\r\n", $bigarray); +} +else +{ + $stoppoint = count($bigarray)-1; +} +for ($i=0; $i<=$stoppoint+1; $i++) +{ +// if ($i<$stoppoint-2 || $i==count($bigarray)-1) + if ($i<$stoppoint-2) + { + $quotamembersarray[] = $bigarray[$i]; + } + unset($bigarray[$i]); +} +$bigarray = array_values($bigarray); + + +//Whatever is the last table - currently +//QUOTA LANGUAGE SETTINGS +$stoppoint = count($bigarray)-1; +for ($i=0; $i<$stoppoint-1; $i++) +{ + if ($i<=$stoppoint) {$quotalsarray[] = $bigarray[$i];} + unset($bigarray[$i]); +} +$bigarray = array_values($bigarray); + +if (isset($surveyarray)) {$countsurveys = count($surveyarray);} else {$countsurveys = 0;} +if (isset($surveylsarray)) {$countlanguages = count($surveylsarray)-1;} else {$countlanguages = 1;} +if (isset($grouparray)) {$countgroups = count($grouparray);} else {$countgroups = 0;} +if (isset($questionarray)) {$countquestions = count($questionarray);} else {$countquestions=0;} +if (isset($answerarray)) {$countanswers = count($answerarray);} else {$countanswers=0;} +if (isset($conditionsarray)) {$countconditions = count($conditionsarray);} else {$countconditions=0;} +if (isset($labelsetsarray)) {$countlabelsets = count($labelsetsarray);} else {$countlabelsets=0;} +if (isset($question_attributesarray)) {$countquestion_attributes = count($question_attributesarray);} else {$countquestion_attributes=0;} +if (isset($assessmentsarray)) {$countassessments=count($assessmentsarray);} else {$countassessments=0;} +if (isset($quotaarray)) {$countquota=count($quotaarray);} else {$countquota=0;} +if (isset($quotamembersarray)) {$countquotamembers=count($quotamembersarray);} else {$countquotamembers=0;} +if (isset($quotalsarray)) {$countquotals=count($quotalsarray);} else {$countquotals=0;} + +// CREATE SURVEY + +if ($importversion>=111) +{ + if ($countsurveys>0){$countsurveys--;}; + if ($countanswers>0){$countanswers=($countanswers-1)/$countlanguages;}; + if ($countgroups>0){$countgroups=($countgroups-1)/$countlanguages;}; + if ($countquestions>0){$countquestions=($countquestions-1)/$countlanguages;}; + if ($countassessments>0){$countassessments--;}; + if ($countconditions>0){$countconditions--;}; + if ($countlabelsets>0){$countlabelsets--;}; + if ($countquestion_attributes>0){$countquestion_attributes--;}; + if ($countquota>0){$countquota--;}; + $sfieldorders =convertCSVRowToArray($surveyarray[0],',','"'); + $sfieldcontents=convertCSVRowToArray($surveyarray[1],',','"'); +} +else + { + $sfieldorders=convertToArray($surveyarray[0], "`, `", "(`", "`)"); + $sfieldcontents=convertToArray($surveyarray[0], "', '", "('", "')"); + } +$surveyrowdata=array_combine($sfieldorders,$sfieldcontents); +$surveyid=$surveyrowdata["sid"]; + + +if (!$surveyid) +{ + if ($importingfrom == "http") + { + $importsurvey .= "
    ".$clang->gT("Error")."
    \n"; + $importsurvey .= $clang->gT("Import of this survey file failed")."
    \n"; + $importsurvey .= $clang->gT("File does not contain LimeSurvey data in the correct format.")."
    \n"; //Couldn't find the SID - cannot continue + $importsurvey .= "\n"; + $importsurvey .= "\n\n"; + unlink($the_full_file_path); //Delete the uploaded file + return; + } + else + { + echo $clang->gT("Import of this survey file failed")."\n".$clang->gT("File does not contain LimeSurvey data in the correct format.")."\n"; + return; + } +} + +// Use the existing surveyid if it does not already exists +// This allows the URL links to the survey to keep working because the sid did not change + $newsid = $surveyid; + $isquery = "SELECT sid FROM {$dbprefix}surveys WHERE sid=$newsid"; + $isresult = db_execute_assoc($isquery); + if ($isresult->RecordCount()>0) + { + // Get new random ids until one is found that is not used + do + { + $newsid = getRandomID(); + $isquery = "SELECT sid FROM {$dbprefix}surveys WHERE sid=$newsid"; + $isresult = db_execute_assoc($isquery); + } + while ($isresult->RecordCount()>0); + } + + +$insert=$surveyarray[0]; +if ($importversion>=111) +{ + $sfieldorders =convertCSVRowToArray($surveyarray[0],',','"'); + $sfieldcontents=convertCSVRowToArray($surveyarray[1],',','"'); +} +else + { + $sfieldorders=convertToArray($surveyarray[0], "`, `", "(`", "`)"); + $sfieldcontents=convertToArray($surveyarray[0], "', '", "('", "')"); + } +$surveyrowdata=array_combine($sfieldorders,$sfieldcontents); +// Set new owner ID +$surveyrowdata['owner_id']=$_SESSION['loginID']; +// Set new survey ID +$surveyrowdata['sid']=$newsid; +$surveyrowdata['active']='N'; + + +if ($importversion<=100) +// find the old language field and replace its contents with the new language shortcuts + { + $oldlanguage=$surveyrowdata['language']; + $newlanguage='en'; //Default + switch ($oldlanguage) + { + case "bulgarian": + $newlanguage='bg'; + break; + case "chinese-simplified": + $newlanguage='zh-Hans'; + break; + case "chinese-traditional": + $newlanguage='zh-Hant-HK'; + break; + case "croatian": + $newlanguage='hr'; + break; + case "danish": + $newlanguage='da'; + break; + case "dutch": + $newlanguage='nl'; + break; + case "english": + $newlanguage='en'; + break; + case "french": + $newlanguage='fr'; + break; + case "german-informal": + $newlanguage='de-informal'; + break; + case "german": + $newlanguage='de'; + break; + case "greek": + $newlanguage='el'; + break; + case "hungarian": + $newlanguage='hu'; + break; + case "italian": + $newlanguage='it'; + break; + case "japanese": + $newlanguage='ja'; + break; + case "lithuanian": + $newlanguage='lt'; + break; + case "norwegian": + $newlanguage='nb'; + break; + case "portuguese": + $newlanguage='pt'; + break; + case "romanian": + $newlanguage='ro'; + break; + case "russian": + $newlanguage='ru'; + break; + case "slovenian": + $newlanguage='sl'; + break; + case "spanish": + $newlanguage='es'; + break; + case "swedish": + $newlanguage='sv'; + break; + } + + $surveyrowdata['language']=$newlanguage; + + // copy the survey row data + + // now prepare the languagesettings table and drop according values from the survey array + $surveylsrowdata=array(); + $surveylsrowdata['surveyls_survey_id']=$newsid; + $surveylsrowdata['surveyls_language']=$newlanguage; + $surveylsrowdata['surveyls_title']=$surveyrowdata['short_title']; + $surveylsrowdata['surveyls_description']=$surveyrowdata['description']; + $surveylsrowdata['surveyls_welcometext']=$surveyrowdata['welcome']; + $surveylsrowdata['surveyls_urldescription']=$surveyrowdata['urldescrip']; + if (isset($surveyrowdata['email_invite_subj'])) $surveylsrowdata['surveyls_email_invite_subj']=$surveyrowdata['email_invite_subj']; + $surveylsrowdata['surveyls_email_invite']=$surveyrowdata['email_invite']; + if (isset($surveyrowdata['email_remind_subj'])) $surveylsrowdata['surveyls_email_remind_subj']=$surveyrowdata['email_remind_subj']; + $surveylsrowdata['surveyls_email_remind']=$surveyrowdata['email_remind']; + if (isset($surveyrowdata['email_register_subj'])) $surveylsrowdata['surveyls_email_register_subj']=$surveyrowdata['email_register_subj']; + $surveylsrowdata['surveyls_email_register']=$surveyrowdata['email_register']; + if (isset($surveyrowdata['email_confirm_subj'])) $surveylsrowdata['surveyls_email_confirm_subj']=$surveyrowdata['email_confirm_subj']; + $surveylsrowdata['surveyls_email_confirm']=$surveyrowdata['email_confirm']; + if(!isset($defaultsurveylanguage)) {$defaultsurveylanguage=$newlanguage;} + unset($surveyrowdata['short_title']); + unset($surveyrowdata['description']); + unset($surveyrowdata['welcome']); + unset($surveyrowdata['urldescrip']); + unset($surveyrowdata['email_invite_subj']); + unset($surveyrowdata['email_invite']); + unset($surveyrowdata['email_remind_subj']); + unset($surveyrowdata['email_remind']); + unset($surveyrowdata['email_register_subj']); + unset($surveyrowdata['email_register']); + unset($surveyrowdata['email_confirm_subj']); + unset($surveyrowdata['email_confirm']); + + + // translate internal links + $surveylsrowdata['surveyls_title']=translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_title']); + $surveylsrowdata['surveyls_description']=translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_description']); + $surveylsrowdata['surveyls_welcometext']=translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_welcometext']); + $surveylsrowdata['surveyls_urldescription']=translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_urldescription']); + $surveylsrowdata['surveyls_email_invite']=translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_email_invite']); + $surveylsrowdata['surveyls_email_remind']=translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_email_remind']); + $surveylsrowdata['surveyls_email_register']=translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_email_register']); + $surveylsrowdata['surveyls_email_confirm']=translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_email_confirm']); + + + + // import the survey language-specific settings + $values=array_values($surveylsrowdata); + $values=array_map(array(&$connect, "qstr"),$values); // quote everything accordingly + $insert = "insert INTO {$dbprefix}surveys_languagesettings (".implode(',',array_keys($surveylsrowdata)).") VALUES (".implode(',',$values).")"; //handle db prefix + $iresult = $connect->Execute($insert) or safe_die("
    ".$clang->gT("Import of this survey file failed")."
    \n[$insert]
    {$surveyarray[0]}

    \n" . $connect->ErrorMsg()); + } + + + +if (isset($surveyrowdata['datecreated'])) {$surveyrowdata['datecreated']=$connect->BindTimeStamp($surveyrowdata['datecreated']);} +unset($surveyrowdata['expires']); +unset($surveyrowdata['attribute1']); +unset($surveyrowdata['attribute2']); +unset($surveyrowdata['usestartdate']); +unset($surveyrowdata['useexpiry']); +unset($surveyrowdata['url']); +if (isset($surveyrowdata['startdate'])) {unset($surveyrowdata['startdate']);} +$surveyrowdata['bounce_email']=$surveyrowdata['adminemail']; +if (!isset($surveyrowdata['datecreated']) || $surveyrowdata['datecreated']=='' || $surveyrowdata['datecreated']=='null') {$surveyrowdata['datecreated']=$connect->BindTimeStamp(date_shift(date("Y-m-d H:i:s"), "Y-m-d", $timeadjust));} + +$values=array_values($surveyrowdata); +$values=array_map(array(&$connect, "qstr"),$values); // quote everything accordingly +$insert = "INSERT INTO {$dbprefix}surveys (".implode(',',array_keys($surveyrowdata)).") VALUES (".implode(',',$values).")"; //handle db prefix +$iresult = $connect->Execute($insert) or safe_die("
    ".$clang->gT("Import of this survey file failed")."
    \n[$insert]
    {$surveyarray[0]}

    \n" . $connect->ErrorMsg()); + +$oldsid=$surveyid; + +// Now import the survey language settings +if ($importversion>=111) +{ + $fieldorders=convertCSVRowToArray($surveylsarray[0],',','"'); + unset($surveylsarray[0]); + foreach ($surveylsarray as $slsrow) { + $fieldcontents=convertCSVRowToArray($slsrow,',','"'); + $surveylsrowdata=array_combine($fieldorders,$fieldcontents); + // convert back the '\'.'n' cahr from the CSV file to true return char "\n" + $surveylsrowdata=array_map('convertCsvreturn2return', $surveylsrowdata); + // Convert the \n return char from welcometext to
    + + // translate internal links + $surveylsrowdata['surveyls_title']=translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_title']); + $surveylsrowdata['surveyls_description']=translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_description']); + $surveylsrowdata['surveyls_welcometext']=translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_welcometext']); + $surveylsrowdata['surveyls_urldescription']=translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_urldescription']); + $surveylsrowdata['surveyls_email_invite']=translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_email_invite']); + $surveylsrowdata['surveyls_email_remind']=translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_email_remind']); + $surveylsrowdata['surveyls_email_register']=translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_email_register']); + $surveylsrowdata['surveyls_email_confirm']=translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_email_confirm']); + + $surveylsrowdata['surveyls_survey_id']=$newsid; + $newvalues=array_values($surveylsrowdata); + $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly + $lsainsert = "INSERT INTO {$dbprefix}surveys_languagesettings (".implode(',',array_keys($surveylsrowdata)).") VALUES (".implode(',',$newvalues).")"; //handle db prefix + $lsiresult=$connect->Execute($lsainsert) or safe_die("
    ".$clang->gT("Import of this survey file failed")."
    \n[$lsainsert]
    \n" . $connect->ErrorMsg() ); + } + +} + + +// DO SURVEY_RIGHTS +$isrquery = "INSERT INTO {$dbprefix}surveys_rights VALUES($newsid,".$_SESSION['loginID'].",1,1,1,1,1,1)"; +@$isrresult = $connect->Execute($isrquery); +$deniedcountlabelsets =0; + + +//DO ANY LABELSETS FIRST, SO WE CAN KNOW WHAT THEIR NEW LID IS FOR THE QUESTIONS +if (isset($labelsetsarray) && $labelsetsarray) { + $csarray=buildLabelSetCheckSumArray(); // build checksums over all existing labelsets + $count=0; + foreach ($labelsetsarray as $lsa) { + + if ($importversion>=111) + { + $fieldorders =convertCSVRowToArray($labelsetsarray[0],',','"'); + $fieldcontents=convertCSVRowToArray($lsa,',','"'); + if ($count==0) {$count++; continue;} + } + else + { + $fieldorders=convertToArray($lsa, "`, `", "(`", "`)"); + $fieldcontents=convertToArray($lsa, "', '", "('", "')"); + } + $labelsetrowdata=array_combine($fieldorders,$fieldcontents); + + // Save old labelid + $oldlid=$labelsetrowdata['lid']; + // set the new language + if ($importversion<=100) + { + $labelsetrowdata['languages']=$newlanguage; + } + unset($labelsetrowdata['lid']); + $newvalues=array_values($labelsetrowdata); + $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly + $lsainsert = "insert INTO {$dbprefix}labelsets (".implode(',',array_keys($labelsetrowdata)).") VALUES (".implode(',',$newvalues).")"; //handle db prefix + $lsiresult=$connect->Execute($lsainsert); + + // Get the new insert id for the labels inside this labelset + $newlid=$connect->Insert_ID("{$dbprefix}labelsets","lid"); + +// $importsurvey .= "OLDLID: $oldlid NEWLID: $newlid"; +// For debugging label import + + if ($labelsarray) { + $count=0; + foreach ($labelsarray as $la) { + if ($importversion>=111) + { + $lfieldorders =convertCSVRowToArray($labelsarray[0],',','"'); + $lfieldcontents=convertCSVRowToArray($la,',','"'); + if ($count==0) {$count++; continue;} + } + else + { + //Get field names into array + $lfieldorders=convertToArray($la, "`, `", "(`", "`)"); + //Get field values into array + $lfieldcontents=convertToArray($la, "', '", "('", "')"); + } + // Combine into one array with keys and values since its easier to handle + $labelrowdata=array_combine($lfieldorders,$lfieldcontents); + if ($importversion<=132) + { + $labelrowdata["assessment_value"]=(int)$labelrowdata["code"]; + } + $labellid=$labelrowdata['lid']; + if ($importversion<=100) + { + $labelrowdata['language']=$newlanguage; + } + if ($labellid == $oldlid) { + $labelrowdata['lid']=$newlid; + + // translate internal links + $labelrowdata['title']=translink('label', $oldlid, $newlid, $labelrowdata['title']); + + $newvalues=array_values($labelrowdata); + $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly + $lainsert = "insert INTO {$dbprefix}labels (".implode(',',array_keys($labelrowdata)).") VALUES (".implode(',',$newvalues).")"; //handle db prefix + $liresult=$connect->Execute($lainsert); + + } + } + } + + //CHECK FOR DUPLICATE LABELSETS + $thisset=""; +/* + $query2 = "SELECT code, title, sortorder, language, assessment_value + FROM {$dbprefix}labels + WHERE lid=".$newlid." + ORDER BY language, sortorder, code"; + $result2 = db_execute_num($query2) or safe_die("Died querying labelset $lid
    $query2
    ".$connect->ErrorMsg()); + while($row2=$result2->FetchRow()) + { + $thisset .= implode('.', $row2); + } // while + $newcs=dechex(crc32($thisset)*1); + unset($lsmatch); + if (isset($csarray)) + { + foreach($csarray as $key=>$val) + { + if ($val == $newcs) + { + $lsmatch=$key; + } + } + } + if (isset($lsmatch) || ($_SESSION['USER_RIGHT_MANAGE_LABEL'] != 1)) + { + //There is a matching labelset or the user is not allowed to edit labels - + // So, we will delete this one and refer to the matched one. + $query = "DELETE FROM {$dbprefix}labels WHERE lid=$newlid"; + $result=$connect->Execute($query) or safe_die("Couldn't delete labels
    $query
    ".$connect->ErrorMsg()); + $query = "DELETE FROM {$dbprefix}labelsets WHERE lid=$newlid"; + $result=$connect->Execute($query) or safe_die("Couldn't delete labelset
    $query
    ".$connect->ErrorMsg()); + if (isset($lsmatch)) {$newlid=$lsmatch;} + else {++$deniedcountlabelsets;--$countlabelsets;} + } + else + { + //There isn't a matching labelset, add this checksum to the $csarray array + $csarray[$newlid]=$newcs; + } + //END CHECK FOR DUPLICATES +*/ + $labelreplacements[]=array($oldlid, $newlid); + } +} + +$importwarning = ""; // used to save the warnings while processing questions +$qtypes = getqtypelist("" ,"array"); + +// DO GROUPS, QUESTIONS FOR GROUPS, THEN ANSWERS FOR QUESTIONS IN A NESTED FORMAT! +if (isset($grouparray) && $grouparray) { + $count=0; + $currentgid=''; + foreach ($grouparray as $ga) { + if ($importversion>=111) + { + $gafieldorders =convertCSVRowToArray($grouparray[0],',','"'); + $gacfieldcontents=convertCSVRowToArray($ga,',','"'); + if ($count==0) {$count++; continue;} + } + else + { + //Get field names into array + $gafieldorders=convertToArray($ga, "`, `", "(`", "`)"); + //Get field values into array + $gacfieldcontents=convertToArray($ga, "', '", "('", "')"); + } + $grouprowdata=array_combine($gafieldorders,$gacfieldcontents); + // remember group id + if ($currentgid=='' || ($currentgid!=$grouprowdata['gid'])) {$currentgid=$grouprowdata['gid'];$newgroup=true;} + else + if ($currentgid==$grouprowdata['gid']) {$newgroup=false;} + $gid=$grouprowdata['gid']; + $gsid=$grouprowdata['sid']; + //Now an additional integrity check if there are any groups not belonging into this survey + if ($gsid != $surveyid) + { + if ($importingfrom == "http") + { + $importsurvey .= "
    \n".$clang->gT("Error")."" + ."
    \n".$clang->gT("A group in the CSV/SQL file is not part of the same survey. The import of the survey was stopped.")."

    \n"; + } + else + { + echo $clang->gT("Error").": A group in the CSV/SQL file is not part of the same Survey. The import of the survey was stopped.\n"; + } + return; + } + //remove the old group id + if ($newgroup) {unset($grouprowdata['gid']);} + else {$grouprowdata['gid']=$newgid;} + //replace old surveyid by new surveyid + $grouprowdata['sid']=$newsid; + // Version <=100 dont have a language field yet so we set it now + if ($importversion<=100) + { + $grouprowdata['language']=$newlanguage; + } + $oldgid=$gid; // save it for later + $grouprowdata=array_map('convertCsvreturn2return', $grouprowdata); + + // translate internal links + $grouprowdata['group_name']=translink('survey', $surveyid, $newsid, $grouprowdata['group_name']); + $grouprowdata['description']=translink('survey', $surveyid, $newsid, $grouprowdata['description']); + + $newvalues=array_values($grouprowdata); + + $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly + + if (isset($grouprowdata['gid'])) {@$connect->Execute('SET IDENTITY_INSERT '.db_table_name('groups')." ON");} + $ginsert = 'insert INTO '.db_table_name('groups').' ('.implode(',',array_keys($grouprowdata)).') VALUES ('.implode(',',$newvalues).')'; + $gres = $connect->Execute($ginsert) or safe_die($clang->gT('Error').": Failed to insert group
    \n$ginsert
    \n".$connect->ErrorMsg()); + if (isset($grouprowdata['gid'])) {@$connect->Execute('SET IDENTITY_INSERT '.db_table_name('groups').' OFF');} + //GET NEW GID + if ($newgroup) {$newgid=$connect->Insert_ID("{$dbprefix}groups","gid");} + + //NOW DO NESTED QUESTIONS FOR THIS GID + + if (isset($questionarray) && $questionarray && $newgroup) { + $count=0; + $currentqid=''; + foreach ($questionarray as $qa) { + if ($importversion>=111) + { + $qafieldorders =convertCSVRowToArray($questionarray[0],',','"'); + $qacfieldcontents=convertCSVRowToArray($qa,',','"'); + if ($count==0) {$count++; continue;} + } + else + { + $qafieldorders=convertToArray($qa, "`, `", "(`", "`)"); + $qacfieldcontents=convertToArray($qa, "', '", "('", "')"); + } + $questionrowdata=array_combine($qafieldorders,$qacfieldcontents); + $questionrowdata=array_map('convertCsvreturn2return', $questionrowdata); + + if ($currentqid=='' || ($currentqid!=$questionrowdata['qid'])) {$currentqid=$questionrowdata['qid'];$newquestion=true;} + else + if ($currentqid==$questionrowdata['qid']) {$newquestion=false;} + + if (!array_key_exists($questionrowdata["type"], $qtypes)) + { + $questionrowdata["type"] = strtoupper($questionrowdata["type"]); + if (!array_key_exists($questionrowdata["type"], $qtypes)) + { + $importwarning .= "
  • " . sprintf($clang->gT("Question \"%s - %s\" was NOT imported because the question type is unknown."), $questionrowdata["title"], $questionrowdata["question"]) . "
  • "; + $countquestions--; + continue; + } + else // the upper case worked well $qtypes[$questionrowdata["type"]] + { + $importwarning .= "
  • " . sprintf($clang->gT("Question \"%s - %s\" was imported but the type was set to '%s' because it is the most similiar one."), $questionrowdata["title"], $questionrowdata["question"], $qtypes[$questionrowdata["type"]]) . "
  • "; + } + } + + + $thisgid=$questionrowdata['gid']; + if ($thisgid == $gid) { + $qid = $questionrowdata['qid']; + // Remove qid field + if ($newquestion) {unset($questionrowdata['qid']);} + else {$questionrowdata['qid']=$newqid;} + + $questionrowdata["sid"] = $newsid; + $questionrowdata["gid"] = $newgid; + // Version <=100 doesn't have a language field yet so we set it now + if ($importversion<=100) + { + $questionrowdata['language']=$newlanguage; + } + $oldqid=$qid; + if (!isset($questionrowdata["lid1"])) + { + $questionrowdata["lid1"]=0; + } + // Now we will fix up the label id + $type = $questionrowdata["type"]; //Get the type + if ($type == "F" || $type == "H" || $type == "W" || + $type == "Z" || $type == "1" || $type == ":" || + $type == ";" ) + {//IF this is a flexible label array, update the lid entry + if (isset($labelreplacements)) { + // We only replace once in each question label + // otherwise could lead to double substitution + // if a new lid collides with an older one + $already_replaced_label = false; + $already_replaced_label1 = false; + foreach ($labelreplacements as $lrp) { + if ($lrp[0] == $questionrowdata["lid"]) + { + if (!$already_replaced_label) + { + $questionrowdata["lid"]=$lrp[1]; + $already_replaced_label = true; + } + } + if ($lrp[0] == $questionrowdata["lid1"]) + { + if (!$already_replaced_label1) + { + $questionrowdata["lid1"]=$lrp[1]; + $already_replaced_label1 = true; + } + } + } + } + } + if (!isset($questionrowdata["question_order"]) || $questionrowdata["question_order"]=='') {$questionrowdata["question_order"]=0;} + $other = $questionrowdata["other"]; //Get 'other' field value + + // translate internal links + $questionrowdata['title']=translink('survey', $surveyid, $newsid, $questionrowdata['title']); + $questionrowdata['question']=translink('survey', $surveyid, $newsid, $questionrowdata['question']); + $questionrowdata['help']=translink('survey', $surveyid, $newsid, $questionrowdata['help']); + + $newvalues=array_values($questionrowdata); + if (isset($questionrowdata['qid'])) {@$connect->Execute('SET IDENTITY_INSERT '.db_table_name('questions').' ON');} + + $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly + $qinsert = "insert INTO {$dbprefix}questions (".implode(',',array_keys($questionrowdata)).") VALUES (".implode(',',$newvalues).")"; + + $qres = $connect->Execute($qinsert) or safe_die ($clang->gT("Error").": Failed to insert question
    \n$qinsert
    \n".$connect->ErrorMsg()); + if (isset($questionrowdata['qid'])) {@$connect->Execute('SET IDENTITY_INSERT '.db_table_name('questions').' OFF');} + if ($newquestion) + { + $newqid=$connect->Insert_ID("{$dbprefix}questions","qid"); + } + + $newrank=0; + $substitutions[]=array($oldsid, $oldgid, $oldqid, $newsid, $newgid, $newqid); + + //NOW DO NESTED ANSWERS FOR THIS QID + if (isset($answerarray) && $answerarray && $newquestion) { + $count=0; + foreach ($answerarray as $aa) { + if ($importversion>=111) + { + $aafieldorders =convertCSVRowToArray($answerarray[0],',','"'); + $aacfieldcontents=convertCSVRowToArray($aa,',','"'); + if ($count==0) {$count++; continue;} + } + else + { + $aafieldorders=convertToArray($aa, "`, `", "(`", "`)"); + $aacfieldcontents=convertToArray($aa, "', '", "('", "')"); + } + $answerrowdata=array_combine($aafieldorders,$aacfieldcontents); + if ($importversion<=132) + { + $answerrowdata["assessment_value"]=(int)$answerrowdata["code"]; + } + $code=$answerrowdata["code"]; + $thisqid=$answerrowdata["qid"]; + if ($thisqid == $qid) + { + $answerrowdata["qid"]=$newqid; + // Version <=100 doesn't have a language field yet so we set it now + if ($importversion<=100) + { + $answerrowdata['language']=$newlanguage; + } + + // translate internal links + $answerrowdata['answer']=translink('survey', $surveyid, $newsid, $answerrowdata['answer']); + + $newvalues=array_values($answerrowdata); + $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly + $ainsert = "insert INTO {$dbprefix}answers (".implode(',',array_keys($answerrowdata)).") VALUES (".implode(',',$newvalues).")"; + $ares = $connect->Execute($ainsert) or safe_die ($clang->gT("Error").": Failed to insert answer
    \n$ainsert
    \n".$connect->ErrorMsg()); + + if ($type == "M" || $type == "P") { + $fieldnames[]=array("oldcfieldname"=>$oldsid."X".$oldgid."X".$oldqid, + "newcfieldname"=>$newsid."X".$newgid."X".$newqid, + "oldfieldname"=>$oldsid."X".$oldgid."X".$oldqid.$code, + "newfieldname"=>$newsid."X".$newgid."X".$newqid.$code); + $fieldnames[]=array("oldcfieldname"=>'+'.$oldsid."X".$oldgid."X".$oldqid.$code, + "newcfieldname"=>'+'.$newsid."X".$newgid."X".$newqid.$code, + "oldfieldname"=>"+".$oldsid."X".$oldgid."X".$oldqid.$code, + "newfieldname"=>"+".$newsid."X".$newgid."X".$newqid.$code); + if ($type == "P") { + $fieldnames[]=array("oldcfieldname"=>$oldsid."X".$oldgid."X".$oldqid."comment", + "newcfieldname"=>$newsid."X".$newgid."X".$newqid.$code."comment", + "oldfieldname"=>$oldsid."X".$oldgid."X".$oldqid.$code."comment", + "newfieldname"=>$newsid."X".$newgid."X".$newqid.$code."comment"); + } + } + elseif ($type == "A" || $type == "B" || $type == "C" || $type == "F" || $type == "H" || $type == "E" || $type == "Q" || $type == "K" || $type == "1") { + $fieldnames[]=array("oldcfieldname"=>$oldsid."X".$oldgid."X".$oldqid.$code, + "newcfieldname"=>$newsid."X".$newgid."X".$newqid.$code, + "oldfieldname"=>$oldsid."X".$oldgid."X".$oldqid.$code, + "newfieldname"=>$newsid."X".$newgid."X".$newqid.$code); + } + elseif ($type == ":" || $type == ";" ) { + // read all label codes from $questionrowdata["lid"] + // for each one (as L) set SGQA_L + $labelq="SELECT DISTINCT code FROM {$dbprefix}labels WHERE lid=".$questionrowdata["lid"]; + $labelqresult=db_execute_num($labelq) or safe_die("Died querying labelset $lid
    $query2
    ".$connect->ErrorMsg()); + while ($labelqrow=$labelqresult->FetchRow()) + { + $fieldnames[]=array("oldcfieldname"=>$oldsid."X".$oldgid."X".$oldqid.$code."_".$labelqrow[0], + "newcfieldname"=>$newsid."X".$newgid."X".$newqid.$code."_".$labelqrow[0], + "oldfieldname"=>$oldsid."X".$oldgid."X".$oldqid.$code."_".$labelqrow[0], + "newfieldname"=>$newsid."X".$newgid."X".$newqid.$code."_".$labelqrow[0]); + } + } + elseif ($type == "R") { + $newrank++; + } + } + } + if (($type == "A" || $type == "B" || $type == "C" || $type == "M" || $type == "P" || $type == "L") && ($other == "Y")) { + $fieldnames[]=array("oldcfieldname"=>$oldsid."X".$oldgid."X".$oldqid."other", + "newcfieldname"=>$newsid."X".$newgid."X".$newqid."other", + "oldfieldname"=>$oldsid."X".$oldgid."X".$oldqid."other", + "newfieldname"=>$newsid."X".$newgid."X".$newqid."other"); + if ($type == "P") { + $fieldnames[]=array("oldcfieldname"=>$oldsid."X".$oldgid."X".$oldqid."othercomment", + "newcfieldname"=>$newsid."X".$newgid."X".$newqid."othercomment", + "oldfieldname"=>$oldsid."X".$oldgid."X".$oldqid."othercomment", + "newfieldname"=>$newsid."X".$newgid."X".$newqid."othercomment"); + } + } + if ($type == "R" && $newrank >0) { + for ($i=1; $i<=$newrank; $i++) { + $fieldnames[]=array("oldcfieldname"=>$oldsid."X".$oldgid."X".$oldqid.$i, + "newcfieldname"=>$newsid."X".$newgid."X".$newqid.$i, + "oldfieldname"=>$oldsid."X".$oldgid."X".$oldqid.$i, + "newfieldname"=>$newsid."X".$newgid."X".$newqid.$i); + } + } + if ($type != "A" && $type != "B" && $type != "C" && $type != "R" && $type != "M" && $type != "P") { + $fieldnames[]=array("oldcfieldname"=>$oldsid."X".$oldgid."X".$oldqid, + "newcfieldname"=>$newsid."X".$newgid."X".$newqid, + "oldfieldname"=>$oldsid."X".$oldgid."X".$oldqid, + "newfieldname"=>$newsid."X".$newgid."X".$newqid); + if ($type == "O") { + $fieldnames[]=array("oldcfieldname"=>$oldsid."X".$oldgid."X".$oldqid."comment", + "newcfieldname"=>$newsid."X".$newgid."X".$newqid."comment", + "oldfieldname"=>$oldsid."X".$oldgid."X".$oldqid."comment", + "newfieldname"=>$newsid."X".$newgid."X".$newqid."comment"); + } + } + } else { + $fieldnames[]=array("oldcfieldname"=>$oldsid."X".$oldgid."X".$oldqid, + "newcfieldname"=>$newsid."X".$newgid."X".$newqid, + "oldfieldname"=>$oldsid."X".$oldgid."X".$oldqid, + "newfieldname"=>$newsid."X".$newgid."X".$newqid); + } + } + } + } + } +} + + // Fix sortorder of the groups - if users removed groups manually from the csv file there would be gaps + fixsortorderGroups(); + //... and for the questions inside the groups + // get all group ids and fix questions inside each group + $gquery = "SELECT gid FROM {$dbprefix}groups where sid=$newsid group by gid ORDER BY gid"; //Get last question added (finds new qid) + $gres = db_execute_assoc($gquery); + while ($grow = $gres->FetchRow()) + { + fixsortorderQuestions($grow['gid'], $surveyid); + } + + //We've built two arrays along the way - one containing the old SID, GID and QIDs - and their NEW equivalents +//and one containing the old 'extended fieldname' and its new equivalent. These are needed to import conditions and question_attributes. +if (isset($question_attributesarray) && $question_attributesarray) {//ONLY DO THIS IF THERE ARE QUESTION_ATTRIBUES + $count=0; + foreach ($question_attributesarray as $qar) { + if ($importversion>=111) + { + $fieldorders =convertCSVRowToArray($question_attributesarray[0],',','"'); + $fieldcontents=convertCSVRowToArray($qar,',','"'); + if ($count==0) {$count++; continue;} + } + else + { + $fieldorders=convertToArray($qar, "`, `", "(`", "`)"); + $fieldcontents=convertToArray($qar, "', '", "('", "')"); + } + $qarowdata=array_combine($fieldorders,$fieldcontents); + $newqid=""; + $oldqid=$qarowdata['qid']; + foreach ($substitutions as $subs) { + if ($oldqid==$subs[2]) {$newqid=$subs[5];} + } + + $qarowdata["qid"]=$newqid; + unset($qarowdata["qaid"]); + + $newvalues=array_values($qarowdata); + $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly + $qainsert = "insert INTO {$dbprefix}question_attributes (".implode(',',array_keys($qarowdata)).") VALUES (".implode(',',$newvalues).")"; + $result=$connect->Execute($qainsert) or safe_die ("Couldn't insert question_attribute
    $qainsert
    ".$connect->ErrorMsg()); + } +} + +if (isset($assessmentsarray) && $assessmentsarray) {//ONLY DO THIS IF THERE ARE QUESTION_ATTRIBUTES + $count=0; + foreach ($assessmentsarray as $qar) { + if ($importversion>=111) + { + $fieldorders =convertCSVRowToArray($assessmentsarray[0],',','"'); + $fieldcontents=convertCSVRowToArray($qar,',','"'); + if ($count==0) {$count++; continue;} + } + else + { + $fieldorders=convertToArray($qar, "`, `", "(`", "`)"); + $fieldcontents=convertToArray($qar, "', '", "('", "')"); + } + $asrowdata=array_combine($fieldorders,$fieldcontents); + if (isset($asrowdata['link'])) + { + if (trim($asrowdata['link'])!='') $asrowdata['message']=$asrowdata['message'].'
    '.$asrowdata['link'].''; + unset($asrowdata['link']); + } + $oldsid=$asrowdata["sid"]; + $oldgid=$asrowdata["gid"]; + if ($oldgid>0) + { + foreach ($substitutions as $subs) { + if ($oldsid==$subs[0]) {$newsid=$subs[3];} + if ($oldgid==$subs[1]) {$newgid=$subs[4];} + } + } + else + { + $newgid=0; + } + + $asrowdata["sid"]=$newsid; + $asrowdata["gid"]=$newgid; + unset($asrowdata["id"]); + + + $newvalues=array_values($asrowdata); + $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly + $asinsert = "insert INTO {$dbprefix}assessments (".implode(',',array_keys($asrowdata)).") VALUES (".implode(',',$newvalues).")"; + $result=$connect->Execute($asinsert) or safe_die ("Couldn't insert assessment
    $asinsert
    ".$connect->ErrorMsg()); + + unset($newgid); + } +} + +if (isset($quotaarray) && $quotaarray) {//ONLY DO THIS IF THERE ARE QUOTAS + $count=0; + foreach ($quotaarray as $qar) { + + $fieldorders=convertCSVRowToArray($quotaarray[0],',','"'); + $fieldcontents=convertCSVRowToArray($qar,',','"'); + if ($count==0) {$count++; continue;} + + $asrowdata=array_combine($fieldorders,$fieldcontents); + + $oldsid=$asrowdata["sid"]; + foreach ($substitutions as $subs) { + if ($oldsid==$subs[0]) {$newsid=$subs[3];} + } + + $asrowdata["sid"]=$newsid; + $oldid = $asrowdata["id"]; + unset($asrowdata["id"]); + $quotadata[]=$asrowdata; //For use later if needed + + $newvalues=array_values($asrowdata); + $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly + + $asinsert = "insert INTO {$dbprefix}quota (".implode(',',array_keys($asrowdata)).") VALUES (".implode(',',$newvalues).")"; + $result=$connect->Execute($asinsert) or safe_die ("Couldn't insert quota
    $asinsert
    ".$connect->ErrorMsg()); + $quotaids[] = array($oldid,$connect->Insert_ID(db_table_name_nq('quota'),"id")); + + } +} + +if (isset($quotamembersarray) && $quotamembersarray) {//ONLY DO THIS IF THERE ARE QUOTA MEMBERS + $count=0; + foreach ($quotamembersarray as $qar) { + + $fieldorders =convertCSVRowToArray($quotamembersarray[0],',','"'); + $fieldcontents=convertCSVRowToArray($qar,',','"'); + if ($count==0) {$count++; continue;} + + $asrowdata=array_combine($fieldorders,$fieldcontents); + + $oldsid=$asrowdata["sid"]; + $newqid=""; + $newquotaid=""; + $oldqid=$asrowdata['qid']; + $oldquotaid=$asrowdata['quota_id']; + + foreach ($substitutions as $subs) { + if ($oldsid==$subs[0]) {$newsid=$subs[3];} + if ($oldqid==$subs[2]) {$newqid=$subs[5];} + } + + foreach ($quotaids as $quotaid) { + if ($oldquotaid==$quotaid[0]) {$newquotaid=$quotaid[1];} + } + + $asrowdata["sid"]=$newsid; + $asrowdata["qid"]=$newqid; + $asrowdata["quota_id"]=$newquotaid; + unset($asrowdata["id"]); + + $newvalues=array_values($asrowdata); + $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly + + $asinsert = "insert INTO {$dbprefix}quota_members (".implode(',',array_keys($asrowdata)).") VALUES (".implode(',',$newvalues).")"; + $result=$connect->Execute($asinsert) or safe_die ("Couldn't insert quota
    $asinsert
    ".$connect->ErrorMsg()); + + } +} + +if (isset($quotalsarray) && $quotalsarray) {//ONLY DO THIS IF THERE ARE QUOTA LANGUAGE SETTINGS + $count=0; + foreach ($quotalsarray as $qar) { + + $fieldorders =convertCSVRowToArray($quotalsarray[0],',','"'); + $fieldcontents=convertCSVRowToArray($qar,',','"'); + if ($count==0) {$count++; continue;} + + $asrowdata=array_combine($fieldorders,$fieldcontents); + + $newquotaid=""; + $oldquotaid=$asrowdata['quotals_quota_id']; + + foreach ($quotaids as $quotaid) { + if ($oldquotaid==$quotaid[0]) {$newquotaid=$quotaid[1];} + } + + $asrowdata["quotals_quota_id"]=$newquotaid; + unset($asrowdata["quotals_id"]); + + $newvalues=array_values($asrowdata); + $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly + + $asinsert = "INSERT INTO {$dbprefix}quota_languagesettings (".implode(',',array_keys($asrowdata)).") VALUES (".implode(',',$newvalues).")"; + $result=$connect->Execute($asinsert) or safe_die ("Couldn't insert quota
    $asinsert
    ".$connect->ErrorMsg()); + } +} + +//if there are quotas, but no quotals, then we need to create default dummy for each quota (this handles exports from pre-language quota surveys) +if ($countquota > 0 && (!isset($countquotals) || $countquotals == 0)) { + $i=0; + $defaultsurveylanguage=isset($defaultsurveylanguage) ? $defaultsurveylanguage : "en"; + foreach($quotaids as $quotaid) { + $newquotaid=$quotaid[1]; + $asrowdata=array("quotals_quota_id" => $newquotaid, + "quotals_language" => $defaultsurveylanguage, + "quotals_name" => $quotadata[$i]["name"], + "quotals_message" => $clang->gT("Sorry your responses have exceeded a quota on this survey."), + "quotals_url" => "", + "quotals_urldescrip" => ""); + $i++; + } + $newvalues = array_values($asrowdata); + $newvalues = array_map(array(&$connect, "qstr"),$newvalues); + + $asinsert = "INSERT INTO {$dbprefix}quota_languagesettings (".implode(',',array_keys($asrowdata)).") VALUES (".implode(',',$newvalues).")"; + $result=$connect->Execute($asinsert) or safe_die ("Couldn't insert quota
    $asinsert
    ".$connect->ErrorMsg()); + $countquotals=$i; +} + +if (isset($conditionsarray) && $conditionsarray) {//ONLY DO THIS IF THERE ARE CONDITIONS! + $count='0'; + foreach ($conditionsarray as $car) { + if ($importversion>=111) + { + $fieldorders =convertCSVRowToArray($conditionsarray[0],',','"'); + $fieldcontents=convertCSVRowToArray($car,',','"'); + if ($count==0) {$count++; continue;} + } + else + { + $fieldorders=convertToArray($car, "`, `", "(`", "`)"); + $fieldcontents=convertToArray($car, "', '", "('", "')"); + } + $conditionrowdata=array_combine($fieldorders,$fieldcontents); + + $oldcid=$conditionrowdata["cid"]; + $oldqid=$conditionrowdata["qid"]; + $oldcfieldname=$conditionrowdata["cfieldname"]; + $oldcqid=$conditionrowdata["cqid"]; + $thisvalue=$conditionrowdata["value"]; + $newvalue=$thisvalue; + + foreach ($substitutions as $subs) { + if ($oldqid==$subs[2]) {$newqid=$subs[5];} + if ($oldcqid==$subs[2]) {$newcqid=$subs[5];} + } + // Exception for conditions based on attributes + if ($oldcqid==0) {$newcqid=0;} + + if (preg_match('/^@([0-9]+)X([0-9]+)X([^@]+)@/',$thisvalue,$targetcfieldname)) + { + foreach ($substitutions as $subs) { + if ($targetcfieldname[1]==$subs[0]) {$targetcfieldname[1]=$subs[3];} + if ($targetcfieldname[2]==$subs[1]) {$targetcfieldname[2]=$subs[4];} + if ($targetcfieldname[3]==$subs[2]) {$targetcfieldname[3]=$subs[5];} + } + $newvalue='@'.$targetcfieldname[1].'X'.$targetcfieldname[2].'X'.$targetcfieldname[3].'@'; + } + foreach($fieldnames as $fns) { + //if the $fns['oldcfieldname'] is not the same as $fns['oldfieldname'] then this is a multiple type question + if ($fns['oldcfieldname'] == $fns['oldfieldname']) { //The normal method - non multiples + if ($oldcfieldname==$fns['oldcfieldname']) { + $newcfieldname=$fns['newcfieldname']; + } + } else { + if ($oldcfieldname == $fns['oldcfieldname'] && $oldcfieldname.$thisvalue == $fns['oldfieldname']) { + $newcfieldname=$fns['newcfieldname']; + } + } + } + if (!isset($newcfieldname)) {$newcfieldname="";} + unset($conditionrowdata["cid"]); + $conditionrowdata["qid"]=$newqid; + $conditionrowdata["cfieldname"]=$newcfieldname; + $conditionrowdata["value"]=$newvalue; + + if (isset($newcqid)) { + $conditionrowdata["cqid"]=$newcqid; + if (!isset($conditionrowdata["method"]) || trim($conditionrowdata["method"])=='') + { + $conditionrowdata["method"]='=='; + } + if (!isset($conditionrowdata["scenario"]) || trim($conditionrowdata["scenario"])=='') + { + $conditionrowdata["scenario"]=1; + } + $newvalues=array_values($conditionrowdata); + $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly + $conditioninsert = "insert INTO {$dbprefix}conditions (".implode(',',array_keys($conditionrowdata)).") VALUES (".implode(',',$newvalues).")"; + $result=$connect->Execute($conditioninsert) or safe_die ("Couldn't insert condition
    $conditioninsert
    ".$connect->ErrorMsg()); + } else { + $importsurvey .= "".sprintf($clang->gT("Condition for %d skipped (%d does not exist)"),$oldqid,$oldcqid)."
    "; + if ($importingfrom != "http") echo sprintf($clang->gT("Condition for %d skipped (%d does not exist)"),$oldqid,$oldcqid)."\n"; + } + unset($newcqid); + } +} + +// Translate INSERTANS codes +if (isset($fieldnames)) +{ + transInsertAns($newsid,$oldsid,$fieldnames); +} + + + + +if ($importingfrom == "http") +{ + $importsurvey .= "
    \n".$clang->gT("Success")."

    \n"; + $importsurvey .= "".$clang->gT("Survey Import Summary")."
    \n"; + $importsurvey .= "
      \n\t
    • ".$clang->gT("Surveys").": $countsurveys
    • \n"; + if ($importversion>=111) + { + $importsurvey .= "\t
    • ".$clang->gT("Languages").": $countlanguages
    • \n"; + } + $importsurvey .= "\t
    • ".$clang->gT("Question groups").": $countgroups
    • \n"; + $importsurvey .= "\t
    • ".$clang->gT("Questions").": $countquestions
    • \n"; + $importsurvey .= "\t
    • ".$clang->gT("Answers").": $countanswers
    • \n"; + $importsurvey .= "\t
    • ".$clang->gT("Conditions").": $countconditions
    • \n"; + $importsurvey .= "\t
    • ".$clang->gT("Label Sets").": $countlabelsets
    • \n"; + if ($deniedcountlabelsets>0) + { + $importsurvey .= "\t
    • ".$clang->gT("Not imported Label Sets").": $deniedcountlabelsets ".$clang->gT("(Label Sets were not imported since you do not have the permission to create new label sets.)")."
    • \n"; + } + $importsurvey .= "\t
    • ".$clang->gT("Question Attributes").": $countquestion_attributes
    • \n"; + $importsurvey .= "\t
    • ".$clang->gT("Assessments").": $countassessments
    • \n"; + $importsurvey .= "\t
    • ".$clang->gT("Quotas").": $countquota ($countquotamembers ".$clang->gT("quota members")." ".$clang->gT("and")." $countquotals ".$clang->gT("quota language settings").")
    • \n
    \n"; + + $importsurvey .= "".$clang->gT("Import of Survey is completed.")."
    \n" + . "".$clang->gT("Go to survey")."
    \n"; + if ($importwarning != "") $importsurvey .= "
    ".$clang->gT("Warnings").":
      " . $importwarning . "

    \n"; + $importsurvey .= "
    \n"; + unlink($the_full_file_path); + unset ($surveyid); // Crazy but necessary because else the html script will search for user rights +} +else +{ + echo "\n".$clang->gT("Success")."\n\n"; + echo $clang->gT("Survey Import Summary")."\n"; + echo $clang->gT("Surveys").": $countsurveys\n"; + if ($importversion>=111) + { + echo $clang->gT("Languages").": $countlanguages\n"; + } + echo $clang->gT("Groups").": $countgroups\n"; + echo $clang->gT("Questions").": $countquestions\n"; + echo $clang->gT("Answers").": $countanswers\n"; + echo $clang->gT("Conditions").": $countconditions\n"; + echo $clang->gT("Label Sets").": $countlabelsets\n"; + if ($deniedcountlabelsets>0) echo $clang->gT("Not imported Label Sets").": $deniedcountlabelsets (".$clang->gT("(Label Sets were not imported since you do not have the permission to create new label sets.)"); + echo $clang->gT("Question Attributes").": $countquestion_attributes\n"; + echo $clang->gT("Assessments").": $countassessments\n\n"; + + echo $clang->gT("Import of Survey is completed.")."\n"; + if ($importwarning != "") echo "\n".$clang->gT("Warnings").":\n" . $importwarning . "\n"; + $surveyid=$newsid; + +} + diff --git a/include/limesurvey/admin/index.html b/include/limesurvey/admin/index.html index 1366682c..3b37a4d6 100644 --- a/include/limesurvey/admin/index.html +++ b/include/limesurvey/admin/index.html @@ -1,7 +1,7 @@ - - - - - - - + + + + + + + diff --git a/include/limesurvey/admin/install/cmd_install.php b/include/limesurvey/admin/install/cmd_install.php new file mode 100644 index 00000000..1ecc00a0 --- /dev/null +++ b/include/limesurvey/admin/install/cmd_install.php @@ -0,0 +1,185 @@ + DEFAULT SET TO EN FOR NOW +require_once($rootdir.'/classes/core/language.php'); +$clang = new limesurvey_lang("en"); +ob_implicit_flush(true); + +if (isset($argv[1]) && $argv[1]=='install') +{ + print("trying to create and populate $databasename on $databaselocation:$databaseport ($databasetype) \n"); + + if (!$database_exists) //Database named in config.php does not exist + { + + if($connect->Execute("CREATE DATABASE $databasename;")) + { + print("\nDatabase $databasename on $databasetype CREATED \n"); + } + else + { + print("\nDatabase $databasename on $databasetype COULD NOT BE CREATED \n"); + print("\n".$connect->ErrorMsg()); + return 1; + } + + } + else + { + if ($databasetype=='mysql' || $databasetype=='mysqli') {$connect->Execute("ALTER DATABASE `$databasename` DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;");} //Set the collation also for manually created DBs + + print("\nDatabase $databasename on $databasetype EXISTS, not created \n"); + + } + + // Connect to the database we created a sec ago or to the existing db. + if(!$connect->Connect($databaselocation,$databaseuser,$databasepass,$databasename)) + { + print("\n".$connect->ErrorMsg()); + return 1; + } + + require_once($homedir."/classes/core/sha256.php"); + + $success = 0; // Let's be optimistic + + $createdbtype=$databasetype; + if ($createdbtype=='mssql_n' || $createdbtype=='odbc_mssql' || $createdbtype=='odbtp') $createdbtype='mssql'; + $sqlfile = dirname(__FILE__).'/create-'.$createdbtype.'.sql' ; + + if (!empty($sqlfile)) { + if (!is_readable($sqlfile)) { + $success = false; + print "\nTried to populate database, but '". $sqlfile ."' doesn't exist!\n"; + return $success; + } else { + $lines = file($sqlfile); + } + } else { + $sqlstring = trim($sqlstring); + if ($sqlstring{strlen($sqlstring)-1} != ";") { + $sqlstring .= ";"; // add it in if it's not there. + } + $lines[] = $sqlstring; + } + + $command = ''; + + $connect->SetFetchMode(ADODB_FETCH_NUM); + foreach ($lines as $line) { + $line = rtrim($line); + $length = strlen($line); + + if ($length and $line[0] <> '#' and substr($line,0,2) <> '--') { + if (substr($line, $length-1, 1) == ';') { + $line = substr($line, 0, $length-1); // strip ; + $command .= $line; + $command = str_replace('prefix_', $dbprefix, $command); // Table prefixes + $command = str_replace('$defaultuser', $defaultuser, $command); // variables By Moses + $command = str_replace('$defaultpass', SHA256::hashing($defaultpass), $command); // variables By Moses + $command = str_replace('$siteadminname', $siteadminname, $command); + $command = str_replace('$siteadminemail', $siteadminemail, $command); // variables By Moses + $command = str_replace('$defaultlang', $defaultlang, $command); // variables By Moses + $command = str_replace('$sessionname', 'ls'.getRandomID().getRandomID().getRandomID().getRandomID(), $command); // variables By Moses + $command = str_replace('$databasetabletype', $databasetabletype, $command); + + + + + if(!$connect->Execute($command,false)) + { + print ("\n".$clang->gT("Executing").".....".$command."...".$clang->gT('Failed! Reason:')."\n".$connect->ErrorMsg()."\n\n"); + $success=1; + } + + + + $command = ''; + } else { + $command .= $line; + } + } + } + $connect->SetFetchMode(ADODB_FETCH_ASSOC); + if($success == 0) + { + print("Database $databasename on $databasetype POPULATED"); + print("\n\neverything went fine"); + return $success; + } + else + { + print("\n\nSomething is strange"); + print("\nplease check you Database and Settings"); + return $success; + } + + + // if (modify_database(dirname(__FILE__).'\create-'.$databasetype.'.sql')) + // { + + // print("\nDatabase $databasename on $databasetype POPULATED \n"); + // return 0; + // } else { + + // print("Could not populate $databasename on $databasetype\n"); + // return 1; + // } +} + +elseif (isset($argv[1]) && $argv[1]=='upgrade') + +{ + + $upgradedbtype=$databasetype; + if ($upgradedbtype=='mssql_n' || $upgradedbtype=='odbc_mssql' || $upgradedbtype=='odbtp') $upgradedbtype='mssql'; + + include ('upgrade-'.$upgradedbtype.'.php'); + $tables = $connect->MetaTables(); + + $usquery = "SELECT stg_value FROM ".db_table_name("settings_global")." where stg_name='DBVersion'"; + $usresult = db_execute_assoc($usquery); + $usrow = $usresult->FetchRow(); + if (intval($usrow['stg_value'])<$dbversionnumber) + { + print("Upgrading db to $dbversionnumber\n"); + db_upgrade(intval($usrow['stg_value'])); + } else { + print("Already at db version $dbversionnumber\n"); + } + return 0; +} +else +{ + print("LimeSurvey Commandline Install\n"); + print("Usage: cmd_install


    \n"; echo ""; @@ -62,10 +67,12 @@ if (!$database_exists) //Database named in config-defaults.php does not exist // TODO SQL: Portable to other databases?? switch ($databasetype) { + case 'mysqli': case 'mysql': $createDb=$connect->Execute("CREATE DATABASE `$dbname` DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci"); break; + case 'mssql_n': case 'odbc_mssql': - case 'mssql': $createDb=$connect->Execute("CREATE DATABASE [$dbname];"); + case 'odbtp': $createDb=$connect->Execute("CREATE DATABASE [$dbname];"); break; default: $createDb=$connect->Execute("CREATE DATABASE $dbname"); } diff --git a/include/limesurvey/admin/install/do_db_create.php b/include/limesurvey/admin/install/do_db_create.php deleted file mode 100644 index ca4f80b9..00000000 --- a/include/limesurvey/admin/install/do_db_create.php +++ /dev/null @@ -1,34 +0,0 @@ - DEFAULT SET TO EN FOR NOW -require_once($rootdir.'/classes/core/language.php'); -$clang = new limesurvey_lang("en"); -ob_implicit_flush(true); - -if ($databasetype=='mysql') {@$connect->Execute("ALTER DATABASE `$dbname` DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;");} //Set the collation also for manually created DBs - -if (modify_database(dirname(__FILE__).'/create-'.$databasetype.'.sql')) -{ - print("Creating $dbname on $databasetype\n"); - return 0; -} else { - print("Could not create $dbname on $databasetype\n"); - return 1; -} -?> diff --git a/include/limesurvey/admin/install/do_db_upgrade.php b/include/limesurvey/admin/install/do_db_upgrade.php deleted file mode 100644 index 260d7973..00000000 --- a/include/limesurvey/admin/install/do_db_upgrade.php +++ /dev/null @@ -1,41 +0,0 @@ - DEFAULT SET TO EN FOR NOW -require_once($rootdir.'/classes/core/language.php'); -$clang = new limesurvey_lang("en"); -ob_implicit_flush(true); - -global $connect, $databasetype, $dbprefix, $dbversionnumber, $clang; -include ('upgrade-'.$databasetype.'.php'); -$tables = $connect->MetaTables(); - -$usquery = "SELECT stg_value FROM ".db_table_name("settings_global")." where stg_name='DBVersion'"; -$usresult = db_execute_assoc($usquery); -$usrow = $usresult->FetchRow(); -if (intval($usrow['stg_value'])<$dbversionnumber) -{ - print("Upgrading db to $dbversionnumber\n"); - db_upgrade(intval($usrow['stg_value'])); -} else { - print("Already at db version $dbversionnumber\n"); -} - - -return 0; -?> diff --git a/include/limesurvey/admin/install/index.php b/include/limesurvey/admin/install/index.php index 77892e0f..132be275 100644 --- a/include/limesurvey/admin/install/index.php +++ b/include/limesurvey/admin/install/index.php @@ -10,7 +10,7 @@ * other free or open source software licenses. * See COPYRIGHT.php for copyright notices and details. * -* $Id: index.php 4346 2008-02-25 21:32:02Z c_schmitz $ +* $Id: index.php 6952 2009-05-27 09:40:07Z c_schmitz $ */ @@ -60,7 +60,7 @@ else $connect->database = $databasename; $connect->Execute("USE DATABASE `$databasename`"); $output=checkforupgrades(); - if (!isset($ouput)) {$adminoutput.='
    LimeSurvey Database is up to date. No action needed';} + if ($output== '') {$adminoutput.='
    LimeSurvey Database is up to date. No action needed';} else {$adminoutput.=$output;} $adminoutput.="
    Please log in."; @@ -73,7 +73,10 @@ function checkforupgrades() { global $connect, $databasetype, $dbprefix, $dbversionnumber, $clang; $adminoutput=''; - include ('upgrade-'.$databasetype.'.php'); + $upgradedbtype=$databasetype; + if ($upgradedbtype=='mssql_n' || $upgradedbtype=='odbc_mssql' || $upgradedbtype=='odbtp') $upgradedbtype='mssql'; + if ($upgradedbtype=='mysqli') $upgradedbtype='mysql'; + include ('upgrade-'.$upgradedbtype.'.php'); $tables = $connect->MetaTables(); $usquery = "SELECT stg_value FROM ".db_table_name("settings_global")." where stg_name='DBVersion'"; diff --git a/include/limesurvey/admin/install/resetadminpw.php b/include/limesurvey/admin/install/resetadminpw.php index 1368af72..a42662da 100644 --- a/include/limesurvey/admin/install/resetadminpw.php +++ b/include/limesurvey/admin/install/resetadminpw.php @@ -22,14 +22,17 @@ sendcacheheaders(); switch ($databasetype) { -case 'mysql': modify_database("",'UPDATE `prefix_users` set password=\'$defaultpass\' where uid=1;'); - echo $modifyoutput; flush(); - break; -case 'odbc_mssql':modify_database("",'UPDATE [prefix_users] set password=\'$defaultpass\' where uid=1;'); - echo $modifyoutput; flush(); - break; -case 'postgres':modify_database("",'UPDATE prefix_users set \"password\"=\'$defaultpass\' where uid=1;'); - echo $modifyoutput; flush(); - break; + case 'mysqli': + case 'mysql' : modify_database("",'UPDATE `prefix_users` set password=\'$defaultpass\' where uid=1;'); + echo $modifyoutput; flush(); + break; + case 'odbtp': + case 'mssql_n': + case 'odbc_mssql':modify_database("",'UPDATE [prefix_users] set password=\'$defaultpass\' where uid=1;'); + echo $modifyoutput; flush(); + break; + case 'postgres':modify_database("",'UPDATE prefix_users set \"password\"=\'$defaultpass\' where uid=1;'); + echo $modifyoutput; flush(); + break; } ?> diff --git a/include/limesurvey/admin/install/upgrade-mssql.php b/include/limesurvey/admin/install/upgrade-mssql.php new file mode 100644 index 00000000..372b27a2 --- /dev/null +++ b/include/limesurvey/admin/install/upgrade-mssql.php @@ -0,0 +1,445 @@ +\n"; + if ($oldversion < 111) { + // Language upgrades from version 110 to 111 since the language names did change + + $oldnewlanguages=array('german_informal'=>'german-informal', + 'cns'=>'cn-Hans', + 'cnt'=>'cn-Hant', + 'pt_br'=>'pt-BR', + 'gr'=>'el', + 'jp'=>'ja', + 'si'=>'sl', + 'se'=>'sv', + 'vn'=>'vi'); + + foreach ($oldnewlanguages as $oldlang=>$newlang) + { + modify_database("","update [prefix_answers] set [language`='$newlang' where language='$oldlang'"); echo $modifyoutput; flush(); + modify_database("","update [prefix_questions] set [language`='$newlang' where language='$oldlang'");echo $modifyoutput;flush(); + modify_database("","update [prefix_groups] set [language`='$newlang' where language='$oldlang'");echo $modifyoutput;flush(); + modify_database("","update [prefix_labels] set [language`='$newlang' where language='$oldlang'");echo $modifyoutput;flush(); + modify_database("","update [prefix_surveys] set [language`='$newlang' where language='$oldlang'");echo $modifyoutput;flush(); + modify_database("","update [prefix_surveys_languagesettings] set [surveyls_language`='$newlang' where surveyls_language='$oldlang'");echo $modifyoutput;flush(); + modify_database("","update [prefix_users] set [lang`='$newlang' where lang='$oldlang'");echo $modifyoutput;flush(); + } + + + + $resultdata=db_execute_assoc("select * from ".db_table_name("labelsets")); + while ($datarow = $resultdata->FetchRow()){ + $toreplace=$datarow['languages']; + $toreplace=str_replace('german_informal','german-informal',$toreplace); + $toreplace=str_replace('cns','cn-Hans',$toreplace); + $toreplace=str_replace('cnt','cn-Hant',$toreplace); + $toreplace=str_replace('pt_br','pt-BR',$toreplace); + $toreplace=str_replace('gr','el',$toreplace); + $toreplace=str_replace('jp','ja',$toreplace); + $toreplace=str_replace('si','sl',$toreplace); + $toreplace=str_replace('se','sv',$toreplace); + $toreplace=str_replace('vn','vi',$toreplace); + modify_database("","update [prefix_labelsets] set [languages`='$toreplace' where lid=".$datarow['lid']);echo $modifyoutput;flush(); + } + + + $resultdata=db_execute_assoc("select * from ".db_table_name("surveys")); + while ($datarow = $resultdata->FetchRow()){ + $toreplace=$datarow['additional_languages']; + $toreplace=str_replace('german_informal','german-informal',$toreplace); + $toreplace=str_replace('cns','cn-Hans',$toreplace); + $toreplace=str_replace('cnt','cn-Hant',$toreplace); + $toreplace=str_replace('pt_br','pt-BR',$toreplace); + $toreplace=str_replace('gr','el',$toreplace); + $toreplace=str_replace('jp','ja',$toreplace); + $toreplace=str_replace('si','sl',$toreplace); + $toreplace=str_replace('se','sv',$toreplace); + $toreplace=str_replace('vn','vi',$toreplace); + modify_database("","update [prefix_surveys] set [additional_languages`='$toreplace' where sid=".$datarow['sid']);echo $modifyoutput;flush(); + } + modify_database("","update [prefix_settings_global] set [stg_value]='111' where stg_name='DBVersion'"); echo $modifyoutput; + + } + + if ($oldversion < 112) { + //The size of the users_name field is now 64 char (20 char before version 112) + modify_database("","ALTER TABLE [prefix_users] ALTER COLUMN [users_name] VARCHAR( 64 ) NOT NULL"); echo $modifyoutput; flush(); + modify_database("","update [prefix_settings_global] set [stg_value]='112' where stg_name='DBVersion'"); echo $modifyoutput; flush(); + } + + if ($oldversion < 113) { + //No action needed + modify_database("","update [prefix_settings_global] set [stg_value]='113' where stg_name='DBVersion'"); echo $modifyoutput; flush(); + } + + if ($oldversion < 114) { + modify_database("","ALTER TABLE [prefix_saved_control] ALTER COLUMN [email] VARCHAR(320) NOT NULL"); echo $modifyoutput; flush(); + modify_database("","ALTER TABLE [prefix_surveys] ALTER COLUMN [adminemail] VARCHAR(320) NOT NULL"); echo $modifyoutput; flush(); + modify_database("","ALTER TABLE [prefix_users] ALTER COLUMN [email] VARCHAR(320) NOT NULL"); echo $modifyoutput; flush(); + modify_database("",'INSERT INTO [prefix_settings_global] VALUES (\'SessionName\', \'$sessionname\');');echo $modifyoutput; flush(); + modify_database("","update [prefix_settings_global] set [stg_value]='114' where stg_name='DBVersion'"); echo $modifyoutput; flush(); + } + + if ($oldversion < 126) { + modify_database("","ALTER TABLE [prefix_surveys] ADD [printanswers] CHAR(1) DEFAULT 'N'"); echo $modifyoutput; flush(); + modify_database("","ALTER TABLE [prefix_surveys] ADD [listpublic] CHAR(1) DEFAULT 'N'"); echo $modifyoutput; flush(); + upgrade_survey_tables117(); + upgrade_survey_tables118(); + //119 + modify_database("","CREATE TABLE [prefix_quota] ( + [id] int NOT NULL IDENTITY (1,1), + [sid] int, + [name] varchar(255) , + [qlimit] int , + [action] int , + [active] int NOT NULL default '1', + PRIMARY KEY ([id]) + );");echo $modifyoutput; flush(); + modify_database("","CREATE TABLE [prefix_quota_members] ( + [id] int NOT NULL IDENTITY (1,1), + [sid] int , + [qid] int , + [quota_id] int , + [code] varchar(5) , + PRIMARY KEY ([id]) + );");echo $modifyoutput; flush(); + + // Rename Norwegian language code from NO to NB + $oldnewlanguages=array('no'=>'nb'); + foreach ($oldnewlanguages as $oldlang=>$newlang) + { + modify_database("","update [prefix_answers] set [language]='$newlang' where [language]='$oldlang'");echo $modifyoutput;flush(); + modify_database("","update [prefix_questions] set [language]='$newlang' where [language]='$oldlang'");echo $modifyoutput;flush(); + modify_database("","update [prefix_groups] set [language]='$newlang' where [language]='$oldlang'");echo $modifyoutput;flush(); + modify_database("","update [prefix_labels] set [language]='$newlang' where [language]='$oldlang'");echo $modifyoutput;flush(); + modify_database("","update [prefix_surveys] set [language]='$newlang' where [language]='$oldlang'");echo $modifyoutput;flush(); + modify_database("","update [prefix_surveys_languagesettings] set [surveyls_language]='$newlang' where surveyls_language='$oldlang'");echo $modifyoutput;flush(); + modify_database("","update [prefix_users] set [lang]='$newlang' where lang='$oldlang'");echo $modifyoutput;flush(); + } + + $resultdata=db_execute_assoc("select * from ".db_table_name("labelsets")); + while ($datarow = $resultdata->FetchRow()){ + $toreplace=$datarow['languages']; + $toreplace2=str_replace('no','nb',$toreplace); + if ($toreplace2!=$toreplace) {modify_database("","update [prefix_labelsets] set [languages]='$toreplace' where lid=".$datarow['lid']);echo $modifyoutput;flush();} + } + + $resultdata=db_execute_assoc("select * from ".db_table_name("surveys")); + while ($datarow = $resultdata->FetchRow()){ + $toreplace=$datarow['additional_languages']; + $toreplace2=str_replace('no','nb',$toreplace); + if ($toreplace2!=$toreplace) {modify_database("","update [prefix_surveys] set [additional_languages]='$toreplace' where sid=".$datarow['sid']);echo $modifyoutput;flush();} + } + + modify_database("","ALTER TABLE [prefix_surveys] ADD [htmlemail] CHAR(1) DEFAULT 'N'"); echo $modifyoutput; flush(); + modify_database("","ALTER TABLE [prefix_surveys] ADD [usecaptcha] CHAR(1) DEFAULT 'N'"); echo $modifyoutput; flush(); + modify_database("","ALTER TABLE [prefix_surveys] ADD [tokenanswerspersistence] CHAR(1) DEFAULT 'N'"); echo $modifyoutput; flush(); + modify_database("","ALTER TABLE [prefix_users] ADD [htmleditormode] CHAR(7) DEFAULT 'default'"); echo $modifyoutput; flush(); + modify_database("","CREATE TABLE [prefix_templates_rights] ( + [uid] int NOT NULL, + [folder] varchar(255) NOT NULL, + [use] int NOT NULL, + PRIMARY KEY ([uid],[folder]) + );");echo $modifyoutput; flush(); + modify_database("","CREATE TABLE [prefix_templates] ( + [folder] varchar(255) NOT NULL, + [creator] int NOT NULL, + PRIMARY KEY ([folder]) + );");echo $modifyoutput; flush(); + //123 + modify_database("","ALTER TABLE [prefix_conditions] ALTER COLUMN [value] VARCHAR(255)"); echo $modifyoutput; flush(); + // There is no other way to remove the previous default value + /*modify_database("","DECLARE @STR VARCHAR(100) + SET @STR = ( + SELECT NAME + FROM SYSOBJECTS SO + JOIN SYSCONSTRAINTS SC ON SO.ID = SC.CONSTID + WHERE OBJECT_NAME(SO.PARENT_OBJ) = 'lime_labels' + AND SO.XTYPE = 'D' AND SC.COLID = + (SELECT COLID FROM SYSCOLUMNS WHERE ID = OBJECT_ID('lime_labels') AND NAME = 'title')) + SET @STR = 'ALTER TABLE lime_labels DROP CONSTRAINT ' + @STR + exec (@STR);"); echo $modifyoutput; flush(); */ + + modify_database("","ALTER TABLE [prefix_labels] ALTER COLUMN [title] varchar(4000)"); echo $modifyoutput; flush(); + //124 + modify_database("","ALTER TABLE [prefix_surveys] ADD [bounce_email] text"); echo $modifyoutput; flush(); + //125 + upgrade_token_tables125(); + modify_database("","EXEC sp_rename 'prefix_users.move_user','superadmin'"); echo $modifyoutput; flush(); + modify_database("","UPDATE [prefix_users] SET [superadmin]=1 where ([create_survey]=1 AND [create_user]=1 AND [delete_user]=1 AND [configurator]=1)"); echo $modifyoutput; flush(); + //126 + modify_database("","ALTER TABLE [prefix_questions] ADD [lid1] int NOT NULL DEFAULT '0'"); echo $modifyoutput; flush(); + modify_database("","UPDATE [prefix_conditions] SET [method]='==' where ( [method] is null) or [method]='' or [method]='0'"); echo $modifyoutput; flush(); + + modify_database("","update [prefix_settings_global] set [stg_value]='126' where stg_name='DBVersion'"); echo $modifyoutput; flush(); + } + + if ($oldversion < 127) { + modify_database("","create index [answers_idx2] on [prefix_answers] ([sortorder])"); echo $modifyoutput; + modify_database("","create index [assessments_idx2] on [prefix_assessments] ([sid])"); echo $modifyoutput; + modify_database("","create index [assessments_idx3] on [prefix_assessments] ([gid])"); echo $modifyoutput; + modify_database("","create index [conditions_idx2] on [prefix_conditions] ([qid])"); echo $modifyoutput; + modify_database("","create index [conditions_idx3] on [prefix_conditions] ([cqid])"); echo $modifyoutput; + modify_database("","create index [groups_idx2] on [prefix_groups] ([sid])"); echo $modifyoutput; + modify_database("","create index [question_attributes_idx2] on [prefix_question_attributes] ([qid])"); echo $modifyoutput; + modify_database("","create index [questions_idx2] on [prefix_questions] ([sid])"); echo $modifyoutput; + modify_database("","create index [questions_idx3] on [prefix_questions] ([gid])"); echo $modifyoutput; + modify_database("","create index [questions_idx4] on [prefix_questions] ([type])"); echo $modifyoutput; + modify_database("","create index [quota_idx2] on [prefix_quota] ([sid])"); echo $modifyoutput; + modify_database("","create index [saved_control_idx2] on [prefix_saved_control] ([sid])"); echo $modifyoutput; + modify_database("","create index [user_in_groups_idx1] on [prefix_user_in_groups] ([ugid], [uid])"); echo $modifyoutput; + modify_database("","update [prefix_settings_global] set [stg_value]='127' where stg_name='DBVersion'"); echo $modifyoutput; flush(); +} + + if ($oldversion < 128) { + upgrade_token_tables128(); + modify_database("","update [prefix_settings_global] set [stg_value]='128' where stg_name='DBVersion'"); echo $modifyoutput; flush(); + } + + if ($oldversion < 129) { + //128 + modify_database("","ALTER TABLE [prefix_surveys] ADD [startdate] DATETIME"); echo $modifyoutput; flush(); + modify_database("","ALTER TABLE [prefix_surveys] ADD [usestartdate] char(1) NOT NULL default 'N'"); echo $modifyoutput; flush(); + modify_database("","update [prefix_settings_global] set [stg_value]='129' where stg_name='DBVersion'"); echo $modifyoutput; flush(); + } + if ($oldversion < 130) + { + modify_database("","ALTER TABLE [prefix_conditions] ADD [scenario] int NOT NULL DEFAULT '1'"); echo $modifyoutput; flush(); + modify_database("","UPDATE [prefix_conditions] SET [scenario]=1 where ( [scenario] is null) or [scenario]='' or [scenario]=0"); echo $modifyoutput; flush(); + modify_database("","update [prefix_settings_global] set [stg_value]='130' where stg_name='DBVersion'"); echo $modifyoutput; flush(); + } + if ($oldversion < 131) + { + modify_database("","ALTER TABLE [prefix_surveys] ADD [publicstatistics] char(1) NOT NULL default 'N'"); echo $modifyoutput; flush(); + modify_database("","update [prefix_settings_global] set [stg_value]='131' where stg_name='DBVersion'"); echo $modifyoutput; flush(); + } + if ($oldversion < 132) + { + modify_database("","ALTER TABLE [prefix_surveys] ADD [publicgraphs] char(1) NOT NULL default 'N'"); echo $modifyoutput; flush(); + modify_database("","update [prefix_settings_global] set [stg_value]='132' where stg_name='DBVersion'"); echo $modifyoutput; flush(); + } + + if ($oldversion < 133) + { + modify_database("","ALTER TABLE [prefix_users] ADD [one_time_pw] text"); echo $modifyoutput; flush(); + // Add new assessment setting + modify_database("","ALTER TABLE [prefix_surveys] ADD [assessments] char(1) NOT NULL default 'N'"); echo $modifyoutput; flush(); + // add new assessment value fields to answers & labels + modify_database("","ALTER TABLE [prefix_answers] ADD [assessment_value] int NOT NULL default '0'"); echo $modifyoutput; flush(); + modify_database("","ALTER TABLE [prefix_labels] ADD [assessment_value] int NOT NULL default '0'"); echo $modifyoutput; flush(); + // copy any valid codes from code field to assessment field + modify_database("","update [prefix_answers] set [assessment_value]=CAST([code] as int)");// no output here is intended + modify_database("","update [prefix_labels] set [assessment_value]=CAST([code] as int)");// no output here is intended + // activate assessment where assesment rules exist + modify_database("","update [prefix_surveys] set [assessments]='Y' where [sid] in (SELECT [sid] FROM [prefix_assessments] group by [sid])"); echo $modifyoutput; flush(); + // add language field to assessment table + modify_database("","ALTER TABLE [prefix_assessments] ADD [language] varchar(20) NOT NULL default 'en'"); echo $modifyoutput; flush(); + // update language field with default language of that particular survey + modify_database("","update [prefix_assessments] set [language]=(select [language] from [prefix_surveys] where [sid]=[prefix_assessments].[sid])"); echo $modifyoutput; flush(); + // copy assessment link to message since from now on we will have HTML assignment messages + modify_database("","update [prefix_assessments] set [message]=cast([message] as varchar) +'
    '+[link]+''"); echo $modifyoutput; flush(); + // drop the old link field + modify_database("","ALTER TABLE [prefix_assessments] DROP COLUMN [link]"); echo $modifyoutput; flush(); + // change the primary index to include language + // and fix missing translations for assessments + upgrade_survey_tables133a(); + + // Add new fields to survey language settings + modify_database("","ALTER TABLE [prefix_surveys_languagesettings] ADD [surveyls_url] varchar(255)"); echo $modifyoutput; flush(); + modify_database("","ALTER TABLE [prefix_surveys_languagesettings] ADD [surveyls_endtext] text"); echo $modifyoutput; flush(); + // copy old URL fields ot language specific entries + modify_database("","update [prefix_surveys_languagesettings] set [surveyls_url]=(select [url] from [prefix_surveys] where [sid]=[prefix_surveys_languagesettings].[surveyls_survey_id])"); echo $modifyoutput; flush(); + // drop old URL field + mssql_drop_constraint('url','surveys'); + modify_database("","ALTER TABLE [prefix_surveys] DROP COLUMN [url]"); echo $modifyoutput; flush(); + + modify_database("","update [prefix_settings_global] set [stg_value]='133' where stg_name='DBVersion'"); echo $modifyoutput; flush(); + } + + if ($oldversion < 134) + { + // Add new assessment setting + modify_database("","ALTER TABLE [prefix_surveys] ADD [usetokens] char(1) NOT NULL default 'N'"); echo $modifyoutput; flush(); + mssql_drop_constraint('attribute1','surveys'); + mssql_drop_constraint('attribute2','surveys'); + modify_database("", "ALTER TABLE [prefix_surveys] ADD [attributedescriptions] TEXT;"); echo $modifyoutput; flush(); + modify_database("","ALTER TABLE [prefix_surveys] DROP COLUMN [attribute1]"); echo $modifyoutput; flush(); + modify_database("","ALTER TABLE [prefix_surveys] DROP COLUMN [attribute2]"); echo $modifyoutput; flush(); + upgrade_token_tables134(); + modify_database("","update [prefix_settings_global] set [stg_value]='134' where stg_name='DBVersion'"); echo $modifyoutput; flush(); + } + if ($oldversion < 135) + { + mssql_drop_constraint('value','question_attributes'); + modify_database("","ALTER TABLE [prefix_question_attributes] ALTER COLUMN [value] text"); echo $modifyoutput; flush(); + modify_database("","ALTER TABLE [prefix_answers] ALTER COLUMN [answer] varchar(8000)"); echo $modifyoutput; flush(); + modify_database("","update [prefix_settings_global] set [stg_value]='135' where stg_name='DBVersion'"); echo $modifyoutput; flush(); + } + if ($oldversion < 136) //New quota functions + { + modify_database("", "ALTER TABLE[prefix_quota] ADD [autoload_url] int NOT NULL default '0'"); echo $modifyoutput; flush(); + modify_database("","CREATE TABLE [prefix_quota_languagesettings] ( + [quotals_id] int NOT NULL IDENTITY (1,1), + [quotals_quota_id] int, + [quotals_language] varchar(45) NOT NULL default 'en', + [quotals_name] varchar(255), + [quotals_message] text, + [quotals_url] varchar(255), + [quotals_urldescrip] varchar(255), + PRIMARY KEY ([quotals_id]) + );");echo $modifyoutput; flush(); + modify_database("","update [prefix_settings_global] set [stg_value]='136' where stg_name='DBVersion'"); echo $modifyoutput; flush(); + } + if ($oldversion < 137) //New date format specs + { + modify_database("", "ALTER TABLE [prefix_surveys_languagesettings] ADD [surveyls_dateformat] int NOT NULL default '1'"); echo $modifyoutput; flush(); + modify_database("", "ALTER TABLE [prefix_users] ADD [dateformat] int NOT NULL default '1'"); echo $modifyoutput; flush(); + modify_database("", "update [prefix_surveys] set startdate=null where usestartdate='N'"); echo $modifyoutput; flush(); + modify_database("", "update [prefix_surveys] set expires=null where useexpiry='N'"); echo $modifyoutput; flush(); + mssql_drop_constraint('usestartdate','surveys'); + mssql_drop_constraint('useexpiry','surveys'); + modify_database("", "ALTER TABLE [prefix_surveys] DROP COLUMN usestartdate"); echo $modifyoutput; flush(); + modify_database("", "ALTER TABLE [prefix_surveys] DROP COLUMN useexpiry"); echo $modifyoutput; flush(); + modify_database("","update [prefix_settings_global] set [stg_value]='137' where stg_name='DBVersion'"); echo $modifyoutput; flush(); + } + + if ($oldversion < 138) //Modify quota field + { + modify_database("", "ALTER TABLE [prefix_quota_members] ALTER COLUMN [code] VARCHAR(11) NULL"); echo $modifyoutput; flush(); + modify_database("", "UPDATE [prefix_settings_global] SET [stg_value]='138' WHERE stg_name='DBVersion'"); echo $modifyoutput; flush(); + } + + return true; +} + + + +function upgrade_survey_tables117() +{ + global $modifyoutput; + $surveyidquery = "SELECT sid FROM ".db_table_name('surveys')." WHERE active='Y' and datestamp='Y'"; + $surveyidresult = db_execute_num($surveyidquery); + if (!$surveyidresult) {return "Database Error";} + else + { + while ( $sv = $surveyidresult->FetchRow() ) + { + modify_database("","ALTER TABLE ".db_table_name('survey_'.$sv[0])." ADD [startdate] datetime"); echo $modifyoutput; flush(); + } + } +} + + +function upgrade_survey_tables118() +{ + global $connect,$modifyoutput,$dbprefix; + $tokentables=$connect->MetaTables('TABLES',false,$dbprefix."tokens%"); + foreach ($tokentables as $sv) + { + modify_database("","ALTER TABLE ".$sv." ALTER COLUMN [token] VARCHAR(36)"); echo $modifyoutput; flush(); + } +} + + +function upgrade_token_tables125() +{ + global $connect,$modifyoutput,$dbprefix; + $tokentables=$connect->MetaTables('TABLES',false,$dbprefix."tokens%"); + foreach ($tokentables as $sv) + { + modify_database("","ALTER TABLE ".$sv." ADD [emailstatus] VARCHAR(300) DEFAULT 'OK'"); echo $modifyoutput; flush(); + } +} + + +function upgrade_token_tables128() +{ + global $connect,$modifyoutput,$dbprefix; + $tokentables=$connect->MetaTables('TABLES',false,$dbprefix."tokens%"); + foreach ($tokentables as $sv) + { + modify_database("","ALTER TABLE ".$sv." ADD [remindersent] VARCHAR(17) DEFAULT 'OK'"); echo $modifyoutput; flush(); + modify_database("","ALTER TABLE ".$sv." ADD [remindercount] int DEFAULT '0'"); echo $modifyoutput; flush(); + } +} + + +function upgrade_survey_tables133a() +{ + global $dbprefix, $connect, $modifyoutput; + // find out the constraint name of the old primary key + $pkquery = " SELECT CONSTRAINT_NAME " + ."FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS " + ."WHERE (TABLE_NAME = '{$dbprefix}assessments') AND (CONSTRAINT_TYPE = 'PRIMARY KEY')"; + + $primarykey=$connect->GetRow($pkquery); + if ($primarykey!=false) + { + modify_database("","ALTER TABLE [prefix_assessments] DROP CONSTRAINT {$primarykey[0]}"); echo $modifyoutput; flush(); + } + // add the new primary key + modify_database("","ALTER TABLE [prefix_assessments] ADD CONSTRAINT pk_assessments_id_lang PRIMARY KEY ([id],[language])"); echo $modifyoutput; flush(); + $surveyidquery = "SELECT sid,additional_languages FROM ".db_table_name('surveys'); + $surveyidresult = db_execute_num($surveyidquery); + while ( $sv = $surveyidresult->FetchRow() ) + { + FixLanguageConsistency($sv[0],$sv[1]); + } +} + + +function upgrade_token_tables134() +{ + global $connect,$modifyoutput,$dbprefix; + $tokentables=$connect->MetaTables('TABLES',false,$dbprefix."tokens%"); + foreach ($tokentables as $sv) + { + modify_database("","ALTER TABLE ".$sv." ADD [validfrom] DATETIME"); echo $modifyoutput; flush(); + modify_database("","ALTER TABLE ".$sv." ADD [validuntil] DATETIME"); echo $modifyoutput; flush(); + } +} + +function mssql_drop_constraint($fieldname, $tablename) +{ + global $dbprefix, $connect, $modifyoutput; + // find out the name of the default constraint + // Did I already mention that this is the most suckiest thing I have ever seen in MSSQL database? + // It proves how badly designer some Microsoft software is! + $dfquery ="SELECT c_obj.name AS constraint_name + FROM sys.sysobjects AS c_obj INNER JOIN + sys.sysobjects AS t_obj ON c_obj.parent_obj = t_obj.id INNER JOIN + sys.sysconstraints AS con ON c_obj.id = con.constid INNER JOIN + sys.syscolumns AS col ON t_obj.id = col.id AND con.colid = col.colid + WHERE (c_obj.xtype = 'D') AND (col.name = '$fieldname') AND (t_obj.name='$dbprefix$tablename')"; + $defaultname=$connect->GetRow($dfquery); + if ($defaultname!=false) + { + modify_database("","ALTER TABLE [prefix_$tablename] DROP CONSTRAINT {$defaultname[0]}"); echo $modifyoutput; flush(); + } + + +} + + +?> diff --git a/include/limesurvey/admin/install/upgrade-mysql.php b/include/limesurvey/admin/install/upgrade-mysql.php index 7439e672..28df1e2f 100644 --- a/include/limesurvey/admin/install/upgrade-mysql.php +++ b/include/limesurvey/admin/install/upgrade-mysql.php @@ -10,7 +10,7 @@ * other free or open source software licenses. * See COPYRIGHT.php for copyright notices and details. * -* $Id: upgrade-mysql.php 4467 2008-03-16 21:19:53Z c_schmitz $ +* $Id: upgrade-mysql.php 7108 2009-06-15 05:43:21Z jcleeland $ */ // There will be a file for each database (accordingly named to the dbADO scheme) @@ -115,12 +115,12 @@ echo str_pad('Loading... ',4096)."
    \n"; modify_database("","CREATE TABLE `prefix_quota` ( `id` int(11) NOT NULL auto_increment, `sid` int(11) default NULL, - `name` varchar(255) collate utf8_unicode_ci default NULL, `qlimit` int(8) default NULL, + `name` varchar(255) collate utf8_unicode_ci default NULL, `action` int(2) default NULL, `active` int(1) NOT NULL default '1', PRIMARY KEY (`id`) - ) TYPE=$databasetabletype CHARACTER SET utf8 COLLATE utf8_unicode_ci;"); echo $modifyoutput; flush(); + ) ENGINE=$databasetabletype CHARACTER SET utf8 COLLATE utf8_unicode_ci;"); echo $modifyoutput; flush(); modify_database("","CREATE TABLE `prefix_quota_members` ( `id` int(11) NOT NULL auto_increment, `sid` int(11) default NULL, @@ -129,7 +129,7 @@ echo str_pad('Loading... ',4096)."
    \n"; `code` varchar(5) collate utf8_unicode_ci default NULL, PRIMARY KEY (`id`), UNIQUE KEY `sid` (`sid`,`qid`,`quota_id`,`code`) - ) TYPE=$databasetabletype CHARACTER SET utf8 COLLATE utf8_unicode_ci;"); echo $modifyoutput; flush(); + ) ENGINE=$databasetabletype CHARACTER SET utf8 COLLATE utf8_unicode_ci;"); echo $modifyoutput; flush(); // Rename Norwegian language code from NO to NB $oldnewlanguages=array('no'=>'nb'); @@ -169,12 +169,12 @@ echo str_pad('Loading... ',4096)."
    \n"; `folder` varchar(255) NOT NULL, `use` int(1) NOT NULL, PRIMARY KEY (`uid`,`folder`) - ) TYPE=$databasetabletype CHARACTER SET utf8 COLLATE utf8_unicode_ci;"); echo $modifyoutput; flush(); + ) ENGINE=$databasetabletype CHARACTER SET utf8 COLLATE utf8_unicode_ci;"); echo $modifyoutput; flush(); modify_database("","CREATE TABLE `prefix_templates` ( `folder` varchar(255) NOT NULL, `creator` int(11) NOT NULL, PRIMARY KEY (`folder`) - ) TYPE=$databasetabletype CHARACTER SET utf8 COLLATE utf8_unicode_ci;"); echo $modifyoutput; flush(); + ) ENGINE=$databasetabletype CHARACTER SET utf8 COLLATE utf8_unicode_ci;"); echo $modifyoutput; flush(); //123 modify_database("","ALTER TABLE `prefix_conditions` CHANGE `value` `value` VARCHAR(255) NOT NULL default ''"); echo $modifyoutput; flush(); @@ -188,16 +188,140 @@ echo str_pad('Loading... ',4096)."
    \n"; modify_database("","ALTER TABLE `prefix_users` DROP COLUMN `move_user`"); echo $modifyoutput; flush(); //126 modify_database("","ALTER TABLE `prefix_questions` ADD `lid1` integer NOT NULL default '0'"); echo $modifyoutput; flush(); - modify_database("","UPDATE `prefix_conditions` SET `method`='==' where (`method` is null) or `method`=''"); echo $modifyoutput; flush(); + modify_database("","UPDATE `prefix_conditions` SET `method`='==' where (`method` is null) or `method`='' or `method`='0'"); echo $modifyoutput; flush(); modify_database("","update `prefix_settings_global` set `stg_value`='126' where stg_name='DBVersion'"); echo $modifyoutput; flush(); } + + if ($oldversion < 127) { + modify_database("","create index `assessments_idx2` on `prefix_assessments` (`sid`)"); echo $modifyoutput; flush(); + modify_database("","create index `assessments_idx3` on `prefix_assessments` (`gid`)"); echo $modifyoutput; flush(); + modify_database("","create index `conditions_idx2` on `prefix_conditions` (`qid`)"); echo $modifyoutput; flush(); + modify_database("","create index `groups_idx2` on `prefix_groups` (`sid`)"); echo $modifyoutput; flush(); + modify_database("","create index `questions_idx2` on `prefix_questions` (`sid`)"); echo $modifyoutput; flush(); + modify_database("","create index `questions_idx3` on `prefix_questions` (`gid`)"); echo $modifyoutput; flush(); + modify_database("","create index `question_attributes_idx2` on `prefix_question_attributes` (`qid`)"); echo $modifyoutput; flush(); + modify_database("","create index `quota_idx2` on `prefix_quota` (`sid`)"); echo $modifyoutput; flush(); + modify_database("","create index `saved_control_idx2` on `prefix_saved_control` (`sid`)"); echo $modifyoutput; flush(); + modify_database("","create index `user_in_groups_idx1` on `prefix_user_in_groups` (`ugid`, `uid`)"); echo $modifyoutput; flush(); + modify_database("","create index `answers_idx2` on `prefix_answers` (`sortorder`)"); echo $modifyoutput; flush(); + modify_database("","create index `conditions_idx3` on `prefix_conditions` (`cqid`)"); echo $modifyoutput; flush(); + modify_database("","create index `questions_idx4` on `prefix_questions` (`type`)"); echo $modifyoutput; flush(); + modify_database("","update `prefix_settings_global` set `stg_value`='127' where stg_name='DBVersion'"); echo $modifyoutput; flush(); + } + + if ($oldversion < 128) { + //128 + upgrade_token_tables128(); + modify_database("","update `prefix_settings_global` set `stg_value`='128' where stg_name='DBVersion'"); echo $modifyoutput; flush(); + } + if ($oldversion < 129) { + //129 + modify_database("","ALTER TABLE `prefix_surveys` ADD `startdate` DATETIME"); echo $modifyoutput; flush(); + modify_database("","ALTER TABLE `prefix_surveys` ADD `usestartdate` varchar(1) NOT NULL default 'N'"); echo $modifyoutput; flush(); + modify_database("","update `prefix_settings_global` set `stg_value`='129' where stg_name='DBVersion'"); echo $modifyoutput; flush(); + } + if ($oldversion < 130) + { + modify_database("","ALTER TABLE `prefix_conditions` ADD `scenario` integer NOT NULL default '1' AFTER `qid`"); echo $modifyoutput; flush(); + modify_database("","UPDATE `prefix_conditions` SET `scenario`=1 where (`scenario` is null) or `scenario`='' or `scenario`=0"); echo $modifyoutput; flush(); + modify_database("","update `prefix_settings_global` set `stg_value`='130' where stg_name='DBVersion'"); echo $modifyoutput; flush(); + } + if ($oldversion < 131) + { + modify_database("","ALTER TABLE `prefix_surveys` ADD `publicstatistics` varchar(1) NOT NULL default 'N'"); echo $modifyoutput; flush(); + modify_database("","update `prefix_settings_global` set `stg_value`='131' where stg_name='DBVersion'"); echo $modifyoutput; flush(); + } + if ($oldversion < 132) + { + modify_database("","ALTER TABLE `prefix_surveys` ADD `publicgraphs` varchar(1) NOT NULL default 'N'"); echo $modifyoutput; flush(); + modify_database("","update `prefix_settings_global` set `stg_value`='132' where stg_name='DBVersion'"); echo $modifyoutput; flush(); + } + + if ($oldversion < 133) + { + modify_database("","ALTER TABLE `prefix_users` ADD `one_time_pw` blob"); echo $modifyoutput; flush(); + // Add new assessment setting + modify_database("","ALTER TABLE `prefix_surveys` ADD `assessments` varchar(1) NOT NULL default 'N'"); echo $modifyoutput; flush(); + // add new assessment value fields to answers & labels + modify_database("","ALTER TABLE `prefix_answers` ADD `assessment_value` int(11) NOT NULL default '0'"); echo $modifyoutput; flush(); + modify_database("","ALTER TABLE `prefix_labels` ADD `assessment_value` int(11) NOT NULL default '0'"); echo $modifyoutput; flush(); + // copy any valid codes from code field to assessment field + modify_database("","update `prefix_answers` set `assessment_value`=CAST(`code` as SIGNED) where `code` REGEXP '^-?[0-9]+$'");echo $modifyoutput; flush(); + modify_database("","update `prefix_labels` set `assessment_value`=CAST(`code` as SIGNED) where `code` REGEXP '^-?[0-9]+$'");echo $modifyoutput; flush(); + // activate assessment where assesment rules exist + modify_database("","update `prefix_surveys` set `assessments`='Y' where `sid` in (SELECT `sid` FROM `prefix_assessments` group by `sid`)"); echo $modifyoutput; flush(); + // add language field to assessment table + modify_database("","ALTER TABLE `prefix_assessments` ADD `language` varchar(20) NOT NULL default 'en'"); echo $modifyoutput; flush(); + // update language field with default language of that particular survey + modify_database("","update `prefix_assessments` set `language`=(select `language` from `prefix_surveys` where `sid`=`prefix_assessments`.`sid`)"); echo $modifyoutput; flush(); + // copy assessment link to message since from now on we will have HTML assignment messages + modify_database("","update `prefix_assessments` set `message`=concat(replace(`message`,'/''',''''),'
    ',`link`,'')"); echo $modifyoutput; flush(); + // drop the old link field + modify_database("","ALTER TABLE `prefix_assessments` DROP COLUMN `link`"); echo $modifyoutput; flush(); + // change the primary index to include language + modify_database("","ALTER TABLE `prefix_assessments` DROP PRIMARY KEY, ADD PRIMARY KEY USING BTREE(`id`, `language`)"); echo $modifyoutput; flush(); + //finally fix missing translations for assessments + upgrade_survey_tables133(); + // Add new fields to survey language settings + modify_database("","ALTER TABLE `prefix_surveys_languagesettings` ADD `surveyls_url` varchar(255)"); echo $modifyoutput; flush(); + modify_database("","ALTER TABLE `prefix_surveys_languagesettings` ADD `surveyls_endtext` text"); echo $modifyoutput; flush(); + // copy old URL fields ot language specific entries + modify_database("","update `prefix_surveys_languagesettings` set `surveyls_url`=(select `url` from `prefix_surveys` where `sid`=`prefix_surveys_languagesettings`.`surveyls_survey_id`)"); echo $modifyoutput; flush(); + // drop old URL field + modify_database("","ALTER TABLE `prefix_surveys` DROP COLUMN `url`"); echo $modifyoutput; flush(); + modify_database("","update `prefix_settings_global` set `stg_value`='133' where stg_name='DBVersion'"); echo $modifyoutput; flush(); + } + if ($oldversion < 134) + { + // Add new tokens setting + modify_database("","ALTER TABLE `prefix_surveys` ADD `usetokens` varchar(1) NOT NULL default 'N'"); echo $modifyoutput; flush(); + modify_database("","ALTER TABLE `prefix_surveys` ADD `attributedescriptions` TEXT;"); echo $modifyoutput; flush(); + modify_database("","ALTER TABLE `prefix_surveys` DROP COLUMN `attribute1`"); echo $modifyoutput; flush(); + modify_database("","ALTER TABLE `prefix_surveys` DROP COLUMN `attribute2`"); echo $modifyoutput; flush(); + upgrade_token_tables134(); + modify_database("","update `prefix_settings_global` set `stg_value`='134' where stg_name='DBVersion'"); echo $modifyoutput; flush(); + } + if ($oldversion < 135) + { + modify_database("","ALTER TABLE `prefix_question_attributes` MODIFY `value` text"); echo $modifyoutput; flush(); + modify_database("","UPDATE `prefix_settings_global` SET `stg_value`='135' WHERE stg_name='DBVersion'"); echo $modifyoutput; flush(); + } + if ($oldversion < 136) //New Quota Functions + { + modify_database("","ALTER TABLE `prefix_quota` ADD `autoload_url` int(1) NOT NULL default '0'"); echo $modifyoutput; flush(); + modify_database("","CREATE TABLE `prefix_quota_languagesettings` ( + `quotals_id` int(11) NOT NULL auto_increment, + `quotals_quota_id` int(11) NOT NULL default '0', + `quotals_language` varchar(45) NOT NULL default 'en', + `quotals_name` varchar(255) collate utf8_unicode_ci default NULL, + `quotals_message` text NOT NULL, + `quotals_url` varchar(255), + `quotals_urldescrip` varchar(255), + PRIMARY KEY (`quotals_id`) + ) ENGINE=$databasetabletype CHARACTER SET utf8 COLLATE utf8_unicode_ci;"); echo $modifyoutput; flush(); + modify_database("","UPDATE `prefix_settings_global` SET `stg_value`='136' WHERE stg_name='DBVersion'"); echo $modifyoutput; flush(); + } + if ($oldversion < 137) //New Quota Functions + { + modify_database("", "ALTER TABLE `prefix_surveys_languagesettings` ADD `surveyls_dateformat` int(1) NOT NULL default '1'"); echo $modifyoutput; flush(); + modify_database("", "ALTER TABLE `prefix_users` ADD `dateformat` int(1) NOT NULL default '1'"); echo $modifyoutput; flush(); + modify_database("", "UPDATE `prefix_surveys` set `startdate`=null where `usestartdate`='N'"); echo $modifyoutput; flush(); + modify_database("", "UPDATE `prefix_surveys` set `expires`=null where `useexpiry`='N'"); echo $modifyoutput; flush(); + modify_database("", "ALTER TABLE `prefix_surveys` DROP COLUMN `useexpiry`"); echo $modifyoutput; flush(); + modify_database("", "ALTER TABLE `prefix_surveys` DROP COLUMN `usestartdate`"); echo $modifyoutput; flush(); + modify_database("", "UPDATE `prefix_settings_global` SET `stg_value`='137' WHERE stg_name='DBVersion'"); echo $modifyoutput; flush(); + } + if ($oldversion < 138) //Modify quota field + { + modify_database("", "ALTER TABLE `prefix_quota_members` CHANGE `code` `code` VARCHAR(11) collate utf8_unicode_ci default NULL"); echo $modifyoutput; flush(); + modify_database("", "UPDATE `prefix_settings_global` SET `stg_value`='138' WHERE stg_name='DBVersion'"); echo $modifyoutput; flush(); + } + return true; } - - function upgrade_survey_tables117() { global $modifyoutput; @@ -205,12 +329,12 @@ function upgrade_survey_tables117() $surveyidresult = db_execute_num($surveyidquery); if (!$surveyidresult) {return "Database Error";} else - { + { while ( $sv = $surveyidresult->FetchRow() ) - { + { modify_database("","ALTER TABLE ".db_table_name('survey_'.$sv[0])." ADD `startdate` datetime AFTER `datestamp`"); echo $modifyoutput; flush(); - } } + } } function upgrade_survey_tables118() @@ -238,61 +362,105 @@ function upgrade_token_tables125() { while ( $sv = $surveyidresult->FetchRow() ) { - modify_database("","ALTER TABLE ".$sv[0]." ADD `emailstatus` varchar(255) NOT NULL DEFAULT 'OK'"); echo $modifyoutput; flush(); + modify_database("","ALTER TABLE ".$sv[0]." ADD `emailstatus` varchar(300) NOT NULL DEFAULT 'OK'"); echo $modifyoutput; flush(); + } + } +} + +// Add the reminders tracking fields +function upgrade_token_tables128() +{ + global $modifyoutput,$dbprefix; + $surveyidquery = "SHOW TABLES LIKE '".$dbprefix."tokens%'"; + $surveyidresult = db_execute_num($surveyidquery); + if (!$surveyidresult) {return "Database Error";} + else + { + while ( $sv = $surveyidresult->FetchRow() ) + { + modify_database("","ALTER TABLE ".$sv[0]." ADD `remindersent` VARCHAR(17) DEFAULT 'N'"); echo $modifyoutput; flush(); + modify_database("","ALTER TABLE ".$sv[0]." ADD `remindercount` INT(11) DEFAULT 0"); echo $modifyoutput; flush(); } } } + + +function upgrade_survey_tables133() +{ + $surveyidquery = "SELECT sid,additional_languages FROM ".db_table_name('surveys'); + $surveyidresult = db_execute_num($surveyidquery); + while ( $sv = $surveyidresult->FetchRow() ) + { + FixLanguageConsistency($sv[0],$sv[1]); + } +} + + +// Add the reminders tracking fields +function upgrade_token_tables134() +{ + global $modifyoutput,$dbprefix; + $surveyidquery = "SHOW TABLES LIKE '".$dbprefix."tokens%'"; + $surveyidresult = db_execute_num($surveyidquery); + if (!$surveyidresult) {return "Database Error";} + else + { + while ( $sv = $surveyidresult->FetchRow() ) + { + modify_database("","ALTER TABLE ".$sv[0]." ADD `validfrom` Datetime"); echo $modifyoutput; flush(); + modify_database("","ALTER TABLE ".$sv[0]." ADD `validuntil` Datetime"); echo $modifyoutput; flush(); + } + } +} + function fix_mysql_collation() { -global $connect, $modifyoutput, $dbprefix; -$sql = 'SHOW TABLE STATUS'; -$result = db_execute_assoc($sql); -if (!$result) { - $modifyoutput .= 'SHOW TABLE - SQL Error'; + global $connect, $modifyoutput, $dbprefix; + $sql = 'SHOW TABLE STATUS'; + $result = db_execute_assoc($sql); + if (!$result) { + $modifyoutput .= 'SHOW TABLE - SQL Error'; + } + + while ( $tables = $result->FetchRow() ) { + // Loop through all tables in this database + $table = $tables['Name']; + $tablecollation=$tables['Collation']; + if (strpos($table,'old_')===false && ($dbprefix=='' || ($dbprefix!='' && strpos($table,$dbprefix)!==false))) + { + if ($tablecollation!='utf8_unicode_ci') + { + modify_database("","ALTER TABLE $table COLLATE utf8_unicode_ci"); + echo $modifyoutput; flush(); + } + + # Now loop through all the fields within this table + $result2 = db_execute_assoc("SHOW FULL COLUMNS FROM ".$table); + while ( $column = $result2->FetchRow()) + { + if ($column['Collation']!= 'utf8_unicode_ci' ) + { + $field_name = $column['Field']; + $field_type = $column['Type']; + $field_default = $column['Default']; + if ($field_default!='NULL') {$field_default="'".$field_default."'";} + # Change text based fields + $skipped_field_types = array('char', 'text', 'enum', 'set'); + + foreach ( $skipped_field_types as $type ) + { + if ( strpos($field_type, $type) !== false ) + { + $modstatement="ALTER TABLE $table CHANGE `$field_name` `$field_name` $field_type CHARACTER SET utf8 COLLATE utf8_unicode_ci"; + if ($type!='text') {$modstatement.=" DEFAULT $field_default";} + modify_database("",$modstatement); + echo $modifyoutput; flush(); + } + } + } + } + } } - -while ( $tables = $result->FetchRow() ) { -// Loop through all tables in this database - $table = $tables['Name']; - $tablecollation=$tables['Collation']; - if (strpos($table,'old_')===false && ($dbprefix=='' || ($dbprefix!='' && strpos($table,$dbprefix)!==false))) - { - if ($tablecollation!='utf8_unicode_ci') - { - modify_database("","ALTER TABLE $table COLLATE utf8_unicode_ci"); - echo $modifyoutput; flush(); - } - - # Now loop through all the fields within this table - $result2 = db_execute_assoc("SHOW FULL COLUMNS FROM ".$table); - while ( $column = $result2->FetchRow()) - { - if ($column['Collation']!= 'utf8_unicode_ci' ) - { - $field_name = $column['Field']; - $field_type = $column['Type']; - $field_default = $column['Default']; - if ($field_default!='NULL') {$field_default="'".$field_default."'";} - # Change text based fields - $skipped_field_types = array('char', 'text', 'enum', 'set'); - - foreach ( $skipped_field_types as $type ) - { - if ( strpos($field_type, $type) !== false ) - { - $modstatement="ALTER TABLE $table CHANGE `$field_name` `$field_name` $field_type CHARACTER SET utf8 COLLATE utf8_unicode_ci"; - if ($type!='text') {$modstatement.=" DEFAULT $field_default";} - modify_database("",$modstatement); - echo $modifyoutput; flush(); - } - } - } - } - } } -} - - -?> diff --git a/include/limesurvey/admin/install/upgrade-odbc_mssql.php b/include/limesurvey/admin/install/upgrade-odbc_mssql.php deleted file mode 100644 index 77ed92e8..00000000 --- a/include/limesurvey/admin/install/upgrade-odbc_mssql.php +++ /dev/null @@ -1,240 +0,0 @@ -\n"; - if ($oldversion < 111) { - // Language upgrades from version 110 to 111 since the language names did change - - $oldnewlanguages=array('german_informal'=>'german-informal', - 'cns'=>'cn-Hans', - 'cnt'=>'cn-Hant', - 'pt_br'=>'pt-BR', - 'gr'=>'el', - 'jp'=>'ja', - 'si'=>'sl', - 'se'=>'sv', - 'vn'=>'vi'); - - foreach ($oldnewlanguages as $oldlang=>$newlang) - { - modify_database("","update [prefix_answers] set [language`='$newlang' where language='$oldlang'"); echo $modifyoutput; flush(); - modify_database("","update [prefix_questions] set [language`='$newlang' where language='$oldlang'");echo $modifyoutput;flush(); - modify_database("","update [prefix_groups] set [language`='$newlang' where language='$oldlang'");echo $modifyoutput;flush(); - modify_database("","update [prefix_labels] set [language`='$newlang' where language='$oldlang'");echo $modifyoutput;flush(); - modify_database("","update [prefix_surveys] set [language`='$newlang' where language='$oldlang'");echo $modifyoutput;flush(); - modify_database("","update [prefix_surveys_languagesettings] set [surveyls_language`='$newlang' where surveyls_language='$oldlang'");echo $modifyoutput;flush(); - modify_database("","update [prefix_users] set [lang`='$newlang' where lang='$oldlang'");echo $modifyoutput;flush(); - } - - - - $resultdata=db_execute_assoc("select * from ".db_table_name("labelsets")); - while ($datarow = $resultdata->FetchRow()){ - $toreplace=$datarow['languages']; - $toreplace=str_replace('german_informal','german-informal',$toreplace); - $toreplace=str_replace('cns','cn-Hans',$toreplace); - $toreplace=str_replace('cnt','cn-Hant',$toreplace); - $toreplace=str_replace('pt_br','pt-BR',$toreplace); - $toreplace=str_replace('gr','el',$toreplace); - $toreplace=str_replace('jp','ja',$toreplace); - $toreplace=str_replace('si','sl',$toreplace); - $toreplace=str_replace('se','sv',$toreplace); - $toreplace=str_replace('vn','vi',$toreplace); - modify_database("","update [prefix_labelsets] set [languages`='$toreplace' where lid=".$datarow['lid']);echo $modifyoutput;flush(); - } - - - $resultdata=db_execute_assoc("select * from ".db_table_name("surveys")); - while ($datarow = $resultdata->FetchRow()){ - $toreplace=$datarow['additional_languages']; - $toreplace=str_replace('german_informal','german-informal',$toreplace); - $toreplace=str_replace('cns','cn-Hans',$toreplace); - $toreplace=str_replace('cnt','cn-Hant',$toreplace); - $toreplace=str_replace('pt_br','pt-BR',$toreplace); - $toreplace=str_replace('gr','el',$toreplace); - $toreplace=str_replace('jp','ja',$toreplace); - $toreplace=str_replace('si','sl',$toreplace); - $toreplace=str_replace('se','sv',$toreplace); - $toreplace=str_replace('vn','vi',$toreplace); - modify_database("","update [prefix_surveys] set [additional_languages`='$toreplace' where sid=".$datarow['sid']);echo $modifyoutput;flush(); - } - modify_database("","update [prefix_settings_global] set [stg_value`='111' where stg_name='DBVersion'"); echo $modifyoutput; - - } - - if ($oldversion < 112) { - //The size of the users_name field is now 64 char (20 char before version 112) - modify_database("","ALTER TABLE [prefix_users] ALTER COLUMN [users_name] VARCHAR( 64 ) NOT NULL"); echo $modifyoutput; flush(); - modify_database("","update [prefix_settings_global] set [stg_value`='112' where stg_name='DBVersion'"); echo $modifyoutput; flush(); - } - - if ($oldversion < 113) { - //No action needed - modify_database("","update [prefix_settings_global] set [stg_value]='113' where stg_name='DBVersion'"); echo $modifyoutput; flush(); - } - - if ($oldversion < 114) { - modify_database("","ALTER TABLE [prefix_saved_control] ALTER COLUMN [email] VARCHAR(320) NOT NULL"); echo $modifyoutput; flush(); - modify_database("","ALTER TABLE [prefix_surveys] ALTER COLUMN [adminemail] VARCHAR(320) NOT NULL"); echo $modifyoutput; flush(); - modify_database("","ALTER TABLE [prefix_users] ALTER COLUMN [email] VARCHAR(320) NOT NULL"); echo $modifyoutput; flush(); - modify_database("",'INSERT INTO [prefix_settings_global] VALUES (\'SessionName\', \'$sessionname\');');echo $modifyoutput; flush(); - modify_database("","update [prefix_settings_global] set [stg_value]='114' where stg_name='DBVersion'"); echo $modifyoutput; flush(); - } - - if ($oldversion < 126) { - modify_database("","ALTER TABLE [prefix_surveys] ADD [printanswers] CHAR(1) DEFAULT 'N'"); echo $modifyoutput; flush(); - modify_database("","ALTER TABLE [prefix_surveys] ADD [listpublic] CHAR(1) DEFAULT 'N'"); echo $modifyoutput; flush(); - upgrade_survey_tables117(); - upgrade_survey_tables118(); - //119 - modify_database("","CREATE TABLE [prefix_quota] ( - [id] int NOT NULL IDENTITY (1,1), - [sid] int, - [name] varchar(255) , - [qlimit] int , - [action] int , - [active] int NOT NULL default '1', - PRIMARY KEY ([id]) - );");echo $modifyoutput; flush(); - modify_database("","CREATE TABLE [prefix_quota_members] ( - [id] int NOT NULL IDENTITY (1,1), - [sid] int , - [qid] int , - [quota_id] int , - [code] varchar(5) , - PRIMARY KEY ([id]) - );");echo $modifyoutput; flush(); - - // Rename Norwegian language code from NO to NB - $oldnewlanguages=array('no'=>'nb'); - foreach ($oldnewlanguages as $oldlang=>$newlang) - { - modify_database("","update [prefix_answers] set [language]='$newlang' where [language]='$oldlang'");echo $modifyoutput;flush(); - modify_database("","update [prefix_questions] set [language]='$newlang' where [language]='$oldlang'");echo $modifyoutput;flush(); - modify_database("","update [prefix_groups] set [language]='$newlang' where [language]='$oldlang'");echo $modifyoutput;flush(); - modify_database("","update [prefix_labels] set [language]='$newlang' where [language]='$oldlang'");echo $modifyoutput;flush(); - modify_database("","update [prefix_surveys] set [language]='$newlang' where [language]='$oldlang'");echo $modifyoutput;flush(); - modify_database("","update [prefix_surveys_languagesettings] set [surveyls_language]='$newlang' where surveyls_language='$oldlang'");echo $modifyoutput;flush(); - modify_database("","update [prefix_users] set [lang]='$newlang' where lang='$oldlang'");echo $modifyoutput;flush(); - } - - $resultdata=db_execute_assoc("select * from ".db_table_name("labelsets")); - while ($datarow = $resultdata->FetchRow()){ - $toreplace=$datarow['languages']; - $toreplace2=str_replace('no','nb',$toreplace); - if ($toreplace2!=$toreplace) {modify_database("","update [prefix_labelsets] set [languages]='$toreplace' where lid=".$datarow['lid']);echo $modifyoutput;flush();} - } - - $resultdata=db_execute_assoc("select * from ".db_table_name("surveys")); - while ($datarow = $resultdata->FetchRow()){ - $toreplace=$datarow['additional_languages']; - $toreplace2=str_replace('no','nb',$toreplace); - if ($toreplace2!=$toreplace) {modify_database("","update [prefix_surveys] set [additional_languages]='$toreplace' where sid=".$datarow['sid']);echo $modifyoutput;flush();} - } - - modify_database("","ALTER TABLE [prefix_surveys] ADD [htmlemail] CHAR(1) DEFAULT 'N'"); echo $modifyoutput; flush(); - modify_database("","ALTER TABLE [prefix_surveys] ADD [usecaptcha] CHAR(1) DEFAULT 'N'"); echo $modifyoutput; flush(); - modify_database("","ALTER TABLE [prefix_surveys] ADD [tokenanswerspersistence] CHAR(1) DEFAULT 'N'"); echo $modifyoutput; flush(); - modify_database("","ALTER TABLE [prefix_users] ADD [htmleditormode] CHAR(7) DEFAULT 'default'"); echo $modifyoutput; flush(); - modify_database("","CREATE TABLE [prefix_templates_rights] ( - [uid] int NOT NULL, - [folder] varchar(255) NOT NULL, - [use] int NOT NULL, - PRIMARY KEY ([uid],[folder]) - );");echo $modifyoutput; flush(); - modify_database("","CREATE TABLE [prefix_templates] ( - [folder] varchar(255) NOT NULL, - [creator] int NOT NULL, - PRIMARY KEY ([folder]) - );");echo $modifyoutput; flush(); - //123 - modify_database("","ALTER TABLE [prefix_conditions] ALTER COLUMN [value] VARCHAR(255)"); echo $modifyoutput; flush(); - // There is no other way to remove the previous default value - /*modify_database("","DECLARE @STR VARCHAR(100) - SET @STR = ( - SELECT NAME - FROM SYSOBJECTS SO - JOIN SYSCONSTRAINTS SC ON SO.ID = SC.CONSTID - WHERE OBJECT_NAME(SO.PARENT_OBJ) = 'lime_labels' - AND SO.XTYPE = 'D' AND SC.COLID = - (SELECT COLID FROM SYSCOLUMNS WHERE ID = OBJECT_ID('lime_labels') AND NAME = 'title')) - SET @STR = 'ALTER TABLE lime_labels DROP CONSTRAINT ' + @STR - exec (@STR);"); echo $modifyoutput; flush(); */ - - modify_database("","ALTER TABLE [prefix_labels] ALTER COLUMN [title] varchar(4000)"); echo $modifyoutput; flush(); - //124 - modify_database("","ALTER TABLE [prefix_surveys] ADD [bounce_email] text"); echo $modifyoutput; flush(); - //125 - upgrade_token_tables125(); - modify_database("","EXEC sp_rename 'prefix_users.move_user','superadmin'"); echo $modifyoutput; flush(); - modify_database("","UPDATE [prefix_users] SET [superadmin]=1 where ([create_survey]=1 AND [create_user]=1 AND [delete_user]=1 AND [configurator]=1)"); echo $modifyoutput; flush(); - //126 - modify_database("","ALTER TABLE [prefix_questions] ADD [lid1] int NOT NULL DEFAULT '0'"); echo $modifyoutput; flush(); - modify_database("","UPDATE [prefix_conditions] SET [method]='==' where ( [method] is null) or [method]=''"); echo $modifyoutput; flush(); - - modify_database("","update [prefix_settings_global] set [stg_value]='126' where stg_name='DBVersion'"); echo $modifyoutput; flush(); - } - - return true; -} - - - -function upgrade_survey_tables117() -{ - global $modifyoutput; - $surveyidquery = "SELECT sid FROM ".db_table_name('surveys')." WHERE active='Y' and datestamp='Y'"; - $surveyidresult = db_execute_num($surveyidquery); - if (!$surveyidresult) {return "Database Error";} - else - { - while ( $sv = $surveyidresult->FetchRow() ) - { - modify_database("","ALTER TABLE ".db_table_name('survey_'.$sv[0])." ADD [startdate] datetime"); echo $modifyoutput; flush(); - } - } -} - - -function upgrade_survey_tables118() -{ - global $connect,$modifyoutput,$dbprefix; - $tokentables=$connect->MetaTables('TABLES',false,$dbprefix."tokens%"); - foreach ($tokentables as $sv) - { - modify_database("","ALTER TABLE ".$sv." ALTER COLUMN [token] VARCHAR(36)"); echo $modifyoutput; flush(); - } -} - - -function upgrade_token_tables125() -{ - global $connect,$modifyoutput,$dbprefix; - $tokentables=$connect->MetaTables('TABLES',false,$dbprefix."tokens%"); - foreach ($tokentables as $sv) - { - modify_database("","ALTER TABLE ".$sv." ADD COLUMN [emailstatus ] VARCHAR(300) DEFAULT 'OK'"); echo $modifyoutput; flush(); - } -} - -?> diff --git a/include/limesurvey/admin/install/upgrade-postgres.php b/include/limesurvey/admin/install/upgrade-postgres.php index 3b599327..f1518211 100644 --- a/include/limesurvey/admin/install/upgrade-postgres.php +++ b/include/limesurvey/admin/install/upgrade-postgres.php @@ -18,14 +18,190 @@ // For this there will be a settings table which holds the last time the database was upgraded function db_upgrade($oldversion) { +global $modifyoutput; - if ($oldversion < 125) { + if ($oldversion < 127) { + modify_database("","create index answers_idx2 on prefix_answers (sortorder)"); echo $modifyoutput; flush(); + modify_database("","create index assessments_idx2 on prefix_assessments (sid)"); echo $modifyoutput; flush(); + modify_database("","create index assessments_idx on prefix_assessments (gid)"); echo $modifyoutput; flush(); + modify_database("","create index conditions_idx2 on prefix_conditions (qid)"); echo $modifyoutput; flush(); + modify_database("","create index conditions_idx3 on prefix_conditions (cqid)"); echo $modifyoutput; flush(); + modify_database("","create index groups_idx2 on prefix_groups (sid)"); echo $modifyoutput; flush(); + modify_database("","create index question_attributes_idx2 on prefix_question_attributes (qid)"); echo $modifyoutput; flush(); + modify_database("","create index questions_idx2 on prefix_questions (sid)"); echo $modifyoutput; flush(); + modify_database("","create index questions_idx3 on prefix_questions (gid)"); echo $modifyoutput; flush(); + modify_database("","create index questions_idx4 on prefix_questions (type)"); echo $modifyoutput; flush(); + modify_database("","create index quota_idx2 on prefix_quota (sid)"); echo $modifyoutput; flush(); + modify_database("","create index saved_control_idx2 on prefix_saved_control (sid)"); echo $modifyoutput; flush(); + modify_database("","create index user_in_groups_idx1 on prefix_user_in_groups (ugid, uid)"); echo $modifyoutput; flush(); + modify_database("","update prefix_settings_global set stg_value='127' where stg_name='DBVersion'"); echo $modifyoutput; flush(); } + if ($oldversion < 128) { + //128 + upgrade_token_tables128(); + modify_database("","update prefix_settings_global set stg_value='128' where stg_name='DBVersion'"); echo $modifyoutput; flush(); + } + + if ($oldversion < 129) { + //129 + modify_database("","ALTER TABLE prefix_surveys ADD startdate date"); echo $modifyoutput; flush(); + modify_database("","ALTER TABLE prefix_surveys ADD usestartdate char(1) NOT NULL default 'N'"); echo $modifyoutput; flush(); + modify_database("","update prefix_settings_global set stg_value='129' where stg_name='DBVersion'"); echo $modifyoutput; flush(); + } + + if ($oldversion < 130) + { + modify_database("","ALTER TABLE prefix_conditions ADD scenario integer NOT NULL default '1'"); echo $modifyoutput; flush(); + modify_database("","UPDATE prefix_conditions SET scenario=1 where (scenario is null) or scenario=0"); echo $modifyoutput; flush(); + modify_database("","update prefix_settings_global set stg_value='130' where stg_name='DBVersion'"); echo $modifyoutput; flush(); + } + if ($oldversion < 131) + { + modify_database("","ALTER TABLE prefix_surveys ADD publicstatistics char(1) NOT NULL default 'N'"); echo $modifyoutput; flush(); + modify_database("","update prefix_settings_global set stg_value='131' where stg_name='DBVersion'"); echo $modifyoutput; flush(); + } + if ($oldversion < 132) + { + modify_database("","ALTER TABLE prefix_surveys ADD publicgraphs char(1) NOT NULL default 'N'"); echo $modifyoutput; flush(); + modify_database("","update prefix_settings_global set stg_value='132' where stg_name='DBVersion'"); echo $modifyoutput; flush(); + } + if ($oldversion < 133) + { + modify_database("","ALTER TABLE prefix_users ADD one_time_pw bytea"); echo $modifyoutput; flush(); + + // Add new assessment setting + modify_database("","ALTER TABLE prefix_surveys ADD assessments char(1) NOT NULL default 'N'"); echo $modifyoutput; flush(); + // add new assessment value fields to answers & labels + modify_database("","ALTER TABLE prefix_answers ADD assessment_value integer NOT NULL default '0'"); echo $modifyoutput; flush(); + modify_database("","ALTER TABLE prefix_labels ADD assessment_value integer NOT NULL default '0'"); echo $modifyoutput; flush(); + // copy any valid codes from code field to assessment field + modify_database("","update [prefix_answers set assessment_value=CAST(code as integer)");// no output here is intended + modify_database("","update prefix_labels set assessment_value=CAST(code as integer)");// no output here is intended + // activate assessment where assesment rules exist + modify_database("","update prefix_surveys set assessments='Y' where sid in (SELECT sid FROM prefix_assessments group by sid)"); echo $modifyoutput; flush(); + // add language field to assessment table + modify_database("","ALTER TABLE prefix_assessments ADD language character varying(20) NOT NULL default 'en'"); echo $modifyoutput; flush(); + // update language field with default language of that particular survey + modify_database("","update prefix_assessments set language=(select language from prefix_surveys where sid=prefix_assessments.sid)"); echo $modifyoutput; flush(); + // copy assessment link to message since from now on we will have HTML assignment messages + modify_database("","update prefix_assessments set message=cast(message as character) ||'
    '||link||''"); echo $modifyoutput; flush(); + // drop the old link field + modify_database("","ALTER TABLE prefix_assessments DROP COLUMN link"); echo $modifyoutput; flush(); + // change the primary index to include language + modify_database("","ALTER TABLE prefix_assessments DROP CONSTRAINT prefix_assessments_pkey"); echo $modifyoutput; flush(); + modify_database("","ALTER TABLE prefix_assessments ADD CONSTRAINT prefix_assessments_pkey PRIMARY KEY (id,language)"); echo $modifyoutput; flush(); + // and fix missing translations for assessments + upgrade_survey_tables133(); + + // Add new fields to survey language settings + modify_database("","ALTER TABLE prefix_surveys_languagesettings ADD surveyls_url character varying(255)"); echo $modifyoutput; flush(); + modify_database("","ALTER TABLE prefix_surveys_languagesettings ADD surveyls_endtext text"); echo $modifyoutput; flush(); + + // copy old URL fields ot language specific entries + modify_database("","update prefix_surveys_languagesettings set surveyls_url=(select url from prefix_surveys where sid=prefix_surveys_languagesettings.surveyls_survey_id)"); echo $modifyoutput; flush(); + // drop old URL field + modify_database("","ALTER TABLE prefix_surveys DROP COLUMN url"); echo $modifyoutput; flush(); + + modify_database("","update prefix_settings_global set stg_value='133' where stg_name='DBVersion'"); echo $modifyoutput; flush(); + } + + if ($oldversion < 134) + { + modify_database("","ALTER TABLE prefix_surveys ADD usetokens char(1) NOT NULL default 'N'"); echo $modifyoutput; flush(); + modify_database("","ALTER TABLE prefix_surveys ADD attributedescriptions TEXT;"); echo $modifyoutput; flush(); + modify_database("","ALTER TABLE prefix_surveys DROP COLUMN attribute1"); echo $modifyoutput; flush(); + modify_database("","ALTER TABLE prefix_surveys DROP COLUMN attribute2"); echo $modifyoutput; flush(); + upgrade_token_tables134(); + modify_database("","update prefix_settings_global set stg_value='134' where stg_name='DBVersion'"); echo $modifyoutput; flush(); + + } + if ($oldversion < 135) + { + modify_database("","ALTER TABLE prefix_question_attributes ALTER COLUMN value TYPE text"); echo $modifyoutput; flush(); + modify_database("","update prefix_settings_global set stg_value='135' where stg_name='DBVersion'"); echo $modifyoutput; flush(); + } + if ($oldversion < 136) + { + modify_database("", "ALTER TABLE prefix_quota ADD autoload_url integer NOT NULL DEFAULT 0"); echo $modifyoutput; flush(); + modify_database("", "CREATE TABLE prefix_quota_languagesettings ( + quotals_id serial NOT NULL, + quotals_quota_id integer NOT NULL DEFAULT 0, + quotals_language character varying(45) NOT NULL DEFAULT 'en'::character varying, + quotals_name character varying(200), + quotals_message text NOT NULL, + quotals_url character varying(255), + quotals_urldescrip character varying(255));"); echo $modifyoutput; flush(); + modify_database("", "ALTER TABLE ONLY prefix_quota_languagesettings + ADD CONSTRAINT prefix_quota_languagesettings_pkey PRIMARY KEY (quotals_id);"); echo $modifyoutput; flush(); + modify_database("", "ALTER TABLE ONLY prefix_users ADD CONSTRAINT prefix_users_pkey PRIMARY KEY (uid)"); echo $modifyoutput; flush(); + modify_database("", "ALTER TABLE ONLY prefix_users ADD CONSTRAINT prefix_user_name_key UNIQUE (users_name)"); echo $modifyoutput; flush(); + modify_database("", "update prefix_settings_global set stg_value='136' where stg_name='DBVersion'"); echo $modifyoutput; flush(); + + } + + if ($oldversion < 137) //New date format specs + { + modify_database("", "ALTER TABLE prefix_surveys_languagesettings ADD surveyls_dateformat integer NOT NULL default 1"); echo $modifyoutput; flush(); + modify_database("", "ALTER TABLE prefix_users ADD \"dateformat\" integer NOT NULL default 1"); echo $modifyoutput; flush(); + modify_database("", "update prefix_surveys set startdate=null where usestartdate='N'"); echo $modifyoutput; flush(); + modify_database("", "update prefix_surveys set expires=null where useexpiry='N'"); echo $modifyoutput; flush(); + modify_database("", "ALTER TABLE prefix_surveys DROP COLUMN usestartdate"); echo $modifyoutput; flush(); + modify_database("", "ALTER TABLE prefix_surveys DROP COLUMN useexpiry"); echo $modifyoutput; flush(); + modify_database("", "update prefix_settings_global set stg_value='137' where stg_name='DBVersion'"); echo $modifyoutput; flush(); + } + + if ($oldversion < 138) //Modify quota field + { + modify_database("", "ALTER TABLE prefix_quota_members ALTER COLUMN code TYPE character varying(11)"); echo $modifyoutput; flush(); + modify_database("", "UPDATE prefix_settings_global SET stg_value='138' WHERE stg_name='DBVersion'"); echo $modifyoutput; flush(); + } return true; } +function upgrade_token_tables128() +{ + global $modifyoutput,$dbprefix; + $surveyidquery = db_select_tables_like($dbprefix."tokens%"); + $surveyidresult = db_execute_num($surveyidquery); + if (!$surveyidresult) {return "Database Error";} + else + { + while ( $sv = $surveyidresult->FetchRow() ) + { + modify_database("","ALTER TABLE ".$sv0." ADD remindersent character varying(17) DEFAULT 'N'"); echo $modifyoutput; flush(); + modify_database("","ALTER TABLE ".$sv0." ADD remindercount INTEGER DEFAULT 0"); echo $modifyoutput; flush(); + } + } +} +function upgrade_survey_tables133() +{ + global $modifyoutput; + + $surveyidquery = "SELECT sid, additional_languages FROM ".db_table_name('surveys'); + $surveyidresult = db_execute_num($surveyidquery); + while ( $sv = $surveyidresult->FetchRow() ) + { + FixLanguageConsistency($sv['0'],$sv['1']); + } +} + +function upgrade_token_tables134() +{ + global $modifyoutput,$dbprefix; + $surveyidquery = db_select_tables_like($dbprefix."tokens%"); + $surveyidresult = db_execute_num($surveyidquery); + if (!$surveyidresult) {return "Database Error";} + else + { + while ( $sv = $surveyidresult->FetchRow() ) + { + modify_database("","ALTER TABLE ".$sv[0]." ADD validfrom timestamp"); echo $modifyoutput; flush(); + modify_database("","ALTER TABLE ".$sv[0]." ADD validuntil timestamp"); echo $modifyoutput; flush(); + } + } +} ?> diff --git a/include/limesurvey/admin/integritycheck.php b/include/limesurvey/admin/integritycheck.php index b75235cf..b7d03017 100644 --- a/include/limesurvey/admin/integritycheck.php +++ b/include/limesurvey/admin/integritycheck.php @@ -1,402 +1,394 @@ -\n" - . "\n" - . "\t\n" - . "\t\t\n" - . "\t\n" - . "\t\n" - ."
    \n"; - } - elseif ($ok == "Y") - { - $integritycheck .= "
    \n" - . "\n" - . "\t\n" - . "\t\t\n" - . "\t\n" - . "\t
    \n" - . "\t\t\t".$clang->gT("Data Consistency Check")."
    ".$clang->gT("If errors are showing up you might have to execute this script repeatedly.")."
    \n" - . "\t\t
    "; - $cdelete=returnglobal('cdelete'); - $adelete=returnglobal('adelete'); - $qdelete=returnglobal('qdelete'); - $gdelete=returnglobal('gdelete'); - $assdelete=returnglobal('assdelete'); - $asgdelete=returnglobal('asgdelete'); - $qadelete=returnglobal('qadelete'); - $sdelete=returnglobal('sdelete'); - - if (isset($sdelete)) { - $integritycheck .= $clang->gT("Deleting Surveys").":
    \n"; - foreach ($sdelete as $ass) { - $integritycheck .= $clang->gT("Deleting Survey ID").":".$ass."
    \n"; - $sql = "DELETE FROM {$dbprefix}surveys WHERE sid=$ass"; - $result = $connect->Execute($sql) or safe_die ("Couldn't delete ($sql)
    ".$connect->ErrorMsg()); - } - } - - if (isset($assdelete)) { - $integritycheck .= $clang->gT( "Deleting Assessments").":
    \n"; - foreach ($assdelete as $ass) { - $integritycheck .= $clang->gT("Deleting ID").":".$ass."
    \n"; - $sql = "DELETE FROM {$dbprefix}assessments WHERE id=$ass"; - $result = $connect->Execute($sql) or safe_die ("Couldn't delete ($sql)
    ".$connect->ErrorMsg()); - } - } - if (isset($asgdelete)) { - $integritycheck .= $clang->gT("Deleting Assessments").":
    \n"; - foreach ($asgdelete as $asg) { - $integritycheck .= $clang->gT("Deleting ID").":".$asg."
    \n"; - $sql = "DELETE FROM {$dbprefix}assessments WHERE id=$asg"; - $result = $connect->Execute($sql) or safe_die ("Couldn't delete ($sql)
    ".$connect->ErrorMsg()); - } - } - if (isset($qadelete)) { - $integritycheck .= $clang->gT("Deleting Question_Attributes").":
    \n"; - foreach ($qadelete as $qad) { - $integritycheck .= "Deleting QAID:".$qad."
    \n"; - $sql = "DELETE FROM {$dbprefix}question_attributes WHERE qaid=$qad"; - $result = $connect->Execute($sql) or safe_die ("Couldn't delete ($sql)
    ".$connect->ErrorMsg()); - } - } - if (isset($cdelete)) { - $integritycheck .= $clang->gT("Deleting Conditions").":
    \n"; - foreach ($cdelete as $cd) { - $integritycheck .= $clang->gT("Deleting cid").":".$cd."
    \n"; - $sql = "DELETE FROM {$dbprefix}conditions WHERE cid=$cd"; - $result=$connect->Execute($sql) or safe_die ("Couldn't Delete ($sql)
    ".$connect->ErrorMsg()); - } - $integritycheck .= "

    \n"; - } - if (isset($adelete)) { - $integritycheck .= $clang->gT("Deleting Answers").":
    \n"; - foreach ($adelete as $ad) { - list($ad1, $ad2)=explode("|", $ad); - $integritycheck .= $clang->gT("Deleting answer with qid").":".$ad1." and code: ".$ad2."
    \n"; - $sql = "DELETE FROM {$dbprefix}answers WHERE qid=$ad1 AND code='$ad2'"; - $result=$connect->Execute($sql) or safe_die ("Couldn't Delete ($sql)
    ".$connect->ErrorMsg()); - } - $integritycheck .= "

    \n"; - } - if (isset($qdelete)) { - $integritycheck .= $clang->gT("Deleting Questions").":
    \n"; - foreach ($qdelete as $qd) { - $integritycheck .= $clang->gT("Deleting qid").":".$qd."
    \n"; - $sql = "DELETE FROM {$dbprefix}questions WHERE qid=$qd"; - $result=$connect->Execute($sql) or safe_die ("Couldn't Delete ($sql)
    ".$connect->ErrorMsg()); - } - $integritycheck .= "

    \n"; - } - if (isset($gdelete)) { - $integritycheck .= $clang->gT("Deleting Groups").":
    \n"; - foreach ($gdelete as $gd) { - $integritycheck .= $clang->gT("Deleting group id").":".$gd."
    \n"; - $sql = "DELETE FROM {$dbprefix}groups WHERE gid=$gd"; - $result=$connect->Execute($sql) or safe_die ("Couldn't Delete ($sql)
    ".$connect->ErrorMsg()); - } - $integritycheck .= "

    \n"; - } - $integritycheck .= $clang->gT("Check database again?")."
    \n" - ."".$clang->gT("Check Again")."
    \n" - ."

    \n"; - } - - $surveyid=false; - } -else - { - $action = "dbchecker"; - include("access_denied.php"); - include("admin.php"); - } -?> +" + . "
    ".$clang->gT("Data Consistency Check")."
    ".$clang->gT("If errors are showing up you might have to execute this script repeatedly.")."
    \n" + . "
      \n"; + // Check conditions + // $query = "SELECT {$dbprefix}questions.sid, {$dbprefix}conditions.* " + // ."FROM {$dbprefix}conditions, {$dbprefix}questions " + // ."WHERE {$dbprefix}conditions.qid={$dbprefix}questions.qid " + // ."ORDER BY qid, scenario, cqid, cfieldname, value"; + $query = "SELECT * FROM {$dbprefix}conditions ORDER BY cid"; + $result = db_execute_assoc($query) or safe_die("Couldn't get list of conditions from database
      $query
      ".$connect->ErrorMsg()); + while ($row=$result->FetchRow()) + { + $qquery="SELECT qid FROM {$dbprefix}questions WHERE qid='{$row['qid']}'"; + $qresult=$connect->Execute($qquery) or safe_die ("Couldn't check questions table for qids
      $qquery
      ".$connect->ErrorMsg()); + $qcount=$qresult->RecordCount(); + if (!$qcount) {$cdelete[]=array("cid"=>$row['cid'], "reason"=>"No matching qid");} + $qquery = "SELECT qid FROM {$dbprefix}questions WHERE qid='{$row['cqid']}'"; + $qresult=$connect->Execute($qquery) or safe_die ("Couldn't check questions table for qids
      $qquery
      ".$connect->ErrorMsg()); + $qcount=$qresult->RecordCount(); + if (!$qcount) {$cdelete[]=array("cid"=>$row['cid'], "reason"=>$clang->gT("No matching Cqid"));} + if ($row['cfieldname']) //Only do this if there actually is a "cfieldname" + { + list ($surveyid, $gid, $rest) = explode("X", $row['cfieldname']); + $qquery = "SELECT gid FROM {$dbprefix}groups WHERE gid=$gid"; + $qresult = $connect->Execute($qquery) or safe_die ("Couldn't check conditional group matches
      $qquery
      ".$connect->ErrorMsg()); + $qcount=$qresult->RecordCount(); + if ($qcount < 1) {$cdelete[]=array("cid"=>$row['cid'], "reason"=>$clang->gT("No matching CFIELDNAME Group!")." ($gid) ({$row['cfieldname']})");} + } + elseif (!$row['cfieldname']) + { + $cdelete[]=array("cid"=>$row['cid'], "reason"=>$clang->gT("No \"CFIELDNAME\" field set!")." ({$row['cfieldname']})"); + } + } + if (isset($cdelete) && $cdelete) + { + $integritycheck .= "
    • ".$clang->gT("The following conditions should be deleted").":

    • \n"; + foreach ($cdelete as $cd) { + $integritycheck .= "CID: {$cd['cid']} ".$clang->gT("because")." {$cd['reason']}
      \n"; + } + $integritycheck .= "
      \n"; + } + else + { + $integritycheck .= "
    • ".$clang->gT("All conditions meet consistency standards")."
    • \n"; + } + + // Check question_attributes to delete + $query = "SELECT * FROM {$dbprefix}question_attributes ORDER BY qid"; + $result = db_execute_assoc($query) or safe_die($connect->ErrorMsg()); + while($row = $result->FetchRow()) + { + $aquery = "SELECT * FROM {$dbprefix}questions WHERE qid = {$row['qid']}"; + $aresult = $connect->Execute($aquery) or safe_die($connect->ErrorMsg()); + $qacount = $aresult->RecordCount(); + if (!$qacount) { + $qadelete[]=array("qaid"=>$row['qaid'], "attribute"=>$row['attribute'], "reason"=>$clang->gT("No matching qid")); + } + } // while + if (isset($qadelete) && $qadelete) { + $integritycheck .= "
    • ".$clang->gT("The following question attributes should be deleted").":

    • \n"; + foreach ($qadelete as $qad) {$integritycheck .= "QAID `{$qad['qaid']}` ATTRIBUTE `{$qad['attribute']}` ".$clang->gT("because")." `{$qad['reason']}`
      \n";} + $integritycheck .= "

      \n"; + } + else + { + $integritycheck .= "
    • ".$clang->gT("All question attributes meet consistency standards")."
    • \n"; + } + + // Check assessments + $query = "SELECT * FROM {$dbprefix}assessments WHERE scope='T' ORDER BY sid"; + $result = db_execute_assoc($query) or safe_die ("Couldn't get list of assessments
      $query
      ".$connect->ErrorMsg()); + while($row = $result->FetchRow()) + { + $aquery = "SELECT * FROM {$dbprefix}surveys WHERE sid = {$row['sid']}"; + $aresult = db_execute_assoc($aquery) or safe_die("Oh dear - died in assessments surveys:".$aquery ."
      ".$connect->ErrorMsg()); + $acount = $aresult->RecordCount(); + if (!$acount) { + $assdelete[]=array("id"=>$row['id'], "assessment"=>$row['name'], "reason"=>$clang->gT("No matching survey")); + } + } // while + + $query = "SELECT * FROM {$dbprefix}assessments WHERE scope='G' ORDER BY gid"; + $result = db_execute_assoc($query) or safe_die ("Couldn't get list of assessments
      $query
      ".$connect->ErrorMsg()); + while($row = $result->FetchRow()) + { + $aquery = "SELECT * FROM {$dbprefix}groups WHERE gid = {$row['gid']}"; + $aresult = $connect->Execute($aquery) or safe_die("Oh dear - died:".$aquery ."
      ".$connect->ErrorMsg()); + $acount = $aresult->RecordCount(); + if (!$acount) { + $asgdelete[]=array("id"=>$row['id'], "assessment"=>$row['name'], "reason"=>$clang->gT("No matching group")); + } + } + + if (isset($assdelete) && $assdelete) + { + $integritycheck .= "
    • ".$clang->gT("The following assessments should be deleted").":
    • \n"; + foreach ($assdelete as $ass) {$integritycheck .= "ID `{$ass['id']}` ASSESSMENT `{$ass['assessment']}` ".$clang->gT("because")." `{$ass['reason']}`
      \n";} + $integritycheck .= "

      \n"; + } + else + { + $integritycheck .= "
    • ".$clang->gT("All Survey (Total) assessments meet consistency standards")."
    • \n"; + } + if (isset($asgdelete) && $asgdelete) + { + $integritycheck .= "".$clang->gT("The following assessments should be deleted").":
      \n"; + foreach ($asgdelete as $asg) {$integritycheck .= "ID `{$asg['id']}` ASSESSMENT `{$asg['assessment']}` ".$clang->gT("because")." `{$asg['reason']}`
      \n";} + $integritycheck .= "

      \n"; + } + else + { + $integritycheck .= "
    • ".$clang->gT("All Group assessments meet consistency standards")."
    • \n"; + } + + // Check answers + $query = "SELECT * FROM {$dbprefix}answers ORDER BY qid"; + $result = db_execute_assoc($query) or safe_die ("Couldn't get list of answers from database
      $query
      ".$connect->ErrorMsg()); + while ($row=$result->FetchRow()) + { + //$integritycheck .= "Checking answer {$row['code']} to qid {$row['qid']}
      \n"; + $qquery="SELECT qid FROM {$dbprefix}questions WHERE qid='{$row['qid']}'"; + $qresult=$connect->Execute($qquery) or safe_die ("Couldn't check questions table for qids from answers
      $qquery
      ".$connect->ErrorMsg()); + $qcount=$qresult->RecordCount(); + if (!$qcount) { + $adelete[]=array("qid"=>$row['qid'], "code"=>$row['code'], "reason"=>$clang->gT("No matching question")); + } + //$integritycheck .= "
      \n"; + } + if (isset($adelete) && $adelete) + { + $integritycheck .= "".$clang->gT("The following answers should be deleted").":
      \n"; + foreach ($adelete as $ad) {$integritycheck .= "QID `{$ad['qid']}` CODE `{$ad['code']}` ".$clang->gT("because")." `{$ad['reason']}`
      \n";} + $integritycheck .= "

      \n"; + } + else + { + $integritycheck .= "
    • ".$clang->gT("All answers meet consistency standards")."
    • \n"; + } + + // Check surveys + $query = "SELECT * FROM {$dbprefix}surveys ORDER BY sid"; + $result = db_execute_assoc($query) or safe_die ("Couldn't get list of answers from database
      $query
      ".$connect->ErrorMsg()); + while ($row=$result->FetchRow()) + { + $qquery="SELECT surveyls_survey_id FROM {$dbprefix}surveys_languagesettings WHERE surveyls_survey_id='{$row['sid']}'"; + $qresult=$connect->Execute($qquery) or safe_die ("Couldn't check languagesettings table for sids from surveys
      $qquery
      ".$connect->ErrorMsg()); + $qcount=$qresult->RecordCount(); + if (!$qcount) { + $sdelete[]=array("sid"=>$row['sid'], "reason"=>$clang->gT("Language specific settings missing")); + } + } + if (isset($sdelete) && $sdelete) + { + $integritycheck .= "".$clang->gT("The following surveys should be deleted").":
      \n"; + foreach ($sdelete as $sd) {$integritycheck .= "SID `{$sd['sid']}` ".$clang->gT("because")." `{$sd['reason']}`
      \n";} + $integritycheck .= "

      \n"; + } + else + { + $integritycheck .= "
    • ".$clang->gT("All survey settings meet consistency standards")."
    • \n"; + } + + //check questions + $query = "SELECT * FROM {$dbprefix}questions ORDER BY sid, gid, qid"; + $result = db_execute_assoc($query) or safe_die ("Couldn't get list of questions from database
      $query
      ".$connect->ErrorMsg()); + while ($row=$result->FetchRow()) + { + //Make sure group exists + $qquery="SELECT * FROM {$dbprefix}groups WHERE gid={$row['gid']}"; + $qresult=$connect->Execute($qquery) or safe_die ("Couldn't check groups table for gids from questions
      $qquery
      ".$connect->ErrorMsg()); + $qcount=$qresult->RecordCount(); + if (!$qcount) {$qdelete[]=array("qid"=>$row['qid'], "reason"=>$clang->gT("No matching group")." ({$row['gid']})");} + //Make sure survey exists + $qquery="SELECT * FROM {$dbprefix}surveys WHERE sid={$row['sid']}"; + $qresult=$connect->Execute($qquery) or safe_die ("Couldn't check surveys table for sids from questions
      $qquery
      ".$connect->ErrorMsg()); + $qcount=$qresult->RecordCount(); + if (!$qcount) { + if (!isset($qdelete) || !in_array($row['qid'], $qdelete)) {$qdelete[]=array("qid"=>$row['qid'], "reason"=>$clang->gT("No matching survey")." ({$row['sid']})");} + } + } + if (isset($qdelete) && $qdelete) + { + $integritycheck .= "".$clang->gT("The following questions should be deleted").":
      \n"; + foreach ($qdelete as $qd) {$integritycheck .= "QID `{$qd['qid']}` ".$clang->gT("because")." `{$qd['reason']}`
      \n";} + $integritycheck .= "

      \n"; + } + else + { + $integritycheck .= "
    • ".$clang->gT("All questions meet consistency standards")."
    • \n"; + } + //check groups + $query = "SELECT * FROM {$dbprefix}groups ORDER BY sid, gid"; + $result=db_execute_assoc($query) or safe_die ("Couldn't get list of groups for checking
      $query
      ".$connect->ErrorMsg()); + while ($row=$result->FetchRow()) + { + //make sure survey exists + $qquery = "SELECT * FROM {$dbprefix}groups WHERE sid={$row['sid']}"; + $qresult=$connect->Execute($qquery) or safe_die("Couldn't check surveys table for gids from groups
      $qquery
      ".$connect->ErrorMsg()); + $qcount=$qresult->RecordCount(); + if (!$qcount) {$gdelete[]=array($row['gid']);} + } + if (isset($gdelete) && $gdelete) + { + $integritycheck .= "
    • ".$clang->gT("The following groups should be deleted").":
    • \n"; + $integritycheck .= implode(", ", $gdelete); + $integritycheck .= "
      \n"; + } + else + { + $integritycheck .= "
    • ".$clang->gT("All groups meet consistency standards")."
    • \n"; + } + $integritycheck .='
    ' ; + //NOW CHECK FOR STRAY SURVEY RESPONSE TABLES AND TOKENS TABLES + if (!isset($cdelete) && !isset($adelete) && !isset($qdelete) && !isset($gdelete) && !isset($asgdelete) && !isset($sdelete) && !isset($assdelete) && !isset($qadelete)) { + $integritycheck .= "
    ".$clang->gT("No database action required"); + } else { + $integritycheck .= "
    ".$clang->gT("Should we proceed with the delete?")."
    \n"; + $integritycheck .= "
    \n"; + if (isset($cdelete)) { + foreach ($cdelete as $cd) { + $integritycheck .= "\n"; + } + } + if (isset($adelete)) { + foreach ($adelete as $ad) { + $integritycheck .= "\n"; + } + } + if (isset($qdelete)) { + foreach($qdelete as $qd) { + $integritycheck .= "\n"; + } + } + if (isset($gdelete)) { + foreach ($gdelete as $gd) { + $integritycheck .= "\n"; + } + } + if (isset($qadelete)) { + foreach ($qadelete as $qad) { + $integritycheck .= "\n"; + } + } + if (isset($assdelete)) { + foreach ($assdelete as $ass) { + $integritycheck .= "\n"; + } + } + if (isset($asgdelete)) { + foreach ($asgdelete as $asg) { + $integritycheck .= "\n"; + } + } + if (isset($sdelete)) { + foreach ($sdelete as $asg) { + $integritycheck .= "\n"; + } + } + $integritycheck .= "\n" + ."\n" + ."
    \n"; + } + $integritycheck .= "
    \n"; + } + elseif ($ok == "Y") + { + $integritycheck .= "
    \n" + . "\n" + . "\t\n" + . "\t\t\n" + . "\t\n" + . "\t
    \n" + . "\t\t\t".$clang->gT("Data Consistency Check")."
    ".$clang->gT("If errors are showing up you might have to execute this script repeatedly.")."
    \n" + . "\t\t
    "; + $cdelete=returnglobal('cdelete'); + $adelete=returnglobal('adelete'); + $qdelete=returnglobal('qdelete'); + $gdelete=returnglobal('gdelete'); + $assdelete=returnglobal('assdelete'); + $asgdelete=returnglobal('asgdelete'); + $qadelete=returnglobal('qadelete'); + $sdelete=returnglobal('sdelete'); + + if (isset($sdelete)) { + $integritycheck .= $clang->gT("Deleting Surveys").":
    \n"; + foreach ($sdelete as $ass) { + $integritycheck .= $clang->gT("Deleting Survey ID").":".$ass."
    \n"; + $sql = "DELETE FROM {$dbprefix}surveys WHERE sid=$ass"; + $result = $connect->Execute($sql) or safe_die ("Couldn't delete ($sql)
    ".$connect->ErrorMsg()); + } + } + + if (isset($assdelete)) { + $integritycheck .= $clang->gT( "Deleting Assessments").":
    \n"; + foreach ($assdelete as $ass) { + $integritycheck .= $clang->gT("Deleting ID").":".$ass."
    \n"; + $sql = "DELETE FROM {$dbprefix}assessments WHERE id=$ass"; + $result = $connect->Execute($sql) or safe_die ("Couldn't delete ($sql)
    ".$connect->ErrorMsg()); + } + } + if (isset($asgdelete)) { + $integritycheck .= $clang->gT("Deleting Assessments").":
    \n"; + foreach ($asgdelete as $asg) { + $integritycheck .= $clang->gT("Deleting ID").":".$asg."
    \n"; + $sql = "DELETE FROM {$dbprefix}assessments WHERE id=$asg"; + $result = $connect->Execute($sql) or safe_die ("Couldn't delete ($sql)
    ".$connect->ErrorMsg()); + } + } + if (isset($qadelete)) { + $integritycheck .= $clang->gT("Deleting Question_Attributes").":
    \n"; + foreach ($qadelete as $qad) { + $integritycheck .= "Deleting QAID:".$qad."
    \n"; + $sql = "DELETE FROM {$dbprefix}question_attributes WHERE qaid=$qad"; + $result = $connect->Execute($sql) or safe_die ("Couldn't delete ($sql)
    ".$connect->ErrorMsg()); + } + } + if (isset($cdelete)) { + $integritycheck .= $clang->gT("Deleting Conditions").":
    \n"; + foreach ($cdelete as $cd) { + $integritycheck .= $clang->gT("Deleting cid").":".$cd."
    \n"; + $sql = "DELETE FROM {$dbprefix}conditions WHERE cid=$cd"; + $result=$connect->Execute($sql) or safe_die ("Couldn't Delete ($sql)
    ".$connect->ErrorMsg()); + } + $integritycheck .= "

    \n"; + } + if (isset($adelete)) { + $integritycheck .= $clang->gT("Deleting Answers").":
    \n"; + foreach ($adelete as $ad) { + list($ad1, $ad2)=explode("|", $ad); + $integritycheck .= $clang->gT("Deleting answer with qid").":".$ad1." and code: ".$ad2."
    \n"; + $sql = "DELETE FROM {$dbprefix}answers WHERE qid=$ad1 AND code='$ad2'"; + $result=$connect->Execute($sql) or safe_die ("Couldn't Delete ($sql)
    ".$connect->ErrorMsg()); + } + $integritycheck .= "

    \n"; + } + if (isset($qdelete)) { + $integritycheck .= $clang->gT("Deleting Questions").":
    \n"; + foreach ($qdelete as $qd) { + $integritycheck .= $clang->gT("Deleting qid").":".$qd."
    \n"; + $sql = "DELETE FROM {$dbprefix}questions WHERE qid=$qd"; + $result=$connect->Execute($sql) or safe_die ("Couldn't Delete ($sql)
    ".$connect->ErrorMsg()); + } + $integritycheck .= "

    \n"; + } + if (isset($gdelete)) { + $integritycheck .= $clang->gT("Deleting Groups").":
    \n"; + foreach ($gdelete as $gd) { + $integritycheck .= $clang->gT("Deleting group id").":".$gd."
    \n"; + $sql = "DELETE FROM {$dbprefix}groups WHERE gid=$gd"; + $result=$connect->Execute($sql) or safe_die ("Couldn't Delete ($sql)
    ".$connect->ErrorMsg()); + } + $integritycheck .= "

    \n"; + } + $integritycheck .= $clang->gT("Check database again?")."
    \n" + ."".$clang->gT("Check Again")."
    \n" + ."

    \n"; + } + + $surveyid=false; + } +else + { + $action = "dbchecker"; + include("access_denied.php"); + include("admin.php"); + } +?> diff --git a/include/limesurvey/admin/iterate_survey.php b/include/limesurvey/admin/iterate_survey.php new file mode 100644 index 00000000..b1629dc4 --- /dev/null +++ b/include/limesurvey/admin/iterate_survey.php @@ -0,0 +1,69 @@ +gT('Iterate survey')); + $iteratesurveyoutput .= "
    \n"; + $iteratesurveyoutput .= "
    ".$clang->gT("Iterate survey")."
    \n"; + $iteratesurveyoutput .= "

    ".$clang->gT("Important instructions")."

    " + . "

    \n" + . "

    ".$clang->gT("Click on the following button if you want to").":
    \n" + . "
      " + . "
    1. ".$clang->gT("Delete all incomplete answers that correspond to a token for which a completed answers is already recorded")."
    2. " + . "
    3. ".$clang->gT("Reset the completed answers to the incomplete state")."
    4. " + . "
    5. ".$clang->gT("Reset all your tokens to the 'not used' state")."
    6. " + . "

    \n" + . "gT("Are you really sure you want to *delete* some incomplete answers and reset the completed state of both answers and tokens?","js")."')){".get2post("$scriptname?action=iteratesurvey&sid=$surveyid&subaction=unfinalizeanswers")."}\" value='".$clang->gT("Reset answers and token completed state")."'>" + . "\n" + ."\t
    "; +} + +if ($subaction=='unfinalizeanswers') +{ + $iteratesurveyoutput = browsemenubar($clang->gT('Iterate survey')); + $baselang = GetBaseLanguageFromSurveyID($surveyid); + $surveytable = db_table_name("survey_$surveyid"); + // First delete incomplete answers that correspond to a token for which a completed answers is already recorded + // subquery in delete or update are tricky things when using the same table for delete and Select + // see http://www.developpez.net/forums/d494961/bases-donnees/mysql/requetes/cant-specify-target-in-from-clause/ + $updateqr = "DELETE from $surveytable WHERE submitdate IS NULL AND token in (SELECT * FROM ( SELECT answ2.token from $surveytable AS answ2 WHERE answ2.submitdate IS NOT NULL) tmp );\n"; +// $updateqr = "DELETE from $surveytable WHERE submitdate IS NULL AND token in (SELECT b.token from $surveytable AS b WHERE b.submitdate IS NOT NULL);\n"; + //error_log("TIBO query = $updateqr"); + $updateres = $connect->Execute($updateqr) or safe_die("Delete incomplete answers with duplicate tokens failed:
    \n" . $connect->ErrorMsg() . "
    $updateqr"); + // Then set all remaining answers to incomplete state + $updateqr = "UPDATE $surveytable SET submitdate=NULL;\n"; + $updateres = $connect->Execute($updateqr) or safe_die("UnFinilize answers failed:
    \n" . $connect->ErrorMsg() . "
    $updateqr"); + // Finally, reset the token completed and sent status + $updateqr="UPDATE ".db_table_name("tokens_$surveyid")." SET sent='N', remindersent='N', remindercount=0, completed='N'"; + $updateres=$connect->Execute($updateqr) or safe_die ("Couldn't reset token completed state
    $updateqr
    ".$connect->ErrorMsg()); + $iteratesurveyoutput .= "
    \n"; + $iteratesurveyoutput .= "
    ".$clang->gT("Iterate survey")."
    \n"; + $iteratesurveyoutput .= "

    \n" + . "".$clang->gT("Success")."
    \n" + . $clang->gT("Answers and tokens have been re-opened.")."
    \n" + . "

    \n" + . "\n" - . "\t\t
    "; +} + +?> diff --git a/include/limesurvey/admin/labels.php b/include/limesurvey/admin/labels.php index c1843221..495ce9d2 100644 --- a/include/limesurvey/admin/labels.php +++ b/include/limesurvey/admin/labels.php @@ -1,864 +1,900 @@ -\n" - . "\t
    \n" - . "\t\t\t\n" - . "\t\t\t\n" - . "\t\t\t\t\n" - ."\n" - ."\t\n" - ."\t\n" - ."\n" - ."\t\n"; - - - if ($action!='labels' || isset($lid)) {$labelsoutput.="
    \n";} - - //NEW SET - if ($action == "newlabelset" || $action == "editlabelset") - { - if ($action == "editlabelset") - { - $query = "SELECT label_name,".db_table_name('labelsets').".lid, languages FROM ".db_table_name('labelsets')." WHERE lid=".$lid; - $result=db_execute_assoc($query); - while ($row=$result->FetchRow()) {$lbname=$row['label_name']; $lblid=$row['lid']; $langids=$row['languages'];} - } - $labelsoutput.= "
    gT("Error: You have to enter a name for this label set.","js")."')\">\n" - ."\n" - ."\t\n" - ."
    \n" - ."\n"; - if ($action == "newlabelset") {$labelsoutput.= $clang->gT("Create or Import New Label Set"); $langids="en"; $tabitem=$clang->gT("Create New Label Set");} - else {$labelsoutput.= $clang->gT("Edit Label Set"); $tabitem=$clang->gT("Edit Label Set");} - $langidsarray=explode(" ",trim($langids)); //Make an array of it - $labelsoutput.= "\n\t
    \n"; - - - $labelsoutput.= "
    \n"; - - $labelsoutput.= "

    ".$tabitem."

    \n"; - - $labelsoutput.= "\n" - ."\t\n" - ."\n" - ."\n" - ."\t\n" - // Additional languages listbox - . "\t\n" - . "" - . "\n" - - // Available languages listbox - . "\n" - ."\n" - ."\n" - ."\t\n"; - $labelsoutput.= "
    ".$clang->gT("Set Name").":\n" - ."\t" - ."\t\n" - ."
    ".$clang->gT("Languages").":gT("Add")."\" onclick=\"DoAdd()\" id=\"AddBtn\" />
    gT("Remove")." >>\" onclick=\"DoRemove(1,'".$clang->gT("You cannot remove this item since you need at least one language in a labelset.", "js")."')\" id=\"RemoveBtn\" />
    \n" - ."
    \n" - ."\n"; - - if ($action == "editlabelset") - { - $labelsoutput.= "\n"; - } - - $labelsoutput.= "
    \n"; - - if ($action == "newlabelset") - { - $labelsoutput.= "

    ".$clang->gT("Import Label Set")."

    \n"; - - $labelsoutput.= "" - ."
    \n" - ."\n" - ."\t\n" - ."\n" - ."\t\n" - ."\t\n" - ."\n" - ."\n" - ."\n" - ."\n" - ."\t\n" - ."\t
    \n" - .$clang->gT("Import Label Set")."\n" - ."
    " - .$clang->gT("Select CSV File:")."" - ."\t
    " - .$clang->gT("Convert Resources links ?")."\n" - ."
    \n" - ."\t
    \n"; - } - $labelsoutput.= "
    \n"; - } - //SET SELECTED - if (isset($lid) && ($action != "editlabelset") && $lid) - { - //CHECK TO SEE IF ANY ACTIVE SURVEYS ARE USING THIS LABELSET (Don't let it be changed if this is the case) - $query = "SELECT ".db_table_name('surveys_languagesettings').".surveyls_title FROM ".db_table_name('questions').", ".db_table_name('surveys')." , ".db_table_name('surveys_languagesettings')." WHERE ".db_table_name('questions').".sid=".db_table_name('surveys').".sid AND ".db_table_name('surveys').".sid=".db_table_name('surveys_languagesettings').".surveyls_survey_id AND ".db_table_name('questions').".lid=$lid AND ".db_table_name('surveys').".active='Y'"; - $result = db_execute_assoc($query); - $activeuse=$result->RecordCount(); - while ($row=$result->FetchRow()) {$activesurveys[]=$row['surveyls_title'];} - //NOW ALSO COUNT UP HOW MANY QUESTIONS ARE USING THIS LABELSET, TO GIVE WARNING ABOUT CHANGES - //$query = "SELECT * FROM ".db_table_name('questions')." WHERE type IN ('F','H','Z','W') AND lid='$lid' GROUP BY qid"; - //NOTE: OK, we're back to "what the hell is Tom up to?". SQL Server complains if the selected columns aren't either aggregated - // part of the GROUP BY clause. This should work for both databases. - $query = "SELECT qid, sid, gid FROM ".db_table_name('questions')." WHERE type IN ('F','H','Z','W') AND lid='$lid' GROUP BY qid, sid, gid"; - $result = db_execute_assoc($query); - $totaluse=$result->RecordCount(); - while($row=$result->FetchRow()) - { - $qidarray[]=array("url"=>"$scriptname?sid=".$row['sid']."&gid=".$row['gid']."&qid=".$row['qid'], "title"=>"QID: ".$row['qid']); - } - //NOW GET THE ANSWERS AND DISPLAY THEM - $query = "SELECT * FROM ".db_table_name('labelsets')." WHERE lid=$lid"; - $result = db_execute_assoc($query); - while ($row=$result->FetchRow()) - { - $labelsoutput.= "\t\n" - ."\n" - ."\n" - ."\t\n" - ."\n" - ."\t\n"; - } - - - //LABEL ANSWERS - SHOW THE MASK FOR EDITING THE LABELS - - - $qulabelset = "SELECT * FROM ".db_table_name('labelsets')." WHERE lid=$lid"; - $rslabelset = db_execute_assoc($qulabelset) or safe_die($connect->ErrorMsg()); - $rwlabelset=$rslabelset->FetchRow(); - $lslanguages=explode(" ", trim($rwlabelset['languages'])); - - $labelsoutput.= PrepareEditorScript("editlabel"); - - $labelsoutput.= "\t\n" - ."\n" - ."\t\n" - ."\n" - ."\t\n"; - if ($totaluse > 0 && $activeuse == 0) //If there are surveys using this labelset, but none are active warn about modifying - { - $labelsoutput.= "\n" - ."\t\n" - ."\n"; - } - $labelsoutput.= "\t
    \n" - .$clang->gT("Labels") - ."\t
    \n" ."
    \n" - ."\n" - ."\n" - ."\n"; - $labelsoutput.= "
    "; - $first=true; - $sortorderids=''; $codeids=''; - foreach ($lslanguages as $lslanguage) - { - $position=0; - $query = "SELECT * FROM ".db_table_name('labels')." WHERE lid=$lid and language='$lslanguage' ORDER BY sortorder, code"; - $result = db_execute_assoc($query) or safe_die($connect->ErrorMsg()); - $labelcount = $result->RecordCount(); - $labelsoutput.= "
    " - ."

    ".getLanguageNameFromCode($lslanguage)."

    " - ."\t\n" - ."" - ."\n" - ."\t\n" -// ."\t\n" -// ."\t\n" -// ."\t\n" - ."" - .""; - while ($row=$result->FetchRow()) - { - $sortorderids=$sortorderids.' '.$row['language'].'_'.$row['sortorder']; - if ($first) {$codeids=$codeids.' '.$row['sortorder'];} - $labelsoutput.= "\n" - ."\t\n" - ."\t\n" - ."\t\n"; - $position++; - } - if ($labelcount>0) - { - $labelsoutput.= "\t\n"; - } - - $position=sprintf("%05d", $position); - if ($activeuse == 0 && $first) - { $labelsoutput.= "\n" - ."\t\n" - ."\t\n" - ."\t\n" - ."\n"; - - } - elseif ($activeuse == 0 && !$first) - { - $labelsoutput.= "\n" - ."\t\n" - ."\n"; - } - else - { - $labelsoutput .= "\n" - ."\t\n" - ."\n"; - } - $first=false; - $labelsoutput.="
    \n" - .$clang->gT("Code") - ."\t\n" - ."\t\n" - .$clang->gT("Title") - ."\t\n" - ."\t\n" - .$clang->gT("Action") - ."\t\n" - ."\t\n" - .$clang->gT("Order") - ."\t
    \n"; - - if ($activeuse > 0) - { - $labelsoutput.= "\t{$row['code']}" - ."\n"; - } - elseif (!$first) - { - $labelsoutput.= "\t{$row['code']}"; - } - else - { - $labelsoutput.= "\t\n"; - $labelsoutput.= "\t\n"; - } - - $labelsoutput.= "\t\n" - ."\t\n" - . getEditor("editlabel", "title_{$row['language']}_{$row['sortorder']}", "[".$clang->gT("Label:", "js")."](".$row['language'].")",'','','',$action) - ."\t\n"; - if ($activeuse == 0) - { - $labelsoutput.= "\t\n"; - } - $labelsoutput.= "\t\n"; - if ($position > 0) - { - $labelsoutput.= "\t\n"; - }; - if ($position < $labelcount-1) - { - // Fill the sortorder hiddenfield so we now what field is moved down - $labelsoutput.= "\t\n"; - } - $labelsoutput.= "\t
    " - ."

    " - ."".$clang->gT("New label").": \n" - ."\t\n" - ."\t\n" - . getEditor("addlabel", "inserttitle", "[".$clang->gT("Label:", "js")."](".$lslanguage.")",'','','',$action) - ."\t\n" - ."\t\n" - ."\t\n" - ."gT('Fix Order')."\">\n" - ."\n" - ."\t
    \n" - ."" - .$clang->gT("Warning").": ".$clang->gT("Inserting New labels must be done on the first language folder.")."\n" - ."\t
    \n" - ."" - .$clang->gT("Warning").": ".$clang->gT("You cannot change codes, add or delete entries in this label set because it is being used by an active survey.")."
    \n"; - if ($totaluse > 0) - { - foreach ($qidarray as $qd) {$labelsoutput.= "[".$qd['title']."] ";} - } - $labelsoutput .= "\t
    \n"; - - $labelsoutput.=("
    "); - } - // Let's close the form for First Languages TABs - $labelsoutput.= "\n"; - $labelsoutput.= "\n"; - - $labelsoutput.= ""; // End First TABs form - - // TAB for resources management - $ZIPimportAction = " onclick='if (validatefilename(this.form,\"".$clang->gT('Please select a file to import!','js')."\")) {this.form.submit();}'"; - if (!function_exists("zip_open")) - { - $ZIPimportAction = " onclick='alert(\"".$clang->gT("zip library not supported by PHP, Import ZIP Disabled","js")."\");'"; - } - - $disabledIfNoResources = ''; - if (hasResources($lid,'label') === false) - { - $disabledIfNoResources = " disabled='disabled'"; - } - - $labelsoutput.= "

    ".$clang->gT("Uploaded Resources Management")."

    \n" - . "\t
    \n" - . "\t\n" - . "\t\n" - . "\t\n" - . "\t" - . "\t\t\n" - . "\t\t\n" - . "\t\t \n" - . "\t\t\n" - . "\t\t\n" - . "\t\t\n" - . "\t
    \n" - . "\t\tgT("Browse Uploaded Resources")."\" $disabledIfNoResources>
    gT("Export Resources As ZIP Archive")."\" $disabledIfNoResources>
    ".$clang->gT("Select ZIP File:")."
    \n"; - - // End TAB Uploaded Resources Management - $labelsoutput.= "
    "; - - $labelsoutput.= "
    "; // End Tab pane - - - // Here starts the hidden Fix Sort order form - $labelsoutput.= "
    " - ."
    " - ."\n" - ."\t" -// ."\n" - ."
    " - ."\t\n" - ."\t\n" - ."
    \n" - ."" - .$clang->gT("Warning").": ".$clang->gT("Some surveys currently use this label set. Modifying the codes, adding or deleting entries to this label set may produce undesired results in other surveys.")."
    "; - foreach ($qidarray as $qd) {$labelsoutput.= "[".$qd['title']."] ";} - $labelsoutput.= "
    \n" - ."\t
    \n"; - } - $labelsoutput.="
    "; - } -else - { - $action = "labels"; - include("access_denied.php"); - include("admin.php"); - } - -//************************FUNCTIONS******************************** -function updateset($lid) -{ - global $dbprefix, $connect, $labelsoutput, $databasetype; - // Get added and deleted languagesid arrays - - if (isset($_POST['languageids'])) - { - $postlanguageids=sanitize_languagecodeS($_POST['languageids']); - } - - if (isset($_POST['label_name'])) - { - $postlabel_name=sanitize_labelname($_POST['label_name']); - } - - $newlanidarray=explode(" ",trim($postlanguageids)); - - $postlanguageids = db_quoteall($postlanguageids,true); - $postlabel_name = db_quoteall($postlabel_name,true); - $oldlangidsarray=array(); - $query = "SELECT languages FROM ".db_table_name('labelsets')." WHERE lid=".$lid; - $result=db_execute_assoc($query); - if ($result) - { - while ($row=$result->FetchRow()) {$oldlangids=$row['languages'];} - $oldlangidsarray=explode(" ",trim($oldlangids)); - } - $addlangidsarray=array_diff($newlanidarray,$oldlangidsarray); - $dellangidsarray=array_diff($oldlangidsarray,$newlanidarray); - - // If new languages are added, create labels' codes and sortorder for the new languages - $query = "SELECT code,sortorder FROM ".db_table_name('labels')." WHERE lid=".$lid." GROUP BY code,sortorder"; - $result=db_execute_assoc($query); - if ($result) { while ($row=$result->FetchRow()) {$oldcodesarray[$row['code']]=$row['sortorder'];} } - if (isset($oldcodesarray) && count($oldcodesarray) > 0 ) - { - foreach ($addlangidsarray as $addedlangid) - { - foreach ($oldcodesarray as $oldcode => $oldsortorder) - { - $sqlvalues[]= " ($lid, '$oldcode', '$oldsortorder', '$addedlangid')"; - } - } - } - if (isset($sqlvalues)) - { - if ($databasetype=='odbc_mssql') {@$connect->Execute("SET IDENTITY_INSERT ".db_table_name('labels')." ON");} - foreach ($sqlvalues as $sqlline) - { - $query = "INSERT INTO ".db_table_name('labels')." (lid,code,sortorder,language) VALUES ".($sqlline); - $result=db_execute_assoc($query); - if (!$result) - { - $labelsoutput.= "\n"; - } - } - if ($databasetype=='odbc_mssql') {@$connect->Execute("SET IDENTITY_INSERT ".db_table_name('labels')." OFF");} - } - - // If languages are removed, delete labels for these languages - $sqlwherelang=''; - foreach ($dellangidsarray as $dellangid) - { - $sqlwherelang .= " OR language='".$dellangid."'"; - } - if ($sqlwherelang) - { - $query = "DELETE FROM ".db_table_name('labels')." WHERE lid=$lid AND (".trim($sqlwherelang, ' OR').")"; - $result=db_execute_assoc($query); - if (!$result) - { - $labelsoutput.= "\n"; - } - } - - // Update the labelset itself - $query = "UPDATE ".db_table_name('labelsets')." SET label_name={$postlabel_name}, languages={$postlanguageids} WHERE lid=$lid"; - if (!$result = $connect->Execute($query)) - { - $labelsoutput.= "\n"; - } -} - - - -function deletelabelset($lid) -// language proof -{ - global $dbprefix, $connect, $clang, $labelsoutput; - //CHECK THAT THERE ARE NO QUESTIONS THAT RELY ON THIS LID - $query = "SELECT qid FROM ".db_table_name('questions')." WHERE type IN ('F','H','W','Z') AND lid=$lid"; - $result = $connect->Execute($query) or safe_die("Error"); - $count = $result->RecordCount(); - if ($count > 0) - { - $labelsoutput.= "\n"; - return false; - } - else //There are no dependencies. We can delete this safely - { - $query = "DELETE FROM ".db_table_name('labels')." WHERE lid=$lid"; - $result = $connect->Execute($query); - $query = "DELETE FROM ".db_table_name('labelsets')." WHERE lid=$lid"; - $result = $connect->Execute($query); - return true; - } -} - - - -function insertlabelset() -{ - global $dbprefix, $connect, $clang, $labelsoutput; -// $labelsoutput.= $_POST['languageids']; For debug purposes - - if (isset($_POST['languageids'])) - { - $postlanguageids=sanitize_languagecodeS($_POST['languageids']); - } - - if (isset($_POST['label_name'])) - { - $postlabel_name=sanitize_labelname($_POST['label_name']); - } - - $postlabel_name = db_quoteall($postlabel_name,true); - $postlanguageids = db_quoteall($postlanguageids,true); - - $query = "INSERT INTO ".db_table_name('labelsets')." (label_name,languages) VALUES ({$postlabel_name},{$postlanguageids})"; - if (!$result = $connect->Execute($query)) - { - $labelsoutput.= "\n"; - } - else - { - return $connect->Insert_ID(db_table_name_nq('labelsets'),"lid"); - } - -} - - - -function modlabelsetanswers($lid) -{ - global $dbprefix, $connect, $clang, $labelsoutput, $databasetype, $filterxsshtml,$postsortorder; - - $qulabelset = "SELECT * FROM ".db_table_name('labelsets')." WHERE lid='$lid'"; - $rslabelset = db_execute_assoc($qulabelset) or safe_die($connect->ErrorMsg()); - $rwlabelset=$rslabelset->FetchRow(); - $lslanguages=explode(" ", trim($rwlabelset['languages'])); - - if (!isset($_POST['method'])) { - $_POST['method'] = $clang->gT("Save"); - } - switch($_POST['method']) - { - case $clang->gT("Add new label", "unescaped"): - if (isset($_POST['insertcode']) && $_POST['insertcode']!='') - { - $_POST['insertcode'] = db_quoteall($_POST['insertcode'],true); - // check that the code doesn't exist yet - $query = "SELECT code FROM ".db_table_name('labels')." WHERE lid='$lid' AND code=".$_POST['insertcode']; - $result = $connect->Execute($query); - $codeoccurences=$result->RecordCount(); - if ($codeoccurences == 0) - { - $query = "select max(sortorder) as maxorder from ".db_table_name('labels')." where lid='$lid'"; - $result = $connect->Execute($query); - $newsortorder=sprintf("%05d", $result->fields['maxorder']+1); - if ($filterxsshtml) - { - require_once("../classes/inputfilter/class.inputfilter_clean.php"); - $myFilter = new InputFilter('','',1,1,1); - $_POST['inserttitle']=$myFilter->process($_POST['inserttitle']); - } - else - { - $_POST['inserttitle'] = html_entity_decode_php4($_POST['inserttitle'], ENT_QUOTES, "UTF-8"); - } - - // Fix bug with FCKEditor saving strange BR types - $_POST['inserttitle']=str_replace('
    ','',$_POST['inserttitle']); - if ($_POST['inserttitle'] == "
    ") - { - $_POST['inserttitle']=''; - } - - $_POST['inserttitle'] = db_quoteall($_POST['inserttitle'],true); - foreach ($lslanguages as $lslanguage) - { - if ($databasetype=='odbc_mssql') {@$connect->Execute("SET IDENTITY_INSERT ".db_table_name('labels')." ON");} - $query = "INSERT INTO ".db_table_name('labels')." (lid, code, title, sortorder,language) VALUES ($lid, {$_POST['insertcode']}, {$_POST['inserttitle']}, '$newsortorder','$lslanguage')"; - if (!$result = $connect->Execute($query)) - { - $labelsoutput.= "\n"; - } - if ($databasetype=='odbc_mssql') {@$connect->Execute("SET IDENTITY_INSERT ".db_table_name('labels')." OFF");} - } - } - else - { - $labelsoutput.= "\n"; - } - } - break; - - // Save all labels with one button - case $clang->gT("Save All", "unescaped"): - //Determine autoids by evaluating the hidden field - $sortorderids=explode(' ', trim($_POST['sortorderids'])); - $codeids=explode(' ', trim($_POST['codeids'])); - $count=0; - - // Quote each code_codeid first - foreach ($codeids as $codeid) - { - $_POST['code_'.$codeid] = db_quoteall($_POST['code_'.$codeid],true); - $_POST['oldcode_'.$codeid] = db_quoteall($_POST['oldcode_'.$codeid],true); - // Get the code values to check for duplicates - $codevalues[] = $_POST['code_'.$codeid]; - } - - // Check that there is no code duplicate - if (count(array_unique($codevalues)) == count($codevalues)) - { - if ($filterxsshtml) - { - require_once("../classes/inputfilter/class.inputfilter_clean.php"); - $myFilter = new InputFilter('','',1,1,1); - } - - foreach ($sortorderids as $sortorderid) - { - $langid=substr($sortorderid,0,strrpos($sortorderid,'_')); - $orderid=substr($sortorderid,strrpos($sortorderid,'_')+1,20); - if ($filterxsshtml) - { - $_POST['title_'.$sortorderid]=$myFilter->process($_POST['title_'.$sortorderid]); - } - else - { - $_POST['title_'.$sortorderid] = html_entity_decode_php4($_POST['title_'.$sortorderid], ENT_QUOTES, "UTF-8"); - } - - - // Fix bug with FCKEditor saving strange BR types - $_POST['title_'.$sortorderid]=str_replace('
    ','',$_POST['title_'.$sortorderid]); - if ($_POST['title_'.$sortorderid] == "
    ") - { - $_POST['title_'.$sortorderid]=''; - } - $_POST['title_'.$sortorderid] = db_quoteall($_POST['title_'.$sortorderid],true); - - $query = "UPDATE ".db_table_name('labels')." SET code=".$_POST['code_'.$codeids[$count]].", title={$_POST['title_'.$sortorderid]} WHERE lid=$lid AND sortorder=$orderid AND language='$langid'"; - - if (!$result = $connect->Execute($query)) - // if update didn't work we assume the label does not exist and insert it - { - - $query = "insert into ".db_table_name('labels')." (code,title,lid,sortorder,language) VALUES (".$_POST['code_'.$codeids[$count]].", {$_POST['title_'.$sortorderid]}, $lid , $orderid , '$langid')"; - if (!$result = $connect->Execute($query)) - { - $labelsoutput.= "\n"; - } - } - - update_labelcodes_in_conditions($lid,$_POST['oldcode_'.$codeids[$count]],$_POST['code_'.$codeids[$count]]); - - $count++; - if ($count>count($codeids)-1) {$count=0;} - } - } - else - { - $labelsoutput.= "\n"; - } - - break; - - // Pressing the Up button - case $clang->gT("Up", "unescaped"): - $newsortorder=$postsortorder-1; - $oldsortorder=$postsortorder; - $cdquery = "UPDATE ".db_table_name('labels')." SET sortorder=-1 WHERE lid=$lid AND sortorder=$newsortorder"; - $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); - $cdquery = "UPDATE ".db_table_name('labels')." SET sortorder=$newsortorder WHERE lid=$lid AND sortorder=$oldsortorder"; - $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); - $cdquery = "UPDATE ".db_table_name('labels')." SET sortorder='$oldsortorder' WHERE lid=$lid AND sortorder=-1"; - $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); - break; - - // Pressing the Down button - case $clang->gT("Dn", "unescaped"): - $newsortorder=$postsortorder+1; - $oldsortorder=$postsortorder; - $cdquery = "UPDATE ".db_table_name('labels')." SET sortorder=-1 WHERE lid=$lid AND sortorder='$newsortorder'"; - $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); - $cdquery = "UPDATE ".db_table_name('labels')." SET sortorder='$newsortorder' WHERE lid=$lid AND sortorder=$oldsortorder"; - $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); - $cdquery = "UPDATE ".db_table_name('labels')." SET sortorder=$oldsortorder WHERE lid=$lid AND sortorder=-1"; - $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); - break; - - // Delete Button - case $clang->gT("Del", "unescaped"): - $query = "DELETE FROM ".db_table_name('labels')." WHERE lid=$lid AND sortorder='{$postsortorder}'"; - if (!$result = $connect->Execute($query)) - { - $labelsoutput.= "\n"; - } - break; - - // Fix Sortorder button - case $clang->gT("Fix Sort", "unescaped"): - fixorder($lid); - break; - } -} - - -function fixorder($lid) //Function rewrites the sortorder for a group of answers -{ - global $dbprefix, $connect, $labelsoutput; - $qulabelset = "SELECT * FROM ".db_table_name('labelsets')." WHERE lid=$lid"; - $rslabelset = db_execute_assoc($qulabelset) or safe_die($connect->ErrorMsg()); - $rwlabelset=$rslabelset->FetchRow(); - $lslanguages=explode(" ", trim($rwlabelset['languages'])); - foreach ($lslanguages as $lslanguage) - { - $query = "SELECT lid, code, title FROM ".db_table_name('labels')." WHERE lid=? and language='$lslanguage' ORDER BY sortorder, code"; - $result = db_execute_num($query, array($lid)); - $position=0; - while ($row=$result->FetchRow()) - { - $position=sprintf("%05d", $position); - $query2="UPDATE ".db_table_name('labels')." SET sortorder='$position' WHERE lid=? AND code=? AND title=? AND language='$lslanguage' "; - $result2=$connect->Execute($query2, array ($row[0], $row[1], $row[2])) or safe_die ("Couldn't update sortorder
    $query2
    ".$connect->ErrorMsg()); - $position++; - } - } -} - -function update_labelcodes_in_conditions($labelid,$oldcode,$newcode) -{ - global $dbprefix, $connect; - - if ($oldcode != $newcode) - { - // If question type is not dual scale, then update only if: value is old label code AND question uses the modified label - // If question is Dualscale then check if it uses the modified label as lid or lid1 and check - $query = "UPDATE ".db_table_name('conditions')." AS c INNER JOIN ".db_table_name('questions')." AS q ON c.cqid=q.qid SET value=$newcode WHERE c.value=$oldcode AND ( (q.type <> 1 AND q.lid=$labelid) OR (q.type = 1 AND q.lid=$labelid AND c.cfieldname like '%#0') OR (q.type = 1 AND q.lid1=$labelid AND c.cfieldname like '%#1') )"; - $result=$connect->Execute($query) or safe_die($connect->ErrorMsg()); - //error_log("TIBO=$query"); - } -} - - -?> +\n" + ."\t
    \n" + ."\t\t
    "; + } +else + { + $action = "labels"; + include("access_denied.php"); + include("admin.php"); + } + +//************************FUNCTIONS******************************** +function updateset($lid) +{ + global $dbprefix, $connect, $labelsoutput, $databasetype; + // Get added and deleted languagesid arrays + + if (isset($_POST['languageids'])) + { + $postlanguageids=sanitize_languagecodeS($_POST['languageids']); + } + + if (isset($_POST['label_name'])) + { + $postlabel_name=sanitize_labelname($_POST['label_name']); + } + + $newlanidarray=explode(" ",trim($postlanguageids)); + + $postlanguageids = db_quoteall($postlanguageids,true); + $postlabel_name = db_quoteall($postlabel_name,true); + $oldlangidsarray=array(); + $query = "SELECT languages FROM ".db_table_name('labelsets')." WHERE lid=".$lid; + $result=db_execute_assoc($query); + if ($result) + { + while ($row=$result->FetchRow()) {$oldlangids=$row['languages'];} + $oldlangidsarray=explode(" ",trim($oldlangids)); + } + $addlangidsarray=array_diff($newlanidarray,$oldlangidsarray); + $dellangidsarray=array_diff($oldlangidsarray,$newlanidarray); + + // If new languages are added, create labels' codes and sortorder for the new languages + $query = "SELECT code,sortorder,assessment_value FROM ".db_table_name('labels')." WHERE lid=".$lid." GROUP BY code,sortorder,assessment_value"; + $result=db_execute_assoc($query); + if ($result) { while ($row=$result->FetchRow()) {$oldcodesarray[$row['code']]=array('sortorder'=>$row['sortorder'],'assessment_value'=>$row['assessment_value']);} } + if (isset($oldcodesarray) && count($oldcodesarray) > 0 ) + { + foreach ($addlangidsarray as $addedlangid) + { + foreach ($oldcodesarray as $oldcode => $olddata) + { + $sqlvalues[]= " ($lid, '$oldcode', '{$olddata['sortorder']}', '$addedlangid', '{$olddata['assessment_value']}' )"; + } + } + } + if (isset($sqlvalues)) + { + if ($connect->databaseType == 'odbc_mssql' || $connect->databaseType == 'odbtp' || $connect->databaseType == 'mssql_n') {@$connect->Execute('SET IDENTITY_INSERT '.db_table_name('labels')." ON");} + foreach ($sqlvalues as $sqlline) + { + $query = "INSERT INTO ".db_table_name('labels')." (lid,code,sortorder,language,assessment_value) VALUES ".($sqlline); + $result=db_execute_assoc($query); + if (!$result) + { + $labelsoutput.= "\n"; + } + } + if ($connect->databaseType == 'odbc_mssql' || $connect->databaseType == 'odbtp' || $connect->databaseType == 'mssql_n') {@$connect->Execute('SET IDENTITY_INSERT '.db_table_name('labels')." OFF");} + } + + // If languages are removed, delete labels for these languages + $sqlwherelang=''; + foreach ($dellangidsarray as $dellangid) + { + $sqlwherelang .= " OR language='".$dellangid."'"; + } + if ($sqlwherelang) + { + $query = "DELETE FROM ".db_table_name('labels')." WHERE lid=$lid AND (".trim($sqlwherelang, ' OR').")"; + $result=db_execute_assoc($query); + if (!$result) + { + $labelsoutput.= "\n"; + } + } + + // Update the labelset itself + $query = "UPDATE ".db_table_name('labelsets')." SET label_name={$postlabel_name}, languages={$postlanguageids} WHERE lid=$lid"; + if (!$result = $connect->Execute($query)) + { + $labelsoutput.= "\n"; + } +} + + + +function deletelabelset($lid) +// language proof +{ + global $dbprefix, $connect, $clang, $labelsoutput; + //CHECK THAT THERE ARE NO QUESTIONS THAT RELY ON THIS LID + $query = "SELECT qid FROM ".db_table_name('questions')." WHERE type IN ('F','H','W','Z') AND lid=$lid"; + $result = $connect->Execute($query) or safe_die("Error"); + $count = $result->RecordCount(); + if ($count > 0) + { + $labelsoutput.= "\n"; + return false; + } + else //There are no dependencies. We can delete this safely + { + $query = "DELETE FROM ".db_table_name('labels')." WHERE lid=$lid"; + $result = $connect->Execute($query); + $query = "DELETE FROM ".db_table_name('labelsets')." WHERE lid=$lid"; + $result = $connect->Execute($query); + return true; + } +} + + + +function insertlabelset() +{ + global $dbprefix, $connect, $clang, $labelsoutput; +// $labelsoutput.= $_POST['languageids']; For debug purposes + + if (isset($_POST['languageids'])) + { + $postlanguageids=sanitize_languagecodeS($_POST['languageids']); + } + + if (isset($_POST['label_name'])) + { + $postlabel_name=sanitize_labelname($_POST['label_name']); + } + + $postlabel_name = db_quoteall($postlabel_name,true); + $postlanguageids = db_quoteall($postlanguageids,true); + + $query = "INSERT INTO ".db_table_name('labelsets')." (label_name,languages) VALUES ({$postlabel_name},{$postlanguageids})"; + if (!$result = $connect->Execute($query)) + { + $labelsoutput.= "\n"; + } + else + { + return $connect->Insert_ID(db_table_name_nq('labelsets'),"lid"); + } + +} + + + +function modlabelsetanswers($lid) +{ + global $dbprefix, $connect, $clang, $labelsoutput, $databasetype, $filterxsshtml,$postsortorder; + + $qulabelset = "SELECT * FROM ".db_table_name('labelsets')." WHERE lid='$lid'"; + $rslabelset = db_execute_assoc($qulabelset) or safe_die($connect->ErrorMsg()); + $rwlabelset=$rslabelset->FetchRow(); + $lslanguages=explode(" ", trim($rwlabelset['languages'])); + + if (!isset($_POST['method'])) { + $_POST['method'] = $clang->gT("Save"); + } + switch($_POST['method']) + { + case $clang->gT("Add new label", "unescaped"): + if (isset($_POST['insertcode']) && $_POST['insertcode']!='') + { + $_SESSION['nextlabelcode']=getNextCode($_POST['insertcode']); + $_POST['insertcode'] = db_quoteall($_POST['insertcode'],true); + // check that the code doesn't exist yet + $query = "SELECT code FROM ".db_table_name('labels')." WHERE lid='$lid' AND code=".$_POST['insertcode']; + $result = $connect->Execute($query); + $codeoccurences=$result->RecordCount(); + if ($codeoccurences == 0) + { + $query = "select max(sortorder) as maxorder from ".db_table_name('labels')." where lid='$lid'"; + $result = $connect->Execute($query); + $newsortorder=sprintf("%05d", $result->fields['maxorder']+1); + if ($filterxsshtml) + { + require_once("../classes/inputfilter/class.inputfilter_clean.php"); + $myFilter = new InputFilter('','',1,1,1); + $_POST['inserttitle']=$myFilter->process($_POST['inserttitle']); + } + else + { + $_POST['inserttitle'] = html_entity_decode($_POST['inserttitle'], ENT_QUOTES, "UTF-8"); + } + + // Fix bug with FCKEditor saving strange BR types + $_POST['inserttitle']=fix_FCKeditor_text($_POST['inserttitle']); + + $_POST['inserttitle'] = db_quoteall($_POST['inserttitle'],true); + $_POST['insertassessmentvalue']=(int)$_POST['insertassessmentvalue']; + foreach ($lslanguages as $lslanguage) + { + if ($connect->databaseType == 'odbc_mssql' || $connect->databaseType == 'odbtp' || $connect->databaseType == 'mssql_n') {@$connect->Execute('SET IDENTITY_INSERT '.db_table_name('labels')." ON");} + $query = "INSERT INTO ".db_table_name('labels')." (lid, code, title, sortorder,language, assessment_value) VALUES ($lid, {$_POST['insertcode']}, {$_POST['inserttitle']}, '$newsortorder','$lslanguage',{$_POST['insertassessmentvalue']})"; + if (!$result = $connect->Execute($query)) + { + $labelsoutput.= "\n"; + } + if ($connect->databaseType == 'odbc_mssql' || $connect->databaseType == 'odbtp' || $connect->databaseType == 'mssql_n') {@$connect->Execute('SET IDENTITY_INSERT '.db_table_name('labels')." OFF");} + } + } + else + { + $labelsoutput.= "\n"; + } + } + break; + + // Save all labels with one button + case $clang->gT("Save Changes", "unescaped"): + //Determine autoids by evaluating the hidden field + $sortorderids=explode(' ', trim($_POST['sortorderids'])); + $codeids=explode(' ', trim($_POST['codeids'])); + $count=0; + + // Quote each code_codeid first + foreach ($codeids as $codeid) + { + $_POST['code_'.$codeid] = db_quoteall($_POST['code_'.$codeid],true); + if (isset($_POST['oldcode_'.$codeid])) $_POST['oldcode_'.$codeid] = db_quoteall($_POST['oldcode_'.$codeid],true); + // Get the code values to check for duplicates + $codevalues[] = $_POST['code_'.$codeid]; + } + + // Check that there is no code duplicate + if (count(array_unique($codevalues)) == count($codevalues)) + { + if ($filterxsshtml) + { + require_once("../classes/inputfilter/class.inputfilter_clean.php"); + $myFilter = new InputFilter('','',1,1,1); + } + + foreach ($sortorderids as $sortorderid) + { + $langid=substr($sortorderid,0,strrpos($sortorderid,'_')); + $orderid=substr($sortorderid,strrpos($sortorderid,'_')+1,20); + if ($filterxsshtml) + { + $_POST['title_'.$sortorderid]=$myFilter->process($_POST['title_'.$sortorderid]); + } + else + { + $_POST['title_'.$sortorderid] = html_entity_decode($_POST['title_'.$sortorderid], ENT_QUOTES, "UTF-8"); + } + + + // Fix bug with FCKEditor saving strange BR types + $_POST['title_'.$sortorderid]=fix_FCKeditor_text($_POST['title_'.$sortorderid]); + $_POST['title_'.$sortorderid] = db_quoteall($_POST['title_'.$sortorderid],true); + + $query = "UPDATE ".db_table_name('labels')." SET code=".$_POST['code_'.$codeids[$count]].", title={$_POST['title_'.$sortorderid]}, assessment_value={$_POST['assessmentvalue_'.$codeids[$count]]} WHERE lid=$lid AND sortorder=$orderid AND language='$langid'"; + + if (!$result = $connect->Execute($query)) + // if update didn't work we assume the label does not exist and insert it + { + + $query = "insert into ".db_table_name('labels')." (code,title,lid,sortorder,language) VALUES (".$_POST['code_'.$codeids[$count]].", {$_POST['title_'.$sortorderid]}, $lid , $orderid , '$langid')"; + if (!$result = $connect->Execute($query)) + { + $labelsoutput.= "\n"; + } + } + + if (isset($_POST['oldcode_'.$codeids[$count]])) update_labelcodes_in_conditions($lid,$_POST['oldcode_'.$codeids[$count]],$_POST['code_'.$codeids[$count]]); + + $count++; + if ($count>count($codeids)-1) {$count=0;} + } + fixorder($lid); + } + else + { + $labelsoutput.= "\n"; + } + + break; + + // Pressing the Up button + case $clang->gT("Up", "unescaped"): + $newsortorder=$postsortorder-1; + $oldsortorder=$postsortorder; + $cdquery = "UPDATE ".db_table_name('labels')." SET sortorder=-1 WHERE lid=$lid AND sortorder=$newsortorder"; + $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); + $cdquery = "UPDATE ".db_table_name('labels')." SET sortorder=$newsortorder WHERE lid=$lid AND sortorder=$oldsortorder"; + $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); + $cdquery = "UPDATE ".db_table_name('labels')." SET sortorder='$oldsortorder' WHERE lid=$lid AND sortorder=-1"; + $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); + break; + + // Pressing the Down button + case $clang->gT("Dn", "unescaped"): + $newsortorder=$postsortorder+1; + $oldsortorder=$postsortorder; + $cdquery = "UPDATE ".db_table_name('labels')." SET sortorder=-1 WHERE lid=$lid AND sortorder='$newsortorder'"; + $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); + $cdquery = "UPDATE ".db_table_name('labels')." SET sortorder='$newsortorder' WHERE lid=$lid AND sortorder=$oldsortorder"; + $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); + $cdquery = "UPDATE ".db_table_name('labels')." SET sortorder=$oldsortorder WHERE lid=$lid AND sortorder=-1"; + $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); + break; + + // Delete Button + case $clang->gT("Del", "unescaped"): + $query = "DELETE FROM ".db_table_name('labels')." WHERE lid=$lid AND sortorder='{$postsortorder}'"; + if (!$result = $connect->Execute($query)) + { + $labelsoutput.= "\n"; + } + fixorder($lid); + break; + } +} + + +function fixorder($lid) //Function rewrites the sortorder for a group of answers +{ + global $dbprefix, $connect, $labelsoutput; + $qulabelset = "SELECT * FROM ".db_table_name('labelsets')." WHERE lid=$lid"; + $rslabelset = db_execute_assoc($qulabelset) or safe_die($connect->ErrorMsg()); + $rwlabelset=$rslabelset->FetchRow(); + $lslanguages=explode(" ", trim($rwlabelset['languages'])); + foreach ($lslanguages as $lslanguage) + { + $query = "SELECT lid, code, title FROM ".db_table_name('labels')." WHERE lid=? and language='$lslanguage' ORDER BY sortorder, code"; + $result = db_execute_num($query, array($lid)); + $position=0; + while ($row=$result->FetchRow()) + { + $position=sprintf("%05d", $position); + $query2="UPDATE ".db_table_name('labels')." SET sortorder='$position' WHERE lid=? AND code=? AND title=? AND language='$lslanguage' "; + $result2=$connect->Execute($query2, array ($row[0], $row[1], $row[2])) or safe_die ("Couldn't update sortorder
    $query2
    ".$connect->ErrorMsg()); + $position++; + } + } +} + +function update_labelcodes_in_conditions($labelid,$oldcode,$newcode) +{ + global $dbprefix, $databasetype, $connect; + + if ($oldcode != $newcode) + { + // If question type is not dual scale, then update only if: value is old label code AND question uses the modified label + // If question is Dualscale then check if it uses the modified label as lid or lid1 and check + if ($connect->databaseType == 'odbc_mssql' || $connect->databaseType == 'odbtp' || $connect->databaseType == 'mssql_n') + { + $query = "UPDATE ".db_table_name('conditions') + ."SET value = $newcode" + ."FROM ".db_table_name('conditions')." AS c INNER JOIN" + .db_table_name('questions')." AS q ON c.cqid = q.qid CROSS JOIN ".db_table_name('conditions') + ."WHERE (q.type <> 1) AND (q.lid = 3) AND (c.value = $oldcode) OR" + ."(q.type = 1) AND (q.lid = $labelid) AND (c.value = $oldcode) AND (c.cfieldname LIKE '%#0') OR" + ."(q.type = 1) AND (q.lid1 = $labelid) AND (c.value = $oldcode) AND (c.cfieldname LIKE '%#1')"; + } + else + { + $query = "UPDATE ".db_table_name('conditions')." AS c INNER JOIN ".db_table_name('questions')." AS q ON c.cqid=q.qid SET value=$newcode " + ."WHERE c.value=$oldcode AND ( (q.type <> 1 AND q.lid=$labelid) OR (q.type = 1 AND q.lid=$labelid AND c.cfieldname like '%#0') OR (q.type = 1 AND q.lid1=$labelid AND c.cfieldname like '%#1') )"; + } + $result=$connect->Execute($query) or safe_die($connect->ErrorMsg()); + } +} + + +?> diff --git a/include/limesurvey/admin/listcolumn.php b/include/limesurvey/admin/listcolumn.php index 44cfbfd1..b32b44bc 100644 --- a/include/limesurvey/admin/listcolumn.php +++ b/include/limesurvey/admin/listcolumn.php @@ -1,71 +1,80 @@ -databaseType == 'odbc_mssql') - { $query = "SELECT id, ".db_quote_id($column)." FROM {$dbprefix}survey_$surveyid WHERE (".db_quote_id($column)." NOT LIKE '')"; } -else - { $query = "SELECT id, ".db_quote_id($column)." FROM {$dbprefix}survey_$surveyid WHERE (".db_quote_id($column)." != '')"; } - -if ($sql && $sql != "NULL") -{ - $query .= " AND ".auto_unescape(urldecode($sql)); -} - -if (incompleteAnsFilterstate() === true) {$query .= " AND submitdate is not null";} - -if ($order == "alpha") -{ - $query .= " ORDER BY ".db_quote_id($column); -} - -$result=db_execute_assoc($query) or safe_die("Error with query: ".$query."
    ".$connect->ErrorMsg()); -$listcolumnoutput= "\n"; -$listcolumnoutput.= "\n"; -$listcolumnoutput.= "\n"; -while ($row=$result->FetchRow()) -{ - $listcolumnoutput.= "" - . "\n"; -} -$listcolumnoutput.= "
    "; -if ($connect->databaseType != 'odbc_mssql') - { $listcolumnoutput.= ""; } -$listcolumnoutput.= "
    " - . "" - . $row['id']."".$row[$column]."
    \n"; - - -?> +databaseType == 'odbc_mssql' || $connect->databaseType == 'odbtp' || $connect->databaseType == 'mssql_n') + { $query = "SELECT id, ".db_quote_id($column)." FROM {$dbprefix}survey_$surveyid WHERE (".db_quote_id($column)." NOT LIKE '')"; } +else + { $query = "SELECT id, ".db_quote_id($column)." FROM {$dbprefix}survey_$surveyid WHERE (".db_quote_id($column)." != '')"; } + +if ($sql && $sql != "NULL") +{ + $query .= " AND ".auto_unescape(urldecode($sql)); +} + +switch (incompleteAnsFilterstate()) { + case 'inc': + //Inclomplete answers only + $query .= ' AND submitdate is null '; + break; + case 'filter': + //Inclomplete answers only + $query .= ' AND submitdate is not null '; + break; + } + +if ($order == "alpha") +{ + $query .= " ORDER BY ".db_quote_id($column); +} + +$result=db_execute_assoc($query) or safe_die("Error with query: ".$query."
    ".$connect->ErrorMsg()); +$listcolumnoutput= "\n"; +$listcolumnoutput.= "\n"; +$listcolumnoutput.= "\n"; +while ($row=$result->FetchRow()) +{ + $listcolumnoutput.= "" + . "\n"; +} +$listcolumnoutput.= "
    "; +if ($connect->databaseType != 'odbc_mssql' && $connect->databaseType != 'odbtp' && $connect->databaseType != 'mssql_n') + { $listcolumnoutput.= ""; } +$listcolumnoutput.= "
    " + . "" + . $row['id']."".htmlspecialchars($row[$column])."
    \n"; + + +?> diff --git a/include/limesurvey/admin/login_check.php b/include/limesurvey/admin/login_check.php index 26b54c4e..7cf53776 100644 --- a/include/limesurvey/admin/login_check.php +++ b/include/limesurvey/admin/login_check.php @@ -1,146 +1,248 @@ -
    ".$clang->gT("You have to enter user name and email.")."

    - - - - - - - - - - - - - - - - - -

    ".$clang->gT("Username")."

    ".$clang->gT("Email")."

      -
     \n
     ".$clang->gT("Main Admin Screen")."
    - "; - } - elseif (!isset($loginsummary)) - { // could be at login or after logout - $refererargs=''; // If this is a direct access to admin.php, no args are given - // If we are called from a link with action and other args set, get them - if (isset($_SERVER['QUERY_STRING']) && $_SERVER['QUERY_STRING']) - { - $refererargs = html_escape($_SERVER['QUERY_STRING']); - } - - $hidden_loginlang = ''; - if (isset($_POST['lang']) && $_POST['lang']) - { - $hidden_loginlang = ""; - } - - if (!isset($logoutsummary)) - { - $loginsummary = "

    ".$clang->gT("You have to login first.")."

    "; - } - else - { - $loginsummary = "
    ".$logoutsummary."

    "; - } - - $loginsummary .= " - - - - - - - - - - - - - - - - - -
    ".$clang->gT("Username")."
    ".$clang->gT("Password")."
      - - $hidden_loginlang -
     \n
     ".$clang->gT("Forgot Your Password?")."
     \n
    -
    "; - - // Language selection - $loginsummary .= "\t
    " - . "\t\n" - . "\t\t\n" - . "\t\n" - . "
    \n" - . "\t\t\t".$clang->gT("Current Language").":\n" - . "\t\t\n" - . "\t\t\t\n" - . "\t\t\t\n" - . "\t\t
    " - . "

    "; - } -} - -if (isset($loginsummary)) { - - $adminoutput.= "\n" - ."\t\n" - ."\t\t\n"; - $adminoutput.= "\t\n"; - $adminoutput.= "
    \n"; - - if(isset($_SESSION['loginID'])) - { - $adminoutput.= showadminmenu(); - } - $adminoutput.= $loginsummary; - - $adminoutput.= "\t\t
    \n"; -} - -?> +".$clang->gT("Data for username and one time password was received but the usage of one time passwords is disabled at your configuration settings. Please add the following line to config.php to enable one time passwords: ")."
    "; + $loginsummary .= '
    $use_one_time_passwords = true;
    '; + $loginsummary .= "

    ".$clang->gT("Continue")."
     \n"; + } + //Data was passed, using one time passwords is enabled + else + { + //check if user exists in DB + $query = "SELECT uid, users_name, password, one_time_pw FROM ".db_table_name('users')." WHERE users_name=".$connect->qstr($user); + $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC; //Checked + $result = $connect->SelectLimit($query, 1) or safe_die ($query."
    ".$connect->ErrorMsg()); + if(!$result) + { + echo "
    ".$connect->ErrorMsg(); + } + if ($result->RecordCount() < 1) + { + // wrong or unknown username + $loginsummary = sprintf($clang->gT("No one-time password found for user %s"),htmlspecialchars($user))."
    "; + session_regenerate_id(); + } + else + { + //get one time pw from db + $srow = $result->FetchRow(); + $otpw = $srow['one_time_pw']; + + //check if passed password and one time password from database DON'T match + if($pw != $otpw) + { + //no match -> warning + $loginsummary = "
    ".sprintf($clang->gT("Passed one time password doesn't match one time password for user %s")," ".htmlspecialchars($user)."")."
    "; + $loginsummary .= "

    ".$clang->gT("Continue")."
     \n"; + } + //both passwords match + else + { + + //delete one time password in database + $uquery = "UPDATE ".db_table_name('users')." + SET one_time_pw='' + WHERE users_name='".db_quote($user)."'"; + + $uresult = $connect->Execute($uquery); + + //data necessary for following functions + $_SESSION['user'] = $srow['users_name']; + $_SESSION['checksessionpost'] = randomkey(10); + $_SESSION['loginID'] = $srow['uid']; + GetSessionUserRights($_SESSION['loginID']); + + // Check if the user has changed his default password + if (strtolower($srow['password'])=='password') + { + $_SESSION['pw_notify']=true; + } + else + { + $_SESSION['pw_notify']=false; + } + + //delete passed information + unset($_GET['user']); + unset($_GET['onepass']); + + } //else -> passwords match + + } //else -> password found + + } //else -> one time passwords enabled + + } //else -> one time passwords set + +} //else -> data was passed by URL + + + + + +// check data for login +if( isset($_POST['user']) && isset($_POST['password']) || + ($action == "forgotpass") || ($action == "login") || + ($action == "logout") || + ($useWebserverAuth === true && !isset($_SESSION['loginID'])) ) // added by Dennis +{ + include("usercontrol.php"); +} + + + + +// login form +if(!isset($_SESSION['loginID']) && $action != "forgotpass" && ($action != "logout" || ($action == "logout" && !isset($_SESSION['loginID'])))) // && $action != "login") // added by Dennis +{ + if($action == "forgotpassword") + { + $loginsummary = ' +
    +

    '.$clang->gT('You have to enter user name and email.').'

    + + + + + + + + + + + + + + + + + + + +
      +
     '.$clang->gT('Main Admin Screen').'
    +
    +'; + } + elseif (!isset($loginsummary)) + { // could be at login or after logout + $refererargs=''; // If this is a direct access to admin.php, no args are given + // If we are called from a link with action and other args set, get them + if (isset($_SERVER['QUERY_STRING']) && $_SERVER['QUERY_STRING']) + { + $refererargs = html_escape($_SERVER['QUERY_STRING']); + } + + $hidden_loginlang = ""; + + + if (!isset($logoutsummary)) + { + $loginsummary = "

    ".$clang->gT("You have to login first.")."

    "; + } + else + { + $loginsummary = "
    ".$logoutsummary."

    "; + } + + $loginsummary .= " + + + + + + + + + + + + + + + + + + + + + +
    ".$clang->gT("Username")."
    ".$clang->gT("Password")."
    ".$clang->gT("Language")." + \n" + . "
      + + $hidden_loginlang +
     \n
     ".$clang->gT("Forgot Your Password?")."
     \n
    +

    "; + $loginsummary .= " \n"; + } +} + +if (isset($loginsummary)) +{ + $adminoutput.= "\n" + ."\t\n" + ."\t\t\n"; + $adminoutput.= "\t\n"; + $adminoutput.= "
    \n"; + + if(isset($_SESSION['loginID'])) + { + $adminoutput.= showadminmenu(); + } + $adminoutput.= $loginsummary; + + $adminoutput.= "\t\t
    \n"; +} + +?> diff --git a/include/limesurvey/admin/login_check_cas.php b/include/limesurvey/admin/login_check_cas.php new file mode 100644 index 00000000..f4561fa9 --- /dev/null +++ b/include/limesurvey/admin/login_check_cas.php @@ -0,0 +1,88 @@ + \ No newline at end of file diff --git a/include/limesurvey/admin/preview.php b/include/limesurvey/admin/preview.php index 8e2e79c8..999580fc 100644 --- a/include/limesurvey/admin/preview.php +++ b/include/limesurvey/admin/preview.php @@ -1,66 +1,91 @@ -FetchRow(); - -$ia = array(0 => $qid, 1 => "FIELDNAME", 2 => $qrows['title'], 3 => $qrows['question'], 4 => $qrows['type'], 5 => $qrows['gid'], -6 => $qrows['mandatory'], 7 => $qrows['other']); -$answers = retrieveAnswers($ia); -$thistpl="$publicdir/templates"; -doHeader(); -//echo "\t\t\t\t
    - "; -echo "
    \n"; -$question=""; -$answer=$answers[0][1]; -$help=$answers[0][2]; -$questioncode=$answers[0][5]; -echo templatereplace(file_get_contents("$thistpl/preview.pstpl")); -echo "
    \n"; -echo "\n"; - - -exit; -?> +FetchRow(); +$ia = array(0 => $qid, + 1 => "FIELDNAME", + 2 => $qrows['title'], + 3 => $qrows['question'], + 4 => $qrows['type'], + 5 => $qrows['gid'], + 6 => $qrows['mandatory'], + 7 => $qrows['other']); + +$answers = retrieveAnswers($ia); +$thistpl="$templaterootdir/".$thissurvey['template']; +doHeader(); +$dummy_js = ' + + +
    + '; + + + +$question=""; +$answer=$answers[0][1]; +$help=$answers[0][2]; +$questioncode=$answers[0][5]; +$content = templatereplace(file_get_contents("$thistpl/startpage.pstpl")); +$content .= templatereplace(file_get_contents("$thistpl/startgroup.pstpl")); +$content .= templatereplace(file_get_contents("$thistpl/question.pstpl")); +$content .= templatereplace(file_get_contents("$thistpl/endgroup.pstpl")).$dummy_js; +$content .= templatereplace(file_get_contents("$thistpl/endpage.pstpl")); +if($qrows['mandatory'] == 'Y') +{ + $mandatory = ' mandatory'; +} +else +{ + $mandatory = ''; +} +$content = str_replace('{QUESTION_CLASS}' , question_class($qrows['type']) . $mandatory , $content); +echo $content; +echo "\n"; + + +exit; +?> diff --git a/include/limesurvey/admin/printablesurvey.php b/include/limesurvey/admin/printablesurvey.php index 12e0cdc2..1362b0de 100644 --- a/include/limesurvey/admin/printablesurvey.php +++ b/include/limesurvey/admin/printablesurvey.php @@ -1,991 +1,1780 @@ -\n" -."\n\n" -. "\n" -. "$sitename\n" -. "\n" -. "\n" -. "\n" -. "\n" -. "\n" -. "\n" -. "\n" -. "\n" -. "\n" -. "\n" -. "\n\n"; - -$surveyid = $_GET['sid']; - -// PRESENT SURVEY DATAENTRY SCREEN -if(isset($_POST['printableexport'])) -{ - $pdf = new PDF ('L','mm','A4'); - $pdf->SetFont($pdfdefaultfont,'',$pdffontsize); - $pdf->AddPage(); -} -// Set the language of the survey, either from GET parameter of session var -if (isset($_GET['lang'])) -{ - $_GET['lang'] = preg_replace("/[^a-zA-Z0-9-]/", "", $_GET['lang']); - if ($_GET['lang']) $surveyprintlang = $_GET['lang']; -} else -{ - $surveyprintlang=GetbaseLanguageFromSurveyid($surveyid); -} - -// Setting the selected language for printout -$clang = new limesurvey_lang($surveyprintlang); - -$desquery = "SELECT * FROM ".db_table_name('surveys')." inner join ".db_table_name('surveys_languagesettings')." on (surveyls_survey_id=sid) WHERE sid=$surveyid and surveyls_language=".$connect->qstr($surveyprintlang); //Getting data for this survey - -$desresult = db_execute_assoc($desquery); -while ($desrow = $desresult->FetchRow()) -{ - $surveyname = $desrow['surveyls_title']; - $surveydesc = $desrow['surveyls_description']; - $surveyactive = $desrow['active']; - $surveytable = db_table_name("survey_".$desrow['sid']); - $surveyuseexpiry = $desrow['useexpiry']; - $surveyexpirydate = $desrow['expires']; - $surveyfaxto = $desrow['faxto']; -} -if (!isset($surveyfaxto) || !$surveyfaxto and isset($surveyfaxnumber)) -{ - $surveyfaxto=$surveyfaxnumber; //Use system fax number if none is set in survey. -} - - -$printablesurveyoutput .="\n"; -if(isset($usepdfexport) && $usepdfexport == 1 && !in_array($surveyprintlang,$notsupportlanguages)) -{ - $printablesurveyoutput .="\n"; - $printablesurveyoutput .="\n"; -$printablesurveyoutput .="\t\t\n"; -$printablesurveyoutput .="\t\n"; -// SURVEY NAME AND DESCRIPTION TO GO HERE - -$fieldmap=createFieldMap($surveyid); - -$degquery = "SELECT * FROM ".db_table_name("groups")." WHERE sid='{$surveyid}' AND language='{$surveyprintlang}' ORDER BY ".db_table_name("groups").".group_order"; -$degresult = db_execute_assoc($degquery); -// GROUP NAME -while ($degrow = $degresult->FetchRow()) -{ - $deqquery = "SELECT * FROM ".db_table_name("questions")." WHERE sid=$surveyid AND gid={$degrow['gid']} AND language='{$surveyprintlang}' AND TYPE<>'I' ORDER BY question_order"; - $deqresult = db_execute_assoc($deqquery); - $deqrows = array(); //Create an empty array in case FetchRow does not return any rows - while ($deqrow = $deqresult->FetchRow()) {$deqrows[] = $deqrow;} // Get table output into array - - // Perform a case insensitive natural sort on group name then question title of a multidimensional array - usort($deqrows, 'CompareGroupThenTitle'); - - $printablesurveyoutput .="\t\n"; - $printablesurveyoutput .="\t\t\n"; - $printablesurveyoutput .="\t\n"; - $gid = $degrow['gid']; - //Alternate bgcolor for different groups - if (!isset($bgc) || $bgc == "#EEEEEE") {$bgc = "#DDDDDD";} - else {$bgc = "#EEEEEE";} - - foreach ($deqrows as $deqrow) - { - //GET ANY CONDITIONS THAT APPLY TO THIS QUESTION - $explanation = ""; //reset conditions explanation - $x=0; - $distinctquery="SELECT DISTINCT cqid, method, ".db_table_name("questions").".title FROM ".db_table_name("conditions").", ".db_table_name("questions")." WHERE ".db_table_name("conditions").".cqid=".db_table_name("questions").".qid AND ".db_table_name("conditions").".qid={$deqrow['qid']} AND language='{$surveyprintlang}' ORDER BY cqid"; - $distinctresult=db_execute_assoc($distinctquery); - while ($distinctrow=$distinctresult->FetchRow()) - { - if ($x > 0) {$explanation .= " ".$clang->gT("and")." ";} - if (trim($distinctrow['method'])=='') {$distinctrow['method']='==';} - if ($distinctrow['method']=='==') {$explanation .= $clang->gT("if you answered")." ";} - elseif ($distinctrow['method']='!=') - {$explanation .= $clang->gT("if you have NOT answered")." ";} - else - {$explanation .= $clang->gT("if you answered")." ";} - - - $conquery="SELECT cid, cqid, ".db_table_name("questions").".title,\n" - ."".db_table_name("questions").".question, value, ".db_table_name("questions").".type,\n" - ."".db_table_name("questions").".lid, cfieldname\n" - ."FROM ".db_table_name("conditions").", ".db_table_name("questions")."\n" - ."WHERE ".db_table_name("conditions").".cqid=".db_table_name("questions").".qid\n" - ."AND ".db_table_name("conditions").".cqid={$distinctrow['cqid']}\n" - ."AND ".db_table_name("conditions").".qid={$deqrow['qid']} AND language='{$surveyprintlang}'"; - $conresult=db_execute_assoc($conquery) or safe_die("$conquery
    ".htmlspecialchars($connect->ErrorMsg())); - $conditions=array(); - while ($conrow=$conresult->FetchRow()) - { - - $postans=""; - $value=$conrow['value']; - switch($conrow['type']) - { - case "Y": - switch ($conrow['value']) - { - case "Y": $conditions[]=$clang->gT("Yes"); break; - case "N": $conditions[]=$clang->gT("No"); break; - } - break; - case "G": - switch($conrow['value']) - { - case "M": $conditions[]=$clang->gT("Male"); break; - case "F": $conditions[]=$clang->gT("Female"); break; - } // switch - break; - case "A": - case "B": - $conditions[]=$conrow['value']; - break; - case "C": - switch($conrow['value']) - { - case "Y": $conditions[]=$clang->gT("Yes"); break; - case "U": $conditions[]=$clang->gT("Uncertain"); break; - case "N": $conditions[]=$clang->gT("No"); break; - } // switch - break; - case "E": - switch($conrow['value']) - { - case "I": $conditions[]=$clang->gT("Increase"); break; - case "D": $conditions[]=$clang->gT("Decrease"); break; - case "S": $conditions[]=$clang->gT("Same"); break; - } - case "F": - case "1": - case "H": - case "W": - case "L": - default: - $value=substr($conrow['cfieldname'], strpos($conrow['cfieldname'], "X".$conrow['cqid'])+strlen("X".$conrow['cqid']), strlen($conrow['cfieldname'])); - $fquery = "SELECT * FROM ".db_table_name("labels")."\n" - . "WHERE lid='{$conrow['lid']}'\n" - . "AND code='{$conrow['value']}' AND language='{$surveyprintlang}'"; - $fresult=db_execute_assoc($fquery) or safe_die("$fquery
    ".htmlspecialchars($connect->ErrorMsg())); - while($frow=$fresult->FetchRow()) - { - $postans=$frow['title']; - $conditions[]=$frow['title']; - } // while - break; - } // switch - $answer_section=""; - switch($conrow['type']) - { - case "A": - case "B": - case "C": - case "E": - $thiscquestion=arraySearchByKey($conrow['cfieldname'], $fieldmap, "fieldname"); - $ansquery="SELECT answer FROM ".db_table_name("answers")." WHERE qid='{$conrow['cqid']}' AND code='{$thiscquestion[0]['aid']}' AND language='{$surveyprintlang}'"; - $ansresult=db_execute_assoc($ansquery); - while ($ansrow=$ansresult->FetchRow()) - { - $answer_section=" (".$ansrow['answer'].")"; - } - break; - default: - $ansquery="SELECT answer FROM ".db_table_name("answers")." WHERE qid='{$conrow['cqid']}' AND code='{$conrow['value']}' AND language='{$surveyprintlang}'"; - $ansresult=db_execute_assoc($ansquery); - while ($ansrow=$ansresult->FetchRow()) - { - $conditions[]=$ansrow['answer']; - } - $conditions = array_unique($conditions); - break; - } - } - if (count($conditions) > 1) - { - $explanation .= "'".implode("' ".$clang->gT("or")." '", $conditions)."'"; - } - elseif (count($conditions) == 1) - { - $explanation .= "'".$conditions[0]."'"; - } - unset($conditions); - $explanation .= " ".$clang->gT("to question")." '".$distinctrow['title']." $answer_section'"; - $x++; - } - - if ($explanation) - { - $explanation = "[".$clang->gT("Only answer this question")." ".$explanation."]"; - $printablesurveyoutput .="\n"; - } - //END OF GETTING CONDITIONS - - $qid = $deqrow['qid']; - $fieldname = "$surveyid"."X"."$gid"."X"."$qid"; - $printablesurveyoutput .="\t\n"; - $printablesurveyoutput .="\t\t\n"; - $printablesurveyoutput .="\t\n"; - //DIFFERENT TYPES OF DATA FIELD HERE - if(isset($_POST['printableexport'])){$pdf->intopdf($deqrow['title']." ".$deqrow['question']);} - $printablesurveyoutput .="\t\n"; - $printablesurveyoutput .="\t\t\n"; - $printablesurveyoutput .="\t\t\n \n \n \n"; - $printablesurveyoutput .="\t\n"; - $printablesurveyoutput .="\t\n"; - if(isset($_POST['printableexport'])){$pdf->ln(5);} - } -} -$printablesurveyoutput .="\t\n"; -$printablesurveyoutput .="\t\t\n"; -$printablesurveyoutput .="\t\n"; -$printablesurveyoutput .="
    "; - $printablesurveyoutput .=""; - $printablesurveyoutput .=""; - $printablesurveyoutput .=""; -} -if(isset($_POST['printableexport'])){$pdf->titleintopdf($surveyname,$surveydesc);} -$printablesurveyoutput .="\t
    \n"; -$printablesurveyoutput .="\t\t\t\n"; -$printablesurveyoutput .="\t\t\t\t\n"; -$printablesurveyoutput .="\t\t\t
    \n"; -$printablesurveyoutput .="\t\t\t\t\t$surveyname\n"; -$printablesurveyoutput .="\t\t\t\t\t
    $surveydesc\n"; -$printablesurveyoutput .="\t\t\t\t
    \n"; -$printablesurveyoutput .="\t\t
    \n"; - $printablesurveyoutput .="\t\t\t{$degrow['group_name']}\n"; - if ($degrow['description']) - { - $printablesurveyoutput .="\t\t\t
    {$degrow['description']}\n"; - } - if(isset($_POST['printableexport'])){$pdf->titleintopdf($degrow['group_name'],$degrow['description']);} - $printablesurveyoutput .="\t\t
    $explanation
    \n"; - $pdfoutput =''; - if ($deqrow['mandatory'] == "Y") - { - $printablesurveyoutput .=$clang->gT("*"); - $pdfoutput .= $clang->gT("*"); - } - $printablesurveyoutput .="\t\t\t{$deqrow['title']}: {$deqrow['question']}\n"; - $printablesurveyoutput .="\t\t
    \n"; - if ($deqrow['help']) - { - $hh = $deqrow['help']; - $printablesurveyoutput .="\t\t\t
    $hh
    \n"; - if(isset($_POST['printableexport'])){$pdf->helptextintopdf($hh);} - } - $printablesurveyoutput .="\t\t
    \n"; - switch($deqrow['type']) - { - case "5": //5 POINT CHOICE - $printablesurveyoutput .="\t\t\t".$clang->gT("Please choose *only one* of the following:")."
    \n"; - if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Please choose *only one* of the following:"),"U");} - $pdfoutput =''; - for ($i=1; $i<=5; $i++) - { - $pdfoutput .=" o ".$i." "; - $printablesurveyoutput .="\t\t\t$i \n"; - } - if(isset($_POST['printableexport'])){$pdf->intopdf($pdfoutput);} - break; - case "D": //DATE - $printablesurveyoutput .="\t\t\t".$clang->gT("Please enter a date:")."
    \n"; - $printablesurveyoutput .="\t\t\t\n"; - if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Please enter a date:")." ___________");} - break; - case "G": //GENDER - $printablesurveyoutput .="\t\t\t".$clang->gT("Please choose *only one* of the following:")."
    \n"; - $printablesurveyoutput .="\t\t\t".$clang->gT("Female")."
    \n"; - $printablesurveyoutput .="\t\t\t".$clang->gT("Male")."
    \n"; - if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Please choose *only one* of the following:"));} - if(isset($_POST['printableexport'])){$pdf->intopdf(" o ".$clang->gT("Female")." | o ".$clang->gT("Male"));} - break; - case "W": //Flexible List - case "Z": - $qidattributes=getQuestionAttributes($deqrow['qid']); - if ($displaycols=arraySearchByKey("display_columns", $qidattributes, "attribute", 1)) - { - $dcols=$displaycols['value']; - } - else - { - $dcols=0; - } - $printablesurveyoutput .="\t\t\t".$clang->gT("Please choose *only one* of the following:")."
    \n"; - if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Please choose *only one* of the following:"),"U");} - $deaquery = "SELECT * FROM ".db_table_name("labels")." WHERE lid={$deqrow['lid']} AND language='{$surveyprintlang}' ORDER BY sortorder"; - $dearesult = db_execute_assoc($deaquery) or safe_die("ERROR: $deaquery
    \n".$connect->ErrorMsg()); - $deacount=$dearesult->RecordCount(); - if ($deqrow['other'] == "Y") {$deacount++;} - if ($dcols > 0 && $deacount >= $dcols) - { - $width=sprintf("%0d", 100/$dcols); - $maxrows=ceil(100*($deacount/$dcols)/100); //Always rounds up to nearest whole number - $divider="
    "; - $upto=0; - $printablesurveyoutput .="\n
    "; - while ($dearow = $dearesult->FetchRow()) - { - if ($upto == $maxrows) - { - $printablesurveyoutput .=$divider; - $upto=0; - } - $printablesurveyoutput .="\t\t\t{$dearow['title']}
    \n"; - if(isset($_POST['printableexport'])){$pdf->intopdf(" o ".$dearow['title']);} - $upto++; - } - if ($deqrow['other'] == "Y") - { - $printablesurveyoutput .="\t\t\t".$clang->gT("Other")."
    \n"; - if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Other").": ________");} - } - $printablesurveyoutput .="
    \n"; - //Let's break the presentation into columns. - } - else - { - while ($dearow = $dearesult->FetchRow()) - { - $printablesurveyoutput .="\t\t\t{$dearow['title']}
    \n"; - if(isset($_POST['printableexport'])){$pdf->intopdf(" o ".$dearow['title']);} - } - if ($deqrow['other'] == "Y") - { - $printablesurveyoutput .="\t\t\t".$clang->gT("Other")."
    \n"; - if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Other").": ________");} - } - } - break; - case "L": //LIST - case "!": - $qidattributes=getQuestionAttributes($deqrow['qid']); - if ($displaycols=arraySearchByKey("display_columns", $qidattributes, "attribute", 1)) - { - $dcols=$displaycols['value']; - } - else - { - $dcols=0; - } - $printablesurveyoutput .="\t\t\t".$clang->gT("Please choose *only one* of the following:")."
    \n"; - if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Please choose *only one* of the following:"));} - $deaquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid={$deqrow['qid']} AND language='{$surveyprintlang}' ORDER BY sortorder, answer"; - $dearesult = db_execute_assoc($deaquery); - $deacount=$dearesult->RecordCount(); - if ($deqrow['other'] == "Y") {$deacount++;} - if ($dcols > 0 && $deacount >= $dcols) - { - $width=sprintf("%0d", 100/$dcols); - $maxrows=ceil(100*($deacount/$dcols)/100); //Always rounds up to nearest whole number - $divider="
    "; - $upto=0; - $printablesurveyoutput .="\n
    "; - while ($dearow = $dearesult->FetchRow()) - { - if ($upto == $maxrows) - { - $printablesurveyoutput .=$divider; - $upto=0; - } - $printablesurveyoutput .="\t\t\t{$dearow['answer']}
    \n"; - if(isset($_POST['printableexport'])){$pdf->intopdf(" o ".$dearow['answer']);} - $upto++; - } - if ($deqrow['other'] == "Y") - { - $printablesurveyoutput .="\t\t\t".$clang->gT("Other")."
    \n"; - if(isset($_POST['printableexport'])){$pdf->intopdf(" o ".$clang->gT("Other").": ________");} - } - $printablesurveyoutput .="
    \n"; - //Let's break the presentation into columns. - } - else - { - while ($dearow = $dearesult->FetchRow()) - { - $printablesurveyoutput .="\t\t\t{$dearow['answer']}
    \n"; - if(isset($_POST['printableexport'])){$pdf->intopdf(" o ".$dearow['answer']);} - } - if ($deqrow['other'] == "Y") - { - $printablesurveyoutput .="\t\t\t".$clang->gT("Other")."
    \n"; - if(isset($_POST['printableexport'])){$pdf->intopdf(" o ".$clang->gT("Other").": ________");} - } - } - break; - case "O": //LIST WITH COMMENT - $printablesurveyoutput .="\t\t\t".$clang->gT("Please choose *only one* of the following:")."
    \n"; - if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Please choose *only one* of the following:"),"U");} - $deaquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid={$deqrow['qid']} AND language='{$surveyprintlang}' ORDER BY sortorder, answer "; - $dearesult = db_execute_assoc($deaquery); - while ($dearow = $dearesult->FetchRow()) - { - $printablesurveyoutput .="\t\t\t{$dearow['answer']}
    \n"; - if(isset($_POST['printableexport'])){$pdf->intopdf($dearow['answer']);} - } - $printablesurveyoutput .="\t\t\t".$clang->gT("Make a comment on your choice here:")."
    \n"; - if(isset($_POST['printableexport'])){$pdf->intopdf("Make a comment on your choice here:");} - $printablesurveyoutput .="\t\t\t\n"; - for($i=0;$i<9;$i++) - { - if(isset($_POST['printableexport'])){$pdf->intopdf("____________________");} - } - break; - case "R": //RANKING Type Question - $reaquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid={$deqrow['qid']} AND language='{$surveyprintlang}' ORDER BY sortorder, answer"; - $rearesult = db_execute_assoc($reaquery) or safe_die ("Couldn't get ranked answers
    ".$connect->ErrorMsg()); - $reacount = $rearesult->RecordCount(); - $printablesurveyoutput .="\t\t\t".$clang->gT("Please number each box in order of preference from 1 to")." $reacount
    \n"; - if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Please number each box in order of preference from 1 to ").$reacount,"U");} - while ($rearow = $rearesult->FetchRow()) - { - $printablesurveyoutput .="\t\t\t\n"; - $printablesurveyoutput .="\t\t\t
     {$rearow['answer']}
    \n"; - if(isset($_POST['printableexport'])){$pdf->intopdf("__ ".$rearow['answer']);} - } - break; - case "M": //MULTIPLE OPTIONS (Quite tricky really!) - $qidattributes=getQuestionAttributes($deqrow['qid']); - if ($displaycols=arraySearchByKey("display_columns", $qidattributes, "attribute", 1)) - { - $dcols=$displaycols['value']; - } - else - { - $dcols=0; - } - if (!$maxansw=arraySearchByKey("max_answers", $qidattributes, "attribute", 1)) - { - $printablesurveyoutput .="\t\t\t".$clang->gT("Please choose *all* that apply:")."
    \n"; - if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Please choose *all* that apply:"),"U");} - } - else - { - $printablesurveyoutput .="\t\t\t".$clang->gT("Please choose *at most* ").$maxansw['value']." ".$clang->gT("answers:")."
    \n"; - if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Please choose *at most* ").$maxansw['value'].$clang->gT("answers:"),"U");} - } - $meaquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid={$deqrow['qid']} AND language='{$surveyprintlang}' ORDER BY sortorder, answer"; - $mearesult = db_execute_assoc($meaquery); - $meacount = $mearesult->RecordCount(); - if ($deqrow['other'] == "Y") {$meacount++;} - if ($dcols > 0 && $meacount >= $dcols) - { - $width=sprintf("%0d", 100/$dcols); - $maxrows=ceil(100*($meacount/$dcols)/100); //Always rounds up to nearest whole number - $divider="
    "; - $upto=0; - $printablesurveyoutput .="\n
    "; - while ($mearow = $mearesult->FetchRow()) - { - if ($upto == $maxrows) - { - $printablesurveyoutput .=$divider; - $upto=0; - } - $printablesurveyoutput .="\t\t\t{$mearow['answer']}
    \n"; - if(isset($_POST['printableexport'])){$pdf->intopdf(" o ".$mearow['answer']);} - $upto++; - } - if ($deqrow['other'] == "Y") - { - $printablesurveyoutput .="\t\t\t".$clang->gT("Other").": \n"; - if(isset($_POST['printableexport'])){$pdf->intopdf(" o ".$clang->gT("Other").": ________");} - - } - $printablesurveyoutput .="
    \n"; - } - else - { - while ($mearow = $mearesult->FetchRow()) - { - $printablesurveyoutput .="\t\t\t{$mearow['answer']}
    \n"; - if(isset($_POST['printableexport'])){$pdf->intopdf(" o ".$mearow['answer']);} - } - if ($deqrow['other'] == "Y") - { - $printablesurveyoutput .="\t\t\t".$clang->gT("Other").": \n"; - if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Other").": ________");} - } - } - break; - /*case "I": //Language Switch in a printable survey does not make sense - $printablesurveyoutput .="\t\t\t".$clang->gT("Please choose *only one* of the following:")."
    \n"; - $answerlangs = GetAdditionalLanguagesFromSurveyID($surveyid); - $answerlangs [] = GetBaseLanguageFromSurveyID($surveyid); - - foreach ($answerlangs as $ansrow) - { - $printablesurveyoutput .="\t\t\t".getLanguageNameFromCode($ansrow, true)."
    \n"; - } - break; - */ - - case "P": //MULTIPLE OPTIONS WITH COMMENTS - $qidattributes=getQuestionAttributes($deqrow['qid']); - if (!$maxansw=arraySearchByKey("max_answers", $qidattributes, "attribute", 1)) - { - $printablesurveyoutput .="\t\t\t".$clang->gT("Please choose all that apply and provide a comment:")."
    \n"; - if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Please choose all that apply and provide a comment:"),"U");} - } - else - { - $printablesurveyoutput .="\t\t\t".$clang->gT("Please choose *at most* ").$maxansw['value']." ".$clang->gT("answers and provide a comment:")."
    \n"; - if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Please choose *at most* ").$maxansw['value'].$clang->gT("answers and provide a comment:"),"U");} - } - $meaquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid={$deqrow['qid']} AND language='{$surveyprintlang}' ORDER BY sortorder, answer"; - $mearesult = db_execute_assoc($meaquery); -// $printablesurveyoutput .="\t\t\t".$clang->gT("Please choose all that apply and provide a comment:")."
    \n"; - $printablesurveyoutput .="\t\t\t\n"; - $pdfoutput=array(); - $j=0; - while ($mearow = $mearesult->FetchRow()) - { - $printablesurveyoutput .="\t\t\t\t\n"; - $printablesurveyoutput .="\t\t\t\t\t\n"; - $printablesurveyoutput .="\t\t\t\t\n"; - $a++; - } - $printablesurveyoutput .="\t\t\t
    tableintopdf($pdfoutput);} - break; - case "Q": //MULTIPLE SHORT TEXT - - - $width=60; - case "K": //MULTIPLE NUMERICAL - $width=(!isset($width)) ? 30 : $width; - if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Please write your answer(s) here:"),"U");} - $printablesurveyoutput .="\t\t\t".$clang->gT("Please write your answer(s) here:")."
    \n"; - $meaquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid={$deqrow['qid']} AND language='{$surveyprintlang}' ORDER BY sortorder, answer"; - $mearesult = db_execute_assoc($meaquery); - $printablesurveyoutput .="\t\t\t\n"; - while ($mearow = $mearesult->FetchRow()) - { - $printablesurveyoutput .="\t\t\t\t\n"; - $printablesurveyoutput .="\t\t\t\t\t
    {$mearow['answer']}:intopdf($mearow['answer'].": ____________________");} - } - $printablesurveyoutput .="\t\t\t
    \n"; - break; - case "S": //SHORT TEXT - $printablesurveyoutput .="\t\t\t".$clang->gT("Please write your answer here:")."
    \n"; - $printablesurveyoutput .="\t\t\t\n"; - if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Please write your answer here:"),"U");} - if(isset($_POST['printableexport'])){$pdf->intopdf("____________________");} - break; - case "T": //LONG TEXT - $printablesurveyoutput .="\t\t\t".$clang->gT("Please write your answer here:")."
    \n"; - $printablesurveyoutput .="\t\t\t\n"; - if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Please write your answer here:"),"U");} - for($i=0;$i<9;$i++) - { - if(isset($_POST['printableexport'])){$pdf->intopdf("____________________");} - } - break; - case "U": //HUGE TEXT - $printablesurveyoutput .="\t\t\t".$clang->gT("Please write your answer here:")."
    \n"; - $printablesurveyoutput .="\t\t\t\n"; - if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Please write your answer here:"),"U");} - for($i=0;$i<20;$i++) - { - if(isset($_POST['printableexport'])){$pdf->intopdf("____________________");} - } - break; - case "N": //NUMERICAL - $printablesurveyoutput .="\t\t\t".$clang->gT("Please write your answer here:")."
    \n"; - $printablesurveyoutput .="\t\t\t\n"; - if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Please write your answer here:"),"U");} - if(isset($_POST['printableexport'])){$pdf->intopdf("____________________");} - - break; - case "Y": //YES/NO - $printablesurveyoutput .="\t\t\t".$clang->gT("Please choose *only one* of the following:")."
    \n"; - $printablesurveyoutput .="\t\t\t".$clang->gT("Yes")."
    \n"; - $printablesurveyoutput .="\t\t\t".$clang->gT("No")."
    \n"; - if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Please choose *only one* of the following:"),"U");} - if(isset($_POST['printableexport'])){$pdf->intopdf(" o ".$clang->gT("Yes"));} - if(isset($_POST['printableexport'])){$pdf->intopdf(" o ".$clang->gT("No"));} - break; - case "A": //ARRAY (5 POINT CHOICE) - $meaquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid={$deqrow['qid']} AND language='{$surveyprintlang}' ORDER BY sortorder, answer"; - $mearesult = db_execute_assoc($meaquery); - $printablesurveyoutput .="\t\t\t".$clang->gT("Please choose the appropriate response for each item:")."
    \n"; - $printablesurveyoutput .="\t\t\t\n"; - if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Please choose the appropriate response for each item:"),"U");} - $pdfoutput = array(); - $j=0; - while ($mearow = $mearesult->FetchRow()) - { - $printablesurveyoutput .="\t\t\t\t\n"; - $answertext=$mearow['answer']; - if (strpos($answertext,'|')) {$answertext=substr($answertext,0, strpos($answertext,'|'));} - $printablesurveyoutput .="\t\t\t\t\t\n"; - $printablesurveyoutput .="\t\t\t\t\t\n"; - $answertext=$mearow['answer']; - if (strpos($answertext,'|')) - { - $answertext=substr($answertext,strpos($answertext,'|')+1); - $printablesurveyoutput .= "\t\t\t\t\n"; - } - $printablesurveyoutput .="\t\t\t\t\n"; - $j++; - } - $printablesurveyoutput .="\t\t\t
    $answertext"; - $pdfoutput[$j][0]=$answertext; - for ($i=1; $i<=5; $i++) - { - $printablesurveyoutput .="\t\t\t\t\t\t$i \n"; - $pdfoutput[$j][$i]=" o ".$i; - } - $printablesurveyoutput .="\t\t\t\t\t$answertext
    \n"; - if(isset($_POST['printableexport'])){$pdf->tableintopdf($pdfoutput);} - break; - case "B": //ARRAY (10 POINT CHOICE) - $meaquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid={$deqrow['qid']} AND language='{$surveyprintlang}' ORDER BY sortorder, answer"; - $mearesult = db_execute_assoc($meaquery); - $printablesurveyoutput .="\t\t\t".$clang->gT("Please choose the appropriate response for each item:")."
    "; - $printablesurveyoutput .="\t\t\t\n"; - if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Please choose the appropriate response for each item:"),"U");} - $pdfoutput=array(); - $j=0; - while ($mearow = $mearesult->FetchRow()) - { - $printablesurveyoutput .="\t\t\t\t\n"; - $printablesurveyoutput .="\t\t\t\t\t\n"; - $printablesurveyoutput .="\t\t\t\t\t\n"; - $printablesurveyoutput .="\t\t\t\t\n"; - $j++; - } - $printablesurveyoutput .="\t\t\t
    {$mearow['answer']}\n"; - $pdfoutput[$j][0]=$mearow['answer']; - for ($i=1; $i<=10; $i++) - { - $printablesurveyoutput .="\t\t\t\t\t\t$i \n"; - $pdfoutput[$j][$i]=" o ".$i; - } - $printablesurveyoutput .="\t\t\t\t\t
    \n"; - if(isset($_POST['printableexport'])){$pdf->tableintopdf($pdfoutput);} - break; - case "C": //ARRAY (YES/UNCERTAIN/NO) - $meaquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid={$deqrow['qid']} AND language='{$surveyprintlang}' ORDER BY sortorder, answer"; - $mearesult = db_execute_assoc($meaquery); - $printablesurveyoutput .="\t\t\t".$clang->gT("Please choose the appropriate response for each item:")."
    \n"; - $printablesurveyoutput .="\t\t\t\n"; - if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Please choose the appropriate response for each item:"),"U");} - $pdfoutput = array(); - $j=0; - while ($mearow = $mearesult->FetchRow()) - { - $printablesurveyoutput .="\t\t\t\t\n"; - $printablesurveyoutput .="\t\t\t\t\t\n"; - $printablesurveyoutput .="\t\t\t\t\t\n"; - $printablesurveyoutput .="\t\t\t\t\n"; - - $pdfoutput[$j]=array($mearow['answer']," o ".$clang->gT("Yes")," o ".$clang->gT("Uncertain")," o ".$clang->gT("No")); - $j++; - } - $printablesurveyoutput .="\t\t\t
    {$mearow['answer']}\n"; - $printablesurveyoutput .="\t\t\t\t\t\t".$clang->gT("Yes")." \n"; - $printablesurveyoutput .="\t\t\t\t\t\t".$clang->gT("Uncertain")." \n"; - $printablesurveyoutput .="\t\t\t\t\t\t".$clang->gT("No")." \n"; - $printablesurveyoutput .="\t\t\t\t\t
    \n"; - if(isset($_POST['printableexport'])){$pdf->tableintopdf($pdfoutput);} - break; - case "E": //ARRAY (Increase/Same/Decrease) - $meaquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid={$deqrow['qid']} AND language='{$surveyprintlang}' ORDER BY sortorder, answer"; - $mearesult = db_execute_assoc($meaquery); - $printablesurveyoutput .="\t\t\t".$clang->gT("Please choose the appropriate response for each item:")."
    \n"; - $printablesurveyoutput .="\t\t\t\n"; - if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Please choose the appropriate response for each item:"),"U");} - $pdfoutput = array(); - $j=0; - while ($mearow = $mearesult->FetchRow()) - { - $printablesurveyoutput .="\t\t\t\t\n"; - $printablesurveyoutput .="\t\t\t\t\t\n"; - $printablesurveyoutput .="\t\t\t\t\t\n"; - $printablesurveyoutput .="\t\t\t\t\n"; - $pdfoutput[$j]=array($mearow['answer'].":"," o ".$clang->gT("Increase")," o ".$clang->gT("Same")," o ".$clang->gT("Decrease")); - $j++; - } - $printablesurveyoutput .="\t\t\t
    {$mearow['answer']}\n"; - $printablesurveyoutput .="\t\t\t\t\t\t".$clang->gT("Increase")." \n"; - $printablesurveyoutput .="\t\t\t\t\t\t".$clang->gT("Same")." \n"; - $printablesurveyoutput .="\t\t\t\t\t\t".$clang->gT("Decrease")." \n"; - $printablesurveyoutput .="\t\t\t\t\t
    \n"; - if(isset($_POST['printableexport'])){$pdf->tableintopdf($pdfoutput);} - break; - case "F": //ARRAY (Flexible Labels) - //$headstyle="style='border-left-style: solid; border-left-width: 1px; border-left-color: #AAAAAA'"; - $headstyle="style='padding-left: 20px; padding-right: 7px'"; - $meaquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid={$deqrow['qid']} AND language='{$surveyprintlang}' ORDER BY sortorder, answer"; - $mearesult = db_execute_assoc($meaquery); - $printablesurveyoutput .="\t\t\t".$clang->gT("Please choose the appropriate response for each item:")."
    \n"; - $printablesurveyoutput .="\t\t\t\n"; - $fquery = "SELECT * FROM ".db_table_name("labels")." WHERE lid='{$deqrow['lid']}' AND language='{$surveyprintlang}' ORDER BY sortorder, code"; - $fresult = db_execute_assoc($fquery); - $fcount = $fresult->RecordCount(); - $fwidth = "120"; - $i=1; - $pdfoutput = array(); - $pdfoutput[0][0]=''; - if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Please choose the appropriate response for each item:"),"U");} - while ($frow = $fresult->FetchRow()) - { - $printablesurveyoutput .="\t\t\t\t\t\t\n"; - $pdfoutput[0][$i] = $frow['title']; - $i++; - } - $printablesurveyoutput .="\t\t\t\t\t\t\n"; - $counter = 1; - while ($mearow = $mearesult->FetchRow()) - { - $printablesurveyoutput .="\t\t\t\t\n"; - $answertext=$mearow['answer']; - if (strpos($answertext,'|')) {$answertext=substr($answertext,0, strpos($answertext,'|'));} - $printablesurveyoutput .="\t\t\t\t\t\n"; - //$printablesurveyoutput .="\t\t\t\t\t\n"; - $pdfoutput[$counter][$i] = "o"; - - } - $counter++; - - $answertext=$mearow['answer']; - if (strpos($answertext,'|')) - { - $answertext=substr($answertext,strpos($answertext,'|')+1); - $printablesurveyoutput .= "\t\t\t\t\n"; - - } - $printablesurveyoutput .="\t\t\t\t\n"; - } - $printablesurveyoutput .="\t\t\t
    {$frow['title']}
    $answertext"; - $pdfoutput[$counter][0]=$answertext; - for ($i=1; $i<=$fcount; $i++) - { - - $printablesurveyoutput .="\t\t\t\t\t 1) {$printablesurveyoutput .=" $headstyle";} - $printablesurveyoutput .=">\n"; - $printablesurveyoutput .="\t\t\t\t\t\t\n"; - $printablesurveyoutput .="\t\t\t\t\t$answertext
    \n"; - if(isset($_POST['printableexport'])){$pdf->tableintopdf($pdfoutput);} - break; - case "1": //ARRAY (Flexible Labels) multi scale - $qidattributes=getQuestionAttributes($deqrow['qid']); - if ($dsheaderA=arraySearchByKey("dualscale_headerA", $qidattributes, "attribute", 1)) - { - $leftheader= $dsheaderA['value']; - } - else - { - $leftheader =''; - } - if ($dsheaderB=arraySearchByKey("dualscale_headerB", $qidattributes, "attribute", 1)) - { - $rightheader= $dsheaderB['value']; - } - else - { - $rightheader =''; - } - - //$headstyle="style='border-left-style: solid; border-left-width: 1px; border-left-color: #AAAAAA'"; - $headstyle="style='padding-left: 20px; padding-right: 7px'"; - $meaquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid={$deqrow['qid']} AND language='{$surveyprintlang}' ORDER BY sortorder, answer"; - $mearesult = db_execute_assoc($meaquery); - $printablesurveyoutput .="\t\t\t".$clang->gT("Please choose the appropriate response for each item:")."
    \n"; - if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Please choose the appropriate response for each item:"),"U");} - $printablesurveyoutput .="\t\t\t"; - - $fquery = "SELECT * FROM ".db_table_name("labels")." WHERE lid='{$deqrow['lid']}' AND language='{$surveyprintlang}' ORDER BY sortorder, code"; - $fresult = db_execute_assoc($fquery); - $fcount = $fresult->RecordCount(); - $fwidth = "120"; - $l1=0; - $printablesurveyoutput2 = ''; - $myheader2 = ''; - $pdfoutput = array(); - $pdfoutput[0][0]=''; - while ($frow = $fresult->FetchRow()) - { - $printablesurveyoutput2 .="\t\t\t\t\t\t\n"; - $myheader2 .= ""; - $pdfoutput[0][$ll+1]=$frow['title']; - $l1++; - } - // second scale - $printablesurveyoutput2 .="\t\t\t\t\t\t\n"; - $fquery1 = "SELECT * FROM ".db_table_name("labels")." WHERE lid='{$deqrow['lid1']}' AND language='{$surveyprintlang}' ORDER BY sortorder, code"; - $fresult1 = db_execute_assoc($fquery1); - $fcount1 = $fresult1->RecordCount(); - $fwidth = "120"; - $l2=0; - while ($frow1 = $fresult1->FetchRow()) - { - $printablesurveyoutput2 .="\t\t\t\t\t\t\n"; - $pdfoutput[1][$l2]=$frow['title']; - $l2++; - } - // build header if needed - if ($leftheader != '' || $rightheader !='') - { - $myheader = "\t\t\t\t\t"; - $myheader .= "\t\t\t\t\t\n"; - - if ($rightheader !='') - { - // $myheader .= "\t\t\t\t\t" .$myheader2; - $myheader .= "\t\t\t\t\t"; - $myheader .= "\t\t\t\t\t\n"; - } - - $myheader .= "\t\t\t\t\n"; - } - else - { - $myheader = ''; - } - $printablesurveyoutput .= $myheader; - $printablesurveyoutput .= $printablesurveyoutput2; - $printablesurveyoutput .="\t\t\t\t\t\t\n"; - while ($mearow = $mearesult->FetchRow()) - { - $printablesurveyoutput .="\t\t\t\t\n"; - $answertext=$mearow['answer']; - if (strpos($answertext,'|')) {$answertext=substr($answertext,0, strpos($answertext,'|'));} - $printablesurveyoutput .="\t\t\t\t\t\n"; - for ($i=1; $i<=$fcount; $i++) - { - $printablesurveyoutput .="\t\t\t\t\t\n"; - } - $printablesurveyoutput .="\t\t\t\t\t\t\n"; - for ($i=1; $i<=$fcount1; $i++) - { - $printablesurveyoutput .="\t\t\t\t\t\n"; - } - - $answertext=$mearow['answer']; - if (strpos($answertext,'|')) - { - $answertext=substr($answertext,strpos($answertext,'|')+1); - $printablesurveyoutput .= "\t\t\t\t\n"; - } - $printablesurveyoutput .="\t\t\t\t\n"; - } - $printablesurveyoutput .="\t\t\t
    {$frow['title']}{$frow1['title']}$leftheader$rightheader
    $answertext 1) {$printablesurveyoutput .=" $headstyle";} - $printablesurveyoutput .=">\n"; - $printablesurveyoutput .="\t\t\t\t\t\t\n"; - $printablesurveyoutput .="\t\t\t\t\t 1) {$printablesurveyoutput .=" $headstyle";} - $printablesurveyoutput .=">\n"; - $printablesurveyoutput .="\t\t\t\t\t\t\n"; - $printablesurveyoutput .="\t\t\t\t\t$answertext
    \n"; - if(isset($_POST['printableexport'])){$pdf->tableintopdf($pdfoutput);} - break; - case "H": //ARRAY (Flexible Labels) by Column - //$headstyle="style='border-left-style: solid; border-left-width: 1px; border-left-color: #AAAAAA'"; - $headstyle="style='padding-left: 20px; padding-right: 7px'"; - $fquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid={$deqrow['qid']} AND language='{$surveyprintlang}' ORDER BY sortorder, answer"; - $fresult = db_execute_assoc($fquery); - $printablesurveyoutput .="\t\t\t".$clang->gT("Please choose the appropriate response for each item:")."
    \n"; - if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Please choose the appropriate response for each item:"),"U");} - $printablesurveyoutput .="\t\t\t\n"; - $meaquery = "SELECT * FROM ".db_table_name("labels")." WHERE lid='{$deqrow['lid']}' AND language='{$surveyprintlang}' ORDER BY sortorder, code"; - $mearesult = db_execute_assoc($meaquery); - $fcount = $fresult->RecordCount(); - $fwidth = "120"; - $i=0; - $pdfoutput = array(); - $pdfoutput[0][0]=''; - while ($frow = $fresult->FetchRow()) - { - $printablesurveyoutput .="\t\t\t\t\t\n"; - $i++; - $pdfoutput[0][$i]=$frow['answer']; - } - $printablesurveyoutput .="\t\t\t\t\t\t\n"; - $a=1; - while ($mearow = $mearesult->FetchRow()) - { - $printablesurveyoutput .="\t\t\t\t\n"; - $printablesurveyoutput .="\t\t\t\t\t\t\n"; - //$printablesurveyoutput .="\t\t\t\t\t\n"; - $pdfoutput[$a][$i]="o"; - } - //$printablesurveyoutput .="\t\t\t\t\t
    {$frow['answer']}
    {$mearow['title']}"; - $pdfoutput[$a][0]=$mearow['title']; - for ($i=1; $i<=$fcount; $i++) - { - - $printablesurveyoutput .="\t\t\t\t\t 1) {$printablesurveyoutput .=" $headstyle";} - $printablesurveyoutput .=">\n"; - $printablesurveyoutput .="\t\t\t\t\t\t\n"; - $printablesurveyoutput .="\t\t\t\t\t
    \n"; - if(isset($_POST['printableexport'])){$pdf->tableintopdf($pdfoutput);} - break; - } - $printablesurveyoutput .="\t\t

    \n"; -$printablesurveyoutput .="\t\t\t\n"; -$printablesurveyoutput .="\t\t\t\t\n"; -$printablesurveyoutput .="\t\t\t\t\t\n"; -$printablesurveyoutput .="\t\t\t\t\n"; -$printablesurveyoutput .="\t\t\t
    \n"; -$printablesurveyoutput .="\t\t\t\t\t\t".$clang->gT("Submit Your Survey.")."
    \n"; -$printablesurveyoutput .="\t\t\t\t\t\t".$clang->gT("Thank you for completing this survey."); -if(isset($_POST['printableexport'])){$pdf->titleintopdf($clang->gT("Submit Your Survey."),$clang->gT("Thank you for completing this survey."));} -if(!empty($surveyfaxto)) //If no fax number exists, don't display faxing information! -{ - $printablesurveyoutput .= $clang->gT("Please fax your completed survey to:")." $surveyfaxto"; - if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Please fax your completed survey to:")."$surveyfaxto",'B');} -} - -if ($surveyuseexpiry=="Y") -{ - $printablesurveyoutput .=$clang->gT("Please submit by")." $surveyexpirydate"; - if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Please submit by")." $surveyexpirydate");} -} -$printablesurveyoutput .=".\n"; -$printablesurveyoutput .="\t\t\t\t\t
    \n"; -$printablesurveyoutput .="\t\t
    \n"; -$printablesurveyoutput .="\n"; -if(isset($_POST['printableexport'])) -{ - $pdf->write_out($clang->gT($surveyname)." ".$surveyid.".pdf"); -} -echo $printablesurveyoutput ; -exit; -?> + 0) + { + return ''; + }; +}; +$surveyid = $_GET['sid']; + +// PRESENT SURVEY DATAENTRY SCREEN +if(isset($_POST['printableexport'])) +{ + $pdf = new PDF ($pdforientation,'mm','A4'); + $pdf->SetFont($pdfdefaultfont,'',$pdffontsize); + $pdf->AddPage(); +} +// Set the language of the survey, either from GET parameter of session var +if (isset($_GET['lang'])) +{ + $_GET['lang'] = preg_replace("/[^a-zA-Z0-9-]/", "", $_GET['lang']); + if ($_GET['lang']) $surveyprintlang = $_GET['lang']; +} else +{ + $surveyprintlang=GetbaseLanguageFromSurveyid($surveyid); +} + +// Setting the selected language for printout +$clang = new limesurvey_lang($surveyprintlang); + +$desquery = "SELECT * FROM ".db_table_name('surveys')." inner join ".db_table_name('surveys_languagesettings')." on (surveyls_survey_id=sid) WHERE sid=$surveyid and surveyls_language=".$connect->qstr($surveyprintlang); //Getting data for this survey + +$desresult = db_execute_assoc($desquery); +while ($desrow = $desresult->FetchRow()) +{ + $template = $desrow['template']; + $welcome = $desrow['surveyls_welcometext']; + $surveyname = $desrow['surveyls_title']; + $surveydesc = $desrow['surveyls_description']; + $surveyactive = $desrow['active']; + $surveytable = db_table_name("survey_".$desrow['sid']); + $surveyexpirydate = $desrow['expires']; + $surveystartdate = $desrow['startdate']; + $surveyfaxto = $desrow['faxto']; +} +if(isset($_POST['printableexport'])){$pdf->titleintopdf($surveyname,$surveydesc);} + + +//define('PRINT_TEMPLATE' , '/templates/print/' , true); +if(is_file($templaterootdir.'/'.$template.'/print_survey.pstpl')) +{ + define('PRINT_TEMPLATE_DIR' , $templaterootdir.'/'.$template.'/' , true); + define('PRINT_TEMPLATE_URL' , $rooturl.'/templates/'.$template.'/' , true); +} +else +{ + define('PRINT_TEMPLATE_DIR' , $templaterootdir.'/default/' , true); + define('PRINT_TEMPLATE_URL' , $rooturl.'/templates/default/' , true); +} + + + +$fieldmap=createFieldMap($surveyid); + +$degquery = "SELECT * FROM ".db_table_name("groups")." WHERE sid='{$surveyid}' AND language='{$surveyprintlang}' ORDER BY ".db_table_name("groups").".group_order"; +$degresult = db_execute_assoc($degquery); + +if (!isset($surveyfaxto) || !$surveyfaxto and isset($surveyfaxnumber)) +{ + $surveyfaxto=$surveyfaxnumber; //Use system fax number if none is set in survey. +} + +$pdf_form=''; +if(isset($usepdfexport) && $usepdfexport == 1 && !in_array($surveyprintlang,$notsupportlanguages)) +{ + $pdf_form = ' +
    + + + +
    + '; +} + +$headelements = getPrintableHeader(); + +$survey_output = array( + 'SITENAME' => $sitename + ,'SURVEYNAME' => $surveyname + ,'SURVEYDESCRIPTION' => $surveydesc + ,'WELCOME' => $welcome + ,'THEREAREXQUESTIONS' => 0 + ,'SUBMIT_TEXT' => $clang->gT("Submit Your Survey.") + ,'SUBMIT_BY' => $surveyexpirydate + ,'THANKS' => $clang->gT("Thank you for completing this survey.") + ,'PDF_FORM' => $pdf_form + ,'HEADELEMENTS' => $headelements + ,'TEMPLATEURL' => PRINT_TEMPLATE_URL + ,'FAXTO' => $surveyfaxto + ,'PRIVACY' => '' + ,'GROUPS' => '' + ); + + + +$survey_output['FAX_TO'] =''; +if(!empty($surveyfaxto) && $surveyfaxto != '000-00000000') //If no fax number exists, don't display faxing information! +{ + $survey_output['FAX_TO'] = $clang->gT("Please fax your completed survey to:")." $surveyfaxto"; +} + + +if ($surveystartdate!='') +{ + $survey_output['SUBMIT_BY'] = sprintf($clang->gT("Please submit by %s"), $surveyexpirydate); +} + +/** + * Output arrays: + * $survey_output = final vaiables for whole survey + * $survey_output['SITENAME'] = + * $survey_output['SURVEYNAME'] = + * $survey_output['SURVEY_DESCRIPTION'] = + * $survey_output['WELCOME'] = + * $survey_output['THEREAREXQUESTIONS'] = + * $survey_output['PDF_FORM'] = + * $survey_output['HEADELEMENTS'] = + * $survey_output['TEMPLATEURL'] = + * $survey_output['SUBMIT_TEXT'] = + * $survey_output['SUBMIT_BY'] = + * $survey_output['THANKS'] = + * $survey_output['FAX_TO'] = + * $survey_output['SURVEY'] = contains an array of all the group arrays + * + * $groups[] = an array of all the groups output + * $group['GROUPNAME'] = + * $group['GROUPDESCRIPTION'] = + * $group['QUESTIONS'] = templated formatted content if $question is appended to this at the end of processing each question. + * $group['ODD_EVEN'] = class to differentiate alternate groups + * $group['SCENARIO'] = + * + * $questions[] = contains an array of all the questions within a group + * $question['QUESTION_CODE'] = content of the question code field + * $question['QUESTION_TEXT'] = content of the question field + * $question['QUESTION_SCENARIO'] = if there are conditions on a question, list the conditions. + * $question['QUESTION_MANDATORY'] = translated 'mandatory' identifier + * $question['QUESTION_CLASS'] = classes to be added to wrapping question div + * $question['QUESTION_TYPE_HELP'] = instructions on how to complete the question + * $question['QUESTION_MAN_MESSAGE'] = (not sure if this is used) mandatory error + * $question['QUESTION_VALID_MESSAGE'] = (not sure if this is used) validation error + * $question['ANSWER'] = contains formatted HTML answer + * $question['QUESTIONHELP'] = content of the question help field. + * + */ + +function populate_template( $template , $input , $line = '') +{ + global $rootdir, $debug; +/** + * A poor mans templating system. + * + * $template template filename (path is privided by config.php) + * $input a key => value array containg all the stuff to be put into the template + * $line for debugging purposes only. + * + * Returns a formatted string containing template with + * keywords replaced by variables. + * + * How: + */ + $full_path = PRINT_TEMPLATE_DIR.'print_'.$template.'.pstpl'; + $full_constant = 'TEMPLATE'.$template.'.pstpl'; + if(!defined($full_constant)) + { + if(is_file($full_path)) + { + define( $full_constant , file_get_contents($full_path)); + + $template_content = constant($full_constant); + $test_empty = trim($template_content); + if(empty($test_empty)) + { + return ""; + }; + } + else + { + define($full_constant , ''); + return ""; + }; + } + else + { + $template_content = constant($full_constant); + $test_empty = trim($template_content); + if(empty($test_empty)) + { + return ""; + }; + }; + + if(is_array($input)) + { + foreach($input as $key => $value) + { + $find[] = '{'.$key.'}'; + $replace[] = $value; + }; + return str_replace( $find , $replace , $template_content ); + } + else + { + if($debug > 0) + { + if(!empty($line)) + { + $line = 'LINE '.$line.': '; + } + return ''."\n"; + }; + }; +}; + + +function input_type_image( $type , $title = '' , $x = 40 , $y = 1 , $line = '' ) +{ + global $rooturl, $rootdir; + + if($type == 'other' or $type == 'othercomment') + { + $x = 1; + }; + $tail = substr($x , -1 , 1); + switch($tail) + { + case '%': + case 'm': + case 'x': $x_ = $x; + break; + default: $x_ = $x / 2; + }; + + if($y < 2) + { + $y_ = 2; + } + else + { + $y_ = $y * 2; + }; + + if(!empty($title)) + { + $div_title = ' title="'.$title.'"'; + } + else + { + $div_title = ''; + } + switch($type) + { + case 'textarea': + case 'text': $style = ' style="width:'.$x_.'em; height:'.$y_.'em;"'; + break; + default: $style = ''; + }; + + switch($type) + { + case 'radio': + case 'checkbox':if(!defined('IMAGE_'.$type.'_SIZE')) + { + $image_dimensions = getimagesize(PRINT_TEMPLATE_DIR.'print_img_'.$type.'.png'); + // define('IMAGE_'.$type.'_SIZE' , ' width="'.$image_dimensions[0].'" height="'.$image_dimensions[1].'"'); + define('IMAGE_'.$type.'_SIZE' , ' width="14" height="14"'); + }; + $output = ''.$title.''; + break; + + case 'rank': + case 'other': + case 'othercomment': + case 'text': + case 'textarea':$output = '
    {NOTEMPTY}
    '; + break; + + default: $output = ''; + }; + return $output; +}; + +function star_replace($input) +{ + return preg_replace( + '/\*(.*)\*/U' + ,'\1' + ,$input + ); +} + +$total_questions = 0; +$mapquestionsNumbers=Array(); + +// ========================================================= +// START doin the business: +$pdfoutput = ''; +while ($degrow = $degresult->FetchRow()) +{ +// --------------------------------------------------- +// START doing groups + + $deqquery = "SELECT * FROM ".db_table_name("questions")." WHERE sid=$surveyid AND gid={$degrow['gid']} AND language='{$surveyprintlang}' AND TYPE<>'I' ORDER BY question_order"; + $deqresult = db_execute_assoc($deqquery); + $deqrows = array(); //Create an empty array in case FetchRow does not return any rows + while ($deqrow = $deqresult->FetchRow()) {$deqrows[] = $deqrow;} // Get table output into array + + // Perform a case insensitive natural sort on group name then question title of a multidimensional array + usort($deqrows, 'CompareGroupThenTitle'); + + if ($degrow['description']) + { + $group_desc = $degrow['description']; + } + else + { + $group_desc = ''; + }; + + $group = array( + 'GROUPNAME' => $degrow['group_name'] + ,'GROUPDESCRIPTION' => $group_desc + ,'QUESTIONS' => '' // templated formatted content if $question is appended to this at the end of processing each question. + ); + + + if(isset($_POST['printableexport'])){$pdf->titleintopdf($degrow['group_name'],$degrow['description']);} + + $gid = $degrow['gid']; + //Alternate bgcolor for different groups + if (!isset($group['ODD_EVEN']) || $group['ODD_EVEN'] == ' g-row-even') + { + $group['ODD_EVEN'] = ' g-row-odd';} + else + { + $group['ODD_EVEN'] = ' g-row-even'; + }; + + foreach ($deqrows as $deqrow) + { +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +// START doing questions + + //GET ANY CONDITIONS THAT APPLY TO THIS QUESTION + + $printablesurveyoutput = ''; + $explanation = ''; //reset conditions explanation + $s=0; + $scenarioquery="SELECT DISTINCT ".db_table_name("conditions").".scenario FROM ".db_table_name("conditions")." WHERE ".db_table_name("conditions").".qid={$deqrow['qid']} ORDER BY scenario"; + $scenarioresult=db_execute_assoc($scenarioquery); + + while ($scenariorow=$scenarioresult->FetchRow()) + { + if($s == 0 && $scenarioresult->RecordCount() > 1) + { + $explanation .= '

    '.try_debug(__LINE__)." -------- Scenario {$scenariorow['scenario']} --------

    \n\n"; + } + if($s > 0) + { + $explanation .= '

    '.try_debug(__LINE__).' -------- '.$clang->gT("or")." Scenario {$scenariorow['scenario']} --------

    \n\n"; + } + + $x=0; + $distinctquery="SELECT cqid, method + FROM ".db_table_name("conditions")." + WHERE ".db_table_name("conditions").".qid={$deqrow['qid']} + AND ".db_table_name("conditions").".scenario={$scenariorow['scenario']} + group by cqid, method + ORDER BY cqid"; + $distinctresult=db_execute_assoc($distinctquery); + while ($distinctrow=$distinctresult->FetchRow()) + { + $subquery='select title, question from '.db_table_name("questions")." where qid={$distinctrow['cqid']} AND language='{$surveyprintlang}'"; + $subresult=$connect->GetRow($subquery); + + if($x > 0) + { + $explanation .= ' '.$clang->gT('and').' '; + } + if(trim($distinctrow['method'])=='') + { + $distinctrow['method']='=='; + } + + if($distinctrow['method']=='==') + { + $explanation .= $clang->gT("Answer was")." "; + } + elseif($distinctrow['method']=='!=') + { + $explanation .= $clang->gT("Answer was NOT")." "; + } + elseif($distinctrow['method']=='<') + { + $explanation .= $clang->gT("Answer was less than")." "; + } + elseif($distinctrow['method']=='<=') + { + $explanation .= $clang->gT("Answer was less than or equal to")." "; + } + elseif($distinctrow['method']=='>=') + { + $explanation .= $clang->gT("Answer was greater than or equal to")." "; + } + elseif($distinctrow['method']=='>') + { + $explanation .= $clang->gT("Answer was greater than")." "; + } + elseif($distinctrow['method']=='RX') + { + $explanation .= $clang->gT("Answer matched (regexp)")." "; + } + else + { + $explanation .= $clang->gT("Answer was")." "; + } + + $conquery="SELECT cid, cqid, ".db_table_name("questions").".title,\n" + ."".db_table_name("questions").".question, value, ".db_table_name("questions").".type,\n" + ."".db_table_name("questions").".lid, ".db_table_name("questions").".lid1, cfieldname\n" + ."FROM ".db_table_name("conditions").", ".db_table_name("questions")."\n" + ."WHERE ".db_table_name("conditions").".cqid=".db_table_name("questions").".qid\n" + ."AND ".db_table_name("conditions").".cqid={$distinctrow['cqid']}\n" + ."AND ".db_table_name("conditions").".qid={$deqrow['qid']} \n" + ."AND ".db_table_name("conditions").".scenario={$scenariorow['scenario']} \n" + ."AND language='{$surveyprintlang}'"; + $conresult=db_execute_assoc($conquery) or safe_die("$conquery
    ".htmlspecialchars($connect->ErrorMsg())); + $conditions=array(); + while ($conrow=$conresult->FetchRow()) + { + + $postans=""; + $value=$conrow['value']; + switch($conrow['type']) + { + case "Y": + switch ($conrow['value']) + { + case "Y": $conditions[]=$clang->gT("Yes"); break; + case "N": $conditions[]=$clang->gT("No"); break; + } + break; + case "G": + switch($conrow['value']) + { + case "M": $conditions[]=$clang->gT("Male"); break; + case "F": $conditions[]=$clang->gT("Female"); break; + } // switch + break; + case "A": + case "B": + case ":": + case ";": + $conditions[]=$conrow['value']; + break; + case "C": + switch($conrow['value']) + { + case "Y": $conditions[]=$clang->gT("Yes"); break; + case "U": $conditions[]=$clang->gT("Uncertain"); break; + case "N": $conditions[]=$clang->gT("No"); break; + } // switch + break; + case "E": + switch($conrow['value']) + { + case "I": $conditions[]=$clang->gT("Increase"); break; + case "D": $conditions[]=$clang->gT("Decrease"); break; + case "S": $conditions[]=$clang->gT("Same"); break; + } + case "1": + $labelIndex=preg_match("/^[^#]+#([01]{1})$/",$conrow['cfieldname']); + if ($labelIndex == 0) + { // TIBO + $fquery = "SELECT * FROM ".db_table_name("labels")."\n" + . "WHERE lid='{$conrow['lid']}'\n" + . "AND code='{$conrow['value']}' AND language='{$surveyprintlang}'"; + $fresult=db_execute_assoc($fquery) or safe_die("$fquery
    ".htmlspecialchars($connect->ErrorMsg())); + while($frow=$fresult->FetchRow()) + { + $postans=$frow['title']; + $conditions[]=$frow['title']; + } // while + } + elseif ($labelIndex == 1) + { + $fquery = "SELECT * FROM ".db_table_name("labels")."\n" + . "WHERE lid='{$conrow['lid1']}'\n" + . "AND code='{$conrow['value']}' AND language='{$surveyprintlang}'"; + $fresult=db_execute_assoc($fquery) or safe_die("$fquery
    ".htmlspecialchars($connect->ErrorMsg())); + while($frow=$fresult->FetchRow()) + { + $postans=$frow['title']; + $conditions[]=$frow['title']; + } // while + } + break; + case "L": + case "!": + case "O": + case "M": + case "P": + case "R": + $ansquery="SELECT answer FROM ".db_table_name("answers")." WHERE qid='{$conrow['cqid']}' AND code='{$conrow['value']}' AND language='{$surveyprintlang}'"; + $ansresult=db_execute_assoc($ansquery); + while ($ansrow=$ansresult->FetchRow()) + { + $conditions[]=$ansrow['answer']; + } + $conditions = array_unique($conditions); + break; + case "F": + case "H": + case "W": + default: + $value=substr($conrow['cfieldname'], strpos($conrow['cfieldname'], "X".$conrow['cqid'])+strlen("X".$conrow['cqid']), strlen($conrow['cfieldname'])); + $fquery = "SELECT * FROM ".db_table_name("labels")."\n" + . "WHERE lid='{$conrow['lid']}'\n" + . "AND code='{$conrow['value']}' AND language='{$surveyprintlang}'"; + $fresult=db_execute_assoc($fquery) or safe_die("$fquery
    ".htmlspecialchars($connect->ErrorMsg())); + while($frow=$fresult->FetchRow()) + { + $postans=$frow['title']; + $conditions[]=$frow['title']; + } // while + break; + } // switch + + // Now let's complete the answer text with the answer_section + $answer_section=""; + switch($conrow['type']) + { + case "A": + case "B": + case "C": + case "E": + case "F": + case "H": + case "K": + $thiscquestion=arraySearchByKey($conrow['cfieldname'], $fieldmap, "fieldname"); + $ansquery="SELECT answer FROM ".db_table_name("answers")." WHERE qid='{$conrow['cqid']}' AND code='{$thiscquestion[0]['aid']}' AND language='{$surveyprintlang}'"; + //$ansquery="SELECT question FROM ".db_table_name("questions")." WHERE qid='{$conrow['cqid']}' AND language='{$surveyprintlang}'"; + $ansresult=db_execute_assoc($ansquery); + while ($ansrow=$ansresult->FetchRow()) + { + $answer_section=" (".$ansrow['answer'].")"; + } + break; + + case "1": // dual: (Label 1), (Label 2) + $labelIndex=preg_match("/^[^#]+#([01]{1})$/",$conrow['cfieldname']); + $thiscquestion=arraySearchByKey($conrow['cfieldname'], $fieldmap, "fieldname"); + $ansquery="SELECT answer FROM ".db_table_name("answers")." WHERE qid='{$conrow['cqid']}' AND code='{$thiscquestion[0]['aid']}' AND language='{$surveyprintlang}'"; + //$ansquery="SELECT question FROM ".db_table_name("questions")." WHERE qid='{$conrow['cqid']}' AND language='{$surveyprintlang}'"; + $ansresult=db_execute_assoc($ansquery); + + if ($labelIndex == 0) + { + while ($ansrow=$ansresult->FetchRow()) + { + $answer_section=" (".$ansrow['answer']." ".$clang->gT("Label")."1)"; + } + } + elseif ($labelIndex == 1) + { + while ($ansrow=$ansresult->FetchRow()) + { + $answer_section=" (".$ansrow['answer']." ".$clang->gT("Label")."2)"; + } + } + break; + case ":": + case ";": //multi flexi: ( answer [label] ) + $thiscquestion=arraySearchByKey($conrow['cfieldname'], $fieldmap, "fieldname"); + $ansquery="SELECT answer FROM ".db_table_name("answers")." WHERE qid='{$conrow['cqid']}' AND code='{$thiscquestion[0]['aid']}' AND language='{$surveyprintlang}'"; + $ansresult=db_execute_assoc($ansquery); + while ($ansrow=$ansresult->FetchRow()) + { + $fquery = "SELECT * FROM ".db_table_name("labels")."\n" + . "WHERE lid='{$conrow['lid']}'\n" + . "AND code='{$conrow['value']}' AND language='{$surveyprintlang}'"; + $fresult=db_execute_assoc($fquery) or safe_die("$fquery
    ".htmlspecialchars($connect->ErrorMsg())); + while($frow=$fresult->FetchRow()) + { + //$conditions[]=$frow['title']; + $answer_section=" (".$ansrow['answer']."[".$frow['title']."])"; + } // while + } + break; + case "R": // (Rank 1), (Rank 2)... TIBO + $thiscquestion=arraySearchByKey($conrow['cfieldname'], $fieldmap, "fieldname"); + $rankid=$thiscquestion[0]['aid']; + $answer_section=" (".$clang->gT("RANK")." $rankid)"; + break; + default: // nothing to add + break; + } + } + + if (count($conditions) > 1) + { + $explanation .= "'".implode("' ".$clang->gT("or")." '", $conditions)."'"; + } + elseif (count($conditions) == 1) + { + $explanation .= "'".$conditions[0]."'"; + } + unset($conditions); + // Following line commented out because answer_section was lost, but is required for some question types + //$explanation .= " ".$clang->gT("to question")." '".$mapquestionsNumbers[$distinctrow['cqid']]."' $answer_section "; + $explanation .= " ".$clang->gT("at question")." '".$mapquestionsNumbers[$distinctrow['cqid']]." [".$subresult['title']."]' (".strip_tags($subresult['question'])."$answer_section)" ; + //$distinctrow + $x++; + } + $s++; + } + if ($explanation) + { + $explanation = "".$clang->gT('Only answer this question if the following conditions are met:')."" + ."
    ° ".$explanation;//"[".sprintf($clang->gT("Only answer this question %s"), $explanation)."]"; + } + else + { + $explanation = ''; + } + + ++$total_questions; + + $question = array( + 'QUESTION_NUMBER' => $total_questions // content of the question code field + ,'QUESTION_CODE' => $deqrow['title'] + ,'QUESTION_TEXT' => preg_replace('/(?:
    |<\/(?:p|h[1-6])>)$/is' , '' , $deqrow['question']) // content of the question field + ,'QUESTION_SCENARIO' => $explanation // if there are conditions on a question, list the conditions. + ,'QUESTION_MANDATORY' => '' // translated 'mandatory' identifier + ,'QUESTION_CLASS' => question_class( $deqrow['type']) // classes to be added to wrapping question div + ,'QUESTION_TYPE_HELP' => '' // instructions on how to complete the question + ,'QUESTION_MAN_MESSAGE' => '' // (not sure if this is used) mandatory error + ,'QUESTION_VALID_MESSAGE' => '' // (not sure if this is used) validation error + ,'QUESTIONHELP' => '' // content of the question help field. + ,'ANSWER' => '' // contains formatted HTML answer + ); + //TIBO map question qid to their q number + $mapquestionsNumbers[$deqrow['qid']]=$total_questions; + //END OF GETTING CONDITIONS + + $qid = $deqrow['qid']; + $fieldname = "$surveyid"."X"."$gid"."X"."$qid"; + + if ($deqrow['mandatory'] == 'Y') + { + $question['QUESTION_MANDATORY'] = $clang->gT('*'); + $question['QUESTION_CLASS'] .= ' mandatory'; + $pdfoutput .= $clang->gT("*"); + } + + $pdfoutput =''; + + //DIFFERENT TYPES OF DATA FIELD HERE + + + if(isset($_POST['printableexport'])){$pdf->intopdf($deqrow['title']." ".$deqrow['question']);} + + if ($deqrow['help']) + { + $hh = $deqrow['help']; + $question['QUESTIONHELP'] = $hh; + + if(isset($_POST['printableexport'])){$pdf->helptextintopdf($hh);} + } + + $qidattributes=getQAttributes($deqrow['qid']); + + if (isset($qidattributes['page_break'])) + { + $question['QUESTION_CLASS'] .=' breakbefore '; + } + + switch($deqrow['type']) + { +// ================================================================== + case "5": //5 POINT CHOICE + $question['QUESTION_TYPE_HELP'] = $clang->gT('Please choose *only one* of the following:'); + if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Please choose *only one* of the following:"),"U");} + $pdfoutput =''; + $question['ANSWER'] .= "\n\t
      \n"; + for ($i=1; $i<=5; $i++) + { + $pdfoutput .=" o ".$i." "; +// $printablesurveyoutput .="\t\t\t$i \n"; + $question['ANSWER'] .="\t\t
    • \n\t\t\t".input_type_image('radio',$i)."\n\t\t\t$i\n\t\t
    • \n"; + } + if(isset($_POST['printableexport'])){$pdf->intopdf($pdfoutput);} + $question['ANSWER'] .="\t
    \n"; + + break; + +// ================================================================== + case "D": //DATE + $question['QUESTION_TYPE_HELP'] = $clang->gT('Please enter a date:'); + $question['ANSWER'] .= "\t".input_type_image('text',$question['QUESTION_TYPE_HELP'],30,1); + if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Please enter a date:")." ___________");} + + break; + +// ================================================================== + case "G": //GENDER + $question['QUESTION_TYPE_HELP'] = $clang->gT("Please choose *only one* of the following:"); + + $question['ANSWER'] .= "\n\t
      \n"; + $question['ANSWER'] .= "\t\t
    • \n\t\t\t".input_type_image('radio',$clang->gT("Female"))."\n\t\t\t".$clang->gT("Female")."\n\t\t
    • \n"; + $question['ANSWER'] .= "\t\t
    • \n\t\t\t".input_type_image('radio',$clang->gT("Male"))."\n\t\t\t".$clang->gT("Male")."\n\t\t
    • \n"; + $question['ANSWER'] .= "\t
    \n"; + + if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Please choose *only one* of the following:"));} + if(isset($_POST['printableexport'])){$pdf->intopdf(" o ".$clang->gT("Female")." | o ".$clang->gT("Male"));} + + break; + +// ================================================================== + case "W": //Flexible List + +// ================================================================== + case "Z": //LIST Flexible drop-down/radio-button list + if (isset($qidattributes["display_columns"])) + { + $dcols=$qidattributes['display_columns']; + } + else + { + $dcols=1; + } + $question['QUESTION_TYPE_HELP'] = "\n\t

    ".$clang->gT("Please choose *only one* of the following:")."

    \n"; + if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Please choose *only one* of the following:"),"U");} + $deaquery = "SELECT * FROM ".db_table_name("labels")." WHERE lid={$deqrow['lid']} AND language='{$surveyprintlang}' ORDER BY sortorder"; + $dearesult = db_execute_assoc($deaquery) or safe_die("ERROR: $deaquery
    \n".$connect->ErrorMsg()); + $deacount=$dearesult->RecordCount(); + if ($deqrow['other'] == "Y") + { + $deacount++; + } + $wrapper = setup_columns($dcols, $deacount); + + $question['ANSWER'] = $wrapper['whole-start']; + + $rowcounter = 0; + $colcounter = 1; + + while ($dearow = $dearesult->FetchRow()) + { + $question['ANSWER'] .= $wrapper['item-start'].input_type_image('radio' , $dearow['code']).' '.$dearow['title'].$wrapper['item-end']; + if(isset($_POST['printableexport'])){$pdf->intopdf(" o ".$dearow['title']);} + + ++$rowcounter; + if ($rowcounter == $wrapper['maxrows'] && $colcounter < $wrapper['cols']) + { + if($colcounter == $wrapper['cols'] - 1) + { + $question['ANSWER'] .= $wrapper['col-devide-last']; + } + else + { + $question['ANSWER'] .= $wrapper['col-devide']; + }; + $rowcounter = 0; + ++$colcounter; + }; + } + if ($deqrow['other'] == "Y") + { + $qAttrib = getQAttributes($deqrow['qid']); + if(!isset($qAttrib["other_replace_text"])) + {$qAttrib["other_replace_text"]="Other";} + + $question['ANSWER'] .= $wrapper['item-start-other'].input_type_image('radio',$clang->gT($qAttrib["other_replace_text"])).' '.$clang->gT($qAttrib["other_replace_text"])."\n\t\t\t".input_type_image('other','')."\n".$wrapper['item-end']; + if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT($qAttrib["other_replace_text"]).": ________");} + } + $question['ANSWER'] .= $wrapper['whole-end']; + //Let's break the presentation into columns. + break; + +// ================================================================== + case 'L': //LIST drop-down/radio-button list + +// ================================================================== + case '!': //List - dropdown + if (isset($qidattributes["display_columns"])) + { + $dcols=$qidattributes['display_columns']; + } + else + { + $dcols=0; + } + + if (isset($qidattributes["category_separator"])) + { + $optCategorySeparator = $qidattributes['category_separator']; + } + else + { + unset($optCategorySeparator); + } + + $question['QUESTION_TYPE_HELP'] = $clang->gT("Please choose *only one* of the following:"); + + if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Please choose *only one* of the following:"));} + $deaquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid={$deqrow['qid']} AND language='{$surveyprintlang}' ORDER BY sortorder, answer"; + $dearesult = db_execute_assoc($deaquery); + $deacount=$dearesult->RecordCount(); + if ($deqrow['other'] == "Y") {$deacount++;} + + $wrapper = setup_columns($dcols, $deacount); + + $question['ANSWER'] = $wrapper['whole-start']; + + $rowcounter = 0; + $colcounter = 1; + + while ($dearow = $dearesult->FetchRow()) + { + if (isset($optCategorySeparator)) + { + list ($category, $answer) = explode($optCategorySeparator,$dearow['answer']); + if ($category != '') + { + $dearow['answer'] = "($category) $answer"; + } + else + { + $dearow['answer'] = $answer; + } + } + + $question['ANSWER'] .= "\t".$wrapper['item-start']."\t\t".input_type_image('radio' , $dearow['answer'])."\n\t\t\t".$dearow['answer']."\n".$wrapper['item-end']; + if(isset($_POST['printableexport'])){$pdf->intopdf(" o ".$dearow['answer']);} + + ++$rowcounter; + if ($rowcounter == $wrapper['maxrows'] && $colcounter < $wrapper['cols']) + { + if($colcounter == $wrapper['cols'] - 1) + { + $question['ANSWER'] .= $wrapper['col-devide-last']; + } + else + { + $question['ANSWER'] .= $wrapper['col-devide']; + }; + $rowcounter = 0; + ++$colcounter; + } + } + if ($deqrow['other'] == 'Y') + { + $qAttrib = getQAttributes($deqrow['qid']); + if(!isset($qAttrib["other_replace_text"])) + {$qAttrib["other_replace_text"]="Other";} +// $printablesurveyoutput .="\t".$wrapper['item-start']."\t\t".input_type_image('radio' , $clang->gT("Other"))."\n\t\t\t".$clang->gT("Other")."\n\t\t\t\n".$wrapper['item-end']; + $question['ANSWER'] .= $wrapper['item-start-other'].input_type_image('radio',$clang->gT($qAttrib["other_replace_text"])).' '.$clang->gT($qAttrib["other_replace_text"])."\n\t\t\t".input_type_image('other')."\n".$wrapper['item-end']; + if(isset($_POST['printableexport'])){$pdf->intopdf(" o ".$clang->gT($qAttrib["other_replace_text"]).": ________");} + } + $question['ANSWER'] .= $wrapper['whole-end']; + //Let's break the presentation into columns. + break; + +// ================================================================== + case "O": //LIST WITH COMMENT + $question['QUESTION_TYPE_HELP'] = $clang->gT("Please choose *only one* of the following:"); + if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Please choose *only one* of the following:"),"U");} + $deaquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid={$deqrow['qid']} AND language='{$surveyprintlang}' ORDER BY sortorder, answer "; + $dearesult = db_execute_assoc($deaquery); + $question['ANSWER'] = "\t
      \n"; + while ($dearow = $dearesult->FetchRow()) + { + $question['ANSWER'] .= "\t\t
    • \n\t\t\t".input_type_image('radio',$dearow['answer'])."\n\t\t\t".$dearow['answer']."\n\t\t
    • \n"; + if(isset($_POST['printableexport'])){$pdf->intopdf($dearow['answer']);} + } + $question['ANSWER'] .= "\t
    \n"; + + $question['ANSWER'] .= "\t

    \n\t\t".$clang->gT("Make a comment on your choice here:")."\n"; + if(isset($_POST['printableexport'])){$pdf->intopdf("Make a comment on your choice here:");} + $question['ANSWER'] .= "\t\t".input_type_image('textarea',$clang->gT("Make a comment on your choice here:"),50,8)."\n\t

    \n"; + + for($i=0;$i<9;$i++) + { + if(isset($_POST['printableexport'])){$pdf->intopdf("____________________");} + } + break; + +// ================================================================== + case "R": //RANKING Type Question + $reaquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid={$deqrow['qid']} AND language='{$surveyprintlang}' ORDER BY sortorder, answer"; + $rearesult = db_execute_assoc($reaquery) or safe_die ("Couldn't get ranked answers
    ".$connect->ErrorMsg()); + $reacount = $rearesult->RecordCount(); + $question['QUESTION_TYPE_HELP'] = $clang->gT("Please number each box in order of preference from 1 to")." $reacount"; + if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Please number each box in order of preference from 1 to ").$reacount,"U");} + $question['ANSWER'] = "\n
      \n"; + while ($rearow = $rearesult->FetchRow()) + { + $question['ANSWER'] .="\t
    • \n\t".input_type_image('rank','',4,1)."\n\t\t".$rearow['answer']."\n\t
    • \n"; + if(isset($_POST['printableexport'])){$pdf->intopdf("__ ".$rearow['answer']);} + }; + $question['ANSWER'] .= "\n
    \n"; + break; + +// ================================================================== + case "M": //MULTIPLE OPTIONS (Quite tricky really!) + + if (isset($qidattributes["display_columns"])) + { + $dcols=$qidattributes['display_columns']; + } + else + { + $dcols=0; + } + if (!isset($qidattributes["max_answers"])) + { + $question['QUESTION_TYPE_HELP'] = $clang->gT("Please choose *all* that apply:"); + if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Please choose *all* that apply:"),"U");} + } + else + { + $maxansw=$qidattributes["max_answers"]; + $question['QUESTION_TYPE_HELP'] = $clang->gT('Please choose *at most* ').' '.$maxansw.' '.$clang->gT('answers:'); + if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Please choose *at most* ").$maxansw.$clang->gT("answers:"),"U");} + } + $meaquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid={$deqrow['qid']} AND language='{$surveyprintlang}' ORDER BY sortorder, answer"; + $mearesult = db_execute_assoc($meaquery); + $meacount = $mearesult->RecordCount(); + if ($deqrow['other'] == 'Y') {$meacount++;} + + $wrapper = setup_columns($dcols, $meacount); + $question['ANSWER'] = $wrapper['whole-start']; + + $rowcounter = 0; + $colcounter = 1; + + while ($mearow = $mearesult->FetchRow()) + { + $question['ANSWER'] .= $wrapper['item-start'].input_type_image('checkbox',$mearow['answer'])."\n\t\t".$mearow['answer'].$wrapper['item-end']; + if(isset($_POST['printableexport'])){$pdf->intopdf(" o ".$mearow['answer']);} +// $upto++; + + ++$rowcounter; + if ($rowcounter == $wrapper['maxrows'] && $colcounter < $wrapper['cols']) + { + if($colcounter == $wrapper['cols'] - 1) + { + $question['ANSWER'] .= $wrapper['col-devide-last']; + } + else + { + $question['ANSWER'] .= $wrapper['col-devide']; + }; + $rowcounter = 0; + ++$colcounter; + }; + } + if ($deqrow['other'] == "Y") + { + if(!isset($qidattributes["other_replace_text"])) + { + $qidattributes["other_replace_text"]="Other"; + } + $question['ANSWER'] .= $wrapper['item-start-other'].input_type_image('checkbox',$mearow['answer']).$clang->gT($qidattributes["other_replace_text"]).":\n\t\t".input_type_image('other').$wrapper['item-end']; + if(isset($_POST['printableexport'])){$pdf->intopdf(" o ".$clang->gT($qidattributes["other_replace_text"]).": ________");} + } + $question['ANSWER'] .= $wrapper['whole-end']; +// }; + break; + +/* +// ================================================================== + case "I": //Language Switch in a printable survey does not make sense + $printablesurveyoutput .="\t\t\t".$clang->gT("Please choose *only one* of the following:")."
    \n"; + $answerlangs = GetAdditionalLanguagesFromSurveyID($surveyid); + $answerlangs [] = GetBaseLanguageFromSurveyID($surveyid); + + foreach ($answerlangs as $ansrow) + { + $printablesurveyoutput .="\t\t\t".getLanguageNameFromCode($ansrow, true)."
    \n"; + } + break; +*/ + + +// ================================================================== + case "P": //MULTIPLE OPTIONS WITH COMMENTS + if (!isset($qidattributes['max_answers'])) + { + $question['QUESTION_TYPE_HELP'] = $clang->gT("Please choose all that apply and provide a comment:"); + if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Please choose all that apply and provide a comment:"),"U");} + } + else + { + $maxansw=$qidattributes['max_answers']; + $question['QUESTION_TYPE_HELP'] = $clang->gT("Please choose *at most* ").''.$maxansw.' '.$clang->gT("answers and provide a comment:"); + if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Please choose *at most* ").$maxansw.$clang->gT("answers and provide a comment:"),"U");} + } + $meaquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid={$deqrow['qid']} AND language='{$surveyprintlang}' ORDER BY sortorder, answer"; + $mearesult = db_execute_assoc($meaquery); +// $printablesurveyoutput .="\t\t\t".$clang->gT("Please choose all that apply and provide a comment:")."
    \n"; + $pdfoutput=array(); + $j=0; + $longest_string = 0; + while ($mearow = $mearesult->FetchRow()) + { + $longest_string = longest_string($mearow['answer'] , $longest_string ); + $question['ANSWER'] .= "\t
  • \n\t\t".input_type_image('checkbox',$mearow['answer']).$mearow['answer']."\n\t\t".input_type_image('text','comment box',60)."\n\t
  • \n"; + $pdfoutput[$j]=array(" o ".$mearow['code']," __________"); + $j++; + } + if ($deqrow['other'] == "Y") + { + $question['ANSWER'] .= "\t
  • \n\t\t
    ".$clang->gT('Other:').input_type_image('other','',1)."
    ".input_type_image('othercomment','comment box',50)."\n\t
  • \n"; + // lemeur: PDFOUTPUT HAS NOT BEEN IMPLEMENTED for these fields + // not sure who did implement this. + $pdfoutput[$j][0]=array(" o "."Other"," __________"); + $pdfoutput[$j][1]=array(" o "."OtherComment"," __________"); + $j++; + } + + $question['ANSWER'] = "\n
      \n".$question['ANSWER']."
    \n"; + if(isset($_POST['printableexport'])){$pdf->tableintopdf($pdfoutput);} + break; + + +// ================================================================== + case "Q": //MULTIPLE SHORT TEXT + $width=60; + +// ================================================================== + case "K": //MULTIPLE NUMERICAL + $width=(isset($width))?$width:16; + if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Please write your answer(s) here:"),"U");} + + $question['QUESTION_TYPE_HELP'] = $clang->gT("Please write your answer(s) here:"); + + $meaquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid={$deqrow['qid']} AND language='{$surveyprintlang}' ORDER BY sortorder, answer"; + $mearesult = db_execute_assoc($meaquery); + $longest_string = 0; + while ($mearow = $mearesult->FetchRow()) + { + $longest_string = longest_string($mearow['answer'] , $longest_string ); + $question['ANSWER'] .= "\t
  • \n\t\t".$mearow['answer']."\n\t\t".input_type_image('text',$mearow['answer'],$width)."\n\t
  • \n"; + if(isset($_POST['printableexport'])){$pdf->intopdf($mearow['answer'].": ____________________");} + } + $question['ANSWER'] = "\n
      \n".$question['ANSWER']."
    \n"; + break; + + +// ================================================================== + case "S": //SHORT TEXT + $question['QUESTION_TYPE_HELP'] = $clang->gT("Please write your answer here:"); + $question['ANSWER'] = input_type_image('text',$question['QUESTION_TYPE_HELP'], 50); + if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Please write your answer here:"),"U");} + if(isset($_POST['printableexport'])){$pdf->intopdf("____________________");} + break; + + +// ================================================================== + case "T": //LONG TEXT + $question['QUESTION_TYPE_HELP'] = $clang->gT("Please write your answer here:"); + $question['ANSWER'] = input_type_image('textarea',$question['QUESTION_TYPE_HELP'], '100%' , 8); + + if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Please write your answer here:"),"U");} + for($i=0;$i<9;$i++) + { + if(isset($_POST['printableexport'])){$pdf->intopdf("____________________");} + } + break; + + +// ================================================================== + case "U": //HUGE TEXT + $question['QUESTION_TYPE_HELP'] = $clang->gT("Please write your answer here:"); + $question['ANSWER'] = input_type_image('textarea',$question['QUESTION_TYPE_HELP'], '100%' , 30); + + if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Please write your answer here:"),"U");} + for($i=0;$i<20;$i++) + { + if(isset($_POST['printableexport'])){$pdf->intopdf("____________________");} + } + break; + + +// ================================================================== + case "N": //NUMERICAL + $question['QUESTION_TYPE_HELP'] = $clang->gT("Please write your answer here:"); + $question['ANSWER'] = input_type_image('text',$question['QUESTION_TYPE_HELP'],20); + + if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Please write your answer here:"),"U");} + if(isset($_POST['printableexport'])){$pdf->intopdf("____________________");} + + break; + +// ================================================================== + case "Y": //YES/NO + $question['QUESTION_TYPE_HELP'] = $clang->gT("Please choose *only one* of the following:"); + $question['ANSWER'] = "\n
      \n\t
    • \n\t\t".input_type_image('radio',$clang->gT('Yes'))."\n\t\t".$clang->gT('Yes')."\n\t
    • \n"; + $question['ANSWER'] .= "\n\t
    • \n\t\t".input_type_image('radio',$clang->gT('No'))."\n\t\t".$clang->gT('No')."\n\t
    • \n
    \n"; + + if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Please choose *only one* of the following:"),"U");} + if(isset($_POST['printableexport'])){$pdf->intopdf(" o ".$clang->gT("Yes"));} + if(isset($_POST['printableexport'])){$pdf->intopdf(" o ".$clang->gT("No"));} + break; + + +// ================================================================== + case "A": //ARRAY (5 POINT CHOICE) + $meaquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid={$deqrow['qid']} AND language='{$surveyprintlang}' ORDER BY sortorder, answer"; + $mearesult = db_execute_assoc($meaquery); + $question['QUESTION_TYPE_HELP'] = $clang->gT("Please choose the appropriate response for each item:"); + + $question['ANSWER'] = ' + + + + + + + + + + + + +'; + + if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Please choose the appropriate response for each item:"),"U");} + $pdfoutput = array(); + $j=0; + $rowclass = 'array1'; + while ($mearow = $mearesult->FetchRow()) + { + $question['ANSWER'] .= "\t\t\n"; + $rowclass = alternation($rowclass,'row'); + $answertext=$mearow['answer']; + if (strpos($answertext,'|')) {$answertext=substr($answertext,0, strpos($answertext,'|'));} + $question['ANSWER'] .= "\t\t\t\n"; + + $pdfoutput[$j][0]=$answertext; + for ($i=1; $i<=5; $i++) + { + $question['ANSWER'] .= "\t\t\t\n"; + $pdfoutput[$j][$i]=" o ".$i; + } + + $answertext=$mearow['answer']; + if (strpos($answertext,'|')) + { + $answertext=substr($answertext,strpos($answertext,'|')+1); + $question['ANSWER'] .= "\t\t\t\n"; + $j++; + } + $question['ANSWER'] .= "\t\n
     12345
    $answertext".input_type_image('radio',$i)."$answertext\n"; + } + $question['ANSWER'] .= "\t\t
    \n"; + if(isset($_POST['printableexport'])){$pdf->tableintopdf($pdfoutput);} + break; + +// ================================================================== + case "B": //ARRAY (10 POINT CHOICE) + $meaquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid={$deqrow['qid']} AND language='{$surveyprintlang}' ORDER BY sortorder, answer"; + + $mearesult = db_execute_assoc($meaquery); + $question['QUESTION_TYPE_HELP'] = $clang->gT("Please choose the appropriate response for each item:"); + + $question['ANSWER'] .= "\n\n\t\n\t\t\n\t\t\t\n"; + for ($i=1; $i<=10; $i++) + { + $question['ANSWER'] .= "\t\t\t\n"; + } + $question['ANSWER'] .= "\t\n\n\t\n"; + if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Please choose the appropriate response for each item:"),"U");} + $pdfoutput=array(); + $j=0; + $rowclass = 'array1'; + while ($mearow = $mearesult->FetchRow()) + { + + $question['ANSWER'] .= "\t\t\n\t\t\t\n"; + $rowclass = alternation($rowclass,'row'); + + $pdfoutput[$j][0]=$mearow['answer']; + for ($i=1; $i<=10; $i++) + { + $question['ANSWER'] .= "\t\t\t\n"; + $pdfoutput[$j][$i]=" o ".$i; + }; + $question['ANSWER'] .= "\t\t\n"; + $j++; + } + $question['ANSWER'] .= "\t\n
     $i
    {$mearow['answer']}".input_type_image('radio',$i)."
    \n"; + if(isset($_POST['printableexport'])){$pdf->tableintopdf($pdfoutput);} + break; + +// ================================================================== + case "C": //ARRAY (YES/UNCERTAIN/NO) + $meaquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid={$deqrow['qid']} AND language='{$surveyprintlang}' ORDER BY sortorder, answer"; + $mearesult = db_execute_assoc($meaquery); + $question['QUESTION_TYPE_HELP'] = $clang->gT("Please choose the appropriate response for each item:"); + + $question['ANSWER'] = ' + + + + + + + + + + +'; + if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Please choose the appropriate response for each item:"),"U");} + $pdfoutput = array(); + $j=0; + + $rowclass = 'array1'; + + while ($mearow = $mearesult->FetchRow()) + { + $question['ANSWER'] .= "\t\t\n"; + $question['ANSWER'] .= "\t\t\t\n"; + $question['ANSWER'] .= "\t\t\t\n"; + $question['ANSWER'] .= "\t\t\t\n"; + $question['ANSWER'] .= "\t\t\t\n"; + $question['ANSWER'] .= "\t\t\n"; + + $pdfoutput[$j]=array($mearow['answer']," o ".$clang->gT("Yes")," o ".$clang->gT("Uncertain")," o ".$clang->gT("No")); + $j++; + $rowclass = alternation($rowclass,'row'); + } + $question['ANSWER'] .= "\t\n
     '.$clang->gT("Yes").''.$clang->gT("Uncertain").''.$clang->gT("No").'
    {$mearow['answer']}".input_type_image('radio',$clang->gT("Yes"))."".input_type_image('radio',$clang->gT("Uncertain"))."".input_type_image('radio',$clang->gT("No"))."
    \n"; + if(isset($_POST['printableexport'])){$pdf->tableintopdf($pdfoutput);} + break; + + case "E": //ARRAY (Increase/Same/Decrease) + $meaquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid={$deqrow['qid']} AND language='{$surveyprintlang}' ORDER BY sortorder, answer"; + $mearesult = db_execute_assoc($meaquery); + $question['QUESTION_TYPE_HELP'] = $clang->gT("Please choose the appropriate response for each item:"); + + $question['ANSWER'] = ' + + + + + + + + + + +'; + if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Please choose the appropriate response for each item:"),"U");} + $pdfoutput = array(); + $j=0; + $rowclass = 'array1'; + + while ($mearow = $mearesult->FetchRow()) + { + $question['ANSWER'] .= "\t\t\n"; + $question['ANSWER'] .= "\t\t\t\n"; + $question['ANSWER'] .= "\t\t\t\n"; + $question['ANSWER'] .= "\t\t\t\n"; + $question['ANSWER'] .= "\t\t\t\n"; + $question['ANSWER'] .= "\t\t\n"; + $pdfoutput[$j]=array($mearow['answer'].":"," o ".$clang->gT("Increase")," o ".$clang->gT("Same")," o ".$clang->gT("Decrease")); + $j++; + $rowclass = alternation($rowclass,'row'); + } + $question['ANSWER'] .= "\t\n
     '.$clang->gT("Increase").''.$clang->gT("Same").''.$clang->gT("Decrease").'
    {$mearow['answer']}".input_type_image('radio',$clang->gT("Increase"))."".input_type_image('radio',$clang->gT("Same"))."".input_type_image('radio',$clang->gT("Decrease"))."
    \n"; + if(isset($_POST['printableexport'])){$pdf->tableintopdf($pdfoutput);} + break; + +// ================================================================== + case ":": //ARRAY (Multi Flexible) (Numbers) + $headstyle="style='padding-left: 20px; padding-right: 7px'"; + if (isset($qidattributes['multiflexible_max'])) { + $maxvalue=$qidattributes['multiflexible_max']; + } + else + { + $maxvalue=10; + } + if (isset($qidattributes['multiflexible_min'])) { + $minvalue=$qidattributes['multiflexible_min']; + } else { + $minvalue=1; + } + if (isset($qidattributes['multiflexible_step'])) { + $stepvalue=$qidattributes['multiflexible_step']; + } + else + { + $stepvalue=1; + } + if (isset($qidattributes['multiflexible_checkbox'])) { + $checkboxlayout=true; + } else { + $checkboxlayout=false; + } + $meaquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid={$deqrow['qid']} AND language='{$surveyprintlang}' ORDER BY sortorder, answer"; + $mearesult = db_execute_assoc($meaquery); + if ($checkboxlayout === false) + { + if ($stepvalue > 1) + { + $question['QUESTION_TYPE_HELP'] = $clang->gT("Please write a multiple of $stepvalue between $minvalue and $maxvalue for each item:"); + if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Please write a multiple of $stepvalue between $minvalue and $maxvalue for each item:"),"U");} + } + else { + $question['QUESTION_TYPE_HELP'] = $clang->gT("Please write a number between $minvalue and $maxvalue for each item:"); + if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Please write a number between $minvalue and $maxvalue for each item:"),"U");} + } + } + else + { + $question['QUESTION_TYPE_HELP'] = $clang->gT("Check any that apply").":"; + if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Check any that apply"),"U");} + } + + $question['ANSWER'] .= "\n\n\t\n\t\t\n\t\t\t\n"; + $fquery = "SELECT * FROM ".db_table_name("labels")." WHERE lid='{$deqrow['lid']}' AND language='{$surveyprintlang}' ORDER BY sortorder, code"; + $fresult = db_execute_assoc($fquery); + $fcount = $fresult->RecordCount(); + $fwidth = "120"; + $i=0; + $pdfoutput = array(); + $pdfoutput[0][0]=' '; + while ($frow = $fresult->FetchRow()) + { + $question['ANSWER'] .= "\t\t\t\n"; + $i++; + $pdfoutput[0][$i]=$frow['title']; + } + $question['ANSWER'] .= "\t\t\n\t\n\n\t\n"; + $a=1; //Counter for pdfoutput + $rowclass = 'array1'; + + while ($mearow = $mearesult->FetchRow()) + { + $question['ANSWER'] .= "\t\n"; + $rowclass = alternation($rowclass,'row'); + + $answertext=$mearow['answer']; + if (strpos($answertext,'|')) {$answertext=substr($answertext,0, strpos($answertext,'|'));} + $question['ANSWER'] .= "\t\t\t\t\t\n"; + //$printablesurveyoutput .="\t\t\t\t\t\n"; + } + $answertext=$mearow['answer']; + if (strpos($answertext,'|')) + { + $answertext=substr($answertext,strpos($answertext,'|')+1); + $question['ANSWER'] .= "\t\t\t\n"; + //$pdfoutput[$a][$i]=$answertext; + } + $question['ANSWER'] .= "\t\t\n"; + $a++; + } + $question['ANSWER'] .= "\t\n
     {$frow['title']}
    $answertext"; + $pdfoutput[$a][0]=$answertext; + for ($i=1; $i<=$fcount; $i++) + { + + $question['ANSWER'] .= "\t\t\t\n"; + if ($checkboxlayout === false) + { + $question['ANSWER'] .= "\t\t\t\t".input_type_image('text','',4)."\n"; + $pdfoutput[$a][$i]="__"; + } + else + { + $question['ANSWER'] .= "\t\t\t\t".input_type_image('checkbox')."\n"; + $pdfoutput[$a][$i]="o"; + } + $question['ANSWER'] .= "\t\t\t$answertext
    \n"; + if(isset($_POST['printableexport'])){$pdf->tableintopdf($pdfoutput);} + break; + +// ================================================================== + case ";": //ARRAY (Multi Flexible) (text) + $headstyle="style='padding-left: 20px; padding-right: 7px'"; + $meaquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid={$deqrow['qid']} AND language='{$surveyprintlang}' ORDER BY sortorder, answer"; + $mearesult = db_execute_assoc($meaquery); + + $question['ANSWER'] .= "\n\n\t\n\t\t\n\t\t\t\n"; + $fquery = "SELECT * FROM ".db_table_name("labels")." WHERE lid='{$deqrow['lid']}' AND language='{$surveyprintlang}' ORDER BY sortorder, code"; + $fresult = db_execute_assoc($fquery); + $fcount = $fresult->RecordCount(); + $fwidth = "120"; + $i=0; + $pdfoutput=array(); + $pdfoutput[0][0]=''; + while ($frow = $fresult->FetchRow()) + { + $question['ANSWER'] .= "\t\t\t\n"; + $i++; + $pdfoutput[0][$i]=$frow['title']; + } + $question['ANSWER'] .= "\t\t\n\t\n\n\n"; + $a=1; + $rowclass = 'array1'; + + while ($mearow = $mearesult->FetchRow()) + { + $question['ANSWER'] .= "\t\t\n"; + $rowclass = alternation($rowclass,'row'); + $answertext=$mearow['answer']; + if (strpos($answertext,'|')) {$answertext=substr($answertext,0, strpos($answertext,'|'));} + $question['ANSWER'] .= "\t\t\t\n"; + $pdfoutput[$a][0]=$answertext; + //$printablesurveyoutput .="\t\t\t\t\t\n"; + $pdfoutput[$a][$i]="_____________"; + } + $answertext=$mearow['answer']; + if (strpos($answertext,'|')) + { + $answertext=substr($answertext,strpos($answertext,'|')+1); + $question['ANSWER'] .= "\t\t\t\t\n"; + } + $question['ANSWER'] .= "\t\t\n"; + $a++; + } + $question['ANSWER'] .= "\t\n
     {$frow['title']}
    $answertext"; + for ($i=1; $i<=$fcount; $i++) + { + $question['ANSWER'] .= "\t\t\t\n"; + $question['ANSWER'] .= "\t\t\t\t".input_type_image('text','',23)."\n"; + $question['ANSWER'] .= "\t\t\t$answertext
    \n"; + if(isset($_POST['printableexport'])){$pdf->tableintopdf($pdfoutput);} + break; + +// ================================================================== + case "F": //ARRAY (Flexible Labels) + + $meaquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid={$deqrow['qid']} AND language='{$surveyprintlang}' ORDER BY sortorder, answer"; + $mearesult = db_execute_assoc($meaquery); + + $question['QUESTION_TYPE_HELP'] = $clang->gT("Please choose the appropriate response for each item:"); + + $fquery = "SELECT * FROM ".db_table_name("labels")." WHERE lid='{$deqrow['lid']}' AND language='{$surveyprintlang}' ORDER BY sortorder, code"; + $fresult = db_execute_assoc($fquery); + $fcount = $fresult->RecordCount(); + $fwidth = "120"; + $i=1; + $pdfoutput = array(); + $pdfoutput[0][0]=''; + if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Please choose the appropriate response for each item:"),"U");} + $column_headings = array(); + while ($frow = $fresult->FetchRow()) + { + $column_headings[] = $frow['title']; + } + $col_width = round(80 / count($column_headings)); + + $question['ANSWER'] .= "\n\n\t\n\t\t\n"; + $question['ANSWER'] .= "\t\t\t\n"; + foreach($column_headings as $heading) + $question['ANSWER'] .= "\t\t\t\n"; + $pdfoutput[0][$i] = $heading; + $i++; + $question['ANSWER'] .= "\t\t\n\t\n\n\t\n"; + $counter = 1; + $rowclass = 'array1'; + + while ($mearow = $mearesult->FetchRow()) + { + $question['ANSWER'] .= "\t\t\n"; + $rowclass = alternation($rowclass,'row'); + $answertext=$mearow['answer']; + if (trim($answertext)=='') $answertext=' '; + if (strpos($answertext,'|')) {$answertext=substr($answertext,0, strpos($answertext,'|'));} + $question['ANSWER'] .= "\t\t\t\n"; + //$printablesurveyoutput .="\t\t\t\t\t\n"; + $pdfoutput[$counter][$i] = "o"; + + } + $counter++; + + $answertext=$mearow['answer']; + if (strpos($answertext,'|')) + { + $answertext=substr($answertext,strpos($answertext,'|')+1); + $question['ANSWER'] .= "\t\t\t\n"; + + } + $question['ANSWER'] .= "\t\t\n"; + } + $question['ANSWER'] .= "\t\n
     $heading
    $answertext"; + $pdfoutput[$counter][0]=$answertext; + for ($i=1; $i<=$fcount; $i++) + { + + $question['ANSWER'] .= "\t\t\t".input_type_image('radio')."$answertext
    \n"; + if(isset($_POST['printableexport'])){$pdf->tableintopdf($pdfoutput);} + break; + +// ================================================================== + case "1": //ARRAY (Flexible Labels) multi scale + if (isset($qidattributes['dualscale_headerA'])) + { + $leftheader= $qidattributes['dualscale_headerA']; + } + else + { + $leftheader =''; + } + if (isset($qidattributes['dualscale_headerB'])) + { + $rightheader= $qidattributes['dualscale_headerB']; + } + else + { + $rightheader =''; + } + + $headstyle = 'style="padding-left: 20px; padding-right: 7px"'; + $meaquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid={$deqrow['qid']} AND language='{$surveyprintlang}' ORDER BY sortorder, answer"; + $mearesult = db_execute_assoc($meaquery); + $question['QUESTION_TYPE_HELP'] = $clang->gT("Please choose the appropriate response for each item:"); + + if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Please choose the appropriate response for each item:"),"U");} + $question['ANSWER'] .= "\n\n\t\n"; + + $fquery = "SELECT * FROM ".db_table_name("labels")." WHERE lid='{$deqrow['lid']}' AND language='{$surveyprintlang}' ORDER BY sortorder, code"; + $fresult = db_execute_assoc($fquery); + $fcount = $fresult->RecordCount(); + $fwidth = "120"; + $l1=0; + $printablesurveyoutput2 = "\t\t\t\n"; + $myheader2 = ''; + $pdfoutput = array(); + $pdfoutput[0][0]=''; + while ($frow = $fresult->FetchRow()) + { + $printablesurveyoutput2 .="\t\t\t\n"; + $myheader2 .= ""; + $pdfoutput[0][$l1+1]=$frow['title']; + $l1++; + } + // second scale + $printablesurveyoutput2 .="\t\t\t\n"; + $fquery1 = "SELECT * FROM ".db_table_name("labels")." WHERE lid='{$deqrow['lid1']}' AND language='{$surveyprintlang}' ORDER BY sortorder, code"; + $fresult1 = db_execute_assoc($fquery1); + $fcount1 = $fresult1->RecordCount(); + $fwidth = "120"; + $l2=0; + while ($frow1 = $fresult1->FetchRow()) + { + $printablesurveyoutput2 .="\t\t\t\n"; + $pdfoutput[1][$l2]=$frow['title']; + $l2++; + } + // build header if needed + if ($leftheader != '' || $rightheader !='') + { + $myheader = "\t\t\t"; + $myheader .= "\t\t\t\n"; + + if ($rightheader !='') + { + // $myheader .= "\t\t\t\t\t" .$myheader2; + $myheader .= "\t\t\t"; + $myheader .= "\t\t\t\n"; + } + else + { + $myheader = ''; + } + $question['ANSWER'] .= $myheader . "\t\t\n\n\t\t\n"; + $question['ANSWER'] .= $printablesurveyoutput2; + $question['ANSWER'] .= "\t\t\n\t\n\n\t\n"; + + $rowclass = 'array1'; + + while ($mearow = $mearesult->FetchRow()) + { + $question['ANSWER'] .= "\t\t\n"; + $rowclass = alternation($rowclass,'row'); + $answertext=$mearow['answer']; + if (strpos($answertext,'|')) {$answertext=substr($answertext,0, strpos($answertext,'|'));} + $question['ANSWER'] .= "\t\t\t\n"; + for ($i=1; $i<=$fcount; $i++) + { + $question['ANSWER'] .= "\t\t\t\n"; + } + $question['ANSWER'] .= "\t\t\t\n"; + for ($i=1; $i<=$fcount1; $i++) + { + $question['ANSWER'] .= "\t\t\t\n"; + } + + $answertext=$mearow['answer']; + if (strpos($answertext,'|')) + { + $answertext=substr($answertext,strpos($answertext,'|')+1); + $question['ANSWER'] .= "\t\t\t\n"; + } + $question['ANSWER'] .= "\t\t\n"; + } + $question['ANSWER'] .= "\t\n
     {$frow['title']} {$frow1['title']} $leftheader $rightheader\n"; + } + + $myheader .= "\t\t\t\t
    $answertext".input_type_image('radio')." ".input_type_image('radio')."$answertext
    \n"; + if(isset($_POST['printableexport'])){$pdf->tableintopdf($pdfoutput);} + break; + +// ================================================================== + case "H": //ARRAY (Flexible Labels) by Column + //$headstyle="style='border-left-style: solid; border-left-width: 1px; border-left-color: #AAAAAA'"; + $headstyle="style='padding-left: 20px; padding-right: 7px'"; + $fquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid={$deqrow['qid']} AND language='{$surveyprintlang}' ORDER BY sortorder, answer"; + $fresult = db_execute_assoc($fquery); + $question['QUESTION_TYPE_HELP'] = $clang->gT("Please choose the appropriate response for each item:"); + if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Please choose the appropriate response for each item:"),"U");} + $question['ANSWER'] .= "\n\n\t\n\t\t\n\t\t\t\n"; + $meaquery = "SELECT * FROM ".db_table_name("labels")." WHERE lid='{$deqrow['lid']}' AND language='{$surveyprintlang}' ORDER BY sortorder, code"; + $mearesult = db_execute_assoc($meaquery); + $fcount = $fresult->RecordCount(); + $fwidth = "120"; + $i=0; + $pdfoutput = array(); + $pdfoutput[0][0]=''; + while ($frow = $fresult->FetchRow()) + { + $question['ANSWER'] .= "\t\t\t\n"; + $i++; + $pdfoutput[0][$i]=$frow['answer']; + } + $question['ANSWER'] .= "\t\t\n\t\n\n\t\n"; + $a=1; + $rowclass = 'array1'; + + + while ($mearow = $mearesult->FetchRow()) + { + $question['ANSWER'] .= "\t\t\n"; + $rowclass = alternation($rowclass,'row'); + $question['ANSWER'] .= "\t\t\t\n"; + //$printablesurveyoutput .="\t\t\t\t\t\n"; + $pdfoutput[$a][$i]="o"; + } + //$printablesurveyoutput .="\t\t\t\t\t
     {$frow['answer']}
    {$mearow['title']}"; + $pdfoutput[$a][0]=$mearow['title']; + for ($i=1; $i<=$fcount; $i++) + { + $question['ANSWER'] .= "\t\t\t".input_type_image('radio')."
    \n"; + $question['ANSWER'] .= "\t\t\n"; + $a++; + } + $question['ANSWER'] .= "\t\n\n"; + + if(isset($_POST['printableexport'])){$pdf->tableintopdf($pdfoutput);} + break; +// === END SWITCH =================================================== + } + if(isset($_POST['printableexport'])){$pdf->ln(5);} + + $question['QUESTION_TYPE_HELP'] = star_replace($question['QUESTION_TYPE_HELP']); + $group['QUESTIONS'] .= populate_template( 'question' , $question); + + } + $survey_output['GROUPS'] .= populate_template( 'group' , $group ); +} + +$survey_output['THEREAREXQUESTIONS'] = str_replace( '{NUMBEROFQUESTIONS}' , $total_questions , $clang->gT('There are {NUMBEROFQUESTIONS} questions in this survey')); + +// START recursive tag stripping. + +$server_is_newer = version_compare(PHP_VERSION , '5.1.0' , '>'); // PHP 5.1.0 introduced the count peramater for preg_replace() and thus allows this procedure to run with only one regular expression. Previous version of PHP need two regular expressions to do the same thing and thus will run a bit slower. +$rounds = 0; +while($rounds < 1) +{ + $replace_count = 0; + if($server_is_newer) // Server version of PHP is at least 5.1.0 or newer + { + $survey_output['GROUPS'] = preg_replace( + array( + '/(?: | | )?<\/td>/isU' + ,'/<([^ >]+)[^>]*>(?: | |\r\n|\n\r|\n|\r|\t| )*<\/\1>/isU' + ) + ,array( + '[[EMPTY-TABLE-CELL]]' + ,'' + ) + ,$survey_output['GROUPS'] + ,-1 + ,$replace_count + ); + } + else // Server version of PHP is older than 5.1.0 + { + $survey_output['GROUPS'] = preg_replace( + array( + '/(?: | | )?<\/td>/isU' + ,'/<([^ >]+)[^>]*>(?: | |\r\n|\n\r|\n|\r|\t| )*<\/\1>/isU' + ) + ,array( + '[[EMPTY-TABLE-CELL]]' + ,'' + ) + ,$survey_output['GROUPS'] + ); + $replace_count = preg_match( + '/<([^ >]+)[^>]*>(?: | |\r\n|\n\r|\n|\r|\t| )*<\/\1>/isU' + , $survey_output['GROUPS'] + ); + }; + + if($replace_count == 0) + { + ++$rounds; + $survey_output['GROUPS'] = preg_replace( + array( + '/\[\[EMPTY-TABLE-CELL\]\]/' + ,'/\n(?:\t*\n)+/' + ) + ,array( + ' ' + ,"\n" + ) + ,$survey_output['GROUPS'] + ); + + }; +}; + +$survey_output['GROUPS'] = preg_replace( '/(]*>){NOTEMPTY}(<\/div>)/' , '\1 \2' , $survey_output['GROUPS']); + +// END recursive empty tag stripping. + +if(isset($_POST['printableexport'])) +{ + if ($surveystartdate!='') + { + if(isset($_POST['printableexport'])){$pdf->intopdf(sprintf($clang->gT("Please submit by %s"), $surveyexpirydate));} + }; + if(!empty($surveyfaxto) && $surveyfaxto != '000-00000000') //If no fax number exists, don't display faxing information! + { + if(isset($_POST['printableexport'])){$pdf->intopdf(sprintf($clang->gT("Please fax your completed survey to: %s"),$surveyfaxto),'B');} + }; + $pdf->titleintopdf($clang->gT("Submit Your Survey."),$clang->gT("Thank you for completing this survey.")); + $pdf->write_out($clang->gT($surveyname)." ".$surveyid.".pdf"); +} + +echo populate_template( 'survey' , $survey_output ); + +exit; +?> diff --git a/include/limesurvey/admin/questionhandling.php b/include/limesurvey/admin/questionhandling.php index e1e4990a..8260b432 100644 --- a/include/limesurvey/admin/questionhandling.php +++ b/include/limesurvey/admin/questionhandling.php @@ -1,931 +1,908 @@ -gT("Error: You have to enter a code for this question.","js")."')\">\n" - . "\n\n" - . "\t\n" - . "\t\t\n" - . "\t
    " - . "\t\t".$clang->gT("Add Question")."\n" - . "\t\t
    \n"; - - $newquestionoutput .= "\t".'
    '."\n"; - - $newquestionoutput .= "\t".'

    '.$clang->gT("Add Question")."

    \n"; - - - $newquestionoutput .= "" - . "\t\n" - . "\t\t\n" - . "\t\t\n" - . "\t\n" - . "\t\t\n" - . "\t\t\n" - . "\t\n" - . "\t\n" - . "\t\t\n" - . "\t\t\n" - . "\t\n" - . "\t\n" - . "\t\t\n" - . "\t\t\n" - . "\t\n"; - - $newquestionoutput .= "\t\n" - . "\t\t\n" - . "\t\t\n" - . "\t\n"; - - $newquestionoutput .= "\t\n" - . "\t\t\n" - . "\t\t\n" - . "\t\t\n" - . "\t\t\n" - . "\t\n"; - - $newquestionoutput .= "\t\n" - . "\t\t\n" - . "\t\t\n" - . "\t\n"; - - $newquestionoutput .= "\t\n" - . "\t\t\n" - . "\t\t\n" - . "\t\n"; - - //Get the questions for this group - $baselang = GetBaseLanguageFromSurveyID($surveyid); - $oqquery = "SELECT * FROM ".db_table_name('questions')." WHERE sid=$surveyid AND gid=$gid AND language='".$baselang."' order by question_order" ; - $oqresult = db_execute_assoc($oqquery); - if ($oqresult->RecordCount()) - { - $newquestionoutput .= "\t\n" - . "\t\t\n" - . "\t\t\n" - . "\t\n"; - } - else - - {$newquestionoutput .= "";} - //Question attributes - $qattributes=questionAttributes(); - - $newquestionoutput .= "\t - - \n"; - $newquestionoutput .= "\t\n" - . "\t\t
    ".$clang->gT("Code:")."" - . " ".$clang->gT("Required")."
    ".$clang->gT("Question:")."" - . getEditor("question-text","question", "[".$clang->gT("Question:", "js")."]",$surveyid,$gid,'',$action) - ."
    ".$clang->gT("Help:")."" - . getEditor("question-help","help", "[".$clang->gT("Help:", "js")."]",$surveyid,$gid,'',$action) - ."
    ".$clang->gT("Type:")."
    ".$clang->gT("Validation:")."\n" - . "\t\t\n" - . "\t\t
    ".$clang->gT("Mandatory:")."\n" - . "\t\t\t" - . "  \n" - . "\t\t\t" - . "\n" - . "\t\t
    ".$clang->gT("Position:")."\n" - . "\t\t\t\n" - . "\t\t
    ".$clang->gT("Question Attributes:")." -
    "; - - if (isset($eqrow)) {$newquestionoutput .= questionjavascript($eqrow['type'], $qattributes);} - else {$newquestionoutput .= questionjavascript('', $qattributes);} - - $newquestionoutput .= "\n" - . "\t\n" - . "\t\n" - . "\t\n" - . "\t\n" - . "
    \n" - . "
    \n" // End TAB - . "\t\n"; - - // Import TAB - $newquestionoutput .='

    '.$clang->gT("Import Question")."

    \n"; - - $newquestionoutput .= "" - . "\t
    \n" - . "\n\t" - . "\t" - . "\t\t\n" - . "\t\t\n" - . "\t\t\t\t\n" - . "\t\t\n" - . "\t
    ".$clang->gT("Select CSV File").":
    ".$clang->gT("Convert Resources links ?")."
    \n" - . "\t\n" - . "\t\n" - . "\t\n" - . "\t
    \n\n" - ."\n"; - - $newquestionoutput .='
    '; -} - -if ($action == "copyquestion") -{ - $questlangs = GetAdditionalLanguagesFromSurveyID($surveyid); - $baselang = GetBaseLanguageFromSurveyID($surveyid); - array_unshift($questlangs,$baselang); - $qattributes=questionAttributes(); - $editquestion = PrepareEditorScript(); - $editquestion .= "\n\t
    " - . "\t\t".$clang->gT("Copy Question")."
    \n" - . "
    \n" - . '
    '; - foreach ($questlangs as $language) - { - $egquery = "SELECT * FROM ".db_table_name('questions')." WHERE sid=$surveyid AND gid=$gid AND qid=$qid and language=".db_quoteall($language); - $egresult = db_execute_assoc($egquery); - $eqrow = $egresult->FetchRow(); - $eqrow = array_map('htmlspecialchars', $eqrow); - $editquestion .= '

    '.getLanguageNameFromCode($eqrow['language'],false); - if ($eqrow['language']==GetBaseLanguageFromSurveyID($surveyid)) - { - $editquestion .= "(".$clang->gT("Base Language").")

    " - . "\t
    ".$clang->gT("Code:")."\n" - . "\t\t ".$clang->gT("Note: You MUST enter a new question code!")."\n" - . "\t
    \n"; - } - else { - $editquestion .= ''; - } - $editquestion .= "\t
    ".$clang->gT("Question:")."\n" - . "\t\t\n" - . getEditor("question-text","question_".$eqrow['language'], "[".$clang->gT("Question:", "js")."](".$eqrow['language'].")",$surveyid,$gid,$qid,$action) - . "\t
    \n" - . "\t
    ".$clang->gT("Help:")."\n" - . "\t\t\n" - . getEditor("question-help","help_".$eqrow['language'], "[".$clang->gT("Help:", "js")."](".$eqrow['language'].")",$surveyid,$gid,$qid,$action) - . "\t
    \n" - . "\t
    \n" - . "\t\t\n" - . "\t
    \n"; - $editquestion .= '
    '; - } - $editquestion .= "\t\n" - . "\t\t\n" - . "\t\t\n" - . "\t\n"; - - $editquestion .= "\t\n" - . "\t\t\n" - . "\t\t\n" - . "\t\n"; - - $editquestion .= "\t\n" - . "\t\t\n" - . "\t\t\n" - . "\t\t\n" - . "\t\n" - . "\t\t\n" - . "\t\t\n" - . "\t\n"; - - $editquestion .= "\t\n" - . "\t\t\n"; - - $editquestion .= "\t\t\n"; - - $editquestion .= "\t\n" - . "\t\t\n" - . "\t\t\n" - . "\t\n" - . "\t\t\n" - . "\t\t\n" - . "\t\t\n" - . "
    ".$clang->gT("Type:")."
    ".$clang->gT("Validation:")."\n" - . "\t\t\n" - . "\t\t
    ".$clang->gT("Group:")."
    ".$clang->gT("Mandatory:")."\n" - . "\t\t\t".$clang->gT("Yes")." gT("No")." \n" - . "\t
    "; - - $editquestion .= questionjavascript($eqrow['type'], $qattributes); - - if ($eqrow['type'] == "J" || $eqrow['type'] == "I") - { - $editquestion .= "\t
    \n" - . "\t\t\n" - . "\t\t\n" - . "\t\t\n" - . "\t\t\n" - . "\t
    \n"; - } - else - { - - $editquestion .= "".$clang->gT("Copy Answers?")."\n" - . "\t\t" - . "\n" - . "\t\n" - . "\t\n" - . "\t\t".$clang->gT("Copy Attributes?")."\n" - . "\t\t" - . "\n" - . "\t\n" - . "\t\n" - . "\t\t\n" - . "\t\t\n" - . "\t\t\n" - . "\t\t\n" - . "\t\n" - . "\n\n"; - } -} - -if ($action == "editquestion" || $action == "editattribute" || $action == "delattribute" || $action == "addattribute") -{ - - $questlangs = GetAdditionalLanguagesFromSurveyID($surveyid); - $baselang = GetBaseLanguageFromSurveyID($surveyid); - $questlangs[] = $baselang; - $questlangs = array_flip($questlangs); - $egquery = "SELECT * FROM ".db_table_name('questions')." WHERE sid=$surveyid AND gid=$gid AND qid=$qid"; - $egresult = db_execute_assoc($egquery); - while ($esrow = $egresult->FetchRow()) - { - if(!array_key_exists($esrow['language'], $questlangs)) // Language Exists, BUT ITS NOT ON THE SURVEY ANYMORE. - { - $egquery = "DELETE FROM ".db_table_name('questions')." WHERE sid='{$surveyid}' AND gid='{$gid}' AND qid='{$qid}' AND language='".$esrow['language']."'"; - $egresultD = $connect->Execute($egquery); - } else { - $questlangs[$esrow['language']] = 99; - } - if ($esrow['language'] == $baselang) $basesettings = array('lid' => $esrow['lid'], 'lid1' => $esrow['lid1'],'question_order' => $esrow['question_order'],'other' => $esrow['other'],'mandatory' => $esrow['mandatory'],'type' => $esrow['type'],'title' => $esrow['title'],'preg' => $esrow['preg'],'question' => $esrow['question'],'help' => $esrow['help']); - - } - - while (list($key,$value) = each($questlangs)) - { - if ($value != 99) - { - if ($databasetype=='odbc_mssql') {@$connect->Execute("SET IDENTITY_INSERT ".db_table_name('questions')." ON");} - $egquery = "INSERT INTO ".db_table_name('questions')." (qid, sid, gid, type, title, question, preg, help, other, mandatory, lid, lid1, question_order, language)" - ." VALUES ('{$qid}','{$surveyid}', '{$gid}', '{$basesettings['type']}', '{$basesettings['title']}'," - ." '{$basesettings['question']}', '{$basesettings['preg']}', '{$basesettings['help']}', '{$basesettings['other']}', '{$basesettings['mandatory']}', '{$basesettings['lid']}', '{$basesettings['lid1']}', '{$basesettings['question_order']}','{$key}')"; - $egresult = $connect->Execute($egquery); - if ($databasetype=='odbc_mssql') {@$connect->Execute("SET IDENTITY_INSERT ".db_table_name('questions')." OFF");} - } - } - - $eqquery = "SELECT * FROM {$dbprefix}questions WHERE sid=$surveyid AND gid=$gid AND qid=$qid AND language='{$baselang}'"; - $eqresult = db_execute_assoc($eqquery); - $editquestion = PrepareEditorScript(); - $editquestion .= "\n\t
    " - . "\t\t".$clang->gT("Edit Question")."
    \n" - . "
    \n" - . '
    '; - - $eqrow = $eqresult->FetchRow(); // there should be only one datarow, therefore we don't need a 'while' construct here. - // Todo: handler in case that record is not found - - $editquestion .= '

    '.getLanguageNameFromCode($eqrow['language'],false); - $editquestion .= '('.$clang->gT("Base Language").')'; - $eqrow = array_map('htmlspecialchars', $eqrow); - $editquestion .= '

    '; - $editquestion .= "\t
    ".$clang->gT("Code:")."\n" - . "\t\t\n" - . "\t
    \n"; - $editquestion .= "\t
    ".$clang->gT("Question:")."\n" - . "\t\t\n" - . getEditor("question-text","question_".$eqrow['language'], "[".$clang->gT("Question:", "js")."](".$eqrow['language'].")",$surveyid,$gid,$qid,$action) - . "\t
    \n" - . "\t
    ".$clang->gT("Help:")."\n" - . "\t\t\n" - . getEditor("question-help","help_".$eqrow['language'], "[".$clang->gT("Help:", "js")."](".$eqrow['language'].")",$surveyid,$gid,$qid,$action) - . "\t
    \n" - . "\t
     \n" - . "\t\t \n" - . "\t
    \n"; - $editquestion .= '
    '; - - $aqquery = "SELECT * FROM {$dbprefix}questions WHERE sid=$surveyid AND gid=$gid AND qid=$qid AND language != '{$baselang}'"; - $aqresult = db_execute_assoc($aqquery); - while (!$aqresult->EOF) - { - $aqrow = $aqresult->FetchRow(); - $editquestion .= '

    '.getLanguageNameFromCode($aqrow['language'],false); - $aqrow = array_map('htmlspecialchars', $aqrow); - $editquestion .= '

    '; - $editquestion .= "\t
    ".$clang->gT("Question:")."\n" - . "\t\t\n" - . getEditor("question-text","question_".$aqrow['language'], "[".$clang->gT("Question:", "js")."](".$aqrow['language'].")",$surveyid,$gid,$qid,$action) - . "\t
    \n" - . "\t
    ".$clang->gT("Help:")."\n" - . "\t\t\n" - . getEditor("question-help","help_".$aqrow['language'], "[".$clang->gT("Help:", "js")."](".$aqrow['language'].")",$surveyid,$gid,$qid,$action) - . "\t
    \n" - . "\t
     \n" - . "\t\t \n" - . "\t
    \n"; - $editquestion .= '

    '; - } - - - //question type: - $editquestion .= "\t\n" - . "\t\t\n"; - if ($activated != "Y") - { - $editquestion .= "\t\t\n"; - } - else - { - $qtypelist=getqtypelist('','array'); - $editquestion .= "\t\t\n"; - } - - $editquestion .="\t\n" - . "\t\t\n" - . "\t\t\n" - . "\t\t\n" - . "\t\n" - . "\t\n" - . "\t\n" - . "\t\t\n" - . "\t\n"; - $editquestion .= "\t\n" - . "\t\t\n"; - - if ($activated != "Y") - { - $editquestion .= "\t\t\n"; - } - $editquestion .= "\t\n"; - - $editquestion .= "\t\n" - . "\t\t\n" - . "\t\t\n"; - - $editquestion .= "\t\n" - . "\t\t\n" - . "\t\t\n" - . "\t\n"; - - - $editquestion .= "\t
    ".$clang->gT("Question Type:")."{$qtypelist[$eqrow['type']]} - ".$clang->gT("Cannot be modified (Survey is active)")."\n" - . "\t\t\t\n" - . "\t\t
    ".$clang->gT("Group:")."
    ".$clang->gT("Other:")."\n" - . "\t\t\t".$clang->gT("No")."\n"; - } - else - { - $editquestion .= " [{$eqrow['other']}] - ".$clang->gT("Cannot be modified")." - ".$clang->gT("Survey is currently active.")."\n" - . "\t\t\t
    ".$clang->gT("Mandatory:")."\n" - . "\t\t\t".$clang->gT("No")."\n" - . "\t
    ".$clang->gT("Validation:")."\n" - . "\t\t\n" - . "\t\t
    \n" - . "\t\n" - . "\t\n" - . "\t
    \n" - . "\t\n"; - - - $qidattributes=getQuestionAttributes($qid); - $editquestion .= "\t\t\t - -
    -
    - - - - - - - - \n"; - $editquestion .= "\t\t\t
    ".$clang->gT("Question Attributes:")."
    - - - -
    \n"; - - foreach ($qidattributes as $qa) - { - $editquestion .= "\t\t\t" - ."
    " - ."
    " - ." - -
    " - .$qa['attribute']." - \n - \n - \n - \n - \n" - ."\t\t\t
    -
    - " - . "\t\n" - . "\t\n" - . "\t\n" - . "\t\n" - . "\t\n" - . "
    \n" - . "
    \n
    "; - } - $editquestion .= "
    "; - $editquestion .= questionjavascript($eqrow['type'], $qattributes); -} - -//Constructing the interface here... -if($action == "orderquestions") -{ - if (isset($_POST['questionordermethod'])) - { - switch($_POST['questionordermethod']) - { - // Pressing the Up button - case $clang->gT("Up", "unescaped"): - $newsortorder=$postsortorder-1; - $oldsortorder=$postsortorder; - $cdquery = "UPDATE ".db_table_name('questions')." SET question_order=-1 WHERE gid=$gid AND question_order=$newsortorder"; - $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); - $cdquery = "UPDATE ".db_table_name('questions')." SET question_order=$newsortorder WHERE gid=$gid AND question_order=$oldsortorder"; - $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); - $cdquery = "UPDATE ".db_table_name('questions')." SET question_order='$oldsortorder' WHERE gid=$gid AND question_order=-1"; - $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); - break; - - // Pressing the Down button - case $clang->gT("Dn", "unescaped"): - $newsortorder=$postsortorder+1; - $oldsortorder=$postsortorder; - $cdquery = "UPDATE ".db_table_name('questions')." SET question_order=-1 WHERE gid=$gid AND question_order=$newsortorder"; - $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); - $cdquery = "UPDATE ".db_table_name('questions')." SET question_order='$newsortorder' WHERE gid=$gid AND question_order=$oldsortorder"; - $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); - $cdquery = "UPDATE ".db_table_name('questions')." SET question_order=$oldsortorder WHERE gid=$gid AND question_order=-1"; - $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); - break; - } - } - if ((!empty($_POST['questionmovefrom']) || (isset($_POST['questionmovefrom']) && $_POST['questionmovefrom'] == '0')) && (!empty($_POST['questionmoveto']) || (isset($_POST['questionmoveto']) && $_POST['questionmoveto'] == '0'))) - { - $newpos=$_POST['questionmoveto']; - $oldpos=$_POST['questionmovefrom']; - if($newpos > $oldpos) - { - //Move the question we're changing out of the way - $cdquery = "UPDATE ".db_table_name('questions')." SET question_order=-1 WHERE gid=$gid AND question_order=$oldpos"; - $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); - //Move all question_orders that are less than the newpos down one - $cdquery = "UPDATE ".db_table_name('questions')." SET question_order=question_order-1 WHERE gid=$gid AND question_order > 0 AND question_order <= $newpos"; - $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); - //Renumber the question we're changing - $cdquery = "UPDATE ".db_table_name('questions')." SET question_order=$newpos WHERE gid=$gid AND question_order=-1"; - $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); - } - if(($newpos+1) < $oldpos) - { - //echo "Newpos $newpos, Oldpos $oldpos"; - //Move the question we're changing out of the way - $cdquery = "UPDATE ".db_table_name('questions')." SET question_order=-1 WHERE gid=$gid AND question_order=$oldpos"; - $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); - //Move all question_orders that are later than the newpos up one - $cdquery = "UPDATE ".db_table_name('questions')." SET question_order=question_order+1 WHERE gid=$gid AND question_order > ".$newpos." AND question_order <= $oldpos"; - $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); - //Renumber the question we're changing - $cdquery = "UPDATE ".db_table_name('questions')." SET question_order=".($newpos+1)." WHERE gid=$gid AND question_order=-1"; - $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); - } - } - - //Get the questions for this group - $baselang = GetBaseLanguageFromSurveyID($surveyid); - $oqquery = "SELECT * FROM ".db_table_name('questions')." WHERE sid=$surveyid AND gid=$gid AND language='".$baselang."' order by question_order" ; - $oqresult = db_execute_assoc($oqquery); - - $orderquestions = "\n\t" - . "
    " - . "\t\t".$clang->gT("Change Question Order")."
    \n"; - -$questioncount = $oqresult->RecordCount(); -$oqarray = $oqresult->GetArray(); -$minioqarray=$oqarray; - -// Get the condition dependecy array for all questions in this array and group -$questdepsarray = GetQuestDepsForConditions($surveyid,$gid); -if (!is_null($questdepsarray)) -{ - $orderquestions .= "
    • ".$clang->gT("Warning").": ".$clang->gT("Current group is using conditional questions")."

      ".$clang->gT("Re-ordering questions in this group is restricted to ensure that questions on which conditions are based aren't reordered after questions having the conditions set")."

      ".$clang->gT("See the conditions marked on the following questions").":
        \n"; - foreach ($questdepsarray as $depqid => $depquestrow) - { - foreach ($depquestrow as $targqid => $targcid) - { - $listcid=implode("-",$targcid); - $question=arraySearchByKey($depqid, $oqarray, "qid", 1); - - $orderquestions .= "
      • ".$question['title'].": ".$question['question']. " [QID: ".$depqid."] "; - } - $orderquestions .= "
      • \n"; - } - $orderquestions .= "
    "; -} - - $orderquestions .= "
      "; - -for($i=0; $i < $questioncount ; $i++) //Assumes that all question orders start with 0 -{ - $downdisabled = ""; - $updisabled = ""; - //Check if question is relied on as a condition dependency by the next question, and if so, don't allow moving down - if ( !is_null($questdepsarray) && $i < $questioncount-1 && - array_key_exists($oqarray[$i+1]['qid'],$questdepsarray) && - array_key_exists($oqarray[$i]['qid'],$questdepsarray[$oqarray[$i+1]['qid']]) ) - { - $downdisabled = "disabled=\"true\" class=\"disabledbtn\""; - } - //Check if question has a condition dependency on the preceding question, and if so, don't allow moving up - if ( !is_null($questdepsarray) && $i !=0 && - array_key_exists($oqarray[$i]['qid'],$questdepsarray) && - array_key_exists($oqarray[$i-1]['qid'],$questdepsarray[$oqarray[$i]['qid']]) ) - { - $updisabled = "disabled=\"true\" class=\"disabledbtn\""; - } - - //Move to location - $orderquestions.="
    • \n" ; - $orderquestions.="\t\n"; - - $orderquestions.= "\t\n"; - if ($i < $questioncount-1) - { - // Fill the sortorder hiddenfield so we know what field is moved down - $orderquestions.= "\t\n"; - } - $orderquestions.= "".$oqarray[$i]['title'].": ".$oqarray[$i]['question']; - $orderquestions.= "
    • \n" ; -} - - $orderquestions.="
    \n" - . "\n" - . "\n" - . "\t" - . "\t" - . "
    " ; - $orderquestions .="
    " ; - -} - -function questionjavascript($type, $qattributes) -{ - $newquestionoutput = "\n"; - - return $newquestionoutput; -} - - -?> +\n\t" + . "\t\t".$clang->gT("Copy Question")."\n" + . "
    \n" + . '
    '; + foreach ($questlangs as $language) + { + $egquery = "SELECT * FROM ".db_table_name('questions')." WHERE sid=$surveyid AND gid=$gid AND qid=$qid and language=".db_quoteall($language); + $egresult = db_execute_assoc($egquery); + $eqrow = $egresult->FetchRow(); + $eqrow = array_map('htmlspecialchars', $eqrow); + $editquestion .= '

    '.getLanguageNameFromCode($eqrow['language'],false); + if ($eqrow['language']==GetBaseLanguageFromSurveyID($surveyid)) + { + $editquestion .= "(".$clang->gT("Base Language").")

    " + . "\t
    ".$clang->gT("Code:")."\n" + . "\t\t ".$clang->gT("Note: You MUST enter a new question code!")."\n" + . "\t
    \n"; + } + else { + $editquestion .= ''; + } + $editquestion .= "\t
    ".$clang->gT("Question:")."\n" + . "\t\t\n" + . getEditor("question-text","question_".$eqrow['language'], "[".$clang->gT("Question:", "js")."](".$eqrow['language'].")",$surveyid,$gid,$qid,$action) + . "\t
    \n" + . "\t
    ".$clang->gT("Help:")."\n" + . "\t\t\n" + . getEditor("question-help","help_".$eqrow['language'], "[".$clang->gT("Help:", "js")."](".$eqrow['language'].")",$surveyid,$gid,$qid,$action) + . "\t
    \n" + . "\t
    \n" + . "\t\t\n" + . "\t
    \n"; + $editquestion .= '
    '; + } + $editquestion .= "\t\n" + . "\t\t\n" + . "\t\t\n" + . "\t\n"; + + $editquestion .= "\t\n" + . "\t\t\n" + . "\t\t\n" + . "\t\n"; + + $editquestion .= "\t\n" + . "\t\t\n" + . "\t\t\n" + . "\t\t\n" + . "\t\n" + . "\t\t\n" + . "\t\t\n" + . "\t\n"; + + $editquestion .= "\t\n" + . "\t\t\n"; + + $editquestion .= "\t\t\n"; + + $editquestion .= "\t\n" + . "\t\t\n" + . "\t\t\n" + . "\t\n" + . "\t\t\n" + . "\t\t\n" + . "\t\t\n" + . "
    ".$clang->gT("Type:")."
    ".$clang->gT("Validation:")."\n" + . "\t\t\n" + . "\t\t
    ".$clang->gT("Question group:")."
    ".$clang->gT("Mandatory:")."\n" + . "\t\t\t".$clang->gT("Yes")." gT("No")." \n" + . "\t
    "; + + $editquestion .= questionjavascript($eqrow['type'], $qattributes); + + if ($eqrow['type'] == "J" || $eqrow['type'] == "I") + { + $editquestion .= "\t
    \n" + . "\t\t\n" + . "\t\t\n" + . "\t\t\n" + . "\t\t\n" + . "\t
    \n"; + } + else + { + + $editquestion .= "".$clang->gT("Copy Answers?")."\n" + . "\t\t" + . "\n" + . "\t\n" + . "\t\n" + . "\t\t".$clang->gT("Copy Attributes?")."\n" + . "\t\t" + . "\n" + . "\t\n" + . "\t\n" + . "\t\t\n" + . "\t\t\n" + . "\t\t\n" + . "\t\t\n" + . "\t\n" + . "\n\n"; + } +} + +if ($action == "editquestion" || $action == "editattribute" || $action == "delattribute" || $action == "addattribute" || $action=="addquestion") +{ + $adding=($action=="addquestion"); + $questlangs = GetAdditionalLanguagesFromSurveyID($surveyid); + $baselang = GetBaseLanguageFromSurveyID($surveyid); + $questlangs[] = $baselang; + $questlangs = array_flip($questlangs); + if (!$adding) + { + $egquery = "SELECT * FROM ".db_table_name('questions')." WHERE sid=$surveyid AND gid=$gid AND qid=$qid"; + $egresult = db_execute_assoc($egquery); + while ($esrow = $egresult->FetchRow()) + { + if(!array_key_exists($esrow['language'], $questlangs)) // Language Exists, BUT ITS NOT ON THE SURVEY ANYMORE. + { + $egquery = "DELETE FROM ".db_table_name('questions')." WHERE sid='{$surveyid}' AND gid='{$gid}' AND qid='{$qid}' AND language='".$esrow['language']."'"; + $egresultD = $connect->Execute($egquery); + } else { + $questlangs[$esrow['language']] = 99; + } + if ($esrow['language'] == $baselang) $basesettings = array('lid' => $esrow['lid'], 'lid1' => $esrow['lid1'],'question_order' => $esrow['question_order'],'other' => $esrow['other'],'mandatory' => $esrow['mandatory'],'type' => $esrow['type'],'title' => $esrow['title'],'preg' => $esrow['preg'],'question' => $esrow['question'],'help' => $esrow['help']); + + } + + + while (list($key,$value) = each($questlangs)) + { + if ($value != 99) + { + if ($connect->databaseType == 'odbc_mssql' || $connect->databaseType == 'odbtp' || $connect->databaseType == 'mssql_n') {@$connect->Execute('SET IDENTITY_INSERT '.db_table_name('questions')." ON");} + $egquery = "INSERT INTO ".db_table_name('questions')." (qid, sid, gid, type, title, question, preg, help, other, mandatory, lid, lid1, question_order, language)" + ." VALUES ('{$qid}','{$surveyid}', '{$gid}', '{$basesettings['type']}', '{$basesettings['title']}'," + ." '{$basesettings['question']}', '{$basesettings['preg']}', '{$basesettings['help']}', '{$basesettings['other']}', '{$basesettings['mandatory']}', '{$basesettings['lid']}', '{$basesettings['lid1']}', '{$basesettings['question_order']}','{$key}')"; + $egresult = $connect->Execute($egquery); + if ($connect->databaseType == 'odbc_mssql' || $connect->databaseType == 'odbtp' || $connect->databaseType == 'mssql_n') {@$connect->Execute('SET IDENTITY_INSERT '.db_table_name('questions')." OFF");} + } + } + + $eqquery = "SELECT * FROM {$dbprefix}questions WHERE sid=$surveyid AND gid=$gid AND qid=$qid AND language='{$baselang}'"; + $eqresult = db_execute_assoc($eqquery); + } + $editquestion = PrepareEditorScript(); + $editquestion .= "\n\t
    "; + if (!$adding) {$editquestion .=$clang->gT("Edit question");} else {$editquestion .=$clang->gT("Add a new question");}; + $editquestion .= "
    \n" + . "
    gT("Error: You have to enter a question code.",'js')."');\">\n" + . '
    '; + + if (!$adding) + { + $eqrow = $eqresult->FetchRow(); // there should be only one datarow, therefore we don't need a 'while' construct here. + // Todo: handler in case that record is not found + } + else + { + $eqrow['language']=$baselang; + $eqrow['title']=''; + $eqrow['question']=''; + $eqrow['help']=''; + $eqrow['type']='T'; + $eqrow['lid']=0; + $eqrow['lid1']=0; + $eqrow['gid']=$gid; + $eqrow['other']='N'; + $eqrow['mandatory']='N'; + $eqrow['preg']=''; + } + $editquestion .= '

    '.getLanguageNameFromCode($eqrow['language'],false); + $editquestion .= '('.$clang->gT("Base Language").')'; + $eqrow = array_map('htmlspecialchars', $eqrow); + $editquestion .= '

    '; + $editquestion .= "\t
    ".$clang->gT("Code:")."\n" + . "\t\t\n" + . "\t
    \n"; + $editquestion .= "\t
    ".$clang->gT("Question:")."\n" + . "\t\t\n" + . getEditor("question-text","question_".$eqrow['language'], "[".$clang->gT("Question:", "js")."](".$eqrow['language'].")",$surveyid,$gid,$qid,$action) + . "\t
    \n" + . "\t
    ".$clang->gT("Help:")."\n" + . "\t\t\n" + . getEditor("question-help","help_".$eqrow['language'], "[".$clang->gT("Help:", "js")."](".$eqrow['language'].")",$surveyid,$gid,$qid,$action) + . "\t
    \n" + . "\t
     \n" + . "\t\t \n" + . "\t
    \n"; + $editquestion .= '
    '; + + + if (!$adding) + { + $aqquery = "SELECT * FROM {$dbprefix}questions WHERE sid=$surveyid AND gid=$gid AND qid=$qid AND language != '{$baselang}'"; + $aqresult = db_execute_assoc($aqquery); + while (!$aqresult->EOF) + { + $aqrow = $aqresult->FetchRow(); + $editquestion .= '

    '.getLanguageNameFromCode($aqrow['language'],false); + $aqrow = array_map('htmlspecialchars', $aqrow); + $editquestion .= '

    '; + $editquestion .= "\t
    ".$clang->gT("Question:")."\n" + . "\t\t\n" + . getEditor("question-text","question_".$aqrow['language'], "[".$clang->gT("Question:", "js")."](".$aqrow['language'].")",$surveyid,$gid,$qid,$action) + . "\t
    \n" + . "\t
    ".$clang->gT("Help:")."\n" + . "\t\t\n" + . getEditor("question-help","help_".$aqrow['language'], "[".$clang->gT("Help:", "js")."](".$aqrow['language'].")",$surveyid,$gid,$qid,$action) + . "\t
    \n" + . "\t
     \n" + . "\t\t \n" + . "\t
    \n"; + $editquestion .= '

    '; + } + } + else + { + $addlanguages=GetAdditionalLanguagesFromSurveyID($surveyid); + foreach ($addlanguages as $addlanguage) + { + $editquestion .= '

    '.getLanguageNameFromCode($addlanguage,false); + $editquestion .= '

    '; + $editquestion .= "\t
    ".$clang->gT("Question:")."\n" + . "\t\t\n" + . getEditor("question-text","question_".$addlanguage, "[".$clang->gT("Question:", "js")."](".$addlanguage.")",$surveyid,$gid,$qid,$action) + . "\t
    \n" + . "\t
    ".$clang->gT("Help:")."\n" + . "\t\t\n" + . getEditor("question-help","help_".$addlanguage, "[".$clang->gT("Help:", "js")."](".$addlanguage.")",$surveyid,$gid,$qid,$action) + . "\t
    \n" + . "\t
     \n" + . "\t\t \n" + . "\t
    \n"; + $editquestion .= '
    '; + } + } + + + + + //question type: + $editquestion .= "\t
    \n" + . "\t\t\n"; + if ($activated != "Y") + { + $editquestion .= "\t\t\n"; + } + else + { + $qtypelist=getqtypelist('','array'); + $editquestion .= "\t\t\n"; + } + + $editquestion .="\t\n" + . "\t\t\n" + . "\t\t\n" + . "\t\t\n" + . "\t\n" + . "\t\n" + . "\t\n" + . "\t\t\n" + . "\t\n"; + $editquestion .= "\t\n" + . "\t\t\n"; + } + else + { + $editquestion .= "\t\t\n" + . "\t\n" + . "\t\n" + . "\t\n" + . "\t\t\n" + . "\t\n"; + $editquestion .= "\t\n" + . "\t\t\n"; + } + + if ($activated != "Y") + { + $editquestion .= "\t\t\n"; + } + $editquestion .= "\t\n"; + + $editquestion .= "\t\n" + . "\t\t\n" + . "\t\t\n"; + + $editquestion .= "\t\n" + . "\t\t\n" + . "\t\t\n" + . "\t\n"; + + + if ($adding) + { + + //Get the questions for this group + $baselang = GetBaseLanguageFromSurveyID($surveyid); + $oqquery = "SELECT * FROM ".db_table_name('questions')." WHERE sid=$surveyid AND gid=$gid AND language='".$baselang."' order by question_order" ; + $oqresult = db_execute_assoc($oqquery); + if ($oqresult->RecordCount()) + { + // select questionposition + $editquestion .= "\t\n" + . "\t\t\n" + . "\t\t\n" + . "\t\n"; + } + else + { + $editquestion .= ""; + } + + $qattributes=questionAttributes(); + + $editquestion .= "\t + + \n"; + $editquestion .= "\t\n" + . "\t\t
    ".$clang->gT("Question Type:")."{$qtypelist[$eqrow['type']]} - ".$clang->gT("Cannot be modified (Survey is active)")."\n" + . "\t\t\t\n" + . "\t\t
    ".$clang->gT("Question group:")."
    ".$clang->gT("Option 'Other':")."
    ".$clang->gT("Question group:")."\n" + . getgrouplist4($eqrow['gid']) + . "\t" + . "\t\t
    ".$clang->gT("Option 'Other':")."\n" + . "\t\t\t".$clang->gT("No")."\n"; + } + else + { + $editquestion .= " [{$eqrow['other']}] - ".$clang->gT("Cannot be modified")." - ".$clang->gT("Survey is currently active.")."\n" + . "\t\t\t
    ".$clang->gT("Mandatory:")."\n" + . "\t\t\t".$clang->gT("No")."\n" + . "\t
    ".$clang->gT("Validation:")."\n" + . "\t\t\n" + . "\t\t
    ".$clang->gT("Position:")."\n" + . "\t\t\t\n" + . "\t\t
    ".$clang->gT("Question Attributes:")." +
    "; + $editquestion .= "\t
    \n" + . "\t

     \n"; + } + else + { + $editquestion .= "\t
    \n" + . "\t\n" + . "\t"; + } + $editquestion .= "\t\n" + . "
    \n" + . "\t\n"; + + + if (!$adding) { + $qidattributes=getQuestionAttributes($qid); + $editquestion .= "\t\t\t + +
    +
    + + + + + + + + \n"; + $editquestion .= "\t\t\t
    ".$clang->gT("Question Attributes:")."
    + + + +
    \n"; + + $attributetranslations=questionAttributes(true); + foreach ($qidattributes as $qa) + { + $editquestion .= "\t\t\t" + ."
    " + ."
    " + ." + +
    " + .$attributetranslations[$qa['attribute']]['caption']." + \n + \n + \n + \n + \n" + ."\t\t\t
    +
    + " + . "\t\n" + . "\t\n" + . "\t\n" + . "\t\n" + . "\t\n" + . "
    \n" + . "
    \n
    "; + } + } + if ($adding) + { + // Import dialogue + + $editquestion .= "\n\t
    "; + $editquestion .=$clang->gT("...or import a question"); + $editquestion .= "
    \n" + . "\t
    \n" + . "\n\t" + . "\t" + . "\t\t\n" + . "\t\t\n" + . "\t\t\t\t\n" + . "\t\t\n" + . "\t
    ".$clang->gT("Select CSV File").":
    ".$clang->gT("Convert resources links?")."
    \n" + . "\t\n" + . "\t\n" + . "\t\n" + . "\t
    \n\n" + ."\n"; + + } + else + { + + $editquestion .= "
    "; + } + + $editquestion .= questionjavascript($eqrow['type'], $qattributes); +} + +//Constructing the interface here... +if($action == "orderquestions") +{ + if (isset($_POST['questionordermethod'])) + { + switch($_POST['questionordermethod']) + { + // Pressing the Up button + case $clang->gT("Up", "unescaped"): + $newsortorder=$postsortorder-1; + $oldsortorder=$postsortorder; + $cdquery = "UPDATE ".db_table_name('questions')." SET question_order=-1 WHERE gid=$gid AND question_order=$newsortorder"; + $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); + $cdquery = "UPDATE ".db_table_name('questions')." SET question_order=$newsortorder WHERE gid=$gid AND question_order=$oldsortorder"; + $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); + $cdquery = "UPDATE ".db_table_name('questions')." SET question_order='$oldsortorder' WHERE gid=$gid AND question_order=-1"; + $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); + break; + + // Pressing the Down button + case $clang->gT("Dn", "unescaped"): + $newsortorder=$postsortorder+1; + $oldsortorder=$postsortorder; + $cdquery = "UPDATE ".db_table_name('questions')." SET question_order=-1 WHERE gid=$gid AND question_order=$newsortorder"; + $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); + $cdquery = "UPDATE ".db_table_name('questions')." SET question_order='$newsortorder' WHERE gid=$gid AND question_order=$oldsortorder"; + $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); + $cdquery = "UPDATE ".db_table_name('questions')." SET question_order=$oldsortorder WHERE gid=$gid AND question_order=-1"; + $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); + break; + } + } + if ((!empty($_POST['questionmovefrom']) || (isset($_POST['questionmovefrom']) && $_POST['questionmovefrom'] == '0')) && (!empty($_POST['questionmoveto']) || (isset($_POST['questionmoveto']) && $_POST['questionmoveto'] == '0'))) + { + $newpos=$_POST['questionmoveto']; + $oldpos=$_POST['questionmovefrom']; + if($newpos > $oldpos) + { + //Move the question we're changing out of the way + $cdquery = "UPDATE ".db_table_name('questions')." SET question_order=-1 WHERE gid=$gid AND question_order=$oldpos"; + $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); + //Move all question_orders that are less than the newpos down one + $cdquery = "UPDATE ".db_table_name('questions')." SET question_order=question_order-1 WHERE gid=$gid AND question_order > 0 AND question_order <= $newpos"; + $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); + //Renumber the question we're changing + $cdquery = "UPDATE ".db_table_name('questions')." SET question_order=$newpos WHERE gid=$gid AND question_order=-1"; + $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); + } + if(($newpos+1) < $oldpos) + { + //echo "Newpos $newpos, Oldpos $oldpos"; + //Move the question we're changing out of the way + $cdquery = "UPDATE ".db_table_name('questions')." SET question_order=-1 WHERE gid=$gid AND question_order=$oldpos"; + $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); + //Move all question_orders that are later than the newpos up one + $cdquery = "UPDATE ".db_table_name('questions')." SET question_order=question_order+1 WHERE gid=$gid AND question_order > ".$newpos." AND question_order <= $oldpos"; + $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); + //Renumber the question we're changing + $cdquery = "UPDATE ".db_table_name('questions')." SET question_order=".($newpos+1)." WHERE gid=$gid AND question_order=-1"; + $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); + } + } + + //Get the questions for this group + $baselang = GetBaseLanguageFromSurveyID($surveyid); + $oqquery = "SELECT * FROM ".db_table_name('questions')." WHERE sid=$surveyid AND gid=$gid AND language='".$baselang."' order by question_order" ; + $oqresult = db_execute_assoc($oqquery); + + $orderquestions = "\n\t" + . "
    " + . "\t\t".$clang->gT("Change Question Order")."
    \n"; + + $questioncount = $oqresult->RecordCount(); + $oqarray = $oqresult->GetArray(); + $minioqarray=$oqarray; + + // Get the condition dependecy array for all questions in this array and group + $questdepsarray = GetQuestDepsForConditions($surveyid,$gid); + if (!is_null($questdepsarray)) + { + $orderquestions .= "
    • ".$clang->gT("Warning").": ".$clang->gT("Current group is using conditional questions")."

      ".$clang->gT("Re-ordering questions in this group is restricted to ensure that questions on which conditions are based aren't reordered after questions having the conditions set")."

      ".$clang->gT("See the conditions marked on the following questions").":
        \n"; + foreach ($questdepsarray as $depqid => $depquestrow) + { + foreach ($depquestrow as $targqid => $targcid) + { + $listcid=implode("-",$targcid); + $question=arraySearchByKey($depqid, $oqarray, "qid", 1); + + $orderquestions .= "
      • ".$question['title'].": ".$question['question']. " [QID: ".$depqid."] "; + } + $orderquestions .= "
      • \n"; + } + $orderquestions .= "
    "; + } + + $orderquestions .= "
      "; + + for($i=0; $i < $questioncount ; $i++) //Assumes that all question orders start with 0 + { + $downdisabled = ""; + $updisabled = ""; + //Check if question is relied on as a condition dependency by the next question, and if so, don't allow moving down + if ( !is_null($questdepsarray) && $i < $questioncount-1 && + array_key_exists($oqarray[$i+1]['qid'],$questdepsarray) && + array_key_exists($oqarray[$i]['qid'],$questdepsarray[$oqarray[$i+1]['qid']]) ) + { + $downdisabled = "disabled=\"true\" class=\"disabledbtn\""; + } + //Check if question has a condition dependency on the preceding question, and if so, don't allow moving up + if ( !is_null($questdepsarray) && $i !=0 && + array_key_exists($oqarray[$i]['qid'],$questdepsarray) && + array_key_exists($oqarray[$i-1]['qid'],$questdepsarray[$oqarray[$i]['qid']]) ) + { + $updisabled = "disabled=\"true\" class=\"disabledbtn\""; + } + + //Move to location + $orderquestions.="
    • \n" ; + $orderquestions.="\t\n"; + + $orderquestions.= "\t\n"; + if ($i < $questioncount-1) + { + // Fill the sortorder hiddenfield so we know what field is moved down + $orderquestions.= "\t\n"; + } + $orderquestions.= "".$oqarray[$i]['title'].": ".$oqarray[$i]['question']; + $orderquestions.= "
    • \n" ; + } + + $orderquestions.="
    \n" + . "\n" + . "\n" + . "\t" + . "\t" + . "
    " ; + $orderquestions .="
    " ; +} + +function questionjavascript($type, $qattributes) +{ + $newquestionoutput = "\n"; + + return $newquestionoutput; +} + + +?> diff --git a/include/limesurvey/admin/quota.php b/include/limesurvey/admin/quota.php index aa39df9f..b322c2d7 100644 --- a/include/limesurvey/admin/quota.php +++ b/include/limesurvey/admin/quota.php @@ -10,7 +10,7 @@ * other free or open source software licenses. * See COPYRIGHT.php for copyright notices and details. * -* $Id: questionquota.php 3571 2007-12-19 10:32:25Z machaven $ +* $Id: quota.php 7132 2009-06-17 14:18:05Z c_schmitz $ */ include_once("login_check.php"); //Login Check dies also if the script is started directly @@ -68,6 +68,34 @@ function getQuotaAnswers($qid,$surveyid,$quota_id) } } + if ($qtype['type'] == 'L' || $qtype['type'] == 'O' || $qtype['type'] == '!') + { + $query = "SELECT * FROM ".db_table_name('quota_members')." WHERE sid='{$surveyid}' and qid='{$qid}' and quota_id='{$quota_id}'"; + $result = db_execute_assoc($query) or safe_die($connect->ErrorMsg()); + + $query = "SELECT code,answer FROM ".db_table_name('answers')." WHERE qid='{$qid}'"; + $ansresult = db_execute_assoc($query) or safe_die($connect->ErrorMsg()); + + $answerlist = array(); + + while ($dbanslist = $ansresult->FetchRow()) + { + $answerlist[$dbanslist['code']] = array('Title'=>$qtype['title'], + 'Display'=>substr($dbanslist['answer'],0,40), + 'code'=>$dbanslist['code']); + } + + if ($result->RecordCount() > 0) + { + while ($quotalist = $result->FetchRow()) + { + $answerlist[$quotalist['code']]['rowexists'] = '1'; + } + + } + + } + if ($qtype['type'] == 'A') { $query = "SELECT * FROM ".db_table_name('quota_members')." WHERE sid='{$surveyid}' and qid='{$qid}' and quota_id='{$quota_id}'"; @@ -188,20 +216,119 @@ if($sumrows5['edit_survey_property'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) if (!isset($quotasoutput)) $quotasoutput = ""; if($subaction == "insertquota") { + if(!isset($_POST['quota_limit']) || $_POST['quota_limit'] < 1) + { + $_POST['quota_limit'] = 1; + } $_POST = array_map('db_quote', $_POST); - $query = "INSERT INTO ".db_table_name('quota')." (sid,name,qlimit,action) VALUES ('$surveyid','{$_POST['quota_name']}','{$_POST['quota_limit']}','{$_POST['quota_action']}')"; - $connect->Execute($query) or safe_die($connect->ErrorMsg()); + $query = "INSERT INTO ".db_table_name('quota')." (sid,name,qlimit,action,autoload_url) + VALUES ('$surveyid','{$_POST['quota_name']}','{$_POST['quota_limit']}','1', '1')"; + $connect->Execute($query) or safe_die("Error inserting limit".$connect->ErrorMsg()); + $quotaid=$connect->Insert_Id(db_table_name_nq('quota'),"id"); + + //Get the languages used in this survey + $langs = GetAdditionalLanguagesFromSurveyID($surveyid); + $baselang = GetBaseLanguageFromSurveyID($surveyid); + $langs[] = $baselang; + //Iterate through each language, and make sure there is a quota message for it + $errorstring = ''; + foreach ($langs as $lang) + { + if (!$_POST['quotals_message_'.$lang]) { $errorstring.= GetLanguageNameFromCode($lang,false)."\\n";} + } + if ($errorstring!='') + { + $databaseoutput .= "\n"; + } + else + //All the required quota messages exist, now we can insert this info into the database + { + require_once("../classes/inputfilter/class.inputfilter_clean.php"); + $myFilter = new InputFilter('','',1,1,1); + + foreach ($langs as $lang) //Iterate through each language + { + //Clean XSS + if ($filterxsshtml) + { + $_POST['quotals_message_'.$lang]=$myFilter->process($_POST['quotals_message_'.$lang]); + } + else + { + $_POST['quotals_message_'.$lang] = html_entity_decode($_POST['quotals_message_'.$lang], ENT_QUOTES, "UTF-8"); + } + + // Fix bug with FCKEditor saving strange BR types + $_POST['quotals_message_'.$lang]=fix_FCKeditor_text($_POST['quotals_message_'.$lang]); + + include_once(dirname(__FILE__) . '/../quexs.php'); + + //Now save the language to the database: + $query = "INSERT INTO ".db_table_name('quota_languagesettings')." (quotals_quota_id, quotals_language, quotals_name, quotals_message, quotals_url, quotals_urldescrip) + VALUES ('$quotaid', '$lang', '".db_quote($_POST['quota_name'])."', '".db_quote($_POST['quotals_message_'.$lang])."', '".QUEXS_URL."rs_quota_end.php', '".QUEXS_URL."rs_quota_end.php')"; + $connect->Execute($query) or safe_die($connect->ErrorMsg()); + } + } //End insert language based components $viewquota = "1"; - } + } //End foreach $lang if($subaction == "modifyquota") { $_POST = array_map('db_quote', $_POST); - $query = "UPDATE ".db_table_name('quota')." SET name='{$_POST['quota_name']}', qlimit='{$_POST['quota_limit']}', action='{$_POST['quota_action']}' where id='{$_POST['quota_id']}' "; - $connect->Execute($query) or safe_die($connect->ErrorMsg()); - $viewquota = "1"; + $query = "UPDATE ".db_table_name('quota')." + SET name='{$_POST['quota_name']}', + qlimit='{$_POST['quota_limit']}' + WHERE id='{$_POST['quota_id']}' "; + $connect->Execute($query) or safe_die("Error modifying quota".$connect->ErrorMsg()); + //Get the languages used in this survey + $langs = GetAdditionalLanguagesFromSurveyID($surveyid); + $baselang = GetBaseLanguageFromSurveyID($surveyid); + $langs[] = $baselang; + //Iterate through each language, and make sure there is a quota message for it + $errorstring = ''; + foreach ($langs as $lang) + { + if (!$_POST['quotals_message_'.$lang]) { $errorstring.= GetLanguageNameFromCode($lang,false)."\\n";} + } + if ($errorstring!='') + { + $databaseoutput .= "\n"; + } + else + //All the required quota messages exist, now we can insert this info into the database + { + require_once("../classes/inputfilter/class.inputfilter_clean.php"); + $myFilter = new InputFilter('','',1,1,1); + + foreach ($langs as $lang) //Iterate through each language + { + //Clean XSS + if ($filterxsshtml) + { + $_POST['quotals_message_'.$lang]=$myFilter->process($_POST['quotals_message_'.$lang]); + } + else + { + $_POST['quotals_message_'.$lang] = html_entity_decode($_POST['quotals_message_'.$lang], ENT_QUOTES, "UTF-8"); + } + + // Fix bug with FCKEditor saving strange BR types + $_POST['quotals_message_'.$lang]=fix_FCKeditor_text($_POST['quotals_message_'.$lang]); + + //Now save the language to the database: + $query = "UPDATE ".db_table_name('quota_languagesettings')." + SET quotals_name='".db_quote($_POST['quota_name'])."', + quotals_message='".db_quote($_POST['quotals_message_'.$lang])."' + WHERE quotals_quota_id = '{$_POST['quota_id']}' + AND quotals_language = '$lang'"; + $connect->Execute($query) or safe_die($connect->ErrorMsg()); + } + } //End insert language based components + + + $viewquota = "1"; } if($subaction == "insertquotaanswer") @@ -216,29 +343,35 @@ if($sumrows5['edit_survey_property'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) if($subaction == "quota_delans") { $_POST = array_map('db_quote', $_POST); - $query = "DELETE FROM ".db_table_name('quota_members')." WHERE qid='{$_POST['quota_qid']}' and code='{$_POST['quota_anscode']}'"; + $query = "DELETE FROM ".db_table_name('quota_members')." + WHERE id = '{$_POST['quota_member_id']}' + AND qid='{$_POST['quota_qid']}' and code='{$_POST['quota_anscode']}'"; $connect->Execute($query) or safe_die($connect->ErrorMsg()); $viewquota = "1"; } - if($subaction == "quota_delquota") { $_POST = array_map('db_quote', $_POST); $query = "DELETE FROM ".db_table_name('quota')." WHERE id='{$_POST['quota_id']}'"; $connect->Execute($query) or safe_die($connect->ErrorMsg()); + $query = "DELETE FROM ".db_table_name('quota_languagesettings')." WHERE quotals_quota_id='{$_POST['quota_id']}'"; + $connect->Execute($query) or safe_die($connect->ErrorMsg()); + $query = "DELETE FROM ".db_table_name('quota_members')." WHERE quota_id='{$_POST['quota_id']}'"; $connect->Execute($query) or safe_die($connect->ErrorMsg()); $viewquota = "1"; - } if ($subaction == "quota_editquota") { + if (isset($_GET['quota_id'])) $_POST['quota_id'] = $_GET['quota_id']; $_POST = array_map('db_quote', $_POST); - $query = "SELECT * FROM ".db_table_name('quota')." where id='{$_POST['quota_id']}'"; + + $query = "SELECT * FROM ".db_table_name('quota')." + WHERE id='{$_POST['quota_id']}'"; $result = db_execute_assoc($query) or safe_die($connect->ErrorMsg()); $quotainfo = $result->FetchRow(); @@ -263,19 +396,57 @@ if($sumrows5['edit_survey_property'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1)
    - -
    -

    '.$clang->gT("Quota Action").':

    -
    - - + + + + + '; + $langs = GetAdditionalLanguagesFromSurveyID($surveyid); + $baselang = GetBaseLanguageFromSurveyID($surveyid); + array_push($langs,$baselang); + + require_once("../classes/inputfilter/class.inputfilter_clean.php"); + $myFilter = new InputFilter('','',1,1,1); + + $quotasoutput .= ' +
    '."\n\n"; + foreach ($langs as $lang) + { + //Get this one + $langquery = "SELECT * FROM ".db_table_name('quota_languagesettings')." WHERE quotals_quota_id='{$_POST['quota_id']}' AND quotals_language = '$lang'"; + $langresult = db_execute_assoc($langquery) or safe_die($connect->ErrorMsg()); + $langquotainfo = $langresult->FetchRow(); + $quotasoutput .= ' +
    +

    '.GetLanguageNameFromCode($lang,false); + if ($lang==$baselang) {$quotasoutput .= '('.$clang->gT("Base Language").')';} + $quotasoutput .= "

    "; + + $quotasoutput.=' + + + + +
    + + + + + + + +
    +

    '.$clang->gT("Quota message").':

    +
    +
    +
    '; + }; + $quotasoutput .= ' + + +
    + +
     
    @@ -297,10 +468,16 @@ if($sumrows5['edit_survey_property'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1)
    '; } + $totalquotas=0; + $totalcompleted=0; + $csvoutput=array(); if (($action == "quotas" && !isset($subaction)) || isset($viewquota)) { - $query = "SELECT * FROM ".db_table_name('quota')." where sid='".$surveyid."'"; + $query = "SELECT * FROM ".db_table_name('quota')." , ".db_table_name('quota_languagesettings')." + WHERE ".db_table_name('quota').".id = ".db_table_name('quota_languagesettings').".quotals_quota_id + AND sid='".$surveyid."' + AND quotals_language = '".$baselang."'"; $result = db_execute_assoc($query) or safe_die($connect->ErrorMsg()); $quotasoutput .=' @@ -326,7 +503,7 @@ if($sumrows5['edit_survey_property'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) while ($quotalisting = $result->FetchRow()) { $quotasoutput .=' - + - +
    '.$quotalisting['name'].''.$quotalisting['name'].' '; if ($quotalisting['active'] == 1) { @@ -342,9 +519,15 @@ if($sumrows5['edit_survey_property'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) } elseif ($quotalisting['action'] == 2) { $quotasoutput .= $clang->gT("Terminate Survey With Warning"); } + $totalquotas+=$quotalisting['qlimit']; + $completed=get_quotaCompletedCount($surveyid, $quotalisting['id']); + $highlight=($completed >= $quotalisting['qlimit']) ? "" : "style='color: red'"; //Incomplete quotas displayed in red + $totalcompleted=$totalcompleted+$completed; + $csvoutput[]=$quotalisting['name'].",".$quotalisting['qlimit'].",".$completed.",".($quotalisting['qlimit']-$completed)."\r\n"; + $quotasoutput .=' '.$quotalisting['qlimit'].'N/A'.$completed.' - + + + + + + + + + - - - - + + +
    @@ -396,6 +579,7 @@ if($sumrows5['edit_survey_property'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) + @@ -418,16 +602,24 @@ if($sumrows5['edit_survey_property'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) } $quotasoutput .='
    +    '.$totalquotas.' 
            '.$totalquotas.''.$totalcompleted.'
    @@ -436,12 +628,22 @@ if($sumrows5['edit_survey_property'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1)
    '; } - + if(isset($_GET['quickreport']) && $_GET['quickreport']) + { + header("Content-Disposition: attachment; filename=results-survey".$surveyid.".csv"); + header("Content-type: text/comma-separated-values; charset=UTF-8"); + echo $clang->gT("Quota Name").",".$clang->gT("Limit").",".$clang->gT("Completed").",".$clang->gT("Remaining")."\r\n"; + foreach($csvoutput as $line) + { + echo $line; + } + die; + } if($subaction == "new_answer" || ($subaction == "new_answer_two" && !isset($_POST['quota_qid']))) { if ($subaction == "new_answer_two") $_POST['quota_id'] = $_POST['quota_id']; - $allowed_types = "(type ='G' or type ='M' or type ='Y' or type ='A' or type ='B' or type ='I')"; + $allowed_types = "(type ='G' or type ='M' or type ='Y' or type ='A' or type ='B' or type ='I' or type = 'L' or type='O' or type='!')"; $query = "SELECT qid, title, question FROM ".db_table_name('questions')." WHERE $allowed_types AND sid='$surveyid' AND language='{$baselang}'"; $result = db_execute_assoc($query) or safe_die($connect->ErrorMsg()); if ($result->RecordCount() == 0) @@ -534,7 +736,7 @@ if($sumrows5['edit_survey_property'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1)
    '; } else { - $quotasoutput .='
    + $quotasoutput .='
    @@ -585,8 +787,8 @@ if($sumrows5['edit_survey_property'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) if ($subaction == "new_quota") { - $quotasoutput .=' - + $quotasoutput .=''; + $quotasoutput.='
    + +
    @@ -598,38 +800,66 @@ if($sumrows5['edit_survey_property'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) - + - + - - - - - - - +

    '.$clang->gT("Quota Name").':

    '.$clang->gT("Quota Limit").':

    -

    '.$clang->gT("Quota Action").':

    -
      - - - +
    + '; - + $langs = GetAdditionalLanguagesFromSurveyID($surveyid); + $baselang = GetBaseLanguageFromSurveyID($surveyid); + array_push($langs,$baselang); + + require_once("../classes/inputfilter/class.inputfilter_clean.php"); + $myFilter = new InputFilter('','',1,1,1); + + $thissurvey=getSurveyInfo($surveyid); + + $quotasoutput .= ' +
    '."\n\n"; + foreach ($langs as $lang) + { + $quotasoutput .= ' +
    +

    '.GetLanguageNameFromCode($lang,false); + if ($lang==$baselang) {$quotasoutput .= '('.$clang->gT("Base Language").')';} + $quotasoutput .= "

    "; + $quotasoutput.=' + + + -
    + + + + +
    +

    '.$clang->gT("Quota message").':

    +
    '; +
    + '; + }; + + $quotasoutput .= ' + + + + + + '; } } diff --git a/include/limesurvey/admin/remotecontrol/groups/BIO.csv b/include/limesurvey/admin/remotecontrol/groups/BIO.csv new file mode 100644 index 00000000..4ad7bb8f --- /dev/null +++ b/include/limesurvey/admin/remotecontrol/groups/BIO.csv @@ -0,0 +1,41 @@ +# LimeSurvey Group Dump +# DBVersion 130 +# This is a dumped group from the LimeSurvey Script +# http://www.limesurvey.org/ +# Do not change this header! + +# +# GROUPS TABLE +# +"gid","sid","group_name","group_order","description","language" +"43","10","Student BIO","6","Fragebogen für Biologistudenten
    ","de" + +# +# QUESTIONS TABLE +# +"qid","sid","gid","type","title","question","preg","help","other","mandatory","lid","lid1","question_order","language" +"211","10","43","L","1","Tragen Sie Biolatschen?
    ","","","N","N","0","0","1","de" + +# +# ANSWERS TABLE +# +"qid","code","answer","default_value","sortorder","language" +"211","1","ja","N","1","de" +"211","2","nein","N","2","de" +"211","3","geht dich nix an!","Y","3","de" + +# +# CONDITIONS TABLE +# + +# +# LABELSETS TABLE +# + +# +# LABELS TABLE +# + +# +# QUESTION_ATTRIBUTES TABLE +# diff --git a/include/limesurvey/admin/remotecontrol/groups/BWL.csv b/include/limesurvey/admin/remotecontrol/groups/BWL.csv new file mode 100644 index 00000000..a6052e32 --- /dev/null +++ b/include/limesurvey/admin/remotecontrol/groups/BWL.csv @@ -0,0 +1,43 @@ +# LimeSurvey Group Dump +# DBVersion 130 +# This is a dumped group from the LimeSurvey Script +# http://www.limesurvey.org/ +# Do not change this header! + +# +# GROUPS TABLE +# +"gid","sid","group_name","group_order","description","language" +"41","10","Student BWL","4","Fragemodul für BWL Studenten
    ","de" + +# +# QUESTIONS TABLE +# +"qid","sid","gid","type","title","question","preg","help","other","mandatory","lid","lid1","question_order","language" +"213","10","41","L","1","Wieviel ist Ihr Auto noch wert?
    ","","","N","N","0","0","1","de" + +# +# ANSWERS TABLE +# +"qid","code","answer","default_value","sortorder","language" +"213","1","nicht mehr als 1000€","N","1","de" +"213","2","nicht mehr als 10.000€","N","2","de" +"213","3","nicht mehr als 30.000€","N","3","de" +"213","4","keine Ahnung, hab ich von Papa","N","4","de" +"213","5","das Auto gehört zum Chauffeuerdienst","N","5","de" + +# +# CONDITIONS TABLE +# + +# +# LABELSETS TABLE +# + +# +# LABELS TABLE +# + +# +# QUESTION_ATTRIBUTES TABLE +# diff --git a/include/limesurvey/admin/remotecontrol/groups/Empty.csv b/include/limesurvey/admin/remotecontrol/groups/Empty.csv new file mode 100644 index 00000000..c4b3d992 --- /dev/null +++ b/include/limesurvey/admin/remotecontrol/groups/Empty.csv @@ -0,0 +1,35 @@ +# LimeSurvey Group Dump +# DBVersion 133 +# This is a dumped group from the LimeSurvey Script +# http://www.limesurvey.org/ +# Do not change this header! + +# +# GROUPS TABLE +# +"gid","sid","group_name","group_order","description","language" +"562","666","Zusätzliche Fragen","1","","de" + +# +# QUESTIONS TABLE +# + +# +# ANSWERS TABLE +# + +# +# CONDITIONS TABLE +# + +# +# LABELSETS TABLE +# + +# +# LABELS TABLE +# + +# +# QUESTION_ATTRIBUTES TABLE +# diff --git a/include/limesurvey/admin/remotecontrol/groups/INF.csv b/include/limesurvey/admin/remotecontrol/groups/INF.csv new file mode 100644 index 00000000..3f8e47c7 --- /dev/null +++ b/include/limesurvey/admin/remotecontrol/groups/INF.csv @@ -0,0 +1,43 @@ +# LimeSurvey Group Dump +# DBVersion 130 +# This is a dumped group from the LimeSurvey Script +# http://www.limesurvey.org/ +# Do not change this header! + +# +# GROUPS TABLE +# +"gid","sid","group_name","group_order","description","language" +"42","10","Student INF","5","Fragebogen für Informatik Studenten
    ","de" + +# +# QUESTIONS TABLE +# +"qid","sid","gid","type","title","question","preg","help","other","mandatory","lid","lid1","question_order","language" +"212","10","42","L","1","Vieviele Computer haben Sie zu Hause?
    ","","Taschenrechner und Smartphones zählen nicht mit
    ","N","N","0","0","1","de" + +# +# ANSWERS TABLE +# +"qid","code","answer","default_value","sortorder","language" +"212","1","keinen","N","1","de" +"212","2","einen","N","2","de" +"212","3","mehr als einen","N","3","de" +"212","4","mehr als 5","N","4","de" +"212","5","da muß ich erstmal zählen gehen","N","5","de" + +# +# CONDITIONS TABLE +# + +# +# LABELSETS TABLE +# + +# +# LABELS TABLE +# + +# +# QUESTION_ATTRIBUTES TABLE +# diff --git a/include/limesurvey/locale/th/index.html b/include/limesurvey/admin/remotecontrol/groups/index.html similarity index 100% rename from include/limesurvey/locale/th/index.html rename to include/limesurvey/admin/remotecontrol/groups/index.html diff --git a/include/limesurvey/admin/scripts/fckeditor.26/editor/dialog/fck_spellerpages/spellerpages/blank.html b/include/limesurvey/admin/remotecontrol/index.html similarity index 100% rename from include/limesurvey/admin/scripts/fckeditor.26/editor/dialog/fck_spellerpages/spellerpages/blank.html rename to include/limesurvey/admin/remotecontrol/index.html diff --git a/include/limesurvey/admin/remotecontrol/lsrc.config.php b/include/limesurvey/admin/remotecontrol/lsrc.config.php new file mode 100644 index 00000000..6c468e25 --- /dev/null +++ b/include/limesurvey/admin/remotecontrol/lsrc.config.php @@ -0,0 +1,79 @@ + \ No newline at end of file diff --git a/include/limesurvey/admin/remotecontrol/lsrc.helper.php b/include/limesurvey/admin/remotecontrol/lsrc.helper.php new file mode 100644 index 00000000..29e7df68 --- /dev/null +++ b/include/limesurvey/admin/remotecontrol/lsrc.helper.php @@ -0,0 +1,3987 @@ +surveyExists($iVid)) + { + $query2num = "SELECT owner_id FROM {$dbprefix}surveys WHERE sid=".sanitize_int($iVid).""; + $rs = db_execute_assoc($query2num); + $field=$rs->FetchRow(); + return $field['owner_id']; + + }else{return false;} + } + + /** + * This function changes data in LS-DB, its very sensitive, because every table can be changed. + * + * @param unknown_type $table + * @param unknown_type $key + * @param unknown_type $value + * @param unknown_type $where + * @return String + */ + function changeTable($table, $key, $value, $where, $mode='0')//XXX + {//be aware that this function may be a security risk + + global $connect ; + // global $dbprefix ; + $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC; + include("lsrc.config.php"); + if($mode=='' || !isset($mode) || $mode=='0') + { + $where = str_replace("\\","",$where); + $query2num = "SELECT {$key} FROM {$dbprefix}{$table} WHERE {$where}"; + $rs = db_execute_assoc($query2num); + + $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", OK ($query2num)"); + + $query2update = "update ".$dbprefix.$table." set ".$key."='".$value."' where ".$where.""; + + $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", OK ($query2update)"); + + if($connect->Execute($query2update)){ + return $rs->RecordCount()." Rows changed"; + } + else{ + return "nothing changed"; + } + } + if($mode==1 || $mode=='1') + { + $query2insert = "INSERT INTO {$dbprefix}{$table} ({$key}) VALUES ({$value});"; + $this->debugLsrc("wir sind in Line ".__LINE__.", inserting ($query2insert)"); + if($connect->Execute($query2insert)) + { + $this->debugLsrc("wir sind in Line ".__LINE__.", inserting OK"); + return true; + + } + else + { + return false; + } + } + + + } + + /** + * + * Enter description here... + * @param $surveyid + * @param $type + * @param $maxLsrcEmails + * @return unknown_type + */ + function emailSender($surveyid, $type, $maxLsrcEmails='') //XXX + { + global $connect,$sitename ; + global $dbprefix ; + $surveyid = sanitize_int($surveyid); + include("lsrc.config.php"); + $lsrcHelper= new LsrcHelper(); + + + // wenn maxmails ber den lsrc gegeben wird das nutzen, ansonsten die default werte aus der config.php + if($maxLsrcEmails!='') + $maxemails = $maxLsrcEmails; + + switch ($type){ + case "custom": + + break; + case "invite": + $lsrcHelper->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", START invite "); + + + + if(isset($surveyid) && getEmailFormat($surveyid) == 'html') + { + $ishtml=true; + } + else + { + $ishtml=false; + } + + //$tokenoutput .= ("Sending Invitations"); + //if (isset($tokenid)) {$tokenoutput .= " (".("Sending to Token ID").": {$tokenid})";} + //$tokenoutput .= "\n"; + $lsrcHelper->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", $surveyid, $type"); + // Texte für Mails aus der Datenbank holen und in die POST Dinger schreiben. Nicht schön aber praktikabel + + $sql = "SELECT surveyls_language, surveyls_email_invite_subj, surveyls_email_invite ". + "FROM {$dbprefix}surveys_languagesettings ". + "WHERE surveyls_survey_id = ".$surveyid." "; + + //GET SURVEY DETAILS + $thissurvey=getSurveyInfo($surveyid); + + // $connect->SetFetchMode(ADODB_FETCH_ASSOC); + // $sqlResult=$connect->Execute($sql); + $sqlResult = db_execute_assoc($sql); + + $lsrcHelper->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", invite "); + + while($languageRow = $sqlResult->FetchRow()) + { + $_POST['message_'.$languageRow['surveyls_language']] = $languageRow['surveyls_email_invite']; + $_POST['subject_'.$languageRow['surveyls_language']] = $languageRow['surveyls_email_invite_subj']; + } + + // if (isset($_POST['bypassbademails']) && $_POST['bypassbademails'] == 'Y') + // { + // $SQLemailstatuscondition = " AND emailstatus = 'OK'"; + // } + // else + // { + // $SQLemailstatuscondition = ""; + // } + $lsrcHelper->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", invite "); + $ctquery = "SELECT * FROM ".db_table_name("tokens_{$surveyid}")." WHERE ((completed ='N') or (completed='')) AND ((sent ='N') or (sent='')) AND token !='' AND email != '' "; + + if (isset($tokenid)) {$ctquery .= " AND tid='{$tokenid}'";} + //$tokenoutput .= "\n"; + $ctresult = $connect->Execute($ctquery); + $ctcount = $ctresult->RecordCount(); + $ctfieldcount = $ctresult->FieldCount(); + + $emquery = "SELECT * "; + //if ($ctfieldcount > 7) {$emquery .= ", attribute_1, attribute_2";} + + $lsrcHelper->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", invite "); + + $emquery .= " FROM ".db_table_name("tokens_{$surveyid}")." WHERE ((completed ='N') or (completed='')) AND ((sent ='N') or (sent='')) AND token !='' AND email != '' "; + + if (isset($tokenid)) {$emquery .= " and tid='{$tokenid}'";} + //$tokenoutput .= "\n\n\n\n"; + $emresult = db_select_limit_assoc($emquery,$maxemails); + $emcount = $emresult->RecordCount(); + + //$tokenoutput .= "\n" + ////."\t\n" + //."\t\t
    \n"; + + $surveylangs = GetAdditionalLanguagesFromSurveyID($surveyid); + $baselanguage = GetBaseLanguageFromSurveyID($surveyid); + array_unshift($surveylangs,$baselanguage); + + $lsrcHelper->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", invite "); + + foreach ($surveylangs as $language) + { + $_POST['message_'.$language]=auto_unescape($_POST['message_'.$language]); + $_POST['subject_'.$language]=auto_unescape($_POST['subject_'.$language]); + if ($ishtml) $_POST['message_'.$language] = html_entity_decode($_POST['message_'.$language], ENT_QUOTES, $emailcharset); + + } + + $lsrcHelper->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", invite "); + if ($emcount > 0) + { + $mailsSend = 0; + while ($emrow = $emresult->FetchRow()) + { + $c=1; + unset($fieldsarray); + $to = $emrow['email']; + $fieldsarray["{EMAIL}"]=$emrow['email']; + $fieldsarray["{FIRSTNAME}"]=$emrow['firstname']; + $fieldsarray["{LASTNAME}"]=$emrow['lastname']; + $fieldsarray["{TOKEN}"]=$emrow['token']; + $fieldsarray["{LANGUAGE}"]=$emrow['language']; + while(isset($emrow["attribute_$c"])) + { + $fieldsarray["{ATTRIBUTE_$c}"]=$emrow["attribute_$c"]; + ++$c; + } + $fieldsarray["{ADMINNAME}"]= $thissurvey['adminname']; + $fieldsarray["{ADMINEMAIL}"]=$thissurvey['adminemail']; + $fieldsarray["{SURVEYNAME}"]=$thissurvey['name']; + $fieldsarray["{SURVEYDESCRIPTION}"]=$thissurvey['description']; + $fieldsarray["{EXPIRY}"]=$thissurvey["expiry"]; + $fieldsarray["{EXPIRY-DMY}"]=date("d-m-Y",strtotime($thissurvey["expiry"])); + $fieldsarray["{EXPIRY-MDY}"]=date("m-d-Y",strtotime($thissurvey["expiry"])); + + $emrow['language']=trim($emrow['language']); + if ($emrow['language']=='') {$emrow['language']=$baselanguage;} //if language is not give use default + $found = array_search($emrow['language'], $surveylangs); + if ($found==false) {$emrow['language']=$baselanguage;} + + $from = $thissurvey['adminemail']; + + + if ($ishtml === false) + { + if ( $modrewrite ) + { + $fieldsarray["{SURVEYURL}"]="$publicurl/$surveyid/lang-".trim($emrow['language'])."/tk-{$emrow['token']}"; + } + else + { + $fieldsarray["{SURVEYURL}"]="$publicurl/index.php?lang=".trim($emrow['language'])."&sid=$surveyid&token={$emrow['token']}"; + } + } + else + { + if ( $modrewrite ) + { + $fieldsarray["{SURVEYURL}"]="".htmlspecialchars("$publicurl/$surveyid/lang-".trim($emrow['language'])."/tk-{$emrow['token']}").""; + } + else + { + $fieldsarray["{SURVEYURL}"]="".htmlspecialchars("$publicurl/index.php?lang=".trim($emrow['language'])."&sid=$surveyid&token={$emrow['token']}").""; + } + } + $lsrcHelper->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", invite "); + $modsubject=Replacefields($_POST['subject_'.$emrow['language']], $fieldsarray); + $modmessage=Replacefields($_POST['message_'.$emrow['language']], $fieldsarray); + + if (MailTextMessage($modmessage, $modsubject, $to , $from, $sitename, $ishtml, getBounceEmail($surveyid))) + { + // Put date into sent + $timeadjust = 0; + $today = date("Y-m-d H:i"); + $lsrcHelper->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", invite Today:".$today); + $udequery = "UPDATE ".db_table_name("tokens_{$surveyid}")."\n" + ."SET sent='$today' WHERE tid={$emrow['tid']}"; + // + $uderesult = $connect->Execute($udequery); + $mailsSend++; + //$tokenoutput .= "[".("Invitation sent to:")."{$emrow['firstname']} {$emrow['lastname']} ($to)]\n"; + } + else + { + //$tokenoutput .= ReplaceFields(("Email to {FIRSTNAME} {LASTNAME} ({EMAIL}) failed. Error Message:")." ".$maildebug."", $fieldsarray); + if($n==1) + $failedAddresses .= ",".$to; + else + { + $failedAddresses = $to; + $n=1; + } + } + } + $lsrcHelper->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", invite "); + if ($ctcount > $emcount) + { + $lefttosend = $ctcount-$maxemails; + + }else{$lefttosend = 0;} + } + else + { + return "No Mails to send"; + } + + if($maxemails>0 && $maxemails!='') + { + $returnValue = "".$mailsSend." Mails send. ".$lefttosend." Mails left to send"; + if(isset($failedAddresses)) + $returnValue .= "\nCould not send to: ".$failedAddresses; + return $returnValue; + } + + if(isset($mailsSend)) + { + $returnValue = "".$mailsSend." Mails send. "; + if(isset($failedAddresses)) + $returnValue .= "\nCould not send to: ".$failedAddresses; + return $returnValue; + } + + + + + break; + case "remind": + // XXX: + // TODO: + // if (!isset($_POST['ok']) || !$_POST['ok']) + // { + + /* + * look if there were reminders send in the past, and if some tokens got lesser reminders than others + * + * - if so: send reminders to the unremindet participants until they got the same remindcount than the others + * - if not: send reminders normally + */ + + $remSQL = "SELECT tid, remindercount " + . "FROM ".db_table_name("tokens_{$surveyid}")." " + . "WHERE (completed = 'N' or completed = '') AND sent <> 'N' and sent <>'' AND token <>'' AND EMAIL <>'' " + . "ORDER BY remindercount desc LIMIT 1"; + $remResult = db_execute_assoc($remSQL); + $remRow = $remResult->FetchRow(); + + $lsrcHelper->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", remind ".$remRow['tid']."; ".$remRow['remindercount']." "); + + $sendOnlySQL = "SELECT tid, remindercount " + . "FROM ".db_table_name("tokens_{$surveyid}")." " + . "WHERE (completed = 'N' or completed = '') AND sent <> 'N' and sent <>'' AND token <>'' AND EMAIL <>'' AND remindercount < ".$remRow['remindercount']." " + . "ORDER BY tid asc LIMIT 1"; + $sendOnlyResult = db_execute_assoc($sendOnlySQL); + + + + if($sendOnlyResult->RecordCount()>0) + { + $sendOnlyRow = $sendOnlyResult->FetchRow(); + $starttokenid = $sendOnlyRow['tid']; + $lsrcHelper->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", remind ".$sendOnlyRow['tid']."; ".$sendOnlyRow['remindercount']." "); + } + + if(isset($surveyid) && getEmailFormat($surveyid) == 'html') + { + $ishtml=true; + } + else + { + $ishtml=false; + } + + //GET SURVEY DETAILS + $thissurvey=getSurveyInfo($surveyid); + + $lsrcHelper->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", $surveyid, $type"); + // Texte für Mails aus der Datenbank holen. + + $sql = "SELECT surveyls_language, surveyls_email_remind_subj, surveyls_email_remind ". + "FROM {$dbprefix}surveys_languagesettings ". + "WHERE surveyls_survey_id = ".$surveyid." "; + + $lsrcHelper->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", remind "); + + $sqlResult = db_execute_assoc($sql); + + while($languageRow = $sqlResult->FetchRow()) + { + $_POST['message_'.$languageRow['surveyls_language']] = $languageRow['surveyls_email_remind']; + $_POST['subject_'.$languageRow['surveyls_language']] = $languageRow['surveyls_email_remind_subj']; + } + $lsrcHelper->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", remind "); + //$tokenoutput .= ("Sending Reminders")."\n"; + + $surveylangs = GetAdditionalLanguagesFromSurveyID($surveyid); + $baselanguage = GetBaseLanguageFromSurveyID($surveyid); + array_unshift($surveylangs,$baselanguage); + + foreach ($surveylangs as $language) + { + $_POST['message_'.$language]=auto_unescape($_POST['message_'.$language]); + $_POST['subject_'.$language]=auto_unescape($_POST['subject_'.$language]); + + } + $lsrcHelper->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", remind "); + $SQLemailstatuscondition = " AND emailstatus = 'OK'"; + + if (isset($_POST['maxremindercount']) && + $_POST['maxremindercount'] != '' && + intval($_POST['maxremindercount']) != 0) + { + $SQLremindercountcondition = " AND remindercount < ".intval($_POST['maxremindercount']); + } + else + { + $SQLremindercountcondition = ""; + } + $lsrcHelper->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", remind "); + if (isset($_POST['minreminderdelay']) && + $_POST['minreminderdelay'] != '' && + intval($_POST['minreminderdelay']) != 0) + { + // $_POST['minreminderdelay'] in days (86400 seconds per day) + $compareddate = date_shift( + date("Y-m-d H:i:s",time() - 86400 * intval($_POST['minreminderdelay'])), + "Y-m-d H:i", + $timeadjust); + $SQLreminderdelaycondition = " AND ( " + . " (remindersent = 'N' AND sent < '".$compareddate."') " + . " OR " + . " (remindersent < '".$compareddate."'))"; + } + else + { + $SQLreminderdelaycondition = ""; + } + $lsrcHelper->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", remind "); + + $ctquery = "SELECT * FROM ".db_table_name("tokens_{$surveyid}")." WHERE (completed ='N' or completed ='') AND sent<>'' AND sent<>'N' AND token <>'' AND email <> '' $SQLemailstatuscondition $SQLremindercountcondition $SQLreminderdelaycondition"; + + if (isset($starttokenid)) {$ctquery .= " AND tid >= '{$starttokenid}'";} + // if (isset($tokenid) && $tokenid) {$ctquery .= " AND tid = '{$tokenid}'";} + // //$tokenoutput .= "\n"; + + $ctresult = $connect->Execute($ctquery) or $this->debugLsrc ("Database error!\n" . $connect->ErrorMsg()); + $ctcount = $ctresult->RecordCount(); + $ctfieldcount = $ctresult->FieldCount(); + $emquery = "SELECT firstname, lastname, email, token, tid, language "; + if ($ctfieldcount > 7) {$emquery .= ", attribute_1, attribute_2";} + + $lsrcHelper->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", remind "); + + // TLR change to put date into sent + $emquery .= " FROM ".db_table_name("tokens_{$surveyid}")." WHERE (completed = 'N' or completed = '') AND sent <> 'N' and sent <>'' AND token <>'' AND EMAIL <>'' $SQLemailstatuscondition $SQLremindercountcondition $SQLreminderdelaycondition"; + + if (isset($starttokenid)) {$emquery .= " AND tid >= '{$starttokenid}'";} + if (isset($tokenid) && $tokenid) {$emquery .= " AND tid = '{$tokenid}'";} + $emquery .= " ORDER BY tid "; + + $lsrcHelper->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", remind, maxemails?: $maxemails, emquery: $emquery "); + + //$emresult = db_select_limit_assoc($emquery, $maxemails) or $this->debugLsrc ("Database error!\n" . $connect->ErrorMsg()); + $emresult = db_execute_assoc($emquery); + $emcount = $emresult->RecordCount() or $this->debugLsrc ("Database error!\n" . $connect->ErrorMsg()); + + $lsrcHelper->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", remind "); + + if ($emcount > 0) + { + while ($emrow = $emresult->FetchRow()) + { + $c=1; + unset($fieldsarray); + $to = $emrow['email']; + $fieldsarray["{EMAIL}"]=$emrow['email']; + $fieldsarray["{FIRSTNAME}"]=$emrow['firstname']; + $fieldsarray["{LASTNAME}"]=$emrow['lastname']; + $fieldsarray["{TOKEN}"]=$emrow['token']; + $fieldsarray["{LANGUAGE}"]=$emrow['language']; + while(isset($emrow["attribute_$c"])) + { + $fieldsarray["{ATTRIBUTE_$c}"]=$emrow["attribute_$c"]; + ++$c; + } + + $fieldsarray["{ADMINNAME}"]= $thissurvey['adminname']; + $fieldsarray["{ADMINEMAIL}"]=$thissurvey['adminemail']; + $fieldsarray["{SURVEYNAME}"]=$thissurvey['name']; + $fieldsarray["{SURVEYDESCRIPTION}"]=$thissurvey['description']; + $fieldsarray["{EXPIRY}"]=$thissurvey["expiry"]; + $fieldsarray["{EXPIRY-DMY}"]=date("d-m-Y",strtotime($thissurvey["expiry"])); + $fieldsarray["{EXPIRY-MDY}"]=date("m-d-Y",strtotime($thissurvey["expiry"])); + + $emrow['language']=trim($emrow['language']); + if ($emrow['language']=='') {$emrow['language']=$baselanguage;} //if language is not give use default + if(!in_array($emrow['language'], $surveylangs)) {$emrow['language']=$baselanguage;} // if given language is not available use default + $found = array_search($emrow['language'], $surveylangs); + if ($found==false) {$emrow['language']=$baselanguage;} + + $from = $thissurvey['adminemail']; //$from = $_POST['from_'.$emrow['language']]; + + + if (getEmailFormat($surveyid) == 'html') + { + $ishtml=true; + } + else + { + $ishtml=false; + } + + if ($ishtml == false) + { + if ( $modrewrite ) + { + $fieldsarray["{SURVEYURL}"]="$publicurl/$surveyid/lang-".trim($emrow['language'])."/tk-{$emrow['token']}"; + } + else + { + $fieldsarray["{SURVEYURL}"]="$publicurl/index.php?lang=".trim($emrow['language'])."&sid=$surveyid&token={$emrow['token']}"; + } + } + else + { + if ( $modrewrite ) + { + $fieldsarray["{SURVEYURL}"]="".htmlspecialchars("$publicurl/$surveyid/lang-".trim($emrow['language'])."/tk-{$emrow['token']}").""; + } + else + { + $fieldsarray["{SURVEYURL}"]="".htmlspecialchars("$publicurl/index.php?lang=".trim($emrow['language'])."&sid=$surveyid&token={$emrow['token']}").""; + $_POST['message_'.$emrow['language']] = html_entity_decode($_POST['message_'.$emrow['language']], ENT_QUOTES, $emailcharset); + } + } + + $msgsubject=Replacefields($_POST['subject_'.$emrow['language']], $fieldsarray); + $sendmessage=Replacefields($_POST['message_'.$emrow['language']], $fieldsarray); + + if (MailTextMessage($sendmessage, $msgsubject, $to, $from, $sitename, $ishtml, getBounceEmail($surveyid))) + { + + // Put date into remindersent + $today = date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i", $timeadjust); + $udequery = "UPDATE ".db_table_name("tokens_{$surveyid}")."\n" + ."SET remindersent='$today',remindercount = remindercount+1 WHERE tid={$emrow['tid']}"; + // + $uderesult = $connect->Execute($udequery) or $this->debugLsrc ("Could not update tokens$udequery".$connect->ErrorMsg()); + //orig: $tokenoutput .= "\t\t\t({$emrow['tid']})[".("Reminder sent to:")." {$emrow['firstname']} {$emrow['lastname']}]\n"; + //$tokenoutput .= "\t\t\t({$emrow['tid']}) [".("Reminder sent to:")." {$emrow['firstname']} {$emrow['lastname']} ($to)]\n"; + $mailsSend++; + } + else + { + //$tokenoutput .= ReplaceFields(("Email to {FIRSTNAME} {LASTNAME} ({EMAIL}) failed. Error Message:")." ".$maildebug."", $fieldsarray); + if($n==1) + $failedAddresses .= ",".$to; + else + { + $failedAddresses = $to; + $n=1; + } + + } + //$lasttid = $emrow['tid']; + + } + if ($ctcount > $emcount) + { + $lefttosend = $ctcount-$maxemails; + }else{$lefttosend = 0;} + } + else + { + return "No Reminders to send"; + } + + if($maxemails>0) + { + $returnValue = "".$mailsSend." Reminders send. ".$lefttosend." Reminders left to send"; + if(isset($failedAddresses)) + $returnValue .= "\nCould not send to: ".$failedAddresses; + return $returnValue; + } + + if(isset($mailsSend)) + { + $returnValue = "".$mailsSend." Reminders send. "; + if(isset($failedAddresses)) + $returnValue .= "\nCould not send to: ".$failedAddresses; + return $returnValue; + } + + + break; + default: + + break; + } + } + + /** + * loginCheck for Lsrc, checks if the user with given password exists in LS Database and + * sets the SESSION rights for this user + * @param String $sUser + * @param String $sPass + * @return boolean + */ + function checkUser($sUser, $sPass) // XXX + { + global $connect ; + global $dbprefix ; + $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC; + include("lsrc.config.php"); + require(dirname(__FILE__)."/../classes/core/sha256.php"); + + $query="SELECT uid, password, lang, superadmin FROM {$dbprefix}users WHERE users_name=".$connect->qstr(sanitize_user($sUser)); + // echo $query; + $result = db_execute_assoc($query); + $gv = $result->FetchRow(); + if($result->RecordCount() < 1) + { + return false; + } + else + { + if((SHA256::hashing($sPass)==$gv['password'])) + { + $_SESSION['loginID']=$gv['uid']; + $_SESSION['lang']=$gv['lang']; + + $squery = "SELECT create_survey, configurator, create_user, delete_user, superadmin, manage_template, manage_label FROM {$dbprefix}users WHERE uid={$gv['uid']}"; + $sresult = db_execute_assoc($squery); //Checked + if ($sresult->RecordCount()>0) + { + $fields = $sresult->FetchRow(); + $_SESSION['USER_RIGHT_CREATE_SURVEY'] = $fields['create_survey']; + $_SESSION['USER_RIGHT_CONFIGURATOR'] = $fields['configurator']; + $_SESSION['USER_RIGHT_CREATE_USER'] = $fields['create_user']; + $_SESSION['USER_RIGHT_DELETE_USER'] = $fields['delete_user']; + $_SESSION['USER_RIGHT_SUPERADMIN'] = $fields['superadmin']; + $_SESSION['USER_RIGHT_MANAGE_TEMPLATE'] = $fields['manage_template']; + $_SESSION['USER_RIGHT_MANAGE_LABEL'] = $fields['manage_label']; + } + return true; + } + else + { + return false; + } + } + } + + /** + * Lsrc checks the existence of Surveys more than one time, so this makes sense to be DRY + * + * @param int $sid + * @return boolean + */ + function surveyExists($sid)//XXX + { + global $connect ; + // global $dbprefix ; + $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC; + include("lsrc.config.php"); + + $query="SELECT * FROM {$dbprefix}surveys WHERE sid = ".$sid; + // echo $query; + $result = db_execute_assoc($query); + if($result->RecordCount() < 1) + { + return false; + } + else + { + return true; + } + } + + /** + * function to import surveys, based on new importsurvey.php 6979 2009-05-30 11:59:03Z c_schmitz $ + * + * @param unknown_type $iVid + * @param unknown_type $sVtit + * @param unknown_type $sVbes + * @return boolean + */ + function importSurvey($iVid, $sVtit , $sVbes, $sVwel, $sUbes, $sVtyp) //XXX + { + global $connect ; + // global $dbprefix ; + + include("lsrc.config.php"); + $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC; + $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", OK "); + // HINT FOR IMPORTERS: go to Line 714 to manipulate the Survey, while it's imported + + $the_full_file_path = $coreDir.$sVtyp.".csv"; + + $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.",the_full_file_path ='$the_full_file_path' OK "); + //$_SERVER['SERVER_NAME'] = ""; // just to avoid notices + //$_SERVER['SERVER_SOFTWARE'] = ""; // just to avoid notices + //require_once(dirname(__FILE__).'/../config-defaults.php'); + //require_once(dirname(__FILE__).'/../common.php'); + + + $handle = fopen($the_full_file_path, "r"); + while (!feof($handle)) + { + //To allow for very long survey lines (up to 64k) + $buffer = fgets($handle, 56550); + $bigarray[] = $buffer; + } + fclose($handle); +// foreach($bigarray as $ba) +// $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", OK ".$ba); + + if (isset($bigarray[0])) $bigarray[0]=$this->removeBOM($bigarray[0]); + // Now we try to determine the dataformat of the survey file. + + if (isset($bigarray[1]) && isset($bigarray[4])&& (substr($bigarray[1], 0, 22) == "# SURVEYOR SURVEY DUMP")&& (substr($bigarray[4], 0, 29) == "# http://www.phpsurveyor.org/")) + { + $importversion = 100; // version 1.0 file + } + elseif + (isset($bigarray[1]) && isset($bigarray[4])&& (substr($bigarray[1], 0, 22) == "# SURVEYOR SURVEY DUMP")&& (substr($bigarray[4], 0, 37) == "# http://phpsurveyor.sourceforge.net/")) + { + $importversion = 99; // Version 0.99 file or older - carries a different URL + } + elseif + (substr($bigarray[0], 0, 24) == "# LimeSurvey Survey Dump" || substr($bigarray[0], 0, 25) == "# PHPSurveyor Survey Dump") + { // Wow.. this seems to be a >1.0 version file - these files carry the version information to read in line two + $importversion=substr($bigarray[1], 12, 3); + } + else // unknown file - show error message + { + if ($importingfrom == "http") + { + // $importsurvey .= "".("Error")."\n"; + // $importsurvey .= ("This file is not a LimeSurvey survey file. Import failed.")."\n"; + // $importsurvey .= "
    \n"; + // $importsurvey .= "\n\n"; + //unlink($the_full_file_path); + return false; + } + else + { + //echo ("This file is not a LimeSurvey survey file. Import failed.")."\n"; + return false; + } + } + + + // okay.. now lets drop the first 9 lines and get to the data + // This works for all versions + for ($i=0; $i<9; $i++) + { + unset($bigarray[$i]); + } + $bigarray = array_values($bigarray); + $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", OK ".print_r($bigarray)); + + + //SURVEYS + if (array_search("# GROUPS TABLE\n", $bigarray)) + { + $stoppoint = array_search("# GROUPS TABLE\n", $bigarray); + } + elseif (array_search("# GROUPS TABLE\r\n", $bigarray)) + { + $stoppoint = array_search("# GROUPS TABLE\r\n", $bigarray); + } + for ($i=0; $i<=$stoppoint+1; $i++) + { + if ($i<$stoppoint-2) {$surveyarray[] = $bigarray[$i];} + unset($bigarray[$i]); + } + $bigarray = array_values($bigarray); + + //GROUPS + if (array_search("# QUESTIONS TABLE\n", $bigarray)) + { + $stoppoint = array_search("# QUESTIONS TABLE\n", $bigarray); + } + elseif (array_search("# QUESTIONS TABLE\r\n", $bigarray)) + { + $stoppoint = array_search("# QUESTIONS TABLE\r\n", $bigarray); + } + else + { + $stoppoint = count($bigarray)-1; + } + for ($i=0; $i<=$stoppoint+1; $i++) + { + if ($i<$stoppoint-2) {$grouparray[] = $bigarray[$i];} + unset($bigarray[$i]); + } + $bigarray = array_values($bigarray); + + //QUESTIONS + if (array_search("# ANSWERS TABLE\n", $bigarray)) + { + $stoppoint = array_search("# ANSWERS TABLE\n", $bigarray); + } + elseif (array_search("# ANSWERS TABLE\r\n", $bigarray)) + { + $stoppoint = array_search("# ANSWERS TABLE\r\n", $bigarray); + } + else + { + $stoppoint = count($bigarray)-1; + } + for ($i=0; $i<=$stoppoint+1; $i++) + { + if ($i<$stoppoint-2) + { + $questionarray[] = $bigarray[$i]; + } + unset($bigarray[$i]); + } + $bigarray = array_values($bigarray); + + //ANSWERS + if (array_search("# CONDITIONS TABLE\n", $bigarray)) + { + $stoppoint = array_search("# CONDITIONS TABLE\n", $bigarray); + } + elseif (array_search("# CONDITIONS TABLE\r\n", $bigarray)) + { + $stoppoint = array_search("# CONDITIONS TABLE\r\n", $bigarray); + } + else + { + $stoppoint = count($bigarray)-1; + } + for ($i=0; $i<=$stoppoint+1; $i++) + { + if ($i<$stoppoint-2) + { + $answerarray[] = str_replace("`default`", "`default_value`", $bigarray[$i]); + } + unset($bigarray[$i]); + } + $bigarray = array_values($bigarray); + + //CONDITIONS + if (array_search("# LABELSETS TABLE\n", $bigarray)) + { + $stoppoint = array_search("# LABELSETS TABLE\n", $bigarray); + } + elseif (array_search("# LABELSETS TABLE\r\n", $bigarray)) + { + $stoppoint = array_search("# LABELSETS TABLE\r\n", $bigarray); + } + else + { //There is no labelsets information, so presumably this is a pre-0.98rc3 survey. + $stoppoint = count($bigarray); + } + for ($i=0; $i<=$stoppoint+1; $i++) + { + if ($i<$stoppoint-2) {$conditionsarray[] = $bigarray[$i];} + unset($bigarray[$i]); + } + $bigarray = array_values($bigarray); + + //LABELSETS + if (array_search("# LABELS TABLE\n", $bigarray)) + { + $stoppoint = array_search("# LABELS TABLE\n", $bigarray); + } + elseif (array_search("# LABELS TABLE\r\n", $bigarray)) + { + $stoppoint = array_search("# LABELS TABLE\r\n", $bigarray); + } + else + { + $stoppoint = count($bigarray)-1; + } + for ($i=0; $i<=$stoppoint+1; $i++) + { + if ($i<$stoppoint-2) {$labelsetsarray[] = $bigarray[$i];} + unset($bigarray[$i]); + } + $bigarray = array_values($bigarray); + + //LABELS + if (array_search("# QUESTION_ATTRIBUTES TABLE\n", $bigarray)) + { + $stoppoint = array_search("# QUESTION_ATTRIBUTES TABLE\n", $bigarray); + } + elseif (array_search("# QUESTION_ATTRIBUTES TABLE\r\n", $bigarray)) + { + $stoppoint = array_search("# QUESTION_ATTRIBUTES TABLE\r\n", $bigarray); + } + else + { + $stoppoint = count($bigarray)-1; + } + + for ($i=0; $i<=$stoppoint+1; $i++) + { + if ($i<$stoppoint-2) {$labelsarray[] = $bigarray[$i];} + unset($bigarray[$i]); + } + $bigarray = array_values($bigarray); + + //QUESTION_ATTRIBUTES + if (array_search("# ASSESSMENTS TABLE\n", $bigarray)) + { + $stoppoint = array_search("# ASSESSMENTS TABLE\n", $bigarray); + } + elseif (array_search("# ASSESSMENTS TABLE\r\n", $bigarray)) + { + $stoppoint = array_search("# ASSESSMENTS TABLE\r\n", $bigarray); + } + else + { + $stoppoint = count($bigarray)-1; + } + for ($i=0; $i<=$stoppoint+1; $i++) + { + if ($i<$stoppoint-2) {$question_attributesarray[] = $bigarray[$i];} + unset($bigarray[$i]); + } + $bigarray = array_values($bigarray); + + + //ASSESSMENTS + if (array_search("# SURVEYS_LANGUAGESETTINGS TABLE\n", $bigarray)) + { + $stoppoint = array_search("# SURVEYS_LANGUAGESETTINGS TABLE\n", $bigarray); + } + elseif (array_search("# SURVEYS_LANGUAGESETTINGS TABLE\r\n", $bigarray)) + { + $stoppoint = array_search("# SURVEYS_LANGUAGESETTINGS TABLE\r\n", $bigarray); + } + else + { + $stoppoint = count($bigarray)-1; + } + for ($i=0; $i<=$stoppoint+1; $i++) + { + // if ($i<$stoppoint-2 || $i==count($bigarray)-1) + if ($i<$stoppoint-2) + { + $assessmentsarray[] = $bigarray[$i]; + } + unset($bigarray[$i]); + } + $bigarray = array_values($bigarray); + + //LANGAUGE SETTINGS + if (array_search("# QUOTA TABLE\n", $bigarray)) + { + $stoppoint = array_search("# QUOTA TABLE\n", $bigarray); + } + elseif (array_search("# QUOTA TABLE\r\n", $bigarray)) + { + $stoppoint = array_search("# QUOTA TABLE\r\n", $bigarray); + } + else + { + $stoppoint = count($bigarray)-1; + } + for ($i=0; $i<=$stoppoint+1; $i++) + { + // if ($i<$stoppoint-2 || $i==count($bigarray)-1) + //$bigarray[$i]= trim($bigarray[$i]); + if (isset($bigarray[$i]) && (trim($bigarray[$i])!='')) + { + if (strpos($bigarray[$i],"#")===0) + { + unset($bigarray[$i]); + unset($bigarray[$i+1]); + unset($bigarray[$i+2]); + break ; + } + else + { + $surveylsarray[] = $bigarray[$i]; + } + } + unset($bigarray[$i]); + } + $bigarray = array_values($bigarray); + + //QUOTA + if (array_search("# QUOTA_MEMBERS TABLE\n", $bigarray)) + { + $stoppoint = array_search("# QUOTA_MEMBERS TABLE\n", $bigarray); + } + elseif (array_search("# QUOTA_MEMBERS TABLE\r\n", $bigarray)) + { + $stoppoint = array_search("# QUOTA_MEMBERS TABLE\r\n", $bigarray); + } + else + { + $stoppoint = count($bigarray)-1; + } + for ($i=0; $i<=$stoppoint+1; $i++) + { + // if ($i<$stoppoint-2 || $i==count($bigarray)-1) + if ($i<$stoppoint-2) + { + $quotaarray[] = $bigarray[$i]; + } + unset($bigarray[$i]); + } + $bigarray = array_values($bigarray); + + //Survey Language Settings + $stoppoint = count($bigarray)-1; + for ($i=0; $i<$stoppoint-1; $i++) + { + if ($i<=$stoppoint) {$quotamembersarray[] = $bigarray[$i];} + unset($bigarray[$i]); + } + $bigarray = array_values($bigarray); + + if (isset($surveyarray)) {$countsurveys = count($surveyarray);} else {$countsurveys = 0;} + if (isset($surveylsarray)) {$countlanguages = count($surveylsarray)-1;} else {$countlanguages = 1;} + if (isset($grouparray)) {$countgroups = count($grouparray);} else {$countgroups = 0;} + if (isset($questionarray)) {$countquestions = count($questionarray);} else {$countquestions=0;} + if (isset($answerarray)) {$countanswers = count($answerarray);} else {$countanswers=0;} + if (isset($conditionsarray)) {$countconditions = count($conditionsarray);} else {$countconditions=0;} + if (isset($labelsetsarray)) {$countlabelsets = count($labelsetsarray);} else {$countlabelsets=0;} + if (isset($question_attributesarray)) {$countquestion_attributes = count($question_attributesarray);} else {$countquestion_attributes=0;} + if (isset($assessmentsarray)) {$countassessments=count($assessmentsarray);} else {$countassessments=0;} + if (isset($quotaarray)) {$countquota=count($quotaarray);} else {$countquota=0;} + + // CREATE SURVEY + + if ($importversion>=111) + { + if ($countsurveys>0){$countsurveys--;}; + if ($countanswers>0){$countanswers=($countanswers-1)/$countlanguages;}; + if ($countgroups>0){$countgroups=($countgroups-1)/$countlanguages;}; + if ($countquestions>0){$countquestions=($countquestions-1)/$countlanguages;}; + if ($countassessments>0){$countassessments--;}; + if ($countconditions>0){$countconditions--;}; + if ($countlabelsets>0){$countlabelsets--;}; + if ($countquestion_attributes>0){$countquestion_attributes--;}; + if ($countquota>0){$countquota--;}; + $sfieldorders =convertCSVRowToArray($surveyarray[0],',','"'); + $sfieldcontents=convertCSVRowToArray($surveyarray[1],',','"'); + } + else + { + $sfieldorders=convertToArray($surveyarray[0], "`, `", "(`", "`)"); + $sfieldcontents=convertToArray($surveyarray[0], "', '", "('", "')"); + } + $surveyrowdata=array_combine($sfieldorders,$sfieldcontents); + $surveyid=$surveyrowdata["sid"]; + + + if (!$surveyid) + { + if ($importingfrom == "http") + { + // $importsurvey .= "".("Error")."\n"; + // $importsurvey .= ("Import of this survey file failed")."\n"; + // $importsurvey .= ("File does not contain LimeSurvey data in the correct format.")."\n"; //Couldn't find the SID - cannot continue + // $importsurvey .= "
    \n"; + // $importsurvey .= "\n\n"; + // unlink($the_full_file_path); //Delete the uploaded file + return false; + } + else + { + //echo ("Import of this survey file failed")."\n".("File does not contain LimeSurvey data in the correct format.")."\n"; + return false; + } + } + + // Use the existing surveyid if it does not already exists + // This allows the URL links to the survey to keep working because the sid did not change + $newsid = $iVid; //XXX Changed from $surveyid --> $iVid + $isquery = "SELECT sid FROM {$dbprefix}surveys WHERE sid=$newsid"; + $isresult = db_execute_assoc($isquery); + if ($isresult->RecordCount()>0) + { + // Get new random ids until one is found that is not used + do + { + $newsid = getRandomID(); + $isquery = "SELECT sid FROM {$dbprefix}surveys WHERE sid=$newsid"; + $isresult = db_execute_assoc($isquery); + } + while ($isresult->RecordCount()>0); + } + + + $insert=$surveyarray[0]; + if ($importversion>=111) + { + $sfieldorders =convertCSVRowToArray($surveyarray[0],',','"'); + $sfieldcontents=convertCSVRowToArray($surveyarray[1],',','"'); + } + else + { + $sfieldorders=convertToArray($surveyarray[0], "`, `", "(`", "`)"); + $sfieldcontents=convertToArray($surveyarray[0], "', '", "('", "')"); + } + $surveyrowdata=array_combine($sfieldorders,$sfieldcontents); + // Set new owner ID + $surveyrowdata['owner_id']=$_SESSION['loginID']; + // Set new survey ID + $surveyrowdata['sid']=$newsid; + $surveyrowdata['active']='N'; + + + if ($importversion<=100) + // find the old language field and replace its contents with the new language shortcuts + { + $oldlanguage=$surveyrowdata['language']; + $newlanguage='en'; //Default + switch ($oldlanguage) + { + case "bulgarian": + $newlanguage='bg'; + break; + case "chinese-simplified": + $newlanguage='zh-Hans'; + break; + case "chinese-traditional": + $newlanguage='zh-Hant-HK'; + break; + case "croatian": + $newlanguage='hr'; + break; + case "danish": + $newlanguage='da'; + break; + case "dutch": + $newlanguage='nl'; + break; + case "english": + $newlanguage='en'; + break; + case "french": + $newlanguage='fr'; + break; + case "german-informal": + $newlanguage='de-informal'; + break; + case "german": + $newlanguage='de'; + break; + case "greek": + $newlanguage='el'; + break; + case "hungarian": + $newlanguage='hu'; + break; + case "italian": + $newlanguage='it'; + break; + case "japanese": + $newlanguage='ja'; + break; + case "lithuanian": + $newlanguage='lt'; + break; + case "norwegian": + $newlanguage='nb'; + break; + case "portuguese": + $newlanguage='pt'; + break; + case "romanian": + $newlanguage='ro'; + break; + case "russian": + $newlanguage='ru'; + break; + case "slovenian": + $newlanguage='sl'; + break; + case "spanish": + $newlanguage='es'; + break; + case "swedish": + $newlanguage='sv'; + break; + } + + $surveyrowdata['language']=$newlanguage; + + // copy the survey row data + + // now prepare the languagesettings table and drop according values from the survey array + $surveylsrowdata=array(); + $surveylsrowdata['surveyls_survey_id']=$newsid; + $surveylsrowdata['surveyls_language']=$newlanguage; + $surveylsrowdata['surveyls_title']=$surveyrowdata['short_title']; + $surveylsrowdata['surveyls_description']=$surveyrowdata['description']; + $surveylsrowdata['surveyls_welcometext']=$surveyrowdata['welcome']; + $surveylsrowdata['surveyls_urldescription']=$surveyrowdata['urldescrip']; + $surveylsrowdata['surveyls_email_invite_subj']=$surveyrowdata['email_invite_subj']; + $surveylsrowdata['surveyls_email_invite']=$surveyrowdata['email_invite']; + $surveylsrowdata['surveyls_email_remind_subj']=$surveyrowdata['email_remind_subj']; + $surveylsrowdata['surveyls_email_remind']=$surveyrowdata['email_remind']; + $surveylsrowdata['surveyls_email_register_subj']=$surveyrowdata['email_register_subj']; + $surveylsrowdata['surveyls_email_register']=$surveyrowdata['email_register']; + $surveylsrowdata['surveyls_email_confirm_subj']=$surveyrowdata['email_confirm_subj']; + $surveylsrowdata['surveyls_email_confirm']=$surveyrowdata['email_confirm']; + unset($surveyrowdata['short_title']); + unset($surveyrowdata['description']); + unset($surveyrowdata['welcome']); + unset($surveyrowdata['urldescrip']); + unset($surveyrowdata['email_invite_subj']); + unset($surveyrowdata['email_invite']); + unset($surveyrowdata['email_remind_subj']); + unset($surveyrowdata['email_remind']); + unset($surveyrowdata['email_register_subj']); + unset($surveyrowdata['email_register']); + unset($surveyrowdata['email_confirm_subj']); + unset($surveyrowdata['email_confirm']); + + + // translate internal links + $surveylsrowdata['surveyls_title']=translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_title']); + $surveylsrowdata['surveyls_description']=translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_description']); + $surveylsrowdata['surveyls_welcometext']=translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_welcometext']); + $surveylsrowdata['surveyls_urldescription']=translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_urldescription']); + $surveylsrowdata['surveyls_email_invite']=translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_email_invite']); + $surveylsrowdata['surveyls_email_remind']=translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_email_remind']); + $surveylsrowdata['surveyls_email_register']=translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_email_register']); + $surveylsrowdata['surveyls_email_confirm']=translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_email_confirm']); + + + + // import the survey language-specific settings + $values=array_values($surveylsrowdata); + $values=array_map(array(&$connect, "qstr"),$values); // quote everything accordingly + $insert = "insert INTO {$dbprefix}surveys_languagesettings (".implode(',',array_keys($surveylsrowdata)).") VALUES (".implode(',',$values).")"; //handle db prefix + try + { + $iresult = $connect->Execute($insert) or $this->debugLsrc("".("Import of this survey file failed")."\n[$insert]{$surveyarray[0]}\n" . $connect->ErrorMsg()); + } + catch(exception $e) + { + throw new SoapFault("Server: ", "$e : $connect->ErrorMsg()"); + exit; + } + + + } + + + + if (isset($surveyrowdata['datecreated'])) {$surveyrowdata['datecreated']=$connect->BindTimeStamp($surveyrowdata['datecreated']);} + unset($surveyrowdata['expires']); + unset($surveyrowdata['attribute1']); + unset($surveyrowdata['attribute2']); + unset($surveyrowdata['usestartdate']); + unset($surveyrowdata['useexpiry']); + unset($surveyrowdata['url']); + if (isset($surveyrowdata['startdate'])) {unset($surveyrowdata['startdate']);} + $surveyrowdata['bounce_email']=$surveyrowdata['adminemail']; + if (!isset($surveyrowdata['datecreated']) || $surveyrowdata['datecreated']=='' || $surveyrowdata['datecreated']=='null') {$surveyrowdata['datecreated']=$connect->BindTimeStamp(date_shift(date("Y-m-d H:i:s"), "Y-m-d", $timeadjust));} + + $values=array_values($surveyrowdata); + $values=array_map(array(&$connect, "qstr"),$values); // quote everything accordingly + $insert = "INSERT INTO {$dbprefix}surveys (".implode(',',array_keys($surveyrowdata)).") VALUES (".implode(',',$values).")"; //handle db prefix + try + { + $iresult = $connect->Execute($insert) or $this->debugLsrc(""."Import of this survey file failed on Line: ".__LINE__."\n[$insert]{$surveyarray[0]}\n" . $connect->ErrorMsg()) and exit; + } + catch(exception $e) + { + throw new SoapFault("Server: ", "$e : $connect->ErrorMsg()"); + exit; + } + $oldsid=$surveyid; + + // Now import the survey language settings + if ($importversion>=111) + { + $fieldorders=convertCSVRowToArray($surveylsarray[0],',','"'); + unset($surveylsarray[0]); + foreach ($surveylsarray as $slsrow) { + $fieldcontents=convertCSVRowToArray($slsrow,',','"'); + $surveylsrowdata=array_combine($fieldorders,$fieldcontents); + // convert back the '\'.'n' cahr from the CSV file to true return char "\n" + $surveylsrowdata=array_map('convertCsvreturn2return', $surveylsrowdata); + // Convert the \n return char from welcometext to + // XXX Change values while Importing here //done by rakete + $surveylsrowdata['surveyls_title'] = $sVtit; + $surveylsrowdata['surveyls_description'] = $sVbes; + $surveylsrowdata['surveyls_welcometext'] = $sVwel; + $surveylsrowdata['surveyls_urldescription'] = $sUbes; + + + // translate internal links + $surveylsrowdata['surveyls_title']=translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_title']); + $surveylsrowdata['surveyls_description']=translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_description']); + $surveylsrowdata['surveyls_welcometext']=translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_welcometext']); + $surveylsrowdata['surveyls_urldescription']=translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_urldescription']); + $surveylsrowdata['surveyls_email_invite']=translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_email_invite']); + $surveylsrowdata['surveyls_email_remind']=translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_email_remind']); + $surveylsrowdata['surveyls_email_register']=translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_email_register']); + $surveylsrowdata['surveyls_email_confirm']=translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_email_confirm']); + + $surveylsrowdata['surveyls_survey_id']=$newsid; + $newvalues=array_values($surveylsrowdata); + $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly + $lsainsert = "INSERT INTO {$dbprefix}surveys_languagesettings (".implode(',',array_keys($surveylsrowdata)).") VALUES (".implode(',',$newvalues).")"; //handle db prefix + $lsiresult=$connect->Execute($lsainsert) or $this->debugLsrc("Import of this survey file failed on Line ".__LINE__."") and exit; + } + + } + + + // DO SURVEY_RIGHTS + $isrquery = "INSERT INTO {$dbprefix}surveys_rights VALUES($newsid,".$_SESSION['loginID'].",1,1,1,1,1,1)"; + @$isrresult = $connect->Execute($isrquery); + $deniedcountlabelsets =0; + + + //DO ANY LABELSETS FIRST, SO WE CAN KNOW WHAT THEIR NEW LID IS FOR THE QUESTIONS + if (isset($labelsetsarray) && $labelsetsarray) { + $csarray=buildLabelSetCheckSumArray(); // build checksums over all existing labelsets + $count=0; + foreach ($labelsetsarray as $lsa) { + + if ($importversion>=111) + { + $fieldorders =convertCSVRowToArray($labelsetsarray[0],',','"'); + $fieldcontents=convertCSVRowToArray($lsa,',','"'); + if ($count==0) {$count++; continue;} + } + else + { + $fieldorders=convertToArray($lsa, "`, `", "(`", "`)"); + $fieldcontents=convertToArray($lsa, "', '", "('", "')"); + } + $labelsetrowdata=array_combine($fieldorders,$fieldcontents); + + // Save old labelid + $oldlid=$labelsetrowdata['lid']; + // set the new language + if ($importversion<=100) + { + $labelsetrowdata['languages']=$newlanguage; + } + unset($labelsetrowdata['lid']); + $newvalues=array_values($labelsetrowdata); + $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly + $lsainsert = "insert INTO {$dbprefix}labelsets (".implode(',',array_keys($labelsetrowdata)).") VALUES (".implode(',',$newvalues).")"; //handle db prefix + $lsiresult=$connect->Execute($lsainsert); + + // Get the new insert id for the labels inside this labelset + $newlid=$connect->Insert_ID("{$dbprefix}labelsets","lid"); + + // $importsurvey .= "OLDLID: $oldlid NEWLID: $newlid"; + // For debugging label import + + if ($labelsarray) { + $count=0; + foreach ($labelsarray as $la) { + if ($importversion>=111) + { + $lfieldorders =convertCSVRowToArray($labelsarray[0],',','"'); + $lfieldcontents=convertCSVRowToArray($la,',','"'); + if ($count==0) {$count++; continue;} + } + else + { + //Get field names into array + $lfieldorders=convertToArray($la, "`, `", "(`", "`)"); + //Get field values into array + $lfieldcontents=convertToArray($la, "', '", "('", "')"); + } + // Combine into one array with keys and values since its easier to handle + $labelrowdata=array_combine($lfieldorders,$lfieldcontents); + if ($importversion<=132) + { + $labelrowdata["assessment_value"]=(int)$labelrowdata["code"]; + } + $labellid=$labelrowdata['lid']; + if ($importversion<=100) + { + $labelrowdata['language']=$newlanguage; + } + if ($labellid == $oldlid) { + $labelrowdata['lid']=$newlid; + + // translate internal links + $labelrowdata['title']=translink('label', $oldlid, $newlid, $labelrowdata['title']); + + $newvalues=array_values($labelrowdata); + $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly + $lainsert = "insert INTO {$dbprefix}labels (".implode(',',array_keys($labelrowdata)).") VALUES (".implode(',',$newvalues).")"; //handle db prefix + $liresult=$connect->Execute($lainsert); + + } + } + } + + //CHECK FOR DUPLICATE LABELSETS + $thisset=""; + + $query2 = "SELECT code, title, sortorder, language + FROM {$dbprefix}labels + WHERE lid=".$newlid." + ORDER BY language, sortorder, code"; + $result2 = db_execute_num($query2) or $this->debugLsrc("Import of this survey file failed on Line ".__LINE__."| ".$connect->ErrorMsg()); + while($row2=$result2->FetchRow()) + { + $thisset .= implode('.', $row2); + } // while + $newcs=dechex(crc32($thisset)*1); + unset($lsmatch); + if (isset($csarray)) + { + foreach($csarray as $key=>$val) + { + if ($val == $newcs) + { + $lsmatch=$key; + } + } + } + if (isset($lsmatch) || ($_SESSION['USER_RIGHT_MANAGE_LABEL'] != 1)) + { + //There is a matching labelset or the user is not allowed to edit labels - + // So, we will delete this one and refer to the matched one. + $query = "DELETE FROM {$dbprefix}labels WHERE lid=$newlid"; + $result=$connect->Execute($query) or $this->debugLsrc("Import of this survey file failed on Line ".__LINE__."| ".$connect->ErrorMsg()); + $query = "DELETE FROM {$dbprefix}labelsets WHERE lid=$newlid"; + $result=$connect->Execute($query) or $this->debugLsrc("Import of this survey file failed on Line ".__LINE__."| ".$connect->ErrorMsg()); + if (isset($lsmatch)) {$newlid=$lsmatch;} + else {++$deniedcountlabelsets;--$countlabelsets;} + } + else + { + //There isn't a matching labelset, add this checksum to the $csarray array + $csarray[$newlid]=$newcs; + } + //END CHECK FOR DUPLICATES + $labelreplacements[]=array($oldlid, $newlid); + } + } + $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", OK "); + $importwarning = ""; // used to save the warnings while processing questions + + $qtypes = $this->getqtypelist("" ,"array"); + + foreach ($qtypes as $type) //XXX FIXME + $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", OK ".$type); + + // DO GROUPS, QUESTIONS FOR GROUPS, THEN ANSWERS FOR QUESTIONS IN A NESTED FORMAT! + if (isset($grouparray) && $grouparray) { + $count=0; + $currentgid=''; + foreach ($grouparray as $ga) { + if ($importversion>=111) + { + $gafieldorders =convertCSVRowToArray($grouparray[0],',','"'); + $gacfieldcontents=convertCSVRowToArray($ga,',','"'); + if ($count==0) {$count++; continue;} + } + else + { + //Get field names into array + $gafieldorders=convertToArray($ga, "`, `", "(`", "`)"); + //Get field values into array + $gacfieldcontents=convertToArray($ga, "', '", "('", "')"); + } + $grouprowdata=array_combine($gafieldorders,$gacfieldcontents); + // remember group id + if ($currentgid=='' || ($currentgid!=$grouprowdata['gid'])) {$currentgid=$grouprowdata['gid'];$newgroup=true;} + else + if ($currentgid==$grouprowdata['gid']) {$newgroup=false;} + $gid=$grouprowdata['gid']; + $gsid=$grouprowdata['sid']; + //Now an additional integrity check if there are any groups not belonging into this survey + if ($gsid != $surveyid) + { + if ($importingfrom == "http") + { + // $importsurvey .= "\n".("Error")."" + // ."\n".("A group in the CSV/SQL file is not part of the same survey. The import of the survey was stopped.")."\n"; + } + else + { + //echo ("Error").": A group in the CSV/SQL file is not part of the same Survey. The import of the survey was stopped.\n"; + } + return false; + } + $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", OK "); + //remove the old group id + if ($newgroup) {unset($grouprowdata['gid']);} + else {$grouprowdata['gid']=$newgid;} + //replace old surveyid by new surveyid + $grouprowdata['sid']=$newsid; + // Version <=100 dont have a language field yet so we set it now + if ($importversion<=100) + { + $grouprowdata['language']=$newlanguage; + } + $oldgid=$gid; // save it for later + $grouprowdata=array_map('convertCsvreturn2return', $grouprowdata); + + // translate internal links + $grouprowdata['group_name']=translink('survey', $surveyid, $newsid, $grouprowdata['group_name']); + $grouprowdata['description']=translink('survey', $surveyid, $newsid, $grouprowdata['description']); + + $newvalues=array_values($grouprowdata); + + $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly + + if (isset($grouprowdata['gid'])) {@$connect->Execute('SET IDENTITY_INSERT '.db_table_name('groups')." ON");} + $ginsert = 'insert INTO '.db_table_name('groups').' ('.implode(',',array_keys($grouprowdata)).') VALUES ('.implode(',',$newvalues).')'; + $gres = $connect->Execute($ginsert) or $this->debugLsrc("Import of this survey file failed on Line ".__LINE__."| ".$connect->ErrorMsg()); + if (isset($grouprowdata['gid'])) {@$connect->Execute('SET IDENTITY_INSERT '.db_table_name('groups').' OFF');} + //GET NEW GID + if ($newgroup) {$newgid=$connect->Insert_ID("{$dbprefix}groups","gid");} + + //NOW DO NESTED QUESTIONS FOR THIS GID + //$this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", OK ".var_dump($questionarray)); + + if (isset($questionarray) && $questionarray && $newgroup) { + $count=0; + $currentqid=''; + foreach ($questionarray as $qa) { + + $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", OK ".$qa); + + if ($importversion>=111) + { + $qafieldorders =convertCSVRowToArray($questionarray[0],',','"'); + $qacfieldcontents=convertCSVRowToArray($qa,',','"'); + if ($count==0) {$count++; continue;} + } + else + { + $qafieldorders=convertToArray($qa, "`, `", "(`", "`)"); + $qacfieldcontents=convertToArray($qa, "', '", "('", "')"); + } + $questionrowdata=array_combine($qafieldorders,$qacfieldcontents); + $questionrowdata=array_map('convertCsvreturn2return', $questionrowdata); + + if ($currentqid=='' || ($currentqid!=$questionrowdata['qid'])) {$currentqid=$questionrowdata['qid'];$newquestion=true;} + else + if ($currentqid==$questionrowdata['qid']) {$newquestion=false;} + + if (!array_key_exists($questionrowdata["type"], $qtypes)) + { + $questionrowdata["type"] = strtoupper($questionrowdata["type"]); + if (!array_key_exists($questionrowdata["type"], $qtypes)) + { + //$importwarning .= "
  • " . sprintf(("Question \"%s - %s\" was NOT imported because the question type is unknown."), $questionrowdata["title"], $questionrowdata["question"]) . "
  • "; + $countquestions--; + $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", OK ".$countquestions); + continue; + } + else // the upper case worked well $qtypes[$questionrowdata["type"]] + { + //$importwarning .= "
  • " . sprintf(("Question \"%s - %s\" was imported but the type was set to '%s' because it is the most similiar one."), $questionrowdata["title"], $questionrowdata["question"], $qtypes[$questionrowdata["type"]]) . "
  • "; + } + } + + $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", OK "); + + $thisgid=$questionrowdata['gid']; + + $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", OK ".$thisgid." == ".$gid); + if ($thisgid == $gid) { + $qid = $questionrowdata['qid']; + // Remove qid field + if ($newquestion) {unset($questionrowdata['qid']);} + else {$questionrowdata['qid']=$newqid;} + + $questionrowdata["sid"] = $newsid; + $questionrowdata["gid"] = $newgid; + // Version <=100 doesn't have a language field yet so we set it now + if ($importversion<=100) + { + $questionrowdata['language']=$newlanguage; + } + $oldqid=$qid; + if (!isset($questionrowdata["lid1"])) + { + $questionrowdata["lid1"]=0; + } + // Now we will fix up the label id + $type = $questionrowdata["type"]; //Get the type + if ($type == "F" || $type == "H" || $type == "W" || + $type == "Z" || $type == "1" || $type == ":" || + $type == ";" ) + {//IF this is a flexible label array, update the lid entry + if (isset($labelreplacements)) { + // We only replace once in each question label + // otherwise could lead to double substitution + // if a new lid collides with an older one + $already_replaced_label = false; + $already_replaced_label1 = false; + foreach ($labelreplacements as $lrp) { + if ($lrp[0] == $questionrowdata["lid"]) + { + if (!$already_replaced_label) + { + $questionrowdata["lid"]=$lrp[1]; + $already_replaced_label = true; + } + } + if ($lrp[0] == $questionrowdata["lid1"]) + { + if (!$already_replaced_label1) + { + $questionrowdata["lid1"]=$lrp[1]; + $already_replaced_label1 = true; + } + } + } + } + } + if (!isset($questionrowdata["question_order"]) || $questionrowdata["question_order"]=='') {$questionrowdata["question_order"]=0;} + $other = $questionrowdata["other"]; //Get 'other' field value + + // translate internal links + $questionrowdata['title']=translink('survey', $surveyid, $newsid, $questionrowdata['title']); + $questionrowdata['question']=translink('survey', $surveyid, $newsid, $questionrowdata['question']); + $questionrowdata['help']=translink('survey', $surveyid, $newsid, $questionrowdata['help']); + + $newvalues=array_values($questionrowdata); + if (isset($questionrowdata['qid'])) {@$connect->Execute('SET IDENTITY_INSERT '.db_table_name('questions').' ON');} + + foreach($questionrowdata as $qrd) + $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", OK ".$qrd); + + $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly + $qinsert = "insert INTO {$dbprefix}questions (".implode(',',array_keys($questionrowdata)).") VALUES (".implode(',',$newvalues).")"; + + $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", OK | ".$qinsert); + + $qres = $connect->Execute($qinsert) or $this->debugLsrc("Import of this survey file failed on Line ".__LINE__."| ".$connect->ErrorMsg()); + if (isset($questionrowdata['qid'])) {@$connect->Execute('SET IDENTITY_INSERT '.db_table_name('questions').' OFF');} + if ($newquestion) + { + $newqid=$connect->Insert_ID("{$dbprefix}questions","qid"); + } + + $newrank=0; + $substitutions[]=array($oldsid, $oldgid, $oldqid, $newsid, $newgid, $newqid); + $this->debugLsrc("HALLO?!:"); + //NOW DO NESTED ANSWERS FOR THIS QID + if (isset($answerarray) && $answerarray && $newquestion) { + $count=0; + foreach ($answerarray as $aa) { + if ($importversion>=111) + { + $aafieldorders =convertCSVRowToArray($answerarray[0],',','"'); + $aacfieldcontents=convertCSVRowToArray($aa,',','"'); + if ($count==0) {$count++; continue;} + } + else + { + $aafieldorders=convertToArray($aa, "`, `", "(`", "`)"); + $aacfieldcontents=convertToArray($aa, "', '", "('", "')"); + } + $answerrowdata=array_combine($aafieldorders,$aacfieldcontents); + if ($importversion<=132) + { + $answerrowdata["assessment_value"]=(int)$answerrowdata["code"]; + } + $code=$answerrowdata["code"]; + $thisqid=$answerrowdata["qid"]; + if ($thisqid == $qid) + { + $answerrowdata["qid"]=$newqid; + // Version <=100 doesn't have a language field yet so we set it now + if ($importversion<=100) + { + $answerrowdata['language']=$newlanguage; + } + + // translate internal links + $answerrowdata['answer']=translink('survey', $surveyid, $newsid, $answerrowdata['answer']); + + $newvalues=array_values($answerrowdata); + $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly + $ainsert = "insert INTO {$dbprefix}answers (".implode(',',array_keys($answerrowdata)).") VALUES (".implode(',',$newvalues).")"; + $ares = $connect->Execute($ainsert) or $this->debugLsrc("Import of this survey file failed on Line ".__LINE__."| ".$connect->ErrorMsg()); + + if ($type == "M" || $type == "P") { + $fieldnames[]=array("oldcfieldname"=>$oldsid."X".$oldgid."X".$oldqid, + "newcfieldname"=>$newsid."X".$newgid."X".$newqid, + "oldfieldname"=>$oldsid."X".$oldgid."X".$oldqid.$code, + "newfieldname"=>$newsid."X".$newgid."X".$newqid.$code); + if ($type == "P") { + $fieldnames[]=array("oldcfieldname"=>$oldsid."X".$oldgid."X".$oldqid."comment", + "newcfieldname"=>$newsid."X".$newgid."X".$newqid.$code."comment", + "oldfieldname"=>$oldsid."X".$oldgid."X".$oldqid.$code."comment", + "newfieldname"=>$newsid."X".$newgid."X".$newqid.$code."comment"); + } + } + elseif ($type == "A" || $type == "B" || $type == "C" || $type == "F" || $type == "H" || $type == "E" || $type == "Q" || $type == "K" || $type == "1") { + $fieldnames[]=array("oldcfieldname"=>$oldsid."X".$oldgid."X".$oldqid.$code, + "newcfieldname"=>$newsid."X".$newgid."X".$newqid.$code, + "oldfieldname"=>$oldsid."X".$oldgid."X".$oldqid.$code, + "newfieldname"=>$newsid."X".$newgid."X".$newqid.$code); + } + elseif ($type == ":" || $type == ";" ) { + // read all label codes from $questionrowdata["lid"] + // for each one (as L) set SGQA_L + $labelq="SELECT DISTINCT code FROM {$dbprefix}labels WHERE lid=".$questionrowdata["lid"]; + $labelqresult=db_execute_num($labelq) or safe_die("Died querying labelset $lid
    $query2
    ".$connect->ErrorMsg()); + while ($labelqrow=$labelqresult->FetchRow()) + { + $fieldnames[]=array("oldcfieldname"=>$oldsid."X".$oldgid."X".$oldqid.$code."_".$labelqrow[0], + "newcfieldname"=>$newsid."X".$newgid."X".$newqid.$code."_".$labelqrow[0], + "oldfieldname"=>$oldsid."X".$oldgid."X".$oldqid.$code."_".$labelqrow[0], + "newfieldname"=>$newsid."X".$newgid."X".$newqid.$code."_".$labelqrow[0]); + } + } + elseif ($type == "R") { + $newrank++; + } + } + } + if (($type == "A" || $type == "B" || $type == "C" || $type == "M" || $type == "P" || $type == "L") && ($other == "Y")) { + $fieldnames[]=array("oldcfieldname"=>$oldsid."X".$oldgid."X".$oldqid."other", + "newcfieldname"=>$newsid."X".$newgid."X".$newqid."other", + "oldfieldname"=>$oldsid."X".$oldgid."X".$oldqid."other", + "newfieldname"=>$newsid."X".$newgid."X".$newqid."other"); + if ($type == "P") { + $fieldnames[]=array("oldcfieldname"=>$oldsid."X".$oldgid."X".$oldqid."othercomment", + "newcfieldname"=>$newsid."X".$newgid."X".$newqid."othercomment", + "oldfieldname"=>$oldsid."X".$oldgid."X".$oldqid."othercomment", + "newfieldname"=>$newsid."X".$newgid."X".$newqid."othercomment"); + } + } + if ($type == "R" && $newrank >0) { + for ($i=1; $i<=$newrank; $i++) { + $fieldnames[]=array("oldcfieldname"=>$oldsid."X".$oldgid."X".$oldqid.$i, + "newcfieldname"=>$newsid."X".$newgid."X".$newqid.$i, + "oldfieldname"=>$oldsid."X".$oldgid."X".$oldqid.$i, + "newfieldname"=>$newsid."X".$newgid."X".$newqid.$i); + } + } + if ($type != "A" && $type != "B" && $type != "C" && $type != "R" && $type != "M" && $type != "P") { + $fieldnames[]=array("oldcfieldname"=>$oldsid."X".$oldgid."X".$oldqid, + "newcfieldname"=>$newsid."X".$newgid."X".$newqid, + "oldfieldname"=>$oldsid."X".$oldgid."X".$oldqid, + "newfieldname"=>$newsid."X".$newgid."X".$newqid); + if ($type == "O") { + $fieldnames[]=array("oldcfieldname"=>$oldsid."X".$oldgid."X".$oldqid."comment", + "newcfieldname"=>$newsid."X".$newgid."X".$newqid."comment", + "oldfieldname"=>$oldsid."X".$oldgid."X".$oldqid."comment", + "newfieldname"=>$newsid."X".$newgid."X".$newqid."comment"); + } + } + } else { + $fieldnames[]=array("oldcfieldname"=>$oldsid."X".$oldgid."X".$oldqid, + "newcfieldname"=>$newsid."X".$newgid."X".$newqid, + "oldfieldname"=>$oldsid."X".$oldgid."X".$oldqid, + "newfieldname"=>$newsid."X".$newgid."X".$newqid); + } + } + } + } + } + } + $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", OK "); + // Fix sortorder of the groups - if users removed groups manually from the csv file there would be gaps + //fixsortorderGroups(); //XXX changed: commented out + //fixsortorderGroups() in full length (using global vars, i cannot work with such things) - rakete + $baselang = GetBaseLanguageFromSurveyID($iVid); + $cdresult = db_execute_assoc("SELECT gid FROM ".db_table_name('groups')." WHERE sid='{$surveyid}' AND language='{$baselang}' ORDER BY group_order, group_name"); + $position=0; + while ($cdrow=$cdresult->FetchRow()) + { + $cd2query="UPDATE ".db_table_name('groups')." SET group_order='{$position}' WHERE gid='{$cdrow['gid']}' "; + $cd2result = $connect->Execute($cd2query) or $this->debugLsrc("Import of this survey file failed on Line ".__LINE__."| ".$connect->ErrorMsg()); //Checked + $position++; + } + + $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", OK "); + + //... and for the questions inside the groups + // get all group ids and fix questions inside each group + $gquery = "SELECT gid FROM {$dbprefix}groups where sid=$newsid group by gid ORDER BY gid"; //Get last question added (finds new qid) + $gres = db_execute_assoc($gquery); + while ($grow = $gres->FetchRow()) + { + //fixsortorderQuestions(0,$grow['gid']); //XXX changed: commented out + // and fully written out: + $qid=sanitize_int(0); + $gid=sanitize_int($grow['gid']); + $baselang = GetBaseLanguageFromSurveyID($iVid); + if ($gid == 0) + { + $result = db_execute_assoc("SELECT gid FROM ".db_table_name('questions')." WHERE qid='{$qid}' and language='{$baselang}'"); //Checked + $row=$result->FetchRow(); + $gid=$row['gid']; + } + $cdresult = db_execute_assoc("SELECT qid FROM ".db_table_name('questions')." WHERE gid='{$gid}' and language='{$baselang}' ORDER BY question_order, title ASC"); //Checked + $position=0; + while ($cdrow=$cdresult->FetchRow()) + { + $cd2query="UPDATE ".db_table_name('questions')." SET question_order='{$position}' WHERE qid='{$cdrow['qid']}' "; + $cd2result = $connect->Execute($cd2query) or $this->debugLsrc("Import of this survey file failed on Line ".__LINE__."| ".$connect->ErrorMsg()); + $position++; + } + + } + $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", OK "); + + //We've built two arrays along the way - one containing the old SID, GID and QIDs - and their NEW equivalents + //and one containing the old 'extended fieldname' and its new equivalent. These are needed to import conditions and question_attributes. + if (isset($question_attributesarray) && $question_attributesarray) {//ONLY DO THIS IF THERE ARE QUESTION_ATTRIBUES + $count=0; + foreach ($question_attributesarray as $qar) { + if ($importversion>=111) + { + $fieldorders =convertCSVRowToArray($question_attributesarray[0],',','"'); + $fieldcontents=convertCSVRowToArray($qar,',','"'); + if ($count==0) {$count++; continue;} + } + else + { + $fieldorders=convertToArray($qar, "`, `", "(`", "`)"); + $fieldcontents=convertToArray($qar, "', '", "('", "')"); + } + $qarowdata=array_combine($fieldorders,$fieldcontents); + $newqid=""; + $oldqid=$qarowdata['qid']; + foreach ($substitutions as $subs) { + if ($oldqid==$subs[2]) {$newqid=$subs[5];} + } + + $qarowdata["qid"]=$newqid; + unset($qarowdata["qaid"]); + + $newvalues=array_values($qarowdata); + $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly + $qainsert = "insert INTO {$dbprefix}question_attributes (".implode(',',array_keys($qarowdata)).") VALUES (".implode(',',$newvalues).")"; + $result=$connect->Execute($qainsert) or $this->debugLsrc("Import of this survey file failed on Line ".__LINE__."| $qainsert |".$connect->ErrorMsg()); + } + } + + if (isset($assessmentsarray) && $assessmentsarray) {//ONLY DO THIS IF THERE ARE QUESTION_ATTRIBUES + $count=0; + foreach ($assessmentsarray as $qar) { + if ($importversion>=111) + { + $fieldorders =convertCSVRowToArray($assessmentsarray[0],',','"'); + $fieldcontents=convertCSVRowToArray($qar,',','"'); + if ($count==0) {$count++; continue;} + } + else + { + $fieldorders=convertToArray($qar, "`, `", "(`", "`)"); + $fieldcontents=convertToArray($qar, "', '", "('", "')"); + } + $asrowdata=array_combine($fieldorders,$fieldcontents); + if (isset($asrowdata['link'])) + { + if (trim($asrowdata['link'])!='') $asrowdata['message']=$asrowdata['message'].'
    '.$asrowdata['link'].''; + unset($asrowdata['link']); + } + $oldsid=$asrowdata["sid"]; + $oldgid=$asrowdata["gid"]; + if ($oldgid>0) + { + foreach ($substitutions as $subs) { + if ($oldsid==$subs[0]) {$newsid=$subs[3];} + if ($oldgid==$subs[1]) {$newgid=$subs[4];} + } + } + else + { + $newgid=0; + } + + $asrowdata["sid"]=$newsid; + $asrowdata["gid"]=$newgid; + unset($asrowdata["id"]); + + + $newvalues=array_values($asrowdata); + $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly + $asinsert = "insert INTO {$dbprefix}assessments (".implode(',',array_keys($asrowdata)).") VALUES (".implode(',',$newvalues).")"; + $result=$connect->Execute($asinsert) or $this->debugLsrc("Import of this survey file failed on Line ".__LINE__."| ".$connect->ErrorMsg()); + + unset($newgid); + } + } + + if (isset($quotaarray) && $quotaarray) {//ONLY DO THIS IF THERE ARE QUOTAS + $count=0; + foreach ($quotaarray as $qar) { + + $fieldorders=convertCSVRowToArray($quotaarray[0],',','"'); + $fieldcontents=convertCSVRowToArray($qar,',','"'); + if ($count==0) {$count++; continue;} + + $asrowdata=array_combine($fieldorders,$fieldcontents); + + $oldsid=$asrowdata["sid"]; + foreach ($substitutions as $subs) { + if ($oldsid==$subs[0]) {$newsid=$subs[3];} + } + + $asrowdata["sid"]=$newsid; + $oldid = $asrowdata["id"]; + unset($asrowdata["id"]); + + $newvalues=array_values($asrowdata); + $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly + + $asinsert = "insert INTO {$dbprefix}quota (".implode(',',array_keys($asrowdata)).") VALUES (".implode(',',$newvalues).")"; + $result=$connect->Execute($asinsert) or $this->debugLsrc("Import of this survey file failed on Line ".__LINE__."| ".$connect->ErrorMsg()); + $quotaids[] = array($oldid,$connect->Insert_ID(db_table_name_nq('quota'),"id")); + + } + } + + if (isset($quotamembersarray) && $quotamembersarray) {//ONLY DO THIS IF THERE ARE QUOTAS + $count=0; + foreach ($quotamembersarray as $qar) { + + $fieldorders =convertCSVRowToArray($quotamembersarray[0],',','"'); + $fieldcontents=convertCSVRowToArray($qar,',','"'); + if ($count==0) {$count++; continue;} + + $asrowdata=array_combine($fieldorders,$fieldcontents); + + $oldsid=$asrowdata["sid"]; + $newqid=""; + $newquotaid=""; + $oldqid=$asrowdata['qid']; + $oldquotaid=$asrowdata['quota_id']; + + foreach ($substitutions as $subs) { + if ($oldsid==$subs[0]) {$newsid=$subs[3];} + if ($oldqid==$subs[2]) {$newqid=$subs[5];} + } + + foreach ($quotaids as $quotaid) { + if ($oldquotaid==$quotaid[0]) {$newquotaid=$quotaid[1];} + } + + $asrowdata["sid"]=$newsid; + $asrowdata["qid"]=$newqid; + $asrowdata["quota_id"]=$newquotaid; + unset($asrowdata["id"]); + + $newvalues=array_values($asrowdata); + $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly + + $asinsert = "insert INTO {$dbprefix}quota_members (".implode(',',array_keys($asrowdata)).") VALUES (".implode(',',$newvalues).")"; + $result=$connect->Execute($asinsert) or $this->debugLsrc("Import of this survey file failed on Line ".__LINE__."| ".$connect->ErrorMsg()); + + } + } + + if (isset($conditionsarray) && $conditionsarray) {//ONLY DO THIS IF THERE ARE CONDITIONS! + $count='0'; + foreach ($conditionsarray as $car) { + if ($importversion>=111) + { + $fieldorders =convertCSVRowToArray($conditionsarray[0],',','"'); + $fieldcontents=convertCSVRowToArray($car,',','"'); + if ($count==0) {$count++; continue;} + } + else + { + $fieldorders=convertToArray($car, "`, `", "(`", "`)"); + $fieldcontents=convertToArray($car, "', '", "('", "')"); + } + $conditionrowdata=array_combine($fieldorders,$fieldcontents); + + $oldcid=$conditionrowdata["cid"]; + $oldqid=$conditionrowdata["qid"]; + $oldcfieldname=$conditionrowdata["cfieldname"]; + $oldcqid=$conditionrowdata["cqid"]; + $thisvalue=$conditionrowdata["value"]; + $newvalue=$thisvalue; + + foreach ($substitutions as $subs) { + if ($oldqid==$subs[2]) {$newqid=$subs[5];} + if ($oldcqid==$subs[2]) {$newcqid=$subs[5];} + } + if (preg_match('/^@([0-9]+)X([0-9]+)X([^@]+)@/',$thisvalue,$targetcfieldname)) + { + foreach ($substitutions as $subs) { + if ($targetcfieldname[1]==$subs[0]) {$targetcfieldname[1]=$subs[3];} + if ($targetcfieldname[2]==$subs[1]) {$targetcfieldname[2]=$subs[4];} + if ($targetcfieldname[3]==$subs[2]) {$targetcfieldname[3]=$subs[5];} + } + $newvalue='@'.$targetcfieldname[1].'X'.$targetcfieldname[2].'X'.$targetcfieldname[3].'@'; + } + foreach($fieldnames as $fns) { + //if the $fns['oldcfieldname'] is not the same as $fns['oldfieldname'] then this is a multiple type question + if ($fns['oldcfieldname'] == $fns['oldfieldname']) { //The normal method - non multiples + if ($oldcfieldname==$fns['oldcfieldname']) { + $newcfieldname=$fns['newcfieldname']; + } + } else { + if ($oldcfieldname == $fns['oldcfieldname'] && $oldcfieldname.$thisvalue == $fns['oldfieldname']) { + $newcfieldname=$fns['newcfieldname']; + } + } + } + if (!isset($newcfieldname)) {$newcfieldname="";} + unset($conditionrowdata["cid"]); + $conditionrowdata["qid"]=$newqid; + $conditionrowdata["cfieldname"]=$newcfieldname; + $conditionrowdata["value"]=$newvalue; + + if (isset($newcqid)) { + $conditionrowdata["cqid"]=$newcqid; + if (!isset($conditionrowdata["method"]) || trim($conditionrowdata["method"])=='') + { + $conditionrowdata["method"]='=='; + } + if (!isset($conditionrowdata["scenario"]) || trim($conditionrowdata["scenario"])=='') + { + $conditionrowdata["scenario"]=1; + } + $newvalues=array_values($conditionrowdata); + $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly + $conditioninsert = "insert INTO {$dbprefix}conditions (".implode(',',array_keys($conditionrowdata)).") VALUES (".implode(',',$newvalues).")"; + $result=$connect->Execute($conditioninsert) or $this->debugLsrc("Import of this survey file failed on Line ".__LINE__."| ".$connect->ErrorMsg()); + } else { + $importsurvey .= "Condition for $oldqid skipped ($oldcqid does not exist)"; + //if ($importingfrom != "http") echo "Condition for $oldqid skipped ($oldcqid does not exist)\n"; + //return; //XXX changed: comment the upper line, returning + } + unset($newcqid); + } + } + + // Translate INSERTANS codes + if (isset($fieldnames)) + { + transInsertAns($newsid,$oldsid,$fieldnames); + } + $surveyid=$newsid; + + return true; + } + + /** + * function to activate surveys based on new activate.php 5771 2008-10-13 02:28:40Z jcleeland $ + * + * @param unknown_type $surveyid + * @return boolean + */ + function activateSurvey($surveyid)//XXX activateSurvey + { + global $connect ; + // global $dbprefix ; + $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC; + include("lsrc.config.php"); + $_GET['sid'] = $surveyid; + $_POST['sid'] = $surveyid; + //$postsid = $surveyid; + //$activateoutput=''; + + $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK "); + + if (!isset($_POST['ok']) || !$_POST['ok']) + { + $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", OK "); + if (isset($_GET['fixnumbering']) && $_GET['fixnumbering']) + { + $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", OK "); + //Fix a question id - requires renumbering a question + $oldqid = $_GET['fixnumbering']; + $query = "SELECT qid FROM {$dbprefix}questions ORDER BY qid DESC"; + $result = db_select_limit_assoc($query, 1) or $this->debugLsrc($query."".$connect->ErrorMsg()); + while ($row=$result->FetchRow()) {$lastqid=$row['qid'];} + $newqid=$lastqid+1; + $query = "UPDATE {$dbprefix}questions SET qid=$newqid WHERE qid=$oldqid"; + $result = $connect->Execute($query) or $this->debugLsrc($query."".$connect->ErrorMsg()); + //Update conditions.. firstly conditions FOR this question + $query = "UPDATE {$dbprefix}conditions SET qid=$newqid WHERE qid=$oldqid"; + $result = $connect->Execute($query) or $this->debugLsrc($query."".$connect->ErrorMsg()); + //Now conditions based upon this question + $query = "SELECT cqid, cfieldname FROM {$dbprefix}conditions WHERE cqid=$oldqid"; + $result = db_execute_assoc($query) or $this->debugLsrc($query."".$connect->ErrorMsg()); + $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", OK "); + while ($row=$result->FetchRow()) + { + $switcher[]=array("cqid"=>$row['cqid'], "cfieldname"=>$row['cfieldname']); + } + if (isset($switcher)) + { + foreach ($switcher as $switch) + { + $query = "UPDATE {$dbprefix}conditions + SET cqid=$newqid, + cfieldname='".str_replace("X".$oldqid, "X".$newqid, $switch['cfieldname'])."' + WHERE cqid=$oldqid"; + $result = $connect->Execute($query) or $this->debugLsrc($query."".$connect->ErrorMsg()); + } + } + $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", OK "); + //Now question_attributes + $query = "UPDATE {$dbprefix}question_attributes SET qid=$newqid WHERE qid=$oldqid"; + $result = $connect->Execute($query) or $this->debugLsrc($query."".$connect->ErrorMsg()); + //Now answers + $query = "UPDATE {$dbprefix}answers SET qid=$newqid WHERE qid=$oldqid"; + $result = $connect->Execute($query) or $this->debugLsrc($query."".$connect->ErrorMsg()); + } + //CHECK TO MAKE SURE ALL QUESTION TYPES THAT REQUIRE ANSWERS HAVE ACTUALLY GOT ANSWERS + //THESE QUESTION TYPES ARE: + // # "L" -> LIST + // # "O" -> LIST WITH COMMENT + // # "M" -> MULTIPLE OPTIONS + // # "P" -> MULTIPLE OPTIONS WITH COMMENTS + // # "A", "B", "C", "E", "F", "H", "^" -> Various Array Types + // # "R" -> RANKING + // # "U" -> FILE CSV MORE + // # "I" -> FILE CSV ONE + // # ":" -> Array Multi Flexi Numbers + // # ";" -> Array Multi Flexi Text + // # "1" -> MULTI SCALE + + + $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", OK "); + + $chkquery = "SELECT qid, question, gid FROM {$dbprefix}questions WHERE sid={$surveyid} AND type IN ('L', 'O', 'M', 'P', 'A', 'B', 'C', 'E', 'F', 'R', 'J', '!', '^', ':', '1')"; + $chkresult = db_execute_assoc($chkquery) or $this->debugLsrc ("Couldn't get list of questions$chkquery".$connect->ErrorMsg()); + while ($chkrow = $chkresult->FetchRow()) + { + $chaquery = "SELECT * FROM {$dbprefix}answers WHERE qid = {$chkrow['qid']} ORDER BY sortorder, answer"; + $charesult=$connect->Execute($chaquery); + $chacount=$charesult->RecordCount(); + if (!$chacount > 0) + { + //$failedcheck[]=array($chkrow['qid'], $chkrow['question'], ": ".("This question is a multiple answer type question but has no answers."), $chkrow['gid']); + } + } + + //NOW CHECK THAT ALL QUESTIONS HAVE A 'QUESTION TYPE' FIELD + $chkquery = "SELECT qid, question, gid FROM {$dbprefix}questions WHERE sid={$surveyid} AND type = ''"; + $chkresult = db_execute_assoc($chkquery) or $this->debugLsrc ("Couldn't check questions for missing types$chkquery".$connect->ErrorMsg()); + while ($chkrow = $chkresult->FetchRow()) + { + //$failedcheck[]=array($chkrow['qid'], $chkrow['question'], ": ".("This question does not have a question 'type' set."), $chkrow['gid']); + } + + $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", OK "); + + + //CHECK THAT FLEXIBLE LABEL TYPE QUESTIONS HAVE AN "LID" SET + $chkquery = "SELECT qid, question, gid FROM {$dbprefix}questions WHERE sid={$surveyid} AND type IN ('F', 'H', 'W', 'Z', ':', '1') AND (lid = 0 OR lid is null)"; + //$chkresult = db_execute_assoc($chkquery) or $this->debugLsrc ("Couldn't check questions for missing LIDs$chkquery".$connect->ErrorMsg()); + while($chkrow = $chkresult->FetchRow()){ + // $failedcheck[]=array($chkrow['qid'], $chkrow['question'], ": ".("This question requires a Labelset, but none is set."), $chkrow['gid']); + } // while + + //CHECK THAT FLEXIBLE LABEL TYPE QUESTIONS HAVE AN "LID1" SET FOR MULTI SCALE + $chkquery = "SELECT qid, question, gid FROM {$dbprefix}questions WHERE sid={$surveyid} AND (type ='1') AND (lid1 = 0 OR lid1 is null)"; + $chkresult = db_execute_assoc($chkquery) or $this->debugLsrc ("Couldn't check questions for missing LIDs$chkquery".$connect->ErrorMsg()); + while($chkrow = $chkresult->FetchRow()){ + // $failedcheck[]=array($chkrow['qid'], $chkrow['question'], ": ".("This question requires a second Labelset, but none is set."), $chkrow['gid']); + } // while + $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", OK "); + + // XXX rakete Changed: This was making errors, for we dont have additional languages and this script throws an error when there are none. + + //NOW check that all used labelsets have all necessary languages + $chkquery = "SELECT qid, question, gid, lid FROM {$dbprefix}questions WHERE sid={$surveyid} AND type IN ('F', 'H', 'W', 'Z', ':', '1') AND (lid > 0) AND (lid is not null)"; + $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", $chkquery "); + $chkresult = db_execute_assoc($chkquery) or $this->debugLsrc ("Couldn't check questions for missing LID languages$chkquery".$connect->ErrorMsg()); + $slangs = GetAdditionalLanguagesFromSurveyID($surveyid); + $baselang = GetBaseLanguageFromSurveyID($surveyid); + array_unshift($slangs,$baselang); + while ($chkrow = $chkresult->FetchRow()) + { + foreach ($slangs as $surveylanguage) + { + $chkquery2 = "SELECT lid FROM {$dbprefix}labels WHERE language='$surveylanguage' AND (lid = {$chkrow['lid']}) "; + $chkresult2 = db_execute_assoc($chkquery2); + if ($chkresult2->RecordCount()==0) + { + $failedcheck[]=array($chkrow['qid'], $chkrow['question'], ": The labelset used in this question does not exists or is missing a translation.", $chkrow['gid']); + } + } //foreach + } //while + + $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", OK "); + //CHECK THAT ALL CONDITIONS SET ARE FOR QUESTIONS THAT PRECEED THE QUESTION CONDITION + //A: Make an array of all the qids in order of appearance + // $qorderquery="SELECT * FROM {$dbprefix}questions, {$dbprefix}groups WHERE {$dbprefix}questions.gid={$dbprefix}groups.gid AND {$dbprefix}questions.sid={$surveyid} ORDER BY {$dbprefix}groups.sortorder, {$dbprefix}questions.title"; + // $qorderresult=$connect->Execute($qorderquery) or $this->debugLsrc("Couldn't generate a list of questions in order$qorderquery".$connect->ErrorMsg()); + // $qordercount=$qorderresult->RecordCount(); + // $c=0; + // while ($qorderrow=$qorderresult->FetchRow()) + // { + // $qidorder[]=array($c, $qorderrow['qid']); + // $c++; + // } + //TO AVOID NATURAL SORT ORDER ISSUES, FIRST GET ALL QUESTIONS IN NATURAL SORT ORDER, AND FIND OUT WHICH NUMBER IN THAT ORDER THIS QUESTION IS + $qorderquery = "SELECT * FROM {$dbprefix}questions WHERE sid=$surveyid AND type not in ('S', 'D', 'T', 'Q')"; + $qorderresult = db_execute_assoc($qorderquery) or $this->debugLsrc ("$qorderquery".$connect->ErrorMsg()); + $qrows = array(); //Create an empty array in case FetchRow does not return any rows + while ($qrow = $qorderresult->FetchRow()) {$qrows[] = $qrow;} // Get table output into array + usort($qrows, 'CompareGroupThenTitle'); // Perform a case insensitive natural sort on group name then question title of a multidimensional array + $c=0; + foreach ($qrows as $qr) + { + $qidorder[]=array($c, $qrow['qid']); + $c++; + } + $qordercount=""; + //1: Get each condition's question id + $conquery= "SELECT {$dbprefix}conditions.qid, cqid, {$dbprefix}questions.question, " + . "{$dbprefix}questions.gid " + . "FROM {$dbprefix}conditions, {$dbprefix}questions, {$dbprefix}groups " + . "WHERE {$dbprefix}conditions.qid={$dbprefix}questions.qid " + . "AND {$dbprefix}questions.gid={$dbprefix}groups.gid ORDER BY {$dbprefix}conditions.qid"; + $conresult=db_execute_assoc($conquery) or $this->debugLsrc("Couldn't check conditions for relative consistency$conquery".$connect->ErrorMsg()); + //2: Check each conditions cqid that it occurs later than the cqid + while ($conrow=$conresult->FetchRow()) + { + $cqidfound=0; + $qidfound=0; + $b=0; + while ($b<$qordercount) + { + if ($conrow['cqid'] == $qidorder[$b][1]) + { + $cqidfound = 1; + $b=$qordercount; + } + if ($conrow['qid'] == $qidorder[$b][1]) + { + $qidfound = 1; + $b=$qordercount; + } + if ($qidfound == 1) + { + //$failedcheck[]=array($conrow['qid'], $conrow['question'], ": ".("This question has a condition set, however the condition is based on a question that appears after it."), $conrow['gid']); + } + $b++; + } + } + //CHECK THAT ALL THE CREATED FIELDS WILL BE UNIQUE + $fieldmap=createFieldMap($surveyid, "full"); + if (isset($fieldmap)) + { + foreach($fieldmap as $fielddata) + { + $fieldlist[]=$fielddata['fieldname']; + } + $fieldlist=array_reverse($fieldlist); //let's always change the later duplicate, not the earlier one + } + $checkKeysUniqueComparison = create_function('$value','if ($value > 1) return true;'); + @$duplicates = array_keys (array_filter (array_count_values($fieldlist), $checkKeysUniqueComparison)); + if (isset($duplicates)) + { + foreach ($duplicates as $dup) + { + $badquestion=arraySearchByKey($dup, $fieldmap, "fieldname", 1); + $fix = "[Click Here to Fix]"; + //$failedcheck[]=array($badquestion['qid'], $badquestion['question'], ": Bad duplicate fieldname $fix", $badquestion['gid']); + } + } + + //IF ANY OF THE CHECKS FAILED, PRESENT THIS SCREEN + if (isset($failedcheck) && $failedcheck) + { + //$activateoutput .= "\n\n"; + //$activateoutput .= "\t\t\t\t\n"; + //$activateoutput .= "\t\n"; + //$activateoutput .= "\t\t\n"; + //$activateoutput .= "\t\n"; + //$activateoutput .= "\t\n"; + //$activateoutput .= "\t\t\n"; + //$activateoutput .= "\t\n"; + //$activateoutput .= "
    ".("Activate Survey")." ($surveyid)
    \n"; + //$activateoutput .= "\t\t\t".("Error")."\n"; + //$activateoutput .= "\t\t\t".("Survey does not pass consistency check")."\n"; + //$activateoutput .= "\t\t
    \n"; + //$activateoutput .= "\t\t\t".("The following problems have been found:")."\n"; + //$activateoutput .= "\t\t\t
      \n"; + foreach ($failedcheck as $fc) + { + //$activateoutput .= "\t\t\t\t
    • Question qid-{$fc[0]} (\"{$fc[1]}\"){$fc[2]}
    • \n"; + } + //$activateoutput .= "\t\t\t
    \n"; + //$activateoutput .= "\t\t\t".("The survey cannot be activated until these problems have been resolved.")."\n"; + //$activateoutput .= "\t\t
     \n"; + $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", NICHT ERWARTET "); + return false; + } + $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", OK "); + //$activateoutput .= "\n\n"; + //$activateoutput .= "\t\t\t\t\n"; + //$activateoutput .= "\t\n"; + //$activateoutput .= "\t\t\n"; + //$activateoutput .= "\t\n"; + //$activateoutput .= "\t\n"; + //$activateoutput .= "\t\t\n"; + //$activateoutput .= "\t\n"; + //$activateoutput .= "\t\n"; + //$activateoutput .= "\t\t\n"; + //$activateoutput .= "\t\n"; + //$activateoutput .= "
    ".("Activate Survey")." ($surveyid)
    \n"; + //$activateoutput .= "\t\t\t".("Warning")."\n"; + //$activateoutput .= "\t\t\t".("READ THIS CAREFULLY BEFORE PROCEEDING")."\n"; + //$activateoutput .= "\t\t\t\n"; + //$activateoutput .= "\t\t
    \n"; + //$activateoutput .= ("You should only activate a survey when you are absolutely certain that your survey setup is finished and will not need changing.")."\n"; + //$activateoutput .= ("Once a survey is activated you can no longer:")."
    • ".("Add or delete groups")."
    • ".("Add or remove answers to Multiple Answer questions")."
    • ".("Add or delete questions")."
    \n"; + //$activateoutput .= ("However you can still:")."
    • ".("Edit (change) your questions code, text or type")."
    • ".("Edit (change) your group names")."
    • ".("Add, Remove or Edit pre-defined question answers (except for Multi-answer questions)")."
    • ".("Change survey name or description")."
    \n"; + //$activateoutput .= ("Once data has been entered into this survey, if you want to add or remove groups or questions, you will need to de-activate this survey, which will move all data that has already been entered into a separate archived table.")."\n"; + //$activateoutput .= "\t\t
    \n"; + //$activateoutput .= "\t\t\t\n"; + //$activateoutput .= "\t\t\t\n"; + //$activateoutput .= "\t\t 
     \n"; + + //XXX Changed rakete, set Post var for lsrc, no else + $_POST['ok'] = "Y"; + $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", OK "); + } + + if (isset($_POST['ok']) || $_POST['ok']) + { + $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", OK "); + //Create the survey responses table + $createsurvey = "id I NOTNULL AUTO PRIMARY,\n"; + $createsurvey .= " submitdate T,\n"; + $createsurvey .= " startlanguage C(20) NOTNULL ,\n"; + //Check for any additional fields for this survey and create necessary fields (token and datestamp) + $pquery = "SELECT private, allowregister, datestamp, ipaddr, refurl FROM {$dbprefix}surveys WHERE sid={$surveyid}"; + $presult=db_execute_assoc($pquery); + while($prow=$presult->FetchRow()) + { + if ($prow['private'] == "N") + { + $createsurvey .= " token C(36),\n"; + $surveynotprivate="TRUE"; + } + if ($prow['allowregister'] == "Y") + { + $surveyallowsregistration="TRUE"; + } + if ($prow['datestamp'] == "Y") + { + $createsurvey .= " datestamp T NOTNULL,\n"; + $createsurvey .= " startdate T NOTNULL,\n"; + } + if ($prow['ipaddr'] == "Y") + { + $createsurvey .= " ipaddr X,\n"; + } + //Check to see if 'refurl' field is required. + if ($prow['refurl'] == "Y") + { + $createsurvey .= " refurl X,\n"; + } + } + //Get list of questions for the base language + $aquery = " SELECT * FROM ".db_table_name('questions').", ".db_table_name('groups') + ." WHERE ".db_table_name('questions').".gid=".db_table_name('groups').".gid " + ." AND ".db_table_name('questions').".sid={$surveyid} " + ." AND ".db_table_name('groups').".language='".GetbaseLanguageFromSurveyid($surveyid). "' " + ." AND ".db_table_name('questions').".language='".GetbaseLanguageFromSurveyid($surveyid). "' " + ." ORDER BY ".db_table_name('groups').".group_order, title"; + $aresult = db_execute_assoc($aquery); + while ($arow=$aresult->FetchRow()) //With each question, create the appropriate field(s) + { + if ( substr($createsurvey, strlen($createsurvey)-2, 2) != ",\n") {$createsurvey .= ",\n";} + + if ($arow['type'] != "M" && $arow['type'] != "A" && $arow['type'] != "B" && + $arow['type'] != "C" && $arow['type'] != "E" && $arow['type'] != "F" && + $arow['type'] != "H" && $arow['type'] != "P" && $arow['type'] != "R" && + $arow['type'] != "Q" && $arow['type'] != "^" && $arow['type'] != "J" && + $arow['type'] != "K" && $arow['type'] != ":" && $arow['type'] != ";" && + $arow['type'] != "1") + { + $createsurvey .= " `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}`"; + switch($arow['type']) + { + case "N": //NUMERICAL + $createsurvey .= " F"; + break; + case "S": //SHORT TEXT + if ($databasetype=='mysql' || $databasetype=='mysqli') {$createsurvey .= " X";} + else {$createsurvey .= " C(255)";} + break; + case "L": //LIST (RADIO) + case "!": //LIST (DROPDOWN) + case "W": + case "Z": + $createsurvey .= " C(5)"; + if ($arow['other'] == "Y") + { + $createsurvey .= ",\n`{$arow['sid']}X{$arow['gid']}X{$arow['qid']}other` X"; + } + break; + case "I": // CSV ONE + $createsurvey .= " C(5)"; + break; + case "O": //DROPDOWN LIST WITH COMMENT + $createsurvey .= " C(5),\n `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}comment` X"; + break; + case "T": //LONG TEXT + $createsurvey .= " X"; + break; + case "U": //HUGE TEXT + $createsurvey .= " X"; + break; + case "D": //DATE + $createsurvey .= " D"; + break; + case "5": //5 Point Choice + case "G": //Gender + case "Y": //YesNo + case "X": //Boilerplate + $createsurvey .= " C(1)"; + break; + } + } + elseif ($arow['type'] == "M" || $arow['type'] == "A" || $arow['type'] == "B" || + $arow['type'] == "C" || $arow['type'] == "E" || $arow['type'] == "F" || + $arow['type'] == "H" || $arow['type'] == "P" || $arow['type'] == "^") + { + //MULTI ENTRY + $abquery = "SELECT a.*, q.other FROM {$dbprefix}answers as a, {$dbprefix}questions as q" + ." WHERE a.qid=q.qid AND sid={$surveyid} AND q.qid={$arow['qid']} " + ." AND a.language='".GetbaseLanguageFromSurveyid($surveyid). "' " + ." AND q.language='".GetbaseLanguageFromSurveyid($surveyid). "' " + ." ORDER BY a.sortorder, a.answer"; + $abresult=db_execute_assoc($abquery) or $this->debugLsrc ("Couldn't get perform answers query$abquery".$connect->ErrorMsg()); + while ($abrow=$abresult->FetchRow()) + { + $createsurvey .= " `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$abrow['code']}` C(5),\n"; + if ($abrow['other']=="Y") {$alsoother="Y";} + if ($arow['type'] == "P") + { + $createsurvey .= " `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$abrow['code']}comment` X,\n"; + } + } + if ((isset($alsoother) && $alsoother=="Y") && ($arow['type']=="M" || $arow['type']=="P" || $arow['type']=="1")) //Sc: check! + { + $createsurvey .= " `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}other` C(255),\n"; + if ($arow['type']=="P") + { + $createsurvey .= " `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}othercomment` X,\n"; + } + } + } + elseif ($arow['type'] == ":" || $arow['type'] == ";") + { + //MULTI ENTRY + $abquery = "SELECT a.*, q.other FROM {$dbprefix}answers as a, {$dbprefix}questions as q" + ." WHERE a.qid=q.qid AND sid={$surveyid} AND q.qid={$arow['qid']} " + ." AND a.language='".GetbaseLanguageFromSurveyid($surveyid). "' " + ." AND q.language='".GetbaseLanguageFromSurveyid($surveyid). "' " + ." ORDER BY a.sortorder, a.answer"; + $abresult=db_execute_assoc($abquery) or die ("Couldn't get perform answers query$abquery".$connect->ErrorMsg()); + $ab2query = "SELECT ".db_table_name('labels').".* + FROM ".db_table_name('questions').", ".db_table_name('labels')." + WHERE sid=$surveyid + AND ".db_table_name('labels').".lid=".db_table_name('questions').".lid + AND ".db_table_name('labels').".language='".GetbaseLanguageFromSurveyid($surveyid)."' + AND ".db_table_name('questions').".qid=".$arow['qid']." + ORDER BY ".db_table_name('labels').".sortorder, ".db_table_name('labels').".title"; + $ab2result=db_execute_assoc($ab2query) or die("Couldn't get list of labels in createFieldMap function (case :)$ab2query".htmlspecialchars($connection->ErrorMsg())); + while($ab2row=$ab2result->FetchRow()) + { + $lset[]=$ab2row; + } + while ($abrow=$abresult->FetchRow()) + { + foreach($lset as $ls) + { + $createsurvey .= " `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$abrow['code']}_{$ls['code']}` X,\n"; + } + } + unset($lset); + } + elseif ($arow['type'] == "Q") + { + $abquery = "SELECT a.*, q.other FROM {$dbprefix}answers as a, {$dbprefix}questions as q WHERE a.qid=q.qid AND sid={$surveyid} AND q.qid={$arow['qid']} " + ." AND a.language='".GetbaseLanguageFromSurveyid($surveyid). "' " + ." AND q.language='".GetbaseLanguageFromSurveyid($surveyid). "' " + ." ORDER BY a.sortorder, a.answer"; + $abresult=db_execute_assoc($abquery) or $this->debugLsrc ("Couldn't get perform answers query$abquery".$connect->ErrorMsg()); + while ($abrow = $abresult->FetchRow()) + { + $createsurvey .= " `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$abrow['code']}`"; + if ($databasetype=='mysql' || $databasetype=='mysqli') + { + $createsurvey .= " X"; + } + else + { + $createsurvey .= " C(255)"; + } + $createsurvey .= ",\n"; + } + } + + elseif ($arow['type'] == "K") //Multiple Numeric - replica of multiple short text, except numbers only + { + $abquery = "SELECT a.*, q.other FROM {$dbprefix}answers as a, {$dbprefix}questions as q WHERE a.qid=q.qid AND sid={$surveyid} AND q.qid={$arow['qid']} " + ." AND a.language='".GetbaseLanguageFromSurveyid($surveyid). "' " + ." AND q.language='".GetbaseLanguageFromSurveyid($surveyid). "' " + ." ORDER BY a.sortorder, a.answer"; + $abresult=db_execute_assoc($abquery) or $this->debugLsrc ("Couldn't get perform answers query$abquery".$connect->ErrorMsg()); + while ($abrow = $abresult->FetchRow()) + { + $createsurvey .= " `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$abrow['code']}` C(20),\n"; + } + } //End if ($arow['type'] == "K") + /* elseif ($arow['type'] == "J") + { + $abquery = "SELECT {$dbprefix}answers.*, {$dbprefix}questions.other FROM {$dbprefix}answers, {$dbprefix}questions WHERE {$dbprefix}answers.qid={$dbprefix}questions.qid AND sid={$surveyid} AND {$dbprefix}questions.qid={$arow['qid']} ORDER BY {$dbprefix}answers.sortorder, {$dbprefix}answers.answer"; + $abresult=db_execute_assoc($abquery) or $this->debugLsrc ("Couldn't get perform answers query$abquery".$connect->ErrorMsg()); + while ($abrow = $abresultt->FetchRow()) + { + $createsurvey .= " `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$abrow['code']}` C(5),\n"; + } + }*/ + elseif ($arow['type'] == "R") + { + //MULTI ENTRY + $abquery = "SELECT a.*, q.other FROM {$dbprefix}answers as a, {$dbprefix}questions as q" + ." WHERE a.qid=q.qid AND sid={$surveyid} AND q.qid={$arow['qid']} " + ." AND a.language='".GetbaseLanguageFromSurveyid($surveyid). "' " + ." AND q.language='".GetbaseLanguageFromSurveyid($surveyid). "' " + ." ORDER BY a.sortorder, a.answer"; + $abresult=$connect->Execute($abquery) or $this->debugLsrc ("Couldn't get perform answers query$abquery".$connect->ErrorMsg()); + $abcount=$abresult->RecordCount(); + for ($i=1; $i<=$abcount; $i++) + { + $createsurvey .= " `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}$i` C(5),\n"; + } + } + elseif ($arow['type'] == "1") + { + $abquery = "SELECT a.*, q.other FROM {$dbprefix}answers as a, {$dbprefix}questions as q" + ." WHERE a.qid=q.qid AND sid={$surveyid} AND q.qid={$arow['qid']} " + ." AND a.language='".GetbaseLanguageFromSurveyid($surveyid). "' " + ." AND q.language='".GetbaseLanguageFromSurveyid($surveyid). "' " + ." ORDER BY a.sortorder, a.answer"; + $abresult=db_execute_assoc($abquery) or $this->debugLsrc ("Couldn't get perform answers query$abquery".$connect->ErrorMsg()); + $abcount=$abresult->RecordCount(); + while ($abrow = $abresult->FetchRow()) + { + $abmultiscalequery = "SELECT a.*, q.other FROM {$dbprefix}answers as a, {$dbprefix}questions as q, {$dbprefix}labels as l" + ." WHERE a.qid=q.qid AND sid={$surveyid} AND q.qid={$arow['qid']} " + ." AND l.lid=q.lid AND sid={$surveyid} AND q.qid={$arow['qid']} AND l.title = '' " + ." AND l.language='".GetbaseLanguageFromSurveyid($surveyid). "' " + ." AND q.language='".GetbaseLanguageFromSurveyid($surveyid). "' "; + $abmultiscaleresult=$connect->Execute($abmultiscalequery) or $this->debugLsrc ("Couldn't get perform answers query$abmultiscalequery".$connect->ErrorMsg()); + $abmultiscaleresultcount =$abmultiscaleresult->RecordCount(); + $abmultiscaleresultcount = 1; + for ($j=0; $j<=$abmultiscaleresultcount; $j++) + { + $createsurvey .= " `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$abrow['code']}#$j` C(5),\n"; + } + } + } + } + + // If last question is of type MCABCEFHP^QKJR let's get rid of the ending coma in createsurvey + $createsurvey = rtrim($createsurvey, ",\n")."\n"; // Does nothing if not ending with a comma + $tabname = "{$dbprefix}survey_{$surveyid}"; # not using db_table_name as it quotes the table name (as does CreateTableSQL) + + $taboptarray = array('mysql' => 'ENGINE='.$databasetabletype.' CHARACTER SET utf8 COLLATE utf8_unicode_ci', + 'mysqli' => 'ENGINE='.$databasetabletype.' CHARACTER SET utf8 COLLATE utf8_unicode_ci'); + $dict = NewDataDictionary($connect); + $sqlarray = $dict->CreateTableSQL($tabname, $createsurvey, $taboptarray); + $execresult=$dict->ExecuteSQLArray($sqlarray,1); + if ($execresult==0 || $execresult==1) + { + // $activateoutput .= "\n\n" . + // "\n" . + // "
    ".("Activate Survey")." ($surveyid)
    \n" . + // "".("Survey could not be actived.")."\n" . + // "
    ".("Main Admin Screen")."
    \n" . + // "DB ".("Error").":\n" . $connect->ErrorMsg() . "\n" . + // "
    $createsurvey
    \n" . + // "

     \n" . + // "\n"; + } + if ($execresult != 0 && $execresult !=1) + { + $anquery = "SELECT autonumber_start FROM {$dbprefix}surveys WHERE sid={$surveyid}"; + if ($anresult=db_execute_assoc($anquery)) + { + //if there is an autonumber_start field, start auto numbering here + while($row=$anresult->FetchRow()) + { + if ($row['autonumber_start'] > 0) + { + $autonumberquery = "ALTER TABLE {$dbprefix}survey_{$surveyid} AUTO_INCREMENT = ".$row['autonumber_start']; + if ($result = $connect->Execute($autonumberquery)) + { + //We're happy it worked! + } + else + { + //Continue regardless - it's not the end of the world + } + } + } + } + + //$activateoutput .= "\n\n"; + //$activateoutput .= "\t\t\t\t\n"; + //$activateoutput .= "\t\t\t\t
    ".("Activate Survey")." ($surveyid)
    ".("Survey has been activated. Results table has been successfully created.")."\n"; + $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK "); + $acquery = "UPDATE {$dbprefix}surveys SET active='Y' WHERE sid=".$surveyid; + $acresult = $connect->Execute($acquery); + $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", FERTIG "); + } + + } + return true; + } // end activateSurvey(); + + /** + * not used, a test, thought this could maybe enhance security, may be deleted + * + * @return Error 404 fake + */ + function fake404()// XXX + { + return ' + + + Objekt nicht gefunden! + + + + + +

    Objekt nicht gefunden!

    +

    + + + Der angeforderte URL konnte auf dem Server nicht gefunden werden. + + + + Sofern Sie den URL manuell eingegeben haben, + überprüfen Sie bitte die Schreibweise und versuchen Sie es erneut. + + + +

    +

    + Sofern Sie dies für eine Fehlfunktion des Servers halten, + informieren Sie bitte den + Webmaster + hierüber. + +

    + +

    Error 404

    +
    + + '.$_SERVER["SERVER_NAME"].' + + '.date("m/d/Y H:i:s").' + Apache/2.2.9 (Win32) DAV/2 mod_ssl/2.2.9 OpenSSL/0.9.8i mod_autoindex_color PHP/5.2.6 mod_jk/1.2.26 +
    + + + + '; + } + + /** + * importing a group into an existing survey + * + * @param int $iVid SurveyID + * @param string $sMod Group that should be loaded into the Survey + */ + function importGroup($surveyid, $sMod) //XXX + { + global $connect ; + // global $dbprefix ; + $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC; + include("lsrc.config.php"); + $newsid = $surveyid; + + $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK "); + + $the_full_file_path = $modDir.$sMod.".csv"; + + $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK $the_full_file_path "); + + $handle = fopen($the_full_file_path, "r"); + while (!feof($handle)) + { + $buffer = fgets($handle); + $bigarray[] = $buffer; + } + fclose($handle); + + if (substr($bigarray[0], 0, 23) != "# LimeSurvey Group Dump" && substr($bigarray[0], 0, 24) != "# PHPSurveyor Group Dump") + { + //$importgroup .= "".("Error")."\n"; + //$importgroup .= ("This file is not a LimeSurvey group file. Import failed.")."\n"; + //$importgroup .= "\n"; + //$importgroup .= "
    \n"; + //unlink($the_full_file_path); + return false; + } + + for ($i=0; $i<9; $i++) + { + unset($bigarray[$i]); + } + $bigarray = array_values($bigarray); + + //GROUPS + if (array_search("# QUESTIONS TABLE\n", $bigarray)) + { + $stoppoint = array_search("# QUESTIONS TABLE\n", $bigarray); + } + elseif (array_search("# QUESTIONS TABLE\r\n", $bigarray)) + { + $stoppoint = array_search("# QUESTIONS TABLE\r\n", $bigarray); + } + else + { + $stoppoint = count($bigarray)-1; + } + for ($i=0; $i<=$stoppoint+1; $i++) + { + if ($i<$stoppoint-2) {$grouparray[] = $bigarray[$i];} + unset($bigarray[$i]); + } + $bigarray = array_values($bigarray); + $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK "); + //QUESTIONS + if (array_search("# ANSWERS TABLE\n", $bigarray)) + { + $stoppoint = array_search("# ANSWERS TABLE\n", $bigarray); + } + elseif (array_search("# ANSWERS TABLE\r\n", $bigarray)) + { + $stoppoint = array_search("# ANSWERS TABLE\r\n", $bigarray); + } + else + { + $stoppoint = count($bigarray)-1; + } + for ($i=0; $i<=$stoppoint+1; $i++) + { + if ($i<$stoppoint-2) {$questionarray[] = $bigarray[$i];} + unset($bigarray[$i]); + } + $bigarray = array_values($bigarray); + $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK "); + //ANSWERS + if (array_search("# CONDITIONS TABLE\n", $bigarray)) + { + $stoppoint = array_search("# CONDITIONS TABLE\n", $bigarray); + } + elseif (array_search("# CONDITIONS TABLE\r\n", $bigarray)) + { + $stoppoint = array_search("# CONDITIONS TABLE\r\n", $bigarray); + } + else + { + $stoppoint = count($bigarray)-1; + } + for ($i=0; $i<=$stoppoint+1; $i++) + { + if ($i<$stoppoint-2) {$answerarray[] = $bigarray[$i];} + unset($bigarray[$i]); + } + $bigarray = array_values($bigarray); + $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK "); + //CONDITIONS + if (array_search("# LABELSETS TABLE\n", $bigarray)) + { + $stoppoint = array_search("# LABELSETS TABLE\n", $bigarray); + } + elseif (array_search("# LABELSETS TABLE\r\n", $bigarray)) + { + $stoppoint = array_search("# LABELSETS TABLE\r\n", $bigarray); + } + else + { + $stoppoint = count($bigarray); + } + for ($i=0; $i<=$stoppoint+1; $i++) + { + if ($i<$stoppoint-2) {$conditionsarray[] = $bigarray[$i];} + unset($bigarray[$i]); + } + $bigarray = array_values($bigarray); + $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK "); + //LABELSETS + if (array_search("# LABELS TABLE\n", $bigarray)) + { + $stoppoint = array_search("# LABELS TABLE\n", $bigarray); + } + elseif (array_search("# LABELS TABLE\r\n", $bigarray)) + { + $stoppoint = array_search("# LABELS TABLE\r\n", $bigarray); + } + else + { + $stoppoint = count($bigarray)-1; + } + for ($i=0; $i<=$stoppoint+1; $i++) + { + if ($i<$stoppoint-2) {$labelsetsarray[] = $bigarray[$i];} + unset($bigarray[$i]); + } + $bigarray = array_values($bigarray); + $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK "); + //LABELS + if (array_search("# QUESTION_ATTRIBUTES TABLE\n", $bigarray)) + { + $stoppoint = array_search("# QUESTION_ATTRIBUTES TABLE\n", $bigarray); + } + elseif (array_search("# QUESTION_ATTRIBUTES TABLE\r\n", $bigarray)) + { + $stoppoint = array_search("# QUESTION_ATTRIBUTES TABLE\r\n", $bigarray); + } + else + { + $stoppoint = count($bigarray)-1; + } + for ($i=0; $i<=$stoppoint+1; $i++) + { + if ($i<$stoppoint-2) {$labelsarray[] = $bigarray[$i];} + unset($bigarray[$i]); + } + $bigarray = array_values($bigarray); + $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK "); + //LAST LOT (now question_attributes) + if (!isset($noconditions) || $noconditions != "Y") + { + // stoppoint is the last line number + // this is an empty line after the QA CSV lines + $stoppoint = count($bigarray)-1; + for ($i=0; $i<=$stoppoint+1; $i++) + { + if ($i<=$stoppoint-1) {$question_attributesarray[] = $bigarray[$i];} + unset($bigarray[$i]); + } + } + $bigarray = array_values($bigarray); + + $countgroups=0; + if (isset($questionarray)) + { + $questionfieldnames=convertCSVRowToArray($questionarray[0],',','"'); + unset($questionarray[0]); + $countquestions = 0; + } + + if (isset($answerarray)) + { + $answerfieldnames=convertCSVRowToArray($answerarray[0],',','"'); + unset($answerarray[0]); + $countanswers = 0; + } + + $countconditions = 0; + $countlabelsets=0; + $countlabels=0; + $countquestion_attributes = 0; + $countanswers = 0; + + $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK "); + // first check that imported group, questions and labels support the + // current survey's baselang + $langcode = GetBaseLanguageFromSurveyID($newsid); + if (isset($grouparray)) + { + $groupfieldnames = convertCSVRowToArray($grouparray[0],',','"'); + $langfieldnum = array_search("language", $groupfieldnames); + $gidfieldnum = array_search("gid", $groupfieldnames); + $groupssupportbaselang = bDoesImportarraySupportsLanguage($grouparray,Array($gidfieldnum),$langfieldnum,$langcode,true); + if (!$groupssupportbaselang) + { + //$importgroup .= "".("Error")."\n"; + //$importgroup .= ("You can't import a group which doesn't support the current survey's base language.")."\n"; + //$importgroup .= "\n"; + //$importgroup .= "\n"; + //unlink($the_full_file_path); + return "Group does not support Surveys Baselanguage ($langcode)"; + } + } + $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK "); + if (isset($questionarray)) + { + $langfieldnum = array_search("language", $questionfieldnames); + $qidfieldnum = array_search("qid", $questionfieldnames); + $questionssupportbaselang = bDoesImportarraySupportsLanguage($questionarray,Array($qidfieldnum), $langfieldnum,$langcode,false); + if (!$questionssupportbaselang) + { + //$importgroup .= "".("Error")."\n"; + //$importgroup .= ("You can't import a question which doesn't support the current survey's base language.")."\n"; + //$importgroup .= "\n"; + //$importgroup .= "\n"; + //unlink($the_full_file_path); + return "Group does not support Surveys Baselanguage ($langcode)"; + } + } + + $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK "); + if (isset($labelsetsarray)) + { + $labelsetfieldname = convertCSVRowToArray($labelsetsarray[0],',','"'); + $langfieldnum = array_search("languages", $labelsetfieldname); + $lidfilednum = array_search("lid", $labelsetfieldname); + $labelsetssupportbaselang = bDoesImportarraySupportsLanguage($labelsetsarray,Array($lidfilednum),$langfieldnum,$langcode,true); + if (!$labelsetssupportbaselang) + { + $importquestion .= "".("Error")."\n" + .("You can't import label sets which don't support the current survey's base language")."\n" + ."\n"; + //unlink($the_full_file_path); + return "Group does not support Surveys Baselanguage ($langcode)"; + } + } + + $newlids = array(); // this array will have the "new lid" for the label sets, the key will be the "old lid" + $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK "); + //DO ANY LABELSETS FIRST, SO WE CAN KNOW WHAT THEIR NEW LID IS FOR THE QUESTIONS + if (isset($labelsetsarray) && $labelsetsarray) { + $csarray=buildLabelSetCheckSumArray(); // build checksums over all existing labelsets + $count=0; + foreach ($labelsetsarray as $lsa) { + $fieldorders =convertCSVRowToArray($labelsetsarray[0],',','"'); + $fieldcontents=convertCSVRowToArray($lsa,',','"'); + if ($count==0) {$count++; continue;} + + $countlabelsets++; + + $labelsetrowdata=array_combine($fieldorders,$fieldcontents); + + // Save old labelid + $oldlid=$labelsetrowdata['lid']; + // set the new language + unset($labelsetrowdata['lid']); + $newvalues=array_values($labelsetrowdata); + $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly + $lsainsert = "INSERT INTO {$dbprefix}labelsets (".implode(',',array_keys($labelsetrowdata)).") VALUES (".implode(',',$newvalues).")"; //handle db prefix + $lsiresult=$connect->Execute($lsainsert); + + // Get the new insert id for the labels inside this labelset + $newlid=$connect->Insert_ID("{$dbprefix}labelsets",'lid'); + + if ($labelsarray) { + $count=0; + foreach ($labelsarray as $la) { + $lfieldorders =convertCSVRowToArray($labelsarray[0],',','"'); + $lfieldcontents=convertCSVRowToArray($la,',','"'); + if ($count==0) {$count++; continue;} + + // Combine into one array with keys and values since its easier to handle + $labelrowdata=array_combine($lfieldorders,$lfieldcontents); + $labellid=$labelrowdata['lid']; + if ($labellid == $oldlid) { + $labelrowdata['lid']=$newlid; + + // translate internal links + $labelrowdata['title']=translink('label', $oldlid, $newlid, $labelrowdata['title']); + + $newvalues=array_values($labelrowdata); + $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly + $lainsert = "INSERT INTO {$dbprefix}labels (".implode(',',array_keys($labelrowdata)).") VALUES (".implode(',',$newvalues).")"; //handle db prefix + $liresult=$connect->Execute($lainsert); + $countlabels++; + } + } + } + + //CHECK FOR DUPLICATE LABELSETS + $thisset=""; + $query2 = "SELECT code, title, sortorder, language + FROM {$dbprefix}labels + WHERE lid=".$newlid." + ORDER BY language, sortorder, code"; + $result2 = db_execute_num($query2) or $this->debugLsrc("Died querying labelset $lid$query2".$connect->ErrorMsg()); + while($row2=$result2->FetchRow()) + { + $thisset .= implode('.', $row2); + } // while + $newcs=dechex(crc32($thisset)*1); + unset($lsmatch); + if (isset($csarray)) + { + foreach($csarray as $key=>$val) + { + if ($val == $newcs) + { + $lsmatch=$key; + } + } + } + if (isset($lsmatch)) + { + //There is a matching labelset. So, we will delete this one and refer + //to the matched one. + $query = "DELETE FROM {$dbprefix}labels WHERE lid=$newlid"; + $result=$connect->Execute($query) or $this->debugLsrc("Couldn't delete labels$query".$connect->ErrorMsg()); + $query = "DELETE FROM {$dbprefix}labelsets WHERE lid=$newlid"; + $result=$connect->Execute($query) or $this->debugLsrc("Couldn't delete labelset$query".$connect->ErrorMsg()); + $newlid=$lsmatch; + } + else + { + //There isn't a matching labelset, add this checksum to the $csarray array + $csarray[$newlid]=$newcs; + } + //END CHECK FOR DUPLICATES + $labelreplacements[]=array($oldlid, $newlid); + $newlids[$oldlid] = $newlid; + } + } + $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK "); + //these arrays will aloud to insert correctly groups an questions multi languague survey imports correctly, and will eliminate the need to "searh" the imported data + //$newgids = array(); // this array will have the "new gid" for the groups, the kwy will be the "old gid" <-- not needed when importing groups + $newqids = array(); // this array will have the "new qid" for the questions, the kwy will be the "old qid" + + // DO GROUPS, QUESTIONS FOR GROUPS, THEN ANSWERS FOR QUESTIONS IN A __NOT__ NESTED FORMAT! + if (isset($grouparray) && $grouparray) + { + $surveylanguages=GetAdditionalLanguagesFromSurveyID($surveyid); + $surveylanguages[]=GetBaseLanguageFromSurveyID($surveyid); + + // do GROUPS + $gafieldorders=convertCSVRowToArray($grouparray[0],',','"'); + unset($grouparray[0]); + $newgid = 0; + $group_order = 0; // just to initialize this variable + foreach ($grouparray as $ga) + { + //GET ORDER OF FIELDS + $gacfieldcontents=convertCSVRowToArray($ga,',','"'); + $grouprowdata=array_combine($gafieldorders,$gacfieldcontents); + + // Skip not supported languages + if (!in_array($grouprowdata['language'],$surveylanguages)) + { + $skippedlanguages[]=$grouprowdata['language']; // this is for the message in the end. + continue; + } + + // replace the sid + $oldsid=$grouprowdata['sid']; + $grouprowdata['sid']=$newsid; + + // replace the gid or remove it if needed (it also will calculate the group order if is a new group) + $oldgid=$grouprowdata['gid']; + if ($newgid == 0) + { + unset($grouprowdata['gid']); + + // find the maximum group order and use this grouporder+1 to assign it to the new group + $qmaxgo = "select max(group_order) as maxgo from ".db_table_name('groups')." where sid=$newsid"; + $gres = db_execute_assoc($qmaxgo) or $this->debugLsrc (("Error")." Failed to find out maximum group order value\n$qmaxqo\n".$connect->ErrorMsg()); + $grow=$gres->FetchRow(); + $group_order = $grow['maxgo']+1; + } + else + $grouprowdata['gid'] = $newgid; + + $grouprowdata["group_order"]= $group_order; + + // Everything set - now insert it + $grouprowdata=array_map('convertCsvreturn2return', $grouprowdata); + + + // translate internal links + $grouprowdata['group_name']=translink('survey', $oldsid, $newsid, $grouprowdata['group_name']); + $grouprowdata['description']=translink('survey', $oldsid, $newsid, $grouprowdata['description']); + + $newvalues=array_values($grouprowdata); + $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly + $ginsert = "insert INTO {$dbprefix}groups (".implode(',',array_keys($grouprowdata)).") VALUES (".implode(',',$newvalues).")"; + $gres = $connect->Execute($ginsert) or $this->debugLsrc("Error: ".": Failed to insert group\n$ginsert\n".$connect->ErrorMsg()); + + //GET NEW GID .... if is not done before and we count a group if a new gid is required + if ($newgid == 0) + { + $newgid = $connect->Insert_ID("{$dbprefix}groups",'gid'); + $countgroups++; + } + } + // GROUPS is DONE + + // do QUESTIONS + if (isset($questionarray) && $questionarray) + { + foreach ($questionarray as $qa) + { + $qacfieldcontents=convertCSVRowToArray($qa,',','"'); + $questionrowdata=array_combine($questionfieldnames,$qacfieldcontents); + + // Skip not supported languages + if (!in_array($questionrowdata['language'],$surveylanguages)) + continue; + + // replace the sid + $questionrowdata["sid"] = $newsid; + + // replace the gid (if the gid is not in the oldgid it means there is a problem with the exported record, so skip it) + if ($questionrowdata['gid'] == $oldgid) + $questionrowdata['gid'] = $newgid; + else + continue; // a problem with this question record -> don't consider + + // replace the qid or remove it if needed + $oldqid = $questionrowdata['qid']; + if (isset($newqids[$oldqid])) + $questionrowdata['qid'] = $newqids[$oldqid]; + else + unset($questionrowdata['qid']); + + // replace the lid for the new one (if there is no new lid in the $newlids array it mean that was not imported -> error, skip this record) + if (in_array($questionrowdata["type"], array("F","H","W","Z", "1", ":", ";"))) // only fot the questions that uses a label set. + if (isset($newlids[$questionrowdata["lid"]])) + { + $questionrowdata["lid"] = $newlids[$questionrowdata["lid"]]; + if(isset($newlids[$questionrowdata["lid1"]])) + { + $questionrowdata["lid1"] = $newlids[$questionrowdata["lid1"]]; + } + } + else + { + continue; // a problem with this question record -> don't consider + } + // $other = $questionrowdata["other"]; //Get 'other' field value + // $oldlid = $questionrowdata['lid']; + + // Everything set - now insert it + $questionrowdata=array_map('convertCsvreturn2return', $questionrowdata); + + // translate internal links ///XXX rakete may change question data here + // $questionrowdata['title']=translink('survey', $oldsid, $newsid, $questionrowdata['title']); + // $questionrowdata['question']=translink('survey', $oldsid, $newsid, $questionrowdata['question']); + // $questionrowdata['help']=translink('survey', $oldsid, $newsid, $questionrowdata['help']); + + $newvalues=array_values($questionrowdata); + $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly + $qinsert = "insert INTO {$dbprefix}questions (".implode(',',array_keys($questionrowdata)).") VALUES (".implode(',',$newvalues).")"; + $qres = $connect->Execute($qinsert) or $this->debugLsrc ("Error: "."Failed to insert question\n$qinsert\n".$connect->ErrorMsg()); + + //GET NEW QID .... if is not done before and we count a question if a new qid is required + if (!isset($newqids[$oldqid])) + { + $newqids[$oldqid] = $connect->Insert_ID("{$dbprefix}questions",'qid'); + $myQid=$newqids[$oldqid]; + $countquestions++; + } + else + { + $myQid=$newqids[$oldqid]; + } + } + } + // QESTIONS is DONE + $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK "); + // do ANSWERS + if (isset($answerarray) && $answerarray) + { + foreach ($answerarray as $aa) + { + $aacfieldcontents=convertCSVRowToArray($aa,',','"'); + $answerrowdata=array_combine($answerfieldnames,$aacfieldcontents); + + // Skip not supported languages + if (!in_array($answerrowdata['language'],$surveylanguages)) + continue; + + // replace the qid for the new one (if there is no new qid in the $newqids array it mean that this answer is orphan -> error, skip this record) + if (isset($newqids[$answerrowdata["qid"]])) + $answerrowdata["qid"] = $newqids[$answerrowdata["qid"]]; + else + continue; // a problem with this answer record -> don't consider + + // Everything set - now insert it + $answerrowdata = array_map('convertCsvreturn2return', $answerrowdata); + + // translate internal links + $answerrowdata['answer']=translink('survey', $oldsid, $newsid, $answerrowdata['answer']); + + $newvalues=array_values($answerrowdata); + $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly + $ainsert = "insert INTO {$dbprefix}answers (".implode(',',array_keys($answerrowdata)).") VALUES (".implode(',',$newvalues).")"; + $ares = $connect->Execute($ainsert) or $this->debugLsrc ("Error: "."Failed to insert answer\n$ainsert\n".$connect->ErrorMsg()); + $countanswers++; + } + } + // ANSWERS is DONE + $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK "); + // Fix Group sortorder + //fixsortorderGroups(); //XXX commented out by rakete... and written in full length + $baselang = GetBaseLanguageFromSurveyID($surveyid); + $cdresult = db_execute_assoc("SELECT gid FROM ".db_table_name('groups')." WHERE sid='{$surveyid}' AND language='{$baselang}' ORDER BY group_order, group_name"); + $position=0; + while ($cdrow=$cdresult->FetchRow()) + { + $cd2query="UPDATE ".db_table_name('groups')." SET group_order='{$position}' WHERE gid='{$cdrow['gid']}' "; + $cd2result = $connect->Execute($cd2query) or $this->debugLsrc ("Couldn't update group_order$cd2query".$connect->ErrorMsg()); //Checked + $position++; + } + + + //... and for the questions inside the groups + // get all group ids and fix questions inside each group + $gquery = "SELECT gid FROM {$dbprefix}groups where sid=$newsid group by gid ORDER BY gid"; //Get last question added (finds new qid) + $gres = db_execute_assoc($gquery); + while ($grow = $gres->FetchRow()) + { + //fixsortorderQuestions(0,$grow['gid']); + $qid=sanitize_int(0); + $gid=sanitize_int($grow['gid']); + $baselang = GetBaseLanguageFromSurveyID($surveyid); + if ($gid == 0) + { + $result = db_execute_assoc("SELECT gid FROM ".db_table_name('questions')." WHERE qid='{$qid}' and language='{$baselang}'"); //Checked + $row=$result->FetchRow(); + $gid=$row['gid']; + } + $cdresult = db_execute_assoc("SELECT qid FROM ".db_table_name('questions')." WHERE gid='{$gid}' and language='{$baselang}' ORDER BY question_order, title ASC"); //Checked + $position=0; + while ($cdrow=$cdresult->FetchRow()) + { + $cd2query="UPDATE ".db_table_name('questions')." SET question_order='{$position}' WHERE qid='{$cdrow['qid']}' "; + $cd2result = $connect->Execute($cd2query) or $this->debugLsrc ("Couldn't update question_order$cd2query".$connect->ErrorMsg()); //Checked + $position++; + } + } + } + $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK "); + // do ATTRIBUTES + if (isset($question_attributesarray) && $question_attributesarray) + { + $fieldorders =convertCSVRowToArray($question_attributesarray[0],',','"'); + unset($question_attributesarray[0]); + foreach ($question_attributesarray as $qar) { + $fieldcontents=convertCSVRowToArray($qar,',','"'); + $qarowdata=array_combine($fieldorders,$fieldcontents); + + // replace the qid for the new one (if there is no new qid in the $newqids array it mean that this attribute is orphan -> error, skip this record) + if (isset($newqids[$qarowdata["qid"]])) + $qarowdata["qid"] = $newqids[$qarowdata["qid"]]; + else + continue; // a problem with this answer record -> don't consider + + unset($qarowdata["qaid"]); + + // Everything set - now insert it + $newvalues=array_values($qarowdata); + $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly + $qainsert = "insert INTO {$dbprefix}question_attributes (".implode(',',array_keys($qarowdata)).") VALUES (".implode(',',$newvalues).")"; + $result=$connect->Execute($qainsert) or $this->debugLsrc ("Couldn't insert question_attribute$qainsert".$connect->ErrorMsg()); + $countquestion_attributes++; + } + } + // ATTRIBUTES is DONE + $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK "); + // do CONDITIONS + if (isset($conditionsarray) && $conditionsarray) + { + $fieldorders=convertCSVRowToArray($conditionsarray[0],',','"'); + unset($conditionsarray[0]); + foreach ($conditionsarray as $car) { + $fieldcontents=convertCSVRowToArray($car,',','"'); + $conditionrowdata=array_combine($fieldorders,$fieldcontents); + + $oldqid = $conditionrowdata["qid"]; + $oldcqid = $conditionrowdata["cqid"]; + + // replace the qid for the new one (if there is no new qid in the $newqids array it mean that this condition is orphan -> error, skip this record) + if (isset($newqids[$oldqid])) + $conditionrowdata["qid"] = $newqids[$oldqid]; + else + continue; // a problem with this answer record -> don't consider + + // replace the cqid for the new one (if there is no new qid in the $newqids array it mean that this condition is orphan -> error, skip this record) + if (isset($newqids[$oldcqid])) + $conditionrowdata["cqid"] = $newqids[$oldcqid]; + else + continue; // a problem with this answer record -> don't consider + + list($oldcsid, $oldcgid, $oldqidanscode) = explode("X",$conditionrowdata["cfieldname"],3); + + if ($oldcgid != $oldgid) // this means that the condition is in another group (so it should not have to be been exported -> skip it + continue; + + unset($conditionrowdata["cid"]); + + // recreate the cfieldname with the new IDs + $newcfieldname = $newsid . "X" . $newgid . "X" . $conditionrowdata["cqid"] .substr($oldqidanscode,strlen($oldqid)); + + $conditionrowdata["cfieldname"] = $newcfieldname; + if (!isset($conditionrowdata["method"]) || trim($conditionrowdata["method"])=='') + { + $conditionrowdata["method"]='=='; + } + $newvalues=array_values($conditionrowdata); + $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly + $conditioninsert = "insert INTO {$dbprefix}conditions (".implode(',',array_keys($conditionrowdata)).") VALUES (".implode(',',$newvalues).")"; + $result=$connect->Execute($conditioninsert) or $this->debugLsrc ("Couldn't insert condition$conditioninsert".$connect->ErrorMsg()); + $countconditions++; + } + } + $this->debugLsrc("wir sind in - ".__FUNCTION__." Line ".__LINE__.", FERTIG "); + // CONDITIONS is DONE + return array('gid'=>$newgid,'qid'=>$myQid); + //return $newgid; + } + + /** + * + * Enter description here... + * @param $surveyid + * @param $sMod + * @param $newGroup + * @return unknown_type + */ + function importQuestion($surveyid, $sMod, $newGroup=false) //XXX + { + global $connect ; + //global $dbprefix ; + $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC; + include("lsrc.config.php"); + $newsid = $surveyid; + + $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", START OK $dbprefix "); + + //$getGidSql = "SELECT gid FROM {$dbprefix} "; + $getGidSql = "SELECT gid + FROM {$dbprefix}groups + WHERE sid=".$surveyid." AND language='".GetBaseLanguageFromSurveyID($surveyid)."' + ORDER BY gid desc "; + $getGidRs = db_execute_num($getGidSql); + $gidRow=$getGidRs->FetchRow(); + $gid = $gidRow[0]; + + if($gid=='')# + { + $this->debugLsrc("No Group for importing the question, available!"); + return "No Group for importing the question, available! Import failed."; + } + + if($newGroup===true) + ++$gid; + + $the_full_file_path = $queDir.$sMod.".csv"; + + $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK $the_full_file_path "); + + $handle = fopen($the_full_file_path, "r"); + while (!feof($handle)) + { + $buffer = fgets($handle, 10240); //To allow for very long survey welcomes (up to 10k) + $bigarray[] = $buffer; + } + fclose($handle); + + // Now we try to determine the dataformat of the survey file. + if ((substr($bigarray[1], 0, 24) == "# SURVEYOR QUESTION DUMP")&& (substr($bigarray[4], 0, 29) == "# http://www.phpsurveyor.org/")) + { + $importversion = 100; // version 1.0 file + } + elseif + ((substr($bigarray[1], 0, 24) == "# SURVEYOR QUESTION DUMP")&& (substr($bigarray[4], 0, 37) == "# http://phpsurveyor.sourceforge.net/")) + { + $importversion = 99; // Version 0.99 file or older - carries a different URL + } + elseif + (substr($bigarray[0], 0, 26) == "# LimeSurvey Question Dump" || substr($bigarray[0], 0, 27) == "# PHPSurveyor Question Dump") + { // Wow.. this seems to be a >1.0 version file - these files carry the version information to read in line two + $importversion=substr($bigarray[1], 12, 3); + } + else // unknown file - show error message + { + // $importquestion .= "".("Error")."\n"; + // $importquestion .= ("This file is not a LimeSurvey question file. Import failed.")."\n"; + // $importquestion .= "\n"; + // $importquestion .= "\n\n"; + // unlink($the_full_file_path); + return "This is not a Limesurvey question file. Import failed"; + } + + // if ($importversion != $dbversionnumber) + // { + //// $importquestion .= "".("Error")."\n"; + //// $importquestion .= ("Sorry, importing questions is limited to the same version. Import failed.")."\n"; + //// $importquestion .= "\n"; + //// $importquestion .= "\n\n"; + //// unlink($the_full_file_path); + // return; + // } + $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK "); + for ($i=0; $i<9; $i++) //skipping the first lines that are not needed + { + unset($bigarray[$i]); + } + $bigarray = array_values($bigarray); + $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK "); + //QUESTIONS + if (array_search("# ANSWERS TABLE\n", $bigarray)) + { + $stoppoint = array_search("# ANSWERS TABLE\n", $bigarray); + } + elseif (array_search("# ANSWERS TABLE\r\n", $bigarray)) + { + $stoppoint = array_search("# ANSWERS TABLE\r\n", $bigarray); + } + else + { + $stoppoint = count($bigarray)-1; + } + for ($i=0; $i<=$stoppoint+1; $i++) + { + if ($i<$stoppoint-2) {$questionarray[] = $bigarray[$i];} + unset($bigarray[$i]); + } + $bigarray = array_values($bigarray); + $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK "); + //ANSWERS + if (array_search("# LABELSETS TABLE\n", $bigarray)) + { + $stoppoint = array_search("# LABELSETS TABLE\n", $bigarray); + } + elseif (array_search("# LABELSETS TABLE\r\n", $bigarray)) + { + $stoppoint = array_search("# LABELSETS TABLE\r\n", $bigarray); + } + else + { + $stoppoint = count($bigarray)-1; + } + for ($i=0; $i<=$stoppoint+1; $i++) + { + if ($i<$stoppoint-2) {$answerarray[] = str_replace("`default`", "`default_value`", $bigarray[$i]);} + unset($bigarray[$i]); + } + $bigarray = array_values($bigarray); + $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK "); + //LABELSETS + if (array_search("# LABELS TABLE\n", $bigarray)) + { + $stoppoint = array_search("# LABELS TABLE\n", $bigarray); + } + elseif (array_search("# LABELS TABLE\r\n", $bigarray)) + { + $stoppoint = array_search("# LABELS TABLE\r\n", $bigarray); + } + else + { + $stoppoint = count($bigarray)-1; + } + for ($i=0; $i<=$stoppoint+1; $i++) + { + if ($i<$stoppoint-2) {$labelsetsarray[] = $bigarray[$i];} + unset($bigarray[$i]); + } + $bigarray = array_values($bigarray); + $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK "); + //LABELS + if (array_search("# QUESTION_ATTRIBUTES TABLE\n", $bigarray)) + { + $stoppoint = array_search("# QUESTION_ATTRIBUTES TABLE\n", $bigarray); + } + elseif (array_search("# QUESTION_ATTRIBUTES TABLE\r\n", $bigarray)) + { + $stoppoint = array_search("# QUESTION_ATTRIBUTES TABLE\r\n", $bigarray); + } + else + { + $stoppoint = count($bigarray)-1; + } + for ($i=0; $i<=$stoppoint+1; $i++) + { + if ($i<$stoppoint-2) {$labelsarray[] = $bigarray[$i];} + unset($bigarray[$i]); + } + $bigarray = array_values($bigarray); + $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK "); + //Question_attributes + if (!isset($noconditions) || $noconditions != "Y") + { + $stoppoint = count($bigarray); + for ($i=0; $i<=$stoppoint+1; $i++) + { + if ($i<$stoppoint-1) {$question_attributesarray[] = $bigarray[$i];} + unset($bigarray[$i]); + } + } + $bigarray = array_values($bigarray); + + if (isset($questionarray)) {$countquestions = count($questionarray)-1;} else {$countquestions=0;} + if (isset($answerarray)) + { + $answerfieldnames=convertCSVRowToArray($answerarray[0],',','"'); + unset($answerarray[0]); + $countanswers = count($answerarray); + } + else {$countanswers=0;} + if (isset($labelsetsarray)) {$countlabelsets = count($labelsetsarray)-1;} else {$countlabelsets=0;} + if (isset($labelsarray)) {$countlabels = count($labelsarray)-1;} else {$countlabels=0;} + if (isset($question_attributesarray)) {$countquestion_attributes = count($question_attributesarray)-1;} else {$countquestion_attributes=0;} + + $languagesSupported = array(); // this array will keep all the languages supported for the survey + + // Let's check that imported objects support at least the survey's baselang + $langcode = GetBaseLanguageFromSurveyID($surveyid); + + $languagesSupported[$langcode] = 1; // adds the base language to the list of supported languages + $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK "); + if ($countquestions > 0) + { + $questionfieldnames = convertCSVRowToArray($questionarray[0],',','"'); + $langfieldnum = array_search("language", $questionfieldnames); + $qidfieldnum = array_search("qid", $questionfieldnames); + $questionssupportbaselang = bDoesImportarraySupportsLanguage($questionarray,Array($qidfieldnum), $langfieldnum,$langcode,true); + if (!$questionssupportbaselang) + { + // $importquestion .= "".("Error")."\n" + // .("You can't import a question which doesn't support the current survey's base language")."\n" + // ."\n"; + // unlink($the_full_file_path); + return "You can't import a question which doesn't support the current survey's base language"; + } + } + $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK "); + foreach (GetAdditionalLanguagesFromSurveyID($surveyid) as $language) + { + $languagesSupported[$language] = 1; + } + + // Let's assume that if the questions do support tye baselang + // Then the answers do support it as well. + // ==> So the following section is commented for now + //if ($countanswers > 0) + //{ + // $langfieldnum = array_search("language", $answerfieldnames); + // $answercodefilednum1 = array_search("qid", $answerfieldnames); + // $answercodefilednum2 = array_search("code", $answerfieldnames); + // $answercodekeysarr = Array($answercodefilednum1,$answercodefilednum2); + // $answerssupportbaselang = bDoesImportarraySupportsLanguage($answerarray,$answercodekeysarr,$langfieldnum,$langcode); + // if (!$answerssupportbaselang) + // { + // $importquestion .= "".("Error")."\n" + // .("You can't import answers which don't support current survey's base language")."\n" + // ."\n"; + // return; + // } + // + //} + $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK "); + if ($countlabelsets > 0) + { + $labelsetfieldname = convertCSVRowToArray($labelsetsarray[0],',','"'); + $langfieldnum = array_search("languages", $labelsetfieldname); + $lidfilednum = array_search("lid", $labelsetfieldname); + $labelsetssupportbaselang = bDoesImportarraySupportsLanguage($labelsetsarray,Array($lidfilednum),$langfieldnum,$langcode,true); + if (!$labelsetssupportbaselang) + { + // $importquestion .= "".("Error")."\n" + // .("You can't import label sets which don't support the current survey's base language")."\n" + // ."\n"; + // unlink($the_full_file_path); + return "You can't import label sets which don't support the current survey's base language"; + } + } + // I assume that if a labelset supports the survey's baselang, + // then it's labels do support it as well + + // GET SURVEY AND GROUP DETAILS + //$surveyid=$postsid; + //$gid=$postgid; + $newsid=$surveyid; + $newgid=$gid; + + $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK "); + + //DO ANY LABELSETS FIRST, SO WE CAN KNOW WHAT THEIR NEW LID IS FOR THE QUESTIONS + if (isset($labelsetsarray) && $labelsetsarray) { + $csarray=buildLabelSetCheckSumArray(); // build checksums over all existing labelsets + $count=0; + $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK "); + foreach ($labelsetsarray as $lsa) { + $fieldorders =convertCSVRowToArray($labelsetsarray[0],',','"'); + $fieldcontents=convertCSVRowToArray($lsa,',','"'); + if ($count==0) {$count++; continue;} + + $labelsetrowdata=array_combine($fieldorders,$fieldcontents); + + // Save old labelid + $oldlid=$labelsetrowdata['lid']; + // set the new language + unset($labelsetrowdata['lid']); + $newvalues=array_values($labelsetrowdata); + $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly + $lsainsert = "INSERT INTO {$dbprefix}labelsets (".implode(',',array_keys($labelsetrowdata)).") VALUES (".implode(',',$newvalues).")"; //handle db prefix + $lsiresult=$connect->Execute($lsainsert); + + // Get the new insert id for the labels inside this labelset + $newlid=$connect->Insert_ID("{$dbprefix}labelsets","lid"); + + if ($labelsarray) { + $count=0; + foreach ($labelsarray as $la) { + $lfieldorders =convertCSVRowToArray($labelsarray[0],',','"'); + $lfieldcontents=convertCSVRowToArray($la,',','"'); + if ($count==0) {$count++; continue;} + + // Combine into one array with keys and values since its easier to handle + $labelrowdata=array_combine($lfieldorders,$lfieldcontents); + $labellid=$labelrowdata['lid']; + if ($labellid == $oldlid) { + $labelrowdata['lid']=$newlid; + + // translate internal links + $labelrowdata['title']=translink('label', $oldlid, $newlid, $labelrowdata['title']); + + $newvalues=array_values($labelrowdata); + $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly + $lainsert = "INSERT INTO {$dbprefix}labels (".implode(',',array_keys($labelrowdata)).") VALUES (".implode(',',$newvalues).")"; //handle db prefix + $liresult=$connect->Execute($lainsert); + } + } + } + + //CHECK FOR DUPLICATE LABELSETS + $thisset=""; + $query2 = "SELECT code, title, sortorder, language + FROM {$dbprefix}labels + WHERE lid=".$newlid." + ORDER BY language, sortorder, code"; + $result2 = db_execute_num($query2) or $this->debugLsrc("Died querying labelset $lid$query2".$connect->ErrorMsg()); + while($row2=$result2->FetchRow()) + { + $thisset .= implode('.', $row2); + } // while + $newcs=dechex(crc32($thisset)*1); + unset($lsmatch); + if (isset($csarray)) + { + foreach($csarray as $key=>$val) + { + if ($val == $newcs) + { + $lsmatch=$key; + } + } + } + if (isset($lsmatch)) + { + //There is a matching labelset. So, we will delete this one and refer + //to the matched one. + $query = "DELETE FROM {$dbprefix}labels WHERE lid=$newlid"; + $result=$connect->Execute($query) or $this->debugLsrc("Couldn't delete labels$query".$connect->ErrorMsg()); + $query = "DELETE FROM {$dbprefix}labelsets WHERE lid=$newlid"; + $result=$connect->Execute($query) or $this->debugLsrc("Couldn't delete labelset$query".$connect->ErrorMsg()); + $newlid=$lsmatch; + } + else + { + //There isn't a matching labelset, add this checksum to the $csarray array + $csarray[$newlid]=$newcs; + } + //END CHECK FOR DUPLICATES + $labelreplacements[]=array($oldlid, $newlid); + } + } + + $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK "); + + // QUESTIONS, THEN ANSWERS FOR QUESTIONS IN A NESTED FORMAT! + if (isset($questionarray) && $questionarray) { + $qafieldorders=convertCSVRowToArray($questionarray[0],',','"'); + unset($questionarray[0]); + + //Assuming we will only import one question at a time we will now find out the maximum question order in this group + //and save it for later + $qmaxqo = "SELECT MAX(question_order) AS maxqo FROM ".db_table_name('questions')." WHERE sid=$newsid AND gid=$newgid"; + $qres = db_execute_assoc($qmaxqo) or $this->debugLsrc ("Error: ".": Failed to find out maximum question order value\n$qmaxqo\n".$connect->ErrorMsg()); + $qrow=$qres->FetchRow(); + $newquestionorder=$qrow['maxqo']+1; + + $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK "); + + foreach ($questionarray as $qa) { + $qacfieldcontents=convertCSVRowToArray($qa,',','"'); + $newfieldcontents=$qacfieldcontents; + $questionrowdata=array_combine($qafieldorders,$qacfieldcontents); + if (isset($languagesSupported[$questionrowdata["language"]])) + { + $oldqid = $questionrowdata['qid']; + $oldsid = $questionrowdata['sid']; + $oldgid = $questionrowdata['gid']; + + // Remove qid field if there is no newqid; and set it to newqid if it's set + if (!isset($newqid)) + unset($questionrowdata['qid']); + else + $questionrowdata['qid'] = $newqid; + + $questionrowdata["sid"] = $newsid; + $questionrowdata["gid"] = $newgid; + $questionrowdata["question_order"] = $newquestionorder; + + $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK "); + // Now we will fix up the label id + $type = $questionrowdata["type"]; //Get the type + if ($type == "F" || $type == "H" || $type == "W" || + $type == "Z" || $type == "1" || $type == ":" || + $type == ";" ) + {//IF this is a flexible label array, update the lid entry + + $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK "); + + if (isset($labelreplacements)) { + foreach ($labelreplacements as $lrp) { + if ($lrp[0] == $questionrowdata["lid"]) { + $questionrowdata["lid"]=$lrp[1]; + } + if ($lrp[0] == $questionrowdata["lid1"]) { + $questionrowdata["lid1"]=$lrp[1]; + } + } + } + } + $other = $questionrowdata["other"]; //Get 'other' field value + $oldlid = $questionrowdata["lid"]; + $questionrowdata=array_map('convertCsvreturn2return', $questionrowdata); + + // translate internal links + $questionrowdata['title']=translink('survey', $oldsid, $newsid, $questionrowdata['title']); + $questionrowdata['question']=translink('survey', $oldsid, $newsid, $questionrowdata['question']); + $questionrowdata['help']=translink('survey', $oldsid, $newsid, $questionrowdata['help']); + + $newvalues=array_values($questionrowdata); + $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly + $qinsert = "INSERT INTO {$dbprefix}questions (".implode(',',array_keys($questionrowdata)).") VALUES (".implode(',',$newvalues).")"; + $qres = $connect->Execute($qinsert) or $this->debugLsrc ("Error: ".": Failed to insert question\n$qinsert\n".$connect->ErrorMsg()); + + $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK "); + // set the newqid only if is not set + if (!isset($newqid)) + $newqid=$connect->Insert_ID("{$dbprefix}questions","qid"); + } + } + $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK "); + //NOW DO ANSWERS FOR THIS QID - Is called just once and only if there was a question + if (isset($answerarray) && $answerarray) { + foreach ($answerarray as $aa) { + $answerfieldcontents=convertCSVRowToArray($aa,',','"'); + $answerrowdata=array_combine($answerfieldnames,$answerfieldcontents); + if ($answerrowdata===false) + { + $importquestion.=''.("Faulty line in import - fields and data don't match").":".implode(',',$answerfieldcontents); + } + if (isset($languagesSupported[$answerrowdata["language"]])) + { + $code=$answerrowdata["code"]; + $thisqid=$answerrowdata["qid"]; + $answerrowdata["qid"]=$newqid; + + // translate internal links + $answerrowdata['answer']=translink('survey', $oldsid, $newsid, $answerrowdata['answer']); + + $newvalues=array_values($answerrowdata); + $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly + $ainsert = "INSERT INTO {$dbprefix}answers (".implode(',',array_keys($answerrowdata)).") VALUES (".implode(',',$newvalues).")"; + $ares = $connect->Execute($ainsert) or $this->debugLsrc ("Error: ".": Failed to insert answer\n$ainsert\n".$connect->ErrorMsg()); + } + } + } + $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK "); + // Finally the question attributes - Is called just once and only if there was a question + if (isset($question_attributesarray) && $question_attributesarray) {//ONLY DO THIS IF THERE ARE QUESTION_ATTRIBUES + $fieldorders =convertCSVRowToArray($question_attributesarray[0],',','"'); + unset($question_attributesarray[0]); + foreach ($question_attributesarray as $qar) { + $fieldcontents=convertCSVRowToArray($qar,',','"'); + $qarowdata=array_combine($fieldorders,$fieldcontents); + $qarowdata["qid"]=$newqid; + unset($qarowdata["qaid"]); + + $newvalues=array_values($qarowdata); + $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly + $qainsert = "INSERT INTO {$dbprefix}question_attributes (".implode(',',array_keys($qarowdata)).") VALUES (".implode(',',$newvalues).")"; + $result=$connect->Execute($qainsert) or $this->debugLsrc ("Couldn't insert question_attribute$qainsert".$connect->ErrorMsg()); + } + } + + } + $this->debugLsrc("wir sind in - ".__FUNCTION__." Line ".__LINE__.", FERTIG "); + // CONDITIONS is DONE + return array('gid'=>$newgid,'qid'=>$newqid); + //return $newgid; + } + + /** + * function to delete a Survey with all questions and answersand Tokentable.... + * + * @param int $surveyid + * @return boolean + */ + function deleteSurvey($surveyid) + { + global $connect ; + // global $dbprefix ; + $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC; + include("lsrc.config.php"); + $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", OK "); + + $tablelist = $connect->MetaTables(); + $dict = NewDataDictionary($connect); + + if (in_array("{$dbprefix}survey_$surveyid", $tablelist)) //delete the survey_$surveyid table + { + $dsquery = $dict->DropTableSQL("{$dbprefix}survey_$surveyid"); + //$dict->ExecuteSQLArray($sqlarray); + $dsresult = $dict->ExecuteSQLArray($dsquery); + } + + if (in_array("{$dbprefix}tokens_$surveyid", $tablelist)) //delete the tokens_$surveyid table + { + $dsquery = $dict->DropTableSQL("{$dbprefix}tokens_$surveyid"); + $dsresult = $dict->ExecuteSQLArray($dsquery) or $this->debugLsrc ("Couldn't \"$dsquery\" because ".$connect->ErrorMsg()); + } + + $dsquery = "SELECT qid FROM {$dbprefix}questions WHERE sid=$surveyid"; + $dsresult = db_execute_assoc($dsquery) or $this->debugLsrc ("Couldn't find matching survey to delete: \n $dsquery \n".$connect->ErrorMsg()); + while ($dsrow = $dsresult->FetchRow()) + { + $asdel = "DELETE FROM {$dbprefix}answers WHERE qid={$dsrow['qid']}"; + $asres = $connect->Execute($asdel); + $cddel = "DELETE FROM {$dbprefix}conditions WHERE qid={$dsrow['qid']}"; + $cdres = $connect->Execute($cddel) or die(); + $qadel = "DELETE FROM {$dbprefix}question_attributes WHERE qid={$dsrow['qid']}"; + $qares = $connect->Execute($qadel); + } + + $qdel = "DELETE FROM {$dbprefix}questions WHERE sid=$surveyid"; + $qres = $connect->Execute($qdel); + + $scdel = "DELETE FROM {$dbprefix}assessments WHERE sid=$surveyid"; + $scres = $connect->Execute($scdel); + + $gdel = "DELETE FROM {$dbprefix}groups WHERE sid=$surveyid"; + $gres = $connect->Execute($gdel); + + $slsdel = "DELETE FROM {$dbprefix}surveys_languagesettings WHERE surveyls_survey_id=$surveyid"; + $slsres = $connect->Execute($slsdel); + + $srdel = "DELETE FROM {$dbprefix}surveys_rights WHERE sid=$surveyid"; + $srres = $connect->Execute($srdel); + + $srdel = "DELETE FROM {$dbprefix}saved_control WHERE sid=$surveyid"; + $srres = $connect->Execute($srdel); + + $sdel = "DELETE FROM {$dbprefix}surveys WHERE sid=$surveyid"; + $sres = $connect->Execute($sdel); + $surveyid=false; + + return true; + + } + /** + * This function removes the UTF-8 Byte Order Mark from a string + * + * @param string $str + * @return string + */ + private function removeBOM($str=""){ + if(substr($str, 0,3) == pack("CCC",0xef,0xbb,0xbf)) { + $str=substr($str, 3); + } + return $str; + } + /** + * This function pulls a CSV representation of the Field map + * + * @param mixed $surveyid - the survey ID you want the Fieldmap for + * @return String $fieldmap + */ + function FieldMap2CSV($surveyid) + { + $fields=array("fieldname", "type", "sid", "gid", "qid", "aid",'title','question','group_name','lid','lid1'); + $fieldmap=createFieldMap($surveyid,'full',true); + + $result='"'.implode('","',$fields).'"'."\n"; + foreach ($fieldmap as $entry) + { + + $destfieldmap=array(); + foreach ($fields as $field) + { + if (isset($entry[$field])) + { + $destfieldmap[$field]=$entry[$field]; + } + else + { + $destfieldmap[$field]=''; + } + } + $entry=array_map('CSVEscape',array_values($destfieldmap)); + $result.=implode(',',$entry)."\n"; + } + return $result; + } + + private function getqtypelist($SelectedCode = "T", $ReturnType = "array") + { + include("lsrc.config.php"); + global $publicurl; + //global $sourcefrom, $clang; + + + $qtypes = array( + "1"=>"Array (Flexible Labels) Dual Scale", + "5"=>"5 Point Choice", + "A"=>"Array (5 Point Choice)", + "B"=>"Array (10 Point Choice)", + "C"=>"Array (Yes/No/Uncertain)", + "D"=>"Date", + "E"=>"Array (Increase, Same, Decrease)", + "F"=>"Array (Flexible Labels)", + "G"=>"Gender", + "H"=>"Array (Flexible Labels) by Column", + "I"=>"Language Switch", + "K"=>"Multiple Numerical Input", + "L"=>"List (Radio)", + "M"=>"Multiple Options", + "N"=>"Numerical Input", + "O"=>"List With Comment", + "P"=>"Multiple Options With Comments", + "Q"=>"Multiple Short Text", + "R"=>"Ranking", + "S"=>"Short Free Text", + "T"=>"Long Free Text", + "U"=>"Huge Free Text", + "W"=>"List (Flexible Labels) (Dropdown)", + "X"=>"Boilerplate Question", + "Y"=>"Yes/No", + "Z"=>"List (Flexible Labels) (Radio)", + "!"=>"List (Dropdown)", + ":"=>"Array (Multi Flexible) (Numbers)", + ";"=>"Array (Multi Flexible) (Text)", + ); + asort($qtypes); + if ($ReturnType == "array") + {return $qtypes;} + + + } +} +?> \ No newline at end of file diff --git a/include/limesurvey/admin/remotecontrol/lsrc.server.php b/include/limesurvey/admin/remotecontrol/lsrc.server.php new file mode 100644 index 00000000..f4008278 --- /dev/null +++ b/include/limesurvey/admin/remotecontrol/lsrc.server.php @@ -0,0 +1,1153 @@ + array( + 'verify_peer' => false, + 'allow_self_signed' => true, + 'local_cert' => $sslCert, + 'passphrase' => 'hisuser', + 'capture_peer_cert' => true + + ) + ); + + $stream_context = stream_context_create($context); + + $server = new SoapServer($wsdl, array('soap_version' => SOAP_1_1, + 'stream_context' => $stream_context)); +} +else{ + $server = new SoapServer($wsdl, array('soap_version' => SOAP_1_1)); +} + + /** + * adds the functions to the SoapServer Object, + * + * the sChangeSurvey function should be commented out for productive Use + */ + //$server->addFunction("sChangeSurvey"); + $server->addFunction("sDeleteSurvey"); + $server->addFunction("sActivateSurvey"); + $server->addFunction("sCreateSurvey"); + $server->addFunction("sInsertToken"); + $server->addFunction("sTokenReturn"); + $server->addFunction("sInsertParticipants"); + $server->addFunction("sImportGroup"); + $server->addFunction("sAvailableModules"); + $server->addFunction("sImportQuestion"); + $server->addFunction("sImportMatrix"); + $server->addFunction("sImportFreetext"); + $server->addFunction("sSendEmail"); + $server->addFunction("sGetFieldmap"); + // handle the soap request! +if($enableLsrc==true) +{ + $server->handle(); +} +/** + * + * Function to change tables in Limesurvey Database, this is too sensitive for productive use, but useful for development and testing + * @param $sUser + * @param $sPass + * @param $table + * @param $key + * @param $value + * @param $where + * @param $mode + * @return unknown_type + */ +function sChangeSurvey($sUser, $sPass, $table, $key, $value, $where, $mode='0') +{ + include("lsrc.config.php"); + $lsrcHelper = new lsrcHelper(); + // check for appropriate rights + if(!$lsrcHelper->checkUser($sUser, $sPass)) + { + throw new SoapFault("Authentication: ", "User or password wrong"); + exit; + } + //check for Surveyowner. Only owners and superadmins can change and activate surveys + if(!$_SESSION['USER_RIGHT_SUPERADMIN']=='1') + { + throw new SoapFault("Authentication: ", "You have no right to change Databasetables"); + exit; + } + + return $lsrcHelper->changeTable($table, $key, $value, $where, $mode); +} +/** + * + * Function to send reminder, invitation or custom mails to participants of a specific survey + * @param $sUser + * @param $sPass + * @param $iVid + * @param $type + * @param $maxLsrcEmails + * @param $subject + * @param $emailText + * @return unknown_type + */ +function sSendEmail($sUser, $sPass, $iVid, $type, $maxLsrcEmails='', $subject='', $emailText='') +{ + global $sitename, $siteadminemail; + include("lsrc.config.php"); + $lsrcHelper = new lsrcHelper(); + $lsrcHelper->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", START OK "); + + // wenn maxmails ber den lsrc gegeben wird das nurtzen, ansonsten die default werte aus der config.php + if($maxLsrcEmails!='') + $maxemails = $maxLsrcEmails; + + if(!$lsrcHelper->checkUser($sUser, $sPass)) + { + throw new SoapFault("Authentication: ", "User or password wrong"); + exit; + } + + // Check if all mandatory parameters are present, else abort... + if(!is_int($iVid) || $iVid==0 || $type=='') + { + throw new SoapFault("Server: ", "Mandatory Parameters missing"); + exit; + } + + if($type=='custom' && $subject!='' && $emailText!='') + { + //GET SURVEY DETAILS not working here... don't know why... + //$thissurvey=getSurveyInfo($iVid); + $from = $siteadminemail; + + $lsrcHelper->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", Admin Email: $from ; survey: $iVid ; dump: ".print_r($thissurvey).""); + $emquery = "SELECT firstname, lastname, email, token, tid, language"; + //if ($ctfieldcount > 7) {$emquery .= ", attribute_1, attribute_2";} + + $emquery .= " FROM ".db_table_name("tokens_{$iVid}")." WHERE email != '' "; + + if (isset($tokenid)) {$emquery .= " and tid='{$tokenid}'";} + $tokenoutput .= "\n\n\n\n"; + //$emresult = db_select_limit_assoc($emquery,$maxemails); + $emresult = db_execute_assoc($emquery); + $emcount = $emresult->RecordCount(); + + if ($emcount > 0) + { + $mailsSend = 0; + while ($emrow = $emresult->FetchRow()) + { + if (MailTextMessage($emailText, $subject, $emrow['email'] , $from, $sitename, $ishtml=false, getBounceEmail($iVid))) + { + $mailsSend++; + } + else + { + //$tokenoutput .= ReplaceFields($clang->gT("Email to {FIRSTNAME} {LASTNAME} ({EMAIL}) failed. Error Message:")." ".$maildebug."
    ", $fieldsarray); + if($n==1) + $failedAddresses .= ",".$emrow['email']; + else + { + $failedAddresses = $emrow['email']; + $n=1; + } + + } + } + + } + else + { + return "No Mails to send"; + } +// if ($ctcount > $emcount) +// { +// $lefttosend = $ctcount-$maxemails; +// +// }else{$lefttosend = 0;} + +// if($maxemails>0) +// { +// $returnValue = "".$mailsSend." Mails send. ".$lefttosend." Mails left to send"; +// if(isset($failedAddresses)) +// $returnValue .= "\nCould not send to: ".$failedAddresses; +// return $returnValue; +// } + + if(isset($mailsSend)) + { + $returnValue = "".$mailsSend." Mails send. "; + if(isset($failedAddresses)) + $returnValue .= "\nCould not send to: ".$failedAddresses; + return $returnValue; + } + } + + if($type=='invite' || $type=='remind') + { + $emailSenderReturn = $lsrcHelper->emailSender($iVid, $type, $maxLsrcEmails); + + return $emailSenderReturn; + + } + else + { + throw new SoapFault("Type: ", "Wrong send Type given. Possible types are: custom, invite or remind"); + exit; + } + +} + +/** + * + * Function to activate a survey in the database and change some Values (starttime, endtime. Required parameters are: + * @param $sUser + * @param $sPass + * @param $iVid + * @param $dStart + * @param $dEnd + * @return unknown_type + */ +function sActivateSurvey($sUser, $sPass, $iVid, $dStart, $dEnd) +{ + include("lsrc.config.php"); + $lsrcHelper = new lsrcHelper(); + $lsrcHelper->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", START OK "); + // check for apropriate rights + if(!$lsrcHelper->checkUser($sUser, $sPass)) + { + throw new SoapFault("Authentication: ", "User or password wrong"); + exit; + } + + // Check if all mandatory parameters are present, else abort... + if(!is_int($iVid) || $iVid==0) + { + throw new SoapFault("Server: ", "Mandatory Parameters missing"); + exit; + } + + // Check if the survey to create already exists. If not, abort with Fault. + if(!$lsrcHelper->surveyExists($iVid)) + { + throw new SoapFault("Database: ", "Survey you want to activate does not exists"); + exit; + } + + //check for Surveyowner. Only owners and superadmins can change and activate surveys + if($lsrcHelper->getSurveyOwner($iVid)!=$_SESSION['loginID'] && !$_SESSION['USER_RIGHT_SUPERADMIN']=='1') + { + throw new SoapFault("Authentication: ", "You have no right to change Surveys from other people"); + exit; + } + + if(!$lsrcHelper->activateSurvey($iVid)) + { + throw new SoapFault("Server: ", "Activation went wrong somehow"); + exit; + } + + if($dStart!='' && substr($dStart,0,10)!='1980-01-01') + { + $lsrcHelper->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", CHANGE start "); + $lsrcHelper->changeTable('surveys','startdate',$dStart,'sid='.$iVid); + } + if($dEnd!='' && substr($dEnd,0,10)!='1980-01-01') + { + $lsrcHelper->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", CHANGE end "); + $lsrcHelper->changeTable('surveys','expires',$dEnd,'sid='.$iVid); + } + + $lsrcHelper->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", aktivierung OK "); + return $iVid; +} + +/** + * + * Function to import a survey into the database and change some Values. Required parameters are: + * @param $sUser + * @param $sPass + * @param $iVid + * @param $sVtit + * @param $sVbes + * @param $sVwel + * @param $sMail + * @param $sName + * @param $sUrl + * @param $sUbes + * @param $sVtyp + * @param $autoRd + * @return unknown_type + */ +function sCreateSurvey($sUser, $sPass, $iVid, $sVtit, $sVbes, $sVwel, $sVend, $sMail, $sName, $sUrl, $sUbes, $sVtyp, $autoRd='N' ) +{ + include("lsrc.config.php"); + $lsrcHelper = new lsrcHelper(); + $lsrcHelper->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.",surveyid=$iVid START OK "); + + + if($sVwel=='') + {//if no welcometext is given, set this one + $sVwel = "Herzlich Willkommen zur Evaluation von \"".$sVtit."\""; + } +// if($sVend=='') +// {//if no endtext is given, set this one +// $sVend = "Vielen Dank für Ihre Teilnahme an der Umfrage!"; +// } + + if(!$lsrcHelper->checkUser($sUser, $sPass)) + {// check for appropriate rights + throw new SoapFault("Authentication: ", "User or password wrong"); + exit; + } + + if((!is_int($iVid) || $iVid==0) || $sVtit=='' || $sVbes=='') + {// Check if mandatory parameters are empty, if so-> abort + throw new SoapFault("Server: ", "Mandatory Parameters missing"); + exit; + } + + if($lsrcHelper->surveyExists($iVid)) + {// Check if the survey to create already exists. If so, abort with Fault. + throw new SoapFault("Database: ", "Survey already exists"); + exit; + } + $lsrcHelper->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.",vor import OK "); + + + if($lsrcHelper->importSurvey($iVid, $sVtit , $sVbes, $sVwel, $sUbes, $sVtyp)) + {// if import of survey went ok it returns true, else nothing + $lsrcHelper->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.",surveyid=$iVid nach import OK "); + + //get the optional data into db + if($sMail!='') + { + $lsrcHelper->changeTable("surveys", "adminemail", $sMail, "sid='$iVid'"); + $lsrcHelper->changeTable("surveys", "bounce_email", $sMail, "sid='$iVid'"); + } + if($sName!='') + $lsrcHelper->changeTable("surveys", "admin", $sName, "sid='$iVid'"); + if($sUrl!='') + $lsrcHelper->changeTable("surveys_languagesettings", "surveyls_url", $sUrl, "surveyls_survey_id='$iVid'"); + if($autoRd=='Y') + $lsrcHelper->changeTable("surveys", "autoredirect", "Y", "sid='$iVid'"); + if($sVend!='') + $lsrcHelper->changeTable("surveys_languagesettings", "surveyls_endtext", $sVend, "surveyls_survey_id='$iVid'"); + + $lsrcHelper->changeTable("surveys", "datecreated", date("Y-m-d"), "sid='$iVid'"); + + return $iVid; + } + else + { + throw new SoapFault("Server: ", "Import went wrong somehow"); + exit; + } + +}//end of function sCreateSurvey + + +/** + * + * Function to insert Tokens to an existing Survey, makes it "closed" + * @param $sUser + * @param $sPass + * @param $iVid + * @param $sToken + * @return unknown_type + */ +function sInsertToken($sUser, $sPass, $iVid, $sToken) +{ + global $connect ; + global $dbprefix ; + //$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC; + include("lsrc.config.php"); + $lsrcHelper = new lsrcHelper(); + $lsrcHelper->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", START OK "); + + // check for apropriate rights + if(!$lsrcHelper->checkUser($sUser, $sPass)) + { + throw new SoapFault("Authentication: ", "User or password wrong"); + exit; + } + + // check if there is a $iVid, else abort + if(!isset($iVid) || $iVid=='' || $iVid==0 ) + { + throw new SoapFault("Server: ", "No SurveyId given"); + exit; + } + + // check if the Survey we want to populate with tokens already exists, else -> Fault + if(!$lsrcHelper->surveyExists($iVid)) + { + throw new SoapFault("Database: ", "Survey does not exists"); + exit; + } + $lsrcHelper->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", ckecks ueberstanden "); + + // check if the Token table already exists, if not, create it... + if(!db_tables_exist("{$dbprefix}tokens_".$iVid)) + { + $lsrcHelper->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", TOken Table existiert nicht "); + $createtokentable= + "tid int I NOTNULL AUTO PRIMARY,\n " + . "firstname C(40) ,\n " + . "lastname C(40) ,\n "; + //MSSQL needs special treatment because of some strangeness in ADODB + if ($databasetype == 'odbc_mssql' || $databasetype == 'odbtp' || $databasetype == 'mssql_n') + { + $createtokentable.= "email C(320) ,\n " + ."emailstatus C(300) DEFAULT 'OK',\n "; + } + else + { + $createtokentable.= "email X(320) ,\n " + ."emailstatus X(300) DEFAULT 'OK',\n "; + } + + $createtokentable.= "token C(36) ,\n " + . "language C(25) ,\n " + . "sent C(17) DEFAULT 'N',\n " + . "remindersent C(17) DEFAULT 'N',\n " + . "remindercount int I DEFAULT 0,\n " + . "completed C(17) DEFAULT 'N',\n " + . "attribute_1 C(100) ,\n" + . "attribute_2 C(100) ,\n" + . "mpid I "; + + $tabname = "{$dbprefix}tokens_{$iVid}"; # not using db_table_name as it quotes the table name (as does CreateTableSQL) + $taboptarray = array('mysql' => 'ENGINE='.$databasetabletype.' CHARACTER SET utf8 COLLATE utf8_unicode_ci', + 'mysqli' => 'ENGINE='.$databasetabletype.' CHARACTER SET utf8 COLLATE utf8_unicode_ci'); + $dict = NewDataDictionary($connect); + $sqlarray = $dict->CreateTableSQL($tabname, $createtokentable, $taboptarray); + $execresult=$dict->ExecuteSQLArray($sqlarray, false); + + $createtokentableindex = $dict->CreateIndexSQL("{$tabname}_idx", $tabname, array('token')); + $dict->ExecuteSQLArray($createtokentableindex, false); + } + $lsrcHelper->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", Token tabelle sollte erstellt sein "); + ################# + + //if the lsrcSeperator is not set, set the default seperator, a comma... + if($sLsrcSeparator=='') + { + $sLsrcSeparator = ","; + } + + // prepare to fill the table lime_tokens_* + // this is sensitiv, if the Seperator is not the defined one, almost everything could happen, BE AWARE OF YOUR SEPERATOR!... + $asTokens = explode($sLsrcSeparator, $sToken); + $givenTokenCount = count($asTokens); + // write the tokens in the token_table + $insertedTokenCount=0; + + foreach($asTokens as $value) + { + if($value!='') + { + $sInsertToken = "INSERT INTO {$dbprefix}tokens_".$iVid." + (token,language) VALUES ('".$value."' , '".$_SESSION['lang']."'); "; + if(!$connect->Execute($sInsertToken)) + { + throw new SoapFault("Server: ", "Token could not be inserted"); + exit; + } + else + { + ++$insertedTokenCount; + } + } + } + return "".$givenTokenCount." Token given, ".$insertedTokenCount." Token inserted."; + +} //end of function sInsertToken + +/** + * TODO: redo better... maybe some other function for compatibility + * Function to insert Participants data while auto creating tokens for everyone... + * @param $sUser + * @param $sPass + * @param $iVid + * @param $sParticipantData + * @return unknown_type + */ +function sInsertParticipants($sUser, $sPass, $iVid, $sParticipantData) +{ + global $connect ; + global $dbprefix ; + $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC; + include("lsrc.config.php"); + $lsrcHelper = new lsrcHelper(); + // check for appropriate rights + if(!$lsrcHelper->checkUser($sUser, $sPass)) + { + throw new SoapFault("Authentication: ", "User or password wrong"); + exit; + } + + // check if there is a $iVid, else abort + if(!isset($iVid) || $iVid=='' || $iVid==0 ) + { + throw new SoapFault("Server: ", "No SurveyId given"); + exit; + } + + // check if the Survey we want to populate with data and tokens already exists, else -> Fault + if(!$lsrcHelper->surveyExists($iVid)) + { + throw new SoapFault("Database: ", "Survey does not exists"); + exit; + } + + // check if the Token table already exists, if not, create it... + if(!db_tables_exist("{$dbprefix}tokens_".$iVid)) + { + $lsrcHelper->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", Token Table existiert nicht "); + $createtokentable= + "tid int I NOTNULL AUTO PRIMARY,\n " + . "firstname C(40) ,\n " + . "lastname C(40) ,\n "; + //MSSQL needs special treatment because of some strangeness in ADODB + if ($databasetype == 'odbc_mssql' || $databasetype == 'odbtp' || $databasetype == 'mssql_n') + { + $createtokentable.= "email C(320) ,\n " + ."emailstatus C(300) DEFAULT 'OK',\n "; + } + else + { + $createtokentable.= "email X(320) ,\n " + ."emailstatus X(300) DEFAULT 'OK',\n "; + } + + $createtokentable.= "token C(36) ,\n " + . "language C(25) ,\n " + . "sent C(17) DEFAULT 'N',\n " + . "remindersent C(17) DEFAULT 'N',\n " + . "remindercount int I DEFAULT 0,\n " + . "completed C(17) DEFAULT 'N',\n " + . "attribute_1 C(255) ,\n" + . "attribute_2 C(255) ,\n" + . "mpid I "; + + $tabname = "{$dbprefix}tokens_{$iVid}"; # not using db_table_name as it quotes the table name (as does CreateTableSQL) + $taboptarray = array('mysql' => 'ENGINE='.$databasetabletype.' CHARACTER SET utf8 COLLATE utf8_unicode_ci', + 'mysqli' => 'ENGINE='.$databasetabletype.' CHARACTER SET utf8 COLLATE utf8_unicode_ci'); + $dict = NewDataDictionary($connect); + $sqlarray = $dict->CreateTableSQL($tabname, $createtokentable, $taboptarray); + $execresult=$dict->ExecuteSQLArray($sqlarray, false); + + $createtokentableindex = $dict->CreateIndexSQL("{$tabname}_idx", $tabname, array('token')); + $dict->ExecuteSQLArray($createtokentableindex, false); + } + $lsrcHelper->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", Token tabelle sollte erstellt sein "); + + //set the Seperators to default if nothing is set in the lsrc.config.php + if(!isset($sDatasetSeperator) || $sDatasetSeperator=='') + {$sDatasetSeperator = "::";} + if(!isset($sDatafieldSeperator) || $sDatafieldSeperator=='') + {$sDatafieldSeperator = ";";} + + // prepare to fill the table lime_tokens_* + // this is sensitiv, if the Seperator is not the defined one, almost everything could happen, BE AWARE OF YOUR SEPERATOR!... + $asDataset = explode($sDatasetSeperator, $sParticipantData); + // write the tokens to the token_table + $iCountParticipants = count($asDataset); + $iInsertedParticipants=0; + + foreach($asDataset as $sData) + { + if($sData!='') + { + $asDatafield = explode($sDatafieldSeperator, $sData); + $checkCnt=1; + // token generieren + while($checkCnt>0) + { + $value = randomkey(5); //change randomkey value for different tokenlength (up to 36 chars max.) + $cQuery= "select token from ".$dbprefix."tokens_".$iVid." where token = '".$value."'; "; + $result = db_execute_assoc($cQuery); + $checkCnt = $result->RecordCount(); + } + if(!isset($asDatafield[5]) || $asDatafield[5]=='') + { + $asDatafield[5]= $value; + } + + $iDataLength = count($asDatafield); + for($n=0;$n>=$iDataLength;++$n) + { + + if($asDatafield[$n]=='') + { + $asDatafield[$n]=null; + } + } + $sInsertParti = "INSERT INTO ".$dbprefix."tokens_".$iVid + ."(firstname,lastname,email,emailstatus,token," + ."language,sent,completed,attribute_1,attribute_2,mpid)" + ."VALUES ('".$asDatafield[0]."' , + '".$asDatafield[1]."' , '".$asDatafield[2]."' , 'OK' , '".$asDatafield[5]."', + '".$_SESSION['lang']."', 'N', 'N', '".$asDatafield[3]."' , '".$asDatafield[4]."' , NULL); "; + + $connect->Execute($sInsertParti); + ++$iInsertedParticipants; + } + + } + + return "".$iCountParticipants."Datasets given, ".$iInsertedParticipants." rows inserted. "; + //return $sParticipantData; +} //end of function sInsertParticipants + +/** + * + * function to return unused Tokens as String, seperated by commas, to get the people who did not complete the Survey + * @param $sUser + * @param $sPass + * @param $iVid + * @return unknown_type + */ +function sTokenReturn($sUser, $sPass, $iVid) +{ + global $connect ; + global $dbprefix ; + $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC; + include("lsrc.config.php"); + $lsrcHelper = new lsrcHelper(); + $lsrcHelper->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", START OK "); + + // check for appropriate rights + if(!$lsrcHelper->checkUser($sUser, $sPass)) + { + throw new SoapFault("Authentication: ", "User or password wrong"); + exit; + } + + // check if there is a $iVid, else abort + if(!isset($iVid) || $iVid=='' || $iVid==0 ) + { + throw new SoapFault("Server: ", "No SurveyId given"); + exit; + } + + // check if the Survey exists, else -> Fault + if(!$lsrcHelper->surveyExists($iVid)) + { + throw new SoapFault("Database: ", "Survey does not exists"); + exit; + } + + // check if the token table exists, else throw fault message + if(db_tables_exist($dbprefix."tokens_".$iVid)) + { + // select all the tokens that did not complete the Survey + $query2select_token = "SELECT token from {$dbprefix}tokens_".$iVid." WHERE completed = 'N'; "; + $rs = db_execute_assoc($query2select_token); + if($rs->RecordCount()<1) + { + throw new SoapFault("Database: ", "No unused Tokens found"); + exit; + } + + $n=0; + while($row = $rs->FetchRow()) + { + if($n == 0) + { + $sReturn = $row['token']; + } + else + { + $sReturn .= ",".$row['token']; + } + $n++; + } + // return Response: array([iVid],[return]) on the client side, you get this as an Array resp. list + // the keys in the array, containing the values, are named as defined in the wsdl under the response Message, in this case: array(iVid =>$iVid, return=>$sReturn) + + return $sReturn; + exit; + } + else + { + throw new SoapFault("Database: ", "Token table for this Survey does not exists"); + exit; + } +}//end of function sTokenReturn + +/** + * + * function to import an exported group of questions into a survey + * @param $sUser + * @param $sPass + * @param $iVid + * @param $sMod + * @param $gName + * @param $gDesc + * @return unknown_type + */ +function sImportGroup($sUser, $sPass, $iVid, $sMod, $gName='', $gDesc='') +{ + include("lsrc.config.php"); + $lsrcHelper = new lsrcHelper(); + $lsrcHelper->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", START OK "); + + if(!$lsrcHelper->checkUser($sUser, $sPass)) + { + throw new SoapFault("Authentication: ", "User or Password wrong"); + exit; + } + + //check for Surveyowner + if($lsrcHelper->getSurveyOwner($iVid)!=$_SESSION['loginID'] && !$_SESSION['USER_RIGHT_SUPERADMIN']=='1') + { + throw new SoapFault("Authentication: ", "You have no right to change Surveys from other people"); + exit; + } + + if(!is_file($modDir.$sMod.".csv")) + { + throw new SoapFault("Server: ", "Survey Module $sMod does not exist"); + exit; + } + + $checkImport = $lsrcHelper->importGroup($iVid, $sMod); + if(is_array($checkImport)) + { + if($gName!='') + $lsrcHelper->changeTable("groups", "group_name", $gName, "gid='".$checkImport['gid']."'"); + if($gDesc!='') + $lsrcHelper->changeTable("groups", "description", $gDesc, "gid='".$checkImport['gid']."'"); + + return "Import OK"; + } + else + { + throw new SoapFault("Server: ", $checkImport); + exit; + } + +} + +/** + * + * function to import a fixed question + * @param $sUser + * @param $sPass + * @param $iVid + * @param $sMod + * @param $mandatory + * @return unknown_type + */ +function sImportQuestion($sUser, $sPass, $iVid, $sMod, $mandatory='N') +{ + include("lsrc.config.php"); + $lsrcHelper = new lsrcHelper(); + $lsrcHelper->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", START OK "); + + // check for appropriate rights + if(!$lsrcHelper->checkUser($sUser, $sPass)) + { + throw new SoapFault("Authentication: ", "User or password wrong"); + exit; + } + + //check for Surveyowner + if($lsrcHelper->getSurveyOwner($iVid)!=$_SESSION['loginID'] && !$_SESSION['USER_RIGHT_SUPERADMIN']=='1') + { + throw new SoapFault("Authentication: ", "You have no right to change Surveys from other people"); + exit; + } + // Check if the file to import exists + if(!is_file($queDir.$sMod.".csv")) + { + throw new SoapFault("Server: ", "Survey Module $sMod does not exist"); + exit; + } + + //import the module + $lastId = $lsrcHelper->importQuestion($iVid,$sMod); + if(is_array($lastId)) + { +// $lsrcHelper->changeTable("questions", "title", $qTitle, "qid='".$lastId['qid']."'"); +// $lsrcHelper->changeTable("questions", "question", $qText, "qid='".$lastId['qid']."'"); +// $lsrcHelper->changeTable("questions", "help", $qHelp, "qid='".$lastId['qid']."'"); + $lsrcHelper->changeTable("questions", "mandatory", $mandatory, "qid='".$lastId['qid']."'"); + return "OK"; + } + else + { + throw new SoapFault("Server: ", $lastId); + exit; + } +} + +/** + * + * function to import one freetext question and change it + * @param $sUser + * @param $sPass + * @param $iVid + * @param $qTitle + * @param $qText + * @param $qHelp + * @param $sMod + * @param $mandatory + * @return unknown_type + */ +function sImportFreetext($sUser, $sPass, $iVid, $qTitle, $qText, $qHelp, $sMod='Freitext', $mandatory='N') +{ + /* + * this var maybe added later to constructor, + * to determine if a new group should be build for the question + * or if the question should be added to the last group in survey + */ + if($sMod=='') + $sMod='Freitext'; + if($mandatory=='') + $mandatory='N'; + + $newGroup=0; + + include("lsrc.config.php"); + $lsrcHelper = new lsrcHelper(); + $lsrcHelper->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", START OK "); + + // check for appropriate rights + if(!$lsrcHelper->checkUser($sUser, $sPass)) + { + throw new SoapFault("Authentication: ", "User or password wrong"); + exit; + } + + //check for Surveyowner + if($lsrcHelper->getSurveyOwner($iVid)!=$_SESSION['loginID'] && !$_SESSION['USER_RIGHT_SUPERADMIN']=='1') + { + throw new SoapFault("Authentication: ", "You have no right to change Surveys from other people"); + exit; + } + // Check if the file to import exists + if(!is_file($queDir.$sMod.".csv")) + { + throw new SoapFault("Server: ", "Survey Module $sMod does not exist"); + exit; + } + + //import the module + $lastId = $lsrcHelper->importQuestion($iVid,$sMod,0); + if(is_array($lastId)) + { + $lsrcHelper->changeTable("questions", "title", $qTitle, "qid='".$lastId['qid']."'"); + $lsrcHelper->changeTable("questions", "question", $qText, "qid='".$lastId['qid']."'"); + $lsrcHelper->changeTable("questions", "help", $qHelp, "qid='".$lastId['qid']."'"); + $lsrcHelper->changeTable("questions", "mandatory", $mandatory, "qid='".$lastId['qid']."'"); + return "OK"; + } + else + { + throw new SoapFault("Server: ", $lastId); + exit; + } +} + +/** + * + * function to import a five scale Matrix question and set 1 to n items + * @param $sUser + * @param $sPass + * @param $iVid + * @param $qTitle + * @param $qText + * @param $qHelp + * @param $sItems + * @param $sMod + * @param $mandatory + * @return unknown_type + */ +function sImportMatrix($sUser, $sPass, $iVid, $qTitle, $qText, $qHelp, $sItems, $sMod='Matrix5', $mandatory='N') +{ + /* + * this var maybe added later to constructor, + * to determine if a new group should be build for the question + * or if the question should be added to the last group in survey + */ + if($sMod=='') + $sMod='Matrix5'; + if($mandatory=='') + $mandatory='N'; + + $newGroup=0; + + global $connect ; + global $dbprefix ; + $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC; + include("lsrc.config.php"); + + $lsrcHelper = new lsrcHelper(); + $lsrcHelper->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", START OK"); + + // check for appropriate rights + if(!$lsrcHelper->checkUser($sUser, $sPass)) + { + throw new SoapFault("Authentication: ", "User or password wrong"); + exit; + } + //check for surveyOwner + if($lsrcHelper->getSurveyOwner($iVid)!=$_SESSION['loginID'] && !$_SESSION['USER_RIGHT_SUPERADMIN']=='1') + { + throw new SoapFault("Authentication: ", "You have no right to change Surveys from other people"); + exit; + } + // Check if the file to import exists + if(!is_file($queDir.$sMod.".csv")) + { + throw new SoapFault("Server: ", "Survey Module $sMod does not exist"); + exit; + } + $lastId = $lsrcHelper->importQuestion($iVid,$sMod,$newGroup); + if(is_array($lastId)) + { + $lsrcHelper->changeTable("questions", "title", $qTitle, "qid='".$lastId['qid']."'"); + $lsrcHelper->changeTable("questions", "question", $qText, "qid='".$lastId['qid']."'"); + $lsrcHelper->changeTable("questions", "help", $qHelp, "qid='".$lastId['qid']."'"); + if($mandatory==''){$mandatory='N';} + $lsrcHelper->changeTable("questions", "mandatory", $mandatory, "qid='".$lastId['qid']."'"); + + $aItems = explode(",", $sItems); + $n=0; + foreach($aItems as $item) + { + ++$n; + $lsrcHelper->changeTable("answers", "qid,code,answer,default_value,sortorder,language", "'".$lastId['qid']."', '$n','$item','N','$n','".GetBaseLanguageFromSurveyID($iVid)."' " , "", 1); + } + return "OK"; + } + else + { + throw new SoapFault("Server: ", $lastId); + exit; + } + +} + +/** + * + * function to collect all available Modules and send them comma seperated to the client + * @param String $sUser + * @param String $sPass + * @param String $mode ("mod" or "core") + * @return commma seperated list of available Modules (groups) + */ +function sAvailableModules($sUser, $sPass, $mode='mod') +{ + include("lsrc.config.php"); + $lsrcHelper = new lsrcHelper(); + $lsrcHelper->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.",mode=$mode START OK "); + + if(!$lsrcHelper->checkUser($sUser, $sPass)) + { + throw new SoapFault("Authentication: ", "User or password wrong"); + exit; + } + switch($mode){ + case ('mod'): + + $mDir = opendir($modDir); + $n=0; + while(false !== ($file = readdir($mDir))) + { + if($file!='.' && $file!='..' && substr($file,-4,4)==".csv") + { + $file = basename ($file, ".csv"); + //$file = str_replace("mod_", "", $file); + + if($n == 0) + { + $return = $file; + $n=1; + } + else + { + $return .= ",".$file; + } + } + + } + return $return; + break; + case ('core'): + + $cDir = opendir($coreDir); + $n=0; + while(false !== ($file = readdir($cDir))) + { + if($file!='.' && $file!='..' && substr($file,-4,4)==".csv") + { + $file = basename ($file, ".csv"); + //$file = str_replace("mod_", "", $file); + if($n == 0) + { + $return = $file; + $n=1; + + } + else + { + $return .= ",".$file; + } + } + } + return $return; + break; + case ('que'): + + $cDir = opendir($queDir); + $n=0; + while(false !== ($file = readdir($cDir))) + { + if($file!='.' && $file!='..' && substr($file,-4,4)==".csv") + { + $file = basename ($file, ".csv"); + //$file = str_replace("mod_", "", $file); + if($n == 0) + { + $return = $file; + $n=1; + + } + else + { + $return .= ",".$file; + } + } + } + return $return; + break; + } +} + +/** + * + * function to delete a survey + * @param unknown_type $sUser + * @param unknown_type $sPass + * @param unknown_type $iVid + */ +function sDeleteSurvey($sUser, $sPass, $iVid) +{ + include("lsrc.config.php"); + $lsrcHelper = new lsrcHelper(); + $lsrcHelper->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.",sid=$iVid START OK "); + + if(!$lsrcHelper->checkUser($sUser, $sPass)) + { + throw new SoapFault("Authentication: ", "User or password wrong"); + exit; + } + + if($lsrcHelper->getSurveyOwner($iVid)!=$_SESSION['loginID'] && !$_SESSION['USER_RIGHT_SUPERADMIN']=='1') + { + throw new SoapFault("Authentication: ", "You have no right to delete Surveys from other people"); + exit; + } + // check if the Survey exists, else -> Fault + if(!$lsrcHelper->surveyExists($iVid)) + { + throw new SoapFault("Database: ", "Survey $iVid does not exists"); + exit; + } + + if($lsrcHelper->deleteSurvey($iVid)) + { + return "Survey $iVid deleted"; + } + else + { + throw new SoapFault("Server: ", "Survey $iVid was not deleted"); + exit; + } + + +} + +/** + * + * This function pulls a CSV representation of the Field map + * @param $sUser + * @param $sPass + * @param $iVid + * @return unknown_type + */ +function sGetFieldmap($sUser, $sPass, $iVid) +{ + include("lsrc.config.php"); + $lsrcHelper = new lsrcHelper(); + + if(!$lsrcHelper->checkUser($sUser, $sPass)) + { + throw new SoapFault("Authentication: ", "User or password wrong"); + exit; + } + if($lsrcHelper->getSurveyOwner($iVid)!=$_SESSION['loginID'] && !$_SESSION['USER_RIGHT_SUPERADMIN']=='1') + { + throw new SoapFault("Authentication: ", "You have no right to get fieldmaps from other peoples Surveys"); + exit; + } + if(!$lsrcHelper->surveyExists($iVid)) + { + throw new SoapFault("Database: ", "Survey $iVid does not exists"); + exit; + } + + $returnCSV = "".$lsrcHelper->FieldMap2CSV($iVid); + return $returnCSV; + +} +?> \ No newline at end of file diff --git a/include/limesurvey/admin/remotecontrol/lsrc.testclient.php b/include/limesurvey/admin/remotecontrol/lsrc.testclient.php new file mode 100644 index 00000000..220e8663 --- /dev/null +++ b/include/limesurvey/admin/remotecontrol/lsrc.testclient.php @@ -0,0 +1,728 @@ + + + + + +LimeSurvey RC Testclient + + +'; + if(class_exists(SoapClient)) + { + $soapCheck .= "
    + SOAP Erweiterung existiert
    "; + } + else + { + $soapCheck .= "
    + SOAP Erweiterung fehlt!
    "; + } + if(LIBXML_VERSION>=20540) + { + $soapCheck .= "
    + libXML version '".LIBXML_DOTTED_VERSION."' OK
    "; + } + else + { + $soapCheck .= "
    + libXML version '".(LIBXML_DOTTED_VERSION )."' nicht OK
    "; + } + // Check ob eine wsdl Datei gefunden werden kann + //$wsdlfile = ; + + ini_set("allow_url_fopen", 1); + if (!fopen($path2wsdl,"r")) + { + $soapCheck .= "
    + Der Pfad zur WSDL Datei ist nicht korrekt oder die WSDL Datei fehlt!
    "; + } + else + { + $soapCheck .= "
    + WSDL Datei konnte gefunden werden
    "; + } + $soapCheck .= "
    +
    + + +
    +
    "; + return $soapCheck; +} + +//// We initiate a SOAPclient Object and give the ssl-certificate, if wished: +//$cert = 'D:\\xampp\apache\privkey.pem'; +if(isset($cert) && $cert!="") +{ + ini_set("allow_url_fopen", 1); + $file = fopen($wsdl,"r"); + if(class_exists(SoapClient) && $file!=FALSE) + { + /** + * TODO: no documentation in PHP manual... no doc here... Can't tell you what to do in order to get Communication working with fixed Certificates + * Can't even say, which certificates, how they have to be (.pem, .crt, .key etc.?) + * Own Microkosmos for Geeks only... Sad truth... + */ + $context = array( + 'ssl'=> array( + 'verify_peer' => false, + 'allow_self_signed' => true, + 'local_cert' => $cert + ) + ); + $stream_context = stream_context_create($context); + + $client = new SoapClient($wsdl, array('soap_version' => SOAP_1_1, + 'trace' => 1, + 'stream_context' => $stream_context + )); + } +} +else +{ + ini_set("allow_url_fopen", 1); + $file = fopen($wsdl,"r"); + if(class_exists(SoapClient) && $file!=FALSE) + { + $client = new SoapClient($wsdl, array('soap_version' => SOAP_1_1, + 'trace' => 1)); + } +} +if($file!=FALSE) +{ + try + { $mods = $client->sAvailableModules($user, "password", "mod");} + catch (SoapFault $fault) + { $mods .= "

    SOAP Error: ".$fault->faultcode." : ".$fault->faultstring."";} +} +if($file!=FALSE) +{ + try + { $cores = $client->sAvailableModules($user, "password", "core");} + catch (SoapFault $fault) + { $cores .= "

    SOAP Error: ".$fault->faultcode." : ".$fault->faultstring."";} +} + +$iVid = $_REQUEST['sid']; +//$sVbes = utf8_encode($sVbes); +//$user = $_REQUEST['user']; +//$pass = $_REQUEST['password']; + +// Calling the desired function //XXX +reset($_REQUEST); +while(list($key, $value) = each($_REQUEST)) +{ + if(substr($key,0,8)=="sendMail") + { + $iVid = $_REQUEST['sid']; + $sType = $_REQUEST['type']; + $maxemails = $_REQUEST['maxemails']; + $subject = $_REQUEST['subject']; + $mailText = $_REQUEST['mailText']; + + try + { + $sReturn = $client->sSendEmail($user, $pass, $iVid, $sType, $maxemails, $subject, $mailText); + } + catch (SoapFault $fault) + { + $sOutput .= "

    SOAP Error: ".$fault->faultcode." : ".$fault->faultstring.""; + } + //these are just outputs for testing + $sOutput .= "

    Return: ". $sReturn; + + + + } + if(substr($key,0,8)=="getField") + { + $iVid = $_REQUEST['sid']; + + try + { + $sReturn = $client->sGetFieldmap($user, $pass, $iVid); + } + catch (SoapFault $fault) + { + $sOutput .= "

    SOAP Error: ".$fault->faultcode." : ".$fault->faultstring.""; + } + //these are just outputs for testing + $sOutput .= "

    Return: ". $sReturn; + + + } + if(substr($key,0,9)=="delsurvey") + { + $iVid = $_REQUEST['sid']; + //$sMod = $_REQUEST['mod']; + try + { + $sReturn = $client->sDeleteSurvey($user, $pass, $iVid); + } + catch (SoapFault $fault) + { + $sOutput .= "

    SOAP Error: ".$fault->faultcode." : ".$fault->faultstring.""; + } + //these are just outputs for testing + $sOutput .= "

    Return: ". $sReturn; + } + + if(substr($key,0,9)=="impMatrix") + { + $iVid = $_REQUEST['sid']; + // $sMod = $_REQUEST['mod']; + // $qTitle = $_REQUEST['title']; + $qText = $_REQUEST['quest']; + $mandatory = $_REQUEST['mandatory']; + for($n=1;$n<10;++$n) + { + if($_REQUEST['item'.$n]!='') + { + if($n==1) + { + $items = $_REQUEST['item'.$n]; + } + else + { + $items .= ",".$_REQUEST['item'.$n]; + } + } + } + + $qHelp = $_REQUEST['help']; + + try + { + + $sReturn = $client->sImportMatrix($user, $pass, $iVid, $qTitle, $qText, $qHelp, $items, "Matrix5", $mandatory); + } + catch (SoapFault $fault) + { + $sOutput .= "

    SOAP Error: ".$fault->faultcode." : ".$fault->faultstring.""; + } + //these are just outputs for testing + $sOutput .= "

    Return: ". $sReturn; + } + + if(substr($key,0,8)=="impQuest") + { + $iVid = $_REQUEST['sid']; + // $sMod = $_REQUEST['mod']; + $qTitle = $_REQUEST['title']; + $qText = $_REQUEST['quest']; + $qHelp = $_REQUEST['help']; + $mandatory = $_REQUEST['mandatory']; + + try + { + + $sReturn = $client->sImportFreetext($user, $pass, $iVid, $qTitle, $qText, $qHelp, "Freitext", $mandatory); + } + catch (SoapFault $fault) + { + $sOutput .= "

    SOAP Error: ".$fault->faultcode." : ".$fault->faultstring.""; + } + //these are just outputs for testing + $sOutput .= "

    Return: ". $sReturn; + } + + if(substr($key,0,8)=="impGroup") + { + $iVid = $_REQUEST['sid']; + $sMod = $_REQUEST['mod']; + $sGroupName = $_REQUEST['groupName']; + $sGroupDescription = $_REQUEST['groupDescription']; + try + { + $sReturn = $client->sImportGroup($user, $pass, $iVid, $sMod, $sGroupName, $sGroupDescription); + } + catch (SoapFault $fault) + { + $sOutput .= "

    SOAP Error: ".$fault->faultcode." : ".$fault->faultstring.""; + } + //these are just outputs for testing + $sOutput .= "

    Return: ". $sReturn; + } + + if(substr($key,0,8)=="activate") + { + $iVid = $_REQUEST['sid']; + $dStart = $_REQUEST['start']; + $dEnd = $_REQUEST['end']; + if(isset($dStart) && $dStart!='') + { + $sUseStart='Y'; + } + if(isset($dEnd) && $dEnd!='') + { + $sUseEnd='Y'; + } + + try + { + $sReturn = $client->sActivateSurvey($user, $pass, $iVid, $dStart, $dEnd); + } + catch (SoapFault $fault) + { + $sOutput .= "

    SOAP Error: ".$fault->faultcode." : ".$fault->faultstring.""; + } + //these are just outputs for testing + $sOutput .= "

    Return: ". $sReturn; + } + + if(substr($key,0,6)=="submit") + { + //$functionToCall = "sCreateSurvey"; + $iVid = $_REQUEST['sid']; + $sVbes = $_REQUEST['sdes']; + $sVtit = $_REQUEST['stit']; + $sVwel = $_REQUEST['sVwel']; + $sVend = $_REQUEST['sVend']; + $sMail = $_REQUEST['sEmail']; + $sName = $_REQUEST['sName']; + $sUrl = $_REQUEST['sUrl']; + $sUbes = $_REQUEST['sUdes']; + $sVtyp = $_REQUEST['core']; + + try + { + $sReturn = $client->sCreateSurvey($user, $pass, $iVid, $sVtit , $sVbes, $sVwel, $sVend, $sMail, $sName, $sUrl, $sUbes, $sVtyp); + } + catch (SoapFault $fault) + { + $sOutput .= "

    SOAP Error: ".$fault->faultcode." : ".$fault->faultstring.""; + } + //these are just outputs for testing + $sOutput .= "

    Return: ". $sReturn; + } + if(substr($key,0,6)=="change") + { + $table = $_REQUEST['table']; + $key = $_REQUEST['key']; + $value = $_REQUEST['value']; + $where = $_REQUEST['whereKey']; + $mode = $_REQUEST['mode']; + //$whereValue = $_REQUEST['whereValue']; + + try + { + $sReturn = $client->sChangeSurvey($user, $pass , $table, $key, $value, $where, $mode); + } + catch (SoapFault $fault) + { + $sOutput .= "

    SOAP Error: ".$fault->faultcode." : ".$fault->faultstring.""; + } + //these are just outputs for testing + $sOutput .= "

    Return: ". $sReturn; + } + if(substr($key,0,6)=="tokens") + { + $sToken = $_REQUEST['token']; + try + { + $sReturn = $client->sInsertToken($user, $pass, $iVid, $sToken ); + } + catch (SoapFault $fault) + { + $sOutput .= "

    SOAP Error: ".$fault->faultcode." : ".$fault->faultstring.""; + } + //this are just outputs for testing + $sOutput .= "

    Return: ". $sReturn; + } + if(substr($key,0,6)=="tokRet") + { + //$functionToCall = "sTokenReturn"; + try + { + $sReturn = $client->sTokenReturn($user, $pass, $iVid); + } + catch (SoapFault $fault) + { + $sOutput .= "

    SOAP Error: ".$fault->faultcode." : ".$fault->faultstring.""; + } + //this are the return Values + $sOutput .= "

    Return:
    ['return'] => ". $sReturn; + } + if(substr($key,0,6)=="insPar") + { + $sParticipantData = $_REQUEST['sParticipantData']; + try + { + $sReturn = $client->sInsertParticipants($user, $pass, $iVid, $sParticipantData); + } + catch (SoapFault $fault) + { + $sOutput .= "

    SOAP Error: ".$fault->faultcode." : ".$fault->faultstring.""; + } + //these are just outputs for testing + $sOutput .= "

    Return: ". $sReturn; + } +} +if(isset($sReturn)) +{ + $sOutput .="

    Dumping request headers:
    "
    +	.$client->__getLastRequestHeaders()."
    "; + + $sOutput .="Dumping request:".htmlentities($client->__getLastRequest()).""; + + $sOutput .="


    Dumping response headers:
    "
    +	.$client->__getLastResponseHeaders()."
    "; + $sOutput .="
    Dumping response:
    ".htmlentities($client->__getLastResponse()).""; + //$resp[] = $client->__getLastResponse(); + // echo $resp['resParam']; +} +?> + + + +Client object functions:
    (As given in the wsdl file. Functions could be disabled or else on the serverside. There is no guarantee the functions really have these Params nor that the functions exist on the serverside.)
    "; + if($file!=FALSE) + { + $funcs=$client->__getFunctions(); + + foreach($funcs as $func) + { + echo '

    '; + print_r($func); + echo '

    '; + } + } +} + +if(isset($sOutput)) +{ + + echo '
    '; + echo '

    testing output:

    '; + if(isset($iVid)) + { + echo "test Survey"; + } + echo $sOutput; + echo '
    '; +} +?> +
    +

    sCreateSurvey function

    +
    ' method='post'> +* VeranstaltungsTyp: +
    +
    +* VeranstaltungsID / SurveyID (have to be Integer): +
    +
    +* Veranstaltungs Titel / Survey Title (used +as part of the welcome message, if welcome Message is left blank):
    +
    +* VeranstaltungsBeschreibung / +SurveyDescription (used as part of the welcome message, if welcome +Message is left blank):
    +
    +Willkommenstext / Welcome Message:
    +
    +Endtext / endtext:
    +
    +Admin Name:
    +
    +Admin Email:
    +
    +End Url:
    +
    +Url Description:
    +
    +" ?> +
    +
    + + +
    +

    sActivateSurvey function

    +
    ' method='post'>* VeranstaltungsID / SurveyID: +
    +
    +Startdate (YYYY-MM-DD):
    +
    +Enddate (YYYY-MM-DD):
    +
    +" ?> +
    +
    + +
    +

    sDeleteSurvey function

    (attention: no safetyquestion is asked!)
    +
    ' method='post'>* VeranstaltungsID / SurveyID: +
    +
    + " ?> +
    +
    + +
    +

    sImportGroup function

    +
    ' method='post'>* VeranstaltungsID / SurveyID (have to be Integer): +
    +
    +* Question group to add (INF,BIO,BWL is +there for testing):
    +
    +Name of the group:
    +
    +groupDescription:
    +
    +" ?> +
    +
    + +
    +

    sImportQuestion

    +
    ' method='post'>* VeranstaltungsID / SurveyID (have to be Integer): +
    +
    + Mandatory
    +* Question Title :
    +
    +* Question:
    +
    +Helptext:
    +
    +" ?> +
    +
    + +
    +

    sImportMatrix

    +
    ' method='post'>* VeranstaltungsID / SurveyID (have to be Integer): +
    +
    + Mandatory
    +* Question :
    +
    +Item {$n} :
    ", + "", + "
    "; +} +?> Helptext:
    +
    +" ?> +
    +
    + + +
    +

    sChangeSurvey function

    +( this is not part of the lsrc, it just shows the power of it,
    it has to be activated in server.php on line ~60 ) +
    ' method='post'> + update + insert
    +Table to change
    +
    +Key
    +
    +Value
    +
    +where Condition
    +
    +
    + +
    +
    +sInsertToken function"; +echo "

    Makes the Survey closed.
    Means: It's only available to people who have an unused token

    "; +echo "
    "; +echo "* VeranstaltungsID / SurveyID (have to be Integer):
    "; +echo ""; +echo "
    "; +echo "Tokens seperated by comma (,) :
    "; +echo ""; +echo "
    "; +echo ""; +echo ""; +echo "
    "; +echo "
    "; + + +echo "
    "; +echo "

    sTokenReturn function

    "; +echo "
    "; +echo "* VeranstaltungsID / SurveyID (have to be Integer):
    "; +echo "
    "; +echo ""; +echo ""; +echo "
    "; + +echo "
    "; +echo "

    sInsertParticipants function

    "; +echo "

    Makes the Survey closed. Means: It's only available to people who have an unused token

    "; +echo "
    "; +echo "* VeranstaltungsID / SurveyID (have to be Integer):
    "; +echo ""; +echo "
    "; +echo "* Data in this Format [params in square brackets are optional]:
    \"FIRSTNAME;LASTNAME;EMAIL[;[ATTRIB1];[ATTRIB2]]::FIRSTNAME;LASTNAME;EMAIL[;[ATTRIB1];[ATTRIB2]]\" and so on :

    "; +echo " "; +echo "
    "; +echo ""; +echo ""; +echo "
    "; +echo "
    "; + +echo "
    "; +echo "

    sSendEmail function

    "; +echo "

    Sends an Email to users of a specific survey. Invite, Remind and custom emails are possible

    "; +echo "
    "; +echo "* SurveyID (have to be Integer):
    "; +echo ""; +echo "
    "; +echo "* Email Type:
    "; +echo " invite"; +echo " remind"; +echo " custom
    "; +echo "Maxemails (have to be Integer):
    "; +echo ""; +echo "
    "; +//echo "* Data in this Format [params in square brackets are optional]:
    \"FIRSTNAME;LASTNAME;EMAIL[;[ATTRIB1];[ATTRIB2]]::FIRSTNAME;LASTNAME;EMAIL[;[ATTRIB1];[ATTRIB2]]\" and so on :

    "; +echo "Subject for custom cails
    "; +echo "
    "; +echo "Mailtext for custom cails
    "; +echo " "; +echo "
    "; +echo ""; +echo ""; +echo "
    "; +echo "
    "; + +echo "
    "; +echo "

    sGetFieldmap function

    "; +echo "

    Gets you the fieldmap from a survey as csv

    "; +echo "
    "; +echo "* VeranstaltungsID / SurveyID (have to be Integer):
    "; +echo "
    "; +echo ""; +echo ""; +echo "
    "; +//phpinfo(); + +?> + + + diff --git a/include/limesurvey/admin/remotecontrol/lsrc_orig.wsdl b/include/limesurvey/admin/remotecontrol/lsrc_orig.wsdl new file mode 100644 index 00000000..b166580c --- /dev/null +++ b/include/limesurvey/admin/remotecontrol/lsrc_orig.wsdl @@ -0,0 +1,606 @@ + + + + + + + + + + Function to start Surveys in LimeSurvey... + + + Admin or Superadmin Account in Limesurvey needed + + + + Correct password for the Superadmin in + Limesurvey + + + + This is the "VeranstaltungsID" similar to the SurveyID... Integer expected... + + + titel of the event, put together from NR and NAME from LSF. veranstaltung + + This is the "Veranstaltungsbeschreibung", the Surveydescription. + String expected. Put together from TYP, DOZENTEN- TITLE, -NAME, + + + + + The E-Mail Adress of the Person who to contact in matters of evaluation. Limesurvey uses this to send notifications of Surveyparticipation, if wante + The Name of the Administrator, resp. the Person whos email Adress was given + + The URL to wich will be redirected when completing the Survey + + The text for the Link, if not loaded automatically + + + + + + + + This is the return Value of sCreateSurvey, if everything went fine it's the sid(SurveyID) resp. vid(VeranstaltungsID) of the newly imported Survey + + + + + + + Admin or Superadmin Account in Limesurvey needed + + + + Correct password for the Superadmin in Limesurvey + + + + SurveyID of existing Survey, which gets the Token table + + + + String of tokens seperated by a comma (default)... You have the possibility to change the desired seperator in LimeSurveys config.php + + + + + + + + This is the return Value of InsertToken, if everything went fine it's "Token table populated successfully" + + + + + + + Admin or Superadmin Account in Limesurvey needed + + + + Correct password for the Superadmin in Limesurvey + + + + SurveyID of existing Survey, which gets the Token table + + + + Data for Participant expected in this format: [Firstname];[Lastname];[email@email.de]::[Firstname];[Lastname];[email@email.de]::[Firstname];[Lastname];[email@email.de] and so on... seperate the Datasets with :: and the Datafields in the Sets with ; + + + + + + This is the return Value of sInsertParticipants, if everything went fine it's "Token table populated successfully" + + + + + + + Admin or Superadmin Account in Limesurvey needed + + + + Correct password for the Superadmin in Limesurvey + + + + SurveyID of existing Survey, which has a Token table + + + + + + + + String of unused Tokens seperated by comma + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Creates (Import and activate) a Survey in LimeSurvey + + + + + + Create Token-Table and populate it for closed LimeSurvey Surveys + + + + + + Create Token-Table and populate it with personal data for closed Surveys + + + + + + Returns unused Tokens from closed LimeSurvey Surveys + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + This is the LsrcService + for remote starting surveys and registering tokens in LimeSurvey. + Make sure to modify the soap:address to the current Location of the lsrcserver.php + It has to be like this: 'http://servername/[limesurveydir]/lsrcservice/lsrcserver.php' + NOTE: http for normal mode, begin the url with https for a SSL Webservice, it's just that easy. + + + + + + + \ No newline at end of file diff --git a/include/limesurvey/admin/remotecontrol/questions/Freitext.csv b/include/limesurvey/admin/remotecontrol/questions/Freitext.csv new file mode 100644 index 00000000..4e7bdf88 --- /dev/null +++ b/include/limesurvey/admin/remotecontrol/questions/Freitext.csv @@ -0,0 +1,27 @@ +# LimeSurvey Question Dump +# DBVersion 132 +# This is a dumped question from the LimeSurvey Script +# http://www.limesurvey.org/ +# Do not change this header! + +# +# QUESTIONS TABLE +# +"qid","sid","gid","type","title","question","preg","help","other","mandatory","lid","lid1","question_order","language" +"2902","666","559","T","1","Placeholder","","Placeholder","N","Y","0","0","0","de" + +# +# ANSWERS TABLE +# + +# +# LABELSETS TABLE +# + +# +# LABELS TABLE +# + +# +# QUESTION_ATTRIBUTES TABLE +# diff --git a/include/limesurvey/admin/remotecontrol/questions/Matrix5.csv b/include/limesurvey/admin/remotecontrol/questions/Matrix5.csv new file mode 100644 index 00000000..873e6c83 --- /dev/null +++ b/include/limesurvey/admin/remotecontrol/questions/Matrix5.csv @@ -0,0 +1,27 @@ +# LimeSurvey Question Dump +# DBVersion 132 +# This is a dumped question from the LimeSurvey Script +# http://www.limesurvey.org/ +# Do not change this header! + +# +# QUESTIONS TABLE +# +"qid","sid","gid","type","title","question","preg","help","other","mandatory","lid","lid1","question_order","language" +"2904","666","560","A","1","This is a question
    ","","","N","N","0","0","0","de" + +# +# ANSWERS TABLE +# + +# +# LABELSETS TABLE +# + +# +# LABELS TABLE +# + +# +# QUESTION_ATTRIBUTES TABLE +# diff --git a/include/limesurvey/admin/remotecontrol/questions/index.html b/include/limesurvey/admin/remotecontrol/questions/index.html new file mode 100644 index 00000000..e69de29b diff --git a/include/limesurvey/admin/remotecontrol/surveys/Empty.csv b/include/limesurvey/admin/remotecontrol/surveys/Empty.csv new file mode 100644 index 00000000..9609958c --- /dev/null +++ b/include/limesurvey/admin/remotecontrol/surveys/Empty.csv @@ -0,0 +1,58 @@ +# LimeSurvey Survey Dump +# DBVersion 138 +# This is a dumped survey from the LimeSurvey Script +# http://www.limesurvey.org/ +# Do not change this header! + +# +# SURVEYS TABLE +# +"sid","owner_id","admin","active","startdate","expires","adminemail","private","faxto","format","template","language","additional_languages","datestamp","usecookie","notification","allowregister","allowsave","printanswers","autonumber_start","autoredirect","allowprev","ipaddr","refurl","datecreated","listpublic","publicstatistics","publicgraphs","htmlemail","tokenanswerspersistence","assessments","usecaptcha","bounce_email","usetokens","attributedescriptions" +"26553","1","Tim Wahrendorff","N","","","wahrendorff@localhost","Y","","G","hisinone","de","","N","N","0","N","Y","N","0","N","Y","N","N","2009-04-21","N","N","N","Y","N","N","D","wahrendorff@localhost","N","" + +# +# GROUPS TABLE +# + +# +# QUESTIONS TABLE +# + +# +# ANSWERS TABLE +# + +# +# CONDITIONS TABLE +# + +# +# LABELSETS TABLE +# + +# +# LABELS TABLE +# + +# +# QUESTION_ATTRIBUTES TABLE +# + +# +# ASSESSMENTS TABLE +# + +# +# SURVEYS_LANGUAGESETTINGS TABLE +# +"surveyls_survey_id","surveyls_language","surveyls_title","surveyls_description","surveyls_welcometext","surveyls_url","surveyls_urldescription","surveyls_endtext","surveyls_email_invite_subj","surveyls_email_invite","surveyls_email_remind_subj","surveyls_email_remind","surveyls_email_register_subj","surveyls_email_register","surveyls_email_confirm_subj","surveyls_email_confirm","surveyls_dateformat" +"26553","de","Empty","","","","","
    ","Einladung zur Teilnahme an einer Umfrage","Hallo {FIRSTNAME},

    Hiermit möchten wir Sie zu einer Umfrage einladen.

    Der Titel der Umfrage ist
    '{SURVEYNAME}'

    '{SURVEYDESCRIPTION}'

    Um an dieser Umfrage teilzunehmen, klicken Sie bitte auf den unten stehenden Link.

    Mit freundlichen Grüßen,

    {ADMINNAME} ({ADMINEMAIL})

    ----------------------------------------------
    Klicken Sie hier um die Umfrage zu starten:
    {SURVEYURL}","Erinnerung an Teilnahme an einer Umfrage","Hallo {FIRSTNAME},

    Vor kurzem haben wir Sie zu einer Umfrage eingeladen.

    Zu unserem Bedauern haben wir bemerkt, dass Sie die Umfrage noch nicht ausgefüllt haben. Wir möchten Ihnen mitteilen, dass die Umfrage noch aktiv ist und würden uns freuen, wenn Sie teilnehmen könnten.

    Der Titel der Umfrage ist
    '{SURVEYNAME}'

    '{SURVEYDESCRIPTION}'

    Um an dieser Umfrage teilzunehmen, klicken Sie bitte auf den unten stehenden Link.

    Mit freundlichen Grüßen,

    {ADMINNAME} ({ADMINEMAIL})

    ----------------------------------------------
    Klicken Sie hier um die Umfrage zu starten:
    {SURVEYURL}","Registrierungsbestätigung für Teilnahmeumfrage","Hallo {FIRSTNAME},

    Sie (oder jemand, der Ihre Email benutzt hat) haben sich für eine Umfrage mit dem Titel {SURVEYNAME} angemeldet.

    Um an dieser Umfrage teilzunehmen, klicken Sie bitte auf den folgenden Link.

    {SURVEYURL}

    Wenn Sie irgendwelche Fragen zu dieser Umfrage haben oder wenn Sie sich _nicht_ für diese Umfrage angemeldet haben und sie glauben, dass Ihnen diese Email irrtümlicherweise zugeschickt worden ist, kontaktieren Sie bitte {ADMINNAME} unter {ADMINEMAIL}.","Abschlussbestätigung einer Umfrage","Hallo {FIRSTNAME},

    Vielen Dank für die Teilnahme an der Umfrage mit dem Titel {SURVEYNAME}. Ihre Antworten wurden bei uns gespeichert.

    Wenn Sie irgendwelche Fragen zu dieser Email haben, kontaktieren Sie bitte {ADMINNAME} unter {ADMINEMAIL}.

    Mit freundlichen Grüßen,

    {ADMINNAME}","1" + +# +# QUOTA TABLE +# + +# +# QUOTA_MEMBERS TABLE +# + diff --git a/include/limesurvey/admin/remotecontrol/surveys/index.html b/include/limesurvey/admin/remotecontrol/surveys/index.html new file mode 100644 index 00000000..e69de29b diff --git a/include/limesurvey/admin/remotecontrol/surveys/template_db138.csv b/include/limesurvey/admin/remotecontrol/surveys/template_db138.csv new file mode 100644 index 00000000..f4d630d4 --- /dev/null +++ b/include/limesurvey/admin/remotecontrol/surveys/template_db138.csv @@ -0,0 +1,146 @@ +# LimeSurvey Survey Dump +# DBVersion 138 +# This is a dumped survey from the LimeSurvey Script +# http://www.limesurvey.org/ +# Do not change this header! + +# +# SURVEYS TABLE +# +"sid","owner_id","admin","active","startdate","expires","adminemail","private","faxto","format","template","language","additional_languages","datestamp","usecookie","notification","allowregister","allowsave","printanswers","autonumber_start","autoredirect","allowprev","ipaddr","refurl","datecreated","listpublic","publicstatistics","publicgraphs","htmlemail","tokenanswerspersistence","assessments","usecaptcha","bounce_email","usetokens","attributedescriptions" +"43521","1","Tim Wahrendorff","N","","","wahrendorff@his.de","Y","","G","hisinone","de","","N","N","0","N","N","N","0","N","Y","N","N","2009-06-02","N","N","N","Y","N","N","D","wahrendorff@his.de","N","" + +# +# GROUPS TABLE +# +"gid","sid","group_name","group_order","description","language" +"21","43521","Angaben zum Teilnehmer / zur Teilnehmerin","0","","de" +"22","43521","Angaben zur Lehrveranstaltung","1","","de" +"23","43521","Angaben zur Lehrperson","2","","de" +"24","43521","Abschließende Bewertung","3","","de" + +# +# QUESTIONS TABLE +# +"qid","sid","gid","type","title","question","preg","help","other","mandatory","lid","lid1","question_order","language" +"65","43521","21","G","1","Geben Sie bitte Ihr Geschlecht an.
    ","","Diese Frage dient der späteren Auswertung nach Geschlecht. Es steht Ihnen frei diese Frage nicht zu beantworten.
    ","N","N","0","0","0","de" +"66","43521","21","Z","2","In welchem Fachsemester befinden Sie sich momentan?
    ","","","N","N","3","0","1","de" +"67","43521","21","S","3","In welchem Studienfach besuchen Sie die Lehrveranstaltung?
    ","","Bitte geben Sie den offiziellen Namen des Studienfachs an, für den Sie eingeschrieben sind.
    ","N","N","0","0","2","de" +"68","43521","21","!","4","Welchen Abschluss streben Sie an?
    ","","","N","N","0","0","3","de" +"69","43521","21","F","5","Haben Sie regelmässig an der Veranstaltung teilgenommen?
    ","","","N","Y","2","0","4","de" +"70","43521","21","M","5a","Ich habe aus folgendem Grund / folgenden Gründen nicht an der Lehrveranstaltung teilgenommen:
    ","","(Mehrfachnennung möglich)
    ","Y","N","0","0","5","de" +"71","43521","21","M","6","
    Was  ist  der  vorrangige  Grund  für  den  Besuch  dieser Lehrveranstaltung?
    \n
    ","","(Mehrfachnennung möglich)","Y","N","0","0","6","de" +"72","43521","22","F","7","Die Lehrveranstaltung fiel häufig aus.
    ","","","N","Y","1","0","0","de" +"73","43521","22","F","8","Die Lehrveranstaltung hat ein erkennbares Ziel.
    ","","","N","Y","1","0","1","de" +"74","43521","22","F","9","Die Leistungsanforderungen in der Lehrveranstaltung sind zu hoch.
    ","","","N","Y","1","0","2","de" +"75","43521","22","F","10","Ich lerne viel in der Lehrveranstaltung.
    ","","","N","Y","1","0","3","de" +"76","43521","22","F","11","Diese Lehrveranstaltung ist im Studienverlauf richtig positioniert.
    ","","","N","Y","1","0","4","de" +"77","43521","23","F","12","Die Lehrperson setzt Medien angemessen ein.
    ","","","N","Y","1","0","0","de" +"78","43521","23","F","13","Die Lehrperson hat die Lehrveranstaltung regelmäßig selbst gehalten.
    ","","","N","Y","1","0","1","de" +"79","43521","23","F","14","Ich würde die Lehrperson für diese Lehrveranstaltung weiterempfehlen.
    ","","","N","Y","1","0","2","de" +"80","43521","24","F","15","Ich würde diese Lehrveranstaltung weiterempfehlen.
    ","","","N","Y","1","0","0","de" + +# +# ANSWERS TABLE +# +"qid","code","answer","default_value","sortorder","assessment_value","language" +"68","bac","Bachelor","N","3","0","de" +"68","dipl","Diplom","N","1","0","de" +"68","mag","Magister","N","4","0","de" +"68","mas","Master","N","2","0","de" +"69","1","Ich habe|an der Veranstaltung teilgenommen","N","1","1","de" +"70","1","Zeitliche Überschneidung mit anderen Kursen","N","1","1","de" +"70","2","Zu viel Kurse","N","2","2","de" +"70","3","Zulassung für andere Kurse erhalten","N","3","3","de" +"70","4","Zu hoher Arbeitsaufwand","N","4","4","de" +"70","5","Thema nicht interessant","N","5","5","de" +"71","1","Pflichtveranstaltung","N","1","1","de" +"71","2","Prüfungsrelevanz","N","2","2","de" +"71","3","Examensvorbereitung","N","3","3","de" +"71","4","Scheinerwerb","N","4","4","de" +"71","5","Interesse","N","5","5","de" +"71","6","Zeitlich günstig","N","6","6","de" +"71","7","Lehrperson","N","7","7","de" +"72","1","trifft zu|trifft nicht zu","N","1","1","de" +"73","1","trifft zu|trifft nicht zu","N","1","1","de" +"74","1","trifft zu|trifft nicht zu","N","1","1","de" +"75","1","trifft zu|trifft nicht zu","N","1","1","de" +"76","1","trifft zu|trifft nicht zu","N","1","1","de" +"77","1","trifft zu|trifft nicht zu","N","1","1","de" +"78","1","trifft zu|trifft nicht zu","N","1","1","de" +"79","1","trifft zu|trifft nicht zu","N","1","0","de" +"80","1","trifft zu|trifft nicht zu","N","1","0","de" + +# +# CONDITIONS TABLE +# +"cid","qid","scenario","cqid","cfieldname","method","value" +"5","70","1","69","43521X21X691","> ","1" + +# +# LABELSETS TABLE +# +"lid","label_name","languages" +"1","1_to_5","de en" +"2","teilgenommen nicht teilgenommen","de" +"3","Fachsemester","de" + +# +# LABELS TABLE +# +"lid","code","title","sortorder","language" +"3","1","1 bis 4","1","de" +"2","1","Immer","1","de" +"1","3","3","3","en" +"3","2","4 bis 8","2","de" +"1","3","3","3","de" +"3","4",">14","4","de" +"1","1","1","1","en" +"1","5","5","5","en" +"3","3","8 bis 14","3","de" +"1","2","2","2","de" +"1","4","4","4","en" +"2","2","Meistens","2","de" +"1","5","5","5","de" +"1","1","1","1","de" +"2","4","Nie","4","de" +"2","3","Selten","3","de" +"1","2","2","2","en" +"1","4","4","4","de" + +# +# QUESTION_ATTRIBUTES TABLE +# +"qaid","qid","attribute","value" +"53","67","text_input_width","80" +"54","68","hide_tip","1" +"55","69","answer_width","70" +"56","71","hide_tip","1" +"57","72","answer_width","70" +"58","73","answer_width","70" +"59","74","answer_width","70" +"60","75","answer_width","70" +"61","76","answer_width","70" +"62","77","answer_width","70" +"63","78","answer_width","70" +"64","79","answer_width","70" +"65","80","answer_width","70" + +# +# ASSESSMENTS TABLE +# + +# +# SURVEYS_LANGUAGESETTINGS TABLE +# +"surveyls_survey_id","surveyls_language","surveyls_title","surveyls_description","surveyls_welcometext","surveyls_url","surveyls_urldescription","surveyls_endtext","surveyls_email_invite_subj","surveyls_email_invite","surveyls_email_remind_subj","surveyls_email_remind","surveyls_email_register_subj","surveyls_email_register","surveyls_email_confirm_subj","surveyls_email_confirm","surveyls_dateformat" +"43521","de","Umfragevorlage 06.2009","Umfragevorlage Universität zu Köln 06/2009
    ","Herzlich Willkommen!
    ","http://his.de","HIS GmbH","Vieln Dank für Ihre Teilnahme an der Umfrage.
    ","Einladung zur Teilnahme an einer Umfrage","Hallo {FIRSTNAME},

    Hiermit möchten wir Sie zu einer Umfrage einladen.

    Der Titel der Umfrage ist
    '{SURVEYNAME}'

    '{SURVEYDESCRIPTION}'

    Um an dieser Umfrage teilzunehmen, klicken Sie bitte auf den unten stehenden Link.

    Mit freundlichen Grüßen,

    {ADMINNAME} ({ADMINEMAIL})

    ----------------------------------------------
    Klicken Sie hier um die Umfrage zu starten:
    {SURVEYURL}","Erinnerung an Teilnahme an einer Umfrage","Hallo {FIRSTNAME},

    Vor kurzem haben wir Sie zu einer Umfrage eingeladen.

    Zu unserem Bedauern haben wir bemerkt, dass Sie die Umfrage noch nicht ausgefüllt haben. Wir möchten Ihnen mitteilen, dass die Umfrage noch aktiv ist und würden uns freuen, wenn Sie teilnehmen könnten.

    Der Titel der Umfrage ist
    '{SURVEYNAME}'

    '{SURVEYDESCRIPTION}'

    Um an dieser Umfrage teilzunehmen, klicken Sie bitte auf den unten stehenden Link.

    Mit freundlichen Grüßen,

    {ADMINNAME} ({ADMINEMAIL})

    ----------------------------------------------
    Klicken Sie hier um die Umfrage zu starten:
    {SURVEYURL}","Registrierungsbestätigung für Teilnahmeumfrage","Hallo {FIRSTNAME},

    Sie (oder jemand, der Ihre Email benutzt hat) haben sich für eine Umfrage mit dem Titel {SURVEYNAME} angemeldet.

    Um an dieser Umfrage teilzunehmen, klicken Sie bitte auf den folgenden Link.

    {SURVEYURL}

    Wenn Sie irgendwelche Fragen zu dieser Umfrage haben oder wenn Sie sich _nicht_ für diese Umfrage angemeldet haben und sie glauben, dass Ihnen diese Email irrtümlicherweise zugeschickt worden ist, kontaktieren Sie bitte {ADMINNAME} unter {ADMINEMAIL}.","Abschlussbestätigung einer Umfrage","Hallo {FIRSTNAME},

    Vielen Dank für die Teilnahme an der Umfrage mit dem Titel {SURVEYNAME}. Ihre Antworten wurden bei uns gespeichert.

    Wenn Sie irgendwelche Fragen zu dieser Email haben, kontaktieren Sie bitte {ADMINNAME} unter {ADMINEMAIL}.

    Mit freundlichen Grüßen,

    {ADMINNAME}","1" + +# +# QUOTA TABLE +# + +# +# QUOTA_MEMBERS TABLE +# + diff --git a/include/limesurvey/admin/resetsurveylogic.php b/include/limesurvey/admin/resetsurveylogic.php index 8479aa09..1313c8af 100644 --- a/include/limesurvey/admin/resetsurveylogic.php +++ b/include/limesurvey/admin/resetsurveylogic.php @@ -10,13 +10,12 @@ * other free or open source software licenses. * See COPYRIGHT.php for copyright notices and details. * -* $Id: resetsurveylogic.php 3571 2007-11-02 20:43:25Z leochaton $ +* $Id: resetsurveylogic.php 6853 2009-05-15 12:51:09Z c_schmitz $ */ //Ensure script is not run directly, avoid path disclosure include_once("login_check.php"); -if (isset($_GET['sid'])) {$surveyid = $_GET['sid'];} -if (isset($_GET['ok'])) {$ok = $_GET['ok'];} +$ok = returnglobal('ok'); $resetsurveylogicoutput = "
    \n"; $resetsurveylogicoutput .= "\n"; @@ -60,7 +59,7 @@ else //delete conditions in the survey $tablelist = $connect->MetaTables(); $dict = NewDataDictionary($connect); - $resetlogicquery = "DELETE c.* FROM {$dbprefix}conditions as c, {$dbprefix}questions as q WHERE c.qid=q.qid AND q.sid=$surveyid"; + $resetlogicquery = "DELETE FROM {$dbprefix}conditions WHERE qid in (select qid from {$dbprefix}questions where sid=$surveyid)"; $resetlogicresult = $connect->Execute($resetlogicquery) or safe_die ("Couldn't delete conditions
    $resetlogicquery
    ".$connect->ErrorMsg()); $resetsurveylogicoutput .= "\t\n"; diff --git a/include/limesurvey/admin/results.php b/include/limesurvey/admin/results.php index 95d63ae1..017e5d03 100644 --- a/include/limesurvey/admin/results.php +++ b/include/limesurvey/admin/results.php @@ -1,539 +1,539 @@ -"FL", "1X2X35"=>"Cork") -* $responsestyle should be "full" - the alternative (which would just be the codes) is not yet coded -* -* This function will return a multi-level array. The first level is a numbered array with an -* entry for every individual response. Within that array will be a further array, with an entry -* for every possible answer to that question. Then, within each of those arrays will be -* the question title, and the answer to that question for that record. -* -* As an example, a single answer type question (like a List, or Yes/No) -* will look like this: -* Array -* ( -* [0]=> Array -* ( -* [4X6X22] => Array -* ( -* [0] => What is your Employment Type? -* [1] => Ongoing -* ) -* ) -* [1]=> Array -* ..... and so forth for each record in the responses table -* -* A multiple answer type question, such as "Multiple Choice" will look like this: -* Array -* ( -* [0]=> Array -* ( -* [2X2X7C] => Array -* ( -* [0] => Choose your favourite foods [Cheese] -* [1] => Yes -* ) -* [2X2X7I] => Array -* ( -* [0] => Choose your favourite foods [Ice Cream] -* [1] => -* ) -* ) -* -* - makeSummaryFromRawData($results) -* Feed this function the "raw results" string generated by the "giveMeRawDataFromFieldNames" -* function and you'll be returned an array containing a summary/count of results -* for every possible answer within that question. -* -* An example result for a single option question (ie: List or Yes/No) is: -* -* Array -* ( -* [4X6X22] => Array -* ( -* [question] => What is your Employment Type? -* [summary] => Array -* ( -* [Ongoing] => 429 -* [Fixed Term] => 61 -* [None] => 4 -* [Agency / Temp] => 4 -* [Casual] => 1 -* ) -* -* ) -* ) -* -* An example result for a multiple answer type question is: -* Array -* ( -* [2X2X7G] => Array -* ( -* [question] => Which of the following issues do you want addressed in negotiations for the next Enterprise Bargaining Agreement? [Accrual of Time In Lieu / Flex Time] -* [summary] => Array -* ( -* [Yes] => 10 -* [None] => 3 -* ) -* -* ) -* -* [2X2X7K] => Array -* ( -* [question] => Which of the following issues do you want addressed in negotiations for the next Enterprise Bargaining Agreement? [Allowances / Reimbursement of Expenses] -* [summary] => Array -* ( -* [Yes] => 5 -* [None] => 8 -* ) -* -* ) -* ) -* -*/ - -//THIS BIT IS JUST FOR DEBUGGING -if (!empty($_GET['debug'])) { - // $table = "survey_4"; - // //$questionfields[]="4X6X22"; - // //$questionfields[]="4X6X23"; - // $limitby=array("4X6X22"=>"A", - // "4X6X23"=>"B"); - // $sql = buildSqlFromFieldnamesArray($limitby); - // $questionfields=buildQuestionFields("4", "7", "29"); - // if (!empty($questionfields)) { - // $results = returnQuestionResults($table, $questionfields, $sql); - // echo "TOTAL RESULTS: ".count($results); - // echo "
    ";
    -	//		print_r($results);
    -	//		echo "
    "; - // } - $surveyid=$_GET['sid']; - $gid=$_GET['gid']; - $qid=$_GET['qid']; - //$results = giveMeRawDataFromFieldNames("4", "6", "22", array(), "full"); - //$results = giveMeRawDataFromFieldNames("2", "2", "7", array(), "full"); - //$results = giveMeRawDataFromFieldNames("8", "18", "66", array(), "full"); - //$results = giveMeRawDataFromFieldNames("29", "89", "559", array(), "full"); - $results = giveMeRawDataFromFieldNames($surveyid, $gid, $qid, array(), "full"); - - $summary = makeSummaryFromRawData($results); - foreach ($results as $result) { foreach ($result as $answer) {echo $answer[1];} } - echo "
    ";
    -	print_r($results);
    -	echo "
    "; - // - // foreach ($summary as $sum) { - // echo "
    \n"; - // echo "\n"; - // foreach ($sum['summary'] as $key=>$val) { - // echo "\n"; - // } - // echo "
    ".$sum['question']."
    $key$val

    "; - // } -} - -function makeSummaryFromRawData($results, $surveyid=null, $gid=null, $qid=null) { - - //echo "
    ";print_r($results);echo "
    "; - if (empty($results)) { - return array(); - } - if (!empty($qid)) { - $thisquestion=getQuestionInfo($qid); - } - $rowcodes=array_keys($results[0]); - // echo "
    ";print_r($rowcodes);echo "
    "; - - $summary = array(); - foreach ($results as $result) { - foreach($rowcodes as $row) { - //echo "
    ";print_r($result);echo "
    "; - - if (is_array($result[$row])) { - //echo "
    ";print_r($result);echo "
    "; - $summary[$row]['question']=$result[$row][0]; - switch($thisquestion['type']) { - case "T": - case "S": - case "H": - if ($result[$row][1] != "") { - if (!isset($summary[$row]['summary'][$clang->gT("Answered")])) { - $summary[$row]['summary'][$clang->gT("Answered")]=1; - } else { - $summary[$row]['summary'][$clang->gT("Answered")]++; - } - } - break; - default: - if (!isset($summary[$row]['summary'][$result[$row][1]])) { - $summary[$row]['summary'][$result[$row][1]]=1; - } else { - $summary[$row]['summary'][$result[$row][1]]++; - } - break; - } - } - if ($thisquestion['type'] == "N") { - ksort($summary[$row]['summary'], SORT_NUMERIC); - } - } - } - //echo "
    ";print_r($summary);echo "
    "; - //fill in the blanks from answer table and sort - if (isset($surveyid) && isset($qid) && $summary) { - //$thissurvey=getSurveyInfo($surveyid); - $rowcodes=array_keys($summary); - switch($thisquestion['type']){ - case "F": - case "H": - $answers=getLabelSet($thisquestion['lid']); - break; - case "!": - case "L": - case "O": - $answers=getAnswersSingle($surveyid, $gid, $qid); - $answers[]=array("code"=>"", "answer"=>$clang->gT("No answer")); - break; - case "W": - case "Z": - case "1": - $answers=getLabelSet($thisquestion['lid']); - $answers[]=array("code"=>"", "answer"=>$clang->gT("No answer")); - break; - case "C": - $answers[]=array("code"=>"Y", "answer"=>$clang->gT("Yes")); - $answers[]=array("code"=>"U", "answer"=>$clang->gT("Uncertain")); - $answers[]=array("code"=>"N", "answer"=>$clang->gT("No")); - break; - case "E": - $answers[]=array("code"=>"I", "answer"=>$clang->gT("Increase")); - $answers[]=array("code"=>"S", "answer"=>$clang->gT("Same")); - $answers[]=array("code"=>"D", "answer"=>$clang->gT("Decrease")); - $answers[]=array("code"=>"", "answer"=>$clang->gT("No answer")); - break; - case "M": - case "P": - $answers[]=array("code"=>"Y", "answer"=>$clang->gT("Yes")); - $answers[]=array("code"=>"", "answer"=>$clang->gT("No answer")); - break; - case "Y": - $answers[]=array("code"=>"Y", "answer"=>$clang->gT("Yes")); - $answers[]=array("code"=>"N", "answer"=>$clang->gT("No")); - $answers[]=array("code"=>"", "answer"=>$clang->gT("No answer")); - break; - case "G": - $answers[]=array("code"=>"M", "answer"=>$clang->gT("Male")); - $answers[]=array("code"=>"F", "answer"=>$clang->gT("Female")); - $answers[]=array("code"=>"", "answer"=>$clang->gT("No answer")); - break; - case "T": - case "S": - case "U": - $answers[]=array("code"=>$clang->gT("Answered"), "answer"=>$clang->gT("Answered")); - $answers[]=array("code"=>"", "answer"=>$clang->gT("No answer")); - break; - } // switch - - if (isset($answers)) { - foreach($rowcodes as $row) { - $newarray[$row]['question']=$summary[$row]['question']; - foreach($answers as $answer) { - //echo "
    ";print_r($answer);echo "
    "; - if (isset($summary[$row]['summary'][$answer['answer']])) { - $newarray[$row]['summary'][$answer['answer']]=$summary[$row]['summary'][$answer['answer']]; - } else { - $newarray[$row]['summary'][$answer['answer']]=0; - } - } - } - $summary=$newarray; - } - } - - //Fix the output for multiple - if ($thisquestion['type'] == "M" || $thisquestion['type'] == "P" || $thisquestion['type'] == "^" || $thisquestion['type'] == "1") { - if (isset($newarray)) {unset($newarray);} - $newarray[$thisquestion['sid']."X".$thisquestion['gid']."X".$thisquestion['qid']]['question']=$thisquestion['question']; - foreach ($summary as $sum) { - ereg("\[(.*)\]", $sum['question'], $regs); - $newarray[$thisquestion['sid']."X".$thisquestion['gid']."X".$thisquestion['qid']]['summary'][$regs[1]]=$sum['summary'][$clang->gT("Yes")]; - } - $summary=$newarray; - } - // echo "
    ";print_r($summary);echo "
    "; - return $summary; -} - -function giveMeRawDataFromFieldNames($surveyid, $gid, $qid, $fieldlimiters=array(), $output="full") { - //Builds output data for question $surveyid$gid$qid, limiting with $fieldlimiters array - $questionfields = buildQuestionFields($surveyid, $qid); - $sql = buildSqlFromFieldnamesArray($fieldlimiters); - $tablename = "survey_".$surveyid; - $fieldmap=createFieldMap($surveyid, "full"); - //echo "
    "; print_r($answers); echo "
    "; - list($questioninfo, $results) = returnQuestionResults($surveyid, $questionfields, $sql); - //echo "
    "; print_r($questioninfo); echo "
    "; - if (count($results) < 1) { - return array(); - } - foreach ($questioninfo as $qi) { - $questiontype=$qi['type']; - } - // echo "[$questiontype]
    "; - if ($output == "full") { - GetBaseLanguageFromSurveyID($surveyid); - //echo "
    "; print_r($answers); echo "
    "; - switch($questiontype) { - case "L": - case "!": - case "O": - case "D": - case "E": - case "M": - case "P": - case "C": - case "B": - case "A": - case "F": - case "H": - case "1": - $answers = getAnswersSingle($surveyid, $gid, $qid); - break; - case "W": - case "Z": - $thisquestion=getQuestionInfo($qid); - $answers=getLabelSet($thisquestion['lid']); - break; - case "Y": - $answers[]=array("code"=>"Y", "answer"=>$clang->gT("Yes")); - $answers[]=array("code"=>"N", "answer"=>$clang->gT("No")); - break; - case "G": - $answers[]=array("code"=>"M", "answer"=>$clang->gT("Male")); - $answers[]=array("code"=>"F", "answer"=>$clang->gT("Female")); - break; - } // switch - $answers[]=array("code"=>"", "answer"=>$clang->gT("No answer")); - $answers[]=array("code"=>"-oth-", "answer"=>$clang->gT("Other")); - - switch($questiontype) { - case "A": - for ($i=1; $i <= 5; $i++) { - $values[]=array("code"=>$i, "answer"=>$i); - } - break; - case "B": - for ($i=1; $i<=10; $i++) { - $values[]=array("code"=>$i, "answer"=>$i); - } - break; - case "E": - $values[]=array("code"=>"I", "answer"=>$clang->gT("Increase")); - $values[]=array("code"=>"S", "answer"=>$clang->gT("Same")); - $values[]=array("code"=>"D", "answer"=>$clang->gT("Decrease")); - break; - case "C": - case "M": - case "P": - $values[]=array("code"=>"Y", "answer"=>$clang->gT("Yes")); - $values[]=array("code"=>"U", "answer"=>$clang->gT("Uncertain")); - $values[]=array("code"=>"N", "answer"=>$clang->gT("No")); - break; - case "F": - case "H": - $thisquestion=getQuestionInfo($qid); - $values = getLabelSet($thisquestion['lid']); - break; - } - $values[]=array("code"=>"", "answer"=>$clang->gT("No answer")); - - switch($questiontype) { - case "L": - case "!": - case "O": - case "Y": - case "G": - case "S": - case "T": - case "H": - case "N": - case "5": - case "D": - case "W": - case "Z": - //The first key needs to be expanded - $firstkey=array_keys($results[0]); - $firstkey=$firstkey[0]; - $questions=arraySearchByKey($firstkey, $fieldmap, "fieldname", 1); - //echo $firstkey; - $i=0; - foreach($results as $result) { - $results[$i][$firstkey]=array($questions['question'], arraySubstitute($result[$firstkey], $answers)); - $i++; - } - break; - case "A": - case "B": - case "C": - case "E": - case "F": - case "H": - case "M": - case "P": - case "Q": - case "1": - $i=0; - foreach($results as $result) { - foreach($result as $key=>$val) { - $questions=arraySearchByKey($key, $fieldmap, "fieldname", 1); - if (substr($key, -7, 7) != "comment") { - $code=substr($key, strlen($surveyid."X".$gid."X".$qid), strlen($key)-strlen($surveyid."X".$gid."X".$qid)); - //echo $code; - $results[$i][$key]=array($questions['question'], arraySubstitute($val, $values)); - } - } - $i++; - } - break; - } // switch - } - return $results; -} - -function buildSqlFromFieldnamesArray($fieldnamesarray) { - //Expects an array like this: "1x2x3"=>"FL" - //and builds SQL "where" statement out of it (without the "WHERE" at the front) - if (count($fieldnamesarray)) { - foreach ($fieldnamesarray as $key=>$val) { - if ($val == "{NULL}") { - $sql[] = "$key IS NULL"; - } else { - $sql[] = "$key = '$val'"; - } - } - if (count($sql) > 1) { - return implode(" AND\n", $sql); - } else { - return $sql[0]; - } - } -} - -function buildQuestionFields($surveyid, $qid) { - //Takes a specific question, and returns an array containing - //all the possible fieldnames for responses to that question - $fieldmap=createFieldMap($surveyid); - foreach ($fieldmap as $fields) { - if ($fields['sid'] == $surveyid && $fields['qid'] == $qid && $fields['aid'] != "comment") { - $questionfields[]=$fields['fieldname']; - } - } - if (!empty($questionfields)) { - return $questionfields; - } else { - return array("id"); - } -} - -function returnQuestionResults($surveyid, $questionfields, $sql=null) { - global $connect; - //Returns uninterpreted raw results from survey table for question(s) - //$table = survcey table name (ie: "survey_1") - //$questionfields should contain an array of the question fields that are being returned - //$sql is any additional "filtering" sql code - $details=array(); - $output=array(); - foreach($questionfields as $questionfield) { - $detailsarray=arraySearchByKey($questionfield, createFieldMap($surveyid), "fieldname"); - foreach ($detailsarray as $dt) { - $details[]=$dt; - } - } - $table="survey_".$surveyid; - - if (count($questionfields) > 1) { - $selects = "`".implode("`, `", $questionfields)."`"; - } else { - $selects = "`".$questionfields[0]."`"; - } - $query = "SELECT $selects - FROM $table"; - if (!empty($sql)) { - $query .= "\nWHERE $sql"; - } - $result = db_execute_assoc($query) or safe_diee("error getting results in returnQuestionResults
    $query
    ".$connect->ErrorMsg()); - while($row=$result->FetchRow()) { - $output[]=$row; - } // while - return array($details, $output); -} - -function getAnswersSingle($surveyid, $gid, $qid) { - global $dbprefix, $connect; - $query = "SELECT * - FROM ".db_table_name("answers")." - WHERE qid=$qid - ORDER BY sortorder, answer"; - $result = db_execute_assoc($query); - while($row = $result->FetchRow()) { - $answer[]=array("code"=>$row['code'], - "answer"=>$row['answer']); - } // while - return $answer; -} - -function getLabelSet($lid) { - global $dbprefix, $connect; - $query = "SELECT * - FROM ".db_table_name("labels")." - WHERE lid=$lid - ORDER BY sortorder"; - $result = db_execute_assoc($query) or safe_die($connect->ErrorMsg()); - while($row = $result->FetchRow()) { - if ($row['title'] <> '') - { - $answer[]=array("code"=>$row['code'], - "answer"=>$row['title']); - } - } // while - return $answer; -} - -function arraySubstitute($value, $substitutes) { - foreach ($substitutes as $sub) { - if ($value == $sub['code']) { - return $sub['answer']; - } - } - return $value; -} -?> +"FL", "1X2X35"=>"Cork") +* $responsestyle should be "full" - the alternative (which would just be the codes) is not yet coded +* +* This function will return a multi-level array. The first level is a numbered array with an +* entry for every individual response. Within that array will be a further array, with an entry +* for every possible answer to that question. Then, within each of those arrays will be +* the question title, and the answer to that question for that record. +* +* As an example, a single answer type question (like a List, or Yes/No) +* will look like this: +* Array +* ( +* [0]=> Array +* ( +* [4X6X22] => Array +* ( +* [0] => What is your Employment Type? +* [1] => Ongoing +* ) +* ) +* [1]=> Array +* ..... and so forth for each record in the responses table +* +* A multiple answer type question, such as "Multiple Choice" will look like this: +* Array +* ( +* [0]=> Array +* ( +* [2X2X7C] => Array +* ( +* [0] => Choose your favourite foods [Cheese] +* [1] => Yes +* ) +* [2X2X7I] => Array +* ( +* [0] => Choose your favourite foods [Ice Cream] +* [1] => +* ) +* ) +* +* - makeSummaryFromRawData($results) +* Feed this function the "raw results" string generated by the "giveMeRawDataFromFieldNames" +* function and you'll be returned an array containing a summary/count of results +* for every possible answer within that question. +* +* An example result for a single option question (ie: List or Yes/No) is: +* +* Array +* ( +* [4X6X22] => Array +* ( +* [question] => What is your Employment Type? +* [summary] => Array +* ( +* [Ongoing] => 429 +* [Fixed Term] => 61 +* [None] => 4 +* [Agency / Temp] => 4 +* [Casual] => 1 +* ) +* +* ) +* ) +* +* An example result for a multiple answer type question is: +* Array +* ( +* [2X2X7G] => Array +* ( +* [question] => Which of the following issues do you want addressed in negotiations for the next Enterprise Bargaining Agreement? [Accrual of Time In Lieu / Flex Time] +* [summary] => Array +* ( +* [Yes] => 10 +* [None] => 3 +* ) +* +* ) +* +* [2X2X7K] => Array +* ( +* [question] => Which of the following issues do you want addressed in negotiations for the next Enterprise Bargaining Agreement? [Allowances / Reimbursement of Expenses] +* [summary] => Array +* ( +* [Yes] => 5 +* [None] => 8 +* ) +* +* ) +* ) +* +*/ + +//THIS BIT IS JUST FOR DEBUGGING +if (!empty($_GET['debug'])) { + // $table = "survey_4"; + // //$questionfields[]="4X6X22"; + // //$questionfields[]="4X6X23"; + // $limitby=array("4X6X22"=>"A", + // "4X6X23"=>"B"); + // $sql = buildSqlFromFieldnamesArray($limitby); + // $questionfields=buildQuestionFields("4", "7", "29"); + // if (!empty($questionfields)) { + // $results = returnQuestionResults($table, $questionfields, $sql); + // echo "TOTAL RESULTS: ".count($results); + // echo "
    ";
    +	//		print_r($results);
    +	//		echo "
    "; + // } + $surveyid=$_GET['sid']; + $gid=$_GET['gid']; + $qid=$_GET['qid']; + //$results = giveMeRawDataFromFieldNames("4", "6", "22", array(), "full"); + //$results = giveMeRawDataFromFieldNames("2", "2", "7", array(), "full"); + //$results = giveMeRawDataFromFieldNames("8", "18", "66", array(), "full"); + //$results = giveMeRawDataFromFieldNames("29", "89", "559", array(), "full"); + $results = giveMeRawDataFromFieldNames($surveyid, $gid, $qid, array(), "full"); + + $summary = makeSummaryFromRawData($results); + foreach ($results as $result) { foreach ($result as $answer) {echo $answer[1];} } + echo "
    ";
    +	print_r($results);
    +	echo "
    "; + // + // foreach ($summary as $sum) { + // echo "\n"; + // echo "\n"; + // foreach ($sum['summary'] as $key=>$val) { + // echo "\n"; + // } + // echo "
    ".$sum['question']."
    $key$val

    "; + // } +} + +function makeSummaryFromRawData($results, $surveyid=null, $gid=null, $qid=null) { + + //echo "
    ";print_r($results);echo "
    "; + if (empty($results)) { + return array(); + } + if (!empty($qid)) { + $thisquestion=getQuestionInfo($qid); + } + $rowcodes=array_keys($results[0]); + // echo "
    ";print_r($rowcodes);echo "
    "; + + $summary = array(); + foreach ($results as $result) { + foreach($rowcodes as $row) { + //echo "
    ";print_r($result);echo "
    "; + + if (is_array($result[$row])) { + //echo "
    ";print_r($result);echo "
    "; + $summary[$row]['question']=$result[$row][0]; + switch($thisquestion['type']) { + case "T": + case "S": + case "H": + if ($result[$row][1] != "") { + if (!isset($summary[$row]['summary'][$clang->gT("Answered")])) { + $summary[$row]['summary'][$clang->gT("Answered")]=1; + } else { + $summary[$row]['summary'][$clang->gT("Answered")]++; + } + } + break; + default: + if (!isset($summary[$row]['summary'][$result[$row][1]])) { + $summary[$row]['summary'][$result[$row][1]]=1; + } else { + $summary[$row]['summary'][$result[$row][1]]++; + } + break; + } + } + if ($thisquestion['type'] == "N") { + ksort($summary[$row]['summary'], SORT_NUMERIC); + } + } + } + //echo "
    ";print_r($summary);echo "
    "; + //fill in the blanks from answer table and sort + if (isset($surveyid) && isset($qid) && $summary) { + //$thissurvey=getSurveyInfo($surveyid); + $rowcodes=array_keys($summary); + switch($thisquestion['type']){ + case "F": + case "H": + $answers=getLabelSet($thisquestion['lid']); + break; + case "!": + case "L": + case "O": + $answers=getAnswersSingle($surveyid, $gid, $qid); + $answers[]=array("code"=>"", "answer"=>$clang->gT("No answer")); + break; + case "W": + case "Z": + case "1": + $answers=getLabelSet($thisquestion['lid']); + $answers[]=array("code"=>"", "answer"=>$clang->gT("No answer")); + break; + case "C": + $answers[]=array("code"=>"Y", "answer"=>$clang->gT("Yes")); + $answers[]=array("code"=>"U", "answer"=>$clang->gT("Uncertain")); + $answers[]=array("code"=>"N", "answer"=>$clang->gT("No")); + break; + case "E": + $answers[]=array("code"=>"I", "answer"=>$clang->gT("Increase")); + $answers[]=array("code"=>"S", "answer"=>$clang->gT("Same")); + $answers[]=array("code"=>"D", "answer"=>$clang->gT("Decrease")); + $answers[]=array("code"=>"", "answer"=>$clang->gT("No answer")); + break; + case "M": + case "P": + $answers[]=array("code"=>"Y", "answer"=>$clang->gT("Yes")); + $answers[]=array("code"=>"", "answer"=>$clang->gT("No answer")); + break; + case "Y": + $answers[]=array("code"=>"Y", "answer"=>$clang->gT("Yes")); + $answers[]=array("code"=>"N", "answer"=>$clang->gT("No")); + $answers[]=array("code"=>"", "answer"=>$clang->gT("No answer")); + break; + case "G": + $answers[]=array("code"=>"M", "answer"=>$clang->gT("Male")); + $answers[]=array("code"=>"F", "answer"=>$clang->gT("Female")); + $answers[]=array("code"=>"", "answer"=>$clang->gT("No answer")); + break; + case "T": + case "S": + case "U": + $answers[]=array("code"=>$clang->gT("Answered"), "answer"=>$clang->gT("Answered")); + $answers[]=array("code"=>"", "answer"=>$clang->gT("No answer")); + break; + } // switch + + if (isset($answers)) { + foreach($rowcodes as $row) { + $newarray[$row]['question']=$summary[$row]['question']; + foreach($answers as $answer) { + //echo "
    ";print_r($answer);echo "
    "; + if (isset($summary[$row]['summary'][$answer['answer']])) { + $newarray[$row]['summary'][$answer['answer']]=$summary[$row]['summary'][$answer['answer']]; + } else { + $newarray[$row]['summary'][$answer['answer']]=0; + } + } + } + $summary=$newarray; + } + } + + //Fix the output for multiple + if ($thisquestion['type'] == "M" || $thisquestion['type'] == "P" || $thisquestion['type'] == "^" || $thisquestion['type'] == "1") { + if (isset($newarray)) {unset($newarray);} + $newarray[$thisquestion['sid']."X".$thisquestion['gid']."X".$thisquestion['qid']]['question']=$thisquestion['question']; + foreach ($summary as $sum) { + preg_match("/\[(.*)\]/", $sum['question'], $regs); + $newarray[$thisquestion['sid']."X".$thisquestion['gid']."X".$thisquestion['qid']]['summary'][$regs[1]]=$sum['summary'][$clang->gT("Yes")]; + } + $summary=$newarray; + } + // echo "
    ";print_r($summary);echo "
    "; + return $summary; +} + +function giveMeRawDataFromFieldNames($surveyid, $gid, $qid, $fieldlimiters=array(), $output="full") { + //Builds output data for question $surveyid$gid$qid, limiting with $fieldlimiters array + $questionfields = buildQuestionFields($surveyid, $qid); + $sql = buildSqlFromFieldnamesArray($fieldlimiters); + $tablename = "survey_".$surveyid; + $fieldmap=createFieldMap($surveyid, "full"); + //echo "
    "; print_r($answers); echo "
    "; + list($questioninfo, $results) = returnQuestionResults($surveyid, $questionfields, $sql); + //echo "
    "; print_r($questioninfo); echo "
    "; + if (count($results) < 1) { + return array(); + } + foreach ($questioninfo as $qi) { + $questiontype=$qi['type']; + } + // echo "[$questiontype]
    "; + if ($output == "full") { + GetBaseLanguageFromSurveyID($surveyid); + //echo "
    "; print_r($answers); echo "
    "; + switch($questiontype) { + case "L": + case "!": + case "O": + case "D": + case "E": + case "M": + case "P": + case "C": + case "B": + case "A": + case "F": + case "H": + case "1": + $answers = getAnswersSingle($surveyid, $gid, $qid); + break; + case "W": + case "Z": + $thisquestion=getQuestionInfo($qid); + $answers=getLabelSet($thisquestion['lid']); + break; + case "Y": + $answers[]=array("code"=>"Y", "answer"=>$clang->gT("Yes")); + $answers[]=array("code"=>"N", "answer"=>$clang->gT("No")); + break; + case "G": + $answers[]=array("code"=>"M", "answer"=>$clang->gT("Male")); + $answers[]=array("code"=>"F", "answer"=>$clang->gT("Female")); + break; + } // switch + $answers[]=array("code"=>"", "answer"=>$clang->gT("No answer")); + $answers[]=array("code"=>"-oth-", "answer"=>$clang->gT("Other")); + + switch($questiontype) { + case "A": + for ($i=1; $i <= 5; $i++) { + $values[]=array("code"=>$i, "answer"=>$i); + } + break; + case "B": + for ($i=1; $i<=10; $i++) { + $values[]=array("code"=>$i, "answer"=>$i); + } + break; + case "E": + $values[]=array("code"=>"I", "answer"=>$clang->gT("Increase")); + $values[]=array("code"=>"S", "answer"=>$clang->gT("Same")); + $values[]=array("code"=>"D", "answer"=>$clang->gT("Decrease")); + break; + case "C": + case "M": + case "P": + $values[]=array("code"=>"Y", "answer"=>$clang->gT("Yes")); + $values[]=array("code"=>"U", "answer"=>$clang->gT("Uncertain")); + $values[]=array("code"=>"N", "answer"=>$clang->gT("No")); + break; + case "F": + case "H": + $thisquestion=getQuestionInfo($qid); + $values = getLabelSet($thisquestion['lid']); + break; + } + $values[]=array("code"=>"", "answer"=>$clang->gT("No answer")); + + switch($questiontype) { + case "L": + case "!": + case "O": + case "Y": + case "G": + case "S": + case "T": + case "H": + case "N": + case "5": + case "D": + case "W": + case "Z": + //The first key needs to be expanded + $firstkey=array_keys($results[0]); + $firstkey=$firstkey[0]; + $questions=arraySearchByKey($firstkey, $fieldmap, "fieldname", 1); + //echo $firstkey; + $i=0; + foreach($results as $result) { + $results[$i][$firstkey]=array($questions['question'], arraySubstitute($result[$firstkey], $answers)); + $i++; + } + break; + case "A": + case "B": + case "C": + case "E": + case "F": + case "H": + case "M": + case "P": + case "Q": + case "1": + $i=0; + foreach($results as $result) { + foreach($result as $key=>$val) { + $questions=arraySearchByKey($key, $fieldmap, "fieldname", 1); + if (substr($key, -7, 7) != "comment") { + $code=substr($key, strlen($surveyid."X".$gid."X".$qid), strlen($key)-strlen($surveyid."X".$gid."X".$qid)); + //echo $code; + $results[$i][$key]=array($questions['question'], arraySubstitute($val, $values)); + } + } + $i++; + } + break; + } // switch + } + return $results; +} + +function buildSqlFromFieldnamesArray($fieldnamesarray) { + //Expects an array like this: "1x2x3"=>"FL" + //and builds SQL "where" statement out of it (without the "WHERE" at the front) + if (count($fieldnamesarray)) { + foreach ($fieldnamesarray as $key=>$val) { + if ($val == "{NULL}") { + $sql[] = "$key IS NULL"; + } else { + $sql[] = "$key = '$val'"; + } + } + if (count($sql) > 1) { + return implode(" AND\n", $sql); + } else { + return $sql[0]; + } + } +} + +function buildQuestionFields($surveyid, $qid) { + //Takes a specific question, and returns an array containing + //all the possible fieldnames for responses to that question + $fieldmap=createFieldMap($surveyid); + foreach ($fieldmap as $fields) { + if ($fields['sid'] == $surveyid && $fields['qid'] == $qid && $fields['aid'] != "comment") { + $questionfields[]=$fields['fieldname']; + } + } + if (!empty($questionfields)) { + return $questionfields; + } else { + return array("id"); + } +} + +function returnQuestionResults($surveyid, $questionfields, $sql=null) { + global $connect; + //Returns uninterpreted raw results from survey table for question(s) + //$table = survcey table name (ie: "survey_1") + //$questionfields should contain an array of the question fields that are being returned + //$sql is any additional "filtering" sql code + $details=array(); + $output=array(); + foreach($questionfields as $questionfield) { + $detailsarray=arraySearchByKey($questionfield, createFieldMap($surveyid), "fieldname"); + foreach ($detailsarray as $dt) { + $details[]=$dt; + } + } + $table="survey_".$surveyid; + + if (count($questionfields) > 1) { + $selects = "`".implode("`, `", $questionfields)."`"; + } else { + $selects = "`".$questionfields[0]."`"; + } + $query = "SELECT $selects + FROM $table"; + if (!empty($sql)) { + $query .= "\nWHERE $sql"; + } + $result = db_execute_assoc($query) or safe_diee("error getting results in returnQuestionResults
    $query
    ".$connect->ErrorMsg()); + while($row=$result->FetchRow()) { + $output[]=$row; + } // while + return array($details, $output); +} + +function getAnswersSingle($surveyid, $gid, $qid) { + global $dbprefix, $connect; + $query = "SELECT * + FROM ".db_table_name("answers")." + WHERE qid=$qid + ORDER BY sortorder, answer"; + $result = db_execute_assoc($query); + while($row = $result->FetchRow()) { + $answer[]=array("code"=>$row['code'], + "answer"=>$row['answer']); + } // while + return $answer; +} + +function getLabelSet($lid) { + global $dbprefix, $connect; + $query = "SELECT * + FROM ".db_table_name("labels")." + WHERE lid=$lid + ORDER BY sortorder"; + $result = db_execute_assoc($query) or safe_die($connect->ErrorMsg()); + while($row = $result->FetchRow()) { + if ($row['title'] <> '') + { + $answer[]=array("code"=>$row['code'], + "answer"=>$row['title']); + } + } // while + return $answer; +} + +function arraySubstitute($value, $substitutes) { + foreach ($substitutes as $sub) { + if ($value == $sub['code']) { + return $sub['answer']; + } + } + return $value; +} +?> diff --git a/include/limesurvey/admin/saved.php b/include/limesurvey/admin/saved.php index f5815a90..9d9d2ca8 100644 --- a/include/limesurvey/admin/saved.php +++ b/include/limesurvey/admin/saved.php @@ -1,137 +1,137 @@ -Execute($query)) - { - //If we were succesful deleting the saved_control entry, - //then delete the rest - $query = "DELETE FROM {$surveytable} WHERE id={$srid}"; - $result = $connect->Execute($query) or die("Couldn't delete"); - - } - else - { - $savedsurveyoutput .= "Couldn't delete
    $query
    ".$connect->ErrorMsg(); - } -} - -$savedsurveyoutput .= "
    \n" -."\n"; -$savedsurveyoutput .= "\t\n"; -$savedsurveyoutput .= savedmenubar(); -$savedsurveyoutput .= "\n"; -$savedsurveyoutput .= "
    \n" -."\n"; -$savedsurveyoutput .= "
    "; - -switch ($subaction) -{ - case "all": - case "delete": - $savedsurveyoutput .= "
    ".$setfont.$clang->gT("Saved Responses:") . " ". getSavedCount($surveyid)."
    "; - showSavedList($surveyid); - break; - default: - $savedsurveyoutput .= "
    ".$setfont.$clang->gT("Saved Responses:") . " ". getSavedCount($surveyid)."
    "; -} -$savedsurveyoutput .= "

     \n"; - -function showSavedList($surveyid) -{ - global $dbprefix, $connect, $clang, $savedsurveyoutput, $scriptname, $surveytable; - $query = "SELECT scid, srid, identifier, ip, saved_date, email, access_code\n" - ."FROM {$dbprefix}saved_control\n" - ."WHERE sid=$surveyid\n" - ."ORDER BY saved_date desc"; - $result = db_execute_assoc($query) or safe_die ("Couldn't summarise saved entries
    $query
    ".$connect->ErrorMsg()); - if ($result->RecordCount() > 0) - { - $savedsurveyoutput .= "\n"; - $savedsurveyoutput .= "" - ."\n"; - while($row=$result->FetchRow()) - { - $savedsurveyoutput .= " - - - - - - - \n"; - } // while - $savedsurveyoutput .= "
    SCID" - .$clang->gT("Identifier")."" - .$clang->gT("IP Address")."" - .$clang->gT("Date Saved")."" - .$clang->gT("Email Address")."" - .$clang->gT("Action")."
    ".$row['scid']."".$row['identifier']."".$row['ip']."".$row['saved_date']."".$row['email']." - [".$clang->gT("Delete")."] - [".$clang->gT("Edit")."] -

     \n"; - } -} - -// [".$clang->gT("Remind")."] -// c_schmitz: Since its without function at the moment i removed it from the above lines - -function savedmenubar() -{ - global $surveyid, $scriptname, $imagefiles, $clang; - //BROWSE MENU BAR - if (!isset($surveyoptions)) {$surveyoptions="";} - $surveyoptions .= "\t\n" - . "\t\t\n" - . "\t\t\tgT("Return to Survey Administration", "js")."')\" >" . - "\n" - . "\t\t\t\n" - . "\t\t\t\n" - . "\t\t\tgT("Show summary information", "js")."')\">" . - "\n" - . "\t\t\tgT("Display Responses", "js")."')\">" . - "\n" - //. "\t\t\t\n" - . "\t\t\t\n" - . "\t\t\n" - . "\t\n"; - return $surveyoptions; -} -?> +Execute($query)) + { + //If we were succesful deleting the saved_control entry, + //then delete the rest + $query = "DELETE FROM {$surveytable} WHERE id={$srid}"; + $result = $connect->Execute($query) or die("Couldn't delete"); + + } + else + { + $savedsurveyoutput .= "Couldn't delete
    $query
    ".$connect->ErrorMsg(); + } +} + +$savedsurveyoutput .= "
    \n" +."\n"; +$savedsurveyoutput .= "\t\n"; +$savedsurveyoutput .= savedmenubar(); +$savedsurveyoutput .= "\n"; +$savedsurveyoutput .= "
    \n" +."\n"; +$savedsurveyoutput .= "
    "; + +switch ($subaction) +{ + case "all": + case "delete": + $savedsurveyoutput .= "
    ".$setfont.$clang->gT("Saved Responses:") . " ". getSavedCount($surveyid)."
    "; + showSavedList($surveyid); + break; + default: + $savedsurveyoutput .= "
    ".$setfont.$clang->gT("Saved Responses:") . " ". getSavedCount($surveyid)."
    "; +} +$savedsurveyoutput .= "

     \n"; + +function showSavedList($surveyid) +{ + global $dbprefix, $connect, $clang, $savedsurveyoutput, $scriptname, $surveytable; + $query = "SELECT scid, srid, identifier, ip, saved_date, email, access_code\n" + ."FROM {$dbprefix}saved_control\n" + ."WHERE sid=$surveyid\n" + ."ORDER BY saved_date desc"; + $result = db_execute_assoc($query) or safe_die ("Couldn't summarise saved entries
    $query
    ".$connect->ErrorMsg()); + if ($result->RecordCount() > 0) + { + $savedsurveyoutput .= "\n"; + $savedsurveyoutput .= "" + ."\n"; + while($row=$result->FetchRow()) + { + $savedsurveyoutput .= " + + + + + + + \n"; + } // while + $savedsurveyoutput .= "
    SCID" + .$clang->gT("Identifier")."" + .$clang->gT("IP Address")."" + .$clang->gT("Date Saved")."" + .$clang->gT("Email Address")."" + .$clang->gT("Action")."
    ".$row['scid']."".$row['identifier']."".$row['ip']."".$row['saved_date']."".$row['email']." + [".$clang->gT("Delete")."] + [".$clang->gT("Edit")."] +

     \n"; + } +} + +// [".$clang->gT("Remind")."] +// c_schmitz: Since its without function at the moment i removed it from the above lines + +function savedmenubar() +{ + global $surveyid, $scriptname, $imagefiles, $clang; + //BROWSE MENU BAR + if (!isset($surveyoptions)) {$surveyoptions="";} + $surveyoptions .= "\t\n" + . "\t\t\n" + . "\t\t\tgT("Return to Survey Administration", "js")."')\" >" . + "\n" + . "\t\t\t\n" + . "\t\t\t\n" + . "\t\t\tgT("Show summary information", "js")."')\">" . + "\n" + . "\t\t\tgT("Display Responses", "js")."')\">" . + "\n" + //. "\t\t\t\n" + . "\t\t\t\n" + . "\t\t\n" + . "\t\n"; + return $surveyoptions; +} +?> diff --git a/include/limesurvey/admin/scripts/addremove.js b/include/limesurvey/admin/scripts/admin_core.js similarity index 50% rename from include/limesurvey/admin/scripts/addremove.js rename to include/limesurvey/admin/scripts/admin_core.js index 051b67c3..4331d6a2 100644 --- a/include/limesurvey/admin/scripts/addremove.js +++ b/include/limesurvey/admin/scripts/admin_core.js @@ -1,5 +1,136 @@ - diff --git a/include/limesurvey/admin/scripts/assessments.js b/include/limesurvey/admin/scripts/assessments.js new file mode 100644 index 00000000..1129f135 --- /dev/null +++ b/include/limesurvey/admin/scripts/assessments.js @@ -0,0 +1,56 @@ +function jquery_goodchars(e, goods) +{ + var key, keychar; + key = e.which; + if (key == null) return true; + + // get character + keychar = String.fromCharCode(key); + keychar = keychar.toLowerCase(); + goods = goods.toLowerCase(); + + // check goodkeys + if (goods.indexOf(keychar) != -1) + return true; + + // control keys + if ( key==null || key==0 || key==8 || key==9 || key==27 ) + return true; + + // else return false + return false; +} + + +$(document).ready(function(){ + $('#languagetabs').tabs(); + $('#radiototal,#radiogroup').change( + function() + { + if ($('#radiototal').attr('checked')==true) + { + $('#newgroupselect').attr('disabled','disabled'); + } + else + { + if ($('#newgroupselect>option').length==0){ + $('#radiototal').attr('checked',true); + alert (strnogroup); + } + else + { + $('#newgroupselect').attr('disabled',false); + } + } + } + ) + $('#radiototal,#radiogroup').change(); + $('.numbersonly').keypress( + function(e){ + return jquery_goodchars(e,'1234567890-'); + } + ) + } +); + + diff --git a/include/limesurvey/admin/scripts/draganddrop.js b/include/limesurvey/admin/scripts/draganddrop.js deleted file mode 100644 index a217e783..00000000 --- a/include/limesurvey/admin/scripts/draganddrop.js +++ /dev/null @@ -1,194 +0,0 @@ - /************************************************************************************************************ - (C) www.dhtmlgoodies.com, October 2005 - - This is a script from www.dhtmlgoodies.com. You will find this and a lot of other scripts at our website. - - Terms of use: - You are free to use this script as long as the copyright message is kept intact. However, you may not - redistribute, sell or repost it without our permission. - - Thank you! - - www.dhtmlgoodies.com - Alf Magne Kalleland - - ************************************************************************************************************/ - - var offsetYInsertDiv = -3; // Y offset for the little arrow indicating where the node should be inserted. - if(!document.all)offsetYInsertDiv = offsetYInsertDiv - 7; // No IE - - - var arrParent = false; - var arrMoveCont = false; - var arrMoveCounter = -1; - var arrTarget = false; - var arrNextSibling = false; - var leftPosArrangableNodes = false; - var widthArrangableNodes = false; - var nodePositionsY = new Array(); - var nodeHeights = new Array(); - var arrInsertDiv = false; - var insertAsFirstNode = false; - var arrNodesDestination = false; - function cancelEvent() - { - return false; - } - function getTopPos(inputObj) - { - - var returnValue = inputObj.offsetTop; - while((inputObj = inputObj.offsetParent) != null){ - returnValue += inputObj.offsetTop; - } - return returnValue; - } - - function getLeftPos(inputObj) - { - var returnValue = inputObj.offsetLeft; - while((inputObj = inputObj.offsetParent) != null)returnValue += inputObj.offsetLeft; - return returnValue; - } - - function clearMovableDiv() - { - if(arrMoveCont.getElementsByTagName('LI').length>0){ - if(arrNextSibling)arrParent.insertBefore(arrTarget,arrNextSibling); else arrParent.appendChild(arrTarget); - } - - } - function testjs() - { - alert('JavaScript includes supported!'); - } - - function initMoveNode(e) - { - clearMovableDiv(); - if(document.all)e = event; - arrMoveCounter = 0; - arrTarget = this; - if(this.nextSibling)arrNextSibling = this.nextSibling; else arrNextSibling = false; - timerMoveNode(); - arrMoveCont.parentNode.style.left = e.clientX + 'px'; - arrMoveCont.parentNode.style.top = e.clientY + 'px'; - return false; - - } - function timerMoveNode() - { - if(arrMoveCounter>=0 && arrMoveCounter<10){ - arrMoveCounter = arrMoveCounter +1; - setTimeout('timerMoveNode()',20); - } - if(arrMoveCounter>=10){ - arrMoveCont.appendChild(arrTarget); - } - } - - function arrangeNodeMove(e) - { - if(document.all)e = event; - if(arrMoveCounter<10)return; - if(document.all && arrMoveCounter>=10 && e.button!=1){ - arrangeNodeStopMove(); - } - - arrMoveCont.parentNode.style.left = e.clientX + 'px'; - arrMoveCont.parentNode.style.top = e.clientY + 'px'; - - var tmpY = e.clientY; - arrInsertDiv.style.display='none'; - arrNodesDestination = false; - - - if(e.clientXleftPosArrangableNodes + widthArrangableNodes)return; - - var subs = arrParent.getElementsByTagName('LI'); - for(var no=0;no=topPos-5){ - arrInsertDiv.style.top = (topPos + offsetYInsertDiv) + 'px'; - arrInsertDiv.style.display = 'block'; - arrNodesDestination = subs[no]; - insertAsFirstNode = true; - return; - } - } - - if(tmpY>=topPos && tmpY<=(topPos+tmpHeight)){ - arrInsertDiv.style.top = (topPos+tmpHeight + offsetYInsertDiv) + 'px'; - arrInsertDiv.style.display = 'block'; - arrNodesDestination = subs[no]; - insertAsFirstNode = false; - return; - } - } - } - - function arrangeNodeStopMove() - { - arrMoveCounter = -1; - arrInsertDiv.style.display='none'; - - if(arrNodesDestination){ - var subs = arrParent.getElementsByTagName('LI'); - if(arrNodesDestination==subs[0] && insertAsFirstNode){ - arrParent.insertBefore(arrTarget,arrNodesDestination); - }else{ - if(arrNodesDestination.nextSibling){ - arrParent.insertBefore(arrTarget,arrNodesDestination.nextSibling); - }else{ - arrParent.appendChild(arrTarget); - } - } - } - arrNodesDestination = false; - clearMovableDiv(); - } - - function saveArrangableNodes() - { - var nodes = arrParent.getElementsByTagName('LI'); - var string = ""; - for(var no=0;no0)string = string + ','; - string = string + nodes[no].id; - } - - document.forms[0].hiddenNodeIds.value = string; - - // Just for testing - //document.getElementById('arrDebug').innerHTML = 'Ready to save these nodes:
    ' + string.replace(/,/g,',
    '); - - document.forms[0].submit(); // Remove the comment in front of this line when you have set an action to the form. - //return string ; - } - - function initArrangableNodes() - { - arrParent = document.getElementById('arrangableNodes'); - arrMoveCont = document.getElementById('movableNode').getElementsByTagName('UL')[0]; - arrInsertDiv = document.getElementById('arrDestInditcator'); - - leftPosArrangableNodes = getLeftPos(arrParent); - arrInsertDiv.style.left = leftPosArrangableNodes - 5 + 'px'; - widthArrangableNodes = arrParent.offsetWidth; - - var subs = arrParent.getElementsByTagName('LI'); - for(var no=0;no= 0 && this.selectIndex < as.length ) + { + as[ this.selectIndex ].onmousedown(); + return false + } + // simply add an enter in the code + else + { + this._hide(); + return true; + } + } + else if( letter=="Tab" || letter=="Down") + { + this._selectNext(); + return false; + } + else if( letter=="Up") + { + this._selectBefore(); + return false; + } + } + // hidden + else + { + + } + + // show current suggestion list and do autoSelect if possible (no matter it's shown or hidden) + if( letter=="Space" && CtrlPressed(e) ) + { + //parent.console.log('SHOW SUGGEST'); + this.forceDisplay = true; + this.autoSelectIfOneResult = true; + this._checkLetter(); + return false; + } + + // wait a short period for check that the cursor isn't moving + setTimeout("editArea.plugins['autocompletion']._checkDelayAndCursorBeforeDisplay();", editArea.check_line_selection_timer +5 ); + this.checkDelayTimer = false; + return true; + } + /** + * Executes a specific command, this function handles plugin commands. + * + * @param {string} cmd: the name of the command being executed + * @param {unknown} param: the parameter of the command + * @return true - pass to next handler in chain, false - stop chain execution + * @type boolean + */ + ,execCommand: function(cmd, param){ + switch( cmd ){ + case 'toggle_autocompletion': + var icon= document.getElementById("autocompletion"); + if(!this.enabled) + { + if(icon != null){ + editArea.restoreClass(icon); + editArea.switchClassSticky(icon, 'editAreaButtonSelected', true); + } + this.enabled= true; + } + else + { + this.enabled= false; + if(icon != null) + editArea.switchClassSticky(icon, 'editAreaButtonNormal', false); + } + return true; + } + return true; + } + ,_checkDelayAndCursorBeforeDisplay: function() + { + this.checkDelayTimer = setTimeout("if(editArea.textarea.selectionStart == "+ editArea.textarea.selectionStart +") EditArea_autocompletion._checkLetter();", this.delayBeforeDisplay - editArea.check_line_selection_timer - 5 ); + } + // hide the suggested box + ,_hide: function(){ + this.container.style.display="none"; + this.selectIndex = -1; + this.shown = false; + this.forceDisplay = false; + this.autoSelectIfOneResult = false; + } + // display the suggested box + ,_show: function(){ + if( !this._isShown() ) + { + this.container.style.display="block"; + this.selectIndex = -1; + this.shown = true; + } + } + // is the suggested box displayed? + ,_isShown: function(){ + return this.shown; + } + // setter and getter + ,_isInMiddleWord: function( new_value ){ + if( typeof( new_value ) == "undefined" ) + return this.isInMiddleWord; + else + this.isInMiddleWord = new_value; + } + // select the next element in the suggested box + ,_selectNext: function() + { + var as = this.container.getElementsByTagName('A'); + + // clean existing elements + for( var i=0; i= as.length || this.selectIndex < 0 ) ? 0 : this.selectIndex; + as[ this.selectIndex ].className += " focus"; + } + // select the previous element in the suggested box + ,_selectBefore: function() + { + var as = this.container.getElementsByTagName('A'); + + // clean existing elements + for( var i=0; i= as.length || this.selectIndex < 0 ) ? as.length-1 : this.selectIndex; + as[ this.selectIndex ].className += " focus"; + } + ,_select: function( content ) + { + cursor_forced_position = content.indexOf( '{@}' ); + content = content.replace(/{@}/g, '' ); + editArea.getIESelection(); + + // retrive the number of matching characters + var start_index = Math.max( 0, editArea.textarea.selectionEnd - content.length ); + + line_string = editArea.textarea.value.substring( start_index, editArea.textarea.selectionEnd + 1); + limit = line_string.length -1; + nbMatch = 0; + for( i =0; i 0 ) + parent.editAreaLoader.setSelectionRange(editArea.id, editArea.textarea.selectionStart - nbMatch , editArea.textarea.selectionEnd); + + parent.editAreaLoader.setSelectedText(editArea.id, content ); + range= parent.editAreaLoader.getSelectionRange(editArea.id); + + if( cursor_forced_position != -1 ) + new_pos = range["end"] - ( content.length-cursor_forced_position ); + else + new_pos = range["end"]; + parent.editAreaLoader.setSelectionRange(editArea.id, new_pos, new_pos); + this._hide(); + } + + + /** + * Parse the AUTO_COMPLETION part of syntax definition files + */ + ,_parseSyntaxAutoCompletionDatas: function(){ + //foreach syntax loaded + for(var lang in parent.editAreaLoader.load_syntax) + { + if(!parent.editAreaLoader.syntax[lang]['autocompletion']) // init the regexp if not already initialized + { + parent.editAreaLoader.syntax[lang]['autocompletion']= {}; + // the file has auto completion datas + if(parent.editAreaLoader.load_syntax[lang]['AUTO_COMPLETION']) + { + // parse them + for(var i in parent.editAreaLoader.load_syntax[lang]['AUTO_COMPLETION']) + { + datas = parent.editAreaLoader.load_syntax[lang]['AUTO_COMPLETION'][i]; + tmp = {}; + if(datas["CASE_SENSITIVE"]!="undefined" && datas["CASE_SENSITIVE"]==false) + tmp["modifiers"]="i"; + else + tmp["modifiers"]=""; + tmp["prefix_separator"]= datas["REGEXP"]["prefix_separator"]; + tmp["match_prefix_separator"]= new RegExp( datas["REGEXP"]["prefix_separator"] +"$", tmp["modifiers"]); + tmp["match_word"]= new RegExp("(?:"+ datas["REGEXP"]["before_word"] +")("+ datas["REGEXP"]["possible_words_letters"] +")$", tmp["modifiers"]); + tmp["match_next_letter"]= new RegExp("^("+ datas["REGEXP"]["letter_after_word_must_match"] +")$", tmp["modifiers"]); + tmp["keywords"]= {}; + //console.log( datas["KEYWORDS"] ); + for( var prefix in datas["KEYWORDS"] ) + { + tmp["keywords"][prefix]= { + prefix: prefix, + prefix_name: prefix, + prefix_reg: new RegExp("(?:"+ parent.editAreaLoader.get_escaped_regexp( prefix ) +")(?:"+ tmp["prefix_separator"] +")$", tmp["modifiers"] ), + datas: [] + }; + for( var j=0; j it's valid + if( !match_prefix_separator && this.curr_syntax[i]["keywords"][prefix]['prefix'].length == 0 ) + { + if( ! before.match( this.curr_syntax[i]["keywords"][prefix]['prefix_reg'] ) ) + hasMatch = true; + } + // we still need to check the prefix if there is one + else if( this.curr_syntax[i]["keywords"][prefix]['prefix'].length > 0 ) + { + if( before.match( this.curr_syntax[i]["keywords"][prefix]['prefix_reg'] ) ) + hasMatch = true; + } + + if( hasMatch ) + results[results.length]= [ this.curr_syntax[i]["keywords"][prefix], this.curr_syntax[i]["keywords"][prefix]['datas'][j] ]; + } + } + } + } + // it doesn't match any possible word but we want to display something + // we'll display to list of all available words + else if( this.forceDisplay || match_prefix_separator ) + { + for(var prefix in this.curr_syntax[i]["keywords"]) + { + for(var j=0; j it's valid + if( !match_prefix_separator && this.curr_syntax[i]["keywords"][prefix]['prefix'].length == 0 ) + { + hasMatch = true; + } + // we still need to check the prefix if there is one + else if( match_prefix_separator && this.curr_syntax[i]["keywords"][prefix]['prefix'].length > 0 ) + { + var before = last_chars; //.substr( 0, last_chars.length ); + if( before.match( this.curr_syntax[i]["keywords"][prefix]['prefix_reg'] ) ) + hasMatch = true; + } + + if( hasMatch ) + results[results.length]= [ this.curr_syntax[i]["keywords"][prefix], this.curr_syntax[i]["keywords"][prefix]['datas'][j] ]; + } + } + } + } + } + + // there is only one result, and we can select it automatically + if( results.length == 1 && this.autoSelectIfOneResult ) + { + // console.log( results ); + this._select( results[0][1]['replace_with'] ); + } + else if( results.length == 0 ) + { + this._hide(); + } + else + { + // build the suggestion box content + var lines=[]; + for(var i=0; i"+ results[i][1]['comment']; + if(results[i][0]['prefix_name'].length>0) + line+=''+ results[i][0]['prefix_name'] +''; + line+=''; + lines[lines.length]=line; + } + // sort results + this.container.innerHTML = '
      '+ lines.sort().join('') +'
    '; + + var cursor = _$("cursor_pos"); + this.container.style.top = ( cursor.cursor_top + editArea.lineHeight ) +"px"; + this.container.style.left = ( cursor.cursor_left + 8 ) +"px"; + this._show(); + } + + this.autoSelectIfOneResult = false; + time=new Date; + t2= time.getTime(); + + //parent.console.log( begin_word +"\n"+ (t2-t1) +"\n"+ html ); + } + } +}; + +// Load as a plugin +editArea.settings['plugins'][ editArea.settings['plugins'].length ] = 'autocompletion'; +editArea.add_plugin('autocompletion', EditArea_autocompletion); \ No newline at end of file diff --git a/include/limesurvey/admin/scripts/edit_area/edit_area.css b/include/limesurvey/admin/scripts/edit_area/edit_area.css new file mode 100644 index 00000000..7547e7c2 --- /dev/null +++ b/include/limesurvey/admin/scripts/edit_area/edit_area.css @@ -0,0 +1,530 @@ +body, html{ + margin: 0; + padding: 0; + height: 100%; + border: none; + overflow: hidden; + background-color: #FFF; +} + +body, html, table, form, textarea{ + font: 12px monospace, sans-serif; +} + +#editor{ + border: solid #D2E0F2 1px; + overflow: hidden; +} + +#result{ + z-index: 4; + overflow-x: auto; + overflow-y: scroll; + border-top: solid #888 1px; + border-bottom: solid #888 1px; + position: relative; + clear: both; +} + +#result.empty{ + overflow: hidden; +} + +#container{ + overflow: hidden; + border: solid blue 0; + position: relative; + z-index: 10; + padding: 0 5px 0 45px; + /*padding-right: 5px;*/ +} + +#textarea{ + position: relative; + top: 0; + left: 0; + margin: 0; + padding: 0; + width: 100%; + height: 100%; + overflow: hidden; + z-index: 7; + border-width: 0; + background-color: transparent; + resize: none; +} + +#textarea, #textarea:hover{ + outline: none; /* safari outline fix */ +} + +#content_highlight{ + white-space: pre; + margin: 0; + padding: 0; + position : absolute; + z-index: 4; + overflow: visible; +} + + +#selection_field, #selection_field_text{ + margin: 0; + background-color: #E1F2F9; +/* height: 1px; */ + position: absolute; + z-index: 5; + top: -100px; + padding: 0; + white-space: pre; + overflow: hidden; +} + +#selection_field.show_colors { + z-index: 3; + background-color:#EDF9FC; + +} + +#selection_field strong{ + font-weight:normal; +} + +#selection_field.show_colors *, #selection_field_text * { + visibility: hidden; +} + +#selection_field_text{ + background-color:transparent; +} + +#selection_field_text strong{ + font-weight:normal; + background-color:#3399FE; + color: #FFF; + visibility:visible; +} + +#container.word_wrap #content_highlight, +#container.word_wrap #selection_field, +#container.word_wrap #selection_field_text, +#container.word_wrap #test_font_size{ + white-space: pre-wrap; /* css-3 */ + white-space: -moz-pre-wrap !important; /* Mozilla, since 1999 */ + white-space: -pre-wrap; /* Opera 4-6 */ + white-space: -o-pre-wrap; /* Opera 7 */ + word-wrap: break-word; /* Internet Explorer 5.5+ */ + width: 99%; +} + +#line_number{ + position: absolute; + overflow: hidden; + border-right: solid black 1px; + z-index:8; + width: 38px; + padding: 0 5px 0 0; + margin: 0 0 0 -45px; + text-align: right; + color: #AAAAAA; +} + +#test_font_size{ + padding: 0; + margin: 0; + visibility: hidden; + position: absolute; + white-space: pre; +} + +pre{ + margin: 0; + padding: 0; +} + +.hidden{ + opacity: 0.2; + filter:alpha(opacity=20); +} + +#result .edit_area_cursor{ + position: absolute; + z-index:6; + background-color: #FF6633; + top: -100px; + margin: 0; +} + +#result .edit_area_selection_field .overline{ + background-color: #996600; +} + + +/* area popup */ +.editarea_popup{ + border: solid 1px #888888; + background-color: #EEF6FF; + width: 250px; + padding: 4px; + position: absolute; + visibility: hidden; + z-index: 15; + top: -500px; +} + +.editarea_popup, .editarea_popup table{ + font-family: sans-serif; + font-size: 10pt; +} + +.editarea_popup img{ + border: 0; +} + +.editarea_popup .close_popup{ + float: right; + line-height: 16px; + border: 0; + padding: 0; +} + +.editarea_popup h1,.editarea_popup h2,.editarea_popup h3,.editarea_popup h4,.editarea_popup h5,.editarea_popup h6{ + margin: 0; + padding: 0; +} + +.editarea_popup .copyright{ + text-align: right; +} + +/* Area_search */ +div#area_search_replace{ + /*width: 250px;*/ +} + +div#area_search_replace img{ + border: 0; +} + +div#area_search_replace div.button{ + text-align: center; + line-height: 1.7em; +} + +div#area_search_replace .button a{ + cursor: pointer; + border: solid 1px #888888; + background-color: #DEDEDE; + text-decoration: none; + padding: 0 2px; + color: #000000; + white-space: nowrap; +} + +div#area_search_replace a:hover{ + /*border: solid 1px #888888;*/ + background-color: #EDEDED; +} + +div#area_search_replace #move_area_search_replace{ + cursor: move; + border: solid 1px #888; +} + +div#area_search_replace #close_area_search_replace{ + text-align: right; + vertical-align: top; + white-space: nowrap; +} + +div#area_search_replace #area_search_msg{ + height: 18px; + overflow: hidden; + border-top: solid 1px #888; + margin-top: 3px; +} + +/* area help */ +#edit_area_help{ + width: 350px; +} + +#edit_area_help div.close_popup{ + float: right; +} + +/* area_toolbar */ +.area_toolbar{ + /*font: 11px sans-serif;*/ + width: 100%; + /*height: 21px; */ + margin: 0; + padding: 0; + background-color: #EEF6FF; + text-align: center; +} + +.area_toolbar, .area_toolbar table{ + font: 11px sans-serif; +} + +.area_toolbar img{ + border: 0; + vertical-align: middle; +} + +.area_toolbar input{ + margin: 0; + padding: 0; +} + +.area_toolbar select{ + font-family: 'MS Sans Serif',sans-serif,Verdana,Arial; + font-size: 7pt; + font-weight: normal; + margin: 2px 0 0 0 ; + padding: 0; + vertical-align: top; + background-color: #F0F0EE; +} + +table.statusbar{ + width: 100%; +} + +.area_toolbar td.infos{ + text-align: center; + width: 130px; + border-right: solid 1px #D2E0F2; + border-width: 0 1px 0 0; + padding: 0; +} + +.area_toolbar td.total{ + text-align: right; + width: 50px; + padding: 0; +} + +.area_toolbar td.resize{ + text-align: right; +} +/* +.area_toolbar span{ + line-height: 1px; + padding: 0; + margin: 0; +}*/ + +.area_toolbar span#resize_area{ + cursor: nw-resize; + visibility: hidden; +} + +/* toolbar buttons */ +.editAreaButtonNormal, .editAreaButtonOver, .editAreaButtonDown, .editAreaSeparator, .editAreaSeparatorLine, .editAreaButtonDisabled, .editAreaButtonSelected { + border: 0; margin: 0; padding: 0; background: transparent; + margin-top: 0; + margin-left: 1px; + padding: 0; +} + +.editAreaButtonNormal { + border: 1px solid #EEF6FF !important; + cursor: pointer; +} + +.editAreaButtonOver { + border: 1px solid #0A246A !important; + cursor: pointer; + background-color: #B6BDD2; +} + +.editAreaButtonDown { + cursor: pointer; + border: 1px solid #0A246A !important; + background-color: #8592B5; +} + +.editAreaButtonSelected { + border: 1px solid #C0C0BB !important; + cursor: pointer; + background-color: #F4F2E8; +} + +.editAreaButtonDisabled { + filter:progid:DXImageTransform.Microsoft.Alpha(opacity=30); + -moz-opacity:0.3; + opacity: 0.3; + border: 1px solid #F0F0EE !important; + cursor: pointer; +} + +.editAreaSeparatorLine { + margin: 1px 2px; + background-color: #C0C0BB; + width: 2px; + height: 18px; +} + +/* waiting screen */ +#processing{ + display: none; + background-color:#ECE9D8; + border: solid #888 1px; + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; + z-index: 100; + text-align: center; +} + +#processing_text{ + position:absolute; + left: 50%; + top: 50%; + width: 200px; + height: 20px; + margin-left: -100px; + margin-top: -10px; + text-align: center; +} +/* end */ + + +/**** tab browsing area ****/ +#tab_browsing_area{ + display: none; + background-color: #CCC9A8; + border-top: 1px solid #888; + text-align: left; + margin: 0; +} + +#tab_browsing_list { + padding: 0; + margin: 0; + list-style-type: none; + white-space: nowrap; +} +#tab_browsing_list li { + float: left; + margin: -1px; +} +#tab_browsing_list a { + position: relative; + display: block; + text-decoration: none; + float: left; + cursor: pointer; + line-height:14px; +} + +#tab_browsing_list a span { + display: block; + color: #000; + background: #EEF6FF; + border: 1px solid #888; + border-width: 1px 1px 0; + text-align: center; + padding: 2px 2px 1px 4px; + position: relative; /*IE 6 hack */ +} + +#tab_browsing_list a b { + display: block; + border-bottom: 2px solid #617994; +} + +#tab_browsing_list a .edited { + display: none; +} + +#tab_browsing_list a.edited .edited { + display: inline; +} + +#tab_browsing_list a img{ + margin-left: 7px; +} + +#tab_browsing_list a.edited img{ + margin-left: 3px; +} + +#tab_browsing_list a:hover span { + background: #F4F2E8; + border-color: #0A246A; +} + +#tab_browsing_list .selected a span{ + background: #046380; + color: #FFF; +} + + +#no_file_selected{ + height: 100%; + width: 150%; /* Opera need more than 100% */ + background: #CCC; + display: none; + z-index: 20; + position: absolute; +} + + +/*** Non-editable mode ***/ +.non_editable #editor +{ + border-width: 0 1px; +} + +.non_editable .area_toolbar +{ + display: none; +} + +/*** Auto completion ***/ +#auto_completion_area +{ + background: #FFF; + border: solid 1px #888; + position: absolute; + z-index: 15; + width: 280px; + height: 180px; + overflow: auto; + display:none; +} + +#auto_completion_area a, #auto_completion_area a:visited +{ + display: block; + padding: 0 2px 1px; + color: #000; + text-decoration:none; +} + +#auto_completion_area a:hover, #auto_completion_area a:focus, #auto_completion_area a.focus +{ + background: #D6E1FE; + text-decoration:none; +} + +#auto_completion_area ul +{ + margin: 0; + padding: 0; + list-style: none inside; +} +#auto_completion_area li +{ + padding: 0; +} +#auto_completion_area .prefix +{ + font-style: italic; + padding: 0 3px; +} \ No newline at end of file diff --git a/include/limesurvey/admin/scripts/edit_area/edit_area.js b/include/limesurvey/admin/scripts/edit_area/edit_area.js new file mode 100644 index 00000000..27674f67 --- /dev/null +++ b/include/limesurvey/admin/scripts/edit_area/edit_area.js @@ -0,0 +1,525 @@ +/****** + * + * EditArea + * Developped by Christophe Dolivet + * Released under LGPL, Apache and BSD licenses (use the one you want) + * +******/ + + function EditArea(){ + var t=this; + t.error= false; // to know if load is interrrupt + + t.inlinePopup= [{popup_id: "area_search_replace", icon_id: "search"}, + {popup_id: "edit_area_help", icon_id: "help"}]; + t.plugins= {}; + + t.line_number=0; + + parent.editAreaLoader.set_browser_infos(t); // navigator identification + // fix IE8 detection as we run in IE7 emulate mode through X-UA tag + if( t.isIE >= 8 ) + t.isIE = 7; + + t.last_selection={}; + t.last_text_to_highlight=""; + t.last_hightlighted_text= ""; + t.syntax_list= []; + t.allready_used_syntax= {}; + t.check_line_selection_timer= 50; // the timer delay for modification and/or selection change detection + + t.textareaFocused= false; + t.highlight_selection_line= null; + t.previous= []; + t.next= []; + t.last_undo=""; + t.files= {}; + t.filesIdAssoc= {}; + t.curr_file= ''; + //t.loaded= false; + t.assocBracket={}; + t.revertAssocBracket= {}; + // bracket selection init + t.assocBracket["("]=")"; + t.assocBracket["{"]="}"; + t.assocBracket["["]="]"; + for(var index in t.assocBracket){ + t.revertAssocBracket[t.assocBracket[index]]=index; + } + t.is_editable= true; + + + /*t.textarea=""; + + t.state="declare"; + t.code = []; // store highlight syntax for languagues*/ + // font datas + t.lineHeight= 16; + /*t.default_font_family= "monospace"; + t.default_font_size= 10;*/ + t.tab_nb_char= 8; //nb of white spaces corresponding to a tabulation + if(t.isOpera) + t.tab_nb_char= 6; + + t.is_tabbing= false; + + t.fullscreen= {'isFull': false}; + + t.isResizing=false; // resize var + + // init with settings and ID (area_id is a global var defined by editAreaLoader on iframe creation + t.id= area_id; + t.settings= editAreas[t.id]["settings"]; + + if((""+t.settings['replace_tab_by_spaces']).match(/^[0-9]+$/)) + { + t.tab_nb_char= t.settings['replace_tab_by_spaces']; + t.tabulation=""; + for(var i=0; i0) + t.syntax_list= t.settings["syntax_selection_allow"].replace(/ /g,"").split(","); + + if(t.settings['syntax']) + t.allready_used_syntax[t.settings['syntax']]=true; + + + }; + EditArea.prototype.init= function(){ + var t=this, a, s=t.settings; + t.textarea = _$("textarea"); + t.container = _$("container"); + t.result = _$("result"); + t.content_highlight = _$("content_highlight"); + t.selection_field = _$("selection_field"); + t.selection_field_text= _$("selection_field_text"); + t.processing_screen = _$("processing"); + t.editor_area = _$("editor"); + t.tab_browsing_area = _$("tab_browsing_area"); + t.test_font_size = _$("test_font_size"); + a = t.textarea; + + if(!s['is_editable']) + t.set_editable(false); + + t.set_show_line_colors( s['show_line_colors'] ); + + if(syntax_selec= _$("syntax_selection")) + { + // set up syntax selection lsit in the toolbar + for(var i=0; i= '3' ) { + t.content_highlight.style.paddingLeft= "1px"; + t.selection_field.style.paddingLeft= "1px"; + t.selection_field_text.style.paddingLeft= "1px"; + } + + if(t.isIE && t.isIE < 8 ){ + a.style.marginTop= "-1px"; + } + /* + if(t.isOpera){ + t.editor_area.style.position= "absolute"; + }*/ + + if( t.isSafari ){ + t.editor_area.style.position = "absolute"; + a.style.marginLeft ="-3px"; + if( t.isSafari < 3.2 ) // Safari 3.0 (3.1?) + a.style.marginTop ="1px"; + } + + // si le textarea n'est pas grand, un click sous le textarea doit provoquer un focus sur le textarea + parent.editAreaLoader.add_event(t.result, "click", function(e){ if((e.target || e.srcElement)==editArea.result) { editArea.area_select(editArea.textarea.value.length, 0);} }); + + if(s['is_multi_files']!=false) + t.open_file({'id': t.curr_file, 'text': ''}); + + t.set_word_wrap( s['word_wrap'] ); + + setTimeout("editArea.focus();editArea.manage_size();editArea.execCommand('EA_load');", 10); + //start checkup routine + t.check_undo(); + t.check_line_selection(true); + t.scroll_to_view(); + + for(var i in t.plugins){ + if(typeof(t.plugins[i].onload)=="function") + t.plugins[i].onload(); + } + if(s['fullscreen']==true) + t.toggle_full_screen(true); + + parent.editAreaLoader.add_event(window, "resize", editArea.update_size); + parent.editAreaLoader.add_event(parent.window, "resize", editArea.update_size); + parent.editAreaLoader.add_event(top.window, "resize", editArea.update_size); + parent.editAreaLoader.add_event(window, "unload", function(){ + // in case where editAreaLoader have been already cleaned + if( parent.editAreaLoader ) + { + parent.editAreaLoader.remove_event(parent.window, "resize", editArea.update_size); + parent.editAreaLoader.remove_event(top.window, "resize", editArea.update_size); + } + if(editAreas[editArea.id] && editAreas[editArea.id]["displayed"]){ + editArea.execCommand("EA_unload"); + } + }); + + + /*date= new Date(); + alert(date.getTime()- parent.editAreaLoader.start_time);*/ + }; + + + + //called by the toggle_on + EditArea.prototype.update_size= function(){ + var d=document,pd=parent.document,height,width,popup,maxLeft,maxTop; + + if( typeof editAreas != 'undefined' && editAreas[editArea.id] && editAreas[editArea.id]["displayed"]==true){ + if(editArea.fullscreen['isFull']){ + pd.getElementById("frame_"+editArea.id).style.width = pd.getElementsByTagName("html")[0].clientWidth + "px"; + pd.getElementById("frame_"+editArea.id).style.height = pd.getElementsByTagName("html")[0].clientHeight + "px"; + } + + if(editArea.tab_browsing_area.style.display=='block' && ( !editArea.isIE || editArea.isIE >= 8 ) ) + { + editArea.tab_browsing_area.style.height = "0px"; + editArea.tab_browsing_area.style.height = (editArea.result.offsetTop - editArea.tab_browsing_area.offsetTop -1)+"px"; + } + + height = d.body.offsetHeight - editArea.get_all_toolbar_height() - 4; + editArea.result.style.height = height +"px"; + + width = d.body.offsetWidth -2; + editArea.result.style.width = width+"px"; + //alert("result h: "+ height+" w: "+width+"\ntoolbar h: "+this.get_all_toolbar_height()+"\nbody_h: "+document.body.offsetHeight); + + // check that the popups don't get out of the screen + for( i=0; i < editArea.inlinePopup.length; i++ ) + { + popup = _$(editArea.inlinePopup[i]["popup_id"]); + maxLeft = d.body.offsetWidth - popup.offsetWidth; + maxTop = d.body.offsetHeight - popup.offsetHeight; + if( popup.offsetTop > maxTop ) + popup.style.top = maxTop+"px"; + if( popup.offsetLeft > maxLeft ) + popup.style.left = maxLeft+"px"; + } + + editArea.manage_size( true ); + editArea.fixLinesHeight( editArea.textarea.value, 0,-1); + } + }; + + + EditArea.prototype.manage_size= function(onlyOneTime){ + if(!editAreas[this.id]) + return false; + + if(editAreas[this.id]["displayed"]==true && this.textareaFocused) + { + var area_height,resized= false; + + //1) Manage display width + //1.1) Calc the new width to use for display + if( !this.settings['word_wrap'] ) + { + var area_width= this.textarea.scrollWidth; + area_height= this.textarea.scrollHeight; + // bug on old opera versions + if(this.isOpera && this.isOpera < 9.6 ){ + area_width=10000; + } + //1.2) the width is not the same, we must resize elements + if(this.textarea.previous_scrollWidth!=area_width) + { + this.container.style.width= area_width+"px"; + this.textarea.style.width= area_width+"px"; + this.content_highlight.style.width= area_width+"px"; + this.textarea.previous_scrollWidth=area_width; + resized=true; + } + } + // manage wrap width + if( this.settings['word_wrap'] ) + { + newW=this.textarea.offsetWidth; + if( this.isFirefox || this.isIE ) + newW-=2; + if( this.isSafari ) + newW-=6; + this.content_highlight.style.width=this.selection_field_text.style.width=this.selection_field.style.width=this.test_font_size.style.width=newW+"px"; + } + + //2) Manage display height + //2.1) Calc the new height to use for display + if( this.isOpera || this.isFirefox || this.isSafari ) { + area_height= this.getLinePosTop( this.last_selection["nb_line"] + 1 ); + } else { + area_height = this.textarea.scrollHeight; + } + //2.2) the width is not the same, we must resize elements + if(this.textarea.previous_scrollHeight!=area_height) + { + this.container.style.height= (area_height+2)+"px"; + this.textarea.style.height= area_height+"px"; + this.content_highlight.style.height= area_height+"px"; + this.textarea.previous_scrollHeight= area_height; + resized=true; + } + + //3) if there is new lines, we add new line numbers in the line numeration area + if(this.last_selection["nb_line"] >= this.line_number) + { + var newLines= '', destDiv=_$("line_number"), start=this.line_number, end=this.last_selection["nb_line"]+100; + for( i = start+1; i < end; i++ ) + { + newLines+='
    '+i+"
    "; + this.line_number++; + } + destDiv.innerHTML= destDiv.innerHTML + newLines; + + this.fixLinesHeight( this.textarea.value, start, -1 ); + } + + //4) be sure the text is well displayed + this.textarea.scrollTop="0px"; + this.textarea.scrollLeft="0px"; + if(resized==true){ + this.scroll_to_view(); + } + } + + if(!onlyOneTime) + setTimeout("editArea.manage_size();", 100); + }; + + EditArea.prototype.execCommand= function(cmd, param){ + + for(var i in this.plugins){ + if(typeof(this.plugins[i].execCommand)=="function"){ + if(!this.plugins[i].execCommand(cmd, param)) + return; + } + } + switch(cmd){ + case "save": + if(this.settings["save_callback"].length>0) + eval("parent."+this.settings["save_callback"]+"('"+ this.id +"', editArea.textarea.value);"); + break; + case "load": + if(this.settings["load_callback"].length>0) + eval("parent."+this.settings["load_callback"]+"('"+ this.id +"');"); + break; + case "onchange": + if(this.settings["change_callback"].length>0) + eval("parent."+this.settings["change_callback"]+"('"+ this.id +"');"); + break; + case "EA_load": + if(this.settings["EA_load_callback"].length>0) + eval("parent."+this.settings["EA_load_callback"]+"('"+ this.id +"');"); + break; + case "EA_unload": + if(this.settings["EA_unload_callback"].length>0) + eval("parent."+this.settings["EA_unload_callback"]+"('"+ this.id +"');"); + break; + case "toggle_on": + if(this.settings["EA_toggle_on_callback"].length>0) + eval("parent."+this.settings["EA_toggle_on_callback"]+"('"+ this.id +"');"); + break; + case "toggle_off": + if(this.settings["EA_toggle_off_callback"].length>0) + eval("parent."+this.settings["EA_toggle_off_callback"]+"('"+ this.id +"');"); + break; + case "re_sync": + if(!this.do_highlight) + break; + case "file_switch_on": + if(this.settings["EA_file_switch_on_callback"].length>0) + eval("parent."+this.settings["EA_file_switch_on_callback"]+"(param);"); + break; + case "file_switch_off": + if(this.settings["EA_file_switch_off_callback"].length>0) + eval("parent."+this.settings["EA_file_switch_off_callback"]+"(param);"); + break; + case "file_close": + if(this.settings["EA_file_close_callback"].length>0) + return eval("parent."+this.settings["EA_file_close_callback"]+"(param);"); + break; + + default: + if(typeof(eval("editArea."+cmd))=="function") + { + if(this.settings["debug"]) + eval("editArea."+ cmd +"(param);"); + else + try{eval("editArea."+ cmd +"(param);");}catch(e){}; + } + } + }; + + EditArea.prototype.get_translation= function(word, mode){ + if(mode=="template") + return parent.editAreaLoader.translate(word, this.settings["language"], mode); + else + return parent.editAreaLoader.get_word_translation(word, this.settings["language"]); + }; + + EditArea.prototype.add_plugin= function(plug_name, plug_obj){ + for(var i=0; i"); + } + }; + + EditArea.prototype.load_script= function(url){ + try{ + script = document.createElement("script"); + script.type = "text/javascript"; + script.src = url; + script.charset= "UTF-8"; + head = document.getElementsByTagName("head"); + head[0].appendChild(script); + }catch(e){ + document.write("\";\n", $sub_scripts); + + + // add the script and use a last compression + if( $this->param['compress'] ) + { + $last_comp = array( 'Ã' => 'this', + 'Â' => 'textarea', + 'Ã' => 'function', + 'Ä' => 'prototype', + 'Ã…' => 'settings', + 'Æ' => 'length', + 'Ç' => 'style', + 'È' => 'parent', + 'É' => 'last_selection', + 'Ê' => 'value', + 'Ë' => 'true', + 'ÃŒ' => 'false' + /*, + 'ÃŽ' => '"', + 'Ã' => "\n", + 'À' => "\r"*/); + } + else + { + $last_comp = array(); + } + + $js_replace= ''; + foreach( $last_comp as $key => $val ) + $js_replace .= ".replace(/". $key ."/g,'". str_replace( array("\n", "\r"), array('\n','\r'), $val ) ."')"; + + $this->datas.= sprintf("editAreaLoader.iframe_script= \"\"%s;\n", + str_replace( array_values($last_comp), array_keys($last_comp), $sub_scripts ), + $js_replace); + + if($this->load_all_plugins) + $this->datas.="editAreaLoader.all_plugins_loaded=true;\n"; + + + // load the template + $this->datas.= sprintf("editAreaLoader.template= \"%s\";\n", $this->get_html_content("template.html")); + // load the css + $this->datas.= sprintf("editAreaLoader.iframe_css= \"\";\n", $this->get_css_content("edit_area.css")); + + // $this->datas= "function editArea(){};editArea.prototype.loader= function(){alert('bouhbouh');} var a= new editArea();a.loader();"; + + } + + function send_datas() + { + if($this->param['debug']){ + $header=sprintf("/* USE PHP COMPRESSION\n"); + $header.=sprintf("javascript size: based files: %s => PHP COMPRESSION => %s ", $this->file_loaded_size, strlen($this->datas)); + if($this->use_gzip){ + $gzip_datas= gzencode($this->datas, 9, FORCE_GZIP); + $header.=sprintf("=> GZIP COMPRESSION => %s", strlen($gzip_datas)); + $ratio = round(100 - strlen($gzip_datas) / $this->file_loaded_size * 100.0); + }else{ + $ratio = round(100 - strlen($this->datas) / $this->file_loaded_size * 100.0); + } + $header.=sprintf(", reduced by %s%%\n", $ratio); + $header.=sprintf("compression time: %s\n", $this->get_microtime()-$this->start_time); + $header.=sprintf("%s\n", implode("\n", $this->infos)); + $header.=sprintf("*/\n"); + $this->datas= $header.$this->datas; + } + $mtime= time(); // ensure that the 2 disk files will have the same update time + // generate gzip file and cahce it if using disk cache + if($this->use_gzip){ + $this->gzip_datas= gzencode($this->datas, 9, FORCE_GZIP); + if($this->param['use_disk_cache']) + $this->file_put_contents($this->gzip_cache_file, $this->gzip_datas, $mtime); + } + + // generate full js file and cache it if using disk cache + if($this->param['use_disk_cache']) + $this->file_put_contents($this->full_cache_file, $this->datas, $mtime); + + // generate output + if($this->use_gzip) + echo $this->gzip_datas; + else + echo $this->datas; + +// die; + } + + + function get_content($end_uri) + { + $end_uri=preg_replace("/\.\./", "", $end_uri); // Remove any .. (security) + $file= $this->path.$end_uri; + if(file_exists($file)){ + $this->infos[]=sprintf("'%s' loaded", $end_uri); + /*$fd = fopen($file, 'rb'); + $content = fread($fd, filesize($file)); + fclose($fd); + return $content;*/ + return $this->file_get_contents($file); + }else{ + $this->infos[]=sprintf("'%s' not loaded", $end_uri); + return ""; + } + } + + function get_javascript_content($end_uri) + { + $val=$this->get_content($end_uri); + + $this->compress_javascript($val); + $this->prepare_string_for_quotes($val); + return $val; + } + + function compress_javascript(&$code) + { + if($this->param['compress']) + { + // remove all comments + // (\"(?:[^\"\\]*(?:\\\\)*(?:\\\"?)?)*(?:\"|$))|(\'(?:[^\'\\]*(?:\\\\)*(?:\\'?)?)*(?:\'|$))|(?:\/\/(?:.|\r|\t)*?(\n|$))|(?:\/\*(?:.|\n|\r|\t)*?(?:\*\/|$)) + $code= preg_replace("/(\"(?:[^\"\\\\]*(?:\\\\\\\\)*(?:\\\\\"?)?)*(?:\"|$))|(\'(?:[^\'\\\\]*(?:\\\\\\\\)*(?:\\\\\'?)?)*(?:\'|$))|(?:\/\/(?:.|\r|\t)*?(\n|$))|(?:\/\*(?:.|\n|\r|\t)*?(?:\*\/|$))/s", "$1$2$3", $code); + // remove line return, empty line and tabulation + $code= preg_replace('/(( |\t|\r)*\n( |\t)*)+/s', " ", $code); + // add line break before "else" otherwise navigators can't manage to parse the file + $code= preg_replace('/(\b(else)\b)/', "\n$1", $code); + // remove unnecessary spaces + $code= preg_replace('/( |\t|\r)*(;|\{|\}|=|==|\-|\+|,|\(|\)|\|\||&\&|\:)( |\t|\r)*/', "$2", $code); + } + } + + function get_css_content($end_uri){ + $code=$this->get_content($end_uri); + // remove comments + $code= preg_replace("/(?:\/\*(?:.|\n|\r|\t)*?(?:\*\/|$))/s", "", $code); + // remove spaces + $code= preg_replace('/(( |\t|\r)*\n( |\t)*)+/s', "", $code); + // remove spaces + $code= preg_replace('/( |\t|\r)?(\:|,|\{|\})( |\t|\r)+/', "$2", $code); + + $this->prepare_string_for_quotes($code); + return $code; + } + + function get_html_content($end_uri){ + $code=$this->get_content($end_uri); + //$code= preg_replace('/(\"(?:\\\"|[^\"])*(?:\"|$))|' . "(\'(?:\\\'|[^\'])*(?:\'|$))|(?:\/\/(?:.|\r|\t)*?(\n|$))|(?:\/\*(?:.|\n|\r|\t)*?(?:\*\/|$))/s", "$1$2$3", $code); + $code= preg_replace('/(( |\t|\r)*\n( |\t)*)+/s', " ", $code); + $this->prepare_string_for_quotes($code); + return $code; + } + + function prepare_string_for_quotes(&$str){ + // prepare the code to be putted into quotes + /*$pattern= array("/(\\\\)?\"/", '/\\\n/' , '/\\\r/' , "/(\r?\n)/"); + $replace= array('$1$1\\"', '\\\\\\n', '\\\\\\r' , '\\\n"$1+"');*/ + $pattern= array("/(\\\\)?\"/", '/\\\n/' , '/\\\r/' , "/(\r?\n)/"); + if($this->param['compress']) + $replace= array('$1$1\\"', '\\\\\\n', '\\\\\\r' , '\n'); + else + $replace= array('$1$1\\"', '\\\\\\n', '\\\\\\r' , "\\n\"\n+\""); + $str= preg_replace($pattern, $replace, $str); + } + + function replace_scripts($var, $param1, $param2) + { + $this->$var=stripslashes($param2); + return $param1."[];"; + } + + /* for php version that have not thoses functions */ + function file_get_contents($file) + { + $fd = fopen($file, 'rb'); + $content = fread($fd, filesize($file)); + fclose($fd); + $this->file_loaded_size+= strlen($content); + return $content; + } + + function file_put_contents($file, &$content, $mtime=-1) + { + if($mtime==-1) + $mtime=time(); + $fp = @fopen($file, "wb"); + if ($fp) { + fwrite($fp, $content); + fclose($fp); + touch($file, $mtime); + return true; + } + return false; + } + + function get_microtime() + { + list($usec, $sec) = explode(" ", microtime()); + return ((float)$usec + (float)$sec); + } + } +?> diff --git a/include/limesurvey/admin/scripts/edit_area/edit_area_full.gz b/include/limesurvey/admin/scripts/edit_area/edit_area_full.gz new file mode 100644 index 00000000..8cfc846f Binary files /dev/null and b/include/limesurvey/admin/scripts/edit_area/edit_area_full.gz differ diff --git a/include/limesurvey/admin/scripts/edit_area/edit_area_full.js b/include/limesurvey/admin/scripts/edit_area/edit_area_full.js new file mode 100644 index 00000000..db136a89 --- /dev/null +++ b/include/limesurvey/admin/scripts/edit_area/edit_area_full.js @@ -0,0 +1,38 @@ + function EAL(){var t=this;t.version="0.8.1.1";date=new Date();t.start_time=date.getTime();t.win="loading";t.error=false;t.baseURL="";t.template="";t.lang={};t.load_syntax={};t.syntax={};t.loadedFiles=[];t.waiting_loading={};t.scripts_to_load=[];t.sub_scripts_to_load=[];t.resize=[];t.hidden={};t.default_settings={debug:false,smooth_selection:true,font_size:"10",font_family:"monospace",start_highlight:false,toolbar:"search,go_to_line,fullscreen,|,undo,redo,|,select_font,|,change_smooth_selection,highlight,reset_highlight,word_wrap,|,help",begin_toolbar:"",end_toolbar:"",is_multi_files:false,allow_resize:"both",show_line_colors:false,min_width:400,min_height:125,replace_tab_by_spaces:false,allow_toggle:true,language:"en",syntax:"",syntax_selection_allow:"basic,brainfuck,c,coldfusion,cpp,css,html,java,js,pas,perl,php,python,ruby,robotstxt,sql,tsql,vb,xml",display:"onload",max_undo:30,browsers:"known",plugins:"",gecko_spellcheck:false,fullscreen:false,is_editable:true,cursor_position:"begin",word_wrap:false,autocompletion:false,load_callback:"",save_callback:"",change_callback:"",submit_callback:"",EA_init_callback:"",EA_delete_callback:"",EA_load_callback:"",EA_unload_callback:"",EA_toggle_on_callback:"",EA_toggle_off_callback:"",EA_file_switch_on_callback:"",EA_file_switch_off_callback:"",EA_file_close_callback:""};t.advanced_buttons=[ ['new_document','newdocument.gif','new_document',false],['search','search.gif','show_search',false],['go_to_line','go_to_line.gif','go_to_line',false],['undo','undo.gif','undo',true],['redo','redo.gif','redo',true],['change_smooth_selection','smooth_selection.gif','change_smooth_selection_mode',true],['reset_highlight','reset_highlight.gif','resync_highlight',true],['highlight','highlight.gif','change_highlight',true],['help','help.gif','show_help',false],['save','save.gif','save',false],['load','load.gif','load',false],['fullscreen','fullscreen.gif','toggle_full_screen',false],['word_wrap','word_wrap.gif','toggle_word_wrap',true],['autocompletion','autocompletion.gif','toggle_autocompletion',true] ];t.set_browser_infos(t);if(t.isIE>=6||t.isGecko||(t.isWebKit&&!t.isSafari<3)||t.isOpera>=9||t.isCamino)t.isValidBrowser=true; +else t.isValidBrowser=false;t.set_base_url();for(var i=0;i0)s["toolbar"]=s["begin_toolbar"]+","+s["toolbar"];if(s["end_toolbar"].length>0)s["toolbar"]=s["toolbar"]+","+s["end_toolbar"];s["tab_toolbar"]=s["toolbar"].replace(/ /g,"").split(",");s["plugins"]=s["plugins"].replace(/ /g,"").split(",");for(i=0;i0){s["syntax"]=s["syntax"].toLowerCase();t.load_script(t.baseURL+"reg_syntax/"+s["syntax"]+".js");}eAs[s["id"]]={"settings":s};eAs[s["id"]]["displayed"]=false;eAs[s["id"]]["hidden"]=false;t.start(s["id"]);},delete_instance:function(id){var d=document,fs=window.frames,span,iframe;eAL.execCommand(id,"EA_delete");if(fs["frame_"+id]&&fs["frame_"+id].editArea){if(eAs[id]["displayed"])eAL.toggle(id,"off");fs["frame_"+id].editArea.execCommand("EA_unload");}span=d.getElementById("EditAreaArroundInfos_"+id);if(span)span.parentNode.removeChild(span);iframe=d.getElementById("frame_"+id);if(iframe){iframe.parentNode.removeChild(iframe);try{delete fs["frame_"+id];}catch(e){}}delete eAs[id];},start:function(id){var t=this,d=document,f,span,father,next,html='',html_toolbar_content='',template,content,i;if(t.win!="loaded"){setTimeout("eAL.start('"+id+"');",50);return;}for(i in t.waiting_loading){if(t.waiting_loading[i]!="loaded"&&typeof(t.waiting_loading[i])!="function"){setTimeout("eAL.start('"+id+"');",50);return;}}if(!t.lang[eAs[id]["settings"]["language"]]||(eAs[id]["settings"]["syntax"].length>0&&!t.load_syntax[eAs[id]["settings"]["syntax"]])){setTimeout("eAL.start('"+id+"');",50);return;}if(eAs[id]["settings"]["syntax"].length>0)t.init_syntax_regexp();if(!d.getElementById("EditAreaArroundInfos_"+id)&&(eAs[id]["settings"]["debug"]||eAs[id]["settings"]["allow_toggle"])){span=d.createElement("span");span.id="EditAreaArroundInfos_"+id;if(eAs[id]["settings"]["allow_toggle"]){checked=(eAs[id]["settings"]["display"]=="onload")?"checked='checked'":"";html+="
    ";html+="";html+="
    ";}if(eAs[id]["settings"]["debug"])html+="
    ";html=t.translate(html,eAs[id]["settings"]["language"]);span.innerHTML=html;father=d.getElementById(id).parentNode;next=d.getElementById(id).nextSibling;if(next==null)father.appendChild(span); +else father.insertBefore(span,next);}if(!eAs[id]["initialized"]){t.execCommand(id,"EA_init");if(eAs[id]["settings"]["display"]=="later"){eAs[id]["initialized"]=true;return;}}if(t.isIE){t.init_ie_textarea(id);}area=eAs[id];for(i=0;i';}for(i=0;i';t.iframe_script+='';}if(!t.iframe_css){t.iframe_css="";}template=t.template.replace(/\[__BASEURL__\]/g,t.baseURL);template=template.replace("[__TOOLBAR__]",html_toolbar_content);template=t.translate(template,area["settings"]["language"],"template");template=template.replace("[__CSSRULES__]",t.iframe_css);template=template.replace("[__JSCODE__]",t.iframe_script);template=template.replace("[__EA_VERSION__]",t.version);area.textarea=d.getElementById(area["settings"]["id"]);eAs[area["settings"]["id"]]["textarea"]=area.textarea;if(typeof(window.frames["frame_"+area["settings"]["id"]])!='undefined')delete window.frames["frame_"+area["settings"]["id"]];father=area.textarea.parentNode;content=d.createElement("iframe");content.name="frame_"+area["settings"]["id"];content.id="frame_"+area["settings"]["id"];content.style.borderWidth="0px";setAttribute(content,"frameBorder","0");content.style.overflow="hidden";content.style.display="none";next=area.textarea.nextSibling;if(next==null)father.appendChild(content); +else father.insertBefore(content,next);f=window.frames["frame_"+area["settings"]["id"]];f.document.open();f.eAs=eAs;f.area_id=area["settings"]["id"];f.document.area_id=area["settings"]["id"];f.document.write(template);f.document.close();},toggle:function(id,toggle_to){if(!toggle_to)toggle_to=(eAs[id]["displayed"]==true)?"off":"on";if(eAs[id]["displayed"]==true&&toggle_to=="off"){this.toggle_off(id);} +else if(eAs[id]["displayed"]==false&&toggle_to=="on"){this.toggle_on(id);}return false;},toggle_off:function(id){var fs=window.frames,f,t,parNod,nxtSib,selStart,selEnd,scrollTop,scrollLeft;if(fs["frame_"+id]){f=fs["frame_"+id];t=eAs[id]["textarea"];if(f.editArea.fullscreen['isFull'])f.editArea.toggle_full_screen(false);eAs[id]["displayed"]=false;t.wrap="off";setAttribute(t,"wrap","off");parNod=t.parentNode;nxtSib=t.nextSibling;parNod.removeChild(t);parNod.insertBefore(t,nxtSib);t.value=f.editArea.textarea.value;selStart=f.editArea.last_selection["selectionStart"];selEnd=f.editArea.last_selection["selectionEnd"];scrollTop=f.document.getElementById("result").scrollTop;scrollLeft=f.document.getElementById("result").scrollLeft;document.getElementById("frame_"+id).style.display='none';t.style.display="inline";try{t.focus();}catch(e){};if(this.isIE){t.selectionStart=selStart;t.selectionEnd=selEnd;t.focused=true;set_IE_selection(t);} +else{if(this.isOpera&&this.isOpera < 9.6){t.setSelectionRange(0,0);}try{t.setSelectionRange(selStart,selEnd);}catch(e){};}t.scrollTop=scrollTop;t.scrollLeft=scrollLeft;f.editArea.execCommand("toggle_off");}},toggle_on:function(id){var fs=window.frames,f,t,selStart=0,selEnd=0,scrollTop=0,scrollLeft=0,curPos,elem;if(fs["frame_"+id]){f=fs["frame_"+id];t=eAs[id]["textarea"];area=f.editArea;area.textarea.value=t.value;curPos=eAs[id]["settings"]["cursor_position"];if(t.use_last==true){selStart=t.last_selectionStart;selEnd=t.last_selectionEnd;scrollTop=t.last_scrollTop;scrollLeft=t.last_scrollLeft;t.use_last=false;} +else if(curPos=="auto"){try{selStart=t.selectionStart;selEnd=t.selectionEnd;scrollTop=t.scrollTop;scrollLeft=t.scrollLeft;}catch(ex){}}this.set_editarea_size_from_textarea(id,document.getElementById("frame_"+id));t.style.display="none";document.getElementById("frame_"+id).style.display="inline";area.execCommand("focus");eAs[id]["displayed"]=true;area.execCommand("update_size");f.document.getElementById("result").scrollTop=scrollTop;f.document.getElementById("result").scrollLeft=scrollLeft;area.area_select(selStart,selEnd-selStart);area.execCommand("toggle_on");} +else{elem=document.getElementById(id);elem.last_selectionStart=elem.selectionStart;elem.last_selectionEnd=elem.selectionEnd;elem.last_scrollTop=elem.scrollTop;elem.last_scrollLeft=elem.scrollLeft;elem.use_last=true;eAL.start(id);}},set_editarea_size_from_textarea:function(id,frame){var elem,width,height;elem=document.getElementById(id);width=Math.max(eAs[id]["settings"]["min_width"],elem.offsetWidth)+"px";height=Math.max(eAs[id]["settings"]["min_height"],elem.offsetHeight)+"px";if(elem.style.width.indexOf("%")!=-1)width=elem.style.width;if(elem.style.height.indexOf("%")!=-1)height=elem.style.height;frame.style.width=width;frame.style.height=height;},set_base_url:function(){var t=this,elems,i,docBasePath;if(!this.baseURL){elems=document.getElementsByTagName('script');for(i=0;i';html+='';return html;},get_control_html:function(button_name,lang){var t=this,i,but,html,si;for(i=0;i";case "|":case "separator":return '';case "select_font":html="";return html;case "syntax_selection":html="";return html;}return "["+button_name+"]";},get_template:function(){if(this.template==""){var xhr_object=null;if(window.XMLHttpRequest)xhr_object=new XMLHttpRequest(); +else if(window.ActiveXObject)xhr_object=new ActiveXObject("Microsoft.XMLHTTP"); +else{alert("XMLHTTPRequest not supported. EditArea not loaded");return;}xhr_object.open("GET",this.baseURL+"template.html",false);xhr_object.send(null);if(xhr_object.readyState==4)this.template=xhr_object.responseText; +else this.has_error();}},translate:function(text,lang,mode){if(mode=="word")text=eAL.get_word_translation(text,lang); +else if(mode="template"){eAL.current_language=lang;text=text.replace(/\{\$([^\}]+)\}/gm,eAL.translate_template);}return text;},translate_template:function(){return eAL.get_word_translation(EAL.prototype.translate_template.arguments[1],eAL.current_language);},get_word_translation:function(val,lang){var i;for(i in eAL.lang[lang]){if(i==val)return eAL.lang[lang][i];}return "_"+val;},load_script:function(url){var t=this,d=document,script,head;if(t.loadedFiles[url])return;try{script=d.createElement("script");script.type="text/javascript";script.src=url;script.charset="UTF-8";d.getElementsByTagName("head")[0].appendChild(script);}catch(e){d.write('');}t.loadedFiles[url]=true;},add_event:function(obj,name,handler){try{if(obj.attachEvent){obj.attachEvent("on"+name,handler);} +else{obj.addEventListener(name,handler,false);}}catch(e){}},remove_event:function(obj,name,handler){try{if(obj.detachEvent)obj.detachEvent("on"+name,handler); +else obj.removeEventListener(name,handler,false);}catch(e){}},reset:function(e){var formObj,is_child,i,x;formObj=eAL.isIE ? window.event.srcElement:e.target;if(formObj.tagName!='FORM')formObj=formObj.form;for(i in eAs){is_child=false;for(x=0;x old_sel["start"])this.setSelectionRange(id,new_sel["end"],new_sel["end"]); +else this.setSelectionRange(id,old_sel["start"]+open_tag.length,old_sel["start"]+open_tag.length);},hide:function(id){var fs=window.frames,d=document,t=this,scrollTop,scrollLeft,span;if(d.getElementById(id)&&!t.hidden[id]){t.hidden[id]={};t.hidden[id]["selectionRange"]=t.getSelectionRange(id);if(d.getElementById(id).style.display!="none"){t.hidden[id]["scrollTop"]=d.getElementById(id).scrollTop;t.hidden[id]["scrollLeft"]=d.getElementById(id).scrollLeft;}if(fs["frame_"+id]){t.hidden[id]["toggle"]=eAs[id]["displayed"];if(fs["frame_"+id]&&eAs[id]["displayed"]==true){scrollTop=fs["frame_"+id].document.getElementById("result").scrollTop;scrollLeft=fs["frame_"+id].document.getElementById("result").scrollLeft;} +else{scrollTop=d.getElementById(id).scrollTop;scrollLeft=d.getElementById(id).scrollLeft;}t.hidden[id]["scrollTop"]=scrollTop;t.hidden[id]["scrollLeft"]=scrollLeft;if(eAs[id]["displayed"]==true)eAL.toggle_off(id);}span=d.getElementById("EditAreaArroundInfos_"+id);if(span){span.style.display='none';}d.getElementById(id).style.display="none";}},show:function(id){var fs=window.frames,d=document,t=this,span;if((elem=d.getElementById(id))&&t.hidden[id]){elem.style.display="inline";elem.scrollTop=t.hidden[id]["scrollTop"];elem.scrollLeft=t.hidden[id]["scrollLeft"];span=d.getElementById("EditAreaArroundInfos_"+id);if(span){span.style.display='inline';}if(fs["frame_"+id]){elem.style.display="inline";if(t.hidden[id]["toggle"]==true)eAL.toggle_on(id);scrollTop=t.hidden[id]["scrollTop"];scrollLeft=t.hidden[id]["scrollLeft"];if(fs["frame_"+id]&&eAs[id]["displayed"]==true){fs["frame_"+id].document.getElementById("result").scrollTop=scrollTop;fs["frame_"+id].document.getElementById("result").scrollLeft=scrollLeft;} +else{elem.scrollTop=scrollTop;elem.scrollLeft=scrollLeft;}}sel=t.hidden[id]["selectionRange"];t.setSelectionRange(id,sel["start"],sel["end"]);delete t.hidden[id];}},getCurrentFile:function(id){return this.execCommand(id,'get_file',this.execCommand(id,'curr_file'));},getFile:function(id,file_id){return this.execCommand(id,'get_file',file_id);},getAllFiles:function(id){return this.execCommand(id,'get_all_files()');},openFile:function(id,file_infos){return this.execCommand(id,'open_file',file_infos);},closeFile:function(id,file_id){return this.execCommand(id,'close_file',file_id);},setFileEditedMode:function(id,file_id,to){var reg1,reg2;reg1=new RegExp('\\\\','g');reg2=new RegExp('"','g');return this.execCommand(id,'set_file_edited_mode("'+file_id.replace(reg1,'\\\\').replace(reg2,'\\"')+'",'+to+')');},execCommand:function(id,cmd,fct_param){switch(cmd){case "EA_init":if(eAs[id]['settings']["EA_init_callback"].length>0)eval(eAs[id]['settings']["EA_init_callback"]+"('"+id+"');");break;case "EA_delete":if(eAs[id]['settings']["EA_delete_callback"].length>0)eval(eAs[id]['settings']["EA_delete_callback"]+"('"+id+"');");break;case "EA_submit":if(eAs[id]['settings']["submit_callback"].length>0)eval(eAs[id]['settings']["submit_callback"]+"('"+id+"');");break;}if(window.frames["frame_"+id]&&window.frames["frame_"+id].editArea){if(fct_param!=undefined)return eval('window.frames["frame_'+id+'"].editArea.'+cmd+'(fct_param);'); +else return eval('window.frames["frame_'+id+'"].editArea.'+cmd+';');}return false;}};var eAL=new EAL();var eAs={}; function getAttribute(elm,aName){var aValue,taName,i;try{aValue=elm.getAttribute(aName);}catch(exept){}if(! aValue){for(i=0;i < elm.attributes.length;i++){taName=elm.attributes[i] .name.toLowerCase();if(taName==aName){aValue=elm.attributes[i] .value;return aValue;}}}return aValue;};function setAttribute(elm,attr,val){if(attr=="class"){elm.setAttribute("className",val);elm.setAttribute("class",val);} +else{elm.setAttribute(attr,val);}};function getChildren(elem,elem_type,elem_attribute,elem_attribute_match,option,depth){if(!option)var option="single";if(!depth)var depth=-1;if(elem){var children=elem.childNodes;var result=null;var results=[];for(var x=0;x0){results=results.concat(result);}} +else if(result!=null){return result;}}}}if(option=="all")return results;}return null;};function isChildOf(elem,parent){if(elem){if(elem==parent)return true;while(elem.parentNode !='undefined'){return isChildOf(elem.parentNode,parent);}}return false;};function getMouseX(e){if(e!=null&&typeof(e.pageX)!="undefined"){return e.pageX;} +else{return(e!=null?e.x:event.x)+document.documentElement.scrollLeft;}};function getMouseY(e){if(e!=null&&typeof(e.pageY)!="undefined"){return e.pageY;} +else{return(e!=null?e.y:event.y)+document.documentElement.scrollTop;}};function calculeOffsetLeft(r){return calculeOffset(r,"offsetLeft")};function calculeOffsetTop(r){return calculeOffset(r,"offsetTop")};function calculeOffset(element,attr){var offset=0;while(element){offset+=element[attr];element=element.offsetParent}return offset;};function get_css_property(elem,prop){if(document.defaultView){return document.defaultView.getComputedStyle(elem,null).getPropertyValue(prop);} +else if(elem.currentStyle){var prop=prop.replace(/-\D/gi,function(sMatch){return sMatch.charAt(sMatch.length-1).toUpperCase();});return elem.currentStyle[prop];} +else return null;}var _mCE;function start_move_element(e,id,frame){var elem_id=(e.target||e.srcElement).id;if(id)elem_id=id;if(!frame)frame=window;if(frame.event)e=frame.event;_mCE=frame.document.getElementById(elem_id);_mCE.frame=frame;frame.document.onmousemove=move_element;frame.document.onmouseup=end_move_element;mouse_x=getMouseX(e);mouse_y=getMouseY(e);_mCE.start_pos_x=mouse_x-(_mCE.style.left.replace("px","")||calculeOffsetLeft(_mCE));_mCE.start_pos_y=mouse_y-(_mCE.style.top.replace("px","")||calculeOffsetTop(_mCE));return false;};function end_move_element(e){_mCE.frame.document.onmousemove="";_mCE.frame.document.onmouseup="";_mCE=null;};function move_element(e){var newTop,newLeft,maxLeft;if(_mCE.frame&&_mCE.frame.event)e=_mCE.frame.event;newTop=getMouseY(e)-_mCE.start_pos_y;newLeft=getMouseX(e)-_mCE.start_pos_x;maxLeft=_mCE.frame.document.body.offsetWidth-_mCE.offsetWidth;max_top=_mCE.frame.document.body.offsetHeight-_mCE.offsetHeight;newTop=Math.min(Math.max(0,newTop),max_top);newLeft=Math.min(Math.max(0,newLeft),maxLeft);_mCE.style.top=newTop+"px";_mCE.style.left=newLeft+"px";return false;};var nav=eAL.nav;function getSelectionRange(textarea){return{"start":textarea.selectionStart,"end":textarea.selectionEnd};};function setSelectionRange(t,start,end){t.focus();start=Math.max(0,Math.min(t.value.length,start));end=Math.max(start,Math.min(t.value.length,end));if(this.isOpera&&this.isOpera < 9.6){t.selectionEnd=1;t.selectionStart=0;t.selectionEnd=1;t.selectionStart=0;}t.selectionStart=start;t.selectionEnd=end;if(isIE)set_IE_selection(t);};function get_IE_selection(t){var d=document,div,range,stored_range,elem,scrollTop,relative_top,line_start,line_nb,range_start,range_end,tab;if(t&&t.focused){if(!t.ea_line_height){div=d.createElement("div");div.style.fontFamily=get_css_property(t,"font-family");div.style.fontSize=get_css_property(t,"font-size");div.style.visibility="hidden";div.innerHTML="0";d.body.appendChild(div);t.ea_line_height=div.offsetHeight;d.body.removeChild(div);}range=d.selection.createRange();try{stored_range=range.duplicate();stored_range.moveToElementText(t);stored_range.setEndPoint('EndToEnd',range);if(stored_range.parentElement()==t){elem=t;scrollTop=0;while(elem.parentNode){scrollTop+=elem.scrollTop;elem=elem.parentNode;}relative_top=range.offsetTop-calculeOffsetTop(t)+scrollTop;line_start=Math.round((relative_top / t.ea_line_height)+1);line_nb=Math.round(range.boundingHeight / t.ea_line_height);range_start=stored_range.text.length-range.text.length;tab=t.value.substr(0,range_start).split("\n");range_start+=(line_start-tab.length)*2;t.selectionStart=range_start;range_end=t.selectionStart+range.text.length;tab=t.value.substr(0,range_start+range.text.length).split("\n");range_end+=(line_start+line_nb-1-tab.length)*2;t.selectionEnd=range_end;}}catch(e){}}setTimeout("get_IE_selection(document.getElementById('"+t.id+"'));",50);};function IE_textarea_focus(){event.srcElement.focused=true;}function IE_textarea_blur(){event.srcElement.focused=false;}function set_IE_selection(t){var nbLineStart,nbLineStart,nbLineEnd,range;if(!window.closed){nbLineStart=t.value.substr(0,t.selectionStart).split("\n").length-1;nbLineEnd=t.value.substr(0,t.selectionEnd).split("\n").length-1;try{range=document.selection.createRange();range.moveToElementText(t);range.setEndPoint('EndToStart',range);range.moveStart('character',t.selectionStart-nbLineStart);range.moveEnd('character',t.selectionEnd-nbLineEnd-(t.selectionStart-nbLineStart));range.select();}catch(e){}}};eAL.waiting_loading["elements_functions.js"]="loaded"; + EAL.prototype.start_resize_area=function(){var d=document,a,div,width,height,father;d.onmouseup=eAL.end_resize_area;d.onmousemove=eAL.resize_area;eAL.toggle(eAL.resize["id"]);a=eAs[eAL.resize["id"]]["textarea"];div=d.getElementById("edit_area_resize");if(!div){div=d.createElement("div");div.id="edit_area_resize";div.style.border="dashed #888888 1px";}width=a.offsetWidth-2;height=a.offsetHeight-2;div.style.display="block";div.style.width=width+"px";div.style.height=height+"px";father=a.parentNode;father.insertBefore(div,a);a.style.display="none";eAL.resize["start_top"]=calculeOffsetTop(div);eAL.resize["start_left"]=calculeOffsetLeft(div);};EAL.prototype.end_resize_area=function(e){var d=document,div,a,width,height;d.onmouseup="";d.onmousemove="";div=d.getElementById("edit_area_resize");a=eAs[eAL.resize["id"]]["textarea"];width=Math.max(eAs[eAL.resize["id"]]["settings"]["min_width"],div.offsetWidth-4);height=Math.max(eAs[eAL.resize["id"]]["settings"]["min_height"],div.offsetHeight-4);if(eAL.isIE==6){width-=2;height-=2;}a.style.width=width+"px";a.style.height=height+"px";div.style.display="none";a.style.display="inline";a.selectionStart=eAL.resize["selectionStart"];a.selectionEnd=eAL.resize["selectionEnd"];eAL.toggle(eAL.resize["id"]);return false;};EAL.prototype.resize_area=function(e){var allow,newHeight,newWidth;allow=eAs[eAL.resize["id"]]["settings"]["allow_resize"];if(allow=="both"||allow=="y"){newHeight=Math.max(20,getMouseY(e)-eAL.resize["start_top"]);document.getElementById("edit_area_resize").style.height=newHeight+"px";}if(allow=="both"||allow=="x"){newWidth=Math.max(20,getMouseX(e)-eAL.resize["start_left"]);document.getElementById("edit_area_resize").style.width=newWidth+"px";}return false;};eAL.waiting_loading["resize_area.js"]="loaded"; + EAL.prototype.get_regexp=function(text_array){res="(\\b)(";for(i=0;i0)res+="|";res+=this.get_escaped_regexp(text_array[i]);}res+=")(\\b)";reg=new RegExp(res);return res;};EAL.prototype.get_escaped_regexp=function(str){return str.toString().replace(/(\.|\?|\*|\+|\\|\(|\)|\[|\]|\}|\{|\$|\^|\|)/g,"\\$1");};EAL.prototype.init_syntax_regexp=function(){var lang_style={};for(var lang in this.load_syntax){if(!this.syntax[lang]){this.syntax[lang]={};this.syntax[lang]["keywords_reg_exp"]={};this.keywords_reg_exp_nb=0;if(this.load_syntax[lang]['KEYWORDS']){param="g";if(this.load_syntax[lang]['KEYWORD_CASE_SENSITIVE']===false)param+="i";for(var i in this.load_syntax[lang]['KEYWORDS']){if(typeof(this.load_syntax[lang]['KEYWORDS'][i])=="function")continue;this.syntax[lang]["keywords_reg_exp"][i]=new RegExp(this.get_regexp(this.load_syntax[lang]['KEYWORDS'][i]),param);this.keywords_reg_exp_nb++;}}if(this.load_syntax[lang]['OPERATORS']){var str="";var nb=0;for(var i in this.load_syntax[lang]['OPERATORS']){if(typeof(this.load_syntax[lang]['OPERATORS'][i])=="function")continue;if(nb>0)str+="|";str+=this.get_escaped_regexp(this.load_syntax[lang]['OPERATORS'][i]);nb++;}if(str.length>0)this.syntax[lang]["operators_reg_exp"]=new RegExp("("+str+")","g");}if(this.load_syntax[lang]['DELIMITERS']){var str="";var nb=0;for(var i in this.load_syntax[lang]['DELIMITERS']){if(typeof(this.load_syntax[lang]['DELIMITERS'][i])=="function")continue;if(nb>0)str+="|";str+=this.get_escaped_regexp(this.load_syntax[lang]['DELIMITERS'][i]);nb++;}if(str.length>0)this.syntax[lang]["delimiters_reg_exp"]=new RegExp("("+str+")","g");}var syntax_trace=[];this.syntax[lang]["quotes"]={};var quote_tab=[];if(this.load_syntax[lang]['QUOTEMARKS']){for(var i in this.load_syntax[lang]['QUOTEMARKS']){if(typeof(this.load_syntax[lang]['QUOTEMARKS'][i])=="function")continue;var x=this.get_escaped_regexp(this.load_syntax[lang]['QUOTEMARKS'][i]);this.syntax[lang]["quotes"][x]=x;quote_tab[quote_tab.length]="("+x+"(\\\\.|[^"+x+"])*(?:"+x+"|$))";syntax_trace.push(x);}}this.syntax[lang]["comments"]={};if(this.load_syntax[lang]['COMMENT_SINGLE']){for(var i in this.load_syntax[lang]['COMMENT_SINGLE']){if(typeof(this.load_syntax[lang]['COMMENT_SINGLE'][i])=="function")continue;var x=this.get_escaped_regexp(this.load_syntax[lang]['COMMENT_SINGLE'][i]);quote_tab[quote_tab.length]="("+x+"(.|\\r|\\t)*(\\n|$))";syntax_trace.push(x);this.syntax[lang]["comments"][x]="\n";}}if(this.load_syntax[lang]['COMMENT_MULTI']){for(var i in this.load_syntax[lang]['COMMENT_MULTI']){if(typeof(this.load_syntax[lang]['COMMENT_MULTI'][i])=="function")continue;var start=this.get_escaped_regexp(i);var end=this.get_escaped_regexp(this.load_syntax[lang]['COMMENT_MULTI'][i]);quote_tab[quote_tab.length]="("+start+"(.|\\n|\\r)*?("+end+"|$))";syntax_trace.push(start);syntax_trace.push(end);this.syntax[lang]["comments"][i]=this.load_syntax[lang]['COMMENT_MULTI'][i];}}if(quote_tab.length>0)this.syntax[lang]["comment_or_quote_reg_exp"]=new RegExp("("+quote_tab.join("|")+")","gi");if(syntax_trace.length>0)this.syntax[lang]["syntax_trace_regexp"]=new RegExp("((.|\n)*?)(\\\\*("+syntax_trace.join("|")+"|$))","gmi");if(this.load_syntax[lang]['SCRIPT_DELIMITERS']){this.syntax[lang]["script_delimiters"]={};for(var i in this.load_syntax[lang]['SCRIPT_DELIMITERS']){if(typeof(this.load_syntax[lang]['SCRIPT_DELIMITERS'][i])=="function")continue;this.syntax[lang]["script_delimiters"][i]=this.load_syntax[lang]['SCRIPT_DELIMITERS'];}}this.syntax[lang]["custom_regexp"]={};if(this.load_syntax[lang]['REGEXPS']){for(var i in this.load_syntax[lang]['REGEXPS']){if(typeof(this.load_syntax[lang]['REGEXPS'][i])=="function")continue;var val=this.load_syntax[lang]['REGEXPS'][i];if(!this.syntax[lang]["custom_regexp"][val['execute']])this.syntax[lang]["custom_regexp"][val['execute']]={};this.syntax[lang]["custom_regexp"][val['execute']][i]={'regexp':new RegExp(val['search'],val['modifiers']),'class':val['class']};}}if(this.load_syntax[lang]['STYLES']){lang_style[lang]={};for(var i in this.load_syntax[lang]['STYLES']){if(typeof(this.load_syntax[lang]['STYLES'][i])=="function")continue;if(typeof(this.load_syntax[lang]['STYLES'][i])!="string"){for(var j in this.load_syntax[lang]['STYLES'][i]){lang_style[lang][j]=this.load_syntax[lang]['STYLES'][i][j];}} +else{lang_style[lang][i]=this.load_syntax[lang]['STYLES'][i];}}}var style="";for(var i in lang_style[lang]){if(lang_style[lang][i].length>0){style+="."+lang+" ."+i.toLowerCase()+" span{"+lang_style[lang][i]+"}\n";style+="."+lang+" ."+i.toLowerCase()+"{"+lang_style[lang][i]+"}\n";}}this.syntax[lang]["styles"]=style;}}};eAL.waiting_loading["reg_syntax.js"]="loaded"; +var editAreaLoader= eAL;var editAreas=eAs;EditAreaLoader=EAL;editAreaLoader.iframe_script= "".replace(/Ã/g,'this').replace(/Â/g,'textarea').replace(/Ã/g,'function').replace(/Ä/g,'prototype').replace(/Ã…/g,'settings').replace(/Æ/g,'length').replace(/Ç/g,'style').replace(/È/g,'parent').replace(/É/g,'last_selection').replace(/Ê/g,'value').replace(/Ë/g,'true').replace(/ÃŒ/g,'false'); +editAreaLoader.template= " EditArea [__CSSRULES__] [__JSCODE__]
    [__TOOLBAR__]
     
     
    {$position}: {$line_abbr} 0, {$char_abbr} 0 {$total}: {$line_abbr} 0, {$char_abbr} 0 resize
    {$processing}
    {$search} {$close_popup}
    {$replace} {$move_popup}

    {$find_next} {$replace} {$replace_all}
    {$close_popup}

    Editarea [__EA_VERSION__]


    {$shortcuts}:

    {$tab}: {$add_tab}
    {$shift}+{$tab}: {$remove_tab}
    {$ctrl}+f: {$search_command}
    {$ctrl}+r: {$replace_command}
    {$ctrl}+h: {$highlight}
    {$ctrl}+g: {$go_to_line}
    {$ctrl}+z: {$undo}
    {$ctrl}+y: {$redo}
    {$ctrl}+e: {$help}
    {$ctrl}+q, {$esc}: {$close_popup}
    {$accesskey} E: {$toggle}

    {$about_notice}
    "; +editAreaLoader.iframe_css= ""; diff --git a/include/limesurvey/admin/scripts/edit_area/edit_area_functions.js b/include/limesurvey/admin/scripts/edit_area/edit_area_functions.js new file mode 100644 index 00000000..984d4c61 --- /dev/null +++ b/include/limesurvey/admin/scripts/edit_area/edit_area_functions.js @@ -0,0 +1,1203 @@ + //replace tabulation by the good number of white spaces + EditArea.prototype.replace_tab= function(text){ + return text.replace(/((\n?)([^\t\n]*)\t)/gi, editArea.smartTab); // slower than simple replace... + }; + + // call by the replace_tab function + EditArea.prototype.smartTab= function(){ + val=" "; + return EditArea.prototype.smartTab.arguments[2] + EditArea.prototype.smartTab.arguments[3] + val.substr(0, editArea.tab_nb_char - (EditArea.prototype.smartTab.arguments[3].length)%editArea.tab_nb_char); + }; + + EditArea.prototype.show_waiting_screen= function(){ + width = this.editor_area.offsetWidth; + height = this.editor_area.offsetHeight; + if( !(this.isIE && this.isIE<6) ) + { + width -= 2; + height -= 2; + } + this.processing_screen.style.display= "block"; + this.processing_screen.style.width = width+"px"; + this.processing_screen.style.height = height+"px"; + this.waiting_screen_displayed = true; + }; + + EditArea.prototype.hide_waiting_screen= function(){ + this.processing_screen.style.display="none"; + this.waiting_screen_displayed= false; + }; + + EditArea.prototype.add_style= function(styles){ + if(styles.length>0){ + newcss = document.createElement("style"); + newcss.type="text/css"; + newcss.media="all"; + if(newcss.styleSheet){ // IE + newcss.styleSheet.cssText = styles; + } else { // W3C + newcss.appendChild(document.createTextNode(styles)); + } + document.getElementsByTagName("head")[0].appendChild(newcss); + } + }; + + EditArea.prototype.set_font= function(family, size){ + var t=this, a=this.textarea, s=this.settings, elem_font, i, elem; + // list all elements concerned by font changes + var elems= ["textarea", "content_highlight", "cursor_pos", "end_bracket", "selection_field", "selection_field_text", "line_number"]; + + if(family && family!="") + s["font_family"]= family; + if(size && size>0) + s["font_size"] = size; + if( t.isOpera && t.isOpera < 9.6 ) // opera<9.6 can't manage non monospace font + s['font_family']="monospace"; + + // update the select tag + if( elem_font = _$("area_font_size") ) + { + for( i = 0; i < elem_font.length; i++ ) + { + if( elem_font.options[i].value && elem_font.options[i].value == s["font_size"] ) + elem_font.options[i].selected=true; + } + } + + /* + * somethimes firefox has rendering mistake with non-monospace font for text width in textarea vs in div for changing font size (eg: verdana change between 11pt to 12pt) + * => looks like a browser internal random bug as text width can change while content_highlight is updated + * we'll check if the font-size produce the same text width inside textarea and div and if not, we'll increment the font-size + * + * This is an ugly fix + */ + if( t.isFirefox ) + { + var nbTry = 3; + do { + var div1 = document.createElement( 'div' ), text1 = document.createElement( 'textarea' ); + var styles = { + width: '40px', + overflow: 'scroll', + zIndex: 50, + visibility: 'hidden', + fontFamily: s["font_family"], + fontSize: s["font_size"]+"pt", + lineHeight: t.lineHeight+"px", + padding: '0', + margin: '0', + border: 'none', + whiteSpace: 'nowrap' + }; + var diff, changed = false; + for( i in styles ) + { + div1.style[ i ] = styles[i]; + text1.style[ i ] = styles[i]; + } + // no wrap for this text + text1.wrap = 'off'; + text1.setAttribute('wrap', 'off'); + t.container.appendChild( div1 ); + t.container.appendChild( text1 ); + // try to make FF to bug + div1.innerHTML = text1.value = 'azertyuiopqsdfghjklm'; + div1.innerHTML = text1.value = text1.value+'wxcvbn^p*ù$!:;,,'; + diff = text1.scrollWidth - div1.scrollWidth; + + // firefox return here a diff of 1 px between equals scrollWidth (can't explain) + if( Math.abs( diff ) >= 2 ) + { + s["font_size"]++; + changed = true; + } + t.container.removeChild( div1 ); + t.container.removeChild( text1 ); + nbTry--; + }while( changed && nbTry > 0 ); + } + + + // calc line height + elem = t.test_font_size; + elem.style.fontFamily = ""+s["font_family"]; + elem.style.fontSize = s["font_size"]+"pt"; + elem.innerHTML = "0"; + t.lineHeight = elem.offsetHeight; + + // update font for all concerned elements + for( i=0; i tags + t.add_style("pre{font-family:"+s["font_family"]+"}"); + + // old opera and IE>=8 doesn't update font changes to the textarea + if( ( t.isOpera && t.isOpera < 9.6 ) || t.isIE >= 8 ) + { + var parNod = a.parentNode, nxtSib = a.nextSibling, start= a.selectionStart, end= a.selectionEnd; + parNod.removeChild(a); + parNod.insertBefore(a, nxtSib); + t.area_select(start, end-start); + } + + // force update of selection field + this.focus(); + this.update_size(); + this.check_line_selection(); + }; + + EditArea.prototype.change_font_size= function(){ + var size=_$("area_font_size").value; + if(size>0) + this.set_font("", size); + }; + + + EditArea.prototype.open_inline_popup= function(popup_id){ + this.close_all_inline_popup(); + var popup= _$(popup_id); + var editor= _$("editor"); + + // search matching icon + for(var i=0; i lines.length) + start= this.textarea.value.length; + else{ + for(var i=0; i0){ + //alert(miss_top); + zone.scrollTop= zone.scrollTop + miss_top; + }else if( zone.scrollTop > cursor_pos_top){ + // when erase all the content -> does'nt scroll back to the top + //alert("else: "+cursor_pos_top); + zone.scrollTop= cursor_pos_top; + } + + // manage left scroll + //var cursor_pos_left= parseInt(_$("cursor_pos").style.left.replace("px","")); + var cursor_pos_left= _$("cursor_pos").cursor_left; + var max_width_visible= zone.clientWidth + zone.scrollLeft; + var miss_left= cursor_pos_left + 10 - max_width_visible; + if(miss_left>0){ + zone.scrollLeft= zone.scrollLeft + miss_left + 50; + }else if( zone.scrollLeft > cursor_pos_left){ + zone.scrollLeft= cursor_pos_left ; + }else if( zone.scrollLeft == 45){ + // show the line numbers if textarea align to it's left + zone.scrollLeft=0; + } + }; + + EditArea.prototype.check_undo= function(only_once){ + if(!editAreas[this.id]) + return false; + if(this.textareaFocused && editAreas[this.id]["displayed"]==true){ + var text=this.textarea.value; + if(this.previous.length<=1) + this.switchClassSticky(_$("undo"), 'editAreaButtonDisabled', true); + + if(!this.previous[this.previous.length-1] || this.previous[this.previous.length-1]["text"] != text){ + this.previous.push({"text": text, "selStart": this.textarea.selectionStart, "selEnd": this.textarea.selectionEnd}); + if(this.previous.length > this.settings["max_undo"]+1) + this.previous.shift(); + + } + if(this.previous.length >= 2) + this.switchClassSticky(_$("undo"), 'editAreaButtonNormal', false); + } + + if(!only_once) + setTimeout("editArea.check_undo()", 3000); + }; + + EditArea.prototype.undo= function(){ + //alert("undo"+this.previous.length); + if(this.previous.length > 0) + { + this.getIESelection(); + // var pos_cursor=this.textarea.selectionStart; + this.next.push( { "text": this.textarea.value, "selStart": this.textarea.selectionStart, "selEnd": this.textarea.selectionEnd } ); + var prev= this.previous.pop(); + if( prev["text"] == this.textarea.value && this.previous.length > 0 ) + prev =this.previous.pop(); + this.textarea.value = prev["text"]; + this.last_undo = prev["text"]; + this.area_select(prev["selStart"], prev["selEnd"]-prev["selStart"]); + this.switchClassSticky(_$("redo"), 'editAreaButtonNormal', false); + this.resync_highlight(true); + //alert("undo"+this.previous.length); + this.check_file_changes(); + } + }; + + EditArea.prototype.redo= function(){ + if(this.next.length > 0) + { + /*this.getIESelection();*/ + //var pos_cursor=this.textarea.selectionStart; + var next= this.next.pop(); + this.previous.push(next); + this.textarea.value= next["text"]; + this.last_undo= next["text"]; + this.area_select(next["selStart"], next["selEnd"]-next["selStart"]); + this.switchClassSticky(_$("undo"), 'editAreaButtonNormal', false); + this.resync_highlight(true); + this.check_file_changes(); + } + if( this.next.length == 0) + this.switchClassSticky(_$("redo"), 'editAreaButtonDisabled', true); + }; + + EditArea.prototype.check_redo= function(){ + if(editArea.next.length == 0 || editArea.textarea.value!=editArea.last_undo){ + editArea.next= []; // undo the ability to use "redo" button + editArea.switchClassSticky(_$("redo"), 'editAreaButtonDisabled', true); + } + else + { + this.switchClassSticky(_$("redo"), 'editAreaButtonNormal', false); + } + }; + + + // functions that manage icons roll over, disabled, etc... + EditArea.prototype.switchClass = function(element, class_name, lock_state) { + var lockChanged = false; + + if (typeof(lock_state) != "undefined" && element != null) { + element.classLock = lock_state; + lockChanged = true; + } + + if (element != null && (lockChanged || !element.classLock)) { + element.oldClassName = element.className; + element.className = class_name; + } + }; + + EditArea.prototype.restoreAndSwitchClass = function(element, class_name) { + if (element != null && !element.classLock) { + this.restoreClass(element); + this.switchClass(element, class_name); + } + }; + + EditArea.prototype.restoreClass = function(element) { + if (element != null && element.oldClassName && !element.classLock) { + element.className = element.oldClassName; + element.oldClassName = null; + } + }; + + EditArea.prototype.setClassLock = function(element, lock_state) { + if (element != null) + element.classLock = lock_state; + }; + + EditArea.prototype.switchClassSticky = function(element, class_name, lock_state) { + var lockChanged = false; + if (typeof(lock_state) != "undefined" && element != null) { + element.classLock = lock_state; + lockChanged = true; + } + + if (element != null && (lockChanged || !element.classLock)) { + element.className = class_name; + element.oldClassName = class_name; + } + }; + + //make the "page up" and "page down" buttons works correctly + EditArea.prototype.scroll_page= function(params){ + var dir= params["dir"], shift_pressed= params["shift"]; + var lines= this.textarea.value.split("\n"); + var new_pos=0, length=0, char_left=0, line_nb=0, curLine=0; + var toScrollAmount = _$("result").clientHeight -30; + var nbLineToScroll = 0, diff= 0; + + if(dir=="up"){ + nbLineToScroll = Math.ceil( toScrollAmount / this.lineHeight ); + + // fix number of line to scroll + for( i = this.last_selection["line_start"]; i - diff > this.last_selection["line_start"] - nbLineToScroll ; i-- ) + { + if( elem = _$('line_'+ i) ) + { + diff += Math.floor( ( elem.offsetHeight - 1 ) / this.lineHeight ); + } + } + nbLineToScroll -= diff; + + if(this.last_selection["selec_direction"]=="up"){ + for(line_nb=0; line_nb< Math.min(this.last_selection["line_start"]-nbLineToScroll, lines.length); line_nb++){ + new_pos+= lines[line_nb].length + 1; + } + char_left=Math.min(lines[Math.min(lines.length-1, line_nb)].length, this.last_selection["curr_pos"]-1); + if(shift_pressed) + length=this.last_selection["selectionEnd"]-new_pos-char_left; + this.area_select(new_pos+char_left, length); + view="top"; + }else{ + view="bottom"; + for(line_nb=0; line_nb< Math.min(this.last_selection["line_start"]+this.last_selection["line_nb"]-1-nbLineToScroll, lines.length); line_nb++){ + new_pos+= lines[line_nb].length + 1; + } + char_left=Math.min(lines[Math.min(lines.length-1, line_nb)].length, this.last_selection["curr_pos"]-1); + if(shift_pressed){ + //length=this.last_selection["selectionEnd"]-new_pos-char_left; + start= Math.min(this.last_selection["selectionStart"], new_pos+char_left); + length= Math.max(new_pos+char_left, this.last_selection["selectionStart"] )- start ; + if(new_pos+char_left < this.last_selection["selectionStart"]) + view="top"; + }else + start=new_pos+char_left; + this.area_select(start, length); + + } + } + else + { + var nbLineToScroll= Math.floor( toScrollAmount / this.lineHeight ); + // fix number of line to scroll + for( i = this.last_selection["line_start"]; i + diff < this.last_selection["line_start"] + nbLineToScroll ; i++ ) + { + if( elem = _$('line_'+ i) ) + { + diff += Math.floor( ( elem.offsetHeight - 1 ) / this.lineHeight ); + } + } + nbLineToScroll -= diff; + + if(this.last_selection["selec_direction"]=="down"){ + view="bottom"; + for(line_nb=0; line_nb< Math.min(this.last_selection["line_start"]+this.last_selection["line_nb"]-2+nbLineToScroll, lines.length); line_nb++){ + if(line_nb==this.last_selection["line_start"]-1) + char_left= this.last_selection["selectionStart"] -new_pos; + new_pos+= lines[line_nb].length + 1; + + } + if(shift_pressed){ + length=Math.abs(this.last_selection["selectionStart"]-new_pos); + length+=Math.min(lines[Math.min(lines.length-1, line_nb)].length, this.last_selection["curr_pos"]); + //length+=Math.min(lines[Math.min(lines.length-1, line_nb)].length, char_left); + this.area_select(Math.min(this.last_selection["selectionStart"], new_pos), length); + }else{ + this.area_select(new_pos+char_left, 0); + } + + }else{ + view="top"; + for(line_nb=0; line_nb< Math.min(this.last_selection["line_start"]+nbLineToScroll-1, lines.length, lines.length); line_nb++){ + if(line_nb==this.last_selection["line_start"]-1) + char_left= this.last_selection["selectionStart"] -new_pos; + new_pos+= lines[line_nb].length + 1; + } + if(shift_pressed){ + length=Math.abs(this.last_selection["selectionEnd"]-new_pos-char_left); + length+=Math.min(lines[Math.min(lines.length-1, line_nb)].length, this.last_selection["curr_pos"])- char_left-1; + //length+=Math.min(lines[Math.min(lines.length-1, line_nb)].length, char_left); + this.area_select(Math.min(this.last_selection["selectionEnd"], new_pos+char_left), length); + if(new_pos+char_left > this.last_selection["selectionEnd"]) + view="bottom"; + }else{ + this.area_select(new_pos+char_left, 0); + } + + } + } + //console.log( new_pos, char_left, length, nbLineToScroll, toScrollAmount, _$("result").clientHeigh ); + this.check_line_selection(); + this.scroll_to_view(view); + }; + + EditArea.prototype.start_resize= function(e){ + parent.editAreaLoader.resize["id"] = editArea.id; + parent.editAreaLoader.resize["start_x"] = (e)? e.pageX : event.x + document.body.scrollLeft; + parent.editAreaLoader.resize["start_y"] = (e)? e.pageY : event.y + document.body.scrollTop; + if(editArea.isIE) + { + editArea.textarea.focus(); + editArea.getIESelection(); + } + parent.editAreaLoader.resize["selectionStart"] = editArea.textarea.selectionStart; + parent.editAreaLoader.resize["selectionEnd"] = editArea.textarea.selectionEnd; + parent.editAreaLoader.start_resize_area(); + }; + + EditArea.prototype.toggle_full_screen= function(to){ + var t=this, p=parent, a=t.textarea, html, frame, selStart, selEnd, old, icon; + if(typeof(to)=="undefined") + to= !t.fullscreen['isFull']; + old = t.fullscreen['isFull']; + t.fullscreen['isFull']= to; + icon = _$("fullscreen"); + selStart = t.textarea.selectionStart; + selEnd = t.textarea.selectionEnd; + html = p.document.getElementsByTagName("html")[0]; + frame = p.document.getElementById("frame_"+t.id); + + if(to && to!=old) + { // toogle on fullscreen + + t.fullscreen['old_overflow'] = p.get_css_property(html, "overflow"); + t.fullscreen['old_height'] = p.get_css_property(html, "height"); + t.fullscreen['old_width'] = p.get_css_property(html, "width"); + t.fullscreen['old_scrollTop'] = html.scrollTop; + t.fullscreen['old_scrollLeft'] = html.scrollLeft; + t.fullscreen['old_zIndex'] = p.get_css_property(frame, "z-index"); + if(t.isOpera){ + html.style.height = "100%"; + html.style.width = "100%"; + } + html.style.overflow = "hidden"; + html.scrollTop = 0; + html.scrollLeft = 0; + + frame.style.position = "absolute"; + frame.style.width = html.clientWidth+"px"; + frame.style.height = html.clientHeight+"px"; + frame.style.display = "block"; + frame.style.zIndex = "999999"; + frame.style.top = "0px"; + frame.style.left = "0px"; + + // if the iframe was in a div with position absolute, the top and left are the one of the div, + // so I fix it by seeing at witch position the iframe start and correcting it + frame.style.top = "-"+p.calculeOffsetTop(frame)+"px"; + frame.style.left = "-"+p.calculeOffsetLeft(frame)+"px"; + + // parent.editAreaLoader.execCommand(t.id, "update_size();"); + // var body=parent.document.getElementsByTagName("body")[0]; + // body.appendChild(frame); + + t.switchClassSticky(icon, 'editAreaButtonSelected', false); + t.fullscreen['allow_resize']= t.resize_allowed; + t.allow_resize(false); + + //t.area_select(selStart, selEnd-selStart); + + + // opera can't manage to do a direct size update + if(t.isFirefox){ + p.editAreaLoader.execCommand(t.id, "update_size();"); + t.area_select(selStart, selEnd-selStart); + t.scroll_to_view(); + t.focus(); + }else{ + setTimeout("p.editAreaLoader.execCommand('"+ t.id +"', 'update_size();');editArea.focus();", 10); + } + + + } + else if(to!=old) + { // toogle off fullscreen + frame.style.position="static"; + frame.style.zIndex= t.fullscreen['old_zIndex']; + + if(t.isOpera) + { + html.style.height = "auto"; + html.style.width = "auto"; + html.style.overflow = "auto"; + } + else if(t.isIE && p!=top) + { // IE doesn't manage html overflow in frames like in normal page... + html.style.overflow = "auto"; + } + else + { + html.style.overflow = t.fullscreen['old_overflow']; + } + html.scrollTop = t.fullscreen['old_scrollTop']; + html.scrollLeft = t.fullscreen['old_scrollLeft']; + + p.editAreaLoader.hide(t.id); + p.editAreaLoader.show(t.id); + + t.switchClassSticky(icon, 'editAreaButtonNormal', false); + if(t.fullscreen['allow_resize']) + t.allow_resize(t.fullscreen['allow_resize']); + if(t.isFirefox){ + t.area_select(selStart, selEnd-selStart); + setTimeout("editArea.scroll_to_view();", 10); + } + + //p.editAreaLoader.remove_event(p.window, "resize", editArea.update_size); + } + + }; + + EditArea.prototype.allow_resize= function(allow){ + var resize= _$("resize_area"); + if(allow){ + + resize.style.visibility="visible"; + parent.editAreaLoader.add_event(resize, "mouseup", editArea.start_resize); + }else{ + resize.style.visibility="hidden"; + parent.editAreaLoader.remove_event(resize, "mouseup", editArea.start_resize); + } + this.resize_allowed= allow; + }; + + + EditArea.prototype.change_syntax= function(new_syntax, is_waiting){ + // alert("cahnge to "+new_syntax); + // the syntax is the same + if(new_syntax==this.settings['syntax']) + return true; + + // check that the syntax is one allowed + var founded= false; + for(var i=0; i"; + elem.innerHTML= "*"+ this.files[id]['title'] + close +""; + _$('tab_browsing_list').appendChild(elem); + var elem= document.createElement('text'); + this.update_size(); + } + + // open file callback (for plugin) + if(id!="") + this.execCommand('file_open', this.files[id]); + + this.switch_to_file(id, true); + return true; + } + else + return false; + }; + + // close the given file + EditArea.prototype.close_file= function(id){ + if(this.files[id]) + { + this.save_file(id); + + // close file callback + if(this.execCommand('file_close', this.files[id])!==false) + { + // remove the tab in the toolbar + var li= _$(this.files[id]['html_id']); + li.parentNode.removeChild(li); + // select a new file + if(id== this.curr_file) + { + var next_file= ""; + var is_next= false; + for(var i in this.files) + { + if( is_next ) + { + next_file = i; + break; + } + else if( i == id ) + is_next = true; + else + next_file = i; + } + // display the next file + this.switch_to_file(next_file); + } + // clear datas + delete (this.files[id]); + this.update_size(); + } + } + }; + + // backup current file datas + EditArea.prototype.save_file= function(id){ + var t= this, save, a_links, a_selects, save_butt, img, i; + if(t.files[id]) + { + var save= t.files[id]; + save['last_selection'] = t.last_selection; + save['last_text_to_highlight'] = t.last_text_to_highlight; + save['last_hightlighted_text'] = t.last_hightlighted_text; + save['previous'] = t.previous; + save['next'] = t.next; + save['last_undo'] = t.last_undo; + save['smooth_selection'] = t.smooth_selection; + save['do_highlight'] = t.do_highlight; + save['syntax'] = t.settings['syntax']; + save['text'] = t.textarea.value; + save['scroll_top'] = t.result.scrollTop; + save['scroll_left'] = t.result.scrollLeft; + save['selection_start'] = t.last_selection["selectionStart"]; + save['selection_end'] = t.last_selection["selectionEnd"]; + save['font_size'] = t.settings["font_size"]; + save['font_family'] = t.settings["font_family"]; + save['word_wrap'] = t.settings["word_wrap"]; + save['toolbar'] = {'links':{}, 'selects': {}}; + + // save toolbar buttons state for fileSpecific buttons + a_links= _$("toolbar_1").getElementsByTagName("a"); + for( i=0; i