From 30e1507c091891bddb9963d330aa81170b791a28 Mon Sep 17 00:00:00 2001 From: Carsten Schmitz Date: Wed, 6 May 2009 15:20:40 +0000 Subject: [PATCH] Added feature #2923: Individual validity time for a token git-svn-id: file:///Users/Shitiz/Downloads/lssvn/source/limesurvey_dev@6786 b72ed6b6-b9f8-46b5-92b4-906544132732 --- admin/fck_LimeReplacementFields.php | 6 +- admin/install/upgrade-mysql.php | 24 +- admin/install/upgrade-odbc_mssql.php | 18 +- admin/install/upgrade-postgres.php | 17 + admin/styles/default/adminstyle.css | 5 + admin/tokens.php | 163 +++++-- classes/dateparser/dateparser-manual.txt | 38 ++ classes/dateparser/dateparser.php | 299 ++++++++++++ common.php | 584 +++++++++-------------- index.php | 46 +- 10 files changed, 777 insertions(+), 423 deletions(-) create mode 100644 classes/dateparser/dateparser-manual.txt create mode 100644 classes/dateparser/dateparser.php diff --git a/admin/fck_LimeReplacementFields.php b/admin/fck_LimeReplacementFields.php index aa2ffb4fa19..33f95359387 100644 --- a/admin/fck_LimeReplacementFields.php +++ b/admin/fck_LimeReplacementFields.php @@ -117,7 +117,7 @@ $replFields[]=array('TOKEN:FIRSTNAME',$clang->gT("Firstname from token")); $replFields[]=array('TOKEN:LASTNAME',$clang->gT("Lastname from token")); $replFields[]=array('TOKEN:EMAIL',$clang->gT("Email from the token")); - $attributes=GetTokenFieldsAndNames($surveyid); + $attributes=GetTokenFieldsAndNames($surveyid,true); foreach ($attributes as $attributefield=>$attributedescription) { $replFields[]=array('TOKEN:'.strtoupper($attributefield), sprintf($clang->gT("Token attribute: %s"),$attributedescription)); @@ -139,7 +139,7 @@ $replFields[]=array('LASTNAME',$clang->gT("Lastname from token")); $replFields[]=array('SURVEYNAME',$clang->gT("Name of the survey")); $replFields[]=array('SURVEYDESCRIPTION',$clang->gT("Description of the survey")); - $attributes=GetTokenFieldsAndNames($surveyid); + $attributes=GetTokenFieldsAndNames($surveyid,true); foreach ($attributes as $attributefield=>$attributedescription) { $replFields[]=array(strtoupper($attributefield), sprintf($clang->gT("Token attribute: %s"),$attributedescription)); @@ -158,7 +158,7 @@ $replFields[]=array('TOKEN:FIRSTNAME',$clang->gT("Firstname from token")); $replFields[]=array('TOKEN:LASTNAME',$clang->gT("Lastname from token")); $replFields[]=array('TOKEN:EMAIL',$clang->gT("Email from the token")); - $attributes=GetTokenFieldsAndNames($surveyid); + $attributes=GetTokenFieldsAndNames($surveyid,true); foreach ($attributes as $attributefield=>$attributedescription) { $replFields[]=array('TOKEN:'.strtoupper($attributefield), sprintf($clang->gT("Token attribute: %s"),$attributedescription)); diff --git a/admin/install/upgrade-mysql.php b/admin/install/upgrade-mysql.php index 457016284e9..a944b4a8a96 100644 --- a/admin/install/upgrade-mysql.php +++ b/admin/install/upgrade-mysql.php @@ -276,10 +276,10 @@ function db_upgrade($oldversion) { { // 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` 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) @@ -369,6 +369,8 @@ function upgrade_token_tables128() } + + function upgrade_survey_tables133() { $surveyidquery = "SELECT sid,additional_languages FROM ".db_table_name('surveys'); @@ -379,6 +381,24 @@ function upgrade_survey_tables133() } } + +// Add the reminders tracking fields +function upgrade_token_tables134() +{ + global $modifyoutput,$dbprefix; + $surveyidquery = "SHOW TABLES LIKE '".$dbprefix."tokens%'"; + $surveyidresult = db_execute_num($surveyidquery); + if (!$surveyidresult) {return "Database Error";} + else + { + while ( $sv = $surveyidresult->FetchRow() ) + { + modify_database("","ALTER TABLE ".$sv[0]." ADD `validfrom` Datetime"); echo $modifyoutput; flush(); + modify_database("","ALTER TABLE ".$sv[0]." ADD `validuntil` Datetime"); echo $modifyoutput; flush(); + } + } +} + function fix_mysql_collation() { global $connect, $modifyoutput, $dbprefix; diff --git a/admin/install/upgrade-odbc_mssql.php b/admin/install/upgrade-odbc_mssql.php index cd853181f7e..760a4f1b7f4 100644 --- a/admin/install/upgrade-odbc_mssql.php +++ b/admin/install/upgrade-odbc_mssql.php @@ -286,6 +286,7 @@ function db_upgrade($oldversion) { 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) @@ -348,7 +349,7 @@ function upgrade_token_tables125() $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(); + modify_database("","ALTER TABLE ".$sv." ADD [emailstatus] VARCHAR(300) DEFAULT 'OK'"); echo $modifyoutput; flush(); } } @@ -359,8 +360,8 @@ function upgrade_token_tables128() $tokentables=$connect->MetaTables('TABLES',false,$dbprefix."tokens%"); foreach ($tokentables as $sv) { - modify_database("","ALTER TABLE ".$sv." ADD COLUMN [remindersent] VARCHAR(17) DEFAULT 'OK'"); echo $modifyoutput; flush(); - modify_database("","ALTER TABLE ".$sv." ADD COLUMN [remindercount] int DEFAULT '0'"); echo $modifyoutput; flush(); + 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(); } } @@ -389,6 +390,17 @@ function upgrade_survey_tables133a() } +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; diff --git a/admin/install/upgrade-postgres.php b/admin/install/upgrade-postgres.php index becde929a57..aa91905ba2f 100644 --- a/admin/install/upgrade-postgres.php +++ b/admin/install/upgrade-postgres.php @@ -112,6 +112,7 @@ function db_upgrade($oldversion) { 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) @@ -168,4 +169,20 @@ function upgrade_survey_tables133() } } +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 ".$sv0." ADD validfrom datetime"); echo $modifyoutput; flush(); + modify_database("","ALTER TABLE ".$sv0." ADD validuntil datetime"); echo $modifyoutput; flush(); + } + } +} + ?> diff --git a/admin/styles/default/adminstyle.css b/admin/styles/default/adminstyle.css index d449ae422be..e55632cfb6b 100644 --- a/admin/styles/default/adminstyle.css +++ b/admin/styles/default/adminstyle.css @@ -520,3 +520,8 @@ font-size:12px; outline-color:#D2E0F2; padding: 2px 5px; } + +.annotation +{ + font-size:10px; +} \ No newline at end of file diff --git a/admin/tokens.php b/admin/tokens.php index a3cb4a6d6a5..e6675e6da94 100644 --- a/admin/tokens.php +++ b/admin/tokens.php @@ -116,7 +116,7 @@ $bresult = db_execute_assoc($bquery) or die ("$bquery
".htmlspecialchars($connect->ErrorMsg())); $bfieldcount=$bresult->FieldCount(); - $tokenoutput .= "tid,firstname,lastname,email,emailstatus,token,language code"; + $tokenoutput .= "tid,firstname,lastname,email,emailstatus,token,languagecode,validfrom,validuntil"; $attrfieldnames=GetAttributeFieldnames($surveyid); foreach ($attrfieldnames as $attr_name) { @@ -131,7 +131,9 @@ $tokenoutput .= '"'.trim($brow['email'])."\","; $tokenoutput .= '"'.trim($brow['emailstatus'])."\","; $tokenoutput .= '"'.trim($brow['token'])."\","; - $tokenoutput .= '"'.trim($brow['language'])."\""; + $tokenoutput .= '"'.trim($brow['language'])."\","; + $tokenoutput .= '"'.trim(convertDateTimeFormat($brow['validfrom'],'Y-m-d H:i:s','Y-m-d H:i'))."\","; + $tokenoutput .= '"'.trim(convertDateTimeFormat($brow['validuntil'],'Y-m-d H:i:s','Y-m-d H:i'))."\""; foreach ($attrfieldnames as $attr_name) { $tokenoutput .=',"'.trim($brow[$attr_name])."\""; @@ -635,7 +637,7 @@ $usresult = $connect->Execute($usquery) or safe_die("Error updating
".$usquery."

".$connect->ErrorMsg()); } } - $tokenoutput .= "
".$clang->gT("Token email settings have been saved.")."
 \n"; + $tokenoutput .= "
".$clang->gT("Token email settings have been saved.")."
 \n"; } @@ -650,7 +652,7 @@ { $query="DELETE FROM ".db_table_name("tokens_$surveyid"); $result=$connect->Execute($query) or safe_die ("Couldn't update sent field
$query
".$connect->ErrorMsg()); - $tokenoutput .= "".$clang->gT("All token entries have been deleted.")."\n"; + $tokenoutput .= "".$clang->gT("All token entries have been deleted.")."\n"; $subaction=""; } @@ -662,7 +664,7 @@ { $query="UPDATE ".db_table_name("tokens_$surveyid")." SET sent='N', remindersent='N', remindercount=0"; $result=$connect->Execute($query) or safe_die ("Couldn't update sent field
$query
".$connect->ErrorMsg()); - $tokenoutput .= "".$clang->gT("All invite entries have been set to 'Not invited'.")."\n"; + $tokenoutput .= "".$clang->gT("All invite entries have been set to 'Not invited'.")."\n"; $subaction=""; } @@ -674,7 +676,7 @@ { $query="UPDATE ".db_table_name("tokens_$surveyid")." SET token=''"; $result=$connect->Execute($query) or safe_die("Couldn't reset the tokens field
$query
".$connect->ErrorMsg()); - $tokenoutput .= "".$clang->gT("All unique token numbers have been removed.")."\n"; + $tokenoutput .= "".$clang->gT("All unique token numbers have been removed.")."\n"; $subaction=""; } @@ -842,7 +844,15 @@ ."\t\t" ."" ."".$clang->gT("Completed?")."\n"; + .$clang->gT("Sort by: ").$clang->gT("Completed?")."' border='0' align='left' />".$clang->gT("Completed?")."\n" + ."\t\t" + ."" + ."".$clang->gT("Valid from")."\n" + ."\t\t" + ."" + ."".$clang->gT("Valid until")."\n"; $attrfieldnames=GetTokenFieldsAndNames($surveyid,true); foreach ($attrfieldnames as $attr_name=>$attr_translation) @@ -854,29 +864,50 @@ } $tokenoutput .="\t\n"; + $tokenfieldorder=array('tid', + 'firstname', + 'lastname', + 'email', + 'emailstatus', + 'token', + 'language', + 'sent', + 'remindersent', + 'remindercount', + 'completed', + 'validfrom', + 'validuntil'); + foreach ($attrfieldnames as $attr_name=>$attr_translation) + { + $tokenfieldorder[]=$attr_name; + } + while ($brow = $bresult->FetchRow()) { $brow['token'] = trim($brow['token']); + if (trim($brow['validfrom'])!=''){ $brow['validfrom']= convertDateTimeFormat($brow['validfrom'],'Y-m-d H:i:s','Y-m-d H:i');}; + if (trim($brow['validuntil'])!=''){ $brow['validuntil']= convertDateTimeFormat($brow['validuntil'],'Y-m-d H:i:s','Y-m-d H:i');}; + if ($bgc == "evenrow") {$bgc = "oddrow";} else {$bgc = "evenrow";} $tokenoutput .= "\t\n"; - foreach ($brow as $a=>$b) + foreach ($tokenfieldorder as $tokenfieldname) { - if ($a=='mpid') continue; - if ($a =='email' && $brow['emailstatus'] != 'OK') + + if ($tokenfieldname =='email' && $brow['emailstatus'] != 'OK') { $tokenoutput .= "\t\t" ."gT('Invalid email address:','js').javascript_escape($brow['emailstatus'])."');return false;\" " - ."onmouseout=\"hideTooltip()\">$brow[$a]\n"; + ."onmouseout=\"hideTooltip()\">$brow[$tokenfieldname]\n"; } - elseif ($a != 'emailstatus') + elseif ($tokenfieldname != 'emailstatus') { - if ($a=='tid') {$tokenoutput.="".$brow[$a]."";} + if ($tokenfieldname=='tid') {$tokenoutput.="".$brow[$tokenfieldname]."";} else { - $tokenoutput .= "\t\t$brow[$a]\n"; + $tokenoutput .= "\t\t$brow[$tokenfieldname]\n"; } } - if ($a=='tid') + if ($tokenfieldname=='tid') { $tokenoutput .= "\t\t\n"; if ($sumrows5['edit_survey_property'] || @@ -888,6 +919,10 @@ $toklang = ($brow['language'] == '') ? $baselanguage : $brow['language']; $tokenoutput .= "\n"; } + else + { + $tokenoutput .= ""; + } $tokenoutput .="\t\t\t" ."".$clang->gT("Valid from").":\n" + + // TLR change to put date into sent and completed + // ."\t\n".$clang->gT('until') + + // TLR change to put date into sent and completed + // ."\t ".$clang->gT('Format: yyyy-mm-dd hh:mm').'' + ."\n" ."\n"; // now the attribute fieds @@ -1851,7 +1901,7 @@ { $tokenoutput .= "\t\t" ."".$attr_description.":\n" - ."\t" .""; @@ -1891,6 +1941,18 @@ $tokenoutput .= "\t" .$clang->gT("Add or Edit Token Entry")."\n" ."\t\n"; + if (trim($_POST['validfrom'])=='') { + $_POST['validfrom']=null; + } + else + { + $_POST['validfrom']=$connect->BindTimeStamp(convertDateTimeFormat(trim($_POST['validfrom']),'Y-m-d H:i','Y-m-d H:i:s')); + } + if (trim($_POST['validuntil'])=='') {$_POST['validuntil']=null;} + else + { + $_POST['validuntil']=$connect->BindTimeStamp(convertDateTimeFormat(trim($_POST['validuntil']),'Y-m-d H:i','Y-m-d H:i:s')); + } $data = array(); $data[] = $_POST['firstname']; $data[] = $_POST['lastname']; @@ -1901,6 +1963,9 @@ $data[] = sanitize_languagecode($_POST['language']); $data[] = $_POST['sent']; $data[] = $_POST['completed']; +// $db->DBTimeStamp("$year-$month-$day $hr:$min:$secs"); + $data[] = $_POST['validfrom']; + $data[] = $_POST['validuntil']; $udresult = $connect->Execute("Select * from ".db_table_name("tokens_$surveyid")." where tid<>{$tokenid} and token<>'' and token='{$santitizedtoken}'") or safe_die ("Update record {$tokenid} failed:
\n$udquery
\n".$connect->ErrorMsg()); if ($udresult->RecordCount()==0) @@ -1911,7 +1976,7 @@ // Using adodb Execute with blinding method so auto-dbquote is done $udquery = "UPDATE ".db_table_name("tokens_$surveyid")." SET firstname=?, " . "lastname=?, email=?, emailstatus=?, " - . "token=?, language=?, sent=?, completed=?"; + . "token=?, language=?, sent=?, completed=?, validfrom=?, validuntil=?"; $attrfieldnames=GetAttributeFieldnames($surveyid); foreach ($attrfieldnames as $attr_name) { @@ -1921,8 +1986,8 @@ $udquery .= " WHERE tid={$tokenid}"; $udresult = $connect->Execute($udquery, $data) or safe_die ("Update record {$tokenid} failed:
\n$udquery
\n".$connect->ErrorMsg()); - $tokenoutput .= "
".$clang->gT("Success")."
\n" - ."
".$clang->gT("Updated Token")."

\n" + $tokenoutput .= "
".$clang->gT("Success")."
\n" + ."
".$clang->gT("The token entry was successfully updated.")."

\n" ."".$clang->gT("Display Tokens")."

\n" ."\t\n"; } @@ -1967,7 +2032,7 @@ { // AutoExecute $inresult = $connect->AutoExecute($tblInsert, $data, 'INSERT') or safe_die ("Add new record failed:
\n$inquery
\n".$connect->ErrorMsg()); - $tokenoutput .= "
".$clang->gT("Success")."
\n" + $tokenoutput .= "
".$clang->gT("Success")."
\n" ."
".$clang->gT("Added New Token")."

\n" ."".$clang->gT("Display Tokens")."
\n" ."".$clang->gT("Add new token entry")."

\n" @@ -1999,7 +2064,7 @@ ."\t\t\n" ."\t\t\t".$clang->gT("Note:")."

\n" ."\t\t\t".$clang->gT("File should be a standard CSV (comma delimited) file with double quotes around values (default for openoffice and excel). The first line must contain the field names. The fields can be in any order.").'

'.$clang->gT("Mandatory fields:")." firstname,lastname,email
" - .''.$clang->gT('Optional fields:')." emailstatus, token, languagecode, attribute_1, attribute_2, attribute_3, ... ." + .''.$clang->gT('Optional fields:')." emailstatus, token, languagecode, validfrom, validuntil, attribute_1, attribute_2, attribute_3, ... ." ."\t\t
\n" ."\t\n" ."
\n" @@ -2058,9 +2123,9 @@ } else { - $tokenoutput .= "
".$clang->gT("Importing CSV File")."
\n".$clang->gT("Success")."

\n" + $tokenoutput .= "
".$clang->gT("Importing CSV File")."
\n".$clang->gT("Success")."

\n" .$clang->gT("Creating Token Entries")."
\n"; - $xz = 0; $xx = 0; $xy = 0; $xv = 0; $invalidemailcount = 0; + $xz = 0; $recordcount = 0; $duplicatecount = 0; $xv = 0; $invalidemailcount = 0; // This allows to read file with MAC line endings too @ini_set('auto_detect_line_endings', true); // open it and trim the ednings @@ -2071,10 +2136,10 @@ { $buffer=@mb_convert_encoding($buffer,"UTF-8",$uploadcharset); $firstname = ""; $lastname = ""; $email = ""; $emailstatus="OK"; $token = ""; $language=""; $attribute1=""; $attribute2=""; //Clear out values from the last path, in case the next line is missing a value - if ($xx==0) + if ($recordcount==0) { // Pick apart the first line - $allowedfieldnames=array('firstname','lastname','email','emailstatus','token','languagecode'); + $allowedfieldnames=array('firstname','lastname','email','emailstatus','token','languagecode', 'validfrom', 'validuntil'); $allowedfieldnames=array_merge($attrfieldnames,$allowedfieldnames); $firstline = convertCSVRowToArray($buffer,',','"'); $firstline=array_map('trim',$firstline); @@ -2105,7 +2170,7 @@ $dupfound=false; $invalidemail=false; - if ($filterduplicatetoken) + if ($filterduplicatetoken!=false) { $dupquery = "SELECT firstname, lastname from ".db_table_name("tokens_$surveyid")." where email=".db_quoteall($writearray['email'])." and firstname = ".db_quoteall($writearray['firstname'])." and lastname= ".db_quoteall($writearray['lastname']).""; $dupresult = $connect->Execute($dupquery); @@ -2135,7 +2200,7 @@ } elseif ($dupfound) { - ++$xy; + ++$duplicatecount; } else { @@ -2143,32 +2208,37 @@ if (!isset($writearray['token'])) $line[4] = ""; if (!isset($writearray['languagecode']) || $writearray['languagecode'] == "") $writearray['language'] = $baselanguage; else $writearray['language']=$writearray['languagecode']; + if (isset($writearray['validfrom']) && trim($writearray['validfrom']=='')){ unset($writearray['validfrom']);} + if (isset($writearray['validuntil']) && trim($writearray['validuntil']=='')){ unset($writearray['validuntil']);} + unset($writearray['languagecode']); $iq = "INSERT INTO ".db_table_name("tokens_$surveyid")." \n" . "(".implode(',',array_keys($writearray)).") \n" . "VALUES ('".implode("','",array_values($writearray))."')"; $ir = $connect->Execute($iq); - if (!$ir) $xy++; + if (!$ir) $duplicatecount++; $xz++; } $xv++; } - $xx++; + $recordcount++; } - $xx = $xx-1; + $recordcount = $recordcount-1; if ($xz != 0) { - $tokenoutput .= "".$clang->gT("Success")."

\n"; + $tokenoutput .= "".$clang->gT("Success")."

\n"; } else { $tokenoutput .= "".$clang->gT("Failed")."

\n"; } - $message = "$xx ".$clang->gT("Records in CSV").".
\n"; - $message .= "$xv ".$clang->gT("Records met minumum requirements").".
\n"; - $message .= "$xz ".$clang->gT("Records imported").".
\n"; + $message = sprintf($clang->gT("%s records in CSV"),$recordcount).".
\n"; + $message .= sprintf($clang->gT("%s records met minumum requirements"),$xv).".
\n"; + $message .= sprintf($clang->gT("%s records imported"),$xz).".
\n"; $message .= "\n"; - $message .= "$xy ".$clang->gT("Duplicate records removed"); - $message .= " [".$clang->gT("List")."]"; - $message .= ""; + } $message .= "
\n"; $message .= "$invalidemailcount ".$clang->gT("Records with invalid email address removed").".
\n"; $tokenoutput .= "$message
\n"; @@ -2238,7 +2309,7 @@ $resultnum=ldap_doTokenSearch($ds, $ldapq, $ResArray); $xz = 0; // imported token count $xv = 0; // meet minim requirement count - $xy = 0; // duplicate tokens skipped count + $duplicatecount = 0; // duplicate tokens skipped count $invalidemailcount = 0; if ($resultnum >= 1) { @@ -2332,7 +2403,7 @@ } elseif ($dupfound) { - ++$xy; + ++$duplicatecount; } elseif ($meetminirequirements===true) { @@ -2347,7 +2418,7 @@ if (!empty($myattr2)) {$iq .= ", '$myattr2'";} $iq .= ")"; $ir = $connect->Execute($iq); - if (!$ir) $xy++; + if (!$ir) $duplicatecount++; $xz++; // or safe_die ("Couldn't insert line
\n$buffer
\n".htmlspecialchars($connect->ErrorMsg())."
$iq
\n"); } @@ -2357,7 +2428,7 @@ if ($xz != 0) { - $tokenoutput .= "".$clang->gT("Success")."

\n"; + $tokenoutput .= "".$clang->gT("Success")."

\n"; } else { @@ -2366,7 +2437,7 @@ $message = "$resultnum ".$clang->gT("Results from LDAP Query").".
\n"; $message .= "$xv ".$clang->gT("Records met minumum requirements").".
\n"; $message .= "$xz ".$clang->gT("Records imported").".
\n"; - $message .= "$xy ".$clang->gT("Duplicate records removed").".
\n"; + $message .= "$duplicatecount ".$clang->gT("Duplicate records removed").".
\n"; $message .= "$invalidemailcount ".$clang->gT("Records with invalid email address removed").".
\n"; $tokenoutput .= "$message
\n"; } diff --git a/classes/dateparser/dateparser-manual.txt b/classes/dateparser/dateparser-manual.txt new file mode 100644 index 00000000000..9459e37dbd7 --- /dev/null +++ b/classes/dateparser/dateparser-manual.txt @@ -0,0 +1,38 @@ +$date = new dateparser(); + +Example usage : $date->parseDate("Y-m-d H:i:s","2008-4-24 20:28:34"); +Returns : array( "Year"=>2008, + "Month"=>4, + "Day"=>24, + "Hour"=>20, + "Minute"=>28, + "Second"=>34, + "Timezone"=>"+0300" + ); + + +======================================= + Other Functions : +======================================= + +$date->Compare($date1,$date2) +------------------------------- +$date1 and $date2 is date in array format which our first function creates. Returns 1 if first is newer,-1 if second is newer, 0 if they are the exactly same. + + +$date->dateDiff($pattern1,$date1,$pattern2,$date2); +--------------------------------------------------- +$date1 and $date2 are string dates and the $pattern1 $pattern2 is the identifier patterns of them. Produces a new array which contains the difference of year,month,day,hour,minute,second variables in date format. + + +$date->Format($patternTo,$patternFrom,$date); +--------------------------------------------- +returns a reformatted date value. for example; + +$date->Format("j F Y H:i","Y-m-d H:i:s","2008-04-29 09:44:32") + +returns "29 April 2008 09:44" + + +Function Localize and generatePattern are internal functions. Localize is not complete yet but I think you can complete it yourself. generatePattern generates RegExp pattern from date patterns for later usage in the parseDate function. All date types which supported in php.net are added to this script. + diff --git a/classes/dateparser/dateparser.php b/classes/dateparser/dateparser.php new file mode 100644 index 00000000000..bd527a7e15c --- /dev/null +++ b/classes/dateparser/dateparser.php @@ -0,0 +1,299 @@ +parseDate("Y-m-d H:i:s","2008-4-24 20:28:34"); + * Returns : array( "Year"=>2008, + * "Month"=>4, + * "Day"=>24, + * "Hour"=>20, + * "Minute"=>28, + * "Second"=>34, + * "Timezone"=>"+0300" + * ); + * + */ +class DateParser { + + var $date; + var $tempdate; + var $patrVal; + var $timezone; + var $days3 = array("Mon","Tue","Wed","Thu","Fri","Sat","Sun"); + var $days = array("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"); + var $month3 = array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"); + var $month = array("January","February","March","April","May","June","July","August","September","October","November","December"); + var $types=array( + "d"=>"([0-9]{2})", + "D"=>"([a-zA-z]{3})", + "j"=>"([0-9]{1,2})", + "l"=>"([A-Z][a-z]{4,7})", + "N"=>"([1-7])", + "S"=>"(st|nd|rd|th)", + "w"=>"([0-6])", + "z"=>"([0-9]{3})", + "W"=>"([0-9]{2})", + "F"=>"([A-Z][a-z]{2,8})", + "m"=>"([0-9]{2})", + "M"=>"([A-Za-z]{3})", + "n"=>"([0-9]{1,2})", + "t"=>"(28|29|30|31)", + "L"=>"(1|0)", + "o"=>"([0-9]{4})", + "Y"=>"([0-9]{4})", + "y"=>"([0-9]{2})", + "a"=>"(am|pm)", + "A"=>"(AM|PM)", + "B"=>"([0-9]{3})", + "g"=>"([1-12])", + "G"=>"([0-23])", + "h"=>"([0-9]{2})", + "H"=>"([0-9]{2})", + "i"=>"([0-9]{2})", + "s"=>"([0-9]{2})", + "u"=>"([0-9]{1,5})", + "e"=>"([A-Za-z0-9_]{3,})", + "I"=>"(1|0)", + "O"=>"(+[0-9]{4})", + "P"=>"(+[0-9]{2}:[0-9]{2})", + "T"=>"([A-Z]{1,4})", + "Z"=>"(-?[0-9]{1,5})", + "c"=>"(\d\d\d\d)(?:-?(\d\d)(?:-?(\d\d)(?:[T](\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(?:Z|(?:([-+])(\d\d)(?::?(\d\d))?)?)?)?)?)?", + "r"=>"([a-zA-Z]{2,}),\040(\d{1,})\040([a-zA-Z]{2,})\040([0-9]{4})\040([0-9]{2}):([0-9]{2}):([0-9]{2})\040([+-][0-9]{4})", + "U"=>"(\d+)" + ); + + private static $hrFormats=array( + "Y"=>"yyyy", + "j"=>"d[d]", + "n"=>"m[m]", + "d"=>"dd", + "m"=>"mm", + "H"=>"hh", + "i"=>"mm", + "s"=>"ss" + ); + + # 0-7 Day + # 8 Week + # 9-13 Month + # 14-17 Year + # 18-27 Time + # 28-33 Timezone + + /** + * Internal function which generates regex pattern from date pattern + * + * @param string $dateformat + * @return string + */ + function generatePattern($dateformat){ + $k=0; + $datearray = preg_split("//",$dateformat); + $patternkey = array(); + for($i=0;$itypes))){ + $patternkey[$i]=$this->types[$datearray[$i]]; + $this->patrVal[$k] = array_search($datearray[$i],array_keys($this->types)); + $k++; + }else{$patternkey[$i]=$datearray[$i];} + } + $patternkey = implode("",$patternkey); + return "/".$patternkey."/"; + } + /** + * Converts the string date to array by using the pattern generated by generatePattern() function + * + * @param string $dateformat + * @param string $date + * @param boolean $localize + * @return array + */ + function parseDate($dateformat,$date,$localize=false){ + $newdate=""; + $dateformat = str_replace(array("\\","\t"),array("@","@t"),$dateformat); + $pattern = $this->generatePattern($dateformat); + preg_match_all($pattern,$date,$newdate); + $newdate = array_slice($newdate,1); + if($this->patrVal[0]==34){ + $resultvar = array("Year"=>$newdate[0], + "Year"=>$newdate[0][0], + "Month"=>$newdate[1][0], + "Day"=>$newdate[2][0], + "Hour"=>$newdate[3][0], + "Minute"=>$newdate[4][0], + "Second"=>$newdate[5][0], + "Timezone"=>$newdate[6][0].$newdate[7][0].$newdate[8][0]); + }elseif($this->patrVal[0]==35){ + $resultvar = array("Year"=>$newdate[0], + "Year"=>$newdate[3][0], + "Month"=>(array_search($newdate[2][0],$this->month3)+1), + "Day"=>$newdate[1][0], + "Hour"=>$newdate[4][0], + "Minute"=>$newdate[5][0], + "Second"=>$newdate[6][0], + "Timezone"=>$newdate[7][0]); + }elseif($this->patrVal[0]==36){ + $result = getdate(mktime($newdate)); + $resultvar = array( + "Year"=>$result["year"], + "Month"=>array_search($result["month"],$this->month)+1, + "Day"=>$result["mday"], + "Hour"=>$result["hours"], + "Minute"=>$result["minutes"], + "Second"=>$result["seconds"], + "Timezone"=>date("O")); + }else{ + $labels = array_keys($this->types); + for($i=0;$ipatrVal[$i]]]=$newdate[$i][0]; + } + if(isset($result["F"])) $month = array_search($result["F"],$this->month)+1; + elseif(isset($result["M"])) $month = array_search($result["M"],$this->month3)+1; + elseif(isset($result["m"])) $month = $result["m"]; + elseif(isset($result["n"])) $month = $result["n"]; + if(isset($result["d"])) $day = $result["d"]; + elseif(isset($result["j"])) $day = $result["j"]; + if(isset($result["Y"])) $year = $result["Y"]; + elseif(isset($result["o"])) $year = $result["o"]; + elseif(isset($result["y"])) $year = ($result["y"]>substr(date("Y",time()),2,2))?(substr(date("Y",time()),0,2)-1).$result["y"]:substr(date("Y",time()),0,2).$result["y"]; + if(isset($result["l"])) $weekday = array_search($result["l"],$this->days)+1; + elseif(isset($result["D"])) $weekday = array_search($result["D"],$this->days3)+1; + elseif(isset($result["N"])) $weekday = $result["N"]; + elseif(isset($result["w"])) $weekday = $result["w"]; + else $weekday = @date("w",mktime(0,0,0,$month,$day,$year)); + $hour='00'; + if(isset($result["H"])) $hour = $result["H"]; + elseif (isset($result["G"])) $hour = $result["G"]; + elseif (isset($result["h"])) $hour = ($result["A"]=="PM"|$result["a"]=="pm")?($result["h"]+12):($result["h"]); + elseif (isset($result["g"])) $hour = ($result["A"]=="PM"|$result["a"]=="pm")?($result["g"]+12):($result["g"]); + if(isset($result["O"])) $timezone = $result["O"]; + elseif (isset($result["Z"])) $timezone = ($result["Z"]/3600); + else $timezone = date("O"); + $minutes = isset($result["i"])?$result["i"]:'00'; + $seconds = isset($result["s"])?$result["s"]:'00'; + + $resultvar = array( + "Year"=>$year, + "Month"=>$month, + "Day"=>$day, + "WeekDay"=>$weekday, + "Hour"=>$hour, + "Minute"=>$minutes, + "Second"=>$seconds, + "Timezone"=>$timezone); + } + + return ($localize)?$this->Localize($resultvar):$resultvar; + } + /** + * Returns the difference between two days as datetime array + * + * @param string $pattern1 + * @param string $date1 + * @param string $pattern2 + * @param string $date2 + * @return array + */ + function diffDate($pattern1,$date1,$pattern2,$date2){ + $pdate1 = $this->parseDate($pattern1,$date1); + $pdate2 = $this->parseDate($pattern2,$date2); + $compare = $this->Compare($pdate1,$pdate2); + if($compare==1){ + $ndate = $pdate1; + $odate = $pdate2; + }elseif($compare==-1){ + $ndate = $pdate2; + $odate = $pdate1; + }else{ + return array("Year"=>0,"Month"=>0,"Day"=>0,"Hour"=>0,"Minute"=>0,"Second"=>0); + } + $hour = intval($ndate["Hour"])-intval($odate["Hour"]); + $minute = intval($ndate["Minute"])-intval($odate["Minute"]); + $second = intval($ndate["Second"])-intval($odate["Second"]); + $month = intval($ndate["Month"])-intval($odate["Month"]); + $day = intval($ndate["Day"])-intval($odate["Day"]); + $year = intval($ndate["Year"])-intval($odate["Year"]); + $difference = mktime($hour,$minute,$second,($month+1),($day+1),($year+1970)); + $result = getdate($difference); + $resultvar = array( + "Year"=>$result["year"]-1970, + "Month"=>array_search($result["month"],$this->month), + "Day"=>$result["mday"]-1, + "Hour"=>$result["hours"], + "Minute"=>$result["minutes"], + "Second"=>$result["seconds"], + "Timezone"=>$this->timezone); + return $resultvar; + } + /** + * Reformats the given date as same as the first date() function variable. + * + * @param string $patternTo + * @param string $patternFrom + * @param string $date + * @return string + */ + function Format($patternTo,$patternFrom,$date){ + $temp = $this->parseDate($patternFrom,$date); + return date($patternTo,mktime($temp["Hour"],$temp["Minute"],$temp["Second"],$temp["Month"],$temp["Day"],$temp["Year"])); + } + + /** + * Not Completed localization function. Adds time to result which is defined by user in $this->timezone, + * + * @param array $date + * @return array + */ + function Localize($date){ + $zonehour = $date["Hour"] + intval(substr($this->timezone,0,1).substr($this->timezone,1,2)); + $zonemin = $date["Minute"] + intval(substr($this->timezone,3,2)); + $newdate = mktime($zonehour,$zonemin,intval($date["Second"]),intval($date["Month"]),intval($date["Day"]),intval($date["Year"])); //Burada bir hata oldu. + $result = getdate($newdate); + $resultvar = array( + "Year"=>$result["year"], + "Month"=>array_search($result["month"],$this->month)+1, + "Day"=>$result["mday"], + "Hour"=>$result["hours"], + "Minute"=>$result["minutes"], + "Second"=>$result["seconds"], + "Timezone"=>""); + return $resultvar; + } + /** + * Compares two date, returns 1 if first is bigger, -1 if second is bigger and 0 if they are same + * + * @param array $date1 + * @param array $date2 + * @return int + */ + function Compare($date1,$date2){ + if($date1["Year"]>$date2["Year"]) return 1; + if($date1["Year"]<$date2["Year"]) return -1; + if($date1["Month"]>$date2["Month"]) return 1; + if($date1["Month"]<$date2["Month"]) return -1; + if($date1["Day"]>$date2["Day"]) return 1; + if($date1["Day"]<$date2["Day"]) return -1; + if($date1["Hour"]>$date2["Hour"]) return 1; + if($date1["Hour"]<$date2["Hour"]) return -1; + if($date1["Minute"]>$date2["Minute"]) return 1; + if($date1["Minute"]<$date2["Minute"]) return -1; + if($date1["Second"]>$date2["Second"]) return 1; + if($date1["Second"]<$date2["Second"]) return -1; + return 0; + } + + public static function getHumanReadableFormat($format) { + return strtr($format,self::$hrFormats); + } + + + +} diff --git a/common.php b/common.php index f8e568b69b5..780d1417625 100644 --- a/common.php +++ b/common.php @@ -17,7 +17,7 @@ //Ensure script is not run directly, avoid path disclosure if (!isset($dbprefix) || isset($_REQUEST['dbprefix'])) {safe_die("Cannot run this script directly");} -$versionnumber = "1.82"; +$versionnumber = "1.85"; $dbversionnumber = 136; $buildnumber = "dev"; @@ -58,10 +58,7 @@ function use_firebug() if(FIREBUG == true) { -// return ' -//'; - return ' -'; + return ''; }; }; @@ -71,6 +68,7 @@ function use_firebug() ## DO NOT EDIT BELOW HERE ################################################################################## require_once ($rootdir.'/classes/adodb/adodb.inc.php'); +require_once ($rootdir.'/classes/dateparser/dateparser.php'); require_once ($rootdir.'/classes/phpmailer/class.phpmailer.php'); require_once ($rootdir.'/classes/php-gettext/gettextinc.php'); require_once ($rootdir.'/classes/core/surveytranslator.php'); @@ -249,167 +247,168 @@ function use_firebug() // SITE STYLES $setfont = ""; - $singleborderstyle = "style='border: 1px solid #111111'"; /** - * showadminmenu() function returns html text for the administration button bar - * @global string $homedir - * @global string $scriptname - * @global string $surveyid - * @global string $setfont - * @global string $imagefiles - * @return string $adminmenu - */ - function showadminmenu() - { - global $homedir, $scriptname, $surveyid, $setfont, $imagefiles, $clang, $debug, $action; - $adminmenu = "\n"; + $adminmenu .= "

 

"; //CSS Firefox 2 transition fix + if (count(getsurveylist(true))==0 && !isset($action) && !isset($surveyid)) { + $adminmenu.= '
' + .'

'.sprintf($clang->gT("Welcome to %s!"),'LimeSurvey').'

' + .'

'.$clang->gT("Some piece-of-cake steps to create your very own first survey:").'
' + .'

    ' + .'
  1. '.sprintf($clang->gT('Create a new survey clicking on the %s icon in the upper right.'),"". $clang->gT("Add survey")."").'
  2. ' + .'
  3. '.$clang->gT('Create a new group inside your survey.').'
  4. ' + .'
  5. '.$clang->gT('Create one or more question inside the new group.').'
  6. ' + .'
  7. '.sprintf($clang->gT('Done. Test your survey using the %s icon.'),"". $clang->gT("Test survey")."").'
  8. ' + .'


 
'; } + + } + return $adminmenu; +} @@ -515,10 +514,13 @@ function db_table_name($name) return db_quote_id($dbprefix.$name); } +/** +* returns the table name without quotes +* +* @param mixed $name +*/ function db_table_name_nq($name) -//returns the table name without quotes { - global $dbprefix; return $dbprefix.$name; } @@ -792,37 +794,6 @@ function getMaxquestionorder($gid) } -/** -* getanswers() queries the database for a list of all answers matching the current question qid -* -* @global string $surveyid -* @global string $gid -* @global string $qid -* @global string $dbprefix -* @global string $code -* -* @return This string is returned containing formatted list of answers matching current qid -*/ -function getanswers() -{ - global $surveyid, $gid, $qid, $code, $dbprefix, $connect, $clang; - $qid=sanitize_int($qid); - $s_lang = GetBaseLanguageFromSurveyID($surveyid); - $aquery = "SELECT code, answer FROM ".db_table_name('answers')." WHERE qid=$qid AND language='$s_lang' ORDER BY sortorder, answer"; - - $aresult = db_execute_assoc($aquery); //Checked - $answerselecter = ""; - while ($arow = $aresult->FetchRow()) - { - $answerselecter .= "\t\t\n".$answerselecter;} - return $answerselecter; -} - - /** * getqtypelist() Returns list of question types available in LimeSurvey. Edit this if you are adding a new * question type @@ -1605,30 +1576,6 @@ function getlabelsets($languages=null) } -function checkactivations() -{ - global $dbprefix, $connect; - $tablelist = $connect->MetaTables(); - $tablenames[] = "ListofTables"; //dummy entry because in_array never finds the first one! - foreach ($tablelist as $tbl) - { - $tablenames[] = $tbl; - } - $caquery = "SELECT sid FROM ".db_table_name('surveys')." WHERE active='Y'"; - $caresult = db_execute_assoc($caquery); //Checked - if (!$caresult) {return "Database Error";} - while ($carow = $caresult->FetchRow()) - { - $surveyname = "{$dbprefix}survey_{$carow['sid']}"; - if (!in_array($surveyname, $tablenames)) - { - $udquery = "UPDATE ".db_table_name('surveys')." SET active='N' WHERE sid={$carow['sid']}"; - $udresult = $connect->Execute($udquery); //Checked - } - } -} - - function checkifemptydb() { global $connect, $dbprefix; @@ -1637,47 +1584,6 @@ function checkifemptydb() else {Return(true);} } -function checkfortables() -{ - global $scriptname, $dbprefix, $setfont, $connect, $clang; - $alltables=array("{$dbprefix}surveys", - "{$dbprefix}groups", - "{$dbprefix}questions", - "{$dbprefix}answers", - "{$dbprefix}conditions", - "{$dbprefix}users", - "{$dbprefix}labelsets", - "{$dbprefix}labels"); - $tables = $connect->MetaTables(); - - foreach($alltables as $at) - { - if (!sql_table_exists($at, $tables)) - { - $checkfields="Y"; - } - } - if (!isset($checkfields)) {$checkfields="";} - if ($checkfields=="Y") - { - echo "
\n" - ."\n" - ."\t\n" - ."\t\n" - ."
" - .$clang->gT("LimeSurvey Setup")."
$setfont\n" - ."\t\t" - .$clang->gT("Error")."
\n" - ."\t\t" - .$clang->gT("It appears as if some tables or fields are missing from your database.")."

\n" - ."\t\t\n" - ."\t
\n" - ."\n"; - exit; - } -} - function sql_table_exists($tableName, $tables) { @@ -1714,17 +1620,6 @@ function StandardSort($a, $b) } -function conditionscount($qid) -{ - global $dbprefix, $connect; - $qid=sanitize_int($qid); - $query="SELECT COUNT(*) FROM ".db_table_name('conditions')." WHERE qid=$qid"; - $result=db_execute_num($query) or safe_die ("Couldn't get conditions
$query
".$connect->ErrorMsg()); - list($count) = $result->FetchRow(); - return $count; -} - - function keycontroljs() { $kcjs=" @@ -2044,18 +1939,6 @@ function sendcacheheaders() } -function getLegitQids($surveyid) -{ - global $dbprefix; - $surveyid=sanitize_int($surveyid); - - //GET LIST OF LEGIT QIDs FOR TESTING LATER - $lq = "SELECT DISTINCT qid FROM ".db_table_name('questions')." WHERE sid=$surveyid AND language='".$_SESSION['s_lang']."'"; - $lr = db_execute_num($lq); //Checked - return array_merge(array("DUMMY ENTRY"), $lr->GetRows()); -} - - function returnquestiontitlefromfieldcode($fieldcode) { // Performance optimized : Nov 13, 2006 @@ -2329,21 +2212,14 @@ function validate_templatedir($templatename) } -function crlf_lineendings($text) -{ - $text=str_replace("\r\n", "~~~~", $text); //First replace any good line endings with ~~~~ - $text=str_replace("\n", "~~~~", $text); //Then replace any solitary \n's with ~~~~ - $text=str_replace("\r", "~~~~", $text); //Then replace any solitary \r's with ~~~~ - $text=str_replace("~~~~", "\r\n", $text); //Finally replace all ~~~~'s with \r\n - return $text; -} - - - -//This function generates an array containing the fieldcode, and matching data in the same -//order as the activate script -// @param: $force_refresh - Forces to really refresh the array, not just take the session copy - +/** +* This function generates an array containing the fieldcode, and matching data in the same order as the activate script +* +* @param string $surveyid +* @param mixed $style +* @param mixed $force_refresh - Forces to really refresh the array, not just take the session copy +* @return mixed +*/ function createFieldMap($surveyid, $style="null", $force_refresh=false) { global $dbprefix, $connect, $globalfieldmap, $clang; @@ -2723,10 +2599,6 @@ function arraySearchByKey($needle, $haystack, $keyname, $maxanswers="") { function templatereplace($line) { - // Performance optimized : Nov 10, 2006 - // Performance Improvement : 49% - // Optimized By : swales - global $surveylist, $sitename, $clienttoken, $rooturl; global $thissurvey, $imagefiles, $defaulttemplate; global $percentcomplete, $move; @@ -3519,33 +3391,6 @@ function questionAttributes($returnByName=false) "help"=>$clang->gT('SGQA identifier to use total of previous question as total for this question'), "caption"=>$clang->gT('Value equals SQGA')); - /* -- > Commented out since not yet used - $qattributes[]=array("name"=>"default_value", - "types"=>"^", - "help"=>"What value to use as the default"); - - $qattributes[]=array("name"=>"minimum_value", - "types"=>"^", - "help"=>"The lowest value on the slider"); - - $qattributes[]=array("name"=>"maximum_value", - "types"=>"^", - "help"=>"The highest value on the slider"); - - $qattributes[]=array("name"=>"left_label", - "types"=>"^", - "help"=>"The label to the left of the slider"); - - $qattributes[]=array("name"=>"centre_label", - "types"=>"^" - "help"=>"The centre label on the slider"); - - $qattributes[]=array("name"=>"right_label", - "types"=>"^", - "help"=>"The ") - - */ - //This builds a more useful array (don't modify) if ($returnByName!=true) { @@ -5127,25 +4972,31 @@ function captcha_enabled($screen, $captchamode='') } } -// used for import[survey|questions|groups] + +/** +* used for import[survey|questions|groups] +* +* @param mixed $string +* @return mixed +*/ function convertCsvreturn2return($string) { - return str_replace('\n', "\n", $string); + return str_replace('\n', "\n", $string); } -// Checks that each object from an array of CSV data -// [question-rows,answer-rows,labelsets-row] -// supports iat least a given language -// -// param: -// $csvarray : array with a line of csv data per row -// $idkeysarray: array of integers giving the csv-row numbers of the object keys -// $langfieldnum: integer giving the csv-row number of the language(s) filed -// ==> the language field can be a single language code or a -// space separated language code list -// $langcode: the language code to be tested -// $hasheader: if we should strip off the first line (if it contains headers) -// + + +/** +* Checks that each object from an array of CSV data [question-rows,answer-rows,labelsets-row] supports at least a given language +* +* @param mixed $csvarray array with a line of csv data per row +* @param mixed $idkeysarray array of integers giving the csv-row numbers of the object keys +* @param mixed $langfieldnum integer giving the csv-row number of the language(s) filed +* ==> the language field can be a single language code or a +* space separated language code list +* @param mixed $langcode the language code to be tested +* @param mixed $hasheader if we should strip off the first line (if it contains headers) +*/ function bDoesImportarraySupportsLanguage($csvarray,$idkeysarray,$langfieldnum,$langcode, $hasheader = false) { // An array with one row per object id and langsupport status as value @@ -5298,33 +5149,25 @@ function bIsTokenCompletedDatestamped($thesurvey) } } -function date_shift($date, $dformat, $shift) -/* example usage - -$date = "2006-12-31 21:00"; -$shift "+6 hours"; // could be days, weeks... see function strtotime() for usage - -echo sql_date_shift($date, "Y-m-d H:i:s", $shift); - -// will output: 2007-01-01 03:00:00 +/** +* example usage +* $date = "2006-12-31 21:00"; +* $shift "+6 hours"; // could be days, weeks... see function strtotime() for usage +* +* echo sql_date_shift($date, "Y-m-d H:i:s", $shift); +* +* will output: 2007-01-01 03:00:00 +* +* @param mixed $date +* @param mixed $dformat +* @param mixed $shift +* @return string */ +function date_shift($date, $dformat, $shift) { -return date($dformat, strtotime($shift, strtotime($date))); + return date($dformat, strtotime($shift, strtotime($date))); } -function mydebug($strOutput) -{ - $datei = fopen("d:\debug.txt","a+"); - fwrite($datei, "$strOutput \n"); - fclose($datei); -} -function mydebug_var($strOutput) -{ - $datei = fopen("d:\debug.txt","a+"); - fwrite($datei, var_export($strOutput, TRUE)); - fwrite($datei, "\n"); - fclose($datei); -} // getBounceEmail: returns email used to receive error notifications function getBounceEmail($surveyid) @@ -6302,6 +6145,23 @@ function strip_javascript($content){ $text = preg_replace($search, '', $content); return $text; } + + +/** +* This functions converts any time format to any other time format +* +* @param mixed $datetime +* @param mixed $inputformat +* @param mixed $outputformat +*/ +function convertDateTimeFormat($datetime, $inputformat, $outputformat) +{ + if (trim($datetime)=='') return ''; + $date = new DateParser(); + return $date->Format($outputformat, $inputformat, $datetime); +} + + /** * * formats a datestring (YY-MM-DD or YYYY-MM-DD or YY-M-D... to whatever) diff --git a/index.php b/index.php index baa824af3b8..fb49c6fe09c 100644 --- a/index.php +++ b/index.php @@ -475,6 +475,9 @@ exit; } + + + //CHECK IF SURVEY ID DETAILS HAVE CHANGED if (isset($_SESSION['oldsid'])) {$oldsid=$_SESSION['oldsid'];} @@ -570,10 +573,10 @@ { //check if token actually does exist - $tkquery = "SELECT COUNT(*) FROM ".db_table_name('tokens_'.$surveyid)." WHERE token='".db_quote($token)."' AND (completed = 'N' or completed='')"; + $tkquery = "SELECT * FROM ".db_table_name('tokens_'.$surveyid)." WHERE token='".db_quote($token)."' AND (completed = 'N' or completed='')"; $tkresult = db_execute_num($tkquery); //Checked - list($tkexist) = $tkresult->FetchRow(); - if (!$tkexist) + $tokendata = $tkresult->FetchRow(); + if ($tkresult->RecordCount()==0) { sendcacheheaders(); doHeader(); @@ -583,15 +586,44 @@ echo "\t

\n" ."\t".$clang->gT("This is a closed-access survey, so you must supply a valid token. Please contact the administrator for assistance.")."

\n" ."\t".$clang->gT("The token you have provided is either not valid, or has already been used.")."\n" - ."\t".sprintf($clang->gT("For further information contact %s"), $thissurvey['adminname']) - ."(" + ."\t".sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname']) + ." (" ."{$thissurvey['adminemail']})

\n" ."\t".$clang->gT("Close this Window")."
 \n"; echo templatereplace(file_get_contents("$thistpl/endpage.pstpl")); doFooter(); exit; } -} +} +elseif ($tokensexist == 1 && isset($token) && $token && !isset($_SESSION['step'])) //check if token is in a valid time frame + { + $tkquery = "SELECT * FROM ".db_table_name('tokens_'.$surveyid)." WHERE token='".db_quote($token)."' AND (completed = 'N' or completed='')"; + $tkresult = db_execute_assoc($tkquery); //Checked + $tokendata = $tkresult->FetchRow(); + if ((trim($tokendata['validfrom'])!='' && convertDateTimeFormat($tokendata['validfrom'],'Y-m-d H:i:s','U')*1>date('U')*1) || + (trim($tokendata['validuntil'])!='' && convertDateTimeFormat($tokendata['validuntil'],'Y-m-d H:i:s','U')*1
\n" + ."\t".$clang->gT("We are sorry but you are not allowed to enter this survey.")."

\n" + ."\t".$clang->gT("Your token seems to be valid but can be used only during a certain time period.")."
\n" + ."\t".sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname'] + ." (" + ."{$thissurvey['adminemail']})")."

\n" + ."\t".$clang->gT("Close this Window")."
 \n"; + echo templatereplace(file_get_contents("$thistpl/endpage.pstpl")); + doFooter(); + exit; + } + } + + + //CLEAR SESSION IF REQUESTED if (isset($_GET['move']) && $_GET['move'] == "clearall") { @@ -2748,7 +2780,7 @@ function check_quota($checkaction,$surveyid) doHeader(); echo templatereplace(file_get_contents("$thistpl/startpage.pstpl")); echo "\t

\n"; - echo "\t".$clang->gT("Sorry your responses have exceeded a quota on this survey.")."
 \n"; + echo "\t".$clang->gT("We are sorry but your responses have exceeded a quota on this survey.")."
 \n"; echo "