2
0
mirror of https://github.com/ACSPRI/queXS synced 2024-04-02 12:12:16 +00:00

Merged from McMasterReports branch

This commit is contained in:
azammitdcarf
2010-01-14 07:45:37 +00:00
parent 18dbb16138
commit d1b139d315
1884 changed files with 555891 additions and 364768 deletions

View File

@@ -72,5 +72,6 @@ T_("Thursday");
T_("Friday"); T_("Friday");
T_("Saturday"); T_("Saturday");
T_("Sunday"); T_("Sunday");
T_("Quota filled");
?> ?>

View File

@@ -64,6 +64,8 @@ print "<li><a href=\"javascript:link('mainobj','dataoutput.php');\">" . T_("Data
print "<li><h3>" . T_("Questionnaire progress") . "</h3>"; print "<li><h3>" . T_("Questionnaire progress") . "</h3>";
print "<ul><li><a href=\"javascript:link('mainobj','displayappointments.php');\">" . T_("Display all future appointments") . "</a></li>"; print "<ul><li><a href=\"javascript:link('mainobj','displayappointments.php');\">" . T_("Display all future appointments") . "</a></li>";
print "<li><a href=\"javascript:link('mainobj','samplecallattempts.php');\">" . T_("Sample call attempts report") . "</a></li>";
print "<li><a href=\"javascript:link('mainobj','quotareport.php');\">" . T_("Quota report") . "</a></li>";
print "<li><a href=\"javascript:link('mainobj','outcomes.php');\">" . T_("Questionnaire outcomes") . "</a></li></ul></li>"; print "<li><a href=\"javascript:link('mainobj','outcomes.php');\">" . T_("Questionnaire outcomes") . "</a></li></ul></li>";
print "<li><h3>" . T_("Performance") . "</h3>"; print "<li><h3>" . T_("Performance") . "</h3>";

View File

@@ -96,10 +96,11 @@ if (isset($_POST['import_file']))
if ($rs) if ($rs)
{ {
$qid = $db->Insert_ID(); $qid = $db->Insert_ID();
print "<p>Successfully inserted $name as questionnaire $qid, linked to $lime_sid</p>"; print "<p>" . T_("Successfully inserted") . " $name " . T_("as questionnaire") . " $qid, " . T_("linked to") . " $lime_sid</p>";
print "<p>" . T_("You must now edit and activate the questionnaire") . "</p>";
}else }else
{ {
print "<p>Error: Failed to insert questionnaire</p>"; print "<p>" . T_("Error: Failed to insert questionnaire") . "</p>";
} }

View File

@@ -64,12 +64,11 @@ include("../functions/functions.input.php");
*/ */
include("../functions/functions.operator.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 "<h2>" . T_("Overall") . "</h2>"; print "<h2>" . T_("Overall") . "</h2>";
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")));
xhtml_table(get_effectiveness(),array("firstName","effectiveness"),array(T_("Operator"),T_("Effectiveness (proportion of time on a call in a case)")),"tclass");
$questionnaire_id = false; $questionnaire_id = false;
if (isset($_GET['questionnaire_id'])) $questionnaire_id = bigintval($_GET['questionnaire_id']); if (isset($_GET['questionnaire_id'])) $questionnaire_id = bigintval($_GET['questionnaire_id']);
@@ -77,10 +76,9 @@ display_questionnaire_chooser($questionnaire_id);
if ($questionnaire_id) if ($questionnaire_id)
{ {
$rs = get_CPH_by_questionnaire($questionnaire_id); $rs = get_stats_total(get_stats_by_questionnaire($questionnaire_id));
print "<h2>" . T_("This project") . "</h2>"; print "<h2>" . T_("This project") . "</h2>";
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")));
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");
$operator_id = get_operator_id(); $operator_id = get_operator_id();
@@ -99,9 +97,9 @@ if ($questionnaire_id)
if ($shift_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 "<h2>" . T_("This shift") . "</h2>"; print "<h2>" . T_("This shift") . "</h2>";
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")));
} }
} }

View File

@@ -69,7 +69,7 @@ include ("../functions/functions.operator.php");
*/ */
include("../functions/functions.input.php"); include("../functions/functions.input.php");
$operator_id = get_operator_id(); $admin_operator_id = get_operator_id();
$questionnaire_id = false; $questionnaire_id = false;
if (isset($_GET['questionnaire_id'])) $questionnaire_id = bigintval($_GET['questionnaire_id']); if (isset($_GET['questionnaire_id'])) $questionnaire_id = bigintval($_GET['questionnaire_id']);
@@ -122,7 +122,7 @@ if ($questionnaire_id != false)
print "</table>"; print "</table>";
$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 FROM `case` AS c, `outcome` AS o
WHERE c.questionnaire_id = '$questionnaire_id' WHERE c.questionnaire_id = '$questionnaire_id'
AND c.current_outcome_id = o.outcome_id AND c.current_outcome_id = o.outcome_id
@@ -133,75 +133,111 @@ if ($questionnaire_id != false)
if (!empty($rs)) if (!empty($rs))
{ {
translate_array($rs,array("des")); 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 "<h2>" . T_("Operator") . ": " . "</h2>";
if(!empty($r))
display_chooser($r,"operator_id","operator_id",true,"questionnaire_id=$questionnaire_id");
if ($operator_id != false)
{
print "<p>" . T_("Operator call outcomes") . "</p>";
$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 "<h2>" . T_("Sample") . ": " . "</h2>";
if(!empty($r))
display_chooser($r,"sample_import_id","sample_import_id",true,"questionnaire_id=$questionnaire_id");
if ($sample_import_id != false)
{
print "<p>" . T_("Sample status") . "</p>";
$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 "<p>" . T_("Outcomes") . "</p>";
$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 "<p>" . T_("No outcomes recorded for this sample") . "</p>";
}
} }
else else
print "<p>" . T_("No outcomes recorded for this questionnaire") . "</p>"; print "<p>" . T_("No outcomes recorded for this questionnaire") . "</p>";
$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 "<h2>" . T_("Sample") . ": " . "</h2>";
if(!empty($r))
display_chooser($r,"sample_import_id","sample_import_id",true,"questionnaire_id=$questionnaire_id");
if ($sample_import_id != false)
{
print "<p>" . T_("Sample status") . "</p>";
$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 "<p>" . T_("Outcomes") . "</p>";
$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 "<p>" . T_("No outcomes recorded for this sample") . "</p>";
}
//display a list of shifts with completions and a link to either add a report or view reports //display a list of shifts with completions and a link to either add a report or view reports
print "<h2>" . T_("Shifts") . "</h2>"; print "<h2>" . T_("Shifts") . "</h2>";
$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, $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('<a href=\'shiftreport.php?questionnaire_id=$questionnaire_id&amp;shift_id=', s.shift_id, '&amp;createnewreport=yes\'>" . T_("No shift reports: Add report") . "</a>') ELSE CONCAT('<a href=\'shiftreport.php?questionnaire_id=$questionnaire_id&amp;shift_id=', s.shift_id, '\'>" . T_("View shift reports") . "</a>') END AS link, c.completions as completions, CONCAT('<a href=\'operatorperformance.php?questionnaire_id=$questionnaire_id&amp;shift_id=', s.shift_id, '\'>" . T_("View operator performance") . "</a>') as operform CASE WHEN sr.shift_id IS NULL THEN CONCAT('<a href=\'shiftreport.php?questionnaire_id=$questionnaire_id&amp;shift_id=', s.shift_id, '&amp;createnewreport=yes\'>" . T_("No shift reports: Add report") . "</a>') ELSE CONCAT('<a href=\'shiftreport.php?questionnaire_id=$questionnaire_id&amp;shift_id=', s.shift_id, '\'>" . T_("View shift reports") . "</a>') END AS link, c.completions as completions, CONCAT('<a href=\'operatorperformance.php?questionnaire_id=$questionnaire_id&amp;shift_id=', s.shift_id, '\'>" . T_("View operator performance") . "</a>') as operform
FROM `shift` as s 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 shift_report as sr on (sr.shift_id = s.shift_id)
LEFT JOIN ( SELECT count(*) as completions,sh.shift_id LEFT JOIN ( SELECT count(*) as completions,sh.shift_id
FROM `call` as a, `case` as b, shift as sh FROM `call` as a, `case` as b, shift as sh

245
admin/quotareport.php Normal file
View File

@@ -0,0 +1,245 @@
<?php
/**
* Display a report of all quota's
* 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
* c. (Questionnaire quota) Monitor outcomes of questions in completed questionnaires, and abort interview when completion limit is reached
*
*
* This file is part of queXS
*
* queXS 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.
*
* queXS 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 queXS; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*
* @author Adam Zammit <adam.zammit@acspri.org.au>
* @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 "<h2>" . T_("Select a questionnaire from the list below") . "</h2>";
$questionnaire_id = false;
if (isset($_GET['questionnaire_id'])) $questionnaire_id = bigintval($_GET['questionnaire_id']);
display_questionnaire_chooser($questionnaire_id);
if ($questionnaire_id)
{
print "<h2>" . T_("Select a sample from the list below") . "</h2>";
$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 = "<a href='?questionnaire_id=$questionnaire_id&amp;sample_import_id=$sample_import_id&amp;rowquota={$v['questionnaire_sample_quota_row_id']}&amp;open=open'>" . T_("closed") . "</a>";
else
$status = "<a href='?questionnaire_id=$questionnaire_id&amp;sample_import_id=$sample_import_id&amp;rowquota={$v['questionnaire_sample_quota_row_id']}&amp;close=close'>" . T_("open") . "</a>";
}
else
{
if ($v['quota_reached'] == 1)
$status = T_("closed");
else
$status = T_("open");
}
$report[] = array("strata" => "<a href='quotarow.php?questionnaire_id=$questionnaire_id&amp;sample_import_id=$sample_import_id'>" . $v['description'] . "</a>", "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" => "<a href='" . LIME_URL . "/admin/admin.php?action=quotas&sid={$r['sid']}&quota_id={$r['id']}&subaction=quota_editquota'>" . $r['name'] . "</a>", "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();
?>

View File

@@ -69,22 +69,29 @@ include("../functions/functions.operator.php");
global $db; 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'])) 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 //need to add quota
$value = -1;
$comparison = -1;
$completions = -1;
$sgqa = -1;
$questionnaire_id = bigintval($_GET['questionnaire_id']); $questionnaire_id = bigintval($_GET['questionnaire_id']);
$sample_import_id = bigintval($_GET['sample_import_id']); $sample_import_id = bigintval($_GET['sample_import_id']);
$value = $db->quote($_GET['value']); if ($_GET['sgqa'] != -1)
$completions = $db->quote($_GET['completions']); {
$sgqa = $db->quote($_GET['sgqa']); $sgqa = $db->quote($_GET['sgqa']);
$comparison = $db->quote($_GET['comparison']); $comparison = $db->quote($_GET['comparison']);
$value = $db->quote($_GET['value']);
$completions = $db->quote($_GET['completions']);
}
$exclude_val = $db->quote($_GET['exclude_val']); $exclude_val = $db->quote($_GET['exclude_val']);
$exclude_var = $db->quote($_GET['exclude_var']); $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) $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)"; VALUES ($questionnaire_id, $sample_import_id, $sgqa, $value, $completions, $comparison, $exclude_var, $exclude_val, $description)";
$db->Execute($sql); $db->Execute($sql);
@@ -99,20 +106,7 @@ if (isset($_GET['questionnaire_id']) && isset($_GET['questionnaire_sample_quota_
$questionnaire_id = bigintval($_GET['questionnaire_id']); $questionnaire_id = bigintval($_GET['questionnaire_id']);
$questionnaire_sample_quota_row_id = bigintval($_GET['questionnaire_sample_quota_row_id']); $questionnaire_sample_quota_row_id = bigintval($_GET['questionnaire_sample_quota_row_id']);
$db->StartTrans(); open_row_quota($questionnaire_sample_quota_row_id);
$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();
} }
$questionnaire_id = false; $questionnaire_id = false;
@@ -142,6 +136,12 @@ if ($questionnaire_id != false)
if ($sample_import_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 "<h3>" . T_("Copied quotas") . "</h3>";
}
print "<h1>" . T_("Current row quotas (click to delete)") . "</h1>"; print "<h1>" . T_("Current row quotas (click to delete)") . "</h1>";
$sql = "SELECT questionnaire_sample_quota_row_id,lime_sgqa,value,completions,quota_reached,lime_sid,comparison,exclude_var,exclude_val $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) foreach($r as $v)
{ {
print "<div><a href='?questionnaire_id=$questionnaire_id&amp;sample_import_id=$sample_import_id&amp;questionnaire_sample_quota_row_id={$v['questionnaire_sample_quota_row_id']}'>" . 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") ."</a> - "; if ($v['lime_sgqa'] == -1)
print "<div><a href='?questionnaire_id=$questionnaire_id&amp;sample_import_id=$sample_import_id&amp;questionnaire_sample_quota_row_id={$v['questionnaire_sample_quota_row_id']}'>" . T_("Replicate: Where") . " " . $v['exclude_var'] . " " . T_("like") . " " . $v['exclude_val'] . "</a> - ";
else
print "<div><a href='?questionnaire_id=$questionnaire_id&amp;sample_import_id=$sample_import_id&amp;questionnaire_sample_quota_row_id={$v['questionnaire_sample_quota_row_id']}'>" . 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") ."</a> - ";
if ($v['quota_reached'] == 1) if ($v['quota_reached'] == 1)
print T_("Row quota reached"); print T_("Row quota reached (Closed)");
else 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 "</div>"; print "</div>";
} }
$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 "<form action='?questionnaire_id=$questionnaire_id&amp;sample_import_id=$sample_import_id' method='post'><p>" . 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 "<input type='submit' id='submit' value='" . T_("Copy") . "'/></p></form>";
}
} }
@@ -193,8 +214,13 @@ if ($questionnaire_id != false)
LEFT JOIN `" . LIME_PREFIX . "answers` AS a ON ( a.qid = q.qid ) LEFT JOIN `" . LIME_PREFIX . "answers` AS a ON ( a.qid = q.qid )
WHERE q.sid = '$lime_sid'"; WHERE q.sid = '$lime_sid'";
$rs = $db->GetAll($sql);
display_chooser($db->GetAll($sql),"sgqa","sgqa",true,"questionnaire_id=$questionnaire_id&amp;sample_import_id=$sample_import_id"); $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&amp;sample_import_id=$sample_import_id");
if ($sgqa != false) if ($sgqa != false)
{ {
@@ -236,9 +262,16 @@ if ($questionnaire_id != false)
?> ?>
<form action="" method="get"> <form action="" method="get">
<p> <p>
<label for="description"><? echo T_("Describe this quota"); ?> </label><input type="text" name="description" id="description"/> <br/>
<? if ($sgqa != -1) { ?>
<label for="value"><? echo T_("The code value to compare"); ?> </label><input type="text" name="value" id="value"/> <br/> <label for="value"><? echo T_("The code value to compare"); ?> </label><input type="text" name="value" id="value"/> <br/>
<label for="comparison"><? echo T_("The type of comparison"); ?></label><select name="comparison" id="comparison"><option value="LIKE">LIKE</option><option value="NOT LIKE">NOT LIKE</option><option value="=">=</option><option value="!=">!=</option><option value="&lt;">&lt;</option><option value="&gt;">&gt;</option><option value="&lt;=">&lt;=</option><option value="&gt;=">&gt;=</option></select><br/> <label for="comparison"><? echo T_("The type of comparison"); ?></label><select name="comparison" id="comparison"><option value="LIKE">LIKE</option><option value="NOT LIKE">NOT LIKE</option><option value="=">=</option><option value="!=">!=</option><option value="&lt;">&lt;</option><option value="&gt;">&gt;</option><option value="&lt;=">&lt;=</option><option value="&gt;=">&gt;=</option></select><br/>
<label for="completions"><? echo T_("The number of completions to stop calling at"); ?> </label><input type="text" name="completions" id="completions"/> <br/> <label for="completions"><? echo T_("The number of completions to stop calling at"); ?> </label><input type="text" name="completions" id="completions"/> <br/>
<? } else { ?>
<input type="hidden" name="value" value="-1"/>
<input type="hidden" name="comparison" value="-1"/>
<input type="hidden" name="completions" value="-1"/>
<? } ?>
<label for="exclude_val"><? echo T_("Exclude from the sample where the value is like"); ?></label> <label for="exclude_val"><? echo T_("Exclude from the sample where the value is like"); ?></label>
<? <?

View File

@@ -0,0 +1,130 @@
<?php
/**
* Display sample call attempt report (A listing of how many attempts made for cases within a sample)
*
*
* This file is part of queXS
*
* queXS 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.
*
* queXS 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 queXS; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*
* @author Adam Zammit <adam.zammit@acspri.org.au>
* @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 "<h2>" . T_("Overall") . "</h2>";
$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 "<h2>" . T_("This project") . "</h2>";
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 "<h2>" . T_("This sample") . "</h2>";
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 "<h2>" . T_("This quota") . "</h2>";
xhtml_table($db->GetAll($sql),array("sample","callattempts"),array(T_("Number of cases"),T_("Call attempts made")),"tclass",false,array("sample"));
}
}
}
xhtml_foot();
?>

View File

@@ -83,6 +83,12 @@ function display_outcomes($contacted,$ca,$case_id)
FROM outcome FROM outcome
WHERE outcome_id = 10"; WHERE outcome_id = 10";
} }
else if (limesurvey_is_quota_full($case_id))
{
$sql = "SELECT outcome_id,description
FROM outcome
WHERE outcome_id = 32";
}
else else
{ {
//see if we have made an appointment on this call attempt //see if we have made an appointment on this call attempt

View File

@@ -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(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(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(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_var` char(128) collate utf8_unicode_ci NOT NULL,
`exclude_val` varchar(256) collate utf8_unicode_ci NOT NULL, `exclude_val` varchar(256) collate utf8_unicode_ci NOT NULL,
`quota_reached` tinyint(1) NOT NULL default '0', `quota_reached` tinyint(1) NOT NULL default '0',
`description` text collate utf8_unicode_ci NOT NULL,
PRIMARY KEY (`questionnaire_sample_quota_row_id`), PRIMARY KEY (`questionnaire_sample_quota_row_id`),
KEY `questionnaire_id` (`questionnaire_id`), KEY `questionnaire_id` (`questionnaire_id`),
KEY `sample_import_id` (`sample_import_id`), KEY `sample_import_id` (`sample_import_id`),

View File

@@ -104,7 +104,6 @@ function display_shift_chooser($questionnaire_id, $shift_id = false)
print "</select></div>"; print "</select></div>";
} }
/** /**
* Display a list of samples to choose from in a drop down list * 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 "</select></div>"; print "</select></div>";
} }
/**
* 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 "<div><select id='questionnaire_sample_quota_row_id' name='questionnaire_sample_quota_row_id' onchange=\"LinkUp('questionnaire_sample_quota_row_id')\"><option value='?questionnaire_id=$questionnaire_id&amp;sample_import_id=$sample_import_id'></option>";
if (!empty($rs))
{
foreach($rs as $r)
{
print "<option value='?sample_import_id=$sample_import_id&amp;questionnaire_id=$questionnaire_id&amp;questionnaire_sample_quota_row_id={$r['questionnaire_sample_quota_row_id']}' {$r['selected']}>{$r['questionnaire_sample_quota_row_id']}: {$r['description']}</option>";
}
}
print "</select></div>";
}
?> ?>

View File

@@ -42,6 +42,40 @@ include_once(dirname(__FILE__).'/../config.inc.php');
*/ */
include_once(dirname(__FILE__).'/../db.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 * 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; 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 * Taken from common.php in the LimeSurvey package
@@ -133,33 +232,33 @@ function create_limesurvey_questionnaire($title)
while (!empty($isresult) && $isresult->RecordCount() > 0); while (!empty($isresult) && $isresult->RecordCount() > 0);
$isquery = "INSERT INTO ". LIME_PREFIX ."surveys\n" $isquery = "INSERT INTO ". LIME_PREFIX ."surveys\n"
. "(sid, owner_id, admin, active, useexpiry, expires, " . "(sid, owner_id, admin, active, expires, "
. "adminemail, private, faxto, format, template, url, " . "adminemail, private, faxto, format, template, "
. "language, datestamp, ipaddr, refurl, usecookie, notification, allowregister, attribute1, attribute2, " . "language, datestamp, ipaddr, refurl, usecookie, notification, allowregister, "
. "allowsave, autoredirect, allowprev,datecreated,tokenanswerspersistence)\n" . "allowsave, autoredirect, allowprev,datecreated,tokenanswerspersistence)\n"
. "VALUES ($surveyid, 1,\n" . "VALUES ($surveyid, 1,\n"
. "'', 'N', \n" . "'', 'N', \n"
. "'N','1980-01-01', '', 'N',\n" . "NULL, '', 'N',\n"
. "'', 'S', 'quexs', '" . QUEXS_URL . "rs_project_end.php',\n" . "'', 'S', 'quexs',\n"
. "'en', 'Y', 'N', 'N',\n" . "'" . DEFAULT_LOCALE . "', 'Y', 'N', 'N',\n"
. "'N', '0', 'Y',\n" . "'N', '0', 'Y',\n"
. "'att1', 'att2', \n"
. "'Y', 'Y', 'Y','".date("Y-m-d")."','Y')"; . "'Y', 'Y', 'Y','".date("Y-m-d")."','Y')";
$isresult = $db->Execute($isquery); $isresult = $db->Execute($isquery) or die ($isquery."<br/>".$db->ErrorMsg());
// insert base language into surveys_language_settings // insert base language into surveys_language_settings
$isquery = "INSERT INTO ".db_table_name('surveys_languagesettings') $isquery = "INSERT INTO ".db_table_name('surveys_languagesettings')
. "(surveyls_survey_id, surveyls_language, surveyls_title, surveyls_description, surveyls_welcometext, surveyls_urldescription, " . "(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_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" . "surveyls_email_register_subj, surveyls_email_register, surveyls_email_confirm_subj, surveyls_email_confirm,surveyls_url)\n"
. "VALUES ($surveyid, 'en', $title, $title,\n" . "VALUES ($surveyid, '" . DEFAULT_LOCALE . "', $title, $title,\n"
. "'',\n" . "'',\n"
. "'', '',\n" . "'', '',\n"
. "'', '',\n" . "'', '',\n"
. "'', '',\n" . "'', '',\n"
. "'', '',\n" . "'', '',\n"
. "'')"; . "'', '" . QUEXS_URL . "rs_project_end.php')";
$isresult = $db->Execute($isquery); $isresult = $db->Execute($isquery) or die ($isquery."<br/>".$db->ErrorMsg());
// Insert into survey_rights // Insert into survey_rights
$isrquery = "INSERT INTO ". LIME_PREFIX . "surveys_rights VALUES($surveyid,1,1,1,1,1,1,1)"; $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']; 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 * Check if LimeSurvey has marked a questionnaire as complete
@@ -271,12 +396,9 @@ function limesurvey_is_completed($case_id)
$r = $db->GetRow($sql); $r = $db->GetRow($sql);
if (!empty($r)) if (!empty($r))
if ($r['completed'] != 'N') return true; if ($r['completed'] != 'N' && $r['completed'] != 'Q') return true;
return false; return false;
} }

View File

@@ -464,8 +464,8 @@ function get_case_id($operator_id, $create = false)
if ($lime_sid) if ($lime_sid)
{ {
$sql = "INSERT INTO ".LIME_PREFIX."tokens_$lime_sid (tid,firstname,lastname,email,token,language,sent,completed,attribute_1,attribute_2,mpid) $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)"; VALUES (NULL,'','','',$case_id,'en','N','N',NULL)";
$db->Execute($sql); $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 * 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 FROM questionnaire_sample_quota_row as qsq, questionnaire as q
WHERE qsq.questionnaire_id = '$questionnaire_id' WHERE qsq.questionnaire_id = '$questionnaire_id'
AND q.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); $rs = $db->GetAll($sql);
@@ -1074,28 +1167,7 @@ function update_row_quota($questionnaire_id)
$db->Execute($sql); $db->Execute($sql);
close_row_quota($r['questionnaire_sample_quota_row_id']);
//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);
}
} }
} }

View File

@@ -51,7 +51,7 @@ function get_CPH_by_shift($qid,$sid)
{ {
global $db; 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 FROM operator as o
JOIN ( SELECT count(*) as completions,a.operator_id JOIN ( SELECT count(*) as completions,a.operator_id
FROM `call` as a, `case` as b, `shift` as s 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.`start` <= a.`start`
AND s.`end` >= a.`start` AND s.`end` >= a.`start`
GROUP BY a.operator_id) as c on (c.operator_id = o.operator_id) 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 FROM `call_attempt` as a, `case` as b, `shift` as s
WHERE a.case_id = b.case_id WHERE a.case_id = b.case_id
AND b.questionnaire_id = '$qid' AND b.questionnaire_id = '$qid'
@@ -85,7 +85,7 @@ function get_CPH_by_questionnaire($qid)
{ {
global $db; 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 FROM operator as o
JOIN ( SELECT count(*) as completions,a.operator_id JOIN ( SELECT count(*) as completions,a.operator_id
FROM `call` as a, `case` as b 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 a.case_id = b.case_id
AND b.questionnaire_id = '$qid' AND b.questionnaire_id = '$qid'
GROUP BY a.operator_id) as c on (c.operator_id = o.operator_id) 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 FROM `call_attempt` as a, `case` as b
WHERE a.case_id = b.case_id WHERE a.case_id = b.case_id
AND b.questionnaire_id = '$qid' AND b.questionnaire_id = '$qid'
GROUP BY operator_id) as ca on (ca.operator_id = o.operator_id) GROUP BY operator_id) as ca on (ca.operator_id = o.operator_id)
ORDER BY cph DESC"; 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); return $db->GetAll($sql);
} }
@@ -113,13 +316,13 @@ function get_CPH()
{ {
global $db; 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 FROM operator as o
JOIN ( SELECT count(*) as completions,operator_id JOIN ( SELECT count(*) as completions,operator_id
FROM `call` FROM `call`
WHERE outcome_id = '10' WHERE outcome_id = '10'
GROUP BY operator_id) as c on (c.operator_id = o.operator_id) 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` FROM `call_attempt`
GROUP BY operator_id) as ca on (ca.operator_id = o.operator_id) GROUP BY operator_id) as ca on (ca.operator_id = o.operator_id)
ORDER BY cph DESC"; ORDER BY cph DESC";

View File

@@ -94,10 +94,12 @@ function xhtml_foot()
* @param bool|array $head False if no header otherwise array of header titles * @param bool|array $head False if no header otherwise array of header titles
* @param string $class Table CSS class * @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 $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 "<table class='$class'>"; print "<table class='$class'>";
if ($head) if ($head)
{ {
@@ -114,8 +116,23 @@ function xhtml_table($content,$fields,$head = false,$class = "tclass",$highlight
print "<tr>"; print "<tr>";
foreach ($fields as $e) foreach ($fields as $e)
{
print "<td>{$row[$e]}</td>"; print "<td>{$row[$e]}</td>";
if ($total && in_array($e,$total))
$tot[$e] += $row[$e];
}
print "</tr>";
}
if ($total)
{
print "<tr>";
foreach ($fields as $e)
{
print "<td>";
if (in_array($e,$total))
print $tot[$e];
print "</td>";
}
print "</tr>"; print "</tr>";
} }
print "</table>"; print "</table>";

View File

@@ -10,7 +10,7 @@
* other free or open source software licenses. * other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details. * See COPYRIGHT.php for copyright notices and details.
* *
* $Id: COPYRIGHT.php 4381 2008-02-29 22:51:41Z c_schmitz $ * $Id: COPYRIGHT.php 5431 2008-08-16 21:05:52Z c_schmitz $
*/ */
// no direct access // no direct access
@@ -85,12 +85,17 @@ Copyright: 2001 - 2003 Brent R. Matzelle
License: GNU Lesser General Public License (LGPL) License: GNU Lesser General Public License (LGPL)
Sanitize Library Sanitize Library
--- ----
Copyright: 2002,2003 Free Software Foundation Copyright: 2002,2003 Free Software Foundation
License: GNU General Public License (GPL) License: GNU General Public License (GPL)
TCPDF Class TCPDF Class
--- ----
Copyright: 2006 Nicola Asuni Copyright: 2006 Nicola Asuni
License: GNU Lesser General Public License (LGPL) License: GNU Lesser General Public License (LGPL)
mint_idea Template
----
Copyright: David Kohout http://www.davidkohout.cz
License: GNU General Public License (GPL)

View File

@@ -10,7 +10,7 @@
* other free or open source software licenses. * other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details. * See COPYRIGHT.php for copyright notices and details.
* *
* $Id: access_denied.php 4247 2008-02-16 00:24:07Z lemeur $ * $Id: access_denied.php 7140 2009-06-18 06:56:20Z mennodekker $
*/ */

View File

@@ -10,7 +10,7 @@
* other free or open source software licenses. * other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details. * See COPYRIGHT.php for copyright notices and details.
* *
* $Id: activate.php 4973 2008-06-01 14:07:01Z c_schmitz $ * $Id: activate.php 7453 2009-08-12 14:41:09Z c_schmitz $
*/ */
@@ -58,6 +58,19 @@ if (!isset($_POST['ok']) || !$_POST['ok'])
$query = "UPDATE {$dbprefix}answers SET qid=$newqid WHERE qid=$oldqid"; $query = "UPDATE {$dbprefix}answers SET qid=$newqid WHERE qid=$oldqid";
$result = $connect->Execute($query) or safe_die($query."<br />".$connect->ErrorMsg()); $result = $connect->Execute($query) or safe_die($query."<br />".$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."<br />".$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 //CHECK TO MAKE SURE ALL QUESTION TYPES THAT REQUIRE ANSWERS HAVE ACTUALLY GOT ANSWERS
//THESE QUESTION TYPES ARE: //THESE QUESTION TYPES ARE:
// # "L" -> LIST // # "L" -> LIST
@@ -68,11 +81,13 @@ if (!isset($_POST['ok']) || !$_POST['ok'])
// # "R" -> RANKING // # "R" -> RANKING
// # "U" -> FILE CSV MORE // # "U" -> FILE CSV MORE
// # "I" -> FILE CSV ONE // # "I" -> FILE CSV ONE
// # ":" -> Array Multi Flexi Numbers
// # ";" -> Array Multi Flexi Text
// # "1" -> MULTI SCALE // # "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')"; $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<br />$chkquery<br />".$connect->ErrorMsg()); $chkresult = db_execute_assoc($chkquery) or safe_die ("Couldn't get list of questions<br />$chkquery<br />".$connect->ErrorMsg());
while ($chkrow = $chkresult->FetchRow()) while ($chkrow = $chkresult->FetchRow())
{ {
@@ -97,7 +112,7 @@ if (!isset($_POST['ok']) || !$_POST['ok'])
//CHECK THAT FLEXIBLE LABEL TYPE QUESTIONS HAVE AN "LID" SET //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)"; $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<br />$chkquery<br />".$connect->ErrorMsg()); $chkresult = db_execute_assoc($chkquery) or safe_die ("Couldn't check questions for missing LIDs<br />$chkquery<br />".$connect->ErrorMsg());
while($chkrow = $chkresult->FetchRow()){ while($chkrow = $chkresult->FetchRow()){
$failedcheck[]=array($chkrow['qid'], $chkrow['question'], ": ".$clang->gT("This question requires a Labelset, but none is set."), $chkrow['gid']); $failedcheck[]=array($chkrow['qid'], $chkrow['question'], ": ".$clang->gT("This question requires a Labelset, but none is set."), $chkrow['gid']);
@@ -112,7 +127,7 @@ if (!isset($_POST['ok']) || !$_POST['ok'])
//NOW check that all used labelsets have all necessary languages //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)"; $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<br />$chkquery<br />".$connect->ErrorMsg()); $chkresult = db_execute_assoc($chkquery) or safe_die ("Couldn't check questions for missing LID languages<br />$chkquery<br />".$connect->ErrorMsg());
$slangs = GetAdditionalLanguagesFromSurveyID($surveyid); $slangs = GetAdditionalLanguagesFromSurveyID($surveyid);
$baselang = GetBaseLanguageFromSurveyID($surveyid); $baselang = GetBaseLanguageFromSurveyID($surveyid);
@@ -209,7 +224,7 @@ if (!isset($_POST['ok']) || !$_POST['ok'])
} }
//IF ANY OF THE CHECKS FAILED, PRESENT THIS SCREEN //IF ANY OF THE CHECKS FAILED, PRESENT THIS SCREEN
if (isset($failedcheck) && $failedcheck) if ((isset($failedcheck) && $failedcheck) || (isset($failedgroupcheck) && $failedgroupcheck))
{ {
$activateoutput .= "<br />\n<table bgcolor='#FFFFFF' width='500' align='center' style='border: 1px solid #555555' cellpadding='6' cellspacing='0'>\n"; $activateoutput .= "<br />\n<table bgcolor='#FFFFFF' width='500' align='center' style='border: 1px solid #555555' cellpadding='6' cellspacing='0'>\n";
$activateoutput .= "\t\t\t\t<tr bgcolor='#555555'><td height='4'><font size='1' face='verdana' color='white'><strong>".$clang->gT("Activate Survey")." ($surveyid)</strong></font></td></tr>\n"; $activateoutput .= "\t\t\t\t<tr bgcolor='#555555'><td height='4'><font size='1' face='verdana' color='white'><strong>".$clang->gT("Activate Survey")." ($surveyid)</strong></font></td></tr>\n";
@@ -227,6 +242,10 @@ if (!isset($_POST['ok']) || !$_POST['ok'])
{ {
$activateoutput .= "\t\t\t\t<li> Question qid-{$fc[0]} (\"<a href='$scriptname?sid=$surveyid&amp;gid=$fc[3]&amp;qid=$fc[0]'>{$fc[1]}</a>\"){$fc[2]}</li>\n"; $activateoutput .= "\t\t\t\t<li> Question qid-{$fc[0]} (\"<a href='$scriptname?sid=$surveyid&amp;gid=$fc[3]&amp;qid=$fc[0]'>{$fc[1]}</a>\"){$fc[2]}</li>\n";
} }
foreach ($failedgroupcheck as $fg)
{
$activateoutput .= "\t\t\t\t<li> Group gid-{$fg[0]} (\"<a href='$scriptname?sid=$surveyid&amp;gid=$fg[0]'>{$fg[1]}</a>\"){$fg[2]}</li>\n";
}
$activateoutput .= "\t\t\t</ul>\n"; $activateoutput .= "\t\t\t</ul>\n";
$activateoutput .= "\t\t\t".$clang->gT("The survey cannot be activated until these problems have been resolved.")."\n"; $activateoutput .= "\t\t\t".$clang->gT("The survey cannot be activated until these problems have been resolved.")."\n";
$activateoutput .= "\t\t</td>\n"; $activateoutput .= "\t\t</td>\n";
@@ -236,30 +255,18 @@ if (!isset($_POST['ok']) || !$_POST['ok'])
return; return;
} }
$activateoutput .= "<br />\n<table class='alertbox'>\n"; $activateoutput .= "<br />\n<div class='messagebox'>\n";
$activateoutput .= "\t\t\t\t<tr><td height='4'><strong>".$clang->gT("Activate Survey")." ($surveyid)</strong></td></tr>\n"; $activateoutput .= "\t\t\t\t<div class='header'>".$clang->gT("Activate Survey")." ($surveyid)</div>\n";
$activateoutput .= "\t<tr>\n"; $activateoutput .= "\t\t<div class='warningheader'>\n";
$activateoutput .= "\t\t<td align='center' bgcolor='#ffeeee'>\n"; $activateoutput .= $clang->gT("Warning")."<br />\n";
$activateoutput .= "\t\t\t<font color='red'><strong>".$clang->gT("Warning")."</strong><br />\n"; $activateoutput .= $clang->gT("READ THIS CAREFULLY BEFORE PROCEEDING")."\n";
$activateoutput .= "\t\t\t".$clang->gT("READ THIS CAREFULLY BEFORE PROCEEDING")."\n"; $activateoutput .= "\t\t\t</div>\n";
$activateoutput .= "\t\t\t</font>\n";
$activateoutput .= "\t\t</td>\n";
$activateoutput .= "\t</tr>\n";
$activateoutput .= "\t<tr>\n";
$activateoutput .= "\t\t<td>\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.")."<br /><br />\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.")."<br /><br />\n";
$activateoutput .= $clang->gT("Once a survey is activated you can no longer:")."<ul><li>".$clang->gT("Add or delete groups")."</li><li>".$clang->gT("Add or remove answers to Multiple Answer questions")."</li><li>".$clang->gT("Add or delete questions")."</li></ul>\n"; $activateoutput .= $clang->gT("Once a survey is activated you can no longer:")."<ul><li>".$clang->gT("Add or delete groups")."</li><li>".$clang->gT("Add or remove answers to Multiple Answer questions")."</li><li>".$clang->gT("Add or delete questions")."</li></ul>\n";
$activateoutput .= $clang->gT("However you can still:")."<ul><li>".$clang->gT("Edit (change) your questions code, text or type")."</li><li>".$clang->gT("Edit (change) your group names")."</li><li>".$clang->gT("Add, Remove or Edit pre-defined question answers (except for Multi-answer questions)")."</li><li>".$clang->gT("Change survey name or description")."</li></ul>\n"; $activateoutput .= $clang->gT("However you can still:")."<ul><li>".$clang->gT("Edit (change) your questions code, text or type")."</li><li>".$clang->gT("Edit (change) your group names")."</li><li>".$clang->gT("Add, Remove or Edit pre-defined question answers (except for Multi-answer questions)")."</li><li>".$clang->gT("Change survey name or description")."</li></ul>\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.")."<br /><br />\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.")."<br /><br />\n";
$activateoutput .= "\t\t</td>\n";
$activateoutput .= "\t</tr>\n";
$activateoutput .= "\t<tr>\n";
$activateoutput .= "\t\t<td align='center'>\n";
// $activateoutput .= "\t\t\t<input type='submit' value=\"".$clang->gT("Activate Survey")."\" onclick=\"window.open('$scriptname?action=activate&amp;ok=Y&amp;sid={$_GET['sid']}', '_self')\" />\n";
$activateoutput .= "\t\t\t<input type='submit' value=\"".$clang->gT("Activate Survey")."\" onclick=\"".get2post("$scriptname?action=activate&amp;ok=Y&amp;sid={$_GET['sid']}")."\" />\n"; $activateoutput .= "\t\t\t<input type='submit' value=\"".$clang->gT("Activate Survey")."\" onclick=\"".get2post("$scriptname?action=activate&amp;ok=Y&amp;sid={$_GET['sid']}")."\" />\n";
$activateoutput .= "\t\t<br />&nbsp;</td>\n"; $activateoutput .= "</div><br />&nbsp;\n";
$activateoutput .= "\t</tr>\n";
$activateoutput .= "</table><br />&nbsp;\n";
} }
else else
@@ -303,7 +310,7 @@ else
." AND ".db_table_name('questions').".sid={$postsid} " ." AND ".db_table_name('questions').".sid={$postsid} "
." AND ".db_table_name('groups').".language='".GetbaseLanguageFromSurveyid($postsid). "' " ." AND ".db_table_name('groups').".language='".GetbaseLanguageFromSurveyid($postsid). "' "
." AND ".db_table_name('questions').".language='".GetbaseLanguageFromSurveyid($postsid). "' " ." AND ".db_table_name('questions').".language='".GetbaseLanguageFromSurveyid($postsid). "' "
." ORDER BY ".db_table_name('groups').".group_order, title"; ." ORDER BY group_order, question_order";
$aresult = db_execute_assoc($aquery); $aresult = db_execute_assoc($aquery);
while ($arow=$aresult->FetchRow()) //With each question, create the appropriate field(s) while ($arow=$aresult->FetchRow()) //With each question, create the appropriate field(s)
{ {
@@ -313,16 +320,17 @@ else
$arow['type'] != "C" && $arow['type'] != "E" && $arow['type'] != "F" && $arow['type'] != "C" && $arow['type'] != "E" && $arow['type'] != "F" &&
$arow['type'] != "H" && $arow['type'] != "P" && $arow['type'] != "R" && $arow['type'] != "H" && $arow['type'] != "P" && $arow['type'] != "R" &&
$arow['type'] != "Q" && $arow['type'] != "^" && $arow['type'] != "J" && $arow['type'] != "Q" && $arow['type'] != "^" && $arow['type'] != "J" &&
$arow['type'] != "K" && $arow['type'] != "1") $arow['type'] != "K" && $arow['type'] != ":" && $arow['type'] != ";" &&
$arow['type'] != "1")
{ {
$createsurvey .= " `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}`"; $createsurvey .= " `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}`";
switch($arow['type']) switch($arow['type'])
{ {
case "N": //NUMERICAL case "N": //NUMERICAL
$createsurvey .= " C(20)"; $createsurvey .= " F";
break; break;
case "S": //SHORT TEXT case "S": //SHORT TEXT
if ($databasetype=='mysql') {$createsurvey .= " X";} if ($databasetype=='mysql' || $databasetype=='mysqli') {$createsurvey .= " X";}
else {$createsurvey .= " C(255)";} else {$createsurvey .= " C(255)";}
break; break;
case "L": //LIST (RADIO) case "L": //LIST (RADIO)
@@ -380,13 +388,43 @@ else
} }
if ((isset($alsoother) && $alsoother=="Y") && ($arow['type']=="M" || $arow['type']=="P" || $arow['type']=="1")) //Sc: check! 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"; $createsurvey .= " `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}other` X,\n";
if ($arow['type']=="P") if ($arow['type']=="P")
{ {
$createsurvey .= " `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}othercomment` X,\n"; $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<br />$abquery<br />".$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 :)<br />$ab2query<br />".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") 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']} " $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']} "
@@ -397,7 +435,7 @@ else
while ($abrow = $abresult->FetchRow()) while ($abrow = $abresult->FetchRow())
{ {
$createsurvey .= " `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$abrow['code']}`"; $createsurvey .= " `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$abrow['code']}`";
if ($databasetype=='mysql') if ($databasetype=='mysql' || $databasetype=='mysqli')
{ {
$createsurvey .= " X"; $createsurvey .= " X";
} }
@@ -418,7 +456,7 @@ else
$abresult=db_execute_assoc($abquery) or safe_die ("Couldn't get perform answers query<br />$abquery<br />".$connect->ErrorMsg()); $abresult=db_execute_assoc($abquery) or safe_die ("Couldn't get perform answers query<br />$abquery<br />".$connect->ErrorMsg());
while ($abrow = $abresult->FetchRow()) while ($abrow = $abresult->FetchRow())
{ {
$createsurvey .= " `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$abrow['code']}` C(20),\n"; $createsurvey .= " `{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$abrow['code']}` F,\n";
} }
} //End if ($arow['type'] == "K") } //End if ($arow['type'] == "K")
/* elseif ($arow['type'] == "J") /* elseif ($arow['type'] == "J")
@@ -476,7 +514,8 @@ else
$createsurvey = rtrim($createsurvey, ",\n")."\n"; // Does nothing if not ending with a comma $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) $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'); $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); $dict = NewDataDictionary($connect);
$sqlarray = $dict->CreateTableSQL($tabname, $createsurvey, $taboptarray); $sqlarray = $dict->CreateTableSQL($tabname, $createsurvey, $taboptarray);
$execresult=$dict->ExecuteSQLArray($sqlarray,1); $execresult=$dict->ExecuteSQLArray($sqlarray,1);
@@ -532,15 +571,14 @@ else
if (isset($surveyallowsregistration) && $surveyallowsregistration == "TRUE") if (isset($surveyallowsregistration) && $surveyallowsregistration == "TRUE")
{ {
$activateoutput .= $clang->gT("This survey allows public registration. A token table must also be created.")."<br /><br />\n"; $activateoutput .= $clang->gT("This survey allows public registration. A token table must also be created.")."<br /><br />\n";
// $activateoutput .= "<input type='submit' value='".$clang->gT("Initialise Tokens")."' onclick=\"window.open('$scriptname?action=tokens&amp;sid={$_GET['sid']}&amp;createtable=Y', '_self')\" />\n";
$activateoutput .= "<input type='submit' value='".$clang->gT("Initialise Tokens")."' onclick=\"".get2post("$scriptname?action=tokens&amp;sid={$postsid}&amp;createtable=Y")."\" />\n"; $activateoutput .= "<input type='submit' value='".$clang->gT("Initialise Tokens")."' onclick=\"".get2post("$scriptname?action=tokens&amp;sid={$postsid}&amp;createtable=Y")."\" />\n";
} }
else else
{ {
$activateoutput .= $clang->gT("This survey is now active, and responses can be recorded.")."<br /><br />\n"; $activateoutput .= $clang->gT("This survey is now active, and responses can be recorded.")."<br /><br />\n";
$activateoutput .= "<strong>".$clang->gT("Open-access mode").":</strong> ".$clang->gT("No invitation code is needed to complete the survey.")."<br />".$clang->gT("You can switch to the closed-access mode by initialising a token table with the button below.")."<br /><br />\n"; $activateoutput .= "<strong>".$clang->gT("Open-access mode").":</strong> ".$clang->gT("No invitation code is needed to complete the survey.")."<br />".$clang->gT("You can switch to the closed-access mode by initialising a token table with the button below.")."<br /><br />\n";
// $activateoutput .= $clang->gT("Optional").": <input type='submit' value='".$clang->gT("Switch to closed-access mode")."' onclick=\"window.open('$scriptname?action=tokens&amp;sid={$_GET['sid']}&amp;createtable=Y', '_self')\" />\n"; $activateoutput .= "<input type='submit' value='".$clang->gT("Switch to closed-access mode")."' onclick=\"".get2post("$scriptname?action=tokens&amp;sid={$postsid}&amp;createtable=Y")."\" />\n";
$activateoutput .= $clang->gT("Optional").": <input type='submit' value='".$clang->gT("Switch to closed-access mode")."' onclick=\"".get2post("$scriptname?action=tokens&amp;sid={$postsid}&amp;createtable=Y")."\" />\n"; $activateoutput .= "<input type='submit' value='".$clang->gT("No, thanks.")."' onclick=\"".get2post("$scriptname?sid={$postsid}")."\" />\n";
} }
$activateoutput .= "\t\t\t\t</font></font></td></tr></table><br />&nbsp;\n"; $activateoutput .= "\t\t\t\t</font></font></td></tr></table><br />&nbsp;\n";
} }

View File

@@ -10,7 +10,7 @@
* other free or open source software licenses. * other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details. * See COPYRIGHT.php for copyright notices and details.
* *
* $Id: admin.php 4945 2008-05-29 17:01:48Z c_schmitz $ * $Id: admin.php 7156 2009-06-22 15:51:06Z lemeur $
*/ */
// Security Checked: POST, GET, SESSION, REQUEST, returnglobal, DB // Security Checked: POST, GET, SESSION, REQUEST, returnglobal, DB
@@ -18,17 +18,16 @@
require_once(dirname(__FILE__).'/../classes/core/startup.php'); require_once(dirname(__FILE__).'/../classes/core/startup.php');
// XML code for LS1.70 is based on the experimental PHP4 domxml // XML code for LS1.70 is based on the experimental PHP4 domxml
// extension. PHP5 uses the PHP5/dom extension. // extension. PHP5 uses the PHP5/dom extension unless the old domxml is activated
// the following file is a wrapper to use PHP4/domxml scripts // the following file is a wrapper to use PHP4/domxml scripts
// with PHP5/dom or PHP6/dom // with PHP5/dom or PHP6/dom
// see http://alexandre.alapetite.net/doc-alex/domxml-php4-php5/index.en.html#licence // see http://alexandre.alapetite.net/doc-alex/domxml-php4-php5/index.en.html#licence
if (version_compare(PHP_VERSION,'5','>=')) if (version_compare(PHP_VERSION,'5','>=')&& !(function_exists('domxml_new_doc')))
{ {
require_once(dirname(__FILE__).'/classes/core/domxml-php4-to-php5.php'); require_once(dirname(__FILE__).'/classes/core/domxml-php4-to-php5.php');
} }
require_once(dirname(__FILE__).'/../config-defaults.php'); require_once(dirname(__FILE__).'/../config-defaults.php');
require_once(dirname(__FILE__).'/../common.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'); require_once('htmleditor-functions.php');
@@ -49,38 +48,47 @@ if (!isset($action)) {$action=returnglobal('action');} //Desired action
if (!isset($subaction)) {$subaction=returnglobal('subaction');} //Desired subaction if (!isset($subaction)) {$subaction=returnglobal('subaction');} //Desired subaction
if (!isset($editedaction)) {$editedaction=returnglobal('editedaction');} // for html editor integration if (!isset($editedaction)) {$editedaction=returnglobal('editedaction');} // for html editor integration
if ($action != "showprintablesurvey")
if ($action != 'showprintablesurvey')
{ {
$adminoutput = helpscreenscript(); $adminoutput = helpscreenscript();
$adminoutput .= "<table width='100%' border='0' cellpadding='0' cellspacing='0' >\n" $adminoutput .= "<table width='100%' border='0' cellpadding='0' cellspacing='0' >\n"
."\t<tr>\n" ."\t<tr>\n"
."\t\t<td valign='top' align='center' bgcolor='#F8F8FF'>\n"; ."\t\t<td valign='top' align='center' bgcolor='#F8F8FF'>\n";
} else {$adminoutput='';} } else {$adminoutput='';}
include_once("login_check.php");
if($casEnabled)
{
include_once("login_check_cas.php");
}
else
{
include_once('login_check.php');
}
if ( $action == 'CSRFwarn') if ( $action == 'CSRFwarn')
{ {
include("access_denied.php"); include('access_denied.php');
} }
if ( $action == 'FakeGET') if ( $action == 'FakeGET')
{ {
include("access_denied.php"); include('access_denied.php');
} }
if(isset($_SESSION['loginID']) && $action!='login') if(isset($_SESSION['loginID']) && $action!='login')
{ {
//VARIOUS DATABASE OPTIONS/ACTIONS PERFORMED HERE //VARIOUS DATABASE OPTIONS/ACTIONS PERFORMED HERE
if ($action == "delsurvey" || $action == "delgroup" || $action == "delgroupall" || if ($action == 'delsurvey' || $action == 'delgroup' ||
$action == "delquestion" || $action == "delquestionall" || $action == "insertnewsurvey" || $action == 'delquestion' || $action == 'insertnewsurvey'||
$action == "copynewquestion" || $action == "insertnewgroup" || $action == "insertCSV" || $action == 'copynewquestion' || $action == 'insertnewgroup' || $action == 'insertCSV' ||
$action == "insertnewquestion" || $action == "updatesurvey" || $action == "updatesurvey2" || $action == 'insertnewquestion' || $action == 'updatesurvey' || $action == 'updatesurvey2' ||
$action == "updategroup" || $action == "deactivate" || $action == 'updategroup' || $action == 'deactivate' || $action == 'savepersonalsettings' ||
$action == "updatequestion" || $action == "modanswer" || $action == "renumberquestions" || $action == 'updatequestion' || $action == 'modanswer' || $action == 'renumberquestions' ||
$action == "delattribute" || $action == "addattribute" || $action == "editattribute") $action == 'delattribute' || $action == 'addattribute' || $action == 'editattribute')
{ {
include("database.php"); include('database.php');
} }
sendcacheheaders(); sendcacheheaders();
@@ -96,44 +104,44 @@ sendcacheheaders();
`superadmin` `superadmin`
*/ */
if ($action == "importsurvey") if ($action == 'importsurvey')
{ {
if ($_SESSION['USER_RIGHT_CREATE_SURVEY']==1) {include("http_importsurvey.php");} if ($_SESSION['USER_RIGHT_CREATE_SURVEY']==1) {include('http_importsurvey.php');}
else { include("access_denied.php");} else { include('access_denied.php');}
} }
elseif ($action == "dumpdb") elseif ($action == 'dumpdb')
{ {
if ($_SESSION['USER_RIGHT_CONFIGURATOR']==1) {include("dumpdb.php");} if ($_SESSION['USER_RIGHT_CONFIGURATOR']==1) {include('dumpdb.php');}
else { include("access_denied.php");} else { include('access_denied.php');}
} }
elseif ($action == "dumplabel") elseif ($action == 'dumplabel')
{ {
if ($_SESSION['USER_RIGHT_MANAGE_LABEL']==1) {include("dumplabel.php");} if ($_SESSION['USER_RIGHT_MANAGE_LABEL']==1) {include('dumplabel.php');}
else { include("access_denied.php");} else { include('access_denied.php');}
} }
elseif ($action == "exportlabelresources") elseif ($action == 'exportlabelresources')
{ {
if ($_SESSION['USER_RIGHT_MANAGE_TEMPLATE']==1) {$_SESSION['FileManagerContext']="edit:label:$lid"; include("export_resources_zip.php");} if ($_SESSION['USER_RIGHT_MANAGE_TEMPLATE']==1) {$_SESSION['FileManagerContext']="edit:label:$lid"; include('export_resources_zip.php');}
else { include("access_denied.php");} else { include('access_denied.php');}
} }
elseif ($action == "checkintegrity") elseif ($action == 'checkintegrity')
{ {
if ($_SESSION['USER_RIGHT_CONFIGURATOR']==1) {include("integritycheck.php");} if ($_SESSION['USER_RIGHT_CONFIGURATOR']==1) {include('integritycheck.php');}
else { include("access_denied.php");} else { include('access_denied.php');}
} }
elseif ($action=="labels" || $action=="newlabelset" || $action=="insertlabelset" || elseif ($action=='labels' || $action=='newlabelset' || $action=='insertlabelset' ||
$action=="deletelabelset" || $action=="editlabelset" || $action=="modlabelsetanswers" || $action=='deletelabelset' || $action=='editlabelset' || $action=='modlabelsetanswers' ||
$action=="updateset" || $action=="importlabels" ||$action == "importlabelresources") $action=='updateset' || $action=='importlabels' ||$action == 'importlabelresources')
{ {
if ($_SESSION['USER_RIGHT_MANAGE_LABEL']==1) {$_SESSION['FileManagerContext']="edit:label:$lid"; include("labels.php");} if ($_SESSION['USER_RIGHT_MANAGE_LABEL']==1) {$_SESSION['FileManagerContext']="edit:label:$lid"; include('labels.php');}
else { include("access_denied.php");} else { include('access_denied.php');}
} }
elseif ($action=="templates" || $action=="templatecopy" || $action=="templatesavechanges" || elseif ($action=='templates' || $action=='templatecopy' || $action=='templatesavechanges' ||
$action=="templaterename" || $action=="templateupload" || $action=="templatefiledelete" || $action=='templaterename' || $action=='templateuploadfile' || $action=='templatefiledelete' ||
$action=="templatezip" || $action=="templaterefresh") $action=='templatezip' || $action=='templaterefresh' || $action=='templateupload')
{ {
if ($_SESSION['USER_RIGHT_MANAGE_TEMPLATE']==1) {include("templates.php");} if ($_SESSION['USER_RIGHT_MANAGE_TEMPLATE']==1) {include('templates.php');}
else { include("access_denied.php");} else { include('access_denied.php');}
} }
@@ -155,251 +163,300 @@ $surresult = db_execute_assoc($surquery);
$surrows = $surresult->FetchRow(); $surrows = $surresult->FetchRow();
} }
if ($action == "activate") if ($action == 'activate')
{ {
if($surrows['activate_survey'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include("activate.php");} if($surrows['activate_survey'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include('activate.php');}
else { include("access_denied.php");} else { include('access_denied.php');}
} }
elseif ($action == "conditions") elseif ($action == 'conditions')
{ {
if($surrows['define_questions'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include("conditions.php");} if($surrows['define_questions'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include('conditionshandling.php');}
else { include("access_denied.php");} else { include('access_denied.php');}
} }
elseif ($action == "importsurvresources") elseif ($action == 'importsurvresources')
{ {
if ($surrows['define_questions'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {$_SESSION['FileManagerContext']="edit:survey:$surveyid";include("import_resources_zip.php");} if ($surrows['define_questions'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {$_SESSION['FileManagerContext']="edit:survey:$surveyid";include('import_resources_zip.php');}
else { include("access_denied.php");} else { include('access_denied.php');}
} }
elseif ($action == "exportstructurecsv") elseif ($action == 'exportstructurecsv')
{ {
if($surrows['export'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include("export_structure_csv.php");} if($surrows['export'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include('export_structure_csv.php');}
else { include("access_denied.php");} else { include('access_denied.php');}
} }
elseif ($action == "exportstructurequexml") elseif ($action == 'exportstructureLsrcCsv')
{ {
if($surrows['export'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include("export_structure_quexml.php");} if($surrows['export'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include('export_structure_lsrc.php');}
else { include("access_denied.php");} else { include('access_denied.php');}
} }
elseif ($action == "exportsurvresources") elseif ($action == 'exportstructurequexml')
{ {
if($surrows['export'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {$_SESSION['FileManagerContext']="edit:survey:$surveyid";include("export_resources_zip.php");} if($surrows['export'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include('export_structure_quexml.php');}
else { include("access_denied.php");} else { include('access_denied.php');}
} }
elseif ($action == "dumpquestion") elseif ($action == 'exportsurvresources')
{ {
if($surrows['export'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include("dumpquestion.php");} if($surrows['export'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {$_SESSION['FileManagerContext']="edit:survey:$surveyid";include('export_resources_zip.php');}
else { include("access_denied.php");} else { include('access_denied.php');}
} }
elseif ($action == "dumpgroup") elseif ($action == 'dumpquestion')
{ {
if($surrows['export'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include("dumpgroup.php");} if($surrows['export'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include('dumpquestion.php');}
else { include("access_denied.php");} else { include('access_denied.php');}
} }
elseif ($action == "deactivate") elseif ($action == 'dumpgroup')
{ {
if($surrows['activate_survey'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include("deactivate.php");} if($surrows['export'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include('dumpgroup.php');}
else { include("access_denied.php");} else { include('access_denied.php');}
} }
elseif ($action == "deletesurvey") elseif ($action == 'deactivate')
{ {
if($surrows['delete_survey'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include("deletesurvey.php");} if($surrows['activate_survey'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include('deactivate.php');}
else { include("access_denied.php");} else { include('access_denied.php');}
} }
elseif ($action == "resetsurveylogic") elseif ($action == 'deletesurvey')
{ {
if($surrows['define_questions'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include("resetsurveylogic.php");} if($surrows['delete_survey'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include('deletesurvey.php');}
else { include("access_denied.php");} else { include('access_denied.php');}
} }
elseif ($action == "importgroup") elseif ($action == 'resetsurveylogic')
{ {
if($surrows['define_questions'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include("importgroup.php");} if($surrows['define_questions'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include('resetsurveylogic.php');}
else { include("access_denied.php");} else { include('access_denied.php');}
} }
elseif ($action == "importquestion") elseif ($action == 'importgroup')
{ {
if($surrows['define_questions'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include("importquestion.php");} if($surrows['define_questions'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include('importgroup.php');}
else { include("access_denied.php");} else { include('access_denied.php');}
} }
elseif ($action == "listcolumn") elseif ($action == 'importquestion')
{ {
if($surrows['browse_response'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include("listcolumn.php");} if($surrows['define_questions'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include('importquestion.php');}
else { include("access_denied.php");} else { include('access_denied.php');}
} }
elseif ($action == "previewquestion") elseif ($action == 'listcolumn')
{ {
if($surrows['define_questions'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include("preview.php");} if($surrows['browse_response'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include('listcolumn.php');}
else { include("access_denied.php");} else { include('access_denied.php');}
} }
elseif ($action=="addgroup" || $action=="editgroup") elseif ($action == 'previewquestion')
{ {
if($surrows['define_questions'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {$_SESSION['FileManagerContext']="edit:group:$surveyid"; include("grouphandling.php");} if($surrows['define_questions'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include('preview.php');}
else { include("access_denied.php");} else { include('access_denied.php');}
} }
elseif ($action == "vvexport") elseif ($action=='addgroup' || $action=='editgroup')
{ {
if($surrows['browse_response'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include("vvexport.php");} if($surrows['define_questions'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {$_SESSION['FileManagerContext']="edit:group:$surveyid"; include('grouphandling.php');}
else { include("access_denied.php");} else { include('access_denied.php');}
} }
elseif ($action == "vvimport") elseif ($action == 'vvexport')
{ {
if($surrows['browse_response'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include("vvimport.php");} if($surrows['browse_response'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include('vvexport.php');}
else { include("access_denied.php");} else { include('access_denied.php');}
} }
elseif ($action == "importoldresponses") elseif ($action == 'vvimport')
{ {
if($surrows['browse_response'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include("importoldresponses.php");} if($surrows['browse_response'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include('vvimport.php');}
else { include("access_denied.php");} else { include('access_denied.php');}
} }
elseif ($action == "saved") elseif ($action == 'importoldresponses')
{ {
if($surrows['browse_response'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include("saved.php");} if($surrows['browse_response'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include('importoldresponses.php');}
else { include("access_denied.php");} else { include('access_denied.php');}
} }
elseif ($action == "exportresults") elseif ($action == 'saved')
{ {
if($surrows['export'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include("exportresults.php");} if($surrows['browse_response'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include('saved.php');}
else { include("access_denied.php");} else { include('access_denied.php');}
} }
elseif ($action == "exportspss") elseif ($action == 'exportresults')
{ {
if($surrows['export'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include("spss.php");} if($surrows['export'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include('exportresults.php');}
else { include("access_denied.php");} else { include('access_denied.php');}
} }
elseif ($action == "statistics") elseif ($action == 'exportspss')
{ {
if($surrows['browse_response'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include("statistics.php");} if($surrows['export'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include('export_data_spss.php');}
else { include("access_denied.php");} else { include('access_denied.php');}
} }
elseif ($action == "dataentry") elseif ($action == 'exportr')
{ {
if($surrows['browse_response'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include("dataentry.php");} if($surrows['export'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include('export_data_r.php');}
else { include("access_denied.php");} else { include('access_denied.php');}
} }
elseif ($action == "browse") elseif ($action == 'statistics')
{ {
if($surrows['browse_response'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include("browse.php");} if($surrows['browse_response'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include('statistics.php');}
else { include("access_denied.php");} else { include('access_denied.php');}
} }
elseif ($action == "tokens") elseif ($action == 'dataentry')
{ {
if($surrows['activate_survey'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {$_SESSION['FileManagerContext']="edit:emailsettings:$surveyid"; include("tokens.php");} if($surrows['browse_response'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include('dataentry.php');}
else { include("access_denied.php"); } else { include('access_denied.php');}
} }
elseif ($action=="showprintablesurvey") elseif ($action == 'browse')
{ {
include("printablesurvey.php"); //No special right needed to show the printable survey if($surrows['browse_response'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include('browse.php');}
else { include('access_denied.php');}
} }
elseif ($action=="assessments" || $action=="assessmentdelete" || $action=="assessmentedit" || $action=="assessmentadd" || $action=="assessmentupdate") elseif ($action == 'tokens')
{ {
if($surrows['define_questions'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {include("assessments.php");} if($surrows['activate_survey'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {$_SESSION['FileManagerContext']="edit:emailsettings:$surveyid"; include('tokens.php');}
else { include("access_denied.php");} else { include('access_denied.php'); }
} }
elseif ($action == "replacementfields") 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) switch ($editedaction)
{ {
case 'labels': case 'labels':
if ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $_SESSION['USER_RIGHT_MANAGE_LABEL']==1) if ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $_SESSION['USER_RIGHT_MANAGE_LABEL']==1)
{ {
include("fck_LimeReplacementFields.php");exit; $_SESSION['FileManagerContext']="edit:label:$lid";
include('fck_LimeReplacementFields.php');exit;
} }
else else
{ {
include("access_denied.php"); include('access_denied.php');
} }
break; break;
case 'newsurvey': case 'newsurvey':
if ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $_SESSION['USER_RIGHT_CREATE_SURVEY'] == 1) if ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $_SESSION['USER_RIGHT_CREATE_SURVEY'] == 1)
{ {
include("fck_LimeReplacementFields.php");exit; include('fck_LimeReplacementFields.php');exit;
} }
else else
{ {
include("access_denied.php"); include('access_denied.php');
} }
break; break;
case 'updatesurvey': case 'updatesurvey':
if ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $surrows['edit_survey_property']) if ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $surrows['edit_survey_property'])
{ {
include("fck_LimeReplacementFields.php");exit; $_SESSION['FileManagerContext']="edit:survey:$surveyid";
include('fck_LimeReplacementFields.php');exit;
} }
else else
{ {
include("access_denied.php"); include('access_denied.php');
} }
break; break;
case 'tokens': // email case 'tokens': // email
if ( $_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $surrows['activate_survey']) if ( $_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $surrows['activate_survey'])
{ {
include("fck_LimeReplacementFields.php");exit; $_SESSION['FileManagerContext']="edit:emailsettings:$surveyid";
include('fck_LimeReplacementFields.php');exit;
} }
else else
{ {
include("access_denied.php"); include('access_denied.php');
} }
break;
case 'editquestion': case 'editquestion':
case 'copyquestion': case 'copyquestion':
case 'editgroup':
case 'addquestion': 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': 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': case 'editanswer':
if ( $_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $surrows['define_questions']) if ( $_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $surrows['define_questions'])
{ {
include("fck_LimeReplacementFields.php");exit; $_SESSION['FileManagerContext']="edit:answer:$surveyid";
include('fck_LimeReplacementFields.php');exit;
} }
else else
{ {
include("access_denied.php"); include('access_denied.php');
} }
break; 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: default:
break; break;
} }
} }
if (!isset($assessmentsoutput) && !isset($statisticsoutput) && !isset($browseoutput) && !isset($savedsurveyoutput) && !isset( $listcolumnoutput ) && if (!isset($assessmentsoutput) && !isset($statisticsoutput) && !isset($browseoutput) && !isset($savedsurveyoutput) && !isset( $listcolumnoutput ) &&
!isset($dataentryoutput) && !isset($conditionsoutput) && !isset($importoldresponsesoutput) && !isset($dataentryoutput) && !isset($conditionsoutput) && !isset($importoldresponsesoutput) && !isset($exportspssoutput) && !isset($exportroutput) &&
!isset($vvoutput) && !isset($tokenoutput) && !isset($exportoutput) && !isset($templatesoutput) && !isset($vvoutput) && !isset($tokenoutput) && !isset($exportoutput) && !isset($templatesoutput) && !isset($iteratesurveyoutput) &&
(isset($surveyid) || $action=="listurveys" || $action=="changelang" || $action=="changehtmleditormode" || $action=="checksettings" || //Still to check (isset($surveyid) || $action=='listurveys' || $action=='personalsettings' || $action=='checksettings' || //Still to check
$action=="editsurvey" || $action=="updatesurvey" || $action=="ordergroups" || $action=='editsurvey' || $action=='updatesurvey' || $action=='ordergroups' ||
$action=="newsurvey" || $action=="listsurveys" || $action=='newsurvey' || $action=='listsurveys' ||
$action=="surveyrights" || $action=="quotas") ) $action=='surveyrights' || $action=='quotas') )
{ {
if ($action=="editsurvey" || $action=="updatesurvey") if ($action=='editsurvey' || $action=='updatesurvey')
{ {
$_SESSION['FileManagerContext']="edit:survey:$surveyid"; $_SESSION['FileManagerContext']="edit:survey:$surveyid";
} }
include("html.php"); include('html.php');
} }
if ($action=="addquestion" || $action=="copyquestion" || $action=="editquestion" || if ($action=='addquestion' || $action=='copyquestion' || $action=='editquestion' ||
$action=="orderquestions" || $action=="editattribute" || $action=="delattribute" || $action=='orderquestions' || $action=='editattribute' || $action=='delattribute' ||
$action=="addattribute" ) $action=='addattribute' )
{if($surrows['define_questions'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {$_SESSION['FileManagerContext']="edit:question:$surveyid";include("questionhandling.php");} {if($surrows['define_questions'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {$_SESSION['FileManagerContext']="edit:question:$surveyid";include('questionhandling.php');}
else { include("access_denied.php");} else { include('access_denied.php');}
} }
if ($action=="adduser" || $action=="deluser" || $action=="moduser" || $action=="setusertemplates" || $action=="usertemplates" || //Still to check if ($action=='adduser' || $action=='deluser' || $action=='moduser' || $action=='setusertemplates' || $action=='usertemplates' || //Still to check
$action=="userrights" || $action=="modifyuser" || $action=="editusers" || $action=='userrights' || $action=='modifyuser' || $action=='editusers' ||
$action=="addusergroup" || $action=="editusergroup" || $action=="mailusergroup" || $action=='addusergroup' || $action=='editusergroup' || $action=='mailusergroup' ||
$action=="delusergroup" || $action=="usergroupindb" || $action=="mailsendusergroup" || $action=='delusergroup' || $action=='usergroupindb' || $action=='mailsendusergroup' ||
$action=="editusergroupindb" || $action=="editusergroups" || $action=="deleteuserfromgroup" || $action=='editusergroupindb' || $action=='editusergroups' || $action=='deleteuserfromgroup' ||
$action=="addusertogroup" || $action=="setuserrights" || $action=="setasadminchild") $action=='addusertogroup' || $action=='setuserrights' || $action=='setasadminchild')
{ {
include ("userrighthandling.php"); include ('userrighthandling.php');
} }
// For some output we dont want to have the standard admin menu bar // For some output we dont want to have the standard admin menu bar
if (!isset($labelsoutput) && !isset($templatesoutput) && !isset($printablesurveyoutput) && if (!isset($labelsoutput) && !isset($templatesoutput) && !isset($printablesurveyoutput) &&
!isset($assessmentsoutput) && !isset($tokenoutput) && !isset($browseoutput) && !isset($assessmentsoutput) && !isset($tokenoutput) && !isset($browseoutput) && !isset($exportspssoutput) && !isset($exportroutput) &&
!isset($dataentryoutput) && !isset($statisticsoutput)&& !isset($savedsurveyoutput) && !isset($dataentryoutput) && !isset($statisticsoutput)&& !isset($savedsurveyoutput) &&
!isset($exportoutput) && !isset($importoldresponsesoutput) && !isset($conditionsoutput) && !isset($exportoutput) && !isset($importoldresponsesoutput) && !isset($conditionsoutput) &&
!isset($vvoutput) && !isset($listcolumnoutput) && !isset($importlabelresources)) !isset($vvoutput) && !isset($listcolumnoutput) && !isset($importlabelresources) && !isset($iteratesurveyoutput))
{ {
$adminoutput.= showadminmenu(); $adminoutput.= showadminmenu();
} }
@@ -447,6 +504,7 @@ elseif ($action == "replacementfields")
if (isset($deactivateoutput)) {$adminoutput.= $deactivateoutput;} if (isset($deactivateoutput)) {$adminoutput.= $deactivateoutput;}
if (isset($tokenoutput)) {$adminoutput.= $tokenoutput;} if (isset($tokenoutput)) {$adminoutput.= $tokenoutput;}
if (isset($browseoutput)) {$adminoutput.= $browseoutput;} if (isset($browseoutput)) {$adminoutput.= $browseoutput;}
if (isset($iteratesurveyoutput)) {$adminoutput.= $iteratesurveyoutput;}
if (isset($dataentryoutput)) {$adminoutput.= $dataentryoutput;} if (isset($dataentryoutput)) {$adminoutput.= $dataentryoutput;}
if (isset($statisticsoutput)) {$adminoutput.= $statisticsoutput;} if (isset($statisticsoutput)) {$adminoutput.= $statisticsoutput;}
if (isset($exportoutput)) {$adminoutput.= $exportoutput;} if (isset($exportoutput)) {$adminoutput.= $exportoutput;}
@@ -457,6 +515,8 @@ elseif ($action == "replacementfields")
if (isset($resetsurveylogicoutput)) {$adminoutput.= $resetsurveylogicoutput;} if (isset($resetsurveylogicoutput)) {$adminoutput.= $resetsurveylogicoutput;}
if (isset($vvoutput)) {$adminoutput.= $vvoutput;} if (isset($vvoutput)) {$adminoutput.= $vvoutput;}
if (isset($dumpdboutput)) {$adminoutput.= $dumpdboutput;} if (isset($dumpdboutput)) {$adminoutput.= $dumpdboutput;}
if (isset($exportspssoutput)) {$adminoutput.= $exportspssoutput;}
if (isset($exportroutput)) {$adminoutput.= $exportroutput;}
if (!isset($printablesurveyoutput) && ($subaction!='export')) if (!isset($printablesurveyoutput) && ($subaction!='export'))
@@ -468,12 +528,12 @@ elseif ($action == "replacementfields")
$adminoutput.= "\t\t</td>\n".helpscreen() $adminoutput.= "\t\t</td>\n".helpscreen()
. "\t</tr>\n" . "\t</tr>\n"
. "</table>\n"; . "</table>\n";
if(!isset($_SESSION['checksessionpost']))
$_SESSION['checksessionpost'] = '';
$adminoutput .= "<script type=\"text/javascript\">\n" $adminoutput .= "<script type=\"text/javascript\">\n"
. "<!--\n" . "<!--\n"
. "\tfor(i=0; i<document.forms.length; i++)\n" . "\tfor(i=0; i<document.forms.length; i++)\n"
. "\t{\n" . "\t{\n"
// . "\t\talert('TIBO formname=' + document.forms[i].name + '\\nformaction=' + document.forms[i].action);\n"
. "\t\tvar el = document.createElement('input');\n" . "\t\tvar el = document.createElement('input');\n"
. "\t\tel.type = 'hidden';\n" . "\t\tel.type = 'hidden';\n"
. "\t\tel.name = 'checksessionbypost';\n" . "\t\tel.name = 'checksessionbypost';\n"
@@ -508,8 +568,7 @@ elseif ($action == "replacementfields")
. "//-->\n" . "//-->\n"
. "</script>\n"; . "</script>\n";
$adminoutput .= "" $adminoutput .= "".getAdminFooter("http://docs.limesurvey.org", $clang->gT("LimeSurvey Online Manual"));
. getAdminFooter("http://docs.limesurvey.org", $clang->gT("LimeSurvey Online Manual"));
} }
} }
@@ -564,23 +623,23 @@ else
global $homeurl, $langdir, $imagefiles; global $homeurl, $langdir, $imagefiles;
global $surveyid, $gid, $qid, $action, $clang; global $surveyid, $gid, $qid, $action, $clang;
$helpoutput="\t\t<td id='help' width='200' valign='top' style='display: none' bgcolor='#CCCCCC'>\n" $helpoutput="\t\t<td id='help' width='200' valign='top' style='display: none' bgcolor='#F8F8FF'>\n"
."\t\t\t<table width='100%'><tr><td>" ."\t\t\t<table width='100%'><tr><td>"
."<table width='100%' align='center' cellspacing='0'>\n" ."<table width='100%' align='center' cellspacing='0'>\n"
."\t\t\t\t<tr>\n" ."\t\t\t\t<tr>\n"
."\t\t\t\t\t<td bgcolor='#555555' height='8'>\n" ."\t\t\t\t\t<td bgcolor='#D2E0F2' height='8'>\n"
."\t\t\t\t\t\t<font color='white' size='1'><strong>" ."\t\t\t\t\t\t<font size='1'><strong>"
.$clang->gT("Help")."</strong>\n" .$clang->gT("Help")."</strong>\n"
."\t\t\t\t\t</font></td>\n" ."\t\t\t\t\t</font></td>\n"
."\t\t\t\t</tr>\n" ."\t\t\t\t</tr>\n"
."\t\t\t\t<tr>\n" ."\t\t\t\t<tr>\n"
."\t\t\t\t\t<td align='center' bgcolor='#AAAAAA' style='border-style: solid; border-width: 1px; border-color: #555555'>\n" ."\t\t\t\t\t<td align='center' bgcolor='#EEF6FF' style='border-style: solid; border-width: 1px; border-color: #D2E0F2'>\n"
."\t\t\t\t\t\t<img src='$imagefiles/blank.gif' alt='' width='20' hspace='0' border='0' align='left' />\n" ."\t\t\t\t\t\t<img src='$imagefiles/blank.gif' alt='' width='20' hspace='0' border='0' align='left' />\n"
."\t\t\t\t\t\t<input type='image' src='$imagefiles/close.gif' name='CloseHelp' align='right' onclick=\"showhelp('hide')\" />\n" ."\t\t\t\t\t\t<input type='image' src='$imagefiles/close.gif' name='CloseHelp' align='right' onclick=\"showhelp('hide')\" />\n"
."\t\t\t\t\t</td>\n" ."\t\t\t\t\t</td>\n"
."\t\t\t\t</tr>\n" ."\t\t\t\t</tr>\n"
."\t\t\t\t<tr>\n" ."\t\t\t\t<tr>\n"
."\t\t\t\t\t<td bgcolor='silver' height='100%' style='border-style: solid; border-width: 1px; border-color: #333333'>\n"; ."\t\t\t\t\t<td bgcolor='#EEF6FF' height='100%' style='border-width: 0px;'>\n";
//determine which help document to show //determine which help document to show
if (!$surveyid && $action != "editusers") if (!$surveyid && $action != "editusers")
{ {
@@ -640,7 +699,6 @@ function get2post($url)
foreach ($aqueryitems as $queryitem) foreach ($aqueryitems as $queryitem)
{ {
list($paramname, $value) = explode ('=', $queryitem); list($paramname, $value) = explode ('=', $queryitem);
//error_log("TIBO URL=$url Form Action=$calledscript, param=$paramname, value=$value");
$arrayParam[] = "'".$paramname."'"; $arrayParam[] = "'".$paramname."'";
$arrayVal[] = "'".$value."'"; $arrayVal[] = "'".$value."'";
} }
@@ -649,7 +707,6 @@ function get2post($url)
$Paramlist = "new Array(" . implode(",",$arrayParam) . ")"; $Paramlist = "new Array(" . implode(",",$arrayParam) . ")";
$Valuelist = "new Array(" . implode(",",$arrayVal) . ")"; $Valuelist = "new Array(" . implode(",",$arrayVal) . ")";
$callscript = "sendPost('$calledscript','".$_SESSION['checksessionpost']."',$Paramlist,$Valuelist);"; $callscript = "sendPost('$calledscript','".$_SESSION['checksessionpost']."',$Paramlist,$Valuelist);";
//error_log("TIBO = $callscript");
return $callscript; return $callscript;
} }

View File

@@ -10,7 +10,7 @@
* other free or open source software licenses. * other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details. * See COPYRIGHT.php for copyright notices and details.
* *
* $Id: assessments.php 5096 2008-06-18 08:28:32Z c_schmitz $ * $Id: assessments.php 7428 2009-08-10 10:26:46Z c_schmitz $
*/ */
@@ -18,59 +18,116 @@ include_once("login_check.php");
if (!isset($surveyid)) {$surveyid=returnglobal('sid');} if (!isset($surveyid)) {$surveyid=returnglobal('sid');}
if (!isset($action)) {$action=returnglobal('action');} if (!isset($action)) {$action=returnglobal('action');}
$surveyinfo=getSurveyInfo($surveyid);
$js_adminheader_includes[]= $homeurl.'/scripts/assessments.js';
$js_adminheader_includes[]= $rooturl.'/scripts/jquery/jquery-ui.js';
// . "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\"styles/default/jquery-ui.css\" />\n";
$actsurquery = "SELECT edit_survey_property FROM {$dbprefix}surveys_rights WHERE sid=$surveyid AND uid = ".$_SESSION['loginID']; //Getting rights for this survey $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()); $actsurresult = $connect->Execute($actsurquery) or safe_die($connect->ErrorMsg());
$actsurrows = $actsurresult->FetchRow(); $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($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $actsurrows['edit_survey_property']){
if ($action == "assessmentadd") { if ($action == "assessmentadd") {
$inserttable=$dbprefix."assessments"; $inserttable=$dbprefix."assessments";
$query = $connect->GetInsertSQL($inserttable, array( $first=true;
'sid' => $surveyid, foreach ($assessmentlangs as $assessmentlang)
'scope' => $_POST['scope'], {
'gid' => $_POST['gid'], if (!isset($_POST['gid'])) $_POST['gid']=0;
'minimum' => $_POST['minimum'],
'maximum' => $_POST['maximum'], $datarray=array(
'name' => $_POST['name'], 'sid' => $surveyid,
'message' => $_POST['message'], 'scope' => $_POST['scope'],
'link' => $_POST['link'] )); 'gid' => $_POST['gid'],
$result=$connect->Execute($query) or safe_die("Error inserting<br />$query<br />".$connect->ErrorMsg()); '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<br />$query<br />".$connect->ErrorMsg());
if ($first==true)
{
$first=false;
$aid=$connect->Insert_ID(db_table_name_nq('assessments'),"id");
}
}
} elseif ($action == "assessmentupdate") { } elseif ($action == "assessmentupdate") {
$query = "UPDATE {$dbprefix}assessments
SET scope='".db_quote($_POST['scope'])."', if ($filterxsshtml)
gid=".sanitize_int($_POST['gid']).", {
minimum='".sanitize_int($_POST['minimum'])."', require_once("../classes/inputfilter/class.inputfilter_clean.php");
maximum='".sanitize_int($_POST['maximum'])."', $myFilter = new InputFilter('','',1,1,1);
name='".db_quote($_POST['name'])."', }
message='".db_quote($_POST['message'])."',
link='".db_quote($_POST['link'])."' foreach ($assessmentlangs as $assessmentlang)
WHERE id=".sanitize_int($_POST['id']); {
$result = $connect->Execute($query) or safe_die("Error updating<br />$query<br />".$connect->ErrorMsg());
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<br />$query<br />".$connect->ErrorMsg());
}
} elseif ($action == "assessmentdelete") { } elseif ($action == "assessmentdelete") {
$query = "DELETE FROM {$dbprefix}assessments $query = "DELETE FROM {$dbprefix}assessments
WHERE id=".sanitize_int($_POST['id']); WHERE id=".sanitize_int($_POST['id']);
$result=$connect->Execute($query); $result=$connect->Execute($query);
} }
$assessmentsoutput= "<table width='100%' border='0' >\n" $assessmentsoutput=PrepareEditorScript();
$assessmentsoutput.="<script type=\"text/javascript\">
<!--
var strnogroup='".$clang->gT("There are no groups available.", "js")."';
--></script>";
$assessmentsoutput.="<table width='100%' border='0' >\n"
. "\t<tr>\n" . "\t<tr>\n"
. "\t\t<td>\n" . "\t\t<td>\n"
. "\t\t\t<table class='menubar'>\n" . "<div class='menubar'>\n"
. "\t\t\t<tr>\n" . "\t<div class='menubar-title'>\n"
. "\t\t\t\t<td colspan='2' height='8'>\n" . "\t\t<strong>".$clang->gT("Assessments")."</strong>\n";
. "\t\t\t\t\t<strong>".$clang->gT("Assessments")."</strong></td></tr>\n";
$assessmentsoutput.= "\t<tr >\n" $assessmentsoutput.= "\t</div>\n"
. "\t\t<td>\n" . "\t<div class='menubar-main'>\n"
. "\t\t<div class='menubar-left'>\n"
. "\t\t\t<a href=\"#\" onclick=\"window.open('$scriptname?sid=$surveyid', '_self')\" onmouseout=\"hideTooltip()\" onmouseover=\"showTooltip(event,'".$clang->gT("Return to Survey Administration", "js")."');return false\">" . . "\t\t\t<a href=\"#\" onclick=\"window.open('$scriptname?sid=$surveyid', '_self')\" onmouseout=\"hideTooltip()\" onmouseover=\"showTooltip(event,'".$clang->gT("Return to Survey Administration", "js")."');return false\">" .
"<img name='Administration' src='$imagefiles/home.png' title='' alt='' align='left' /></a>\n" "<img name='Administration' src='$imagefiles/home.png' title='' alt='' /></a>\n"
. "\t\t\t<img src='$imagefiles/blank.gif' alt='' width='11' border='0' hspace='0' align='left' />\n" . "\t\t\t<img src='$imagefiles/blank.gif' alt='' width='11' />\n"
. "\t\t\t<img src='$imagefiles/seperator.gif' alt='' border='0' hspace='0' align='left' />\n" . "\t\t\t<img src='$imagefiles/seperator.gif' alt='' />\n";
. "\t\t</td>\n"
. "\t</tr>\n"; if ($surveyinfo['assessments']!='Y')
$assessmentsoutput.= "</table>"; {
$assessmentsoutput.='<span style="font-size:11px;">'.sprintf($clang->gT("Notice: Assessment mode for this survey is not activated. You can activate it in the %s survey settings %s (tab 'Notification & data management')."),'<a href="admin.php?action=editsurvey&sid='.$surveyid.'">','</a>').'</span>';
}
$assessmentsoutput.= "\t\t</div>\n"
. "\t</div>\n"
. "</div>\n";
$assessmentsoutput .= "<p style='margin:0;font-size:1px;line-height:1px;height:1px;'>&nbsp;</p>"; //CSS Firefox 2 transition fix
if ($surveyid == "") { if ($surveyid == "") {
$assessmentsoutput.= $clang->gT("No SID Provided"); $assessmentsoutput.= $clang->gT("No SID Provided");
@@ -80,42 +137,39 @@ if($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $actsurrows['edit_survey_property'
$assessments=getAssessments($surveyid); $assessments=getAssessments($surveyid);
//$assessmentsoutput.= "<pre>";print_r($assessments);echo "</pre>"; //$assessmentsoutput.= "<pre>";print_r($assessments);echo "</pre>";
$groups=getGroups($surveyid); $groups=getGroups($surveyid);
$groupselect="<select name='gid'>\n"; $groupselect="<select name='gid' id='newgroupselect'>\n";
foreach($groups as $group) { foreach($groups as $group) {
$groupselect.="<option value='".$group['gid']."'>".$group['group_name']."</option>\n"; $groupselect.="<option value='".$group['gid']."'>".$group['group_name']."</option>\n";
} }
$groupselect .="</select>\n"; $groupselect .="</select>\n";
$headings=array($clang->gT("Scope"), $clang->gT("Group"), $clang->gT("Minimum"), $clang->gT("Maximum"), $clang->gT("Heading"), $clang->gT("Message"), $clang->gT("URL")); $headings=array($clang->gT("Scope"), $clang->gT("Question group"), $clang->gT("Minimum"), $clang->gT("Maximum"));
$inputs=array("<select name='scope'><option value='T'>".$clang->gT("Total")."</option><option value='G'>".$clang->gT("Group")."</option></select>", $inputs=array("<input type='radio' id='radiototal' name='scope' value='T' checked='checked'>".$clang->gT("Total")."</input><input type='radio' id='radiogroup' name='scope' value='G'>".$clang->gT("Group")."</input>",
$groupselect, $groupselect,
"<input type='text' name='minimum' />", "<input type='text' name='minimum' class='numbersonly' />",
"<input type='text' name='maximum' />", "<input type='text' name='maximum' class='numbersonly' />");
"<input type='text' name='name' size='80'/>",
"<textarea name='message' rows='10' cols='80'></textarea >",
"<input type='text' name='link' size='80' />");
$actiontitle=$clang->gT("Add"); $actiontitle=$clang->gT("Add");
$actionvalue="assessmentadd"; $actionvalue="assessmentadd";
$thisid=""; $thisid="";
if ($action == "assessmentedit") { if ($action == "assessmentedit") {
$query = "SELECT * FROM {$dbprefix}assessments WHERE id=".sanitize_int($_POST['id']); $query = "SELECT * FROM {$dbprefix}assessments WHERE id=".sanitize_int($_POST['id'])." and language='$baselang'";
$results = db_execute_assoc($query); $results = db_execute_assoc($query);
while($row=$results->FetchRow()) { while($row=$results->FetchRow()) {
$editdata=$row; $editdata=$row;
} }
$scopeselect = "<select name='scope'><option "; $scopeselect = "<input type='radio' id='radiototal' name='scope' ";
if ($editdata['scope'] == "T") {$scopeselect .= "selected='selected' ";} if ($editdata['scope'] == "T") {$scopeselect .= "checked='checked' ";}
$scopeselect .= "value='T'>".$clang->gT("Total")."</option><option value='G'"; $scopeselect .= "value='T'>".$clang->gT("Total")."</input>";
if ($editdata['scope'] == "G") {$scopeselect .= " selected='selected'";} $scopeselect .= "<input type='radio' name='scope' id='radiogroup' value='G'";
$scopeselect .= ">".$clang->gT("Group")."</option></select>"; if ($editdata['scope'] == "G") {$scopeselect .= " checked='checked'";}
$scopeselect .= ">".$clang->gT("Question group")."</input>";
$groupselect=str_replace("'".$editdata['gid']."'", "'".$editdata['gid']."' selected", $groupselect); $groupselect=str_replace("'".$editdata['gid']."'", "'".$editdata['gid']."' selected", $groupselect);
$inputs=array($scopeselect, $inputs=array($scopeselect,
$groupselect, $groupselect,
"<input type='text' name='minimum' value='".$editdata['minimum']."' />", "<input type='text' name='minimum' value='".$editdata['minimum']."' class='numbersonly' />",
"<input type='text' name='maximum' value='".$editdata['maximum']."' />", "<input type='text' name='maximum' value='".$editdata['maximum']."' class='numbersonly' />",
"<input type='text' name='name' size='80' value='".htmlentities(stripslashes($editdata['name']), ENT_QUOTES,'UTF-8')."'/>", "<input type='text' name='name' size='80' value='".htmlentities(stripslashes($editdata['name']), ENT_QUOTES,'UTF-8')."'/>",
"<textarea name='message' rows='10' cols='80'>".htmlentities(stripslashes($editdata['message']), ENT_QUOTES,'UTF-8')."</textarea>", "<textarea name='message' id='assessmentmessage' rows='10' cols='80'>".htmlentities(stripslashes($editdata['message']), ENT_QUOTES,'UTF-8')."</textarea>");
"<input type='text' name='link' size='80' value='".$editdata['link']."' />");
$actiontitle=$clang->gT("Edit"); $actiontitle=$clang->gT("Edit");
$actionvalue="assessmentupdate"; $actionvalue="assessmentupdate";
$thisid=$editdata['id']; $thisid=$editdata['id'];
@@ -123,13 +177,14 @@ if($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $actsurrows['edit_survey_property'
//$assessmentsoutput.= "<pre>"; print_r($edits); $assessmentsoutput.= "</pre>"; //$assessmentsoutput.= "<pre>"; print_r($edits); $assessmentsoutput.= "</pre>";
//PRESENT THE PAGE //PRESENT THE PAGE
$assessmentsoutput.= "<br /><table align='center' width='90%'> $assessmentsoutput.= "<br /><table align='center' width='90%'>
<tr><td colspan='12'>".$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")."</th></tr>" <tr><th colspan='12'>".$clang->gT("Assessment rules")."</th></tr>"
."<tr><th>ID</th><th>SID</th>\n"; ."<tr><th>".$clang->gT("ID")."</th><th>".$clang->gT("SID")."</th>\n";
foreach ($headings as $head) { foreach ($headings as $head) {
$assessmentsoutput.= "<th>$head</th>\n"; $assessmentsoutput.= "<th>$head</th>\n";
} }
$assessmentsoutput.= "<th>".$clang->gT("Actions")."</th>"; $assessmentsoutput.= "<th>".$clang->gT("Title")."</th><th>".$clang->gT("Message")."</th><th>".$clang->gT("Actions")."</th>";
$assessmentsoutput.= "</tr>\n"; $assessmentsoutput.= "</tr>\n";
$flipflop=true; $flipflop=true;
foreach($assessments as $assess) { foreach($assessments as $assess) {
@@ -139,16 +194,22 @@ if($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $actsurrows['edit_survey_property'
$assessmentsoutput.= "<td>".$assess['id']."</td>\n"; $assessmentsoutput.= "<td>".$assess['id']."</td>\n";
$assessmentsoutput.= "<td>".$assess['sid']."</td>\n"; $assessmentsoutput.= "<td>".$assess['sid']."</td>\n";
if ($assess['scope'] == "T") { $assessmentsoutput.= "<td>".$clang->gT("Total")."</td>\n"; } if ($assess['scope'] == "T")
else {$assessmentsoutput.= "<td>".$clang->gT("Group")."</td>\n"; } {
$assessmentsoutput.= "<td>".$clang->gT("Total")."</td>\n";
$assessmentsoutput.= "<td>-</td>\n";
}
else
{
$assessmentsoutput.= "<td>".$clang->gT("Question group")."</td>\n";
$assessmentsoutput.= "<td>".$groups[$assess['gid']]['group_name']." (".$assess['gid'].")</td>\n";
}
$assessmentsoutput.= "<td>".$groups[$assess['gid']]['group_name']." (".$assess['gid'].")</td>\n";
$assessmentsoutput.= "<td>".$assess['minimum']."</td>\n"; $assessmentsoutput.= "<td>".$assess['minimum']."</td>\n";
$assessmentsoutput.= "<td>".$assess['maximum']."</td>\n"; $assessmentsoutput.= "<td>".$assess['maximum']."</td>\n";
$assessmentsoutput.= "<td>".stripslashes($assess['name'])."</td>\n"; $assessmentsoutput.= "<td>".stripslashes($assess['name'])."</td>\n";
$assessmentsoutput.= "<td>".stripslashes($assess['message'])."</td>\n"; $assessmentsoutput.= "<td>".strip_tags(strip_javascript($assess['message']))."</td>\n";
$assessmentsoutput.= "<td>".stripslashes($assess['link'])."</td>\n";
$assessmentsoutput.= "<td> $assessmentsoutput.= "<td>
<table width='100%'> <table width='100%'>
@@ -169,21 +230,67 @@ if($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $actsurrows['edit_survey_property'
$assessmentsoutput.= "</tr>\n"; $assessmentsoutput.= "</tr>\n";
} }
$assessmentsoutput.= "</table>"; $assessmentsoutput.= "</table>";
//now present edit/insert form
$assessmentsoutput.= "<br /><form method='post' name='assessmentsform' action='$scriptname?sid=$surveyid'><table align='center' cellspacing='0' border='0' class='form2columns'>\n"; $assessmentsoutput.= "<br /><form method='post' name='assessmentsform' action='$scriptname?sid=$surveyid'><table align='center' cellspacing='0' border='0' class='form2columns'>\n";
$assessmentsoutput.= "<tr><th colspan='2'>$actiontitle</th></tr>\n"; $assessmentsoutput.= "<tr><th colspan='2'>$actiontitle</th></tr>\n";
$i=0; $i=0;
foreach ($headings as $head) { foreach ($headings as $head) {
$assessmentsoutput.= "<tr><td>$head</td><td>".$inputs[$i]."</td></tr>\n"; $assessmentsoutput.= "<tr><td>$head</td><td>".$inputs[$i]."<br /></td></tr>\n";
$i++; $i++;
} }
$assessmentsoutput.= "<tr><th colspan='2' align='center'><input type='submit' value='".$clang->gT("Save")."' />\n";
// start tabs
$assessmentsoutput.= "<tr><td>&nbsp;</td><td>&nbsp;</td></tr>\n";
$assessmentsoutput.='</table><div id="languagetabs">'
.'<ul>';
foreach ($assessmentlangs as $assessmentlang)
{
$position=0;
$assessmentsoutput .= '<li><a href="#tablang'.$assessmentlang.'"><span>'.getLanguageNameFromCode($assessmentlang, false);
if ($assessmentlang==$baselang) {$assessmentsoutput .= ' ('.$clang->gT("Base Language").')';}
$assessmentsoutput .='</span></a></li>';
}
$assessmentsoutput.= '</ul>';
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 .= '<div id="tablang'.$assessmentlang.'">';
$assessmentsoutput .= $clang->gT("Heading")."<br/>"
."<input type='text' name='name_$assessmentlang' size='80' value='$heading'/><br /><br />"
.$clang->gT("Message")
."<textarea name='assessmentmessage_$assessmentlang' id='assessmentmessage_$assessmentlang' rows='10' cols='80'>$message</textarea >";
$assessmentsoutput .='</div>';
}
$assessmentsoutput .='</div>';
$assessmentsoutput.= "<div style='width:200px;margin:5px auto;'><input type='submit' value='".$clang->gT("Save")."' />\n";
if ($action == "assessmentedit") $assessmentsoutput.= "&nbsp;&nbsp;&nbsp;&nbsp;<input type='submit' value='".$clang->gT("Cancel")."' onclick=\"document.assessmentsform.action.value='assessments'\" />\n"; if ($action == "assessmentedit") $assessmentsoutput.= "&nbsp;&nbsp;&nbsp;&nbsp;<input type='submit' value='".$clang->gT("Cancel")."' onclick=\"document.assessmentsform.action.value='assessments'\" />\n";
$assessmentsoutput.= "<input type='hidden' name='sid' value='$surveyid' />\n" $assessmentsoutput.= "<input type='hidden' name='sid' value='$surveyid' />\n"
."<input type='hidden' name='action' value='$actionvalue' />\n" ."<input type='hidden' name='action' value='$actionvalue' />\n"
."<input type='hidden' name='id' value='$thisid' />\n" ."<input type='hidden' name='id' value='$thisid' />\n"
."</th></tr>\n" ."<div>\n"
."</table></form></td></tr></table>\n"; ."</form>\n";
foreach ($assessmentlangs as $assessmentlang)
{
$assessmentsoutput.=getEditor("assessment-text","assessmentmessage_$assessmentlang", "[".$clang->gT("Message:", "js")."]",$surveyid,$gid,$qid,$action);
}
} }
else else
{ {
@@ -193,10 +300,10 @@ else
} }
function getAssessments($surveyid) { function getAssessments($surveyid) {
global $dbprefix, $connect; global $dbprefix, $connect, $baselang;
$query = "SELECT id, sid, scope, gid, minimum, maximum, name, message, link $query = "SELECT id, sid, scope, gid, minimum, maximum, name, message
FROM ".db_table_name('assessments')." FROM ".db_table_name('assessments')."
WHERE sid='$surveyid' WHERE sid='$surveyid' and language='$baselang'
ORDER BY scope, gid"; ORDER BY scope, gid";
$result=db_execute_assoc($query) or safe_die("Error getting assessments<br />$query<br />".$connect->ErrorMsg()); $result=db_execute_assoc($query) or safe_die("Error getting assessments<br />$query<br />".$connect->ErrorMsg());
$output=array(); $output=array();

View File

@@ -10,7 +10,7 @@
* other free or open source software licenses. * other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details. * See COPYRIGHT.php for copyright notices and details.
* *
* $Id: browse.php 5144 2008-06-22 12:46:05Z c_schmitz $ * $Id: browse.php 7392 2009-08-03 07:03:00Z c_schmitz $
*/ */
include_once("login_check.php"); //Login Check dies also if the script is started directly include_once("login_check.php"); //Login Check dies also if the script is started directly
@@ -55,16 +55,14 @@ else
$language = GetBaseLanguageFromSurveyID($surveyid); $language = GetBaseLanguageFromSurveyID($surveyid);
} }
$surveyoptions = browsemenubar($clang->gT("Browse Responses"));
$surveyoptions = browsemenubar(); $browseoutput = "<table style='background-color:#F8F8FF;' width='100%' align='center'>\n";
$browseoutput = "<table><tr><td></td></tr></table>\n"
."<table class='menubar'>\n";
if (!$database_exists) //DATABASE DOESN'T EXIST OR CAN'T CONNECT if (!$database_exists) //DATABASE DOESN'T EXIST OR CAN'T CONNECT
{ {
$browseoutput .= "\t<tr ><td colspan='2' height='4'><strong>" $browseoutput .= "\t<tr ><td colspan='2' height='4'><strong>"
. $clang->gT("Browse Responses")."</strong></td></tr>\n" . $clang->gT("Browse Responses")."</strong></td></tr>\n"
."\t<tr><td align='center'>$setfont\n" ."\t<tr><td align='center'>\n"
."<strong><font color='red'>".$clang->gT("Error")."</font></strong><br />\n" ."<strong><font color='red'>".$clang->gT("Error")."</font></strong><br />\n"
. $clang->gT("The defined LimeSurvey database does not exist")."<br />\n" . $clang->gT("The defined LimeSurvey database does not exist")."<br />\n"
. $clang->gT("Either your selected database has not yet been created or there is a problem accessing it.")."<br /><br />\n" . $clang->gT("Either your selected database has not yet been created or there is a problem accessing it.")."<br /><br />\n"
@@ -77,7 +75,7 @@ if (!$surveyid && !$subaction) //NO SID OR ACTION PROVIDED
{ {
$browseoutput .= "\t<tr ><td colspan='2' height='4'><strong>" $browseoutput .= "\t<tr ><td colspan='2' height='4'><strong>"
. $clang->gT("Browse Responses")."</strong></td></tr>\n" . $clang->gT("Browse Responses")."</strong></td></tr>\n"
."\t<tr><td align='center'>$setfont\n" ."\t<tr><td align='center'>\n"
."<strong><font color='red'>".$clang->gT("Error")."</font></strong><br />\n" ."<strong><font color='red'>".$clang->gT("Error")."</font></strong><br />\n"
. $clang->gT("You have not selected a survey to browse.")."<br /><br />\n" . $clang->gT("You have not selected a survey to browse.")."<br /><br />\n"
."<input type='submit' value='" ."<input type='submit' value='"
@@ -96,6 +94,14 @@ if ($actcount > 0)
while ($actrow = $actresult->FetchRow()) while ($actrow = $actresult->FetchRow())
{ {
$surveytable = db_table_name("survey_".$actrow['sid']); $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']}"; $surveyname = "{$actrow['surveyls_title']}";
if ($actrow['active'] == "N") //SURVEY IS NOT ACTIVE YET if ($actrow['active'] == "N") //SURVEY IS NOT ACTIVE YET
{ {
@@ -129,11 +135,9 @@ else //SURVEY MATCHING $surveyid DOESN'T EXIST
$qulanguage = GetBaseLanguageFromSurveyID($surveyid); $qulanguage = GetBaseLanguageFromSurveyID($surveyid);
if ($subaction == "id") // Looking at a SINGLE entry if ($subaction == "id") // Looking at a SINGLE entry
{ {
$dateformatdetails=getDateFormatData($_SESSION['dateformat']);
//SHOW HEADER //SHOW HEADER
$browseoutput .= "\t<tr><td colspan='2' height='4'><strong>".$clang->gT("Browse Responses").":</strong> $surveyname</td></tr>\n"; if (!isset($_POST['sql']) || !$_POST['sql']) {$browseoutput .= '<tr><td>'.$surveyoptions;} // Don't show options if coming from tokens script
if (!isset($_POST['sql']) || !$_POST['sql']) {$browseoutput .= "$surveyoptions";} // Don't show options if coming from tokens script
$browseoutput .= "</table>\n"
."<table><tr><td></td></tr></table>\n";
//FIRST LETS GET THE NAMES OF THE QUESTIONS AND MATCH THEM TO THE FIELD NAMES FOR THE DATABASE //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")." $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 WHERE ".db_table_name("questions").".gid=".db_table_name("groups").".gid AND ".db_table_name("groups").".sid=".db_table_name("surveys").".sid
@@ -194,6 +198,34 @@ if ($subaction == "id") // Looking at a SINGLE entry
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")) 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").")"); $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") elseif ($fnrow['type'] == "R")
@@ -231,12 +263,12 @@ if ($subaction == "id") // Looking at a SINGLE entry
$field = "{$fnrow['sid']}X{$fnrow['gid']}X{$fnrow['qid']}{$i2row['code']}#0"; $field = "{$fnrow['sid']}X{$fnrow['gid']}X{$fnrow['qid']}{$i2row['code']}#0";
$ftitle = "Grp{$fnrow['gid']}Qst{$fnrow['title']}Opt{$i2row['code']}"; $ftitle = "Grp{$fnrow['gid']}Qst{$fnrow['title']}Opt{$i2row['code']}";
if ($i2row['other'] == "Y") {$otherexists = "Y";} if ($i2row['other'] == "Y") {$otherexists = "Y";}
$fnames[] = array("$field", "$ftitle", "{$fnrow['question']}<br />\n[{$i2row['answer']}]<br>[".$clang->gT("1. scale")."]", "{$fnrow['gid']}"); $fnames[] = array("$field", "$ftitle", "{$fnrow['question']}<br />\n[{$i2row['answer']}]<br />[".$clang->gT("1. scale")."]", "{$fnrow['gid']}");
// second scale // second scale
$field = "{$fnrow['sid']}X{$fnrow['gid']}X{$fnrow['qid']}{$i2row['code']}#1"; $field = "{$fnrow['sid']}X{$fnrow['gid']}X{$fnrow['qid']}{$i2row['code']}#1";
$ftitle = "Grp{$fnrow['gid']}Qst{$fnrow['title']}Opt{$i2row['code']}"; $ftitle = "Grp{$fnrow['gid']}Qst{$fnrow['title']}Opt{$i2row['code']}";
if ($i2row['other'] == "Y") {$otherexists = "Y";} if ($i2row['other'] == "Y") {$otherexists = "Y";}
$fnames[] = array("$field", "$ftitle", "{$fnrow['question']}<br />\n[{$i2row['answer']}]<br>[".$clang->gT("2. scale")."]", "{$fnrow['gid']}"); $fnames[] = array("$field", "$ftitle", "{$fnrow['question']}<br />\n[{$i2row['answer']}]<br />[".$clang->gT("2. scale")."]", "{$fnrow['gid']}");
} }
if ($otherexists == "Y") if ($otherexists == "Y")
{ {
@@ -258,7 +290,8 @@ if ($subaction == "id") // Looking at a SINGLE entry
$nfncount = count($fnames)-1; $nfncount = count($fnames)-1;
//SHOW INDIVIDUAL RECORD //SHOW INDIVIDUAL RECORD
$idquery = "SELECT *, CASE WHEN submitdate IS NULL THEN 'N' ELSE 'Y' END as completed FROM $surveytable WHERE "; $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 (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 ($id<1) {$id=1;}
if (isset($_POST['sql']) && $_POST['sql']) if (isset($_POST['sql']) && $_POST['sql'])
{ {
@@ -270,43 +303,45 @@ if ($subaction == "id") // Looking at a SINGLE entry
while ($idrow = $idresult->FetchRow()) {$id=$idrow['id']; $rlangauge=$idrow['startlanguage'];} while ($idrow = $idresult->FetchRow()) {$id=$idrow['id']; $rlangauge=$idrow['startlanguage'];}
$next=$id+1; $next=$id+1;
$last=$id-1; $last=$id-1;
$browseoutput .= "<table width='99%' align='center' style='border: 1px solid #555555' cellpadding='1' cellspacing='0'>\n" $browseoutput .= "<div class='menubar'>\n"
."\t<tr>\n" ."\t\t<div class='menubar-title'>"
."\t\t<td colspan='2' height='4'><strong>" ."<strong>".$clang->gT("View Response").":</strong> $id\n"
. $clang->gT("View Response").":</strong> $id</td></tr>\n" ."\t</div><div class='menubar-main'>\n"
."\t<tr><td colspan='2'>\n"
."\t\t\t<img src='$imagefiles/blank.gif' width='31' height='20' border='0' hspace='0' align='left' alt='' />\n" ."\t\t\t<img src='$imagefiles/blank.gif' width='31' height='20' border='0' hspace='0' align='left' alt='' />\n"
."\t\t\t<img src='$imagefiles/seperator.gif' border='0' hspace='0' align='left' alt='' />\n"; ."\t\t\t<img src='$imagefiles/seperator.gif' border='0' hspace='0' align='left' alt='' />\n";
if (isset($rlangauge)) if (isset($rlangauge))
{ {
$browseoutput .="\t\t\t<a href='$scriptname?action=dataentry&amp;subaction=edit&amp;id=$id&amp;sid=$surveyid&amp;language=$rlangauge&amp;surveytable=$surveytable'" . $browseoutput .="\t\t\t<a href='$scriptname?action=dataentry&amp;subaction=edit&amp;id=$id&amp;sid=$surveyid&amp;language=$rlangauge'" .
"onmouseout=\"hideTooltip()\" onmouseover=\"showTooltip(event,'".$clang->gT("Edit this entry", "js")."')\">" . "onmouseout=\"hideTooltip()\" onmouseover=\"showTooltip(event,'".$clang->gT("Edit this entry", "js")."')\">" .
"<img align='left' src='$imagefiles/edit.png' title='' alt='' /></a>\n"; "<img align='left' src='$imagefiles/edit.png' title='' alt='' /></a>\n";
} }
if ($sumrows5['delete_survey']) if (($sumrows5['delete_survey'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) && isset($rlangauge))
{ {
// $browseoutput .= "\t\t\t<a href='$scriptname?action=dataentry&amp;subaction=delete&amp;id=$id&amp;sid=$surveyid&amp;surveytable=$surveytable'" .
// "onmouseout=\"hideTooltip()\" onmouseover=\"showTooltip(event,'".$clang->gT("Delete this entry", "js")."')\">" $browseoutput .= "\t\t\t<a href='#'"
// ."<img align='left' hspace='0' border='0' src='$imagefiles/delete.png' alt='' title='' onclick=\"return confirm('".$clang->gT("Are you sure you want to delete this entry?","js")."')\" /></a>\n"; ."onmouseout=\"hideTooltip()\" onmouseover=\"showTooltip(event,'".$clang->gT("Delete this entry", "js")."')\">"
$browseoutput .= "\t\t\t<a href='#'" . ."<img align='left' hspace='0' border='0' src='$imagefiles/delete.png' alt='' title='' onclick=\"if (confirm('".$clang->gT("Are you sure you want to delete this entry?","js")."')) {".get2post($scriptname.'?action=dataentry&amp;subaction=delete&amp;id='.$id.'&amp;sid='.$surveyid)."}\" /></a>\n";
"onmouseout=\"hideTooltip()\" onmouseover=\"showTooltip(event,'".$clang->gT("Delete this entry", "js")."')\">"
."<img align='left' hspace='0' border='0' src='$imagefiles/delete.png' alt='' title='' onclick=\"if (confirm('".$clang->gT("Are you sure you want to delete this entry?","js")."')) {".get2post("$scriptname?action=dataentry&amp;subaction=delete&amp;id=$id&amp;sid=$surveyid&amp;surveytable=$surveytable")."}\" /></a>\n";
} }
else
{
$browseoutput .= "\t\t\t<img align='left' hspace='0' border='0' src='$imagefiles/delete_disabled.png' alt='' title='' onmouseout=\"hideTooltip()\" onmouseover=\"showTooltip(event,'".$clang->gT("You don't have permission to delete this entry.", "js")."')\" />";
}
$browseoutput .= "\t\t\t<a href='$scriptname?action=exportresults&amp;sid=$surveyid&amp;id=$id'" . $browseoutput .= "\t\t\t<a href='$scriptname?action=exportresults&amp;sid=$surveyid&amp;id=$id'" .
"onmouseout=\"hideTooltip()\" onmouseover=\"showTooltip(event,'".$clang->gT("Export this Response", "js")."')\">" . "onmouseout=\"hideTooltip()\" onmouseover=\"showTooltip(event,'".$clang->gT("Export this Response", "js")."')\">" .
"<img name='ExportAnswer' src='$imagefiles/export.png' title='' alt='". $clang->gT("Export this Response")."'align='left' /></a>\n" "<img name='ExportAnswer' src='$imagefiles/export.png' title='' alt='". $clang->gT("Export this Response")."'align='left' /></a>\n"
."\t\t\t<img src='$imagefiles/seperator.gif' border='0' hspace='0' align='left' alt='' />\n" ."\t\t\t<img src='$imagefiles/seperator.gif' border='0' hspace='0' align='left' alt='' />\n"
."\t\t\t<img src='$imagefiles/blank.gif' width='20' height='20' border='0' hspace='0' align='left' alt='' />\n" ."\t\t\t<img src='$imagefiles/blank.gif' width='20' height='20' border='0' hspace='0' align='left' alt='' />\n"
."\t\t\t<a href='$scriptname?action=browse&amp;subaction=id&amp;id=$last&amp;sid=$surveyid&amp;surveytable=$surveytable'" . ."\t\t\t<a href='$scriptname?action=browse&amp;subaction=id&amp;id=$last&amp;sid=$surveyid'" .
"onmouseout=\"hideTooltip()\" onmouseover=\"showTooltip(event,'".$clang->gT("Show previous...", "js")."')\">". "onmouseout=\"hideTooltip()\" onmouseover=\"showTooltip(event,'".$clang->gT("Show previous...", "js")."')\">".
"<img name='DataBack' align='left' src='$imagefiles/databack.png' alt='' /></a>\n" "<img name='DataBack' align='left' src='$imagefiles/databack.png' alt='' /></a>\n"
."\t\t\t<img src='$imagefiles/blank.gif' width='13' height='20' border='0' hspace='0' align='left' alt='' />\n" ."\t\t\t<img src='$imagefiles/blank.gif' width='13' height='20' border='0' hspace='0' align='left' alt='' />\n"
."\t\t\t<a href='$scriptname?action=browse&amp;subaction=id&amp;id=$next&amp;sid=$surveyid&amp;surveytable=$surveytable'" . ."\t\t\t<a href='$scriptname?action=browse&amp;subaction=id&amp;id=$next&amp;sid=$surveyid'" .
"onmouseout=\"hideTooltip()\" onmouseover=\"showTooltip(event,'".$clang->gT("Show next...", "js")."')\">" . "onmouseout=\"hideTooltip()\" onmouseover=\"showTooltip(event,'".$clang->gT("Show next...", "js")."')\">" .
"<img name='DataForward' align='left' src='$imagefiles/dataforward.png' alt='' /></a>\n" "<img name='DataForward' align='left' src='$imagefiles/dataforward.png' alt='' /></a>\n"
."\t\t</td>\n" ."\t\t</div>\n"
."\t</tr>\n" ."\t</div>\n";
."\t<tr><td colspan='2' bgcolor='#CCCCCC' height='1'></td></tr>\n";
$browseoutput .= "<table class='browsetable' width='99%'>\n";
$idresult = db_execute_assoc($idquery) or safe_die ("Couldn't get entry<br />$idquery<br />".$connect->ErrorMsg()); $idresult = db_execute_assoc($idquery) or safe_die ("Couldn't get entry<br />$idquery<br />".$connect->ErrorMsg());
while ($idrow = $idresult->FetchRow()) while ($idrow = $idresult->FetchRow())
{ {
@@ -314,35 +349,27 @@ if ($subaction == "id") // Looking at a SINGLE entry
for ($i; $i<$nfncount+1; $i++) for ($i; $i<$nfncount+1; $i++)
{ {
$browseoutput .= "\t<tr>\n" $browseoutput .= "\t<tr>\n"
."\t\t<td bgcolor='#EFEFEF' valign='top' align='right' width='33%' style='padding-right: 5px'>" ."\t\t<th align='right' width='50%'>"
."$setfont{$fnames[$i][2]}</font></td>\n" .strip_tags(strip_javascript($fnames[$i][2]))."</th>\n"
."\t\t<td valign='top' align='left' style='padding-left: 5px'>$setfont" ."\t\t<td align='left' >"
.htmlspecialchars(getextendedanswer($fnames[$i][0], $idrow[$fnames[$i][0]]), ENT_QUOTES) .htmlspecialchars(strip_tags(strip_javascript(getextendedanswer($fnames[$i][0], $idrow[$fnames[$i][0]], '', $dateformatdetails['phpdate']))), ENT_QUOTES)
."</font></td>\n" ."</td>\n"
."\t</tr>\n" ."\t</tr>\n";
."\t<tr><td colspan='2' bgcolor='#CCCCCC' height='1'></td></tr>\n";
} }
} }
$browseoutput .= "</table>\n" $browseoutput .= "</table>\n";
."<table width='99%' align='center'>\n"
."\t<tr>\n"
."\t\t<td bgcolor='#EEEEEE' align='center'>\n";
// if (isset($_POST['sql']) && $_POST['sql']) {$browseoutput .= "\t\t\t<input type='submit' value='Close Window' onclick=\"window.close();\" />\n";}
$browseoutput .= "\t\t</td>\n"
."\t</tr>\n"
."</table>\n";
} }
elseif ($subaction == "all") elseif ($subaction == "all")
{ {
$browseoutput .= ("\t<tr><td colspan='2' height='4'><strong>"
. $clang->gT("Browse Responses").":</strong> $surveyname</td></tr>\n");
if (!isset($_POST['sql'])) if (!isset($_POST['sql']))
{$browseoutput .= "$surveyoptions";} //don't show options when called from another script with a filter on {$browseoutput .= '<tr><td>'.$surveyoptions;} //don't show options when called from another script with a filter on
else else
{ {
$browseoutput .= "\n<tr><td><table width='100%' align='center' border='0' bgcolor='#EFEFEF'>\n" $browseoutput .= "\t<tr><td colspan='2' height='4'><strong>".$clang->gT("Browse Responses").":</strong> $surveyname</td></tr>\n"
."\n<tr><td><table width='100%' align='center' border='0' bgcolor='#EFEFEF'>\n"
."\t<tr>\n" ."\t<tr>\n"
."\t\t<td align='center'>\n" ."\t\t<td align='center'>\n"
."\t\t\t".$clang->gT("Showing Filtered Results")."<br />\n" ."\t\t\t".$clang->gT("Showing Filtered Results")."<br />\n"
@@ -376,28 +403,28 @@ elseif ($subaction == "all")
if ($private == "N") //Add token to list if ($private == "N") //Add token to list
{ {
$fnames[] = array("token", $clang->gT("Token"), $clang->gT("Token ID"), "0"); $fnames[] = array("token", $clang->gT("Token"), $clang->gT("Token ID"), "0", '');
} }
$fnames[] = array("completed", "Completed", $clang->gT("Completed"), "0"); $fnames[] = array("completed", "Completed", $clang->gT("Completed"), "0", 'D');
if ($datestamp == "Y") //Add datestamp if ($datestamp == "Y") //Add datestamp
{ {
// submitdate for not-datestamped surveys is always 1980/01/01 // submitdate for not-datestamped surveys is always 1980/01/01
// so only display it when datestamped // so only display it when datestamped
$fnames[] = array("startdate", "startdate", $clang->gT("Date Started"), "0"); $fnames[] = array("startdate", "startdate", $clang->gT("Date Started"), "0", 'D');
$fnames[] = array("datestamp", "Datestamp", $clang->gT("Date Last Action"), "0"); $fnames[] = array("datestamp", "Datestamp", $clang->gT("Date Last Action"), "0", 'D');
$fnames[] = array("submitdate", "submitdate", $clang->gT("Date Submitted"), "0"); $fnames[] = array("submitdate", "submitdate", $clang->gT("Date Submitted"), "0", 'D');
} }
if ($ipaddr == "Y") // Add IP Address if ($ipaddr == "Y") // Add IP Address
{ {
$fnames[] = array("ipaddr", "IPAddress", $clang->gT("IP Address"), "0"); $fnames[] = array("ipaddr", "IPAddress", $clang->gT("IP Address"), "0",'');
} }
if ($refurl == "Y") // refurl if ($refurl == "Y") // refurl
{ {
$fnames[] = array("refurl", "refurl", $clang->gT("Referring URL"), "0"); $fnames[] = array("refurl", "refurl", $clang->gT("Referring URL"), "0",'');
} }
foreach ($fnrows as $fnrow) foreach ($fnrows as $fnrow)
{ {
@@ -405,15 +432,17 @@ elseif ($subaction == "all")
$fnrow['type'] != "B" && $fnrow['type'] != "C" && $fnrow['type'] != "E" && $fnrow['type'] != "B" && $fnrow['type'] != "C" && $fnrow['type'] != "E" &&
$fnrow['type'] != "F" && $fnrow['type'] != "H" && $fnrow['type'] != "P" && $fnrow['type'] != "F" && $fnrow['type'] != "H" && $fnrow['type'] != "P" &&
$fnrow['type'] != "J" && $fnrow['type'] != "K" && $fnrow['type'] != "1" && $fnrow['type'] != "J" && $fnrow['type'] != "K" && $fnrow['type'] != "1" &&
$fnrow['type'] != "O" && $fnrow['type'] != "R" && $fnrow['type'] != "^") $fnrow['type'] != "O" && $fnrow['type'] != "R" && $fnrow['type'] != "^" &&
$fnrow['type'] != ":" && $fnrow['type'] != ";")
{ {
$field = "{$fnrow['sid']}X{$fnrow['gid']}X{$fnrow['qid']}"; $field = "{$fnrow['sid']}X{$fnrow['gid']}X{$fnrow['qid']}";
$ftitle = "Grp{$fnrow['gid']}Qst{$fnrow['title']}"; $ftitle = "Grp{$fnrow['gid']}Qst{$fnrow['title']}";
$fquestion = $fnrow['question']; $fquestion = $fnrow['question'];
$fnames[] = array("$field", "$ftitle", "$fquestion", "{$fnrow['gid']}");
$fnames[] = array("$field", "$ftitle", "$fquestion", $fnrow['gid'], $fnrow['type']);
if (($fnrow['type'] == "L" || $fnrow['type'] == "!" || $fnrow['type'] == "W" || $fnrow['type'] == "Z") && $fnrow['other'] == "Y") 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']}"); $fnames[] = array("$field"."other", "$ftitle"."other", "{$fnrow['question']}(".$clang->gT("Other").")", $fnrow['gid'], $fnrow['type']);
} }
} }
@@ -422,11 +451,11 @@ elseif ($subaction == "all")
$field = "{$fnrow['sid']}X{$fnrow['gid']}X{$fnrow['qid']}"; $field = "{$fnrow['sid']}X{$fnrow['gid']}X{$fnrow['qid']}";
$ftitle = "Grp{$fnrow['gid']}Qst{$fnrow['title']}"; $ftitle = "Grp{$fnrow['gid']}Qst{$fnrow['title']}";
$fquestion = $fnrow['question']; $fquestion = $fnrow['question'];
$fnames[] = array("$field", "$ftitle", "$fquestion", "{$fnrow['gid']}"); $fnames[] = array("$field", "$ftitle", "$fquestion", $fnrow['gid'], $fnrow['type']);
$field .= "comment"; $field .= "comment";
$ftitle .= "[comment]"; $ftitle .= "[comment]";
$fquestion .= " (comment)"; $fquestion .= " (comment)";
$fnames[] = array("$field", "$ftitle", "$fquestion", "{$fnrow['gid']}"); $fnames[] = array("$field", "$ftitle", "$fquestion", $fnrow['gid'], $fnrow['type']);
} }
elseif ($fnrow['type'] == "1") // multi scale elseif ($fnrow['type'] == "1") // multi scale
{ {
@@ -443,21 +472,21 @@ elseif ($subaction == "all")
$field = "{$fnrow['sid']}X{$fnrow['gid']}X{$fnrow['qid']}{$i2row['code']}#0"; $field = "{$fnrow['sid']}X{$fnrow['gid']}X{$fnrow['qid']}{$i2row['code']}#0";
$ftitle = "Grp{$fnrow['gid']}Qst{$fnrow['title']}Opt{$i2row['code']}"; $ftitle = "Grp{$fnrow['gid']}Qst{$fnrow['title']}Opt{$i2row['code']}";
if ($i2row['other'] == "Y") {$otherexists = "Y";} if ($i2row['other'] == "Y") {$otherexists = "Y";}
$fnames[] = array("$field", "$ftitle", "{$fnrow['question']}<br />\n[{$i2row['answer']}]<br>[".$clang->gT("1. scale")."]", "{$fnrow['gid']}"); $fnames[] = array("$field", "$ftitle", "{$fnrow['question']}<br />\n[{$i2row['answer']}]<br />[".$clang->gT("1. scale")."]", $fnrow['gid'], $fnrow['type']);
// second scale // second scale
$field = "{$fnrow['sid']}X{$fnrow['gid']}X{$fnrow['qid']}{$i2row['code']}#1"; $field = "{$fnrow['sid']}X{$fnrow['gid']}X{$fnrow['qid']}{$i2row['code']}#1";
$ftitle = "Grp{$fnrow['gid']}Qst{$fnrow['title']}Opt{$i2row['code']}"; $ftitle = "Grp{$fnrow['gid']}Qst{$fnrow['title']}Opt{$i2row['code']}";
if ($i2row['other'] == "Y") {$otherexists = "Y";} if ($i2row['other'] == "Y") {$otherexists = "Y";}
$fnames[] = array("$field", "$ftitle", "{$fnrow['question']}<br />\n[{$i2row['answer']}]<br>[".$clang->gT("2. scale")."]", "{$fnrow['gid']}"); $fnames[] = array("$field", "$ftitle", "{$fnrow['question']}<br />\n[{$i2row['answer']}]<br />[".$clang->gT("2. scale")."]", $fnrow['gid'], $fnrow['type']);
} }
if ($otherexists == "Y") if ($otherexists == "Y")
{ {
$field = "{$fnrow['sid']}X{$fnrow['gid']}X{$fnrow['qid']}"."other"; $field = "{$fnrow['sid']}X{$fnrow['gid']}X{$fnrow['qid']}"."other";
$ftitle = "Grp{$fnrow['gid']}Qst{$fnrow['title']}OptOther"; $ftitle = "Grp{$fnrow['gid']}Qst{$fnrow['title']}OptOther";
$fnames[] = array("$field", "$ftitle", "{$fnrow['question']}<br />\n[Other]", "{$fnrow['gid']}"); $fnames[] = array("$field", "$ftitle", "{$fnrow['question']}<br />\n[Other]", $fnrow['gid'], $fnrow['type']);
if ($fnrow['type'] == "P") if ($fnrow['type'] == "P")
{ {
$fnames[] = array("$field"."comment", "$ftitle"."Comment", "{$fnrow['question']}<br />\n[Other]<br />\n[Comment]", "{$fnrow['gid']}"); $fnames[] = array("$field"."comment", "$ftitle"."Comment", "{$fnrow['question']}<br />\n[Other]<br />\n[Comment]", $fnrow['gid'], $fnrow['type']);
} }
} }
} }
@@ -475,7 +504,39 @@ elseif ($subaction == "all")
{ {
$field = "{$fnrow['sid']}X{$fnrow['gid']}X{$fnrow['qid']}$i"; $field = "{$fnrow['sid']}X{$fnrow['gid']}X{$fnrow['qid']}$i";
$ftitle = "Grp{$fnrow['qid']}Qst{$fnrow['title']}Opt$i"; $ftitle = "Grp{$fnrow['qid']}Qst{$fnrow['title']}Opt$i";
$fnames[] = array("$field", "$ftitle", "{$fnrow['question']}<br />\n[$i]", "{$fnrow['gid']}"); $fnames[] = array("$field", "$ftitle", "{$fnrow['question']}<br />\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 :)<br />$ab2query<br />".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']}<br />\n[{$i2row['answer']}]<br />[{$ls['title']}]", $fnrow['qid'], $fnrow['type']);
}
} }
} }
else else
@@ -492,17 +553,17 @@ elseif ($subaction == "all")
$field = "{$fnrow['sid']}X{$fnrow['gid']}X{$fnrow['qid']}{$i2row['code']}"; $field = "{$fnrow['sid']}X{$fnrow['gid']}X{$fnrow['qid']}{$i2row['code']}";
$ftitle = "Grp{$fnrow['gid']}Qst{$fnrow['title']}Opt{$i2row['code']}"; $ftitle = "Grp{$fnrow['gid']}Qst{$fnrow['title']}Opt{$i2row['code']}";
if ($i2row['other'] == "Y") {$otherexists = "Y";} if ($i2row['other'] == "Y") {$otherexists = "Y";}
$fnames[] = array("$field", "$ftitle", "{$fnrow['question']}<br />\n[{$i2row['answer']}]", "{$fnrow['gid']}"); $fnames[] = array("$field", "$ftitle", "{$fnrow['question']}<br />\n[{$i2row['answer']}]", $fnrow['gid'], $fnrow['type']);
if ($fnrow['type'] == "P") {$fnames[] = array("$field"."comment", "$ftitle", "{$fnrow['question']}<br />\n[{$i2row['answer']}]<br />\n[Comment]", "{$fnrow['gid']}");} if ($fnrow['type'] == "P") {$fnames[] = array("$field"."comment", "$ftitle", "{$fnrow['question']}<br />\n[{$i2row['answer']}]<br />\n[Comment]", $fnrow['gid'], $fnrow['type']);}
} }
if ($otherexists == "Y") if ($otherexists == "Y")
{ {
$field = "{$fnrow['sid']}X{$fnrow['gid']}X{$fnrow['qid']}"."other"; $field = "{$fnrow['sid']}X{$fnrow['gid']}X{$fnrow['qid']}"."other";
$ftitle = "Grp{$fnrow['gid']}Qst{$fnrow['title']}OptOther"; $ftitle = "Grp{$fnrow['gid']}Qst{$fnrow['title']}OptOther";
$fnames[] = array("$field", "$ftitle", "{$fnrow['question']}<br />\n[Other]", "{$fnrow['gid']}"); $fnames[] = array("$field", "$ftitle", "{$fnrow['question']}<br />\n[Other]", $fnrow['gid'], $fnrow['type']);
if ($fnrow['type'] == "P") if ($fnrow['type'] == "P")
{ {
$fnames[] = array("$field"."comment", "$ftitle"."Comment", "{$fnrow['question']}<br />\n[Other]<br />\n[Comment]", "{$fnrow['gid']}"); $fnames[] = array("$field"."comment", "$ftitle"."Comment", "{$fnrow['question']}<br />\n[Other]<br />\n[Comment]", $fnrow['gid'], $fnrow['type']);
} }
} }
} }
@@ -512,10 +573,10 @@ elseif ($subaction == "all")
//NOW LETS CREATE A TABLE WITH THOSE HEADINGS //NOW LETS CREATE A TABLE WITH THOSE HEADINGS
if ($fncount < 10) {$cellwidth = "10%";} else {$cellwidth = "100";} if ($fncount < 10) {$cellwidth = "10%";} else {$cellwidth = "100";}
$tableheader = "<!-- DATA TABLE -->"; $tableheader = "<!-- DATA TABLE -->";
if ($fncount < 10) {$tableheader .= "<table width='100%' border='0' cellpadding='0' cellspacing='1' style='border: 1px solid #555555' class='menu2columns'>\n";} if ($fncount < 10) {$tableheader .= "<table class='browsetable' width='100%' cellpadding='0' cellspacing='1'>\n";}
else {$fnwidth = (($fncount-1)*180); $tableheader .= "<table width='$fnwidth' border='0' cellpadding='1' cellspacing='1' style='border: 1px solid #555555'>\n";} else {$tableheader .= "<table class='browsetable' border='0' cellpadding='1' cellspacing='1' style='border: 1px solid #555555'>\n";}
$tableheader .= "\t<tr valign='top'>\n" $tableheader .= "\t<thead><tr valign='top'>\n"
. "\t\t<td class='evenrow' width='$cellwidth'><strong>id</strong></td>\n"; . "\t\t<th class='evenrow' width='$cellwidth'><strong>id</strong></th>\n";
foreach ($fnames as $fn) foreach ($fnames as $fn)
{ {
if (!isset($currentgroup)) {$currentgroup = $fn[3]; $gbc = "oddrow";} if (!isset($currentgroup)) {$currentgroup = $fn[3]; $gbc = "oddrow";}
@@ -525,11 +586,11 @@ elseif ($subaction == "all")
if ($gbc == "oddrow") {$gbc = "evenrow";} if ($gbc == "oddrow") {$gbc = "evenrow";}
else {$gbc = "oddrow";} else {$gbc = "oddrow";}
} }
$tableheader .= "\t\t<td class='$gbc' width='$cellwidth'><strong>" $tableheader .= "\t\t<th class='$gbc' width='$cellwidth'><strong>"
. strip_tags("$fn[2]") . strip_tags(strip_javascript("$fn[2]"))
. "</strong></td>\n"; . "</strong></th>\n";
} }
$tableheader .= "\t</tr>\n\n"; $tableheader .= "\t</tr></thead>\n\n";
$start=returnglobal('start'); $start=returnglobal('start');
$limit=returnglobal('limit'); $limit=returnglobal('limit');
@@ -538,7 +599,8 @@ elseif ($subaction == "all")
//LETS COUNT THE DATA //LETS COUNT THE DATA
$dtquery = "SELECT count(*) FROM $surveytable"; $dtquery = "SELECT count(*) FROM $surveytable";
if (incompleteAnsFilterstate() === true) {$dtquery .= " WHERE submitdate is not null ";} if (incompleteAnsFilterstate() == "inc") {$dtquery .= "WHERE submitdate IS NULL ";}
elseif (incompleteAnsFilterstate() == "filter") {$dtquery .= " WHERE submitdate is not null ";}
$dtresult=db_execute_num($dtquery); $dtresult=db_execute_num($dtquery);
while ($dtrow=$dtresult->FetchRow()) {$dtcount=$dtrow[0];} while ($dtrow=$dtresult->FetchRow()) {$dtcount=$dtrow[0];}
@@ -550,13 +612,18 @@ elseif ($subaction == "all")
if ($_POST['sql'] == "NULL") if ($_POST['sql'] == "NULL")
{ {
$dtquery = "SELECT *, CASE WHEN submitdate IS NULL THEN 'N' ELSE 'Y' END as completed FROM $surveytable "; $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 ";} if (incompleteAnsFilterstate() == "inc") {$dtquery .= "WHERE submitdate is null";}
elseif (incompleteAnsFilterstate() == "filter") {$dtquery .= " WHERE submitdate is not null ";}
$dtquery .= " ORDER BY id"; $dtquery .= " ORDER BY id";
} }
else else
{ {
$dtquery = "SELECT *, CASE WHEN submitdate IS NULL THEN 'N' ELSE 'Y' END as completed FROM $surveytable WHERE "; $dtquery = "SELECT *, CASE WHEN submitdate IS NULL THEN 'N' ELSE 'Y' END as completed FROM $surveytable WHERE ";
if (incompleteAnsFilterstate() === true) { if (incompleteAnsFilterstate() == "inc") {
$dtquery .= "submitdate is null ";
if (stripcslashes($_POST['sql']) !== "") { $dtquery .= " AND "; }
}
elseif (incompleteAnsFilterstate() == "filter") {
$dtquery .= " submitdate is not null "; $dtquery .= " submitdate is not null ";
if (stripcslashes($_POST['sql']) !== "") { $dtquery .= " AND "; } if (stripcslashes($_POST['sql']) !== "") { $dtquery .= " AND "; }
} }
@@ -567,7 +634,8 @@ elseif ($subaction == "all")
else else
{ {
$dtquery = "SELECT *, CASE WHEN submitdate IS NULL THEN 'N' ELSE 'Y' END as completed FROM $surveytable "; $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 ";} if (incompleteAnsFilterstate() == "inc") {$dtquery .= " WHERE submitdate is null ";}
elseif (incompleteAnsFilterstate() == "filter") {$dtquery .= " WHERE submitdate is not null ";}
$dtquery .= " ORDER BY id"; $dtquery .= " ORDER BY id";
} }
if ($order == "desc") {$dtquery .= " DESC";} if ($order == "desc") {$dtquery .= " DESC";}
@@ -619,28 +687,37 @@ elseif ($subaction == "all")
$browseoutput .= "\t<tr><td align='left'>\n"; $browseoutput .= "\t<tr><td align='left'>\n";
} }
if (incompleteAnsFilterstate() === true) if(incompleteAnsFilterstate() == "inc")
{
$selecthide="";
$selectshow="";
$selectinc="selected='selected'";
}
elseif (incompleteAnsFilterstate() == "filter")
{ {
$selecthide="selected='selected'"; $selecthide="selected='selected'";
$selectshow=""; $selectshow="";
$selectinc="";
} }
else else
{ {
$selecthide=""; $selecthide="";
$selectshow="selected='selected'"; $selectshow="selected='selected'";
$selectinc="";
} }
$browseoutput .=("\t\t</td>\n" $browseoutput .=("\t\t</td>\n"
."\t\t<td align='left' valign='center'>\n" ."\t\t<td align='left'>\n"
."\t\t<form action='$scriptname?action=browse' method='post'><font size='1' face='verdana'>\n" ."\t\t<form action='$scriptname?action=browse' method='post'><font size='1' face='verdana'>\n"
."\t\t\t<img src='$imagefiles/blank.gif' width='31' height='20' border='0' hspace='0' align='right' alt='' />\n" ."\t\t\t<img src='$imagefiles/blank.gif' width='31' height='20' border='0' hspace='0' align='right' alt='' />\n"
."\t\t\t".$clang->gT("Records Displayed:")."<input type='text' size='4' value='$dtcount2' name='limit' id='limit' />\n" ."\t\t\t".$clang->gT("Records Displayed:")."<input type='text' size='4' value='$dtcount2' name='limit' id='limit' />\n"
."\t\t\t&nbsp&nbsp ".$clang->gT("Starting From:")."<input type='text' size='4' value='$start' name='start' id='start' />\n" ."\t\t\t&nbsp;&nbsp; ".$clang->gT("Starting From:")."<input type='text' size='4' value='$start' name='start' id='start' />\n"
."\t\t\t&nbsp&nbsp ".$clang->gT("Filter incomplete answers:")."<select name='filterinc' onchange='javascript:document.getElementById(\"limit\").value=\"\";submit();'>\n" ."\t\t\t&nbsp;&nbsp; ".$clang->gT("Display:")."<select name='filterinc' onchange='javascript:document.getElementById(\"limit\").value=\"\";submit();'>\n"
."\t\t\t\t<option value='filter' $selecthide>".$clang->gT("Enable")."</option>\n" ."\t\t\t\t<option value='filter' $selecthide>".$clang->gT("Completed Records Only")."</option>\n"
."\t\t\t\t<option value='show' $selectshow>".$clang->gT("Disable")."</option>\n" ."\t\t\t\t<option value='show' $selectshow>".$clang->gT("All Records")."</option>\n"
."\t\t\t\t<option value='incomplete' $selectinc>".$clang->gT("Incomplete Records Only")."</option>\n"
."\t\t\t</select>\n" ."\t\t\t</select>\n"
."\t\t\t&nbsp&nbsp&nbsp&nbsp<input type='submit' value='".$clang->gT("Show")."' />\n" ."\t\t\t&nbsp;&nbsp;&nbsp;&nbsp;<input type='submit' value='".$clang->gT("Show")."' />\n"
."\t\t</font>\n" ."\t\t</font>\n"
."\t\t<input type='hidden' name='sid' value='$surveyid' />\n" ."\t\t<input type='hidden' name='sid' value='$surveyid' />\n"
."\t\t<input type='hidden' name='action' value='browse' />\n" ."\t\t<input type='hidden' name='action' value='browse' />\n"
@@ -655,6 +732,7 @@ elseif ($subaction == "all")
."<table><tr><td></td></tr></table>\n"; ."<table><tr><td></td></tr></table>\n";
$browseoutput .= $tableheader; $browseoutput .= $tableheader;
$dateformatdetails=getDateFormatData($_SESSION['dateformat']);
while ($dtrow = $dtresult->FetchRow()) while ($dtrow = $dtresult->FetchRow())
{ {
@@ -665,12 +743,12 @@ elseif ($subaction == "all")
else {$bgcc = "evenrow";} else {$bgcc = "evenrow";}
} }
$browseoutput .= "\t<tr class='$bgcc' valign='top'>\n" $browseoutput .= "\t<tr class='$bgcc' valign='top'>\n"
."\t\t<td align='center'><font face='verdana' size='1'>\n" ."\t\t<td align='center'>\n"
."\t\t\t<a href='$scriptname?action=browse&amp;sid=$surveyid&amp;subaction=id&amp;id={$dtrow['id']}' title='".$clang->gT("View This Record")."'>" ."\t\t\t<a href='$scriptname?action=browse&amp;sid=$surveyid&amp;subaction=id&amp;id={$dtrow['id']}' title='".$clang->gT("View This Record")."'>"
."{$dtrow['id']}</a></font></td>\n"; ."{$dtrow['id']}</a></td>\n";
$i = 0; $i = 0;
if ($private == "N") if ($private == "N" && $dtrow['token'])
{ {
$SQL = "Select * FROM ".db_table_name('tokens_'.$surveyid)." WHERE token=?"; $SQL = "Select * FROM ".db_table_name('tokens_'.$surveyid)." WHERE token=?";
if ( db_tables_exist(db_table_name_nq('tokens_'.$surveyid)) && if ( db_tables_exist(db_table_name_nq('tokens_'.$surveyid)) &&
@@ -678,7 +756,7 @@ elseif ($subaction == "all")
{ {
$TokenRow = $SQLResult->FetchRow(); $TokenRow = $SQLResult->FetchRow();
} }
$browseoutput .= "\t\t<td align='center'><font size='1'>\n"; $browseoutput .= "\t\t<td align='center'>\n";
if (isset($TokenRow) && $TokenRow) if (isset($TokenRow) && $TokenRow)
{ {
$browseoutput .= "\t\t<a href='$scriptname?action=tokens&amp;sid=$surveyid&amp;subaction=edit&amp;tid={$TokenRow['tid']}' title='".$clang->gT("Edit this token")."'>"; $browseoutput .= "\t\t<a href='$scriptname?action=tokens&amp;sid=$surveyid&amp;subaction=edit&amp;tid={$TokenRow['tid']}' title='".$clang->gT("Edit this token")."'>";
@@ -693,9 +771,14 @@ elseif ($subaction == "all")
for ($i; $i<$fncount; $i++) for ($i; $i<$fncount; $i++)
{ {
$browseoutput .= "\t\t<td align='center'><font size='1' face='verdana'>" $browsedatafield=htmlspecialchars($dtrow[$fnames[$i][0]]);
. htmlspecialchars($dtrow[$fnames[$i][0]]) if ($fnames[$i][4]=='D' && $dtrow[$fnames[$i][0]]!='N' && $dtrow[$fnames[$i][0]]!='Y' && $dtrow[$fnames[$i][0]]!='')
."</font></td>\n"; {
$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='&nbsp;';
$browseoutput .= "\t\t<td align='center'>$browsedatafield</td>\n";
} }
$browseoutput .= "\t</tr>\n"; $browseoutput .= "\t</tr>\n";
} }
@@ -703,10 +786,7 @@ elseif ($subaction == "all")
} }
else else
{ {
$browseoutput .= "\t<tr><td colspan='2' height='4'><strong>" $browseoutput .= '<tr><td>'.$surveyoptions;
. $clang->gT("Browse Responses").":</strong> $surveyname</td></tr>\n"
. $surveyoptions;
$browseoutput .= "</table>\n";
$num_total_answers=0; $num_total_answers=0;
$num_completed_answers=0; $num_completed_answers=0;
$gnquery = "SELECT count(id) FROM $surveytable"; $gnquery = "SELECT count(id) FROM $surveytable";
@@ -721,7 +801,7 @@ else
.sprintf($clang->gT("%d full responses"), $num_completed_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).")" .sprintf($clang->gT("%d responses not completely filled out"), $num_total_answers-$num_completed_answers).")"
."\t</td></tr>\n" ."\t</td></tr>\n"
."</table>\n"; ."</table></table>\n";
} }

View File

@@ -30,7 +30,7 @@
If you want to distribute this code, please do it as a link to: If you want to distribute this code, please do it as a link to:
http://alexandre.alapetite.net/doc-alex/domxml-php4-php5/ http://alexandre.alapetite.net/doc-alex/domxml-php4-php5/
*/ */
@ini_set('zend.ze1_compatibility_mode', '0');
define('DOMXML_LOAD_PARSING',0); define('DOMXML_LOAD_PARSING',0);
define('DOMXML_LOAD_VALIDATING',1); define('DOMXML_LOAD_VALIDATING',1);
define('DOMXML_LOAD_RECOVERING',2); 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_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_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 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('&apos;'=>'\'')),ENT_QUOTES,'UTF-8');} function _entityDecode($text) {return html_entity_decode(strtr($text,array('&apos;'=>'\'')),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)));} 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 class php4DOMAttr extends php4DOMNode

View File

@@ -3,7 +3,7 @@
/******************************************************************************* /*******************************************************************************
* *
* SHA256 static class for PHP4 * SHA256 static class for PHP
* implemented by feyd _at_ devnetwork .dot. net * implemented by feyd _at_ devnetwork .dot. net
* specification from http://csrc.nist.gov/cryptval/shs/sha256-384-512.pdf * specification from http://csrc.nist.gov/cryptval/shs/sha256-384-512.pdf
* *
@@ -15,10 +15,10 @@
*----- Version 1.0.1 ---------------------------------------------------------- *----- Version 1.0.1 ----------------------------------------------------------
* *
* Syntax: * Syntax:
* string SHA256::hash( string message[, string format ]) * string SHA256::hashing( string message[, string format ])
* *
* Description: * 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: * and optionally `format`. Possible values for `format` are:
* 'bin' binary string output * 'bin' binary string output
* 'hex' default; hexidecimal string output (lower case) * 'hex' default; hexidecimal string output (lower case)
@@ -26,7 +26,7 @@
* Failures return FALSE. * Failures return FALSE.
* *
* Usage: * 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() // static class. Access via SHA256::hash()
class SHA256 extends hash class SHA256 extends hash
{ {
function hash($str, $mode = 'hex') static function hashing($str, $mode = 'hex')
{ {
static $modes = array( 'hex', 'bin', 'bit' ); static $modes = array( 'hex', 'bin', 'bit' );
$ret = false; $ret = false;
@@ -147,7 +147,7 @@ class SHA256 extends hash
} }
else else
{ {
$data =& new SHA256Data($str); $data = new SHA256Data($str);
SHA256::compute($data); SHA256::compute($data);
@@ -171,7 +171,7 @@ class SHA256 extends hash
// begin internal functions // begin internal functions
// 32-bit summation // 32-bit summation
function sum() static function sum()
{ {
$T = 0; $T = 0;
for($x = 0, $y = func_num_args(); $x < $y; $x++) for($x = 0, $y = func_num_args(); $x < $y; $x++)
@@ -202,7 +202,7 @@ class SHA256 extends hash
// compute the hash // compute the hash
function compute(&$hashData) static function compute(&$hashData)
{ {
static $vars = 'abcdefgh'; static $vars = 'abcdefgh';
static $K = null; static $K = null;
@@ -292,7 +292,7 @@ class SHA256 extends hash
// set up the display of the hash in hex. // set up the display of the hash in hex.
function hashHex(&$hashData) static function hashHex(&$hashData)
{ {
$str = ''; $str = '';
@@ -385,7 +385,7 @@ function test1()
echo 'Testing ' . var_export($str,true) . "\n"; echo 'Testing ' . var_export($str,true) . "\n";
list($s1,$s2) = explode(' ', microtime()); list($s1,$s2) = explode(' ', microtime());
for($x = 0; $x < $it; $x++) for($x = 0; $x < $it; $x++)
$data =& new SHA256Data($str); $data = new SHA256Data($str);
list($e1,$e2) = explode(' ', microtime()); list($e1,$e2) = explode(' ', microtime());
echo hexerize($data->chunks); echo hexerize($data->chunks);
echo hexerize($data->hash); echo hexerize($data->hash);

View File

@@ -305,7 +305,7 @@ class OLE extends PEAR
* @param string $ascii The ASCII string to transform * @param string $ascii The ASCII string to transform
* @return string The string in Unicode * @return string The string in Unicode
*/ */
function Asc2Ucs($ascii) static function Asc2Ucs($ascii)
{ {
$rawname = ''; $rawname = '';
for ($i = 0; $i < strlen($ascii); $i++) { for ($i = 0; $i < strlen($ascii); $i++) {
@@ -323,7 +323,7 @@ class OLE extends PEAR
* @param integer $date A timestamp * @param integer $date A timestamp
* @return string The string for the OLE container * @return string The string for the OLE container
*/ */
function LocalDate2OLE($date = null) static function LocalDate2OLE($date = null)
{ {
if (!isset($date)) { if (!isset($date)) {
return "\x00\x00\x00\x00\x00\x00\x00\x00"; 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 * @param integer $string A binary string with the encoded date
* @return string The timestamp corresponding to the string * @return string The timestamp corresponding to the string
*/ */
function OLE2LocalDate($string) static function OLE2LocalDate($string)
{ {
if (strlen($string) != 8) { if (strlen($string) != 8) {
return new PEAR_Error("Expecting 8 byte string"); return new PEAR_Error("Expecting 8 byte string");

View File

@@ -266,7 +266,7 @@ class PEAR
*/ */
function isError($data, $code = null) function isError($data, $code = null)
{ {
if (is_a($data, 'PEAR_Error')) { if ($data instanceof PEAR_Error) {
if (is_null($code)) { if (is_null($code)) {
return true; return true;
} elseif (is_string($code)) { } elseif (is_string($code)) {
@@ -554,10 +554,10 @@ class PEAR
$ec = 'PEAR_Error'; $ec = 'PEAR_Error';
} }
if ($skipmsg) { if ($skipmsg) {
$a = &new $ec($code, $mode, $options, $userinfo); $a = new $ec($code, $mode, $options, $userinfo);
return $a; return $a;
} else { } else {
$a = &new $ec($message, $code, $mode, $options, $userinfo); $a = new $ec($message, $code, $mode, $options, $userinfo);
return $a; return $a;
} }
} }

View File

@@ -1207,7 +1207,7 @@ class Spreadsheet_Excel_Writer_Parser extends PEAR
default: default:
// if it's a reference // if it's a reference
if (preg_match('/^\$?[A-Ia-i]?[A-Za-z]\$?[0-9]+$/',$token) and 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 != ':') and ($this->_lookahead != '.') and
($this->_lookahead != '!')) ($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) // 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 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 != '.')) ($this->_lookahead != ':') and ($this->_lookahead != '.'))
{ {
return $token; return $token;
} }
// If it's an external reference ('Sheet1'!A1 or 'Sheet1:Sheet2'!A1) // 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 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 != '.')) ($this->_lookahead != ':') and ($this->_lookahead != '.'))
{ {
return $token; return $token;
} }
// if it's a range (A1:A2) // 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 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; return $token;
} }
// if it's a range (A1..A2) // 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 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; return $token;
} }
// If it's an external range like Sheet1!A1 or Sheet1:Sheet2!A1:B2 // 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 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; return $token;
} }
// If it's an external range like 'Sheet1'!A1 or 'Sheet1:Sheet2'!A1:B2 // 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 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; return $token;
} }
@@ -1259,12 +1259,12 @@ class Spreadsheet_Excel_Writer_Parser extends PEAR
return $token; return $token;
} }
// If it's a string (of maximum 255 characters) // If it's a string (of maximum 255 characters)
elseif (ereg("^\"[^\"]{0,255}\"$",$token)) elseif (preg_match("/^\"[^\"]{0,255}\"$/",$token))
{ {
return $token; return $token;
} }
// if it's a function call // 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; return $token;
} }
@@ -1364,7 +1364,7 @@ class Spreadsheet_Excel_Writer_Parser extends PEAR
function _expression() function _expression()
{ {
// If it's a string return a string node // 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, '', ''); $result = $this->_createTree($this->_current_token, '', '');
$this->_advance(); $this->_advance();
return $result; return $result;
@@ -1522,7 +1522,7 @@ class Spreadsheet_Excel_Writer_Parser extends PEAR
return $result; return $result;
} }
// if it's a function call // 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(); $result = $this->_func();
return $result; return $result;

View File

@@ -184,7 +184,7 @@ class Spreadsheet_Excel_Writer_Workbook extends Spreadsheet_Excel_Writer_BIFFwri
$this->Spreadsheet_Excel_Writer_BIFFwriter(); $this->Spreadsheet_Excel_Writer_BIFFwriter();
$this->_filename = $filename; $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->_1904 = 0;
$this->_activesheet = 0; $this->_activesheet = 0;
$this->_firstsheet = 0; $this->_firstsheet = 0;
@@ -193,7 +193,7 @@ class Spreadsheet_Excel_Writer_Workbook extends Spreadsheet_Excel_Writer_BIFFwri
$this->_fileclosed = 0; $this->_fileclosed = 0;
$this->_biffsize = 0; $this->_biffsize = 0;
$this->_sheetname = 'Sheet'; $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->_worksheets = array();
$this->_sheetnames = array(); $this->_sheetnames = array();
$this->_formats = array(); $this->_formats = array();

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,190 @@
<?php
/**
* @file CAS/PGTStorage/pgt-db.php
* Basic class for PGT database storage
*/
/**
* @class PGTStorageDB
* The PGTStorageDB class is a class for PGT database storage. An instance of
* this class is returned by CASClient::SetPGTStorageDB().
*
* @author Pascal Aubry <pascal.aubry at univ-rennes1.fr>
*
* @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();
}
/** @} */
}
?>

View File

@@ -0,0 +1,249 @@
<?php
/**
* @file CAS/PGTStorage/pgt-file.php
* Basic class for PGT file storage
*/
/**
* @class PGTStorageFile
* The PGTStorageFile class is a class for PGT file storage. An instance of
* this class is returned by CASClient::SetPGTStorageFile().
*
* @author Pascal Aubry <pascal.aubry at univ-rennes1.fr>
*
* @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;
}
/** @} */
}
?>

View File

@@ -0,0 +1,188 @@
<?php
/**
* @file CAS/PGTStorage/pgt-main.php
* Basic class for PGT storage
*/
/**
* @class PGTStorage
* The PGTStorage class is a generic class for PGT storage. This class should
* not be instanciated itself but inherited by specific PGT storage classes.
*
* @author Pascal Aubry <pascal.aubry at univ-rennes1.fr>
*
* @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');
?>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,277 @@
<?php
/**
* @file domxml-php4-php5.php
* Require PHP5, uses built-in DOM extension.
* To be used in PHP4 scripts using DOMXML extension.
* Allows PHP4/DOMXML scripts to run on PHP5/DOM.
* (Requires PHP5/XSL extension for domxml_xslt functions)
*
* Typical use:
* <pre>
* {
* if (version_compare(PHP_VERSION,'5','>='))
* require_once('domxml-php4-to-php5.php');
* }
* </pre>
*
* Version 1.5.5, 2005-01-18, http://alexandre.alapetite.net/doc-alex/domxml-php4-php5/
*
* ------------------------------------------------------------------<br>
* 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();}
}
}
?>

View File

@@ -0,0 +1,27 @@
<?php
/**
* @file languages/spanish.php
* @author Iván-Benjamín García Torà <ivaniclixx AT gmail DOT com>
* @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 <a href="%s">aquí</a> per a continuar.',
CAS_STR_AUTHENTICATION_FAILED
=> 'Autentificació CAS fallida!',
CAS_STR_YOU_WERE_NOT_AUTHENTICATED
=> '<p>No estàs autentificat.</p><p>Pots tornar a intentar-ho fent click <a href="%s">aquí</a>.</p><p>Si el problema persisteix hauría de contactar amb l\'<a href="mailto:%s">administrador d\'aquest llocc</a>.</p>',
CAS_STR_SERVICE_UNAVAILABLE
=> 'El servei `<b>%s</b>\' no està disponible (<b>%s</b>).'
);
?>

View File

@@ -0,0 +1,27 @@
<?php
/**
* @file languages/english.php
* @author Pascal Aubry <pascal.aubry at univ-rennes1.fr>
* @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 <a href="%s">here</a> to continue.',
CAS_STR_AUTHENTICATION_FAILED
=> 'CAS Authentication failed!',
CAS_STR_YOU_WERE_NOT_AUTHENTICATED
=> '<p>You were not authenticated.</p><p>You may submit your request again by clicking <a href="%s">here</a>.</p><p>If the problem persists, you may contact <a href="mailto:%s">the administrator of this site</a>.</p>',
CAS_STR_SERVICE_UNAVAILABLE
=> 'The service `<b>%s</b>\' is not available (<b>%s</b>).'
);
?>

View File

@@ -0,0 +1,28 @@
<?php
/**
* @file languages/english.php
* @author Pascal Aubry <pascal.aubry at univ-rennes1.fr>
* @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&nbsp;!',
CAS_STR_LOGOUT
=> 'Déconnexion demandée&nbsp;!',
CAS_STR_SHOULD_HAVE_BEEN_REDIRECTED
=> 'Vous auriez du etre redirigé(e) vers le serveur CAS. Cliquez <a href="%s">ici</a> pour continuer.',
CAS_STR_AUTHENTICATION_FAILED
=> 'Authentification CAS infructueuse&nbsp;!',
CAS_STR_YOU_WERE_NOT_AUTHENTICATED
=> '<p>Vous n\'avez pas été authentifié(e).</p><p>Vous pouvez soumettre votre requete à nouveau en cliquant <a href="%s">ici</a>.</p><p>Si le problème persiste, vous pouvez contacter <a href="mailto:%s">l\'administrateur de ce site</a>.</p>',
CAS_STR_SERVICE_UNAVAILABLE
=> 'Le service `<b>%s</b>\' est indisponible (<b>%s</b>)'
);
?>

View File

@@ -0,0 +1,27 @@
<?php
/**
* @file languages/german.php
* @author Henrik Genssen <hg at mediafactory.de>
* @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&auml;ten Sie zum CAS Server weitergeleitet werden sollen. Dr&uuml;cken Sie <a href="%s">hier</a> um fortzufahren.',
CAS_STR_AUTHENTICATION_FAILED
=> 'CAS Anmeldung fehlgeschlagen!',
CAS_STR_YOU_WERE_NOT_AUTHENTICATED
=> '<p>Sie wurden nicht angemeldet.</p><p>Um es erneut zu versuchen klicken Sie <a href="%s">hier</a>.</p><p>Wenn das Problem bestehen bleibt, kontkatieren Sie den <a href="mailto:%s">Administrator</a> dieser Seite.</p>',
CAS_STR_SERVICE_UNAVAILABLE
=> 'Der Dienst `<b>%s</b>\' ist nicht verf&uuml;gbar (<b>%s</b>).'
);
?>

View File

@@ -0,0 +1,27 @@
<?php
/**
* @file languages/greek.php
* @author Vangelis Haniotakis <haniotak at ucnet.uoc.gr>
* @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. ÊÜíôå êëßê <a href="%s">åäþ</a> ãéá íá óõíå÷ßóåôå.',
CAS_STR_AUTHENTICATION_FAILED
=> 'Ç ôáõôïðïßçóç CAS áðÝôõ÷å!',
CAS_STR_YOU_WERE_NOT_AUTHENTICATED
=> '<p>Äåí ôáõôïðïéçèÞêáôå.</p><p>Ìðïñåßôå íá îáíáðñïóðáèÞóåôå, êÜíïíôáò êëßê <a href="%s">åäþ</a>.</p><p>Åáí ôï ðñüâëçìá åðéìåßíåé, åëÜôå óå åðáöÞ ìå ôïí <a href="mailto:%s">äéá÷åéñéóôÞ</a>.</p>',
CAS_STR_SERVICE_UNAVAILABLE
=> 'Ç õðçñåóßá `<b>%s</b>\' äåí åßíáé äéáèÝóéìç (<b>%s</b>).'
);
?>

View File

@@ -0,0 +1,27 @@
<?php
/**
* @file languages/japanese.php
* @author fnorif (fnorif@yahoo.co.jp)
*
* Now Encoding is EUC-JP and LF
**/
$this->_strings = array(
CAS_STR_USING_SERVER
=> 'using server',
CAS_STR_AUTHENTICATION_WANTED
=> 'CASによる認証を行います',
CAS_STR_LOGOUT
=> 'CASからログアウトします!',
CAS_STR_SHOULD_HAVE_BEEN_REDIRECTED
=> 'CASサーバに行く必要があります。自動的に転送されない場合は <a href="%s">こちら</a> をクリックして続行します。',
CAS_STR_AUTHENTICATION_FAILED
=> 'CASによる認証に失敗しました',
CAS_STR_YOU_WERE_NOT_AUTHENTICATED
=> '<p>認証できませんでした.</p><p>もう一度リクエストを送信する場合は<a href="%s">こちら</a>をクリック.</p><p>問題が解決しない場合は <a href="mailto:%s">このサイトの管理者</a>に問い合わせてください.</p>',
CAS_STR_SERVICE_UNAVAILABLE
=> 'サービス `<b>%s</b>\' は利用できません (<b>%s</b>).'
);
?>

View File

@@ -0,0 +1,24 @@
<?php
/**
* @file languages/languages.php
* Internationalization constants
* @author Pascal Aubry <pascal.aubry at univ-rennes1.fr>
* @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);
//@}
?>

View File

@@ -0,0 +1,27 @@
<?php
/**
* @file languages/spanish.php
* @author Iván-Benjamín García Torà <ivaniclixx AT gmail DOT com>
* @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 <a href="%s">aquí</a> para continuar.',
CAS_STR_AUTHENTICATION_FAILED
=> '¡Autentificación CAS fallida!',
CAS_STR_YOU_WERE_NOT_AUTHENTICATED
=> '<p>No estás autentificado.</p><p>Puedes volver a intentarlo haciendo click <a href="%s">aquí</a>.</p><p>Si el problema persiste debería contactar con el <a href="mailto:%s">administrador de este sitio</a>.</p>',
CAS_STR_SERVICE_UNAVAILABLE
=> 'El servicio `<b>%s</b>\' no está disponible (<b>%s</b>).'
);
?>

View File

@@ -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.

View File

@@ -36,7 +36,7 @@ class PHPZip
if (is_file($filename)) if (is_file($filename))
{ {
$fd = fopen ($filename, "r"); $fd = fopen ($filename, "r");
$content = fread ($fd, filesize ($filename)); $content = @fread ($fd, filesize ($filename));
fclose ($fd); fclose ($fd);
if (is_array($dir)) $filename = basename($filename); if (is_array($dir)) $filename = basename($filename);
@@ -218,7 +218,6 @@ class PHPZip
// This comes from http://de.tikiwiki.org/xref-BRANCH-1-9/nav.html?lib/sheet/include/org/apicnet/io/archive/CZip.php.source.html // 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){ function extract($dir, $zipfilename){
if (function_exists("zip_open")) { if (function_exists("zip_open")) {
//$dir = eregi_replace("(\..*$)", "", $zipfilename);
$this->createDir($dir); $this->createDir($dir);
$zip = zip_open($zipfilename); $zip = zip_open($zipfilename);
@@ -226,10 +225,9 @@ function extract($dir, $zipfilename){
while ($zip_entry = zip_read($zip)) { while ($zip_entry = zip_read($zip)) {
if (zip_entry_open($zip, $zip_entry, "r")) { if (zip_entry_open($zip, $zip_entry, "r")) {
$buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry)); $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 // LimeSurvey Only extract first dir for the moment
if ( ! eregi("(\/)", zip_entry_name($zip_entry))) if ( ! preg_match("/(\/)/i", zip_entry_name($zip_entry)))
{ {
$this->createFile($dir."/".zip_entry_name($zip_entry), $buf,zip_entry_filesize($zip_entry)); $this->createFile($dir."/".zip_entry_name($zip_entry), $buf,zip_entry_filesize($zip_entry));
} }
@@ -247,7 +245,7 @@ function extract($dir, $zipfilename){
} }
function createDir($dir){ function createDir($dir){
if (eregi("(\/$)", $dir)) @mkdir (substr($dir, 0, strlen($dir) - 1)); if (preg_match("/(\/$)/", $dir)) @mkdir (substr($dir, 0, strlen($dir) - 1));
else @mkdir ($dir); else @mkdir ($dir);
} }

View File

@@ -1,10 +0,0 @@
<?php
if (version_compare(PHP_VERSION, '5.0.0', '<') && version_compare(PHP_VERSION, '4.0.0', '>'))
{
require_once('tcpdf_php4.php');
}
else if (version_compare(PHP_VERSION, '5.0.0', '>'))
{
require_once('tcpdf.php');
}
?>

View File

@@ -1,19 +1,12 @@
<?php <?php
require_once('checkphpversion.php'); require_once('tcpdf.php');
class PDF extends TCPDF class PDF extends TCPDF
{ {
function PDF($orientation='L', $unit='mm', $format='A4') function PDF($orientation='L', $unit='mm', $format='A4')
{ {
if (version_compare(PHP_VERSION, '5.0.0', '<') && version_compare(PHP_VERSION, '4.0.0', '>')) parent::__construct($orientation,$unit,$format);
{
parent::TCPDF($orientation,$unit,$format);
}
else if(version_compare(PHP_VERSION, '5.0.0', '>'))
{
parent::__construct($orientation,$unit,$format);
}
$this->SetAutoPageBreak(true,10); $this->SetAutoPageBreak(true,10);
$this->AliasNbPages(); $this->AliasNbPages();
@@ -21,6 +14,7 @@ class PDF extends TCPDF
function intopdf($text,$format='') function intopdf($text,$format='')
{ {
$text = $this->delete_html($text);
$oldformat = $this->FontStyle; $oldformat = $this->FontStyle;
$this->SetFont('',$format,$this->FontSizePt); $this->SetFont('',$format,$this->FontSizePt);
$this->Write(5,$text); $this->Write(5,$text);
@@ -31,7 +25,7 @@ class PDF extends TCPDF
{ {
$oldsize = $this->FontSizePt; $oldsize = $this->FontSizePt;
$this->SetFontSize($oldsize-2); $this->SetFontSize($oldsize-2);
$this->Write(5,$text); $this->Write(5,$this->delete_html($text));
$this->ln(5); $this->ln(5);
$this->SetFontSize($oldsize); $this->SetFontSize($oldsize);
} }
@@ -39,6 +33,7 @@ class PDF extends TCPDF
{ {
if(!empty($title)) if(!empty($title))
{ {
$title = $this->delete_html($title);
$oldsize = $this->FontSizePt; $oldsize = $this->FontSizePt;
$this->SetFontSize($oldsize+4); $this->SetFontSize($oldsize+4);
$this->Line(5,$this->y,($this->w-5),$this->y); $this->Line(5,$this->y,($this->w-5),$this->y);
@@ -46,6 +41,7 @@ class PDF extends TCPDF
$this->MultiCell('','',$title,'','C',0); $this->MultiCell('','',$title,'','C',0);
if(!empty($description) && isset($description)) if(!empty($description) && isset($description))
{ {
$description = $this->delete_html($description);
$this->ln(7); $this->ln(7);
$this->SetFontSize($oldsize+2); $this->SetFontSize($oldsize+2);
$this->MultiCell('','',$description,'','C',0); $this->MultiCell('','',$description,'','C',0);
@@ -68,7 +64,7 @@ class PDF extends TCPDF
{ {
for($b=0;$b<sizeof($array[$a]);$b++) for($b=0;$b<sizeof($array[$a]);$b++)
{ {
$this->Cell($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(); $this->ln();
} }
@@ -99,5 +95,11 @@ class PDF extends TCPDF
{ {
$this->Output($name,"D"); $this->Output($name,"D");
} }
function delete_html($text)
{
$text = html_entity_decode($text);
return strip_tags($text);
}
} }
?> ?>

View File

@@ -5548,7 +5548,7 @@ if(!class_exists('TCPDF', false)) {
if (isset($dash)) { if (isset($dash)) {
$dash_string = ""; $dash_string = "";
if ($dash) { if ($dash) {
if (ereg("^.+,", $dash)) { if (preg_match("/^.+,/", $dash)) {
$tab = explode(",", $dash); $tab = explode(",", $dash);
} else { } else {
$tab = array($dash); $tab = array($dash);

File diff suppressed because it is too large Load Diff

View File

@@ -10,7 +10,7 @@
* other free or open source software licenses. * other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details. * See COPYRIGHT.php for copyright notices and details.
* *
* $Id: cmdline_importsurvey.php 5028 2008-06-09 11:20:29Z c_schmitz $ * $Id: cmdline_importsurvey.php 6981 2009-05-30 23:04:55Z c_schmitz $
*/ */
@@ -61,7 +61,7 @@ if ($result->RecordCount() < 1)
else else
{ {
$fields = $result->FetchRow(); $fields = $result->FetchRow();
if (SHA256::hash($userpass) == $fields['password']) if (SHA256::hashing($userpass) == $fields['password'])
{ {
$_SESSION['loginID'] = intval($fields['uid']); $_SESSION['loginID'] = intval($fields['uid']);
$clang = new limesurvey_lang($fields['lang']); $clang = new limesurvey_lang($fields['lang']);

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -10,7 +10,7 @@
* other free or open source software licenses. * other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details. * See COPYRIGHT.php for copyright notices and details.
* *
* $Id: deactivate.php 4916 2008-05-25 17:25:33Z c_schmitz $ * $Id: deactivate.php 6976 2009-05-30 00:53:41Z c_schmitz $
*/ */
include_once("login_check.php"); //Login Check dies also if the script is started directly include_once("login_check.php"); //Login Check dies also if the script is started directly
@@ -21,30 +21,18 @@ $date = date('YmdHis'); //'Hi' adds 24hours+minutes to name to allow multiple de
$deactivateoutput=''; $deactivateoutput='';
if (!isset($_POST['ok']) || !$_POST['ok']) if (!isset($_POST['ok']) || !$_POST['ok'])
{ {
$deactivateoutput .= "<br />\n<table class='alertbox'>\n"; $deactivateoutput .= "<br />\n<div class='messagebox'>\n";
$deactivateoutput .= "\t\t\t\t<tr ><td height='4'><strong>".$clang->gT("Deactivate Survey")." ($surveyid)</strong></td></tr>\n"; $deactivateoutput .= "\t\t\t\t<div class='header'>".$clang->gT("Deactivate Survey")." ($surveyid)</div>\n";
$deactivateoutput .= "\t<tr>\n"; $deactivateoutput .= "\t<div class='warningheader'>\n";
$deactivateoutput .= "\t\t<td align='center' bgcolor='#FFEEEE'>\n";
$deactivateoutput .= "\t\t\t<font color='red'><strong>";
$deactivateoutput .= $clang->gT("Warning")."<br />".$clang->gT("READ THIS CAREFULLY BEFORE PROCEEDING"); $deactivateoutput .= $clang->gT("Warning")."<br />".$clang->gT("READ THIS CAREFULLY BEFORE PROCEEDING");
$deactivateoutput .= "\t\t</strong></font></td>\n"; $deactivateoutput .= "\t\t</div>\n";
$deactivateoutput .= "\t</tr>\n";
$deactivateoutput .= "\t<tr>";
$deactivateoutput .= "\t\t<td>\n";
$deactivateoutput .= "\t\t\t".$clang->gT("In an active survey, a table is created to store all the data-entry records.")."\n"; $deactivateoutput .= "\t\t\t".$clang->gT("In an active survey, a table is created to store all the data-entry records.")."\n";
$deactivateoutput .= "\t\t\t<p>".$clang->gT("When you deactivate a survey all the data entered in the original table will be moved elsewhere, and when you activate the survey again, the table will be empty. You will not be able to access this data using LimeSurvey any more.")."</p>\n"; $deactivateoutput .= "\t\t\t<p>".$clang->gT("When you deactivate a survey all the data entered in the original table will be moved elsewhere, and when you activate the survey again, the table will be empty. You will not be able to access this data using LimeSurvey any more.")."</p>\n";
$deactivateoutput .= "\t\t\t<p>".$clang->gT("Deactivated survey data can only be accessed by system administrators using a Database data access tool like phpmyadmin. If your survey uses tokens, this table will also be renamed and will only be accessible by system administrators.")."</p>\n"; $deactivateoutput .= "\t\t\t<p>".$clang->gT("Deactivated survey data can only be accessed by system administrators using a Database data access tool like phpmyadmin. If your survey uses tokens, this table will also be renamed and will only be accessible by system administrators.")."</p>\n";
$deactivateoutput .= "\t\t\t<p>".$clang->gT("Your responses table will be renamed to:")." {$dbprefix}old_{$_GET['sid']}_{$date}</p>\n"; $deactivateoutput .= "\t\t\t<p>".$clang->gT("Your responses table will be renamed to:")." {$dbprefix}old_{$_GET['sid']}_{$date}</p>\n";
$deactivateoutput .= "\t\t\t<p>".$clang->gT("Also you should export your responses before deactivating.")."</p>\n"; $deactivateoutput .= "\t\t\t<p>".$clang->gT("Also you should export your responses before deactivating.")."</p>\n";
$deactivateoutput .= "\t\t</td>\n"; $deactivateoutput .= "\t\t\t<input type='submit' value='".$clang->gT("Deactivate Survey")."' onclick=\"".get2post("$scriptname?action=deactivate&amp;ok=Y&amp;sid={$_GET['sid']}")."\" />\n";
$deactivateoutput .= "\t</tr>\n"; $deactivateoutput .= "</div><br />\n";
$deactivateoutput .= "\t<tr>\n";
$deactivateoutput .= "\t\t<td align='center'>\n";
// $deactivateoutput .= "\t\t\t<input type='submit' value='".$clang->gT("Deactivate Survey")."' onclick=\"window.open('$scriptname?action=deactivate&amp;ok=Y&amp;sid={$_GET['sid']}', '_self')\">\n";
$deactivateoutput .= "\t\t\t<input type='submit' value='".$clang->gT("Deactivate Survey")."' onclick=\"".get2post("$scriptname?action=deactivate&amp;ok=Y&amp;sid={$_GET['sid']}")."\">\n";
$deactivateoutput .= "\t\t<br />&nbsp;</td>\n";
$deactivateoutput .= "\t</tr>\n";
$deactivateoutput .= "</table><br />&nbsp;\n";
} }
else else

View File

@@ -10,7 +10,7 @@
* other free or open source software licenses. * other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details. * See COPYRIGHT.php for copyright notices and details.
* *
* $Id: deletesurvey.php 4973 2008-06-01 14:07:01Z c_schmitz $ * $Id: deletesurvey.php 7503 2009-08-21 00:30:44Z jcleeland $
*/ */
//Ensure script is not run directly, avoid path disclosure //Ensure script is not run directly, avoid path disclosure
@@ -58,7 +58,7 @@ if (!isset($deleteok) || !$deleteok)
$deletesurveyoutput .= "\t<tr>\n"; $deletesurveyoutput .= "\t<tr>\n";
$deletesurveyoutput .= "\t\t<td align='center'><br />\n"; $deletesurveyoutput .= "\t\t<td align='center'><br />\n";
$deletesurveyoutput .= "\t\t\t<input type='submit' value='".$clang->gT("Cancel")."' onclick=\"window.open('admin.php?sid=$surveyid', '_self')\" /><br />\n"; $deletesurveyoutput .= "\t\t\t<input type='submit' value='".$clang->gT("Cancel")."' onclick=\"window.open('admin.php?sid=$surveyid', '_self')\" /><br />\n";
// $deletesurveyoutput .= "\t\t\t<input type='submit' value='".$clang->gT("Delete")."' onclick=\"window.open('$scriptname?action=deletesurvey&amp;sid=$surveyid&amp;ok=Y','_self')\" />\n"; // $deletesurveyoutput .= "\t\t\t<input type='submit' value='".$clang->gT("Delete")."' onclick=\"window.open('$scriptname?action=deletesurvey&amp;sid=$surveyid&amp;ok=Y','_top')\" />\n";
$deletesurveyoutput .= "\t\t\t<input type='submit' value='".$clang->gT("Delete")."' onclick=\"".get2post("$scriptname?action=deletesurvey&amp;sid=$surveyid&amp;deleteok=Y")."\" />\n"; $deletesurveyoutput .= "\t\t\t<input type='submit' value='".$clang->gT("Delete")."' onclick=\"".get2post("$scriptname?action=deletesurvey&amp;sid=$surveyid&amp;deleteok=Y")."\" />\n";
$deletesurveyoutput .= "\t\t</td>\n"; $deletesurveyoutput .= "\t\t</td>\n";
$deletesurveyoutput .= "\t</tr>\n"; $deletesurveyoutput .= "\t</tr>\n";
@@ -116,6 +116,14 @@ else //delete the survey
$sdel = "DELETE FROM {$dbprefix}surveys WHERE sid=$surveyid"; $sdel = "DELETE FROM {$dbprefix}surveys WHERE sid=$surveyid";
$sres = $connect->Execute($sdel); $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<tr>\n"; $deletesurveyoutput .= "\t<tr>\n";
$deletesurveyoutput .= "\t\t<td align='center'><br />\n"; $deletesurveyoutput .= "\t\t<td align='center'><br />\n";

View File

@@ -10,12 +10,12 @@
* other free or open source software licenses. * other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details. * See COPYRIGHT.php for copyright notices and details.
* *
* $Id: dumpdb.php 4727 2008-04-29 04:31:51Z jcleeland $ * $Id: dumpdb.php 7519 2009-08-23 21:55:32Z c_schmitz $
*/ */
include_once("login_check.php"); //Login Check dies also if the script is started directly include_once("login_check.php"); //Login Check dies also if the script is started directly
if ($database_exists && $databasetype=='mysql') { if ($database_exists && ($databasetype=='mysql' || $databasetype=='mysqli') && $demoModeOnly != true) {
$tables = $connect->MetaTables(); $tables = $connect->MetaTables();
@@ -77,7 +77,7 @@ if ($database_exists && $databasetype=='mysql') {
if ($row["Extra"] != "") $def .= " $row[Extra]"; if ($row["Extra"] != "") $def .= " $row[Extra]";
$def .= ",\n"; $def .= ",\n";
} }
$def = ereg_replace(",\n$","", $def); $def = preg_replace("#,\n$#","", $def);
$result = db_execute_assoc("SHOW KEYS FROM $tablename"); $result = db_execute_assoc("SHOW KEYS FROM $tablename");
while($row = $result->FetchRow()) while($row = $result->FetchRow())
@@ -116,9 +116,17 @@ if ($database_exists && $databasetype=='mysql') {
@set_time_limit(5); @set_time_limit(5);
$result .= "INSERT INTO ".$table." VALUES("; $result .= "INSERT INTO ".$table." VALUES(";
for($j=0; $j<$num_fields; $j++) { for($j=0; $j<$num_fields; $j++) {
$row[$j] = addslashes($row[$j]); if (isset($row[$j]) && !is_null($row[$j]))
$row[$j] = ereg_replace("\n","\\n",$row[$j]); {
if (isset($row[$j])) $result .= "\"$row[$j]\"" ; else $result .= "\"\""; $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 .= ","; if ($j<($num_fields-1)) $result .= ",";
} }
$result .= ");\n"; $result .= ");\n";

View File

@@ -10,7 +10,7 @@
* other free or open source software licenses. * other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details. * See COPYRIGHT.php for copyright notices and details.
* *
* $Id: dumpgroup.php 4646 2008-04-14 18:47:45Z awarren $ * $Id: dumpgroup.php 6853 2009-05-15 12:51:09Z c_schmitz $
*/ */
@@ -62,34 +62,94 @@ header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Pragma: cache"); header("Pragma: cache");
//0: Groups Table //0: Groups Table
$gquery = "SELECT * FROM {$dbprefix}groups WHERE gid=$gid"; $gquery = "SELECT *
FROM {$dbprefix}groups
WHERE gid=$gid";
$gdump = BuildCSVFromQuery($gquery); $gdump = BuildCSVFromQuery($gquery);
//1: Questions Table //1: Questions Table
$qquery = "SELECT * FROM {$dbprefix}questions WHERE gid=$gid"; $qquery = "SELECT *
FROM {$dbprefix}questions
WHERE gid=$gid";
$qdump = BuildCSVFromQuery($qquery); $qdump = BuildCSVFromQuery($qquery);
//2: Answers table //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)"; $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); $adump = BuildCSVFromQuery($aquery);
//3: Conditions table - THIS CAN ONLY EXPORT CONDITIONS THAT RELATE TO THE SAME GROUP //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)"; $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); $cdump = BuildCSVFromQuery($cquery);
//4: Labelsets Table //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)"; $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); $lsdump = BuildCSVFromQuery($lsquery);
//5: Labels Table //5: Labelsets1 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)"; //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); $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 //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)"; $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); $qadump = BuildCSVFromQuery($query);
// HTTP/1.0 // HTTP/1.0
echo $dumphead, $gdump, $qdump, $adump, $cdump, $lsdump, $ldump, $qadump; echo $dumphead, $gdump, $qdump, $adump, $cdump, $lsdump, $ls1dump, $ldump, $l1dump, $qadump;
exit; exit;
?> ?>

View File

@@ -10,7 +10,7 @@
* other free or open source software licenses. * other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details. * See COPYRIGHT.php for copyright notices and details.
* *
* $Id: dumplabel.php 4769 2008-05-06 23:20:29Z c_schmitz $ * $Id: dumplabel.php 7382 2009-08-01 19:48:15Z c_schmitz $
*/ */
@@ -48,7 +48,7 @@ $qquery = "SELECT * FROM {$dbprefix}labelsets WHERE lid=$lid";
$qdump = BuildCSVFromQuery($qquery); $qdump = BuildCSVFromQuery($qquery);
//2: Answers table //2: Answers table
$aquery = "SELECT lid, code, title, sortorder, language FROM {$dbprefix}labels WHERE lid=$lid"; $aquery = "SELECT lid, code, title, sortorder, language, assessment_value FROM {$dbprefix}labels WHERE lid=$lid";
$adump = BuildCSVFromQuery($aquery); $adump = BuildCSVFromQuery($aquery);
$fn = "limesurvey_labelset_$lid.csv"; $fn = "limesurvey_labelset_$lid.csv";

View File

@@ -10,7 +10,7 @@
* other free or open source software licenses. * other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details. * See COPYRIGHT.php for copyright notices and details.
* *
* $Id: dumpquestion.php 4973 2008-06-01 14:07:01Z c_schmitz $ * $Id: dumpquestion.php 6853 2009-05-15 12:51:09Z c_schmitz $
*/ */
@@ -86,33 +86,87 @@ function BuildOutput($Query)
//1: Questions Table //1: Questions Table
$qquery = "SELECT * FROM {$dbprefix}questions WHERE qid=$qid"; $qquery = "SELECT *
FROM {$dbprefix}questions
WHERE qid=$qid";
$qdump = BuildCSVFromQuery($qquery); $qdump = BuildCSVFromQuery($qquery);
//2: Answers table //2: Answers table
$aquery = "SELECT {$dbprefix}answers.* FROM {$dbprefix}answers WHERE {$dbprefix}answers.qid = $qid"; $aquery = "SELECT {$dbprefix}answers.*
FROM {$dbprefix}answers
WHERE {$dbprefix}answers.qid = $qid";
$adump = BuildCSVFromQuery($aquery); $adump = BuildCSVFromQuery($aquery);
//3: Labelsets Table //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='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"; $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); $lsdump = BuildCSVFromQuery($lsquery);
//4: Labels Table //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"; $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); $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 //5: Question Attributes
$query = "SELECT {$dbprefix}question_attributes.* FROM {$dbprefix}question_attributes WHERE {$dbprefix}question_attributes.qid=$qid"; $query = "SELECT {$dbprefix}question_attributes.*
FROM {$dbprefix}question_attributes
WHERE {$dbprefix}question_attributes.qid=$qid";
$qadump = BuildCSVFromQuery($query); $qadump = BuildCSVFromQuery($query);
$fn = "limesurvey_question_$qid.csv"; $fn = "limesurvey_question_$qid.csv";
header("Content-Type: application/download"); header("Content-Type: application/download");
header("Content-Disposition: attachment; filename=$fn"); header("Content-Disposition: attachment; filename=$fn");
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past 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("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Pragma: cache"); // HTTP/1.0 header("Pragma: cache"); // HTTP/1.0
echo $dumphead, $qdump, $adump, $lsdump, $ldump, $qadump; echo $dumphead, $qdump, $adump, $lsdump, $ls1dump, $ldump, $l1dump, $qadump;
exit; exit;
?> ?>

View File

@@ -0,0 +1,457 @@
<?php
/*
* LimeSurvey
* Copyright (C) 2007 The LimeSurvey Project Team / Carsten Schmitz
* All rights reserved.
* License: GNU/GPL License v2 or later, see LICENSE.php
* LimeSurvey is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details.
*
* $Id: export_data_functions.php 7406 2009-08-05 12:25:57Z mennodekker $
*/
$length_vallabel = '120'; // Set the max text length of Value Labels
$length_data = '255'; // Set the max text length of Text Data
/**
* Strips html tags and replaces new lines
*
* @param $string
* @return $string
*/
function strip_tags_full($string) {
$string=html_entity_decode($string, ENT_QUOTES, "UTF-8");
//combining these into one mb_ereg_replace call ought to speed things up
$string = str_replace(array("\r\n","\r","\n",'-oth-'), '', $string);
//The backslashes must be escaped twice, once for php, and again for the regexp
$string = str_replace("'|\\\\'", "&apos;", $string);
return strip_tags($string);
}
/**
* Returns true if passed $value is numeric
*
* @param $value
* @return bool
*/
function my_is_numeric($value) {
$american = preg_match ("/^(-){0,1}([0-9]+)(,[0-9][0-9][0-9])*([.][0-9]){0,1}([0-9]*)$/" ,$value) == 1;
$world = preg_match ("/^(-){0,1}([0-9]+)(.[0-9][0-9][0-9])*([,][0-9]){0,1}([0-9]*)$/" ,$value) == 1;
return ($american or $world);
}
function spss_export_data ($na = null) {
global $length_data;
// 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<br />$query<br />".$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<br />$query<br />".$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<br />$query<br />".$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<br />$query<br />".$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;
}
?>

View File

@@ -0,0 +1,244 @@
<?php
/*
* LimeSurvey
* Copyright (C) 2007 The LimeSurvey Project Team / Carsten Schmitz
* All rights reserved.
* License: GNU/GPL License v2 or later, see LICENSE.php
* LimeSurvey is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details.
*
* $Id: export_data_r.php 7315 2009-07-14 11:12:04Z mennodekker $
*/
// Security Checked: POST, GET, SESSION, REQUEST, returnglobal, DB
/*
* The SPSS DATA LIST / BEGIN DATA parser is rather simple minded, the number after the type
* specifier identifies the field width (maximum number of characters to scan)
* It will stop short of that number of characters, honouring quote delimited
* space separated strings, however if the width is too small the remaining data in the current
* line becomes part of the next column. Since we want to restrict this script to ONE scan of
* the data (scan & output at same time), the information needed to construct the
* DATA LIST is held in the $fields array, while the actual data is written to a
* to a temporary location, updating length (size) values in the $fields array as
* the tmp file is generated (uses @fwrite's return value rather than strlen).
* Final output renders $fields to a DATA LIST, and then stitches in the tmp file data.
*
* Optimization opportunities remain in the VALUE LABELS section, which runs a query / column
*/
$length_varlabel = '255'; // Set the max text length of Variable Labels
$headerComment = '';
$tempFile = '';
include_once('login_check.php');
//for scale 1=nominal, 2=ordinal, 3=scale
$typeMap = array(
'5'=>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 .= "<br />\n";
$exportroutput .= "<div class='header'>".$clang->gT("Export result data to R")."</div>\n";
$exportroutput .= "<p style='width:100%;'><ul style='width:300px;margin:0 auto;'><li><a href='$scriptname?action=exportr&amp;sid=$surveyid&amp;subaction=dlstructure'>".$clang->gT("Export R syntax file")."</a></li><li>"
."<a href='$scriptname?action=exportr&amp;sid=$surveyid&amp;subaction=dldata'>".$clang->gT("Export .csv data file")."</a></li></ul></p><br />\n"
."<h3>".$clang->gT("Instructions for the impatient")."</h3>"
."<ol style='width:500px;margin:0 auto; font-size:8pt;'>"
."<li>".$clang->gT("Download the data and the syntax file.")."</li>"
."<li>".$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)").".</li>"
."<li>".$clang->gT("digit: source(\"Surveydata_syntax.R\", encoding = \"UTF-8\") on the R command window")."</li>"
."</ol><br />"
.$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.")
."<table><tr><td>";
} 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<br />$query<br />".$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;
}
?>

View File

@@ -0,0 +1,241 @@
<?php
/*
* LimeSurvey
* Copyright (C) 2007 The LimeSurvey Project Team / Carsten Schmitz
* All rights reserved.
* License: GNU/GPL License v2 or later, see LICENSE.php
* LimeSurvey is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details.
*
* $Id: export_data_spss.php 7175 2009-06-25 11:06:45Z mennodekker $
*/
// Security Checked: POST, GET, SESSION, REQUEST, returnglobal, DB
/*
* The SPSS DATA LIST / BEGIN DATA parser is rather simple minded, the number after the type
* specifier identifies the field width (maximum number of characters to scan)
* It will stop short of that number of characters, honouring quote delimited
* space separated strings, however if the width is too small the remaining data in the current
* line becomes part of the next column. Since we want to restrict this script to ONE scan of
* the data (scan & output at same time), the information needed to construct the
* DATA LIST is held in the $fields array, while the actual data is written to a
* to a temporary location, updating length (size) values in the $fields array as
* the tmp file is generated (uses @fwrite's return value rather than strlen).
* Final output renders $fields to a DATA LIST, and then stitches in the tmp file data.
*
* Optimization opportunities remain in the VALUE LABELS section, which runs a query / column
*/
$length_varlabel = '255'; // Set the max text length of Variable Labels
$headerComment = '';
$tempFile = '';
include_once('login_check.php');
//for scale 1=nominal, 2=ordinal, 3=scale
$typeMap = array(
'5'=>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 .= "<br />\n";
$exportspssoutput .= "<div class='header'>".$clang->gT("Export result data to SPSS")."</div>\n";
$exportspssoutput .= "<p style='width:100%;'><ul style='width:300px;margin:0 auto;'><li><a href='$scriptname?action=exportspss&amp;sid=$surveyid&amp;subaction=dlstructure'>".$clang->gT("Export SPSS syntax file")."</a></li><li>"
."<a href='$scriptname?action=exportspss&amp;sid=$surveyid&amp;subaction=dldata'>".$clang->gT("Export SPSS data file")."</a></li></ul></p><br />\n"
."<h3>".$clang->gT("Instructions for the impatient")."</h3>"
."<ol style='width:500px;margin:0 auto; font-size:8pt;'>"
."<li>".$clang->gT("Download the data and the syntax file.")."</li>"
."<li>".$clang->gT("Open the syntax file in SPSS in Unicode mode").".</li>"
."<li>".$clang->gT("Edit the 4th line and complete the filename with a full path to the downloaded data file.")."</li>"
."<li>".$clang->gT("Choose 'Run/All' from the menu to run the import.")."</li>"
."</ol><br />"
.$clang->gT("Your data should be imported now.")
."<table><tr><td>";
} 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<br />$query<br />".$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;
}
?>

View File

@@ -10,7 +10,7 @@
* other free or open source software licenses. * other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details. * 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 $
*/ */

View File

@@ -10,7 +10,7 @@
* other free or open source software licenses. * other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details. * See COPYRIGHT.php for copyright notices and details.
* *
* $Id: export_structure_csv.php 4646 2008-04-14 18:47:45Z awarren $ * $Id: export_structure_csv.php 7499 2009-08-20 03:26:29Z jcleeland $
*/ */
@@ -61,53 +61,94 @@ $dumphead = "# LimeSurvey Survey Dump\n"
. "# Do not change this header!\n"; . "# Do not change this header!\n";
//1: Surveys table //1: Surveys table
$squery = "SELECT * FROM {$dbprefix}surveys WHERE sid=$surveyid"; $squery = "SELECT *
FROM {$dbprefix}surveys
WHERE sid=$surveyid";
$sdump = BuildCSVFromQuery($squery); $sdump = BuildCSVFromQuery($squery);
//2: Surveys Languagsettings table //2: Surveys Languagsettings table
$slsquery = "SELECT * FROM {$dbprefix}surveys_languagesettings WHERE surveyls_survey_id=$surveyid"; $slsquery = "SELECT *
FROM {$dbprefix}surveys_languagesettings
WHERE surveyls_survey_id=$surveyid";
$slsdump = BuildCSVFromQuery($slsquery); $slsdump = BuildCSVFromQuery($slsquery);
//3: Groups Table //3: Groups Table
$gquery = "SELECT * FROM {$dbprefix}groups WHERE sid=$surveyid order by gid"; $gquery = "SELECT *
FROM {$dbprefix}groups
WHERE sid=$surveyid
ORDER BY gid";
$gdump = BuildCSVFromQuery($gquery); $gdump = BuildCSVFromQuery($gquery);
//4: Questions Table //4: Questions Table
$qquery = "SELECT * FROM {$dbprefix}questions WHERE sid=$surveyid order by qid"; $qquery = "SELECT *
FROM {$dbprefix}questions
WHERE sid=$surveyid
ORDER BY qid";
$qdump = BuildCSVFromQuery($qquery); $qdump = BuildCSVFromQuery($qquery);
//5: Answers table //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"; $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); $adump = BuildCSVFromQuery($aquery);
//6: Conditions table //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"; $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); $cdump = BuildCSVFromQuery($cquery);
//7: Label Sets //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"; $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); $lsdump = BuildCSVFromQuery($lsquery);
//8: Labels //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"; $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); $ldump = BuildCSVFromQuery($lquery);
//9: Question Attributes //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"; $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); $qadump = BuildCSVFromQuery($query);
//10: Assessments; //10: Assessments;
$query = "SELECT {$dbprefix}assessments.* FROM {$dbprefix}assessments WHERE {$dbprefix}assessments.sid=$surveyid"; $query = "SELECT {$dbprefix}assessments.*
FROM {$dbprefix}assessments
WHERE {$dbprefix}assessments.sid=$surveyid";
$asdump = BuildCSVFromQuery($query); $asdump = BuildCSVFromQuery($query);
//11: Quota; //11: Quota;
$query = "SELECT {$dbprefix}quota.* FROM {$dbprefix}quota WHERE {$dbprefix}quota.sid=$surveyid"; $query = "SELECT {$dbprefix}quota.*
FROM {$dbprefix}quota
WHERE {$dbprefix}quota.sid=$surveyid";
$quotadump = BuildCSVFromQuery($query); $quotadump = BuildCSVFromQuery($query);
//12: Quota Members; //12: Quota Members;
$query = "SELECT {$dbprefix}quota_members.* FROM {$dbprefix}quota_members WHERE {$dbprefix}quota_members.sid=$surveyid"; $query = "SELECT {$dbprefix}quota_members.*
FROM {$dbprefix}quota_members
WHERE {$dbprefix}quota_members.sid=$surveyid";
$quotamemdump = BuildCSVFromQuery($query); $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"; $fn = "limesurvey_survey_$surveyid.csv";
header("Content-Type: application/download"); header("Content-Type: application/download");
@@ -117,6 +158,6 @@ header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Pragma: cache"); // HTTP/1.0 header("Pragma: cache"); // HTTP/1.0
echo $dumphead, $sdump, $gdump, $qdump, $adump, $cdump, $lsdump, $ldump, $qadump, $asdump, $slsdump, $quotadump, $quotamemdump."\n"; echo $dumphead, $sdump, $gdump, $qdump, $adump, $cdump, $lsdump, $ldump, $qadump, $asdump, $slsdump, $quotadump, $quotamemdump, $quotalsdump."\n";
exit; exit;
?> ?>

View File

@@ -0,0 +1,170 @@
<?php
/*
* LimeSurvey
* Copyright (C) 2007 The LimeSurvey Project Team / Carsten Schmitz
* All rights reserved.
* License: GNU/GPL License v2 or later, see LICENSE.php
* LimeSurvey is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details.
*
* $Id: export_structure_csv.php 5747 2008-10-07 19:40:33Z c_schmitz $
*/
// DUMP THE RELATED DATA FOR A SINGLE SURVEY INTO A SQL FILE FOR IMPORTING LATER ON OR ON ANOTHER SURVEY SETUP
// DUMP ALL DATA WITH RELATED SID FROM THE FOLLOWING TABLES
// 1. Surveys
// 2. Surveys Language Table
// 3. Groups
// 4. Questions
// 5. Answers
// 6. Conditions
// 7. Label Sets
// 8. Labels
// 9. Question Attributes
// 10. Assessments
// 11. Quota
// 12. Quota Members
include_once("login_check.php");
if (!isset($surveyid)) {$surveyid=returnglobal('sid');}
if (!$surveyid)
{
echo $htmlheader
."<br />\n"
."<table width='350' align='center' style='border: 1px solid #555555' cellpadding='1' cellspacing='0'>\n"
."\t<tr bgcolor='#555555'><td colspan='2' height='4'><font size='1' face='verdana' color='white'><strong>"
.$clang->gT("Export Survey")."</strong></td></tr>\n"
."\t<tr><td align='center'>\n"
."<br /><strong><font color='red'>"
.$clang->gT("Error")."</font></strong><br />\n"
.$clang->gT("No SID has been provided. Cannot dump survey")."<br />\n"
."<br /><input type='submit' value='"
.$clang->gT("Main Admin Screen")."' onclick=\"window.open('$scriptname', '_top')\">\n"
."\t</td></tr>\n"
."</table>\n"
."</body></html>\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;
?>

View File

@@ -416,7 +416,7 @@ while ($Row = $QueryResult->FetchRow())
$question->append_child($response); $question->append_child($response);
break; break;
case "S": //SHORT FREE TEXT 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); $question->append_child($response);
break; break;
case "T": //LONG FREE TEXT case "T": //LONG FREE TEXT
@@ -503,6 +503,7 @@ while ($Row = $QueryResult->FetchRow())
$response->append_child(create_free("text",16,"")); $response->append_child(create_free("text",16,""));
$question->append_child($response); $question->append_child($response);
$questionnaire->append_child($section); $questionnaire->append_child($section);
} }

File diff suppressed because it is too large Load Diff

View File

@@ -10,7 +10,7 @@
* other free or open source software licenses. * other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details. * 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"); include_once("login_check.php");
@@ -32,19 +32,30 @@ $InsertansUnsupportedtypes=Array(); // Currently all question types are supporte
$replFields=Array(); $replFields=Array();
$isInstertansEnabled=false; $isInstertansEnabled=false;
$limereplacementoutput="" $limereplacementoutput="<html>\n"
. "<script language=\"javascript\">\n" . "\t<head>\n"
. "var oEditor = window.parent.InnerDialogLoaded() ;\n" . "\t\t<title>LimeReplacementFields</title>\n"
. "var dialog = oEditor.FCK ;\n" . "\t\t<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n"
. "var FCKLang = oEditor.FCKLang ;\n" . "\t\t<meta content=\"noindex, nofollow\" name=\"robots\">\n"
. "var FCKLimeReplacementFieldss = oEditor.FCKLimeReplacementFieldss ;\n" . "\t\t<script src=\"$fckeditordir/editor/dialog/common/fck_dialog_common.js\" type=\"text/javascript\"></script>\n"
. "window.onload = function ()\n" . "\t\t<script src=\"$rooturl/scripts/jquery/jquery.js\" type=\"text/javascript\"></script>\n"
. "{\n" . "\t\t<script language=\"javascript\">\n"
. "\toEditor.FCKLanguageManager.TranslatePage( document ) ;\n" . "\t\t\tvar mydialog = window.parent ;\n"
. "\tLoadSelected() ;\n" . "\t\t\tvar oEditor = mydialog.InnerDialogLoaded() ;\n"
. "\twindow.parent.SetOkButton( true ) ;\n" . "\t\t\tvar dialog = oEditor.FCK ;\n"
. "}\n" . "\t\t\tvar FCKLang = oEditor.FCKLang ;\n"
. "\t\t\tvar FCKLimeReplacementFieldss = oEditor.FCKLimeReplacementFieldss ;\n"
. "\t\t\$(document).ready(function ()\n"
. "\t\t\t{\n"
. "\t\t\t\toEditor.FCKLanguageManager.TranslatePage( document ) ;\n"
. "\t\t\t\tLoadSelected() ;\n"
. "\t\t\t\tmydialog.SetOkButton( true ) ;\n"
. "\n" . "\n"
. "\t\t\t\tSelectField( 'cquestions' ) ;\n"
. "\t\t\t});\n"
. "\n";
/**$limereplacementoutput="\n"
. "if (! oEditor.FCKBrowserInfo.IsIE)\n" . "if (! oEditor.FCKBrowserInfo.IsIE)\n"
. "{\n" . "{\n"
. "\tinnertext = '' + dialog.EditorWindow.getSelection() + '' ;\n" . "\tinnertext = '' + dialog.EditorWindow.getSelection() + '' ;\n"
@@ -52,39 +63,70 @@ $limereplacementoutput=""
. "else\n" . "else\n"
. "{\n" . "{\n"
. "\tinnertext = '' + dialog.EditorDocument.selection.createRange().text + '' ;\n" . "\tinnertext = '' + dialog.EditorDocument.selection.createRange().text + '' ;\n"
. "}\n" . "}\n";
. "\n" **/
. "function Ok()\n"
. "{\n" $limereplacementoutput .= ""
. "\tvar sValue = document.getElementById('cquestions').value ;\n" . "\t\t\tvar eSelected = dialog.Selection.GetSelectedElement() ;\n"
. "\tFCKLimeReplacementFieldss.Add( sValue ) ;\n" . "\n";
. "\treturn true ;\n"
. "}\n" /**
$limereplacementoutput="\n"
. "function LoadSelected()\n" . "function LoadSelected()\n"
. "{\n" . "{\n"
. "\tif ( innertext == '' )\n" . "\tif ( innertext == '' )\n"
. "\t\treturn ;\n" . "\t\treturn ;\n"
// . "\tif ( eSelected.tagName == 'SPAN' && eSelected._fckLimeReplacementFields )\n"
. "var replcode=innertext.substring(innertext.indexOf('{')+1,innertext.lastIndexOf('}'));\n" . "var replcode=innertext.substring(innertext.indexOf('{')+1,innertext.lastIndexOf('}'));\n"
// . "alert('TIBO=' + replcode);\n"
. "\t\tdocument.getElementById('cquestions').value = replcode;\n" . "\t\tdocument.getElementById('cquestions').value = replcode;\n"
// . "\telse\n" . "}\n";
// . "\t\teSelected == null ;\n" **/
. "}\n"
. "</script>\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 .= "<table><tr><td>"; $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</script>\n"
. "\t\t</head>\n";
$limereplacementoutput .= "\t<body scroll=\"no\" style=\"OVERFLOW: hidden\">\n"
. "\t\t<table height=\"100%\" cellSpacing=\"0\" cellPadding=\"0\" width=\"100%\" border=\"0\">\n"
. "\t\t\t<tr>\n"
. "\t\t\t\t<td>\n";
switch ($fieldtype) switch ($fieldtype)
{ {
case 'survey-desc': case 'survey-desc':
case 'survey-welc': case 'survey-welc':
case 'survey-endtext':
$replFields[]=array('TOKEN:FIRSTNAME',$clang->gT("Firstname from token")); $replFields[]=array('TOKEN:FIRSTNAME',$clang->gT("Firstname from token"));
$replFields[]=array('TOKEN:LASTNAME',$clang->gT("Lastname from token")); $replFields[]=array('TOKEN:LASTNAME',$clang->gT("Lastname from token"));
$replFields[]=array('TOKEN:EMAIL',$clang->gT("Email from the token")); $replFields[]=array('TOKEN:EMAIL',$clang->gT("Email from the token"));
$replFields[]=array('TOKEN:ATTRIBUTE_1',$clang->gT("Attribute_1 from token")); $attributes=GetTokenFieldsAndNames($surveyid,true);
$replFields[]=array('TOKEN:ATTRIBUTE_2',$clang->gT("Attribute_2 from token")); 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; break;
case 'email-inv': case 'email-inv':
@@ -99,11 +141,17 @@ switch ($fieldtype)
$replFields[]=array('LASTNAME',$clang->gT("Lastname from token")); $replFields[]=array('LASTNAME',$clang->gT("Lastname from token"));
$replFields[]=array('SURVEYNAME',$clang->gT("Name of the survey")); $replFields[]=array('SURVEYNAME',$clang->gT("Name of the survey"));
$replFields[]=array('SURVEYDESCRIPTION',$clang->gT("Description of the survey")); $replFields[]=array('SURVEYDESCRIPTION',$clang->gT("Description of the survey"));
$replFields[]=array('ATTRIBUTE_1',$clang->gT("Attribute_1 from token")); $attributes=GetTokenFieldsAndNames($surveyid,true);
$replFields[]=array('ATTRIBUTE_2',$clang->gT("Attribute_2 from token")); 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('ADMINNAME',$clang->gT("Name of the survey administrator"));
$replFields[]=array('ADMINEMAIL',$clang->gT("Email address 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('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; break;
case 'group-desc': case 'group-desc':
@@ -112,10 +160,21 @@ switch ($fieldtype)
$replFields[]=array('TOKEN:FIRSTNAME',$clang->gT("Firstname from token")); $replFields[]=array('TOKEN:FIRSTNAME',$clang->gT("Firstname from token"));
$replFields[]=array('TOKEN:LASTNAME',$clang->gT("Lastname from token")); $replFields[]=array('TOKEN:LASTNAME',$clang->gT("Lastname from token"));
$replFields[]=array('TOKEN:EMAIL',$clang->gT("Email from the token")); $replFields[]=array('TOKEN:EMAIL',$clang->gT("Email from the token"));
$replFields[]=array('TOKEN:ATTRIBUTE_1',$clang->gT("Attribute_1 from token")); $attributes=GetTokenFieldsAndNames($surveyid,true);
$replFields[]=array('TOKEN:ATTRIBUTE_2',$clang->gT("Attribute_2 from token")); 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; $isInstertansEnabled=true;
break; 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; break;
case 'editanswer':
case 'copyquestion': case 'copyquestion':
case 'editquestion': case 'editquestion':
if (empty($gid)) {die("No GID provided.");} if (empty($gid)) {die("No GID provided.");}
@@ -314,6 +374,40 @@ if ($isInstertansEnabled===true)
} //while } //while
} //if A,B,C,E,F,H } //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<br />$aquery<br />".$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 elseif ($rows['type'] == "R") //Answer Ranking
{ {
$aquery="SELECT * " $aquery="SELECT * "
@@ -396,30 +490,33 @@ if ($isInstertansEnabled===true)
if (count($replFields) > 0 || isset($cquestions) ) if (count($replFields) > 0 || isset($cquestions) )
{ {
$limereplacementoutput .= "\t\t\t<select name='cquestions' id='cquestions' style='font-family:verdana; background-color: #FFFFFF; font-size:10; border: 0px;width:99%;' size='15' ondblclick='Ok();'>\n"; $limereplacementoutput .= "\t\t\t\t\t<select name='cquestions' id='cquestions' style='font-family:verdana; background-color: #FFFFFF; font-size:10; border: 0px;width:99%;' size='15' ondblclick='Ok();'>\n";
$noselection = false;
} }
else else
{ {
$limereplacementoutput = $clang->gT("No replacement variable available for this field"); $limereplacementoutput .= $clang->gT("No replacement variable available for this field");
echo $limereplacementoutput; //echo $limereplacementoutput;
return; //return;
$noselection = true;
} }
if (count($replFields) > 0) if (count($replFields) > 0)
{ {
$limereplacementoutput .= "\t\t\t\t<optgroup label='".$clang->gT("Standard Fields")."'>\n"; $limereplacementoutput .= "\t\t\t\t\t\t<optgroup label='".$clang->gT("Standard Fields")."'>\n";
foreach ($replFields as $stdfield) foreach ($replFields as $stdfield)
{ {
$limereplacementoutput .= "\t\t\t\t<option value='".$stdfield[0]."'"; $limereplacementoutput .= "\t\t\t\t\t\t\t<option value='".$stdfield[0]."'";
$limereplacementoutput .= ">".$stdfield[1]."</option>\n"; $limereplacementoutput .= ">".$stdfield[1]."</option>\n";
} }
$limereplacementoutput .= "\t\t\t\t</optgroup>\n"; $limereplacementoutput .= "\t\t\t\t\t\t</optgroup>\n";
} }
if (isset($cquestions)) if (isset($cquestions))
{ {
$limereplacementoutput .= "\t\t\t\t<optgroup label='".$clang->gT("Previous Answers Fields")."'>\n"; $limereplacementoutput .= "\t\t\t\t\t\t<optgroup label='".$clang->gT("Previous Answers Fields")."'>\n";
foreach ($cquestions as $cqn) foreach ($cquestions as $cqn)
{ {
$isDisabled=""; $isDisabled="";
@@ -432,36 +529,53 @@ if (isset($cquestions))
$isDisabled=" disabled='disabled'"; $isDisabled=" disabled='disabled'";
} }
$limereplacementoutput .= "\t\t\t\t<option value='INSERTANS:$cqn[3]'"; $limereplacementoutput .= "\t\t\t\t\t\t\t<option value='INSERTANS:$cqn[3]'";
$limereplacementoutput .= " $isDisabled >$cqn[0]</option>\n"; $limereplacementoutput .= " $isDisabled >$cqn[0]</option>\n";
} }
$limereplacementoutput .= "\t\t\t\t</optgroup>\n"; $limereplacementoutput .= "\t\t\t\t\t\t</optgroup>\n";
} }
$limereplacementoutput .= "\t\t\t</select>\n"; if ($noselection === false)
$limereplacementoutput .= "</td></tr>\n"; {
$limereplacementoutput .= "\t\t\t\t\t</select>\n";
}
$limereplacementoutput .= "\t\t\t\t</td>\n"
. "\t\t\t</tr>\n";
if (isset($surveyformat)) if (isset($surveyformat))
{ {
switch ($surveyformat) switch ($surveyformat)
{ {
case 'A': case 'A':
$limereplacementoutput .= "<tr><td>\n"; $limereplacementoutput .= "\t\t\t<tr>\n"
$limereplacementoutput .= "<br /><font color='orange'>".$clang->gT("Some Question have been disabled")."</font>"; . "\t\t\t\t<td>\n";
$limereplacementoutput .= "<br />".sprintf($clang->gT("Survey Format is %s:"), $clang->gT("All in one"))."<br /><i>".$clang->gT("Only Previous pages answers are available")."</i><br />"; $limereplacementoutput .= "\t\t\t\t\t<br />\n"
$limereplacementoutput .= "</td></tr>\n"; . "\t\t\t\t\t<font color='orange'>".$clang->gT("Some Question have been disabled")."</font>\n";
$limereplacementoutput .= "\t\t\t\t\t<br />\n"
. "\t\t\t\t\t".sprintf($clang->gT("Survey Format is %s:"), $clang->gT("All in one"))
. "\t\t\t\t\t<br />\n"
. "\t\t\t\t\t<i>".$clang->gT("Only Previous pages answers are available")."</i>\n"
. "\t\t\t\t\t<br />\n";
$limereplacementoutput .= "\t\t\t\t</td>\n"
. "\t\t\t</tr>\n";
break; break;
case 'G': case 'G':
$limereplacementoutput .= "<tr><td>\n"; $limereplacementoutput .= "\t\t\t<tr>\n"
$limereplacementoutput .= "<br /><font color='orange'>".$clang->gT("Some Question have been disabled")."</font>"; . "\t\t\t\t<td>\n";
$limereplacementoutput .= "<br />".sprintf($clang->gT("Survey mode is set to %s:"), $clang->gT("Group by Group"))."<br/><i>".$clang->gT("Only Previous pages answers are available")."</i><br />"; $limereplacementoutput .= "</td></tr>\n"; $limereplacementoutput .= "\t\t\t\t\t<br /><font color='orange'>".$clang->gT("Some Question have been disabled")."</font>";
$limereplacementoutput .= "<br />".sprintf($clang->gT("Survey mode is set to %s:"), $clang->gT("Group by Group"))."<br/><i>".$clang->gT("Only Previous pages answers are available")."</i><br />";
$limereplacementoutput .= "\t\t\t\t</td>\n"
. "\t\t\t</tr>\n";
break; break;
} }
} }
$limereplacementoutput .= "</table>\n"; $limereplacementoutput .= "\t\t</table>\n"
. "\t</body>\n"
. "</html>";
echo $limereplacementoutput; echo $limereplacementoutput;
exit;
?> ?>

View File

@@ -10,7 +10,7 @@
* other free or open source software licenses. * other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details. * See COPYRIGHT.php for copyright notices and details.
* *
* $Id: grouphandling.php 4973 2008-06-01 14:07:01Z c_schmitz $ * $Id: grouphandling.php 7446 2009-08-11 18:28:47Z c_schmitz $
*/ */
@@ -32,9 +32,16 @@ if ($action == "addgroup")
// $newgroupoutput .="<table width='100%' border='0' class='tab-page'>\n\t<tr><td>\n" // $newgroupoutput .="<table width='100%' border='0' class='tab-page'>\n\t<tr><td>\n"
$newgroupoutput .= "<form action='$scriptname' id ='addnewgroupfrom' name='addnewgroupfrom' method='post'>";
$newgroupoutput .="\n" $newgroupoutput .="\n"
. '<div class="tab-pane" id="tab-pane-1">'; . '<div class="tab-pane" id="tab-pane-newgroup">';
$newgroupoutput .= "<form action='$scriptname' id ='addnewgroupfrom' name='addnewgroupfrom' method='post' onsubmit=\"if (1==0 ";
foreach ($grplangs as $grouplang)
{
$newgroupoutput .= "|| document.getElementById('group_name_$grouplang').value.length==0 ";
}
$newgroupoutput .=" ) {alert ('".$clang->gT("Error: You have to enter a group title for each language.",'js')."'); return false;}\" ";
foreach ($grplangs as $grouplang) foreach ($grplangs as $grouplang)
{ {
$newgroupoutput .= '<div class="tab-page"> <h2 class="tab">'.GetLanguageNameFromCode($grouplang,false); $newgroupoutput .= '<div class="tab-page"> <h2 class="tab">'.GetLanguageNameFromCode($grouplang,false);
@@ -70,8 +77,8 @@ if ($action == "addgroup")
. "\t\n" . "\t\n"
. "\t\t<td><strong>".$clang->gT("Select CSV File:")."</strong></td>\n" . "\t\t<td><strong>".$clang->gT("Select CSV File:")."</strong></td>\n"
. "\t\t<td><input name=\"the_file\" type=\"file\" size=\"35\" /></td></tr>\n" . "\t\t<td><input name=\"the_file\" type=\"file\" size=\"35\" /></td></tr>\n"
. "\t\t<tr>\t\t<td>".$clang->gT("Convert Resources links ?")."</td>\n" . "\t\t<tr>\t\t<td>".$clang->gT("Convert resources links?")."</td>\n"
. "\t\t<td><input name=\"translinksfields\" type=\"checkbox\" /></td></tr>\n" . "\t\t<td><input name=\"translinksfields\" type=\"checkbox\" checked=\"checked\"/></td></tr>\n"
. "\t<tr><td colspan='2'class='centered'><input type='submit' value='".$clang->gT("Import Group")."' />\n" . "\t<tr><td colspan='2'class='centered'><input type='submit' value='".$clang->gT("Import Group")."' />\n"
. "\t<input type='hidden' name='action' value='importgroup' />\n" . "\t<input type='hidden' name='action' value='importgroup' />\n"
. "\t<input type='hidden' name='sid' value='$surveyid' />\n" . "\t<input type='hidden' name='sid' value='$surveyid' />\n"
@@ -130,7 +137,7 @@ if ($action == "editgroup")
$editgroup .= "<table width='100%' border='0'>\n\t<tr><td class='settingcaption'>" $editgroup .= "<table width='100%' border='0'>\n\t<tr><td class='settingcaption'>"
. "\t\t".$clang->gT("Edit Group")."</td></tr></table>\n" . "\t\t".$clang->gT("Edit Group")."</td></tr></table>\n"
. "<form name='editgroup' action='$scriptname' method='post'>\n" . "<form name='editgroup' action='$scriptname' method='post'>\n"
. '<div class="tab-pane" id="tab-pane-1">'; . '<div class="tab-pane" id="tab-pane-group-'.$gid.'">';
$esrow = $egresult->FetchRow(); $esrow = $egresult->FetchRow();
$editgroup .= '<div class="tab-page"> <h2 class="tab">'.getLanguageNameFromCode($esrow['language'],false); $editgroup .= '<div class="tab-page"> <h2 class="tab">'.getLanguageNameFromCode($esrow['language'],false);

File diff suppressed because it is too large Load Diff

View File

@@ -10,7 +10,7 @@
* other free or open source software licenses. * other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details. * See COPYRIGHT.php for copyright notices and details.
* *
* $Id: htmleditor-functions.php 4916 2008-05-25 17:25:33Z c_schmitz $ * $Id: htmleditor-functions.php 7076 2009-06-11 20:38:09Z lemeur $
*/ */
//include_once("login_check.php"); //include_once("login_check.php");
@@ -215,7 +215,7 @@ function getPopupEditor($fieldtype,$fieldname,$fieldtext, $surveyID=null,$gID=nu
$fieldtype == 'editlabel' || $fieldtype == 'editlabel' ||
$fieldtype == 'addlabel') $fieldtype == 'addlabel')
{ {
$imgopts = "width='14px' height='14px'"; $imgopts = "width='14' height='14'";
} }
$htmlcode .= "" $htmlcode .= ""
@@ -226,13 +226,14 @@ function getPopupEditor($fieldtype,$fieldname,$fieldtext, $surveyID=null,$gID=nu
function getInlineEditor($fieldtype,$fieldname,$fieldtext, $surveyID=null,$gID=null,$qID=null,$action=null) function getInlineEditor($fieldtype,$fieldname,$fieldtext, $surveyID=null,$gID=null,$qID=null,$action=null)
{ {
global $clang, $imagefiles, $homeurl, $rooturl, $fckeditordir; global $clang, $imagefiles, $homeurl, $rooturl, $fckeditordir, $fckeditexpandtoolbar;
$htmlcode = ''; $htmlcode = '';
$imgopts = ''; $imgopts = '';
$toolbarname = 'Basic'; $toolbarname = 'Basic';
$toolbaroption=""; $toolbaroption="";
$htmlformatoption=""; $htmlformatoption="";
$oFCKeditorVarName = "oFCKeditor_".str_replace("-","_",$fieldname);
if ($fieldtype == 'editanswer' || if ($fieldtype == 'editanswer' ||
$fieldtype == 'addanswer' || $fieldtype == 'addanswer' ||
@@ -240,10 +241,17 @@ function getInlineEditor($fieldtype,$fieldname,$fieldtext, $surveyID=null,$gID=n
$fieldtype == 'addlabel') $fieldtype == 'addlabel')
{ {
$toolbarname = 'LimeSurveyToolbarfull'; $toolbarname = 'LimeSurveyToolbarfull';
$toolbaroption="oFCKeditor_$fieldname.Config[\"ToolbarLocation\"]=\"Out:xToolbar\";\n" $toolbaroption="$oFCKeditorVarName.Config[\"ToolbarLocation\"]=\"Out:xToolbar\";\n"
. "oFCKeditor_$fieldname.Config[\"ToolbarStartExpanded\"]=true;\n" . "$oFCKeditorVarName.Config[\"ToolbarStartExpanded\"]=true;\n"
. "oFCKeditor_$fieldname.Config[\"ToolbarCanCollapse\"]=false;\n" . "$oFCKeditorVarName.Config[\"ToolbarCanCollapse\"]=false;\n"
. "oFCKeditor_$fieldname.Height = \"50\"\n"; . "$oFCKeditorVarName.Height = \"50\"\n";
}
else
{
if (!isset($fckeditexpandtoolbar) || $fckeditexpandtoolbar == true)
{
$toolbaroption .= "$oFCKeditorVarName.Config[\"ToolbarStartExpanded\"]=true;\n";
}
} }
if ( $fieldtype == 'email-inv' || if ( $fieldtype == 'email-inv' ||
@@ -251,33 +259,34 @@ function getInlineEditor($fieldtype,$fieldname,$fieldtext, $surveyID=null,$gID=n
$fieldtype == 'email-conf' || $fieldtype == 'email-conf' ||
$fieldtype == 'email-rem' ) $fieldtype == 'email-rem' )
{ {
$htmlformatoption = "oFCKeditor_$fieldname.Config[\"FullPage\"]=true;\n"; $htmlformatoption = "$oFCKeditorVarName.Config[\"FullPage\"]=true;\n";
} }
$htmlcode .= "" $htmlcode .= ""
. "<script type=\"text/javascript\">\n" . "<script type=\"text/javascript\">\n"
. "var oFCKeditor_$fieldname = new FCKeditor('$fieldname');\n" . "var $oFCKeditorVarName = new FCKeditor('$fieldname');\n"
. "oFCKeditor_$fieldname.BasePath = '".$fckeditordir."/';\n" . "$oFCKeditorVarName.BasePath = '".$fckeditordir."/';\n"
. "oFCKeditor_$fieldname.Config[\"CustomConfigurationsPath\"] = \"".$fckeditordir."/limesurvey-config.js\";\n" . "$oFCKeditorVarName.Config[\"CustomConfigurationsPath\"] = \"".$fckeditordir."/limesurvey-config.js\";\n"
. "oFCKeditor_$fieldname.Config[\"LimeReplacementFieldsType\"] = \"".$fieldtype."\";\n" . "$oFCKeditorVarName.Config[\"LimeReplacementFieldsType\"] = \"".$fieldtype."\";\n"
. "oFCKeditor_$fieldname.Config[\"LimeReplacementFieldsSID\"] = \"".$surveyID."\";\n" . "$oFCKeditorVarName.Config[\"LimeReplacementFieldsSID\"] = \"".$surveyID."\";\n"
. "oFCKeditor_$fieldname.Config[\"LimeReplacementFieldsGID\"] = \"".$gID."\";\n" . "$oFCKeditorVarName.Config[\"LimeReplacementFieldsGID\"] = \"".$gID."\";\n"
. "oFCKeditor_$fieldname.Config[\"LimeReplacementFieldsQID\"] = \"".$qID."\";\n" . "$oFCKeditorVarName.Config[\"LimeReplacementFieldsQID\"] = \"".$qID."\";\n"
. "oFCKeditor_$fieldname.Config[\"LimeReplacementFieldsType\"] = \"".$fieldtype."\";\n" . "$oFCKeditorVarName.Config[\"LimeReplacementFieldsType\"] = \"".$fieldtype."\";\n"
. "oFCKeditor_$fieldname.Config[\"LimeReplacementFieldsAction\"] = \"".$action."\";\n" . "$oFCKeditorVarName.Config[\"LimeReplacementFieldsAction\"] = \"".$action."\";\n"
. "oFCKeditor_$fieldname.Config[\"SmileyPath\"] = \"".$rooturl."/upload/images/smiley/msn/\";\n" . "$oFCKeditorVarName.Config[\"SmileyPath\"] = \"".$rooturl."/upload/images/smiley/msn/\";\n"
. $htmlformatoption . $htmlformatoption
. $toolbaroption; . $toolbaroption;
if ($fieldtype == 'answer' || $fieldtype == 'label') if ($fieldtype == 'answer' || $fieldtype == 'label')
{ {
$htmlcode .= "" $htmlcode .= ""
. "oFCKeditor_$fieldname.Config[ 'ToolbarLocation' ] = 'Out:xToolbar' ;\n"; . "$oFCKeditorVarName.Config[ 'ToolbarLocation' ] = 'Out:xToolbar' ;\n";
} }
$htmlcode .= "" $htmlcode .= ""
. "oFCKeditor_$fieldname.ToolbarSet = '".$toolbarname."';\n" . "$oFCKeditorVarName.ToolbarSet = '".$toolbarname."';\n"
. "oFCKeditor_$fieldname.ReplaceTextarea() ;\n" . "$oFCKeditorVarName.ReplaceTextarea() ;\n"
. '</script>'; . '</script>';
return $htmlcode; return $htmlcode;

View File

@@ -10,7 +10,7 @@
* other free or open source software licenses. * other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details. * See COPYRIGHT.php for copyright notices and details.
* *
* $Id: htmleditor-popup.php 5074 2008-06-15 11:56:13Z c_schmitz $ * $Id: htmleditor-popup.php 6853 2009-05-15 12:51:09Z c_schmitz $
*/ */
//Ensure script is not run directly, avoid path disclosure //Ensure script is not run directly, avoid path disclosure
@@ -46,8 +46,8 @@ if (!isset($_GET['fieldname']) || !isset($_GET['fieldtext']))
</div> </div>
<hr /> <hr />
<tr><td align="center"><br /><font color="red"><strong> <tr><td align="center"><br /><span style="color:red;"><strong>
</strong></font><br /> </strong></span><br />
</table> </table>
<form onsubmit="self.close()"> <form onsubmit="self.close()">
<input type="submit" value="'.$clang->gT("Close Editor").'" /> <input type="submit" value="'.$clang->gT("Close Editor").'" />

View File

@@ -10,7 +10,7 @@
* other free or open source software licenses. * other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details. * See COPYRIGHT.php for copyright notices and details.
* *
* $Id: http_importsurvey.php 4037 2008-01-20 15:23:53Z c_schmitz $ * $Id: http_importsurvey.php 6853 2009-05-15 12:51:09Z c_schmitz $
*/ */
//Ensure script is not run directly, avoid path disclosure //Ensure script is not run directly, avoid path disclosure

View File

@@ -10,7 +10,7 @@
* other free or open source software licenses. * other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details. * 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'); returnglobal('lid');
} }
if ($action == "importsurvresources" && $surveyid) { if ($action == "importsurvresources" && $surveyid) {
if ($demoModeOnly === true)
{
$importsurvresourcesoutput = "<strong><font color='red'>".$clang->gT("Error")."</font></strong><br />\n";
$importsurvresourcesoutput .= $clang->gT("Demo Mode Only: Uploading file is disabled in this system.")."<br /><br />\n";
$importsurvresourcesoutput .= "<input type='submit' value='".$clang->gT("Back")."' onclick=\"window.open('$scriptname?action=editsurvey&amp;sid=$surveyid', '_self')\" />&nbsp;<br />&nbsp;<br />\n";
return;
}
require("classes/phpzip/phpzip.inc.php"); require("classes/phpzip/phpzip.inc.php");
$zipfile=$_FILES['the_file']['tmp_name']; $zipfile=$_FILES['the_file']['tmp_name'];
$z = new PHPZip(); $z = new PHPZip();
@@ -197,6 +206,15 @@ if ($action == "importsurvresources" && $surveyid) {
if ($action == "importlabelresources" && $lid) if ($action == "importlabelresources" && $lid)
{ {
if ($demoModeOnly === true)
{
$importlabelresourcesoutput .= "<strong><font color='red'>".$clang->gT("Error")."</font></strong><br />\n";
$importlabelresourcesoutput .= sprintf ($clang->gT("Demo Mode Only: Uploading file is disabled in this system."),$basedestdir)."<br /><br />\n";
$importlabelresourcesoutput .= "<input type='submit' value='".$clang->gT("Main Admin Screen")."' onclick=\"window.open('$scriptname?action=labels&lid=$lid', '_self')\">\n";
$importlabelresourcesoutput .= "</td></tr></table><br />&nbsp;\n";
return;
}
require("classes/phpzip/phpzip.inc.php"); require("classes/phpzip/phpzip.inc.php");
//$the_full_file_path = $tempdir . "/" . $_FILES['the_file']['name']; //$the_full_file_path = $tempdir . "/" . $_FILES['the_file']['name'];
$zipfile=$_FILES['the_file']['tmp_name']; $zipfile=$_FILES['the_file']['tmp_name'];
@@ -363,6 +381,187 @@ if ($action == "importlabelresources" && $lid)
if ($action == "templateupload")
{
if ($demoModeOnly === true)
{
$importtemplateresourcesoutput .= "<strong><font color='red'>".$clang->gT("Error")."</font></strong><br />\n";
$importtemplateoutput .= sprintf ($clang->gT("Demo mode: Uploading templates is disabled."),$basedestdir)."<br /><br />\n";
$importtemplateoutput .= "</td></tr></table><br />&nbsp;\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 = "<br />\n";
$importtemplateoutput .= "<table class='alertbox'>\n";
$importtemplateoutput .= "\t<tr><td colspan='2' height='4'><strong>".$clang->gT("Import Label Set")."</strong></td></tr>\n";
$importtemplateoutput .= "\t<tr><td align='center'>\n";
if (!is_writeable($basedestdir))
{
$importtemplateoutput .= "<strong><font color='red'>".$clang->gT("Error")."</font></strong><br />\n";
$importtemplateoutput .= sprintf ($clang->gT("Incorrect permissions in your %s folder."),$basedestdir)."<br /><br />\n";
$importtemplateoutput .= "</td></tr></table><br />&nbsp;\n";
return;
}
if (!is_dir($destdir))
{
mkdir($destdir);
}
else
{
$importtemplateoutput .= "<strong><font color='red'>".$clang->gT("Error")."</font></strong><br />\n";
$importtemplateoutput .= sprintf ($clang->gT("Template '%s' does already exist."),$newdir)."<br /><br />\n";
$importtemplateoutput .= "</td></tr></table><br />&nbsp;\n";
return;
}
$aImportedFilesInfo=array();
$aErrorFilesInfo=array();
if (is_file($zipfile))
{
$importtemplateoutput .= "<strong><font class='successtitle'>".$clang->gT("Success")."</font></strong><br />\n";
$importtemplateoutput .= $clang->gT("File upload succeeded.")."<br /><br />\n";
$importtemplateoutput .= $clang->gT("Reading file..")."<br />\n";
if ($z->extract($extractdir,$zipfile) != 'OK')
{
$importtemplateoutput .= "<strong><font color='red'>".$clang->gT("Error")."</font></strong><br />\n";
$importtemplateoutput .= $clang->gT("This file is not a valid ZIP file archive. Import failed.")."<br /><br />\n";
$importtemplateoutput .= "</td></tr></table><br />&nbsp;\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 .= "<br /><strong><u>".$clang->gT("Imported Files List").":</u></strong><br />\n";
}
elseif (count($aErrorFilesInfo)==0 && count($aImportedFilesInfo)==0)
{
$importtemplateoutput .= "<strong><font color='red'>".$clang->gT("Error")."</font></strong><br />\n";
$importtemplateoutput .= $clang->gT("This ZIP archive contains no valid template files. Import failed.")."<br /><br />\n";
$importtemplateoutput .= $clang->gT("Remember that we do not support subdirectories in ZIP archives.")."<br /><br />\n";
$importtemplateoutput .= "</td></tr></table><br />&nbsp;\n";
return;
}
elseif (count($aErrorFilesInfo)>0 && count($aImportedFilesInfo)>0)
{
$status=$clang->gT("Partial");
$color='orange';
$okfiles = count($aImportedFilesInfo);
$errfiles = count($aErrorFilesInfo);
$ErrorListHeader .= "<br /><strong><u>".$clang->gT("Error Files List").":</u></strong><br />\n";
$ImportListHeader .= "<br /><strong><u>".$clang->gT("Imported Files List").":</u></strong><br />\n";
}
else
{
$status=$clang->gT("Error");
$color='red';
$errfiles = count($aErrorFilesInfo);
$ErrorListHeader .= "<br /><strong><u>".$clang->gT("Error Files List").":</u></strong><br />\n";
}
$importtemplateoutput .= "<strong>".$clang->gT("Imported template files for")."</strong> $lid<br />\n";
$importtemplateoutput .= "<br />\n<strong><font color='$color'>".$status."</font></strong><br />\n";
$importtemplateoutput .= "<strong><u>".$clang->gT("Resources Import Summary")."</u></strong><br />\n";
$importtemplateoutput .= "".$clang->gT("Total Imported files").": $okfiles<br />\n";
$importtemplateoutput .= "".$clang->gT("Total Errors").": $errfiles<br />\n";
$importtemplateoutput .= $ImportListHeader;
foreach ($aImportedFilesInfo as $entry)
{
$importtemplateoutput .= "\t<li>".$clang->gT("File").": ".$entry["filename"]."</li>\n";
}
$importtemplateoutput .= "\t</ul><br /><br />\n";
$importtemplateoutput .= $ErrorListHeader;
foreach ($aErrorFilesInfo as $entry)
{
$importtemplateoutput .= "\t<li>".$clang->gT("File").": ".$entry['filename']." (".$entry['status'].")</li>\n";
}
}
else
{
$importtemplateoutput .= "<strong><font color='red'>".$clang->gT("Error")."</font></strong><br />\n";
$importtemplateoutput .= sprintf ($clang->gT("An error occurred uploading your file. This may be caused by incorrect permissions in your %s folder."),$basedestdir)."<br /><br />\n";
$importtemplateoutput .= "</td></tr></table><br />&nbsp;\n";
return;
}
$importtemplateoutput .= "<input type='submit' value='".$clang->gT("Open imported template")."' onclick=\"window.open('$scriptname?action=templates&templatename=$newdir', '_self')\">\n";
}
//--------------------- //---------------------
// Comes from http://fr2.php.net/tempnam // Comes from http://fr2.php.net/tempnam
function tempdir($dir, $prefix='', $mode=0700) function tempdir($dir, $prefix='', $mode=0700)
@@ -377,4 +576,20 @@ if ($action == "importlabelresources" && $lid)
return $path; 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;
}
?> ?>

View File

@@ -10,7 +10,7 @@
* other free or open source software licenses. * other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details. * See COPYRIGHT.php for copyright notices and details.
* *
* $Id: importgroup.php 4973 2008-06-01 14:07:01Z c_schmitz $ * $Id: importgroup.php 7382 2009-08-01 19:48:15Z c_schmitz $
*/ */
include_once("login_check.php"); include_once("login_check.php");
@@ -71,6 +71,10 @@ if (substr($bigarray[0], 0, 23) != "# LimeSurvey Group Dump" && substr($bigarray
unlink($the_full_file_path); unlink($the_full_file_path);
return; return;
} }
else
{
$importversion=(int)trim(substr($bigarray[1],12));
}
for ($i=0; $i<9; $i++) for ($i=0; $i<9; $i++)
{ {
@@ -322,13 +326,17 @@ if (isset($labelsetsarray) && $labelsetsarray) {
if ($count==0) {$count++; continue;} if ($count==0) {$count++; continue;}
// Combine into one array with keys and values since its easier to handle // Combine into one array with keys and values since its easier to handle
$labelrowdata=array_combine($lfieldorders,$lfieldcontents); $labelrowdata=array_combine($lfieldorders,$lfieldcontents);
$labellid=$labelrowdata['lid']; $labellid=$labelrowdata['lid'];
if ($importversion<=132)
{
$labelrowdata["assessment_value"]=(int)$labelrowdata["code"];
}
if ($labellid == $oldlid) { if ($labellid == $oldlid) {
$labelrowdata['lid']=$newlid; $labelrowdata['lid']=$newlid;
// translate internal links // translate internal links
$labelrowdata['title']=translink('label', $oldlid, $newlid, $labelrowdata['title']); $labelrowdata['title']=translink('label', $oldlid, $newlid, $labelrowdata['title']);
$newvalues=array_values($labelrowdata); $newvalues=array_values($labelrowdata);
$newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly
@@ -341,7 +349,7 @@ if (isset($labelsetsarray) && $labelsetsarray) {
//CHECK FOR DUPLICATE LABELSETS //CHECK FOR DUPLICATE LABELSETS
$thisset=""; $thisset="";
$query2 = "SELECT code, title, sortorder, language $query2 = "SELECT code, title, sortorder, language, assessment_value
FROM {$dbprefix}labels FROM {$dbprefix}labels
WHERE lid=".$newlid." WHERE lid=".$newlid."
ORDER BY language, sortorder, code"; ORDER BY language, sortorder, code";
@@ -483,12 +491,19 @@ if (isset($grouparray) && $grouparray)
unset($questionrowdata['qid']); 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) // 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 (in_array($questionrowdata["type"], array("F","H","W","Z", "1", ":", ";"))) // only fot the questions that uses a label set.
if (isset($newlids[$questionrowdata["lid"]])) if (isset($newlids[$questionrowdata["lid"]]))
{
$questionrowdata["lid"] = $newlids[$questionrowdata["lid"]]; $questionrowdata["lid"] = $newlids[$questionrowdata["lid"]];
else if(isset($newlids[$questionrowdata["lid1"]]))
continue; // a problem with this question record -> don't consider {
$questionrowdata["lid1"] = $newlids[$questionrowdata["lid1"]];
}
}
else
{
continue; // a problem with this question record -> don't consider
}
// $other = $questionrowdata["other"]; //Get 'other' field value // $other = $questionrowdata["other"]; //Get 'other' field value
// $oldlid = $questionrowdata['lid']; // $oldlid = $questionrowdata['lid'];
@@ -533,6 +548,12 @@ if (isset($grouparray) && $grouparray)
else else
continue; // a problem with this answer record -> don't consider continue; // a problem with this answer record -> don't consider
if ($importversion<=132)
{
$answerrowdata["assessment_value"]=(int)$answerrowdata["code"];
}
// Everything set - now insert it // Everything set - now insert it
$answerrowdata = array_map('convertCsvreturn2return', $answerrowdata); $answerrowdata = array_map('convertCsvreturn2return', $answerrowdata);
@@ -556,7 +577,7 @@ if (isset($grouparray) && $grouparray)
$gres = db_execute_assoc($gquery); $gres = db_execute_assoc($gquery);
while ($grow = $gres->FetchRow()) while ($grow = $gres->FetchRow())
{ {
fixsortorderQuestions(0,$grow['gid']); fixsortorderQuestions($grow['gid'], $surveyid);
} }
} }
@@ -619,7 +640,14 @@ if (isset($grouparray) && $grouparray)
unset($conditionrowdata["cid"]); unset($conditionrowdata["cid"]);
// recreate the cfieldname with the new IDs // recreate the cfieldname with the new IDs
$newcfieldname = $newsid . "X" . $newgid . "X" . $conditionrowdata["cqid"] .substr($oldqidanscode,strlen($oldcgid)); 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; $conditionrowdata["cfieldname"] = $newcfieldname;
if (!isset($conditionrowdata["method"]) || trim($conditionrowdata["method"])=='') if (!isset($conditionrowdata["method"]) || trim($conditionrowdata["method"])=='')
@@ -651,7 +679,7 @@ else
$importgroup .= "<br />\n<strong><font class='successtitle'>".$clang->gT("Success")."</font></strong><br />\n"; $importgroup .= "<br />\n<strong><font class='successtitle'>".$clang->gT("Success")."</font></strong><br />\n";
} }
$importgroup .="<strong><u>".$clang->gT("Group Import Summary")."</u></strong><br />\n" $importgroup .="<strong><u>".$clang->gT("Group Import Summary")."</u></strong><br />\n"
."<ul>\n\t<li>".$clang->gT("Groups").": "; ."<ul>\n\t<li>".$clang->gT("Groups:");
if (isset($countgroups)) {$importgroup .= $countgroups;} if (isset($countgroups)) {$importgroup .= $countgroups;}
$importgroup .= "</li>\n" $importgroup .= "</li>\n"
."\t<li>".$clang->gT("Questions").": "; ."\t<li>".$clang->gT("Questions").": ";
@@ -671,8 +699,9 @@ $importgroup .= ")</li>\n";
$importgroup .= "\t<li>".$clang->gT("Question Attributes: "); $importgroup .= "\t<li>".$clang->gT("Question Attributes: ");
$importgroup .= $countquestion_attributes; $importgroup .= $countquestion_attributes;
$importgroup .= "</li>\n</ul>\n"; $importgroup .= "</li>\n</ul>\n";
$importgroup .= "<strong>".$clang->gT("Import of group is completed.")."</strong><br />&nbsp;\n" $importgroup .= "<strong>".$clang->gT("Import of group is completed.")."</strong><br />&nbsp;\n";
."</td></tr></table><br />&nbsp;\n"; $importgroup .= "<a href='$scriptname?sid=$newsid&amp;gid=$newgid'>".$clang->gT("Go to group")."</a><br />\n";
$importgroup .= "</td></tr></table><br />&nbsp;\n";
unlink($the_full_file_path); unlink($the_full_file_path);

View File

@@ -10,7 +10,7 @@
* other free or open source software licenses. * other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details. * See COPYRIGHT.php for copyright notices and details.
* *
* $Id: importlabel.php 4973 2008-06-01 14:07:01Z c_schmitz $ * $Id: importlabel.php 7382 2009-08-01 19:48:15Z c_schmitz $
*/ */
//Ensure script is not run directly, avoid path disclosure //Ensure script is not run directly, avoid path disclosure
@@ -145,8 +145,12 @@ if (isset($labelsetsarray) && $labelsetsarray) {
if ($labellid == $oldlid) { if ($labellid == $oldlid) {
$labelrowdata['lid']=$newlid; $labelrowdata['lid']=$newlid;
// translate internal links // translate internal links
$labelrowdata['title']=translink('label', $oldlid, $newlid, $labelrowdata['title']); $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_values($labelrowdata);
$newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly
@@ -158,7 +162,7 @@ if (isset($labelsetsarray) && $labelsetsarray) {
//CHECK FOR DUPLICATE LABELSETS //CHECK FOR DUPLICATE LABELSETS
$thisset=""; $thisset="";
$query2 = "SELECT code, title, sortorder, language $query2 = "SELECT code, title, sortorder, language, assessment_value
FROM ".db_table_name('labels')." FROM ".db_table_name('labels')."
WHERE lid=".$newlid." WHERE lid=".$newlid."
ORDER BY sortorder, code"; ORDER BY sortorder, code";

View File

@@ -10,9 +10,10 @@
* other free or open source software licenses. * other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details. * See COPYRIGHT.php for copyright notices and details.
* *
* $Id: importoldresponses.php 4973 2008-06-01 14:07:01Z c_schmitz $ * $Id: importoldresponses.php 7058 2009-06-10 14:42:27Z c_schmitz $
*/ */
//import responses from an old_ survey table into an active survey //import responses from an old_ survey table into an active survey
include_once("login_check.php"); include_once("login_check.php");
@@ -24,114 +25,244 @@ if (!$subaction == "import")
{ {
// show UI for choosing old table // show UI for choosing old table
$query = db_select_tables_like("{$dbprefix}old\_survey_{$surveyid}\_%"); $query = db_select_tables_like("{$dbprefix}old\_survey\_%");
$result = db_execute_num($query) or safe_die("Error:<br />$query<br />".$connect->ErrorMsg()); $result = db_execute_num($query) or safe_die("Error:<br />$query<br />".$connect->ErrorMsg());
$optionElements = ''; $optionElements = '';
$queryCheckColumnsActive = "SELECT * FROM {$dbprefix}survey_{$surveyid} ";
$resultActive = db_execute_num($queryCheckColumnsActive) or safe_die("Error:<br />$query<br />".$connect->ErrorMsg());
$countActive = $resultActive->FieldCount();
while ($row = $result->FetchRow()) while ($row = $result->FetchRow())
{ {
$optionElements .= "\t\t\t<option>{$row[0]}</option>\n"; $queryCheckColumnsOld = "SELECT * FROM {$row[0]} ";
$resultOld = db_execute_num($queryCheckColumnsOld) or safe_die("Error:<br />$query<br />".$connect->ErrorMsg());
if($countActive== $resultOld->FieldCount())
{
$optionElements .= "\t\t\t<option value='{$row[0]}'>{$row[0]}</option>\n";
}
} }
$importoldresponsesoutput = "";
$importoldresponsesoutput .= "<table width='99%' align='center' class='menubar' cellpadding='1' cellspacing='0'>\n"
."\t<tr><td colspan='2' height='4'><strong>".$clang->gT("Quick Statistics")."</strong></td></tr>\n";
//Get the menubar //Get the menubar
$importoldresponsesoutput .= browsemenubar(); $importoldresponsesoutput = browsemenubar($clang->gT("Quick Statistics"));
$importoldresponsesoutput .= "</table>\n"; $importoldresponsesoutput .= "<br />
$importoldresponsesoutput .= "<br /><table align='center' class='outlinetable'> <div class='header'>
<tr> ".$clang->gT("Import responses from an deactivated survey table")."
<th colspan='2'>".$clang->gT("Import responses from an old (deactivated) survey table into an active survey")."</th> </div>
</tr> <form id='personalsettings' method='post'>
<form method='post'> <ul>
<tr> <li><label for='spansurveyid'>".$clang->gT("Target survey ID:")."</label>
<td align='right'>".$clang->gT("Target Survey ID")."</td> <span id='spansurveyid'> $surveyid<input type='hidden' value='$surveyid' name='sid'></span>
<td> $surveyid<input type='hidden' value='$surveyid' name='sid'></td> </li>
</tr> <li>
<tr> <label for='oldtable'>
<td align='right'> ".$clang->gT("Source table:")."
".$clang->gT("Source table").": </label>
</td>
<td>
<select name='oldtable' > <select name='oldtable' >
{$optionElements} {$optionElements}
</select> </select>
</td> </li>
</tr> </ul>
<tr>
<td colspan='2' align='center'>
<input type='submit' value='".$clang->gT("Import Responses")."' onclick='return confirm(\"".$clang->gT("Are you sure?","js").")'>&nbsp; <input type='submit' value='".$clang->gT("Import Responses")."' onclick='return confirm(\"".$clang->gT("Are you sure?","js").")'>&nbsp;
<input type='hidden' name='subaction' value='import'> <input type='hidden' name='subaction' value='import'><br /><br />
</td> <div class='warningtitle'>".$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.")."</div>
</tr>
</form> </form>
</table><br />&nbsp;"; </div>
<br />";
} }
elseif (isset($surveyid) && $surveyid && isset($oldtable)) 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";
// options (UI not implemented) //Fields we don't want to import
$dontimportfields = array(
'id' //,'otherfield'
);
$dontimportfields = array( // fields we can import
'id' //,'otherfield' $importablefields = array();
); if($databasetype=="postgres")
$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:<br />$query<br />".$connect->ErrorMsg());
while ($row = $result->FetchRow())
{
if (!in_array($row['Field'],$dontimportfields))
{ {
$importablefields[] = $row['Field']; $query = "SELECT column_name as field FROM information_schema.columns WHERE table_name = '{$activetable}' ";
} }
} else
// fields we can supply
$availablefields = array();
$query = "SHOW COLUMNS FROM {$oldtable}";
$result = db_execute_assoc($query) or safe_die("Error:<br />$query<br />".$connect->ErrorMsg());
while ($row = $result->FetchRow())
{
$availablefields[] = $row['Field'];
}
foreach ($presetfields as $field => $value)
{
if (!in_array($field,$availablefields))
{ {
$availablefields[] = $field; $query = "SHOW COLUMNS FROM {$activetable}";
} }
}
$fieldstoimport = array_intersect($importablefields,$availablefields); $result = db_execute_assoc($query) or safe_die("Error:<br />$query<br />".$connect->ErrorMsg());
// data sources for each field (field of oldtable or preset value) while ($row = $result->FetchRow())
$sourcefields = array(); {
foreach ($fieldstoimport as $field) if($databasetype=="postgres")
{ {
$sourcefields[] = array_key_exists($field,$presetfields)? if (!in_array($row['field'],$dontimportfields))
$presetfields[$field] {
: ($oldtable.'.'.$field); $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."\""; }
}
$query = "INSERT INTO {$activetable} (\n\t".join("\t, ",$fieldstoimport)."\n) " //fields we can supply //fields in the old database
."SELECT\n\t".join("\t,",$sourcefields)."\n" $availablefields = array();
."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:<br />$query<br />".$connect->ErrorMsg()); 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:<br />$query<br />".$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:<br />$queryOldValues<br />".$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:<br />$insertOldValues<br />".$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:<br />$query<br />".$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:<br />$query<br />".$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:<br />$query<br />".$connect->ErrorMsg());
// }
header("Location: $scriptname?action=browse&sid=$surveyid"); header("Location: $scriptname?action=browse&sid=$surveyid");
} }

View File

@@ -10,7 +10,7 @@
* other free or open source software licenses. * other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details. * See COPYRIGHT.php for copyright notices and details.
* *
* $Id: importquestion.php 4973 2008-06-01 14:07:01Z c_schmitz $ * $Id: importquestion.php 7382 2009-08-01 19:48:15Z c_schmitz $
*/ */
//Ensure script is not run directly, avoid path disclosure //Ensure script is not run directly, avoid path disclosure
@@ -101,16 +101,6 @@ else // unknown file - show error message
return; return;
} }
if ($importversion != $dbversionnumber)
{
$importquestion .= "<strong><font color='red'>".$clang->gT("Error")."</font></strong><br />\n";
$importquestion .= $clang->gT("Sorry, importing questions is limited to the same version. Import failed.")."<br /><br />\n";
$importquestion .= "</font></td></tr></table>\n";
$importquestion .= "</body>\n</html>\n";
unlink($the_full_file_path);
return;
}
for ($i=0; $i<9; $i++) //skipping the first lines that are not needed for ($i=0; $i<9; $i++) //skipping the first lines that are not needed
{ {
unset($bigarray[$i]); unset($bigarray[$i]);
@@ -326,11 +316,16 @@ if (isset($labelsetsarray) && $labelsetsarray) {
// Combine into one array with keys and values since its easier to handle // Combine into one array with keys and values since its easier to handle
$labelrowdata=array_combine($lfieldorders,$lfieldcontents); $labelrowdata=array_combine($lfieldorders,$lfieldcontents);
$labellid=$labelrowdata['lid']; $labellid=$labelrowdata['lid'];
if ($importversion<=132)
{
$labelrowdata["assessment_value"]=(int)$labelrowdata["code"];
}
if ($labellid == $oldlid) { if ($labellid == $oldlid) {
$labelrowdata['lid']=$newlid; $labelrowdata['lid']=$newlid;
// translate internal links // translate internal links
$labelrowdata['title']=translink('label', $oldlid, $newlid, $labelrowdata['title']); $labelrowdata['title']=translink('label', $oldlid, $newlid, $labelrowdata['title']);
$newvalues=array_values($labelrowdata); $newvalues=array_values($labelrowdata);
$newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly
@@ -342,7 +337,7 @@ if (isset($labelsetsarray) && $labelsetsarray) {
//CHECK FOR DUPLICATE LABELSETS //CHECK FOR DUPLICATE LABELSETS
$thisset=""; $thisset="";
$query2 = "SELECT code, title, sortorder, language $query2 = "SELECT code, title, sortorder, language, assessment_value
FROM {$dbprefix}labels FROM {$dbprefix}labels
WHERE lid=".$newlid." WHERE lid=".$newlid."
ORDER BY language, sortorder, code"; ORDER BY language, sortorder, code";
@@ -420,13 +415,18 @@ if (isset($questionarray) && $questionarray) {
// Now we will fix up the label id // Now we will fix up the label id
$type = $questionrowdata["type"]; //Get the type $type = $questionrowdata["type"]; //Get the type
if ($type == "F" || $type == "H" || $type == "W" || $type == "Z") 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 this is a flexible label array, update the lid entry
if (isset($labelreplacements)) { if (isset($labelreplacements)) {
foreach ($labelreplacements as $lrp) { foreach ($labelreplacements as $lrp) {
if ($lrp[0] == $questionrowdata["lid"]) { if ($lrp[0] == $questionrowdata["lid"]) {
$questionrowdata["lid"]=$lrp[1]; $questionrowdata["lid"]=$lrp[1];
} }
if ($lrp[0] == $questionrowdata["lid1"]) {
$questionrowdata["lid1"]=$lrp[1];
}
} }
} }
} }
@@ -455,18 +455,25 @@ if (isset($questionarray) && $questionarray) {
foreach ($answerarray as $aa) { foreach ($answerarray as $aa) {
$answerfieldcontents=convertCSVRowToArray($aa,',','"'); $answerfieldcontents=convertCSVRowToArray($aa,',','"');
$answerrowdata=array_combine($answerfieldnames,$answerfieldcontents); $answerrowdata=array_combine($answerfieldnames,$answerfieldcontents);
if ($answerrowdata===false)
{
$importquestion.='<br />'.$clang->gT("Faulty line in import - fields and data don't match").":".implode(',',$answerfieldcontents);
}
if (isset($languagesSupported[$answerrowdata["language"]])) if (isset($languagesSupported[$answerrowdata["language"]]))
{ {
$code=$answerrowdata["code"]; $code=$answerrowdata["code"];
$thisqid=$answerrowdata["qid"]; $thisqid=$answerrowdata["qid"];
$answerrowdata["qid"]=$newqid; $answerrowdata["qid"]=$newqid;
// translate internal links // translate internal links
$answerrowdata['answer']=translink('survey', $oldsid, $newsid, $answerrowdata['answer']); $answerrowdata['answer']=translink('survey', $oldsid, $newsid, $answerrowdata['answer']);
if ($importversion<=132)
$newvalues=array_values($answerrowdata); {
$newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly $answerrowdata["assessment_value"]=(int)$answerrowdata["code"];
$ainsert = "INSERT INTO {$dbprefix}answers (".implode(',',array_keys($answerrowdata)).") VALUES (".implode(',',$newvalues).")"; }
$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<br />\n$ainsert<br />\n".$connect->ErrorMsg()); $ares = $connect->Execute($ainsert) or safe_die ($clang->gT("Error").": Failed to insert answer<br />\n$ainsert<br />\n".$connect->ErrorMsg());
} }
} }
@@ -509,8 +516,9 @@ $importquestion .= "\t<li>".$clang->gT("Question Attributes:");
if (isset($countquestion_attributes)) {$importquestion .= $countquestion_attributes;} if (isset($countquestion_attributes)) {$importquestion .= $countquestion_attributes;}
$importquestion .= "</li></ul><br />\n"; $importquestion .= "</li></ul><br />\n";
$importquestion .= "<strong>".$clang->gT("Question import is complete.")."</strong><br />&nbsp;\n" $importquestion .= "<strong>".$clang->gT("Question import is complete.")."</strong><br />&nbsp;\n";
."</td></tr></table><br/>\n"; $importquestion .= "<a href='$scriptname?sid=$newsid&amp;gid=$newgid&amp;qid=$newqid'>".$clang->gT("Go to question")."</a><br />\n";
$importquestion .= "</td></tr></table><br/>\n";
unlink($the_full_file_path); unlink($the_full_file_path);

View File

@@ -10,7 +10,7 @@
* other free or open source software licenses. * other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details. * See COPYRIGHT.php for copyright notices and details.
* *
* $Id: importsurvey.php 4973 2008-06-01 14:07:01Z c_schmitz $ * $Id: importsurvey.php 7506 2009-08-21 09:28:59Z c_schmitz $
*/ */
//Ensure script is not run directly, avoid path disclosure //Ensure script is not run directly, avoid path disclosure
@@ -26,15 +26,15 @@ while (!feof($handle))
} }
fclose($handle); fclose($handle);
if (isset($bigarray[0])) $bigarray[0]=removeBOM($bigarray[0]);
// Now we try to determine the dataformat of the survey file. // Now we try to determine the dataformat of the survey file.
if ((substr($bigarray[1], 0, 22) == "# SURVEYOR SURVEY DUMP")&& (substr($bigarray[4], 0, 29) == "# http://www.phpsurveyor.org/")) 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 $importversion = 100; // version 1.0 file
} }
elseif elseif
((substr($bigarray[1], 0, 22) == "# SURVEYOR SURVEY DUMP")&& (substr($bigarray[4], 0, 37) == "# http://phpsurveyor.sourceforge.net/")) (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 $importversion = 99; // Version 0.99 file or older - carries a different URL
} }
@@ -319,11 +319,37 @@ for ($i=0; $i<=$stoppoint+1; $i++)
} }
$bigarray = array_values($bigarray); $bigarray = array_values($bigarray);
//Survey Language Settings //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; $stoppoint = count($bigarray)-1;
for ($i=0; $i<$stoppoint-1; $i++) for ($i=0; $i<$stoppoint-1; $i++)
{ {
if ($i<=$stoppoint) {$quotamembersarray[] = $bigarray[$i];} if ($i<=$stoppoint) {$quotalsarray[] = $bigarray[$i];}
unset($bigarray[$i]); unset($bigarray[$i]);
} }
$bigarray = array_values($bigarray); $bigarray = array_values($bigarray);
@@ -338,6 +364,8 @@ if (isset($labelsetsarray)) {$countlabelsets = count($labelsetsarray);} else {$c
if (isset($question_attributesarray)) {$countquestion_attributes = count($question_attributesarray);} else {$countquestion_attributes=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($assessmentsarray)) {$countassessments=count($assessmentsarray);} else {$countassessments=0;}
if (isset($quotaarray)) {$countquota=count($quotaarray);} else {$countquota=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 // CREATE SURVEY
@@ -507,14 +535,15 @@ if ($importversion<=100)
$surveylsrowdata['surveyls_description']=$surveyrowdata['description']; $surveylsrowdata['surveyls_description']=$surveyrowdata['description'];
$surveylsrowdata['surveyls_welcometext']=$surveyrowdata['welcome']; $surveylsrowdata['surveyls_welcometext']=$surveyrowdata['welcome'];
$surveylsrowdata['surveyls_urldescription']=$surveyrowdata['urldescrip']; $surveylsrowdata['surveyls_urldescription']=$surveyrowdata['urldescrip'];
$surveylsrowdata['surveyls_email_invite_subj']=$surveyrowdata['email_invite_subj']; if (isset($surveyrowdata['email_invite_subj'])) $surveylsrowdata['surveyls_email_invite_subj']=$surveyrowdata['email_invite_subj'];
$surveylsrowdata['surveyls_email_invite']=$surveyrowdata['email_invite']; $surveylsrowdata['surveyls_email_invite']=$surveyrowdata['email_invite'];
$surveylsrowdata['surveyls_email_remind_subj']=$surveyrowdata['email_remind_subj']; if (isset($surveyrowdata['email_remind_subj'])) $surveylsrowdata['surveyls_email_remind_subj']=$surveyrowdata['email_remind_subj'];
$surveylsrowdata['surveyls_email_remind']=$surveyrowdata['email_remind']; $surveylsrowdata['surveyls_email_remind']=$surveyrowdata['email_remind'];
$surveylsrowdata['surveyls_email_register_subj']=$surveyrowdata['email_register_subj']; if (isset($surveyrowdata['email_register_subj'])) $surveylsrowdata['surveyls_email_register_subj']=$surveyrowdata['email_register_subj'];
$surveylsrowdata['surveyls_email_register']=$surveyrowdata['email_register']; $surveylsrowdata['surveyls_email_register']=$surveyrowdata['email_register'];
$surveylsrowdata['surveyls_email_confirm_subj']=$surveyrowdata['email_confirm_subj']; if (isset($surveyrowdata['email_confirm_subj'])) $surveylsrowdata['surveyls_email_confirm_subj']=$surveyrowdata['email_confirm_subj'];
$surveylsrowdata['surveyls_email_confirm']=$surveyrowdata['email_confirm']; $surveylsrowdata['surveyls_email_confirm']=$surveyrowdata['email_confirm'];
if(!isset($defaultsurveylanguage)) {$defaultsurveylanguage=$newlanguage;}
unset($surveyrowdata['short_title']); unset($surveyrowdata['short_title']);
unset($surveyrowdata['description']); unset($surveyrowdata['description']);
unset($surveyrowdata['welcome']); unset($surveyrowdata['welcome']);
@@ -546,15 +575,18 @@ if ($importversion<=100)
$values=array_map(array(&$connect, "qstr"),$values); // quote everything accordingly $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 $insert = "insert INTO {$dbprefix}surveys_languagesettings (".implode(',',array_keys($surveylsrowdata)).") VALUES (".implode(',',$values).")"; //handle db prefix
$iresult = $connect->Execute($insert) or safe_die("<br />".$clang->gT("Import of this survey file failed")."<br />\n[$insert]<br />{$surveyarray[0]}<br /><br />\n" . $connect->ErrorMsg()); $iresult = $connect->Execute($insert) or safe_die("<br />".$clang->gT("Import of this survey file failed")."<br />\n[$insert]<br />{$surveyarray[0]}<br /><br />\n" . $connect->ErrorMsg());
} }
if (isset($surveyrowdata['datecreated'])) {$surveyrowdata['datecreated']=$connect->BindTimeStamp($surveyrowdata['datecreated']);} if (isset($surveyrowdata['datecreated'])) {$surveyrowdata['datecreated']=$connect->BindTimeStamp($surveyrowdata['datecreated']);}
unset($surveyrowdata['expires']); 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']; $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));} 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));}
@@ -659,6 +691,10 @@ if (isset($labelsetsarray) && $labelsetsarray) {
} }
// Combine into one array with keys and values since its easier to handle // Combine into one array with keys and values since its easier to handle
$labelrowdata=array_combine($lfieldorders,$lfieldcontents); $labelrowdata=array_combine($lfieldorders,$lfieldcontents);
if ($importversion<=132)
{
$labelrowdata["assessment_value"]=(int)$labelrowdata["code"];
}
$labellid=$labelrowdata['lid']; $labellid=$labelrowdata['lid'];
if ($importversion<=100) if ($importversion<=100)
{ {
@@ -681,9 +717,8 @@ if (isset($labelsetsarray) && $labelsetsarray) {
//CHECK FOR DUPLICATE LABELSETS //CHECK FOR DUPLICATE LABELSETS
$thisset=""; $thisset="";
/*
/* $query2 = "SELECT code, title, sortorder, language, assessment_value
$query2 = "SELECT code, title, sortorder, language
FROM {$dbprefix}labels FROM {$dbprefix}labels
WHERE lid=".$newlid." WHERE lid=".$newlid."
ORDER BY language, sortorder, code"; ORDER BY language, sortorder, code";
@@ -721,8 +756,7 @@ if (isset($labelsetsarray) && $labelsetsarray) {
$csarray[$newlid]=$newcs; $csarray[$newlid]=$newcs;
} }
//END CHECK FOR DUPLICATES //END CHECK FOR DUPLICATES
*/ */
$labelreplacements[]=array($oldlid, $newlid); $labelreplacements[]=array($oldlid, $newlid);
} }
} }
@@ -789,8 +823,11 @@ if (isset($grouparray) && $grouparray) {
$newvalues=array_values($grouprowdata); $newvalues=array_values($grouprowdata);
$newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly $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<br />\n$ginsert<br />\n".$connect->ErrorMsg()); 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<br />\n$ginsert<br />\n".$connect->ErrorMsg());
if (isset($grouprowdata['gid'])) {@$connect->Execute('SET IDENTITY_INSERT '.db_table_name('groups').' OFF');}
//GET NEW GID //GET NEW GID
if ($newgroup) {$newgid=$connect->Insert_ID("{$dbprefix}groups","gid");} if ($newgroup) {$newgid=$connect->Insert_ID("{$dbprefix}groups","gid");}
@@ -823,13 +860,13 @@ if (isset($grouparray) && $grouparray) {
$questionrowdata["type"] = strtoupper($questionrowdata["type"]); $questionrowdata["type"] = strtoupper($questionrowdata["type"]);
if (!array_key_exists($questionrowdata["type"], $qtypes)) if (!array_key_exists($questionrowdata["type"], $qtypes))
{ {
$importwarning .= "<li>" . $clang->gT("Question") . " \"{$questionrowdata["title"]} - {$questionrowdata["question"]}\" " . $clang->gT("was NOT imported because the question type is unknown.") . "</li>"; $importwarning .= "<li>" . sprintf($clang->gT("Question \"%s - %s\" was NOT imported because the question type is unknown."), $questionrowdata["title"], $questionrowdata["question"]) . "</li>";
$countquestions--; $countquestions--;
continue; continue;
} }
else // the upper case worked well $qtypes[$questionrowdata["type"]] else // the upper case worked well $qtypes[$questionrowdata["type"]]
{ {
$importwarning .= "<li>" . $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"]]) . "</li>"; $importwarning .= "<li>" . 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"]]) . "</li>";
} }
} }
@@ -845,47 +882,66 @@ if (isset($grouparray) && $grouparray) {
$questionrowdata["gid"] = $newgid; $questionrowdata["gid"] = $newgid;
// Version <=100 doesn't have a language field yet so we set it now // Version <=100 doesn't have a language field yet so we set it now
if ($importversion<=100) if ($importversion<=100)
{ {
$questionrowdata['language']=$newlanguage; $questionrowdata['language']=$newlanguage;
} }
$oldqid=$qid; $oldqid=$qid;
if (!isset($questionrowdata["lid1"])) if (!isset($questionrowdata["lid1"]))
{ {
$questionrowdata["lid1"]=0; $questionrowdata["lid1"]=0;
} }
// Now we will fix up the label id // Now we will fix up the label id
$type = $questionrowdata["type"]; //Get the type $type = $questionrowdata["type"]; //Get the type
if ($type == "F" || $type == "H" || $type == "W" || $type == "Z" || $type == "1") if ($type == "F" || $type == "H" || $type == "W" ||
{//IF this is a flexible label array, update the lid entry $type == "Z" || $type == "1" || $type == ":" ||
$type == ";" )
{//IF this is a flexible label array, update the lid entry
if (isset($labelreplacements)) { 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) { foreach ($labelreplacements as $lrp) {
if ($lrp[0] == $questionrowdata["lid"]) if ($lrp[0] == $questionrowdata["lid"])
{ {
$questionrowdata["lid"]=$lrp[1]; if (!$already_replaced_label)
} {
if ($lrp[0] == $questionrowdata["lid1"]) $questionrowdata["lid"]=$lrp[1];
{ $already_replaced_label = true;
$questionrowdata["lid1"]=$lrp[1]; }
} }
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;} if (!isset($questionrowdata["question_order"]) || $questionrowdata["question_order"]=='') {$questionrowdata["question_order"]=0;}
$other = $questionrowdata["other"]; //Get 'other' field value $other = $questionrowdata["other"]; //Get 'other' field value
// translate internal links // translate internal links
$questionrowdata['title']=translink('survey', $surveyid, $newsid, $questionrowdata['title']); $questionrowdata['title']=translink('survey', $surveyid, $newsid, $questionrowdata['title']);
$questionrowdata['question']=translink('survey', $surveyid, $newsid, $questionrowdata['question']); $questionrowdata['question']=translink('survey', $surveyid, $newsid, $questionrowdata['question']);
$questionrowdata['help']=translink('survey', $surveyid, $newsid, $questionrowdata['help']); $questionrowdata['help']=translink('survey', $surveyid, $newsid, $questionrowdata['help']);
$newvalues=array_values($questionrowdata); $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 $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly
$qinsert = "insert INTO {$dbprefix}questions (".implode(',',array_keys($questionrowdata)).") VALUES (".implode(',',$newvalues).")"; $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<br />\n$qinsert<br />\n".$connect->ErrorMsg());
$qres = $connect->Execute($qinsert) or safe_die ($clang->gT("Error").": Failed to insert question<br />\n$qinsert<br />\n".$connect->ErrorMsg());
if (isset($questionrowdata['qid'])) {@$connect->Execute('SET IDENTITY_INSERT '.db_table_name('questions').' OFF');}
if ($newquestion) if ($newquestion)
{ {
$newqid=$connect->Insert_ID("{$dbprefix}questions","qid"); $newqid=$connect->Insert_ID("{$dbprefix}questions","qid");
} }
$newrank=0; $newrank=0;
$substitutions[]=array($oldsid, $oldgid, $oldqid, $newsid, $newgid, $newqid); $substitutions[]=array($oldsid, $oldgid, $oldqid, $newsid, $newgid, $newqid);
@@ -906,6 +962,10 @@ if (isset($grouparray) && $grouparray) {
$aacfieldcontents=convertToArray($aa, "', '", "('", "')"); $aacfieldcontents=convertToArray($aa, "', '", "('", "')");
} }
$answerrowdata=array_combine($aafieldorders,$aacfieldcontents); $answerrowdata=array_combine($aafieldorders,$aacfieldcontents);
if ($importversion<=132)
{
$answerrowdata["assessment_value"]=(int)$answerrowdata["code"];
}
$code=$answerrowdata["code"]; $code=$answerrowdata["code"];
$thisqid=$answerrowdata["qid"]; $thisqid=$answerrowdata["qid"];
if ($thisqid == $qid) if ($thisqid == $qid)
@@ -913,12 +973,12 @@ if (isset($grouparray) && $grouparray) {
$answerrowdata["qid"]=$newqid; $answerrowdata["qid"]=$newqid;
// Version <=100 doesn't have a language field yet so we set it now // Version <=100 doesn't have a language field yet so we set it now
if ($importversion<=100) if ($importversion<=100)
{ {
$answerrowdata['language']=$newlanguage; $answerrowdata['language']=$newlanguage;
} }
// translate internal links // translate internal links
$answerrowdata['answer']=translink('survey', $surveyid, $newsid, $answerrowdata['answer']); $answerrowdata['answer']=translink('survey', $surveyid, $newsid, $answerrowdata['answer']);
$newvalues=array_values($answerrowdata); $newvalues=array_values($answerrowdata);
$newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly
@@ -930,6 +990,10 @@ if (isset($grouparray) && $grouparray) {
"newcfieldname"=>$newsid."X".$newgid."X".$newqid, "newcfieldname"=>$newsid."X".$newgid."X".$newqid,
"oldfieldname"=>$oldsid."X".$oldgid."X".$oldqid.$code, "oldfieldname"=>$oldsid."X".$oldgid."X".$oldqid.$code,
"newfieldname"=>$newsid."X".$newgid."X".$newqid.$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") { if ($type == "P") {
$fieldnames[]=array("oldcfieldname"=>$oldsid."X".$oldgid."X".$oldqid."comment", $fieldnames[]=array("oldcfieldname"=>$oldsid."X".$oldgid."X".$oldqid."comment",
"newcfieldname"=>$newsid."X".$newgid."X".$newqid.$code."comment", "newcfieldname"=>$newsid."X".$newgid."X".$newqid.$code."comment",
@@ -943,6 +1007,19 @@ if (isset($grouparray) && $grouparray) {
"oldfieldname"=>$oldsid."X".$oldgid."X".$oldqid.$code, "oldfieldname"=>$oldsid."X".$oldgid."X".$oldqid.$code,
"newfieldname"=>$newsid."X".$newgid."X".$newqid.$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<br />$query2<br />".$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") { elseif ($type == "R") {
$newrank++; $newrank++;
} }
@@ -1000,7 +1077,7 @@ if (isset($grouparray) && $grouparray) {
$gres = db_execute_assoc($gquery); $gres = db_execute_assoc($gquery);
while ($grow = $gres->FetchRow()) while ($grow = $gres->FetchRow())
{ {
fixsortorderQuestions(0,$grow['gid']); fixsortorderQuestions($grow['gid'], $surveyid);
} }
//We've built two arrays along the way - one containing the old SID, GID and QIDs - and their NEW equivalents //We've built two arrays along the way - one containing the old SID, GID and QIDs - and their NEW equivalents
@@ -1036,7 +1113,7 @@ if (isset($question_attributesarray) && $question_attributesarray) {//ONLY DO TH
} }
} }
if (isset($assessmentsarray) && $assessmentsarray) {//ONLY DO THIS IF THERE ARE QUESTION_ATTRIBUES if (isset($assessmentsarray) && $assessmentsarray) {//ONLY DO THIS IF THERE ARE QUESTION_ATTRIBUTES
$count=0; $count=0;
foreach ($assessmentsarray as $qar) { foreach ($assessmentsarray as $qar) {
if ($importversion>=111) if ($importversion>=111)
@@ -1051,12 +1128,24 @@ if (isset($assessmentsarray) && $assessmentsarray) {//ONLY DO THIS IF THERE ARE
$fieldcontents=convertToArray($qar, "', '", "('", "')"); $fieldcontents=convertToArray($qar, "', '", "('", "')");
} }
$asrowdata=array_combine($fieldorders,$fieldcontents); $asrowdata=array_combine($fieldorders,$fieldcontents);
if (isset($asrowdata['link']))
{
if (trim($asrowdata['link'])!='') $asrowdata['message']=$asrowdata['message'].'<br /><a href="'.$asrowdata['link'].'">'.$asrowdata['link'].'</a>';
unset($asrowdata['link']);
}
$oldsid=$asrowdata["sid"]; $oldsid=$asrowdata["sid"];
$oldgid=$asrowdata["gid"]; $oldgid=$asrowdata["gid"];
foreach ($substitutions as $subs) { if ($oldgid>0)
if ($oldsid==$subs[0]) {$newsid=$subs[3];} {
if ($oldgid==$subs[1]) {$newgid=$subs[4];} 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["sid"]=$newsid;
$asrowdata["gid"]=$newgid; $asrowdata["gid"]=$newgid;
@@ -1090,6 +1179,7 @@ if (isset($quotaarray) && $quotaarray) {//ONLY DO THIS IF THERE ARE QUOTAS
$asrowdata["sid"]=$newsid; $asrowdata["sid"]=$newsid;
$oldid = $asrowdata["id"]; $oldid = $asrowdata["id"];
unset($asrowdata["id"]); unset($asrowdata["id"]);
$quotadata[]=$asrowdata; //For use later if needed
$newvalues=array_values($asrowdata); $newvalues=array_values($asrowdata);
$newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly
@@ -1101,7 +1191,7 @@ if (isset($quotaarray) && $quotaarray) {//ONLY DO THIS IF THERE ARE QUOTAS
} }
} }
if (isset($quotamembersarray) && $quotamembersarray) {//ONLY DO THIS IF THERE ARE QUOTAS if (isset($quotamembersarray) && $quotamembersarray) {//ONLY DO THIS IF THERE ARE QUOTA MEMBERS
$count=0; $count=0;
foreach ($quotamembersarray as $qar) { foreach ($quotamembersarray as $qar) {
@@ -1140,6 +1230,56 @@ if (isset($quotamembersarray) && $quotamembersarray) {//ONLY DO THIS IF THERE AR
} }
} }
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<br />$asinsert<br />".$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<br />$asinsert<br />".$connect->ErrorMsg());
$countquotals=$i;
}
if (isset($conditionsarray) && $conditionsarray) {//ONLY DO THIS IF THERE ARE CONDITIONS! if (isset($conditionsarray) && $conditionsarray) {//ONLY DO THIS IF THERE ARE CONDITIONS!
$count='0'; $count='0';
foreach ($conditionsarray as $car) { foreach ($conditionsarray as $car) {
@@ -1161,11 +1301,24 @@ if (isset($conditionsarray) && $conditionsarray) {//ONLY DO THIS IF THERE ARE CO
$oldcfieldname=$conditionrowdata["cfieldname"]; $oldcfieldname=$conditionrowdata["cfieldname"];
$oldcqid=$conditionrowdata["cqid"]; $oldcqid=$conditionrowdata["cqid"];
$thisvalue=$conditionrowdata["value"]; $thisvalue=$conditionrowdata["value"];
$newvalue=$thisvalue;
foreach ($substitutions as $subs) { foreach ($substitutions as $subs) {
if ($oldqid==$subs[2]) {$newqid=$subs[5];} if ($oldqid==$subs[2]) {$newqid=$subs[5];}
if ($oldcqid==$subs[2]) {$newcqid=$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) { foreach($fieldnames as $fns) {
//if the $fns['oldcfieldname'] is not the same as $fns['oldfieldname'] then this is a multiple type question //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 ($fns['oldcfieldname'] == $fns['oldfieldname']) { //The normal method - non multiples
@@ -1182,6 +1335,7 @@ if (isset($conditionsarray) && $conditionsarray) {//ONLY DO THIS IF THERE ARE CO
unset($conditionrowdata["cid"]); unset($conditionrowdata["cid"]);
$conditionrowdata["qid"]=$newqid; $conditionrowdata["qid"]=$newqid;
$conditionrowdata["cfieldname"]=$newcfieldname; $conditionrowdata["cfieldname"]=$newcfieldname;
$conditionrowdata["value"]=$newvalue;
if (isset($newcqid)) { if (isset($newcqid)) {
$conditionrowdata["cqid"]=$newcqid; $conditionrowdata["cqid"]=$newcqid;
@@ -1189,13 +1343,17 @@ if (isset($conditionsarray) && $conditionsarray) {//ONLY DO THIS IF THERE ARE CO
{ {
$conditionrowdata["method"]='=='; $conditionrowdata["method"]='==';
} }
if (!isset($conditionrowdata["scenario"]) || trim($conditionrowdata["scenario"])=='')
{
$conditionrowdata["scenario"]=1;
}
$newvalues=array_values($conditionrowdata); $newvalues=array_values($conditionrowdata);
$newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly
$conditioninsert = "insert INTO {$dbprefix}conditions (".implode(',',array_keys($conditionrowdata)).") VALUES (".implode(',',$newvalues).")"; $conditioninsert = "insert INTO {$dbprefix}conditions (".implode(',',array_keys($conditionrowdata)).") VALUES (".implode(',',$newvalues).")";
$result=$connect->Execute($conditioninsert) or safe_die ("Couldn't insert condition<br />$conditioninsert<br />".$connect->ErrorMsg()); $result=$connect->Execute($conditioninsert) or safe_die ("Couldn't insert condition<br />$conditioninsert<br />".$connect->ErrorMsg());
} else { } else {
$importsurvey .= "<font size=1>Condition for $oldqid skipped ($oldcqid does not exist)</font><br />"; $importsurvey .= "<font size=1>".sprintf($clang->gT("Condition for %d skipped (%d does not exist)"),$oldqid,$oldcqid)."</font><br />";
if ($importingfrom != "http") echo "Condition for $oldqid skipped ($oldcqid does not exist)\n"; if ($importingfrom != "http") echo sprintf($clang->gT("Condition for %d skipped (%d does not exist)"),$oldqid,$oldcqid)."\n";
} }
unset($newcqid); unset($newcqid);
} }
@@ -1219,7 +1377,7 @@ if ($importingfrom == "http")
{ {
$importsurvey .= "\t<li>".$clang->gT("Languages").": $countlanguages</li>\n"; $importsurvey .= "\t<li>".$clang->gT("Languages").": $countlanguages</li>\n";
} }
$importsurvey .= "\t<li>".$clang->gT("Groups").": $countgroups</li>\n"; $importsurvey .= "\t<li>".$clang->gT("Question groups").": $countgroups</li>\n";
$importsurvey .= "\t<li>".$clang->gT("Questions").": $countquestions</li>\n"; $importsurvey .= "\t<li>".$clang->gT("Questions").": $countquestions</li>\n";
$importsurvey .= "\t<li>".$clang->gT("Answers").": $countanswers</li>\n"; $importsurvey .= "\t<li>".$clang->gT("Answers").": $countanswers</li>\n";
$importsurvey .= "\t<li>".$clang->gT("Conditions").": $countconditions</li>\n"; $importsurvey .= "\t<li>".$clang->gT("Conditions").": $countconditions</li>\n";
@@ -1230,11 +1388,12 @@ if ($importingfrom == "http")
} }
$importsurvey .= "\t<li>".$clang->gT("Question Attributes").": $countquestion_attributes</li>\n"; $importsurvey .= "\t<li>".$clang->gT("Question Attributes").": $countquestion_attributes</li>\n";
$importsurvey .= "\t<li>".$clang->gT("Assessments").": $countassessments</li>\n"; $importsurvey .= "\t<li>".$clang->gT("Assessments").": $countassessments</li>\n";
$importsurvey .= "\t<li>".$clang->gT("Quotas").": $countquota</li>\n</ul>\n"; $importsurvey .= "\t<li>".$clang->gT("Quotas").": $countquota ($countquotamembers ".$clang->gT("quota members")." ".$clang->gT("and")." $countquotals ".$clang->gT("quota language settings").")</li>\n</ul>\n";
$importsurvey .= "<strong>".$clang->gT("Import of Survey is completed.")."</strong><br />\n"; $importsurvey .= "<strong>".$clang->gT("Import of Survey is completed.")."</strong><br />\n"
if ($importwarning != "") $importsurvey .= "<br><strong>".$clang->gT("Warnings").":</strong><br><ul style=\"text-align:left;\">" . $importwarning . "</ul><br>\n"; . "<a href='$scriptname?sid=$newsid'>".$clang->gT("Go to survey")."</a><br />\n";
$importsurvey .= "</td></tr></table><br />\n"; if ($importwarning != "") $importsurvey .= "<br /><strong>".$clang->gT("Warnings").":</strong><br /><ul style=\"text-align:left;\">" . $importwarning . "</ul><br />\n";
$importsurvey .= "</td></tr></table><br /></table>\n";
unlink($the_full_file_path); unlink($the_full_file_path);
unset ($surveyid); // Crazy but necessary because else the html script will search for user rights unset ($surveyid); // Crazy but necessary because else the html script will search for user rights
} }
@@ -1262,4 +1421,3 @@ else
} }
?>

View File

@@ -0,0 +1,185 @@
<?php
/*
* LimeSurvey
* Copyright (C) 2007 The LimeSurvey Project Team / Nicolas Barcet
* All rights reserved.
* License: http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* LimeSurvey is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details.
*
* $Id: index.php 4729 2008-05-31 21:32:02Z nijaba $
*/
$cmd_install=true;
if (isset($argv[1]) && ($argv[1]=='install'|| $argv[1]=='upgrade') && isset($argv[2]) && isset($argv[3]))
{
require_once($argv[2]);
require_once($argv[3]);
}
else
{
require_once(dirname(__FILE__).'/../../config-defaults.php');
require_once(dirname(__FILE__).'/../../common.php');
}
// SET THE LANGUAGE???? -> 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 <option> < <<path1>> <<path2>> >\n");
print("<option> - 'install' or 'upgrade' \n");
print("<<path1>> - Full path including filename to a custom config-defaults.php\n");
print("<<path2>> - Full path including filename to a custom common.php\n");
print("Paths are optional. If used both paths must be set.\n");
return 2;
}
?>

View File

@@ -1,4 +1,4 @@
-- phpSurveyor MS SQL Server 2000 database schema -- LimeSurvey MS SQL Server 2000 database schema
-- -------------------------------------------------------- -- --------------------------------------------------------
@@ -9,11 +9,21 @@ CREATE TABLE [prefix_quota] (
[qlimit] int , [qlimit] int ,
[action] int , [action] int ,
[active] int NOT NULL default '1', [active] int NOT NULL default '1',
[autoload_url] int NOT NULL default '0',
PRIMARY KEY ([id]) PRIMARY KEY ([id])
); );
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])
);
CREATE TABLE [prefix_quota_members] ( CREATE TABLE [prefix_quota_members] (
@@ -21,7 +31,7 @@ CREATE TABLE [prefix_quota_members] (
[sid] int , [sid] int ,
[qid] int , [qid] int ,
[quota_id] int , [quota_id] int ,
[code] varchar(5) , [code] varchar(11) ,
PRIMARY KEY ([id]) PRIMARY KEY ([id])
); );
@@ -35,9 +45,10 @@ CREATE TABLE [prefix_quota_members] (
CREATE TABLE [prefix_answers] ( CREATE TABLE [prefix_answers] (
[qid] INT NOT NULL default '0', [qid] INT NOT NULL default '0',
[code] VARCHAR(5) NOT NULL default '', [code] VARCHAR(5) NOT NULL default '',
[answer] varchar(255) NOT NULL, [answer] varchar(8000) NOT NULL,
[default_value] char(1) NOT NULL default 'N', [default_value] char(1) NOT NULL default 'N',
[sortorder] INT NOT NULL, [sortorder] INT NOT NULL,
[assessment_value] INT NOT NULL default '0',
[language] VARCHAR(20) default 'en', [language] VARCHAR(20) default 'en',
PRIMARY KEY ([qid],[code],[language]) PRIMARY KEY ([qid],[code],[language])
) )
@@ -58,8 +69,8 @@ CREATE TABLE [prefix_assessments] (
[minimum] VARCHAR(50) NOT NULL default '', [minimum] VARCHAR(50) NOT NULL default '',
[maximum] VARCHAR(50) NOT NULL default '', [maximum] VARCHAR(50) NOT NULL default '',
[message] text NOT NULL, [message] text NOT NULL,
[link] text NOT NULL, [language] VARCHAR(20) NOT NULL default 'en',
PRIMARY KEY ([id]) PRIMARY KEY ([id],[language])
) )
; ;
@@ -72,6 +83,7 @@ CREATE TABLE [prefix_assessments] (
CREATE TABLE [prefix_conditions] ( CREATE TABLE [prefix_conditions] (
[cid] INT NOT NULL IDENTITY (1,1), [cid] INT NOT NULL IDENTITY (1,1),
[qid] INT NOT NULL default '0', [qid] INT NOT NULL default '0',
[scenario] INT NOT NULL default '1',
[cqid] INT NOT NULL default '0', [cqid] INT NOT NULL default '0',
[cfieldname] VARCHAR(50) NOT NULL default '', [cfieldname] VARCHAR(50) NOT NULL default '',
[method] char(2) NOT NULL default '', [method] char(2) NOT NULL default '',
@@ -107,6 +119,7 @@ CREATE TABLE [prefix_labels] (
[title] VARCHAR(4000), [title] VARCHAR(4000),
[sortorder] INT NOT NULL, [sortorder] INT NOT NULL,
[language] VARCHAR(20) default 'en', [language] VARCHAR(20) default 'en',
[assessment_value] INT NOT NULL default '0',
PRIMARY KEY ([lid],[sortorder],[language]), PRIMARY KEY ([lid],[sortorder],[language]),
) )
; ;
@@ -139,7 +152,7 @@ CREATE TABLE [prefix_question_attributes] (
[qaid] INT NOT NULL IDENTITY (1,1), [qaid] INT NOT NULL IDENTITY (1,1),
[qid] INT NOT NULL default '0', [qid] INT NOT NULL default '0',
[attribute] VARCHAR(50) default NULL, [attribute] VARCHAR(50) default NULL,
[value] VARCHAR(20) default NULL, [value] TEXT default NULL,
PRIMARY KEY ([qaid]) PRIMARY KEY ([qaid])
) )
; ;
@@ -203,35 +216,38 @@ CREATE TABLE [prefix_surveys] (
[owner_id] INT NOT NULL, [owner_id] INT NOT NULL,
[admin] VARCHAR(50) default NULL, [admin] VARCHAR(50) default NULL,
[active] char(1) NOT NULL default 'N', [active] char(1) NOT NULL default 'N',
[startdate] DATETIME default NULL,
[expires] DATETIME default NULL, [expires] DATETIME default NULL,
[adminemail] VARCHAR(320) default NULL, [adminemail] VARCHAR(320) default NULL,
[private] char(1) default NULL, [private] char(1) default NULL,
[faxto] VARCHAR(20) default NULL, [faxto] VARCHAR(20) default NULL,
[format] char(1) default NULL, [format] char(1) default NULL,
[template] VARCHAR(100) default 'default', [template] VARCHAR(100) default 'default',
[url] VARCHAR(255) default NULL,
[language] VARCHAR(50) default NULL, [language] VARCHAR(50) default NULL,
[additional_languages] VARCHAR(255) default NULL, [additional_languages] VARCHAR(255) default NULL,
[datestamp] char(1) default 'N', [datestamp] char(1) default 'N',
[usecookie] char(1) default 'N', [usecookie] char(1) default 'N',
[notification] char(1) default '0', [notification] char(1) default '0',
[allowregister] char(1) default 'N', [allowregister] char(1) default 'N',
[attribute1] VARCHAR(255) default NULL,
[attribute2] VARCHAR(255) default NULL,
[allowsave] char(1) default 'Y', [allowsave] char(1) default 'Y',
[autonumber_start] bigINT default '0', [autonumber_start] bigINT default '0',
[autoredirect] char(1) default 'N', [autoredirect] char(1) default 'N',
[allowprev] char(1) default 'Y', [allowprev] char(1) default 'Y',
[printanswers] char(1) default 'N', [printanswers] char(1) default 'N',
[ipaddr] char(1) default 'N', [ipaddr] char(1) default 'N',
[useexpiry] char(1) NOT NULL default 'N',
[refurl] char(1) default 'N', [refurl] char(1) default 'N',
[datecreated] DATETIME default NULL, [datecreated] DATETIME default NULL,
[listpublic] char(1) default 'N', [listpublic] char(1) default 'N',
[publicstatistics] char(1) default 'N',
[publicgraphs] char(1) default 'N',
[htmlemail] char(1) default 'N', [htmlemail] char(1) default 'N',
[tokenanswerspersistence] char(1) default 'N', [tokenanswerspersistence] char(1) default 'N',
[assessments] char(1) default 'N',
[usecaptcha] char(1) default 'N', [usecaptcha] char(1) default 'N',
[usetokens] char(1) default 'N',
[bounce_email] VARCHAR(320) default NULL, [bounce_email] VARCHAR(320) default NULL,
[attributedescriptions] text,
PRIMARY KEY ([sid]) PRIMARY KEY ([sid])
) )
; ;
@@ -249,6 +265,8 @@ CREATE TABLE [prefix_surveys_languagesettings] (
[surveyls_title] VARCHAR(200) NOT NULL, [surveyls_title] VARCHAR(200) NOT NULL,
[surveyls_description] TEXT NULL, [surveyls_description] TEXT NULL,
[surveyls_welcometext] TEXT NULL, [surveyls_welcometext] TEXT NULL,
[surveyls_endtext] TEXT NULL,
[surveyls_url] VARCHAR(255) NULL,
[surveyls_urldescription] VARCHAR(255) NULL, [surveyls_urldescription] VARCHAR(255) NULL,
[surveyls_email_invite_subj] VARCHAR(255) NULL, [surveyls_email_invite_subj] VARCHAR(255) NULL,
[surveyls_email_invite] TEXT NULL, [surveyls_email_invite] TEXT NULL,
@@ -258,6 +276,7 @@ CREATE TABLE [prefix_surveys_languagesettings] (
[surveyls_email_register] TEXT NULL, [surveyls_email_register] TEXT NULL,
[surveyls_email_confirm_subj] VARCHAR(255) NULL, [surveyls_email_confirm_subj] VARCHAR(255) NULL,
[surveyls_email_confirm] TEXT NULL, [surveyls_email_confirm] TEXT NULL,
[surveyls_dateformat] INT NOT NULL DEFAULT 1,
PRIMARY KEY ([surveyls_survey_id],[surveyls_language]) PRIMARY KEY ([surveyls_survey_id],[surveyls_language])
) )
; ;
@@ -269,7 +288,7 @@ CREATE TABLE [prefix_surveys_languagesettings] (
CREATE TABLE [prefix_users] ( CREATE TABLE [prefix_users] (
[uid] INT NOT NULL IDENTITY (1,1) PRIMARY KEY, [uid] INT NOT NULL IDENTITY (1,1) PRIMARY KEY,
[users_name] VARCHAR(64) NOT NULL UNIQUE default '', [users_name] VARCHAR(64) NOT NULL UNIQUE default '',
[password] TEXT NOT NULL default '', [password] varchar(8000) NOT NULL default '',
[full_name] VARCHAR(50) NOT NULL, [full_name] VARCHAR(50) NOT NULL,
[parent_id] INT NOT NULL, [parent_id] INT NOT NULL,
[lang] VARCHAR(20), [lang] VARCHAR(20),
@@ -281,9 +300,11 @@ CREATE TABLE [prefix_users] (
[configurator] TINYINT NOT NULL default '0', [configurator] TINYINT NOT NULL default '0',
[manage_template] TINYINT NOT NULL default '0', [manage_template] TINYINT NOT NULL default '0',
[manage_label] TINYINT NOT NULL default '0', [manage_label] TINYINT NOT NULL default '0',
[htmleditormode] char(7) default 'default' [htmleditormode] char(7) default 'default',
) [one_time_pw] TEXT,
; [dateformat] INT NOT NULL DEFAULT 1
);
-- --
-- Table structure for table [surveys_rights] -- Table structure for table [surveys_rights]
@@ -352,12 +373,30 @@ CREATE TABLE [prefix_templates] (
-- Table [settings_global] -- Table [settings_global]
-- --
INSERT INTO [prefix_settings_global] VALUES ('DBVersion', '126'); INSERT INTO [prefix_settings_global] VALUES ('DBVersion', '138');
INSERT INTO [prefix_settings_global] VALUES ('SessionName', '$sessionname'); INSERT INTO [prefix_settings_global] VALUES ('SessionName', '$sessionname');
-- --
-- Table [users] -- indexes
--
create index [answers_idx2] on [prefix_answers] ([sortorder]);
create index [assessments_idx2] on [prefix_assessments] ([sid]);
create index [assessments_idx3] on [prefix_assessments] ([gid]);
create index [conditions_idx2] on [prefix_conditions] ([qid]);
create index [conditions_idx3] on [prefix_conditions] ([cqid]);
create index [groups_idx2] on [prefix_groups] ([sid]);
create index [questions_idx2] on [prefix_questions] ([sid]);
create index [questions_idx3] on [prefix_questions] ([gid]);
create index [questions_idx4] on [prefix_questions] ([type]);
create index [question_attributes_idx2] on [prefix_question_attributes] ([qid]);
create index [quota_idx2] on [prefix_quota] ([sid]);
create index [saved_control_idx2] on [prefix_saved_control] ([sid]);
create index [user_in_groups_idx1] on [prefix_user_in_groups] ([ugid], [uid]);
--
-- Create the admin user
-- --
INSERT INTO [prefix_users] VALUES ('$defaultuser', '$defaultpass', '$siteadminname', 0, '$defaultlang', '$siteadminemail', 1,1,1,1,1,1,1,'default'); INSERT INTO [prefix_users] ([users_name], [password], [full_name], [parent_id], [lang] ,[email], [create_survey], [create_user] ,[delete_user] ,[superadmin] ,[configurator] ,[manage_template] , [manage_label]) VALUES ('$defaultuser', '$defaultpass', '$siteadminname', 0, '$defaultlang', '$siteadminemail', 1,1,1,1,1,1,1);

View File

@@ -1,17 +1,3 @@
-- phpMyAdmin SQL Dump
-- version 2.8.0.2
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Jul 23, 2006 at 07:56 PM
-- Server version: 5.0.20
-- PHP Version: 5.1.4
--
-- Database: `limesurvey-development`
--
-- --
-- Table structure for table `answers` -- Table structure for table `answers`
-- --
@@ -21,10 +7,11 @@ CREATE TABLE `prefix_answers` (
`code` varchar(5) NOT NULL default '', `code` varchar(5) NOT NULL default '',
`answer` text NOT NULL, `answer` text NOT NULL,
`default_value` char(1) NOT NULL default 'N', `default_value` char(1) NOT NULL default 'N',
`assessment_value` int(11) NOT NULL default '0',
`sortorder` int(11) NOT NULL, `sortorder` int(11) NOT NULL,
`language` varchar(20) default 'en', `language` varchar(20) default 'en',
PRIMARY KEY (`qid`,`code`,`language`) PRIMARY KEY (`qid`,`code`,`language`)
) TYPE=$databasetabletype CHARACTER SET utf8 COLLATE utf8_unicode_ci; ) ENGINE=$databasetabletype CHARACTER SET utf8 COLLATE utf8_unicode_ci;
-- -------------------------------------------------------- -- --------------------------------------------------------
@@ -41,9 +28,9 @@ CREATE TABLE `prefix_assessments` (
`minimum` varchar(50) NOT NULL default '', `minimum` varchar(50) NOT NULL default '',
`maximum` varchar(50) NOT NULL default '', `maximum` varchar(50) NOT NULL default '',
`message` text NOT NULL, `message` text NOT NULL,
`link` text NOT NULL, `language` varchar(20) NOT NULL default 'en',
PRIMARY KEY (`id`) PRIMARY KEY (`id`,`language`)
) TYPE=$databasetabletype AUTO_INCREMENT=1 CHARACTER SET utf8 COLLATE utf8_unicode_ci; ) ENGINE=$databasetabletype AUTO_INCREMENT=1 CHARACTER SET utf8 COLLATE utf8_unicode_ci;
-- -------------------------------------------------------- -- --------------------------------------------------------
@@ -54,12 +41,13 @@ CREATE TABLE `prefix_assessments` (
CREATE TABLE `prefix_conditions` ( CREATE TABLE `prefix_conditions` (
`cid` int(11) NOT NULL auto_increment, `cid` int(11) NOT NULL auto_increment,
`qid` int(11) NOT NULL default '0', `qid` int(11) NOT NULL default '0',
`scenario` int(11) NOT NULL default '1',
`cqid` int(11) NOT NULL default '0', `cqid` int(11) NOT NULL default '0',
`cfieldname` varchar(50) NOT NULL default '', `cfieldname` varchar(50) NOT NULL default '',
`method` char(2) NOT NULL default '', `method` char(2) NOT NULL default '',
`value` varchar(255) NOT NULL default '', `value` varchar(255) NOT NULL default '',
PRIMARY KEY (`cid`) PRIMARY KEY (`cid`)
) TYPE=$databasetabletype AUTO_INCREMENT=1 CHARACTER SET utf8 COLLATE utf8_unicode_ci; ) ENGINE=$databasetabletype AUTO_INCREMENT=1 CHARACTER SET utf8 COLLATE utf8_unicode_ci;
-- --
@@ -74,7 +62,7 @@ CREATE TABLE `prefix_groups` (
`description` text, `description` text,
`language` varchar(20) default 'en', `language` varchar(20) default 'en',
PRIMARY KEY (`gid`,`language`) PRIMARY KEY (`gid`,`language`)
) TYPE=$databasetabletype AUTO_INCREMENT=1 CHARACTER SET utf8 COLLATE utf8_unicode_ci; ) ENGINE=$databasetabletype AUTO_INCREMENT=1 CHARACTER SET utf8 COLLATE utf8_unicode_ci;
-- -------------------------------------------------------- -- --------------------------------------------------------
@@ -87,10 +75,11 @@ CREATE TABLE `prefix_labels` (
`code` varchar(5) NOT NULL default '', `code` varchar(5) NOT NULL default '',
`title` text, `title` text,
`sortorder` int(11) NOT NULL, `sortorder` int(11) NOT NULL,
`assessment_value` int(11) NOT NULL default '0',
`language` varchar(20) default 'en', `language` varchar(20) default 'en',
PRIMARY KEY (`lid`,`sortorder`,`language`), PRIMARY KEY (`lid`,`sortorder`,`language`),
KEY `ixcode` (`code`) KEY `ixcode` (`code`)
) TYPE=$databasetabletype CHARACTER SET utf8 COLLATE utf8_unicode_ci; ) ENGINE=$databasetabletype CHARACTER SET utf8 COLLATE utf8_unicode_ci;
-- -------------------------------------------------------- -- --------------------------------------------------------
@@ -103,7 +92,7 @@ CREATE TABLE `prefix_labelsets` (
`label_name` varchar(100) NOT NULL default '', `label_name` varchar(100) NOT NULL default '',
`languages` varchar(200) default 'en', `languages` varchar(200) default 'en',
PRIMARY KEY (`lid`) PRIMARY KEY (`lid`)
) TYPE=$databasetabletype AUTO_INCREMENT=1 CHARACTER SET utf8 COLLATE utf8_unicode_ci; ) ENGINE=$databasetabletype AUTO_INCREMENT=1 CHARACTER SET utf8 COLLATE utf8_unicode_ci;
-- -------------------------------------------------------- -- --------------------------------------------------------
@@ -115,9 +104,9 @@ CREATE TABLE `prefix_question_attributes` (
`qaid` int(11) NOT NULL auto_increment, `qaid` int(11) NOT NULL auto_increment,
`qid` int(11) NOT NULL default '0', `qid` int(11) NOT NULL default '0',
`attribute` varchar(50) default NULL, `attribute` varchar(50) default NULL,
`value` varchar(20) default NULL, `value` text default NULL,
PRIMARY KEY (`qaid`) PRIMARY KEY (`qaid`)
) TYPE=$databasetabletype AUTO_INCREMENT=1 CHARACTER SET utf8 COLLATE utf8_unicode_ci; ) ENGINE=$databasetabletype AUTO_INCREMENT=1 CHARACTER SET utf8 COLLATE utf8_unicode_ci;
-- -------------------------------------------------------- -- --------------------------------------------------------
@@ -129,10 +118,25 @@ CREATE TABLE `prefix_quota` (
`qlimit` int(8) default NULL, `qlimit` int(8) default NULL,
`action` int(2) default NULL, `action` int(2) default NULL,
`active` int(1) NOT NULL default '1', `active` int(1) NOT NULL default '1',
`autoload_url` int(1) NOT NULL default '0',
PRIMARY KEY (`id`) PRIMARY KEY (`id`)
) TYPE=$databasetabletype CHARACTER SET utf8 COLLATE utf8_unicode_ci; ) ENGINE=$databasetabletype CHARACTER SET utf8 COLLATE utf8_unicode_ci;
--
-- Table Structure for table quota_languagesettings
--
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;
@@ -141,10 +145,10 @@ CREATE TABLE `prefix_quota_members` (
`sid` int(11) default NULL, `sid` int(11) default NULL,
`qid` int(11) default NULL, `qid` int(11) default NULL,
`quota_id` int(11) default NULL, `quota_id` int(11) default NULL,
`code` varchar(5) collate utf8_unicode_ci default NULL, `code` varchar(11) collate utf8_unicode_ci default NULL,
PRIMARY KEY (`id`), PRIMARY KEY (`id`),
UNIQUE KEY `sid` (`sid`,`qid`,`quota_id`,`code`) UNIQUE KEY `sid` (`sid`,`qid`,`quota_id`,`code`)
) TYPE=$databasetabletype CHARACTER SET utf8 COLLATE utf8_unicode_ci; ) ENGINE=$databasetabletype CHARACTER SET utf8 COLLATE utf8_unicode_ci;
-- --
@@ -167,7 +171,7 @@ CREATE TABLE `prefix_questions` (
`question_order` int(11) NOT NULL, `question_order` int(11) NOT NULL,
`language` varchar(20) default 'en', `language` varchar(20) default 'en',
PRIMARY KEY (`qid`,`language`) PRIMARY KEY (`qid`,`language`)
) TYPE=$databasetabletype AUTO_INCREMENT=1 CHARACTER SET utf8 COLLATE utf8_unicode_ci; ) ENGINE=$databasetabletype AUTO_INCREMENT=1 CHARACTER SET utf8 COLLATE utf8_unicode_ci;
-- -------------------------------------------------------- -- --------------------------------------------------------
@@ -189,7 +193,7 @@ CREATE TABLE `prefix_saved_control` (
`saved_date` datetime NOT NULL, `saved_date` datetime NOT NULL,
`refurl` text, `refurl` text,
PRIMARY KEY (`scid`) PRIMARY KEY (`scid`)
) TYPE=$databasetabletype AUTO_INCREMENT=1 CHARACTER SET utf8 COLLATE utf8_unicode_ci; ) ENGINE=$databasetabletype AUTO_INCREMENT=1 CHARACTER SET utf8 COLLATE utf8_unicode_ci;
-- -------------------------------------------------------- -- --------------------------------------------------------
@@ -201,7 +205,7 @@ CREATE TABLE `prefix_settings_global` (
`stg_name` varchar(50) NOT NULL default '', `stg_name` varchar(50) NOT NULL default '',
`stg_value` varchar(255) NOT NULL default '', `stg_value` varchar(255) NOT NULL default '',
PRIMARY KEY (`stg_name`) PRIMARY KEY (`stg_name`)
) TYPE=$databasetabletype CHARACTER SET utf8 COLLATE utf8_unicode_ci; ) ENGINE=$databasetabletype CHARACTER SET utf8 COLLATE utf8_unicode_ci;
-- --
@@ -214,36 +218,38 @@ CREATE TABLE `prefix_surveys` (
`admin` varchar(50) default NULL, `admin` varchar(50) default NULL,
`active` char(1) NOT NULL default 'N', `active` char(1) NOT NULL default 'N',
`expires` date default NULL, `expires` date default NULL,
`startdate` date default NULL,
`adminemail` varchar(320) default NULL, `adminemail` varchar(320) default NULL,
`private` char(1) default NULL, `private` char(1) default NULL,
`faxto` varchar(20) default NULL, `faxto` varchar(20) default NULL,
`format` char(1) default NULL, `format` char(1) default NULL,
`template` varchar(100) default 'default', `template` varchar(100) default 'default',
`url` varchar(255) default NULL,
`language` varchar(50) default NULL, `language` varchar(50) default NULL,
`additional_languages` varchar(255) default NULL, `additional_languages` varchar(255) default NULL,
`datestamp` char(1) default 'N', `datestamp` char(1) default 'N',
`usecookie` char(1) default 'N', `usecookie` char(1) default 'N',
`notification` char(1) default '0', `notification` char(1) default '0',
`allowregister` char(1) default 'N', `allowregister` char(1) default 'N',
`attribute1` varchar(255) default NULL,
`attribute2` varchar(255) default NULL,
`allowsave` char(1) default 'Y', `allowsave` char(1) default 'Y',
`autonumber_start` bigint(11) default '0', `autonumber_start` bigint(11) default '0',
`autoredirect` char(1) default 'N', `autoredirect` char(1) default 'N',
`allowprev` char(1) default 'Y', `allowprev` char(1) default 'Y',
`printanswers` char(1) default 'N', `printanswers` char(1) default 'N',
`ipaddr` char(1) default 'N', `ipaddr` char(1) default 'N',
`useexpiry` char(1) NOT NULL default 'N',
`refurl` char(1) default 'N', `refurl` char(1) default 'N',
`datecreated` date default NULL, `datecreated` date default NULL,
`publicstatistics` char(1) default 'N',
`publicgraphs` char(1) default 'N',
`listpublic` char(1) default 'N', `listpublic` char(1) default 'N',
`htmlemail` char(1) default 'N', `htmlemail` char(1) default 'N',
`tokenanswerspersistence` char(1) default 'N', `tokenanswerspersistence` char(1) default 'N',
`assessments` char(1) default 'N',
`usecaptcha` char(1) default 'N', `usecaptcha` char(1) default 'N',
`usetokens` char(1) default 'N',
`bounce_email` varchar(320) default NULL, `bounce_email` varchar(320) default NULL,
`attributedescriptions` text,
PRIMARY KEY (`sid`) PRIMARY KEY (`sid`)
) TYPE=$databasetabletype CHARACTER SET utf8 COLLATE utf8_unicode_ci; ) ENGINE=$databasetabletype CHARACTER SET utf8 COLLATE utf8_unicode_ci;
-- --
@@ -258,6 +264,8 @@ CREATE TABLE `prefix_surveys_languagesettings` (
`surveyls_title` VARCHAR(200) NOT NULL, `surveyls_title` VARCHAR(200) NOT NULL,
`surveyls_description` TEXT NULL, `surveyls_description` TEXT NULL,
`surveyls_welcometext` TEXT NULL, `surveyls_welcometext` TEXT NULL,
`surveyls_endtext` TEXT NULL,
`surveyls_url` VARCHAR(255) NULL,
`surveyls_urldescription` VARCHAR(255) NULL, `surveyls_urldescription` VARCHAR(255) NULL,
`surveyls_email_invite_subj` VARCHAR(255) NULL, `surveyls_email_invite_subj` VARCHAR(255) NULL,
`surveyls_email_invite` TEXT NULL, `surveyls_email_invite` TEXT NULL,
@@ -267,6 +275,8 @@ CREATE TABLE `prefix_surveys_languagesettings` (
`surveyls_email_register` TEXT NULL, `surveyls_email_register` TEXT NULL,
`surveyls_email_confirm_subj` VARCHAR(255) NULL, `surveyls_email_confirm_subj` VARCHAR(255) NULL,
`surveyls_email_confirm` TEXT NULL, `surveyls_email_confirm` TEXT NULL,
`surveyls_dateformat` INT UNSIGNED NOT NULL DEFAULT 1,
PRIMARY KEY (`surveyls_survey_id`, `surveyls_language`) PRIMARY KEY (`surveyls_survey_id`, `surveyls_language`)
) )
TYPE = $databasetabletype CHARACTER SET utf8 COLLATE utf8_unicode_ci; TYPE = $databasetabletype CHARACTER SET utf8 COLLATE utf8_unicode_ci;
@@ -286,7 +296,7 @@ CREATE TABLE `prefix_surveys_rights` (
`delete_survey` tinyint(1) NOT NULL default '0', `delete_survey` tinyint(1) NOT NULL default '0',
`activate_survey` tinyint(1) NOT NULL default '0', `activate_survey` tinyint(1) NOT NULL default '0',
PRIMARY KEY (sid, uid) PRIMARY KEY (sid, uid)
) TYPE=$databasetabletype CHARACTER SET utf8 COLLATE utf8_unicode_ci; ) ENGINE=$databasetabletype CHARACTER SET utf8 COLLATE utf8_unicode_ci;
@@ -295,14 +305,14 @@ CREATE TABLE `prefix_user_groups` (
`name` varchar(20) NOT NULL UNIQUE, `name` varchar(20) NOT NULL UNIQUE,
`description` TEXT NOT NULL, `description` TEXT NOT NULL,
`owner_id` int(10) unsigned NOT NULL `owner_id` int(10) unsigned NOT NULL
) TYPE=$databasetabletype CHARACTER SET utf8 COLLATE utf8_unicode_ci; ) ENGINE=$databasetabletype CHARACTER SET utf8 COLLATE utf8_unicode_ci;
CREATE TABLE `prefix_user_in_groups` ( CREATE TABLE `prefix_user_in_groups` (
`ugid` int(10) unsigned NOT NULL, `ugid` int(10) unsigned NOT NULL,
`uid` int(10) unsigned NOT NULL `uid` int(10) unsigned NOT NULL
) TYPE=$databasetabletype CHARACTER SET utf8 COLLATE utf8_unicode_ci; ) ENGINE=$databasetabletype CHARACTER SET utf8 COLLATE utf8_unicode_ci;
-- --
-- Table structure for table `users` -- Table structure for table `users`
@@ -323,8 +333,11 @@ CREATE TABLE `prefix_users` (
`configurator` tinyint(1) NOT NULL default '0', `configurator` tinyint(1) NOT NULL default '0',
`manage_template` tinyint(1) NOT NULL default '0', `manage_template` tinyint(1) NOT NULL default '0',
`manage_label` tinyint(1) NOT NULL default '0', `manage_label` tinyint(1) NOT NULL default '0',
`htmleditormode` varchar(7) default 'default' `htmleditormode` varchar(7) default 'default',
) TYPE=$databasetabletype CHARACTER SET utf8 COLLATE utf8_unicode_ci; `one_time_pw` BLOB,
`dateformat` INT UNSIGNED NOT NULL DEFAULT 1
) ENGINE=$databasetabletype CHARACTER SET utf8 COLLATE utf8_unicode_ci;
@@ -334,25 +347,44 @@ CREATE TABLE `prefix_templates_rights` (
`folder` varchar(255) NOT NULL, `folder` varchar(255) NOT NULL,
`use` int(1) NOT NULL, `use` int(1) NOT NULL,
PRIMARY KEY (`uid`,`folder`) PRIMARY KEY (`uid`,`folder`)
) TYPE=$databasetabletype CHARACTER SET utf8 COLLATE utf8_unicode_ci; ) ENGINE=$databasetabletype CHARACTER SET utf8 COLLATE utf8_unicode_ci;
CREATE TABLE `prefix_templates` ( CREATE TABLE `prefix_templates` (
`folder` varchar(255) NOT NULL, `folder` varchar(255) NOT NULL,
`creator` int(11) NOT NULL, `creator` int(11) NOT NULL,
PRIMARY KEY (`folder`) PRIMARY KEY (`folder`)
) TYPE=$databasetabletype CHARACTER SET utf8 COLLATE utf8_unicode_ci; ) ENGINE=$databasetabletype CHARACTER SET utf8 COLLATE utf8_unicode_ci;
-- --
-- Table `settings_global` -- Table `settings_global`
-- --
INSERT INTO `prefix_settings_global` VALUES ('DBVersion', '126'); INSERT INTO `prefix_settings_global` VALUES ('DBVersion', '138');
INSERT INTO `prefix_settings_global` VALUES ('SessionName', '$sessionname'); INSERT INTO `prefix_settings_global` VALUES ('SessionName', '$sessionname');
-- --
-- Table `users` -- Table `users`
-- --
INSERT INTO `prefix_users` VALUES (NULL, '$defaultuser', '$defaultpass', '$siteadminname', 0, '$defaultlang', '$siteadminemail', 1,1,1,1,1,1,1,'default'); INSERT INTO `prefix_users` (`users_name`, `password`, `full_name`, `parent_id`, `lang` ,`email`, `create_survey`,`create_user` ,`delete_user` ,`superadmin` ,`configurator` ,`manage_template` , `manage_label`) VALUES ('$defaultuser', '$defaultpass', '$siteadminname', 0, '$defaultlang', '$siteadminemail', 1,1,1,1,1,1,1);
--
-- indexes
--
create index `answers_idx2` on `prefix_answers` (`sortorder`);
create index `assessments_idx2` on `prefix_assessments` (`sid`);
create index `assessments_idx3` on `prefix_assessments` (`gid`);
create index `conditions_idx2` on `prefix_conditions` (`qid`);
create index `conditions_idx3` on `prefix_conditions` (`cqid`);
create index `groups_idx2` on `prefix_groups` (`sid`);
create index `question_attributes_idx2` on `prefix_question_attributes` (`qid`);
create index `questions_idx2` on `prefix_questions` (`sid`);
create index `questions_idx3` on `prefix_questions` (`gid`);
create index `questions_idx4` on `prefix_questions` (`type`);
create index `quota_idx2` on `prefix_quota` (`sid`);
create index `saved_control_idx2` on `prefix_saved_control` (`sid`);
create index `user_in_groups_idx1` on `prefix_user_in_groups` (`ugid`, `uid`);

View File

@@ -22,6 +22,7 @@ CREATE TABLE prefix_answers (
answer text NOT NULL, answer text NOT NULL,
default_value character(1) DEFAULT 'N'::bpchar NOT NULL, default_value character(1) DEFAULT 'N'::bpchar NOT NULL,
sortorder integer NOT NULL, sortorder integer NOT NULL,
assessment_value integer DEFAULT 0 NOT NULL,
"language" character varying(20) DEFAULT 'en'::character varying NOT NULL "language" character varying(20) DEFAULT 'en'::character varying NOT NULL
); );
@@ -41,7 +42,7 @@ CREATE TABLE prefix_assessments (
minimum character varying(50) DEFAULT ''::character varying NOT NULL, minimum character varying(50) DEFAULT ''::character varying NOT NULL,
maximum character varying(50) DEFAULT ''::character varying NOT NULL, maximum character varying(50) DEFAULT ''::character varying NOT NULL,
message text NOT NULL, message text NOT NULL,
link text NOT NULL language character(20) DEFAULT 'en'::bpchar NOT NULL
); );
@@ -54,6 +55,7 @@ CREATE TABLE prefix_assessments (
CREATE TABLE prefix_conditions ( CREATE TABLE prefix_conditions (
cid serial, cid serial,
qid integer DEFAULT 0 NOT NULL, qid integer DEFAULT 0 NOT NULL,
scenario integer DEFAULT 1 NOT NULL,
cqid integer DEFAULT 0 NOT NULL, cqid integer DEFAULT 0 NOT NULL,
cfieldname character varying(50) DEFAULT ''::character varying NOT NULL, cfieldname character varying(50) DEFAULT ''::character varying NOT NULL,
method character(2) DEFAULT ''::bpchar NOT NULL, method character(2) DEFAULT ''::bpchar NOT NULL,
@@ -87,6 +89,7 @@ CREATE TABLE prefix_labels (
code character varying(5) DEFAULT ''::character varying NOT NULL, code character varying(5) DEFAULT ''::character varying NOT NULL,
title text, title text,
sortorder integer NOT NULL, sortorder integer NOT NULL,
assessment_value integer DEFAULT 0 NOT NULL,
"language" character varying(20) DEFAULT 'en'::character varying NOT NULL "language" character varying(20) DEFAULT 'en'::character varying NOT NULL
); );
@@ -115,7 +118,7 @@ CREATE TABLE prefix_question_attributes (
qaid serial NOT NULL, qaid serial NOT NULL,
qid integer DEFAULT 0 NOT NULL, qid integer DEFAULT 0 NOT NULL,
attribute character varying(50), attribute character varying(50),
value character varying(20) value text NULL
); );
-- --
@@ -128,20 +131,33 @@ CREATE TABLE prefix_quota (
name character varying(255), name character varying(255),
qlimit integer, qlimit integer,
"action" integer, "action" integer,
"active" integer NOT NULL default '1' "active" integer NOT NULL default '1',
autoload_url integer NOT NULL DEFAULT 0
); );
ALTER TABLE ONLY prefix_quota ALTER TABLE ONLY prefix_quota
ADD CONSTRAINT prefix_quota_pkey PRIMARY KEY (id); ADD CONSTRAINT prefix_quota_pkey PRIMARY KEY (id);
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)
);
ALTER TABLE ONLY prefix_quota_languagesettings
ADD CONSTRAINT prefix_quota_languagesettings_pkey PRIMARY KEY (quotals_id);
CREATE TABLE prefix_quota_members ( CREATE TABLE prefix_quota_members (
id serial, id serial,
sid integer, sid integer,
qid integer, qid integer,
quota_id integer, quota_id integer,
code character varying(5) code character varying(11)
); );
ALTER TABLE ONLY prefix_quota_members ALTER TABLE ONLY prefix_quota_members
@@ -213,36 +229,37 @@ CREATE TABLE prefix_surveys (
owner_id integer NOT NULL, owner_id integer NOT NULL,
"admin" character varying(50), "admin" character varying(50),
active character(1) DEFAULT 'N'::bpchar NOT NULL, active character(1) DEFAULT 'N'::bpchar NOT NULL,
startdate date,
expires date, expires date,
adminemail character varying(320) NOT NULL, adminemail character varying(320) NOT NULL,
private character(1), private character(1),
faxto character varying(20), faxto character varying(20),
format character(1), format character(1),
"template" character varying(100) DEFAULT 'default'::character varying, "template" character varying(100) DEFAULT 'default'::character varying,
url character varying(255),
"language" character varying(50), "language" character varying(50),
additional_languages character varying(255), additional_languages character varying(255),
datestamp character(1) DEFAULT 'N'::bpchar, datestamp character(1) DEFAULT 'N'::bpchar,
usecookie character(1) DEFAULT 'N'::bpchar, usecookie character(1) DEFAULT 'N'::bpchar,
notification character(1) DEFAULT '0'::bpchar, notification character(1) DEFAULT '0'::bpchar,
allowregister character(1) DEFAULT 'N'::bpchar, allowregister character(1) DEFAULT 'N'::bpchar,
attribute1 character varying(255),
attribute2 character varying(255),
allowsave character(1) DEFAULT 'Y'::bpchar, allowsave character(1) DEFAULT 'Y'::bpchar,
printanswers character(1) DEFAULT 'N'::bpchar, printanswers character(1) DEFAULT 'N'::bpchar,
autonumber_start integer DEFAULT 0, autonumber_start integer DEFAULT 0,
autoredirect character(1) DEFAULT 'N'::bpchar, autoredirect character(1) DEFAULT 'N'::bpchar,
allowprev character(1) DEFAULT 'Y'::bpchar, allowprev character(1) DEFAULT 'Y'::bpchar,
ipaddr character(1) DEFAULT 'N'::bpchar, ipaddr character(1) DEFAULT 'N'::bpchar,
useexpiry character(1) DEFAULT 'N'::bpchar NOT NULL,
refurl character(1) DEFAULT 'N'::bpchar, refurl character(1) DEFAULT 'N'::bpchar,
datecreated date, datecreated date,
listpublic character(1) DEFAULT 'N'::bpchar, listpublic character(1) DEFAULT 'N'::bpchar,
publicstatistics character(1) DEFAULT 'N'::bpchar,
publicgraphs character(1) DEFAULT 'N'::bpchar,
htmlemail character(1) DEFAULT 'N'::bpchar, htmlemail character(1) DEFAULT 'N'::bpchar,
tokenanswerspersistence character(1) DEFAULT 'N'::bpchar, tokenanswerspersistence character(1) DEFAULT 'N'::bpchar,
assessments character(1) DEFAULT 'N'::bpchar,
usecaptcha character(1) DEFAULT 'N'::bpchar, usecaptcha character(1) DEFAULT 'N'::bpchar,
"bounce_email" character varying(320) NOT NULL usetokens character(1) DEFAULT 'N'::bpchar,
"bounce_email" character varying(320) NOT NULL,
attributedescriptions text
); );
@@ -258,7 +275,9 @@ CREATE TABLE prefix_surveys_languagesettings (
surveyls_title character varying(200) NOT NULL, surveyls_title character varying(200) NOT NULL,
surveyls_description text, surveyls_description text,
surveyls_welcometext text, surveyls_welcometext text,
surveyls_url character varying(255),
surveyls_urldescription character varying(255), surveyls_urldescription character varying(255),
surveyls_endtext text,
surveyls_email_invite_subj character varying(255), surveyls_email_invite_subj character varying(255),
surveyls_email_invite text, surveyls_email_invite text,
surveyls_email_remind_subj character varying(255), surveyls_email_remind_subj character varying(255),
@@ -266,7 +285,8 @@ CREATE TABLE prefix_surveys_languagesettings (
surveyls_email_register_subj character varying(255), surveyls_email_register_subj character varying(255),
surveyls_email_register text, surveyls_email_register text,
surveyls_email_confirm_subj character varying(255), surveyls_email_confirm_subj character varying(255),
surveyls_email_confirm text surveyls_email_confirm text,
surveyls_dateformat integer DEFAULT 1 NOT NULL
); );
@@ -310,8 +330,8 @@ CREATE TABLE prefix_user_in_groups (
-- --
CREATE TABLE prefix_users ( CREATE TABLE prefix_users (
uid serial NOT NULL, uid serial PRIMARY KEY NOT NULL,
users_name character varying(64) DEFAULT ''::character varying NOT NULL, users_name character varying(64) DEFAULT ''::character varying UNIQUE NOT NULL,
"password" bytea NOT NULL, "password" bytea NOT NULL,
full_name character varying(50) NOT NULL, full_name character varying(50) NOT NULL,
parent_id integer NOT NULL, parent_id integer NOT NULL,
@@ -324,10 +344,11 @@ CREATE TABLE prefix_users (
configurator integer DEFAULT 0 NOT NULL, configurator integer DEFAULT 0 NOT NULL,
manage_template integer DEFAULT 0 NOT NULL, manage_template integer DEFAULT 0 NOT NULL,
manage_label integer DEFAULT 0 NOT NULL, manage_label integer DEFAULT 0 NOT NULL,
htmleditormode character(7) DEFAULT 'default'::bpchar htmleditormode character(7) DEFAULT 'default'::bpchar,
one_time_pw bytea,
"dateformat" integer DEFAULT 1 NOT NULL
); );
CREATE TABLE prefix_templates_rights ( CREATE TABLE prefix_templates_rights (
"uid" integer NOT NULL, "uid" integer NOT NULL,
"folder" character varying(255) NOT NULL, "folder" character varying(255) NOT NULL,
@@ -364,7 +385,7 @@ ALTER TABLE ONLY prefix_answers
-- --
ALTER TABLE ONLY prefix_assessments ALTER TABLE ONLY prefix_assessments
ADD CONSTRAINT prefix_assessments_pkey PRIMARY KEY (id); ADD CONSTRAINT prefix_assessments_pkey PRIMARY KEY (id,language);
-- --
@@ -489,11 +510,29 @@ CREATE INDEX prefix_labels_ixcode_idx ON prefix_labels USING btree (code);
-- Table `settings_global` -- Table `settings_global`
-- --
INSERT INTO prefix_settings_global VALUES ('DBVersion', '126'); INSERT INTO prefix_settings_global VALUES ('DBVersion', '138');
INSERT INTO prefix_settings_global VALUES ('SessionName', '$sessionname'); INSERT INTO prefix_settings_global VALUES ('SessionName', '$sessionname');
-- --
-- Table `users` -- indexes
--
create index assessments_idx2 on prefix_assessments (sid);
create index assessments_idx3 on prefix_assessments (gid);
create index conditions_idx2 on prefix_conditions (qid);
create index groups_idx2 on prefix_groups (sid);
create index question_attributes_idx2 on prefix_question_attributes (qid);
create index questions_idx2 on prefix_questions (sid);
create index questions_idx3 on prefix_questions (gid);
create index quota_idx2 on prefix_quota (sid);
create index saved_control_idx2 on prefix_saved_control (sid);
create index user_in_groups_idx1 on prefix_user_in_groups (ugid, uid);
--
-- Create admin user
-- --
INSERT INTO prefix_users( INSERT INTO prefix_users(
@@ -502,3 +541,7 @@ INSERT INTO prefix_users(
manage_template, manage_label,htmleditormode) manage_template, manage_label,htmleditormode)
VALUES ('$defaultuser', '$defaultpass', '$siteadminname', 0, '$defaultlang', '$siteadminemail',1,1,1,1,1,1,1,'default'); VALUES ('$defaultuser', '$defaultpass', '$siteadminname', 0, '$defaultlang', '$siteadminemail',1,1,1,1,1,1,1,'default');

View File

@@ -10,7 +10,7 @@
* other free or open source software licenses. * other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details. * See COPYRIGHT.php for copyright notices and details.
* *
* $Id: createdb.php 4333 2008-02-25 13:19:12Z c_schmitz $ * $Id: createdb.php 7053 2009-06-10 10:43:43Z c_schmitz $
*/ */
//Ensure script is not run directly, avoid path disclosure //Ensure script is not run directly, avoid path disclosure
@@ -32,8 +32,13 @@ echo "\t<tr bgcolor='#CCCCCC'><td align='center'>$setfont\n";
// In Step2 fill the database with data // In Step2 fill the database with data
if (returnglobal('createdbstep2')==$clang->gT("Populate Database")) if (returnglobal('createdbstep2')==$clang->gT("Populate Database"))
{ {
if ($databasetype=='mysql') {@$connect->Execute("ALTER DATABASE `$dbname` DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;");} //Set the collation also for manually created DBs $createdbtype=$databasetype;
if (modify_database(dirname(__FILE__).'/create-'.$databasetype.'.sql')) if ($databasetype=='mysql' || $databasetype=='mysqli') {
@$connect->Execute("ALTER DATABASE `$dbname` DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;");
$createdbtype='mysql';
}
if ($createdbtype=='mssql_n' || $createdbtype=='odbc_mssql' || $createdbtype=='odbtp') $createdbtype='mssql';
if (modify_database(dirname(__FILE__).'/create-'.$createdbtype.'.sql'))
{ {
echo sprintf($clang->gT("Database `%s` has been successfully populated."),$dbname)."</font></strong></font><br /><br />\n"; echo sprintf($clang->gT("Database `%s` has been successfully populated."),$dbname)."</font></strong></font><br /><br />\n";
echo "<input type='submit' value='".$clang->gT("Main Admin Screen")."' onclick='location.href=\"../$scriptname\"'>"; echo "<input type='submit' value='".$clang->gT("Main Admin Screen")."' onclick='location.href=\"../$scriptname\"'>";
@@ -62,10 +67,12 @@ if (!$database_exists) //Database named in config-defaults.php does not exist
// TODO SQL: Portable to other databases?? // TODO SQL: Portable to other databases??
switch ($databasetype) switch ($databasetype)
{ {
case 'mysqli':
case 'mysql': $createDb=$connect->Execute("CREATE DATABASE `$dbname` DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci"); case 'mysql': $createDb=$connect->Execute("CREATE DATABASE `$dbname` DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci");
break; break;
case 'mssql_n':
case 'odbc_mssql': case 'odbc_mssql':
case 'mssql': $createDb=$connect->Execute("CREATE DATABASE [$dbname];"); case 'odbtp': $createDb=$connect->Execute("CREATE DATABASE [$dbname];");
break; break;
default: $createDb=$connect->Execute("CREATE DATABASE $dbname"); default: $createDb=$connect->Execute("CREATE DATABASE $dbname");
} }

View File

@@ -1,34 +0,0 @@
<?php
/*
* LimeSurvey
* Copyright (C) 2007 The LimeSurvey Project Team / Nicolas Barcet
* All rights reserved.
* License: http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* LimeSurvey is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details.
*
* $Id: index.php 4729 2008-05-31 21:32:02Z nijaba $
*/
require_once(dirname(__FILE__).'/../../config-defaults.php');
require_once(dirname(__FILE__).'/../../common.php');
// SET THE LANGUAGE???? -> 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;
}
?>

View File

@@ -1,41 +0,0 @@
<?php
/*
* LimeSurvey
* Copyright (C) 2007 The LimeSurvey Project Team / Nicolas Barcet
* All rights reserved.
* License: http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* LimeSurvey is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details.
*
* $Id: index.php 4729 2008-05-31 21:32:02Z nijaba $
*/
require_once(dirname(__FILE__).'/../../config-defaults.php');
require_once(dirname(__FILE__).'/../../common.php');
// SET THE LANGUAGE???? -> 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;
?>

View File

@@ -10,7 +10,7 @@
* other free or open source software licenses. * other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details. * 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->database = $databasename;
$connect->Execute("USE DATABASE `$databasename`"); $connect->Execute("USE DATABASE `$databasename`");
$output=checkforupgrades(); $output=checkforupgrades();
if (!isset($ouput)) {$adminoutput.='<br />LimeSurvey Database is up to date. No action needed';} if ($output== '') {$adminoutput.='<br />LimeSurvey Database is up to date. No action needed';}
else {$adminoutput.=$output;} else {$adminoutput.=$output;}
$adminoutput.="<br />Please <a href='$homeurl/$scriptname'>log in.</a>"; $adminoutput.="<br />Please <a href='$homeurl/$scriptname'>log in.</a>";
@@ -73,7 +73,10 @@ function checkforupgrades()
{ {
global $connect, $databasetype, $dbprefix, $dbversionnumber, $clang; global $connect, $databasetype, $dbprefix, $dbversionnumber, $clang;
$adminoutput=''; $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(); $tables = $connect->MetaTables();
$usquery = "SELECT stg_value FROM ".db_table_name("settings_global")." where stg_name='DBVersion'"; $usquery = "SELECT stg_value FROM ".db_table_name("settings_global")." where stg_name='DBVersion'";

View File

@@ -22,14 +22,17 @@ sendcacheheaders();
switch ($databasetype) switch ($databasetype)
{ {
case 'mysql': modify_database("",'UPDATE `prefix_users` set password=\'$defaultpass\' where uid=1;'); case 'mysqli':
echo $modifyoutput; flush(); case 'mysql' : modify_database("",'UPDATE `prefix_users` set password=\'$defaultpass\' where uid=1;');
break; echo $modifyoutput; flush();
case 'odbc_mssql':modify_database("",'UPDATE [prefix_users] set password=\'$defaultpass\' where uid=1;'); break;
echo $modifyoutput; flush(); case 'odbtp':
break; case 'mssql_n':
case 'postgres':modify_database("",'UPDATE prefix_users set \"password\"=\'$defaultpass\' where uid=1;'); case 'odbc_mssql':modify_database("",'UPDATE [prefix_users] set password=\'$defaultpass\' where uid=1;');
echo $modifyoutput; flush(); echo $modifyoutput; flush();
break; break;
case 'postgres':modify_database("",'UPDATE prefix_users set \"password\"=\'$defaultpass\' where uid=1;');
echo $modifyoutput; flush();
break;
} }
?> ?>

View File

@@ -0,0 +1,445 @@
<?PHP
/*
* LimeSurvey
* Copyright (C) 2007 The LimeSurvey Project Team / Carsten Schmitz
* All rights reserved.
* License: http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* LimeSurvey is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details.
*
* $Id: upgrade-mssql.php 7122 2009-06-16 13:42:29Z c_schmitz $
*/
// There will be a file for each database (accordingly named to the dbADO scheme)
// where based on the current database version the database is upgraded
// For this there will be a settings table which holds the last time the database was upgraded
function db_upgrade($oldversion) {
/// This function does anything necessary to upgrade
/// older versions to match current functionality
global $modifyoutput, $dbprefix;
echo str_pad('Loading... ',4096)."<br />\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) +'<br /><a href=\"'+[link]+'\">'+[link]+'</a>'"); 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();
}
}
?>

View File

@@ -10,7 +10,7 @@
* other free or open source software licenses. * other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details. * 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) // There will be a file for each database (accordingly named to the dbADO scheme)
@@ -115,12 +115,12 @@ echo str_pad('Loading... ',4096)."<br />\n";
modify_database("","CREATE TABLE `prefix_quota` ( modify_database("","CREATE TABLE `prefix_quota` (
`id` int(11) NOT NULL auto_increment, `id` int(11) NOT NULL auto_increment,
`sid` int(11) default NULL, `sid` int(11) default NULL,
`name` varchar(255) collate utf8_unicode_ci default NULL,
`qlimit` int(8) default NULL, `qlimit` int(8) default NULL,
`name` varchar(255) collate utf8_unicode_ci default NULL,
`action` int(2) default NULL, `action` int(2) default NULL,
`active` int(1) NOT NULL default '1', `active` int(1) NOT NULL default '1',
PRIMARY KEY (`id`) 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` ( modify_database("","CREATE TABLE `prefix_quota_members` (
`id` int(11) NOT NULL auto_increment, `id` int(11) NOT NULL auto_increment,
`sid` int(11) default NULL, `sid` int(11) default NULL,
@@ -129,7 +129,7 @@ echo str_pad('Loading... ',4096)."<br />\n";
`code` varchar(5) collate utf8_unicode_ci default NULL, `code` varchar(5) collate utf8_unicode_ci default NULL,
PRIMARY KEY (`id`), PRIMARY KEY (`id`),
UNIQUE KEY `sid` (`sid`,`qid`,`quota_id`,`code`) 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 // Rename Norwegian language code from NO to NB
$oldnewlanguages=array('no'=>'nb'); $oldnewlanguages=array('no'=>'nb');
@@ -169,12 +169,12 @@ echo str_pad('Loading... ',4096)."<br />\n";
`folder` varchar(255) NOT NULL, `folder` varchar(255) NOT NULL,
`use` int(1) NOT NULL, `use` int(1) NOT NULL,
PRIMARY KEY (`uid`,`folder`) 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` ( modify_database("","CREATE TABLE `prefix_templates` (
`folder` varchar(255) NOT NULL, `folder` varchar(255) NOT NULL,
`creator` int(11) NOT NULL, `creator` int(11) NOT NULL,
PRIMARY KEY (`folder`) 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 //123
modify_database("","ALTER TABLE `prefix_conditions` CHANGE `value` `value` VARCHAR(255) NOT NULL default ''"); echo $modifyoutput; flush(); 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)."<br />\n";
modify_database("","ALTER TABLE `prefix_users` DROP COLUMN `move_user`"); echo $modifyoutput; flush(); modify_database("","ALTER TABLE `prefix_users` DROP COLUMN `move_user`"); echo $modifyoutput; flush();
//126 //126
modify_database("","ALTER TABLE `prefix_questions` ADD `lid1` integer NOT NULL default '0'"); echo $modifyoutput; flush(); 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(); 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`,'/''',''''),'<br /><a href=\"',`link`,'\">',`link`,'</a>')"); 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; return true;
} }
function upgrade_survey_tables117() function upgrade_survey_tables117()
{ {
global $modifyoutput; global $modifyoutput;
@@ -205,12 +329,12 @@ function upgrade_survey_tables117()
$surveyidresult = db_execute_num($surveyidquery); $surveyidresult = db_execute_num($surveyidquery);
if (!$surveyidresult) {return "Database Error";} if (!$surveyidresult) {return "Database Error";}
else else
{ {
while ( $sv = $surveyidresult->FetchRow() ) while ( $sv = $surveyidresult->FetchRow() )
{ {
modify_database("","ALTER TABLE ".db_table_name('survey_'.$sv[0])." ADD `startdate` datetime AFTER `datestamp`"); echo $modifyoutput; flush(); modify_database("","ALTER TABLE ".db_table_name('survey_'.$sv[0])." ADD `startdate` datetime AFTER `datestamp`"); echo $modifyoutput; flush();
}
} }
}
} }
function upgrade_survey_tables118() function upgrade_survey_tables118()
@@ -238,61 +362,105 @@ function upgrade_token_tables125()
{ {
while ( $sv = $surveyidresult->FetchRow() ) 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() function fix_mysql_collation()
{ {
global $connect, $modifyoutput, $dbprefix; global $connect, $modifyoutput, $dbprefix;
$sql = 'SHOW TABLE STATUS'; $sql = 'SHOW TABLE STATUS';
$result = db_execute_assoc($sql); $result = db_execute_assoc($sql);
if (!$result) { if (!$result) {
$modifyoutput .= 'SHOW TABLE - SQL Error'; $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();
}
}
}
}
}
} }
}
?>

View File

@@ -1,240 +0,0 @@
<?PHP
/*
* LimeSurvey
* Copyright (C) 2007 The LimeSurvey Project Team / Carsten Schmitz
* All rights reserved.
* License: http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* LimeSurvey is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details.
*
* $Id: upgrade-odbc_mssql.php 4453 2008-03-13 22:41:44Z c_schmitz $
*/
// There will be a file for each database (accordingly named to the dbADO scheme)
// where based on the current database version the database is upgraded
// For this there will be a settings table which holds the last time the database was upgraded
function db_upgrade($oldversion) {
/// This function does anything necessary to upgrade
/// older versions to match current functionality
global $modifyoutput;
echo str_pad('Loading... ',4096)."<br />\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();
}
}
?>

View File

@@ -18,14 +18,190 @@
// For this there will be a settings table which holds the last time the database was upgraded // For this there will be a settings table which holds the last time the database was upgraded
function db_upgrade($oldversion) { 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) ||'<br /><a href=\"'||link||'\">'||link||'</a>'"); 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; 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();
}
}
}
?> ?>

View File

@@ -10,7 +10,7 @@
* other free or open source software licenses. * other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details. * See COPYRIGHT.php for copyright notices and details.
* *
* $Id: integritycheck.php 4973 2008-06-01 14:07:01Z c_schmitz $ * $Id: integritycheck.php 6976 2009-05-30 00:53:41Z c_schmitz $
*/ */
@@ -24,21 +24,14 @@ if($_SESSION['USER_RIGHT_CONFIGURATOR'] == 1)
$integritycheck=''; $integritycheck='';
if (!isset($ok) || $ok != "Y") // do the check, but don't delete anything if (!isset($ok) || $ok != "Y") // do the check, but don't delete anything
{ {
$integritycheck .= "<table><tr><td height='1'></td></tr></table>\n" $integritycheck .= "<div class='messagebox'>"
. "<table align='center' class='menu2columns' style='border: 1px solid #555555' " . "<div class='header'>".$clang->gT("Data Consistency Check")."<br /><span style='font-size:7pt;'>".$clang->gT("If errors are showing up you might have to execute this script repeatedly.")."</span></div>\n"
. "cellpadding='1' cellspacing='0' width='450'>\n" . "<ul>\n";
. "\t<tr>\n"
. "\t\t<td colspan='2' align='center'>\n"
. "\t\t\t<strong>".$clang->gT("Data Consistency Check")."<br /><font size='1'>".$clang->gT("If errors are showing up you might have to execute this script repeatedly.")."</font></strong>\n"
. "\t\t</td>\n"
. "\t</tr>\n"
. "\t<tr><td align='center'>"
. "<br />\n";
// Check conditions // Check conditions
// $query = "SELECT {$dbprefix}questions.sid, {$dbprefix}conditions.* " // $query = "SELECT {$dbprefix}questions.sid, {$dbprefix}conditions.* "
// ."FROM {$dbprefix}conditions, {$dbprefix}questions " // ."FROM {$dbprefix}conditions, {$dbprefix}questions "
// ."WHERE {$dbprefix}conditions.qid={$dbprefix}questions.qid " // ."WHERE {$dbprefix}conditions.qid={$dbprefix}questions.qid "
// ."ORDER BY qid, cqid, cfieldname, value"; // ."ORDER BY qid, scenario, cqid, cfieldname, value";
$query = "SELECT * FROM {$dbprefix}conditions ORDER BY cid"; $query = "SELECT * FROM {$dbprefix}conditions ORDER BY cid";
$result = db_execute_assoc($query) or safe_die("Couldn't get list of conditions from database<br />$query<br />".$connect->ErrorMsg()); $result = db_execute_assoc($query) or safe_die("Couldn't get list of conditions from database<br />$query<br />".$connect->ErrorMsg());
while ($row=$result->FetchRow()) while ($row=$result->FetchRow())
@@ -66,15 +59,15 @@ if($_SESSION['USER_RIGHT_CONFIGURATOR'] == 1)
} }
if (isset($cdelete) && $cdelete) if (isset($cdelete) && $cdelete)
{ {
$integritycheck .= "<strong>".$clang->gT("The following conditions should be deleted").":</strong><br /><font size='1'>\n"; $integritycheck .= "<li>".$clang->gT("The following conditions should be deleted").":</li><br /><span style='font-size:7pt;'>\n";
foreach ($cdelete as $cd) { foreach ($cdelete as $cd) {
$integritycheck .= "CID: {$cd['cid']} ".$clang->gT("because")." {$cd['reason']}<br />\n"; $integritycheck .= "CID: {$cd['cid']} ".$clang->gT("because")." {$cd['reason']}<br />\n";
} }
$integritycheck .= "</font><br />\n"; $integritycheck .= "<br />\n";
} }
else else
{ {
$integritycheck .= "<strong>".$clang->gT("All conditions meet consistency standards")."</strong><br />\n"; $integritycheck .= "<li>".$clang->gT("All conditions meet consistency standards")."</li>\n";
} }
// Check question_attributes to delete // Check question_attributes to delete
@@ -90,13 +83,13 @@ if($_SESSION['USER_RIGHT_CONFIGURATOR'] == 1)
} }
} // while } // while
if (isset($qadelete) && $qadelete) { if (isset($qadelete) && $qadelete) {
$integritycheck .= "<strong>".$clang->gT("The following question attributes should be deleted").":</strong><br /><font size='1'>\n"; $integritycheck .= "<li>".$clang->gT("The following question attributes should be deleted").":</li><br /><span style='font-size:7pt;'>\n";
foreach ($qadelete as $qad) {$integritycheck .= "QAID `{$qad['qaid']}` ATTRIBUTE `{$qad['attribute']}` ".$clang->gT("because")." `{$qad['reason']}`<br />\n";} foreach ($qadelete as $qad) {$integritycheck .= "QAID `{$qad['qaid']}` ATTRIBUTE `{$qad['attribute']}` ".$clang->gT("because")." `{$qad['reason']}`<br />\n";}
$integritycheck .= "</font><br />\n"; $integritycheck .= "</span><br />\n";
} }
else else
{ {
$integritycheck .= "<strong>".$clang->gT("All question_attributes meet consistency standards")."</strong><br />\n"; $integritycheck .= "<li>".$clang->gT("All question attributes meet consistency standards")."</li>\n";
} }
// Check assessments // Check assessments
@@ -126,23 +119,23 @@ if($_SESSION['USER_RIGHT_CONFIGURATOR'] == 1)
if (isset($assdelete) && $assdelete) if (isset($assdelete) && $assdelete)
{ {
$integritycheck .= "<strong>".$clang->gT("The following assessments should be deleted").":</strong><br /><font size='1'>\n"; $integritycheck .= "<li>".$clang->gT("The following assessments should be deleted").":</li><span style='font-size:7pt;'>\n";
foreach ($assdelete as $ass) {$integritycheck .= "ID `{$ass['id']}` ASSESSMENT `{$ass['assessment']}` ".$clang->gT("because")." `{$ass['reason']}`<br />\n";} foreach ($assdelete as $ass) {$integritycheck .= "ID `{$ass['id']}` ASSESSMENT `{$ass['assessment']}` ".$clang->gT("because")." `{$ass['reason']}`<br />\n";}
$integritycheck .= "</font><br />\n"; $integritycheck .= "</span><br />\n";
} }
else else
{ {
$integritycheck .= "<strong>".$clang->gT("All Survey (Total) assessments meet consistency standards")."</strong><br />\n"; $integritycheck .= "<li>".$clang->gT("All Survey (Total) assessments meet consistency standards")."</li>\n";
} }
if (isset($asgdelete) && $asgdelete) if (isset($asgdelete) && $asgdelete)
{ {
$integritycheck .= "<strong>".$clang->gT("The following assessments should be deleted").":</strong><br /><font size='1'>\n"; $integritycheck .= "<strong>".$clang->gT("The following assessments should be deleted").":</strong><br /><span style='font-size:7pt;'>\n";
foreach ($asgdelete as $asg) {$integritycheck .= "ID `{$asg['id']}` ASSESSMENT `{$asg['assessment']}` ".$clang->gT("because")." `{$asg['reason']}`<br />\n";} foreach ($asgdelete as $asg) {$integritycheck .= "ID `{$asg['id']}` ASSESSMENT `{$asg['assessment']}` ".$clang->gT("because")." `{$asg['reason']}`<br />\n";}
$integritycheck .= "</font><br />\n"; $integritycheck .= "</span><br />\n";
} }
else else
{ {
$integritycheck .= "<strong>".$clang->gT("All Group assessments meet consistency standards")."</strong><br />\n"; $integritycheck .= "<li>".$clang->gT("All Group assessments meet consistency standards")."</li>\n";
} }
// Check answers // Check answers
@@ -161,13 +154,13 @@ if($_SESSION['USER_RIGHT_CONFIGURATOR'] == 1)
} }
if (isset($adelete) && $adelete) if (isset($adelete) && $adelete)
{ {
$integritycheck .= "<strong>".$clang->gT("The following answers should be deleted").":</strong><br /><font size='1'>\n"; $integritycheck .= "<strong>".$clang->gT("The following answers should be deleted").":</strong><br /><span style='font-size:7pt;'>\n";
foreach ($adelete as $ad) {$integritycheck .= "QID `{$ad['qid']}` CODE `{$ad['code']}` ".$clang->gT("because")." `{$ad['reason']}`<br />\n";} foreach ($adelete as $ad) {$integritycheck .= "QID `{$ad['qid']}` CODE `{$ad['code']}` ".$clang->gT("because")." `{$ad['reason']}`<br />\n";}
$integritycheck .= "</font><br />\n"; $integritycheck .= "</span><br />\n";
} }
else else
{ {
$integritycheck .= "<strong>".$clang->gT("All answers meet consistency standards")."</strong><br />\n"; $integritycheck .= "<li>".$clang->gT("All answers meet consistency standards")."</li>\n";
} }
// Check surveys // Check surveys
@@ -184,13 +177,13 @@ if($_SESSION['USER_RIGHT_CONFIGURATOR'] == 1)
} }
if (isset($sdelete) && $sdelete) if (isset($sdelete) && $sdelete)
{ {
$integritycheck .= "<strong>".$clang->gT("The following surveys should be deleted").":</strong><br /><font size='1'>\n"; $integritycheck .= "<strong>".$clang->gT("The following surveys should be deleted").":</strong><br /><span style='font-size:7pt;'>\n";
foreach ($sdelete as $sd) {$integritycheck .= "SID `{$sd['sid']}` ".$clang->gT("because")." `{$sd['reason']}`<br />\n";} foreach ($sdelete as $sd) {$integritycheck .= "SID `{$sd['sid']}` ".$clang->gT("because")." `{$sd['reason']}`<br />\n";}
$integritycheck .= "</font><br />\n"; $integritycheck .= "</span><br />\n";
} }
else else
{ {
$integritycheck .= "<strong>".$clang->gT("All survey settings meet consistency standards")."</strong><br />\n"; $integritycheck .= "<li>".$clang->gT("All survey settings meet consistency standards")."</li>\n";
} }
//check questions //check questions
@@ -202,24 +195,24 @@ if($_SESSION['USER_RIGHT_CONFIGURATOR'] == 1)
$qquery="SELECT * FROM {$dbprefix}groups WHERE gid={$row['gid']}"; $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<br />$qquery<br />".$connect->ErrorMsg()); $qresult=$connect->Execute($qquery) or safe_die ("Couldn't check groups table for gids from questions<br />$qquery<br />".$connect->ErrorMsg());
$qcount=$qresult->RecordCount(); $qcount=$qresult->RecordCount();
if (!$qcount) {$qdelete[]=array("qid"=>$row['qid'], "reason"=>$clang->gT("No matching Group")." ({$row['gid']})");} if (!$qcount) {$qdelete[]=array("qid"=>$row['qid'], "reason"=>$clang->gT("No matching group")." ({$row['gid']})");}
//Make sure survey exists //Make sure survey exists
$qquery="SELECT * FROM {$dbprefix}surveys WHERE sid={$row['sid']}"; $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<br />$qquery<br />".$connect->ErrorMsg()); $qresult=$connect->Execute($qquery) or safe_die ("Couldn't check surveys table for sids from questions<br />$qquery<br />".$connect->ErrorMsg());
$qcount=$qresult->RecordCount(); $qcount=$qresult->RecordCount();
if (!$qcount) { 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) || !in_array($row['qid'], $qdelete)) {$qdelete[]=array("qid"=>$row['qid'], "reason"=>$clang->gT("No matching survey")." ({$row['sid']})");}
} }
} }
if (isset($qdelete) && $qdelete) if (isset($qdelete) && $qdelete)
{ {
$integritycheck .= "<strong>".$clang->gT("The following questions should be deleted").":</strong><br /><font size='1'>\n"; $integritycheck .= "<strong>".$clang->gT("The following questions should be deleted").":</strong><br /><span style='font-size:7pt;'>\n";
foreach ($qdelete as $qd) {$integritycheck .= "QID `{$qd['qid']}` ".$clang->gT("because")." `{$qd['reason']}`<br />\n";} foreach ($qdelete as $qd) {$integritycheck .= "QID `{$qd['qid']}` ".$clang->gT("because")." `{$qd['reason']}`<br />\n";}
$integritycheck .= "</font><br />\n"; $integritycheck .= "</span><br />\n";
} }
else else
{ {
$integritycheck .= "<strong>".$clang->gT("All questions meet consistency standards")."</strong><br />\n"; $integritycheck .= "<li>".$clang->gT("All questions meet consistency standards")."</li>\n";
} }
//check groups //check groups
$query = "SELECT * FROM {$dbprefix}groups ORDER BY sid, gid"; $query = "SELECT * FROM {$dbprefix}groups ORDER BY sid, gid";
@@ -234,14 +227,15 @@ if($_SESSION['USER_RIGHT_CONFIGURATOR'] == 1)
} }
if (isset($gdelete) && $gdelete) if (isset($gdelete) && $gdelete)
{ {
$integritycheck .= "<strong>".$clang->gT("The following groups should be deleted").":</strong><br /><font size='1'>\n"; $integritycheck .= "<li>".$clang->gT("The following groups should be deleted").":</li><span style='font-size:7pt;'>\n";
$integritycheck .= implode(", ", $gdelete); $integritycheck .= implode(", ", $gdelete);
$integritycheck .= "</font><br />\n"; $integritycheck .= "</span><br />\n";
} }
else else
{ {
$integritycheck .= "<strong>".$clang->gT("All groups meet consistency standards")."</strong><br />\n"; $integritycheck .= "<li>".$clang->gT("All groups meet consistency standards")."</li>\n";
} }
$integritycheck .='</ul>' ;
//NOW CHECK FOR STRAY SURVEY RESPONSE TABLES AND TOKENS TABLES //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)) { if (!isset($cdelete) && !isset($adelete) && !isset($qdelete) && !isset($gdelete) && !isset($asgdelete) && !isset($sdelete) && !isset($assdelete) && !isset($qadelete)) {
$integritycheck .= "<br />".$clang->gT("No database action required"); $integritycheck .= "<br />".$clang->gT("No database action required");
@@ -292,9 +286,7 @@ if($_SESSION['USER_RIGHT_CONFIGURATOR'] == 1)
."<input type='submit' value='".$clang->gT("Yes - Delete Them!")."'>\n" ."<input type='submit' value='".$clang->gT("Yes - Delete Them!")."'>\n"
."</form>\n"; ."</form>\n";
} }
$integritycheck .= "<br /><br />\n" $integritycheck .= "</div><br />\n";
."</td></tr></table>\n"
."<table><tr><td height='1'></td></tr></table>\n";
} }
elseif ($ok == "Y") elseif ($ok == "Y")
{ {
@@ -303,7 +295,7 @@ if($_SESSION['USER_RIGHT_CONFIGURATOR'] == 1)
. "cellpadding='1' cellspacing='0' width='450'>\n" . "cellpadding='1' cellspacing='0' width='450'>\n"
. "\t<tr>\n" . "\t<tr>\n"
. "\t\t<td colspan='2' align='center'>\n" . "\t\t<td colspan='2' align='center'>\n"
. "\t\t\t<strong>".$clang->gT("Data Consistency Check")."<br /><font size='1'>".$clang->gT("If errors are showing up you might have to execute this script repeatedly.")."</strong>\n" . "\t\t\t<strong>".$clang->gT("Data Consistency Check")."<br /><span style='font-size:7pt;'>".$clang->gT("If errors are showing up you might have to execute this script repeatedly.")."</strong>\n"
. "\t\t</td>\n" . "\t\t</td>\n"
. "\t</tr>\n" . "\t</tr>\n"
. "\t<tr><td align='center'>"; . "\t<tr><td align='center'>";
@@ -317,7 +309,7 @@ if($_SESSION['USER_RIGHT_CONFIGURATOR'] == 1)
$sdelete=returnglobal('sdelete'); $sdelete=returnglobal('sdelete');
if (isset($sdelete)) { if (isset($sdelete)) {
$integritycheck .= $clang->gT("Deleting Surveys").":<br /><fontsize='1'>\n"; $integritycheck .= $clang->gT("Deleting Surveys").":<br /><spanstyle='font-size:7pt;'>\n";
foreach ($sdelete as $ass) { foreach ($sdelete as $ass) {
$integritycheck .= $clang->gT("Deleting Survey ID").":".$ass."<br />\n"; $integritycheck .= $clang->gT("Deleting Survey ID").":".$ass."<br />\n";
$sql = "DELETE FROM {$dbprefix}surveys WHERE sid=$ass"; $sql = "DELETE FROM {$dbprefix}surveys WHERE sid=$ass";
@@ -326,7 +318,7 @@ if($_SESSION['USER_RIGHT_CONFIGURATOR'] == 1)
} }
if (isset($assdelete)) { if (isset($assdelete)) {
$integritycheck .= $clang->gT( "Deleting Assessments").":<br /><fontsize='1'>\n"; $integritycheck .= $clang->gT( "Deleting Assessments").":<br /><spanstyle='font-size:7pt;'>\n";
foreach ($assdelete as $ass) { foreach ($assdelete as $ass) {
$integritycheck .= $clang->gT("Deleting ID").":".$ass."<br />\n"; $integritycheck .= $clang->gT("Deleting ID").":".$ass."<br />\n";
$sql = "DELETE FROM {$dbprefix}assessments WHERE id=$ass"; $sql = "DELETE FROM {$dbprefix}assessments WHERE id=$ass";
@@ -334,7 +326,7 @@ if($_SESSION['USER_RIGHT_CONFIGURATOR'] == 1)
} }
} }
if (isset($asgdelete)) { if (isset($asgdelete)) {
$integritycheck .= $clang->gT("Deleting Assessments").":<br /><fontsize='1'>\n"; $integritycheck .= $clang->gT("Deleting Assessments").":<br /><spanstyle='font-size:7pt;'>\n";
foreach ($asgdelete as $asg) { foreach ($asgdelete as $asg) {
$integritycheck .= $clang->gT("Deleting ID").":".$asg."<br />\n"; $integritycheck .= $clang->gT("Deleting ID").":".$asg."<br />\n";
$sql = "DELETE FROM {$dbprefix}assessments WHERE id=$asg"; $sql = "DELETE FROM {$dbprefix}assessments WHERE id=$asg";
@@ -342,7 +334,7 @@ if($_SESSION['USER_RIGHT_CONFIGURATOR'] == 1)
} }
} }
if (isset($qadelete)) { if (isset($qadelete)) {
$integritycheck .= $clang->gT("Deleting Question_Attributes").":<br /><fontsize='1'>\n"; $integritycheck .= $clang->gT("Deleting Question_Attributes").":<br /><spanstyle='font-size:7pt;'>\n";
foreach ($qadelete as $qad) { foreach ($qadelete as $qad) {
$integritycheck .= "Deleting QAID:".$qad."<br />\n"; $integritycheck .= "Deleting QAID:".$qad."<br />\n";
$sql = "DELETE FROM {$dbprefix}question_attributes WHERE qaid=$qad"; $sql = "DELETE FROM {$dbprefix}question_attributes WHERE qaid=$qad";
@@ -350,41 +342,41 @@ if($_SESSION['USER_RIGHT_CONFIGURATOR'] == 1)
} }
} }
if (isset($cdelete)) { if (isset($cdelete)) {
$integritycheck .= $clang->gT("Deleting Conditions").":<br /><font size='1'>\n"; $integritycheck .= $clang->gT("Deleting Conditions").":<br /><span style='font-size:7pt;'>\n";
foreach ($cdelete as $cd) { foreach ($cdelete as $cd) {
$integritycheck .= $clang->gT("Deleting cid").":".$cd."<br />\n"; $integritycheck .= $clang->gT("Deleting cid").":".$cd."<br />\n";
$sql = "DELETE FROM {$dbprefix}conditions WHERE cid=$cd"; $sql = "DELETE FROM {$dbprefix}conditions WHERE cid=$cd";
$result=$connect->Execute($sql) or safe_die ("Couldn't Delete ($sql)<br />".$connect->ErrorMsg()); $result=$connect->Execute($sql) or safe_die ("Couldn't Delete ($sql)<br />".$connect->ErrorMsg());
} }
$integritycheck .= "</font><br />\n"; $integritycheck .= "</span><br />\n";
} }
if (isset($adelete)) { if (isset($adelete)) {
$integritycheck .= $clang->gT("Deleting Answers").":<br /><font size='1'>\n"; $integritycheck .= $clang->gT("Deleting Answers").":<br /><span style='font-size:7pt;'>\n";
foreach ($adelete as $ad) { foreach ($adelete as $ad) {
list($ad1, $ad2)=explode("|", $ad); list($ad1, $ad2)=explode("|", $ad);
$integritycheck .= $clang->gT("Deleting answer with qid").":".$ad1." and code: ".$ad2."<br />\n"; $integritycheck .= $clang->gT("Deleting answer with qid").":".$ad1." and code: ".$ad2."<br />\n";
$sql = "DELETE FROM {$dbprefix}answers WHERE qid=$ad1 AND code='$ad2'"; $sql = "DELETE FROM {$dbprefix}answers WHERE qid=$ad1 AND code='$ad2'";
$result=$connect->Execute($sql) or safe_die ("Couldn't Delete ($sql)<br />".$connect->ErrorMsg()); $result=$connect->Execute($sql) or safe_die ("Couldn't Delete ($sql)<br />".$connect->ErrorMsg());
} }
$integritycheck .= "</font><br />\n"; $integritycheck .= "</span><br />\n";
} }
if (isset($qdelete)) { if (isset($qdelete)) {
$integritycheck .= $clang->gT("Deleting Questions").":<br /><font size='1'>\n"; $integritycheck .= $clang->gT("Deleting Questions").":<br /><span style='font-size:7pt;'>\n";
foreach ($qdelete as $qd) { foreach ($qdelete as $qd) {
$integritycheck .= $clang->gT("Deleting qid").":".$qd."<br />\n"; $integritycheck .= $clang->gT("Deleting qid").":".$qd."<br />\n";
$sql = "DELETE FROM {$dbprefix}questions WHERE qid=$qd"; $sql = "DELETE FROM {$dbprefix}questions WHERE qid=$qd";
$result=$connect->Execute($sql) or safe_die ("Couldn't Delete ($sql)<br />".$connect->ErrorMsg()); $result=$connect->Execute($sql) or safe_die ("Couldn't Delete ($sql)<br />".$connect->ErrorMsg());
} }
$integritycheck .= "</font><br />\n"; $integritycheck .= "</span><br />\n";
} }
if (isset($gdelete)) { if (isset($gdelete)) {
$integritycheck .= $clang->gT("Deleting Groups").":<br /><font size='1'>\n"; $integritycheck .= $clang->gT("Deleting Groups").":<br /><span style='font-size:7pt;'>\n";
foreach ($gdelete as $gd) { foreach ($gdelete as $gd) {
$integritycheck .= $clang->gT("Deleting group id").":".$gd."<br />\n"; $integritycheck .= $clang->gT("Deleting group id").":".$gd."<br />\n";
$sql = "DELETE FROM {$dbprefix}groups WHERE gid=$gd"; $sql = "DELETE FROM {$dbprefix}groups WHERE gid=$gd";
$result=$connect->Execute($sql) or safe_die ("Couldn't Delete ($sql)<br />".$connect->ErrorMsg()); $result=$connect->Execute($sql) or safe_die ("Couldn't Delete ($sql)<br />".$connect->ErrorMsg());
} }
$integritycheck .= "</font><br />\n"; $integritycheck .= "</span><br />\n";
} }
$integritycheck .= $clang->gT("Check database again?")."<br />\n" $integritycheck .= $clang->gT("Check database again?")."<br />\n"
."<a href='{$_SERVER['PHP_SELF']}?action=checkintegrity'>".$clang->gT("Check Again")."</a><br />\n" ."<a href='{$_SERVER['PHP_SELF']}?action=checkintegrity'>".$clang->gT("Check Again")."</a><br />\n"

View File

@@ -0,0 +1,69 @@
<?php
/*
* LimeSurvey
* Copyright (C) 2007 The LimeSurvey Project Team / Carsten Schmitz
* All rights reserved.
* License: GNU/GPL License v2 or later, see LICENSE.php
* LimeSurvey is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details.
*
* $Id: iterate_survey.php 6380 2009-02-16 13:30:17Z c_schmitz $
*/
/*
* Set completed answers to the incomplete state and reset the tokens to 'not used' so that
* the survey can be published again to the same set of participants.
* Partipants will see their previous answers and may change them.
*/
include_once('login_check.php');
if (!isset($surveyid)) {$surveyid=returnglobal('sid');}
if (!isset($subaction))
{ // subaction is not set, then display instructions
$iteratesurveyoutput = browsemenubar($clang->gT('Iterate survey'));
$iteratesurveyoutput .= "<br />\n";
$iteratesurveyoutput .= "<div class='header'>".$clang->gT("Iterate survey")."</div>\n";
$iteratesurveyoutput .= "<h3>".$clang->gT("Important instructions")."</h3>"
. "<p style='width:80%;'>\n"
. "<div align='center'>".$clang->gT("Click on the following button if you want to").":<br /></div>\n"
. "<ol style='width:500px;margin:0 auto; font-size:8pt;'>"
. "<li>".$clang->gT("Delete all incomplete answers that correspond to a token for which a completed answers is already recorded")."</li>"
. "<li>".$clang->gT("Reset the completed answers to the incomplete state")."</li>"
. "<li>".$clang->gT("Reset all your tokens to the 'not used' state")."</li>"
. "</ol><br />\n"
. "<input type='button' onclick=\"if( confirm('".$clang->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&amp;sid=$surveyid&amp;subaction=unfinalizeanswers")."}\" value='".$clang->gT("Reset answers and token completed state")."'>"
. "<table><tr><td>";
}
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:<br />\n" . $connect->ErrorMsg() . "<br />$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:<br />\n" . $connect->ErrorMsg() . "<br />$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<br />$updateqr<br />".$connect->ErrorMsg());
$iteratesurveyoutput .= "<br />\n";
$iteratesurveyoutput .= "<div class='header'>".$clang->gT("Iterate survey")."</div>\n";
$iteratesurveyoutput .= "<p style='width:100%;'>\n"
. "<font class='successtitle'>".$clang->gT("Success")."</font><br />\n"
. $clang->gT("Answers and tokens have been re-opened.")."<br />\n"
. "</p>\n"
. "<table><tr><td>";
}
?>

View File

@@ -10,7 +10,7 @@
* other free or open source software licenses. * other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details. * See COPYRIGHT.php for copyright notices and details.
* *
* $Id: labels.php 5144 2008-06-22 12:46:05Z c_schmitz $ * $Id: labels.php 7451 2009-08-12 03:56:38Z paraya $
*/ */
include_once("login_check.php"); //Login Check dies also if the script is started directly include_once("login_check.php"); //Login Check dies also if the script is started directly
@@ -27,6 +27,7 @@ if (isset($_POST['method']) && get_magic_quotes_gpc())
$_POST['method'] = stripslashes($_POST['method']); $_POST['method'] = stripslashes($_POST['method']);
} }
$labelsoutput='';
if($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $_SESSION['USER_RIGHT_MANAGE_LABEL'] == 1) if($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $_SESSION['USER_RIGHT_MANAGE_LABEL'] == 1)
{ {
@@ -36,7 +37,6 @@ if($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $_SESSION['USER_RIGHT_MANAGE_LABEL
if (!isset($action)) {$action=returnglobal('action');} if (!isset($action)) {$action=returnglobal('action');}
if (!isset($lid)) {$lid=returnglobal('lid');} if (!isset($lid)) {$lid=returnglobal('lid');}
if (!isset($lid1)) {$lid1=returnglobal('lid1');} if (!isset($lid1)) {$lid1=returnglobal('lid1');}
$labelsoutput= include2var('./scripts/addremove.js');
//DO DATABASE UPDATESTUFF //DO DATABASE UPDATESTUFF
if ($action == "updateset") {updateset($lid);} if ($action == "updateset") {updateset($lid);}
@@ -57,37 +57,27 @@ if($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $_SESSION['USER_RIGHT_MANAGE_LABEL
} }
$labelsoutput.= "<table width='100%' border='0' >\n" $labelsoutput= "<table width='100%' border='0' >\n"
. "\t<tr>\n" ."\t<tr>\n"
. "\t\t<td>\n" ."\t<td>\n"
. "\t\t\t<table class='menubar'>\n" ."\t\t<div class='menubar'>\n"
. "\t\t\t<tr >\n" ."\t\t<div class='menubar-title'>\n"
. "\t\t\t\t<td colspan='2' height='8'>\n" ."\t\t<strong>".$clang->gT("Label Sets Administration")."</strong>\n"
. "\t\t\t\t<strong>" ."\t\t</div>\n"
.$clang->gT("Label Sets Administration")."</strong></td></tr>\n" ."\t<div class='menubar-main'>\n"
."<tr >\n" ."\t<div class='menubar-left'>\n"
."\t<td>\n"
."\t<a href='$scriptname' onmouseout=\"hideTooltip()\" title=\"".$clang->gTview("Return to Survey Administration")."\" onmouseover=\"showTooltip(event,'".$clang->gT("Return to Survey Administration", "js")."');return false\">" . ."\t<a href='$scriptname' onmouseout=\"hideTooltip()\" title=\"".$clang->gTview("Return to Survey Administration")."\" onmouseover=\"showTooltip(event,'".$clang->gT("Return to Survey Administration", "js")."');return false\">" .
"<img name='Administration' src='$imagefiles/home.png' title='' alt='' align='left' /></a>" "<img name='Administration' src='$imagefiles/home.png' title='' alt='' /></a>"
."\t<img src='$imagefiles/blank.gif' width='11' height='20' border='0' hspace='0' align='left' alt='' />\n" ."\t<img src='$imagefiles/blank.gif' width='11' height='20' alt='' />\n"
."\t<img src='$imagefiles/seperator.gif' border='0' hspace='0' align='left' alt='' />\n" ."\t<img src='$imagefiles/seperator.gif' alt='' />\n"
."\t</td>\n" ."\t</div>\n"
."\t<td align='right' width='620'>\n" ."\t<div class='menubar-right'>\n"
."<a href=\"#\" onclick=\"showhelp('show')\"" ."\t<img src='$imagefiles/blank.gif' width='5' height='20' alt='' />\n"
."onmouseout=\"hideTooltip()\""
."title=\"".$clang->gTview("Show Help")."\""
."onmouseover=\"showTooltip(event,'".$clang->gT("Show Help", "js")."');return false\">"
."<img src='$imagefiles/showhelp.png' name='ShowHelp' title=''"
."alt='". $clang->gT("Show Help")."' align='right' /></a>"
."\t<img src='$imagefiles/blank.gif' width='42' height='20' align='right' hspace='0' border='0' alt='' />\n"
."\t<img src='$imagefiles/seperator.gif' align='right' hspace='0' border='0' alt='' />\n"
."<a href=\"#\" onclick=\"window.open('admin.php?action=newlabelset', '_self')\""
."onmouseout=\"hideTooltip()\""
."title=\"".$clang->gTview("Add New Label Set")."\""
."onmouseover=\"showTooltip(event,'".$clang->gT("Add New Label Set", "js")."');return false\">"
."<img src='$imagefiles/add.png' align='right' name='AddLabel' title='' alt='". $clang->gT("Add new label set")."' /></a>\n"
."\t<font class='boxcaption'>".$clang->gT("Labelsets").": </font>" ."\t<font class='boxcaption'>".$clang->gT("Labelsets").": </font>"
."\t<select onchange=\"window.open(this.options[this.selectedIndex].value,'_self')\">\n"; ."\t<select onchange=\"window.open(this.options[this.selectedIndex].value,'_self')\">\n";
$labelsoutput.= "<option value=''";
if (!isset($lid) || $lid<1) {$labelsoutput.= " selected='selected'";}
$labelsoutput.= ">".$clang->gT("Please Choose...")."</option>\n";
$labelsets=getlabelsets(); $labelsets=getlabelsets();
if (count($labelsets)>0) if (count($labelsets)>0)
{ {
@@ -98,18 +88,34 @@ if($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $_SESSION['USER_RIGHT_MANAGE_LABEL
$labelsoutput.= ">{$lb[1]}</option>\n"; $labelsoutput.= ">{$lb[1]}</option>\n";
} }
} }
$labelsoutput.= "<option value=''";
if (!isset($lid) || $lid<1) {$labelsoutput.= " selected='selected'";}
$labelsoutput.= ">".$clang->gT("Please Choose...")."</option>\n";
$labelsoutput.= "\t</select>\n" $labelsoutput.= "\t</select>\n"
."\t</td>\n" ."<a href=\"#\" onclick=\"window.open('admin.php?action=newlabelset', '_self')\""
."</tr>\n" ."onmouseout=\"hideTooltip()\""
."\t</table>\n"; ."title=\"".$clang->gTview("Add new label set")."\""
."onmouseover=\"showTooltip(event,'".$clang->gT("Add new label set", "js")."');return false\">"
."<img src='$imagefiles/add.png' name='AddLabel' title='' alt='". $clang->gT("Add new label set")."' /></a>\n"
//Logout button
."\t<img src='$imagefiles/seperator.gif' alt='' />\n"
."\t<img src='$imagefiles/blank.gif' width='5' height='20' alt='' />\n"
. "\t\t<a href=\"#\" onclick=\"window.open('$scriptname?action=logout', '_self')\""
. "title=\"".$clang->gTview("Logout")."\" "
. "onmouseout=\"hideTooltip()\""
. "onmouseover=\"showTooltip(event,'".$clang->gT("Logout", "js")."');return false\">"
. "<img src='$imagefiles/logout.png' name='Logout'"
. "title='' alt='".$clang->gT("Logout")."' /></a>"
."<a href=\"#\" onclick=\"showhelp('show')\""
."onmouseout=\"hideTooltip()\""
."title=\"".$clang->gTview("Show Help")."\""
."onmouseover=\"showTooltip(event,'".$clang->gT("Show Help", "js")."');return false\">"
."<img src='$imagefiles/showhelp.png' name='ShowHelp' title=''"
."alt='". $clang->gT("Show Help")."' /></a>"
."\t\t</div>\n"
."\t</div>\n"
."</div>\n";
$labelsoutput .= "<p style='margin:0;font-size:1px;line-height:1px;height:1px;'>&nbsp;</p>"; //CSS Firefox 2 transition fix
if ($action!='labels' || isset($lid)) {$labelsoutput.="<table ><tr><td></td></tr></table>\n";}
//NEW SET //NEW SET
if ($action == "newlabelset" || $action == "editlabelset") if ($action == "newlabelset" || $action == "editlabelset")
{ {
@@ -125,13 +131,13 @@ if($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $_SESSION['USER_RIGHT_MANAGE_LABEL
."<th>\n" ."<th>\n"
."<input type='image' src='$imagefiles/close.gif' align='right' " ."<input type='image' src='$imagefiles/close.gif' align='right' "
."onclick=\"window.open('admin.php?action=labels&amp;lid=$lid', '_self')\" />\n"; ."onclick=\"window.open('admin.php?action=labels&amp;lid=$lid', '_self')\" />\n";
if ($action == "newlabelset") {$labelsoutput.= $clang->gT("Create or Import New Label Set"); $langids="en"; $tabitem=$clang->gT("Create New Label Set");} if ($action == "newlabelset") {$labelsoutput.= $clang->gT("Create or Import New Label Set"); $langids=$_SESSION['adminlang']; $tabitem=$clang->gT("Create New Label Set");}
else {$labelsoutput.= $clang->gT("Edit Label Set"); $tabitem=$clang->gT("Edit Label Set");} else {$labelsoutput.= $clang->gT("Edit Label Set"); $tabitem=$clang->gT("Edit Label Set");}
$langidsarray=explode(" ",trim($langids)); //Make an array of it $langidsarray=explode(" ",trim($langids)); //Make an array of it
$labelsoutput.= "\n\t</th></tr></table>\n"; $labelsoutput.= "\n\t</th></tr></table>\n";
if (isset($row['lid'])) { $panecookie=$row['lid'];} else {$panecookie='new';}
$labelsoutput.= "<div class='tab-pane' id='tab-pane-1'>\n"; $labelsoutput.= "<div class='tab-pane' id='tab-pane-labelset-{$panecookie}'>\n";
$labelsoutput.= "<div class='tab-page'> <h2 class='tab'>".$tabitem."</h2>\n"; $labelsoutput.= "<div class='tab-page'> <h2 class='tab'>".$tabitem."</h2>\n";
@@ -208,8 +214,8 @@ if($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $_SESSION['USER_RIGHT_MANAGE_LABEL
."<td><input name=\"the_file\" type=\"file\" size=\"35\" />" ."<td><input name=\"the_file\" type=\"file\" size=\"35\" />"
."\t<tr>\n" ."\t<tr>\n"
."<td align='right'><strong>" ."<td align='right'><strong>"
.$clang->gT("Convert Resources links ?")."</strong></td>\n" .$clang->gT("Convert resources links?")."</strong></td>\n"
."<td><input name=\"translinksfields\" type=\"checkbox\" />\n" ."<td><input name=\"translinksfields\" type=\"checkbox\" checked=\"checked\" />\n"
."</td></tr>\n" ."</td></tr>\n"
."\t<tr><td></td><td><input type='submit' value='".$clang->gT("Import Label Set")."' />\n" ."\t<tr><td></td><td><input type='submit' value='".$clang->gT("Import Label Set")."' />\n"
."\t<input type='hidden' name='action' value='importlabels' /></td>\n" ."\t<input type='hidden' name='action' value='importlabels' /></td>\n"
@@ -229,7 +235,7 @@ if($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $_SESSION['USER_RIGHT_MANAGE_LABEL
//$query = "SELECT * FROM ".db_table_name('questions')." WHERE type IN ('F','H','Z','W') AND lid='$lid' GROUP BY qid"; //$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 //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. // 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"; $query = "SELECT qid, sid, gid FROM ".db_table_name('questions')." WHERE type IN ('F','H','Z','W','1',':',';') AND lid='$lid' OR lid1='$lid' GROUP BY qid, sid, gid";
$result = db_execute_assoc($query); $result = db_execute_assoc($query);
$totaluse=$result->RecordCount(); $totaluse=$result->RecordCount();
while($row=$result->FetchRow()) while($row=$result->FetchRow())
@@ -241,15 +247,13 @@ if($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $_SESSION['USER_RIGHT_MANAGE_LABEL
$result = db_execute_assoc($query); $result = db_execute_assoc($query);
while ($row=$result->FetchRow()) while ($row=$result->FetchRow())
{ {
$labelsoutput.= "\t<table class='menubar'>\n" $labelsoutput.= "<div class='menubar'>\n"
."<tr><td height='4' colspan='2'>" ."<div class='menubar-title'>\n"
."<strong>".$clang->gT("Label Set").":</strong> {$row['label_name']}</td></tr>\n" ."\t<strong>".$clang->gT("Label Set").":</strong> {$row['label_name']}\n"
."<tr>\n" ."</div>\n"
."\t<td>\n" ."<div class='menubar-main'>\n"
."\t<input type='image' src='$imagefiles/close.gif' title='" ."\t<div class='menubar-left'>\n"
.$clang->gT("Close Window")."' align='right' " ."\t<img src='$imagefiles/blank.gif' width='60' height='20' border='0' hspace='0' align='left' alt='' />\n"
."onclick=\"window.open('admin.php?action=labels', '_self')\" />\n"
."\t<img src='$imagefiles/blank.gif' width='50' height='20' border='0' hspace='0' align='left' alt='' />\n"
."\t<img src='$imagefiles/seperator.gif' border='0' hspace='0' align='left' alt='' />\n" ."\t<img src='$imagefiles/seperator.gif' border='0' hspace='0' align='left' alt='' />\n"
."\t<a href='admin.php?action=editlabelset&amp;lid=$lid' onmouseout=\"hideTooltip()\" title=\"".$clang->gTview("Edit label set")."\" onmouseover=\"showTooltip(event,'".$clang->gT("Edit label set", "js")."');return false\">" . ."\t<a href='admin.php?action=editlabelset&amp;lid=$lid' onmouseout=\"hideTooltip()\" title=\"".$clang->gTview("Edit label set")."\" onmouseover=\"showTooltip(event,'".$clang->gT("Edit label set", "js")."');return false\">" .
"<img name='EditLabelsetButton' src='$imagefiles/edit.png' alt='' align='left' /></a>" "<img name='EditLabelsetButton' src='$imagefiles/edit.png' alt='' align='left' /></a>"
@@ -260,9 +264,14 @@ if($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $_SESSION['USER_RIGHT_MANAGE_LABEL
."\t<img src='$imagefiles/seperator.gif' border='0' hspace='0' align='left' alt='' />\n" ."\t<img src='$imagefiles/seperator.gif' border='0' hspace='0' align='left' alt='' />\n"
."\t<a href='admin.php?action=dumplabel&amp;lid=$lid' onmouseout=\"hideTooltip()\" title=\"".$clang->gTview("Export Label Set")."\" onmouseover=\"showTooltip(event,'".$clang->gT("Export Label Set", "js")."');return false\">" . ."\t<a href='admin.php?action=dumplabel&amp;lid=$lid' onmouseout=\"hideTooltip()\" title=\"".$clang->gTview("Export Label Set")."\" onmouseover=\"showTooltip(event,'".$clang->gT("Export Label Set", "js")."');return false\">" .
"<img src='$imagefiles/exportcsv.png' alt='".$clang->gT("Export Label Set")."' title='' align='left' /></a>" "<img src='$imagefiles/exportcsv.png' alt='".$clang->gT("Export Label Set")."' title='' align='left' /></a>"
."\t</td>\n" ."\t</div>\n"
."</tr>\n" ."\t<div class='menubar-right'>\n"
."\t</table>\n"; ."\t<input type='image' src='$imagefiles/close.gif' title='".$clang->gT("Close Window")."'"
."onclick=\"window.open('admin.php?action=labels', '_self')\" />\n"
."\t</div>\n"
."\t</div>\n"
."\t</div>\n";
$labelsoutput .= "<p style='margin:0;font-size:1px;line-height:1px;height:1px;'>&nbsp;</p>"; //CSS Firefox 2 transition fix
} }
@@ -276,17 +285,23 @@ if($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $_SESSION['USER_RIGHT_MANAGE_LABEL
$labelsoutput.= PrepareEditorScript("editlabel"); $labelsoutput.= PrepareEditorScript("editlabel");
$maxquery = "SELECT max(sortorder) as maxsortorder FROM ".db_table_name('labels')." WHERE lid=$lid and language='{$lslanguages[0]}'";
$maxresult = db_execute_assoc($maxquery) or safe_die($connect->ErrorMsg());
$msorow=$maxresult->FetchRow();
$maxsortorder=$msorow['maxsortorder']+1;
$labelsoutput.= "\t<table width='100%'>\n" $labelsoutput.= "\t<table width='100%'>\n"
."<tr>\n" ."<tr>\n"
."\t<td colspan='4' class='header'><strong>\n" ."\t<td colspan='4' class='header'><strong>\n"
.$clang->gT("Labels") .$clang->gT("Labels")
."\t</strong></td>\n" ."\t</strong></td>\n"
."</tr>\n" ."</tr>\n"
."\t<tr><td colspan='4'>\n" ."<form method='post' action='admin.php'>\n" ."\t<tr><td colspan='4'>\n"
."<form method='post' action='admin.php' onsubmit=\"return codeCheck('code_',$maxsortorder,'".$clang->gT("Error: You are trying to use duplicate label codes.",'js')."');\">\n"
."<input type='hidden' name='sortorder' value='{$row['sortorder']}' />\n" ."<input type='hidden' name='sortorder' value='{$row['sortorder']}' />\n"
."<input type='hidden' name='lid' value='$lid' />\n" ."<input type='hidden' name='lid' value='$lid' />\n"
."<input type='hidden' name='action' value='modlabelsetanswers' />\n"; ."<input type='hidden' name='action' value='modlabelsetanswers' />\n";
$labelsoutput.= "<div class='tab-pane' id='tab-pane-1'>"; $labelsoutput.= "<div class='tab-pane' id='tab-pane-labels-{$lid}'>";
$first=true; $first=true;
$sortorderids=''; $codeids=''; $sortorderids=''; $codeids='';
foreach ($lslanguages as $lslanguage) foreach ($lslanguages as $lslanguage)
@@ -297,31 +312,40 @@ if($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $_SESSION['USER_RIGHT_MANAGE_LABEL
$labelcount = $result->RecordCount(); $labelcount = $result->RecordCount();
$labelsoutput.= "<div class='tab-page'>" $labelsoutput.= "<div class='tab-page'>"
."<h2 class='tab'>".getLanguageNameFromCode($lslanguage)."</h2>" ."<h2 class='tab'>".getLanguageNameFromCode($lslanguage)."</h2>"
."\t<table width='100%' class='form2columns'>\n" ."\t<table id='labels' class='answertable' align='center'>\n"
."<thead align='center'>" ."<thead align='center'>"
."<tr>\n" ."<tr>\n"
."\t<td width='25%' align='right' class='settingcaption'><strong>\n" ."\t<th align='right' class='settingcaption'>\n"
.$clang->gT("Code") .$clang->gT("Code")
."\t</strong></td>\n" ."\t</th>\n";
// ."\t<td width='35%' class='settingcaption'><strong>\n" $labelsoutput.="<th align='right' class='settingcaption'>".$clang->gT("Assessment value").'</th>';
."\t<td class='settingcaption'><strong>\n" $labelsoutput.="\t<th class='settingcaption'>\n"
.$clang->gT("Title") .$clang->gT("Title")
."\t</strong></td>\n" ."\t</th>\n"
// ."\t<td width='15%' class='settingcaption'><strong>\n" ."\t<th align='center' class='settingcaption'>\n"
."\t<td class='settingcaption'><strong>\n"
.$clang->gT("Action") .$clang->gT("Action")
."\t</strong></td>\n" ."\t</th>\n"
// ."\t<td width='25%' align='center' class='settingcaption'><strong>\n" ."\t<th align='center' class='settingcaption'>\n"
."\t<td align='center' class='settingcaption'><strong>\n"
.$clang->gT("Order") .$clang->gT("Order")
."\t</strong></td>\n" ."\t</th>\n"
."</tr></thead>" ."</tr></thead>"
."<tbody align='center'>"; ."<tbody align='center'>";
$alternate=false;
while ($row=$result->FetchRow()) while ($row=$result->FetchRow())
{ {
$sortorderids=$sortorderids.' '.$row['language'].'_'.$row['sortorder']; $sortorderids=$sortorderids.' '.$row['language'].'_'.$row['sortorder'];
if ($first) {$codeids=$codeids.' '.$row['sortorder'];} if ($first) {$codeids=$codeids.' '.$row['sortorder'];}
$labelsoutput.= "<tr><td align='right'>\n"; $labelsoutput.= "<tr style='white-space: nowrap;' ";
if ($alternate==true)
{
$labelsoutput.=' class="highlight" ';
$alternate=false;
}
else
{
$alternate=true;
}
$labelsoutput.="><td align='right'>\n";
if ($activeuse > 0) if ($activeuse > 0)
{ {
@@ -335,15 +359,30 @@ if($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $_SESSION['USER_RIGHT_MANAGE_LABEL
else else
{ {
$labelsoutput.= "\t<input type='hidden' name='oldcode_{$row['sortorder']}' value=\"{$row['code']}\" />\n"; $labelsoutput.= "\t<input type='hidden' name='oldcode_{$row['sortorder']}' value=\"{$row['code']}\" />\n";
$labelsoutput.= "\t<input type='text' name='code_{$row['sortorder']}' maxlength='5' size='10' value=\"{$row['code']}\" onkeypress=\"return catchenter(event,'saveallbtn');\" />\n"; $labelsoutput.= "\t<input type='text' id='code_{$row['sortorder']}' name='code_{$row['sortorder']}' maxlength='5' size='6' value=\"{$row['code']}\" onkeypress=\"return catchenter(event,'saveallbtn_$lslanguage');\" />\n";
} }
$labelsoutput.= "\t</td>\n" $labelsoutput.= "\t</td>\n"
."\t<td>\n" ."\t<td style='text-align:center;'>\n";
."\t<input type='text' name='title_{$row['language']}_{$row['sortorder']}' maxlength='3000' size='80' value=\"".html_escape($row['title'])."\" onkeypress=\"return catchenter(event,'saveallbtn');\"/>\n" if ($first)
. getEditor("editlabel", "title_{$row['language']}_{$row['sortorder']}", "[".$clang->gT("Label:", "js")."](".$row['language'].")",'','','',$action) {
$labelsoutput.= "\t<input type='text' id='assessmentvalue_{$row['sortorder']}' style='text-align: right;' name='assessmentvalue_{$row['sortorder']}' maxlength='5' size='6' value=\"{$row['assessment_value']}\" "
."onkeypress=\" if(event.keyCode==13) {if (event && event.preventDefault) event.preventDefault(); document.getElementById('saveallbtn_$lslanguage').click(); return false;} return goodchars(event,'1234567890-')\" />";
}
else
{
$labelsoutput.= $row['assessment_value'];
}
$labelsoutput.= "\t</td>\n"
."\t<td>\n"
."\t<input type='text' name='title_{$row['language']}_{$row['sortorder']}' maxlength='3000' size='80' value=\"".html_escape($row['title'])."\" onkeypress=\"return catchenter(event,'saveallbtn_$lslanguage');\"/>\n"
. getEditor("editlabel", "title_{$row['language']}_{$row['sortorder']}", "[".$clang->gT("Label:", "js")."](".$row['language'].")",'','','',$action)
."\t</td>\n" ."\t</td>\n"
."\t<td>\n"; ."\t<td style='text-align:center;'>\n";
if ($activeuse == 0) if ($activeuse == 0)
{ {
$labelsoutput.= "\t<input type='submit' name='method' value='".$clang->gT("Del")."' onclick=\"this.form.sortorder.value='{$row['sortorder']}'\" />\n"; $labelsoutput.= "\t<input type='submit' name='method' value='".$clang->gT("Del")."' onclick=\"this.form.sortorder.value='{$row['sortorder']}'\" />\n";
@@ -356,7 +395,7 @@ if($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $_SESSION['USER_RIGHT_MANAGE_LABEL
}; };
if ($position < $labelcount-1) if ($position < $labelcount-1)
{ {
// Fill the sortorder hiddenfield so we now what field is moved down // Fill the sortorder hiddenfield so we know what field is moved down
$labelsoutput.= "\t<input type='submit' name='method' value='".$clang->gT("Dn")."' onclick=\"this.form.sortorder.value='{$row['sortorder']}'\" />\n"; $labelsoutput.= "\t<input type='submit' name='method' value='".$clang->gT("Dn")."' onclick=\"this.form.sortorder.value='{$row['sortorder']}'\" />\n";
} }
$labelsoutput.= "\t</td></tr>\n"; $labelsoutput.= "\t</td></tr>\n";
@@ -364,24 +403,26 @@ if($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $_SESSION['USER_RIGHT_MANAGE_LABEL
} }
if ($labelcount>0) if ($labelcount>0)
{ {
$labelsoutput.= "\t<tr><td colspan='4'><center><input type='submit' name='method' value='".$clang->gT("Save All")."' id='saveallbtn' />" $labelsoutput.= "\t<tr><td colspan='5'><center><input type='submit' name='method' value='".$clang->gT("Save Changes")."' id='saveallbtn_$lslanguage' />"
."</center></td></tr>\n"; ."</center></td></tr>\n";
} }
$position=sprintf("%05d", $position); $position=sprintf("%05d", $position);
if (!isset($_SESSION['nextlabelcode'])) $_SESSION['nextlabelcode']='';
if ($activeuse == 0 && $first) if ($activeuse == 0 && $first)
{ $labelsoutput.= "<tr><td><br /></td></tr><tr><td align='right'>" { $labelsoutput.= "<tr><td><br /></td></tr><tr><td align='right'>"
."<strong>".$clang->gT("New label").":</strong> <input type='text' maxlength='5' name='insertcode' size='10' id='addnewlabelcode' onkeypress=\"return catchenter(event,'addnewlabelbtn');\" />\n" ."<strong>".$clang->gT("New label").":</strong> <input type='text' maxlength='5' name='insertcode' size='6' value='".$_SESSION['nextlabelcode']."' id='addnewlabelcode' onkeypress=\"return catchenter(event,'addnewlabelbtn');\" />\n"
."\t</td>\n" ."\t</td>\n"
."<td style='text-align:center;'>"
."<input style='text-align:right;' type='text' maxlength='5' name='insertassessmentvalue' size='6' id='insertassessmentvalue' value='0'"
."onkeypress=\" if(event.keyCode==13) {if (event && event.preventDefault) event.preventDefault(); document.getElementById('addnewlabelbtn').click(); return false;} return goodchars(event,'1234567890-')\" />"
."\t</td>\n"
."\t<td>\n" ."\t<td>\n"
."\t<input type='text' maxlength='3000' name='inserttitle' size='80' onkeypress=\"return catchenter(event,'addnewlabelbtn');\"/>\n" ."\t<input type='text' maxlength='3000' name='inserttitle' size='80' onkeypress=\"return catchenter(event,'addnewlabelbtn');\"/>\n"
. getEditor("addlabel", "inserttitle", "[".$clang->gT("Label:", "js")."](".$lslanguage.")",'','','',$action) . getEditor("addlabel", "inserttitle", "[".$clang->gT("Label:", "js")."](".$lslanguage.")",'','','',$action)
."\t</td>\n" ."\t</td>\n"
."\t<td>\n" ."\t<td colspan='2'>\n"
."\t<input type='submit' name='method' value='".$clang->gT("Add new label")."' id='addnewlabelbtn' />\n" ."\t<input type='submit' name='method' value='".$clang->gT("Add new label")."' id='addnewlabelbtn' />\n"
."\t</td>\n"
."\t<td>\n"
."<input type='button' onclick=\"document.getElementById('formfixorder').submit();\" value=\"".$clang->gT('Fix Order')."\">\n"
."<script type='text/javascript'>\n" ."<script type='text/javascript'>\n"
."<!--\n" ."<!--\n"
."document.getElementById('addnewlabelcode').focus();\n" ."document.getElementById('addnewlabelcode').focus();\n"
@@ -407,7 +448,7 @@ if($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $_SESSION['USER_RIGHT_MANAGE_LABEL
$labelsoutput.= "<tr>\n" $labelsoutput.= "<tr>\n"
."\t<td colspan='4' align='center'>\n" ."\t<td colspan='4' align='center'>\n"
."<font color='green' size='1'><i><strong>" ."<font color='green' size='1'><i><strong>"
.$clang->gT("Warning")."</strong>: ".$clang->gT("Inserting New labels must be done on the first language folder.")."</i></font>\n" .$clang->gT("Note: Inserting new labels must be done on the first language tab.")."</i></font>\n"
."\t</td>\n" ."\t</td>\n"
."</tr>\n"; ."</tr>\n";
} }
@@ -424,6 +465,7 @@ if($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $_SESSION['USER_RIGHT_MANAGE_LABEL
$labelsoutput .= "\t</center></td>\n" $labelsoutput .= "\t</center></td>\n"
."</tr>\n"; ."</tr>\n";
} }
unset($_SESSION['nextlabelcode']);
$first=false; $first=false;
$labelsoutput.="</tbody></table>\n"; $labelsoutput.="</tbody></table>\n";
@@ -450,16 +492,16 @@ if($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $_SESSION['USER_RIGHT_MANAGE_LABEL
$labelsoutput.= "<div class='tab-page'> <h2 class='tab'>".$clang->gT("Uploaded Resources Management")."</h2>\n" $labelsoutput.= "<div class='tab-page'> <h2 class='tab'>".$clang->gT("Uploaded Resources Management")."</h2>\n"
. "\t<form enctype='multipart/form-data' name='importlabelresources' action='$scriptname' method='post' onsubmit='return validatefilename(this,\"".$clang->gT('Please select a file to import!','js')."\");'>\n" . "\t<form enctype='multipart/form-data' name='importlabelresources' action='$scriptname' method='post' onsubmit='return validatefilename(this,\"".$clang->gT('Please select a file to import!','js')."\");'>\n"
. "\t<input type='hidden' name='lid' value='$lid'>\n" . "\t<input type='hidden' name='lid' value='$lid' />\n"
. "\t<input type='hidden' name='action' value='importlabelresources'>\n" . "\t<input type='hidden' name='action' value='importlabelresources' />\n"
. "\t<table width='100%' class='form2columns'>\n" . "\t<table width='100%' class='form2columns'>\n"
. "\t<tbody align='center'>" . "\t<tbody align='center'>"
. "\t\t<tr><td></td><td>\n" . "\t\t<tr><td></td><td>\n"
. "\t\t<input type='button' onclick='window.open(\"$fckeditordir/editor/filemanager/browser/default/browser.html?Connector=../../connectors/php/connector.php?\", \"_blank\")'/ value=\"".$clang->gT("Browse Uploaded Resources")."\" $disabledIfNoResources></td><td><td></tr>\n" . "\t\t<input type='button' onclick='window.open(\"$fckeditordir/editor/filemanager/browser/default/browser.html?Connector=../../connectors/php/connector.php?\", \"_blank\")' value=\"".$clang->gT("Browse Uploaded Resources")."\" $disabledIfNoResources /></td><td><td></tr>\n"
. "\t\t<tr><td></td><td><input type='button' onclick='window.open(\"$scriptname?action=exportlabelresources&amp;lid={$lid}\", \"_blank\")'/ value=\"".$clang->gT("Export Resources As ZIP Archive")."\" $disabledIfNoResources></td><td><td></tr>\n" . "\t\t<tr><td></td><td><input type='button' onclick='window.open(\"$scriptname?action=exportlabelresources&amp;lid={$lid}\", \"_blank\")' value=\"".$clang->gT("Export Resources As ZIP Archive")."\" $disabledIfNoResources /></td><td>&nbsp;</td></tr>\n"
. "\t\t<tr></tr>&nbsp;<tr><td>".$clang->gT("Select ZIP File:")."</td>\n" . "\t\t<tr><td>".$clang->gT("Select ZIP File:")."</td>\n"
. "\t\t<td><input name=\"the_file\" type=\"file\" size=\"50\" /></td><td></td></tr>\n" . "\t\t<td><input name=\"the_file\" type=\"file\" size=\"50\" /></td><td></td></tr>\n"
. "\t\t<tr><td></td><td><input type='button' value='".$clang->gT("Import Resources ZIP Archive")."' $ZIPimportAction/></td><td></td>\n" . "\t\t<tr><td></td><td><input type='button' value='".$clang->gT("Import Resources ZIP Archive")."' $ZIPimportAction /></td><td></td>\n"
. "\t\t</tr>\n" . "\t\t</tr>\n"
. "\t</tbody></table></form>\n"; . "\t</tbody></table></form>\n";
@@ -470,17 +512,7 @@ if($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $_SESSION['USER_RIGHT_MANAGE_LABEL
// Here starts the hidden Fix Sort order form // Here starts the hidden Fix Sort order form
$labelsoutput.= "</td></tr><tr><td colspan='4'>" $labelsoutput.= "</td></tr>\n";
."<form id='formfixorder' style='margin-bottom:0;' action='admin.php?action=labels' method='post'>"
."<table width='100%' style='border: solid; border-width: 0px; border-color: #555555' cellspacing='0'><tbody align='center'>\n"
."\t<tr><td width='80%'></td>"
// ."<td></td><td><input type='submit' name='method' value='"
."<td></td><td><input type='hidden' name='method' value='"
.$clang->gT("Fix Sort")."' /></td>\n"
."</tr></tbody></table>"
."\t<input type='hidden' name='lid' value='$lid' />\n"
."\t<input type='hidden' name='action' value='modlabelsetanswers' />\n"
."</form></td></tr>\n";
if ($totaluse > 0 && $activeuse == 0) //If there are surveys using this labelset, but none are active warn about modifying if ($totaluse > 0 && $activeuse == 0) //If there are surveys using this labelset, but none are active warn about modifying
{ {
$labelsoutput.= "<tr>\n" $labelsoutput.= "<tr>\n"
@@ -535,32 +567,32 @@ function updateset($lid)
$dellangidsarray=array_diff($oldlangidsarray,$newlanidarray); $dellangidsarray=array_diff($oldlangidsarray,$newlanidarray);
// If new languages are added, create labels' codes and sortorder for the new languages // 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"; $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); $result=db_execute_assoc($query);
if ($result) { while ($row=$result->FetchRow()) {$oldcodesarray[$row['code']]=$row['sortorder'];} } if ($result) { while ($row=$result->FetchRow()) {$oldcodesarray[$row['code']]=array('sortorder'=>$row['sortorder'],'assessment_value'=>$row['assessment_value']);} }
if (isset($oldcodesarray) && count($oldcodesarray) > 0 ) if (isset($oldcodesarray) && count($oldcodesarray) > 0 )
{ {
foreach ($addlangidsarray as $addedlangid) foreach ($addlangidsarray as $addedlangid)
{ {
foreach ($oldcodesarray as $oldcode => $oldsortorder) foreach ($oldcodesarray as $oldcode => $olddata)
{ {
$sqlvalues[]= " ($lid, '$oldcode', '$oldsortorder', '$addedlangid')"; $sqlvalues[]= " ($lid, '$oldcode', '{$olddata['sortorder']}', '$addedlangid', '{$olddata['assessment_value']}' )";
} }
} }
} }
if (isset($sqlvalues)) if (isset($sqlvalues))
{ {
if ($databasetype=='odbc_mssql') {@$connect->Execute("SET IDENTITY_INSERT ".db_table_name('labels')." ON");} 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) foreach ($sqlvalues as $sqlline)
{ {
$query = "INSERT INTO ".db_table_name('labels')." (lid,code,sortorder,language) VALUES ".($sqlline); $query = "INSERT INTO ".db_table_name('labels')." (lid,code,sortorder,language,assessment_value) VALUES ".($sqlline);
$result=db_execute_assoc($query); $result=db_execute_assoc($query);
if (!$result) if (!$result)
{ {
$labelsoutput.= "<script type=\"text/javascript\">\n<!--\n alert(\"".$clang->gT("Failed to Copy already defined labels to added languages","js")." - ".$query." - ".$connect->ErrorMsg()."\")\n //-->\n</script>\n"; $labelsoutput.= "<script type=\"text/javascript\">\n<!--\n alert(\"".$clang->gT("Failed to Copy already defined labels to added languages","js")." - ".$query." - ".$connect->ErrorMsg()."\")\n //-->\n</script>\n";
} }
} }
if ($databasetype=='odbc_mssql') {@$connect->Execute("SET IDENTITY_INSERT ".db_table_name('labels')." OFF");} 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 // If languages are removed, delete labels for these languages
@@ -663,6 +695,7 @@ function modlabelsetanswers($lid)
case $clang->gT("Add new label", "unescaped"): case $clang->gT("Add new label", "unescaped"):
if (isset($_POST['insertcode']) && $_POST['insertcode']!='') if (isset($_POST['insertcode']) && $_POST['insertcode']!='')
{ {
$_SESSION['nextlabelcode']=getNextCode($_POST['insertcode']);
$_POST['insertcode'] = db_quoteall($_POST['insertcode'],true); $_POST['insertcode'] = db_quoteall($_POST['insertcode'],true);
// check that the code doesn't exist yet // check that the code doesn't exist yet
$query = "SELECT code FROM ".db_table_name('labels')." WHERE lid='$lid' AND code=".$_POST['insertcode']; $query = "SELECT code FROM ".db_table_name('labels')." WHERE lid='$lid' AND code=".$_POST['insertcode'];
@@ -681,26 +714,23 @@ function modlabelsetanswers($lid)
} }
else else
{ {
$_POST['inserttitle'] = html_entity_decode_php4($_POST['inserttitle'], ENT_QUOTES, "UTF-8"); $_POST['inserttitle'] = html_entity_decode($_POST['inserttitle'], ENT_QUOTES, "UTF-8");
} }
// Fix bug with FCKEditor saving strange BR types // Fix bug with FCKEditor saving strange BR types
$_POST['inserttitle']=str_replace('<br type="_moz" />','',$_POST['inserttitle']); $_POST['inserttitle']=fix_FCKeditor_text($_POST['inserttitle']);
if ($_POST['inserttitle'] == "<br />")
{
$_POST['inserttitle']='';
}
$_POST['inserttitle'] = db_quoteall($_POST['inserttitle'],true); $_POST['inserttitle'] = db_quoteall($_POST['inserttitle'],true);
$_POST['insertassessmentvalue']=(int)$_POST['insertassessmentvalue'];
foreach ($lslanguages as $lslanguage) foreach ($lslanguages as $lslanguage)
{ {
if ($databasetype=='odbc_mssql') {@$connect->Execute("SET IDENTITY_INSERT ".db_table_name('labels')." ON");} 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) VALUES ($lid, {$_POST['insertcode']}, {$_POST['inserttitle']}, '$newsortorder','$lslanguage')"; $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)) if (!$result = $connect->Execute($query))
{ {
$labelsoutput.= "<script type=\"text/javascript\">\n<!--\n alert(\"".$clang->gT("Failed to insert label", "js")." - ".$query." - ".$connect->ErrorMsg()."\")\n //-->\n</script>\n"; $labelsoutput.= "<script type=\"text/javascript\">\n<!--\n alert(\"".$clang->gT("Failed to insert label", "js")." - ".$query." - ".$connect->ErrorMsg()."\")\n //-->\n</script>\n";
} }
if ($databasetype=='odbc_mssql') {@$connect->Execute("SET IDENTITY_INSERT ".db_table_name('labels')." OFF");} if ($connect->databaseType == 'odbc_mssql' || $connect->databaseType == 'odbtp' || $connect->databaseType == 'mssql_n') {@$connect->Execute('SET IDENTITY_INSERT '.db_table_name('labels')." OFF");}
} }
} }
else else
@@ -711,7 +741,7 @@ function modlabelsetanswers($lid)
break; break;
// Save all labels with one button // Save all labels with one button
case $clang->gT("Save All", "unescaped"): case $clang->gT("Save Changes", "unescaped"):
//Determine autoids by evaluating the hidden field //Determine autoids by evaluating the hidden field
$sortorderids=explode(' ', trim($_POST['sortorderids'])); $sortorderids=explode(' ', trim($_POST['sortorderids']));
$codeids=explode(' ', trim($_POST['codeids'])); $codeids=explode(' ', trim($_POST['codeids']));
@@ -721,7 +751,7 @@ function modlabelsetanswers($lid)
foreach ($codeids as $codeid) foreach ($codeids as $codeid)
{ {
$_POST['code_'.$codeid] = db_quoteall($_POST['code_'.$codeid],true); $_POST['code_'.$codeid] = db_quoteall($_POST['code_'.$codeid],true);
$_POST['oldcode_'.$codeid] = db_quoteall($_POST['oldcode_'.$codeid],true); if (isset($_POST['oldcode_'.$codeid])) $_POST['oldcode_'.$codeid] = db_quoteall($_POST['oldcode_'.$codeid],true);
// Get the code values to check for duplicates // Get the code values to check for duplicates
$codevalues[] = $_POST['code_'.$codeid]; $codevalues[] = $_POST['code_'.$codeid];
} }
@@ -745,19 +775,15 @@ function modlabelsetanswers($lid)
} }
else else
{ {
$_POST['title_'.$sortorderid] = html_entity_decode_php4($_POST['title_'.$sortorderid], ENT_QUOTES, "UTF-8"); $_POST['title_'.$sortorderid] = html_entity_decode($_POST['title_'.$sortorderid], ENT_QUOTES, "UTF-8");
} }
// Fix bug with FCKEditor saving strange BR types // Fix bug with FCKEditor saving strange BR types
$_POST['title_'.$sortorderid]=str_replace('<br type="_moz" />','',$_POST['title_'.$sortorderid]); $_POST['title_'.$sortorderid]=fix_FCKeditor_text($_POST['title_'.$sortorderid]);
if ($_POST['title_'.$sortorderid] == "<br />")
{
$_POST['title_'.$sortorderid]='';
}
$_POST['title_'.$sortorderid] = db_quoteall($_POST['title_'.$sortorderid],true); $_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'"; $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 (!$result = $connect->Execute($query))
// if update didn't work we assume the label does not exist and insert it // if update didn't work we assume the label does not exist and insert it
@@ -770,11 +796,12 @@ function modlabelsetanswers($lid)
} }
} }
update_labelcodes_in_conditions($lid,$_POST['oldcode_'.$codeids[$count]],$_POST['code_'.$codeids[$count]]); if (isset($_POST['oldcode_'.$codeids[$count]])) update_labelcodes_in_conditions($lid,$_POST['oldcode_'.$codeids[$count]],$_POST['code_'.$codeids[$count]]);
$count++; $count++;
if ($count>count($codeids)-1) {$count=0;} if ($count>count($codeids)-1) {$count=0;}
} }
fixorder($lid);
} }
else else
{ {
@@ -814,11 +841,7 @@ function modlabelsetanswers($lid)
{ {
$labelsoutput.= "<script type=\"text/javascript\">\n<!--\n alert(\"".$clang->gT("Failed to delete label","js")." - ".$query." - ".$connect->ErrorMsg()."\")\n //-->\n</script>\n"; $labelsoutput.= "<script type=\"text/javascript\">\n<!--\n alert(\"".$clang->gT("Failed to delete label","js")." - ".$query." - ".$connect->ErrorMsg()."\")\n //-->\n</script>\n";
} }
break; fixorder($lid);
// Fix Sortorder button
case $clang->gT("Fix Sort", "unescaped"):
fixorder($lid);
break; break;
} }
} }
@@ -848,15 +871,28 @@ function fixorder($lid) //Function rewrites the sortorder for a group of answers
function update_labelcodes_in_conditions($labelid,$oldcode,$newcode) function update_labelcodes_in_conditions($labelid,$oldcode,$newcode)
{ {
global $dbprefix, $connect; global $dbprefix, $databasetype, $connect;
if ($oldcode != $newcode) 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 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 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') )"; 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()); $result=$connect->Execute($query) or safe_die($connect->ErrorMsg());
//error_log("TIBO=$query");
} }
} }

View File

@@ -10,7 +10,7 @@
* other free or open source software licenses. * other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details. * See COPYRIGHT.php for copyright notices and details.
* *
* $Id: listcolumn.php 4973 2008-06-01 14:07:01Z c_schmitz $ * $Id: listcolumn.php 7212 2009-07-03 07:32:05Z c_schmitz $
*/ */
include_once("login_check.php"); include_once("login_check.php");
@@ -34,7 +34,7 @@ if (!$column)
exit; exit;
} }
if ($connect->databaseType == 'odbc_mssql') if ($connect->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 '')"; } { $query = "SELECT id, ".db_quote_id($column)." FROM {$dbprefix}survey_$surveyid WHERE (".db_quote_id($column)." NOT LIKE '')"; }
else else
{ $query = "SELECT id, ".db_quote_id($column)." FROM {$dbprefix}survey_$surveyid WHERE (".db_quote_id($column)." != '')"; } { $query = "SELECT id, ".db_quote_id($column)." FROM {$dbprefix}survey_$surveyid WHERE (".db_quote_id($column)." != '')"; }
@@ -44,7 +44,16 @@ if ($sql && $sql != "NULL")
$query .= " AND ".auto_unescape(urldecode($sql)); $query .= " AND ".auto_unescape(urldecode($sql));
} }
if (incompleteAnsFilterstate() === true) {$query .= " AND submitdate is not null";} 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") if ($order == "alpha")
{ {
@@ -53,17 +62,17 @@ if ($order == "alpha")
$result=db_execute_assoc($query) or safe_die("Error with query: ".$query."<br />".$connect->ErrorMsg()); $result=db_execute_assoc($query) or safe_die("Error with query: ".$query."<br />".$connect->ErrorMsg());
$listcolumnoutput= "<table width='98%' class='statisticstable' border='1' cellpadding='2' cellspacing='0'>\n"; $listcolumnoutput= "<table width='98%' class='statisticstable' border='1' cellpadding='2' cellspacing='0'>\n";
$listcolumnoutput.= "<tr><td><input type='image' src='$imagefiles/downarrow.png' align='middle' onclick=\"window.open('admin.php?action=listcolumn&amp;sid=$surveyid&amp;column=$column&amp;order=id', '_self')\" /></td>\n"; $listcolumnoutput.= "<thead><tr><th><input type='image' src='$imagefiles/downarrow.png' align='middle' onclick=\"window.open('admin.php?action=listcolumn&amp;sid=$surveyid&amp;column=$column&amp;order=id', '_self')\" /></th>\n";
$listcolumnoutput.= "<td valign='top'><input type='image' align='right' src='$imagefiles/close.gif' onclick='window.close()' />"; $listcolumnoutput.= "<th valign='top'><input type='image' align='right' src='$imagefiles/close.gif' onclick='window.close()' />";
if ($connect->databaseType != 'odbc_mssql') if ($connect->databaseType != 'odbc_mssql' && $connect->databaseType != 'odbtp' && $connect->databaseType != 'mssql_n')
{ $listcolumnoutput.= "<input type='image' src='$imagefiles/downarrow.png' align='left' onclick=\"window.open('admin.php?action=listcolumn&amp;sid=$surveyid&amp;column=$column&amp;order=alpha', '_self')\" />"; } { $listcolumnoutput.= "<input type='image' src='$imagefiles/downarrow.png' align='left' onclick=\"window.open('admin.php?action=listcolumn&amp;sid=$surveyid&amp;column=$column&amp;order=alpha', '_self')\" />"; }
$listcolumnoutput.= "</td></tr>\n"; $listcolumnoutput.= "</th></tr>\n";
while ($row=$result->FetchRow()) while ($row=$result->FetchRow())
{ {
$listcolumnoutput.= "<tr><td valign='top' align='center' >" $listcolumnoutput.= "<tr><td valign='top' align='center' >"
. "<a href='$scriptname?action=browse&amp;sid=$surveyid&amp;subaction=id&amp;id=".$row['id']."' target='home'>" . "<a href='$scriptname?action=browse&amp;sid=$surveyid&amp;subaction=id&amp;id=".$row['id']."' target='home'>"
. $row['id']."</a></td>" . $row['id']."</a></td>"
. "<td valign='top'>".$row[$column]."</td></tr>\n"; . "<td valign='top'>".htmlspecialchars($row[$column])."</td></tr>\n";
} }
$listcolumnoutput.= "</table>\n"; $listcolumnoutput.= "</table>\n";

View File

@@ -10,13 +10,118 @@
* other free or open source software licenses. * other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details. * See COPYRIGHT.php for copyright notices and details.
* *
* $Id: login_check.php 5039 2008-06-10 19:12:04Z c_schmitz $ * $Id: login_check.php 6871 2009-05-18 14:53:08Z c_schmitz $
*/ */
if (!isset($dbprefix) || isset($_REQUEST['dbprefix'])) {die("Cannot run this script directly");} if (!isset($dbprefix) || isset($_REQUEST['dbprefix'])) {die("Cannot run this script directly");}
if (!isset($action)) {$action=returnglobal('action');} if (!isset($action)) {$action=returnglobal('action');}
/*
* New feature since version 1.81: One time passwords
* The user can call the limesurvey login at /limesurvey/admin and pass username and
* a one time password which was previously written into the users table (column one_time_pw) by
* an external application.
* Furthermore there is a setting in config-defaults which has to be turned on (default = off)
* to enable the usage of one time passwords.
*/
//check if data was passed by URL
if(isset($_GET['user']) && isset($_GET['onepass']))
{
//take care of passed data
$user = sanitize_user($_GET['user']);
$pw = sanitize_paranoid_string(md5($_GET['onepass']));
//check if setting $use_one_time_passwords exists in config file
if(isset($use_one_time_passwords))
{
//$use_one_time_passwords switched OFF but data was passed by URL: Show error message
if($use_one_time_passwords === false)
{
//create an error message
$loginsummary = "<br />".$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: ")."<br />";
$loginsummary .= '<br /><em>$use_one_time_passwords = true;</em><br />';
$loginsummary .= "<br /><br /><a href='$scriptname'>".$clang->gT("Continue")."</a><br />&nbsp;\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."<br />".$connect->ErrorMsg());
if(!$result)
{
echo "<br />".$connect->ErrorMsg();
}
if ($result->RecordCount() < 1)
{
// wrong or unknown username
$loginsummary = sprintf($clang->gT("No one-time password found for user %s"),htmlspecialchars($user))."<br />";
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 = "<br />".sprintf($clang->gT("Passed one time password doesn't match one time password for user %s")," <em>".htmlspecialchars($user)."</em>")."<br />";
$loginsummary .= "<br /><br /><a href='$scriptname'>".$clang->gT("Continue")."</a><br />&nbsp;\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 // check data for login
if( isset($_POST['user']) && isset($_POST['password']) || if( isset($_POST['user']) && isset($_POST['password']) ||
($action == "forgotpass") || ($action == "login") || ($action == "forgotpass") || ($action == "login") ||
@@ -27,32 +132,39 @@ if( isset($_POST['user']) && isset($_POST['password']) ||
} }
// login form // login form
if(!isset($_SESSION['loginID']) && $action != "forgotpass" && ($action != "logout" || ($action == "logout" && !isset($_SESSION['loginID'])))) // && $action != "login") // added by Dennis if(!isset($_SESSION['loginID']) && $action != "forgotpass" && ($action != "logout" || ($action == "logout" && !isset($_SESSION['loginID'])))) // && $action != "login") // added by Dennis
{ {
if($action == "forgotpassword") if($action == "forgotpassword")
{ {
$loginsummary = "<form name='forgot' id='forgot' method='post' action='$rooturl/admin/admin.php' ><br /><strong>".$clang->gT("You have to enter user name and email.")."</strong><br /> <br /> $loginsummary = '
<table> <form name="forgot" id="forgot" method="post" action="'.$rooturl.'/admin/admin.php" >
<tr> <p><strong>'.$clang->gT('You have to enter user name and email.').'</strong></p>
<td><p>".$clang->gT("Username")."</p></td>
<td><input name='user' type='text' id='user' size='40' maxlength='40' value='' /></td> <table>
</tr> <tbody>
<tr> <tr>
<td><p>".$clang->gT("Email")."</p></td> <td><label for="user">'.$clang->gT('Username').'</label></td>
<td><input name='email' id='email' type='text' size='40' maxlength='40' value='' /></td> <td><input name="user" id="user" type="text" size="40" maxlength="40" value="" /></td>
</tr> </tr>
<tr> <tr>
<td>&nbsp;</td> <td><label for="email">'.$clang->gT('Email').'</label></td>
<td><input type='hidden' name='action' value='forgotpass' /> <td><input name="email" id="email" type="text" size="40" maxlength="40" value="" /></td>
<input class='action' type='submit' value='".$clang->gT("Check Data")."' /><br />&nbsp;\n</td> </tr>
</tr> <tr>
<tr> <td>&nbsp;</td>
<td>&nbsp;</td> <td><input type="hidden" name="action" value="forgotpass" />
<td><a href='$scriptname'>".$clang->gT("Main Admin Screen")."</a></td> <input class="action" type="submit" value="'.$clang->gT('Check Data').'" /></td>
</tr> </tr>
</table> <tr>
</form>"; <td>&nbsp;</td>
<td><a href="'.$scriptname.'">'.$clang->gT('Main Admin Screen').'</a></td>
</tr>
</table>
</form>
';
} }
elseif (!isset($loginsummary)) elseif (!isset($loginsummary))
{ // could be at login or after logout { // could be at login or after logout
@@ -63,11 +175,8 @@ if(!isset($_SESSION['loginID']) && $action != "forgotpass" && ($action != "logou
$refererargs = html_escape($_SERVER['QUERY_STRING']); $refererargs = html_escape($_SERVER['QUERY_STRING']);
} }
$hidden_loginlang = ''; $hidden_loginlang = "<input type='hidden' name='loginlang' id='loginlang' value='".$defaultlang."' />";
if (isset($_POST['lang']) && $_POST['lang'])
{
$hidden_loginlang = "<input type='hidden' name='loginlang' value='".sanitize_languagecode($_POST['lang'])."' />";
}
if (!isset($logoutsummary)) if (!isset($logoutsummary))
{ {
@@ -82,12 +191,24 @@ if(!isset($_SESSION['loginID']) && $action != "forgotpass" && ($action != "logou
<table> <table>
<tr> <tr>
<td>".$clang->gT("Username")."</td> <td>".$clang->gT("Username")."</td>
<td><input name='user' type='text' id='user' size='40' maxlength='40' value='' /></td> <td><input name='user' id='user' type='text' size='40' maxlength='40' value='' /></td>
</tr> </tr>
<tr> <tr>
<td>".$clang->gT("Password")."</td> <td>".$clang->gT("Password")."</td>
<td><input name='password' id='password' type='password' size='40' maxlength='40' /></td> <td><input name='password' id='password' type='password' size='40' maxlength='40' /></td>
</tr> </tr>
<tr>
<td>".$clang->gT("Language")."</td>
<td>
<select name='lang' style='width:216px;' onchange='loginlang.value=this.value;'>\n";
$loginsummary .='<option value="default">'.$clang->gT('Default').'</option>';
foreach (getlanguagedata() as $langkey=>$languagekind)
{
$loginsummary .= "\t\t\t\t<option value='$langkey'>".$languagekind['description']." - ".$languagekind['nativedescription']."</option>\n";
}
$loginsummary .= "\t\t\t</select>\n"
. "</td>
</tr>
<tr> <tr>
<td>&nbsp;</td> <td>&nbsp;</td>
<td align='center'><input type='hidden' name='action' value='login' /> <td align='center'><input type='hidden' name='action' value='login' />
@@ -97,37 +218,18 @@ if(!isset($_SESSION['loginID']) && $action != "forgotpass" && ($action != "logou
</tr> </tr>
<tr> <tr>
<td>&nbsp;</td> <td>&nbsp;</td>
<td><a href='$scriptname?action=forgotpassword'>".$clang->gT("Forgot Your Password?")."</a><br />&nbsp;\n</td> <td align='center'><a href='$scriptname?action=forgotpassword'>".$clang->gT("Forgot Your Password?")."</a><br />&nbsp;\n</td>
</tr> </tr>
</table> </table>
</form>"; </form><br />";
$loginsummary .= " <script type='text/javascript'>\n";
// Language selection $loginsummary .= " document.getElementById('user').focus();\n";
$loginsummary .= "\t<form name='language' id='language' method='post' action='$rooturl/admin/admin.php' >" $loginsummary .= " </script>\n";
. "\t<table><tr>\n"
. "\t\t<td align='center' >\n"
. "\t\t\t".$clang->gT("Current Language").":\n"
. "\t\t</td><td>\n"
. "\t\t\t<select name='lang' onchange='form.submit()'>\n";
foreach (getlanguagedata() as $langkey=>$languagekind)
{
$loginsummary .= "\t\t\t\t<option value='$langkey'";
if (isset($_SESSION['adminlang']) && $langkey == $_SESSION['adminlang']) {$loginsummary .= " selected='selected'";}
// in case it is a logout, session has already been killed
if (!isset($_SESSION['adminlang']) && $langkey == $clang->getlangcode() ){$loginsummary .= " selected='selected'";}
$loginsummary .= ">".$languagekind['description']." - ".$languagekind['nativedescription']."</option>\n";
}
$loginsummary .= "\t\t\t</select>\n"
. "\t\t\t<input type='hidden' name='action' value='changelang' />\n"
. "\t\t</td>\n"
. "\t</tr>\n"
. "</table>"
. "</form><br />";
} }
} }
if (isset($loginsummary)) { if (isset($loginsummary))
{
$adminoutput.= "<table width='100%' border='0' cellpadding='0' cellspacing='0'>\n" $adminoutput.= "<table width='100%' border='0' cellpadding='0' cellspacing='0'>\n"
."\t<tr>\n" ."\t<tr>\n"
."\t\t<td valign='top' align='center' bgcolor='#F8F8FF'>\n"; ."\t\t<td valign='top' align='center' bgcolor='#F8F8FF'>\n";

View File

@@ -0,0 +1,88 @@
<?php
/*
* LimeSurvey
* Copyright (C) 2007 The LimeSurvey Project Team / Carsten Schmitz
* All rights reserved.
* License: GNU/GPL License v2 or later, see LICENSE.php
* LimeSurvey is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details.
*
* $Id: $
*/
if (!isset($dbprefix) || isset($_REQUEST['dbprefix'])) {die("Cannot run this script directly");}
if (!isset($action)) {$action=returnglobal('action');}
//
// phpCAS simple client
//
if(!isset($_SESSION['CASauthenticated']) || (isset($_SESSION['CASauthenticated']) && $_SESSION['CASauthenticated']==FALSE) || isset($_REQUEST['action']))
{
// import phpCAS lib
include_once('classes/phpCAS/CAS.php');
phpCAS::setDebug();
// initialize phpCAS
phpCAS::client(CAS_VERSION_2_0, $casAuthServer, $casAuthPort, $casAuthUri, false);
// no SSL validation for the CAS server
phpCAS::setNoCasServerValidation();
//if($action=='logout')
if (isset($_REQUEST['action']) && $_REQUEST['action']=='logout')
{
session_destroy();
session_write_close();
phpCAS::logout();
//phpCAS::forceAuthentication();
}
//if ($action=='login')
if (isset($_REQUEST['action']) && $_REQUEST['action']=='login')
{
phpCAS::forceAuthentication();
}
// check CAS authentication
$auth = phpCAS::checkAuthentication();
$_SESSION['CASauthenticated'] = $auth;
if($auth)
{
/**
* User is authenticated from CAS, with this, he gets full Superadmin rights, when successful authenticates with CAS.
* This is very basic though, you should try to use what your CAS server provides you with (ROLES, rights, extra attibutes, etc.)
*
*/
$_SESSION['user'] = phpCAS::getUser();
$_SESSION['loginID'] = 1;
/**
* @var unknown_type
*/
$_SESSION['USER_RIGHT_CREATE_SURVEY'] = 1;
$_SESSION['USER_RIGHT_CONFIGURATOR'] = 1;
$_SESSION['USER_RIGHT_CREATE_USER'] = 1;
$_SESSION['USER_RIGHT_DELETE_USER'] = 1;
$_SESSION['USER_RIGHT_SUPERADMIN'] = 1;
$_SESSION['USER_RIGHT_MANAGE_TEMPLATE'] = 1;
$_SESSION['USER_RIGHT_MANAGE_LABEL'] = 1;
// Passwort notify for not changed Passwort have to be false when authing over CAS (or Warnings appear, because it is not set)
$_SESSION['pw_notify'] = false;
}
else
{
phpCAS::forceAuthentication();
}
// echo $auth;
// echo phpCAS::getUser();
// echo phpCAS::getVersion();
}
?>

View File

@@ -10,7 +10,7 @@
* other free or open source software licenses. * other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details. * See COPYRIGHT.php for copyright notices and details.
* *
* $Id: preview.php 4907 2008-05-24 10:21:08Z c_schmitz $ * $Id: preview.php 7389 2009-08-02 20:22:15Z c_schmitz $
*/ */
@@ -34,31 +34,56 @@ if (!isset($_GET['lang']) || $_GET['lang'] == "")
$_SESSION['s_lang'] = $language; $_SESSION['s_lang'] = $language;
$clang = new limesurvey_lang($language); $clang = new limesurvey_lang($language);
$thissurvey=getSurveyInfo($surveyid);
$qquery = 'SELECT * FROM '.db_table_name('questions')." WHERE sid='$surveyid' AND qid='$qid' AND language='{$language}'"; $qquery = 'SELECT * FROM '.db_table_name('questions')." WHERE sid='$surveyid' AND qid='$qid' AND language='{$language}'";
$qresult = db_execute_assoc($qquery); $qresult = db_execute_assoc($qquery);
$qrows = $qresult->FetchRow(); $qrows = $qresult->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']);
$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); $answers = retrieveAnswers($ia);
$thistpl="$publicdir/templates"; $thistpl="$templaterootdir/".$thissurvey['template'];
doHeader(); doHeader();
//echo "\t\t\t\t<div id='question'"; $dummy_js = '
echo "<!-- JAVASCRIPT FOR CONDITIONAL QUESTIONS --> <!-- JAVASCRIPT FOR CONDITIONAL QUESTIONS -->
<script type='text/javascript'> <script type="text/javascript">
<!-- <!--
function checkconditions(value, name, type) function checkconditions(value, name, type)
{ {
} }
//--> //-->
</script>"; </script>
echo "<form method='post' action='index.php' id='limesurvey' name='limesurvey'>\n"; <form method="post" action="index.php" id="limesurvey" name="limesurvey">
';
$question="<label for='$answers[0][7]'>" . $answers[0][0] . "</label>"; $question="<label for='$answers[0][7]'>" . $answers[0][0] . "</label>";
$answer=$answers[0][1]; $answer=$answers[0][1];
$help=$answers[0][2]; $help=$answers[0][2];
$questioncode=$answers[0][5]; $questioncode=$answers[0][5];
echo templatereplace(file_get_contents("$thistpl/preview.pstpl")); $content = templatereplace(file_get_contents("$thistpl/startpage.pstpl"));
echo "</form>\n"; $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 "</html>\n"; echo "</html>\n";

File diff suppressed because it is too large Load Diff

View File

@@ -10,7 +10,7 @@
* other free or open source software licenses. * other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details. * See COPYRIGHT.php for copyright notices and details.
* *
* $Id: questionhandling.php 5076 2008-06-15 13:01:16Z jcleeland $ * $Id: questionhandling.php 7446 2009-08-11 18:28:47Z c_schmitz $
*/ */
@@ -19,183 +19,6 @@ include_once("login_check.php");
if (isset($_POST['sortorder'])) {$postsortorder=sanitize_int($_POST['sortorder']);} if (isset($_POST['sortorder'])) {$postsortorder=sanitize_int($_POST['sortorder']);}
if ($action == "addquestion")
{
if (!isset($gid)) {$gid=returnglobal('gid');}
$newquestionoutput = PrepareEditorScript();
$newquestionoutput .= "\t<form action='$scriptname' name='addnewquestion1' method='post'onsubmit=\"return isEmpty(document.getElementById('title'), '".$clang->gT("Error: You have to enter a code for this question.","js")."')\">\n"
. "<table width='100%' border='0'>\n\n"
. "\t<tr>\n"
. "\t\t<td colspan='2' class='settingcaption'>"
. "\t\t<strong>".$clang->gT("Add Question")."\n"
. "\t\t</strong></td>\n"
. "\t</tr></table>\n";
$newquestionoutput .= "\t".'<div class="tab-pane" id="tab-pane-1">'."\n";
$newquestionoutput .= "\t".'<div class="tab-page"> <h2 class="tab">'.$clang->gT("Add Question")."</h2>\n";
$newquestionoutput .= "<table width='100%' border='0' class='form2columns'>"
. "\t<tr>\n"
. "\t\t<td align='right' width='35%'><strong>".$clang->gT("Code:")."</strong></td>\n"
. "\t\t<td align='left'><input type='text' maxlength='20' size='20' name='title' id='title' />"
. "<font color='red' face='verdana' size='1'> ".$clang->gT("Required")."</font></td></tr>\n"
. "\t<tr>\n"
. "\t\t<td align='right' width='35%'><strong>".$clang->gT("Question:")."</strong></td>\n"
. "\t\t<td align='left'><textarea cols='50' rows='3' name='question'></textarea>"
. getEditor("question-text","question", "[".$clang->gT("Question:", "js")."]",$surveyid,$gid,'',$action)
."</td>\n"
. "\t</tr>\n"
. "\t<tr>\n"
. "\t\t<td align='right' width='35%'><strong>".$clang->gT("Help:")."</strong></td>\n"
. "\t\t<td align='left'><textarea cols='50' rows='3' name='help'></textarea>"
. getEditor("question-help","help", "[".$clang->gT("Help:", "js")."]",$surveyid,$gid,'',$action)
."</td>\n"
. "\t</tr>\n"
. "\t<tr>\n"
. "\t\t<td align='right' width='35%'><strong>".$clang->gT("Type:")."</strong></td>\n"
. "\t\t<td align='left'><select name='type' id='question_type' "
. "onchange='OtherSelection(this.options[this.selectedIndex].value);'>\n"
. "$qtypeselect"
. "\t\t</select></td>\n"
. "\t</tr>\n";
$newquestionoutput .= "\t<tr id='Validation'>\n"
. "\t\t<td align='right'><strong>".$clang->gT("Validation:")."</strong></td>\n"
. "\t\t<td align='left'>\n"
. "\t\t<input type='text' name='preg' size='50' />\n"
. "\t\t</td>\n"
. "\t</tr>\n";
$newquestionoutput .= "\t<tr id='LabelSets' style='display: none'>\n"
. "\t\t<td align='right'><strong>".$clang->gT("Label Set:")."</strong></td>\n"
. "\t\t<td align='left'>\n"
. "\t\t<select name='lid' >\n";
$labelsets=getlabelsets(GetBaseLanguageFromSurveyID($surveyid));
if (count($labelsets)>0)
{
$newquestionoutput .= "\t\t\t<option value=''>".$clang->gT("Please Choose...")."</option>\n";
foreach ($labelsets as $lb)
{
$newquestionoutput .= "\t\t\t<option value='{$lb[0]}'>{$lb[1]}</option>\n";
}
}
$newquestionoutput .= "\t\t</select>\n";
$newquestionoutput .= "\t<tr id='LabelSets1' style='display: none'>\n"
. "\t\t<td align='right'><strong>".$clang->gT("Second Label Set:")."</strong></td>\n"
. "\t\t<td align='left'>\n"
. "\t\t<select name='lid1' >\n";
$labelsets1=getlabelsets(GetBaseLanguageFromSurveyID($surveyid));
if (count($labelsets1)>0)
{
$newquestionoutput .= "\t\t\t<option value=''>".$clang->gT("Please Choose...")."</option>\n";
foreach ($labelsets as $lb)
{
$newquestionoutput .= "\t\t\t<option value='{$lb[0]}'>{$lb[1]}</option>\n";
}
}
$newquestionoutput .= "\t\t</select>\n"
. "\t\t</td>\n"
. "\t</tr>\n";
$newquestionoutput .= "\t<tr id='OtherSelection' style='display: none'>\n"
. "\t\t<td align='right'><strong>".$clang->gT("Other:")."</strong></td>\n"
. "\t\t<td align='left'>\n"
. "\t\t\t<label for='OY'>".$clang->gT("Yes")."</label>"
. "<input id='OY' type='radio' class='radiobtn' name='other' value='Y' />&nbsp;&nbsp;\n"
. "\t\t\t<label for='ON'>".$clang->gT("No")."</label>"
. "<input id='ON' type='radio' class='radiobtn' name='other' value='N' checked='checked' />\n"
. "\t\t</td>\n"
. "\t</tr>\n";
$newquestionoutput .= "\t<tr id='MandatorySelection'>\n"
. "\t\t<td align='right'><strong>".$clang->gT("Mandatory:")."</strong></td>\n"
. "\t\t<td align='left'>\n"
. "\t\t\t<label for='MY'>".$clang->gT("Yes")."</label>"
. "<input id='MY' type='radio' class='radiobtn' name='mandatory' value='Y' />&nbsp;&nbsp;\n"
. "\t\t\t<label for='MN'>".$clang->gT("No")."</label>"
. "<input id='MN' type='radio' class='radiobtn' name='mandatory' value='N' checked='checked' />\n"
. "\t\t</td>\n"
. "\t</tr>\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<tr id='questionposition'>\n"
. "\t\t<td align='right'><strong>".$clang->gT("Position:")."</strong></td>\n"
. "\t\t<td align='left'>\n"
. "\t\t\t<select name='questionposition'>\n"
. "\t\t\t\t<option value=''>".$clang->gT("At end")."</option>\n"
. "\t\t\t\t<option value='-1'>".$clang->gT("At beginning")."</option>\n";
while ($oq = $oqresult->FetchRow())
{
$newquestionoutput .= "<option value='".$oq['question_order']."'>".$clang->gT("After").": ".$oq['title']."</option>\n";
}
$newquestionoutput .= "\t\t\t</select>\n"
. "\t\t</td>\n"
. "\t</tr>\n";
}
else
{$newquestionoutput .= "<tr><td><input type='hidden' name='questionposition' value='' /></tr></td>";}
//Question attributes
$qattributes=questionAttributes();
$newquestionoutput .= "\t<tr id='QTattributes'>
<td align='right'><strong>".$clang->gT("Question Attributes:")."</strong></td>
<td align='left'><select id='QTlist' name='attribute_name' >
</select>
<input type='text' id='QTtext' name='attribute_value' maxlength='20' /></td></tr>\n";
$newquestionoutput .= "\t<tr>\n"
. "\t\t<td align='right'></td><td align='left'>";
if (isset($eqrow)) {$newquestionoutput .= questionjavascript($eqrow['type'], $qattributes);}
else {$newquestionoutput .= questionjavascript('', $qattributes);}
$newquestionoutput .= "<input type='submit' value='"
. $clang->gT("Add Question")."' />\n"
. "\t\n"
. "\t<input type='hidden' name='action' value='insertnewquestion' />\n"
. "\t<input type='hidden' name='sid' value='$surveyid' />\n"
. "\t<input type='hidden' name='gid' value='$gid' />\n"
. "</td></tr></table>\n"
. "</div>\n" // End TAB
. "\t</form>\n";
// Import TAB
$newquestionoutput .='<div class="tab-page"> <h2 class="tab">'.$clang->gT("Import Question")."</h2>\n";
$newquestionoutput .= ""
. "\t<form enctype='multipart/form-data' name='importquestion' action='$scriptname' method='post' onsubmit='return validatefilename(this,\"".$clang->gT('Please select a file to import!','js')."\");'>\n"
. "<table width='100%' border='0' >\n\t"
. "\t<tr>"
. "\t\t<td align='right' width='35%'><strong>".$clang->gT("Select CSV File").":</strong></td>\n"
. "\t\t<td align='left'><input name=\"the_file\" type=\"file\" size=\"50\" /></td></tr>\n"
. "\t\t<tr>\t\t<td align='right' width='35%'>".$clang->gT("Convert Resources links ?")."</td>\n"
. "\t\t<td><input name=\"translinksfields\" type=\"checkbox\" /></td></tr>\n"
. "\t<tr><td colspan='2' align='center'><input type='submit' "
. "value='".$clang->gT("Import Question")."' />\n"
. "\t<input type='hidden' name='action' value='importquestion' />\n"
. "\t<input type='hidden' name='sid' value='$surveyid' />\n"
. "\t<input type='hidden' name='gid' value='$gid' />\n"
. "\t</td></tr></table></form>\n\n"
."<script type='text/javascript'>\n"
."<!--\n"
."document.getElementById('title').focus();\n"
."//-->\n"
."</script>\n";
$newquestionoutput .='</div>';
}
if ($action == "copyquestion") if ($action == "copyquestion")
{ {
$questlangs = GetAdditionalLanguagesFromSurveyID($surveyid); $questlangs = GetAdditionalLanguagesFromSurveyID($surveyid);
@@ -206,7 +29,7 @@ if ($action == "copyquestion")
$editquestion .= "<table width='100%' border='0' class='form2columns'>\n\t<tr><th>" $editquestion .= "<table width='100%' border='0' class='form2columns'>\n\t<tr><th>"
. "\t\t".$clang->gT("Copy Question")."</th></tr></table>\n" . "\t\t".$clang->gT("Copy Question")."</th></tr></table>\n"
. "<form name='frmeditquestion' action='$scriptname' method='post'>\n" . "<form name='frmeditquestion' action='$scriptname' method='post'>\n"
. '<div class="tab-pane" id="tab-pane-1">'; . '<div class="tab-pane" id="tab-pane-copyquestion">';
foreach ($questlangs as $language) 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); $egquery = "SELECT * FROM ".db_table_name('questions')." WHERE sid=$surveyid AND gid=$gid AND qid=$qid and language=".db_quoteall($language);
@@ -218,7 +41,7 @@ if ($action == "copyquestion")
{ {
$editquestion .= "(".$clang->gT("Base Language").")</h2>" $editquestion .= "(".$clang->gT("Base Language").")</h2>"
. "\t<div class='settingrow'><span class='settingcaption'>".$clang->gT("Code:")."</span>\n" . "\t<div class='settingrow'><span class='settingcaption'>".$clang->gT("Code:")."</span>\n"
. "\t\t<span class='settingentry'><input type='text' size='20' maxlength='20' name='title' value='' /> ".$clang->gT("Note: You MUST enter a new question code!")."\n" . "\t\t<span class='settingentry'><input type='text' size='20' maxlength='20' id='title' name='title' value='' /> ".$clang->gT("Note: You MUST enter a new question code!")."\n"
. "\t</span></div>\n"; . "\t</span></div>\n";
} }
else { else {
@@ -293,14 +116,14 @@ if ($action == "copyquestion")
. "\t\t</td>\n" . "\t\t</td>\n"
. "\t</tr>\n" . "\t</tr>\n"
. "\t<tr>\n" . "\t<tr>\n"
. "\t\t<td ><strong>".$clang->gT("Group:")."</strong></td>\n" . "\t\t<td ><strong>".$clang->gT("Question group:")."</strong></td>\n"
. "\t\t<td><select name='gid'>\n" . "\t\t<td><select name='gid'>\n"
. getgrouplist3($eqrow['gid']) . getgrouplist3($eqrow['gid'])
. "\t\t\t</select></td>\n" . "\t\t\t</select></td>\n"
. "\t</tr>\n"; . "\t</tr>\n";
$editquestion .= "\t<tr id='OtherSelection' style='display: none'>\n" $editquestion .= "\t<tr id='OtherSelection' style='display: none'>\n"
. "\t\t<td><strong>".$clang->gT("Other:")."</strong></td>\n"; . "\t\t<td><strong>".$clang->gT("Option 'Other':")."</strong></td>\n";
$editquestion .= "\t\t<td>\n" $editquestion .= "\t\t<td>\n"
. "\t\t\t".$clang->gT("Yes")." <input type='radio' class='radiobtn' name='other' value='Y'"; . "\t\t\t".$clang->gT("Yes")." <input type='radio' class='radiobtn' name='other' value='Y'";
@@ -362,58 +185,79 @@ if ($action == "copyquestion")
} }
} }
if ($action == "editquestion" || $action == "editattribute" || $action == "delattribute" || $action == "addattribute") if ($action == "editquestion" || $action == "editattribute" || $action == "delattribute" || $action == "addattribute" || $action=="addquestion")
{ {
$adding=($action=="addquestion");
$questlangs = GetAdditionalLanguagesFromSurveyID($surveyid); $questlangs = GetAdditionalLanguagesFromSurveyID($surveyid);
$baselang = GetBaseLanguageFromSurveyID($surveyid); $baselang = GetBaseLanguageFromSurveyID($surveyid);
$questlangs[] = $baselang; $questlangs[] = $baselang;
$questlangs = array_flip($questlangs); $questlangs = array_flip($questlangs);
$egquery = "SELECT * FROM ".db_table_name('questions')." WHERE sid=$surveyid AND gid=$gid AND qid=$qid"; if (!$adding)
$egresult = db_execute_assoc($egquery); {
while ($esrow = $egresult->FetchRow()) $egquery = "SELECT * FROM ".db_table_name('questions')." WHERE sid=$surveyid AND gid=$gid AND qid=$qid";
{ $egresult = db_execute_assoc($egquery);
if(!array_key_exists($esrow['language'], $questlangs)) // Language Exists, BUT ITS NOT ON THE SURVEY ANYMORE. while ($esrow = $egresult->FetchRow())
{ {
$egquery = "DELETE FROM ".db_table_name('questions')." WHERE sid='{$surveyid}' AND gid='{$gid}' AND qid='{$qid}' AND language='".$esrow['language']."'"; if(!array_key_exists($esrow['language'], $questlangs)) // Language Exists, BUT ITS NOT ON THE SURVEY ANYMORE.
$egresultD = $connect->Execute($egquery); {
} else { $egquery = "DELETE FROM ".db_table_name('questions')." WHERE sid='{$surveyid}' AND gid='{$gid}' AND qid='{$qid}' AND language='".$esrow['language']."'";
$questlangs[$esrow['language']] = 99; $egresultD = $connect->Execute($egquery);
} } else {
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']); $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}'"; while (list($key,$value) = each($questlangs))
$eqresult = db_execute_assoc($eqquery); {
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 = PrepareEditorScript();
$editquestion .= "<table width='100%' border='0'>\n\t<tr><td class='settingcaption'>" $editquestion .= "<table width='100%' border='0'>\n\t<tr><td class='settingcaption'>";
. "\t\t".$clang->gT("Edit Question")."</td></tr></table>\n" if (!$adding) {$editquestion .=$clang->gT("Edit question");} else {$editquestion .=$clang->gT("Add a new question");};
. "<form name='frmeditquestion' action='$scriptname' method='post'>\n" $editquestion .= "</td></tr></table>\n"
. '<div class="tab-pane" id="tab-pane-1">'; . "<form name='frmeditquestion' id='frmeditquestion' action='$scriptname' method='post' onsubmit=\"return isEmpty(document.getElementById('title'), '".$clang->gT("Error: You have to enter a question code.",'js')."');\">\n"
. '<div class="tab-pane" id="tab-pane-editquestion-'.$surveyid.'">';
$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
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 .= '<div class="tab-page"> <h2 class="tab">'.getLanguageNameFromCode($eqrow['language'],false); $editquestion .= '<div class="tab-page"> <h2 class="tab">'.getLanguageNameFromCode($eqrow['language'],false);
$editquestion .= '('.$clang->gT("Base Language").')'; $editquestion .= '('.$clang->gT("Base Language").')';
$eqrow = array_map('htmlspecialchars', $eqrow); $eqrow = array_map('htmlspecialchars', $eqrow);
$editquestion .= '</h2>'; $editquestion .= '</h2>';
$editquestion .= "\t<div class='settingrow'><span class='settingcaption'>".$clang->gT("Code:")."</span>\n" $editquestion .= "\t<div class='settingrow'><span class='settingcaption'>".$clang->gT("Code:")."</span>\n"
. "\t\t<span class='settingentry'><input type='text' size='20' maxlength='20' name='title' value=\"{$eqrow['title']}\" />\n" . "\t\t<span class='settingentry'><input type='text' size='20' maxlength='20' id='title' name='title' value=\"{$eqrow['title']}\" />\n"
. "\t</span></div>\n"; . "\t</span></div>\n";
$editquestion .= "\t<div class='settingrow'><span class='settingcaption'>".$clang->gT("Question:")."</span>\n" $editquestion .= "\t<div class='settingrow'><span class='settingcaption'>".$clang->gT("Question:")."</span>\n"
. "\t\t<span class='settingentry'><textarea cols='50' rows='4' name='question_{$eqrow['language']}'>{$eqrow['question']}</textarea>\n" . "\t\t<span class='settingentry'><textarea cols='50' rows='4' name='question_{$eqrow['language']}'>{$eqrow['question']}</textarea>\n"
@@ -428,31 +272,58 @@ if ($action == "editquestion" || $action == "editattribute" || $action == "delat
. "\t</span></div>\n"; . "\t</span></div>\n";
$editquestion .= '</div>'; $editquestion .= '</div>';
$aqquery = "SELECT * FROM {$dbprefix}questions WHERE sid=$surveyid AND gid=$gid AND qid=$qid AND language != '{$baselang}'";
$aqresult = db_execute_assoc($aqquery); if (!$adding)
while (!$aqresult->EOF) {
{ $aqquery = "SELECT * FROM {$dbprefix}questions WHERE sid=$surveyid AND gid=$gid AND qid=$qid AND language != '{$baselang}'";
$aqrow = $aqresult->FetchRow(); $aqresult = db_execute_assoc($aqquery);
$editquestion .= '<div class="tab-page"> <h2 class="tab">'.getLanguageNameFromCode($aqrow['language'],false); while (!$aqresult->EOF)
$aqrow = array_map('htmlspecialchars', $aqrow); {
$editquestion .= '</h2>'; $aqrow = $aqresult->FetchRow();
$editquestion .= "\t<div class='settingrow'><span class='settingcaption'>".$clang->gT("Question:")."</span>\n" $editquestion .= '<div class="tab-page"> <h2 class="tab">'.getLanguageNameFromCode($aqrow['language'],false);
. "\t\t<span class='settingentry'><textarea cols='50' rows='4' name='question_{$aqrow['language']}'>{$aqrow['question']}</textarea>\n" $aqrow = array_map('htmlspecialchars', $aqrow);
. getEditor("question-text","question_".$aqrow['language'], "[".$clang->gT("Question:", "js")."](".$aqrow['language'].")",$surveyid,$gid,$qid,$action) $editquestion .= '</h2>';
. "\t</span></div>\n" $editquestion .= "\t<div class='settingrow'><span class='settingcaption'>".$clang->gT("Question:")."</span>\n"
. "\t<div class='settingrow'><span class='settingcaption'>".$clang->gT("Help:")."</span>\n" . "\t\t<span class='settingentry'><textarea cols='50' rows='4' name='question_{$aqrow['language']}'>{$aqrow['question']}</textarea>\n"
. "\t\t<span class='settingentry'><textarea cols='50' rows='4' name='help_{$aqrow['language']}'>{$aqrow['help']}</textarea>\n" . getEditor("question-text","question_".$aqrow['language'], "[".$clang->gT("Question:", "js")."](".$aqrow['language'].")",$surveyid,$gid,$qid,$action)
. getEditor("question-help","help_".$aqrow['language'], "[".$clang->gT("Help:", "js")."](".$aqrow['language'].")",$surveyid,$gid,$qid,$action) . "\t</span></div>\n"
. "\t</span></div>\n" . "\t<div class='settingrow'><span class='settingcaption'>".$clang->gT("Help:")."</span>\n"
. "\t<div class='settingrow'><span class='settingcaption'>&nbsp;</span>\n" . "\t\t<span class='settingentry'><textarea cols='50' rows='4' name='help_{$aqrow['language']}'>{$aqrow['help']}</textarea>\n"
. "\t\t<span class='settingentry'>&nbsp;\n" . getEditor("question-help","help_".$aqrow['language'], "[".$clang->gT("Help:", "js")."](".$aqrow['language'].")",$surveyid,$gid,$qid,$action)
. "\t</span></div>\n"; . "\t</span></div>\n"
$editquestion .= '</div><br />'; . "\t<div class='settingrow'><span class='settingcaption'>&nbsp;</span>\n"
. "\t\t<span class='settingentry'>&nbsp;\n"
. "\t</span></div>\n";
$editquestion .= '</div><br />';
}
} }
else
{
$addlanguages=GetAdditionalLanguagesFromSurveyID($surveyid);
foreach ($addlanguages as $addlanguage)
{
$editquestion .= '<div class="tab-page"> <h2 class="tab">'.getLanguageNameFromCode($addlanguage,false);
$editquestion .= '</h2>';
$editquestion .= "\t<div class='settingrow'><span class='settingcaption'>".$clang->gT("Question:")."</span>\n"
. "\t\t<span class='settingentry'><textarea cols='50' rows='4' name='question_{$addlanguage}'></textarea>\n"
. getEditor("question-text","question_".$addlanguage, "[".$clang->gT("Question:", "js")."](".$addlanguage.")",$surveyid,$gid,$qid,$action)
. "\t</span></div>\n"
. "\t<div class='settingrow'><span class='settingcaption'>".$clang->gT("Help:")."</span>\n"
. "\t\t<span class='settingentry'><textarea cols='50' rows='4' name='help_{$addlanguage}'></textarea>\n"
. getEditor("question-help","help_".$addlanguage, "[".$clang->gT("Help:", "js")."](".$addlanguage.")",$surveyid,$gid,$qid,$action)
. "\t</span></div>\n"
. "\t<div class='settingrow'><span class='settingcaption'>&nbsp;</span>\n"
. "\t\t<span class='settingentry'>&nbsp;\n"
. "\t</span></div>\n";
$editquestion .= '</div>';
}
}
//question type: //question type:
$editquestion .= "\t<table><tr>\n" $editquestion .= "\t<div id='questionbottom'><table><tr>\n"
. "\t\t<td align='right'><strong>".$clang->gT("Question Type:")."</strong></td>\n"; . "\t\t<td align='right'><strong>".$clang->gT("Question Type:")."</strong></td>\n";
if ($activated != "Y") if ($activated != "Y")
{ {
@@ -473,7 +344,11 @@ if ($action == "editquestion" || $action == "editattribute" || $action == "delat
. "\t\t<td align='right'><strong>".$clang->gT("Label Set:")."</strong></td>\n" . "\t\t<td align='right'><strong>".$clang->gT("Label Set:")."</strong></td>\n"
. "\t\t<td align='left'>\n"; . "\t\t<td align='left'>\n";
$qattributes=questionAttributes(); if (!$adding) {$qattributes=questionAttributes();}
else
{
$qattributes=array();
}
if ($activated != "Y") if ($activated != "Y")
{ {
$editquestion .= "\t\t<select name='lid' >\n"; $editquestion .= "\t\t<select name='lid' >\n";
@@ -523,16 +398,33 @@ if ($action == "editquestion" || $action == "editattribute" || $action == "delat
. "<input type='hidden' name='lid1' value=\"{$eqrow['lid1']}\" />\n"; . "<input type='hidden' name='lid1' value=\"{$eqrow['lid1']}\" />\n";
} }
$editquestion .= "\t\t</td>\n" if ($activated != "Y")
. "\t</tr>\n" {
. "\t<tr>\n" $editquestion .= "\t\t</td>\n"
. "\t<td align='right'><strong>".$clang->gT("Group:")."</strong></td>\n" . "\t</tr>\n"
. "\t\t<td align='left'><select name='gid'>\n" . "\t<tr>\n"
. getgrouplist3($eqrow['gid']) . "\t<td align='right'><strong>".$clang->gT("Question group:")."</strong></td>\n"
. "\t\t</select></td>\n" . "\t\t<td align='left'><select name='gid'>\n"
. "\t</tr>\n"; . getgrouplist3($eqrow['gid'])
$editquestion .= "\t<tr id='OtherSelection'>\n" . "\t\t</select></td>\n"
. "\t\t<td align='right'><strong>".$clang->gT("Other:")."</strong></td>\n"; . "\t</tr>\n";
$editquestion .= "\t<tr id='OtherSelection'>\n"
. "\t\t<td align='right'><strong>".$clang->gT("Option 'Other':")."</strong></td>\n";
}
else
{
$editquestion .= "\t\t</td>\n"
. "\t</tr>\n"
. "\t<tr>\n"
. "\t<td align='right'><strong>".$clang->gT("Question group:")."</strong></td>\n"
. "\t\t<td align='left'>\n"
. getgrouplist4($eqrow['gid'])
. "\t<input type='hidden' name='gid' value='{$eqrow['gid']}' />"
. "\t\t</td>\n"
. "\t</tr>\n";
$editquestion .= "\t<tr id='OtherSelection'>\n"
. "\t\t<td align='right'><strong>".$clang->gT("Option 'Other':")."</strong></td>\n";
}
if ($activated != "Y") if ($activated != "Y")
{ {
@@ -572,62 +464,144 @@ if ($action == "editquestion" || $action == "editattribute" || $action == "delat
. "\t</tr>\n"; . "\t</tr>\n";
$editquestion .= "\t<tr><td align='center' colspan='2'><input type='submit' value='".$clang->gT("Update Question")."' />\n" if ($adding)
. "\t<input type='hidden' name='action' value='updatequestion' />\n" {
. "\t<input type='hidden' name='sid' value='$surveyid' />\n"
. "\t<input type='hidden' name='qid' value='$qid' /></td></tr></table></div></form>\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())
{
// select questionposition
$editquestion .= "\t<tr id='questionposition'>\n"
. "\t\t<td align='right'><strong>".$clang->gT("Position:")."</strong></td>\n"
. "\t\t<td align='left'>\n"
. "\t\t\t<select name='questionposition'>\n"
. "\t\t\t\t<option value=''>".$clang->gT("At end")."</option>\n"
. "\t\t\t\t<option value='0'>".$clang->gT("At beginning")."</option>\n";
while ($oq = $oqresult->FetchRow())
{
//Bug Fix: add 1 to question_order
$question_order_plus_one = $oq['question_order']+1;
$editquestion .= "<option value='".$question_order_plus_one."'>".$clang->gT("After").": ".$oq['title']."</option>\n";
}
$editquestion .= "\t\t\t</select>\n"
. "\t\t</td>\n"
. "\t</tr>\n";
}
else
{
$editquestion .= "<tr><td><input type='hidden' name='questionposition' value='' /></tr></td>";
}
$qattributes=questionAttributes();
$editquestion .= "\t<tr id='QTattributes'>
<td align='right'><strong><a name='qtattributes'>".$clang->gT("Question Attributes:")."</a></strong></td>
<td align='left'><select id='QTlist' name='attribute_name' >
</select>
<input type='text' id='QTtext' name='attribute_value' /></td></tr>\n";
$editquestion .= "\t<tr>\n"
. "\t\t<td align='right'></td><td align='left'>";
$editquestion .= "\t<tr><td align='center' colspan='2'><input type='submit' value='".$clang->gT("Add question")."' />\n"
. "\t<input type='hidden' name='action' value='insertnewquestion' /><br/><br/>&nbsp;\n";
}
else
{
$editquestion .= "\t<tr><td align='center' colspan='2'><input type='submit' value='".$clang->gT("Update Question")."' />\n"
. "\t<input type='hidden' name='action' value='updatequestion' />\n"
. "\t<input type='hidden' name='qid' value='$qid' />";
}
$editquestion .= "\t<input type='hidden' name='sid' value='$surveyid' />\n"
. "</td></tr></table></div></form>\n"
. "\t\n"; . "\t\n";
$qidattributes=getQuestionAttributes($qid); if (!$adding) {
$editquestion .= "\t\t\t<table id='QTattributes' width='40%' > $qidattributes=getQuestionAttributes($qid);
<tr> $editquestion .= "\t\t\t<table id='QTattributes' width='40%' >
<td colspan='2' align='center'> <tr>
<form action='$scriptname' method='post'><table class='attributetable'> <td colspan='2' align='center'>
<tr> <form action='$scriptname#qtattributes' method='post'><table class='attributetable'>
<th colspan='4'>".$clang->gT("Question Attributes:")."</th> <tr>
</tr> <th colspan='4'><a name='qtattributes'>".$clang->gT("Question Attributes:")."</a></th>
<tr><th colspan='4' height='5'></th></tr> </tr>
<tr> <tr><th colspan='4' height='5'></th></tr>
<td nowrap='nowrap' width='50%' ><select id='QTlist' name='attribute_name' > <tr>
</select></td><td align='center' width='20%'><input type='text' id='QTtext' name='attribute_value' maxlength='20' /></td> <td nowrap='nowrap' width='50%' ><select id='QTlist' name='attribute_name' >
<td align='center'><input type='submit' value='".$clang->gT("Add")."' /> </select></td><td align='center' width='20%'><input type='text' id='QTtext' name='attribute_value' /></td>
<input type='hidden' name='action' value='addattribute' /> <td align='center'><input type='submit' value='".$clang->gT("Add")."' />
<input type='hidden' name='sid' value='$surveyid' /> <input type='hidden' name='action' value='addattribute' />
<input type='hidden' name='qid' value='$qid' /> <input type='hidden' name='sid' value='$surveyid' />
<input type='hidden' name='gid' value='$gid' /></td></tr> <input type='hidden' name='qid' value='$qid' />
<tr><th colspan='4' height='10'></th></tr>\n"; <input type='hidden' name='gid' value='$gid' /></td></tr>
$editquestion .= "\t\t\t</table></form>\n"; <tr><th colspan='4' height='10'></th></tr>\n";
$editquestion .= "\t\t\t</table></form>\n";
$attributetranslations=questionAttributes(true);
foreach ($qidattributes as $qa)
{
$editquestion .= "\t\t\t<table class='attributetable' width='90%' border='0' cellspacing='0'>"
."<tr><td width='85%'>"
."<form action='$scriptname#qtattributes' method='post'>"
."<table width='100%'><tr><td width='65%'><span title='".$attributetranslations[$qa['attribute']]['help']."'>"
.$attributetranslations[$qa['attribute']]['caption']."</span></td>
<td align='center' width='25%'><input type='text' name='attribute_value' value='"
.$qa['value']."' /></td>
<td ><input type='submit' value='"
.$clang->gT("Save")."' />
<input type='hidden' name='action' value='editattribute' />\n
<input type='hidden' name='sid' value='$surveyid' />\n
<input type='hidden' name='gid' value='$gid' />\n
<input type='hidden' name='qid' value='$qid' />\n
<input type='hidden' name='qaid' value='".$qa['qaid']."' />\n"
."\t\t\t</td></tr></table></form></td><td>
<form action='$scriptname#qtattributes' method='post'><table width='100%'><tr><td width='5%'>
<input type='submit' value='"
.$clang->gT("Delete")."' />"
. "\t<input type='hidden' name='action' value='delattribute' />\n"
. "\t<input type='hidden' name='sid' value='$surveyid' />\n"
. "\t<input type='hidden' name='qid' value='$qid' />\n"
. "\t<input type='hidden' name='gid' value='$gid' />\n"
. "\t<input type='hidden' name='qaid' value='".$qa['qaid']."' />\n"
. "</td></tr></table>\n"
. "</form>\n</table>";
}
}
if ($adding)
{
// Import dialogue
$editquestion .= "<table width='100%' border='0'>\n\t<tr><td class='settingcaption'>";
$editquestion .=$clang->gT("...or import a question");
$editquestion .= "</td></tr></table>\n"
. "\t<form enctype='multipart/form-data' id='importquestion' name='importquestion' action='$scriptname' method='post' onsubmit='return validatefilename(this,\"".$clang->gT('Please select a file to import!','js')."\");'>\n"
. "<table width='100%' border='0' >\n\t"
. "\t<tr>"
. "\t\t<td align='right' width='35%'><strong>".$clang->gT("Select CSV File").":</strong></td>\n"
. "\t\t<td align='left'><input name=\"the_file\" type=\"file\" size=\"50\" /></td></tr>\n"
. "\t\t<tr>\t\t<td align='right' width='35%'>".$clang->gT("Convert resources links?")."</td>\n"
. "\t\t<td><input name='translinksfields' type='checkbox' checked='checked'/></td></tr>\n"
. "\t<tr><td colspan='2' align='center'><input type='submit' "
. "value='".$clang->gT("Import Question")."' />\n"
. "\t<input type='hidden' name='action' value='importquestion' />\n"
. "\t<input type='hidden' name='sid' value='$surveyid' />\n"
. "\t<input type='hidden' name='gid' value='$gid' />\n"
. "\t</td></tr></table></form>\n\n"
."<script type='text/javascript'>\n"
."<!--\n"
."document.getElementById('title').focus();\n"
."//-->\n"
."</script>\n";
}
else
{
$editquestion .= "</td></tr></table><div>";
}
foreach ($qidattributes as $qa)
{
$editquestion .= "\t\t\t<table class='attributetable' width='90%' border='0' cellspacing='0'>"
."<tr><td width='85%'>"
."<form action='$scriptname' method='post'>"
."<table width='100%'><tr><td width='65%'>"
.$qa['attribute']."</td>
<td align='center' width='25%'><input type='text' name='attribute_value' value='"
.$qa['value']."' maxlength='20' /></td>
<td ><input type='submit' value='"
.$clang->gT("Save")."' />
<input type='hidden' name='action' value='editattribute' />\n
<input type='hidden' name='sid' value='$surveyid' />\n
<input type='hidden' name='gid' value='$gid' />\n
<input type='hidden' name='qid' value='$qid' />\n
<input type='hidden' name='qaid' value='".$qa['qaid']."' />\n"
."\t\t\t</td></tr></table></form></td><td>
<form action='$scriptname' method='post'><table width='100%'><tr><td width='5%'>
<input type='submit' value='"
.$clang->gT("Delete")."' />"
. "\t<input type='hidden' name='action' value='delattribute' />\n"
. "\t<input type='hidden' name='sid' value='$surveyid' />\n"
. "\t<input type='hidden' name='qid' value='$qid' />\n"
. "\t<input type='hidden' name='gid' value='$gid' />\n"
. "\t<input type='hidden' name='qaid' value='".$qa['qaid']."' />\n"
. "</td></tr></table>\n"
. "</form>\n</table>";
}
$editquestion .= "</td></tr></table>";
$editquestion .= questionjavascript($eqrow['type'], $qattributes); $editquestion .= questionjavascript($eqrow['type'], $qattributes);
} }
@@ -703,64 +677,64 @@ if($action == "orderquestions")
. "\t\t".$clang->gT("Change Question Order")."</td></tr>" . "\t\t".$clang->gT("Change Question Order")."</td></tr>"
. "</table>\n"; . "</table>\n";
$questioncount = $oqresult->RecordCount(); $questioncount = $oqresult->RecordCount();
$oqarray = $oqresult->GetArray(); $oqarray = $oqresult->GetArray();
$minioqarray=$oqarray; $minioqarray=$oqarray;
// Get the condition dependecy array for all questions in this array and group // Get the condition dependecy array for all questions in this array and group
$questdepsarray = GetQuestDepsForConditions($surveyid,$gid); $questdepsarray = GetQuestDepsForConditions($surveyid,$gid);
if (!is_null($questdepsarray)) if (!is_null($questdepsarray))
{ {
$orderquestions .= "<ul><li class='movableNode'><strong><font color='orange'>".$clang->gT("Warning").":</font> ".$clang->gT("Current group is using conditional questions")."</strong><br /><br /><i>".$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")."</i></strong><br /><br/>".$clang->gT("See the conditions marked on the following questions").":<ul>\n"; $orderquestions .= "<ul><li class='movableNode'><strong><font color='orange'>".$clang->gT("Warning").":</font> ".$clang->gT("Current group is using conditional questions")."</strong><br /><br /><i>".$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")."</i></strong><br /><br/>".$clang->gT("See the conditions marked on the following questions").":<ul>\n";
foreach ($questdepsarray as $depqid => $depquestrow) foreach ($questdepsarray as $depqid => $depquestrow)
{ {
foreach ($depquestrow as $targqid => $targcid) foreach ($depquestrow as $targqid => $targcid)
{ {
$listcid=implode("-",$targcid); $listcid=implode("-",$targcid);
$question=arraySearchByKey($depqid, $oqarray, "qid", 1); $question=arraySearchByKey($depqid, $oqarray, "qid", 1);
$orderquestions .= "<li><a href='#' onclick=\"window.open('admin.php?sid=".$surveyid."&amp;gid=".$gid."&amp;qid=".$depqid."&amp;action=conditions&amp;markcid=".$listcid."')\">".$question['title'].": ".$question['question']. " [QID: ".$depqid."] </a> "; $orderquestions .= "<li><a href='#' onclick=\"window.open('admin.php?sid=".$surveyid."&amp;gid=".$gid."&amp;qid=".$depqid."&amp;action=conditions&amp;markcid=".$listcid."','_top')\">".$question['title'].": ".$question['question']. " [QID: ".$depqid."] </a> ";
} }
$orderquestions .= "</li>\n"; $orderquestions .= "</li>\n";
} }
$orderquestions .= "</ul></li></ul>"; $orderquestions .= "</ul></li></ul>";
} }
$orderquestions .= "<form method='post' action=''><ul class='movableList'>"; $orderquestions .= "<form method='post' action=''><ul class='movableList'>";
for($i=0; $i < $questioncount ; $i++) //Assumes that all question orders start with 0 for($i=0; $i < $questioncount ; $i++) //Assumes that all question orders start with 0
{ {
$downdisabled = ""; $downdisabled = "";
$updisabled = ""; $updisabled = "";
//Check if question is relied on as a condition dependency by the next question, and if so, don't allow moving down //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 && if ( !is_null($questdepsarray) && $i < $questioncount-1 &&
array_key_exists($oqarray[$i+1]['qid'],$questdepsarray) && array_key_exists($oqarray[$i+1]['qid'],$questdepsarray) &&
array_key_exists($oqarray[$i]['qid'],$questdepsarray[$oqarray[$i+1]['qid']]) ) array_key_exists($oqarray[$i]['qid'],$questdepsarray[$oqarray[$i+1]['qid']]) )
{ {
$downdisabled = "disabled=\"true\" class=\"disabledbtn\""; $downdisabled = "disabled=\"true\" class=\"disabledbtn\"";
} }
//Check if question has a condition dependency on the preceding question, and if so, don't allow moving up //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 && if ( !is_null($questdepsarray) && $i !=0 &&
array_key_exists($oqarray[$i]['qid'],$questdepsarray) && array_key_exists($oqarray[$i]['qid'],$questdepsarray) &&
array_key_exists($oqarray[$i-1]['qid'],$questdepsarray[$oqarray[$i]['qid']]) ) array_key_exists($oqarray[$i-1]['qid'],$questdepsarray[$oqarray[$i]['qid']]) )
{ {
$updisabled = "disabled=\"true\" class=\"disabledbtn\""; $updisabled = "disabled=\"true\" class=\"disabledbtn\"";
} }
//Move to location //Move to location
$orderquestions.="<li class='movableNode'>\n" ; $orderquestions.="<li class='movableNode'>\n" ;
$orderquestions.="\t<select style='float:right; margin-left: 5px;"; $orderquestions.="\t<select style='float:right; margin-left: 5px;";
$orderquestions.="' name='questionmovetomethod$i' onchange=\"this.form.questionmovefrom.value='".$oqarray[$i]['question_order']."';this.form.questionmoveto.value=this.value;submit()\">\n"; $orderquestions.="' name='questionmovetomethod$i' onchange=\"this.form.questionmovefrom.value='".$oqarray[$i]['question_order']."';this.form.questionmoveto.value=this.value;submit()\">\n";
$orderquestions.="<option value=''>".$clang->gT("Place after..")."</option>\n"; $orderquestions.="<option value=''>".$clang->gT("Place after..")."</option>\n";
//Display the "position at beginning" item //Display the "position at beginning" item
if(!is_null($questdepsarray) && $i != 0 && if(empty($questdepsarray) || (!is_null($questdepsarray) && $i != 0 &&
!array_key_exists($oqarray[$i]['qid'], $questdepsarray)) !array_key_exists($oqarray[$i]['qid'], $questdepsarray)))
{ {
$orderquestions.="<option value='-1'>".$clang->gT("At beginning")."</option>\n"; $orderquestions.="<option value='-1'>".$clang->gT("At beginning")."</option>\n";
} }
//Find out if there are any dependencies //Find out if there are any dependencies
$max_start_order=0; $max_start_order=0;
if ( !is_null($questdepsarray) && $i!=0 && if ( !is_null($questdepsarray) && $i!=0 &&
array_key_exists($oqarray[$i]['qid'], $questdepsarray)) //This should find out if there are any dependencies array_key_exists($oqarray[$i]['qid'], $questdepsarray)) //This should find out if there are any dependencies
{ {
foreach($questdepsarray[$oqarray[$i]['qid']] as $key=>$val) { foreach($questdepsarray[$oqarray[$i]['qid']] as $key=>$val) {
@@ -773,57 +747,56 @@ for($i=0; $i < $questioncount ; $i++) //Assumes that all question orders start w
} }
} }
} }
//Find out if any questions use this as a dependency //Find out if any questions use this as a dependency
$max_end_order=$questioncount+1; $max_end_order=$questioncount+1;
if ( !is_null($questdepsarray)) if ( !is_null($questdepsarray))
{
//There doesn't seem to be any choice but to go through the questdepsarray one at a time
//to find which question has a dependence on this one
foreach($questdepsarray as $qdarray)
{ {
if (array_key_exists($oqarray[$i]['qid'], $qdarray)) //There doesn't seem to be any choice but to go through the questdepsarray one at a time
//to find which question has a dependence on this one
foreach($questdepsarray as $qdarray)
{ {
$cqidquery = "SELECT question_order if (array_key_exists($oqarray[$i]['qid'], $qdarray))
{
$cqidquery = "SELECT question_order
FROM ".db_table_name('conditions').", ".db_table_name('questions')." FROM ".db_table_name('conditions').", ".db_table_name('questions')."
WHERE ".db_table_name('conditions').".qid=".db_table_name('questions').".qid WHERE ".db_table_name('conditions').".qid=".db_table_name('questions').".qid
AND cid=".$qdarray[$oqarray[$i]['qid']][0]; AND cid=".$qdarray[$oqarray[$i]['qid']][0];
$cqidresult = db_execute_assoc($cqidquery); $cqidresult = db_execute_assoc($cqidquery);
$cqidrow = $cqidresult->FetchRow(); $cqidrow = $cqidresult->FetchRow();
$max_end_order=$cqidrow['question_order']; $max_end_order=$cqidrow['question_order'];
} }
}
} }
} $minipos=$minioqarray[0]['question_order']; //Start at the very first question_order
$minipos=$minioqarray[0]['question_order']; //Start at the very first question_order foreach($minioqarray as $mo)
foreach($minioqarray as $mo) {
{ if($minipos >= $max_start_order && $minipos < $max_end_order)
if($minipos >= $max_start_order && $minipos < $max_end_order) {
{ $orderquestions.="<option value='".$mo['question_order']."'>".$mo['title']."</option>\n";
$orderquestions.="<option value='".$mo['question_order']."'>".$mo['title']."</option>\n"; }
} $minipos++;
$minipos++; }
} $orderquestions.="</select>\n";
$orderquestions.="</select>\n";
$orderquestions.= "\t<input style='float:right;"; $orderquestions.= "\t<input style='float:right;";
if ($i == 0) {$orderquestions.="visibility:hidden;";} if ($i == 0) {$orderquestions.="visibility:hidden;";}
$orderquestions.="' type='submit' name='questionordermethod' value='".$clang->gT("Up")."' onclick=\"this.form.sortorder.value='{$oqarray[$i]['question_order']}'\" ".$updisabled."/>\n"; $orderquestions.="' type='submit' name='questionordermethod' value='".$clang->gT("Up")."' onclick=\"this.form.sortorder.value='{$oqarray[$i]['question_order']}'\" ".$updisabled."/>\n";
if ($i < $questioncount-1) if ($i < $questioncount-1)
{ {
// Fill the sortorder hiddenfield so we know what field is moved down // Fill the sortorder hiddenfield so we know what field is moved down
$orderquestions.= "\t<input type='submit' style='float:right;' name='questionordermethod' value='".$clang->gT("Dn")."' onclick=\"this.form.sortorder.value='{$oqarray[$i]['question_order']}'\" ".$downdisabled."/>\n"; $orderquestions.= "\t<input type='submit' style='float:right;' name='questionordermethod' value='".$clang->gT("Dn")."' onclick=\"this.form.sortorder.value='{$oqarray[$i]['question_order']}'\" ".$downdisabled."/>\n";
}
$orderquestions.= "<a href='admin.php?sid=$surveyid&amp;gid=$gid&amp;qid={$oqarray[$i]['qid']}' title='".$clang->gT("View Question")."'>".$oqarray[$i]['title']."</a>: ".$oqarray[$i]['question'];
$orderquestions.= "</li>\n" ;
} }
$orderquestions.= "<a href='admin.php?sid=$surveyid&amp;gid=$gid&amp;qid={$oqarray[$i]['qid']}' title='".$clang->gT("View Question")."'>".$oqarray[$i]['title']."</a>: ".$oqarray[$i]['question'];
$orderquestions.= "</li>\n" ;
}
$orderquestions.="</ul>\n" $orderquestions.="</ul>\n"
. "<input type='hidden' name='questionmovefrom' />\n" . "<input type='hidden' name='questionmovefrom' />\n"
. "<input type='hidden' name='questionmoveto' />\n" . "<input type='hidden' name='questionmoveto' />\n"
. "\t<input type='hidden' name='sortorder' />" . "\t<input type='hidden' name='sortorder' />"
. "\t<input type='hidden' name='action' value='orderquestions' />" . "\t<input type='hidden' name='action' value='orderquestions' />"
. "</form>" ; . "</form>" ;
$orderquestions .="<br />" ; $orderquestions .="<br />" ;
} }
function questionjavascript($type, $qattributes) function questionjavascript($type, $qattributes)
@@ -834,12 +807,16 @@ function questionjavascript($type, $qattributes)
$jc=0; $jc=0;
$newquestionoutput .= "\t\t\tvar qtypes = new Array();\n"; $newquestionoutput .= "\t\t\tvar qtypes = new Array();\n";
$newquestionoutput .= "\t\t\tvar qnames = new Array();\n\n"; $newquestionoutput .= "\t\t\tvar qnames = new Array();\n\n";
$newquestionoutput .= "\t\t\tvar qhelp = new Array();\n\n";
$newquestionoutput .= "\t\t\tvar qcaption = new Array();\n\n";
foreach ($qattributes as $key=>$val) foreach ($qattributes as $key=>$val)
{ {
foreach ($val as $vl) foreach ($val as $vl)
{ {
$newquestionoutput .= "\t\t\tqtypes[$jc]='".$key."';\n"; $newquestionoutput .= "\t\t\tqtypes[$jc]='".$key."';\n";
$newquestionoutput .= "\t\t\tqnames[$jc]='".$vl['name']."';\n"; $newquestionoutput .= "\t\t\tqnames[$jc]='".$vl['name']."';\n";
$newquestionoutput .= "\t\t\tqhelp[$jc]='".javascript_escape($vl['help'],false,true)."';\n";
$newquestionoutput .= "\t\t\tqcaption[$jc]='".javascript_escape($vl['caption'],false,true)."';\n";
$jc++; $jc++;
} }
} }
@@ -855,7 +832,7 @@ function questionjavascript($type, $qattributes)
if (qtypes[i] == type) if (qtypes[i] == type)
{ {
document.getElementById('QTattributes').style.display=''; document.getElementById('QTattributes').style.display='';
document.getElementById('QTlist').options[document.getElementById('QTlist').options.length] = new Option(qnames[i], qnames[i]); document.getElementById('QTlist').options[document.getElementById('QTlist').options.length] = new Option(qcaption[i]+' - '+qnames[i], qnames[i]);
} }
} }
}"; }";
@@ -879,7 +856,7 @@ function questionjavascript($type, $qattributes)
. "\t\tdocument.getElementById('Validation').style.display = 'none';\n" . "\t\tdocument.getElementById('Validation').style.display = 'none';\n"
. "\t\tdocument.getElementById('MandatorySelection').style.display='';\n" . "\t\tdocument.getElementById('MandatorySelection').style.display='';\n"
. "\t\t}\n" . "\t\t}\n"
. "\telse if (QuestionType == 'F' || QuestionType == 'H')\n" . "\telse if (QuestionType == 'F' || QuestionType == 'H' || QuestionType == ':' || QuestionType == ';')\n"
. "\t\t{\n" . "\t\t{\n"
. "\t\tdocument.getElementById('LabelSets').style.display = '';\n" . "\t\tdocument.getElementById('LabelSets').style.display = '';\n"
. "\t\tif (document.getElementById('LabelSets1')) {document.getElementById('LabelSets1').style.display = 'none';}\n" . "\t\tif (document.getElementById('LabelSets1')) {document.getElementById('LabelSets1').style.display = 'none';}\n"

Some files were not shown because too many files have changed in this diff Show More