From 7e7f5914655d624e49b0ae73226ee6134491e25e Mon Sep 17 00:00:00 2001 From: Carsten Schmitz Date: Fri, 20 Apr 2012 10:27:56 +0200 Subject: [PATCH] Fixed issue #6027: Users who have token creation permission can't create token table --- admin/tokens.php | 5346 +++++++++++++++++++++++----------------------- 1 file changed, 2673 insertions(+), 2673 deletions(-) diff --git a/admin/tokens.php b/admin/tokens.php index 73a8b60e352..69dcea0c5af 100644 --- a/admin/tokens.php +++ b/admin/tokens.php @@ -1,17 +1,17 @@ $clang->gT("ARMSCII-8 Armenian") - ,"ascii"=>$clang->gT("US ASCII") - ,"auto"=>$clang->gT("Automatic") - ,"big5"=>$clang->gT("Big5 Traditional Chinese") - ,"binary"=>$clang->gT("Binary pseudo charset") - ,"cp1250"=>$clang->gT("Windows Central European") - ,"cp1251"=>$clang->gT("Windows Cyrillic") - ,"cp1256"=>$clang->gT("Windows Arabic") - ,"cp1257"=>$clang->gT("Windows Baltic") - ,"cp850"=>$clang->gT("DOS West European") - ,"cp852"=>$clang->gT("DOS Central European") - ,"cp866"=>$clang->gT("DOS Russian") - ,"cp932"=>$clang->gT("SJIS for Windows Japanese") - ,"dec8"=>$clang->gT("DEC West European") - ,"eucjpms"=>$clang->gT("UJIS for Windows Japanese") - ,"euckr"=>$clang->gT("EUC-KR Korean") - ,"gb2312"=>$clang->gT("GB2312 Simplified Chinese") - ,"gbk"=>$clang->gT("GBK Simplified Chinese") - ,"geostd8"=>$clang->gT("GEOSTD8 Georgian") - ,"greek"=>$clang->gT("ISO 8859-7 Greek") - ,"hebrew"=>$clang->gT("ISO 8859-8 Hebrew") - ,"hp8"=>$clang->gT("HP West European") - ,"keybcs2"=>$clang->gT("DOS Kamenicky Czech-Slovak") - ,"koi8r"=>$clang->gT("KOI8-R Relcom Russian") - ,"koi8u"=>$clang->gT("KOI8-U Ukrainian") - ,"latin1"=>$clang->gT("cp1252 West European") - ,"latin2"=>$clang->gT("ISO 8859-2 Central European") - ,"latin5"=>$clang->gT("ISO 8859-9 Turkish") - ,"latin7"=>$clang->gT("ISO 8859-13 Baltic") - ,"macce"=>$clang->gT("Mac Central European") - ,"macroman"=>$clang->gT("Mac West European") - ,"sjis"=>$clang->gT("Shift-JIS Japanese") - ,"swe7"=>$clang->gT("7bit Swedish") - ,"tis620"=>$clang->gT("TIS620 Thai") - ,"ucs2"=>$clang->gT("UCS-2 Unicode") - ,"ujis"=>$clang->gT("EUC-JP Japanese") - ,"utf8"=>$clang->gT("UTF-8 Unicode")); - if (isset($_POST['csvcharset']) && $_POST['csvcharset']) //sanitize charset - if encoding is not found sanitize to 'auto' - { - $uploadcharset=$_POST['csvcharset']; - if (!array_key_exists($uploadcharset,$encodingsarray)) {$uploadcharset='auto';} - $filterduplicatetoken=(isset($_POST['filterduplicatetoken']) && $_POST['filterduplicatetoken']=='on'); - $filterblankemail=(isset($_POST['filterblankemail']) && $_POST['filterblankemail']=='on'); - } + $js_admin_includes[]='scripts/tokens.js'; + + $encodingsarray = array("armscii8"=>$clang->gT("ARMSCII-8 Armenian") + ,"ascii"=>$clang->gT("US ASCII") + ,"auto"=>$clang->gT("Automatic") + ,"big5"=>$clang->gT("Big5 Traditional Chinese") + ,"binary"=>$clang->gT("Binary pseudo charset") + ,"cp1250"=>$clang->gT("Windows Central European") + ,"cp1251"=>$clang->gT("Windows Cyrillic") + ,"cp1256"=>$clang->gT("Windows Arabic") + ,"cp1257"=>$clang->gT("Windows Baltic") + ,"cp850"=>$clang->gT("DOS West European") + ,"cp852"=>$clang->gT("DOS Central European") + ,"cp866"=>$clang->gT("DOS Russian") + ,"cp932"=>$clang->gT("SJIS for Windows Japanese") + ,"dec8"=>$clang->gT("DEC West European") + ,"eucjpms"=>$clang->gT("UJIS for Windows Japanese") + ,"euckr"=>$clang->gT("EUC-KR Korean") + ,"gb2312"=>$clang->gT("GB2312 Simplified Chinese") + ,"gbk"=>$clang->gT("GBK Simplified Chinese") + ,"geostd8"=>$clang->gT("GEOSTD8 Georgian") + ,"greek"=>$clang->gT("ISO 8859-7 Greek") + ,"hebrew"=>$clang->gT("ISO 8859-8 Hebrew") + ,"hp8"=>$clang->gT("HP West European") + ,"keybcs2"=>$clang->gT("DOS Kamenicky Czech-Slovak") + ,"koi8r"=>$clang->gT("KOI8-R Relcom Russian") + ,"koi8u"=>$clang->gT("KOI8-U Ukrainian") + ,"latin1"=>$clang->gT("cp1252 West European") + ,"latin2"=>$clang->gT("ISO 8859-2 Central European") + ,"latin5"=>$clang->gT("ISO 8859-9 Turkish") + ,"latin7"=>$clang->gT("ISO 8859-13 Baltic") + ,"macce"=>$clang->gT("Mac Central European") + ,"macroman"=>$clang->gT("Mac West European") + ,"sjis"=>$clang->gT("Shift-JIS Japanese") + ,"swe7"=>$clang->gT("7bit Swedish") + ,"tis620"=>$clang->gT("TIS620 Thai") + ,"ucs2"=>$clang->gT("UCS-2 Unicode") + ,"ujis"=>$clang->gT("EUC-JP Japanese") + ,"utf8"=>$clang->gT("UTF-8 Unicode")); + if (isset($_POST['csvcharset']) && $_POST['csvcharset']) //sanitize charset - if encoding is not found sanitize to 'auto' + { + $uploadcharset=$_POST['csvcharset']; + if (!array_key_exists($uploadcharset,$encodingsarray)) {$uploadcharset='auto';} + $filterduplicatetoken=(isset($_POST['filterduplicatetoken']) && $_POST['filterduplicatetoken']=='on'); + $filterblankemail=(isset($_POST['filterblankemail']) && $_POST['filterblankemail']=='on'); + } } if ($subaction == "importldap" || $subaction == "uploadldap" ) { - $filterduplicatetoken=(isset($_POST['filterduplicatetoken']) && $_POST['filterduplicatetoken']=='on'); - $filterblankemail=(isset($_POST['filterblankemail']) && $_POST['filterblankemail']=='on'); + $filterduplicatetoken=(isset($_POST['filterduplicatetoken']) && $_POST['filterduplicatetoken']=='on'); + $filterblankemail=(isset($_POST['filterblankemail']) && $_POST['filterblankemail']=='on'); } $tokenoutput = ""; @@ -119,313 +119,313 @@ $bquery .= " LEFT JOIN ".db_table_name("survey_$surveyid")." s on t.token=s.token "; } $bquery.=' where 1=1'; - if (trim($_POST['filteremail'])!='') - { - if ($databasetype=='odbc_mssql' || $databasetype=='odbtp' || $databasetype=='mssql_n' || $connect->databaseType == 'mssqlnative') + if (trim($_POST['filteremail'])!='') { - $bquery .= ' and CAST(email as varchar) like '.db_quoteall('%'.$_POST['filteremail'].'%', true); + if ($databasetype=='odbc_mssql' || $databasetype=='odbtp' || $databasetype=='mssql_n' || $connect->databaseType == 'mssqlnative') + { + $bquery .= ' and CAST(email as varchar) like '.db_quoteall('%'.$_POST['filteremail'].'%', true); + } + else + { + $bquery .= ' and email like '.db_quoteall('%'.$_POST['filteremail'].'%', true); + } } - else + if ($_POST['tokenstatus']==1) { - $bquery .= ' and email like '.db_quoteall('%'.$_POST['filteremail'].'%', true); + $bquery .= " and completed<>'N'"; } - } - if ($_POST['tokenstatus']==1) - { - $bquery .= " and completed<>'N'"; - } - if ($_POST['tokenstatus']==2) - { - $bquery .= " and completed='N'"; - if ($thissurvey['anonymized']=='N') + if ($_POST['tokenstatus']==2) { + $bquery .= " and completed='N'"; + if ($thissurvey['anonymized']=='N') + { $bquery .=" and s.token is null "; + } } - } - if ($_POST['tokenstatus']==3 && $thissurvey['anonymized']=='N') - { + if ($_POST['tokenstatus']==3 && $thissurvey['anonymized']=='N') + { $bquery .= " and completed='N' and s.token is not null"; - } - if ($_POST['invitationstatus']==1) - { - $bquery .= " and sent<>'N'"; - } - if ($_POST['invitationstatus']==2) - { - $bquery .= " and sent='N'"; - } - - if ($_POST['reminderstatus']==1) - { - $bquery .= " and remindersent<>'N'"; - } - if ($_POST['reminderstatus']==2) - { - $bquery .= " and remindersent='N'"; - } - - if ($_POST['tokenlanguage']!='') - { - $bquery .= " and language=".db_quoteall($_POST['tokenlanguage']); - } - $bquery .= " ORDER BY tid"; - - $bresult = db_execute_assoc($bquery) or die ("$bquery
".htmlspecialchars($connect->ErrorMsg())); - $bfieldcount=$bresult->FieldCount(); - - //HEADERS should be after the above query else timeout errors in case there are lots of tokens! - header("Content-Disposition: attachment; filename=tokens_".$surveyid.".csv"); - header("Content-type: text/comma-separated-values; charset=UTF-8"); - header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); - header("Pragma: cache"); - - // Export UTF8 WITH BOM - $tokenoutput = chr(hexdec('EF')).chr(hexdec('BB')).chr(hexdec('BF')); - $tokenoutput .= "tid,firstname,lastname,email,emailstatus,token,language,validfrom,validuntil,invited,reminded,remindercount,completed,usesleft"; - $attrfieldnames = GetAttributeFieldnames($surveyid); - $attrfielddescr = GetTokenFieldsAndNames($surveyid, true); - foreach ($attrfieldnames as $attr_name) - { - $tokenoutput .=", $attr_name"; - if (isset($attrfielddescr[$attr_name])) - $tokenoutput .=" <".str_replace(","," ",$attrfielddescr[$attr_name]).">"; - } - $tokenoutput .="\n"; - while ($brow = $bresult->FetchRow()) - { + } + if ($_POST['invitationstatus']==1) + { + $bquery .= " and sent<>'N'"; + } + if ($_POST['invitationstatus']==2) + { + $bquery .= " and sent='N'"; + } - if (trim($brow['validfrom']!='')) + if ($_POST['reminderstatus']==1) + { + $bquery .= " and remindersent<>'N'"; + } + if ($_POST['reminderstatus']==2) { - $datetimeobj = new Date_Time_Converter($brow['validfrom'] , "Y-m-d H:i:s"); - $brow['validfrom']=$datetimeobj->convert('Y-m-d H:i'); + $bquery .= " and remindersent='N'"; } - if (trim($brow['validuntil']!='')) + + if ($_POST['tokenlanguage']!='') { - $datetimeobj = new Date_Time_Converter($brow['validuntil'] , "Y-m-d H:i:s"); - $brow['validuntil']=$datetimeobj->convert('Y-m-d H:i'); + $bquery .= " and language=".db_quoteall($_POST['tokenlanguage']); } + $bquery .= " ORDER BY tid"; + + $bresult = db_execute_assoc($bquery) or die ("$bquery
".htmlspecialchars($connect->ErrorMsg())); + $bfieldcount=$bresult->FieldCount(); + + //HEADERS should be after the above query else timeout errors in case there are lots of tokens! + header("Content-Disposition: attachment; filename=tokens_".$surveyid.".csv"); + header("Content-type: text/comma-separated-values; charset=UTF-8"); + header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); + header("Pragma: cache"); - $tokenoutput .= '"'.trim($brow['tid']).'",'; - $tokenoutput .= '"'.trim($brow['firstname']).'",'; - $tokenoutput .= '"'.trim($brow['lastname']).'",'; - $tokenoutput .= '"'.trim($brow['email']).'",'; - $tokenoutput .= '"'.trim($brow['emailstatus']).'",'; - $tokenoutput .= '"'.trim($brow['token']).'",'; - $tokenoutput .= '"'.trim($brow['language']).'",'; - $tokenoutput .= '"'.trim($brow['validfrom']).'",'; - $tokenoutput .= '"'.trim($brow['validuntil']).'",'; - $tokenoutput .= '"'.trim($brow['sent']).'",'; - $tokenoutput .= '"'.trim($brow['remindersent']).'",'; - $tokenoutput .= '"'.trim($brow['remindercount']).'",'; - $tokenoutput .= '"'.trim($brow['completed']).'",'; - $tokenoutput .= '"'.trim($brow['usesleft']).'",'; + // Export UTF8 WITH BOM + $tokenoutput = chr(hexdec('EF')).chr(hexdec('BB')).chr(hexdec('BF')); + $tokenoutput .= "tid,firstname,lastname,email,emailstatus,token,language,validfrom,validuntil,invited,reminded,remindercount,completed,usesleft"; + $attrfieldnames = GetAttributeFieldnames($surveyid); + $attrfielddescr = GetTokenFieldsAndNames($surveyid, true); foreach ($attrfieldnames as $attr_name) { - $tokenoutput .='"'.trim($brow[$attr_name]).'",'; + $tokenoutput .=", $attr_name"; + if (isset($attrfielddescr[$attr_name])) + $tokenoutput .=" <".str_replace(","," ",$attrfielddescr[$attr_name]).">"; } - $tokenoutput = substr($tokenoutput,0,-1); // remove last comma - $tokenoutput .= "\n"; - } - echo $tokenoutput; - exit; + $tokenoutput .="\n"; + while ($brow = $bresult->FetchRow()) + { + + if (trim($brow['validfrom']!='')) + { + $datetimeobj = new Date_Time_Converter($brow['validfrom'] , "Y-m-d H:i:s"); + $brow['validfrom']=$datetimeobj->convert('Y-m-d H:i'); + } + if (trim($brow['validuntil']!='')) + { + $datetimeobj = new Date_Time_Converter($brow['validuntil'] , "Y-m-d H:i:s"); + $brow['validuntil']=$datetimeobj->convert('Y-m-d H:i'); + } + + $tokenoutput .= '"'.trim($brow['tid']).'",'; + $tokenoutput .= '"'.trim($brow['firstname']).'",'; + $tokenoutput .= '"'.trim($brow['lastname']).'",'; + $tokenoutput .= '"'.trim($brow['email']).'",'; + $tokenoutput .= '"'.trim($brow['emailstatus']).'",'; + $tokenoutput .= '"'.trim($brow['token']).'",'; + $tokenoutput .= '"'.trim($brow['language']).'",'; + $tokenoutput .= '"'.trim($brow['validfrom']).'",'; + $tokenoutput .= '"'.trim($brow['validuntil']).'",'; + $tokenoutput .= '"'.trim($brow['sent']).'",'; + $tokenoutput .= '"'.trim($brow['remindersent']).'",'; + $tokenoutput .= '"'.trim($brow['remindercount']).'",'; + $tokenoutput .= '"'.trim($brow['completed']).'",'; + $tokenoutput .= '"'.trim($brow['usesleft']).'",'; + foreach ($attrfieldnames as $attr_name) + { + $tokenoutput .='"'.trim($brow[$attr_name]).'",'; + } + $tokenoutput = substr($tokenoutput,0,-1); // remove last comma + $tokenoutput .= "\n"; + } + echo $tokenoutput; + exit; } // Bouceprocessing if($subaction=='bounceprocessing') { - if($thissurvey['bounceprocessing'] != 'N' && bHasSurveyPermission($surveyid,'tokens','update')) - { - $bouncetotal=0; - $checktotal=0; - if($thissurvey['bounceprocessing']=='G') + if($thissurvey['bounceprocessing'] != 'N' && bHasSurveyPermission($surveyid,'tokens','update')) { - $accounttype=getGlobalSetting('bounceaccounttype'); - $hostname=getGlobalSetting('bounceaccounthost'); - $username=getGlobalSetting('bounceaccountuser'); - $pass=getGlobalSetting('bounceaccountpass'); - $hostencryption=getGlobalSetting('bounceencryption'); + $bouncetotal=0; + $checktotal=0; + if($thissurvey['bounceprocessing']=='G') + { + $accounttype=getGlobalSetting('bounceaccounttype'); + $hostname=getGlobalSetting('bounceaccounthost'); + $username=getGlobalSetting('bounceaccountuser'); + $pass=getGlobalSetting('bounceaccountpass'); + $hostencryption=getGlobalSetting('bounceencryption'); - } - else - { - $accounttype=$thissurvey['bounceaccounttype']; - $hostname=$thissurvey['bounceaccounthost']; - $username=$thissurvey['bounceaccountuser']; - $pass=$thissurvey['bounceaccountpass']; - $hostencryption=$thissurvey['bounceaccountencryption']; + } + else + { + $accounttype=$thissurvey['bounceaccounttype']; + $hostname=$thissurvey['bounceaccounthost']; + $username=$thissurvey['bounceaccountuser']; + $pass=$thissurvey['bounceaccountpass']; + $hostencryption=$thissurvey['bounceaccountencryption']; - } - @list($hostname,$port) = split(':', $hostname); + } + @list($hostname,$port) = split(':', $hostname); if(empty($port)) { - if($accounttype=="IMAP") + if($accounttype=="IMAP") { - switch($hostencryption) - { - case "Off": - $hostname = $hostname.":143"; - break; - case "SSL": - $hostname = $hostname.":993"; - break; - case "TLS": - $hostname = $hostname.":993"; - break; - } + switch($hostencryption) + { + case "Off": + $hostname = $hostname.":143"; + break; + case "SSL": + $hostname = $hostname.":993"; + break; + case "TLS": + $hostname = $hostname.":993"; + break; + } } - else + else { - switch($hostencryption) - { - case "Off": - $hostname = $hostname.":110"; - break; - case "SSL": - $hostname = $hostname.":995"; - break; - case "TLS": - $hostname = $hostname.":995"; - break; - } + switch($hostencryption) + { + case "Off": + $hostname = $hostname.":110"; + break; + case "SSL": + $hostname = $hostname.":995"; + break; + case "TLS": + $hostname = $hostname.":995"; + break; + } } } - $flags=""; - switch($accounttype) - { - case "IMAP": - $flags.="/imap"; - break; - case "POP": - $flags.="/pop3"; - break; - } - switch($hostencryption) // novalidate-cert to have personal CA , maybe option. - { - case "SSL": - $flags.="/ssl/novalidate-cert"; - break; - case "TLS": - $flags.="/tls/novalidate-cert"; - break; - } - if(@$mbox=imap_open('{'.$hostname.$flags.'}INBOX',$username,$pass)) - { - imap_errors(); - $count=imap_num_msg($mbox); - if($count>0) + $flags=""; + switch($accounttype) + { + case "IMAP": + $flags.="/imap"; + break; + case "POP": + $flags.="/pop3"; + break; + } + switch($hostencryption) // novalidate-cert to have personal CA , maybe option. + { + case "SSL": + $flags.="/ssl/novalidate-cert"; + break; + case "TLS": + $flags.="/tls/novalidate-cert"; + break; + } + if(@$mbox=imap_open('{'.$hostname.$flags.'}INBOX',$username,$pass)) { - $lasthinfo=imap_headerinfo($mbox,$count); - $datelcu = strtotime($lasthinfo->date); - $datelastbounce= $datelcu; - $lastbounce = $thissurvey['bouncetime']; - while($datelcu > $lastbounce) + imap_errors(); + $count=imap_num_msg($mbox); + if($count>0) { - $header = explode("\r\n",@imap_body($mbox,$count,FT_PEEK)); // Don't put read - foreach ($header as $item) + $lasthinfo=imap_headerinfo($mbox,$count); + $datelcu = strtotime($lasthinfo->date); + $datelastbounce= $datelcu; + $lastbounce = $thissurvey['bouncetime']; + while($datelcu > $lastbounce) { - if (preg_match('/^X-surveyid/',$item)) - { - $surveyidBounce=explode(": ",$item); - } - if (preg_match('/^X-tokenid/',$item)) + $header = explode("\r\n",@imap_body($mbox,$count,FT_PEEK)); // Don't put read + foreach ($header as $item) { - $tokenBounce=explode(": ",$item); - if($surveyid == $surveyidBounce[1]) + if (preg_match('/^X-surveyid/',$item)) { - $bouncequery = "UPDATE ".db_table_name("tokens_{$surveyid}")." SET emailstatus='bounced', usesleft=0 WHERE token=".db_quoteall($tokenBounce[1]); - $bmark=$connect->Execute($bouncequery); - $readbounce=imap_body($mbox,$count); // Put read - if (isset($thissurvey['bounceremove']) && $thissurvey['bounceremove']) // TODO Y or just true, and a imap_delete + $surveyidBounce=explode(": ",$item); + } + if (preg_match('/^X-tokenid/',$item)) + { + $tokenBounce=explode(": ",$item); + if($surveyid == $surveyidBounce[1]) { - $deletebounce=imap_delete($mbox,$count); // Put delete + $bouncequery = "UPDATE ".db_table_name("tokens_{$surveyid}")." SET emailstatus='bounced', usesleft=0 WHERE token=".db_quoteall($tokenBounce[1]); + $bmark=$connect->Execute($bouncequery); + $readbounce=imap_body($mbox,$count); // Put read + if (isset($thissurvey['bounceremove']) && $thissurvey['bounceremove']) // TODO Y or just true, and a imap_delete + { + $deletebounce=imap_delete($mbox,$count); // Put delete + } + $bouncetotal++; } - $bouncetotal++; } } - } - $count--; - $lasthinfo=@imap_headerinfo($mbox,$count); - $datelc=$lasthinfo->date; - $datelcu = strtotime($datelc); - $checktotal++; + $count--; + $lasthinfo=@imap_headerinfo($mbox,$count); + $datelc=$lasthinfo->date; + $datelcu = strtotime($datelc); + $checktotal++; - } - if($bouncetotal>0) - { - echo sprintf($clang->gT("%s messages were scanned out of which %s were marked as bounce by the system."), $checktotal,$bouncetotal); + } + if($bouncetotal>0) + { + echo sprintf($clang->gT("%s messages were scanned out of which %s were marked as bounce by the system."), $checktotal,$bouncetotal); + } + else + { + echo sprintf($clang->gT("%s messages were scanned, none were marked as bounce by the system."),$checktotal); + } } else { - echo sprintf($clang->gT("%s messages were scanned, none were marked as bounce by the system."),$checktotal); + echo sprintf($clang->gT("Your inbox is empty.")); } + @imap_close($mbox); + $entertimestamp = "update ".db_table_name("surveys")." set bouncetime='$datelastbounce' where sid='$surveyid'"; + $executetimestamp = $connect->Execute($entertimestamp); + } else { - echo sprintf($clang->gT("Your inbox is empty.")); + echo $clang->gT("Please check your settings"); } - @imap_close($mbox); - $entertimestamp = "update ".db_table_name("surveys")." set bouncetime='$datelastbounce' where sid='$surveyid'"; - $executetimestamp = $connect->Execute($entertimestamp); - } else { - echo $clang->gT("Please check your settings"); + echo $clang->gT("We are sorry but you don't have permissions to do this."); } - } - else - { - echo $clang->gT("We are sorry but you don't have permissions to do this."); - } - exit(0); // if bounceprocessing : javascript : no more todo + exit(0); // if bounceprocessing : javascript : no more todo } if ($subaction == "delete" && bHasSurveyPermission($surveyid, 'tokens','delete')) { - $_SESSION['metaHeader']=""; + $_SESSION['metaHeader']=""; } if ($subaction == "deletegroup" && bHasSurveyPermission($surveyid, 'tokens','delete')) { - $_SESSION['metaHeader']=""; + $_SESSION['metaHeader']=""; } // MAKE SURE THAT THERE IS A SID if (!isset($surveyid) || !$surveyid) { - $tokenoutput .= "\t
" - .$clang->gT("Token control")."
\n" - ."\t
".$clang->gT("Error")."
" - ."
".$clang->gT("You have not selected a survey")."

" - ."
\n" - ."
\n"; - return; + $tokenoutput .= "\t
" + .$clang->gT("Token control")."
\n" + ."\t
".$clang->gT("Error")."
" + ."
".$clang->gT("You have not selected a survey")."

" + ."
\n" + ."
\n"; + return; } // MAKE SURE THAT THE SURVEY EXISTS $thissurvey=getSurveyInfo($surveyid); if ($thissurvey===false) { - $tokenoutput .= "\t
\n
\n" - .$clang->gT("Token control")."
\n" - ."\t
".$clang->gT("Error")."
" - ."
".$clang->gT("The survey you selected does not exist") - ."

\n\t
" - ."
\n"; - return; + $tokenoutput .= "\t
\n
\n" + .$clang->gT("Token control")."
\n" + ."\t
".$clang->gT("Error")."
" + ."
".$clang->gT("The survey you selected does not exist") + ."

\n\t
" + ."
\n"; + return; } else // A survey DOES exist { - if($subaction != 'bounceprocessing') - { + if($subaction != 'bounceprocessing') + { - $tokenoutput .= "\t\n"; + + } else { + $createtokentableindex = $dict->CreateIndexSQL("{$tabname}_idx", $tabname, array('token')); + $dict->ExecuteSQLArray($createtokentableindex, false) or safe_die ("Failed to create token table index
$createtokentableindex

".$connect->ErrorMsg()); + if ($connect->databaseType == 'mysql' || $connect->databaseType == 'mysqli') + { + $query = 'CREATE INDEX idx_'.$tabname.'_efl ON '.$tabname.' ( email(120), firstname, lastname )'; + $result=$connect->Execute($query) or safe_die("Failed Rename!
".$query."
".$connect->ErrorMsg()); + } - $tabname = "{$dbprefix}tokens_{$surveyid}"; # not using db_table_name as it quotes the table name (as does CreateTableSQL) - $taboptarray = array('mysql' => 'ENGINE='.$databasetabletype.' CHARACTER SET utf8 COLLATE utf8_unicode_ci', - 'mysqli' => 'ENGINE='.$databasetabletype.' CHARACTER SET utf8 COLLATE utf8_unicode_ci'); - $dict = NewDataDictionary($connect); - $sqlarray = $dict->CreateTableSQL($tabname, $createtokentable, $taboptarray); - $execresult=$dict->ExecuteSQLArray($sqlarray, false); - if ($execresult==0 || $execresult==1) + $tokenoutput .= "\t

\n" + .$clang->gT("A token table has been created for this survey.")." (\"".$dbprefix."tokens_$surveyid\")

\n" + ."\n"; + } + return; + } + elseif (returnglobal('restoretable') == "Y" && returnglobal('oldtable') && bHasSurveyPermission($surveyid, 'surveyactivation','update')) { + $query = db_rename_table(returnglobal('oldtable') , db_table_name_nq("tokens_$surveyid")); + $result=$connect->Execute($query) or safe_die("Failed Rename!
".$query."
".$connect->ErrorMsg()); + + LimeExpressionManager::SetDirtyFlag(); // so that knows that token tables have changed $tokenoutput .= "\t

\n" - ."
".$clang->gT("Token table could not be created.")."
\n" - .$clang->gT("Error").": \n" . $connect->ErrorMsg() . "\n" - ."
".htmlspecialchars(implode(" ",$sqlarray))."
\n" - ."
" + ."
".$clang->gT("Import old tokens")."
" + ."
".$clang->gT("A token table has been created for this survey and the old tokens were imported.")." (\"".$dbprefix."tokens_$surveyid\")

\n" ."\n" - ."
\n" + .$clang->gT("Continue")."' onclick=\"window.open('$scriptname?action=tokens&sid=$surveyid', '_top')\" />\n" ."\n"; - - } else { - $createtokentableindex = $dict->CreateIndexSQL("{$tabname}_idx", $tabname, array('token')); - $dict->ExecuteSQLArray($createtokentableindex, false) or safe_die ("Failed to create token table index
$createtokentableindex

".$connect->ErrorMsg()); - if ($connect->databaseType == 'mysql' || $connect->databaseType == 'mysqli') - { - $query = 'CREATE INDEX idx_'.$tabname.'_efl ON '.$tabname.' ( email(120), firstname, lastname )'; - $result=$connect->Execute($query) or safe_die("Failed Rename!
".$query."
".$connect->ErrorMsg()); - } - - - $tokenoutput .= "\t

\n" - .$clang->gT("A token table has been created for this survey.")." (\"".$dbprefix."tokens_$surveyid\")

\n" - ."\n"; + return; } - return; - } - elseif (returnglobal('restoretable') == "Y" && returnglobal('oldtable') && bHasSurveyPermission($surveyid, 'surveyactivation','update')) - { - $query = db_rename_table(returnglobal('oldtable') , db_table_name_nq("tokens_$surveyid")); - $result=$connect->Execute($query) or safe_die("Failed Rename!
".$query."
".$connect->ErrorMsg()); - - LimeExpressionManager::SetDirtyFlag(); // so that knows that token tables have changed - - $tokenoutput .= "\t

\n" - ."
".$clang->gT("Import old tokens")."
" - ."
".$clang->gT("A token table has been created for this survey and the old tokens were imported.")." (\"".$dbprefix."tokens_$surveyid\")

\n" - ."\n" - ."
\n"; - return; - } - else - { - $query=db_select_tables_like("{$dbprefix}old\_tokens\_".$surveyid."\_%"); - $result=db_execute_num($query) or safe_die("Couldn't get old table list
".$query."
".$connect->ErrorMsg()); - $tcount=$result->RecordCount(); - if ($tcount > 0) + else { - while($rows=$result->FetchRow()) + $query=db_select_tables_like("{$dbprefix}old\_tokens\_".$surveyid."\_%"); + $result=db_execute_num($query) or safe_die("Couldn't get old table list
".$query."
".$connect->ErrorMsg()); + $tcount=$result->RecordCount(); + if ($tcount > 0) { - $oldlist[]=$rows[0]; + while($rows=$result->FetchRow()) + { + $oldlist[]=$rows[0]; + } } - } - $tokenoutput .= "\t
\n" - ."
".$clang->gT("Warning")."
\n" - ."
".$clang->gT("Tokens have not been initialised for this survey.")."

\n"; - if (bHasSurveyPermission($surveyid, 'surveyactivation','update')) - { - $tokenoutput .= $clang->gT("If you initialise tokens for this survey then this survey will only be accessible to users who provide a token either manually or by URL.") - ."

\n"; - - $thissurvey=getSurveyInfo($surveyid); - - if ($thissurvey['anonymized'] == 'Y') + $tokenoutput .= "\t
\n" + ."
".$clang->gT("Warning")."
\n" + ."
".$clang->gT("Tokens have not been initialised for this survey.")."

\n"; + if (bHasSurveyPermission($surveyid, 'surveyactivation','update') || bHasSurveyPermission($surveyid, 'tokens','create')) { - $tokenoutput .= "".$clang->gT("Note: If you turn on the -Anonymized responses- option for this survey then LimeSurvey will mark your completed tokens only with a 'Y' instead of date/time to ensure the anonymity of your participants.") + $tokenoutput .= $clang->gT("If you initialise tokens for this survey then this survey will only be accessible to users who provide a token either manually or by URL.") ."

\n"; - } - $tokenoutput .= $clang->gT("Do you want to create a token table for this survey?"); - $tokenoutput .= "

\n"; - $tokenoutput .= "\n"; - $tokenoutput .= "
\n"; - } - else - { - $tokenoutput .= $clang->gT("You don't have the permission to activate tokens."); - $tokenoutput .= "\n"; + $thissurvey=getSurveyInfo($surveyid); - } - // Do not offer old postgres token tables for restore since these are having an issue with missing index - if ($tcount>0 && $databasetype!='postgres' && bHasSurveyPermission($surveyid, 'surveyactivation','update')) - { - $tokenoutput .= "
".$clang->gT("Restore options")."
\n" - ."
\n" - ."
\n" - .$clang->gT("The following old token tables could be restored:")."

\n" - ."\n"; + $tokenoutput .= "
\n"; + } + else { - $tokenoutput .= "\n"; + $tokenoutput .= $clang->gT("You don't have the permission to activate tokens."); + $tokenoutput .= "\n"; + + } + // Do not offer old postgres token tables for restore since these are having an issue with missing index + if ($tcount>0 && $databasetype!='postgres' && bHasSurveyPermission($surveyid, 'surveyactivation','update')) + { + $tokenoutput .= "
".$clang->gT("Restore options")."
\n" + ."
\n" + ."\n" + .$clang->gT("The following old token tables could be restored:")."

\n" + ."

\n" + ."\n" + ."\n" + ."\n" + ."
\n"; } - $tokenoutput .= "

\n" - ."\n" - ."\n" - ."\n" - ."\n"; - } - return; - } + return; + } } #Lookup the names of the attributes /*$query = "SELECT attribute1, attribute2 FROM ".db_table_name('surveys')." WHERE sid=$surveyid"; - $result = db_execute_assoc($query) or safe_die("Couldn't execute query:
$query
".$connect->ErrorMsg()); - $row = $result->FetchRow(); - if ($row["attribute1"]) {$attr1_name = $row["attribute1"];} else {$attr1_name=$clang->gT("Attribute 1");} - if ($row["attribute2"]) {$attr2_name = $row["attribute2"];} else {$attr2_name=$clang->gT("Attribute 2");}*/ + $result = db_execute_assoc($query) or safe_die("Couldn't execute query:
$query
".$connect->ErrorMsg()); + $row = $result->FetchRow(); + if ($row["attribute1"]) {$attr1_name = $row["attribute1"];} else {$attr1_name=$clang->gT("Attribute 1");} + if ($row["attribute2"]) {$attr2_name = $row["attribute2"];} else {$attr2_name=$clang->gT("Attribute 2");}*/ // IF WE MADE IT THIS FAR, THEN THERE IS A TOKENS TABLE, SO LETS DEVELOP THE MENU ITEMS if($subaction != 'bounceprocessing') { - $tokenoutput .= "\t\n"; } // SEE HOW MANY RECORDS ARE IN THE TOKEN TABLE $tksq = "SELECT count(tid) FROM ".db_table_name("tokens_$surveyid"); @@ -688,36 +688,36 @@ // GIVE SOME INFORMATION ABOUT THE TOKENS if ($subaction=='') { - $tokenoutput .= "\t
".$clang->gT("Token summary")."
\n" - ."
\n" - ."\t\n" - ."\n"; + $tokenoutput .= "\t
".$clang->gT("Token summary")."
\n" + ."
\n" - .$clang->gT("Total records in this token table")." $tkcount
\n" + ."\t\n" + ."\n"; - $tksq = "SELECT count(*) FROM ".db_table_name("tokens_$surveyid")." WHERE token IS NULL OR token=''"; - $tksr = db_execute_num($tksq); - while ($tkr = $tksr->FetchRow()) - {$tokenoutput .= "\n";} + $tksq = "SELECT count(*) FROM ".db_table_name("tokens_$surveyid")." WHERE token IS NULL OR token=''"; + $tksr = db_execute_num($tksq); + while ($tkr = $tksr->FetchRow()) + {$tokenoutput .= "\n";} - $tksq = "SELECT count(*) FROM ".db_table_name("tokens_$surveyid")." WHERE (sent!='N' and sent<>'')"; - $tksr = db_execute_num($tksq); - while ($tkr = $tksr->FetchRow()) - {$tokenoutput .= "\n";} + $tksq = "SELECT count(*) FROM ".db_table_name("tokens_$surveyid")." WHERE (sent!='N' and sent<>'')"; + $tksr = db_execute_num($tksq); + while ($tkr = $tksr->FetchRow()) + {$tokenoutput .= "\n";} - $tksq = "SELECT count(*) FROM ".db_table_name("tokens_$surveyid")." WHERE emailstatus = 'optOut'"; - $tksr = db_execute_num($tksq); - while ($tkr = $tksr->FetchRow()) - {$tokenoutput .= "\n";} + $tksq = "SELECT count(*) FROM ".db_table_name("tokens_$surveyid")." WHERE emailstatus = 'optOut'"; + $tksr = db_execute_num($tksq); + while ($tkr = $tksr->FetchRow()) + {$tokenoutput .= "\n";} - $tksq = "SELECT count(*) FROM ".db_table_name("tokens_$surveyid")." WHERE (completed!='N' and completed<>'')"; - $tksr = db_execute_num($tksq) or safe_die ("Couldn't execute token selection query
$abquery
".$connect->ErrorMsg()); - while ($tkr = $tksr->FetchRow()) - {$tokenoutput .= "\n" - ."\t\n" - ."
\n" + .$clang->gT("Total records in this token table")." $tkcount
".$clang->gT("Total with no unique Token")." $tkr[0] / $tkcount
".$clang->gT("Total with no unique Token")." $tkr[0] / $tkcount
".$clang->gT("Total invitations sent")." $tkr[0] / $tkcount
".$clang->gT("Total invitations sent")." $tkr[0] / $tkcount
".$clang->gT("Total opted out")." $tkr[0] / $tkcount
".$clang->gT("Total opted out")." $tkr[0] / $tkcount
".$clang->gT("Total surveys completed")." $tkr[0] / $tkcount\n";} - $tokenoutput .= "

\n"; + $tksq = "SELECT count(*) FROM ".db_table_name("tokens_$surveyid")." WHERE (completed!='N' and completed<>'')"; + $tksr = db_execute_num($tksq) or safe_die ("Couldn't execute token selection query
$abquery
".$connect->ErrorMsg()); + while ($tkr = $tksr->FetchRow()) + {$tokenoutput .= "".$clang->gT("Total surveys completed")." $tkr[0] / $tkcount\n";} + $tokenoutput .= "\n" + ."\t\n" + ."
\n"; } @@ -726,85 +726,85 @@ if(isset($surveyid) && getEmailFormat($surveyid) == 'html') { - $ishtml=true; + $ishtml=true; } else { - $ishtml=false; + $ishtml=false; } if ($subaction == "exportdialog" && bHasSurveyPermission($surveyid, 'tokens','export') )//EXPORT FEATURE SUBMITTED BY PIETERJAN HEYSE { - $langquery = "SELECT language FROM ".db_table_name("tokens_$surveyid")." group by language"; - $langresult = db_execute_assoc($langquery); + $langquery = "SELECT language FROM ".db_table_name("tokens_$surveyid")." group by language"; + $langresult = db_execute_assoc($langquery); - $tokenoutput .= "\t
".$clang->gT("Token export options")."
\n"; - $tokenoutput .= "
\n" - ."" - ."

" - ."" - ."" - ."" - ."

"; + $tokenoutput.=" " + ."
  • " + ."
  •  
  • " + // ."
  • " + ."" + ."

    " + ."" + ."" + ."" + ."

    "; } $tokenoutput .= ""; + ."surveyid = '$surveyid'" + .""; if($subaction=="surveysettingsave") { - global $connect; - @$fieldvalue = array("bounceprocessing"=>$_POST['bounceprocessing'], - "bounce_email"=>$_POST['bounce_email'], - ); + global $connect; + @$fieldvalue = array("bounceprocessing"=>$_POST['bounceprocessing'], + "bounce_email"=>$_POST['bounce_email'], + ); - if(@$_POST['bounceprocessing']=='L') - { - $fieldvalue['bounceaccountencryption']=$_POST['bounceaccountencryption']; - $fieldvalue['bounceaccountuser']=$_POST['bounceaccountuser']; - $fieldvalue['bounceaccountpass']=$_POST['bounceaccountpass']; - $fieldvalue['bounceaccounttype']=$_POST['bounceaccounttype']; - $fieldvalue['bounceaccounthost']=$_POST['bounceaccounthost']; - } + if(@$_POST['bounceprocessing']=='L') + { + $fieldvalue['bounceaccountencryption']=$_POST['bounceaccountencryption']; + $fieldvalue['bounceaccountuser']=$_POST['bounceaccountuser']; + $fieldvalue['bounceaccountpass']=$_POST['bounceaccountpass']; + $fieldvalue['bounceaccounttype']=$_POST['bounceaccounttype']; + $fieldvalue['bounceaccounthost']=$_POST['bounceaccounthost']; + } - $connect->AutoExecute("{$dbprefix}surveys", $fieldvalue, 2,"sid=$surveyid",get_magic_quotes_gpc()); - $tokenoutput .= "
    ".$clang->gT("Bounce settings")."
    \n" - ."
    " - ."\t
    ".$clang->gT("Bounce settings have been saved.")."
    \n" - ."
    "; + $connect->AutoExecute("{$dbprefix}surveys", $fieldvalue, 2,"sid=$surveyid",get_magic_quotes_gpc()); + $tokenoutput .= "
    ".$clang->gT("Bounce settings")."
    \n" + ."
    " + ."\t
    ".$clang->gT("Bounce settings have been saved.")."
    \n" + ."
    "; } @@ -813,2497 +813,2497 @@ $settings=getSurveyInfo($surveyid); $tokenoutput .= "\t
    ".$clang->gT("Bounce settings")."
    \n"; $tokenoutput .= "
    \n" - ."
    " - - ."\t\n
  • \n" - ."\t\t
  • \n" - - ."\t
  • \n" - ."\t\t
  • \n" - . "\t
  • \n" - . "\t\t
  • \n" - - . "\t
  • \n" - . "\t\t\n"."".$clang->gT("Enter your hostname and port, e.g.: imap.gmail.com:995")."\n" - . "\t
  • \n" - . "\t\t
  • \n" - . "\t
  • \n" - . "\t\t
  • \n"; - $tokenoutput.= "\t
  • \n" - . "\t\t
  • \n
    ".""; - $tokenoutput .= "\t


    \n"; - - } + ."
    " + + ."\t\n
  • \n" + ."\t\t
  • \n" + + ."\t
  • \n" + ."\t\t
  • \n" + . "\t
  • \n" + . "\t\t
  • \n" + + . "\t
  • \n" + . "\t\t\n"."".$clang->gT("Enter your hostname and port, e.g.: imap.gmail.com:995")."\n" + . "\t
  • \n" + . "\t\t
  • \n" + . "\t
  • \n" + . "\t\t
  • \n"; + $tokenoutput.= "\t
  • \n" + . "\t\t
  • \n
    "."
    "; + $tokenoutput .= "\t


    \n"; + + } if ($subaction == "deleteall" && bHasSurveyPermission($surveyid, 'tokens', 'delete')){ - $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("Delete all token entries")."
    \n" - ."
    ".$clang->gT("All token entries have been deleted.")."

    \n"; - $subaction=""; + $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("Delete all token entries")."
    \n" + ."
    ".$clang->gT("All token entries have been deleted.")."

    \n"; + $subaction=""; } if ($subaction == "clearinvites" && bHasSurveyPermission($surveyid, 'tokens', 'update')) { - $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("Reset token invitation status")."
    \n" - ."
    ".$clang->gT("All token entries have been set to 'Not invited'.")."

    \n"; - $subaction=""; + $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("Reset token invitation status")."
    \n" + ."
    ".$clang->gT("All token entries have been set to 'Not invited'.")."

    \n"; + $subaction=""; } if ($subaction == "cleartokens" && bHasSurveyPermission($surveyid, 'tokens', 'update')) { - $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("Remove unique token numbers")."
    \n" - ."
    ".$clang->gT("All unique token numbers have been removed.")."

    \n"; - $subaction=""; + $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("Remove unique token numbers")."
    \n" + ."
    ".$clang->gT("All unique token numbers have been removed.")."

    \n"; + $subaction=""; } if (!$subaction && (bHasSurveyPermission($surveyid, 'tokens', 'update') || bHasSurveyPermission($surveyid, 'tokens', 'delete'))) { - $tokenoutput .= "\t
    ".$clang->gT("Token database administration options")."
    \n" - ."
    "; - - if (bHasSurveyPermission($surveyid, 'tokens', 'update')) - { - $tokenoutput .="
    \n"; + if (bHasSurveyPermission($surveyid, 'tokens', 'update')) + { + $tokenoutput .="\n"; } if ($subaction == "browse" || $subaction == "search") { - if (!isset($limit)) {$limit = 100;} - if (!isset($start)) {$start = 0;} - - if ($limit > $tkcount) {$limit=$tkcount;} - $next=$start+$limit; - $last=$start-$limit; - $end=$tkcount-$limit; - if ($end < 0) {$end=0;} - if ($last <0) {$last=0;} - if ($next >= $tkcount) {$next=$tkcount-$limit;} - if ($end < 0) {$end=0;} - $baselanguage = GetBaseLanguageFromSurveyID($surveyid); - - //ALLOW SELECTION OF NUMBER OF RECORDS SHOWN + if (!isset($limit)) {$limit = 100;} + if (!isset($start)) {$start = 0;} + + if ($limit > $tkcount) {$limit=$tkcount;} + $next=$start+$limit; + $last=$start-$limit; + $end=$tkcount-$limit; + if ($end < 0) {$end=0;} + if ($last <0) {$last=0;} + if ($next >= $tkcount) {$next=$tkcount-$limit;} + if ($end < 0) {$end=0;} + $baselanguage = GetBaseLanguageFromSurveyID($surveyid); + + //ALLOW SELECTION OF NUMBER OF RECORDS SHOWN if($subaction != 'bounceprocessing') { - $tokenoutput .="\t\n"; - $tokenoutput .= "\n"; - //COLUMN HEADINGS - $tokenoutput .= "\t\n" - ."\n" //Checkbox + $tokenoutput .= "
    \n"; + //COLUMN HEADINGS + $tokenoutput .= "\t\n" + ."\n" //Checkbox ."\n" // ID - - ."\n" //Actions + ."" + .""
+        .$clang->gT("Sort by: ")
+        ."ID"."ID\n" // ID + + ."\n" //Actions ."\n" + ."" + .""
+        .$clang->gT("Sort by: ")
+        .$clang->gT("First name")
+        ."".$clang->gT("First name")."\n" ."\n" + ."" + .""
+        .$clang->gT("Sort by: ")
+        .$clang->gT("Last name")
+        ."".$clang->gT("Last name")."\n" ."\n" + ."" + .""
+        .$clang->gT("Sort by: ")
+        .$clang->gT("Email address")
+        ."".$clang->gT("Email address")."\n" ."\n" - - ."\n" + ."" + .""
+        .$clang->gT("Sort by: ")
+        .$clang->gT("Email status")
+        ."".$clang->gT("Email status")."\n" + + ."\n" ."\n" + ."" + .""
+        .$clang->gT("Sort by: ")
+        .$clang->gT("Language")
+        ."".$clang->gT("Language")."\n" ."\n" + ."" + .""
+        .$clang->gT("Sort by: ")
+        .$clang->gT("Invitation sent?")
+        ."".$clang->gT("Invitation sent?")."\n" ."\n" - - ."\n" + ."" + .""
+        .$clang->gT("Sort by: ")
+        .$clang->gT("Reminder sent?")
+        ."".$clang->gT("Reminder sent?")."\n" + + ."\n" ."\n" - - ."\n" - - ."\n" - - ."\n"; - - $attrfieldnames=GetTokenFieldsAndNames($surveyid,true); - foreach ($attrfieldnames as $attr_name=>$attr_translation) - { - $tokenoutput .= "\n"; - } - $tokenoutput .="\t\n"; - - $tokenfieldorder=array('tid', - 'firstname', - 'lastname', - 'email', - 'emailstatus', - 'token', - 'language', - 'sent', - 'remindersent', - 'remindercount', - 'completed', - 'usesleft', - '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'])!=''){ - $datetimeobj = new Date_Time_Converter($brow['validfrom'] , "Y-m-d H:i:s"); - $brow['validfrom']=$datetimeobj->convert($dateformatdetails['phpdate'].' H:i'); - }; - if (trim($brow['validuntil'])!=''){ - $datetimeobj = new Date_Time_Converter($brow['validuntil'] , "Y-m-d H:i:s"); - $brow['validuntil']=$datetimeobj->convert($dateformatdetails['phpdate'].' H:i'); - }; - - if ($bgc == "evenrow") {$bgc = "oddrow";} else {$bgc = "evenrow";} - $tokenoutput .= "\t\n"; - - $tokenoutput .= "\n"; - - foreach ($tokenfieldorder as $tokenfieldname) + ."" + .""
+        .$clang->gT("Sort by: ")
+        .$clang->gT("Completed?")
+        ."".$clang->gT("Completed?")."\n" + + ."\n" + + ."\n" + + ."\n"; + + $attrfieldnames=GetTokenFieldsAndNames($surveyid,true); + foreach ($attrfieldnames as $attr_name=>$attr_translation) + { + $tokenoutput .= "\n"; + } + $tokenoutput .="\t\n"; + + $tokenfieldorder=array('tid', + 'firstname', + 'lastname', + 'email', + 'emailstatus', + 'token', + 'language', + 'sent', + 'remindersent', + 'remindercount', + 'completed', + 'usesleft', + 'validfrom', + 'validuntil'); + foreach ($attrfieldnames as $attr_name=>$attr_translation) { + $tokenfieldorder[]=$attr_name; + } - if ($tokenfieldname =='email' && $brow['emailstatus'] != 'OK') + while ($brow = $bresult->FetchRow()) + { + $brow['token'] = trim($brow['token']); + if (trim($brow['validfrom'])!=''){ + $datetimeobj = new Date_Time_Converter($brow['validfrom'] , "Y-m-d H:i:s"); + $brow['validfrom']=$datetimeobj->convert($dateformatdetails['phpdate'].' H:i'); + }; + if (trim($brow['validuntil'])!=''){ + $datetimeobj = new Date_Time_Converter($brow['validuntil'] , "Y-m-d H:i:s"); + $brow['validuntil']=$datetimeobj->convert($dateformatdetails['phpdate'].' H:i'); + }; + + if ($bgc == "evenrow") {$bgc = "oddrow";} else {$bgc = "evenrow";} + $tokenoutput .= "\t\n"; + + $tokenoutput .= "\n"; + + foreach ($tokenfieldorder as $tokenfieldname) { - if ($brow['emailstatus']!='OptOut') - { - $tokenoutput .= "\n"; - } - else + + if ($tokenfieldname =='email' && $brow['emailstatus'] != 'OK') { - $tokenoutput .= "\n"; + if ($brow['emailstatus']!='OptOut') + { + $tokenoutput .= "\n"; + } + else + { + $tokenoutput .= "\n"; + } } - } // elseif ($tokenfieldname != 'emailstatus') - else - { - if ($tokenfieldname=='tid') - { - $tokenoutput.=""; - } else { - $tokenoutput .= '\n"; - } - } - if ($tokenfieldname=='tid') - { - $tokenoutput .= ""; } else { - $tokenoutput .= ""; + $tokenoutput .= '\n"; } - $tokenoutput .=" "; } - if (bHasSurveyPermission($surveyid, 'tokens','delete')) + if ($tokenfieldname=='tid') { - $tokenoutput .="gT("Are you sure you want to delete this entry?","js")." (".$brow['tid'].")')) {".get2post("$scriptname?action=tokens&sid=$surveyid&subaction=delete&tid=".$brow['tid']."&limit=$limit&start=$start&order=$order")."}\" />"; - } + $tokenoutput .= "\n"; } - elseif ($brow['completed'] == "N" && $brow['token'] && $brow['sent'] == "N" && trim($brow['email'])!='' && bHasSurveyPermission($surveyid, 'tokens','update')) - { - $tokenoutput .= ""; - } - elseif ($brow['completed'] == "N" && $brow['token'] && $brow['sent'] != "N" && trim($brow['email'])!='') // reminder button - { - $tokenoutput .= ""; - } - $tokenoutput .= "\n\n"; } + $tokenoutput .= "\t\n"; } - $tokenoutput .= "\t\n"; - } - // Multiple item actions - if ($bresult->rowCount() > 0) { - $tokenoutput .= "\n" - . "\n" + . "\n" - . "\n"; - } - //End multiple item actions + if (bHasSurveyPermission($surveyid, 'tokens','update')) + { + $tokenoutput .= " " + . "" + . " " + . ""; + } + $tokenoutput .= "\n"; + $tokenoutput .= "\n" + . "\n"; + } + //End multiple item actions - $tokenoutput .= "
    " - ."" - .""
-    .$clang->gT("Sort by: ")
-    ."ID"."ID".$clang->gT("Actions")."".$clang->gT("Actions")."" - ."" - .""
-    .$clang->gT("Sort by: ")
-    .$clang->gT("First name")
-    ."".$clang->gT("First name")."" - ."" - .""
-    .$clang->gT("Sort by: ")
-    .$clang->gT("Last name")
-    ."".$clang->gT("Last name")."" - ."" - .""
-    .$clang->gT("Sort by: ")
-    .$clang->gT("Email address")
-    ."".$clang->gT("Email address")."" - ."" - .""
-    .$clang->gT("Sort by: ")
-    .$clang->gT("Email status")
-    ."".$clang->gT("Email status")."" - ."" - .""
-    .$clang->gT("Sort by: ")
-    .$clang->gT("Token")
-    ."".$clang->gT("Token")."" + ."" + .""
+        .$clang->gT("Sort by: ")
+        .$clang->gT("Token")
+        ."".$clang->gT("Token")."" - ."" - .""
-    .$clang->gT("Sort by: ")
-    .$clang->gT("Language")
-    ."".$clang->gT("Language")."" - ."" - .""
-    .$clang->gT("Sort by: ")
-    .$clang->gT("Invitation sent?")
-    ."".$clang->gT("Invitation sent?")."" - ."" - .""
-    .$clang->gT("Sort by: ")
-    .$clang->gT("Reminder sent?")
-    ."".$clang->gT("Reminder sent?")."" - ."" - .""
-    .$clang->gT("Sort by: ")
-    .$clang->gT("Reminder count")
-    ."".$clang->gT("Reminder count")."" + ."" + .""
+        .$clang->gT("Sort by: ")
+        .$clang->gT("Reminder count")
+        ."".$clang->gT("Reminder count")."" - ."" - .""
-    .$clang->gT("Sort by: ")
-    .$clang->gT("Completed?")
-    ."".$clang->gT("Completed?")."" - ."" - .""
-    .$clang->gT("Sort by: ")
-    .$clang->gT("Uses left")
-    ."".$clang->gT("Uses left")."" - ."" - .""
-    .$clang->gT("Sort by: ")
-    .$clang->gT("Valid from")
-    ."".$clang->gT("Valid from")."" - ."" - .""
-    .$clang->gT("Sort by: ")
-    .$clang->gT("Valid until")
-    ."".$clang->gT("Valid until")."" - ."" - ."".htmlspecialchars($attr_translation,ENT_QUOTES,'utf-8')."
    " + ."" + .""
+        .$clang->gT("Sort by: ")
+        .$clang->gT("Uses left")
+        ."".$clang->gT("Uses left")."" + ."" + .""
+        .$clang->gT("Sort by: ")
+        .$clang->gT("Valid from")
+        ."".$clang->gT("Valid from")."" + ."" + .""
+        .$clang->gT("Sort by: ")
+        .$clang->gT("Valid until")
+        ."".$clang->gT("Valid until")."" + ."" + ."".htmlspecialchars($attr_translation,ENT_QUOTES,'utf-8')."
    " - ."" - ."$brow[$tokenfieldname]" - ."" - ."$brow[$tokenfieldname]" + ."" + ."$brow[$tokenfieldname]" + ."" + ."$brow[$tokenfieldname]".$brow[$tokenfieldname]."'.htmlspecialchars($brow[$tokenfieldname])."\n"; - if (bHasSurveyPermission($surveyid, 'tokens','update')) - { - if (($brow['completed'] == "N" || $brow['completed'] == "") &&$brow['token']) + if ($tokenfieldname=='tid') { - $toklang = ($brow['language'] == '') ? $baselanguage : $brow['language']; - $tokenoutput .= "\n"; + $tokenoutput.="".$brow[$tokenfieldname]."'.htmlspecialchars($brow[$tokenfieldname])."\n"; + if (bHasSurveyPermission($surveyid, 'tokens','update')) + { + if (($brow['completed'] == "N" || $brow['completed'] == "") &&$brow['token']) + { + $toklang = ($brow['language'] == '') ? $baselanguage : $brow['language']; + $tokenoutput .= "\n"; + } + else + { + $tokenoutput .= ""; + } + $tokenoutput .=" "; + } + if (bHasSurveyPermission($surveyid, 'tokens','delete')) + { + $tokenoutput .="gT("Are you sure you want to delete this entry?","js")." (".$brow['tid'].")')) {".get2post("$scriptname?action=tokens&sid=$surveyid&subaction=delete&tid=".$brow['tid']."&limit=$limit&start=$start&order=$order")."}\" />"; + } - if ($brow['completed'] != "N" && $brow['completed']!="" && $surveyprivate == "N" && $thissurvey['active']=='Y') - { - // Get response Id - $query="SELECT id FROM ".db_table_name('survey_'.$surveyid)." WHERE token='{$brow['token']}' ORDER BY id desc"; - $result=db_execute_num($query) or safe_die ("
    Could not find token!
    \n" .$connect->ErrorMsg()); - list($id) = $result->FetchRow(); + if ($brow['completed'] != "N" && $brow['completed']!="" && $surveyprivate == "N" && $thissurvey['active']=='Y') + { + // Get response Id + $query="SELECT id FROM ".db_table_name('survey_'.$surveyid)." WHERE token='{$brow['token']}' ORDER BY id desc"; + $result=db_execute_num($query) or safe_die ("
    Could not find token!
    \n" .$connect->ErrorMsg()); + list($id) = $result->FetchRow(); - // UPDATE button to the tokens display in the MPID Actions column - if ($id) + // UPDATE button to the tokens display in the MPID Actions column + if ($id) + { + $tokenoutput .= "\n"; + } + } + elseif ($brow['completed'] == "N" && $brow['token'] && $brow['sent'] == "N" && trim($brow['email'])!='' && bHasSurveyPermission($surveyid, 'tokens','update')) { - $tokenoutput .= "\n"; + .$clang->gT("Send invitation email to this entry") + ."' onclick=\"window.open('{$scriptname}?action=tokens&sid={$surveyid}&subaction=email&tid=".$brow['tid']."', '_top')\" />"; } + elseif ($brow['completed'] == "N" && $brow['token'] && $brow['sent'] != "N" && trim($brow['email'])!='') // reminder button + { + $tokenoutput .= ""; + } + $tokenoutput .= "\n
    "; + // Multiple item actions + if ($bresult->rowCount() > 0) { + $tokenoutput .= "
    "; - if (bHasSurveyPermission($surveyid, 'tokens','delete')) - { - $tokenoutput .= "" - . "gT("Are you sure you want to delete the selected entries?","js") - ."')) {".get2post("{$scriptname}?action=tokens&sid={$surveyid}&subaction=delete&tids=document.getElementById('tokenboxeschecked').value&limit={$limit}&start={$start}&order={$order}")."}}else{alert('".$clang->gT("No tokens selected",'js')."');}\" />"; + if (bHasSurveyPermission($surveyid, 'tokens','delete')) + { + $tokenoutput .= "" + . "gT("Are you sure you want to delete the selected entries?","js") + ."')) {".get2post("{$scriptname}?action=tokens&sid={$surveyid}&subaction=delete&tids=document.getElementById('tokenboxeschecked').value&limit={$limit}&start={$start}&order={$order}")."}}else{alert('".$clang->gT("No tokens selected",'js')."');}\" />"; - } + } - if (bHasSurveyPermission($surveyid, 'tokens','update')) - { - $tokenoutput .= " " - . "" - . " " - . ""; - } - $tokenoutput .= "\n"; - $tokenoutput .= "
    \n
    \n"; + $tokenoutput .= "\n
    \n"; } if ($subaction == "kill" && bHasSurveyPermission($surveyid, 'surveyactivation', 'update')) { - $date = date('YmdHis'); - $tokenoutput .= "
    ".$clang->gT("Delete Tokens Table")."
    \n" - ."
    \n"; - // ToDo: Just delete it if there is no token in the table - if (!isset($_POST['ok']) || !$_POST['ok']) - { - $tokenoutput .= "
    ".$clang->gT("Warning")."

    \n" - .$clang->gT("If you delete this table tokens will no longer be required to access this survey.")."
    ".$clang->gT("A backup of this table will be made if you proceed. Your system administrator will be able to access this table.")."
    \n" - ."( \"old_tokens_{$surveyid}_$date\" )

    \n" - ."\n" - ."\n"; - } - elseif (isset($_POST['ok']) && $_POST['ok'] == "surething") - { - $oldtable = "tokens_$surveyid"; - $newtable = "old_tokens_{$surveyid}_$date"; - $deactivatequery = db_rename_table( db_table_name_nq($oldtable), db_table_name_nq($newtable)); - - if ($databasetype=='postgres') - { - // If you deactivate a postgres table you have to rename the according sequence too and alter the id field to point to the changed sequence - $oldTableJur = db_table_name_nq($oldtable); - $deactivatequery = db_rename_table(db_table_name_nq($oldtable),db_table_name_nq($newtable).'_tid_seq'); - $deactivateresult = $connect->Execute($deactivatequery) or die ("oldtable : ".$oldtable. " / oldtableJur : ". $oldTableJur . " / ".htmlspecialchars($deactivatequery)." / Could not rename the old sequence for this token table. The database reported the following error:
    ".htmlspecialchars($connect->ErrorMsg())."

    ".$clang->gT("Main Admin Screen").""); - $setsequence="ALTER TABLE ".db_table_name_nq($newtable)."_tid_seq ALTER COLUMN tid SET DEFAULT nextval('".db_table_name_nq($newtable)."_tid_seq'::regclass);"; - $deactivateresult = $connect->Execute($setsequence) or die (htmlspecialchars($setsequence)." Could not alter the field tid to point to the new sequence name for this token table. The database reported the following error:
    ".htmlspecialchars($connect->ErrorMsg())."

    Survey was not deactivated either.

    ".$clang->gT("Main Admin Screen").""); - $setidx="ALTER INDEX ".db_table_name_nq($oldtable)."_idx RENAME TO ".db_table_name_nq($newtable)."_idx;"; - $deactivateresult = $connect->Execute($setidx) or die (htmlspecialchars($setidx)." Could not alter the index for this token table. The database reported the following error:
    ".htmlspecialchars($connect->ErrorMsg())."

    Survey was not deactivated either.

    ".$clang->gT("Main Admin Screen").""); - } else { - $deactivateresult = $connect->Execute($deactivatequery) or die ("Couldn't deactivate because:
    \n".htmlspecialchars($connect->ErrorMsg())." - Query: ".htmlspecialchars($deactivatequery)."

    \nAdmin\n"); + $date = date('YmdHis'); + $tokenoutput .= "
    ".$clang->gT("Delete Tokens Table")."
    \n" + ."
    \n"; + // ToDo: Just delete it if there is no token in the table + if (!isset($_POST['ok']) || !$_POST['ok']) + { + $tokenoutput .= "
    ".$clang->gT("Warning")."

    \n" + .$clang->gT("If you delete this table tokens will no longer be required to access this survey.")."
    ".$clang->gT("A backup of this table will be made if you proceed. Your system administrator will be able to access this table.")."
    \n" + ."( \"old_tokens_{$surveyid}_$date\" )

    \n" + ."\n" + ."\n"; } - LimeExpressionManager::SetDirtyFlag(); // so that knows that token tables have changed + elseif (isset($_POST['ok']) && $_POST['ok'] == "surething") + { + $oldtable = "tokens_$surveyid"; + $newtable = "old_tokens_{$surveyid}_$date"; + $deactivatequery = db_rename_table( db_table_name_nq($oldtable), db_table_name_nq($newtable)); - $tokenoutput .= '
    '.$clang->gT("The tokens table has now been removed and tokens are no longer required to access this survey.")."
    ".$clang->gT("A backup of this table has been made and can be accessed by your system administrator.")."
    \n" - ."(\"{$dbprefix}old_tokens_{$surveyid}_$date\")"."

    \n" - ."\n"; - } - $tokenoutput .= "
    \n"; + if ($databasetype=='postgres') + { + // If you deactivate a postgres table you have to rename the according sequence too and alter the id field to point to the changed sequence + $oldTableJur = db_table_name_nq($oldtable); + $deactivatequery = db_rename_table(db_table_name_nq($oldtable),db_table_name_nq($newtable).'_tid_seq'); + $deactivateresult = $connect->Execute($deactivatequery) or die ("oldtable : ".$oldtable. " / oldtableJur : ". $oldTableJur . " / ".htmlspecialchars($deactivatequery)." / Could not rename the old sequence for this token table. The database reported the following error:
    ".htmlspecialchars($connect->ErrorMsg())."

    ".$clang->gT("Main Admin Screen").""); + $setsequence="ALTER TABLE ".db_table_name_nq($newtable)."_tid_seq ALTER COLUMN tid SET DEFAULT nextval('".db_table_name_nq($newtable)."_tid_seq'::regclass);"; + $deactivateresult = $connect->Execute($setsequence) or die (htmlspecialchars($setsequence)." Could not alter the field tid to point to the new sequence name for this token table. The database reported the following error:
    ".htmlspecialchars($connect->ErrorMsg())."

    Survey was not deactivated either.

    ".$clang->gT("Main Admin Screen").""); + $setidx="ALTER INDEX ".db_table_name_nq($oldtable)."_idx RENAME TO ".db_table_name_nq($newtable)."_idx;"; + $deactivateresult = $connect->Execute($setidx) or die (htmlspecialchars($setidx)." Could not alter the index for this token table. The database reported the following error:
    ".htmlspecialchars($connect->ErrorMsg())."

    Survey was not deactivated either.

    ".$clang->gT("Main Admin Screen").""); + } else { + $deactivateresult = $connect->Execute($deactivatequery) or die ("Couldn't deactivate because:
    \n".htmlspecialchars($connect->ErrorMsg())." - Query: ".htmlspecialchars($deactivatequery)."

    \nAdmin\n"); + } + LimeExpressionManager::SetDirtyFlag(); // so that knows that token tables have changed + + $tokenoutput .= '
    '.$clang->gT("The tokens table has now been removed and tokens are no longer required to access this survey.")."
    ".$clang->gT("A backup of this table has been made and can be accessed by your system administrator.")."
    \n" + ."(\"{$dbprefix}old_tokens_{$surveyid}_$date\")"."

    \n" + ."\n"; + } + $tokenoutput .= "
    \n"; } if ($subaction == "email" && bHasSurveyPermission($surveyid, 'tokens','update')) { - if (getEmailFormat($surveyid) == 'html') - { - $ishtml=true; - } - else - { - $ishtml=false; - } - - $tokenoutput .= PrepareEditorScript(); - $tokenoutput .= "\t
    " - .$clang->gT("Send email invitations")."
    \n" - ."\t

    \n"; // Wrapping Div - if (!isset($_POST['ok']) || !$_POST['ok']) - { - if ($thissurvey['active']!='Y') + if (getEmailFormat($surveyid) == 'html') { - $tokenoutput .="
    ".$clang->gT('Warning!')."
    ".$clang->gT("This survey is not yet activated and so your participants won't be able to fill out the survey.")."
    "; + $ishtml=true; } - $tokenoutput .= "\n
    \n" // Tabs Div - . "\n"; - $tokenoutput .= "
    "; // Form - - foreach ($surveylangs as $language) + $tokenoutput .= PrepareEditorScript(); + $tokenoutput .= "\t
    " + .$clang->gT("Send email invitations")."
    \n" + ."\t

    \n"; // Wrapping Div + if (!isset($_POST['ok']) || !$_POST['ok']) { - //GET SURVEY DETAILS - $thissurvey=getSurveyInfo($surveyid,$language); - $bplang = new limesurvey_lang($language); - - if ($ishtml===true) + if ($thissurvey['active']!='Y') { - $aDefaultTexts=aTemplateDefaultTexts($bplang); + $tokenoutput .="
    ".$clang->gT('Warning!')."
    ".$clang->gT("This survey is not yet activated and so your participants won't be able to fill out the survey.")."
    "; } - else + $tokenoutput .= "\n
    \n" // Tabs Div + . "\n"; + $tokenoutput .= ""; // Form + + + foreach ($surveylangs as $language) { + //GET SURVEY DETAILS + $thissurvey=getSurveyInfo($surveyid,$language); + $bplang = new limesurvey_lang($language); + if ($ishtml===true) { - $thissurvey['email_invite']=html_escape($aDefaultTexts['invitation']); + $aDefaultTexts=aTemplateDefaultTexts($bplang); } else { - $thissurvey['email_invite']=$aDefaultTexts['invitation']; + $aDefaultTexts=aTemplateDefaultTexts($bplang,'unescaped'); + } + if (!$thissurvey['email_invite']) + { + if ($ishtml===true) + { + $thissurvey['email_invite']=html_escape($aDefaultTexts['invitation']); + } + else + { + $thissurvey['email_invite']=$aDefaultTexts['invitation']; + } + } + if (!$thissurvey['email_invite_subj']) + { + $thissurvey['email_invite_subj']=$aDefaultTexts['invitation_subject']; } + $fieldsarray["{ADMINNAME}"]= $thissurvey['adminname']; + $fieldsarray["{ADMINEMAIL}"]=$thissurvey['adminemail']; + $fieldsarray["{SURVEYNAME}"]=$thissurvey['name']; + $fieldsarray["{SURVEYDESCRIPTION}"]=$thissurvey['description']; + $fieldsarray["{EXPIRY}"]=$thissurvey["expiry"]; + + $subject=Replacefields($thissurvey['email_invite_subj'], $fieldsarray,false); + $textarea=Replacefields($thissurvey['email_invite'], $fieldsarray,false); + if ($ishtml!==true){$textarea=str_replace(array('',''),array(''),$textarea);} + $tokenoutput .= '
    '."\n"; // Language Tab Div + + $tokenoutput .= "\t
      \n" + ."
    • \n" + ."\" />
    • \n" + + ."
    • \n" + ."
    • \n" + + ."
    • \n" + ."\n" + . getEditor("email-inv","message_$language","[".$clang->gT("Invitation email:", "js")."](".$language.")",$surveyid,'','',$action) + ."
    • \n" + ."\t
    \n"; // End Language Tab Div + } - if (!$thissurvey['email_invite_subj']) + //$tokenoutput .= "
    "; // TIBO: commenting this unexpected end div + /* + if (isset($tokenid)) { - $thissurvey['email_invite_subj']=$aDefaultTexts['invitation_subject']; - } - $fieldsarray["{ADMINNAME}"]= $thissurvey['adminname']; - $fieldsarray["{ADMINEMAIL}"]=$thissurvey['adminemail']; - $fieldsarray["{SURVEYNAME}"]=$thissurvey['name']; - $fieldsarray["{SURVEYDESCRIPTION}"]=$thissurvey['description']; - $fieldsarray["{EXPIRY}"]=$thissurvey["expiry"]; - - $subject=Replacefields($thissurvey['email_invite_subj'], $fieldsarray,false); - $textarea=Replacefields($thissurvey['email_invite'], $fieldsarray,false); - if ($ishtml!==true){$textarea=str_replace(array('',''),array(''),$textarea);} - $tokenoutput .= '
    '."\n"; // Language Tab Div - - $tokenoutput .= "\t
      \n" - ."
    • \n" - ."\" />
    • \n" - - ."
    • \n" - ."
    • \n" - - ."
    • \n" - ."\n" - . getEditor("email-inv","message_$language","[".$clang->gT("Invitation email:", "js")."](".$language.")",$surveyid,'','',$action) - ."
    • \n" - ."\t
    \n"; // End Language Tab Div - - } - //$tokenoutput .= "
    "; // TIBO: commenting this unexpected end div - /* - if (isset($tokenid)) - { - $tokenoutput .= "
  • ".$tokenid - ."
  • "; - } - if (isset($tokenids) && count($tokenids) > 0) - { - $tokenoutput .= "
  • ".implode(", ", $tokenids) - ."
  • "; - } else { - $tokenoutput .= "
  • " - .$clang->gT("All tokens who have not yet been sent an invitation") - ."
  • "; - } - */ - $tokenoutput .="\t

    \n" - ."\t

    \n" - ."\t\n" - ."\t\n" - ."\t\n" - ."\t\n"; - if (isset($tokenid)) {$tokenoutput .= "\t\n";} - if (isset($tokenids)) {$tokenoutput .= "\n\n";} - $tokenoutput .= "

    \n"; - - } - else - { - $tokenoutput .= "
    \n" - ."\t
    \n"; - $tokenoutput .= $clang->gT("Sending invitations..."); - $tokenoutput .= "\n\t
    \n"; - if (isset($tokenid)) {$tokenoutput .= " (".$clang->gT("Sending to Token ID").": {$tokenid})";} - if (isset($tokenids)) {$tokenoutput .= " (".$clang->gT("Sending to Token IDs").": ".implode(", ", $tokenids).")";} - $tokenoutput .= "
    \n"; + $tokenoutput .= "
  • ".$tokenid + ."
  • "; + } + if (isset($tokenids) && count($tokenids) > 0) + { + $tokenoutput .= "
  • ".implode(", ", $tokenids) + ."
  • "; + } else { + $tokenoutput .= "
  • " + .$clang->gT("All tokens who have not yet been sent an invitation") + ."
  • "; + } + */ + $tokenoutput .="\t

    \n" + ."\t

    \n" + ."\t\n" + ."\t\n" + ."\t\n" + ."\t\n"; + if (isset($tokenid)) {$tokenoutput .= "\t\n";} + if (isset($tokenids)) {$tokenoutput .= "\n\n";} + $tokenoutput .= "

    \n"; - if (isset($_POST['bypassbademails']) && $_POST['bypassbademails'] == 'Y') - { - $SQLemailstatuscondition = " AND emailstatus = 'OK'"; } else { - $SQLemailstatuscondition = " AND emailstatus <> 'OptOut'"; - } + $tokenoutput .= "
    \n" + ."\t
    \n"; + $tokenoutput .= $clang->gT("Sending invitations..."); + $tokenoutput .= "\n\t
    \n"; + if (isset($tokenid)) {$tokenoutput .= " (".$clang->gT("Sending to Token ID").": {$tokenid})";} + if (isset($tokenids)) {$tokenoutput .= " (".$clang->gT("Sending to Token IDs").": ".implode(", ", $tokenids).")";} + $tokenoutput .= "
    \n"; + + if (isset($_POST['bypassbademails']) && $_POST['bypassbademails'] == 'Y') + { + $SQLemailstatuscondition = " AND emailstatus = 'OK'"; + } + else + { + $SQLemailstatuscondition = " AND emailstatus <> 'OptOut'"; + } - $ctquery = "SELECT * FROM ".db_table_name("tokens_{$surveyid}")." WHERE ((completed ='N') or (completed='')) AND ((sent ='N') or (sent='')) AND token !='' AND email != '' $SQLemailstatuscondition"; + $ctquery = "SELECT * FROM ".db_table_name("tokens_{$surveyid}")." WHERE ((completed ='N') or (completed='')) AND ((sent ='N') or (sent='')) AND token !='' AND email != '' $SQLemailstatuscondition"; - if (isset($tokenid)) {$ctquery .= " AND tid='{$tokenid}'";} - if (isset($tokenids)) {$ctquery .= " AND tid IN ('".implode("', '", $tokenids)."')";} - $tokenoutput .= "\n"; - $ctresult = $connect->Execute($ctquery) or safe_die("Database error!
    \n" . $connect->ErrorMsg()); - $ctcount = $ctresult->RecordCount(); - $ctfieldcount = $ctresult->FieldCount(); + if (isset($tokenid)) {$ctquery .= " AND tid='{$tokenid}'";} + if (isset($tokenids)) {$ctquery .= " AND tid IN ('".implode("', '", $tokenids)."')";} + $tokenoutput .= "\n"; + $ctresult = $connect->Execute($ctquery) or safe_die("Database error!
    \n" . $connect->ErrorMsg()); + $ctcount = $ctresult->RecordCount(); + $ctfieldcount = $ctresult->FieldCount(); - $emquery = "SELECT * FROM ".db_table_name("tokens_{$surveyid}")." WHERE ((completed ='N') or (completed='')) AND ((sent ='N') or (sent='')) AND token !='' AND email != '' $SQLemailstatuscondition"; + $emquery = "SELECT * FROM ".db_table_name("tokens_{$surveyid}")." WHERE ((completed ='N') or (completed='')) AND ((sent ='N') or (sent='')) AND token !='' AND email != '' $SQLemailstatuscondition"; - if (isset($tokenid)) {$emquery .= " and tid='{$tokenid}'";} - if (isset($tokenids)) {$emquery .= " AND tid IN ('".implode("', '", $tokenids)."')";} - $tokenoutput .= "\n\n\n\n"; - $emresult = db_select_limit_assoc($emquery,$maxemails) or safe_die ("Couldn't do query.
    \n$emquery
    \n".$connect->ErrorMsg()); - $emcount = $emresult->RecordCount(); + if (isset($tokenid)) {$emquery .= " and tid='{$tokenid}'";} + if (isset($tokenids)) {$emquery .= " AND tid IN ('".implode("', '", $tokenids)."')";} + $tokenoutput .= "\n\n\n\n"; + $emresult = db_select_limit_assoc($emquery,$maxemails) or safe_die ("Couldn't do query.
    \n$emquery
    \n".$connect->ErrorMsg()); + $emcount = $emresult->RecordCount(); - $surveylangs = GetAdditionalLanguagesFromSurveyID($surveyid); - $baselanguage = GetBaseLanguageFromSurveyID($surveyid); - array_unshift($surveylangs,$baselanguage); + $surveylangs = GetAdditionalLanguagesFromSurveyID($surveyid); + $baselanguage = GetBaseLanguageFromSurveyID($surveyid); + array_unshift($surveylangs,$baselanguage); - foreach ($surveylangs as $language) - { - $_POST['message_'.$language]=auto_unescape($_POST['message_'.$language]); - $_POST['subject_'.$language]=auto_unescape($_POST['subject_'.$language]); - if ($ishtml) $_POST['message_'.$language] = html_entity_decode($_POST['message_'.$language], ENT_QUOTES, $emailcharset); - } + foreach ($surveylangs as $language) + { + $_POST['message_'.$language]=auto_unescape($_POST['message_'.$language]); + $_POST['subject_'.$language]=auto_unescape($_POST['subject_'.$language]); + if ($ishtml) $_POST['message_'.$language] = html_entity_decode($_POST['message_'.$language], ENT_QUOTES, $emailcharset); + } - $attributes=GetTokenFieldsAndNames($surveyid); - if ($emcount > 0) - { - $tokenoutput .= "
      \n"; - $oMail = new PHPMailer; - while ($emrow = $emresult->FetchRow()) + $attributes=GetTokenFieldsAndNames($surveyid); + if ($emcount > 0) { - unset($fieldsarray); + $tokenoutput .= "
        \n"; + $oMail = new PHPMailer; + while ($emrow = $emresult->FetchRow()) + { + unset($fieldsarray); $to=array(); $aEmailaddresses=explode(';',$emrow['email']); foreach($aEmailaddresses as $sEmailaddress) { $to[]=$emrow['firstname']." ".$emrow['lastname']." <{$sEmailaddress}>"; } - $fieldsarray["{EMAIL}"]=$emrow['email']; - $fieldsarray["{FIRSTNAME}"]=$emrow['firstname']; - $fieldsarray["{LASTNAME}"]=$emrow['lastname']; - $fieldsarray["{TOKEN}"]=$emrow['token']; - $fieldsarray["{LANGUAGE}"]=$emrow['language']; - $fieldsarray["{SID}"]=$fieldsarray["{SURVEYID}"]=$surveyid; - $fieldsarray["{SURVEYNAME}"]=$thissurvey["surveyls_title"]; - - foreach ($attributes as $attributefield=>$attributedescription) - { - $fieldsarray['{'.strtoupper($attributefield).'}']=$emrow[$attributefield]; - $fieldsarray['{TOKEN:'.strtoupper($attributefield).'}']=$emrow[$attributefield]; - } - - $emrow['language']=trim($emrow['language']); - if ($emrow['language']=='') {$emrow['language']=$baselanguage;} //if language is not given use default - $found = array_search($emrow['language'], $surveylangs); - if ($found==false) {$emrow['language']=$baselanguage;} + $fieldsarray["{EMAIL}"]=$emrow['email']; + $fieldsarray["{FIRSTNAME}"]=$emrow['firstname']; + $fieldsarray["{LASTNAME}"]=$emrow['lastname']; + $fieldsarray["{TOKEN}"]=$emrow['token']; + $fieldsarray["{LANGUAGE}"]=$emrow['language']; + $fieldsarray["{SID}"]=$fieldsarray["{SURVEYID}"]=$surveyid; + $fieldsarray["{SURVEYNAME}"]=$thissurvey["surveyls_title"]; + + foreach ($attributes as $attributefield=>$attributedescription) + { + $fieldsarray['{'.strtoupper($attributefield).'}']=$emrow[$attributefield]; + $fieldsarray['{TOKEN:'.strtoupper($attributefield).'}']=$emrow[$attributefield]; + } - $from = $_POST['from_'.$emrow['language']]; + $emrow['language']=trim($emrow['language']); + if ($emrow['language']=='') {$emrow['language']=$baselanguage;} //if language is not given use default + $found = array_search($emrow['language'], $surveylangs); + if ($found==false) {$emrow['language']=$baselanguage;} - if ($ishtml === false) - { - $fieldsarray["{OPTOUTURL}"]="$publicurl/optout.php?lang=".trim($emrow['language'])."&sid=$surveyid&token={$emrow['token']}"; + $from = $_POST['from_'.$emrow['language']]; - if ( $modrewrite ) + if ($ishtml === false) { - $fieldsarray["{SURVEYURL}"]="$publicurl/$surveyid/lang-".trim($emrow['language'])."/tk-{$emrow['token']}"; + $fieldsarray["{OPTOUTURL}"]="$publicurl/optout.php?lang=".trim($emrow['language'])."&sid=$surveyid&token={$emrow['token']}"; + + if ( $modrewrite ) + { + $fieldsarray["{SURVEYURL}"]="$publicurl/$surveyid/lang-".trim($emrow['language'])."/tk-{$emrow['token']}"; + } + else + { + $fieldsarray["{SURVEYURL}"]="$publicurl/index.php?lang=".trim($emrow['language'])."&sid=$surveyid&token={$emrow['token']}"; + } } else { - $fieldsarray["{SURVEYURL}"]="$publicurl/index.php?lang=".trim($emrow['language'])."&sid=$surveyid&token={$emrow['token']}"; + $fieldsarray["{OPTOUTURL}"]="".htmlspecialchars("$publicurl/optout.php?lang=".trim($emrow['language'])."&sid=$surveyid&token={$emrow['token']}").""; + if ( $modrewrite ) + { + $fieldsarray["{SURVEYURL}"]="".htmlspecialchars("$publicurl/$surveyid/lang-".trim($emrow['language'])."/tk-{$emrow['token']}").""; + $barebone_link="$publicurl/$surveyid/lang-".trim($emrow['language'])."/tk-{$emrow['token']}"; + } + else + { + $fieldsarray["{SURVEYURL}"]="".htmlspecialchars("$publicurl/index.php?lang=".trim($emrow['language'])."&sid=$surveyid&token={$emrow['token']}").""; + $barebone_link="$publicurl/index.php?lang=".trim($emrow['language'])."&sid=$surveyid&token={$emrow['token']}"; + } } - } - else - { - $fieldsarray["{OPTOUTURL}"]="".htmlspecialchars("$publicurl/optout.php?lang=".trim($emrow['language'])."&sid=$surveyid&token={$emrow['token']}").""; - if ( $modrewrite ) + $customheaders = array( '1' => "X-surveyid: ".$surveyid, + '2' => "X-tokenid: ".$fieldsarray["{TOKEN}"]); + + $modsubject=Replacefields($_POST['subject_'.$emrow['language']], $fieldsarray); + $modmessage=Replacefields($_POST['message_'.$emrow['language']], $fieldsarray); + + $modsubject = str_replace("@@SURVEYURL@@", $barebone_link, $modsubject); + $modmessage = str_replace("@@SURVEYURL@@", $barebone_link, $modmessage); + + if (trim($emrow['validfrom'])!='' && convertDateTimeFormat($emrow['validfrom'],'Y-m-d H:i:s','U')*1>date('U')*1) { - $fieldsarray["{SURVEYURL}"]="".htmlspecialchars("$publicurl/$surveyid/lang-".trim($emrow['language'])."/tk-{$emrow['token']}").""; - $barebone_link="$publicurl/$surveyid/lang-".trim($emrow['language'])."/tk-{$emrow['token']}"; + $tokenoutput .= $emrow['tid'] ." ".ReplaceFields($clang->gT("Email to {FIRSTNAME} {LASTNAME} ({EMAIL}) delayed: Token is not yet valid.")."
        ", $fieldsarray); } - else + elseif (trim($emrow['validuntil'])!='' && convertDateTimeFormat($emrow['validuntil'],'Y-m-d H:i:s','U')*1".htmlspecialchars("$publicurl/index.php?lang=".trim($emrow['language'])."&sid=$surveyid&token={$emrow['token']}").""; - $barebone_link="$publicurl/index.php?lang=".trim($emrow['language'])."&sid=$surveyid&token={$emrow['token']}"; + $tokenoutput .= $emrow['tid'] ." ".ReplaceFields($clang->gT("Email to {FIRSTNAME} {LASTNAME} ({EMAIL}) skipped: Token is not valid anymore.")."
        ", $fieldsarray); } - } - $customheaders = array( '1' => "X-surveyid: ".$surveyid, - '2' => "X-tokenid: ".$fieldsarray["{TOKEN}"]); - - $modsubject=Replacefields($_POST['subject_'.$emrow['language']], $fieldsarray); - $modmessage=Replacefields($_POST['message_'.$emrow['language']], $fieldsarray); - - $modsubject = str_replace("@@SURVEYURL@@", $barebone_link, $modsubject); - $modmessage = str_replace("@@SURVEYURL@@", $barebone_link, $modmessage); - - if (trim($emrow['validfrom'])!='' && convertDateTimeFormat($emrow['validfrom'],'Y-m-d H:i:s','U')*1>date('U')*1) - { - $tokenoutput .= $emrow['tid'] ." ".ReplaceFields($clang->gT("Email to {FIRSTNAME} {LASTNAME} ({EMAIL}) delayed: Token is not yet valid.")."
        ", $fieldsarray); - } - elseif (trim($emrow['validuntil'])!='' && convertDateTimeFormat($emrow['validuntil'],'Y-m-d H:i:s','U')*1gT("Email to {FIRSTNAME} {LASTNAME} ({EMAIL}) skipped: Token is not valid anymore.")."
        ", $fieldsarray); - } - elseif (SendEmailMessage($oMail, $modmessage, $modsubject, $to , $from, $sitename, $ishtml, getBounceEmail($surveyid),null,$customheaders)) - { - // Put date into sent - $today = date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i", $timeadjust); - $udequery = "UPDATE ".db_table_name("tokens_{$surveyid}")."\n" - ."SET sent='$today' WHERE tid={$emrow['tid']}"; - // - $uderesult = $connect->Execute($udequery) or safe_die ("Could not update tokens
        $udequery
        ".$connect->ErrorMsg()); + elseif (SendEmailMessage($oMail, $modmessage, $modsubject, $to , $from, $sitename, $ishtml, getBounceEmail($surveyid),null,$customheaders)) + { + // Put date into sent + $today = date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i", $timeadjust); + $udequery = "UPDATE ".db_table_name("tokens_{$surveyid}")."\n" + ."SET sent='$today' WHERE tid={$emrow['tid']}"; + // + $uderesult = $connect->Execute($udequery) or safe_die ("Could not update tokens
        $udequery
        ".$connect->ErrorMsg()); $tokenoutput .= $clang->gT("Invitation sent to:")." {$emrow['firstname']} {$emrow['lastname']} (".htmlspecialchars(implode(',',$to)).")
        \n"; - if ($emailsmtpdebug==2) + if ($emailsmtpdebug==2) + { + $tokenoutput .=$maildebug; + } + } + else { - $tokenoutput .=$maildebug; + unset($oMail); + $oMail = new PHPMailer; + $tokenoutput .= '
      • '.ReplaceFields($clang->gT("Email to {FIRSTNAME} {LASTNAME} ({EMAIL}) failed. Error Message:")." ".$maildebug."
        ", $fieldsarray).'
      • '; + if ($debug>0) + { + $tokenoutput .= "
        Subject : $modsubject

        ".htmlspecialchars($maildebugbody)."
        "; + } } } - else + if ($ctcount > $emcount) { - unset($oMail); - $oMail = new PHPMailer; - $tokenoutput .= '
      • '.ReplaceFields($clang->gT("Email to {FIRSTNAME} {LASTNAME} ({EMAIL}) failed. Error Message:")." ".$maildebug."
        ", $fieldsarray).'
      • '; - if ($debug>0) + $i = 0; + if (isset($tokenids)) + { + while($i < $maxemails) + { array_shift($tokenids); $i++; } + $tids = '|'.implode('|',$tokenids); + } + $lefttosend = $ctcount-$maxemails; + $tokenoutput .= "
      \n" + ."
      ".$clang->gT("Warning")."

      \n" + ."
      " + .$clang->gT("There are more emails pending than can be sent in one batch. Continue sending emails by clicking below.")."

      \n"; + $tokenoutput .= str_replace("{EMAILCOUNT}", "$lefttosend", $clang->gT("There are {EMAILCOUNT} emails still to be sent.")); + $tokenoutput .= "

      \n"; + $tokenoutput .= "\n" + ."\n" + ."\n" + ."\n" + ."\n" + ."\n"; + if (isset($tokenids)) + { + $tokenoutput .= "\n"; + } + foreach ($surveylangs as $language) { - $tokenoutput .= "
      Subject : $modsubject

      ".htmlspecialchars($maildebugbody)."
      "; + $message = html_escape($_POST['message_'.$language]); + $subject = html_escape($_POST['subject_'.$language]); + $tokenoutput .="\n" + ."\n" + ."\n"; } + $tokenoutput .="
      \n"; } + $oMail->SmtpClose(); } - if ($ctcount > $emcount) + else { - $i = 0; - if (isset($tokenids)) - { - while($i < $maxemails) - { array_shift($tokenids); $i++; } - $tids = '|'.implode('|',$tokenids); - } - $lefttosend = $ctcount-$maxemails; - $tokenoutput .= "
    \n" - ."
    ".$clang->gT("Warning")."

    \n" - ."
    " - .$clang->gT("There are more emails pending than can be sent in one batch. Continue sending emails by clicking below.")."

    \n"; - $tokenoutput .= str_replace("{EMAILCOUNT}", "$lefttosend", $clang->gT("There are {EMAILCOUNT} emails still to be sent.")); - $tokenoutput .= "

    \n"; - $tokenoutput .= "\n" - ."\n" - ."\n" - ."\n" - ."\n" - ."\n"; - if (isset($tokenids)) - { - $tokenoutput .= "\n"; - } - foreach ($surveylangs as $language) - { - $message = html_escape($_POST['message_'.$language]); - $subject = html_escape($_POST['subject_'.$language]); - $tokenoutput .="\n" - ."\n" - ."\n"; - } - $tokenoutput .="
    \n"; + $tokenoutput .= "
    ".$clang->gT("Warning")."
    \n".$clang->gT("There were no eligible emails to send. This will be because none satisfied the criteria of:") + ."
     
    • ".$clang->gT("having a valid email address")."
    • " + ."
    • ".$clang->gT("not having been sent an invitation already")."
    • " + ."
    • ".$clang->gT("having already completed the survey")."
    • " + ."
    • ".$clang->gT("having a token")."
    "; } - $oMail->SmtpClose(); } - else - { - $tokenoutput .= "
    ".$clang->gT("Warning")."
    \n".$clang->gT("There were no eligible emails to send. This will be because none satisfied the criteria of:") - ."
     
    • ".$clang->gT("having a valid email address")."
    • " - ."
    • ".$clang->gT("not having been sent an invitation already")."
    • " - ."
    • ".$clang->gT("having already completed the survey")."
    • " - ."
    • ".$clang->gT("having a token")."
    "; - } - } - //$tokenoutput .= "
    \n
    \n"; - $tokenoutput .= "\n"; // TIBO only close on div, cause dialog-modal will cklose wrapper + //$tokenoutput .= "\n\n"; + $tokenoutput .= "\n"; // TIBO only close on div, cause dialog-modal will cklose wrapper } if ($subaction == "remind" && bHasSurveyPermission($surveyid, 'tokens','update')) { - $tokenoutput .= PrepareEditorScript(); - $tokenoutput .= "\t
    " - .$clang->gT("Send email reminder")."

    \n"; - if (!isset($_POST['ok']) || !$_POST['ok']) - { - if ($thissurvey['active']!='Y') - { - $tokenoutput .="
    ".$clang->gT('Warning!')."
    ".$clang->gT("This survey is not yet activated and so your participants won't be able to fill out the survey.")."
    "; - } - //GET SURVEY DETAILS - $tokenoutput .= "
    "; - $surveylangs = GetAdditionalLanguagesFromSurveyID($surveyid); - $baselang = GetBaseLanguageFromSurveyID($surveyid); - array_unshift($surveylangs,$baselang); - - $tokenoutput .= "
    "; - foreach ($surveylangs as $language) + $tokenoutput .= PrepareEditorScript(); + $tokenoutput .= "\t
    " + .$clang->gT("Send email reminder")."

    \n"; + if (!isset($_POST['ok']) || !$_POST['ok']) { - //GET SURVEY DETAILS - $thissurvey=getSurveyInfo($surveyid,$language); - if (!$thissurvey['email_remind']) {$thissurvey['email_remind']=str_replace("\n", "\r\n", $clang->gT("Dear {FIRSTNAME},\n\nRecently we invited you to participate in a survey.\n\nWe note that you have not yet completed the survey, and wish to remind you that the survey is still available should you wish to take part.\n\nThe survey is titled:\n\"{SURVEYNAME}\"\n\n\"{SURVEYDESCRIPTION}\"\n\nTo participate, please click on the link below.\n\nSincerely,\n\n{ADMINNAME} ({ADMINEMAIL})\n\n----------------------------------------------\nClick here to do the survey:\n{SURVEYURL}")."\n\n".$clang->gT("If you do not want to participate in this survey and don't want to receive any more invitations please click the following link:\n{OPTOUTURL}"));} - $tokenoutput .= '

    '.getLanguageNameFromCode($language,false); - if ($language==$baselang) + if ($thissurvey['active']!='Y') { - $tokenoutput .= "(".$clang->gT("Base language").")"; + $tokenoutput .="
    ".$clang->gT('Warning!')."
    ".$clang->gT("This survey is not yet activated and so your participants won't be able to fill out the survey.")."
    "; } - $tokenoutput .= "

      \n" - ."
    • \n" - ."\" />
    • \n" + //GET SURVEY DETAILS + $tokenoutput .= ""; + $surveylangs = GetAdditionalLanguagesFromSurveyID($surveyid); + $baselang = GetBaseLanguageFromSurveyID($surveyid); + array_unshift($surveylangs,$baselang); + + $tokenoutput .= "
      "; + foreach ($surveylangs as $language) + { + //GET SURVEY DETAILS + $thissurvey=getSurveyInfo($surveyid,$language); + if (!$thissurvey['email_remind']) {$thissurvey['email_remind']=str_replace("\n", "\r\n", $clang->gT("Dear {FIRSTNAME},\n\nRecently we invited you to participate in a survey.\n\nWe note that you have not yet completed the survey, and wish to remind you that the survey is still available should you wish to take part.\n\nThe survey is titled:\n\"{SURVEYNAME}\"\n\n\"{SURVEYDESCRIPTION}\"\n\nTo participate, please click on the link below.\n\nSincerely,\n\n{ADMINNAME} ({ADMINEMAIL})\n\n----------------------------------------------\nClick here to do the survey:\n{SURVEYURL}")."\n\n".$clang->gT("If you do not want to participate in this survey and don't want to receive any more invitations please click the following link:\n{OPTOUTURL}"));} + $tokenoutput .= '

      '.getLanguageNameFromCode($language,false); + if ($language==$baselang) + { + $tokenoutput .= "(".$clang->gT("Base language").")"; + } + $tokenoutput .= "

        \n" + ."
      • \n" + ."\" />
      • \n" - ."
      • \n"; + ."
      • \n"; - $fieldsarray["{ADMINNAME}"]= $thissurvey['adminname']; - $fieldsarray["{ADMINEMAIL}"]=$thissurvey['adminemail']; - $fieldsarray["{SURVEYNAME}"]=$thissurvey['name']; - $fieldsarray["{SURVEYDESCRIPTION}"]=$thissurvey['description']; - $fieldsarray["{EXPIRY}"]=$thissurvey["expiry"]; + $fieldsarray["{ADMINNAME}"]= $thissurvey['adminname']; + $fieldsarray["{ADMINEMAIL}"]=$thissurvey['adminemail']; + $fieldsarray["{SURVEYNAME}"]=$thissurvey['name']; + $fieldsarray["{SURVEYDESCRIPTION}"]=$thissurvey['description']; + $fieldsarray["{EXPIRY}"]=$thissurvey["expiry"]; - $subject=Replacefields($thissurvey['email_remind_subj'], $fieldsarray, false); - $textarea=Replacefields($thissurvey['email_remind'], $fieldsarray, false); - if ($ishtml!==true){$textarea=str_replace(array('',''),array(''),$textarea);} + $subject=Replacefields($thissurvey['email_remind_subj'], $fieldsarray, false); + $textarea=Replacefields($thissurvey['email_remind'], $fieldsarray, false); + if ($ishtml!==true){$textarea=str_replace(array('',''),array(''),$textarea);} - $tokenoutput .= "
      • \n"; + $tokenoutput .= "\n"; - $tokenoutput .= "\t
      • \n" - ."\n" - ."\n" + . getEditor("email-rem","message_$language","[".$clang->gT("Reminder Email:", "js")."](".$language.")",$surveyid,'','',$action) + ."
      • \n" + ."
      "; + } - $tokenoutput .= "\n" - . getEditor("email-rem","message_$language","[".$clang->gT("Reminder Email:", "js")."](".$language.")",$surveyid,'','',$action) - ."\n" - ."
    "; + $tokenoutput .= "

    \n" + ."\n" + ."\t\n" + ."\t\n" + ."\t\n"; + if (isset($tokenid)) {$tokenoutput .= "\t\n";} + if (isset($tokenids)) {$tokenoutput .= "\n\n";} + $tokenoutput .= "

    \n"; } + else + { - $tokenoutput .= "

    \n" - ."\n" - ."\t\n" - ."\t\n" - ."\t\n"; - if (isset($tokenid)) {$tokenoutput .= "\t\n";} - if (isset($tokenids)) {$tokenoutput .= "\n\n";} - $tokenoutput .= "\n"; - } - else - { - - $tokenoutput .= "

    \n" - . "
    "; - $tokenoutput .= $clang->gT("Sending Reminders") - ."

    \n"; - - $surveylangs = GetAdditionalLanguagesFromSurveyID($surveyid); - $baselanguage = GetBaseLanguageFromSurveyID($surveyid); - array_unshift($surveylangs,$baselanguage); + $surveylangs = GetAdditionalLanguagesFromSurveyID($surveyid); + $baselanguage = GetBaseLanguageFromSurveyID($surveyid); + array_unshift($surveylangs,$baselanguage); - foreach ($surveylangs as $language) - { - $_POST['message_'.$language]=auto_unescape($_POST['message_'.$language]); - $_POST['subject_'.$language]=auto_unescape($_POST['subject_'.$language]); + foreach ($surveylangs as $language) + { + $_POST['message_'.$language]=auto_unescape($_POST['message_'.$language]); + $_POST['subject_'.$language]=auto_unescape($_POST['subject_'.$language]); - } + } - if (isset($starttokenid)) {$tokenoutput .= " (".$clang->gT("From Token ID").": {$starttokenid})";} - if (isset($tokenid)) {$tokenoutput .= " (".$clang->gT("Sending to Token ID").": {$tokenid})";} - if (isset($tokenids)) {$tokenoutput .= " (".$clang->gT("Sending to Token IDs").": ".implode("|", $tokenids).")";} + if (isset($starttokenid)) {$tokenoutput .= " (".$clang->gT("From Token ID").": {$starttokenid})";} + if (isset($tokenid)) {$tokenoutput .= " (".$clang->gT("Sending to Token ID").": {$tokenid})";} + if (isset($tokenids)) {$tokenoutput .= " (".$clang->gT("Sending to Token IDs").": ".implode("|", $tokenids).")";} - if (isset($_POST['bypassbademails']) && $_POST['bypassbademails'] == 'Y') - { - $SQLemailstatuscondition = " AND emailstatus = 'OK'"; - } - else - { - $SQLemailstatuscondition = ""; - } + if (isset($_POST['bypassbademails']) && $_POST['bypassbademails'] == 'Y') + { + $SQLemailstatuscondition = " AND emailstatus = 'OK'"; + } + else + { + $SQLemailstatuscondition = ""; + } - if (isset($_POST['maxremindercount']) && - $_POST['maxremindercount'] != '' && - intval($_POST['maxremindercount']) != 0) - { - $SQLremindercountcondition = " AND remindercount < ".intval($_POST['maxremindercount']); - } - else - { - $SQLremindercountcondition = ""; - } + if (isset($_POST['maxremindercount']) && + $_POST['maxremindercount'] != '' && + intval($_POST['maxremindercount']) != 0) + { + $SQLremindercountcondition = " AND remindercount < ".intval($_POST['maxremindercount']); + } + else + { + $SQLremindercountcondition = ""; + } - if (isset($_POST['minreminderdelay']) && - $_POST['minreminderdelay'] != '' && - intval($_POST['minreminderdelay']) != 0) - { - // $_POST['minreminderdelay'] in days (86400 seconds per day) - $compareddate = date_shift( - date("Y-m-d H:i:s",time() - 86400 * intval($_POST['minreminderdelay'])), - "Y-m-d H:i", - $timeadjust); - $SQLreminderdelaycondition = " AND ( " - . " (remindersent = 'N' AND sent < '".$compareddate."') " - . " OR " - . " (remindersent < '".$compareddate."'))"; - } - else - { - $SQLreminderdelaycondition = ""; - } + if (isset($_POST['minreminderdelay']) && + $_POST['minreminderdelay'] != '' && + intval($_POST['minreminderdelay']) != 0) + { + // $_POST['minreminderdelay'] in days (86400 seconds per day) + $compareddate = date_shift( + date("Y-m-d H:i:s",time() - 86400 * intval($_POST['minreminderdelay'])), + "Y-m-d H:i", + $timeadjust); + $SQLreminderdelaycondition = " AND ( " + . " (remindersent = 'N' AND sent < '".$compareddate."') " + . " OR " + . " (remindersent < '".$compareddate."'))"; + } + else + { + $SQLreminderdelaycondition = ""; + } - $ctquery = "SELECT * FROM ".db_table_name("tokens_{$surveyid}")." WHERE (completed ='N' or completed ='') AND sent<>'' AND sent<>'N' AND token <>'' AND email <> '' $SQLemailstatuscondition $SQLremindercountcondition $SQLreminderdelaycondition"; + $ctquery = "SELECT * FROM ".db_table_name("tokens_{$surveyid}")." WHERE (completed ='N' or completed ='') AND sent<>'' AND sent<>'N' AND token <>'' AND email <> '' $SQLemailstatuscondition $SQLremindercountcondition $SQLreminderdelaycondition"; - if (isset($starttokenid)) {$ctquery .= " AND tid > '{$starttokenid}'";} - if (isset($tokenid) && $tokenid) {$ctquery .= " AND tid = '{$tokenid}'";} - if (isset($tokenids)) {$ctquery .= " AND tid IN (".implode(", ", $tokenids).")";} - $tokenoutput .= "\n"; - $ctresult = $connect->Execute($ctquery) or safe_die ("Database error!
    \n" . $connect->ErrorMsg()); - $ctcount = $ctresult->RecordCount(); - $ctfieldcount = $ctresult->FieldCount(); - $emquery = "SELECT * FROM ".db_table_name("tokens_{$surveyid}")." WHERE (completed = 'N' or completed = '') AND sent <> 'N' and sent <>'' AND token <>'' AND EMAIL <>'' $SQLemailstatuscondition $SQLremindercountcondition $SQLreminderdelaycondition"; + if (isset($starttokenid)) {$ctquery .= " AND tid > '{$starttokenid}'";} + if (isset($tokenid) && $tokenid) {$ctquery .= " AND tid = '{$tokenid}'";} + if (isset($tokenids)) {$ctquery .= " AND tid IN (".implode(", ", $tokenids).")";} + $tokenoutput .= "\n"; + $ctresult = $connect->Execute($ctquery) or safe_die ("Database error!
    \n" . $connect->ErrorMsg()); + $ctcount = $ctresult->RecordCount(); + $ctfieldcount = $ctresult->FieldCount(); + $emquery = "SELECT * FROM ".db_table_name("tokens_{$surveyid}")." WHERE (completed = 'N' or completed = '') AND sent <> 'N' and sent <>'' AND token <>'' AND EMAIL <>'' $SQLemailstatuscondition $SQLremindercountcondition $SQLreminderdelaycondition"; - if (isset($starttokenid)) {$emquery .= " AND tid > '{$starttokenid}'";} - if (isset($tokenid) && $tokenid) {$emquery .= " AND tid = '{$tokenid}'";} - if (isset($tokenids)) {$emquery .= " AND tid IN (".implode(", ", $tokenids).")";} - $emquery .= " ORDER BY tid "; - $emresult = db_select_limit_assoc($emquery, $maxemails) or safe_die ("Couldn't do query.
    $emquery
    ".$connect->ErrorMsg()); - $emcount = $emresult->RecordCount(); + if (isset($starttokenid)) {$emquery .= " AND tid > '{$starttokenid}'";} + if (isset($tokenid) && $tokenid) {$emquery .= " AND tid = '{$tokenid}'";} + if (isset($tokenids)) {$emquery .= " AND tid IN (".implode(", ", $tokenids).")";} + $emquery .= " ORDER BY tid "; + $emresult = db_select_limit_assoc($emquery, $maxemails) or safe_die ("Couldn't do query.
    $emquery
    ".$connect->ErrorMsg()); + $emcount = $emresult->RecordCount(); - $attributes=GetTokenFieldsAndNames($surveyid); - if ($emcount > 0) - { - $tokenoutput .= "\n" - ."\t\n" - ."\n" - ."\t\n" - ."\t" - ."\n" - ."\t\n" - ."\t\n" - ."\t\n" - ."\t\n" - ."\t\n"; - //Include values for constraints minreminderdelay and maxremindercount if they exist - if (isset($_POST['minreminderdelay']) && - $_POST['minreminderdelay'] != '' && - intval($_POST['minreminderdelay']) != 0) - { - $tokenoutput .= "\t\n"; - } - if (isset($_POST['maxremindercount']) && - $_POST['maxremindercount'] != '' && - intval($_POST['maxremindercount']) != 0) - { - $tokenoutput .= "\t\n"; - } - // - foreach ($surveylangs as $language) - { - $message = html_escape($_POST['message_'.$language]); - $tokenoutput .="\n" - ."\n" - ."\n"; - } - $tokenoutput.="\t\n" - ."\t\n"; + $tokenoutput .= "
    ".$clang->gT("Warning")."
    \n" + .$clang->gT("There were no eligible emails to send. This will be because none satisfied the criteria of:")."\n" + ."
     
    \n"; } - $tokenoutput .= "\t\n" - ."
    \n"; - $oMail = new PHPMailer; - while ($emrow = $emresult->FetchRow()) + $attributes=GetTokenFieldsAndNames($surveyid); + if ($emcount > 0) { - unset($fieldsarray); + $tokenoutput .= "\n" + ."\t\n" + ."\n" + ."\t\n" + ."\t" + ."\n" + ."\t\n" + ."\t\n" + ."\t\n" + ."\t\n" + ."\t\n"; + //Include values for constraints minreminderdelay and maxremindercount if they exist + if (isset($_POST['minreminderdelay']) && + $_POST['minreminderdelay'] != '' && + intval($_POST['minreminderdelay']) != 0) { - $tokenoutput .= "
    Subject : $msgsubject

    ".htmlspecialchars($maildebugbody)."
    "; + $tokenoutput .= "\t\n"; } - + if (isset($_POST['maxremindercount']) && + $_POST['maxremindercount'] != '' && + intval($_POST['maxremindercount']) != 0) + { + $tokenoutput .= "\t\n"; + } + // + foreach ($surveylangs as $language) + { + $message = html_escape($_POST['message_'.$language]); + $tokenoutput .="\n" + ."\n" + ."\n"; + } + $tokenoutput.="\t\n" + ."\t\n"; } - $lasttid = $emrow['tid']; + $tokenoutput .= "\t\n" + ."
    \n"; + $oMail = new PHPMailer; + while ($emrow = $emresult->FetchRow()) + { + unset($fieldsarray); $to=array(); $aEmailaddresses=explode(';',$emrow['email']); foreach($aEmailaddresses as $sEmailaddress) { $to[]=$emrow['firstname']." ".$emrow['lastname']." <{$sEmailaddress}>"; } - $fieldsarray["{EMAIL}"]=$emrow['email']; - $fieldsarray["{FIRSTNAME}"]=$emrow['firstname']; - $fieldsarray["{LASTNAME}"]=$emrow['lastname']; - $fieldsarray["{TOKEN}"]=$emrow['token']; - $fieldsarray["{LANGUAGE}"]=$emrow['language']; - $fieldsarray["{SID}"]=$fieldsarray["{SURVEYID}"]=$surveyid; - $fieldsarray["{SURVEYNAME}"]=$thissurvey["surveyls_title"]; - - foreach ($attributes as $attributefield=>$attributedescription) - { - $fieldsarray['{'.strtoupper($attributefield).'}']=$emrow[$attributefield]; - $fieldsarray['{TOKEN:'.strtoupper($attributefield).'}']=$emrow[$attributefield]; - } + $fieldsarray["{EMAIL}"]=$emrow['email']; + $fieldsarray["{FIRSTNAME}"]=$emrow['firstname']; + $fieldsarray["{LASTNAME}"]=$emrow['lastname']; + $fieldsarray["{TOKEN}"]=$emrow['token']; + $fieldsarray["{LANGUAGE}"]=$emrow['language']; + $fieldsarray["{SID}"]=$fieldsarray["{SURVEYID}"]=$surveyid; + $fieldsarray["{SURVEYNAME}"]=$thissurvey["surveyls_title"]; + + foreach ($attributes as $attributefield=>$attributedescription) + { + $fieldsarray['{'.strtoupper($attributefield).'}']=$emrow[$attributefield]; + $fieldsarray['{TOKEN:'.strtoupper($attributefield).'}']=$emrow[$attributefield]; + } - $emrow['language']=trim($emrow['language']); - if ($emrow['language']=='') {$emrow['language']=$baselanguage;} //if language is not give use default - $found = array_search($emrow['language'], $surveylangs); - if ($found==false) {$emrow['language']=$baselanguage;} + $emrow['language']=trim($emrow['language']); + if ($emrow['language']=='') {$emrow['language']=$baselanguage;} //if language is not give use default + $found = array_search($emrow['language'], $surveylangs); + if ($found==false) {$emrow['language']=$baselanguage;} - $from = $_POST['from_'.$emrow['language']]; + $from = $_POST['from_'.$emrow['language']]; - if (getEmailFormat($surveyid) == 'html') - { - $ishtml=true; - } - else - { - $ishtml=false; - } - - if ($ishtml == false) - { - $fieldsarray["{OPTOUTURL}"]="$publicurl/optout.php?lang=".trim($emrow['language'])."&sid=$surveyid&token={$emrow['token']}"; - if ( $modrewrite ) + if (getEmailFormat($surveyid) == 'html') { - $fieldsarray["{SURVEYURL}"]="$publicurl/$surveyid/lang-".trim($emrow['language'])."/tk-{$emrow['token']}"; + $ishtml=true; } else { - $fieldsarray["{SURVEYURL}"]="$publicurl/index.php?lang=".trim($emrow['language'])."&sid=$surveyid&token={$emrow['token']}"; + $ishtml=false; } - } - else - { - $fieldsarray["{OPTOUTURL}"]="".htmlspecialchars("$publicurl/optout.php?lang=".trim($emrow['language'])."&sid=$surveyid&token={$emrow['token']}").""; - if ( $modrewrite ) + + if ($ishtml == false) { - $fieldsarray["{SURVEYURL}"]="".htmlspecialchars("$publicurl/$surveyid/lang-".trim($emrow['language'])."/tk-{$emrow['token']}").""; - $barebone_link="$publicurl/$surveyid/lang-".trim($emrow['language'])."/tk-{$emrow['token']}"; + $fieldsarray["{OPTOUTURL}"]="$publicurl/optout.php?lang=".trim($emrow['language'])."&sid=$surveyid&token={$emrow['token']}"; + if ( $modrewrite ) + { + $fieldsarray["{SURVEYURL}"]="$publicurl/$surveyid/lang-".trim($emrow['language'])."/tk-{$emrow['token']}"; + } + else + { + $fieldsarray["{SURVEYURL}"]="$publicurl/index.php?lang=".trim($emrow['language'])."&sid=$surveyid&token={$emrow['token']}"; + } } else { - $fieldsarray["{SURVEYURL}"]="".htmlspecialchars("$publicurl/index.php?lang=".trim($emrow['language'])."&sid=$surveyid&token={$emrow['token']}").""; - $barebone_link="$publicurl/index.php?lang=".trim($emrow['language'])."&sid=$surveyid&token={$emrow['token']}"; - $_POST['message_'.$emrow['language']] = html_entity_decode($_POST['message_'.$emrow['language']], ENT_QUOTES, $emailcharset); + $fieldsarray["{OPTOUTURL}"]="".htmlspecialchars("$publicurl/optout.php?lang=".trim($emrow['language'])."&sid=$surveyid&token={$emrow['token']}").""; + if ( $modrewrite ) + { + $fieldsarray["{SURVEYURL}"]="".htmlspecialchars("$publicurl/$surveyid/lang-".trim($emrow['language'])."/tk-{$emrow['token']}").""; + $barebone_link="$publicurl/$surveyid/lang-".trim($emrow['language'])."/tk-{$emrow['token']}"; + } + else + { + $fieldsarray["{SURVEYURL}"]="".htmlspecialchars("$publicurl/index.php?lang=".trim($emrow['language'])."&sid=$surveyid&token={$emrow['token']}").""; + $barebone_link="$publicurl/index.php?lang=".trim($emrow['language'])."&sid=$surveyid&token={$emrow['token']}"; + $_POST['message_'.$emrow['language']] = html_entity_decode($_POST['message_'.$emrow['language']], ENT_QUOTES, $emailcharset); + } } - } - $msgsubject=Replacefields($_POST['subject_'.$emrow['language']], $fieldsarray); - $sendmessage=Replacefields($_POST['message_'.$emrow['language']], $fieldsarray); + $msgsubject=Replacefields($_POST['subject_'.$emrow['language']], $fieldsarray); + $sendmessage=Replacefields($_POST['message_'.$emrow['language']], $fieldsarray); - $msgsubject = str_replace("@@SURVEYURL@@", $barebone_link, $msgsubject); - $sendmessage = str_replace("@@SURVEYURL@@", $barebone_link, $sendmessage); + $msgsubject = str_replace("@@SURVEYURL@@", $barebone_link, $msgsubject); + $sendmessage = str_replace("@@SURVEYURL@@", $barebone_link, $sendmessage); - $customheaders = array( '1' => "X-surveyid: ".$surveyid, - '2' => "X-tokenid: ".$fieldsarray["{TOKEN}"]); + $customheaders = array( '1' => "X-surveyid: ".$surveyid, + '2' => "X-tokenid: ".$fieldsarray["{TOKEN}"]); - if (trim($emrow['validfrom'])!='' && convertDateTimeFormat($emrow['validfrom'],'Y-m-d H:i:s','U')*1>date('U')*1) - { - $tokenoutput .= $emrow['tid'] ." ".ReplaceFields($clang->gT("Email to {FIRSTNAME} {LASTNAME} ({EMAIL}) delayed: Token is not yet valid.")."
    ", $fieldsarray); - } - elseif (trim($emrow['validuntil'])!='' && convertDateTimeFormat($emrow['validuntil'],'Y-m-d H:i:s','U')*1gT("Email to {FIRSTNAME} {LASTNAME} ({EMAIL}) skipped: Token is not valid anymore.")."
    ", $fieldsarray); - } - elseif (SendEmailMessage($oMail, $sendmessage, $msgsubject, $to, $from, $sitename,$ishtml,getBounceEmail($surveyid),null,$customheaders)) - { + if (trim($emrow['validfrom'])!='' && convertDateTimeFormat($emrow['validfrom'],'Y-m-d H:i:s','U')*1>date('U')*1) + { + $tokenoutput .= $emrow['tid'] ." ".ReplaceFields($clang->gT("Email to {FIRSTNAME} {LASTNAME} ({EMAIL}) delayed: Token is not yet valid.")."
    ", $fieldsarray); + } + elseif (trim($emrow['validuntil'])!='' && convertDateTimeFormat($emrow['validuntil'],'Y-m-d H:i:s','U')*1gT("Email to {FIRSTNAME} {LASTNAME} ({EMAIL}) skipped: Token is not valid anymore.")."
    ", $fieldsarray); + } + elseif (SendEmailMessage($oMail, $sendmessage, $msgsubject, $to, $from, $sitename,$ishtml,getBounceEmail($surveyid),null,$customheaders)) + { - // Put date into remindersent - $today = date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i", $timeadjust); - $udequery = "UPDATE ".db_table_name("tokens_{$surveyid}")."\n" - ."SET remindersent='$today',remindercount = remindercount+1 WHERE tid={$emrow['tid']}"; - // - $uderesult = $connect->Execute($udequery) or safe_die ("Could not update tokens
    $udequery
    ".$connect->ErrorMsg()); - //orig: $tokenoutput .= "({$emrow['tid']})[".$clang->gT("Reminder sent to:")." {$emrow['firstname']} {$emrow['lastname']}]
    \n"; - $tokenoutput .= "({$emrow['tid']}) [".$clang->gT("Reminder sent to:")." {$emrow['firstname']} {$emrow['lastname']} ($to)]
    \n"; - } - else - { + // Put date into remindersent + $today = date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i", $timeadjust); + $udequery = "UPDATE ".db_table_name("tokens_{$surveyid}")."\n" + ."SET remindersent='$today',remindercount = remindercount+1 WHERE tid={$emrow['tid']}"; + // + $uderesult = $connect->Execute($udequery) or safe_die ("Could not update tokens
    $udequery
    ".$connect->ErrorMsg()); + //orig: $tokenoutput .= "({$emrow['tid']})[".$clang->gT("Reminder sent to:")." {$emrow['firstname']} {$emrow['lastname']}]
    \n"; + $tokenoutput .= "({$emrow['tid']}) [".$clang->gT("Reminder sent to:")." {$emrow['firstname']} {$emrow['lastname']} ($to)]
    \n"; + } + else + { unset($oMail); $oMail = new PHPMailer; - $tokenoutput .= $emrow['tid'] ." ".ReplaceFields($clang->gT("Email to {FIRSTNAME} {LASTNAME} ({EMAIL}) failed. Error Message:")." ".$maildebug."
    ", $fieldsarray); - if ($debug>0) + $tokenoutput .= $emrow['tid'] ." ".ReplaceFields($clang->gT("Email to {FIRSTNAME} {LASTNAME} ({EMAIL}) failed. Error Message:")." ".$maildebug."
    ", $fieldsarray); + if ($debug>0) + { + $tokenoutput .= "
    Subject : $msgsubject

    ".htmlspecialchars($maildebugbody)."
    "; + } + + } + $lasttid = $emrow['tid']; + } + $oMail->SmtpClose(); + if ($ctcount > $emcount) + { + $lefttosend = $ctcount-$maxemails; + $tokenoutput .= "
    \n" + ."".$clang->gT("Warning")."

    \n" + .$clang->gT("There are more emails pending than can be sent in one batch. Continue sending emails by clicking below.")."

    \n" + .str_replace("{EMAILCOUNT}", $lefttosend, $clang->gT("There are {EMAILCOUNT} emails still to be sent.")) + ."
    \n" + ."\n" + ."
    \n"; } - $oMail->SmtpClose(); - if ($ctcount > $emcount) + else { - $lefttosend = $ctcount-$maxemails; - $tokenoutput .= "
    \n" - ."".$clang->gT("Warning")."

    \n" - .$clang->gT("There are more emails pending than can be sent in one batch. Continue sending emails by clicking below.")."

    \n" - .str_replace("{EMAILCOUNT}", $lefttosend, $clang->gT("There are {EMAILCOUNT} emails still to be sent.")) - ."
    \n" - ."\n" - ."
    \n"; - } - else - { - $tokenoutput .= "
    ".$clang->gT("Warning")."
    \n" - .$clang->gT("There were no eligible emails to send. This will be because none satisfied the criteria of:")."\n" - ."
     
    \n"; + $tokenoutput .= "
    \n"; } - $tokenoutput .= "\n"; - } } if ($subaction == "tokenify" && bHasSurveyPermission($surveyid, 'tokens', 'update')) { - $tokenoutput .= "
    ".$clang->gT("Create tokens")."
    \n"; - $tokenoutput .= "
    \n"; - if (!isset($_POST['ok']) || !$_POST['ok']) - { - $tokenoutput .= "".$clang->gT("Clicking yes will generate tokens for all those in this token list that have not been issued one. Is this OK?")."

    \n" - ."\n" - .$clang->gT("Yes")."' onclick=\"".get2post("$scriptname?action=tokens&sid=$surveyid&subaction=tokenify&ok=Y")."\" />\n" - ."\n" - ."
    \n"; - } - else - { - //get token length from survey settings - $tlquery = "SELECT tokenlength FROM ".db_table_name("surveys")." WHERE sid=$surveyid"; - $tlresult = db_execute_assoc($tlquery); - while ($tlrow = $tlresult->FetchRow()) + $tokenoutput .= "
    ".$clang->gT("Create tokens")."
    \n"; + $tokenoutput .= "
    \n"; + if (!isset($_POST['ok']) || !$_POST['ok']) { - $tokenlength = $tlrow['tokenlength']; + $tokenoutput .= "".$clang->gT("Clicking yes will generate tokens for all those in this token list that have not been issued one. Is this OK?")."

    \n" + ."\n" + .$clang->gT("Yes")."' onclick=\"".get2post("$scriptname?action=tokens&sid=$surveyid&subaction=tokenify&ok=Y")."\" />\n" + ."\n" + ."
    \n"; } - - //if tokenlength is not set or there are other problems use the default value (15) - if(!isset($tokenlength) || $tokenlength == '') + else { - $tokenlength = 15; - } + //get token length from survey settings + $tlquery = "SELECT tokenlength FROM ".db_table_name("surveys")." WHERE sid=$surveyid"; + $tlresult = db_execute_assoc($tlquery); + while ($tlrow = $tlresult->FetchRow()) + { + $tokenlength = $tlrow['tokenlength']; + } - // select all existing tokens - $ntquery = "SELECT token FROM ".db_table_name("tokens_$surveyid")." group by token"; - $ntresult = db_execute_assoc($ntquery); - while ($tkrow = $ntresult->FetchRow()) - { - $existingtokens[$tkrow['token']]=null; - } - $newtokencount = 0; - $tkquery = "SELECT tid FROM ".db_table_name("tokens_$surveyid")." WHERE token IS NULL OR token=''"; - $tkresult = db_execute_assoc($tkquery) or safe_die ("Mucked up!
    $tkquery
    ".$connect->ErrorMsg()); - while ($tkrow = $tkresult->FetchRow()) - { - $isvalidtoken = false; - while ($isvalidtoken == false) + //if tokenlength is not set or there are other problems use the default value (15) + if(!isset($tokenlength) || $tokenlength == '') { - $newtoken = sRandomChars($tokenlength); - if (!isset($existingtokens[$newtoken])) { - $isvalidtoken = true; - $existingtokens[$newtoken]=null; + $tokenlength = 15; + } + + // select all existing tokens + $ntquery = "SELECT token FROM ".db_table_name("tokens_$surveyid")." group by token"; + $ntresult = db_execute_assoc($ntquery); + while ($tkrow = $ntresult->FetchRow()) + { + $existingtokens[$tkrow['token']]=null; + } + $newtokencount = 0; + $tkquery = "SELECT tid FROM ".db_table_name("tokens_$surveyid")." WHERE token IS NULL OR token=''"; + $tkresult = db_execute_assoc($tkquery) or safe_die ("Mucked up!
    $tkquery
    ".$connect->ErrorMsg()); + while ($tkrow = $tkresult->FetchRow()) + { + $isvalidtoken = false; + while ($isvalidtoken == false) + { + $newtoken = sRandomChars($tokenlength); + if (!isset($existingtokens[$newtoken])) { + $isvalidtoken = true; + $existingtokens[$newtoken]=null; + } } + $itquery = "UPDATE ".db_table_name("tokens_$surveyid")." SET token='$newtoken' WHERE tid={$tkrow['tid']}"; + $itresult = $connect->Execute($itquery); + $newtokencount++; } - $itquery = "UPDATE ".db_table_name("tokens_$surveyid")." SET token='$newtoken' WHERE tid={$tkrow['tid']}"; - $itresult = $connect->Execute($itquery); - $newtokencount++; + $message=str_replace("{TOKENCOUNT}", $newtokencount, $clang->gT("{TOKENCOUNT} tokens have been created")); + $tokenoutput .= "
    $message
    \n"; } - $message=str_replace("{TOKENCOUNT}", $newtokencount, $clang->gT("{TOKENCOUNT} tokens have been created")); - $tokenoutput .= "
    $message
    \n"; - } - $tokenoutput .= "
    \n"; + $tokenoutput .= "
    \n"; } if ($subaction == "delete" && bHasSurveyPermission($surveyid, 'tokens','delete')) { - $tokenoutput .= "
    \n" - ."\t
    " - .$clang->gT("Delete") - ."\t
    \n" - ."\t


    "; - if(isset($tokenids) && count($tokenids)>0) { - if(implode(", ", $tokenids) != "") { - $dlquery = "DELETE FROM ".db_table_name("tokens_$surveyid")." WHERE tid IN (".implode(", ", $tokenids).")"; - $dlresult = $connect->Execute($dlquery) or safe_die ("Couldn't delete record {$tokenid}
    ".$connect->ErrorMsg()."\n\n$dlquery"); - $tokenoutput .= $clang->gT("Marked tokens have been deleted."); - } else { - $tokenoutput .= $clang->gT("No tokens were selected for deletion"); - } - } elseif (isset($tokenid)) { - $dlquery = "DELETE FROM ".db_table_name("tokens_$surveyid")." WHERE tid={$tokenid}"; - $dlresult = $connect->Execute($dlquery) or safe_die ("Couldn't delete record {$tokenid}
    ".$connect->ErrorMsg()); - $tokenoutput .= $clang->gT("Token has been deleted."); - } - $tokenoutput .= "

    ".$clang->gT("Reloading Screen. Please wait.")."

    \n" - ."

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


    "; + if(isset($tokenids) && count($tokenids)>0) { + if(implode(", ", $tokenids) != "") { + $dlquery = "DELETE FROM ".db_table_name("tokens_$surveyid")." WHERE tid IN (".implode(", ", $tokenids).")"; + $dlresult = $connect->Execute($dlquery) or safe_die ("Couldn't delete record {$tokenid}
    ".$connect->ErrorMsg()."\n\n$dlquery"); + $tokenoutput .= $clang->gT("Marked tokens have been deleted."); + } else { + $tokenoutput .= $clang->gT("No tokens were selected for deletion"); + } + } elseif (isset($tokenid)) { + $dlquery = "DELETE FROM ".db_table_name("tokens_$surveyid")." WHERE tid={$tokenid}"; + $dlresult = $connect->Execute($dlquery) or safe_die ("Couldn't delete record {$tokenid}
    ".$connect->ErrorMsg()); + $tokenoutput .= $clang->gT("Token has been deleted."); + } + $tokenoutput .= "

    ".$clang->gT("Reloading Screen. Please wait.")."

    \n" + ."

    \n
    \n"; } if ($subaction == "managetokenattributes" && bHasSurveyPermission($surveyid, 'tokens', 'update')) { - $tokenoutput .= "
    ".$clang->gT("Manage token attribute fields")."
    \n"; - $tokenfields=GetTokenFieldsAndNames($surveyid,true); - $nrofattributes=0; - $tokenoutput.='
    ' - .""; + $tokenoutput .= "
    ".$clang->gT("Manage token attribute fields")."
    \n"; + $tokenfields=GetTokenFieldsAndNames($surveyid,true); + $nrofattributes=0; + $tokenoutput.='' + ."
    ".$clang->gT("Attribute field")."".$clang->gT("Field description")."".$clang->gT("Example data")."
    "; - $exampledataquery = "SELECT * FROM ".db_table_name("tokens_$surveyid"); - $exampledata = db_select_limit_assoc($exampledataquery,1) or safe_die ("Could not get example data!
    $exampledataquery
    ".$connect->ErrorMsg()); - $examplerow = $exampledata->FetchRow(); + $exampledataquery = "SELECT * FROM ".db_table_name("tokens_$surveyid"); + $exampledata = db_select_limit_assoc($exampledataquery,1) or safe_die ("Could not get example data!
    $exampledataquery
    ".$connect->ErrorMsg()); + $examplerow = $exampledata->FetchRow(); - foreach ($tokenfields as $tokenfield=>$tokendescription) - { - $nrofattributes++; - $tokenoutput.=""; - } - $tokenoutput.="
    ".$clang->gT("Attribute field")."".$clang->gT("Field description")."".$clang->gT("Example data")."
    $tokenfield"; - if ($examplerow!==false) - { - $tokenoutput.=htmlspecialchars($examplerow[$tokenfield]); - } - else + foreach ($tokenfields as $tokenfield=>$tokendescription) { - $tokenoutput.=$clang->gT(''); - } - $tokenoutput.="

    " - .'' - ."\n" - ."\n" - ."

    \n" - .'


    '; - - $tokenoutput .= "
    ".$clang->gT("Add token attributes")."

    \n"; - - $tokenoutput .=sprintf($clang->gT('There are %s user attribute fields in this token table'),$nrofattributes).'

    ' - .'
    ' - .'

    ' - .'' - .'' - .'

    ' - .'

    ' - .'' - ."" - ."" - ."" - ."

    " - .'
    ' - .'

    '; + $nrofattributes++; + $tokenoutput.="$tokenfield"; + if ($examplerow!==false) + { + $tokenoutput.=htmlspecialchars($examplerow[$tokenfield]); + } + else + { + $tokenoutput.=$clang->gT(''); + } + $tokenoutput.=""; + } + $tokenoutput.="

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

    \n" + .'

    '; + + $tokenoutput .= "
    ".$clang->gT("Add token attributes")."

    \n"; + + $tokenoutput .=sprintf($clang->gT('There are %s user attribute fields in this token table'),$nrofattributes).'

    ' + .'
    ' + .'

    ' + .'' + .'' + .'

    ' + .'

    ' + .'' + ."" + ."" + ."" + ."

    " + .'
    ' + .'

    '; } if ($subaction == "updatetokenattributedescriptions" && bHasSurveyPermission($surveyid, 'tokens', 'update')) { - // find out the existing token attribute fieldnames - $tokenattributefieldnames=GetAttributeFieldNames($surveyid); - $fieldcontents=''; - foreach ($tokenattributefieldnames as $fieldname) - { - $fieldcontents.=$fieldname.'='.strip_tags($_POST['description_'.$fieldname])."\n"; - } - $updatequery = "update ".db_table_name('surveys').' set attributedescriptions='.db_quoteall($fieldcontents,true)." where sid=$surveyid"; - $execresult=db_execute_assoc($updatequery); + // find out the existing token attribute fieldnames + $tokenattributefieldnames=GetAttributeFieldNames($surveyid); + $fieldcontents=''; + foreach ($tokenattributefieldnames as $fieldname) + { + $fieldcontents.=$fieldname.'='.strip_tags($_POST['description_'.$fieldname])."\n"; + } + $updatequery = "update ".db_table_name('surveys').' set attributedescriptions='.db_quoteall($fieldcontents,true)." where sid=$surveyid"; + $execresult=db_execute_assoc($updatequery); - $tokenoutput .= "\t
    ".$clang->gT("Update token attribute descriptions")."
    \n" - ."\t
    "; - if ($execresult===false) - { - $tokenoutput.="\t\t
    ".$clang->gT("Updating token attribute descriptions failed:")."".htmlspecialchars($connect->ErrorMsg())."
    " - ."\t\t
    \n"; - } - else - { - $tokenoutput.="\t\t
    ".$clang->gT("Token attribute descriptions were successfully updated.")."
    " - ."\t\t
    \n"; - } - $tokenoutput .= "\t
    "; + $tokenoutput .= "\t
    ".$clang->gT("Update token attribute descriptions")."
    \n" + ."\t
    "; + if ($execresult===false) + { + $tokenoutput.="\t\t
    ".$clang->gT("Updating token attribute descriptions failed:")."".htmlspecialchars($connect->ErrorMsg())."
    " + ."\t\t
    \n"; + } + else + { + $tokenoutput.="\t\t
    ".$clang->gT("Token attribute descriptions were successfully updated.")."
    " + ."\t\t
    \n"; + } + $tokenoutput .= "\t
    "; } $tokenoutput .= "
    "; if ($subaction == "updatetokenattributes" && bHasSurveyPermission($surveyid, 'tokens', 'update')) { - $number2add=sanitize_int($_POST['addnumber'],1,100); - // find out the existing token attribute fieldnames - $tokenfieldnames = array_values($connect->MetaColumnNames("{$dbprefix}tokens_$surveyid", true)); - $tokenattributefieldnames=array_filter($tokenfieldnames,'filterforattributes'); - $i=1; - for ($b=0;$b<$number2add;$b++) - { - while (in_array('attribute_'.$i,$tokenattributefieldnames)!==false) { - $i++; + $number2add=sanitize_int($_POST['addnumber'],1,100); + // find out the existing token attribute fieldnames + $tokenfieldnames = array_values($connect->MetaColumnNames("{$dbprefix}tokens_$surveyid", true)); + $tokenattributefieldnames=array_filter($tokenfieldnames,'filterforattributes'); + $i=1; + for ($b=0;$b<$number2add;$b++) + { + while (in_array('attribute_'.$i,$tokenattributefieldnames)!==false) { + $i++; + } + $tokenattributefieldnames[]='attribute_'.$i; + $fields[]=array('attribute_'.$i,'C','255'); } - $tokenattributefieldnames[]='attribute_'.$i; - $fields[]=array('attribute_'.$i,'C','255'); - } - $dict = NewDataDictionary($connect); - $sqlarray = $dict->ChangeTableSQL("{$dbprefix}tokens_$surveyid", $fields); - $execresult=$dict->ExecuteSQLArray($sqlarray, false); + $dict = NewDataDictionary($connect); + $sqlarray = $dict->ChangeTableSQL("{$dbprefix}tokens_$surveyid", $fields); + $execresult=$dict->ExecuteSQLArray($sqlarray, false); - $tokenoutput .= "\t
    ".$clang->gT("Update token attributes")."
    \n" - ."\t
    "; - if ($execresult==0) - { - $tokenoutput.="\t\t
    ".$clang->gT("Adding attribute fields failed:")."".htmlspecialchars($connect->ErrorMsg())."
    " - ."\t\t
    \n"; - } - else - { - $tokenoutput.="\t\t
    ".sprintf($clang->gT("%s field(s) were successfully added."),$number2add)."
    " - ."\t\t
    \n"; - } - $tokenoutput .= "\t
    "; + $tokenoutput .= "\t
    ".$clang->gT("Update token attributes")."
    \n" + ."\t
    "; + if ($execresult==0) + { + $tokenoutput.="\t\t
    ".$clang->gT("Adding attribute fields failed:")."".htmlspecialchars($connect->ErrorMsg())."
    " + ."\t\t
    \n"; + } + else + { + $tokenoutput.="\t\t
    ".sprintf($clang->gT("%s field(s) were successfully added."),$number2add)."
    " + ."\t\t
    \n"; + } + $tokenoutput .= "\t
    "; - LimeExpressionManager::SetDirtyFlag(); // so that knows that token tables have changed + LimeExpressionManager::SetDirtyFlag(); // so that knows that token tables have changed } if (($subaction == "edit" && bHasSurveyPermission($surveyid, 'tokens','update')) || ($subaction == "addnew" && bHasSurveyPermission($surveyid, 'tokens','create'))) { - if ($subaction == "edit") - { - $edquery = "SELECT * FROM ".db_table_name("tokens_$surveyid")." WHERE tid={$tokenid}"; - $edresult = db_execute_assoc($edquery); - $edfieldcount = $edresult->FieldCount(); - while($edrow = $edresult->FetchRow()) + if ($subaction == "edit") { - //Create variables with the same names as the database column names and fill in the value - foreach ($edrow as $Key=>$Value) {$$Key = $Value;} + $edquery = "SELECT * FROM ".db_table_name("tokens_$surveyid")." WHERE tid={$tokenid}"; + $edresult = db_execute_assoc($edquery); + $edfieldcount = $edresult->FieldCount(); + while($edrow = $edresult->FetchRow()) + { + //Create variables with the same names as the database column names and fill in the value + foreach ($edrow as $Key=>$Value) {$$Key = $Value;} + } + } + if ($subaction != "edit") + { + $edquery = "SELECT * FROM ".db_table_name("tokens_$surveyid"); + $edresult = db_select_limit_assoc($edquery, 1); + $edfieldcount = $edresult->FieldCount(); } - } - if ($subaction != "edit") - { - $edquery = "SELECT * FROM ".db_table_name("tokens_$surveyid"); - $edresult = db_select_limit_assoc($edquery, 1); - $edfieldcount = $edresult->FieldCount(); - } - - $tokenoutput .= "
    "; - if ($subaction == "edit") - { - $tokenoutput .=$clang->gT("Edit token entry"); - } - else - { - $tokenoutput .=$clang->gT("Add token entry"); - } - - $tokenoutput .="
    " - ."
    \n" - ."
      \n" - ."\t
    • \n"; - if ($subaction == "edit") - {$tokenoutput .=$tokenid;} else {$tokenoutput .=$clang->gT("Auto");} - $tokenoutput .= "
    • \n" - ."
    • \n" - ."
    • \n" - ."
    • \n" - ."
    • \n" - ."\t
    • \n" - ."\t
    • \n" - ."
    • \n" - ."
    • \n" - ."
    • \n" - ."\n"; - if ($subaction == "addnew") - { - $tokenoutput .= "".$clang->gT("You can leave this blank, and automatically generate tokens using 'Generate Tokens'")."\n"; - } - $tokenoutput .= "\t
    • \n" - ."
    • \n"; - if (isset($language)) {$tokenoutput .= languageDropdownClean($surveyid,$language);} - else { - $tokenoutput .= languageDropdownClean($surveyid,GetBaseLanguageFromSurveyID($surveyid)); - } - $tokenoutput .= "
    • \n" - ."\t
    • \n" - ."\t
    • \n" + $tokenoutput .= "
      "; + if ($subaction == "edit") + { + $tokenoutput .=$clang->gT("Edit token entry"); + } + else + { + $tokenoutput .=$clang->gT("Add token entry"); + } + + $tokenoutput .="
      " + ."\n" + ."
        \n" + ."\t
      • \n"; + if ($subaction == "edit") + {$tokenoutput .=$tokenid;} else {$tokenoutput .=$clang->gT("Auto");} + $tokenoutput .= "
      • \n" + ."
      • \n" + ."
      • \n" + ."
      • \n" + ."
      • \n" + ."\t
      • \n" + ."\t
      • \n" + ."
      • \n" + ."
      • \n" + ."
      • \n" + ."\n"; + if ($subaction == "addnew") + { + $tokenoutput .= "".$clang->gT("You can leave this blank, and automatically generate tokens using 'Generate Tokens'")."\n"; + } + $tokenoutput .= "\t
      • \n" + ."
      • \n"; + if (isset($language)) {$tokenoutput .= languageDropdownClean($surveyid,$language);} + else { + $tokenoutput .= languageDropdownClean($surveyid,GetBaseLanguageFromSurveyID($surveyid)); + } + $tokenoutput .= "
      • \n" - ."\t
      • \n" - ."\t
      • \n"; + ."\t
      • \n" + ."\t
      • \n" - if ($subaction == "edit") - { - $tokenoutput.="\t
      • \n" - ."\t\n" + ."\t
      • \n"; - } - - $tokenoutput.="\t
      • \n" - ."\t
      • \n" - - ."\t
      • \n" - ."\t
      • \n" - - ."\t
      • \n" - ."\tconvert($dateformatdetails['phpdate'].' H:i'); - } - $tokenoutput .= "\" />\n convert($dateformatdetails['phpdate'].' H:i'); - } - $tokenoutput .= "\" /> ".sprintf($clang->gT('Format: %s'),$dateformatdetails['dateformat'].' '.$clang->gT('hh:mm')).'' - ."
      • \n"; - // now the attribute fieds - $attrfieldnames=GetTokenFieldsAndNames($surveyid,true); - foreach ($attrfieldnames as $attr_name=>$attr_description) - { - $tokenoutput .= "
      • " - ."\n" - ."\tgT("Reminder count:")."\n" + ."\t
      • \n"; + } + + $tokenoutput.="\t
      • \n" + ."\t
      • \n" + + ."\t
      • \n" + ."\t
      • \n" + + ."\t
      • \n" + ."\tconvert($dateformatdetails['phpdate'].' H:i'); + } + $tokenoutput .= "\" />\n convert($dateformatdetails['phpdate'].' H:i'); + } + $tokenoutput .= "\" /> ".sprintf($clang->gT('Format: %s'),$dateformatdetails['dateformat'].' '.$clang->gT('hh:mm')).'' + ."
      • \n"; + + // now the attribute fieds + $attrfieldnames=GetTokenFieldsAndNames($surveyid,true); + foreach ($attrfieldnames as $attr_name=>$attr_description) + { + $tokenoutput .= "
      • " + ."\n" + ."\tgT("Update token entry")."' />\n" - ."\n" - ."\n"; - break; - case "addnew": - $tokenoutput .= "\n" - ."\n"; - break; - } - $tokenoutput .= "

        \n" - ."
      • \n"; + $tokenoutput .="\t

      "; + switch($subaction) + { + case "edit": + $tokenoutput .= "\n" + ."\n" + ."\n"; + break; + case "addnew": + $tokenoutput .= "\n" + ."\n"; + break; + } + $tokenoutput .= "

      \n" + ."\n"; } if ($subaction == "adddummys" && bHasSurveyPermission($surveyid, 'tokens','create')) { - //get token length from survey settings - $tlquery = "SELECT tokenlength FROM ".db_table_name("surveys")." WHERE sid=$surveyid"; - $tlresult = db_execute_assoc($tlquery); - while ($tlrow = $tlresult->FetchRow()) - { - $tokenlength = $tlrow['tokenlength']; - } - - //if tokenlength is not set or there are other problems use the default value (15) - if(!isset($tokenlength) || $tokenlength == '') - { - $tokenlength = 15; - } + //get token length from survey settings + $tlquery = "SELECT tokenlength FROM ".db_table_name("surveys")." WHERE sid=$surveyid"; + $tlresult = db_execute_assoc($tlquery); + while ($tlrow = $tlresult->FetchRow()) + { + $tokenlength = $tlrow['tokenlength']; + } - $tokenoutput .= "
      "; - $tokenoutput .=$clang->gT("Create dummy tokens"); - $tokenoutput .="
      " - ."
      \n" - ."
        \n" - ."\t
      • \n"; - $tokenoutput .=$clang->gT("Auto"); - $tokenoutput .= "
      • \n" - ."
      • \n" - ."
      • \n" - ."
      • \n" - ."
      • \n" - ."
      • \n" - ."
      • \n" - ."
      • \n" - ."
      • \n" - ."\t
      • \n" - ."\t
      • \n"; - $tokenoutput .= "\t\n" - ."
      • \n"; - $tokenoutput .= languageDropdownClean($surveyid,GetBaseLanguageFromSurveyID($surveyid)); - $tokenoutput .= "
      • \n" - ."\t
      • \n" - ."\t
      • \n" - ."\t
      • \n" - ."\tconvert($dateformatdetails['phpdate'].' H:i'); - } - $tokenoutput .= "\" />\n convert($dateformatdetails['phpdate'].' H:i'); - } - $tokenoutput .= "\" /> ".sprintf($clang->gT('Format: %s'),$dateformatdetails['dateformat'].' '.$clang->gT('hh:mm')).'' - ."
      • \n"; + //if tokenlength is not set or there are other problems use the default value (15) + if(!isset($tokenlength) || $tokenlength == '') + { + $tokenlength = 15; + } - // now the attribute fieds - $attrfieldnames=GetTokenFieldsAndNames($surveyid,true); - foreach ($attrfieldnames as $attr_name=>$attr_description) - { - $tokenoutput .= "
      • " - ."\n" - ."\tgT("Create dummy tokens"); + $tokenoutput .="" + ."\n" + ."
          \n" + ."\t
        • \n"; + $tokenoutput .=$clang->gT("Auto"); + $tokenoutput .= "
        • \n" + ."
        • \n" + ."
        • \n" + ."
        • \n" + ."
        • \n" + ."
        • \n" + ."
        • \n" + ."
        • \n" + ."
        • \n" + ."\t
        • \n" + ."\t
        • \n"; + $tokenoutput .= "\t\n" + ."
        • \n"; + $tokenoutput .= languageDropdownClean($surveyid,GetBaseLanguageFromSurveyID($surveyid)); + $tokenoutput .= "
        • \n" + ."\t
        • \n" + ."\t
        • \n" + ."\t
        • \n" + ."\tconvert($dateformatdetails['phpdate'].' H:i'); + } + $tokenoutput .= "\" />\n convert($dateformatdetails['phpdate'].' H:i'); + } + $tokenoutput .= "\" /> ".sprintf($clang->gT('Format: %s'),$dateformatdetails['dateformat'].' '.$clang->gT('hh:mm')).'' + ."
        • \n"; + + // now the attribute fieds + $attrfieldnames=GetTokenFieldsAndNames($surveyid,true); + foreach ($attrfieldnames as $attr_name=>$attr_description) + { + $tokenoutput .= "
        • " + ."\n" + ."\tgT("Add dummy tokens")."' />\n" - ."\n"; - $tokenoutput .= "

          \n" - ."
        • \n"; + $tokenoutput .="\t

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

        \n" + ."\n"; } if ($subaction == "updatetoken" && bHasSurveyPermission($surveyid, 'tokens','update')) { - $tokenoutput .= "\t
        ".$clang->gT("Edit token entry")."
        \n" - ."\t
        \n"; - if (trim($_POST['validfrom'])=='') { - $_POST['validfrom']=null; - } - else - { - $datetimeobj = new Date_Time_Converter(trim($_POST['validfrom']), $dateformatdetails['phpdate'].' H:i'); - $_POST['validfrom'] =$datetimeobj->convert('Y-m-d H:i:s'); - } - if (trim($_POST['validuntil'])=='') {$_POST['validuntil']=null;} - else - { - $datetimeobj = new Date_Time_Converter(trim($_POST['validuntil']), $dateformatdetails['phpdate'].' H:i'); - $_POST['validuntil'] =$datetimeobj->convert('Y-m-d H:i:s'); - } - $data = array(); - $data[] = $_POST['firstname']; - $data[] = $_POST['lastname']; - $data[] = sanitize_email($_POST['email']); - $data[] = $_POST['emailstatus']; - $santitizedtoken=sanitize_token($_POST['token']); - $data[] = $santitizedtoken; - $data[] = sanitize_languagecode($_POST['language']); - $data[] = $_POST['sent']; - $data[] = $_POST['completed']; - $data[] = $_POST['usesleft']; - // $db->DBTimeStamp("$year-$month-$day $hr:$min:$secs"); - $data[] = $_POST['validfrom']; - $data[] = $_POST['validuntil']; - $data[] = $_POST['remindersent']; - $data[] = intval($_POST['remindercount']); - - $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) - { - $udresult = $connect->Execute("Select * from ".db_table_name("tokens_$surveyid")." where tid={$tokenid} and email='".sanitize_email($_POST['email'])."'") or safe_die ("Update record {$tokenid} failed:
        \n$udquery
        \n".$connect->ErrorMsg()); - - - // 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=?, usesleft=?, validfrom=?, validuntil=?, remindersent=?, remindercount=?"; - $attrfieldnames=GetAttributeFieldnames($surveyid); - foreach ($attrfieldnames as $attr_name) + $tokenoutput .= "\t
        ".$clang->gT("Edit token entry")."
        \n" + ."\t
        \n"; + if (trim($_POST['validfrom'])=='') { + $_POST['validfrom']=null; + } + else { - $udquery.= ", $attr_name=?"; - $data[].=$_POST[$attr_name]; + $datetimeobj = new Date_Time_Converter(trim($_POST['validfrom']), $dateformatdetails['phpdate'].' H:i'); + $_POST['validfrom'] =$datetimeobj->convert('Y-m-d H:i:s'); } + if (trim($_POST['validuntil'])=='') {$_POST['validuntil']=null;} + else + { + $datetimeobj = new Date_Time_Converter(trim($_POST['validuntil']), $dateformatdetails['phpdate'].' H:i'); + $_POST['validuntil'] =$datetimeobj->convert('Y-m-d H:i:s'); + } + $data = array(); + $data[] = $_POST['firstname']; + $data[] = $_POST['lastname']; + $data[] = sanitize_email($_POST['email']); + $data[] = $_POST['emailstatus']; + $santitizedtoken=sanitize_token($_POST['token']); + $data[] = $santitizedtoken; + $data[] = sanitize_languagecode($_POST['language']); + $data[] = $_POST['sent']; + $data[] = $_POST['completed']; + $data[] = $_POST['usesleft']; + // $db->DBTimeStamp("$year-$month-$day $hr:$min:$secs"); + $data[] = $_POST['validfrom']; + $data[] = $_POST['validuntil']; + $data[] = $_POST['remindersent']; + $data[] = intval($_POST['remindercount']); + + $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) + { + $udresult = $connect->Execute("Select * from ".db_table_name("tokens_$surveyid")." where tid={$tokenid} and email='".sanitize_email($_POST['email'])."'") or safe_die ("Update record {$tokenid} failed:
        \n$udquery
        \n".$connect->ErrorMsg()); - $udquery .= " WHERE tid={$tokenid}"; - $udresult = $connect->Execute($udquery, $data) or safe_die ("Update record {$tokenid} failed:
        \n$udquery
        \n".$connect->ErrorMsg()); - $tokenoutput .= "\t\t
        ".$clang->gT("Success")."
        \n" - ."\t\t
        ".$clang->gT("The token entry was successfully updated.")."

        \n" - ."\t\t\n"; - } - else - { - $tokenoutput .= "\t\t
        ".$clang->gT("Failed")."
        \n" - ."\t\t
        ".$clang->gT("There is already an entry with that exact token in the table. The same token cannot be used in multiple entries.")."

        \n" - ."\t\t\n"; - } - $tokenoutput .= "\t
        "; - } - if ($subaction == "inserttoken" && (bHasSurveyPermission($surveyid, 'tokens','create'))) - { - //Fix up dates and match to database format - if (trim($_POST['validfrom'])=='') { - $_POST['validfrom']=null; - } - else - { - $datetimeobj = new Date_Time_Converter(trim($_POST['validfrom']), $dateformatdetails['phpdate'].' H:i'); - $_POST['validfrom'] =$datetimeobj->convert('Y-m-d H:i:s'); - } - if (trim($_POST['validuntil'])=='') {$_POST['validuntil']=null;} - else - { - $datetimeobj = new Date_Time_Converter(trim($_POST['validuntil']), $dateformatdetails['phpdate'].' H:i'); - $_POST['validuntil'] =$datetimeobj->convert('Y-m-d H:i:s'); - } - - $santitizedtoken=sanitize_token($_POST['token']); - - $tokenoutput .= "\t
        ".$clang->gT("Add token entry")."
        \n" - ."\t
        \n"; - $data = array('firstname' => $_POST['firstname'], - 'lastname' => $_POST['lastname'], - 'email' => sanitize_email($_POST['email']), - 'emailstatus' => $_POST['emailstatus'], - 'token' => $santitizedtoken, - 'language' => sanitize_languagecode($_POST['language']), - 'sent' => $_POST['sent'], - 'remindersent' => $_POST['remindersent'], - 'completed' => $_POST['completed'], - 'usesleft' => $_POST['usesleft'], - 'validfrom' => $_POST['validfrom'], - 'validuntil' => $_POST['validuntil']); - // add attributes - $attrfieldnames=GetAttributeFieldnames($surveyid); - foreach ($attrfieldnames as $attr_name) - { - $data[$attr_name]=$_POST[$attr_name]; - } - $tblInsert=db_table_name('tokens_'.$surveyid); - $udresult = $connect->Execute("Select * from ".db_table_name("tokens_$surveyid")." where token<>'' and token='{$santitizedtoken}'"); - if ($udresult->RecordCount()==0) - { - // AutoExecute - $inresult = $connect->AutoExecute($tblInsert, $data, 'INSERT') or safe_die ("Add new record failed:
        \n$inquery
        \n".$connect->ErrorMsg()); - $tokenoutput .= "\t\t
        ".$clang->gT("Success")."
        \n" - ."\t\t
        ".$clang->gT("New token was added.")."

        \n" - ."\t\t
        \n" - ."\t\t
        \n"; - } - else - { - $tokenoutput .= "\t\t
        ".$clang->gT("Failed")."
        \n" - ."\t\t
        ".$clang->gT("There is already an entry with that exact token in the table. The same token cannot be used in multiple entries.")."

        \n" - ."\t\t
        \n" - ."\t\t
        \n"; - } - $tokenoutput .= "\t
        "; - } + // 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=?, usesleft=?, validfrom=?, validuntil=?, remindersent=?, remindercount=?"; + $attrfieldnames=GetAttributeFieldnames($surveyid); + foreach ($attrfieldnames as $attr_name) + { + $udquery.= ", $attr_name=?"; + $data[].=$_POST[$attr_name]; + } - if ($subaction == "insertdummys" && (bHasSurveyPermission($surveyid, 'tokens','create'))) - { - //Fix up dates and match to database format - if (trim($_POST['validfrom'])=='') { - $_POST['validfrom']=null; + $udquery .= " WHERE tid={$tokenid}"; + $udresult = $connect->Execute($udquery, $data) or safe_die ("Update record {$tokenid} failed:
        \n$udquery
        \n".$connect->ErrorMsg()); + $tokenoutput .= "\t\t
        ".$clang->gT("Success")."
        \n" + ."\t\t
        ".$clang->gT("The token entry was successfully updated.")."

        \n" + ."\t\t\n"; + } + else + { + $tokenoutput .= "\t\t
        ".$clang->gT("Failed")."
        \n" + ."\t\t
        ".$clang->gT("There is already an entry with that exact token in the table. The same token cannot be used in multiple entries.")."

        \n" + ."\t\t\n"; + } + $tokenoutput .= "\t
        "; } - else - { - $datetimeobj = new Date_Time_Converter(trim($_POST['validfrom']), $dateformatdetails['phpdate'].' H:i'); - $_POST['validfrom'] =$datetimeobj->convert('Y-m-d H:i:s'); - } - if (trim($_POST['validuntil'])=='') {$_POST['validuntil']=null;} - else + if ($subaction == "inserttoken" && (bHasSurveyPermission($surveyid, 'tokens','create'))) { - $datetimeobj = new Date_Time_Converter(trim($_POST['validuntil']), $dateformatdetails['phpdate'].' H:i'); - $_POST['validuntil'] =$datetimeobj->convert('Y-m-d H:i:s'); + //Fix up dates and match to database format + if (trim($_POST['validfrom'])=='') { + $_POST['validfrom']=null; + } + else + { + $datetimeobj = new Date_Time_Converter(trim($_POST['validfrom']), $dateformatdetails['phpdate'].' H:i'); + $_POST['validfrom'] =$datetimeobj->convert('Y-m-d H:i:s'); + } + if (trim($_POST['validuntil'])=='') {$_POST['validuntil']=null;} + else + { + $datetimeobj = new Date_Time_Converter(trim($_POST['validuntil']), $dateformatdetails['phpdate'].' H:i'); + $_POST['validuntil'] =$datetimeobj->convert('Y-m-d H:i:s'); + } + + $santitizedtoken=sanitize_token($_POST['token']); + + $tokenoutput .= "\t
        ".$clang->gT("Add token entry")."
        \n" + ."\t
        \n"; + $data = array('firstname' => $_POST['firstname'], + 'lastname' => $_POST['lastname'], + 'email' => sanitize_email($_POST['email']), + 'emailstatus' => $_POST['emailstatus'], + 'token' => $santitizedtoken, + 'language' => sanitize_languagecode($_POST['language']), + 'sent' => $_POST['sent'], + 'remindersent' => $_POST['remindersent'], + 'completed' => $_POST['completed'], + 'usesleft' => $_POST['usesleft'], + 'validfrom' => $_POST['validfrom'], + 'validuntil' => $_POST['validuntil']); + // add attributes + $attrfieldnames=GetAttributeFieldnames($surveyid); + foreach ($attrfieldnames as $attr_name) + { + $data[$attr_name]=$_POST[$attr_name]; + } + $tblInsert=db_table_name('tokens_'.$surveyid); + $udresult = $connect->Execute("Select * from ".db_table_name("tokens_$surveyid")." where token<>'' and token='{$santitizedtoken}'"); + if ($udresult->RecordCount()==0) + { + // AutoExecute + $inresult = $connect->AutoExecute($tblInsert, $data, 'INSERT') or safe_die ("Add new record failed:
        \n$inquery
        \n".$connect->ErrorMsg()); + $tokenoutput .= "\t\t
        ".$clang->gT("Success")."
        \n" + ."\t\t
        ".$clang->gT("New token was added.")."

        \n" + ."\t\t
        \n" + ."\t\t
        \n"; + } + else + { + $tokenoutput .= "\t\t
        ".$clang->gT("Failed")."
        \n" + ."\t\t
        ".$clang->gT("There is already an entry with that exact token in the table. The same token cannot be used in multiple entries.")."

        \n" + ."\t\t
        \n" + ."\t\t
        \n"; + } + $tokenoutput .= "\t
        "; } - $santitizedtoken=''; - - $tokenoutput .= "\t
        ".$clang->gT("Add dummy tokens")."
        \n" - ."\t
        \n"; - $data = array('firstname' => $_POST['firstname'], - 'lastname' => $_POST['lastname'], - 'email' => sanitize_email($_POST['email']), - 'emailstatus' => 'OK', - 'token' => $santitizedtoken, - 'language' => sanitize_languagecode($_POST['language']), - 'sent' => 'N', - 'remindersent' => 'N', - 'completed' => 'N', - 'usesleft' => $_POST['usesleft'], - 'validfrom' => $_POST['validfrom'], - 'validuntil' => $_POST['validuntil']); - - // add attributes - $attrfieldnames=GetAttributeFieldnames($surveyid); - foreach ($attrfieldnames as $attr_name) + if ($subaction == "insertdummys" && (bHasSurveyPermission($surveyid, 'tokens','create'))) { - $data[$attr_name]=$_POST[$attr_name]; - } - $tblInsert=db_table_name('tokens_'.$surveyid); - $amount = sanitize_int($_POST['amount']); - $tokenlength = sanitize_int($_POST['tokenlen']); + //Fix up dates and match to database format + if (trim($_POST['validfrom'])=='') { + $_POST['validfrom']=null; + } + + else + { + $datetimeobj = new Date_Time_Converter(trim($_POST['validfrom']), $dateformatdetails['phpdate'].' H:i'); + $_POST['validfrom'] =$datetimeobj->convert('Y-m-d H:i:s'); + } + if (trim($_POST['validuntil'])=='') {$_POST['validuntil']=null;} + else + { + $datetimeobj = new Date_Time_Converter(trim($_POST['validuntil']), $dateformatdetails['phpdate'].' H:i'); + $_POST['validuntil'] =$datetimeobj->convert('Y-m-d H:i:s'); + } - for ($i=0; $i<$amount;$i++){ - $dataToInsert = $data; - $dataToInsert['firstname'] = str_replace('{TOKEN_COUNTER}',"$i",$dataToInsert['firstname']); - $dataToInsert['lastname'] = str_replace('{TOKEN_COUNTER}',"$i",$dataToInsert['lastname']); - $dataToInsert['email'] = str_replace('{TOKEN_COUNTER}',"$i",$dataToInsert['email']); + $santitizedtoken=''; - $isvalidtoken = false; - while ($isvalidtoken == false) + $tokenoutput .= "\t
        ".$clang->gT("Add dummy tokens")."
        \n" + ."\t
        \n"; + $data = array('firstname' => $_POST['firstname'], + 'lastname' => $_POST['lastname'], + 'email' => sanitize_email($_POST['email']), + 'emailstatus' => 'OK', + 'token' => $santitizedtoken, + 'language' => sanitize_languagecode($_POST['language']), + 'sent' => 'N', + 'remindersent' => 'N', + 'completed' => 'N', + 'usesleft' => $_POST['usesleft'], + 'validfrom' => $_POST['validfrom'], + 'validuntil' => $_POST['validuntil']); + + // add attributes + $attrfieldnames=GetAttributeFieldnames($surveyid); + foreach ($attrfieldnames as $attr_name) { - $newtoken = sRandomChars($tokenlength); - if (!isset($existingtokens[$newtoken])) { - $isvalidtoken = true; - $existingtokens[$newtoken]=null; - } + $data[$attr_name]=$_POST[$attr_name]; } - $dataToInsert['token'] = $newtoken; $tblInsert=db_table_name('tokens_'.$surveyid); - $inresult = $connect->AutoExecute($tblInsert, $dataToInsert, 'INSERT') or safe_die ("Add new record failed:
        \n$inquery
        \n".$connect->ErrorMsg()); + $amount = sanitize_int($_POST['amount']); + $tokenlength = sanitize_int($_POST['tokenlen']); - } + for ($i=0; $i<$amount;$i++){ + $dataToInsert = $data; + $dataToInsert['firstname'] = str_replace('{TOKEN_COUNTER}',"$i",$dataToInsert['firstname']); + $dataToInsert['lastname'] = str_replace('{TOKEN_COUNTER}',"$i",$dataToInsert['lastname']); + $dataToInsert['email'] = str_replace('{TOKEN_COUNTER}',"$i",$dataToInsert['email']); + + $isvalidtoken = false; + while ($isvalidtoken == false) + { + $newtoken = sRandomChars($tokenlength); + if (!isset($existingtokens[$newtoken])) { + $isvalidtoken = true; + $existingtokens[$newtoken]=null; + } + } + $dataToInsert['token'] = $newtoken; + $tblInsert=db_table_name('tokens_'.$surveyid); + $inresult = $connect->AutoExecute($tblInsert, $dataToInsert, 'INSERT') or safe_die ("Add new record failed:
        \n$inquery
        \n".$connect->ErrorMsg()); - $tokenoutput .= "\t\t
        ".$clang->gT("Success")."
        \n" - ."\t\t
        ".$clang->gT("New dummy tokens were added.")."

        \n" - ."\t\t
        \n"; - $tokenoutput .= "\t
        "; + } + + $tokenoutput .= "\t\t
        ".$clang->gT("Success")."
        \n" + ."\t\t
        ".$clang->gT("New dummy tokens were added.")."

        \n" + ."\t\t
        \n"; + $tokenoutput .= "\t
        "; } if ($subaction == "import" && bHasSurveyPermission($surveyid, 'tokens','import')) { - $tokenoutput .= "\t
        ".$clang->gT("Upload CSV File")."
        \n"; - form_csv_upload(); - $tokenoutput .= "
        \n" - ."
        ".$clang->gT("CSV input format")."
        \n" - ."

        ".$clang->gT("File should be a standard CSV (comma delimited) file with optional 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, language, validfrom, validuntil, attribute_1, attribute_2, attribute_3, usesleft, ... ." - ."
        \n"; + $tokenoutput .= "\t
        ".$clang->gT("Upload CSV File")."
        \n"; + form_csv_upload(); + $tokenoutput .= "
        \n" + ."
        ".$clang->gT("CSV input format")."
        \n" + ."

        ".$clang->gT("File should be a standard CSV (comma delimited) file with optional 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, language, validfrom, validuntil, attribute_1, attribute_2, attribute_3, usesleft, ... ." + ."
        \n"; } if ($subaction == "importldap" && bHasSurveyPermission($surveyid, 'tokens','import')) { - $tokenoutput .= "\t
        ".$clang->gT("Upload LDAP entries")."
        \n"; - formldap(); - $tokenoutput .= "
        \n" - ."\t
        ".$clang->gT("Note:")."

        \n" - .$clang->gT("LDAP queries are defined by the administrator in the config-ldap.php file")."\n" - ."
        \n"; + $tokenoutput .= "\t
        ".$clang->gT("Upload LDAP entries")."
        \n"; + formldap(); + $tokenoutput .= "
        \n" + ."\t
        ".$clang->gT("Note:")."

        \n" + .$clang->gT("LDAP queries are defined by the administrator in the config-ldap.php file")."\n" + ."
        \n"; } if ($subaction == "upload" && bHasSurveyPermission($surveyid, 'tokens','import')) { - $attrfieldnames=GetAttributeFieldnames($surveyid); - $duplicatelist=array(); - $invalidemaillist=array(); - $invalidformatlist=array(); - $tokenoutput .= "\t
        ".$clang->gT("Token file upload")."
        \n" - ."\t
        \n"; - if (!isset($tempdir)) - { - $the_path = $homedir; - } - else - { - $the_path = $tempdir; - } - $the_file_name = $_FILES['the_file']['name']; - $the_file = $_FILES['the_file']['tmp_name']; - $the_full_file_path = $the_path."/".$the_file_name; - if (!@move_uploaded_file($the_file, $the_full_file_path)) - { - $errormessage="
        ".$clang->gT("Error")."

        ".$clang->gT("Upload file not found. Check your permissions and path ({$the_full_file_path}) for the upload directory")."

        \n"; - form_csv_upload($errormessage); - } - else - { - $tokenoutput .= "
        ".$clang->gT("Uploaded CSV file successfully")."

        \n"; - $xz = 0; $recordcount = 0; $xv = 0; - // This allows to read file with MAC line endings too - @ini_set('auto_detect_line_endings', true); - // open it and trim the ednings - $tokenlistarray = file($the_full_file_path); - $baselanguage=GetBaseLanguageFromSurveyID($surveyid); - if (!isset($tokenlistarray)) + $attrfieldnames=GetAttributeFieldnames($surveyid); + $duplicatelist=array(); + $invalidemaillist=array(); + $invalidformatlist=array(); + $tokenoutput .= "\t
        ".$clang->gT("Token file upload")."
        \n" + ."\t
        \n"; + if (!isset($tempdir)) { - $tokenoutput .= "
        ".$clang->gT("Failed to open the uploaded file!")."

        \n"; + $the_path = $homedir; } - if (!isset($_POST['filterduplicatefields']) || (isset($_POST['filterduplicatefields']) && count($_POST['filterduplicatefields'])==0)) + else { - $filterduplicatefields=array('firstname','lastname','email'); - } else { - $filterduplicatefields=$_POST['filterduplicatefields']; + $the_path = $tempdir; } - $separator = returnglobal('separator'); - foreach ($tokenlistarray as $buffer) + $the_file_name = $_FILES['the_file']['name']; + $the_file = $_FILES['the_file']['tmp_name']; + $the_full_file_path = $the_path."/".$the_file_name; + if (!@move_uploaded_file($the_file, $the_full_file_path)) + { + $errormessage="
        ".$clang->gT("Error")."

        ".$clang->gT("Upload file not found. Check your permissions and path ({$the_full_file_path}) for the upload directory")."

        \n"; + form_csv_upload($errormessage); + } + else { - $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 ($recordcount==0) + $tokenoutput .= "
        ".$clang->gT("Uploaded CSV file successfully")."

        \n"; + $xz = 0; $recordcount = 0; $xv = 0; + // This allows to read file with MAC line endings too + @ini_set('auto_detect_line_endings', true); + // open it and trim the ednings + $tokenlistarray = file($the_full_file_path); + $baselanguage=GetBaseLanguageFromSurveyID($surveyid); + if (!isset($tokenlistarray)) { - // Pick apart the first line - $buffer=removeBOM($buffer); - $allowedfieldnames=array('firstname','lastname','email','emailstatus','token','language', 'validfrom', 'validuntil', 'usesleft'); - $allowedfieldnames=array_merge($attrfieldnames,$allowedfieldnames); - - switch ($separator) { - case 'comma': - $separator = ','; - break; - case 'semicolon': - $separator = ';'; - break; - default: - $comma = substr_count($buffer,','); - $semicolon = substr_count($buffer,';'); - if ($semicolon>$comma) $separator = ';'; else $separator = ','; - } - $firstline = convertCSVRowToArray($buffer,$separator,'"'); - $firstline=array_map('trim',$firstline); - $ignoredcolumns=array(); - //now check the first line for invalid fields - foreach ($firstline as $index=>$fieldname) + $tokenoutput .= "
        ".$clang->gT("Failed to open the uploaded file!")."

        \n"; + } + if (!isset($_POST['filterduplicatefields']) || (isset($_POST['filterduplicatefields']) && count($_POST['filterduplicatefields'])==0)) + { + $filterduplicatefields=array('firstname','lastname','email'); + } else { + $filterduplicatefields=$_POST['filterduplicatefields']; + } + $separator = returnglobal('separator'); + foreach ($tokenlistarray as $buffer) + { + $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 ($recordcount==0) { - $firstline[$index] = preg_replace("/(.*) <[^,]*>$/","$1",$fieldname); - $fieldname = $firstline[$index]; - if (!in_array($fieldname,$allowedfieldnames)) + // Pick apart the first line + $buffer=removeBOM($buffer); + $allowedfieldnames=array('firstname','lastname','email','emailstatus','token','language', 'validfrom', 'validuntil', 'usesleft'); + $allowedfieldnames=array_merge($attrfieldnames,$allowedfieldnames); + + switch ($separator) { + case 'comma': + $separator = ','; + break; + case 'semicolon': + $separator = ';'; + break; + default: + $comma = substr_count($buffer,','); + $semicolon = substr_count($buffer,';'); + if ($semicolon>$comma) $separator = ';'; else $separator = ','; + } + $firstline = convertCSVRowToArray($buffer,$separator,'"'); + $firstline=array_map('trim',$firstline); + $ignoredcolumns=array(); + //now check the first line for invalid fields + foreach ($firstline as $index=>$fieldname) + { + $firstline[$index] = preg_replace("/(.*) <[^,]*>$/","$1",$fieldname); + $fieldname = $firstline[$index]; + if (!in_array($fieldname,$allowedfieldnames)) + { + $ignoredcolumns[]=$fieldname; + } + } + if (!in_array('firstname',$firstline) || !in_array('lastname',$firstline) || !in_array('email',$firstline)) { - $ignoredcolumns[]=$fieldname; + $tokenoutput .= "
        ".$clang->gT("Error: Your uploaded file is missing one or more of the mandatory columns: 'firstname', 'lastname' or 'email'")."

        "; + $recordcount=count($tokenlistarray); + break; } + } - if (!in_array('firstname',$firstline) || !in_array('lastname',$firstline) || !in_array('email',$firstline)) + else { - $tokenoutput .= "
        ".$clang->gT("Error: Your uploaded file is missing one or more of the mandatory columns: 'firstname', 'lastname' or 'email'")."

        "; - $recordcount=count($tokenlistarray); - break; - } - - } - else - { - - $line = convertCSVRowToArray($buffer,$separator,'"'); - if (count($firstline)!=count($line)) - { - $invalidformatlist[]=$recordcount; - $recordcount++; - continue; - } - $writearray=array_combine($firstline,$line); + $line = convertCSVRowToArray($buffer,$separator,'"'); - //kick out ignored columns - foreach ($ignoredcolumns as $column) - { - unset($writearray[$column]); - } - $dupfound=false; - $invalidemail=false; + if (count($firstline)!=count($line)) + { + $invalidformatlist[]=$recordcount; + $recordcount++; + continue; + } + $writearray=array_combine($firstline,$line); - if ($filterduplicatetoken!=false) - { - $dupquery = "SELECT tid from ".db_table_name("tokens_$surveyid")." where 1=1"; - foreach($filterduplicatefields as $field) + //kick out ignored columns + foreach ($ignoredcolumns as $column) { - if (isset($writearray[$field])) { - $dupquery.=' and '.db_quote_id($field).' = '.db_quoteall($writearray[$field]); - } + unset($writearray[$column]); } - $dupresult = $connect->Execute($dupquery) or safe_die ("Invalid field in duplicate check
        $dupquery

        ".$connect->ErrorMsg()); - if ( $dupresult->RecordCount() > 0) + $dupfound=false; + $invalidemail=false; + + if ($filterduplicatetoken!=false) { - $dupfound = true; - $duplicatelist[]=$writearray['firstname']." ".$writearray['lastname']." (".$writearray['email'].")"; + $dupquery = "SELECT tid from ".db_table_name("tokens_$surveyid")." where 1=1"; + foreach($filterduplicatefields as $field) + { + if (isset($writearray[$field])) { + $dupquery.=' and '.db_quote_id($field).' = '.db_quoteall($writearray[$field]); + } + } + $dupresult = $connect->Execute($dupquery) or safe_die ("Invalid field in duplicate check
        $dupquery

        ".$connect->ErrorMsg()); + if ( $dupresult->RecordCount() > 0) + { + $dupfound = true; + $duplicatelist[]=$writearray['firstname']." ".$writearray['lastname']." (".$writearray['email'].")"; + } } - } - $writearray['email'] = trim($writearray['email']); + $writearray['email'] = trim($writearray['email']); - //treat blank emails - if ($filterblankemail && $writearray['email']=='') - { - $invalidemail=true; - $invalidemaillist[]=$line[0]." ".$line[1]." ( )"; - } - if ($writearray['email']!='') - { - $aEmailAddresses=explode(';',$writearray['email']); - foreach ($aEmailAddresses as $sEmailaddress) + //treat blank emails + if ($filterblankemail && $writearray['email']=='') + { + $invalidemail=true; + $invalidemaillist[]=$line[0]." ".$line[1]." ( )"; + } + if ($writearray['email']!='') { - if (!validate_email($sEmailaddress)) + $aEmailAddresses=explode(';',$writearray['email']); + foreach ($aEmailAddresses as $sEmailaddress) { - $invalidemail=true; - $invalidemaillist[]=$line[0]." ".$line[1]." (".$line[2].")"; - } + if (!validate_email($sEmailaddress)) + { + $invalidemail=true; + $invalidemaillist[]=$line[0]." ".$line[1]." (".$line[2].")"; + } + } } - } - if (!isset($writearray['token'])) { - $writearray['token'] = ''; - } else { - $writearray['token']=sanitize_token($writearray['token']); - } + if (!isset($writearray['token'])) { + $writearray['token'] = ''; + } else { + $writearray['token']=sanitize_token($writearray['token']); + } - if (!$dupfound && !$invalidemail) - { - if (!isset($writearray['emailstatus']) || $writearray['emailstatus']=='') $writearray['emailstatus'] = "OK"; - if (!isset($writearray['language']) || $writearray['language'] == "") $writearray['language'] = $baselanguage; - if (isset($writearray['validfrom']) && trim($writearray['validfrom']=='')){ unset($writearray['validfrom']);} - if (isset($writearray['validuntil']) && trim($writearray['validuntil']=='')){ unset($writearray['validuntil']);} + if (!$dupfound && !$invalidemail) + { + if (!isset($writearray['emailstatus']) || $writearray['emailstatus']=='') $writearray['emailstatus'] = "OK"; + if (!isset($writearray['language']) || $writearray['language'] == "") $writearray['language'] = $baselanguage; + if (isset($writearray['validfrom']) && trim($writearray['validfrom']=='')){ unset($writearray['validfrom']);} + if (isset($writearray['validuntil']) && trim($writearray['validuntil']=='')){ unset($writearray['validuntil']);} - // sanitize it before writing into table - $sanitizedArray = array_map('db_quote',array_values($writearray)); + // sanitize it before writing into table + $sanitizedArray = array_map('db_quote',array_values($writearray)); - $iq = "INSERT INTO ".db_table_name("tokens_$surveyid")." \n" - . "(".implode(',',array_keys($writearray)).") \n" - . "VALUES ('".implode("','",$sanitizedArray)."')"; - $ir = $connect->Execute($iq); + $iq = "INSERT INTO ".db_table_name("tokens_$surveyid")." \n" + . "(".implode(',',array_keys($writearray)).") \n" + . "VALUES ('".implode("','",$sanitizedArray)."')"; + $ir = $connect->Execute($iq); - if (!$ir) - { - $duplicatelist[]=$writearray['firstname']." ".$writearray['lastname']." (".$writearray['email'].")"; - } else { - $xz++; + if (!$ir) + { + $duplicatelist[]=$writearray['firstname']." ".$writearray['lastname']." (".$writearray['email'].")"; + } else { + $xz++; + } } + $xv++; } - $xv++; + $recordcount++; } - $recordcount++; - } - $recordcount = $recordcount-1; - if ($xz != 0) - { - $tokenoutput .= "
        ".$clang->gT("Successfully created token entries")."

        \n"; - } else { - $tokenoutput .= "
        ".$clang->gT("Failed to create token entries")."
        \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"; - + $recordcount = $recordcount-1; + if ($xz != 0) + { + $tokenoutput .= "
        ".$clang->gT("Successfully created token entries")."

        \n"; + } else { + $tokenoutput .= "
        ".$clang->gT("Failed to create token entries")."
        \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"; - if (count($duplicatelist)>0 || count($invalidformatlist)>0 || count($invalidemaillist)>0) - { - $message .="
        ".$clang->gT('Warnings')."
          "; - if (count($duplicatelist)>0) + if (count($duplicatelist)>0 || count($invalidformatlist)>0 || count($invalidemaillist)>0) { - $message .= '
        • '.sprintf($clang->gT("%s duplicate records removed"),count($duplicatelist)); - $message .= " [".$clang->gT("List")."]"; - $message .= ""; - $message .= "
        • \n"; - } - if (count($invalidformatlist)>0) - { - $message .= '
        • '.sprintf($clang->gT("%s lines had a mismatching number of fields."),count($invalidformatlist)); - $message .= " [".$clang->gT("List")."]"; - $message .= ""; + $message .= "
          \n"; + $message .= sprintf($clang->gT("%s records with invalid email address removed"),$invalidemailcount); + $message .= " [".$clang->gT("List")."]"; + $message .= "
        • $data
        • \n"; + } + $message .= "
        "; + $message .= "
        \n"; + $tokenoutput .= "$message
        \n"; } - else - { - $tokenoutput .= "".$clang->gT("Failed")."

        \n"; - } - $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"); - $message .= " [".$clang->gT("List")."]"; - $message .= "
      • $data
      • \n"; - } - $message .= ""; - $message .= "
        \n"; - $message .= sprintf($clang->gT("%s records with invalid email address removed"),$invalidemailcount); - $message .= " [".$clang->gT("List")."]"; - $message .= ""; - $message .= "
        \n"; - $tokenoutput .= "$message
        \n"; + else { + $errormessage="".$clang->gT("Error").": ".$clang->gT("Can't bind to the LDAP directory")."\n"; + formldap($errormessage); + } + @ldap_close($ds); } else { - $errormessage="".$clang->gT("Error").": ".$clang->gT("Can't bind to the LDAP directory")."\n"; + $errormessage="".$clang->gT("Error").": ".$clang->gT("Can't connect to the LDAP directory")."\n"; formldap($errormessage); } - @ldap_close($ds); - } - else { - $errormessage="".$clang->gT("Error").": ".$clang->gT("Can't connect to the LDAP directory")."\n"; - formldap($errormessage); - } } // Now for the function function form_csv_upload($error=false) { - global $surveyid, $tokenoutput,$scriptname, $clang, $encodingsarray; + global $surveyid, $tokenoutput,$scriptname, $clang, $encodingsarray; - if ($error) {$tokenoutput .= $error . "

        \n";} - asort($encodingsarray); - $charsetsout=''; - foreach ($encodingsarray as $charset=>$title) - { - $charsetsout.=""; - if ($separator == 'comma') $selected = " selected = 'selected'"; else $selected = ''; - $separatorout .= ""; - if ($separator == 'semicolon') $selected = " selected = 'selected'"; else $selected = ''; - $separatorout .= ""; - $tokenoutput .= "
          \n" - . "
        • \n" - . "
        • \n" - . "
        • \n" - . "
        • \n" - . "
        • " - . "
        • " - . "
        • \n" + . "
        • \n" + . "
        • \n" + . "
        • \n" + . "
        • " + . "
        • " + . " " - . "
        \n" - . "

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

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

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

      \n\n"; } # END form function formldap($error=false) { - global $surveyid, $tokenoutput, $ldap_queries, $clang, $scriptname; + global $surveyid, $tokenoutput, $ldap_queries, $clang, $scriptname; - if ($error) {$tokenoutput .= $error . "

      \n";} + if ($error) {$tokenoutput .= $error . "

      \n";} - if (!function_exists('ldap_connect')) - { - $tokenoutput .= '

      '; - $tokenoutput .= $clang->gT('Sorry, but the LDAP module is missing in your PHP configuration.'); - $tokenoutput .= '
      '; - } + if (!function_exists('ldap_connect')) + { + $tokenoutput .= '

      '; + $tokenoutput .= $clang->gT('Sorry, but the LDAP module is missing in your PHP configuration.'); + $tokenoutput .= '
      '; + } - elseif (! isset($ldap_queries) || ! is_array($ldap_queries) || count($ldap_queries) == 0) { - $tokenoutput .= '
      '; - $tokenoutput .= $clang->gT('LDAP is disabled or no LDAP query defined.'); - $tokenoutput .= '


      '; - } - else { - $tokenoutput .= "

      "; - $tokenoutput .= '

      '; - $tokenoutput .= $clang->gT("Select the LDAP query you want to run:")."
      "; - $tokenoutput .= "
      "; - $tokenoutput .= '

      '; - $tokenoutput .= "

      \n" - . "

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

      "; - $tokenoutput .= '
      '; - } + elseif (! isset($ldap_queries) || ! is_array($ldap_queries) || count($ldap_queries) == 0) { + $tokenoutput .= '
      '; + $tokenoutput .= $clang->gT('LDAP is disabled or no LDAP query defined.'); + $tokenoutput .= '


      '; + } + else { + $tokenoutput .= "
      "; + $tokenoutput .= '

      '; + $tokenoutput .= $clang->gT("Select the LDAP query you want to run:")."
      "; + $tokenoutput .= "
      "; + $tokenoutput .= '

      '; + $tokenoutput .= "

      \n" + . "

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

      "; + $tokenoutput .= '
      '; + } } function getLine($file) { - $buffer=""; - // iterate over each character in line. - while (!feof($file)) - { - // append the character to the buffer. - $character = fgetc($file); - $buffer .= $character; - // check for end of line. - if (($character == "\n") or ($character == "\r")) - { - // checks if the next character is part of the line ending, as in - // the case of windows '\r\n' files, or not as in the case of - // mac classic '\r', and unix/os x '\n' files. + $buffer=""; + // iterate over each character in line. + while (!feof($file)) + { + // append the character to the buffer. $character = fgetc($file); - if ($character == "\n") - { - // part of line ending, append to buffer. - $buffer .= $character; - } - else + $buffer .= $character; + // check for end of line. + if (($character == "\n") or ($character == "\r")) { - // not part of line ending, roll back file pointer. - fseek($file, -1, SEEK_CUR); + // checks if the next character is part of the line ending, as in + // the case of windows '\r\n' files, or not as in the case of + // mac classic '\r', and unix/os x '\n' files. + $character = fgetc($file); + if ($character == "\n") + { + // part of line ending, append to buffer. + $buffer .= $character; + } + else + { + // not part of line ending, roll back file pointer. + fseek($file, -1, SEEK_CUR); + } + // end of line, so stop reading. + break; } - // end of line, so stop reading. - break; } - } - // return the line buffer. - return $buffer; + // return the line buffer. + return $buffer; } ?> \ No newline at end of file