Example #1
0
 /**
  *
  * Enter description here...
  * @param $surveyid
  * @param $type
  * @param $maxLsrcEmails
  * @return unknown_type
  */
 function emailSender($surveyid, $type, $maxLsrcEmails = '')
 {
     global $publicurl, $maxemails;
     global $connect, $sitename;
     global $dbprefix;
     $surveyid = sanitize_int($surveyid);
     include "lsrc.config.php";
     // wenn maxmails ber den lsrc gegeben wird das nutzen, ansonsten die default werte aus der config.php
     if ($maxLsrcEmails != '') {
         $maxemails = $maxLsrcEmails;
     }
     switch ($type) {
         case "custom":
             break;
         case "invite":
             $this->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ", START invite ");
             if (isset($surveyid) && getEmailFormat($surveyid) == 'html') {
                 $ishtml = true;
             } else {
                 $ishtml = false;
             }
             //$tokenoutput .= ("Sending Invitations");
             //if (isset($tokenid)) {$tokenoutput .= " (".("Sending to Token ID").": {$tokenid})";}
             //$tokenoutput .= "\n";
             $this->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ", {$surveyid}, {$type}");
             // Texte für Mails aus der Datenbank holen und in die POST Dinger schreiben. Nicht schön aber praktikabel
             $sql = "SELECT surveyls_language, surveyls_email_invite_subj, surveyls_email_invite  " . "FROM {$dbprefix}surveys_languagesettings " . "WHERE surveyls_survey_id = " . $surveyid . " ";
             //GET SURVEY DETAILS
             $thissurvey = getSurveyInfo($surveyid);
             //				$connect->SetFetchMode(ADODB_FETCH_ASSOC);
             //				$sqlResult=$connect->Execute($sql);
             $sqlResult = db_execute_assoc($sql);
             $this->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ", invite ");
             while ($languageRow = $sqlResult->FetchRow()) {
                 $_POST['message_' . $languageRow['surveyls_language']] = $languageRow['surveyls_email_invite'];
                 $_POST['subject_' . $languageRow['surveyls_language']] = $languageRow['surveyls_email_invite_subj'];
             }
             //				if (isset($_POST['bypassbademails']) && $_POST['bypassbademails'] == 'Y')
             //				{
             //					$SQLemailstatuscondition = " AND emailstatus = 'OK'";
             //				}
             //				else
             //				{
             //					$SQLemailstatuscondition = "";
             //				}
             $this->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ", invite ");
             $ctquery = "SELECT * FROM " . db_table_name("tokens_{$surveyid}") . " WHERE ((completed ='N') or (completed='')) AND ((sent ='N') or (sent='')) AND emailstatus = 'OK' ";
             if (isset($tokenid)) {
                 $ctquery .= " AND tid='{$tokenid}'";
             }
             //$tokenoutput .= "<!-- ctquery: $ctquery -->\n";
             $ctresult = $connect->Execute($ctquery);
             $ctcount = $ctresult->RecordCount();
             $ctfieldcount = $ctresult->FieldCount();
             $emquery = "SELECT * ";
             //if ($ctfieldcount > 7) {$emquery .= ", attribute_1, attribute_2";}
             $this->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ", invite ");
             $emquery .= " FROM " . db_table_name("tokens_{$surveyid}") . " WHERE ((completed ='N') or (completed='')) AND ((sent ='N') or (sent=''))  AND emailstatus = 'OK' ";
             if (isset($tokenid)) {
                 $emquery .= " and tid='{$tokenid}'";
             }
             //$tokenoutput .= "\n\n<!-- emquery: $emquery -->\n\n";
             $emresult = db_select_limit_assoc($emquery, $maxemails);
             $emcount = $emresult->RecordCount();
             //$tokenoutput .= "<table width='500px' align='center' >\n"
             ////."\t<tr>\n"
             //."\t\t<td><font size='1'>\n";
             $surveylangs = GetAdditionalLanguagesFromSurveyID($surveyid);
             $baselanguage = GetBaseLanguageFromSurveyID($surveyid);
             array_unshift($surveylangs, $baselanguage);
             $this->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ", invite ");
             foreach ($surveylangs as $language) {
                 $_POST['message_' . $language] = auto_unescape($_POST['message_' . $language]);
                 $_POST['subject_' . $language] = auto_unescape($_POST['subject_' . $language]);
                 if ($ishtml) {
                     $_POST['message_' . $language] = html_entity_decode($_POST['message_' . $language], ENT_QUOTES, $emailcharset);
                 }
             }
             $this->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ", invite ");
             if ($emcount > 0) {
                 $mailsSend = 0;
                 while ($emrow = $emresult->FetchRow()) {
                     $c = 1;
                     unset($fieldsarray);
                     $to = $emrow['email'];
                     $fieldsarray["{EMAIL}"] = $emrow['email'];
                     $fieldsarray["{FIRSTNAME}"] = $emrow['firstname'];
                     $fieldsarray["{LASTNAME}"] = $emrow['lastname'];
                     $fieldsarray["{TOKEN}"] = $emrow['token'];
                     $fieldsarray["{LANGUAGE}"] = $emrow['language'];
                     while (isset($emrow["attribute_{$c}"])) {
                         $fieldsarray["{ATTRIBUTE_{$c}}"] = $emrow["attribute_{$c}"];
                         $fieldsarray["{TOKEN:ATTRIBUTE_{$c}}"] = $emrow["attribute_{$c}"];
                         ++$c;
                     }
                     $fieldsarray["{ADMINNAME}"] = $thissurvey['adminname'];
                     $fieldsarray["{ADMINEMAIL}"] = $thissurvey['adminemail'];
                     $fieldsarray["{SURVEYNAME}"] = $thissurvey['name'];
                     $fieldsarray["{SURVEYDESCRIPTION}"] = $thissurvey['description'];
                     $fieldsarray["{EXPIRY}"] = $thissurvey["expiry"];
                     $emrow['language'] = trim($emrow['language']);
                     if ($emrow['language'] == '') {
                         $emrow['language'] = $baselanguage;
                     }
                     //if language is not give use default
                     $found = array_search($emrow['language'], $surveylangs);
                     if ($found == false) {
                         $emrow['language'] = $baselanguage;
                     }
                     $from = $thissurvey['adminemail'];
                     if ($ishtml === false) {
                         if ($modrewrite) {
                             $fieldsarray["{SURVEYURL}"] = "{$publicurl}/{$surveyid}/lang-" . trim($emrow['language']) . "/tk-{$emrow['token']}";
                         } else {
                             $fieldsarray["{SURVEYURL}"] = "{$publicurl}/index.php?lang=" . trim($emrow['language']) . "&sid={$surveyid}&token={$emrow['token']}";
                         }
                     } else {
                         if ($modrewrite) {
                             $fieldsarray["{SURVEYURL}"] = "<a href='{$publicurl}/{$surveyid}/lang-" . trim($emrow['language']) . "/tk-{$emrow['token']}'>" . htmlspecialchars("{$publicurl}/{$surveyid}/lang-" . trim($emrow['language']) . "/tk-{$emrow['token']}") . "</a>";
                         } else {
                             $fieldsarray["{SURVEYURL}"] = "<a href='{$publicurl}/index.php?lang=" . trim($emrow['language']) . "&sid={$surveyid}&token={$emrow['token']}'>" . htmlspecialchars("{$publicurl}/index.php?lang=" . trim($emrow['language']) . "&sid={$surveyid}&token={$emrow['token']}") . "</a>";
                         }
                     }
                     $this->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ", invite ");
                     $modsubject = Replacefields($_POST['subject_' . $emrow['language']], $fieldsarray);
                     $modmessage = Replacefields($_POST['message_' . $emrow['language']], $fieldsarray);
                     if (SendEmailMessage($modmessage, $modsubject, $to, $from, $sitename, $ishtml, getBounceEmail($surveyid))) {
                         // Put date into sent
                         //$timeadjust = 0;
                         $today = date("Y-m-d H:i");
                         $this->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ", invite Today:" . $today);
                         $udequery = "UPDATE " . db_table_name("tokens_{$surveyid}") . "\n" . "SET sent='{$today}' WHERE tid={$emrow['tid']}";
                         //
                         $uderesult = $connect->Execute($udequery);
                         $mailsSend++;
                         //$tokenoutput .= "[".("Invitation sent to:")."{$emrow['firstname']} {$emrow['lastname']} ($to)]\n";
                     } else {
                         //$tokenoutput .= ReplaceFields(("Email to {FIRSTNAME} {LASTNAME} ({EMAIL}) failed. Error Message:")." ".$maildebug."", $fieldsarray);
                         if ($n == 1) {
                             $failedAddresses .= "," . $to;
                         } else {
                             $failedAddresses = $to;
                             $n = 1;
                         }
                     }
                 }
                 $this->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ", invite ");
                 if ($ctcount > $emcount) {
                     $lefttosend = $ctcount - $maxemails;
                 } else {
                     $lefttosend = 0;
                 }
             } else {
                 return "No Mails to send";
             }
             if ($maxemails > 0 && $maxemails != '') {
                 $returnValue = "" . $mailsSend . " Mails send. " . $lefttosend . " Mails left to send";
                 if (isset($failedAddresses)) {
                     $returnValue .= "\nCould not send to: " . $failedAddresses;
                 }
                 return $returnValue;
             }
             if (isset($mailsSend)) {
                 $returnValue = "" . $mailsSend . " Mails send. ";
                 if (isset($failedAddresses)) {
                     $returnValue .= "\nCould not send to: " . $failedAddresses;
                 }
                 return $returnValue;
             }
             break;
         case "remind":
             // XXX:
             // TODO:
             //				if (!isset($_POST['ok']) || !$_POST['ok'])
             //				{
             /*
              * look if there were reminders send in the past, and if some tokens got lesser reminders than others
              *
              * - if so: send reminders to the unremindet participants until they got the same remindcount than the others
              * - if not: send reminders normally
              */
             $remSQL = "SELECT tid, remindercount " . "FROM " . db_table_name("tokens_{$surveyid}") . " " . "WHERE (completed = 'N' or completed = '') AND sent <> 'N' and sent <>'' AND token <>'' AND EMAIL <>'' " . "ORDER BY remindercount desc LIMIT 1";
             $this->debugLsrc("Executing SQL: " . $remSQL);
             $remResult = db_execute_assoc($remSQL);
             $remRow = $remResult->FetchRow();
             /* Get the reminder count from the row, if we have a row.  If 
              * we don't have a row then we set reminderCount to 0 to prevent
              * queries down below from bombing out. */
             $reminderCount = $remRow['remindercount'];
             if (empty($reminderCount)) {
                 $this->debugLsrc("There are no reminders to send.");
                 $reminderCount = 0;
             }
             $this->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ", remind " . $remRow['tid'] . "; " . $reminderCount . " ");
             $sendOnlySQL = "SELECT tid, remindercount " . "FROM " . db_table_name("tokens_{$surveyid}") . " " . "WHERE (completed = 'N' or completed = '') AND sent <> 'N' and sent <>'' AND token <>'' AND EMAIL <>'' AND remindercount < " . $reminderCount . " " . "ORDER BY tid asc LIMIT 1";
             $this->debugLsrc("Executing SQL: " . $sendOnlySQL);
             if ($sendOnlyResult->RecordCount() > 0) {
                 $sendOnlyRow = $sendOnlyResult->FetchRow();
                 $starttokenid = $sendOnlyRow['tid'];
                 $this->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ", remind " . $sendOnlyRow['tid'] . "; " . $sendOnlyRow['remindercount'] . " ");
             }
             if (isset($surveyid) && getEmailFormat($surveyid) == 'html') {
                 $ishtml = true;
             } else {
                 $ishtml = false;
             }
             //GET SURVEY DETAILS
             $thissurvey = getSurveyInfo($surveyid);
             $this->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ", {$surveyid}, {$type}");
             // Texte für Mails aus der Datenbank holen.
             $sql = "SELECT surveyls_language, surveyls_email_remind_subj, surveyls_email_remind  " . "FROM {$dbprefix}surveys_languagesettings " . "WHERE surveyls_survey_id = " . $surveyid . " ";
             $this->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ", invite ");
             $sqlResult = db_execute_assoc($sql);
             while ($languageRow = $sqlResult->FetchRow()) {
                 $_POST['message_' . $languageRow['surveyls_language']] = $languageRow['surveyls_email_remind'];
                 $_POST['subject_' . $languageRow['surveyls_language']] = $languageRow['surveyls_email_remind_subj'];
             }
             //$tokenoutput .= ("Sending Reminders")."\n";
             $surveylangs = GetAdditionalLanguagesFromSurveyID($surveyid);
             $baselanguage = GetBaseLanguageFromSurveyID($surveyid);
             array_unshift($surveylangs, $baselanguage);
             foreach ($surveylangs as $language) {
                 $_POST['message_' . $language] = auto_unescape($_POST['message_' . $language]);
                 $_POST['subject_' . $language] = auto_unescape($_POST['subject_' . $language]);
             }
             $SQLemailstatuscondition = " AND emailstatus = 'OK'";
             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 = "";
             }
             $ctquery = "SELECT * FROM " . db_table_name("tokens_{$surveyid}") . " WHERE (completed ='N' or completed ='') AND sent<>'' AND sent<>'N' AND token <>'' AND email <> '' {$SQLemailstatuscondition} {$SQLremindercountcondition} {$SQLreminderdelaycondition}";
             if (isset($starttokenid)) {
                 $ctquery .= " AND tid >= '{$starttokenid}'";
             }
             //					if (isset($tokenid) && $tokenid) {$ctquery .= " AND tid = '{$tokenid}'";}
             //					//$tokenoutput .= "<!-- ctquery: $ctquery -->\n";
             $ctresult = $connect->Execute($ctquery) or $this->debugLsrc("Database error!\n" . $connect->ErrorMsg());
             $ctcount = $ctresult->RecordCount();
             $ctfieldcount = $ctresult->FieldCount();
             $emquery = "SELECT * ";
             //if ($ctfieldcount > 7) {$emquery .= ", attribute_1, attribute_2";}
             // TLR change to put date into sent
             $emquery .= " FROM " . db_table_name("tokens_{$surveyid}") . " WHERE (completed = 'N' or completed = '') AND sent <> 'N' and sent <>'' AND token <>'' AND EMAIL <>'' {$SQLemailstatuscondition} {$SQLremindercountcondition} {$SQLreminderdelaycondition}";
             if (isset($starttokenid)) {
                 $emquery .= " AND tid >= '{$starttokenid}'";
             }
             if (isset($tokenid) && $tokenid) {
                 $emquery .= " AND tid = '{$tokenid}'";
             }
             $emquery .= " ORDER BY tid ";
             $emresult = db_select_limit_assoc($emquery, $maxemails);
             //$emresult = db_execute_assoc($emquery);
             $emcount = $emresult->RecordCount();
             if ($emcount > 0) {
                 while ($emrow = $emresult->FetchRow()) {
                     $c = 1;
                     unset($fieldsarray);
                     $to = $emrow['email'];
                     $fieldsarray["{EMAIL}"] = $emrow['email'];
                     $fieldsarray["{FIRSTNAME}"] = $emrow['firstname'];
                     $fieldsarray["{LASTNAME}"] = $emrow['lastname'];
                     $fieldsarray["{TOKEN}"] = $emrow['token'];
                     $fieldsarray["{LANGUAGE}"] = $emrow['language'];
                     while (isset($emrow["attribute_{$c}"])) {
                         $fieldsarray["{ATTRIBUTE_{$c}}"] = $emrow["attribute_{$c}"];
                         $fieldsarray["{TOKEN:ATTRIBUTE_{$c}}"] = $emrow["attribute_{$c}"];
                         ++$c;
                     }
                     $fieldsarray["{ADMINNAME}"] = $thissurvey['adminname'];
                     $fieldsarray["{ADMINEMAIL}"] = $thissurvey['adminemail'];
                     $fieldsarray["{SURVEYNAME}"] = $thissurvey['name'];
                     $fieldsarray["{SURVEYDESCRIPTION}"] = $thissurvey['description'];
                     $fieldsarray["{EXPIRY}"] = $thissurvey["expiry"];
                     $emrow['language'] = trim($emrow['language']);
                     if ($emrow['language'] == '') {
                         $emrow['language'] = $baselanguage;
                     }
                     //if language is not give use default
                     if (!in_array($emrow['language'], $surveylangs)) {
                         $emrow['language'] = $baselanguage;
                     }
                     // if given language is not available use default
                     $found = array_search($emrow['language'], $surveylangs);
                     if ($found == false) {
                         $emrow['language'] = $baselanguage;
                     }
                     $from = $thissurvey['adminemail'];
                     if (getEmailFormat($surveyid) == 'html') {
                         $ishtml = true;
                     } else {
                         $ishtml = false;
                     }
                     if ($ishtml == false) {
                         if ($modrewrite) {
                             $fieldsarray["{SURVEYURL}"] = "{$publicurl}/{$surveyid}/lang-" . trim($emrow['language']) . "/tk-{$emrow['token']}";
                         } else {
                             $fieldsarray["{SURVEYURL}"] = "{$publicurl}/index.php?lang=" . trim($emrow['language']) . "&sid={$surveyid}&token={$emrow['token']}";
                         }
                     } else {
                         if ($modrewrite) {
                             $fieldsarray["{SURVEYURL}"] = "<a href='{$publicurl}/{$surveyid}/lang-" . trim($emrow['language']) . "/tk-{$emrow['token']}'>" . htmlspecialchars("{$publicurl}/{$surveyid}/lang-" . trim($emrow['language']) . "/tk-{$emrow['token']}") . "</a>";
                         } else {
                             $fieldsarray["{SURVEYURL}"] = "<a href='{$publicurl}/index.php?lang=" . trim($emrow['language']) . "&sid={$surveyid}&token={$emrow['token']}'>" . htmlspecialchars("{$publicurl}/index.php?lang=" . trim($emrow['language']) . "&sid={$surveyid}&token={$emrow['token']}") . "</a>";
                             $_POST['message_' . $emrow['language']] = html_entity_decode($_POST['message_' . $emrow['language']], ENT_QUOTES, $emailcharset);
                         }
                     }
                     $msgsubject = Replacefields($_POST['subject_' . $emrow['language']], $fieldsarray);
                     $sendmessage = Replacefields($_POST['message_' . $emrow['language']], $fieldsarray);
                     if (SendEmailMessage($sendmessage, $msgsubject, $to, $from, $sitename, $ishtml, getBounceEmail($surveyid))) {
                         // Put date into remindersent
                         $today = date("Y-m-d H:i");
                         $udequery = "UPDATE " . db_table_name("tokens_{$surveyid}") . "\n" . "SET remindersent='{$today}',remindercount = remindercount+1  WHERE tid={$emrow['tid']}";
                         //
                         $uderesult = $connect->Execute($udequery) or $this->debugLsrc("Could not update tokens{$udequery}" . $connect->ErrorMsg());
                         //orig: $tokenoutput .= "\t\t\t({$emrow['tid']})[".("Reminder sent to:")." {$emrow['firstname']} {$emrow['lastname']}]\n";
                         //$tokenoutput .= "\t\t\t({$emrow['tid']}) [".("Reminder sent to:")." {$emrow['firstname']} {$emrow['lastname']} ($to)]\n";
                         $mailsSend++;
                     } else {
                         //$tokenoutput .= ReplaceFields(("Email to {FIRSTNAME} {LASTNAME} ({EMAIL}) failed. Error Message:")." ".$maildebug."", $fieldsarray);
                         if ($n == 1) {
                             $failedAddresses .= "," . $to;
                         } else {
                             $failedAddresses = $to;
                             $n = 1;
                         }
                     }
                     //$lasttid = $emrow['tid'];
                 }
                 if ($ctcount > $emcount) {
                     $lefttosend = $ctcount - $maxemails;
                 } else {
                     $lefttosend = 0;
                 }
             } else {
                 return "No Reminders to send";
             }
             if ($maxemails > 0) {
                 $returnValue = "" . $mailsSend . " Reminders send. " . $lefttosend . " Reminders left to send";
                 if (isset($failedAddresses)) {
                     $returnValue .= "\nCould not send to: " . $failedAddresses;
                 }
                 return $returnValue;
             }
             if (isset($mailsSend)) {
                 $returnValue = "" . $mailsSend . " Reminders send. ";
                 if (isset($failedAddresses)) {
                     $returnValue .= "\nCould not send to: " . $failedAddresses;
                 }
                 return $returnValue;
             }
             break;
         default:
             break;
     }
 }
Example #2
0
 ////////////////////////////////////////////////////////////////////////
 // SURVEY MENU BAR
 ////////////////////////////////////////////////////////////////////////
 $surveysummary .= "" . "<div class='menubar surveybar'>\n" . "<div class='menubar-title ui-widget-header'>\n" . "<strong>" . $clang->gT("Survey") . "</strong> " . "<span class='basic'>{$surveyinfo['surveyls_title']} (" . $clang->gT("ID") . ":{$surveyid})</span></div>\n" . "<div class='menubar-main'>\n" . "<div class='menubar-left'>\n";
 // ACTIVATE SURVEY BUTTON
 if ($activated == "N") {
     $surveysummary .= "<img src='{$imageurl}/inactive.png' " . "alt='" . $clang->gT("This survey is currently not active") . "' />\n";
     if ($sumcount3 > 0 && bHasSurveyPermission($surveyid, 'surveyactivation', 'update')) {
         $surveysummary .= "<a href=\"#\" onclick=\"window.open('{$scriptname}?action=activate&amp;sid={$surveyid}', '_top')\"" . " title=\"" . $clang->gTview("Activate this Survey") . "\" >" . "<img src='{$imageurl}/activate.png' name='ActivateSurvey' alt='" . $clang->gT("Activate this Survey") . "'/></a>\n";
     } else {
         $surveysummary .= "<img src='{$imageurl}/activate_disabled.png' alt='" . $clang->gT("Survey cannot be activated. Either you have no permission or there are no questions.") . "' />\n";
     }
 } elseif ($activated == "Y") {
     if ($surveyinfo['expires'] != '' && $surveyinfo['expires'] < date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i", $timeadjust)) {
         $surveysummary .= "<img src='{$imageurl}/expired.png' " . "alt='" . $clang->gT("This survey is active but expired.") . "' />\n";
     } elseif ($surveyinfo['startdate'] != '' && $surveyinfo['startdate'] > date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i", $timeadjust)) {
         $surveysummary .= "<img src='{$imageurl}/notyetstarted.png' " . "alt='" . $clang->gT("This survey is active but has a start date.") . "' />\n";
     } else {
         $surveysummary .= "<img src='{$imageurl}/active.png' title='' " . "alt='" . $clang->gT("This survey is currently active.") . "' />\n";
     }
     if (bHasSurveyPermission($surveyid, 'surveyactivation', 'update')) {
         $surveysummary .= "<a href=\"#\" onclick=\"window.open('{$scriptname}?action=deactivate&amp;sid={$surveyid}', '_top')\"" . " title=\"" . $clang->gTview("Deactivate this Survey") . "\" >" . "<img src='{$imageurl}/deactivate.png' alt='" . $clang->gT("Deactivate this Survey") . "' /></a>\n";
     } else {
         $surveysummary .= "<img src='{$imageurl}/blank.gif' alt='' width='14' />\n";
     }
 }
 $surveysummary .= "<img src='{$imageurl}/seperator.gif' alt=''  />\n" . "</div>\n";
 // Start of suckerfish menu
 $surveysummary .= "<ul class='sf-menu'>\n";
 // ACTIVATE SURVEY BUTTON
 if ($activated == "N") {
/**
* This function imports a LimeSurvey .lss survey XML file
*
* @param mixed $sFullFilepath  The full filepath of the uploaded file
*/
function XMLImportSurvey($sFullFilepath,$sXMLdata=NULL,$sNewSurveyName=NULL,$iDesiredSurveyId=NULL, $bTranslateInsertansTags=true)
{
    global $connect, $dbprefix, $clang, $timeadjust;

    $results['error']=false;
    if ($sXMLdata == NULL)
    {
        $xml = simplexml_load_file($sFullFilepath);
    } else
    {
        $xml = simplexml_load_string($sXMLdata);
    }

    if ($xml->LimeSurveyDocType!='Survey')
    {
        $results['error'] = $clang->gT("This is not a valid LimeSurvey survey structure XML file.");
        return $results;
    }
    else
    {
        //$results['error'] = $clang->gT("This is VALID LimeSurvey survey structure XML file.");
        //echo $clang->gT("This is VALID LimeSurvey survey structure XML file.");
        //return $results;
    }
    $dbversion = (int) $xml->DBVersion;
    $aQIDReplacements=array();
    $aQuotaReplacements=array();
    $results['defaultvalues']=0;
    $results['answers']=0;
    $results['surveys']=0;
    $results['questions']=0;
    $results['subquestions']=0;
    $results['question_attributes']=0;
    $results['groups']=0;
    $results['assessments']=0;
    $results['quota']=0;
    $results['quotals']=0;
    $results['quotamembers']=0;
    $results['importwarnings']=array();


    $aLanguagesSupported=array();
    foreach ($xml->languages->language as $language)
    {
        $aLanguagesSupported[]=(string)$language;
    }
    $results['languages']=count($aLanguagesSupported);


    // First get an overview of fieldnames - it's not useful for the moment but might be with newer versions
    /*
    $fieldnames=array();
    foreach ($xml->questions->fields->fieldname as $fieldname )
    {
        $fieldnames[]=(string)$fieldname;
    };*/


    // Import surveys table ===================================================================================

    $tablename=$dbprefix.'surveys';
    foreach ($xml->surveys->rows->row as $row)
    {
        $insertdata=array();
        foreach ($row as $key=>$value)
        {
            $insertdata[(string)$key]=(string)$value;
        }
        $oldsid=$insertdata['sid'];
        if($iDesiredSurveyId!=NULL)
        {
            $newsid=GetNewSurveyID($iDesiredSurveyId);
        }
        else
        {
            $newsid=GetNewSurveyID($oldsid);
        }
        if ($dbversion<=143)
        {
            $insertdata['anonymized']=$insertdata['private'];
            unset($insertdata['private']);
            unset($insertdata['notification']);
        }
        $insertdata['startdate']=NULL;
        //Now insert the new SID and change some values
        $insertdata['sid']=$newsid;
        //Make sure it is not set active
        $insertdata['active']='N';
        //Set current user to be the owner
        $insertdata['owner_id']=$_SESSION['loginID'];
        //Change creation date to import date
        $insertdata['datecreated']=$connect->BindTimeStamp(date_shift(date("Y-m-d H:i:s"), "Y-m-d", $timeadjust));

        db_switchIDInsert('surveys',true);
        $query=$connect->GetInsertSQL($tablename,$insertdata);
        $result = $connect->Execute($query) or safe_die ($clang->gT("Error").": Failed to insert data<br />{$query}<br />\n".$connect->ErrorMsg());
        $results['surveys']++;
        db_switchIDInsert('surveys',false);
    }
    $results['newsid']=$newsid;

    // Import survey languagesettings table ===================================================================================

    $tablename=$dbprefix.'surveys_languagesettings';
    foreach ($xml->surveys_languagesettings->rows->row as $row)
    {
        $insertdata=array();
        foreach ($row as $key=>$value)
        {
            $insertdata[(string)$key]=(string)$value;
        }
        $insertdata['surveyls_survey_id']=$newsid;
        if ($sNewSurveyName == NULL)
        {
            $insertdata['surveyls_title']=translink('survey', $oldsid, $newsid, $insertdata['surveyls_title']);
        } else {
            $insertdata['surveyls_title']=translink('survey', $oldsid, $newsid, $sNewSurveyName);
        }

        $insertdata['surveyls_description']=translink('survey', $oldsid, $newsid, $insertdata['surveyls_description']);
        $insertdata['surveyls_welcometext']=translink('survey', $oldsid, $newsid, $insertdata['surveyls_welcometext']);
        $insertdata['surveyls_urldescription']=translink('survey', $oldsid, $newsid, $insertdata['surveyls_urldescription']);
        $insertdata['surveyls_email_invite']=translink('survey', $oldsid, $newsid, $insertdata['surveyls_email_invite']);
        $insertdata['surveyls_email_remind']=translink('survey', $oldsid, $newsid, $insertdata['surveyls_email_remind']);
        $insertdata['surveyls_email_register']=translink('survey', $oldsid, $newsid, $insertdata['surveyls_email_register']);
        $insertdata['surveyls_email_confirm']=translink('survey', $oldsid, $newsid, $insertdata['surveyls_email_confirm']);

        $query=$connect->GetInsertSQL($tablename,$insertdata);
        $result = $connect->Execute($query) or safe_die ($clang->gT("Error").": Failed to insert data<br />{$query}<br />\n".$connect->ErrorMsg());
    }


    // Import groups table ===================================================================================

    $tablename=$dbprefix.'groups';
    foreach ($xml->groups->rows->row as $row)
    {
       $insertdata=array();
        foreach ($row as $key=>$value)
        {
            $insertdata[(string)$key]=(string)$value;
        }
        $oldsid=$insertdata['sid'];
        $insertdata['sid']=$newsid;
        $oldgid=$insertdata['gid']; unset($insertdata['gid']); // save the old qid

        // now translate any links
        $insertdata['group_name']=translink('survey', $oldsid, $newsid, $insertdata['group_name']);
        $insertdata['description']=translink('survey', $oldsid, $newsid, $insertdata['description']);
        // Insert the new group
        if (isset($aGIDReplacements[$oldgid]))
        {
           db_switchIDInsert('groups',true);
           $insertdata['gid']=$aGIDReplacements[$oldgid];
        }
        $query=$connect->GetInsertSQL($tablename,$insertdata);
        $result = $connect->Execute($query) or safe_die ($clang->gT("Error").": Failed to insert data<br />{$query}<br />\n".$connect->ErrorMsg());
        $results['groups']++;

        if (!isset($aGIDReplacements[$oldgid]))
        {
            $newgid=$connect->Insert_ID($tablename,"gid"); // save this for later
            $aGIDReplacements[$oldgid]=$newgid; // add old and new qid to the mapping array
        }
        else
        {
           db_switchIDInsert('groups',false);
        }
    }


    // Import questions table ===================================================================================

    // We have to run the question table data two times - first to find all main questions
    // then for subquestions (because we need to determine the new qids for the main questions first)
    if(isset($xml->questions))  // there could be surveys without a any questions
    {
        $tablename=$dbprefix.'questions';
        foreach ($xml->questions->rows->row as $row)
        {
           $insertdata=array();
            foreach ($row as $key=>$value)
            {
                $insertdata[(string)$key]=(string)$value;
            }
            $oldsid=$insertdata['sid'];
            $insertdata['sid']=$newsid;
            $insertdata['gid']=$aGIDReplacements[$insertdata['gid']];
            $oldqid=$insertdata['qid']; unset($insertdata['qid']); // save the old qid

            // now translate any links
            $insertdata['title']=translink('survey', $oldsid, $newsid, $insertdata['title']);
            $insertdata['question']=translink('survey', $oldsid, $newsid, $insertdata['question']);
            $insertdata['help']=translink('survey', $oldsid, $newsid, $insertdata['help']);
            // Insert the new question
            if (isset($aQIDReplacements[$oldqid]))
            {
               $insertdata['qid']=$aQIDReplacements[$oldqid];
               db_switchIDInsert('questions',true);

            }
            $query=$connect->GetInsertSQL($tablename,$insertdata);
            $result = $connect->Execute($query) or safe_die ($clang->gT("Error").": Failed to insert data<br />{$query}<br />\n".$connect->ErrorMsg());
            if (!isset($aQIDReplacements[$oldqid]))
            {
                $newqid=$connect->Insert_ID($tablename,"qid"); // save this for later
                $aQIDReplacements[$oldqid]=$newqid; // add old and new qid to the mapping array
                $results['questions']++;
            }
            else
            {
               db_switchIDInsert('questions',false);
            }
        }
    }

    // Import subquestions --------------------------------------------------------------
    if(isset($xml->subquestions))
    {
        $tablename=$dbprefix.'questions';

        foreach ($xml->subquestions->rows->row as $row)
        {
            $insertdata=array();
            foreach ($row as $key=>$value)
            {
                $insertdata[(string)$key]=(string)$value;
            }
            $insertdata['sid']=$newsid;
            $insertdata['gid']=$aGIDReplacements[(int)$insertdata['gid']];;
            $oldsqid=(int)$insertdata['qid']; unset($insertdata['qid']); // save the old qid
            $insertdata['parent_qid']=$aQIDReplacements[(int)$insertdata['parent_qid']]; // remap the parent_qid

            // now translate any links
            $insertdata['title']=translink('survey', $oldsid, $newsid, $insertdata['title']);
            $insertdata['question']=translink('survey', $oldsid, $newsid, $insertdata['question']);
            $insertdata['help']=translink('survey', $oldsid, $newsid, $insertdata['help']);
            if (isset($aQIDReplacements[$oldsqid])){
               $insertdata['qid']=$aQIDReplacements[$oldsqid];
               db_switchIDInsert('questions',true);
            }

            $query=$connect->GetInsertSQL($tablename,$insertdata);
            $result = $connect->Execute($query) or safe_die ($clang->gT("Error").": Failed to insert data<br />{$query}<br />\n".$connect->ErrorMsg());
            $newsqid=$connect->Insert_ID($tablename,"qid"); // save this for later
            if (!isset($insertdata['qid']))
            {
                $aQIDReplacements[$oldsqid]=$newsqid; // add old and new qid to the mapping array
            }
            else
            {
               db_switchIDInsert('questions',false);
            }
            $results['subquestions']++;
        }
    }

    // Import answers --------------------------------------------------------------
    if(isset($xml->answers))
    {
        $tablename=$dbprefix.'answers';

        foreach ($xml->answers->rows->row as $row)
        {
           $insertdata=array();
            foreach ($row as $key=>$value)
            {
                $insertdata[(string)$key]=(string)$value;
            }
            $insertdata['qid']=$aQIDReplacements[(int)$insertdata['qid']]; // remap the parent_qid

            // now translate any links
            $insertdata['answer']=translink('survey', $oldsid, $newsid, $insertdata['answer']);
            $query=$connect->GetInsertSQL($tablename,$insertdata);
            $result=$connect->Execute($query) or safe_die ($clang->gT("Error").": Failed to insert data<br />{$query}<br />\n".$connect->ErrorMsg());
            $results['answers']++;
        }
    }

    // Import questionattributes --------------------------------------------------------------
    if(isset($xml->question_attributes))
    {
        $tablename=$dbprefix.'question_attributes';

        foreach ($xml->question_attributes->rows->row as $row)
        {
            $insertdata=array();
            foreach ($row as $key=>$value)
            {
                $insertdata[(string)$key]=(string)$value;
            }
            unset($insertdata['qaid']);
            $insertdata['qid']=$aQIDReplacements[(integer)$insertdata['qid']]; // remap the parent_qid

            // now translate any links
            $query=$connect->GetInsertSQL($tablename,$insertdata);
            $result=$connect->Execute($query) or safe_die ($clang->gT("Error").": Failed to insert data<br />{$query}<br />\n".$connect->ErrorMsg());
            $results['question_attributes']++;
        }
    }


    // Import defaultvalues --------------------------------------------------------------
    if(isset($xml->defaultvalues))
    {
        $tablename=$dbprefix.'defaultvalues';

        $results['defaultvalues']=0;
        foreach ($xml->defaultvalues->rows->row as $row)
        {
           $insertdata=array();
            foreach ($row as $key=>$value)
            {
                $insertdata[(string)$key]=(string)$value;
            }
            $insertdata['qid']=$aQIDReplacements[(int)$insertdata['qid']]; // remap the qid
            if (isset($aQIDReplacements[(int)$insertdata['sqid']])) $insertdata['sqid']=$aQIDReplacements[(int)$insertdata['sqid']]; // remap the subquestion id

            // now translate any links
            $query=$connect->GetInsertSQL($tablename,$insertdata);
            $result=$connect->Execute($query) or safe_die ($clang->gT("Error").": Failed to insert data<br />\$query<br />\n".$connect->ErrorMsg());
            $results['defaultvalues']++;
        }
    }

    // Import conditions --------------------------------------------------------------
    if(isset($xml->conditions))
    {
        $tablename=$dbprefix.'conditions';

        $results['conditions']=0;
        foreach ($xml->conditions->rows->row as $row)
        {
            $insertdata=array();
            foreach ($row as $key=>$value)
            {
                $insertdata[(string)$key]=(string)$value;
            }
            // replace the qid for the new one (if there is no new qid in the $aQIDReplacements array it mean that this condition is orphan -> error, skip this record)
            if (isset($aQIDReplacements[$insertdata['qid']]))
            {
                $insertdata['qid']=$aQIDReplacements[$insertdata['qid']]; // remap the qid
            }
            else continue; // a problem with this answer record -> don't consider
            if ($insertdata['cqid'] != 0)
            {
                if (isset($aQIDReplacements[$insertdata['cqid']]))
                {
                    $insertdata['cqid']=$aQIDReplacements[$insertdata['cqid']]; // remap the qid
                }
                else continue; // a problem with this answer record -> don't consider

                list($oldcsid, $oldcgid, $oldqidanscode) = explode("X",$insertdata["cfieldname"],3);

                // replace the gid for the new one in the cfieldname(if there is no new gid in the $aGIDReplacements array it means that this condition is orphan -> error, skip this record)
                if (!isset($aGIDReplacements[$oldcgid]))
                    continue;
            }

            unset($insertdata["cid"]);

            // recreate the cfieldname with the new IDs
            if ($insertdata['cqid'] != 0)
            {
                if (preg_match("/^\+/",$oldcsid))
                {
                    $newcfieldname = '+'.$newsid . "X" . $aGIDReplacements[$oldcgid] . "X" . $insertdata["cqid"] .substr($oldqidanscode,strlen($oldqid));
                }
                else
                {
                    $newcfieldname = $newsid . "X" . $aGIDReplacements[$oldcgid] . "X" . $insertdata["cqid"] .substr($oldqidanscode,strlen($oldqid));
                }
            }
            else
            { // The cfieldname is a not a previous question cfield but a {XXXX} replacement field
                $newcfieldname = $insertdata["cfieldname"];
            }
            $insertdata["cfieldname"] = $newcfieldname;
            if (trim($insertdata["method"])=='')
            {
                $insertdata["method"]='==';
            }

            // now translate any links
            $query=$connect->GetInsertSQL($tablename,$insertdata);
            $result=$connect->Execute($query) or safe_die ($clang->gT("Error").": Failed to insert data<br />\$query<br />\n".$connect->ErrorMsg());
            $results['conditions']++;
        }
    }

    // Import assessments --------------------------------------------------------------
    if(isset($xml->assessments))
    {
        $tablename=$dbprefix.'assessments';

        foreach ($xml->assessments->rows->row as $row)
        {
            $insertdata=array();
            foreach ($row as $key=>$value)
            {
                $insertdata[(string)$key]=(string)$value;
            }
            if  ($insertdata['gid']>0)
            {
                $insertdata['gid']=$aGIDReplacements[(int)$insertdata['gid']]; // remap the qid
            }

            $insertdata['sid']=$newsid; // remap the survey id

            // now translate any links
            $query=$connect->GetInsertSQL($tablename,$insertdata);
            $result=$connect->Execute($query) or safe_die ($clang->gT("Error").": Failed to insert data<br />\$query<br />\n".$connect->ErrorMsg());
            $results['assessments']++;
        }
    }

    // Import quota --------------------------------------------------------------
    if(isset($xml->quota))
    {
        $tablename=$dbprefix.'quota';

        foreach ($xml->quota->rows->row as $row)
        {
            $insertdata=array();
            foreach ($row as $key=>$value)
            {
                $insertdata[(string)$key]=(string)$value;
            }
            $insertdata['sid']=$newsid; // remap the survey id
            $oldid=$insertdata['id'];
            unset($insertdata['id']);
            // now translate any links
            $query=$connect->GetInsertSQL($tablename,$insertdata);
            $result=$connect->Execute($query) or safe_die ($clang->gT("Error").": Failed to insert data<br />\$query<br />\n".$connect->ErrorMsg());
            $aQuotaReplacements[$oldid] = $connect->Insert_ID(db_table_name_nq('quota'),"id");
            $results['quota']++;
        }
    }

    // Import quota_members --------------------------------------------------------------
    if(isset($xml->quota_members))
    {
        $tablename=$dbprefix.'quota_members';

        foreach ($xml->quota_members->rows->row as $row)
        {
            $insertdata=array();
            foreach ($row as $key=>$value)
            {
                $insertdata[(string)$key]=(string)$value;
            }
            $insertdata['sid']=$newsid; // remap the survey id
            $insertdata['qid']=$aQIDReplacements[(int)$insertdata['qid']]; // remap the qid
            $insertdata['quota_id']=$aQuotaReplacements[(int)$insertdata['quota_id']]; // remap the qid
            unset($insertdata['id']);
            // now translate any links
            $query=$connect->GetInsertSQL($tablename,$insertdata);
            $result=$connect->Execute($query) or safe_die ($clang->gT("Error").": Failed to insert data<br />\$query<br />\n".$connect->ErrorMsg());
            $results['quotamembers']++;
        }
    }

    // Import quota_languagesettings --------------------------------------------------------------
    if(isset($xml->quota_languagesettings))
    {
        $tablename=$dbprefix.'quota_languagesettings';

        foreach ($xml->quota_languagesettings->rows->row as $row)
        {
            $insertdata=array();
            foreach ($row as $key=>$value)
            {
                $insertdata[(string)$key]=(string)$value;
            }
            $insertdata['quotals_quota_id']=$aQuotaReplacements[(int)$insertdata['quotals_quota_id']]; // remap the qid
            unset($insertdata['quotals_id']);
            // now translate any links
            $query=$connect->GetInsertSQL($tablename,$insertdata);
            $result=$connect->Execute($query) or safe_die ($clang->gT("Error").": Failed to insert data<br />\$query<br />\n".$connect->ErrorMsg());
            $results['quotals']++;
        }
    }

    // Set survey rights
    GiveAllSurveyPermissions($_SESSION['loginID'],$newsid);
    if ($bTranslateInsertansTags)
    {
        $aOldNewFieldmap=aReverseTranslateFieldnames($oldsid,$newsid,$aGIDReplacements,$aQIDReplacements);
        TranslateInsertansTags($newsid,$oldsid,$aOldNewFieldmap);
    }

    return $results;
}
Example #4
0
    include $homedir . "/sessioncontrol.php";
    /**
     * @param string $htmlheader
     * This is the html header text for all administration pages
     *
     */
    $htmlheader = getAdminHeader();
}
//SET LANGUAGE DIRECTORY
if ($sourcefrom == "admin") {
    $langdir = "{$publicurl}/locale/" . $_SESSION['adminlang'] . "/help";
    $langdirlocal = "{$rootdir}/locale/" . $_SESSION['adminlang'] . "/help";
    if (!is_dir($langdirlocal)) {
        $langdir = "{$publicurl}/locale/en/help";
        //default to english if there is no matching language dir
    }
}
if ($sourcefrom == "admin" && $buildnumber != "" && $updatecheckperiod > 0 && $updatelastcheck < date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", "-" . $updatecheckperiod . " days")) {
    //updatecheck();
}
//SET LOCAL TIME
if (substr($timeadjust, 0, 1) != '-' && substr($timeadjust, 0, 1) != '+') {
    $timeadjust = '+' . $timeadjust;
}
if (strpos($timeadjust, 'hours') === false && strpos($timeadjust, 'minutes') === false && strpos($timeadjust, 'days') === false) {
    $timeadjust = $timeadjust . ' hours';
}
// SITE STYLES
$setfont = "<font size='2' face='verdana'>";
$singleborderstyle = "style='border: 1px solid #111111'";
// Closing PHP tag intentionally left out - yes, it is okay
Example #5
0
/**
* This function imports a LimeSurvey .lss survey XML file
* 
* @param mixed $sFullFilepath  The full filepath of the uploaded file
* @param string $sXMLdata  Alternatively you can specify XML data to import in this variable - $sFullFilepath is then ignored - default NULL
* @param string $sNewSurveyName  Name of the to be imported survey (optional) - default NULL
* @param boolean $bTranslateInsertansTags If INSERTANS tags should be translated - defaults to true
*/
function XMLImportSurvey($sFullFilepath, $sXMLdata = NULL, $sNewSurveyName = NULL, $bTranslateInsertansTags = true)
{
    global $connect, $dbprefix, $clang, $timeadjust;
    if ($sXMLdata == NULL) {
        $xml = simplexml_load_file($sFullFilepath);
    } else {
        $xml = simplexml_load_string($sXMLdata);
    }
    if ($xml->LimeSurveyDocType != 'Survey') {
        safe_die('This is not a valid LimeSurvey survey structure XML file.');
    }
    $dbversion = (int) $xml->DBVersion;
    $aQIDReplacements = array();
    $aQuotaReplacements = array();
    $results['defaultvalues'] = 0;
    $results['answers'] = 0;
    $results['surveys'] = 0;
    $results['questions'] = 0;
    $results['subquestions'] = 0;
    $results['question_attributes'] = 0;
    $results['groups'] = 0;
    $results['assessments'] = 0;
    $results['quota'] = 0;
    $results['quotals'] = 0;
    $results['quotamembers'] = 0;
    $results['importwarnings'] = array();
    $aLanguagesSupported = array();
    foreach ($xml->languages->language as $language) {
        $aLanguagesSupported[] = (string) $language;
    }
    $results['languages'] = count($aLanguagesSupported);
    // First get an overview of fieldnames - it's not useful for the moment but might be with newer versions
    /*
        $fieldnames=array();
        foreach ($xml->questions->fields->fieldname as $fieldname )
        {
            $fieldnames[]=(string)$fieldname;
        };*/
    // Import surveys table ===================================================================================
    $tablename = $dbprefix . 'surveys';
    foreach ($xml->surveys->rows->row as $row) {
        $insertdata = array();
        foreach ($row as $key => $value) {
            $insertdata[(string) $key] = (string) $value;
        }
        $oldsid = $insertdata['sid'];
        $newsid = GetNewSurveyID($oldsid);
        //Now insert the new SID and change some values
        $insertdata['sid'] = $newsid;
        //Make sure it is not set active
        $insertdata['active'] = 'N';
        //Set current user to be the owner
        $insertdata['owner_id'] = $_SESSION['loginID'];
        //Change creation date to import date
        $insertdata['datecreated'] = $connect->BindTimeStamp(date_shift(date("Y-m-d H:i:s"), "Y-m-d", $timeadjust));
        db_switchIDInsert('surveys', true);
        $query = $connect->GetInsertSQL($tablename, $insertdata);
        $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />{$query}<br />\n" . $connect->ErrorMsg());
        $results['surveys']++;
        db_switchIDInsert('surveys', false);
    }
    $results['newsid'] = $newsid;
    // Import survey languagesettings table ===================================================================================
    $tablename = $dbprefix . 'surveys_languagesettings';
    foreach ($xml->surveys_languagesettings->rows->row as $row) {
        $insertdata = array();
        foreach ($row as $key => $value) {
            $insertdata[(string) $key] = (string) $value;
        }
        $insertdata['surveyls_survey_id'] = $newsid;
        if ($sNewSurveyName == NULL) {
            $insertdata['surveyls_title'] = translink('survey', $oldsid, $newsid, $insertdata['surveyls_title']);
        } else {
            $insertdata['surveyls_title'] = translink('survey', $oldsid, $newsid, $sNewSurveyName);
        }
        $insertdata['surveyls_description'] = translink('survey', $oldsid, $newsid, $insertdata['surveyls_description']);
        $insertdata['surveyls_welcometext'] = translink('survey', $oldsid, $newsid, $insertdata['surveyls_welcometext']);
        $insertdata['surveyls_urldescription'] = translink('survey', $oldsid, $newsid, $insertdata['surveyls_urldescription']);
        $insertdata['surveyls_email_invite'] = translink('survey', $oldsid, $newsid, $insertdata['surveyls_email_invite']);
        $insertdata['surveyls_email_remind'] = translink('survey', $oldsid, $newsid, $insertdata['surveyls_email_remind']);
        $insertdata['surveyls_email_register'] = translink('survey', $oldsid, $newsid, $insertdata['surveyls_email_register']);
        $insertdata['surveyls_email_confirm'] = translink('survey', $oldsid, $newsid, $insertdata['surveyls_email_confirm']);
        $query = $connect->GetInsertSQL($tablename, $insertdata);
        $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />{$query}<br />\n" . $connect->ErrorMsg());
    }
    // Import groups table ===================================================================================
    $tablename = $dbprefix . 'groups';
    foreach ($xml->groups->rows->row as $row) {
        $insertdata = array();
        foreach ($row as $key => $value) {
            $insertdata[(string) $key] = (string) $value;
        }
        $oldsid = $insertdata['sid'];
        $insertdata['sid'] = $newsid;
        $oldgid = $insertdata['gid'];
        unset($insertdata['gid']);
        // save the old qid
        // now translate any links
        $insertdata['group_name'] = translink('survey', $oldsid, $newsid, $insertdata['group_name']);
        $insertdata['description'] = translink('survey', $oldsid, $newsid, $insertdata['description']);
        // Insert the new group
        if (isset($aGIDReplacements[$oldgid])) {
            db_switchIDInsert('groups', true);
            $insertdata['gid'] = $aGIDReplacements[$oldgid];
        }
        $query = $connect->GetInsertSQL($tablename, $insertdata);
        $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />{$query}<br />\n" . $connect->ErrorMsg());
        $results['groups']++;
        if (!isset($aGIDReplacements[$oldgid])) {
            $newgid = $connect->Insert_ID($tablename, "gid");
            // save this for later
            $aGIDReplacements[$oldgid] = $newgid;
            // add old and new qid to the mapping array
        } else {
            db_switchIDInsert('groups', false);
        }
    }
    // Import questions table ===================================================================================
    // We have to run the question table data two times - first to find all main questions
    // then for subquestions (because we need to determine the new qids for the main questions first)
    if (isset($xml->questions)) {
        $tablename = $dbprefix . 'questions';
        foreach ($xml->questions->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $oldsid = $insertdata['sid'];
            $insertdata['sid'] = $newsid;
            if (!isset($aGIDReplacements[$insertdata['gid']]) || trim($insertdata['title']) == '') {
                continue;
            }
            // Skip questions with invalid group id
            $insertdata['gid'] = $aGIDReplacements[$insertdata['gid']];
            $oldqid = $insertdata['qid'];
            unset($insertdata['qid']);
            // save the old qid
            // now translate any links
            $insertdata['title'] = translink('survey', $oldsid, $newsid, $insertdata['title']);
            $insertdata['question'] = translink('survey', $oldsid, $newsid, $insertdata['question']);
            $insertdata['help'] = translink('survey', $oldsid, $newsid, $insertdata['help']);
            // Insert the new question
            if (isset($aQIDReplacements[$oldqid])) {
                $insertdata['qid'] = $aQIDReplacements[$oldqid];
                db_switchIDInsert('questions', true);
            }
            $query = $connect->GetInsertSQL($tablename, $insertdata);
            $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />{$query}<br />\n" . $connect->ErrorMsg());
            if (!isset($aQIDReplacements[$oldqid])) {
                $newqid = $connect->Insert_ID($tablename, "qid");
                // save this for later
                $aQIDReplacements[$oldqid] = $newqid;
                // add old and new qid to the mapping array
                $results['questions']++;
            } else {
                db_switchIDInsert('questions', false);
            }
        }
    }
    // Import subquestions --------------------------------------------------------------
    if (isset($xml->subquestions)) {
        $tablename = $dbprefix . 'questions';
        foreach ($xml->subquestions->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['sid'] = $newsid;
            if (!isset($aGIDReplacements[$insertdata['gid']])) {
                continue;
            }
            // Skip questions with invalid group id
            $insertdata['gid'] = $aGIDReplacements[(int) $insertdata['gid']];
            $oldsqid = (int) $insertdata['qid'];
            unset($insertdata['qid']);
            // save the old qid
            $insertdata['parent_qid'] = $aQIDReplacements[(int) $insertdata['parent_qid']];
            // remap the parent_qid
            // now translate any links
            $insertdata['title'] = translink('survey', $oldsid, $newsid, $insertdata['title']);
            $insertdata['question'] = translink('survey', $oldsid, $newsid, $insertdata['question']);
            $insertdata['help'] = translink('survey', $oldsid, $newsid, $insertdata['help']);
            if (isset($aQIDReplacements[$oldsqid])) {
                $insertdata['qid'] = $aQIDReplacements[$oldsqid];
                db_switchIDInsert('questions', true);
            }
            $query = $connect->GetInsertSQL($tablename, $insertdata);
            $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />{$query}<br />\n" . $connect->ErrorMsg());
            $newsqid = $connect->Insert_ID($tablename, "qid");
            // save this for later
            if (!isset($insertdata['qid'])) {
                $aQIDReplacements[$oldsqid] = $newsqid;
                // add old and new qid to the mapping array
            } else {
                db_switchIDInsert('questions', false);
            }
            $results['subquestions']++;
        }
    }
    // Import answers --------------------------------------------------------------
    if (isset($xml->answers)) {
        $tablename = $dbprefix . 'answers';
        foreach ($xml->answers->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            if (!isset($aQIDReplacements[(int) $insertdata['qid']])) {
                continue;
            }
            // Skip questions with invalid group id
            $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']];
            // remap the parent_qid
            // now translate any links
            $query = $connect->GetInsertSQL($tablename, $insertdata);
            $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />{$query}<br />\n" . $connect->ErrorMsg());
            $results['answers']++;
        }
    }
    // Import questionattributes --------------------------------------------------------------
    if (isset($xml->question_attributes)) {
        $tablename = $dbprefix . 'question_attributes';
        foreach ($xml->question_attributes->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            unset($insertdata['qaid']);
            if (!isset($aQIDReplacements[(int) $insertdata['qid']])) {
                continue;
            }
            // Skip questions with invalid group id
            $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']];
            // remap the parent_qid
            // now translate any links
            $query = $connect->GetInsertSQL($tablename, $insertdata);
            $result = $connect->Execute($query);
            $results['question_attributes']++;
        }
    }
    // Import defaultvalues --------------------------------------------------------------
    if (isset($xml->defaultvalues)) {
        $tablename = $dbprefix . 'defaultvalues';
        $results['defaultvalues'] = 0;
        foreach ($xml->defaultvalues->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']];
            // remap the qid
            if (isset($aQIDReplacements[(int) $insertdata['sqid']])) {
                $insertdata['sqid'] = $aQIDReplacements[(int) $insertdata['sqid']];
            }
            // remap the subquestion id
            // now translate any links
            $query = $connect->GetInsertSQL($tablename, $insertdata);
            $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />\$query<br />\n" . $connect->ErrorMsg());
            $results['defaultvalues']++;
        }
    }
    // At this point we know the new/old SID, GIDs, QIDs and we are able to build
    // the aray mapping old and new fieldnames
    // this will be usefull in order to translate conditions cfieldname and @SGQA@ codes, as well as INSERTANS links.
    $aOldNewFieldmap = aReverseTranslateFieldnames($oldsid, $newsid, $aGIDReplacements, $aQIDReplacements);
    // Import conditions --------------------------------------------------------------
    if (isset($xml->conditions)) {
        $tablename = $dbprefix . 'conditions';
        $results['conditions'] = 0;
        foreach ($xml->conditions->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            // replace the qid for the new one (if there is no new qid in the $aQIDReplacements array it mean that this condition is orphan -> error, skip this record)
            if (isset($aQIDReplacements[$insertdata['qid']])) {
                $insertdata['qid'] = $aQIDReplacements[$insertdata['qid']];
                // remap the qid
            } else {
                continue;
            }
            // a problem with this answer record -> don't consider
            if (isset($aQIDReplacements[$insertdata['cqid']])) {
                $oldcqid = $insertdata['cqid'];
                $insertdata['cqid'] = $aQIDReplacements[$insertdata['cqid']];
                // remap the qid
            } else {
                continue;
            }
            // a problem with this answer record -> don't consider
            // replace the old cfieldname by the new one
            // first get the cfieldname without optionnal leading Meta-character
            //  (see Multiple-options (single checkbox)
            preg_match("/^(\\+{0,1})(.*)\$/", $insertdata["cfieldname"], $insertedCfieldname);
            if (isset($aOldNewFieldmap[$insertedCfieldname[2]])) {
                if ($insertedCfieldname[1] == "+") {
                    // this is a single-checkbox cfieldname in the form +SGQA
                    $newcfieldname = '+' . $aOldNewFieldmap[$insertedCfieldname[2]];
                } else {
                    // this is a normal cfieldname in the form SGQ or SGQA
                    // in the case of Multiple-options, this can be a virtual global
                    // cfieldname grouping all checkboxes (in the form SGQ)
                    $newcfieldname = $aOldNewFieldmap[$insertdata["cfieldname"]];
                }
                $insertdata["cfieldname"] = $newcfieldname;
            } else {
                //error_log("TIBO: oldcfieldname={$insertdata["cfieldname"]}//{$insertedCfieldname[2]} can't be found in aOldNewFieldmap");
                continue;
                // a problem with cfieldname mapping -> don't consider
            }
            if (preg_match("/^@(.*)@\$/", $insertdata["value"], $cfieldnameInCondValue)) {
                if (isset($aOldNewFieldmap[$cfieldnameInCondValue[1]])) {
                    $newvalue = '@' . $aOldNewFieldmap[$cfieldnameInCondValue[1]] . '@';
                    $insertdata["value"] = $newvalue;
                } else {
                    //error_log("TIBO2: oldvalue=@..{$cfieldnameInCondValue[1]}..@ can't be found in aOldNewFieldmap");
                    continue;
                    // a problem with cfieldname mapping -> don't consider
                }
            }
            if (trim($insertdata["method"]) == '') {
                $insertdata["method"] = '==';
            }
            unset($insertdata["cid"]);
            $query = $connect->GetInsertSQL($tablename, $insertdata);
            $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />\$query<br />\n" . $connect->ErrorMsg());
            $results['conditions']++;
        }
    }
    // Import assessments --------------------------------------------------------------
    if (isset($xml->assessments)) {
        $tablename = $dbprefix . 'assessments';
        foreach ($xml->assessments->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            if ($insertdata['gid'] > 0) {
                $insertdata['gid'] = $aGIDReplacements[(int) $insertdata['gid']];
                // remap the qid
            }
            $insertdata['sid'] = $newsid;
            // remap the survey id
            // now translate any links
            $query = $connect->GetInsertSQL($tablename, $insertdata);
            $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />\$query<br />\n" . $connect->ErrorMsg());
            $results['assessments']++;
        }
    }
    // Import quota --------------------------------------------------------------
    if (isset($xml->quota)) {
        $tablename = $dbprefix . 'quota';
        foreach ($xml->quota->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['sid'] = $newsid;
            // remap the survey id
            $oldid = $insertdata['id'];
            unset($insertdata['id']);
            // now translate any links
            $query = $connect->GetInsertSQL($tablename, $insertdata);
            $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />\$query<br />\n" . $connect->ErrorMsg());
            $aQuotaReplacements[$oldid] = $connect->Insert_ID(db_table_name_nq('quota'), "id");
            $results['quota']++;
        }
    }
    // Import quota_members --------------------------------------------------------------
    if (isset($xml->quota_members)) {
        $tablename = $dbprefix . 'quota_members';
        foreach ($xml->quota_members->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['sid'] = $newsid;
            // remap the survey id
            $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']];
            // remap the qid
            $insertdata['quota_id'] = $aQuotaReplacements[(int) $insertdata['quota_id']];
            // remap the qid
            unset($insertdata['id']);
            // now translate any links
            $query = $connect->GetInsertSQL($tablename, $insertdata);
            $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />\$query<br />\n" . $connect->ErrorMsg());
            $results['quotamembers']++;
        }
    }
    // Import quota_languagesettings --------------------------------------------------------------
    if (isset($xml->quota_languagesettings)) {
        $tablename = $dbprefix . 'quota_languagesettings';
        foreach ($xml->quota_languagesettings->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['quotals_quota_id'] = $aQuotaReplacements[(int) $insertdata['quotals_quota_id']];
            // remap the qid
            unset($insertdata['quotals_id']);
            // now translate any links
            $query = $connect->GetInsertSQL($tablename, $insertdata);
            $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />\$query<br />\n" . $connect->ErrorMsg());
            $results['quotals']++;
        }
    }
    // Set survey rights
    $sQuery = "INSERT INTO {$dbprefix}surveys_rights (sid, uid, edit_survey_property, define_questions, browse_response, export, delete_survey, activate_survey) VALUES({$newsid}," . $_SESSION['loginID'] . ",1,1,1,1,1,1)";
    $connect->Execute($sQuery);
    if ($bTranslateInsertansTags) {
        if (isset($aOldNewFieldmap)) {
            // It should be set anyway !
            TranslateInsertansTags($newsid, $oldsid, $aOldNewFieldmap);
        }
    }
    return $results;
}
Example #6
0
 /**
  * function to import surveys, based on new importsurvey.php 6979 2009-05-30 11:59:03Z c_schmitz $
  *
  * @param unknown_type $iVid
  * @param unknown_type $sVtit
  * @param unknown_type $sVbes
  * @return boolean
  */
 function importSurvey($iVid, $sVtit, $sVbes, $sVwel, $sUbes, $sVtyp)
 {
     global $connect;
     global $dbprefix;
     global $clang;
     include "lsrc.config.php";
     $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
     $this->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ", OK ");
     // HINT FOR IMPORTERS: go to Line 714 to manipulate the Survey, while it's imported
     $the_full_file_path = $coreDir . $sVtyp . ".csv";
     $this->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ",the_full_file_path ='{$the_full_file_path}' OK ");
     //$_SERVER['SERVER_NAME'] = "";				// just to avoid notices
     //$_SERVER['SERVER_SOFTWARE'] = "";		// just to avoid notices
     //require_once(dirname(__FILE__).'/../config-defaults.php');
     //require_once(dirname(__FILE__).'/../common.php');
     $handle = fopen($the_full_file_path, "r");
     while (!feof($handle)) {
         //To allow for very long survey lines (up to 64k)
         $buffer = fgets($handle, 56550);
         $bigarray[] = $buffer;
     }
     fclose($handle);
     //		foreach($bigarray as $ba)
     //			$this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", OK ".$ba);
     if (isset($bigarray[0])) {
         $bigarray[0] = $this->removeBOM($bigarray[0]);
     }
     // Now we try to determine the dataformat of the survey file.
     if (isset($bigarray[1]) && isset($bigarray[4]) && substr($bigarray[1], 0, 22) == "# SURVEYOR SURVEY DUMP" && substr($bigarray[4], 0, 29) == "# http://www.phpsurveyor.org/") {
         $importversion = 100;
         // version 1.0 file
     } elseif (isset($bigarray[1]) && isset($bigarray[4]) && substr($bigarray[1], 0, 22) == "# SURVEYOR SURVEY DUMP" && substr($bigarray[4], 0, 37) == "# http://phpsurveyor.sourceforge.net/") {
         $importversion = 99;
         // Version 0.99 file or older - carries a different URL
     } elseif (substr($bigarray[0], 0, 24) == "# LimeSurvey Survey Dump" || substr($bigarray[0], 0, 25) == "# PHPSurveyor Survey Dump") {
         // Wow.. this seems to be a >1.0 version file - these files carry the version information to read in line two
         $importversion = substr($bigarray[1], 12, 3);
     } else {
         if ($importingfrom == "http") {
             //			    $importsurvey .= "<strong><font color='red'>".("Error")."</font></strong>\n";
             //			  	$importsurvey .= ("This file is not a LimeSurvey survey file. Import failed.")."\n";
             //			  	$importsurvey .= "</font></td></tr></table>\n";
             //			  	$importsurvey .= "</body>\n</html>\n";
             //unlink($the_full_file_path);
             return false;
         } else {
             //echo ("This file is not a LimeSurvey survey file. Import failed.")."\n";
             return false;
         }
     }
     // okay.. now lets drop the first 9 lines and get to the data
     // This works for all versions
     for ($i = 0; $i < 9; $i++) {
         unset($bigarray[$i]);
     }
     $bigarray = array_values($bigarray);
     //$this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", OK ".print_r($bigarray));
     //SURVEYS
     if (array_search("# GROUPS TABLE\n", $bigarray)) {
         $stoppoint = array_search("# GROUPS TABLE\n", $bigarray);
     } elseif (array_search("# GROUPS TABLE\r\n", $bigarray)) {
         $stoppoint = array_search("# GROUPS TABLE\r\n", $bigarray);
     }
     for ($i = 0; $i <= $stoppoint + 1; $i++) {
         if ($i < $stoppoint - 2) {
             $surveyarray[] = $bigarray[$i];
         }
         unset($bigarray[$i]);
     }
     $bigarray = array_values($bigarray);
     //GROUPS
     if (array_search("# QUESTIONS TABLE\n", $bigarray)) {
         $stoppoint = array_search("# QUESTIONS TABLE\n", $bigarray);
     } elseif (array_search("# QUESTIONS TABLE\r\n", $bigarray)) {
         $stoppoint = array_search("# QUESTIONS TABLE\r\n", $bigarray);
     } else {
         $stoppoint = count($bigarray) - 1;
     }
     for ($i = 0; $i <= $stoppoint + 1; $i++) {
         if ($i < $stoppoint - 2) {
             $grouparray[] = $bigarray[$i];
         }
         unset($bigarray[$i]);
     }
     $bigarray = array_values($bigarray);
     //QUESTIONS
     if (array_search("# ANSWERS TABLE\n", $bigarray)) {
         $stoppoint = array_search("# ANSWERS TABLE\n", $bigarray);
     } elseif (array_search("# ANSWERS TABLE\r\n", $bigarray)) {
         $stoppoint = array_search("# ANSWERS TABLE\r\n", $bigarray);
     } else {
         $stoppoint = count($bigarray) - 1;
     }
     for ($i = 0; $i <= $stoppoint + 1; $i++) {
         if ($i < $stoppoint - 2) {
             $questionarray[] = $bigarray[$i];
         }
         unset($bigarray[$i]);
     }
     $bigarray = array_values($bigarray);
     //ANSWERS
     if (array_search("# CONDITIONS TABLE\n", $bigarray)) {
         $stoppoint = array_search("# CONDITIONS TABLE\n", $bigarray);
     } elseif (array_search("# CONDITIONS TABLE\r\n", $bigarray)) {
         $stoppoint = array_search("# CONDITIONS TABLE\r\n", $bigarray);
     } else {
         $stoppoint = count($bigarray) - 1;
     }
     for ($i = 0; $i <= $stoppoint + 1; $i++) {
         if ($i < $stoppoint - 2) {
             $answerarray[] = str_replace("`default`", "`default_value`", $bigarray[$i]);
         }
         unset($bigarray[$i]);
     }
     $bigarray = array_values($bigarray);
     //CONDITIONS
     if (array_search("# LABELSETS TABLE\n", $bigarray)) {
         $stoppoint = array_search("# LABELSETS TABLE\n", $bigarray);
     } elseif (array_search("# LABELSETS TABLE\r\n", $bigarray)) {
         $stoppoint = array_search("# LABELSETS TABLE\r\n", $bigarray);
     } else {
         //There is no labelsets information, so presumably this is a pre-0.98rc3 survey.
         $stoppoint = count($bigarray);
     }
     for ($i = 0; $i <= $stoppoint + 1; $i++) {
         if ($i < $stoppoint - 2) {
             $conditionsarray[] = $bigarray[$i];
         }
         unset($bigarray[$i]);
     }
     $bigarray = array_values($bigarray);
     //LABELSETS
     if (array_search("# LABELS TABLE\n", $bigarray)) {
         $stoppoint = array_search("# LABELS TABLE\n", $bigarray);
     } elseif (array_search("# LABELS TABLE\r\n", $bigarray)) {
         $stoppoint = array_search("# LABELS TABLE\r\n", $bigarray);
     } else {
         $stoppoint = count($bigarray) - 1;
     }
     for ($i = 0; $i <= $stoppoint + 1; $i++) {
         if ($i < $stoppoint - 2) {
             $labelsetsarray[] = $bigarray[$i];
         }
         unset($bigarray[$i]);
     }
     $bigarray = array_values($bigarray);
     //LABELS
     if (array_search("# QUESTION_ATTRIBUTES TABLE\n", $bigarray)) {
         $stoppoint = array_search("# QUESTION_ATTRIBUTES TABLE\n", $bigarray);
     } elseif (array_search("# QUESTION_ATTRIBUTES TABLE\r\n", $bigarray)) {
         $stoppoint = array_search("# QUESTION_ATTRIBUTES TABLE\r\n", $bigarray);
     } else {
         $stoppoint = count($bigarray) - 1;
     }
     for ($i = 0; $i <= $stoppoint + 1; $i++) {
         if ($i < $stoppoint - 2) {
             $labelsarray[] = $bigarray[$i];
         }
         unset($bigarray[$i]);
     }
     $bigarray = array_values($bigarray);
     //QUESTION_ATTRIBUTES
     if (array_search("# ASSESSMENTS TABLE\n", $bigarray)) {
         $stoppoint = array_search("# ASSESSMENTS TABLE\n", $bigarray);
     } elseif (array_search("# ASSESSMENTS TABLE\r\n", $bigarray)) {
         $stoppoint = array_search("# ASSESSMENTS TABLE\r\n", $bigarray);
     } else {
         $stoppoint = count($bigarray) - 1;
     }
     for ($i = 0; $i <= $stoppoint + 1; $i++) {
         if ($i < $stoppoint - 2) {
             $question_attributesarray[] = $bigarray[$i];
         }
         unset($bigarray[$i]);
     }
     $bigarray = array_values($bigarray);
     //ASSESSMENTS
     if (array_search("# SURVEYS_LANGUAGESETTINGS TABLE\n", $bigarray)) {
         $stoppoint = array_search("# SURVEYS_LANGUAGESETTINGS TABLE\n", $bigarray);
     } elseif (array_search("# SURVEYS_LANGUAGESETTINGS TABLE\r\n", $bigarray)) {
         $stoppoint = array_search("# SURVEYS_LANGUAGESETTINGS TABLE\r\n", $bigarray);
     } else {
         $stoppoint = count($bigarray) - 1;
     }
     for ($i = 0; $i <= $stoppoint + 1; $i++) {
         //	if ($i<$stoppoint-2 || $i==count($bigarray)-1)
         if ($i < $stoppoint - 2) {
             $assessmentsarray[] = $bigarray[$i];
         }
         unset($bigarray[$i]);
     }
     $bigarray = array_values($bigarray);
     //LANGAUGE SETTINGS
     if (array_search("# QUOTA TABLE\n", $bigarray)) {
         $stoppoint = array_search("# QUOTA TABLE\n", $bigarray);
     } elseif (array_search("# QUOTA TABLE\r\n", $bigarray)) {
         $stoppoint = array_search("# QUOTA TABLE\r\n", $bigarray);
     } else {
         $stoppoint = count($bigarray) - 1;
     }
     for ($i = 0; $i <= $stoppoint + 1; $i++) {
         //	if ($i<$stoppoint-2 || $i==count($bigarray)-1)
         //$bigarray[$i]=        trim($bigarray[$i]);
         if (isset($bigarray[$i]) && trim($bigarray[$i]) != '') {
             if (strpos($bigarray[$i], "#") === 0) {
                 unset($bigarray[$i]);
                 unset($bigarray[$i + 1]);
                 unset($bigarray[$i + 2]);
                 break;
             } else {
                 $surveylsarray[] = $bigarray[$i];
             }
         }
         unset($bigarray[$i]);
     }
     $bigarray = array_values($bigarray);
     //QUOTA
     if (array_search("# QUOTA_MEMBERS TABLE\n", $bigarray)) {
         $stoppoint = array_search("# QUOTA_MEMBERS TABLE\n", $bigarray);
     } elseif (array_search("# QUOTA_MEMBERS TABLE\r\n", $bigarray)) {
         $stoppoint = array_search("# QUOTA_MEMBERS TABLE\r\n", $bigarray);
     } else {
         $stoppoint = count($bigarray) - 1;
     }
     for ($i = 0; $i <= $stoppoint + 1; $i++) {
         //	if ($i<$stoppoint-2 || $i==count($bigarray)-1)
         if ($i < $stoppoint - 2) {
             $quotaarray[] = $bigarray[$i];
         }
         unset($bigarray[$i]);
     }
     $bigarray = array_values($bigarray);
     //Survey Language Settings
     $stoppoint = count($bigarray) - 1;
     for ($i = 0; $i < $stoppoint - 1; $i++) {
         if ($i <= $stoppoint) {
             $quotamembersarray[] = $bigarray[$i];
         }
         unset($bigarray[$i]);
     }
     $bigarray = array_values($bigarray);
     if (isset($surveyarray)) {
         $countsurveys = count($surveyarray);
     } else {
         $countsurveys = 0;
     }
     if (isset($surveylsarray)) {
         $countlanguages = count($surveylsarray) - 1;
     } else {
         $countlanguages = 1;
     }
     if (isset($grouparray)) {
         $countgroups = count($grouparray);
     } else {
         $countgroups = 0;
     }
     if (isset($questionarray)) {
         $countquestions = count($questionarray);
     } else {
         $countquestions = 0;
     }
     if (isset($answerarray)) {
         $countanswers = count($answerarray);
     } else {
         $countanswers = 0;
     }
     if (isset($conditionsarray)) {
         $countconditions = count($conditionsarray);
     } else {
         $countconditions = 0;
     }
     if (isset($labelsetsarray)) {
         $countlabelsets = count($labelsetsarray);
     } else {
         $countlabelsets = 0;
     }
     if (isset($question_attributesarray)) {
         $countquestion_attributes = count($question_attributesarray);
     } else {
         $countquestion_attributes = 0;
     }
     if (isset($assessmentsarray)) {
         $countassessments = count($assessmentsarray);
     } else {
         $countassessments = 0;
     }
     if (isset($quotaarray)) {
         $countquota = count($quotaarray);
     } else {
         $countquota = 0;
     }
     // CREATE SURVEY
     if ($countsurveys > 0) {
         $countsurveys--;
     }
     if ($countanswers > 0) {
         $countanswers = ($countanswers - 1) / $countlanguages;
     }
     if ($countgroups > 0) {
         $countgroups = ($countgroups - 1) / $countlanguages;
     }
     if ($countquestions > 0) {
         $countquestions = ($countquestions - 1) / $countlanguages;
     }
     if ($countassessments > 0) {
         $countassessments--;
     }
     if ($countconditions > 0) {
         $countconditions--;
     }
     if ($countlabelsets > 0) {
         $countlabelsets--;
     }
     if ($countquestion_attributes > 0) {
         $countquestion_attributes--;
     }
     if ($countquota > 0) {
         $countquota--;
     }
     $sfieldorders = convertCSVRowToArray($surveyarray[0], ',', '"');
     $sfieldcontents = convertCSVRowToArray($surveyarray[1], ',', '"');
     $surveyrowdata = array_combine($sfieldorders, $sfieldcontents);
     $surveyid = $surveyrowdata["sid"];
     if (!$surveyid) {
         if ($importingfrom == "http") {
             //				$importsurvey .= "<strong><font color='red'>".("Error")."</strong></font>\n";
             //				$importsurvey .= ("Import of this survey file failed")."\n";
             //				$importsurvey .= ("File does not contain LimeSurvey data in the correct format.")."\n"; //Couldn't find the SID - cannot continue
             //				$importsurvey .= "</font></td></tr></table>\n";
             //				$importsurvey .= "</body>\n</html>\n";
             //				unlink($the_full_file_path); //Delete the uploaded file
             return false;
         } else {
             //echo ("Import of this survey file failed")."\n".("File does not contain LimeSurvey data in the correct format.")."\n";
             return false;
         }
     }
     // Use the existing surveyid if it does not already exists
     // This allows the URL links to the survey to keep working because the sid did not change
     $newsid = $iVid;
     //XXX Changed from $surveyid --> $iVid
     $isquery = "SELECT sid FROM {$dbprefix}surveys WHERE sid={$newsid}";
     $isresult = db_execute_assoc($isquery);
     if ($isresult->RecordCount() > 0) {
         // Get new random ids until one is found that is not used
         do {
             $newsid = getRandomID();
             $isquery = "SELECT sid FROM {$dbprefix}surveys WHERE sid={$newsid}";
             $isresult = db_execute_assoc($isquery);
         } while ($isresult->RecordCount() > 0);
     }
     $insert = $surveyarray[0];
     $sfieldorders = convertCSVRowToArray($surveyarray[0], ',', '"');
     $sfieldcontents = convertCSVRowToArray($surveyarray[1], ',', '"');
     $surveyrowdata = array_combine($sfieldorders, $sfieldcontents);
     // Set new owner ID
     $surveyrowdata['owner_id'] = $_SESSION['loginID'];
     // Set new survey ID
     $surveyrowdata['sid'] = $newsid;
     $surveyrowdata['active'] = 'N';
     if ($importversion <= 100) {
         $oldlanguage = $surveyrowdata['language'];
         $newlanguage = 'en';
         //Default
         switch ($oldlanguage) {
             case "bulgarian":
                 $newlanguage = 'bg';
                 break;
             case "chinese-simplified":
                 $newlanguage = 'zh-Hans';
                 break;
             case "chinese-traditional":
                 $newlanguage = 'zh-Hant-HK';
                 break;
             case "croatian":
                 $newlanguage = 'hr';
                 break;
             case "danish":
                 $newlanguage = 'da';
                 break;
             case "dutch":
                 $newlanguage = 'nl';
                 break;
             case "english":
                 $newlanguage = 'en';
                 break;
             case "french":
                 $newlanguage = 'fr';
                 break;
             case "german-informal":
                 $newlanguage = 'de-informal';
                 break;
             case "german":
                 $newlanguage = 'de';
                 break;
             case "greek":
                 $newlanguage = 'el';
                 break;
             case "hungarian":
                 $newlanguage = 'hu';
                 break;
             case "italian":
                 $newlanguage = 'it';
                 break;
             case "japanese":
                 $newlanguage = 'ja';
                 break;
             case "lithuanian":
                 $newlanguage = 'lt';
                 break;
             case "norwegian":
                 $newlanguage = 'nb';
                 break;
             case "portuguese":
                 $newlanguage = 'pt';
                 break;
             case "romanian":
                 $newlanguage = 'ro';
                 break;
             case "russian":
                 $newlanguage = 'ru';
                 break;
             case "slovenian":
                 $newlanguage = 'sl';
                 break;
             case "spanish":
                 $newlanguage = 'es';
                 break;
             case "swedish":
                 $newlanguage = 'sv';
                 break;
         }
         $surveyrowdata['language'] = $newlanguage;
         // copy the survey row data
         // now prepare the languagesettings table and drop according values from the survey array
         $surveylsrowdata = array();
         $surveylsrowdata['surveyls_survey_id'] = $newsid;
         $surveylsrowdata['surveyls_language'] = $newlanguage;
         $surveylsrowdata['surveyls_title'] = $surveyrowdata['short_title'];
         $surveylsrowdata['surveyls_description'] = $surveyrowdata['description'];
         $surveylsrowdata['surveyls_welcometext'] = $surveyrowdata['welcome'];
         $surveylsrowdata['surveyls_urldescription'] = $surveyrowdata['urldescrip'];
         $surveylsrowdata['surveyls_email_invite_subj'] = $surveyrowdata['email_invite_subj'];
         $surveylsrowdata['surveyls_email_invite'] = $surveyrowdata['email_invite'];
         $surveylsrowdata['surveyls_email_remind_subj'] = $surveyrowdata['email_remind_subj'];
         $surveylsrowdata['surveyls_email_remind'] = $surveyrowdata['email_remind'];
         $surveylsrowdata['surveyls_email_register_subj'] = $surveyrowdata['email_register_subj'];
         $surveylsrowdata['surveyls_email_register'] = $surveyrowdata['email_register'];
         $surveylsrowdata['surveyls_email_confirm_subj'] = $surveyrowdata['email_confirm_subj'];
         $surveylsrowdata['surveyls_email_confirm'] = $surveyrowdata['email_confirm'];
         unset($surveyrowdata['short_title']);
         unset($surveyrowdata['description']);
         unset($surveyrowdata['welcome']);
         unset($surveyrowdata['urldescrip']);
         unset($surveyrowdata['email_invite_subj']);
         unset($surveyrowdata['email_invite']);
         unset($surveyrowdata['email_remind_subj']);
         unset($surveyrowdata['email_remind']);
         unset($surveyrowdata['email_register_subj']);
         unset($surveyrowdata['email_register']);
         unset($surveyrowdata['email_confirm_subj']);
         unset($surveyrowdata['email_confirm']);
         // translate internal links
         $surveylsrowdata['surveyls_title'] = translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_title']);
         $surveylsrowdata['surveyls_description'] = translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_description']);
         $surveylsrowdata['surveyls_welcometext'] = translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_welcometext']);
         $surveylsrowdata['surveyls_urldescription'] = translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_urldescription']);
         $surveylsrowdata['surveyls_email_invite'] = translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_email_invite']);
         $surveylsrowdata['surveyls_email_remind'] = translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_email_remind']);
         $surveylsrowdata['surveyls_email_register'] = translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_email_register']);
         $surveylsrowdata['surveyls_email_confirm'] = translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_email_confirm']);
         // import the survey language-specific settings
         $values = array_values($surveylsrowdata);
         $values = array_map(array(&$connect, "qstr"), $values);
         // quote everything accordingly
         $insert = "insert INTO {$dbprefix}surveys_languagesettings (" . implode(',', array_keys($surveylsrowdata)) . ") VALUES (" . implode(',', $values) . ")";
         //handle db prefix
         try {
             $iresult = $connect->Execute($insert) or $this->debugLsrc("" . "Import of this survey file failed" . "\n[{$insert}]{$surveyarray[0]}\n" . $connect->ErrorMsg());
         } catch (exception $e) {
             throw new SoapFault("Server: ", "{$e} : {$connect->ErrorMsg}()");
             exit;
         }
     }
     if (isset($surveyrowdata['datecreated'])) {
         $surveyrowdata['datecreated'] = $connect->BindTimeStamp($surveyrowdata['datecreated']);
     }
     unset($surveyrowdata['expires']);
     unset($surveyrowdata['attribute1']);
     unset($surveyrowdata['attribute2']);
     unset($surveyrowdata['usestartdate']);
     unset($surveyrowdata['useexpiry']);
     unset($surveyrowdata['url']);
     if (isset($surveyrowdata['startdate'])) {
         unset($surveyrowdata['startdate']);
     }
     $surveyrowdata['bounce_email'] = $surveyrowdata['adminemail'];
     if (!isset($surveyrowdata['datecreated']) || $surveyrowdata['datecreated'] == '' || $surveyrowdata['datecreated'] == 'null') {
         $surveyrowdata['datecreated'] = $connect->BindTimeStamp(date_shift(date("Y-m-d H:i:s"), "Y-m-d", $timeadjust));
     }
     $values = array_values($surveyrowdata);
     $values = array_map(array(&$connect, "qstr"), $values);
     // quote everything accordingly
     $insert = "INSERT INTO {$dbprefix}surveys (" . implode(',', array_keys($surveyrowdata)) . ") VALUES (" . implode(',', $values) . ")";
     //handle db prefix
     try {
         $iresult = $connect->Execute($insert) or $this->debugLsrc("" . "Import of this survey file failed on Line: " . __LINE__ . "\n[{$insert}]{$surveyarray[0]}\n" . $connect->ErrorMsg()) and exit;
     } catch (exception $e) {
         throw new SoapFault("Server: ", "{$e} : {$connect->ErrorMsg}()");
         exit;
     }
     $oldsid = $surveyid;
     // Now import the survey language settings
     if ($importversion >= 111) {
         $fieldorders = convertCSVRowToArray($surveylsarray[0], ',', '"');
         unset($surveylsarray[0]);
         foreach ($surveylsarray as $slsrow) {
             $fieldcontents = convertCSVRowToArray($slsrow, ',', '"');
             $surveylsrowdata = array_combine($fieldorders, $fieldcontents);
             // convert back the '\'.'n' cahr from the CSV file to true return char "\n"
             $surveylsrowdata = array_map('convertCsvreturn2return', $surveylsrowdata);
             // Convert the \n return char from welcometext to
             // XXX Change values while Importing here //done by rakete
             $surveylsrowdata['surveyls_title'] = $sVtit;
             $surveylsrowdata['surveyls_description'] = $sVbes;
             $surveylsrowdata['surveyls_welcometext'] = $sVwel;
             $surveylsrowdata['surveyls_urldescription'] = $sUbes;
             // translate internal links
             $surveylsrowdata['surveyls_title'] = translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_title']);
             $surveylsrowdata['surveyls_description'] = translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_description']);
             $surveylsrowdata['surveyls_welcometext'] = translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_welcometext']);
             $surveylsrowdata['surveyls_urldescription'] = translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_urldescription']);
             $surveylsrowdata['surveyls_email_invite'] = translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_email_invite']);
             $surveylsrowdata['surveyls_email_remind'] = translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_email_remind']);
             $surveylsrowdata['surveyls_email_register'] = translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_email_register']);
             $surveylsrowdata['surveyls_email_confirm'] = translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_email_confirm']);
             $surveylsrowdata['surveyls_survey_id'] = $newsid;
             $newvalues = array_values($surveylsrowdata);
             $newvalues = array_map(array(&$connect, "qstr"), $newvalues);
             // quote everything accordingly
             $lsainsert = "INSERT INTO {$dbprefix}surveys_languagesettings (" . implode(',', array_keys($surveylsrowdata)) . ") VALUES (" . implode(',', $newvalues) . ")";
             //handle db prefix
             $lsiresult = $connect->Execute($lsainsert) or $this->debugLsrc("Import of this survey file failed on Line " . __LINE__ . "") and exit;
         }
     }
     // DO SURVEY_RIGHTS
     $isrquery = "INSERT INTO {$dbprefix}surveys_rights VALUES({$newsid}," . $_SESSION['loginID'] . ",1,1,1,1,1,1)";
     @($isrresult = $connect->Execute($isrquery));
     $deniedcountlabelsets = 0;
     //DO ANY LABELSETS FIRST, SO WE CAN KNOW WHAT THEIR NEW LID IS FOR THE QUESTIONS
     if (isset($labelsetsarray) && $labelsetsarray) {
         $csarray = buildLabelSetCheckSumArray();
         // build checksums over all existing labelsets
         $count = 0;
         foreach ($labelsetsarray as $lsa) {
             $fieldorders = convertCSVRowToArray($labelsetsarray[0], ',', '"');
             $fieldcontents = convertCSVRowToArray($lsa, ',', '"');
             if ($count == 0) {
                 $count++;
                 continue;
             }
             $labelsetrowdata = array_combine($fieldorders, $fieldcontents);
             // Save old labelid
             $oldlid = $labelsetrowdata['lid'];
             // set the new language
             if ($importversion <= 100) {
                 $labelsetrowdata['languages'] = $newlanguage;
             }
             unset($labelsetrowdata['lid']);
             $newvalues = array_values($labelsetrowdata);
             $newvalues = array_map(array(&$connect, "qstr"), $newvalues);
             // quote everything accordingly
             $lsainsert = "insert INTO {$dbprefix}labelsets (" . implode(',', array_keys($labelsetrowdata)) . ") VALUES (" . implode(',', $newvalues) . ")";
             //handle db prefix
             $lsiresult = $connect->Execute($lsainsert);
             // Get the new insert id for the labels inside this labelset
             $newlid = $connect->Insert_ID("{$dbprefix}labelsets", "lid");
             //		$importsurvey .= "OLDLID: $oldlid   NEWLID: $newlid";
             //      For debugging label import
             if ($labelsarray) {
                 $count = 0;
                 foreach ($labelsarray as $la) {
                     if ($importversion >= 111) {
                         $lfieldorders = convertCSVRowToArray($labelsarray[0], ',', '"');
                     }
                     $lfieldcontents = convertCSVRowToArray($la, ',', '"');
                     if ($count == 0) {
                         $count++;
                         continue;
                     }
                     // Combine into one array with keys and values since its easier to handle
                     $labelrowdata = array_combine($lfieldorders, $lfieldcontents);
                     if ($importversion <= 132) {
                         $labelrowdata["assessment_value"] = (int) $labelrowdata["code"];
                     }
                     $labellid = $labelrowdata['lid'];
                     if ($importversion <= 100) {
                         $labelrowdata['language'] = $newlanguage;
                     }
                     if ($labellid == $oldlid) {
                         $labelrowdata['lid'] = $newlid;
                         // translate internal links
                         $labelrowdata['title'] = translink('label', $oldlid, $newlid, $labelrowdata['title']);
                         $newvalues = array_values($labelrowdata);
                         $newvalues = array_map(array(&$connect, "qstr"), $newvalues);
                         // quote everything accordingly
                         $lainsert = "insert INTO {$dbprefix}labels (" . implode(',', array_keys($labelrowdata)) . ") VALUES (" . implode(',', $newvalues) . ")";
                         //handle db prefix
                         $liresult = $connect->Execute($lainsert);
                     }
                 }
             }
             //CHECK FOR DUPLICATE LABELSETS
             $thisset = "";
             $query2 = "SELECT code, title, sortorder, language\r\n\t\t                   FROM {$dbprefix}labels\r\n\t\t                   WHERE lid=" . $newlid . "\r\n\t\t                   ORDER BY language, sortorder, code";
             $result2 = db_execute_num($query2) or $this->debugLsrc("Import of this survey file failed on Line " . __LINE__ . "| " . $connect->ErrorMsg());
             while ($row2 = $result2->FetchRow()) {
                 $thisset .= implode('.', $row2);
             }
             // while
             $newcs = dechex(crc32($thisset) * 1);
             unset($lsmatch);
             if (isset($csarray)) {
                 foreach ($csarray as $key => $val) {
                     if ($val == $newcs) {
                         $lsmatch = $key;
                     }
                 }
             }
             if (isset($lsmatch) || $_SESSION['USER_RIGHT_MANAGE_LABEL'] != 1) {
                 //There is a matching labelset or the user is not allowed to edit labels -
                 // So, we will delete this one and refer to the matched one.
                 $query = "DELETE FROM {$dbprefix}labels WHERE lid={$newlid}";
                 $result = $connect->Execute($query) or $this->debugLsrc("Import of this survey file failed on Line " . __LINE__ . "| " . $connect->ErrorMsg());
                 $query = "DELETE FROM {$dbprefix}labelsets WHERE lid={$newlid}";
                 $result = $connect->Execute($query) or $this->debugLsrc("Import of this survey file failed on Line " . __LINE__ . "| " . $connect->ErrorMsg());
                 if (isset($lsmatch)) {
                     $newlid = $lsmatch;
                 } else {
                     ++$deniedcountlabelsets;
                     --$countlabelsets;
                 }
             } else {
                 //There isn't a matching labelset, add this checksum to the $csarray array
                 $csarray[$newlid] = $newcs;
             }
             //END CHECK FOR DUPLICATES
             $labelreplacements[] = array($oldlid, $newlid);
         }
     }
     $this->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ", OK ");
     $importwarning = "";
     // used to save the warnings while processing questions
     $qtypes = $this->getqtypelist("", "array");
     foreach ($qtypes as $type) {
         //XXX FIXME
         $this->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ", OK " . $type);
     }
     // DO GROUPS, QUESTIONS FOR GROUPS, THEN ANSWERS FOR QUESTIONS IN A NESTED FORMAT!
     if (isset($grouparray) && $grouparray) {
         $count = 0;
         $currentgid = '';
         foreach ($grouparray as $ga) {
             $gafieldorders = convertCSVRowToArray($grouparray[0], ',', '"');
             $gacfieldcontents = convertCSVRowToArray($ga, ',', '"');
             if ($count == 0) {
                 $count++;
                 continue;
             }
             $grouprowdata = array_combine($gafieldorders, $gacfieldcontents);
             // remember group id
             if ($currentgid == '' || $currentgid != $grouprowdata['gid']) {
                 $currentgid = $grouprowdata['gid'];
                 $newgroup = true;
             } else {
                 if ($currentgid == $grouprowdata['gid']) {
                     $newgroup = false;
                 }
             }
             $gid = $grouprowdata['gid'];
             $gsid = $grouprowdata['sid'];
             //Now an additional integrity check if there are any groups not belonging into this survey
             if ($gsid != $surveyid) {
                 if ($importingfrom == "http") {
                     //		                $importsurvey .= "\n<font color='red'><strong>".("Error")."</strong></font>"
                     //		                                ."\n".("A group in the CSV/SQL file is not part of the same survey. The import of the survey was stopped.")."\n";
                 } else {
                     //echo ("Error").": A group in the CSV/SQL file is not part of the same Survey. The import of the survey was stopped.\n";
                 }
                 return false;
             }
             $this->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ", OK ");
             //remove the old group id
             if ($newgroup) {
                 unset($grouprowdata['gid']);
             } else {
                 $grouprowdata['gid'] = $newgid;
             }
             //replace old surveyid by new surveyid
             $grouprowdata['sid'] = $newsid;
             // Version <=100 dont have a language field yet so we set it now
             if ($importversion <= 100) {
                 $grouprowdata['language'] = $newlanguage;
             }
             $oldgid = $gid;
             // save it for later
             $grouprowdata = array_map('convertCsvreturn2return', $grouprowdata);
             // translate internal links
             $grouprowdata['group_name'] = translink('survey', $surveyid, $newsid, $grouprowdata['group_name']);
             $grouprowdata['description'] = translink('survey', $surveyid, $newsid, $grouprowdata['description']);
             $newvalues = array_values($grouprowdata);
             $newvalues = array_map(array(&$connect, "qstr"), $newvalues);
             // quote everything accordingly
             db_switchIDInsert('groups', true);
             $ginsert = 'insert INTO ' . db_table_name('groups') . ' (' . implode(',', array_keys($grouprowdata)) . ') VALUES (' . implode(',', $newvalues) . ')';
             $gres = $connect->Execute($ginsert) or $this->debugLsrc("Import of this survey file failed on Line " . __LINE__ . "| " . $connect->ErrorMsg());
             db_switchIDInsert('groups', false);
             //GET NEW GID
             if ($newgroup) {
                 $newgid = $connect->Insert_ID("{$dbprefix}groups", "gid");
             }
             //NOW DO NESTED QUESTIONS FOR THIS GID
             //$this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", OK ".var_dump($questionarray));
             if (isset($questionarray) && $questionarray && $newgroup) {
                 $count = 0;
                 $currentqid = '';
                 foreach ($questionarray as $qa) {
                     //$this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", OK ".$qa);
                     $qafieldorders = convertCSVRowToArray($questionarray[0], ',', '"');
                     $qacfieldcontents = convertCSVRowToArray($qa, ',', '"');
                     if ($count == 0) {
                         $count++;
                         continue;
                     }
                     $questionrowdata = array_combine($qafieldorders, $qacfieldcontents);
                     $questionrowdata = array_map('convertCsvreturn2return', $questionrowdata);
                     if ($currentqid == '' || $currentqid != $questionrowdata['qid']) {
                         $currentqid = $questionrowdata['qid'];
                         $newquestion = true;
                     } else {
                         if ($currentqid == $questionrowdata['qid']) {
                             $newquestion = false;
                         }
                     }
                     if (!array_key_exists($questionrowdata["type"], $qtypes)) {
                         $questionrowdata["type"] = strtoupper($questionrowdata["type"]);
                         if (!array_key_exists($questionrowdata["type"], $qtypes)) {
                             //$importwarning .= "<li>" . sprintf(("Question \"%s - %s\" was NOT imported because the question type is unknown."), $questionrowdata["title"], $questionrowdata["question"]) . "</li>";
                             $countquestions--;
                             $this->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ", OK " . $countquestions);
                             continue;
                         } else {
                             //$importwarning .= "<li>" . sprintf(("Question \"%s - %s\" was imported but the type was set to '%s' because it is the most similiar one."), $questionrowdata["title"], $questionrowdata["question"], $qtypes[$questionrowdata["type"]]) . "</li>";
                         }
                     }
                     $this->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ", OK ");
                     $thisgid = $questionrowdata['gid'];
                     $this->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ", OK " . $thisgid . " == " . $gid);
                     if ($thisgid == $gid) {
                         $qid = $questionrowdata['qid'];
                         // Remove qid field
                         if ($newquestion) {
                             unset($questionrowdata['qid']);
                         } else {
                             $questionrowdata['qid'] = $newqid;
                         }
                         $questionrowdata["sid"] = $newsid;
                         $questionrowdata["gid"] = $newgid;
                         // Version <=100 doesn't have a language field yet so we set it now
                         if ($importversion <= 100) {
                             $questionrowdata['language'] = $newlanguage;
                         }
                         $oldqid = $qid;
                         if (!isset($questionrowdata["lid1"])) {
                             $questionrowdata["lid1"] = 0;
                         }
                         // Now we will fix up the label id
                         $type = $questionrowdata["type"];
                         //Get the type
                         if ($type == "F" || $type == "H" || $type == "W" || $type == "Z" || $type == "1" || $type == ":" || $type == ";") {
                             //IF this is a flexible label array, update the lid entry
                             if (isset($labelreplacements)) {
                                 // We only replace once in each question label
                                 // otherwise could lead to double substitution
                                 // if a new lid collides with an older one
                                 $already_replaced_label = false;
                                 $already_replaced_label1 = false;
                                 foreach ($labelreplacements as $lrp) {
                                     if ($lrp[0] == $questionrowdata["lid"]) {
                                         if (!$already_replaced_label) {
                                             $questionrowdata["lid"] = $lrp[1];
                                             $already_replaced_label = true;
                                         }
                                     }
                                     if ($lrp[0] == $questionrowdata["lid1"]) {
                                         if (!$already_replaced_label1) {
                                             $questionrowdata["lid1"] = $lrp[1];
                                             $already_replaced_label1 = true;
                                         }
                                     }
                                 }
                             }
                         }
                         if (!isset($questionrowdata["question_order"]) || $questionrowdata["question_order"] == '') {
                             $questionrowdata["question_order"] = 0;
                         }
                         $other = $questionrowdata["other"];
                         //Get 'other' field value
                         // translate internal links
                         $questionrowdata['title'] = translink('survey', $surveyid, $newsid, $questionrowdata['title']);
                         $questionrowdata['question'] = translink('survey', $surveyid, $newsid, $questionrowdata['question']);
                         $questionrowdata['help'] = translink('survey', $surveyid, $newsid, $questionrowdata['help']);
                         $newvalues = array_values($questionrowdata);
                         db_switchIDInsert('questions', true);
                         //foreach($questionrowdata as $qrd)
                         //$this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", OK ".$qrd);
                         $newvalues = array_map(array(&$connect, "qstr"), $newvalues);
                         // quote everything accordingly
                         $qinsert = "insert INTO {$dbprefix}questions (" . implode(',', array_keys($questionrowdata)) . ") VALUES (" . implode(',', $newvalues) . ")";
                         $this->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ", OK | " . $qinsert);
                         $qres = $connect->Execute($qinsert) or $this->debugLsrc("Import of this survey file failed on Line " . __LINE__ . "| " . $connect->ErrorMsg());
                         db_switchIDInsert('questions', false);
                         if ($newquestion) {
                             $newqid = $connect->Insert_ID("{$dbprefix}questions", "qid");
                         }
                         $newrank = 0;
                         $substitutions[] = array($oldsid, $oldgid, $oldqid, $newsid, $newgid, $newqid);
                         //$this->debugLsrc("HALLO?!:");
                         //NOW DO NESTED ANSWERS FOR THIS QID
                         if (isset($answerarray) && $answerarray && $newquestion) {
                             $count = 0;
                             foreach ($answerarray as $aa) {
                                 $aafieldorders = convertCSVRowToArray($answerarray[0], ',', '"');
                                 $aacfieldcontents = convertCSVRowToArray($aa, ',', '"');
                                 if ($count == 0) {
                                     $count++;
                                     continue;
                                 }
                                 $answerrowdata = array_combine($aafieldorders, $aacfieldcontents);
                                 if ($importversion <= 132) {
                                     $answerrowdata["assessment_value"] = (int) $answerrowdata["code"];
                                 }
                                 $code = $answerrowdata["code"];
                                 $thisqid = $answerrowdata["qid"];
                                 if ($thisqid == $qid) {
                                     $answerrowdata["qid"] = $newqid;
                                     // Version <=100 doesn't have a language field yet so we set it now
                                     if ($importversion <= 100) {
                                         $answerrowdata['language'] = $newlanguage;
                                     }
                                     // translate internal links
                                     $answerrowdata['answer'] = translink('survey', $surveyid, $newsid, $answerrowdata['answer']);
                                     $newvalues = array_values($answerrowdata);
                                     $newvalues = array_map(array(&$connect, "qstr"), $newvalues);
                                     // quote everything accordingly
                                     $ainsert = "insert INTO {$dbprefix}answers (" . implode(',', array_keys($answerrowdata)) . ") VALUES (" . implode(',', $newvalues) . ")";
                                     $ares = $connect->Execute($ainsert) or $this->debugLsrc("Import of this survey file failed on Line " . __LINE__ . "| " . $connect->ErrorMsg());
                                     if ($type == "M" || $type == "P") {
                                         $fieldnames[] = array("oldcfieldname" => $oldsid . "X" . $oldgid . "X" . $oldqid, "newcfieldname" => $newsid . "X" . $newgid . "X" . $newqid, "oldfieldname" => $oldsid . "X" . $oldgid . "X" . $oldqid . $code, "newfieldname" => $newsid . "X" . $newgid . "X" . $newqid . $code);
                                         if ($type == "P") {
                                             $fieldnames[] = array("oldcfieldname" => $oldsid . "X" . $oldgid . "X" . $oldqid . "comment", "newcfieldname" => $newsid . "X" . $newgid . "X" . $newqid . $code . "comment", "oldfieldname" => $oldsid . "X" . $oldgid . "X" . $oldqid . $code . "comment", "newfieldname" => $newsid . "X" . $newgid . "X" . $newqid . $code . "comment");
                                         }
                                     } elseif ($type == "A" || $type == "B" || $type == "C" || $type == "F" || $type == "H" || $type == "E" || $type == "Q" || $type == "K" || $type == "1") {
                                         $fieldnames[] = array("oldcfieldname" => $oldsid . "X" . $oldgid . "X" . $oldqid . $code, "newcfieldname" => $newsid . "X" . $newgid . "X" . $newqid . $code, "oldfieldname" => $oldsid . "X" . $oldgid . "X" . $oldqid . $code, "newfieldname" => $newsid . "X" . $newgid . "X" . $newqid . $code);
                                     } elseif ($type == ":" || $type == ";") {
                                         // read all label codes from $questionrowdata["lid"]
                                         // for each one (as L) set SGQA_L
                                         $labelq = "SELECT DISTINCT code FROM {$dbprefix}labels WHERE lid=" . $questionrowdata["lid"];
                                         $labelqresult = db_execute_num($labelq) or safe_die("Died querying labelset {$lid}<br />{$query2}<br />" . $connect->ErrorMsg());
                                         while ($labelqrow = $labelqresult->FetchRow()) {
                                             $fieldnames[] = array("oldcfieldname" => $oldsid . "X" . $oldgid . "X" . $oldqid . $code . "_" . $labelqrow[0], "newcfieldname" => $newsid . "X" . $newgid . "X" . $newqid . $code . "_" . $labelqrow[0], "oldfieldname" => $oldsid . "X" . $oldgid . "X" . $oldqid . $code . "_" . $labelqrow[0], "newfieldname" => $newsid . "X" . $newgid . "X" . $newqid . $code . "_" . $labelqrow[0]);
                                         }
                                     } elseif ($type == "R") {
                                         $newrank++;
                                     }
                                 }
                             }
                             if (($type == "A" || $type == "B" || $type == "C" || $type == "M" || $type == "P" || $type == "L") && $other == "Y") {
                                 $fieldnames[] = array("oldcfieldname" => $oldsid . "X" . $oldgid . "X" . $oldqid . "other", "newcfieldname" => $newsid . "X" . $newgid . "X" . $newqid . "other", "oldfieldname" => $oldsid . "X" . $oldgid . "X" . $oldqid . "other", "newfieldname" => $newsid . "X" . $newgid . "X" . $newqid . "other");
                                 if ($type == "P") {
                                     $fieldnames[] = array("oldcfieldname" => $oldsid . "X" . $oldgid . "X" . $oldqid . "othercomment", "newcfieldname" => $newsid . "X" . $newgid . "X" . $newqid . "othercomment", "oldfieldname" => $oldsid . "X" . $oldgid . "X" . $oldqid . "othercomment", "newfieldname" => $newsid . "X" . $newgid . "X" . $newqid . "othercomment");
                                 }
                             }
                             if ($type == "R" && $newrank > 0) {
                                 for ($i = 1; $i <= $newrank; $i++) {
                                     $fieldnames[] = array("oldcfieldname" => $oldsid . "X" . $oldgid . "X" . $oldqid . $i, "newcfieldname" => $newsid . "X" . $newgid . "X" . $newqid . $i, "oldfieldname" => $oldsid . "X" . $oldgid . "X" . $oldqid . $i, "newfieldname" => $newsid . "X" . $newgid . "X" . $newqid . $i);
                                 }
                             }
                             if ($type != "A" && $type != "B" && $type != "C" && $type != "R" && $type != "M" && $type != "P") {
                                 $fieldnames[] = array("oldcfieldname" => $oldsid . "X" . $oldgid . "X" . $oldqid, "newcfieldname" => $newsid . "X" . $newgid . "X" . $newqid, "oldfieldname" => $oldsid . "X" . $oldgid . "X" . $oldqid, "newfieldname" => $newsid . "X" . $newgid . "X" . $newqid);
                                 if ($type == "O") {
                                     $fieldnames[] = array("oldcfieldname" => $oldsid . "X" . $oldgid . "X" . $oldqid . "comment", "newcfieldname" => $newsid . "X" . $newgid . "X" . $newqid . "comment", "oldfieldname" => $oldsid . "X" . $oldgid . "X" . $oldqid . "comment", "newfieldname" => $newsid . "X" . $newgid . "X" . $newqid . "comment");
                                 }
                             }
                         } else {
                             $fieldnames[] = array("oldcfieldname" => $oldsid . "X" . $oldgid . "X" . $oldqid, "newcfieldname" => $newsid . "X" . $newgid . "X" . $newqid, "oldfieldname" => $oldsid . "X" . $oldgid . "X" . $oldqid, "newfieldname" => $newsid . "X" . $newgid . "X" . $newqid);
                         }
                     }
                 }
             }
         }
     }
     $this->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ", OK ");
     // Fix sortorder of the groups  - if users removed groups manually from the csv file there would be gaps
     fixSortOrderGroups($surveyid);
     $baselang = GetBaseLanguageFromSurveyID($iVid);
     $cdresult = db_execute_assoc("SELECT gid FROM " . db_table_name('groups') . " WHERE sid='{$surveyid}' AND language='{$baselang}' ORDER BY group_order, group_name");
     $position = 0;
     while ($cdrow = $cdresult->FetchRow()) {
         $cd2query = "UPDATE " . db_table_name('groups') . " SET group_order='{$position}' WHERE gid='{$cdrow['gid']}' ";
         $cd2result = $connect->Execute($cd2query) or $this->debugLsrc("Import of this survey file failed on Line " . __LINE__ . "| " . $connect->ErrorMsg());
         //Checked
         $position++;
     }
     $this->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ", OK ");
     //... and for the questions inside the groups
     // get all group ids and fix questions inside each group
     $gquery = "SELECT gid FROM {$dbprefix}groups where sid={$newsid} group by gid ORDER BY gid";
     //Get last question added (finds new qid)
     $gres = db_execute_assoc($gquery);
     while ($grow = $gres->FetchRow()) {
         //fixsortorderQuestions(0,$grow['gid']); //XXX changed: commented out
         // and fully written out:
         $qid = sanitize_int(0);
         $gid = sanitize_int($grow['gid']);
         $baselang = GetBaseLanguageFromSurveyID($iVid);
         if ($gid == 0) {
             $result = db_execute_assoc("SELECT gid FROM " . db_table_name('questions') . " WHERE qid='{$qid}' and language='{$baselang}'");
             //Checked
             $row = $result->FetchRow();
             $gid = $row['gid'];
         }
         $cdresult = db_execute_assoc("SELECT qid FROM " . db_table_name('questions') . " WHERE gid='{$gid}' and language='{$baselang}' ORDER BY question_order, title ASC");
         //Checked
         $position = 0;
         while ($cdrow = $cdresult->FetchRow()) {
             $cd2query = "UPDATE " . db_table_name('questions') . " SET question_order='{$position}' WHERE qid='{$cdrow['qid']}' ";
             $cd2result = $connect->Execute($cd2query) or $this->debugLsrc("Import of this survey file failed on Line " . __LINE__ . "| " . $connect->ErrorMsg());
             $position++;
         }
     }
     $this->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ", OK ");
     //We've built two arrays along the way - one containing the old SID, GID and QIDs - and their NEW equivalents
     //and one containing the old 'extended fieldname' and its new equivalent.  These are needed to import conditions and question_attributes.
     if (isset($question_attributesarray) && $question_attributesarray) {
         //ONLY DO THIS IF THERE ARE QUESTION_ATTRIBUES
         $count = 0;
         foreach ($question_attributesarray as $qar) {
             $fieldorders = convertCSVRowToArray($question_attributesarray[0], ',', '"');
             $fieldcontents = convertCSVRowToArray($qar, ',', '"');
             if ($count == 0) {
                 $count++;
                 continue;
             }
             $qarowdata = array_combine($fieldorders, $fieldcontents);
             $newqid = "";
             $oldqid = $qarowdata['qid'];
             foreach ($substitutions as $subs) {
                 if ($oldqid == $subs[2]) {
                     $newqid = $subs[5];
                 }
             }
             $qarowdata["qid"] = $newqid;
             unset($qarowdata["qaid"]);
             $newvalues = array_values($qarowdata);
             $newvalues = array_map(array(&$connect, "qstr"), $newvalues);
             // quote everything accordingly
             $qainsert = "insert INTO {$dbprefix}question_attributes (" . implode(',', array_keys($qarowdata)) . ") VALUES (" . implode(',', $newvalues) . ")";
             $result = $connect->Execute($qainsert) or $this->debugLsrc("Import of this survey file failed on Line " . __LINE__ . "|  {$qainsert}  |" . $connect->ErrorMsg());
         }
     }
     if (isset($assessmentsarray) && $assessmentsarray) {
         //ONLY DO THIS IF THERE ARE QUESTION_ATTRIBUES
         $count = 0;
         foreach ($assessmentsarray as $qar) {
             $fieldorders = convertCSVRowToArray($assessmentsarray[0], ',', '"');
             $fieldcontents = convertCSVRowToArray($qar, ',', '"');
             if ($count == 0) {
                 $count++;
                 continue;
             }
             $asrowdata = array_combine($fieldorders, $fieldcontents);
             if (isset($asrowdata['link'])) {
                 if (trim($asrowdata['link']) != '') {
                     $asrowdata['message'] = $asrowdata['message'] . '<br /><a href="' . $asrowdata['link'] . '">' . $asrowdata['link'] . '</a>';
                 }
                 unset($asrowdata['link']);
             }
             $oldsid = $asrowdata["sid"];
             $oldgid = $asrowdata["gid"];
             if ($oldgid > 0) {
                 foreach ($substitutions as $subs) {
                     if ($oldsid == $subs[0]) {
                         $newsid = $subs[3];
                     }
                     if ($oldgid == $subs[1]) {
                         $newgid = $subs[4];
                     }
                 }
             } else {
                 $newgid = 0;
             }
             $asrowdata["sid"] = $newsid;
             $asrowdata["gid"] = $newgid;
             unset($asrowdata["id"]);
             $newvalues = array_values($asrowdata);
             $newvalues = array_map(array(&$connect, "qstr"), $newvalues);
             // quote everything accordingly
             $asinsert = "insert INTO {$dbprefix}assessments (" . implode(',', array_keys($asrowdata)) . ") VALUES (" . implode(',', $newvalues) . ")";
             $result = $connect->Execute($asinsert) or $this->debugLsrc("Import of this survey file failed on Line " . __LINE__ . "| " . $connect->ErrorMsg());
             unset($newgid);
         }
     }
     if (isset($quotaarray) && $quotaarray) {
         //ONLY DO THIS IF THERE ARE QUOTAS
         $count = 0;
         foreach ($quotaarray as $qar) {
             $fieldorders = convertCSVRowToArray($quotaarray[0], ',', '"');
             $fieldcontents = convertCSVRowToArray($qar, ',', '"');
             if ($count == 0) {
                 $count++;
                 continue;
             }
             $asrowdata = array_combine($fieldorders, $fieldcontents);
             $oldsid = $asrowdata["sid"];
             foreach ($substitutions as $subs) {
                 if ($oldsid == $subs[0]) {
                     $newsid = $subs[3];
                 }
             }
             $asrowdata["sid"] = $newsid;
             $oldid = $asrowdata["id"];
             unset($asrowdata["id"]);
             $newvalues = array_values($asrowdata);
             $newvalues = array_map(array(&$connect, "qstr"), $newvalues);
             // quote everything accordingly
             $asinsert = "insert INTO {$dbprefix}quota (" . implode(',', array_keys($asrowdata)) . ") VALUES (" . implode(',', $newvalues) . ")";
             $result = $connect->Execute($asinsert) or $this->debugLsrc("Import of this survey file failed on Line " . __LINE__ . "| " . $connect->ErrorMsg());
             $quotaids[] = array($oldid, $connect->Insert_ID(db_table_name_nq('quota'), "id"));
         }
     }
     if (isset($quotamembersarray) && $quotamembersarray) {
         //ONLY DO THIS IF THERE ARE QUOTAS
         $count = 0;
         foreach ($quotamembersarray as $qar) {
             $fieldorders = convertCSVRowToArray($quotamembersarray[0], ',', '"');
             $fieldcontents = convertCSVRowToArray($qar, ',', '"');
             if ($count == 0) {
                 $count++;
                 continue;
             }
             $asrowdata = array_combine($fieldorders, $fieldcontents);
             $oldsid = $asrowdata["sid"];
             $newqid = "";
             $newquotaid = "";
             $oldqid = $asrowdata['qid'];
             $oldquotaid = $asrowdata['quota_id'];
             foreach ($substitutions as $subs) {
                 if ($oldsid == $subs[0]) {
                     $newsid = $subs[3];
                 }
                 if ($oldqid == $subs[2]) {
                     $newqid = $subs[5];
                 }
             }
             foreach ($quotaids as $quotaid) {
                 if ($oldquotaid == $quotaid[0]) {
                     $newquotaid = $quotaid[1];
                 }
             }
             $asrowdata["sid"] = $newsid;
             $asrowdata["qid"] = $newqid;
             $asrowdata["quota_id"] = $newquotaid;
             unset($asrowdata["id"]);
             $newvalues = array_values($asrowdata);
             $newvalues = array_map(array(&$connect, "qstr"), $newvalues);
             // quote everything accordingly
             $asinsert = "insert INTO {$dbprefix}quota_members (" . implode(',', array_keys($asrowdata)) . ") VALUES (" . implode(',', $newvalues) . ")";
             $result = $connect->Execute($asinsert) or $this->debugLsrc("Import of this survey file failed on Line " . __LINE__ . "| " . $connect->ErrorMsg());
         }
     }
     if (isset($conditionsarray) && $conditionsarray) {
         //ONLY DO THIS IF THERE ARE CONDITIONS!
         $count = '0';
         foreach ($conditionsarray as $car) {
             $fieldorders = convertCSVRowToArray($conditionsarray[0], ',', '"');
             $fieldcontents = convertCSVRowToArray($car, ',', '"');
             if ($count == 0) {
                 $count++;
                 continue;
             }
             $conditionrowdata = array_combine($fieldorders, $fieldcontents);
             $oldcid = $conditionrowdata["cid"];
             $oldqid = $conditionrowdata["qid"];
             $oldcfieldname = $conditionrowdata["cfieldname"];
             $oldcqid = $conditionrowdata["cqid"];
             $thisvalue = $conditionrowdata["value"];
             $newvalue = $thisvalue;
             foreach ($substitutions as $subs) {
                 if ($oldqid == $subs[2]) {
                     $newqid = $subs[5];
                 }
                 if ($oldcqid == $subs[2]) {
                     $newcqid = $subs[5];
                 }
             }
             if (ereg('^@([0-9]+)X([0-9]+)X([^@]+)@', $thisvalue, $targetcfieldname)) {
                 foreach ($substitutions as $subs) {
                     if ($targetcfieldname[1] == $subs[0]) {
                         $targetcfieldname[1] = $subs[3];
                     }
                     if ($targetcfieldname[2] == $subs[1]) {
                         $targetcfieldname[2] = $subs[4];
                     }
                     if ($targetcfieldname[3] == $subs[2]) {
                         $targetcfieldname[3] = $subs[5];
                     }
                 }
                 $newvalue = '@' . $targetcfieldname[1] . 'X' . $targetcfieldname[2] . 'X' . $targetcfieldname[3] . '@';
             }
             foreach ($fieldnames as $fns) {
                 //if the $fns['oldcfieldname'] is not the same as $fns['oldfieldname'] then this is a multiple type question
                 if ($fns['oldcfieldname'] == $fns['oldfieldname']) {
                     //The normal method - non multiples
                     if ($oldcfieldname == $fns['oldcfieldname']) {
                         $newcfieldname = $fns['newcfieldname'];
                     }
                 } else {
                     if ($oldcfieldname == $fns['oldcfieldname'] && $oldcfieldname . $thisvalue == $fns['oldfieldname']) {
                         $newcfieldname = $fns['newcfieldname'];
                     }
                 }
             }
             if (!isset($newcfieldname)) {
                 $newcfieldname = "";
             }
             unset($conditionrowdata["cid"]);
             $conditionrowdata["qid"] = $newqid;
             $conditionrowdata["cfieldname"] = $newcfieldname;
             $conditionrowdata["value"] = $newvalue;
             if (isset($newcqid)) {
                 $conditionrowdata["cqid"] = $newcqid;
                 if (!isset($conditionrowdata["method"]) || trim($conditionrowdata["method"]) == '') {
                     $conditionrowdata["method"] = '==';
                 }
                 if (!isset($conditionrowdata["scenario"]) || trim($conditionrowdata["scenario"]) == '') {
                     $conditionrowdata["scenario"] = 1;
                 }
                 $newvalues = array_values($conditionrowdata);
                 $newvalues = array_map(array(&$connect, "qstr"), $newvalues);
                 // quote everything accordingly
                 $conditioninsert = "insert INTO {$dbprefix}conditions (" . implode(',', array_keys($conditionrowdata)) . ") VALUES (" . implode(',', $newvalues) . ")";
                 $result = $connect->Execute($conditioninsert) or $this->debugLsrc("Import of this survey file failed on Line " . __LINE__ . "| " . $connect->ErrorMsg());
             } else {
                 $importsurvey .= "<font size=1>Condition for {$oldqid} skipped ({$oldcqid} does not exist)</font>";
                 //if ($importingfrom != "http") echo "Condition for $oldqid skipped ($oldcqid does not exist)\n";
                 //return; //XXX changed: comment the upper line, returning
             }
             unset($newcqid);
         }
     }
     // Translate INSERTANS codes
     if (isset($fieldnames)) {
         TranslateInsertansTags($newsid, $oldsid, $fieldnames);
     }
     $surveyid = $newsid;
     return true;
 }
Example #7
0
/**
 * Marks a tokens as completed and sends a confirmation email to the participiant.
 * If $quotaexit is set to true then the user exited the survey due to a quota
 * restriction and the according token is only marked as 'Q'
 *
 * @param mixed $quotaexit
 */
function submittokens($quotaexit = false)
{
    global $thissurvey, $timeadjust, $emailcharset;
    global $dbprefix, $surveyid, $connect;
    global $sitename, $thistpl, $clang, $clienttoken;
    // Shift the date due to global timeadjust setting
    $today = date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i", $timeadjust);
    $utquery = "UPDATE {$dbprefix}tokens_{$surveyid}\n";
    if ($quotaexit == true) {
        $utquery .= "SET completed='Q'\n";
    } elseif (bIsTokenCompletedDatestamped($thissurvey)) {
        $utquery .= "SET completed='{$today}'\n";
    } else {
        $utquery .= "SET completed='Y'\n";
    }
    $utquery .= "WHERE token='" . db_quote($clienttoken) . "'";
    $utresult = $connect->Execute($utquery) or safe_die("Couldn't update tokens table!<br />\n{$utquery}<br />\n" . $connect->ErrorMsg());
    //Checked
    if ($quotaexit == false) {
        // TLR change to put date into sent and completed
        $cnfquery = "SELECT * FROM " . db_table_name("tokens_{$surveyid}") . " WHERE token='" . db_quote($clienttoken) . "' AND completed!='N' AND completed!=''";
        $cnfresult = db_execute_assoc($cnfquery);
        //Checked
        $cnfrow = $cnfresult->FetchRow();
        if (isset($cnfrow)) {
            $from = "{$thissurvey['adminname']} <{$thissurvey['adminemail']}>";
            $to = $cnfrow['email'];
            $subject = $thissurvey['email_confirm_subj'];
            $fieldsarray["{ADMINNAME}"] = $thissurvey['adminname'];
            $fieldsarray["{ADMINEMAIL}"] = $thissurvey['adminemail'];
            $fieldsarray["{SURVEYNAME}"] = $thissurvey['name'];
            $fieldsarray["{SURVEYDESCRIPTION}"] = $thissurvey['description'];
            $fieldsarray["{FIRSTNAME}"] = $cnfrow['firstname'];
            $fieldsarray["{LASTNAME}"] = $cnfrow['lastname'];
            $fieldsarray["{TOKEN}"] = $clienttoken;
            $attrfieldnames = GetAttributeFieldnames($surveyid);
            foreach ($attrfieldnames as $attr_name) {
                $fieldsarray["{" . strtoupper($attr_name) . "}"] = $cnfrow[$attr_name];
            }
            $dateformatdatat = getDateFormatData($thissurvey['surveyls_dateformat']);
            $fieldsarray["{EXPIRY}"] = convertDateTimeFormat($thissurvey["expiry"], 'Y-m-d H:i:s', $dateformatdatat['phpdate']);
            $subject = Replacefields($subject, $fieldsarray);
            if ($thissurvey['private'] == "N") {
                // Survey is not anonymous, we can translate insertAns placeholder
                $subject = insertansReplace($subject);
            }
            $subject = html_entity_decode($subject, ENT_QUOTES, $emailcharset);
            if (getEmailFormat($surveyid) == 'html') {
                $ishtml = true;
            } else {
                $ishtml = false;
            }
            if (trim(strip_tags($thissurvey['email_confirm'])) != "") {
                $message = $thissurvey['email_confirm'];
                $message = Replacefields($message, $fieldsarray);
                if ($thissurvey['private'] == "N") {
                    // Survey is not anonymous, we can translate insertAns placeholder
                    $message = insertansReplace($message);
                }
                if (!$ishtml) {
                    $message = strip_tags(br2nl(html_entity_decode($message, ENT_QUOTES, $emailcharset)));
                } else {
                    $message = html_entity_decode($message, ENT_QUOTES, $emailcharset);
                }
                //Only send confirmation email if there is a valid email address
                if (validate_email($cnfrow['email'])) {
                    SendEmailMessage($message, $subject, $to, $from, $sitename, $ishtml);
                }
            } else {
                //There is nothing in the message, so don't send a confirmation email
                //This section only here as placeholder to indicate new feature :-)
            }
        }
    }
}
                 break;
         }
         //$dataentryoutput .= " [$surveyid"."X"."$gid"."X"."$qid]";
         $dataentryoutput .= "</td>\n";
         $dataentryoutput .= "\t</tr>\n";
         $dataentryoutput .= "\t<tr class='data-entry-separator'><td colspan='3'></td></tr>\n";
     }
 }
 if ($thissurvey['active'] == "Y") {
     // Show Finalize response option
     $dataentryoutput .= "<script type='text/javascript'>\n\t\t\t\t  <!--\n\t\t\t\t\tfunction saveshow(value)\n\t\t\t\t\t\t{\n\t\t\t\t\t\tif (document.getElementById(value).checked == true)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\tdocument.getElementById(\"closerecord\").checked=false;\n\t\t\t\t\t\t\tdocument.getElementById(\"closerecord\").disabled=true;\n\t\t\t\t\t\t\tdocument.getElementById(\"saveoptions\").style.display=\"\";\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\tdocument.getElementById(\"saveoptions\").style.display=\"none\";\n\t\t\t\t\t\t\t document.getElementById(\"closerecord\").disabled=false;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t  //-->\n\t\t\t\t  </script>\n";
     $dataentryoutput .= "\t<tr>\n";
     $dataentryoutput .= "<td colspan='3' align='center'>\n";
     $dataentryoutput .= "<table><tr><td align='left'>\n";
     $dataentryoutput .= "\t<input type='checkbox' class='checkboxbtn' name='closerecord' id='closerecord' checked='checked'/><label for='closerecord'>" . $clang->gT("Finalize response submission") . "</label></td></tr>\n";
     $dataentryoutput .= "<input type='hidden' name='closedate' value='" . date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust) . "' />\n";
     if ($thissurvey['allowsave'] == "Y") {
         //Show Save Option
         $dataentryoutput .= "\t<tr><td align='left'><input type='checkbox' class='checkboxbtn' name='save' id='save' onclick='saveshow(this.id)' /><label for='save'>" . $clang->gT("Save for further completion by survey user") . "</label>\n";
         $dataentryoutput .= "</td></tr></table>\n";
         $dataentryoutput .= "<div name='saveoptions' id='saveoptions' style='display: none'>\n";
         $dataentryoutput .= "<table align='center' class='outlinetable' cellspacing='0'>\n\t\t\t\t\t  <tr><td align='right'>" . $clang->gT("Identifier:") . "</td>\n\t\t\t\t\t  <td><input type='text' name='save_identifier' /></td></tr>\n\t\t\t\t\t  <tr><td align='right'>" . $clang->gT("Password:"******"</td>\n\t\t\t\t\t  <td><input type='password' name='save_password' /></td></tr>\n\t\t\t\t\t  <tr><td align='right'>" . $clang->gT("Confirm Password:"******"</td>\n\t\t\t\t\t  <td><input type='password' name='save_confirmpassword' /></td></tr>\n\t\t\t\t\t  <tr><td align='right'>" . $clang->gT("Email:") . "</td>\n\t\t\t\t\t  <td><input type='text' name='save_email' /></td></tr>\n\t\t\t\t\t  <tr><td align='right'>" . $clang->gT("Start Language:") . "</td>\n\t\t\t\t\t  <td>";
         $slangs = GetAdditionalLanguagesFromSurveyID($surveyid);
         $sbaselang = GetBaseLanguageFromSurveyID($surveyid);
         array_unshift($slangs, $sbaselang);
         $dataentryoutput .= "<select name='save_language'>\n";
         foreach ($slangs as $lang) {
             if ($lang == $baselang) {
                 $dataentryoutput .= "\t<option value='{$lang}' selected='selected'>" . getLanguageNameFromCode($lang, false) . "</option>\n";
             } else {
                 $dataentryoutput .= "\t<option value='{$lang}'>" . getLanguageNameFromCode($lang, false) . "</option>\n";
 public function get_current_shifts($gen_id = null)
 {
     if ($gen_id) {
         $current_gen = Gen::find($gen_id);
     } else {
         $current_gen = Gen::getCurrentGen();
     }
     $shifts = $current_gen->shifts()->get();
     $weeks = $shifts->pluck('week')->unique()->sortByDesc(function ($week, $key) {
         return $week;
     });
     $return_arr = [];
     foreach ($weeks as $week) {
         $week_shifts = $shifts->where('week', $week);
         $dates = $week_shifts->pluck('date')->unique();
         $return_dates = [];
         foreach ($dates as $date) {
             $obj = new \stdClass();
             $obj->date = date_shift(strtotime($date));
             $obj->shifts = $shifts->filter(function ($item) use($date) {
                 return $item->date == $date;
             });
             $shiftsData = $this->shiftTransfromer->transformCollection($obj->shifts);
             $obj->shifts = $shiftsData;
             $return_dates[] = $obj;
         }
         $return_arr[] = ['dates' => $return_dates, 'week' => $week];
     }
     return response()->json(['weeks' => $return_arr]);
 }
 * Copyright (C) 2007 The LimeSurvey Project Team / Carsten Schmitz
 * All rights reserved.
 * License: GNU/GPL License v2 or later, see LICENSE.php
 * LimeSurvey is free software. This version may have been modified pursuant
 * to the GNU General Public License, and as distributed it includes or
 * is derivative of works licensed under the GNU General Public License or
 * other free or open source software licenses.
 * See COPYRIGHT.php for copyright notices and details.
 *
 * $Id: dumpdb.php 10475 2011-07-11 16:14:32Z c_schmitz $
 */
include_once "login_check.php";
//Login Check dies also if the script is started directly
if ($database_exists && ($databasetype == 'mysql' || $databasetype == 'mysqli') && $demoModeOnly != true && $action == 'dumpdb') {
    $export = completedump();
    $file_name = "LimeSurvey_{$databasename}_dump_" . date_shift(date("Y-m-d H:i:s"), "Y-m-d", $timeadjust) . ".sql";
    Header("Content-type: application/octet-stream");
    Header("Content-Disposition: attachment; filename={$file_name}");
    Header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    Header("Pragma: Public");
    echo $export;
    exit;
    // needs to be inside the condition so the updater still can include this file
}
/**
 * Creates a full dump of the current LimeSurvey database
 *
 * @returns string Contains the dumped data
 */
function completedump()
{
Example #11
0
 /**
  * Write values to database.
  * @param <type> $updatedValues
  * @param <boolean> $finished - true if the survey needs to be finalized
  */
 private function _UpdateValuesInDatabase($updatedValues, $finished = false, $setSubmitDate = false)
 {
     // Update these values in the database
     global $connect;
     //  TODO - now that using $this->updatedValues, may be able to remove local copies of it (unless needed by other sub-systems)
     $updatedValues = $this->updatedValues;
     if (!$this->surveyOptions['deletenonvalues']) {
         $nonNullValues = array();
         foreach ($updatedValues as $key => $value) {
             if (!is_null($value)) {
                 if (isset($value['value']) && !is_null($value['value'])) {
                     $nonNullValues[$key] = $value;
                 }
             }
         }
         $updatedValues = $nonNullValues;
     }
     $message = '';
     if ($this->surveyOptions['datestamp'] == true && $this->surveyOptions['anonymized'] == true) {
         // On anonymous datestamped surveys, set the datestamp to 1-1-1980
         $datestamp = date("Y-m-d H:i:s", mktime(0, 0, 0, 1, 1, 1980));
     } else {
         // Otherwise, use the real date/time, it will only be saved when the table holds a
         // datestamp field
         $datestamp = date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $this->surveyOptions['timeadjust']);
     }
     $_SESSION['datestamp'] = $datestamp;
     if ($this->surveyOptions['active'] && !isset($_SESSION['srid'])) {
         // Create initial insert row for this record
         $sdata = array("datestamp" => $datestamp, "ipaddr" => $this->surveyOptions['ipaddr'] ? getIPAddress() : '', "startlanguage" => $this->surveyOptions['startlanguage'], "token" => $this->surveyOptions['token'], "refurl" => $this->surveyOptions['refurl'] ? getenv("HTTP_REFERER") : NULL, "startdate" => $datestamp);
         //One of the strengths of ADOdb's AutoExecute() is that only valid field names for $table are updated
         if ($connect->AutoExecute($this->surveyOptions['tablename'], $sdata, 'INSERT')) {
             $srid = $connect->Insert_ID($this->surveyOptions['tablename'], "id");
             $_SESSION['srid'] = $srid;
         } else {
             $message .= $this->gT("Unable to insert record into survey table: ") . $connect->ErrorMsg() . "<br/>";
             $_SESSION['flashmessage'] = $message;
             echo $message;
         }
         //Insert Row for Timings, if needed
         if ($this->surveyOptions['savetimings']) {
             $tdata = array('id' => $srid, 'interviewtime' => 0);
             if ($connect->AutoExecute($this->surveyOptions['tablename_timings'], $tdata, 'INSERT')) {
                 $trid = $connect->Insert_ID($this->surveyOptions['tablename_timings'], "sid");
             } else {
                 $message .= $this->gT("Unable to insert record into timings table ") . $connect->ErrorMsg() . "<br/>";
                 $_SESSION['flashmessage'] = $message;
                 echo $message;
             }
         }
     }
     if (count($updatedValues) > 0 || $finished) {
         $query = 'UPDATE ' . $this->surveyOptions['tablename'] . " SET ";
         $setter = array();
         switch ($this->surveyMode) {
             case 'question':
                 $thisstep = $this->currentQuestionSeq;
                 break;
             case 'group':
                 $thisstep = $this->currentGroupSeq;
                 break;
             case 'survey':
                 $thisstep = 1;
                 break;
         }
         $setter[] = db_quote_id('lastpage') . "=" . db_quoteall($thisstep);
         if ($this->surveyOptions['datestamp'] && isset($_SESSION['datestamp'])) {
             $setter[] = db_quote_id('datestamp') . "=" . db_quoteall($_SESSION['datestamp']);
         }
         if ($this->surveyOptions['ipaddr']) {
             $setter[] = db_quote_id('ipaddr') . "=" . db_quoteall(getIPAddress());
         }
         foreach ($updatedValues as $key => $value) {
             if (!empty($key)) {
                 $val = is_null($value) ? NULL : $value['value'];
                 $type = is_null($value) ? NULL : $value['type'];
                 // Clean up the values to cope with database storage requirements
                 switch ($type) {
                     case 'D':
                         //DATE
                         if (trim($val) == '') {
                             $val = NULL;
                             // since some databases can't store blanks in date fields
                         }
                         // otherwise will already be in yyyy-mm-dd format after ProcessCurrentResponses()
                         break;
                     case '|':
                         //File upload
                         // This block can be removed once we require 5.3 or later
                         if (function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) {
                             $val = addslashes($val);
                         }
                         break;
                     case 'N':
                         //NUMERICAL QUESTION TYPE
                     //NUMERICAL QUESTION TYPE
                     case 'K':
                         //MULTIPLE NUMERICAL QUESTION
                         if (trim($val) == '') {
                             $val = NULL;
                             // since some databases can't store blanks in numerical inputs
                         }
                         break;
                     default:
                         break;
                 }
                 if (is_null($val)) {
                     $setter[] = db_quote_id($key) . "=NULL";
                 } else {
                     $setter[] = db_quote_id($key) . "=" . db_quoteall($val, true);
                 }
             }
         }
         $query .= implode(', ', $setter);
         $query .= " WHERE ID=";
         if (isset($_SESSION['srid']) && $this->surveyOptions['active']) {
             $query .= $_SESSION['srid'];
             if (!db_execute_assoc($query)) {
                 echo submitfailed($connect->ErrorMsg());
                 if (($this->debugLevel & LEM_DEBUG_VALIDATION_SUMMARY) == LEM_DEBUG_VALIDATION_SUMMARY) {
                     $message .= 'Error in SQL update: ' . $connect->ErrorMsg() . '<br/>';
                 }
             }
             // Save Timings if needed
             if ($this->surveyOptions['savetimings']) {
                 set_answer_time();
             }
             if ($finished) {
                 // Delete the save control record if successfully finalize the submission
                 $query = "DELETE FROM " . db_table_name("saved_control") . " where srid=" . $_SESSION['srid'] . ' and sid=' . $this->sid;
                 $connect->Execute($query);
                 // Checked
                 if (($this->debugLevel & LEM_DEBUG_VALIDATION_SUMMARY) == LEM_DEBUG_VALIDATION_SUMMARY) {
                     $message .= ';<br/>' . $query;
                 }
             } elseif ($this->surveyOptions['allowsave'] && isset($_SESSION['scid'])) {
                 $connect->Execute("UPDATE " . db_table_name("saved_control") . " SET saved_thisstep=" . db_quoteall($thisstep) . " where scid=" . $_SESSION['scid']);
                 // Checked
             }
             // Check quotas whenever results are saved
             $bQuotaMatched = false;
             $aQuotas = check_quota('return', $this->sid);
             if ($aQuotas !== false) {
                 if ($aQuotas != false) {
                     foreach ($aQuotas as $aQuota) {
                         if (isset($aQuota['status']) && $aQuota['status'] == 'matched') {
                             $bQuotaMatched = true;
                         }
                     }
                 }
             }
             if ($bQuotaMatched) {
                 check_quota('enforce', $this->sid);
                 // will create a page and quit.
             } else {
                 if ($finished) {
                     $sQuery = 'UPDATE ' . $this->surveyOptions['tablename'] . " SET " . db_quote_id('submitdate') . "=" . db_quoteall($datestamp) . " WHERE ID=" . $_SESSION['srid'];
                     $connect->Execute($sQuery);
                     // Checked
                 }
             }
         }
         if (($this->debugLevel & LEM_DEBUG_VALIDATION_SUMMARY) == LEM_DEBUG_VALIDATION_SUMMARY) {
             $message .= $query;
         }
     }
     return $message;
 }
 /**
  * Write values to database.
  * @param <type> $updatedValues
  * @param <boolean> $finished - true if the survey needs to be finalized
  */
 private function _UpdateValuesInDatabase($updatedValues, $finished = false)
 {
     // Update these values in the database
     global $connect;
     $message = '';
     $_SESSION['datestamp'] = date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $this->surveyOptions['timeadjust']);
     if ($this->surveyOptions['active'] && !isset($_SESSION['srid'])) {
         // Create initial insert row for this record
         $today = date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $this->surveyOptions['timeadjust']);
         $sdata = array("datestamp" => $today, "ipaddr" => $this->surveyOptions['ipaddr'] && isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '', "startlanguage" => $this->surveyOptions['startlanguage'], "token" => $this->surveyOptions['token'], "datestamp" => $this->surveyOptions['datestamp'] ? $_SESSION['datestamp'] : NULL, "refurl" => $this->surveyOptions['refurl'] ? getenv("HTTP_REFERER") : NULL, "startdate" => $this->surveyOptions['datestamp'] ? $_SESSION['datestamp'] : date("Y-m-d H:i:s", 0));
         //One of the strengths of ADOdb's AutoExecute() is that only valid field names for $table are updated
         if ($connect->AutoExecute($this->surveyOptions['tablename'], $sdata, 'INSERT')) {
             $srid = $connect->Insert_ID($this->surveyOptions['tablename'], "id");
             $_SESSION['srid'] = $srid;
         } else {
             $message .= $this->gT("Unable to insert record into survey table: ") . $connect->ErrorMsg() . "<br/>";
             $_SESSION['flashmessage'] = $message;
             echo $message;
         }
         //Insert Row for Timings, if needed
         if ($this->surveyOptions['savetimings']) {
             $tdata = array('id' => $srid, 'interviewtime' => 0);
             if ($connect->AutoExecute($this->surveyOptions['tablename_timings'], $tdata, 'INSERT')) {
                 $trid = $connect->Insert_ID($this->surveyOptions['tablename_timings'], "sid");
             } else {
                 $message .= $this->gT("Unable to insert record into timings table ") . $connect->ErrorMsg() . "<br/>";
                 $_SESSION['flashmessage'] = $message;
                 echo $message;
             }
         }
     }
     if (count($updatedValues) > 0 || $finished) {
         $query = 'UPDATE ' . $this->surveyOptions['tablename'] . " SET ";
         $setter = array();
         switch ($this->surveyMode) {
             case 'question':
                 $thisstep = $this->currentQuestionSeq;
                 break;
             case 'group':
                 $thisstep = $this->currentGroupSeq;
                 break;
             case 'survey':
                 $thisstep = 1;
                 break;
         }
         $setter[] = db_quote_id('lastpage') . "=" . db_quoteall($thisstep);
         if ($this->surveyOptions['datestamp'] && isset($_SESSION['datestamp'])) {
             $setter[] = db_quote_id('datestamp') . "=" . db_quoteall($_SESSION['datestamp']);
         }
         if ($this->surveyOptions['ipaddr'] && isset($_SERVER['REMOTE_ADDR'])) {
             $setter[] = db_quote_id('ipaddr') . "=" . db_quoteall($_SERVER['REMOTE_ADDR']);
         }
         if ($finished) {
             $setter[] = db_quote_id('submitdate') . "=" . db_quoteall($_SESSION['datestamp']);
         }
         foreach ($updatedValues as $key => $value) {
             $val = is_null($value) ? NULL : $value['value'];
             $type = is_null($value) ? NULL : $value['type'];
             // Clean up the values to cope with database storage requirements
             switch ($type) {
                 case 'D':
                     //DATE
                     if (trim($val) == '') {
                         $val = NULL;
                         // since some databases can't store blanks in date fields
                     }
                     // otherwise will already be in yyyy-mm-dd format after ProcessCurrentResponses()
                     break;
                 case 'N':
                     //NUMERICAL QUESTION TYPE
                 //NUMERICAL QUESTION TYPE
                 case 'K':
                     //MULTIPLE NUMERICAL QUESTION
                     if (trim($val) == '') {
                         $val = NULL;
                         // since some databases can't store blanks in numerical inputs
                     }
                     break;
                 default:
                     break;
             }
             if (is_null($val)) {
                 $setter[] = db_quote_id($key) . "=NULL";
             } else {
                 $setter[] = db_quote_id($key) . "=" . db_quoteall($val);
             }
         }
         $query .= implode(', ', $setter);
         $query .= " WHERE ID=";
         if (isset($_SESSION['srid']) && $this->surveyOptions['active']) {
             $query .= $_SESSION['srid'];
             if (!db_execute_assoc($query)) {
                 echo submitfailed($connect->ErrorMsg());
                 if (($this->debugLevel & LEM_DEBUG_VALIDATION_SUMMARY) == LEM_DEBUG_VALIDATION_SUMMARY) {
                     $message .= 'Error in SQL update: ' . $connect->ErrorMsg() . '<br/>';
                 }
             }
             // Save Timings if needed
             if ($this->surveyOptions['savetimings']) {
                 set_answer_time();
             }
             if ($finished) {
                 // Delete the save control record if successfully finalize the submission
                 $query = "DELETE FROM " . db_table_name("saved_control") . " where srid=" . $_SESSION['srid'] . ' and sid=' . $this->sid;
                 $connect->Execute($query);
                 // Checked
                 if (($this->debugLevel & LEM_DEBUG_VALIDATION_SUMMARY) == LEM_DEBUG_VALIDATION_SUMMARY) {
                     $message .= ';<br/>' . $query;
                 }
                 // Check Quotas
                 $bQuotaMatched = false;
                 $aQuotas = check_quota('return', $this->sid);
                 if ($aQuotas !== false) {
                     if ($aQuotas != false) {
                         foreach ($aQuotas as $aQuota) {
                             if (isset($aQuota['status']) && $aQuota['status'] == 'matched') {
                                 $bQuotaMatched = true;
                             }
                         }
                     }
                 }
                 if ($bQuotaMatched) {
                     check_quota('enforce', $this->sid);
                     // will create a page and quit.
                 }
             } else {
                 if ($this->surveyOptions['allowsave'] && isset($_SESSION['scid'])) {
                     $connect->Execute("UPDATE " . db_table_name("saved_control") . " SET saved_thisstep=" . db_quoteall($thisstep) . " where scid=" . $_SESSION['scid']);
                     // Checked
                 }
             }
         }
         if (($this->debugLevel & LEM_DEBUG_VALIDATION_SUMMARY) == LEM_DEBUG_VALIDATION_SUMMARY) {
             $message .= $query;
         }
     }
     return $message;
 }
 $datetimeobj = new Date_Time_Converter($rows['datecreated'], "Y-m-d H:i:s");
 $datecreated = $datetimeobj->convert($dateformatdetails['phpdate']);
 if (in_array($rows['owner_id'], getuserlist('onlyuidarray'))) {
     $ownername = $rows['users_name'];
 } else {
     $ownername = "---";
 }
 $questionsCount = 0;
 $questionsCountQuery = "SELECT * FROM " . db_table_name('questions') . " WHERE sid={$rows['sid']} AND language='" . $rows['language'] . "'";
 //Getting a count of questions for this survey
 $questionsCountResult = $connect->Execute($questionsCountQuery);
 //Checked
 $questionsCount = $questionsCountResult->RecordCount();
 $listsurveys .= "<tr>";
 if ($rows['active'] == "Y") {
     if ($rows['expires'] != '' && $rows['expires'] < date_shift(date("Y-m-d H:i:s"), "Y-m-d", $timeadjust)) {
         $listsurveys .= "<td><img src='{$imageurl}/expired.png' " . "alt='" . $clang->gT("This survey is active but expired.") . "' /></td>";
     } else {
         if (bHasSurveyPermission($rows['sid'], 'surveyactivation', 'update')) {
             $listsurveys .= "<td><a href=\"#\" onclick=\"window.open('{$scriptname}?action=deactivate&amp;sid={$rows['sid']}', '_top')\"" . " title=\"" . $clang->gTview("This survey is active - click here to deactivate this survey.") . "\" >" . "<img src='{$imageurl}/active.png' alt='" . $clang->gT("This survey is active - click here to deactivate this survey.") . "' /></a></td>\n";
         } else {
             $listsurveys .= "<td><img src='{$imageurl}/active.png' " . "alt='" . $clang->gT("This survey is currently active.") . "' /></td>\n";
         }
     }
 } else {
     if ($questionsCount > 0 && bHasSurveyPermission($rows['sid'], 'surveyactivation', 'update')) {
         $listsurveys .= "<td><a href=\"#\" onclick=\"window.open('{$scriptname}?action=activate&amp;sid={$rows['sid']}', '_top')\"" . " title=\"" . $clang->gTview("This survey is currently not active - click here to activate this survey.") . "\" >" . "<img src='{$imageurl}/inactive.png' title='' alt='" . $clang->gT("This survey is currently not active - click here to activate this survey.") . "' /></a></td>\n";
     } else {
         $listsurveys .= "<td><img src='{$imageurl}/inactive.png'" . " title='" . $clang->gT("This survey is currently not active.") . "' alt='" . $clang->gT("This survey is currently not active.") . "' />" . "</td>\n";
     }
 }
Example #14
0
function savedcontrol()
{
    //This data will be saved to the "saved_control" table with one row per response.
    // - a unique "saved_id" value (autoincremented)
    // - the "sid" for this survey
    // - the "srid" for the survey_x row id
    // - "saved_thisstep" which is the step the user is up to in this survey
    // - "saved_ip" which is the ip address of the submitter
    // - "saved_date" which is the date ofthe saved response
    // - an "identifier" which is like a username
    // - a "password"
    // - "fieldname" which is the fieldname of the saved response
    // - "value" which is the value of the response
    //We start by generating the first 5 values which are consistent for all rows.
    global $connect, $surveyid, $dbprefix, $thissurvey, $errormsg, $publicurl, $sitename, $timeadjust, $clang, $clienttoken, $thisstep;
    //Check that the required fields have been completed.
    $errormsg = "";
    /* queXS Removal
    
            if (!isset($_POST['savename']) || !$_POST['savename']) {$errormsg.=$clang->gT("You must supply a name for this saved session.")."<br />\n";}
            if (!isset($_POST['savepass']) || !$_POST['savepass']) {$errormsg.=$clang->gT("You must supply a password for this saved session.")."<br />\n";}
            if ((isset($_POST['savepass']) && !isset($_POST['savepass2'])) || $_POST['savepass'] != $_POST['savepass2'])
            {$errormsg.=$clang->gT("Your passwords do not match.")."<br />\n";}
            // if security question asnwer is incorrect
            if (function_exists("ImageCreate") && captcha_enabled('saveandloadscreen',$thissurvey['usecaptcha']))
            {
                if (!isset($_POST['loadsecurity']) ||
                !isset($_SESSION['secanswer']) ||
                $_POST['loadsecurity'] != $_SESSION['secanswer'])
                {
                    $errormsg .= $clang->gT("The answer to the security question is incorrect.")."<br />\n";
                }
            }
    
            if (trim($_POST['saveemail'])!='' && !validate_email($_POST['saveemail']))
            {
                $errormsg .= $clang->gT("The email address is not valid. Please leave the email field blank or give a valid email address.")."<br />\n";
            }
    
    	end queXS Removal */
    if ($errormsg) {
        return;
    }
    //All the fields are correct. Now make sure there's not already a matching saved item
    $query = "SELECT COUNT(*) FROM {$dbprefix}saved_control\n" . "WHERE sid={$surveyid}\n" . "AND identifier=" . db_quoteall($_POST['token'], true);
    $result = db_execute_num($query) or safe_die("Error checking for duplicates!<br />{$query}<br />" . $connect->ErrorMsg());
    // Checked
    list($count) = $result->FetchRow();
    if ($count == 1) {
        //we should update the field with the latest $_SESSION['step'] - stored in saved_thisstep - queXS addition
        $sql = "UPDATE {$dbprefix}saved_control SET saved_thisstep = '{$_SESSION['step']}' WHERE sid={$surveyid} AND identifier='{$_POST['token']}'";
        $connect->Execute($sql);
    } else {
        if ($count > 0) {
            $errormsg .= $clang->gT("This name has already been used for this survey. You must use a unique save name.") . "<br />\n";
            return;
        } else {
            //INSERT BLANK RECORD INTO "survey_x" if one doesn't already exist
            if (!isset($_SESSION['srid'])) {
                $today = date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust);
                $sdata = array("datestamp" => $today, "ipaddr" => getIPAddress(), "startlanguage" => $_SESSION['s_lang'], "refurl" => getenv("HTTP_REFERER"), "token" => $_POST['token']);
                //One of the strengths of ADOdb's AutoExecute() is that only valid field names for $table are updated
                if ($connect->AutoExecute($thissurvey['tablename'], $sdata, 'INSERT')) {
                    $srid = $connect->Insert_ID($thissurvey['tablename'], "sid");
                    $_SESSION['srid'] = $srid;
                } else {
                    safe_die("Unable to insert record into survey table.<br /><br />" . $connect->ErrorMsg());
                }
            }
            //CREATE ENTRY INTO "saved_control"
            $today = date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust);
            $scdata = array("sid" => $surveyid, "srid" => $_SESSION['srid'], "identifier" => $_POST['token'], "access_code" => md5($_POST['token']), "email" => $_POST['token'], "ip" => getIPAddress(), "refurl" => getenv("HTTP_REFERER"), "saved_thisstep" => $thisstep, "status" => "S", "saved_date" => $today);
            if ($connect->AutoExecute("{$dbprefix}saved_control", $scdata, 'INSERT')) {
                $scid = $connect->Insert_ID("{$dbprefix}saved_control", 'scid');
                $_SESSION['scid'] = $scid;
            } else {
                safe_die("Unable to insert record into saved_control table.<br /><br />" . $connect->ErrorMsg());
            }
            $_SESSION['holdname'] = $_POST['token'];
            //Session variable used to load answers every page. Unsafe - so it has to be taken care of on output
            $_SESSION['holdpass'] = $_POST['token'];
            //Session variable used to load answers every page.  Unsafe - so it has to be taken care of on output
            /* queXS Removal
            
                        //Email if needed
                        if (isset($_POST['saveemail']) && validate_email($_POST['saveemail']))
                        {
                            $subject=$clang->gT("Saved Survey Details") . " - " . $thissurvey['name'];
                            $message=$clang->gT("Thank you for saving your survey in progress.  The following details can be used to return to this survey and continue where you left off.  Please keep this e-mail for your reference - we cannot retrieve the password for you.","unescaped");
                            $message.="\n\n".$thissurvey['name']."\n\n";
                            $message.=$clang->gT("Name","unescaped").": ".$_POST['savename']."\n";
                            $message.=$clang->gT("Password","unescaped").": ".$_POST['savepass']."\n\n";
                            $message.=$clang->gT("Reload your survey by clicking on the following link (or pasting it into your browser):","unescaped")."\n";
                            $message.=$publicurl."/index.php?sid=$surveyid&loadall=reload&scid=".$scid."&loadname=".urlencode($_POST['savename'])."&loadpass="******"&token=".$clienttoken;}
                            $from="{$thissurvey['adminname']} <{$thissurvey['adminemail']}>";
                            if (SendEmailMessage(null, $message, $subject, $_POST['saveemail'], $from, $sitename, false, getBounceEmail($surveyid)))
                            {
                                $emailsent="Y";
                            }
                            else
                            {
                                echo $clang->gT('Error: Email failed, this may indicate a PHP Mail Setup problem on the server. Your survey details have still been saved, however you will not get an email with the details. You should note the "name" and "password" you just used for future reference.');
                            }
                        }
            
            		end queXS Removal */
            return $clang->gT('Your survey was successfully saved.');
        }
    }
}
function globalsettingsdisplay()
{
    global $action, $connect, $js_admin_includes, $editsurvey, $subaction, $scriptname, $clang;
    global $updateversion, $updatebuild, $updateavailable, $updatelastcheck, $demoModeOnly;

    if (isset($subaction) && $subaction == "updatecheck")
    {
        $updateinfo=updatecheck();
    }

    if (isset($action) && $action == "globalsettings")
    {
        if($_SESSION['USER_RIGHT_SUPERADMIN'] == 1)
        {
            $js_admin_includes[]='scripts/globalsettings.js';
            // header
            $editsurvey = "<div class='header ui-widget-header'>".$clang->gT("Global settings")."</div>\n";
            // beginning TABs section
            $editsurvey .= "\t<div id='tabs'>
            <ul>
            <li><a href='#overview'>".$clang->gT("Overview & update")."</a></li>
            <li><a href='#general'>".$clang->gT("General")."</a></li>
            <li><a href='#email'>".$clang->gT("Email settings")."</a></li>
            <li><a href='#bounce'>".$clang->gT("Bounce settings")."</a></li>
            <li><a href='#security'>".$clang->gT("Security")."</a></li>
            <li><a href='#presentation'>".$clang->gT("Presentation")."</a></li>
            </ul>\n";
            $editsurvey .= "<form class='form30' id='frmglobalsettings' name='frmglobalsettings' action='$scriptname' method='post'>\n";
            $editsurvey .= "<div id='overview'>\n";
            $editsurvey .= checksettings();
            $thisupdatecheckperiod=getGlobalSetting('updatecheckperiod');
            $editsurvey .= "<br /></p><div class='header ui-widget-header'>".$clang->gT("Updates")."</div><ul>"
            . "\t<li><label for='updatecheckperiod'>".$clang->gT("Check for updates:")."</label>\n"
            . "\t\t\t<select name='updatecheckperiod' id='updatecheckperiod'>\n"
            . "\t\t\t\t<option value='0'";
            if ($thisupdatecheckperiod==0) {$editsurvey .= " selected='selected'";}
            $editsurvey .=">".$clang->gT("Never")."</option>\n"
            . "\t\t\t\t<option value='1'";
            if ($thisupdatecheckperiod==1) {$editsurvey .= " selected='selected'";}
            $editsurvey .=">".$clang->gT("Every day")."</option>\n"
            . "\t\t\t\t<option value='7'";
            if ($thisupdatecheckperiod==7) {$editsurvey .= " selected='selected'";}
            $editsurvey .=">".$clang->gT("Every week")."</option>\n"
            . "<option value='14'";
            if ($thisupdatecheckperiod==14) {$editsurvey .= " selected='selected'";}
            $editsurvey .=">".$clang->gT("Every 2 weeks")."</option>\n"
            . "<option value='30'";
            if ($thisupdatecheckperiod==30) {$editsurvey .= " selected='selected'";}
            $editsurvey .=">".$clang->gT("Every month")."</option>\n"
            . "</select>&nbsp;<input type='button' onclick=\"window.open('$scriptname?action=globalsettings&amp;subaction=updatecheck', '_top')\" value='".$clang->gT("Check now")."' />&nbsp;<span id='lastupdatecheck'>".sprintf($clang->gT("Last check: %s"),$updatelastcheck)."</span></li></ul><p>\n";

            if (isset($updateavailable) && $updateavailable==1)
            {
                $editsurvey .='<span style="font-weight: bold;">'.sprintf($clang->gT('There is a LimeSurvey update available: Version %s'),$updateversion."($updatebuild)").'</span><br />';
                $editsurvey .=sprintf($clang->gT('You can update %smanually%s or use the %s'),"<a href='http://docs.limesurvey.org/tiki-index.php?page=Upgrading+from+a+previous+version'>","</a>","<a href='$scriptname?action=update'>".$clang->gT('3-Click ComfortUpdate').'</a>').'.<br />';
            }
            elseif (isset($updateinfo['errorcode']))
            {
                $editsurvey .=sprintf($clang->gT('There was an error on update check (%s)'),$updateinfo['errorcode']).'.<br />';
                $editsurvey .="<textarea readonly='readonly' style='width:35%; height:60px; overflow: auto;'>".strip_tags($updateinfo['errorhtml']).'</textarea>';

            }
            else
            {
                $editsurvey .=$clang->gT('There is currently no newer LimeSurvey version available.');
            }
            $editsurvey .= "</p></div>";



            // General TAB
            $editsurvey .= "\t<div id='general'>\n";
            // Administrator...
            $editsurvey .= "<ul>"
            . "\t<li><label for='sitename'>".$clang->gT("Site name:").(($demoModeOnly==true)?'*':'')."</label>\n"
            . "\t\t<input type='text' size='50' id='sitename' name='sitename' value=\"".htmlspecialchars(getGlobalSetting('sitename'))."\" /></li>\n"
            . "\t<li><label for='defaultlang'>".$clang->gT("Default site language:").(($demoModeOnly==true)?'*':'')."</label>\n"
            . "\t\t<select name='defaultlang' id='defaultlang'>\n";
            $actuallang=getGlobalSetting('defaultlang');
            foreach (getLanguageData(true) as  $langkey2=>$langname)
            {
                $editsurvey .= "\t\t\t<option value='".$langkey2."'";
                if ($actuallang == $langkey2) {$editsurvey .= " selected='selected'";}
                $editsurvey .= ">".$langname['nativedescription']." - ".$langname['description']."</option>\n";
            }

            $editsurvey .= "\t\t</select></li>";

            $thisdefaulttemplate=getGlobalSetting('defaulttemplate');
            $templatenames=array_keys(gettemplatelist());
            $editsurvey .= ""
            . "\t<li><label for='defaulttemplate'>".$clang->gT("Default template:")."</label>\n"
            . "\t\t\t<select name='defaulttemplate' id='defaulttemplate'>\n";
            foreach ($templatenames as $templatename)
            {
                $editsurvey.= "\t\t\t\t<option value='$templatename'";
                if ($thisdefaulttemplate==$templatename) {$editsurvey .= " selected='selected'";}
                $editsurvey .=">$templatename</option>\n";
            }
            $editsurvey .="\t\t\t</select></li>\n";


            $thisdefaulthtmleditormode=getGlobalSetting('defaulthtmleditormode');
            $editsurvey .= ""
            . "\t<li><label for='defaulthtmleditormode'>".$clang->gT("Default HTML editor mode:").(($demoModeOnly==true)?'*':'')."</label>\n"
            . "\t\t\t<select name='defaulthtmleditormode' id='defaulthtmleditormode'>\n"
            . "\t\t\t\t<option value='default'";
            if ($thisdefaulthtmleditormode=='default') {$editsurvey .= " selected='selected'";}
            $editsurvey .=">".$clang->gT("Default HTML editor mode")."</option>\n"
            . "\t\t\t\t<option value='none'";
            if ($thisdefaulthtmleditormode=='none') {$editsurvey .= " selected='selected'";}
            $editsurvey .=">".$clang->gT("No HTML editor")."</option>\n"
            . "<option value='inline'";
            if ($thisdefaulthtmleditormode=='inline') {$editsurvey .= " selected='selected'";}
            $editsurvey .=">".$clang->gT("Inline HTML editor")."</option>\n"
            . "<option value='popup'";
            if ($thisdefaulthtmleditormode=='popup') {$editsurvey .= " selected='selected'";}
            $editsurvey .=">".$clang->gT("Popup HTML editor")."</option>\n"
            . "</select></li>\n";

            $dateformatdata=getDateFormatData($_SESSION['dateformat']);
            $editsurvey.= "\t<li><label for='timeadjust'>".$clang->gT("Time difference (in hours):")."</label>\n"
            . "\t\t<span><input type='text' size='10' id='timeadjust' name='timeadjust' value=\"".htmlspecialchars(str_replace(array('+',' hours'),array('',''),getGlobalSetting('timeadjust')))."\" /> "
            . $clang->gT("Server time:").' '.convertDateTimeFormat(date('Y-m-d H:i:s'),'Y-m-d H:i:s',$dateformatdata['phpdate'].' H:i')." - ".$clang->gT("Corrected time :").' '.convertDateTimeFormat(date_shift(date("Y-m-d H:i:s"), 'Y-m-d H:i:s', getGlobalSetting('timeadjust')),'Y-m-d H:i:s',$dateformatdata['phpdate'].' H:i')."
            </span></li>\n";

            $thisusepdfexport=getGlobalSetting('usepdfexport');
            $editsurvey .= "\t<li><label for='usepdfexport'>".$clang->gT("PDF export available:")."</label>\n"
            . "<select name='usepdfexport' id='usepdfexport'>\n"
            . "<option value='1'";
            if ( $thisusepdfexport == true) {$editsurvey .= " selected='selected'";}
            $editsurvey .= ">".$clang->gT("On")."</option>\n"
            . "<option value='0'";
            if ( $thisusepdfexport == false) {$editsurvey .= " selected='selected'";}
            $editsurvey .= ">".$clang->gT("Off")."</option>\n"
            . "\t\t</select>\n\t</li>\n";

            $thisaddTitleToLinks=getGlobalSetting('addTitleToLinks');
            $editsurvey .= "\t<li><label for='addTitleToLinks'>".$clang->gT("Screen reader compatibility mode:")."</label>\n"
            . "<select name='addTitleToLinks' id='addTitleToLinks'>\n"
            . "<option value='1'";
            if ( $thisaddTitleToLinks == true) {$editsurvey .= " selected='selected'";}
            $editsurvey .= ">".$clang->gT("On")."</option>\n"
            . "<option value='0'";
            if ( $thisaddTitleToLinks == false) {$editsurvey .= " selected='selected'";}
            $editsurvey .= ">".$clang->gT("Off")."</option>\n"
            . "</select>\n</li>\n"
            . "<li><label for='sessionlifetime'>".$clang->gT("Session lifetime (seconds):")."</label>\n"
            . "<input type='text' size='10' id='sessionlifetime' name='sessionlifetime' value=\"".htmlspecialchars(getGlobalSetting('sessionlifetime'))."\" /></li>"
            . "<li><label for='ipInfoDbAPIKey'>".$clang->gT("IP Info DB API Key:")."</label>\n"
            . "<input type='text' size='35' id='ipInfoDbAPIKey' name='ipInfoDbAPIKey' value=\"".htmlspecialchars(getGlobalSetting('ipInfoDbAPIKey'))."\" /></li>"
            . "<li><label for='googleMapsAPIKey'>".$clang->gT("Google Maps API key:")."</label>\n"
            . "<input type='text' size='35' id='googleMapsAPIKey' name='googleMapsAPIKey' value=\"".htmlspecialchars(getGlobalSetting('googleMapsAPIKey'))."\" /></li>"

                    ;


            // End General TAB

            $editsurvey .= "\t</ul></div>\n";

            // Email TAB
            $editsurvey .= "\t<div id='email'><ul>\n";
			 //Format
            $editsurvey.= "\t<li><label for='siteadminemail'>".$clang->gT("Default site admin email:")."</label>\n"
            . "\t\t<input type='text' size='50' id='siteadminemail' name='siteadminemail' value=\"".htmlspecialchars(getGlobalSetting('siteadminemail'))."\" /></li>\n"

            . "\t<li><label for='siteadminname'>".$clang->gT("Administrator name:")."</label>\n"
            . "\t\t<input type='text' size='50' id='siteadminname' name='siteadminname' value=\"".htmlspecialchars(getGlobalSetting('siteadminname'))."\" /><br /><br /></li>\n"
            . "\t<li><label for='emailmethod'>".$clang->gT("Email method:")."</label>\n"
            . "\t\t<select id='emailmethod' name='emailmethod'>\n"
            . "\t\t\t<option value='mail'";
            if (getGlobalSetting('emailmethod')=='mail') {$editsurvey .= " selected='selected'";}
            $editsurvey .= ">".$clang->gT("PHP (default)")."</option>\n"
            . "\t\t\t<option value='smtp'";
            if (getGlobalSetting('emailmethod')=='smtp') {$editsurvey .= " selected='selected'";}
            $editsurvey .= ">".$clang->gT("SMTP")."</option>\n"
            . "\t\t\t<option value='sendmail'";
            if (getGlobalSetting('emailmethod')=='sendmail') {$editsurvey .= " selected='selected'";}
            $editsurvey .= ">".$clang->gT("Sendmail")."</option>\n"
            . "\t\t\t<option value='qmail'";
            if (getGlobalSetting('emailmethod')=='qmail') {$editsurvey .= " selected='selected'";}
            $editsurvey .= ">".$clang->gT("Qmail")."</option>\n"
            . "\t\t</select></li>\n"
            . "\t<li>\n\t\t<label for=\"emailsmtphost\">".$clang->gT("SMTP host:")."</label>\n"
            . "\t\t<input type='text' size='50' id='emailsmtphost' name='emailsmtphost' value=\"".htmlspecialchars(getGlobalSetting('emailsmtphost'))."\" />&nbsp;<font size='1'>".$clang->gT("Enter your hostname and port, e.g.: my.smtp.com:25")."</font></li>\n"
            . "\t<li><label for='emailsmtpuser'>".$clang->gT("SMTP username:"******"</label>\n"
            . "\t\t<input type='text' size='50' id='emailsmtpuser' name='emailsmtpuser' value=\"".htmlspecialchars(getGlobalSetting('emailsmtpuser'))."\" /></li>\n"
            . "\t<li><label for='emailsmtppassword'>".$clang->gT("SMTP password:"******"</label>\n"
            . "\t\t<input type='password' size='50' id='emailsmtppassword' name='emailsmtppassword' value='somepassword' /></li>\n"
            . "\t<li><label for='emailsmtpssl'>".$clang->gT("SMTP SSL/TLS:")."</label>\n"
            . "\t\t<select id='emailsmtpssl' name='emailsmtpssl'>\n"
            . "\t\t\t<option value=''";
            if (getGlobalSetting('emailsmtpssl')=='') {$editsurvey .= " selected='selected'";}
            $editsurvey .= ">".$clang->gT("Off")."</option>\n"
            . "\t\t\t<option value='ssl'";
            if (getGlobalSetting('emailsmtpssl')=='ssl' || getGlobalSetting('emailsmtpssl')==1) {$editsurvey .= " selected='selected'";}
            $editsurvey .= ">".$clang->gT("SSL")."</option>\n"
            . "\t\t\t<option value='tls'";
            if (getGlobalSetting('emailsmtpssl')=='tls') {$editsurvey .= " selected='selected'";}
            $editsurvey .= ">".$clang->gT("TLS")."</option>\n"
            . "\t\t</select></li>\n"
            . "\t<li><label for='emailsmtpdebug'>".$clang->gT("SMTP debug mode:")."</label>\n"
            . "\t\t<select id='emailsmtpdebug' name='emailsmtpdebug'>\n"
            . "\t\t\t<option value=''";
            if (getGlobalSetting('emailsmtpdebug')=='0') {$editsurvey .= " selected='selected'";}
            $editsurvey .= ">".$clang->gT("Off")."</option>\n"
            . "\t\t\t<option value='1'";
            if (getGlobalSetting('emailsmtpdebug')=='1' || getGlobalSetting('emailsmtpssl')==1) {$editsurvey .= " selected='selected'";}
            $editsurvey .= ">".$clang->gT("On errors")."</option>\n"
            . "\t\t\t<option value='2'";
            if (getGlobalSetting('emailsmtpdebug')=='2' || getGlobalSetting('emailsmtpssl')==1) {$editsurvey .= " selected='selected'";}
            $editsurvey .= ">".$clang->gT("Always")."</option>\n"
            . "\t\t</select><br />&nbsp;</li>\n"
            . "\t<li><label for='maxemails'>".$clang->gT("Email batch size:")."</label>\n"
            . "\t\t<input type='text' size='5' id='maxemails' name='maxemails' value=\"".htmlspecialchars(getGlobalSetting('maxemails'))."\" /></li>\n"
            . "\t</ul>\n";
            // End Email TAB
            $editsurvey .= "\t</div>\n";
            // Start bounce tab
            $editsurvey .= "\t<div id='bounce'><ul>\n"
            . "\t<li><label for='siteadminbounce'>".$clang->gT("Default site bounce email:")."</label>\n"
            . "\t\t<input type='text' size='50' id='siteadminbounce' name='siteadminbounce' value=\"".htmlspecialchars(getGlobalSetting('siteadminbounce'))."\" /></li>\n"
            . "\t<li><label for='bounceaccounttype'>".$clang->gT("Server type:")."</label>\n"
	        . "\t\t<select id='bounceaccounttype' name='bounceaccounttype'>\n"
  	        . "\t\t\t<option value='off'";
            if (getGlobalSetting('bounceaccounttype')=='off') {$editsurvey .= " selected='selected'";}
            $editsurvey .= ">".$clang->gT("Off")."</option>\n"
            . "\t\t\t<option value='IMAP'";
            if (getGlobalSetting('bounceaccounttype')=='IMAP') {$editsurvey .= " selected='selected'";}
            $editsurvey .= ">".$clang->gT("IMAP")."</option>\n"
            . "\t\t\t<option value='POP'";
            if (getGlobalSetting('bounceaccounttype')=='POP') {$editsurvey .= " selected='selected'";}
            $editsurvey .= ">".$clang->gT("POP")."</option>\n"
            ."\t\t</select></li>\n"

            . "\t<li><label for='bounceaccounthost'>".$clang->gT("Server name & port:")."</label>\n"
            . "\t\t<input type='text' size='50' id='bounceaccounthost' name='bounceaccounthost' value=\"".htmlspecialchars(getGlobalSetting('bounceaccounthost'))."\" />\n"."<font size='1'>".$clang->gT("Enter your hostname and port, e.g.: imap.gmail.com:995")."</font>\n"

            . "\t<li><label for='bounceaccountuser'>".$clang->gT("User name:")."</label>\n"
            . "\t\t<input type='text' size='50' id='bounceaccountuser' name='bounceaccountuser' value=\"".htmlspecialchars(getGlobalSetting('bounceaccountuser'))."\" /></li>\n"
            . "\t<li><label for='bounceaccountpass'>".$clang->gT("Password:"******"</label>\n"
            . "\t\t<input type='password' size='50' id='bounceaccountpass' name='bounceaccountpass' value='enteredpassword' /></li>\n";
	    $editsurvey.= "\t<li><label for='bounceencryption'>".$clang->gT("Encryption type:")."</label>\n"
	    . "\t\t<select id='bounceencryption' name='bounceencryption'>\n"
  	    . "\t\t\t<option value='off'";
            if (getGlobalSetting('bounceencryption')=='off') {$editsurvey .= " selected='selected'";}
            $editsurvey .= ">".$clang->gT("Off")."</option>\n"
            . "\t\t\t<option value='SSL'";
            if (getGlobalSetting('bounceencryption')=='SSL') {$editsurvey .= " selected='selected'";}
            $editsurvey .= ">".$clang->gT("SSL")."</option>\n"
            . "\t\t\t<option value='TLS'";
            if (getGlobalSetting('bounceencryption')=='TLS') {$editsurvey .= " selected='selected'";}
            $editsurvey .= ">".$clang->gT("TLS")."</option>\n"
            ."\t\t</select></li>\n</ul>";
            $editsurvey .= "\t</div>\n";
            // End of bounce tabs
            // Security Settings
            $editsurvey .= "\t<div id='security'><ul>\n";
            // Expiration
            $thissurveyPreview_require_Auth=getGlobalSetting('surveyPreview_require_Auth');
            $editsurvey .= "\t<li><label for='surveyPreview_require_Auth'>".$clang->gT("Survey preview only for administration users")."</label>\n"
            . "\t\t<select id='surveyPreview_require_Auth' name='surveyPreview_require_Auth'>\n"
            . "\t\t\t<option value='1'";
            if ($thissurveyPreview_require_Auth == true) {$editsurvey .= " selected='selected'";}
            $editsurvey .= ">".$clang->gT("Yes")."</option>\n"
            . "\t\t\t<option value='0'";
            if ($thissurveyPreview_require_Auth == false) {$editsurvey .= " selected='selected'";}
            $editsurvey .= ">".$clang->gT("No")."</option>\n"
            . "\t\t</select></li>\n";

            // Auto registration
            $thisfilterxsshtml=getGlobalSetting('filterxsshtml');
            $editsurvey .= "\t<li><label for='filterxsshtml'>".$clang->gT("Filter HTML for XSS:").(($demoModeOnly==true)?'*':'')."</label>\n"
            . "\t\t<select id='filterxsshtml' name='filterxsshtml'>\n"
            . "\t\t\t<option value='1'";
            if ( $thisfilterxsshtml == true) {$editsurvey .= " selected='selected'";}
            $editsurvey .= ">".$clang->gT("Yes")."</option>\n"
            . "\t\t\t<option value='0'";
            if ( $thisfilterxsshtml == false) {$editsurvey .= " selected='selected'";}
            $editsurvey .= ">".$clang->gT("No")."</option>\n"
            . "\t\t</select></li>\n";

            $thisusercontrolSameGroupPolicy=getGlobalSetting('usercontrolSameGroupPolicy');
            $editsurvey .= "\t<li><label for='usercontrolSameGroupPolicy'>".$clang->gT("Group member can only see own group:")."</label>\n"
            . "\t\t<select id='usercontrolSameGroupPolicy' name='usercontrolSameGroupPolicy'>\n"
            . "\t\t\t<option value='1'";
            if ( $thisusercontrolSameGroupPolicy == true) {$editsurvey .= " selected='selected'";}
            $editsurvey .= ">".$clang->gT("Yes")."</option>\n"
            . "\t\t\t<option value='0'";
            if ( $thisusercontrolSameGroupPolicy == false) {$editsurvey .= " selected='selected'";}
            $editsurvey .= ">".$clang->gT("No")."</option>\n"
            . "\t\t</select></li>\n";

            $thisforce_ssl = getGlobalSetting('force_ssl');
	    $opt_force_ssl_on = $opt_force_ssl_off = $opt_force_ssl_neither = '';
	    $warning_force_ssl = $clang->gT('Warning: Before turning on HTTPS, ')
	    . '<a href="https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].'"title="'
	    . $clang->gT('Test if your server has SSL enabled by clicking on this link.').'">'
	    . $clang->gT('check if this link works.').'</a><br/> '
	    . $clang->gT("If the link does not work and you turn on HTTPS, LimeSurvey will break and you won't be able to access it.");
//	    $warning_force_ssl = ' Do <strong>NOT</strong> force "On" if you\'re <strong>not completely certain</strong> your server has a SSL enabled. <br />'
//	    . 'Before turning on HTTPS, <a href="https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].'">See if this link works</a><br />'
//	    . 'If not, <strong>LimeSurvey will break</strong> if SSL is forced on but your server does not have a valid secure certificate installed and enabled.<br />';
	    switch($thisforce_ssl)
	    {
	    	case 'on':
		    $warning_force_ssl = '&nbsp;';
		    break;
		case 'off':
		case 'neither':
		    break;
	    	default:
		    $thisforce_ssl = 'neither';
	    };
	    $this_opt = 'opt_force_ssl_'.$thisforce_ssl;
	    $$this_opt = ' selected="selected"';
	    $editsurvey .= '<li><label for="force_ssl">'.$clang->gT('Force HTTPS:')."</label>\n"
	    . "<select name=\"force_ssl\" id=\"force_ssl\">\n\t"
            . '<option value="on" '.$opt_force_ssl_on.'>'.$clang->gT('On')."</option>\n\t"
            . '<option value="off" '.$opt_force_ssl_off.'>'.$clang->gT('Off')."</option>\n\t"
            . '<option value="neither" '.$opt_force_ssl_neither.'>'.$clang->gT('Don\'t force on or off')."</option>\n\t"
	    . "</select></li>\n"
	    . "<li><span style='font-size:0.7em;'>$warning_force_ssl\n</span></li>\n";
	    unset($thisforce_ssl,$opt_force_ssl_on,$opt_force_ssl_off,$opt_force_ssl_neither,$warning_force_ssl,$this_opt);


        $editsurvey .= "\t</ul></div>\n";

        // presentation settings tab
        $editsurvey .= "\t<div id='presentation'><ul>\n";
        // shownoanswer
        $shownoanswer=getGlobalSetting('shownoanswer');
	    $sel_na = array( 0 => '' , 1 => '' , 2 => '');
	    $sel_na[$shownoanswer] = ' selected="selected"';
        $editsurvey .= "\t<li><label for='shownoanswer'>".$clang->gT("Show 'no answer' option for non-mandatory questions:")."</label>\n"
        . "\t\t<select id='shownoanswer' name='shownoanswer'>\n"
        . "\t\t\t<option value=\"1\"{$sel_na[1]}>".$clang->gT('Yes')."</option>\n"
        . "\t\t\t<option value=\"0\"{$sel_na[0]}>".$clang->gT('No')."</option>\n"
        . "\t\t\t<option value=\"2\"{$sel_na[2]}>".$clang->gT('Survey admin can choose')."</option>\n"
        . "\t\t</select></li>\n";

        $thisrepeatheadings=getGlobalSetting('repeatheadings');
        $editsurvey .= "\t<li><label for='repeatheadings'>".$clang->gT("Repeating headings in array questions every X subquestions:")."</label>\n"
        . "\t\t<input id='repeatheadings' name='repeatheadings' value='$thisrepeatheadings' size='4' maxlength='4' /></li>\n";


        // showXquestions
        $set_xq=getGlobalSetting('showXquestions');
	    $sel_xq = array( 'hide' => '' , 'show' => '' , 'choose' => '');
	    $sel_xq[$set_xq] = ' selected="selected"';
	    if( empty($sel_xq['hide']) && empty($sel_xq['show']) && empty($sel_xq['choose']))
	    {
	    	$sel_xq['choose'] = ' selected="selected"';
	    };
            $editsurvey .= "\t<li><label for=\"showXquestions\">".$clang->gT('Show "There are X questions in this survey"')."</label>\n"
            . "\t\t<select id=\"showXquestions\" name=\"showXquestions\">\n"
            . "\t\t\t<option value=\"show\"{$sel_xq['show']}>".$clang->gT('Yes')."</option>\n"
            . "\t\t\t<option value=\"hide\"{$sel_xq['hide']}>".$clang->gT('No')."</option>\n"
            . "\t\t\t<option value=\"choose\"{$sel_xq['choose']}>".$clang->gT('Survey admin can choose')."</option>\n"
            . "\t\t</select></li>\n";
	    unset($set_xq,$sel_xq);






	    // showgroupinfo
            $set_gri=getGlobalSetting('showgroupinfo');
	    $sel_gri = array( 'both' => '' , 'choose' =>'' , 'description' => '' , 'name' => '' , 'none' => '' );
	    $sel_gri[$set_gri] = ' selected="selected"';
	    if( empty($sel_gri['both']) && empty($sel_gri['choose']) && empty($sel_gri['description']) && empty($sel_gri['name']) && empty($sel_gri['none']))
	    {
	    	$sel_gri['choose'] = ' selected="selected"';
	    };
            $editsurvey .= "\t<li><label for=\"showgroupinfo\">".$clang->gT('Show question group name and/or description')."</label>\n"
            . "\t\t<select id=\"showgroupinfo\" name=\"showgroupinfo\">\n"
            . "\t\t\t<option value=\"both\"{$sel_gri['both']}>".$clang->gT('Show both')."</option>\n"
            . "\t\t\t<option value=\"name\"{$sel_gri['name']}>".$clang->gT('Show group name only')."</option>\n"
            . "\t\t\t<option value=\"description\"{$sel_gri['description']}>".$clang->gT('Show group description only')."</option>\n"
            . "\t\t\t<option value=\"none\"{$sel_gri['none']}>".$clang->gT('Hide both')."</option>\n"
            . "\t\t\t<option value=\"choose\"{$sel_gri['choose']}>".$clang->gT('Survey admin can choose')."</option>\n"
            . "\t\t</select></li>\n";
	    unset($set_gri,$sel_gri);

	    // showqnumcode
            $set_qnc=getGlobalSetting('showqnumcode');
	    $sel_qnc = array( 'both' => '' , 'choose' =>'' , 'number' => '' , 'code' => '' , 'none' => '' );
	    $sel_qnc[$set_qnc] = ' selected="selected"';
	    if( empty($sel_qnc['both']) && empty($sel_qnc['choose']) && empty($sel_qnc['number']) && empty($sel_qnc['code']) && empty($sel_qnc['none']))
	    {
	    	$sel_qnc['choose'] = ' selected="selected"';
	    };
            $editsurvey .= "\t<li><label for=\"showqnumcode\">".$clang->gT('Show question number and/or question code')."</label>\n"
            . "\t\t<select id=\"showqnumcode\" name=\"showqnumcode\">\n"
            . "\t\t\t<option value=\"both\"{$sel_qnc['both']}>".$clang->gT('Show both')."</option>\n"
            . "\t\t\t<option value=\"number\"{$sel_qnc['number']}>".$clang->gT('Show question number only')."</option>\n"
            . "\t\t\t<option value=\"code\"{$sel_qnc['code']}>".$clang->gT('Show question code only')."</option>\n"
            . "\t\t\t<option value=\"none\"{$sel_qnc['none']}>".$clang->gT('Hide both')."</option>\n"
            . "\t\t\t<option value=\"choose\"{$sel_qnc['choose']}>".$clang->gT('Survey admin can choose')."</option>\n"
           . "\t\t</select></li>\n";
	    unset($set_qnc,$sel_qnc);

            $editsurvey .= "\t</ul>\n";
            // End TAB page & form
            $editsurvey .= "\t</div><input type='hidden' name='action' value='globalsettingssave'/></form>\n";

            // End tabs
            $editsurvey .= "</div>\n";

            // The external button to sumbit Survey edit changes
            $editsurvey .= "\t<p><input type='button' onclick='$(\"#frmglobalsettings\").submit();' class='standardbtn' value='".$clang->gT("Save settings")."' /><br /></p>\n";
            if ($demoModeOnly==true)
            {
                $editsurvey .= '<p>'.$clang->gT("Note: Demo mode is activated. Marked (*) settings can't be changed.").'</p>\n';
            }




        }
        else
        {
            include("access_denied.php");
        }
    }
}
Example #16
0
function submitanswer()
{
    global $thissurvey, $timeadjust;
    global $surveyid, $connect, $clang, $move;
    if ($thissurvey['private'] == "Y" && $thissurvey['datestamp'] == "N") {
        // In case of anonymous answers survey with no datestamp
        // then the the answer submutdate gets a conventional timestamp
        // 1st Jan 1980
        $mysubmitdate = date("Y-m-d H:i:s", mktime(0, 0, 0, 1, 1, 1980));
    } else {
        $mysubmitdate = date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust);
    }
    $query = "";
    if (isset($move) && $move == "movesubmit" && $thissurvey['active'] == "Y") {
        if (!isset($_SESSION['srid'])) {
            //due to conditions no answer was displayed and yet we must submit
            $query = createinsertquery();
            if ($result = $connect->Execute($query)) {
                $tempID = $connect->Insert_ID($thissurvey['tablename'], "id");
                $_SESSION['srid'] = $tempID;
            }
        }
        $query = "UPDATE {$thissurvey['tablename']} SET ";
        $query .= " submitdate = " . $connect->DBDate($mysubmitdate);
        $query .= " WHERE id=" . $_SESSION['srid'];
    }
    $result = $connect->Execute($query);
    // Checked
    return $result;
}
/**
 * getsurveylist() Queries the database (survey table) for a list of existing surveys
 *
 * @param mixed $returnarray   boolean - if set to true an array instead of an HTML option list is given back
 *
 * @global string $surveyid
 * @global string $dbprefix
 * @global string $scriptname
 * @global string $connect
 * @global string $clang
 *
 * @return string This string is returned containing <option></option> formatted list of existing surveys
 *
 */
function getsurveylist($returnarray = false, $returnwithouturl = false)
{
    global $surveyid, $dbprefix, $scriptname, $connect, $clang, $timeadjust;
    static $cached = null;
    if (is_null($cached)) {
        $surveyidquery = " SELECT a.*, surveyls_title, surveyls_description, surveyls_welcometext, surveyls_url " . " FROM " . db_table_name('surveys') . " AS a " . "INNER JOIN " . db_table_name('surveys_languagesettings') . " on (surveyls_survey_id=a.sid and surveyls_language=a.language) ";
        if (!bHasGlobalPermission('USER_RIGHT_SUPERADMIN')) {
            $surveyidquery .= "WHERE a.sid in (select sid from " . db_table_name('survey_permissions') . " where uid={$_SESSION['loginID']} and permission='survey' and read_p=1) ";
        }
        $surveyidquery .= " order by active DESC, surveyls_title";
        $surveyidresult = db_execute_assoc($surveyidquery);
        //Checked
        if (!$surveyidresult) {
            return "Database Error";
        }
        $surveynames = $surveyidresult->GetRows();
        $cached = $surveynames;
    } else {
        $surveynames = $cached;
    }
    $surveyselecter = "";
    if ($returnarray === true) {
        return $surveynames;
    }
    $activesurveys = '';
    $inactivesurveys = '';
    $expiredsurveys = '';
    if ($surveynames) {
        foreach ($surveynames as $sv) {
            $surveylstitle = FlattenText($sv['surveyls_title']);
            if (strlen($surveylstitle) > 45) {
                $surveylstitle = htmlspecialchars(mb_strcut(html_entity_decode($surveylstitle, ENT_QUOTES, 'UTF-8'), 0, 45, 'UTF-8')) . "...";
            }
            if ($sv['active'] != 'Y') {
                $inactivesurveys .= "<option ";
                if ($_SESSION['loginID'] == $sv['owner_id']) {
                    $inactivesurveys .= " style=\"font-weight: bold;\"";
                }
                if ($sv['sid'] == $surveyid) {
                    $inactivesurveys .= " selected='selected'";
                    $svexist = 1;
                }
                if ($returnwithouturl === false) {
                    $inactivesurveys .= " value='{$scriptname}?sid={$sv['sid']}'>{$surveylstitle}</option>\n";
                } else {
                    $inactivesurveys .= " value='{$sv['sid']}'>{$surveylstitle}</option>\n";
                }
            } elseif ($sv['expires'] != '' && $sv['expires'] < date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust)) {
                $expiredsurveys .= "<option ";
                if ($_SESSION['loginID'] == $sv['owner_id']) {
                    $expiredsurveys .= " style=\"font-weight: bold;\"";
                }
                if ($sv['sid'] == $surveyid) {
                    $expiredsurveys .= " selected='selected'";
                    $svexist = 1;
                }
                if ($returnwithouturl === false) {
                    $expiredsurveys .= " value='{$scriptname}?sid={$sv['sid']}'>{$surveylstitle}</option>\n";
                } else {
                    $expiredsurveys .= " value='{$sv['sid']}'>{$surveylstitle}</option>\n";
                }
            } else {
                $activesurveys .= "<option ";
                if ($_SESSION['loginID'] == $sv['owner_id']) {
                    $activesurveys .= " style=\"font-weight: bold;\"";
                }
                if ($sv['sid'] == $surveyid) {
                    $activesurveys .= " selected='selected'";
                    $svexist = 1;
                }
                if ($returnwithouturl === false) {
                    $activesurveys .= " value='{$scriptname}?sid={$sv['sid']}'>{$surveylstitle}</option>\n";
                } else {
                    $activesurveys .= " value='{$sv['sid']}'>{$surveylstitle}</option>\n";
                }
            }
        }
        // End Foreach
    }
    //Only show each activesurvey group if there are some
    if ($activesurveys != '') {
        $surveyselecter .= "<optgroup label='" . $clang->gT("Active") . "' class='activesurveyselect'>\n";
        $surveyselecter .= $activesurveys . "</optgroup>";
    }
    if ($expiredsurveys != '') {
        $surveyselecter .= "<optgroup label='" . $clang->gT("Expired") . "' class='expiredsurveyselect'>\n";
        $surveyselecter .= $expiredsurveys . "</optgroup>";
    }
    if ($inactivesurveys != '') {
        $surveyselecter .= "<optgroup label='" . $clang->gT("Inactive") . "' class='inactivesurveyselect'>\n";
        $surveyselecter .= $inactivesurveys . "</optgroup>";
    }
    if (!isset($svexist)) {
        $surveyselecter = "<option selected='selected' value=''>" . $clang->gT("Please choose...") . "</option>\n" . $surveyselecter;
    } else {
        if ($returnwithouturl === false) {
            $surveyselecter = "<option value='{$scriptname}?sid='>" . $clang->gT("None") . "</option>\n" . $surveyselecter;
        } else {
            $surveyselecter = "<option value=''>" . $clang->gT("None") . "</option>\n" . $surveyselecter;
        }
    }
    return $surveyselecter;
}
Example #18
0
$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.")."<br />", $fieldsarray);
                }
                elseif (trim($emrow['validuntil'])!='' && convertDateTimeFormat($emrow['validuntil'],'Y-m-d H:i:s','U')*1<date('U')*1)
                {
                    $tokenoutput .= $emrow['tid'] ." ".ReplaceFields($clang->gT("Email to {FIRSTNAME} {LASTNAME} ({EMAIL}) skipped: Token is not valid anymore.")."<br />", $fieldsarray);
                }
                elseif (SendEmailMessage($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<br />$udequery<br />".$connect->ErrorMsg());
                    //orig: $tokenoutput .= "({$emrow['tid']})[".$clang->gT("Reminder sent to:")." {$emrow['firstname']} {$emrow['lastname']}]<br />\n";
                    $tokenoutput .= "({$emrow['tid']}) [".$clang->gT("Reminder sent to:")." {$emrow['firstname']} {$emrow['lastname']} ($to)]<br />\n";
                }
                else
                {
                    $tokenoutput .= $emrow['tid'] ." ".ReplaceFields($clang->gT("Email to {FIRSTNAME} {LASTNAME} ({EMAIL}) failed. Error Message:")." ".$maildebug."<br />", $fieldsarray);
                    if ($debug>0)
                    {
                        $tokenoutput .= "<pre>Subject : $msgsubject<br /><br />".htmlspecialchars($maildebugbody)."<br /></pre>";
                    }
Example #19
0
function globalsettingsdisplay()
{
    global $action, $connect, $js_admin_includes, $editsurvey, $subaction, $scriptname, $clang;
    global $updateversion, $updatebuild, $updateavailable, $updatelastcheck, $demoModeOnly;
    if (isset($subaction) && $subaction == "updatecheck") {
        $updateinfo = updatecheck();
    }
    if (isset($action) && $action == "globalsettings") {
        if ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {
            $js_admin_includes[] = 'scripts/globalsettings.js';
            // header
            $editsurvey = "<div class='header'>" . $clang->gT("Global settings") . "</div>\n";
            // beginning TABs section
            $editsurvey .= "\t<div class='tab-pane' id='tab-pane-globalsettings'>\n";
            $editsurvey .= "<form id='frmglobalsettings' name='frmglobalsettings' action='{$scriptname}' method='post'>\n";
            $editsurvey .= "\t<div class='tab-page'> <h2 class='tab'>" . $clang->gT("Overview & Update") . "</h2>\n";
            $editsurvey .= checksettings();
            $thisupdatecheckperiod = getGlobalSetting('updatecheckperiod');
            $editsurvey .= "<br /></p><div class='header'>" . $clang->gT("Updates") . "</div><ul>" . "\t<li><label for='updatecheckperiod'>" . $clang->gT("Check for updates:") . "</label>\n" . "\t\t\t<select name='updatecheckperiod' id='updatecheckperiod'>\n" . "\t\t\t\t<option value='0'";
            if ($thisupdatecheckperiod == 0) {
                $editsurvey .= " selected='selected'";
            }
            $editsurvey .= ">" . $clang->gT("Never") . "</option>\n" . "\t\t\t\t<option value='1'";
            if ($thisupdatecheckperiod == 1) {
                $editsurvey .= " selected='selected'";
            }
            $editsurvey .= ">" . $clang->gT("Every day") . "</option>\n" . "\t\t\t\t<option value='7'";
            if ($thisupdatecheckperiod == 7) {
                $editsurvey .= " selected='selected'";
            }
            $editsurvey .= ">" . $clang->gT("Every week") . "</option>\n" . "<option value='14'";
            if ($thisupdatecheckperiod == 14) {
                $editsurvey .= " selected='selected'";
            }
            $editsurvey .= ">" . $clang->gT("Every 2 weeks") . "</option>\n" . "<option value='30'";
            if ($thisupdatecheckperiod == 30) {
                $editsurvey .= " selected='selected'";
            }
            $editsurvey .= ">" . $clang->gT("Every month") . "</option>\n" . "</select>&nbsp;<input type='button' onclick=\"window.open('{$scriptname}?action=globalsettings&amp;subaction=updatecheck', '_top')\" value='" . $clang->gT("Check now") . "' />&nbsp;<span id='lastupdatecheck'>" . sprintf($clang->gT("Last check: %s"), $updatelastcheck) . "</span></li></ul><p>\n";
            if (isset($updateavailable) && $updateavailable == 1) {
                $editsurvey .= '<span style="font-weight: bold;">' . sprintf($clang->gT('There is a LimeSurvey update available: Version %s'), $updateversion . "({$updatebuild})") . '</span><br />';
                $editsurvey .= sprintf($clang->gT('You can update %smanually%s or use the %s'), "<a href='http://docs.limesurvey.org/tiki-index.php?page=Upgrading+from+a+previous+version'>", "</a>", "<a href='{$scriptname}?action=update'>" . $clang->gT('3-Click ComfortUpdate') . '</a>') . '.<br />';
            } elseif (isset($updateinfo['errorcode'])) {
                $editsurvey .= sprintf($clang->gT('There was an error on update check (%s)'), $updateinfo['errorcode']) . '.<br />';
                $editsurvey .= "<textarea readonly='readonly' style='width:35%; height:60px; overflow: auto;'>" . strip_tags($updateinfo['errorhtml']) . '</textarea>';
            } else {
                $editsurvey .= $clang->gT('There is currently no newer LimeSurvey version available.');
            }
            $editsurvey .= "</p></div>";
            // General TAB
            $editsurvey .= "\t<div class='tab-page'> <h2 class='tab'>" . $clang->gT("General") . "</h2>\n";
            // Administrator...
            $editsurvey .= "<ul>" . "\t<li><label for='sitename'>" . $clang->gT("Site name:") . ($demoModeOnly == true ? '*' : '') . "</label>\n" . "\t\t<input type='text' size='50' id='sitename' name='sitename' value=\"" . htmlspecialchars(getGlobalSetting('sitename')) . "\" /></li>\n" . "\t<li><label for='defaultlang'>" . $clang->gT("Default site language:") . ($demoModeOnly == true ? '*' : '') . "</label>\n" . "\t\t<select name='defaultlang' id='defaultlang'>\n";
            $actuallang = getGlobalSetting('defaultlang');
            foreach (getLanguageData(true) as $langkey2 => $langname) {
                $editsurvey .= "\t\t\t<option value='" . $langkey2 . "'";
                if ($actuallang == $langkey2) {
                    $editsurvey .= " selected='selected'";
                }
                $editsurvey .= ">" . $langname['nativedescription'] . " - " . $langname['description'] . "</option>\n";
            }
            $editsurvey .= "\t\t</select></li>";
            $thisdefaulttemplate = getGlobalSetting('defaulttemplate');
            $templatenames = array_keys(gettemplatelist());
            $editsurvey .= "" . "\t<li><label for='defaulttemplate'>" . $clang->gT("Default template:") . "</label>\n" . "\t\t\t<select name='defaulttemplate' id='defaulttemplate'>\n";
            foreach ($templatenames as $templatename) {
                $editsurvey .= "\t\t\t\t<option value='{$templatename}'";
                if ($thisdefaulttemplate == $templatename) {
                    $editsurvey .= " selected='selected'";
                }
                $editsurvey .= ">{$templatename}</option>\n";
            }
            $editsurvey .= "\t\t\t</select></li>\n";
            $thisdefaulthtmleditormode = getGlobalSetting('defaulthtmleditormode');
            $editsurvey .= "" . "\t<li><label for='defaulthtmleditormode'>" . $clang->gT("Default HTML editor mode:") . ($demoModeOnly == true ? '*' : '') . "</label>\n" . "\t\t\t<select name='defaulthtmleditormode' id='defaulthtmleditormode'>\n" . "\t\t\t\t<option value='default'";
            if ($thisdefaulthtmleditormode == 'default') {
                $editsurvey .= " selected='selected'";
            }
            $editsurvey .= ">" . $clang->gT("Default HTML editor mode") . "</option>\n" . "\t\t\t\t<option value='none'";
            if ($thisdefaulthtmleditormode == 'none') {
                $editsurvey .= " selected='selected'";
            }
            $editsurvey .= ">" . $clang->gT("No HTML editor") . "</option>\n" . "<option value='inline'";
            if ($thisdefaulthtmleditormode == 'inline') {
                $editsurvey .= " selected='selected'";
            }
            $editsurvey .= ">" . $clang->gT("Inline HTML editor") . "</option>\n" . "<option value='popup'";
            if ($thisdefaulthtmleditormode == 'popup') {
                $editsurvey .= " selected='selected'";
            }
            $editsurvey .= ">" . $clang->gT("Popup HTML editor") . "</option>\n" . "</select></li>\n";
            $dateformatdata = getDateFormatData($_SESSION['dateformat']);
            $editsurvey .= "\t<li><label for='timeadjust'>" . $clang->gT("Time difference (in hours):") . "</label>\n" . "\t\t<input type='text' size='10' id='timeadjust' name='timeadjust' value=\"" . htmlspecialchars(str_replace(array('+', ' hours'), array('', ''), getGlobalSetting('timeadjust'))) . "\" /> " . $clang->gT("Server time:") . ' ' . convertDateTimeFormat(date('Y-m-d H:i:s'), 'Y-m-d H:i:s', $dateformatdata['phpdate'] . ' H:i') . " - " . $clang->gT("Corrected time :") . ' ' . convertDateTimeFormat(date_shift(date("Y-m-d H:i:s"), 'Y-m-d H:i:s', getGlobalSetting('timeadjust')), 'Y-m-d H:i:s', $dateformatdata['phpdate'] . ' H:i') . "\r\n            </li>\n";
            $thisusepdfexport = getGlobalSetting('usepdfexport');
            $editsurvey .= "\t<li><label for='usepdfexport'>" . $clang->gT("PDF export available:") . "</label>\n" . "<select name='usepdfexport' id='usepdfexport'>\n" . "<option value='1'";
            if ($thisusepdfexport == true) {
                $editsurvey .= " selected='selected'";
            }
            $editsurvey .= ">" . $clang->gT("On") . "</option>\n" . "<option value='0'";
            if ($thisusepdfexport == false) {
                $editsurvey .= " selected='selected'";
            }
            $editsurvey .= ">" . $clang->gT("Off") . "</option>\n" . "\t\t</select>\n\t</li>\n";
            $thisaddTitleToLinks = getGlobalSetting('addTitleToLinks');
            $editsurvey .= "\t<li><label for='addTitleToLinks'>" . $clang->gT("Screen reader compatibility mode:") . "</label>\n" . "<select name='addTitleToLinks' id='addTitleToLinks'>\n" . "<option value='1'";
            if ($thisaddTitleToLinks == true) {
                $editsurvey .= " selected='selected'";
            }
            $editsurvey .= ">" . $clang->gT("On") . "</option>\n" . "<option value='0'";
            if ($thisaddTitleToLinks == false) {
                $editsurvey .= " selected='selected'";
            }
            $editsurvey .= ">" . $clang->gT("Off") . "</option>\n" . "</select>\n</li>\n" . "<li><label for='sessionlifetime'>" . $clang->gT("Session lifetime (seconds):") . "</label>\n" . "<input type='text' size='10' id='sessionlifetime' name='sessionlifetime' value=\"" . htmlspecialchars(getGlobalSetting('sessionlifetime')) . "\" /></li>";
            // End General TAB
            $editsurvey .= "\t</ul></div>\n";
            // Email TAB
            $editsurvey .= "\t<div class='tab-page'> <h2 class='tab'>" . $clang->gT("Email settings") . "</h2><ul>\n";
            //Format
            $editsurvey .= "\t<li><label for='siteadminemail'>" . $clang->gT("Default site admin email:") . "</label>\n" . "\t\t<input type='text' size='50' id='siteadminemail' name='siteadminemail' value=\"" . htmlspecialchars(getGlobalSetting('siteadminemail')) . "\" /></li>\n" . "\t<li><label for='siteadminbounce'>" . $clang->gT("Default site bounce email:") . "</label>\n" . "\t\t<input type='text' size='50' id='siteadminbounce' name='siteadminbounce' value=\"" . htmlspecialchars(getGlobalSetting('siteadminbounce')) . "\" /></li>\n" . "\t<li><label for='siteadminname'>" . $clang->gT("Administrator name:") . "</label>\n" . "\t\t<input type='text' size='50' id='siteadminname' name='siteadminname' value=\"" . htmlspecialchars(getGlobalSetting('siteadminname')) . "\" /><br /><br /></li>\n" . "\t<li><label for='emailmethod'>" . $clang->gT("Email method:") . "</label>\n" . "\t\t<select id='emailmethod' name='emailmethod'>\n" . "\t\t\t<option value='mail'";
            if (getGlobalSetting('emailmethod') == 'mail') {
                $editsurvey .= " selected='selected'";
            }
            $editsurvey .= ">" . $clang->gT("PHP (default)") . "</option>\n" . "\t\t\t<option value='smtp'";
            if (getGlobalSetting('emailmethod') == 'smtp') {
                $editsurvey .= " selected='selected'";
            }
            $editsurvey .= ">" . $clang->gT("SMTP") . "</option>\n" . "\t\t\t<option value='sendmail'";
            if (getGlobalSetting('emailmethod') == 'sendmail') {
                $editsurvey .= " selected='selected'";
            }
            $editsurvey .= ">" . $clang->gT("Sendmail") . "</option>\n" . "\t\t\t<option value='qmail'";
            if (getGlobalSetting('emailmethod') == 'qmail') {
                $editsurvey .= " selected='selected'";
            }
            $editsurvey .= ">" . $clang->gT("Qmail") . "</option>\n" . "\t\t</select></li>\n" . "\t<li><label for='emailsmtphost'>" . $clang->gT("SMTP host:") . "</label>\n" . "\t\t<input type='text' size='50' id='emailsmtphost' name='emailsmtphost' value=\"" . htmlspecialchars(getGlobalSetting('emailsmtphost')) . "\" />&nbsp;<font size='1'>" . $clang->gT("Enter your hostname and port, e.g.: my.smtp.com:25") . "</font></li>\n" . "\t<li><label for='emailsmtpuser'>" . $clang->gT("SMTP username:"******"</label>\n" . "\t\t<input type='text' size='50' id='emailsmtpuser' name='emailsmtpuser' value=\"" . htmlspecialchars(getGlobalSetting('emailsmtpuser')) . "\" /></li>\n" . "\t<li><label for='emailsmtppassword'>" . $clang->gT("SMTP password:"******"</label>\n" . "\t\t<input type='password' size='50' id='emailsmtppassword' name='emailsmtppassword' value='somepassword' /></li>\n" . "\t<li><label for='emailsmtpssl'>" . $clang->gT("SMTP SSL/TLS:") . "</label>\n" . "\t\t<select id='emailsmtpssl' name='emailsmtpssl'>\n" . "\t\t\t<option value=''";
            if (getGlobalSetting('emailsmtpssl') == '') {
                $editsurvey .= " selected='selected'";
            }
            $editsurvey .= ">" . $clang->gT("Off") . "</option>\n" . "\t\t\t<option value='ssl'";
            if (getGlobalSetting('emailsmtpssl') == 'ssl' || getGlobalSetting('emailsmtpssl') == 1) {
                $editsurvey .= " selected='selected'";
            }
            $editsurvey .= ">" . $clang->gT("SSL") . "</option>\n" . "\t\t\t<option value='tls'";
            if (getGlobalSetting('emailsmtpssl') == 'tls') {
                $editsurvey .= " selected='selected'";
            }
            $editsurvey .= ">" . $clang->gT("TLS") . "</option>\n" . "\t\t</select></li>\n" . "\t<li><label for='emailsmtpdebug'>" . $clang->gT("SMTP debug mode:") . "</label>\n" . "\t\t<select id='emailsmtpdebug' name='emailsmtpdebug'>\n" . "\t\t\t<option value=''";
            if (getGlobalSetting('emailsmtpdebug') == '0') {
                $editsurvey .= " selected='selected'";
            }
            $editsurvey .= ">" . $clang->gT("Off") . "</option>\n" . "\t\t\t<option value='1'";
            if (getGlobalSetting('emailsmtpdebug') == '1' || getGlobalSetting('emailsmtpssl') == 1) {
                $editsurvey .= " selected='selected'";
            }
            $editsurvey .= ">" . $clang->gT("On errors") . "</option>\n" . "\t\t\t<option value='2'";
            if (getGlobalSetting('emailsmtpdebug') == '2' || getGlobalSetting('emailsmtpssl') == 1) {
                $editsurvey .= " selected='selected'";
            }
            $editsurvey .= ">" . $clang->gT("Always") . "</option>\n" . "\t\t</select><br />&nbsp;</li>\n" . "\t<li><label for='maxemails'>" . $clang->gT("Email batch size:") . "</label>\n" . "\t\t<input type='text' size='5' id='maxemails' name='maxemails' value=\"" . htmlspecialchars(getGlobalSetting('maxemails')) . "\" /></li>\n" . "\t</ul>\n";
            // End Email TAB
            $editsurvey .= "\t</div>\n";
            // Security Settings
            $editsurvey .= "\t<div class='tab-page'> <h2 class='tab'>" . $clang->gT("Security") . "</h2><ul>\n";
            // Expiration
            $thissurveyPreview_require_Auth = getGlobalSetting('surveyPreview_require_Auth');
            $editsurvey .= "\t<li><label for='surveyPreview_require_Auth'>" . $clang->gT("Survey preview only for administration users") . "</label>\n" . "\t\t<select id='surveyPreview_require_Auth' name='surveyPreview_require_Auth'>\n" . "\t\t\t<option value='1'";
            if ($thissurveyPreview_require_Auth == true) {
                $editsurvey .= " selected='selected'";
            }
            $editsurvey .= ">" . $clang->gT("Yes") . "</option>\n" . "\t\t\t<option value='0'";
            if ($thissurveyPreview_require_Auth == false) {
                $editsurvey .= " selected='selected'";
            }
            $editsurvey .= ">" . $clang->gT("No") . "</option>\n" . "\t\t</select></li>\n";
            // Auto registration
            $thisfilterxsshtml = getGlobalSetting('filterxsshtml');
            $editsurvey .= "\t<li><label for='filterxsshtml'>" . $clang->gT("Filter HTML for XSS:") . ($demoModeOnly == true ? '*' : '') . "</label>\n" . "\t\t<select id='filterxsshtml' name='filterxsshtml'>\n" . "\t\t\t<option value='1'";
            if ($thisfilterxsshtml == true) {
                $editsurvey .= " selected='selected'";
            }
            $editsurvey .= ">" . $clang->gT("Yes") . "</option>\n" . "\t\t\t<option value='0'";
            if ($thisfilterxsshtml == false) {
                $editsurvey .= " selected='selected'";
            }
            $editsurvey .= ">" . $clang->gT("No") . "</option>\n" . "\t\t</select></li>\n";
            $thisusercontrolSameGroupPolicy = getGlobalSetting('usercontrolSameGroupPolicy');
            $editsurvey .= "\t<li><label for='usercontrolSameGroupPolicy'>" . $clang->gT("Group member can only see own group:") . "</label>\n" . "\t\t<select id='usercontrolSameGroupPolicy' name='usercontrolSameGroupPolicy'>\n" . "\t\t\t<option value='1'";
            if ($thisusercontrolSameGroupPolicy == true) {
                $editsurvey .= " selected='selected'";
            }
            $editsurvey .= ">" . $clang->gT("Yes") . "</option>\n" . "\t\t\t<option value='0'";
            if ($thisusercontrolSameGroupPolicy == false) {
                $editsurvey .= " selected='selected'";
            }
            $editsurvey .= ">" . $clang->gT("No") . "</option>\n" . "\t\t</select></li>\n";
            $editsurvey .= "\t</ul></div>\n";
            // Miscellaneous Settings
            $editsurvey .= "\t<div class='tab-page'> <h2 class='tab'>" . $clang->gT("Miscellaneous") . "</h2><ul>\n";
            // shownoanswer
            $shownoanswer = getGlobalSetting('shownoanswer');
            $editsurvey .= "\t<li><label for='shownoanswer'>" . $clang->gT("Show 'no answer' option for non-mandatory questions:") . "</label>\n" . "\t\t<select id='shownoanswer' name='shownoanswer'>\n" . "\t\t\t<option value='1'";
            if ($shownoanswer == 1) {
                $editsurvey .= " selected='selected'";
            }
            $editsurvey .= ">" . $clang->gT("Yes") . "</option>\n" . "\t\t\t<option value='0'";
            if ($shownoanswer == 0) {
                $editsurvey .= " selected='selected'";
            }
            $editsurvey .= ">" . $clang->gT("No") . "</option>\n" . "\t\t</select></li>\n";
            $thisrepeatheadings = getGlobalSetting('repeatheadings');
            $editsurvey .= "\t<li><label for='repeatheadings'>" . $clang->gT("Number of answers to show before repeating the headings in array questions:") . "</label>\n" . "\t\t<input id='repeatheadings' name='repeatheadings' value='{$thisrepeatheadings}' size='4' maxlength='4' /></li>\n";
            $editsurvey .= "\t</ul>\n";
            // End TAB page & form
            $editsurvey .= "\t</div><input type='hidden' name='action' value='globalsettingssave'/></form>\n";
            // End tabs
            $editsurvey .= "</div>\n";
            // The external button to sumbit Survey edit changes
            $editsurvey .= "\t<p><input type='button' onclick='\$(\"#frmglobalsettings\").submit();' class='standardbtn' value='" . $clang->gT("Save settings") . "' /><br /></p>\n";
            if ($demoModeOnly == true) {
                $editsurvey .= '<p>' . $clang->gT("Note: Demo mode is activated. Marked (*) settings can't be changed.") . '</p>\\n';
            }
        } else {
            include "access_denied.php";
        }
    }
}