示例#1
0
// Check the security question's answer
if (function_exists("ImageCreate") && captcha_enabled('registrationscreen', $thissurvey['usecaptcha'])) {
    if (!isset($_POST['loadsecurity']) || !isset($_SESSION['secanswer']) || $_POST['loadsecurity'] != $_SESSION['secanswer']) {
        $register_errormsg .= $clang->gT("The answer to the security question is incorrect.") . "<br />\n";
    }
}
//Check that the email is a valid style address
if (!validate_email(returnglobal('register_email'))) {
    $register_errormsg .= $clang->gT("The email you used is not valid. Please try again.");
}
if ($register_errormsg != "") {
    include "index.php";
    exit;
}
//Check if this email already exists in token database
$query = "SELECT email FROM {$dbprefix}tokens_{$surveyid}\n" . "WHERE email = " . db_quoteall(sanitize_email(returnglobal('register_email')));
$result = $connect->Execute($query) or safe_die($query . "<br />" . $connect->ErrorMsg());
//Checked
if ($result->RecordCount() > 0) {
    $register_errormsg = $clang->gT("The email you used has already been registered.");
    include "index.php";
    exit;
}
$mayinsert = false;
while ($mayinsert != true) {
    $newtoken = randomkey(15);
    $ntquery = "SELECT * FROM {$dbprefix}tokens_{$surveyid} WHERE token='{$newtoken}'";
    $ntresult = $connect->Execute($ntquery);
    //Checked
    if (!$ntresult->RecordCount()) {
        $mayinsert = true;
                 $updateqr .= db_quote_id($fieldname) . " = '{$datetimeobj->convert("Y-m-d H:i:s")}', \n";
             }
         } elseif (($irow['type'] == 'N' || $irow['type'] == 'K') && $thisvalue == "") {
             $updateqr .= db_quote_id($fieldname) . " = NULL, \n";
         } elseif ($irow['type'] == '|' && strpos($irow['fieldname'], '_filecount') && $thisvalue == "") {
             $updateqr .= db_quote_id($fieldname) . " = NULL, \n";
         } elseif ($irow['type'] == 'submitdate') {
             if (isset($_POST['completed']) && $_POST['completed'] == "N") {
                 $updateqr .= db_quote_id($fieldname) . " = NULL, \n";
             } elseif (isset($_POST['completed']) && $thisvalue == "") {
                 $updateqr .= db_quote_id($fieldname) . " = " . db_quoteall($_POST['completed'], true) . ", \n";
             } else {
                 $updateqr .= db_quote_id($fieldname) . " = " . db_quoteall($thisvalue, true) . ", \n";
             }
         } else {
             $updateqr .= db_quote_id($fieldname) . " = " . db_quoteall($thisvalue, true) . ", \n";
         }
     }
     $updateqr = substr($updateqr, 0, -3);
     $updateqr .= " WHERE id={$id}";
     $updateres = $connect->Execute($updateqr) or safe_die("Update failed:<br />\n" . $connect->ErrorMsg() . "<br />{$updateqr}");
     $thissurvey = getSurveyInfo($surveyid);
     while (ob_get_level() > 0) {
         ob_end_flush();
     }
     $dataentryoutput .= "<div class='messagebox ui-corner-all'><div class='successheader'>" . $clang->gT("Success") . "</div>\n" . $clang->gT("Record has been updated.") . "<br /><br />\n" . "<input type='submit' value='" . $clang->gT("View This Record") . "' onclick=\"window.open('{$scriptname}?action=browse&amp;sid={$surveyid}&amp;subaction=id&amp;id={$id}', '_top')\" /><br /><br />\n" . "<input type='submit' value='" . $clang->gT("Browse Responses") . "' onclick=\"window.open('{$scriptname}?action=browse&amp;sid={$surveyid}&amp;subaction=all', '_top')\" />\n" . "</div>\n";
 } elseif ($subaction == "delete" && bHasSurveyPermission($surveyid, 'responses', 'delete')) {
     $dataentryoutput .= "<div class='header ui-widget-header'>" . $clang->gT("Data entry") . "</div>\n";
     $dataentryoutput .= "<div class='messagebox ui-corner-all'>\n";
     $thissurvey = getSurveyInfo($surveyid);
     $delquery = "DELETE FROM {$surveytable} WHERE id={$id}";
示例#3
0
                            // No issue, let's import
                            $iq = "INSERT INTO ".db_table_name("tokens_$surveyid")." \n"
                            . "(firstname, lastname, email, emailstatus, token, language";

                            foreach ($aTokenAttr as $thisattrfieldname)
                            {
                                $attridx=substr($thisattrfieldname,10); // the 'attribute_' prefix is 10 chars long
                                if (!empty($myattrArray[$attridx])) {$iq .= ", $thisattrfieldname";}
                            }
                            $iq .=") \n"
                            . "VALUES (".db_quoteall($myfirstname).", ".db_quoteall($mylastname).", ".db_quoteall($myemail).", 'OK', ".db_quoteall($mytoken).", ".db_quoteall($mylanguage)."";

                            foreach ($aTokenAttr as $thisattrfieldname)
                            {
                                $attridx=substr($thisattrfieldname,10); // the 'attribute_' prefix is 10 chars long
                                if (!empty($myattrArray[$attridx])) {$iq .= ", ".db_quoteall($myattrArray[$attridx]).""; }// dbquote_all encloses str with quotes
                            }
                            $iq .= ")";
                            $ir = $connect->Execute($iq);
                            if (!$ir) $duplicatecount++;
                            $xz++;
                            // or safe_die ("Couldn't insert line<br />\n$buffer<br />\n".htmlspecialchars($connect->ErrorMsg())."<pre style='text-align: left'>$iq</pre>\n");
                        }
                    } // End for each entry
                } // End foreach responseGroup
            } // End of if resnum >= 1

            if ($xz != 0)
            {
                $tokenoutput .= "<span class='successtitle'>".$clang->gT("Success")."</span><br /><br />\n";
            }
示例#4
0
文件: save.php 项目: ddrmoscow/queXS
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.');
        }
    }
}
示例#5
0
function modlabelsetanswers($lid)
{
    global $dbprefix, $connect, $clang, $labelsoutput, $databasetype, $filterxsshtml,$postsortorder;

    $qulabelset = "SELECT * FROM ".db_table_name('labelsets')." WHERE lid='$lid'";
    $rslabelset = db_execute_assoc($qulabelset) or safe_die($connect->ErrorMsg());
    $rwlabelset=$rslabelset->FetchRow();
    $lslanguages=explode(" ", trim($rwlabelset['languages']));

    if (!isset($_POST['method'])) {
        $_POST['method'] = $clang->gT("Save");
    }
    switch($_POST['method'])
    {
        case $clang->gT("Add new label", "unescaped"):
            if (isset($_POST['insertcode']) && $_POST['insertcode']!='')
            {
                $_SESSION['nextlabelcode']=getNextCode($_POST['insertcode']);
                $_POST['insertcode'] = db_quoteall($_POST['insertcode'],true);
                // check that the code doesn't exist yet
                $query = "SELECT code FROM ".db_table_name('labels')." WHERE lid='$lid' AND code=".$_POST['insertcode'];
                $result = $connect->Execute($query);
                $codeoccurences=$result->RecordCount();
                if ($codeoccurences == 0)
                {
                    $query = "select max(sortorder) as maxorder from ".db_table_name('labels')." where lid='$lid'";
                    $result = $connect->Execute($query);
                    $newsortorder=sprintf("%05d", $result->fields['maxorder']+1);
                    if ($filterxsshtml)
                    {
                        require_once("../classes/inputfilter/class.inputfilter_clean.php");
                        $myFilter = new InputFilter('','',1,1,1);
                        $_POST['inserttitle']=$myFilter->process($_POST['inserttitle']);
                    }
                    else
                    {
                        $_POST['inserttitle'] = html_entity_decode($_POST['inserttitle'], ENT_QUOTES, "UTF-8");
                    }

                    // Fix bug with FCKEditor saving strange BR types
                    $_POST['inserttitle']=fix_FCKeditor_text($_POST['inserttitle']);
                     
                    $_POST['inserttitle'] = db_quoteall($_POST['inserttitle'],true);
                    $_POST['insertassessmentvalue']=(int)$_POST['insertassessmentvalue'];
                    foreach ($lslanguages as $lslanguage)
                    {
                        db_switchIDInsert('labels',true);
                        $query = "INSERT INTO ".db_table_name('labels')." (lid, code, title, sortorder,language, assessment_value) VALUES ($lid, {$_POST['insertcode']}, {$_POST['inserttitle']}, '$newsortorder','$lslanguage',{$_POST['insertassessmentvalue']})";
                        if (!$result = $connect->Execute($query))
                        {
                            $labelsoutput.= "<script type=\"text/javascript\">\n<!--\n alert(\"".$clang->gT("Failed to insert label", "js")." - ".$query." - ".$connect->ErrorMsg()."\")\n //-->\n</script>\n";
                        }
                        db_switchIDInsert('labels',false);
                    }
                }
                else
                {
                    $labelsoutput.= "<script type=\"text/javascript\">\n<!--\n alert(\"".$clang->gT("This label code is already used in this labelset. Please choose another code or rename the existing one.", "js")."\")\n //-->\n</script>\n";
                }
            }
            break;

            // Save all labels with one button
        case $clang->gT("Save Changes", "unescaped"):
            //Determine autoids by evaluating the hidden field
            $sortorderids=explode(' ', trim($_POST['sortorderids']));
            $codeids=explode(' ', trim($_POST['codeids']));
            $count=0;

            // Quote each code_codeid first
            foreach ($codeids as $codeid)
            {
                $_POST['code_'.$codeid] = db_quoteall($_POST['code_'.$codeid],true);
                if (isset($_POST['oldcode_'.$codeid])) $_POST['oldcode_'.$codeid] = db_quoteall($_POST['oldcode_'.$codeid],true);
                // Get the code values to check for duplicates
                $codevalues[] = $_POST['code_'.$codeid];
            }

            // Check that there is no code duplicate
            if (count(array_unique($codevalues)) == count($codevalues))
            {
                if ($filterxsshtml)
                {
                    require_once("../classes/inputfilter/class.inputfilter_clean.php");
                    $myFilter = new InputFilter('','',1,1,1);
                }

                foreach ($sortorderids as $sortorderid)
                {
                    $orderid=substr($sortorderid,strrpos($sortorderid,'_')+1,20);
                    foreach ($lslanguages as $langid)
                        {
                        $sortorderid = $langid . '_' . $orderid;
                        if ($filterxsshtml)
                        {
                            $_POST['title_'.$sortorderid]=$myFilter->process($_POST['title_'.$sortorderid]);
                        }
                        else
                        {
                            $_POST['title_'.$sortorderid] = html_entity_decode($_POST['title_'.$sortorderid], ENT_QUOTES, "UTF-8");
                        }


                        // Fix bug with FCKEditor saving strange BR types
                        $_POST['title_'.$sortorderid]=fix_FCKeditor_text($_POST['title_'.$sortorderid]);
                        $_POST['title_'.$sortorderid] = db_quoteall($_POST['title_'.$sortorderid],true);

                        $query = "UPDATE ".db_table_name('labels')." SET code=".$_POST['code_'.$codeids[$count]].", title={$_POST['title_'.$sortorderid]}, assessment_value={$_POST['assessmentvalue_'.$codeids[$count]]} WHERE lid=$lid AND sortorder=$orderid AND language='$langid'";

                        if (!$result = $connect->Execute($query))
                        // if update didn't work we assume the label does not exist and insert it
                        {

                            $query = "insert into ".db_table_name('labels')." (code,title,lid,sortorder,language) VALUES (".$_POST['code_'.$codeids[$count]].", {$_POST['title_'.$sortorderid]}, $lid , $orderid , '$langid')";
                            if (!$result = $connect->Execute($query))
                            {
                                $labelsoutput.= "<script type=\"text/javascript\">\n<!--\n alert(\"".$clang->gT("Failed to update label","js")." - ".$query." - ".$connect->ErrorMsg()."\")\n //-->\n</script>\n";
                            }
                        }
                    }
                    $count++;
                    if ($count>count($codeids)-1) {$count=0;}
                }
                fixorder($lid);
            }
            else
            {
                $labelsoutput.= "<script type=\"text/javascript\">\n<!--\n alert(\"".$clang->gT("Can't update labels because you are using duplicated codes","js")."\")\n //-->\n</script>\n";
            }

            break;

            // Pressing the Up button
        case $clang->gT("Up", "unescaped"):
            $newsortorder=$postsortorder-1;
            $oldsortorder=$postsortorder;
            $cdquery = "UPDATE ".db_table_name('labels')." SET sortorder=-1 WHERE lid=$lid AND sortorder=$newsortorder";
            $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg());
            $cdquery = "UPDATE ".db_table_name('labels')." SET sortorder=$newsortorder WHERE lid=$lid AND sortorder=$oldsortorder";
            $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg());
            $cdquery = "UPDATE ".db_table_name('labels')." SET sortorder='$oldsortorder' WHERE lid=$lid AND sortorder=-1";
            $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg());
            break;

            // Pressing the Down button
        case $clang->gT("Dn", "unescaped"):
            $newsortorder=$postsortorder+1;
            $oldsortorder=$postsortorder;
            $cdquery = "UPDATE ".db_table_name('labels')." SET sortorder=-1 WHERE lid=$lid AND sortorder='$newsortorder'";
            $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg());
            $cdquery = "UPDATE ".db_table_name('labels')." SET sortorder='$newsortorder' WHERE lid=$lid AND sortorder=$oldsortorder";
            $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg());
            $cdquery = "UPDATE ".db_table_name('labels')." SET sortorder=$oldsortorder WHERE lid=$lid AND sortorder=-1";
            $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg());
            break;

            // Delete Button
        case $clang->gT("Del", "unescaped"):
            $query = "DELETE FROM ".db_table_name('labels')." WHERE lid=$lid AND sortorder='{$postsortorder}'";
            if (!$result = $connect->Execute($query))
            {
                $labelsoutput.= "<script type=\"text/javascript\">\n<!--\n alert(\"".$clang->gT("Failed to delete label","js")." - ".$query." - ".$connect->ErrorMsg()."\")\n //-->\n</script>\n";
            }
            fixorder($lid);
            break;
    }
}
示例#6
0
文件: quota.php 项目: ddrmoscow/queXS
             }
             // Fix bug with FCKEditor saving strange BR types
             $_POST['quotals_message_' . $lang] = fix_FCKeditor_text($_POST['quotals_message_' . $lang]);
             include_once dirname(__FILE__) . '/../quexs.php';
             //queXS Addition
             //Now save the language to the database:
             $query = "INSERT INTO " . db_table_name('quota_languagesettings') . " (quotals_quota_id, quotals_language, quotals_name, quotals_message, quotals_url, quotals_urldescrip)\n                    VALUES ('{$quotaid}', '{$lang}', '" . db_quote($_POST['quota_name'], true) . "', '" . db_quote($_POST['quotals_message_' . $lang], true) . "', '" . QUEXS_URL . "rs_quota_end.php" . "', '" . QUEXS_URL . "rs_quota_end.php" . "')";
             $connect->Execute($query) or safe_die($connect->ErrorMsg());
         }
     }
     //End insert language based components
     $viewquota = "1";
 }
 //End foreach $lang
 if ($subaction == "modifyquota" && bHasSurveyPermission($surveyid, 'quotas', 'update')) {
     $query = "UPDATE " . db_table_name('quota') . "\n            SET name=" . db_quoteall($_POST['quota_name'], true) . ",\n            qlimit=" . db_quoteall($_POST['quota_limit'], true) . "\n            WHERE id=" . db_quoteall($_POST['quota_id'], true);
     $connect->Execute($query) or safe_die("Error modifying quota" . $connect->ErrorMsg());
     //Get the languages used in this survey
     $langs = GetAdditionalLanguagesFromSurveyID($surveyid);
     $baselang = GetBaseLanguageFromSurveyID($surveyid);
     array_push($langs, $baselang);
     //Iterate through each language, and make sure there is a quota message for it
     $errorstring = '';
     foreach ($langs as $lang) {
         if (!$_POST['quotals_message_' . $lang]) {
             $errorstring .= GetLanguageNameFromCode($lang, false) . "\\n";
         }
     }
     if ($errorstring != '') {
         $quotasoutput .= "<script type=\"text/javascript\">\n<!--\n alert(\"" . $clang->gT("Quota could not be added.\\n\\nIt is missing a quota message for the following languages", "js") . ":\\n" . $errorstring . "\")\n //-->\n</script>\n";
     } else {
示例#7
0
         $lr = db_execute_assoc($lq);
         while ($lrow = $lr->FetchRow()) {
             $fquest .= " [" . strip_tags_full($lrow['question']) . "]";
         }
     }
     break;
 case ":":
 case ";":
     list($faid, $fcode) = explode("_", $faid);
     if ($answers == "short") {
         $fquest .= " [{$fcode}] [{$faid}]";
     } else {
         $fquery = "SELECT sq.question" . " FROM " . db_table_name('questions') . " sq" . " WHERE sq.sid={$surveyid} " . "AND sq.language='" . GetBaseLanguageFromSurveyID($surveyid) . "'" . " AND sq.language='" . GetBaseLanguageFromSurveyID($surveyid) . "'\n                               AND sq.parent_qid={$fqid} and sq.title=" . db_quoteall($faid) . "\n                               AND sq.scale_id=0";
         $sSubquestionY = $connect->GetOne($fquery);
         // Get the X-Axis
         $aquery = "SELECT sq.question\n                                FROM " . db_table_name('questions') . " q, " . db_table_name('questions') . " sq \n                                WHERE q.sid={$surveyid} \n                                AND sq.parent_qid=q.qid\n                                AND q.language='" . GetBaseLanguageFromSurveyID($surveyid) . "'\n                                AND sq.language='" . GetBaseLanguageFromSurveyID($surveyid) . "'\n                                AND q.parent_qid={$faid} and q.title=" . db_quoteall($fcode) . "\n                                AND sq.scale_id=1";
         $sSubquestionX = $connect->GetOne($aquery);
         $fquest .= " [" . strip_tags_full($sSubquestionY) . "] [" . strip_tags_full($sSubquestionX) . "]";
     }
     break;
 case "1":
     // multi scale Headline
     $iAnswerScale = substr($fieldinfo, -1) + 1;
     $lq = "select sq.question from {$dbprefix}questions as sq where sq.title='{$faid}' and parent_qid={$fqid} AND sq.language='{$surveybaselang}' and sq.scale_id=0";
     $lr = db_execute_assoc($lq);
     $j = 0;
     while ($lrow = $lr->FetchRow()) {
         $fquest .= " [" . FlattenText($lrow['question'], true) . "][Scale {$iAnswerScale}]";
         $j++;
     }
     break;
/**
* Returns true when a token can not be used (either doesn't exist or has less then one usage left
*
* @param mixed $tid Token
*/
function usedTokens($token)
{
    global $dbprefix, $surveyid;
    $utresult = true;
    $query = "SELECT tid, usesleft from {$dbprefix}tokens_{$surveyid} WHERE token=" . db_quoteall($token);
    $result = db_execute_assoc($query, null, true);
    if ($result !== false) {
        $row = $result->FetchRow();
        if ($row['usesleft'] > 0) {
            $utresult = false;
        }
    }
    return $utresult;
}
示例#9
0
 $editsurvey .= "<div id='tabs'><ul>\n            <li><a href='#general'>" . $clang->gT("General") . "</a></li>\n            <li><a href='#presentation'>" . $clang->gT("Presentation & navigation") . "</a></li>\n            <li><a href='#publication'>" . $clang->gT("Publication & access control") . "</a></li>\n            <li><a href='#notification'>" . $clang->gT("Notification & data management") . "</a></li>\n            <li><a href='#tokens'>" . $clang->gT("Tokens") . "</a></li>\n            <li><a href='#import'>" . $clang->gT("Import") . "</a></li>\n            <li><a href='#copy'>" . $clang->gT("Copy") . "</a></li>\n            </ul>\n            \n";
 $editsurvey .= "<form class='form30' name='addnewsurvey' id='addnewsurvey' action='{$scriptname}' method='post' >\n";
 // General & Contact TAB
 $editsurvey .= "<div id='general'>\n";
 // Survey Language
 $editsurvey .= "<ul><li><label for='language' title='" . $clang->gT("This is the base language of your survey and it can't be changed later. You can add more languages after you have created the survey.") . "'><span class='annotationasterisk'>*</span>" . $clang->gT("Base language:") . "</label>\n" . "<select id='language' name='language'>\n";
 foreach (getLanguageData() as $langkey2 => $langname) {
     $editsurvey .= "<option value='" . $langkey2 . "'";
     if ($defaultlang == $langkey2) {
         $editsurvey .= " selected='selected'";
     }
     $editsurvey .= ">" . $langname['description'] . "</option>\n";
 }
 $editsurvey .= "</select>\n";
 //Use the current user details for the default administrator name and email for this survey
 $query = "SELECT full_name, email FROM " . db_table_name('users') . " WHERE users_name = " . db_quoteall($_SESSION['user']);
 $result = db_execute_assoc($query) or safe_die($connect->ErrorMsg());
 $owner = $result->FetchRow();
 //Degrade gracefully to $siteadmin details if anything is missing.
 if (empty($owner['full_name'])) {
     $owner['full_name'] = $siteadminname;
 }
 if (empty($owner['email'])) {
     $owner['email'] = $siteadminemail;
 }
 //Bounce setting by default to global if it set globally
 if (getGlobalSetting('bounceaccounttype') != 'off') {
     $owner['bounce_email'] = getGlobalSetting('siteadminbounce');
 } else {
     $owner['bounce_email'] = $owner['email'];
 }
示例#10
0
/**
 * Caculate assessement scores
 *
 * @param mixed $surveyid
 * @param mixed $returndataonly - only returns an array with data
 */
function doAssessment($surveyid, $returndataonly = false)
{
    global $dbprefix, $thistpl, $connect;
    $baselang = GetBaseLanguageFromSurveyID($surveyid);
    $total = 0;
    if (!isset($_SESSION['s_lang'])) {
        $_SESSION['s_lang'] = $baselang;
    }
    $query = "SELECT * FROM " . db_table_name('assessments') . "\n\t\t\t  WHERE sid={$surveyid} and language='{$_SESSION['s_lang']}'\n\t\t\t  ORDER BY scope";
    if ($result = db_execute_assoc($query)) {
        if ($result->RecordCount() > 0) {
            while ($row = $result->FetchRow()) {
                if ($row['scope'] == "G") {
                    $assessment['group'][$row['gid']][] = array("name" => $row['name'], "min" => $row['minimum'], "max" => $row['maximum'], "message" => $row['message']);
                } else {
                    $assessment['total'][] = array("name" => $row['name'], "min" => $row['minimum'], "max" => $row['maximum'], "message" => $row['message']);
                }
            }
            $fieldmap = createFieldMap($surveyid, "full");
            $i = 0;
            $total = 0;
            $groups = array();
            foreach ($fieldmap as $field) {
                if (in_array($field['type'], array('1', 'F', 'H', 'W', 'Z', 'L', '!', 'M', 'O', 'P'))) {
                    $fieldmap[$field['fieldname']]['assessment_value'] = 0;
                    if (isset($_SESSION[$field['fieldname']])) {
                        if ($field['type'] == ':') {
                            $fieldmap[$field['fieldname']]['assessment_value'] = $_SESSION[$field['fieldname']];
                            $total = $total + $_SESSION[$field['fieldname']];
                        } else {
                            $usquery = "SELECT assessment_value FROM " . db_table_name("answers") . " where qid=" . $field['qid'] . " and language='{$baselang}' and code=" . db_quoteall($_SESSION[$field['fieldname']]);
                            $usresult = db_execute_assoc($usquery);
                            //Checked
                            if ($usresult) {
                                $usrow = $usresult->FetchRow();
                                if ($field['type'] == "M" || $field['type'] == "P") {
                                    if ($_SESSION[$field['fieldname']] == "Y") {
                                        $aAttributes = getQuestionAttributes($field['qid'], $field['type']);
                                        $fieldmap[$field['fieldname']]['assessment_value'] = (int) $aAttributes['assessment_value'];
                                        $total = $total + $usrow['assessment_value'];
                                    }
                                } else {
                                    $fieldmap[$field['fieldname']]['assessment_value'] = $usrow['assessment_value'];
                                    $total = $total + $usrow['assessment_value'];
                                }
                            }
                        }
                    }
                    $groups[] = $field['gid'];
                }
                $i++;
            }
            $groups = array_unique($groups);
            foreach ($groups as $group) {
                $grouptotal = 0;
                foreach ($fieldmap as $field) {
                    if ($field['gid'] == $group && isset($field['assessment_value'])) {
                        //$grouptotal=$grouptotal+$field['answer'];
                        if (isset($_SESSION[$field['fieldname']])) {
                            if ($field['type'] == "M" and $_SESSION[$field['fieldname']] == "Y") {
                                // for Multiple Options type questions
                                $grouptotal = $grouptotal + $field['assessment_value'];
                            } else {
                                // any other type of question
                                $grouptotal = $grouptotal + $field['assessment_value'];
                            }
                        }
                    }
                }
                $subtotal[$group] = $grouptotal;
            }
        }
        $assessments = "";
        if (isset($subtotal) && is_array($subtotal)) {
            foreach ($subtotal as $key => $val) {
                if (isset($assessment['group'][$key])) {
                    foreach ($assessment['group'][$key] as $assessed) {
                        if ($val >= $assessed['min'] && $val <= $assessed['max'] && $returndataonly === false) {
                            $assessments .= "\t<!-- GROUP ASSESSMENT: Score: {$val} Min: " . $assessed['min'] . " Max: " . $assessed['max'] . "-->\n        \t\t\t\t\t    <table class='assessments' align='center'>\n\t\t\t\t\t\t\t\t <tr>\n\t\t\t\t\t\t\t\t  <th>" . str_replace(array("{PERC}", "{TOTAL}"), array($val, $total), $assessed['name']) . "\n\t\t\t\t\t\t\t\t  </th>\n\t\t\t\t\t\t\t\t </tr>\n\t\t\t\t\t\t\t\t <tr>\n\t\t\t\t\t\t\t\t  <td align='center'>" . str_replace(array("{PERC}", "{TOTAL}"), array($val, $total), $assessed['message']) . "\n\t\t\t\t\t\t\t\t </td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t   </table><br />\n";
                        }
                    }
                }
            }
        }
        if (isset($assessment['total'])) {
            foreach ($assessment['total'] as $assessed) {
                if ($total >= $assessed['min'] && $total <= $assessed['max'] && $returndataonly === false) {
                    $assessments .= "\t\t\t<!-- TOTAL ASSESSMENT: Score: {$total} Min: " . $assessed['min'] . " Max: " . $assessed['max'] . "-->\n\t\t\t\t\t\t<table class='assessments' align='center'><tr><th>" . str_replace(array("{PERC}", "{TOTAL}"), array($val, $total), stripslashes($assessed['name'])) . "\n\t\t\t\t\t\t </th></tr>\n\t\t\t\t\t\t <tr>\n\t\t\t\t\t\t  <td align='center'>" . str_replace(array("{PERC}", "{TOTAL}"), array($val, $total), stripslashes($assessed['message'])) . "\n\t\t\t\t\t\t  </td>\n\t\t\t\t\t\t </tr>\n\t\t\t\t\t\t</table>\n";
                }
            }
        }
        if ($returndataonly == true) {
            return array('total' => $total);
        } else {
            return $assessments;
        }
    }
}
示例#11
0
/**
* This function imports an old-school question group file (*.csv,*.sql)
*
* @param mixed $sFullFilepath Full file patch to the import file
* @param mixed $newsid  Survey ID to which the question is attached
*/
function CSVImportGroup($sFullFilepath, $newsid)
{
    global $dbprefix, $connect, $clang;
    $aLIDReplacements = array();
    $aQIDReplacements = array();
    // this array will have the "new qid" for the questions, the key will be the "old qid"
    $aGIDReplacements = array();
    $handle = fopen($sFullFilepath, "r");
    while (!feof($handle)) {
        $buffer = fgets($handle);
        $bigarray[] = $buffer;
    }
    fclose($handle);
    if (substr($bigarray[0], 0, 23) != "# LimeSurvey Group Dump") {
        $results['fatalerror'] = $clang->gT("This file is not a LimeSurvey question file. Import failed.");
        $importversion = 0;
    } else {
        $importversion = (int) trim(substr($bigarray[1], 12));
    }
    if ((int) $importversion < 112) {
        $results['fatalerror'] = $clang->gT("This file is too old. Only files from LimeSurvey version 1.50 (DBVersion 112) and newer are supported.");
    }
    for ($i = 0; $i < 9; $i++) {
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);
    //GROUPS
    if (array_search("# QUESTIONS TABLE\n", $bigarray)) {
        $stoppoint = array_search("# QUESTIONS TABLE\n", $bigarray);
    } elseif (array_search("# QUESTIONS TABLE\r\n", $bigarray)) {
        $stoppoint = array_search("# QUESTIONS TABLE\r\n", $bigarray);
    } else {
        $stoppoint = count($bigarray) - 1;
    }
    for ($i = 0; $i <= $stoppoint + 1; $i++) {
        if ($i < $stoppoint - 2) {
            $grouparray[] = $bigarray[$i];
        }
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);
    //QUESTIONS
    if (array_search("# ANSWERS TABLE\n", $bigarray)) {
        $stoppoint = array_search("# ANSWERS TABLE\n", $bigarray);
    } elseif (array_search("# ANSWERS TABLE\r\n", $bigarray)) {
        $stoppoint = array_search("# ANSWERS TABLE\r\n", $bigarray);
    } else {
        $stoppoint = count($bigarray) - 1;
    }
    for ($i = 0; $i <= $stoppoint + 1; $i++) {
        if ($i < $stoppoint - 2) {
            $questionarray[] = $bigarray[$i];
        }
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);
    //ANSWERS
    if (array_search("# CONDITIONS TABLE\n", $bigarray)) {
        $stoppoint = array_search("# CONDITIONS TABLE\n", $bigarray);
    } elseif (array_search("# CONDITIONS TABLE\r\n", $bigarray)) {
        $stoppoint = array_search("# CONDITIONS TABLE\r\n", $bigarray);
    } else {
        $stoppoint = count($bigarray) - 1;
    }
    for ($i = 0; $i <= $stoppoint + 1; $i++) {
        if ($i < $stoppoint - 2) {
            $answerarray[] = 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);
    }
    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 (!isset($noconditions) || $noconditions != "Y") {
        // stoppoint is the last line number
        // this is an empty line after the QA CSV lines
        $stoppoint = count($bigarray) - 1;
        for ($i = 0; $i <= $stoppoint + 1; $i++) {
            if ($i <= $stoppoint - 1) {
                $question_attributesarray[] = $bigarray[$i];
            }
            unset($bigarray[$i]);
        }
    }
    $bigarray = array_values($bigarray);
    $countgroups = 0;
    if (isset($questionarray)) {
        $questionfieldnames = convertCSVRowToArray($questionarray[0], ',', '"');
        unset($questionarray[0]);
        $countquestions = 0;
    }
    if (isset($answerarray)) {
        $answerfieldnames = convertCSVRowToArray($answerarray[0], ',', '"');
        unset($answerarray[0]);
        $countanswers = count($answerarray);
    } else {
        $countanswers = 0;
    }
    $aLanguagesSupported = array();
    // this array will keep all the languages supported for the survey
    $sBaseLanguage = GetBaseLanguageFromSurveyID($newsid);
    $aLanguagesSupported[] = $sBaseLanguage;
    // adds the base language to the list of supported languages
    $aLanguagesSupported = array_merge($aLanguagesSupported, GetAdditionalLanguagesFromSurveyID($newsid));
    // Let's check that imported objects support at least the survey's baselang
    $langcode = GetBaseLanguageFromSurveyID($newsid);
    if (isset($grouparray)) {
        $groupfieldnames = convertCSVRowToArray($grouparray[0], ',', '"');
        $langfieldnum = array_search("language", $groupfieldnames);
        $gidfieldnum = array_search("gid", $groupfieldnames);
        $groupssupportbaselang = bDoesImportarraySupportsLanguage($grouparray, array($gidfieldnum), $langfieldnum, $sBaseLanguage, true);
        if (!$groupssupportbaselang) {
            $results['fatalerror'] = $clang->gT("You can't import a group which doesn't support at least the survey base language.");
            return $results;
        }
    }
    if (isset($questionarray)) {
        $langfieldnum = array_search("language", $questionfieldnames);
        $qidfieldnum = array_search("qid", $questionfieldnames);
        $questionssupportbaselang = bDoesImportarraySupportsLanguage($questionarray, array($qidfieldnum), $langfieldnum, $sBaseLanguage, true);
        if (!$questionssupportbaselang) {
            $results['fatalerror'] = $clang->gT("You can't import a question which doesn't support at least the survey base language.");
            return $results;
        }
    }
    if ($countanswers > 0) {
        $langfieldnum = array_search("language", $answerfieldnames);
        $answercodefilednum1 = array_search("qid", $answerfieldnames);
        $answercodefilednum2 = array_search("code", $answerfieldnames);
        $answercodekeysarr = array($answercodefilednum1, $answercodefilednum2);
        $answerssupportbaselang = bDoesImportarraySupportsLanguage($answerarray, $answercodekeysarr, $langfieldnum, $sBaseLanguage);
        if (!$answerssupportbaselang) {
            $results['fatalerror'] = $clang->gT("You can't import answers which doesn't support at least the survey base language.");
            return $results;
        }
    }
    if (count($labelsetsarray) > 1) {
        $labelsetfieldname = convertCSVRowToArray($labelsetsarray[0], ',', '"');
        $langfieldnum = array_search("languages", $labelsetfieldname);
        $lidfilednum = array_search("lid", $labelsetfieldname);
        $labelsetssupportbaselang = bDoesImportarraySupportsLanguage($labelsetsarray, array($lidfilednum), $langfieldnum, $sBaseLanguage, true);
        if (!$labelsetssupportbaselang) {
            $results['fatalerror'] = $clang->gT("You can't import label sets which don't support the current survey's base language");
            return $results;
        }
    }
    // I assume that if a labelset supports the survey's baselang,
    // then it's labels do support it as well
    //DO ANY LABELSETS FIRST, SO WE CAN KNOW WHAT THEIR NEW LID IS FOR THE QUESTIONS
    $results['labelsets'] = 0;
    $qtypes = getqtypelist("", "array");
    $results['labels'] = 0;
    $results['labelsets'] = 0;
    $results['answers'] = 0;
    $results['subquestions'] = 0;
    //Do label sets
    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'];
            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);
            $results['labelsets']++;
            // Get the new insert id for the labels inside this labelset
            $newlid = $connect->Insert_ID("{$dbprefix}labelsets", 'lid');
            if ($labelsarray) {
                $count = 0;
                foreach ($labelsarray as $la) {
                    $lfieldorders = convertCSVRowToArray($labelsarray[0], ',', '"');
                    $lfieldcontents = convertCSVRowToArray($la, ',', '"');
                    if ($count == 0) {
                        $count++;
                        continue;
                    }
                    // Combine into one array with keys and values since its easier to handle
                    $labelrowdata = array_combine($lfieldorders, $lfieldcontents);
                    $labellid = $labelrowdata['lid'];
                    if ($importversion <= 132) {
                        $labelrowdata["assessment_value"] = (int) $labelrowdata["code"];
                    }
                    if ($labellid == $oldlid) {
                        $labelrowdata['lid'] = $newlid;
                        // translate internal links
                        $labelrowdata['title'] = translink('label', $oldlid, $newlid, $labelrowdata['title']);
                        $newvalues = array_values($labelrowdata);
                        $newvalues = array_map(array(&$connect, "qstr"), $newvalues);
                        // quote everything accordingly
                        $lainsert = "INSERT INTO {$dbprefix}labels (" . implode(',', array_keys($labelrowdata)) . ") VALUES (" . implode(',', $newvalues) . ")";
                        //handle db prefix
                        $liresult = $connect->Execute($lainsert);
                        if ($liresult !== false) {
                            $results['labels']++;
                        }
                    }
                }
            }
            //CHECK FOR DUPLICATE LABELSETS
            $thisset = "";
            $query2 = "SELECT code, title, sortorder, language, assessment_value\n                       FROM {$dbprefix}labels\n                       WHERE lid=" . $newlid . "\n                       ORDER BY language, sortorder, code";
            $result2 = db_execute_num($query2) or safe_die("Died querying labelset {$lid}<br />{$query2}<br />" . $connect->ErrorMsg());
            while ($row2 = $result2->FetchRow()) {
                $thisset .= implode('.', $row2);
            }
            // while
            $newcs = dechex(crc32($thisset) * 1);
            unset($lsmatch);
            if (isset($csarray)) {
                foreach ($csarray as $key => $val) {
                    if ($val == $newcs) {
                        $lsmatch = $key;
                    }
                }
            }
            if (isset($lsmatch) || $_SESSION['USER_RIGHT_MANAGE_LABEL'] != 1) {
                //There is a matching labelset or the user is not allowed to edit labels -
                // So, we will delete this one and refer to the matched one.
                $query = "DELETE FROM {$dbprefix}labels WHERE lid={$newlid}";
                $result = $connect->Execute($query) or safe_die("Couldn't delete labels<br />{$query}<br />" . $connect->ErrorMsg());
                $results['labels'] = $results['labels'] - $connect->Affected_Rows();
                $query = "DELETE FROM {$dbprefix}labelsets WHERE lid={$newlid}";
                $result = $connect->Execute($query) or safe_die("Couldn't delete labelset<br />{$query}<br />" . $connect->ErrorMsg());
                $results['labelsets'] = $results['labelsets'] - $connect->Affected_Rows();
                $newlid = $lsmatch;
            } else {
                //There isn't a matching labelset, add this checksum to the $csarray array
                $csarray[$newlid] = $newcs;
            }
            //END CHECK FOR DUPLICATES
            $aLIDReplacements[$oldlid] = $newlid;
        }
    }
    // Import groups
    if (isset($grouparray) && $grouparray) {
        // do GROUPS
        $gafieldorders = convertCSVRowToArray($grouparray[0], ',', '"');
        unset($grouparray[0]);
        $newgid = 0;
        $group_order = 0;
        // just to initialize this variable
        foreach ($grouparray as $ga) {
            $gacfieldcontents = convertCSVRowToArray($ga, ',', '"');
            $grouprowdata = array_combine($gafieldorders, $gacfieldcontents);
            // Skip not supported languages
            if (!in_array($grouprowdata['language'], $aLanguagesSupported)) {
                $skippedlanguages[] = $grouprowdata['language'];
                // this is for the message in the end.
                continue;
            }
            // replace the sid
            $oldsid = $grouprowdata['sid'];
            $grouprowdata['sid'] = $newsid;
            // replace the gid  or remove it if needed (it also will calculate the group order if is a new group)
            $oldgid = $grouprowdata['gid'];
            if ($newgid == 0) {
                unset($grouprowdata['gid']);
                // find the maximum group order and use this grouporder+1 to assign it to the new group
                $qmaxgo = "select max(group_order) as maxgo from " . db_table_name('groups') . " where sid={$newsid}";
                $gres = db_execute_assoc($qmaxgo) or safe_die($clang->gT("Error") . " Failed to find out maximum group order value<br />\n{$qmaxqo}<br />\n" . $connect->ErrorMsg());
                $grow = $gres->FetchRow();
                $group_order = $grow['maxgo'] + 1;
            } else {
                $grouprowdata['gid'] = $newgid;
            }
            $grouprowdata["group_order"] = $group_order;
            // Everything set - now insert it
            $grouprowdata = array_map('convertCsvreturn2return', $grouprowdata);
            // translate internal links
            $grouprowdata['group_name'] = translink('survey', $oldsid, $newsid, $grouprowdata['group_name']);
            $grouprowdata['description'] = translink('survey', $oldsid, $newsid, $grouprowdata['description']);
            db_switchIDInsert('groups', true);
            $tablename = $dbprefix . 'groups';
            $ginsert = $connect->GetinsertSQL($tablename, $grouprowdata);
            $gres = $connect->Execute($ginsert) or safe_die($clang->gT('Error') . ": Failed to insert group<br />\n{$ginsert}<br />\n" . $connect->ErrorMsg());
            db_switchIDInsert('groups', false);
            //GET NEW GID  .... if is not done before and we count a group if a new gid is required
            if ($newgid == 0) {
                $newgid = $connect->Insert_ID("{$dbprefix}groups", 'gid');
                $countgroups++;
            }
        }
        // GROUPS is DONE
        // Import questions
        if (isset($questionarray) && $questionarray) {
            foreach ($questionarray as $qa) {
                $qacfieldcontents = convertCSVRowToArray($qa, ',', '"');
                $questionrowdata = array_combine($questionfieldnames, $qacfieldcontents);
                $questionrowdata = array_map('convertCsvreturn2return', $questionrowdata);
                $questionrowdata["type"] = strtoupper($questionrowdata["type"]);
                // Skip not supported languages
                if (!in_array($questionrowdata['language'], $aLanguagesSupported)) {
                    continue;
                }
                // replace the sid
                $questionrowdata["sid"] = $newsid;
                // replace the gid (if the gid is not in the oldgid it means there is a problem with the exported record, so skip it)
                if ($questionrowdata['gid'] == $oldgid) {
                    $questionrowdata['gid'] = $newgid;
                } else {
                    continue;
                }
                // a problem with this question record -> don't consider
                if (isset($aQIDReplacements[$questionrowdata['qid']])) {
                    $questionrowdata['qid'] = $aQIDReplacements[$questionrowdata['qid']];
                } else {
                    $oldqid = $questionrowdata['qid'];
                    unset($questionrowdata['qid']);
                }
                // Save the following values - will need them for proper conversion later                if ((int)$questionrowdata['lid']>0)
                unset($oldlid1);
                unset($oldlid2);
                if (isset($questionrowdata['lid']) && $questionrowdata['lid'] > 0) {
                    $oldlid1 = $questionrowdata['lid'];
                }
                if (isset($questionrowdata['lid1']) && $questionrowdata['lid1'] > 0) {
                    $oldlid2 = $questionrowdata['lid1'];
                }
                unset($questionrowdata['lid']);
                unset($questionrowdata['lid1']);
                if ($questionrowdata['type'] == 'W') {
                    $questionrowdata['type'] = '!';
                } elseif ($questionrowdata['type'] == 'Z') {
                    $questionrowdata['type'] = 'L';
                }
                if (!isset($questionrowdata["question_order"]) || $questionrowdata["question_order"] == '') {
                    $questionrowdata["question_order"] = 0;
                }
                $questionrowdata = array_map('convertCsvreturn2return', $questionrowdata);
                // translate internal links
                $questionrowdata['title'] = translink('survey', $oldsid, $newsid, $questionrowdata['title']);
                $questionrowdata['question'] = translink('survey', $oldsid, $newsid, $questionrowdata['question']);
                $questionrowdata['help'] = translink('survey', $oldsid, $newsid, $questionrowdata['help']);
                $newvalues = array_values($questionrowdata);
                $newvalues = array_map(array(&$connect, "qstr"), $newvalues);
                // quote everything accordingly
                if (isset($questionrowdata['qid'])) {
                    db_switchIDInsert('questions', true);
                }
                $tablename = $dbprefix . 'questions';
                $qinsert = $connect->GetInsertSQL($tablename, $questionrowdata);
                $qres = $connect->Execute($qinsert) or safe_die($clang->gT("Error") . ": Failed to insert question<br />\n{$qinsert}<br />\n" . $connect->ErrorMsg());
                $results['questions']++;
                //GET NEW QID  .... if is not done before and we count a question if a new qid is required
                if (isset($questionrowdata['qid'])) {
                    $saveqid = $questionrowdata['qid'];
                } else {
                    $aQIDReplacements[$oldqid] = $connect->Insert_ID("{$dbprefix}questions", 'qid');
                    $saveqid = $aQIDReplacements[$oldqid];
                }
                $qtypes = getqtypelist("", "array");
                $aSQIDReplacements = array();
                db_switchIDInsert('questions', false);
                // Now we will fix up old label sets where they are used as answers
                if ((isset($oldlid1) || isset($oldlid2)) && ($qtypes[$questionrowdata['type']]['answerscales'] > 0 || $qtypes[$questionrowdata['type']]['subquestions'] > 1)) {
                    $query = "select * from " . db_table_name('labels') . " where lid={$aLIDReplacements[$oldlid1]} and language='{$questionrowdata['language']}'";
                    $oldlabelsresult = db_execute_assoc($query);
                    while ($labelrow = $oldlabelsresult->FetchRow()) {
                        if (in_array($labelrow['language'], $aLanguagesSupported)) {
                            if ($qtypes[$questionrowdata['type']]['subquestions'] < 2) {
                                $qinsert = "insert INTO " . db_table_name('answers') . " (qid,code,answer,sortorder,language,assessment_value)\n                                        VALUES ({$aQIDReplacements[$oldqid]}," . db_quoteall($labelrow['code']) . "," . db_quoteall($labelrow['title']) . "," . db_quoteall($labelrow['sortorder']) . "," . db_quoteall($labelrow['language']) . "," . db_quoteall($labelrow['assessment_value']) . ")";
                                $qres = $connect->Execute($qinsert) or safe_die($clang->gT("Error") . ": Failed to insert answer (lid1) <br />\n{$qinsert}<br />\n" . $connect->ErrorMsg());
                            } else {
                                if (isset($aSQIDReplacements[$labelrow['code'] . '_' . $saveqid])) {
                                    $fieldname = 'qid,';
                                    $data = $aSQIDReplacements[$labelrow['code'] . '_' . $saveqid] . ',';
                                } else {
                                    $fieldname = '';
                                    $data = '';
                                }
                                $qinsert = "insert INTO " . db_table_name('questions') . " ({$fieldname} parent_qid,title,question,question_order,language,scale_id,type, sid, gid)\n                                        VALUES ({$data}{$aQIDReplacements[$oldqid]}," . db_quoteall($labelrow['code']) . "," . db_quoteall($labelrow['title']) . "," . db_quoteall($labelrow['sortorder']) . "," . db_quoteall($labelrow['language']) . ",1,'{$questionrowdata['type']}',{$questionrowdata['sid']},{$questionrowdata['gid']})";
                                $qres = $connect->Execute($qinsert) or safe_die($clang->gT("Error") . ": Failed to insert question <br />\n{$qinsert}<br />\n" . $connect->ErrorMsg());
                                if ($fieldname == '') {
                                    $aSQIDReplacements[$labelrow['code'] . '_' . $saveqid] = $connect->Insert_ID("{$dbprefix}questions", "qid");
                                }
                            }
                        }
                    }
                    if (isset($oldlid2) && $qtypes[$questionrowdata['type']]['answerscales'] > 1) {
                        $query = "select * from " . db_table_name('labels') . " where lid={$aLIDReplacements[$oldlid2]} and language='{$questionrowdata['language']}'";
                        $oldlabelsresult = db_execute_assoc($query);
                        while ($labelrow = $oldlabelsresult->FetchRow()) {
                            $qinsert = "insert INTO " . db_table_name('answers') . " (qid,code,answer,sortorder,language,assessment_value,scale_id)\n                                    VALUES ({$aQIDReplacements[$oldqid]}," . db_quoteall($labelrow['code']) . "," . db_quoteall($labelrow['title']) . "," . db_quoteall($labelrow['sortorder']) . "," . db_quoteall($labelrow['language']) . "," . db_quoteall($labelrow['assessment_value']) . ",1)";
                            $qres = $connect->Execute($qinsert) or safe_die($clang->gT("Error") . ": Failed to insert answer (lid2)<br />\n{$qinsert}<br />\n" . $connect->ErrorMsg());
                        }
                    }
                }
            }
        }
        //Do answers
        $results['subquestions'] = 0;
        if (isset($answerarray) && $answerarray) {
            foreach ($answerarray as $aa) {
                $answerfieldcontents = convertCSVRowToArray($aa, ',', '"');
                $answerrowdata = array_combine($answerfieldnames, $answerfieldcontents);
                if ($answerrowdata === false) {
                    $importquestion .= '<br />' . $clang->gT("Faulty line in import - fields and data don't match") . ":" . implode(',', $answerfieldcontents);
                }
                // Skip not supported languages
                if (!in_array($answerrowdata['language'], $aLanguagesSupported)) {
                    continue;
                }
                // replace the qid for the new one (if there is no new qid in the $aQIDReplacements array it mean that this answer is orphan -> error, skip this record)
                if (isset($aQIDReplacements[$answerrowdata["qid"]])) {
                    $answerrowdata["qid"] = $aQIDReplacements[$answerrowdata["qid"]];
                } else {
                    continue;
                }
                // a problem with this answer record -> don't consider
                if ($importversion <= 132) {
                    $answerrowdata["assessment_value"] = (int) $answerrowdata["code"];
                }
                // Convert default values for single select questions
                $questiontemp = $connect->GetRow('select type,gid from ' . db_table_name('questions') . ' where qid=' . $answerrowdata["qid"]);
                $oldquestion['newtype'] = $questiontemp['type'];
                $oldquestion['gid'] = $questiontemp['gid'];
                if ($answerrowdata['default_value'] == 'Y' && ($oldquestion['newtype'] == 'L' || $oldquestion['newtype'] == 'O' || $oldquestion['newtype'] == '!')) {
                    $insertdata = array();
                    $insertdata['qid'] = $newqid;
                    $insertdata['language'] = $answerrowdata['language'];
                    $insertdata['defaultvalue'] = $answerrowdata['answer'];
                    $query = $connect->GetInsertSQL($dbprefix . 'defaultvalues', $insertdata);
                    $qres = $connect->Execute($query) or safe_die("Error: Failed to insert defaultvalue <br />{$query}<br />\n" . $connect->ErrorMsg());
                }
                // translate internal links
                $answerrowdata['answer'] = translink('survey', $oldsid, $newsid, $answerrowdata['answer']);
                // Everything set - now insert it
                $answerrowdata = array_map('convertCsvreturn2return', $answerrowdata);
                if ($qtypes[$oldquestion['newtype']]['subquestions'] > 0) {
                    $questionrowdata = array();
                    if (isset($aSQIDReplacements[$answerrowdata['code'] . $answerrowdata['qid']])) {
                        $questionrowdata['qid'] = $aSQIDReplacements[$answerrowdata['code'] . $answerrowdata['qid']];
                    }
                    $questionrowdata['parent_qid'] = $answerrowdata['qid'];
                    $questionrowdata['sid'] = $newsid;
                    $questionrowdata['gid'] = $oldquestion['gid'];
                    $questionrowdata['title'] = $answerrowdata['code'];
                    $questionrowdata['question'] = $answerrowdata['answer'];
                    $questionrowdata['question_order'] = $answerrowdata['sortorder'];
                    $questionrowdata['language'] = $answerrowdata['language'];
                    $questionrowdata['type'] = $oldquestion['newtype'];
                    $tablename = $dbprefix . 'questions';
                    $query = $connect->GetInsertSQL($tablename, $questionrowdata);
                    if (isset($questionrowdata['qid'])) {
                        db_switchIDInsert('questions', true);
                    }
                    $qres = $connect->Execute($query) or safe_die("Error: Failed to insert subquestion <br />{$query}<br />" . $connect->ErrorMsg());
                    if (!isset($questionrowdata['qid'])) {
                        $aSQIDReplacements[$answerrowdata['code'] . $answerrowdata['qid']] = $connect->Insert_ID("{$dbprefix}questions", "qid");
                    } else {
                        db_switchIDInsert('questions', false);
                    }
                    $results['subquestions']++;
                    // also convert default values subquestions for multiple choice
                    if ($answerrowdata['default_value'] == 'Y' && ($oldquestion['newtype'] == 'M' || $oldquestion['newtype'] == 'P')) {
                        $insertdata = array();
                        $insertdata['qid'] = $newqid;
                        $insertdata['sqid'] = $aSQIDReplacements[$answerrowdata['code']];
                        $insertdata['language'] = $answerrowdata['language'];
                        $insertdata['defaultvalue'] = 'Y';
                        $tablename = $dbprefix . 'defaultvalues';
                        $query = $connect->GetInsertSQL($tablename, $insertdata);
                        $qres = $connect->Execute($query) or safe_die("Error: Failed to insert defaultvalue <br />{$query}<br />\n" . $connect->ErrorMsg());
                    }
                } else {
                    unset($answerrowdata['default_value']);
                    $tablename = $dbprefix . 'answers';
                    $query = $connect->GetInsertSQL($tablename, $answerrowdata);
                    $ares = $connect->Execute($query) or safe_die("Error: Failed to insert answer<br />{$query}<br />\n" . $connect->ErrorMsg());
                    $results['answers']++;
                }
            }
        }
        // ANSWERS is DONE
        // Fix sortorder of the groups  - if users removed groups manually from the csv file there would be gaps
        fixSortOrderGroups($surveyid);
        //... and for the questions inside the groups
        // get all group ids and fix questions inside each group
        $gquery = "SELECT gid FROM {$dbprefix}groups where sid={$newsid} group by gid ORDER BY gid";
        //Get last question added (finds new qid)
        $gres = db_execute_assoc($gquery);
        while ($grow = $gres->FetchRow()) {
            fixsortorderQuestions($grow['gid'], $newsid);
        }
    }
    $results['question_attributes'] = 0;
    // Finally the question attributes - it is called just once and only if there was a question
    if (isset($question_attributesarray) && $question_attributesarray) {
        //ONLY DO THIS IF THERE ARE QUESTION_ATTRIBUES
        $fieldorders = convertCSVRowToArray($question_attributesarray[0], ',', '"');
        unset($question_attributesarray[0]);
        foreach ($question_attributesarray as $qar) {
            $fieldcontents = convertCSVRowToArray($qar, ',', '"');
            $qarowdata = array_combine($fieldorders, $fieldcontents);
            // replace the qid for the new one (if there is no new qid in the $aQIDReplacements array it mean that this attribute is orphan -> error, skip this record)
            if (isset($aQIDReplacements[$qarowdata["qid"]])) {
                $qarowdata["qid"] = $aQIDReplacements[$qarowdata["qid"]];
            } else {
                continue;
            }
            // a problem with this answer record -> don't consider
            unset($qarowdata["qaid"]);
            $tablename = "{$dbprefix}question_attributes";
            $qainsert = $connect->GetInsertSQL($tablename, $qarowdata);
            $result = $connect->Execute($qainsert);
            if ($result !== false) {
                $results['question_attributes']++;
            }
        }
    }
    // ATTRIBUTES is DONE
    // do CONDITIONS
    $results['conditions'] = 0;
    if (isset($conditionsarray) && $conditionsarray) {
        $fieldorders = convertCSVRowToArray($conditionsarray[0], ',', '"');
        unset($conditionsarray[0]);
        foreach ($conditionsarray as $car) {
            $fieldcontents = convertCSVRowToArray($car, ',', '"');
            $conditionrowdata = array_combine($fieldorders, $fieldcontents);
            $oldqid = $conditionrowdata["qid"];
            $oldcqid = $conditionrowdata["cqid"];
            // replace the qid for the new one (if there is no new qid in the $aQIDReplacements array it mean that this condition is orphan -> error, skip this record)
            if (isset($aQIDReplacements[$oldqid])) {
                $conditionrowdata["qid"] = $aQIDReplacements[$oldqid];
            } else {
                continue;
            }
            // a problem with this answer record -> don't consider
            // replace the cqid for the new one (if there is no new qid in the $aQIDReplacements array it mean that this condition is orphan -> error, skip this record)
            if (isset($aQIDReplacements[$oldcqid])) {
                $conditionrowdata["cqid"] = $aQIDReplacements[$oldcqid];
            } else {
                continue;
            }
            // a problem with this answer record -> don't consider
            list($oldcsid, $oldcgid, $oldqidanscode) = explode("X", $conditionrowdata["cfieldname"], 3);
            if ($oldcgid != $oldgid) {
                // this means that the condition is in another group (so it should not have to be been exported -> skip it
                continue;
            }
            unset($conditionrowdata["cid"]);
            // recreate the cfieldname with the new IDs
            if (preg_match("/^\\+/", $oldcsid)) {
                $newcfieldname = '+' . $newsid . "X" . $newgid . "X" . $conditionrowdata["cqid"] . substr($oldqidanscode, strlen($oldqid));
            } else {
                $newcfieldname = $newsid . "X" . $newgid . "X" . $conditionrowdata["cqid"] . substr($oldqidanscode, strlen($oldqid));
            }
            $conditionrowdata["cfieldname"] = $newcfieldname;
            if (!isset($conditionrowdata["method"]) || trim($conditionrowdata["method"]) == '') {
                $conditionrowdata["method"] = '==';
            }
            $newvalues = array_values($conditionrowdata);
            $newvalues = array_map(array(&$connect, "qstr"), $newvalues);
            // quote everything accordingly
            $conditioninsert = "insert INTO {$dbprefix}conditions (" . implode(',', array_keys($conditionrowdata)) . ") VALUES (" . implode(',', $newvalues) . ")";
            $result = $connect->Execute($conditioninsert) or safe_die("Couldn't insert condition<br />{$conditioninsert}<br />" . $connect->ErrorMsg());
            $results['conditions']++;
        }
    }
    LimeExpressionManager::RevertUpgradeConditionsToRelevance($newsid);
    LimeExpressionManager::UpgradeConditionsToRelevance($newsid);
    $results['groups'] = 1;
    $results['newgid'] = $newgid;
    return $results;
}
示例#12
0
		        	      VALUES ('$quotaid', '$lang', '".db_quote($_POST['quota_name'],true)."', '".db_quote($_POST['quotals_message_'.$lang],true)."', '".db_quote($_POST['quotals_url_'.$lang],true)."', '".db_quote($_POST['quotals_urldescrip_'.$lang],true)."')";
                $connect->Execute($query) or safe_die($connect->ErrorMsg());
            }
        } //End insert language based components
        $viewquota = "1";

    } //End foreach $lang

    if($subaction == "modifyquota" && bHasSurveyPermission($surveyid, 'quotas','update'))
    {
        $query = "UPDATE ".db_table_name('quota')."
			      SET name=".db_quoteall($_POST['quota_name'],true).",
				  qlimit=".db_quoteall($_POST['quota_limit'],true).",
				  action=".db_quoteall($_POST['quota_action'],true).",
				  autoload_url=".db_quoteall($_POST['autoload_url'],true)."
				  WHERE id=".db_quoteall($_POST['quota_id'],true);
        $connect->Execute($query) or safe_die("Error modifying quota".$connect->ErrorMsg());

        //Get the languages used in this survey
        $langs = GetAdditionalLanguagesFromSurveyID($surveyid);
        $baselang = GetBaseLanguageFromSurveyID($surveyid);
        array_push($langs, $baselang);
        //Iterate through each language, and make sure there is a quota message for it
        $errorstring = '';
        foreach ($langs as $lang)
        {
            if (!$_POST['quotals_message_'.$lang]) { $errorstring.= GetLanguageNameFromCode($lang,false)."\\n";}
        }
        if ($errorstring!='')
        {
            $quotasoutput .= "<script type=\"text/javascript\">\n<!--\n alert(\"".$clang->gT("Quota could not be added.\\n\\nIt is missing a quota message for the following languages","js").":\\n".$errorstring."\")\n //-->\n</script>\n";
示例#13
0
$js_admin_includes[] = '../scripts/jquery/jquery.selectboxes.min.js';
$_SESSION['FileManagerContext'] = "edit:answer:{$surveyid}";
// Get languages select on survey.
$anslangs = GetAdditionalLanguagesFromSurveyID($surveyid);
$baselang = GetBaseLanguageFromSurveyID($surveyid);
$qquery = "SELECT type FROM " . db_table_name('questions') . " WHERE qid={$qid} AND language='" . $baselang . "'";
$qrow = $connect->GetRow($qquery);
$qtype = $qrow['type'];
$scalecount = $qtypes[$qtype]['answerscales'];
//Check if there is at least one answer
for ($i = 0; $i < $scalecount; $i++) {
    $qquery = "SELECT count(*) as num_ans  FROM " . db_table_name('answers') . " WHERE qid={$qid} AND scale_id={$i} AND language='" . $baselang . "'";
    $qresult = $connect->GetOne($qquery);
    //Checked
    if ($qresult == 0) {
        $query = "INSERT into " . db_table_name('answers') . " (qid,code,answer,language,sortorder,scale_id) VALUES ({$qid},'A1'," . db_quoteall($clang->gT("Some example answer option")) . ",'{$baselang}',0,{$i})";
        $connect->execute($query);
    }
}
// check that there are answers for every language supported by the survey
for ($i = 0; $i < $scalecount; $i++) {
    foreach ($anslangs as $language) {
        $iAnswerCount = $connect->GetOne("SELECT count(*) as num_ans  FROM " . db_table_name('answers') . " WHERE qid={$qid} AND scale_id={$i} AND language='" . $language . "'");
        if ($iAnswerCount == 0) {
            $qquery = "INSERT INTO " . db_table_name('answers') . " (qid,code,answer,sortorder,language,scale_id, assessment_value) (SELECT qid,code,answer,sortorder, '" . $language . "','{$i}', assessment_value FROM " . db_table_name('answers') . " WHERE qid={$qid} AND scale_id={$i} AND language='" . $baselang . "')";
            $connect->Execute($qquery);
            //Checked
        }
    }
}
array_unshift($anslangs, $baselang);
示例#14
0
/**
* This function imports an old-school question file (*.csv,*.sql)
*
* @param mixed $sFullFilepath Full file patch to the import file
* @param mixed $newsid  Survey ID to which the question is attached
* @param mixed $newgid  Group ID top which the question is attached
*/
function CSVImportQuestion($sFullFilepath, $newsid, $newgid)
{
    global $dbprefix, $connect, $clang;
    $aLIDReplacements = array();
    $aQIDReplacements = array();
    // this array will have the "new qid" for the questions, the key will be the "old qid"
    $aSQIDReplacements = array();
    $results['labelsets'] = 0;
    $results['labels'] = 0;
    $handle = fopen($sFullFilepath, "r");
    while (!feof($handle)) {
        $buffer = fgets($handle);
        //To allow for very long survey welcomes (up to 10k)
        $bigarray[] = $buffer;
    }
    fclose($handle);
    $importversion = 0;
    // Now we try to determine the dataformat of the survey file.
    if (substr($bigarray[1], 0, 24) == "# SURVEYOR QUESTION DUMP") {
        $importversion = 100;
        // version 1.0 or 0.99 file
    } elseif (substr($bigarray[0], 0, 26) == "# LimeSurvey Question Dump" || substr($bigarray[0], 0, 27) == "# PHPSurveyor Question Dump") {
        // This is a >1.0 version file - these files carry the version information to read in line two
        $importversion = (int) substr($bigarray[1], 12, 3);
    } else {
        $results['fatalerror'] = $clang->gT("This file is not a LimeSurvey question file. Import failed.");
        return $results;
    }
    if ((int) $importversion < 112) {
        $results['fatalerror'] = $clang->gT("This file is too old. Only files from LimeSurvey version 1.50 (DBVersion 112) and newer are supported.");
        return $results;
    }
    for ($i = 0; $i < 9; $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("# LABELSETS TABLE\n", $bigarray)) {
        $stoppoint = array_search("# LABELSETS TABLE\n", $bigarray);
    } elseif (array_search("# LABELSETS TABLE\r\n", $bigarray)) {
        $stoppoint = array_search("# LABELSETS TABLE\r\n", $bigarray);
    } else {
        $stoppoint = count($bigarray) - 1;
    }
    for ($i = 0; $i <= $stoppoint + 1; $i++) {
        if ($i < $stoppoint - 2) {
            $answerarray[] = $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
    $stoppoint = count($bigarray);
    for ($i = 0; $i <= $stoppoint + 1; $i++) {
        if ($i < $stoppoint - 1) {
            $question_attributesarray[] = $bigarray[$i];
        }
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);
    if (isset($questionarray)) {
        $questionfieldnames = convertCSVRowToArray($questionarray[0], ',', '"');
        unset($questionarray[0]);
        $countquestions = count($questionarray) - 1;
    } else {
        $countquestions = 0;
    }
    if (isset($answerarray)) {
        $answerfieldnames = convertCSVRowToArray($answerarray[0], ',', '"');
        unset($answerarray[0]);
        $countanswers = count($answerarray);
    } else {
        $countanswers = 0;
    }
    if (isset($labelsetsarray)) {
        $countlabelsets = count($labelsetsarray) - 1;
    } else {
        $countlabelsets = 0;
    }
    if (isset($labelsarray)) {
        $countlabels = count($labelsarray) - 1;
    } else {
        $countlabels = 0;
    }
    if (isset($question_attributesarray)) {
        $countquestion_attributes = count($question_attributesarray) - 1;
    } else {
        $countquestion_attributes = 0;
    }
    $aLanguagesSupported = array();
    // this array will keep all the languages supported for the survey
    $sBaseLanguage = GetBaseLanguageFromSurveyID($newsid);
    $aLanguagesSupported[] = $sBaseLanguage;
    // adds the base language to the list of supported languages
    $aLanguagesSupported = array_merge($aLanguagesSupported, GetAdditionalLanguagesFromSurveyID($newsid));
    // Let's check that imported objects support at least the survey's baselang
    if (isset($questionarray)) {
        $langfieldnum = array_search("language", $questionfieldnames);
        $qidfieldnum = array_search("qid", $questionfieldnames);
        $questionssupportbaselang = bDoesImportarraySupportsLanguage($questionarray, array($qidfieldnum), $langfieldnum, $sBaseLanguage, true);
        if (!$questionssupportbaselang) {
            $results['fatalerror'] = $clang->gT("You can't import a question which doesn't support at least the survey base language.");
            return $results;
        }
    }
    if ($countanswers > 0) {
        $langfieldnum = array_search("language", $answerfieldnames);
        $answercodefilednum1 = array_search("qid", $answerfieldnames);
        $answercodefilednum2 = array_search("code", $answerfieldnames);
        $answercodekeysarr = array($answercodefilednum1, $answercodefilednum2);
        $answerssupportbaselang = bDoesImportarraySupportsLanguage($answerarray, $answercodekeysarr, $langfieldnum, $sBaseLanguage);
        if (!$answerssupportbaselang) {
            $results['fatalerror'] = $clang->gT("You can't import answers which doesn't support at least the survey base language.");
            return $results;
        }
    }
    if ($countlabelsets > 0) {
        $labelsetfieldname = convertCSVRowToArray($labelsetsarray[0], ',', '"');
        $langfieldnum = array_search("languages", $labelsetfieldname);
        $lidfilednum = array_search("lid", $labelsetfieldname);
        $labelsetssupportbaselang = bDoesImportarraySupportsLanguage($labelsetsarray, array($lidfilednum), $langfieldnum, $sBaseLanguage, true);
        if (!$labelsetssupportbaselang) {
            $results['fatalerror'] = $clang->gT("You can't import label sets which don't support the current survey's base language");
            return $results;
        }
    }
    // I assume that if a labelset supports the survey's baselang,
    // then it's labels do support it as well
    //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;
            }
            $results['labelsets']++;
            $labelsetrowdata = array_combine($fieldorders, $fieldcontents);
            // Save old labelid
            $oldlid = $labelsetrowdata['lid'];
            // set the new language
            unset($labelsetrowdata['lid']);
            $newvalues = array_values($labelsetrowdata);
            $newvalues = array_map(array(&$connect, "qstr"), $newvalues);
            // quote everything accordingly
            $lsainsert = "INSERT INTO {$dbprefix}labelsets (" . implode(',', array_keys($labelsetrowdata)) . ") VALUES (" . implode(',', $newvalues) . ")";
            //handle db prefix
            $lsiresult = $connect->Execute($lsainsert);
            // Get the new insert id for the labels inside this labelset
            $newlid = $connect->Insert_ID("{$dbprefix}labelsets", 'lid');
            if ($labelsarray) {
                $count = 0;
                foreach ($labelsarray as $la) {
                    $lfieldorders = convertCSVRowToArray($labelsarray[0], ',', '"');
                    $lfieldcontents = convertCSVRowToArray($la, ',', '"');
                    if ($count == 0) {
                        $count++;
                        continue;
                    }
                    // Combine into one array with keys and values since its easier to handle
                    $labelrowdata = array_combine($lfieldorders, $lfieldcontents);
                    $labellid = $labelrowdata['lid'];
                    if ($importversion <= 132) {
                        $labelrowdata["assessment_value"] = (int) $labelrowdata["code"];
                    }
                    if ($labellid == $oldlid) {
                        $labelrowdata['lid'] = $newlid;
                        // translate internal links
                        $labelrowdata['title'] = translink('label', $oldlid, $newlid, $labelrowdata['title']);
                        $newvalues = array_values($labelrowdata);
                        $newvalues = array_map(array(&$connect, "qstr"), $newvalues);
                        // quote everything accordingly
                        $lainsert = "INSERT INTO {$dbprefix}labels (" . implode(',', array_keys($labelrowdata)) . ") VALUES (" . implode(',', $newvalues) . ")";
                        //handle db prefix
                        $liresult = $connect->Execute($lainsert);
                        $results['labels']++;
                    }
                }
            }
            //CHECK FOR DUPLICATE LABELSETS
            $thisset = "";
            $query2 = "SELECT code, title, sortorder, language, assessment_value\n                       FROM {$dbprefix}labels\n                       WHERE lid=" . $newlid . "\n                       ORDER BY language, sortorder, code";
            $result2 = db_execute_num($query2) or safe_die("Died querying labelset {$lid}<br />{$query2}<br />" . $connect->ErrorMsg());
            while ($row2 = $result2->FetchRow()) {
                $thisset .= implode('.', $row2);
            }
            // while
            $newcs = dechex(crc32($thisset) * 1);
            unset($lsmatch);
            if (isset($csarray)) {
                foreach ($csarray as $key => $val) {
                    if ($val == $newcs) {
                        $lsmatch = $key;
                    }
                }
            }
            if (isset($lsmatch)) {
                //There is a matching labelset. So, we will delete this one and refer
                //to the matched one.
                $query = "DELETE FROM {$dbprefix}labels WHERE lid={$newlid}";
                $result = $connect->Execute($query) or safe_die("Couldn't delete labels<br />{$query}<br />" . $connect->ErrorMsg());
                $query = "DELETE FROM {$dbprefix}labelsets WHERE lid={$newlid}";
                $result = $connect->Execute($query) or safe_die("Couldn't delete labelset<br />{$query}<br />" . $connect->ErrorMsg());
                $newlid = $lsmatch;
            } else {
                //There isn't a matching labelset, add this checksum to the $csarray array
                $csarray[$newlid] = $newcs;
            }
            //END CHECK FOR DUPLICATES
            $aLIDReplacements[$oldlid] = $newlid;
        }
    }
    // Import questions
    if (isset($questionarray) && $questionarray) {
        //Assuming we will only import one question at a time we will now find out the maximum question order in this group
        //and save it for later
        $newquestionorder = $connect->GetOne("SELECT MAX(question_order) AS maxqo FROM " . db_table_name('questions') . " WHERE sid={$newsid} AND gid={$newgid}");
        if (is_null($newquestionorder)) {
            $newquestionorder = 0;
        } else {
            $newquestionorder++;
        }
        foreach ($questionarray as $qa) {
            $qacfieldcontents = convertCSVRowToArray($qa, ',', '"');
            $questionrowdata = array_combine($questionfieldnames, $qacfieldcontents);
            // Skip not supported languages
            if (!in_array($questionrowdata['language'], $aLanguagesSupported)) {
                continue;
            }
            // replace the sid
            $oldqid = $questionrowdata['qid'];
            $oldsid = $questionrowdata['sid'];
            $oldgid = $questionrowdata['gid'];
            // Remove qid field if there is no newqid; and set it to newqid if it's set
            if (!isset($newqid)) {
                unset($questionrowdata['qid']);
            } else {
                db_switchIDInsert('questions', true);
                $questionrowdata['qid'] = $newqid;
            }
            $questionrowdata["sid"] = $newsid;
            $questionrowdata["gid"] = $newgid;
            $questionrowdata["question_order"] = $newquestionorder;
            // Save the following values - will need them for proper conversion later                if ((int)$questionrowdata['lid']>0)
            if ((int) $questionrowdata['lid'] > 0) {
                $oldquestion['lid1'] = (int) $questionrowdata['lid'];
            }
            if ((int) $questionrowdata['lid1'] > 0) {
                $oldquestion['lid2'] = (int) $questionrowdata['lid1'];
            }
            $oldquestion['oldtype'] = $questionrowdata['type'];
            // Unset label set IDs and convert question types
            unset($questionrowdata['lid']);
            unset($questionrowdata['lid1']);
            if ($questionrowdata['type'] == 'W') {
                $questionrowdata['type'] = '!';
            } elseif ($questionrowdata['type'] == 'Z') {
                $questionrowdata['type'] = 'L';
            }
            $oldquestion['newtype'] = $questionrowdata['type'];
            $questionrowdata = array_map('convertCsvreturn2return', $questionrowdata);
            // translate internal links
            $questionrowdata['title'] = translink('survey', $oldsid, $newsid, $questionrowdata['title']);
            $questionrowdata['question'] = translink('survey', $oldsid, $newsid, $questionrowdata['question']);
            $questionrowdata['help'] = translink('survey', $oldsid, $newsid, $questionrowdata['help']);
            $newvalues = array_values($questionrowdata);
            $newvalues = array_map(array(&$connect, "qstr"), $newvalues);
            // quote everything accordingly
            $qinsert = "INSERT INTO {$dbprefix}questions (" . implode(',', array_keys($questionrowdata)) . ") VALUES (" . implode(',', $newvalues) . ")";
            $qres = $connect->Execute($qinsert) or safe_die("Error: Failed to insert question<br />\n{$qinsert}<br />\n" . $connect->ErrorMsg());
            // set the newqid only if is not set
            if (!isset($newqid)) {
                $newqid = $connect->Insert_ID("{$dbprefix}questions", "qid");
            } else {
                db_switchIDInsert('questions', false);
            }
        }
        $qtypes = getqtypelist("", "array");
        $results['answers'] = 0;
        $results['subquestions'] = 0;
        // Now we will fix up old label sets where they are used as answers
        if ((isset($oldquestion['lid1']) || isset($oldquestion['lid2'])) && ($qtypes[$oldquestion['newtype']]['answerscales'] > 0 || $qtypes[$oldquestion['newtype']]['subquestions'] > 1)) {
            $query = "select * from " . db_table_name('labels') . " where lid={$aLIDReplacements[$oldquestion['lid1']]} ";
            $oldlabelsresult = db_execute_assoc($query);
            while ($labelrow = $oldlabelsresult->FetchRow()) {
                if (in_array($labelrow['language'], $aLanguagesSupported)) {
                    if ($qtypes[$oldquestion['newtype']]['subquestions'] < 2) {
                        $qinsert = "insert INTO " . db_table_name('answers') . " (qid,code,answer,sortorder,language,assessment_value,scale_id)\n                                    VALUES ({$newqid}," . db_quoteall($labelrow['code']) . "," . db_quoteall($labelrow['title']) . "," . db_quoteall($labelrow['sortorder']) . "," . db_quoteall($labelrow['language']) . "," . db_quoteall($labelrow['assessment_value']) . ",0)";
                        $qres = $connect->Execute($qinsert) or safe_die("Error: Failed to insert answer <br />\n{$qinsert}<br />\n" . $connect->ErrorMsg());
                        $results['answers']++;
                    } else {
                        if (isset($aSQIDReplacements[$labelrow['code']])) {
                            $fieldname = 'qid,';
                            $data = $aSQIDReplacements[$labelrow['code']] . ',';
                            db_switchIDInsert('questions', true);
                        } else {
                            $fieldname = '';
                            $data = '';
                        }
                        $qinsert = "insert INTO " . db_table_name('questions') . " ({$fieldname} sid,gid,parent_qid,title,question,question_order,language,scale_id,type)\n                                    VALUES ({$data} {$newsid},{$newgid},{$newqid}," . db_quoteall($labelrow['code']) . "," . db_quoteall($labelrow['title']) . "," . db_quoteall($labelrow['sortorder']) . "," . db_quoteall($labelrow['language']) . ",1," . db_quoteall($oldquestion['newtype']) . ")";
                        $qres = $connect->Execute($qinsert) or safe_die("Error: Failed to insert subquestion <br />\n{$qinsert}<br />\n" . $connect->ErrorMsg());
                        if ($fieldname == '') {
                            $aSQIDReplacements[$labelrow['code']] = $connect->Insert_ID("{$dbprefix}questions", "qid");
                        } else {
                            db_switchIDInsert('questions', false);
                        }
                    }
                }
            }
            if (isset($oldquestion['lid2']) && $qtypes[$oldquestion['newtype']]['answerscales'] > 1) {
                $query = "select * from " . db_table_name('labels') . " where lid={$aLIDReplacements[$oldquestion['lid2']]}";
                $oldlabelsresult = db_execute_assoc($query);
                while ($labelrow = $oldlabelsresult->FetchRow()) {
                    if (in_array($labelrow['language'], $aLanguagesSupported)) {
                        $qinsert = "insert INTO " . db_table_name('answers') . " (qid,code,answer,sortorder,language,assessment_value,scale_id)\n                                    VALUES ({$newqid}," . db_quoteall($labelrow['code']) . "," . db_quoteall($labelrow['title']) . "," . db_quoteall($labelrow['sortorder']) . "," . db_quoteall($labelrow['language']) . "," . db_quoteall($labelrow['assessment_value']) . ",1)";
                        $qres = $connect->Execute($qinsert) or safe_die($clang->gT("Error") . ": Failed to insert answer <br />\n{$qinsert}<br />\n" . $connect->ErrorMsg());
                    }
                }
            }
        }
        //Do answers
        if (isset($answerarray) && $answerarray) {
            foreach ($answerarray as $aa) {
                $answerfieldcontents = convertCSVRowToArray($aa, ',', '"');
                $answerrowdata = array_combine($answerfieldnames, $answerfieldcontents);
                if ($answerrowdata === false) {
                    $importquestion .= '<br />' . $clang->gT("Faulty line in import - fields and data don't match") . ":" . implode(',', $answerfieldcontents);
                }
                // Skip not supported languages
                if (!in_array($answerrowdata['language'], $aLanguagesSupported)) {
                    continue;
                }
                $code = $answerrowdata["code"];
                $thisqid = $answerrowdata["qid"];
                $answerrowdata["qid"] = $newqid;
                if ($importversion <= 132) {
                    $answerrowdata["assessment_value"] = (int) $answerrowdata["code"];
                }
                // Convert default values for single select questions
                if ($answerrowdata['default_value'] == 'Y' && ($oldquestion['newtype'] == 'L' || $oldquestion['newtype'] == 'O' || $oldquestion['newtype'] == '!')) {
                    $insertdata = array();
                    $insertdata['qid'] = $newqid;
                    $insertdata['language'] = $answerrowdata['language'];
                    $insertdata['defaultvalue'] = $answerrowdata['answer'];
                    $query = $connect->GetInsertSQL($dbprefix . 'defaultvalues', $insertdata);
                    $qres = $connect->Execute($query) or safe_die("Error: Failed to insert defaultvalue <br />{$query}<br />\n" . $connect->ErrorMsg());
                }
                // translate internal links
                $answerrowdata['answer'] = translink('survey', $oldsid, $newsid, $answerrowdata['answer']);
                // Everything set - now insert it
                $answerrowdata = array_map('convertCsvreturn2return', $answerrowdata);
                if ($qtypes[$oldquestion['newtype']]['subquestions'] > 0) {
                    $questionrowdata = array();
                    if (isset($aSQIDReplacements[$answerrowdata['code'] . $answerrowdata['qid']])) {
                        $questionrowdata['qid'] = $aSQIDReplacements[$answerrowdata['code'] . $answerrowdata['qid']];
                        db_switchIDInsert('questions', true);
                    }
                    $questionrowdata['parent_qid'] = $answerrowdata['qid'];
                    $questionrowdata['sid'] = $newsid;
                    $questionrowdata['gid'] = $newgid;
                    $questionrowdata['title'] = $answerrowdata['code'];
                    $questionrowdata['question'] = $answerrowdata['answer'];
                    $questionrowdata['question_order'] = $answerrowdata['sortorder'];
                    $questionrowdata['language'] = $answerrowdata['language'];
                    $questionrowdata['type'] = $oldquestion['newtype'];
                    $tablename = $dbprefix . 'questions';
                    $query = $connect->GetInsertSQL($tablename, $questionrowdata);
                    $qres = $connect->Execute($query) or safe_die("Error: Failed to insert question <br />{$query}<br />\n" . $connect->ErrorMsg());
                    if (!isset($questionrowdata['qid'])) {
                        $aSQIDReplacements[$answerrowdata['code'] . $answerrowdata['qid']] = $connect->Insert_ID("{$dbprefix}questions", "qid");
                    } else {
                        db_switchIDInsert('questions', false);
                    }
                    $results['subquestions']++;
                    // also convert default values subquestions for multiple choice
                    if ($answerrowdata['default_value'] == 'Y' && ($oldquestion['newtype'] == 'M' || $oldquestion['newtype'] == 'P')) {
                        $insertdata = array();
                        $insertdata['qid'] = $newqid;
                        $insertdata['sqid'] = $aSQIDReplacements[$answerrowdata['code']];
                        $insertdata['language'] = $answerrowdata['language'];
                        $insertdata['defaultvalue'] = 'Y';
                        $tablename = $dbprefix . 'defaultvalues';
                        $query = $connect->GetInsertSQL($tablename, $insertdata);
                        $qres = $connect->Execute($query) or safe_die("Error: Failed to insert defaultvalue <br />{$query}<br />\n" . $connect->ErrorMsg());
                    }
                } else {
                    unset($answerrowdata['default_value']);
                    $tablename = $dbprefix . 'answers';
                    $query = $connect->GetInsertSQL($tablename, $answerrowdata);
                    $ares = $connect->Execute($query) or safe_die("Error: Failed to insert answer<br />{$query}<br />\n" . $connect->ErrorMsg());
                    $results['answers']++;
                }
            }
        }
        $results['question_attributes'] = 0;
        // Finally the question attributes - it is called just once and only if there was a question
        if (isset($question_attributesarray) && $question_attributesarray) {
            //ONLY DO THIS IF THERE ARE QUESTION_ATTRIBUES
            $fieldorders = convertCSVRowToArray($question_attributesarray[0], ',', '"');
            unset($question_attributesarray[0]);
            foreach ($question_attributesarray as $qar) {
                $fieldcontents = convertCSVRowToArray($qar, ',', '"');
                $qarowdata = array_combine($fieldorders, $fieldcontents);
                $qarowdata["qid"] = $newqid;
                unset($qarowdata["qaid"]);
                $tablename = "{$dbprefix}question_attributes";
                $qainsert = $connect->GetInsertSQL($tablename, $qarowdata);
                $result = $connect->Execute($qainsert) or safe_die("Couldn't insert question_attribute<br />{$qainsert}<br />" . $connect->ErrorMsg());
                $results['question_attributes']++;
            }
        }
    }
    LimeExpressionManager::SetDirtyFlag();
    // so refreshes syntax highlighting
    $results['newqid'] = $newqid;
    $results['questions'] = 1;
    $results['newqid'] = $newqid;
    return $results;
}
/**
 * setupTranslateFields() creates a customised array with database query
 * information for use by survey translation
 * @global $dbprefix, $clang;
 * @param string $surveyid Survey id
 * @param string $type Type of database field that is being translated, e.g. title, question, etc.
 * @param string $baselang The source translation language code, e.g. "En"
 * @param string $tolang The target translation language code, e.g. "De"
 * @param string $new The new value of the translated string
 * @param string $id1 An index variable used in the database select and update query
 * @param string $id2 An index variable used in the database select and update query
 * @return array
 */
function setupTranslateFields($surveyid, $type, $tolang, $baselang, $id1 = "", $id2 = "", $new = "")
{
    global $dbprefix, $clang;
    switch ($type) {
        case 'title':
            $amTypeOptions = array("querybase" => "SELECT * " . "FROM " . db_table_name('surveys_languagesettings') . " WHERE surveyls_survey_id=" . db_quoteall($surveyid) . " AND surveyls_language=" . db_quoteall($baselang), "queryto" => "SELECT * " . "FROM " . db_table_name('surveys_languagesettings') . " WHERE surveyls_survey_id=" . db_quoteall($surveyid) . " AND surveyls_language=" . db_quoteall($tolang), "queryupdate" => "UPDATE " . db_table_name('surveys_languagesettings') . " SET surveyls_title = " . db_quoteall($new) . " WHERE surveyls_survey_id=" . db_quoteall($surveyid) . " AND surveyls_language=" . db_quoteall($tolang), "id1" => "", "id2" => "", "gid" => FALSE, "qid" => FALSE, "dbColumn" => 'surveyls_title', "description" => $clang->gT("Survey title and description"), "HTMLeditorType" => "title", "HTMLeditorDisplay" => "Inline", "associated" => "description");
            break;
        case 'description':
            $amTypeOptions = array("querybase" => "SELECT * " . "FROM " . db_table_name('surveys_languagesettings') . "WHERE surveyls_survey_id=" . db_quoteall($surveyid) . "AND surveyls_language='{$baselang}'  ", "queryto" => "SELECT * " . "FROM " . db_table_name('surveys_languagesettings') . "WHERE surveyls_survey_id=" . db_quoteall($surveyid) . "AND surveyls_language='{$tolang}'  ", "queryupdate" => "UPDATE " . db_table_name('surveys_languagesettings') . "SET surveyls_description = " . db_quoteall($new) . "WHERE surveyls_survey_id=" . db_quoteall($surveyid) . "AND surveyls_language='{$tolang}'", "id1" => "", "id2" => "", "gid" => FALSE, "qid" => FALSE, "dbColumn" => 'surveyls_description', "description" => $clang->gT("Description:"), "HTMLeditorType" => "description", "HTMLeditorDisplay" => "Inline", "associated" => "");
            break;
        case 'welcome':
            $amTypeOptions = array("querybase" => "SELECT * " . "FROM " . db_table_name('surveys_languagesettings') . "WHERE surveyls_survey_id=" . db_quoteall($surveyid) . "AND surveyls_language='{$baselang}'  ", "queryto" => "SELECT * " . "FROM " . db_table_name('surveys_languagesettings') . "WHERE surveyls_survey_id=" . db_quoteall($surveyid) . "AND surveyls_language='{$tolang}'  ", "queryupdate" => "UPDATE " . db_table_name('surveys_languagesettings') . "SET surveyls_welcometext = " . db_quoteall($new) . "WHERE surveyls_survey_id=" . db_quoteall($surveyid) . "AND surveyls_language='{$tolang}'", "id1" => "", "id2" => "", "gid" => FALSE, "qid" => FALSE, "dbColumn" => 'surveyls_welcometext', "description" => $clang->gT("Welcome and end text"), "HTMLeditorType" => "welcome", "HTMLeditorDisplay" => "Inline", "associated" => "end");
            break;
        case 'end':
            $amTypeOptions = array("querybase" => "SELECT * " . "FROM " . db_table_name('surveys_languagesettings') . "WHERE surveyls_survey_id=" . db_quoteall($surveyid) . "AND surveyls_language='{$baselang}'  ", "queryto" => "SELECT * " . "FROM " . db_table_name('surveys_languagesettings') . "WHERE surveyls_survey_id=" . db_quoteall($surveyid) . "AND surveyls_language='{$tolang}'  ", "queryupdate" => "UPDATE " . db_table_name('surveys_languagesettings') . "SET surveyls_endtext = " . db_quoteall($new) . "WHERE surveyls_survey_id=" . db_quoteall($surveyid) . "AND surveyls_language='{$tolang}'", "id1" => "", "id2" => "", "gid" => FALSE, "qid" => FALSE, "dbColumn" => 'surveyls_endtext', "description" => $clang->gT("End message:"), "HTMLeditorType" => "end", "HTMLeditorDisplay" => "Inline", "associated" => "");
            break;
        case 'group':
            $amTypeOptions = array("querybase" => "SELECT * " . "FROM " . db_table_name('groups') . "WHERE sid=" . db_quoteall($surveyid) . "AND language='{$baselang}' " . "ORDER BY gid ", "queryto" => "SELECT * " . "FROM " . db_table_name('groups') . "WHERE sid=" . db_quoteall($surveyid) . "AND language=" . db_quoteall($tolang) . "ORDER BY gid ", "queryupdate" => "UPDATE " . db_table_name('groups') . "SET group_name = " . db_quoteall($new) . "WHERE gid = '{$id1}' " . "AND sid=" . db_quoteall($surveyid) . "AND language='{$tolang}'", "id1" => "gid", "id2" => "", "gid" => TRUE, "qid" => FALSE, "dbColumn" => "group_name", "description" => $clang->gT("Question groups"), "HTMLeditorType" => "group", "HTMLeditorDisplay" => "Popup", "associated" => "group_desc");
            break;
        case 'group_desc':
            $amTypeOptions = array("querybase" => "SELECT * " . "FROM " . db_table_name('groups') . "WHERE sid=" . db_quoteall($surveyid) . "AND language='{$baselang}' " . "ORDER BY gid ", "queryto" => "SELECT *" . "FROM " . db_table_name('groups') . "WHERE sid=" . db_quoteall($surveyid) . "AND language=" . db_quoteall($tolang) . "ORDER BY gid ", "queryupdate" => "UPDATE " . db_table_name('groups') . "SET description = " . db_quoteall($new) . "WHERE gid = '{$id1}' " . "AND sid=" . db_quoteall($surveyid) . "AND language='{$tolang}'", "id1" => "gid", "id2" => "", "gid" => TRUE, "qid" => FALSE, "dbColumn" => "description", "description" => $clang->gT("Group description"), "HTMLeditorType" => "group_desc", "HTMLeditorDisplay" => "Popup", "associated" => "");
            break;
            //    case 'label':
            //      $amTypeOptions = array(
            //        "querybase" => "SELECT * "
            //                                   ."FROM ".db_table_name('labels')
            //                                   ."WHERE language='{$baselang}' "
            //                                   .  "AND lid='$code' ",
            //        "queryto"   => "SELECT * "
            //                                    ."FROM ".db_table_name('labels')
            //                                    ."WHERE language=".db_quoteall($tolang)
            //                                    .  "AND lid='$code' ",
            //        "queryupdate" => "UPDATE ".db_table_name('labels')
            //                   ."SET title = ".db_quoteall($new)
            //                         ."WHERE lid = '{$id1}' "
            //                           ."AND code='{$id2}' "
            //                           ."AND language='{$tolang}' LIMIT 1",
            //        "dbColumn" => 'title',
            //        "id1"  => 'lid',
            //        "id2"  => 'code',
            //        "description" => $clang->gT("Label sets")
            //      );
            //      break;
        //    case 'label':
        //      $amTypeOptions = array(
        //        "querybase" => "SELECT * "
        //                                   ."FROM ".db_table_name('labels')
        //                                   ."WHERE language='{$baselang}' "
        //                                   .  "AND lid='$code' ",
        //        "queryto"   => "SELECT * "
        //                                    ."FROM ".db_table_name('labels')
        //                                    ."WHERE language=".db_quoteall($tolang)
        //                                    .  "AND lid='$code' ",
        //        "queryupdate" => "UPDATE ".db_table_name('labels')
        //                   ."SET title = ".db_quoteall($new)
        //                         ."WHERE lid = '{$id1}' "
        //                           ."AND code='{$id2}' "
        //                           ."AND language='{$tolang}' LIMIT 1",
        //        "dbColumn" => 'title',
        //        "id1"  => 'lid',
        //        "id2"  => 'code',
        //        "description" => $clang->gT("Label sets")
        //      );
        //      break;
        case 'question':
            $amTypeOptions = array("querybase" => "SELECT * " . "FROM " . db_table_name('questions') . "WHERE sid=" . db_quoteall($surveyid) . "AND language='{$baselang}' " . "AND parent_qid=0 " . "ORDER BY qid ", "queryto" => "SELECT * " . "FROM " . db_table_name('questions') . "WHERE sid=" . db_quoteall($surveyid) . "AND language='{$tolang}' " . " AND parent_qid=0 " . "ORDER BY qid ", "queryupdate" => "UPDATE " . db_table_name('questions') . "SET question = " . db_quoteall($new) . "WHERE qid = '{$id1}' " . "AND sid=" . db_quoteall($surveyid) . " AND parent_qid=0 " . "AND language='{$tolang}'", "dbColumn" => 'question', "id1" => 'qid', "id2" => "", "gid" => TRUE, "qid" => TRUE, "description" => $clang->gT("Questions"), "HTMLeditorType" => "question", "HTMLeditorDisplay" => "Popup", "associated" => "question_help");
            break;
        case 'question_help':
            $amTypeOptions = array("querybase" => "SELECT * " . "FROM " . db_table_name('questions') . "WHERE sid=" . db_quoteall($surveyid) . "AND language='{$baselang}' " . "AND parent_qid=0 " . "ORDER BY qid ", "queryto" => "SELECT * " . "FROM " . db_table_name('questions') . "WHERE sid=" . db_quoteall($surveyid) . "AND language='{$tolang}' " . " AND parent_qid=0 " . "ORDER BY qid ", "queryupdate" => "UPDATE " . db_table_name('questions') . "SET help = " . db_quoteall($new) . "WHERE qid = '{$id1}' " . "AND sid=" . db_quoteall($surveyid) . " AND parent_qid=0 " . "AND language='{$tolang}'", "dbColumn" => 'help', "id1" => 'qid', "id2" => "", "gid" => TRUE, "qid" => TRUE, "description" => "", "HTMLeditorType" => "question_help", "HTMLeditorDisplay" => "Popup", "associated" => "");
            break;
        case 'subquestion':
            $amTypeOptions = array("querybase" => "SELECT * " . "FROM " . db_table_name('questions') . "WHERE sid=" . db_quoteall($surveyid) . "AND language='{$baselang}' AND parent_qid>0 " . "ORDER BY parent_qid,qid ", "queryto" => "SELECT * " . "FROM " . db_table_name('questions') . "WHERE sid=" . db_quoteall($surveyid) . "AND language=" . db_quoteall($tolang) . " AND parent_qid>0 ORDER BY parent_qid,qid ", "queryupdate" => "UPDATE " . db_table_name('questions') . "SET question = " . db_quoteall($new) . "WHERE qid = '{$id1}' " . "AND sid=" . db_quoteall($surveyid) . "AND language='{$tolang}'", "dbColumn" => 'question', "id1" => 'qid', "id2" => "", "gid" => TRUE, "qid" => TRUE, "description" => $clang->gT("Subquestions"), "HTMLeditorType" => "question", "HTMLeditorDisplay" => "Popup", "associated" => "");
            break;
        case 'answer':
            $amTypeOptions = array("querybase" => "SELECT" . db_table_name('answers') . ".*, " . db_table_name('questions') . ".gid " . " FROM " . db_table_name('answers') . ", " . db_table_name('questions') . " WHERE " . db_table_name('questions') . ".sid ='{$surveyid}' " . " AND " . db_table_name('questions') . ".qid = " . db_table_name('answers') . ".qid " . " AND " . db_table_name('questions') . ".language = " . db_table_name('answers') . ".language " . " AND " . db_table_name('questions') . ".language='{$baselang}' " . " ORDER BY qid,code,sortorder", "queryto" => "SELECT" . db_table_name('answers') . ".*, " . db_table_name('questions') . ".gid " . " FROM " . db_table_name('answers') . ", " . db_table_name('questions') . " WHERE " . db_table_name('questions') . ".sid ='{$surveyid}' " . " AND " . db_table_name('questions') . ".qid = " . db_table_name('answers') . ".qid " . " AND " . db_table_name('questions') . ".language = " . db_table_name('answers') . ".language " . " AND " . db_table_name('questions') . ".language=" . db_quoteall($tolang) . "ORDER BY qid,code,sortorder", "queryupdate" => "UPDATE " . db_table_name('answers') . "SET answer = " . db_quoteall($new) . "WHERE qid = '{$id1}' " . "AND code='{$id2}' " . "AND language='{$tolang}'", "dbColumn" => 'answer', "id1" => 'qid', "id2" => 'code', "gid" => FALSE, "qid" => TRUE, "description" => $clang->gT("Answer options"), "HTMLeditorType" => "subquestion", "HTMLeditorDisplay" => "Popup", "associated" => "");
            break;
        case 'emailinvite':
            $amTypeOptions = array("querybase" => "SELECT * FROM " . db_table_name("surveys_languagesettings") . " WHERE surveyls_survey_id={$surveyid} and surveyls_language='{$baselang}'", "queryto" => "SELECT * FROM " . db_table_name("surveys_languagesettings") . " WHERE surveyls_survey_id={$surveyid} and surveyls_language='{$tolang}'", "queryupdate" => "UPDATE " . db_table_name("surveys_languagesettings") . "SET surveyls_email_invite_subj = " . db_quoteall($new) . " WHERE surveyls_survey_id={$surveyid} " . "AND surveyls_language='{$tolang}'", "dbColumn" => 'surveyls_email_invite_subj', "id1" => '', "id2" => '', "gid" => FALSE, "qid" => FALSE, "description" => $clang->gT("Invitation email"), "HTMLeditorType" => "email", "HTMLeditorDisplay" => "", "associated" => "emailinvitebody");
            break;
        case 'emailinvitebody':
            $amTypeOptions = array("querybase" => "SELECT * FROM " . db_table_name("surveys_languagesettings") . " WHERE surveyls_survey_id={$surveyid} and surveyls_language='{$baselang}'", "queryto" => "SELECT * FROM " . db_table_name("surveys_languagesettings") . " WHERE surveyls_survey_id={$surveyid} and surveyls_language='{$tolang}'", "queryupdate" => "UPDATE " . db_table_name("surveys_languagesettings") . "SET surveyls_email_invite = " . db_quoteall($new) . " WHERE surveyls_survey_id={$surveyid} " . "AND surveyls_language='{$tolang}'", "dbColumn" => 'surveyls_email_invite', "id1" => '', "id2" => '', "gid" => FALSE, "qid" => FALSE, "description" => "", "HTMLeditorType" => "email", "HTMLeditorDisplay" => "", "associated" => "");
            break;
        case 'emailreminder':
            $amTypeOptions = array("querybase" => "SELECT * FROM " . db_table_name("surveys_languagesettings") . " WHERE surveyls_survey_id={$surveyid} and surveyls_language='{$baselang}'", "queryto" => "SELECT * FROM " . db_table_name("surveys_languagesettings") . " WHERE surveyls_survey_id={$surveyid} and surveyls_language='{$tolang}'", "queryupdate" => "UPDATE " . db_table_name("surveys_languagesettings") . "SET surveyls_email_remind_subj = " . db_quoteall($new) . " WHERE surveyls_survey_id={$surveyid} " . "AND surveyls_language='{$tolang}'", "dbColumn" => 'surveyls_email_remind_subj', "id1" => '', "id2" => '', "gid" => FALSE, "qid" => FALSE, "description" => $clang->gT("Reminder email"), "HTMLeditorType" => "email", "HTMLeditorDisplay" => "", "associated" => "emailreminderbody");
            break;
        case 'emailreminderbody':
            $amTypeOptions = array("querybase" => "SELECT * FROM " . db_table_name("surveys_languagesettings") . " WHERE surveyls_survey_id={$surveyid} and surveyls_language='{$baselang}'", "queryto" => "SELECT * FROM " . db_table_name("surveys_languagesettings") . " WHERE surveyls_survey_id={$surveyid} and surveyls_language='{$tolang}'", "queryupdate" => "UPDATE " . db_table_name("surveys_languagesettings") . "SET surveyls_email_remind = " . db_quoteall($new) . " WHERE surveyls_survey_id={$surveyid} " . "AND surveyls_language='{$tolang}'", "dbColumn" => 'surveyls_email_remind', "id1" => '', "id2" => '', "gid" => FALSE, "qid" => FALSE, "description" => "", "HTMLeditorType" => "email", "HTMLeditorDisplay" => "", "associated" => "");
            break;
        case 'emailconfirmation':
            $amTypeOptions = array("querybase" => "SELECT * FROM " . db_table_name("surveys_languagesettings") . " WHERE surveyls_survey_id={$surveyid} and surveyls_language='{$baselang}'", "queryto" => "SELECT * FROM " . db_table_name("surveys_languagesettings") . " WHERE surveyls_survey_id={$surveyid} and surveyls_language='{$tolang}'", "queryupdate" => "UPDATE " . db_table_name("surveys_languagesettings") . "SET surveyls_email_confirm_subj = " . db_quoteall($new) . " WHERE surveyls_survey_id={$surveyid} " . "AND surveyls_language='{$tolang}'", "dbColumn" => 'surveyls_email_confirm_subj', "id1" => '', "id2" => '', "gid" => FALSE, "qid" => FALSE, "description" => $clang->gT("Confirmation email"), "HTMLeditorType" => "email", "HTMLeditorDisplay" => "", "associated" => "emailconfirmationbody");
            break;
        case 'emailconfirmationbody':
            $amTypeOptions = array("querybase" => "SELECT * FROM " . db_table_name("surveys_languagesettings") . " WHERE surveyls_survey_id={$surveyid} and surveyls_language='{$baselang}'", "queryto" => "SELECT * FROM " . db_table_name("surveys_languagesettings") . " WHERE surveyls_survey_id={$surveyid} and surveyls_language='{$tolang}'", "queryupdate" => "UPDATE " . db_table_name("surveys_languagesettings") . "SET surveyls_email_confirm = " . db_quoteall($new) . " WHERE surveyls_survey_id={$surveyid} " . "AND surveyls_language='{$tolang}'", "dbColumn" => 'surveyls_email_confirm', "id1" => '', "id2" => '', "gid" => FALSE, "qid" => FALSE, "description" => "", "HTMLeditorType" => "email", "HTMLeditorDisplay" => "", "associated" => "");
            break;
        case 'emailregistration':
            $amTypeOptions = array("querybase" => "SELECT * FROM " . db_table_name("surveys_languagesettings") . " WHERE surveyls_survey_id={$surveyid} and surveyls_language='{$baselang}'", "queryto" => "SELECT * FROM " . db_table_name("surveys_languagesettings") . " WHERE surveyls_survey_id={$surveyid} and surveyls_language='{$tolang}'", "queryupdate" => "UPDATE " . db_table_name("surveys_languagesettings") . "SET surveyls_email_register_subj = " . db_quoteall($new) . " WHERE surveyls_survey_id={$surveyid} " . "AND surveyls_language='{$tolang}'", "dbColumn" => 'surveyls_email_register_subj', "id1" => '', "id2" => '', "gid" => FALSE, "qid" => FALSE, "description" => $clang->gT("Registration email"), "HTMLeditorType" => "email", "HTMLeditorDisplay" => "", "associated" => "emailregistrationbody");
            break;
        case 'emailregistrationbody':
            $amTypeOptions = array("querybase" => "SELECT * FROM " . db_table_name("surveys_languagesettings") . " WHERE surveyls_survey_id={$surveyid} and surveyls_language='{$baselang}'", "queryto" => "SELECT * FROM " . db_table_name("surveys_languagesettings") . " WHERE surveyls_survey_id={$surveyid} and surveyls_language='{$tolang}'", "queryupdate" => "UPDATE " . db_table_name("surveys_languagesettings") . "SET surveyls_email_register = " . db_quoteall($new) . " WHERE surveyls_survey_id={$surveyid} " . "AND surveyls_language='{$tolang}'", "dbColumn" => 'surveyls_email_register', "id1" => '', "id2" => '', "gid" => FALSE, "qid" => FALSE, "description" => "", "HTMLeditorType" => "email", "HTMLeditorDisplay" => "", "associated" => "");
            break;
        case 'email_confirm':
            $amTypeOptions = array("querybase" => "SELECT * FROM " . db_table_name("surveys_languagesettings") . " WHERE surveyls_survey_id={$surveyid} and surveyls_language='{$baselang}'", "queryto" => "SELECT * FROM " . db_table_name("surveys_languagesettings") . " WHERE surveyls_survey_id={$surveyid} and surveyls_language='{$tolang}'", "queryupdate" => "UPDATE " . db_table_name("surveys_languagesettings") . "SET surveyls_email_confirm_subj = " . db_quoteall($new) . " WHERE surveyls_survey_id={$surveyid} " . "AND surveyls_language='{$tolang}'", "dbColumn" => 'surveyls_email_confirm_subj', "id1" => '', "id2" => '', "gid" => FALSE, "qid" => FALSE, "description" => $clang->gT("Confirmation email"), "HTMLeditorType" => "email", "HTMLeditorDisplay" => "", "associated" => "email_confirmbody");
            break;
        case 'email_confirmbody':
            $amTypeOptions = array("querybase" => "SELECT * FROM " . db_table_name("surveys_languagesettings") . " WHERE surveyls_survey_id={$surveyid} and surveyls_language='{$baselang}'", "queryto" => "SELECT * FROM " . db_table_name("surveys_languagesettings") . " WHERE surveyls_survey_id={$surveyid} and surveyls_language='{$tolang}'", "queryupdate" => "UPDATE " . db_table_name("surveys_languagesettings") . "SET surveyls_email_confirm = " . db_quoteall($new) . " WHERE surveyls_survey_id={$surveyid} " . "AND surveyls_language='{$tolang}'", "dbColumn" => 'surveyls_email_confirm', "id1" => '', "id2" => '', "gid" => FALSE, "qid" => FALSE, "description" => "", "HTMLeditorType" => "email", "HTMLeditorDisplay" => "", "associated" => "");
            break;
    }
    return $amTypeOptions;
}
         } elseif ($meetminirequirements === true) {
             // No issue, let's import
             $iq = "INSERT INTO " . db_table_name("tokens_{$surveyid}") . " \n" . "(firstname, lastname, email, emailstatus, token, language";
             foreach ($aTokenAttr as $thisattrfieldname) {
                 $attridx = substr($thisattrfieldname, 10);
                 // the 'attribute_' prefix is 10 chars long
                 if (!empty($myattrArray[$attridx])) {
                     $iq .= ", {$thisattrfieldname}";
                 }
             }
             $iq .= ") \n" . "VALUES (" . db_quoteall($myfirstname) . ", " . db_quoteall($mylastname) . ", " . db_quoteall($myemail) . ", 'OK', " . db_quoteall($mytoken) . ", " . db_quoteall($mylanguage) . "";
             foreach ($aTokenAttr as $thisattrfieldname) {
                 $attridx = substr($thisattrfieldname, 10);
                 // the 'attribute_' prefix is 10 chars long
                 if (!empty($myattrArray[$attridx])) {
                     $iq .= ", " . db_quoteall($myattrArray[$attridx]) . "";
                 }
                 // dbquote_all encloses str with quotes
             }
             $iq .= ")";
             $ir = $connect->Execute($iq);
             if (!$ir) {
                 $duplicatecount++;
             }
             $xz++;
             // or safe_die ("Couldn't insert line<br />\n$buffer<br />\n".htmlspecialchars($connect->ErrorMsg())."<pre style='text-align: left'>$iq</pre>\n");
         }
     }
     // End for each entry
 }
 // End foreach responseGroup
示例#17
0
//Check that the email is a valid style address
if (!validate_email(returnglobal('register_email')))
{
    $register_errormsg .= $clang->gT("The email you used is not valid. Please try again.");
}

if ($register_errormsg != "")
{
    include "index.php";
    exit;
}

//Check if this email already exists in token database
$query = "SELECT email FROM {$dbprefix}tokens_$surveyid\n"
. "WHERE email = ".db_quoteall(sanitize_email(returnglobal('register_email')));
$result = $connect->Execute($query) or safe_die ($query."<br />".$connect->ErrorMsg());   //Checked
if (($result->RecordCount()) > 0)
{
    $register_errormsg=$clang->gT("The email you used has already been registered.");
    include "index.php";
    exit;
}

$mayinsert = false;
while ($mayinsert != true)
{
    $newtoken = sRandomChars(15);
    $ntquery = "SELECT * FROM {$dbprefix}tokens_$surveyid WHERE token='$newtoken'";
    $ntresult = $connect->Execute($ntquery); //Checked
    if (!$ntresult->RecordCount()) {$mayinsert = true;}
示例#18
0
    if (count($subquestiondata) == 0) {
        $sQuery = "INSERT INTO " . db_table_name('questions') . " (sid,gid,parent_qid,title,question,question_order,language,scale_id)\n                       VALUES({$surveyid},{$gid},{$qid},'SQ001'," . db_quoteall($clang->gT('Some example subquestion')) . ",1," . db_quoteall($baselang) . ",{$iScale})";
        $connect->Execute($sQuery);
        //Checked
        $sQuery = "SELECT * FROM " . db_table_name('questions') . " WHERE parent_qid={$qid} AND language='{$baselang}' and scale_id={$iScale}";
        $subquestiondata = $connect->GetArray($sQuery);
    }
    // check that there are subquestions for every language supported by the survey
    foreach ($anslangs as $language) {
        foreach ($subquestiondata as $row) {
            $sQuery = "SELECT count(*) FROM " . db_table_name('questions') . " WHERE parent_qid={$qid} AND language='{$language}' AND qid={$row['qid']} and scale_id={$iScale}";
            $qrow = $connect->GetOne($sQuery);
            //Checked
            if ($qrow == 0) {
                db_switchIDInsert('questions', true);
                $sQuery = "INSERT INTO " . db_table_name('questions') . " (qid,sid,gid,parent_qid,title,question,question_order,language, scale_id)\n                               VALUES({$row['qid']},{$surveyid},{$row['gid']},{$qid}," . db_quoteall($row['title']) . "," . db_quoteall($row['question']) . ",{$row['question_order']}," . db_quoteall($language) . ",{$iScale})";
                $connect->Execute($sQuery);
                //Checked
                db_switchIDInsert('questions', false);
            }
        }
    }
}
array_unshift($anslangs, $baselang);
// makes an array with ALL the languages supported by the survey -> $anslangs
$vasummary = "\n<script type='text/javascript'>\n                      var languagecount=" . count($anslangs) . ";\n\n                      var newansweroption_text='" . $clang->gT('New answer option', 'js') . "';\n                      var strcode='" . $clang->gT('Code', 'js') . "';\n                      var strlabel='" . $clang->gT('Label', 'js') . "';\n                      var strCantDeleteLastAnswer='" . $clang->gT('You cannot delete the last subquestion.', 'js') . "';\n                      var lsbrowsertitle='" . $clang->gT('Label set browser', 'js') . "';\n                      var quickaddtitle='" . $clang->gT('Quick-add subquestions', 'js') . "';\n                      var duplicateanswercode='" . $clang->gT('Error: You are trying to use duplicate subquestion codes.', 'js') . "';\n                      var strNoLabelSet='" . $clang->gT('There are no label sets which match the survey default language', 'js') . "';\n                      var langs='" . implode(';', $anslangs) . "';</script>\n";
//delete the subquestions in languages not supported by the survey
$qquery = "SELECT DISTINCT language FROM " . db_table_name('questions') . " WHERE (parent_qid = {$qid}) AND (language NOT IN ('" . implode("','", $anslangs) . "'))";
$qresult = db_execute_assoc($qquery);
//Checked
while ($qrow = $qresult->FetchRow()) {
示例#19
0
/**
* This is a convenience function to update/delete answer default values. If the given
* $defaultvalue is empty then the entry is removed from table defaultvalues
*
* @param mixed $qid   Question ID
* @param mixed $scale_id  Scale ID
* @param mixed $specialtype  Special type (i.e. for  'Other')
* @param mixed $language     Language (defaults are language specific)
* @param mixed $defaultvalue    The default value itself
* @param boolean $ispost   If defaultvalue is from a $_POST set this to true to properly quote things
*/
function Updatedefaultvalues($qid, $sqid, $scale_id, $specialtype, $language, $defaultvalue, $ispost)
{
    global $connect;
    if ($defaultvalue == '') {
        $connect->execute("DELETE FROM " . db_table_name('defaultvalues') . " WHERE sqid={$sqid} AND qid={$qid} AND specialtype='{$specialtype}' AND scale_id={$scale_id} AND language='{$language}'");
    } else {
        $exists = $connect->GetOne("SELECT qid FROM " . db_table_name('defaultvalues') . " WHERE sqid={$sqid} AND qid={$qid} AND specialtype={$specialtype}'' AND scale_id={$scale_id} AND language='{$language}'");
        if ($exists === false || $exists === null) {
            $connect->execute('INSERT INTO ' . db_table_name('defaultvalues') . " (defaultvalue,qid,scale_id,language,specialtype,sqid) VALUES (" . db_quoteall($defaultvalue, $ispost) . ",{$qid},{$scale_id},'{$language}','{$specialtype}',{$sqid})");
        } else {
            $connect->execute('UPDATE ' . db_table_name('defaultvalues') . " set defaultvalue=" . db_quoteall($defaultvalue, $ispost) . "  WHERE sqid={$sqid} AND qid={$qid} AND specialtype='{$specialtype}' AND scale_id={$scale_id} AND language='{$language}'");
        }
    }
}
/**
* This function imports the old CSV data from 1.50 to 1.87 or older. Starting with 1.90 (DBVersion 143) there is an XML format instead
*
* @param array $sFullFilepath
* @returns array Information of imported questions/answers/etc.
*/
function CSVImportSurvey($sFullFilepath,$iDesiredSurveyId=NULL)
{
    global $dbprefix, $connect, $timeadjust, $clang;

    $handle = fopen($sFullFilepath, "r");
    while (!feof($handle))
    {

        $buffer = fgets($handle);
        $bigarray[] = $buffer;
    }
    fclose($handle);

    $aIgnoredAnswers=array();
    $aSQIDReplacements=array();
    $aLIDReplacements=array();
    $aGIDReplacements=array();
    $substitutions=array();
    $aQuotaReplacements=array();
    $importresults['error']=false;
    $importresults['importwarnings']=array();
    $importresults['question_attributes']=0;

    if (isset($bigarray[0])) $bigarray[0]=removeBOM($bigarray[0]);

    // Now we try to determine the dataformat of the survey file.
    $importversion=0;
    if (isset($bigarray[1]) && isset($bigarray[4])&& (substr($bigarray[1], 0, 22) == "# SURVEYOR SURVEY DUMP"))
    {
        $importversion = 100;  // Version 0.99 or  1.0 file
    }
    elseif
    (substr($bigarray[0], 0, 24) == "# LimeSurvey Survey Dump" || substr($bigarray[0], 0, 25) == "# PHPSurveyor Survey Dump")
    {  // Seems to be a >1.0 version file - these files carry the version information to read in line two
        $importversion=substr($bigarray[1], 12, 3);
    }
    else    // unknown file - show error message
    {
        $importresults['error'] = $clang->gT("This file is not a LimeSurvey survey file. Import failed.")."\n";
        return $importresults;
    }

    if  ((int)$importversion<112)
    {
        $importresults['error'] = $clang->gT("This file is too old. Only files from LimeSurvey version 1.50 (DBVersion 112) and newer are supported.");
        return $importresults;
    }

    // okay.. now lets drop the first 9 lines and get to the data
    // This works for all versions
    for ($i=0; $i<9; $i++)
    {
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);


    //SURVEYS
    if (array_search("# GROUPS TABLE\n", $bigarray))
    {
        $stoppoint = array_search("# GROUPS TABLE\n", $bigarray);
    }
    elseif (array_search("# GROUPS TABLE\r\n", $bigarray))
    {
        $stoppoint = array_search("# GROUPS TABLE\r\n", $bigarray);
    }
    for ($i=0; $i<=$stoppoint+1; $i++)
    {
        if ($i<$stoppoint-2) {$surveyarray[] = $bigarray[$i];}
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);

    //GROUPS
    if (array_search("# QUESTIONS TABLE\n", $bigarray))
    {
        $stoppoint = array_search("# QUESTIONS TABLE\n", $bigarray);
    }
    elseif (array_search("# QUESTIONS TABLE\r\n", $bigarray))
    {
        $stoppoint = array_search("# QUESTIONS TABLE\r\n", $bigarray);
    }
    else
    {
        $stoppoint = count($bigarray)-1;
    }
    for ($i=0; $i<=$stoppoint+1; $i++)
    {
        if ($i<$stoppoint-2) {$grouparray[] = $bigarray[$i];}
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);

    //QUESTIONS
    if (array_search("# ANSWERS TABLE\n", $bigarray))
    {
        $stoppoint = array_search("# ANSWERS TABLE\n", $bigarray);
    }
    elseif (array_search("# ANSWERS TABLE\r\n", $bigarray))
    {
        $stoppoint = array_search("# ANSWERS TABLE\r\n", $bigarray);
    }
    else
    {
        $stoppoint = count($bigarray)-1;
    }
    for ($i=0; $i<=$stoppoint+1; $i++)
    {
        if ($i<$stoppoint-2)
        {
            $questionarray[] = $bigarray[$i];
        }
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);

    //ANSWERS
    if (array_search("# CONDITIONS TABLE\n", $bigarray))
    {
        $stoppoint = array_search("# CONDITIONS TABLE\n", $bigarray);
    }
    elseif (array_search("# CONDITIONS TABLE\r\n", $bigarray))
    {
        $stoppoint = array_search("# CONDITIONS TABLE\r\n", $bigarray);
    }
    else
    {
        $stoppoint = count($bigarray)-1;
    }
    for ($i=0; $i<=$stoppoint+1; $i++)
    {
        if ($i<$stoppoint-2)
        {
            $answerarray[] = str_replace("`default`", "`default_value`", $bigarray[$i]);
        }
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);

    //CONDITIONS
    if (array_search("# LABELSETS TABLE\n", $bigarray))
    {
        $stoppoint = array_search("# LABELSETS TABLE\n", $bigarray);
    }
    elseif (array_search("# LABELSETS TABLE\r\n", $bigarray))
    {
        $stoppoint = array_search("# LABELSETS TABLE\r\n", $bigarray);
    }
    for ($i=0; $i<=$stoppoint+1; $i++)
    {
        if ($i<$stoppoint-2) {$conditionsarray[] = $bigarray[$i];}
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);

    //LABELSETS
    if (array_search("# LABELS TABLE\n", $bigarray))
    {
        $stoppoint = array_search("# LABELS TABLE\n", $bigarray);
    }
    elseif (array_search("# LABELS TABLE\r\n", $bigarray))
    {
        $stoppoint = array_search("# LABELS TABLE\r\n", $bigarray);
    }
    else
    {
        $stoppoint = count($bigarray)-1;
    }
    for ($i=0; $i<=$stoppoint+1; $i++)
    {
        if ($i<$stoppoint-2) {$labelsetsarray[] = $bigarray[$i];}
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);

    //LABELS
    if (array_search("# QUESTION_ATTRIBUTES TABLE\n", $bigarray))
    {
        $stoppoint = array_search("# QUESTION_ATTRIBUTES TABLE\n", $bigarray);
    }
    elseif (array_search("# QUESTION_ATTRIBUTES TABLE\r\n", $bigarray))
    {
        $stoppoint = array_search("# QUESTION_ATTRIBUTES TABLE\r\n", $bigarray);
    }
    else
    {
        $stoppoint = count($bigarray)-1;
    }

    for ($i=0; $i<=$stoppoint+1; $i++)
    {
        if ($i<$stoppoint-2) {$labelsarray[] = $bigarray[$i];}
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);

    //Question attributes
    if (array_search("# ASSESSMENTS TABLE\n", $bigarray))
    {
        $stoppoint = array_search("# ASSESSMENTS TABLE\n", $bigarray);
    }
    elseif (array_search("# ASSESSMENTS TABLE\r\n", $bigarray))
    {
        $stoppoint = array_search("# ASSESSMENTS TABLE\r\n", $bigarray);
    }
    else
    {
        $stoppoint = count($bigarray)-1;
    }
    for ($i=0; $i<=$stoppoint+1; $i++)
    {
        if ($i<$stoppoint-2) {$question_attributesarray[] = $bigarray[$i];}
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);


    //ASSESSMENTS
    if (array_search("# SURVEYS_LANGUAGESETTINGS TABLE\n", $bigarray))
    {
        $stoppoint = array_search("# SURVEYS_LANGUAGESETTINGS TABLE\n", $bigarray);
    }
    elseif (array_search("# SURVEYS_LANGUAGESETTINGS TABLE\r\n", $bigarray))
    {
        $stoppoint = array_search("# SURVEYS_LANGUAGESETTINGS TABLE\r\n", $bigarray);
    }
    else
    {
        $stoppoint = count($bigarray)-1;
    }
    for ($i=0; $i<=$stoppoint+1; $i++)
    {
        //    if ($i<$stoppoint-2 || $i==count($bigarray)-1)
        if ($i<$stoppoint-2)
        {
            $assessmentsarray[] = $bigarray[$i];
        }
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);

    //LANGAUGE SETTINGS
    if (array_search("# QUOTA TABLE\n", $bigarray))
    {
        $stoppoint = array_search("# QUOTA TABLE\n", $bigarray);
    }
    elseif (array_search("# QUOTA TABLE\r\n", $bigarray))
    {
        $stoppoint = array_search("# QUOTA TABLE\r\n", $bigarray);
    }
    else
    {
        $stoppoint = count($bigarray)-1;
    }
    for ($i=0; $i<=$stoppoint+1; $i++)
    {
        //    if ($i<$stoppoint-2 || $i==count($bigarray)-1)
        //$bigarray[$i]=        trim($bigarray[$i]);
        if (isset($bigarray[$i]) && (trim($bigarray[$i])!=''))
        {
            if (strpos($bigarray[$i],"#")===0)
            {
                unset($bigarray[$i]);
                unset($bigarray[$i+1]);
                unset($bigarray[$i+2]);
                break ;
            }
            else
            {
                $surveylsarray[] = $bigarray[$i];
            }
        }
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);

    //QUOTA
    if (array_search("# QUOTA_MEMBERS TABLE\n", $bigarray))
    {
        $stoppoint = array_search("# QUOTA_MEMBERS TABLE\n", $bigarray);
    }
    elseif (array_search("# QUOTA_MEMBERS TABLE\r\n", $bigarray))
    {
        $stoppoint = array_search("# QUOTA_MEMBERS TABLE\r\n", $bigarray);
    }
    else
    {
        $stoppoint = count($bigarray)-1;
    }
    for ($i=0; $i<=$stoppoint+1; $i++)
    {
        //    if ($i<$stoppoint-2 || $i==count($bigarray)-1)
        if ($i<$stoppoint-2)
        {
            $quotaarray[] = $bigarray[$i];
        }
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);

    //QUOTA MEMBERS
    if (array_search("# QUOTA_LANGUAGESETTINGS TABLE\n", $bigarray))
    {
        $stoppoint = array_search("# QUOTA_LANGUAGESETTINGS TABLE\n", $bigarray);
    }
    elseif (array_search("# QUOTA_LANGUAGESETTINGS TABLE\r\n", $bigarray))
    {
        $stoppoint = array_search("# QUOTA_LANGUAGESETTINGS TABLE\r\n", $bigarray);
    }
    else
    {
        $stoppoint = count($bigarray)-1;
    }
    for ($i=0; $i<=$stoppoint+1; $i++)
    {
        //    if ($i<$stoppoint-2 || $i==count($bigarray)-1)
        if ($i<$stoppoint-2)
        {
            $quotamembersarray[] = $bigarray[$i];
        }
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);


    //Whatever is the last table - currently
    //QUOTA LANGUAGE SETTINGS
    $stoppoint = count($bigarray)-1;
    for ($i=0; $i<$stoppoint-1; $i++)
    {
        if ($i<=$stoppoint) {$quotalsarray[] = $bigarray[$i];}
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);

    if (isset($surveyarray)) {$importresults['surveys'] = count($surveyarray);} else {$importresults['surveys'] = 0;}
    if (isset($surveylsarray)) {$importresults['languages'] = count($surveylsarray)-1;} else {$importresults['languages'] = 1;}
    if (isset($grouparray)) {$importresults['groups'] = count($grouparray)-1;} else {$importresults['groups'] = 0;}
    if (isset($questionarray)) {$importresults['questions'] = count($questionarray);} else {$importresults['questions']=0;}
    if (isset($answerarray)) {$importresults['answers'] = count($answerarray);} else {$importresults['answers']=0;}
    if (isset($conditionsarray)) {$importresults['conditions'] = count($conditionsarray);} else {$importresults['conditions']=0;}
    if (isset($labelsetsarray)) {$importresults['labelsets'] = count($labelsetsarray);} else {$importresults['labelsets']=0;}
    if (isset($assessmentsarray)) {$importresults['assessments']=count($assessmentsarray);} else {$importresults['assessments']=0;}
    if (isset($quotaarray)) {$importresults['quota']=count($quotaarray);} else {$importresults['quota']=0;}
    if (isset($quotamembersarray)) {$importresults['quotamembers']=count($quotamembersarray);} else {$importresults['quotamembers']=0;}
    if (isset($quotalsarray)) {$importresults['quotals']=count($quotalsarray);} else {$importresults['quotals']=0;}

    // CREATE SURVEY

    if ($importresults['surveys']>0){$importresults['surveys']--;};
    if ($importresults['answers']>0){$importresults['answers']=($importresults['answers']-1)/$importresults['languages'];};
    if ($importresults['groups']>0){$countgroups=($importresults['groups']-1)/$importresults['languages'];};
    if ($importresults['questions']>0){$importresults['questions']=($importresults['questions']-1)/$importresults['languages'];};
    if ($importresults['assessments']>0){$importresults['assessments']--;};
    if ($importresults['conditions']>0){$importresults['conditions']--;};
    if ($importresults['labelsets']>0){$importresults['labelsets']--;};
    if ($importresults['quota']>0){$importresults['quota']--;};
    $sfieldorders  =convertCSVRowToArray($surveyarray[0],',','"');
    $sfieldcontents=convertCSVRowToArray($surveyarray[1],',','"');
    $surveyrowdata=array_combine($sfieldorders,$sfieldcontents);
    $oldsid=$surveyrowdata["sid"];

    if($iDesiredSurveyId!=NULL)
        $oldsid = $iDesiredSurveyId;

    if (!$oldsid)
    {
        if ($importingfrom == "http")
        {
            $importsurvey .= "<br /><div class='warningheader'>".$clang->gT("Error")."</div><br />\n";
            $importsurvey .= $clang->gT("Import of this survey file failed")."<br />\n";
            $importsurvey .= $clang->gT("File does not contain LimeSurvey data in the correct format.")."<br /><br />\n"; //Couldn't find the SID - cannot continue
            $importsurvey .= "<input type='submit' value='".$clang->gT("Main Admin Screen")."' onclick=\"window.open('$scriptname', '_top')\" />\n";
            $importsurvey .= "</div>\n";
            unlink($sFullFilepath); //Delete the uploaded file
            return;
        }
        else
        {
            echo $clang->gT("Import of this survey file failed")."\n".$clang->gT("File does not contain LimeSurvey data in the correct format.")."\n";
            return;
        }
    }

    $newsid = GetNewSurveyID($oldsid);

    $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 (validate_templatedir($surveyrowdata['template'])!==$surveyrowdata['template']) $importresults['importwarnings'][] = sprintf($clang->gT('Template %s not found, please review when activating.'),$surveyrowdata['template']);

    if (isset($surveyrowdata['datecreated'])) {$surveyrowdata['datecreated']=$connect->BindTimeStamp($surveyrowdata['datecreated']);}
    unset($surveyrowdata['expires']);
    unset($surveyrowdata['attribute1']);
    unset($surveyrowdata['attribute2']);
    unset($surveyrowdata['usestartdate']);
    unset($surveyrowdata['notification']);
    unset($surveyrowdata['useexpiry']);
    unset($surveyrowdata['url']);
    unset($surveyrowdata['lastpage']);
    if (isset($surveyrowdata['private'])){
        $surveyrowdata['anonymized']=$surveyrowdata['private'];
        unset($surveyrowdata['private']);
    }
    if (isset($surveyrowdata['startdate'])) {unset($surveyrowdata['startdate']);}
    $surveyrowdata['bounce_email']=$surveyrowdata['adminemail'];
    if (!isset($surveyrowdata['datecreated']) || $surveyrowdata['datecreated']=='' || $surveyrowdata['datecreated']=='null') {$surveyrowdata['datecreated']=$connect->BindTimeStamp(date_shift(date("Y-m-d H:i:s"), "Y-m-d", $timeadjust));}

    $values=array_values($surveyrowdata);
    $values=array_map(array(&$connect, "qstr"),$values); // quote everything accordingly
    $insert = "INSERT INTO {$dbprefix}surveys (".implode(',',array_keys($surveyrowdata)).") VALUES (".implode(',',$values).")"; //handle db prefix
    $iresult = $connect->Execute($insert) or safe_die("<br />".$clang->gT("Import of this survey file failed")."<br />\n[$insert]<br />{$surveyarray[0]}<br /><br />\n" . $connect->ErrorMsg());

    // Now import the survey language settings
    $fieldorders=convertCSVRowToArray($surveylsarray[0],',','"');
    unset($surveylsarray[0]);
    foreach ($surveylsarray as $slsrow) {
        $fieldcontents=convertCSVRowToArray($slsrow,',','"');
        $surveylsrowdata=array_combine($fieldorders,$fieldcontents);
        // convert back the '\'.'n' char from the CSV file to true return char "\n"
        $surveylsrowdata=array_map('convertCsvreturn2return', $surveylsrowdata);
        // Convert the \n return char from welcometext to <br />

        // translate internal links
        $surveylsrowdata['surveyls_title']=translink('survey', $oldsid, $newsid, $surveylsrowdata['surveyls_title']);
        $surveylsrowdata['surveyls_description']=translink('survey', $oldsid, $newsid, $surveylsrowdata['surveyls_description']);
        $surveylsrowdata['surveyls_welcometext']=translink('survey', $oldsid, $newsid, $surveylsrowdata['surveyls_welcometext']);
        $surveylsrowdata['surveyls_urldescription']=translink('survey', $oldsid, $newsid, $surveylsrowdata['surveyls_urldescription']);
        $surveylsrowdata['surveyls_email_invite']=translink('survey', $oldsid, $newsid, $surveylsrowdata['surveyls_email_invite']);
        $surveylsrowdata['surveyls_email_remind']=translink('survey', $oldsid, $newsid, $surveylsrowdata['surveyls_email_remind']);
        $surveylsrowdata['surveyls_email_register']=translink('survey', $oldsid, $newsid, $surveylsrowdata['surveyls_email_register']);
        $surveylsrowdata['surveyls_email_confirm']=translink('survey', $oldsid, $newsid, $surveylsrowdata['surveyls_email_confirm']);
        unset($surveylsrowdata['lastpage']);
        $surveylsrowdata['surveyls_survey_id']=$newsid;
        $newvalues=array_values($surveylsrowdata);
        $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly
        $lsainsert = "INSERT INTO {$dbprefix}surveys_languagesettings (".implode(',',array_keys($surveylsrowdata)).") VALUES (".implode(',',$newvalues).")"; //handle db prefix
        $lsiresult=$connect->Execute($lsainsert) or safe_die("<br />".$clang->gT("Import of this survey file failed")."<br />\n[$lsainsert]<br />\n" . $connect->ErrorMsg() );
    }

    // The survey languagesettings are imported now
    $aLanguagesSupported = array();  // this array will keep all the languages supported for the survey

    $sBaseLanguage = GetBaseLanguageFromSurveyID($newsid);
    $aLanguagesSupported[]=$sBaseLanguage;     // adds the base language to the list of supported languages
    $aLanguagesSupported=array_merge($aLanguagesSupported,GetAdditionalLanguagesFromSurveyID($newsid));


    // DO SURVEY_RIGHTS
    GiveAllSurveyPermissions($_SESSION['loginID'],$newsid);
    $importresults['deniedcountls'] =0;


    $qtypes = getqtypelist("" ,"array");
    $results['labels']=0;
    $results['labelsets']=0;
    $results['answers']=0;
    $results['subquestions']=0;

    //Do label sets
    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'];

            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);
            $results['labelsets']++;
            // Get the new insert id for the labels inside this labelset
            $newlid=$connect->Insert_ID("{$dbprefix}labelsets",'lid');

            if ($labelsarray) {
                $count=0;
                foreach ($labelsarray as $la) {
                    $lfieldorders  =convertCSVRowToArray($labelsarray[0],',','"');
                    $lfieldcontents=convertCSVRowToArray($la,',','"');
                    if ($count==0) {$count++; continue;}

                    // Combine into one array with keys and values since its easier to handle
                    $labelrowdata=array_combine($lfieldorders,$lfieldcontents);
                    $labellid=$labelrowdata['lid'];
                    if ($importversion<=132)
                    {
                        $labelrowdata["assessment_value"]=(int)$labelrowdata["code"];
                    }
                    if ($labellid == $oldlid) {
                        $labelrowdata['lid']=$newlid;

                        // translate internal links
                        $labelrowdata['title']=translink('label', $oldlid, $newlid, $labelrowdata['title']);

                        $newvalues=array_values($labelrowdata);
                        $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly
                        $lainsert = "INSERT INTO {$dbprefix}labels (".implode(',',array_keys($labelrowdata)).") VALUES (".implode(',',$newvalues).")"; //handle db prefix
                        $liresult=$connect->Execute($lainsert);
                        if ($liresult!==false) $results['labels']++;
                    }
                }
            }

            //CHECK FOR DUPLICATE LABELSETS
            $thisset="";

            $query2 = "SELECT code, title, sortorder, language, assessment_value
                       FROM {$dbprefix}labels
                       WHERE lid=".$newlid."
                       ORDER BY language, sortorder, code";
            $result2 = db_execute_num($query2) or safe_die("Died querying labelset $lid<br />$query2<br />".$connect->ErrorMsg());
            while($row2=$result2->FetchRow())
            {
                $thisset .= implode('.', $row2);
            } // while
            $newcs=dechex(crc32($thisset)*1);
            unset($lsmatch);
            if (isset($csarray))
            {
                foreach($csarray as $key=>$val)
                {
                    if ($val == $newcs)
                    {
                        $lsmatch=$key;
                    }
                }
            }
            if (isset($lsmatch) || ($_SESSION['USER_RIGHT_MANAGE_LABEL'] != 1))
            {
                //There is a matching labelset or the user is not allowed to edit labels -
                // So, we will delete this one and refer to the matched one.
                $query = "DELETE FROM {$dbprefix}labels WHERE lid=$newlid";
                $result=$connect->Execute($query) or safe_die("Couldn't delete labels<br />$query<br />".$connect->ErrorMsg());
                $results['labels']=$results['labels']-$connect->Affected_Rows();

                $query = "DELETE FROM {$dbprefix}labelsets WHERE lid=$newlid";
                $result=$connect->Execute($query) or safe_die("Couldn't delete labelset<br />$query<br />".$connect->ErrorMsg());
                $results['labelsets']=$results['labelsets']-$connect->Affected_Rows();
                $newlid=$lsmatch;
            }
            else
            {
                //There isn't a matching labelset, add this checksum to the $csarray array
                $csarray[$newlid]=$newcs;
            }
            //END CHECK FOR DUPLICATES
            $aLIDReplacements[$oldlid]=$newlid;
        }
    }

    // Import groups
    if (isset($grouparray) && $grouparray)
    {
        // do GROUPS
        $gafieldorders=convertCSVRowToArray($grouparray[0],',','"');
        unset($grouparray[0]);
        foreach ($grouparray as $ga)
        {
            $gacfieldcontents=convertCSVRowToArray($ga,',','"');
            $grouprowdata=array_combine($gafieldorders,$gacfieldcontents);

            //Now an additional integrity check if there are any groups not belonging into this survey
            if ($grouprowdata['sid'] != $oldsid)
            {
                $results['fatalerror'] = $clang->gT("A group in the CSV/SQL file is not part of the same survey. The import of the survey was stopped.")."<br />\n";
                return $results;
            }
            $grouprowdata['sid']=$newsid;
            // remember group id
            $oldgid=$grouprowdata['gid'];

            //update/remove the old group id
            if (isset($aGIDReplacements[$oldgid]))
            $grouprowdata['gid'] = $aGIDReplacements[$oldgid];
            else
            unset($grouprowdata['gid']);

            // Everything set - now insert it
            $grouprowdata=array_map('convertCsvreturn2return', $grouprowdata);

            // translate internal links
            $grouprowdata['group_name']=translink('survey', $oldsid, $newsid, $grouprowdata['group_name']);
            $grouprowdata['description']=translink('survey', $oldsid, $newsid, $grouprowdata['description']);

            if (isset($grouprowdata['gid'])) db_switchIDInsert('groups',true);
            $tablename=$dbprefix.'groups';
            $ginsert = $connect->GetinsertSQL($tablename,$grouprowdata);
            $gres = $connect->Execute($ginsert) or safe_die($clang->gT('Error').": Failed to insert group<br />\n$ginsert<br />\n".$connect->ErrorMsg());
            if (isset($grouprowdata['gid'])) db_switchIDInsert('groups',false);
            //GET NEW GID
            if (!isset($grouprowdata['gid'])) {$aGIDReplacements[$oldgid]=$connect->Insert_ID("{$dbprefix}groups","gid");}
        }
        // Fix sortorder of the groups  - if users removed groups manually from the csv file there would be gaps
        fixSortOrderGroups($newsid);
    }
    // GROUPS is DONE

    // Import questions
    if (isset($questionarray) && $questionarray)
    {
        $qafieldorders=convertCSVRowToArray($questionarray[0],',','"');
        unset($questionarray[0]);
        foreach ($questionarray as $qa)
        {
            $qacfieldcontents=convertCSVRowToArray($qa,',','"');
            $questionrowdata=array_combine($qafieldorders,$qacfieldcontents);
            $questionrowdata=array_map('convertCsvreturn2return', $questionrowdata);
            $questionrowdata["type"]=strtoupper($questionrowdata["type"]);

            // Skip not supported languages
            if (!in_array($questionrowdata['language'],$aLanguagesSupported))
                continue;

            // replace the sid
            $questionrowdata["sid"] = $newsid;
            // Skip if gid is invalid
            if (!isset($aGIDReplacements[$questionrowdata['gid']])) continue;
            $questionrowdata["gid"] = $aGIDReplacements[$questionrowdata['gid']];
            if (isset($aQIDReplacements[$questionrowdata['qid']]))
            {
                $questionrowdata['qid']=$aQIDReplacements[$questionrowdata['qid']];
            }
            else
            {
                $oldqid=$questionrowdata['qid'];
                unset($questionrowdata['qid']);
            }

            unset($oldlid1); unset($oldlid2);
            if ((isset($questionrowdata['lid']) && $questionrowdata['lid']>0))
            {
                $oldlid1=$questionrowdata['lid'];
            }
            if ((isset($questionrowdata['lid1']) && $questionrowdata['lid1']>0))
            {
                $oldlid2=$questionrowdata['lid1'];
            }
            unset($questionrowdata['lid']);
            unset($questionrowdata['lid1']);
            if ($questionrowdata['type']=='W')
            {
                $questionrowdata['type']='!';
            }
            elseif ($questionrowdata['type']=='Z')
            {
                $questionrowdata['type']='L';
                $aIgnoredAnswers[]=$oldqid;
            }

            if (!isset($questionrowdata["question_order"]) || $questionrowdata["question_order"]=='') {$questionrowdata["question_order"]=0;}
            // translate internal links
            $questionrowdata['title']=translink('survey', $oldsid, $newsid, $questionrowdata['title']);
            $questionrowdata['question']=translink('survey', $oldsid, $newsid, $questionrowdata['question']);
            $questionrowdata['help']=translink('survey', $oldsid, $newsid, $questionrowdata['help']);


            if (isset($questionrowdata['qid'])) {
                db_switchIDInsert('questions',true);
            }

            $tablename=$dbprefix.'questions';
            $qinsert = $connect->GetInsertSQL($tablename,$questionrowdata);
            $qres = $connect->Execute($qinsert) or safe_die ($clang->gT("Error").": Failed to insert question<br />\n$qinsert<br />\n".$connect->ErrorMsg());

            if (isset($questionrowdata['qid'])) {
                db_switchIDInsert('questions',false);
                $saveqid=$questionrowdata['qid'];
            }
            else
            {
                $aQIDReplacements[$oldqid]=$connect->Insert_ID("{$dbprefix}questions",'qid');
                $saveqid=$aQIDReplacements[$oldqid];
            }


            // Now we will fix up old label sets where they are used as answers
            if (((isset($oldlid1) && isset($aLIDReplacements[$oldlid1])) || (isset($oldlid2) && isset($aLIDReplacements[$oldlid2]))) && ($qtypes[$questionrowdata['type']]['answerscales']>0 || $qtypes[$questionrowdata['type']]['subquestions']>1))
            {
                $query="select * from ".db_table_name('labels')." where lid={$aLIDReplacements[$oldlid1]} and language='{$questionrowdata['language']}'";
                $oldlabelsresult=db_execute_assoc($query);
                while($labelrow=$oldlabelsresult->FetchRow())
                {
                    if (in_array($labelrow['language'],$aLanguagesSupported))
                    {

                        if ($qtypes[$questionrowdata['type']]['subquestions']<2)
                        {
                            $qinsert = "insert INTO ".db_table_name('answers')." (qid,code,answer,sortorder,language,assessment_value)
                                        VALUES ({$aQIDReplacements[$oldqid]},".db_quoteall($labelrow['code']).",".db_quoteall($labelrow['title']).",".db_quoteall($labelrow['sortorder']).",".db_quoteall($labelrow['language']).",".db_quoteall($labelrow['assessment_value']).")";
                            $qres = $connect->Execute($qinsert) or safe_die ($clang->gT("Error").": Failed to insert answer (lid1) <br />\n$qinsert<br />\n".$connect->ErrorMsg());
                        }
                        else
                        {
                            if (isset($aSQIDReplacements[$labelrow['code'].'_'.$saveqid])){
                               $fieldname='qid,';
                               $data=$aSQIDReplacements[$labelrow['code'].'_'.$saveqid].',';
                            }
                            else{
                               $fieldname='' ;
                               $data='';
                            }

                            $qinsert = "insert INTO ".db_table_name('questions')." ($fieldname parent_qid,title,question,question_order,language,scale_id,type, sid, gid)
                                        VALUES ($data{$aQIDReplacements[$oldqid]},".db_quoteall($labelrow['code']).",".db_quoteall($labelrow['title']).",".db_quoteall($labelrow['sortorder']).",".db_quoteall($labelrow['language']).",1,'{$questionrowdata['type']}',{$questionrowdata['sid']},{$questionrowdata['gid']})";
                            $qres = $connect->Execute($qinsert) or safe_die ($clang->gT("Error").": Failed to insert question <br />\n$qinsert<br />\n".$connect->ErrorMsg());
                            if ($fieldname=='')
                            {
                               $aSQIDReplacements[$labelrow['code'].'_'.$saveqid]=$connect->Insert_ID("{$dbprefix}questions","qid");
                            }
                        }
                    }
                }
                if (isset($oldlid2) && $qtypes[$questionrowdata['type']]['answerscales']>1)
                {
                    $query="select * from ".db_table_name('labels')." where lid={$aLIDReplacements[$oldlid2]} and language='{$questionrowdata['language']}'";
                    $oldlabelsresult=db_execute_assoc($query);
                    while($labelrow=$oldlabelsresult->FetchRow())
                    {
                        $qinsert = "insert INTO ".db_table_name('answers')." (qid,code,answer,sortorder,language,assessment_value,scale_id)
                                    VALUES ({$aQIDReplacements[$oldqid]},".db_quoteall($labelrow['code']).",".db_quoteall($labelrow['title']).",".db_quoteall($labelrow['sortorder']).",".db_quoteall($labelrow['language']).",".db_quoteall($labelrow['assessment_value']).",1)";
                        $qres = $connect->Execute($qinsert) or safe_die ($clang->gT("Error").": Failed to insert answer (lid2)<br />\n$qinsert<br />\n".$connect->ErrorMsg());
                    }
                }
            }
        }
    }

    //Do answers
    if (isset($answerarray) && $answerarray)
    {
        $answerfieldnames = convertCSVRowToArray($answerarray[0],',','"');
        unset($answerarray[0]);
        foreach ($answerarray as $aa)
        {
            $answerfieldcontents = convertCSVRowToArray($aa,',','"');
            $answerrowdata = array_combine($answerfieldnames,$answerfieldcontents);
            if (in_array($answerrowdata['qid'],$aIgnoredAnswers))
            {
                 // Due to a bug in previous LS versions there may be orphaned answers with question type Z (which is now L)
                 // this way they are ignored
                 continue;
            }
            if ($answerrowdata===false)
            {
                $importquestion.='<br />'.$clang->gT("Faulty line in import - fields and data don't match").":".implode(',',$answerfieldcontents);
            }
            // Skip not supported languages
            if (!in_array($answerrowdata['language'],$aLanguagesSupported))
                continue;

            // replace the qid for the new one (if there is no new qid in the $aQIDReplacements array it mean that this answer is orphan -> error, skip this record)
            if (isset($aQIDReplacements[$answerrowdata["qid"]]))
            $answerrowdata["qid"] = $aQIDReplacements[$answerrowdata["qid"]];
            else
            continue; // a problem with this answer record -> don't consider

            if ($importversion<=132)
            {
                $answerrowdata["assessment_value"]=(int)$answerrowdata["code"];
            }
            // Convert default values for single select questions
            $questiontemp=$connect->GetRow('select type,gid from '.db_table_name('questions').' where qid='.$answerrowdata["qid"]);
            $oldquestion['newtype']=$questiontemp['type'];
            $oldquestion['gid']=$questiontemp['gid'];
            if ($answerrowdata['default_value']=='Y' && ($oldquestion['newtype']=='L' || $oldquestion['newtype']=='O' || $oldquestion['newtype']=='!'))
                            {
                $insertdata=array();
                $insertdata['qid']=$newqid;
                $insertdata['language']=$answerrowdata['language'];
                $insertdata['defaultvalue']=$answerrowdata['answer'];
                $query=$connect->GetInsertSQL($dbprefix.'defaultvalues',$insertdata);
                $qres = $connect->Execute($query) or safe_die ("Error: Failed to insert defaultvalue <br />{$query}<br />\n".$connect->ErrorMsg());

            }
            // translate internal links
            $answerrowdata['answer']=translink('survey', $oldsid, $newsid, $answerrowdata['answer']);
            // Everything set - now insert it
            $answerrowdata = array_map('convertCsvreturn2return', $answerrowdata);

            if ($qtypes[$oldquestion['newtype']]['subquestions']>0) //hmmm.. this is really a subquestion
            {
                $questionrowdata=array();
                if (isset($aSQIDReplacements[$answerrowdata['code'].$answerrowdata['qid']])){
                   $questionrowdata['qid']=$aSQIDReplacements[$answerrowdata['code'].$answerrowdata['qid']];
                }
                $questionrowdata['parent_qid']=$answerrowdata['qid'];;
                $questionrowdata['sid']=$newsid;
                $questionrowdata['gid']=$oldquestion['gid'];
                $questionrowdata['title']=$answerrowdata['code'];
                $questionrowdata['question']=$answerrowdata['answer'];
                $questionrowdata['question_order']=$answerrowdata['sortorder'];
                $questionrowdata['language']=$answerrowdata['language'];
                $questionrowdata['type']=$oldquestion['newtype'];

                $tablename=$dbprefix.'questions';
                $query=$connect->GetInsertSQL($tablename,$questionrowdata);
                if (isset($questionrowdata['qid'])) db_switchIDInsert('questions',true);
                $qres = $connect->Execute($query) or safe_die ("Error: Failed to insert subquestion <br />{$query}<br />".$connect->ErrorMsg());
                if (!isset($questionrowdata['qid']))
                {
                   $aSQIDReplacements[$answerrowdata['code'].$answerrowdata['qid']]=$connect->Insert_ID("{$dbprefix}questions","qid");
                }
                else
                {
                    db_switchIDInsert('questions',false);
                }
                $results['subquestions']++;
                // also convert default values subquestions for multiple choice
                if ($answerrowdata['default_value']=='Y' && ($oldquestion['newtype']=='M' || $oldquestion['newtype']=='P'))
                {
                    $insertdata=array();
                    $insertdata['qid']=$newqid;
                    $insertdata['sqid']=$aSQIDReplacements[$answerrowdata['code']];
                    $insertdata['language']=$answerrowdata['language'];
                    $insertdata['defaultvalue']='Y';
                    $tablename=$dbprefix.'defaultvalues';
                    $query=$connect->GetInsertSQL($tablename,$insertdata);
                    $qres = $connect->Execute($query) or safe_die ("Error: Failed to insert defaultvalue <br />{$query}<br />\n".$connect->ErrorMsg());
                }

            }
            else   // insert answers
            {
                unset($answerrowdata['default_value']);
                $tablename=$dbprefix.'answers';
                $query=$connect->GetInsertSQL($tablename,$answerrowdata);
                $ares = $connect->Execute($query) or safe_die ("Error: Failed to insert answer<br />{$query}<br />\n".$connect->ErrorMsg());
                $results['answers']++;
            }

        }
    }

    // get all group ids and fix questions inside each group
    $gquery = "SELECT gid FROM {$dbprefix}groups where sid=$newsid group by gid ORDER BY gid"; //Get last question added (finds new qid)
    $gres = db_execute_assoc($gquery);
    while ($grow = $gres->FetchRow())
    {
        fixsortorderQuestions($grow['gid'], $newsid);
    }

    //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
        $fieldorders  =convertCSVRowToArray($question_attributesarray[0],',','"');
        unset($question_attributesarray[0]);
        foreach ($question_attributesarray as $qar) {
            $fieldcontents=convertCSVRowToArray($qar,',','"');
            $qarowdata=array_combine($fieldorders,$fieldcontents);
            $newqid="";
            $qarowdata["qid"]=$aQIDReplacements[$qarowdata["qid"]];
            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); // no safe_die since some LimeSurvey version export duplicate question attributes - these are just ignored
            if ($connect->Affected_Rows()>0) {$importresults['question_attributes']++;}
        }
    }

    if (isset($assessmentsarray) && $assessmentsarray) {//ONLY DO THIS IF THERE ARE QUESTION_ATTRIBUTES
        $fieldorders=convertCSVRowToArray($assessmentsarray[0],',','"');
        unset($assessmentsarray[0]);
        foreach ($assessmentsarray as $qar)
        {
            $fieldcontents=convertCSVRowToArray($qar,',','"');
            $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']);
            }
            if  ($asrowdata["gid"]>0)
            {
                $asrowdata["gid"]=$aGIDReplacements[$asrowdata["gid"]];
            }

            $asrowdata["sid"]=$newsid;
            unset($asrowdata["id"]);

            $tablename=$dbprefix.'assessments';
            $asinsert = $connect->GetInsertSQL($tablename,$asrowdata);
            $result=$connect->Execute($asinsert) or safe_die ("Couldn't insert assessment<br />$asinsert<br />".$connect->ErrorMsg());

            unset($newgid);
        }
    }

    if (isset($quotaarray) && $quotaarray) {//ONLY DO THIS IF THERE ARE QUOTAS
        $fieldorders=convertCSVRowToArray($quotaarray[0],',','"');
        unset($quotaarray[0]);
        foreach ($quotaarray as $qar)
        {
            $fieldcontents=convertCSVRowToArray($qar,',','"');

            $asrowdata=array_combine($fieldorders,$fieldcontents);

            $oldsid=$asrowdata["sid"];
            foreach ($substitutions as $subs) {
                if ($oldsid==$subs[0]) {$newsid=$subs[3];}
            }

            $asrowdata["sid"]=$newsid;
            $oldid = $asrowdata["id"];
            unset($asrowdata["id"]);
            $quotadata[]=$asrowdata; //For use later if needed
            $tablename=$dbprefix.'quota';
            $asinsert = $connect->getInsertSQL($tablename,$asrowdata);
            $result=$connect->Execute($asinsert) or safe_die ("Couldn't insert quota<br />$asinsert<br />".$connect->ErrorMsg());
            $aQuotaReplacements[$oldid] = $connect->Insert_ID(db_table_name_nq('quota'),"id");
        }
    }

    if (isset($quotamembersarray) && $quotamembersarray) {//ONLY DO THIS IF THERE ARE QUOTA MEMBERS
        $count=0;
        foreach ($quotamembersarray as $qar) {

            $fieldorders  =convertCSVRowToArray($quotamembersarray[0],',','"');
            $fieldcontents=convertCSVRowToArray($qar,',','"');
            if ($count==0) {$count++; continue;}

            $asrowdata=array_combine($fieldorders,$fieldcontents);

            $oldsid=$asrowdata["sid"];
            $newqid="";
            $newquotaid="";
            $oldqid=$asrowdata['qid'];
            $oldquotaid=$asrowdata['quota_id'];

            foreach ($substitutions as $subs) {
                if ($oldsid==$subs[0]) {$newsid=$subs[3];}
                if ($oldqid==$subs[2]) {$newqid=$subs[5];}
            }

            $newquotaid=$aQuotaReplacements[$oldquotaid];

            $asrowdata["sid"]=$newsid;
            $asrowdata["qid"]=$newqid;
            $asrowdata["quota_id"]=$newquotaid;
            unset($asrowdata["id"]);

            $tablename=$dbprefix.'quota_members';
            $asinsert = $connect->getInsertSQL($tablename,$asrowdata);

            $result=$connect->Execute($asinsert) or safe_die ("Couldn't insert quota<br />$asinsert<br />".$connect->ErrorMsg());

        }
    }

    if (isset($quotalsarray) && $quotalsarray) {//ONLY DO THIS IF THERE ARE QUOTA LANGUAGE SETTINGS
        $count=0;
        foreach ($quotalsarray as $qar) {

            $fieldorders  =convertCSVRowToArray($quotalsarray[0],',','"');
            $fieldcontents=convertCSVRowToArray($qar,',','"');
            if ($count==0) {$count++; continue;}

            $asrowdata=array_combine($fieldorders,$fieldcontents);

            $newquotaid="";
            $oldquotaid=$asrowdata['quotals_quota_id'];

            $newquotaid=$aQuotaReplacements[$oldquotaid];

            $asrowdata["quotals_quota_id"]=$newquotaid;
            unset($asrowdata["quotals_id"]);

            $tablename=$dbprefix.'quota_languagesettings';
            $asinsert = $connect->getInsertSQL($tablename,$asrowdata);
            $result=$connect->Execute($asinsert) or safe_die ("Couldn't insert quota<br />$asinsert<br />".$connect->ErrorMsg());
        }
    }

    //if there are quotas, but no quotals, then we need to create default dummy for each quota (this handles exports from pre-language quota surveys)
    if ($importresults['quota'] > 0 && (!isset($importresults['quotals']) || $importresults['quotals'] == 0)) {
        $i=0;
        $defaultsurveylanguage=isset($defaultsurveylanguage) ? $defaultsurveylanguage : "en";
        foreach($aQuotaReplacements as $oldquotaid=>$newquotaid) {
            $asrowdata=array("quotals_quota_id" => $newquotaid,
                             "quotals_language" => $defaultsurveylanguage,
                             "quotals_name" => $quotadata[$i]["name"],
                             "quotals_message" => $clang->gT("Sorry your responses have exceeded a quota on this survey."),
                             "quotals_url" => "",
                             "quotals_urldescrip" => "");
            $i++;
        }
        $tablename=$dbprefix.'quota_languagesettings';
        $asinsert = $connect->getInsertSQL($tablename,$asrowdata);
        $result=$connect->Execute($asinsert) or safe_die ("Couldn't insert quota<br />$asinsert<br />".$connect->ErrorMsg());
        $countquotals=$i;
    }

    // Do conditions
    if (isset($conditionsarray) && $conditionsarray) {//ONLY DO THIS IF THERE ARE CONDITIONS!
        $fieldorders  =convertCSVRowToArray($conditionsarray[0],',','"');
        unset($conditionsarray[0]);
       // Exception for conditions based on attributes
        $aQIDReplacements[0]=0;
        foreach ($conditionsarray as $car) {
            $fieldcontents=convertCSVRowToArray($car,',','"');
            $conditionrowdata=array_combine($fieldorders,$fieldcontents);

            unset($conditionrowdata["cid"]);
            if (!isset($conditionrowdata["method"]) || trim($conditionrowdata["method"])=='')
            {
                $conditionrowdata["method"]='==';
            }
            if (!isset($conditionrowdata["scenario"]) || trim($conditionrowdata["scenario"])=='')
            {
                $conditionrowdata["scenario"]=1;
            }
            $oldcqid=$conditionrowdata["cqid"];
            $oldgid=array_search($connect->GetOne('select gid from '.db_table_name('questions').' where qid='.$aQIDReplacements[$conditionrowdata["cqid"]]),$aGIDReplacements);
            $conditionrowdata["qid"]=$aQIDReplacements[$conditionrowdata["qid"]];
            $conditionrowdata["cqid"]=$aQIDReplacements[$conditionrowdata["cqid"]];
            $oldcfieldname=$conditionrowdata["cfieldname"];
            $conditionrowdata["cfieldname"]=str_replace($oldsid.'X'.$oldgid.'X'.$oldcqid,$newsid.'X'.$aGIDReplacements[$oldgid].'X'.$conditionrowdata["cqid"],$conditionrowdata["cfieldname"]);

            $tablename=$dbprefix.'conditions';
            $conditioninsert = $connect->getInsertSQL($tablename,$conditionrowdata);
            $result=$connect->Execute($conditioninsert) or safe_die ("Couldn't insert condition<br />$conditioninsert<br />".$connect->ErrorMsg());

        }
    }
    $importresults['importversion']=$importversion;
    $importresults['newsid']=$newsid;
    $importresults['oldsid']=$oldsid;
    return $importresults;
}
示例#21
0
     foreach ($donotimport as $not) {
         unset($fieldvalues[$not]);
     }
 }
 // sometimes columns with nothing in them get omitted by excel
 while (count($fieldnames) > count($fieldvalues)) {
     $fieldvalues[] = "";
 }
 // sometimes columns with nothing in them get added by excel
 while (count($fieldnames) < count($fieldvalues) && trim($fieldvalues[count($fieldvalues) - 1]) == "") {
     unset($fieldvalues[count($fieldvalues) - 1]);
 }
 // make this safe for DB (*after* we undo first excel's
 // and then our escaping).
 $fieldvalues = array_map('db_quoteall', $fieldvalues);
 $fieldvalues = str_replace(db_quoteall('{question_not_shown}'), 'NULL', $fieldvalues);
 $fielddata = $fieldnames === array() && $fieldvalues === array() ? array() : array_combine($fieldnames, $fieldvalues);
 foreach ($datefields as $datefield) {
     if ($fielddata[db_quote_id($datefield)] == '') {
         unset($fielddata[db_quote_id($datefield)]);
     }
 }
 foreach ($numericfields as $numericfield) {
     if ($fielddata[db_quote_id($numericfield)] == '') {
         unset($fielddata[db_quote_id($numericfield)]);
     }
 }
 if (isset($fielddata[db_quote_id('submitdate')]) && $fielddata[db_quote_id('submitdate')] == 'NULL') {
     unset($fielddata[db_quote_id('submitdate')]);
 }
 if ($fielddata[db_quote_id('lastpage')] == '') {
示例#22
0
function modlabelsetanswers($lid)
{
    global $dbprefix, $connect, $clang, $labelsoutput, $databasetype, $filterxsshtml, $postsortorder;
    $ajax = false;
    if (isset($_POST['ajax']) && $_POST['ajax'] == "1") {
        $ajax = true;
    }
    if (!isset($_POST['method'])) {
        $_POST['method'] = $clang->gT("Save");
    }
    $data = json_decode(html_entity_decode($_POST['dataToSend'], ENT_QUOTES, "UTF-8"));
    if ($ajax) {
        $lid = insertlabelset();
    }
    if (count(array_unique($data->{'codelist'})) == count($data->{'codelist'})) {
        if ($filterxsshtml) {
            require_once "../classes/inputfilter/class.inputfilter_clean.php";
            $myFilter = new InputFilter('', '', 1, 1, 1);
        }
        $query = "DELETE FROM " . db_table_name('labels') . "  WHERE lid = {$lid}";
        $result = db_execute_assoc($query) or safe_die($connect->ErrorMsg());
        foreach ($data->{'codelist'} as $index => $codeid) {
            $codeObj = $data->{$codeid};
            $actualcode = db_quoteall($codeObj->{'code'}, true);
            $codeid = db_quoteall($codeid, true);
            $assessmentvalue = (int) $codeObj->{'assessmentvalue'};
            foreach ($data->{'langs'} as $lang) {
                $strTemp = 'text_' . $lang;
                $title = $codeObj->{$strTemp};
                if ($filterxsshtml) {
                    $title = $myFilter->process($title);
                } else {
                    $title = html_entity_decode($title, ENT_QUOTES, "UTF-8");
                }
                // Fix bug with FCKEditor saving strange BR types
                $title = fix_FCKeditor_text($title);
                $title = db_quoteall($title, true);
                $sort_order = db_quoteall($index);
                $lang = db_quoteall($lang);
                $query = "INSERT INTO " . db_table_name('labels') . " (lid,code,title,sortorder, assessment_value, language)\n                    VALUES({$lid},{$actualcode},{$title},{$sort_order},{$assessmentvalue},{$lang})";
                $result = db_execute_assoc($query) or safe_die($connect->ErrorMsg());
            }
        }
        $_SESSION['flashmessage'] = $clang->gT("Labels sucessfully updated");
    } else {
        $labelsoutput .= "<script type=\"text/javascript\">\n<!--\n alert(\"" . $clang->gT("Can't update labels because you are using duplicated codes", "js") . "\")\n //-->\n</script>\n";
    }
    if ($ajax) {
        die;
    }
}
 } else {
     // developer:
     $auth = array($grouprel_config['userIdAttribute'] => 'urn:collab:person:test.surfguest.nl:mdobrinic');
 }
 $o = new GroupTokens($auth, $surveyid, $grouprel_config);
 $invite_output = $o->invite();
 $persons = $o->_allmembers;
 $personcount = count($persons);
 if ($personcount > 0) {
     $language = GetBaseLanguageFromSurveyID($surveyid);
     foreach ($persons as $p) {
         $iq = "INSERT INTO " . db_table_name("tokens_{$surveyid}") . " \n" . "(firstname, lastname, email, emailstatus, language) \n" . "VALUES (%1, %2, %3, 'OK', " . db_quoteall($language) . ")";
         $a = $p->getAttributes();
         $iq = str_replace('%1', db_quoteall($a['firstname']), $iq);
         $iq = str_replace('%2', db_quoteall($a['lastname']), $iq);
         $iq = str_replace('%3', db_quoteall($a['email']), $iq);
         if (true) {
             $ir = $connect->Execute($iq);
         } else {
             echo "Executing: '{$iq}' <br/>\n";
         }
     }
     // foreach(persons)
     $tokenoutput .= "<span class='successtitle'>" . $clang->gT("Success") . "</span><br /><br />\n";
 } else {
     $tokenoutput .= "<font color='red'>" . $clang->gT("Failed") . "</font><br /><br />\n";
     $tokenoutput .= $clang->gT("There were no group(s) selected or group-member(s) retrieved.");
 }
 // if (count>0)
 $message = "{$personcount} " . $clang->gT("persons have been added to the survey") . ".<br />\n";
 $tokenoutput .= "\t<div class='messagebox ui-corner-all'>\n";
示例#24
0
             } else {
                 $_POST['quotals_message_' . $lang] = html_entity_decode($_POST['quotals_message_' . $lang], ENT_QUOTES, "UTF-8");
             }
             // Fix bug with FCKEditor saving strange BR types
             $_POST['quotals_message_' . $lang] = fix_FCKeditor_text($_POST['quotals_message_' . $lang]);
             //Now save the language to the database:
             $query = "INSERT INTO " . db_table_name('quota_languagesettings') . " (quotals_quota_id, quotals_language, quotals_name, quotals_message, quotals_url, quotals_urldescrip)\r\n\t\t        \t      VALUES ('{$quotaid}', '{$lang}', '" . db_quote($_POST['quota_name'], true) . "', '" . db_quote($_POST['quotals_message_' . $lang], true) . "', '" . db_quote($_POST['quotals_url_' . $lang], true) . "', '" . db_quote($_POST['quotals_urldescrip_' . $lang], true) . "')";
             $connect->Execute($query) or safe_die($connect->ErrorMsg());
         }
     }
     //End insert language based components
     $viewquota = "1";
 }
 //End foreach $lang
 if ($subaction == "modifyquota") {
     $query = "UPDATE " . db_table_name('quota') . "\r\n\t\t\t      SET name=" . db_quoteall($_POST['quota_name'], true) . ",\r\n\t\t\t\t  qlimit=" . db_quoteall($_POST['quota_limit'], true) . ",\r\n\t\t\t\t  action=" . db_quoteall($_POST['quota_action'], true) . ",\r\n\t\t\t\t  autoload_url=" . db_quoteall($_POST['autoload_url'], true) . "\r\n\t\t\t\t  WHERE id=" . db_quoteall($_POST['quota_id'], true);
     $connect->Execute($query) or safe_die("Error modifying quota" . $connect->ErrorMsg());
     //Get the languages used in this survey
     $langs = GetAdditionalLanguagesFromSurveyID($surveyid);
     $baselang = GetBaseLanguageFromSurveyID($surveyid);
     array_push($langs, $baselang);
     //Iterate through each language, and make sure there is a quota message for it
     $errorstring = '';
     foreach ($langs as $lang) {
         if (!$_POST['quotals_message_' . $lang]) {
             $errorstring .= GetLanguageNameFromCode($lang, false) . "\\n";
         }
     }
     if ($errorstring != '') {
         $quotasoutput .= "<script type=\"text/javascript\">\n<!--\n alert(\"" . $clang->gT("Quota could not be added.\\n\\nIt is missing a quota message for the following languages", "js") . ":\\n" . $errorstring . "\")\n //-->\n</script>\n";
     } else {
示例#25
0
function createinsertquery()
{
    global $thissurvey, $timeadjust, $move, $thisstep;
    global $deletenonvalues, $thistpl;
    global $surveyid, $connect, $clang, $postedfieldnames, $bFinalizeThisAnswer;
    require_once "classes/inputfilter/class.inputfilter_clean.php";
    $myFilter = new InputFilter('', '', 1, 1, 1);
    $fieldmap = createFieldMap($surveyid);
    //Creates a list of the legitimate questions for this survey
    if (isset($_SESSION['insertarray']) && is_array($_SESSION['insertarray'])) {
        $inserts = array_unique($_SESSION['insertarray']);
        $colnames_hidden = array();
        foreach ($inserts as $value) {
            //Work out if the field actually exists in this survey
            $fieldexists = '';
            if (isset($fieldmap[$value])) {
                $fieldexists = $fieldmap[$value];
            }
            //Iterate through possible responses
            if (isset($_SESSION[$value]) && !empty($fieldexists)) {
                //Only create column name and data entry if there is actually data!
                $colnames[] = $value;
                //If deletenonvalues is ON, delete any values that shouldn't exist
                if ($deletenonvalues == 1 && !checkconfield($value)) {
                    $values[] = 'NULL';
                    $colnames_hidden[] = $value;
                } elseif ($_SESSION[$value] == '' && $fieldexists['type'] == 'D' || $_SESSION[$value] == '' && $fieldexists['type'] == 'K' || $_SESSION[$value] == '' && $fieldexists['type'] == 'N') {
                    // most databases do not allow to insert an empty value into a datefield,
                    // therefore if no date was chosen in a date question the insert value has to be NULL
                    $values[] = 'NULL';
                } else {
                    // Empty the 'Other' field if a value other than '-oth-' was set for the main field (prevent invalid other values being saved - for example if Javascript fails to hide the 'Other' input field)
                    if ($fieldexists['type'] == '!' && $fieldmap[$value]['aid'] == 'other' && isset($_POST[substr($value, 0, strlen($value) - 5)]) && $_POST[substr($value, 0, strlen($value) - 5)] != '-oth-') {
                        $_SESSION[$value] = '';
                    } elseif ($fieldexists['type'] == 'N') {
                        $_SESSION[$value] = sanitize_float($_SESSION[$value]);
                    } elseif ($fieldexists['type'] == 'D' && is_array($postedfieldnames) && in_array($value, $postedfieldnames)) {
                        // convert the date to the right DB Format but only if it was posted
                        $dateformatdatat = getDateFormatData($thissurvey['surveyls_dateformat']);
                        $datetimeobj = new Date_Time_Converter($_SESSION[$value], $dateformatdatat['phpdate']);
                        $_SESSION[$value] = $datetimeobj->convert("Y-m-d");
                        $_SESSION[$value] = $connect->BindDate($_SESSION[$value]);
                    }
                    $values[] = $connect->qstr($_SESSION[$value], get_magic_quotes_gpc());
                }
            }
        }
        if ($thissurvey['datestamp'] == "Y") {
            $_SESSION['datestamp'] = date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust);
        }
        // First compute the submitdate
        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);
        }
        // CHECK TO SEE IF ROW ALREADY EXISTS
        // srid (=Survey Record ID ) is set when the there were already answers saved for that survey
        if (!isset($_SESSION['srid'])) {
            //Prepare row insertion
            if (!isset($colnames) || !is_array($colnames)) {
                echo submitfailed();
                exit;
            }
            // INSERT NEW ROW
            $query = "INSERT INTO " . db_quote_id($thissurvey['tablename']) . "\n" . "(" . implode(', ', array_map('db_quote_id', $colnames));
            $query .= "," . db_quote_id('lastpage');
            if ($thissurvey['datestamp'] == "Y") {
                $query .= "," . db_quote_id('datestamp');
                $query .= "," . db_quote_id('startdate');
            }
            if ($thissurvey['ipaddr'] == "Y") {
                $query .= "," . db_quote_id('ipaddr');
            }
            $query .= "," . db_quote_id('startlanguage');
            if ($thissurvey['refurl'] == "Y") {
                $query .= "," . db_quote_id('refurl');
            }
            if ($bFinalizeThisAnswer === true && $thissurvey['format'] != "A") {
                $query .= "," . db_quote_id('submitdate');
            }
            $query .= ") ";
            $query .= "VALUES (" . implode(", ", $values);
            $query .= "," . ($thisstep + 1);
            if ($thissurvey['datestamp'] == "Y") {
                $query .= ", '" . $_SESSION['datestamp'] . "'";
                $query .= ", '" . $_SESSION['datestamp'] . "'";
            }
            if ($thissurvey['ipaddr'] == "Y") {
                $query .= ", '" . $_SERVER['REMOTE_ADDR'] . "'";
            }
            $query .= ", '" . $_SESSION['s_lang'] . "'";
            if ($thissurvey['refurl'] == "Y") {
                $query .= ", '" . $_SESSION['refurl'] . "'";
            }
            if ($bFinalizeThisAnswer === true && $thissurvey['format'] != "A") {
                // is if a ALL-IN-ONE survey, we don't set the submit date before the data is validated
                $query .= ", " . $connect->DBDate($mysubmitdate);
            }
            $query .= ")";
        } else {
            // UPDATE EXISTING ROW
            // Updates only the MODIFIED fields posted on current page.
            if (isset($postedfieldnames) && $postedfieldnames) {
                $query = "UPDATE {$thissurvey['tablename']} SET ";
                $query .= " lastpage = '" . $thisstep . "',";
                if ($thissurvey['datestamp'] == "Y") {
                    $query .= " datestamp = '" . $_SESSION['datestamp'] . "',";
                }
                if ($thissurvey['ipaddr'] == "Y") {
                    $query .= " ipaddr = '" . $_SERVER['REMOTE_ADDR'] . "',";
                }
                // is if a ALL-IN-ONE survey, we don't set the submit date before the data is validated
                if ($bFinalizeThisAnswer === true && $thissurvey['format'] != "A") {
                    $query .= " submitdate = " . $connect->DBDate($mysubmitdate) . ", ";
                }
                // Resets fields hidden due to conditions
                if ($deletenonvalues == 1) {
                    $hiddenfields = array_unique(array_values($colnames_hidden));
                    foreach ($hiddenfields as $hiddenfield) {
                        //$fieldinfo = arraySearchByKey($hiddenfield, $fieldmap, "fieldname", 1);
                        //if ($fieldinfo['type']=='D' || $fieldinfo['type']=='N' || $fieldinfo['type']=='K')
                        //{
                        $query .= db_quote_id($hiddenfield) . " = NULL,";
                        //}
                        //else
                        //{
                        //	$query .= db_quote_id($hiddenfield)." = '',";
                        //}
                    }
                } else {
                    $hiddenfields = array();
                }
                $fields = $postedfieldnames;
                $fields = array_unique($fields);
                $fields = array_diff($fields, $hiddenfields);
                // Do not take fields that are hidden
                foreach ($fields as $field) {
                    if (!empty($field)) {
                        $fieldinfo = $fieldmap[$field];
                        if (!isset($_POST[$field])) {
                            $_POST[$field] = '';
                        }
                        //fixed numerical question fields. They have to be NULL instead of '' to avoid database errors
                        if ($_POST[$field] == '' && $fieldinfo['type'] == 'D' || $_POST[$field] == '' && $fieldinfo['type'] == 'N' || $_POST[$field] == '' && $fieldinfo['type'] == 'K') {
                            $query .= db_quote_id($field) . " = NULL,";
                        } else {
                            // Empty the 'Other' field if a value other than '-oth-' was set for the main field (prevent invalid other values being saved - for example if Javascript fails to hide the 'Other' input field)
                            if ($fieldinfo['type'] == '!' && $fieldmap[$field]['aid'] == 'other' && $_POST[substr($field, 0, strlen($field) - 5)] != '-oth-') {
                                $qfield = "''";
                            } elseif ($fieldinfo['type'] == 'N') {
                                $qfield = db_quoteall(sanitize_float($_POST[$field]));
                            } elseif ($fieldinfo['type'] == 'D') {
                                $dateformatdatat = getDateFormatData($thissurvey['surveyls_dateformat']);
                                $datetimeobj = new Date_Time_Converter($_POST[$field], $dateformatdatat['phpdate']);
                                $qfield = db_quoteall($connect->BindDate($datetimeobj->convert("Y-m-d")));
                            } else {
                                $qfield = db_quoteall($_POST[$field], true);
                            }
                            $query .= db_quote_id($field) . " = " . $qfield . ",";
                        }
                    }
                }
                $query .= "WHERE id=" . $_SESSION['srid'];
                $query = str_replace(",WHERE", " WHERE", $query);
                // remove comma before WHERE clause
            } else {
                $query = "";
                if ($bFinalizeThisAnswer === true) {
                    $query = "UPDATE {$thissurvey['tablename']} SET ";
                    $query .= " submitdate = " . $connect->DBDate($mysubmitdate);
                    $query .= " WHERE id=" . $_SESSION['srid'];
                }
            }
        }
        //DEBUG START
        //echo $query;
        //DEBUG END
        return $query;
    } else {
        sendcacheheaders();
        doHeader();
        foreach (file("{$thistpl}/startpage.pstpl") as $op) {
            echo templatereplace($op);
        }
        echo "<br /><center><font face='verdana' size='2'><font color='red'><strong>" . $clang->gT("Error") . "</strong></font><br /><br />\n";
        echo $clang->gT("Cannot submit results - there are none to submit.") . "<br /><br />\n";
        echo "<font size='1'>" . $clang->gT("This error can occur if you have already submitted your responses and pressed 'refresh' on your browser. In this case, your responses have already been saved.") . "<br /><br />" . $clang->gT("If you receive this message in the middle of completing a survey, you should choose '<- BACK' on your browser and then refresh/reload the previous page. While you will lose answers from the last page all your others will still exist. This problem can occur if the webserver is suffering from overload or excessive use. We apologise for this problem.") . "<br />\n";
        echo "</font></center><br /><br />";
        exit;
    }
}
             $editdefvalues .= "value='{$answer['code']}'>{$answer['answer']}</option>";
         }
         $editdefvalues .= "</select></li> ";
         if ($questionrow['other'] == 'Y') {
             $defaultvalue = $connect->GetOne("SELECT defaultvalue FROM " . db_table_name('defaultvalues') . " WHERE qid={$qid} and specialtype='other' AND scale_id={$scale_id} AND language='{$language}'");
             if (is_null($defaultvalue)) {
                 $defaultvalue = '';
             }
             $editdefvalues .= "<li><label for='other_{$scale_id}_{$language}'>" . $clang->gT("Default value for option 'Other':") . "<label><input type='text' name='other_{$scale_id}_{$language}' value='{$defaultvalue}' id='other_{$scale_id}_{$language}'></li>";
         }
     }
 }
 // If there are subquestions and no answerscales
 if ($qtproperties[$questionrow['type']]['answerscales'] == 0 && $qtproperties[$questionrow['type']]['subquestions'] > 0) {
     for ($scale_id = 0; $scale_id < $qtproperties[$questionrow['type']]['subquestions']; $scale_id++) {
         $sqquery = "SELECT * FROM " . db_table_name('questions') . " WHERE sid={$surveyid} AND gid={$gid} AND parent_qid={$qid} and language=" . db_quoteall($language) . " and scale_id=0 order by question_order";
         $sqresult = db_execute_assoc($sqquery);
         $sqrows = $sqresult->GetRows();
         if ($qtproperties[$questionrow['type']]['subquestions'] > 1) {
             $editdefvalues .= " <div class='header ui-widget-header'>" . sprintf($clang->gT('Default answer for scale %s:'), $scale_id) . "</div>";
         }
         if ($questionrow['type'] == 'M' || $questionrow['type'] == 'P') {
             $options = array('' => $clang->gT('<No default value>'), 'Y' => $clang->gT('Checked'));
         }
         $editdefvalues .= "<ul>";
         foreach ($sqrows as $aSubquestion) {
             $defaultvalue = $connect->GetOne("SELECT defaultvalue FROM " . db_table_name('defaultvalues') . " WHERE qid={$qid} AND specialtype='' and sqid={$aSubquestion['qid']} and scale_id={$scale_id} AND language='{$language}'");
             $editdefvalues .= "<li><label for='defaultanswerscale_{$scale_id}_{$language}_{$aSubquestion['qid']}'>{$aSubquestion['title']}: " . FlattenText($aSubquestion['question']) . "</label>";
             $editdefvalues .= "<select name='defaultanswerscale_{$scale_id}_{$language}_{$aSubquestion['qid']}' id='defaultanswerscale_{$scale_id}_{$language}_{$aSubquestion['qid']}'>";
             foreach ($options as $value => $label) {
                 $editdefvalues .= "<option ";
function upgrade_tables143()
{
    global $modifyoutput, $dbprefix, $connect;
    $aQIDReplacements = array();
    $answerquery = "select a.*, q.sid, q.gid from {$dbprefix}answers a,{$dbprefix}questions q where a.qid=q.qid and q.type in ('L','O','!') and a.default_value='Y'";
    $answerresult = db_execute_assoc($answerquery);
    if (!$answerresult) {
        return "Database Error";
    } else {
        while ($row = $answerresult->FetchRow()) {
            modify_database("", "INSERT INTO {$dbprefix}defaultvalues (qid, scale_id,language,specialtype,defaultvalue) VALUES ({$row['qid']},0," . db_quoteall($row['language']) . ",''," . db_quoteall($row['code']) . ")");
            echo $modifyoutput;
            flush();
            ob_flush();
        }
    }
    // Convert answers to subquestions
    $answerquery = "select a.*, q.sid, q.gid, q.type from {$dbprefix}answers a,{$dbprefix}questions q where a.qid=q.qid and a.language=q.language and q.type in ('1','A','B','C','E','F','H','K',';',':','M','P','Q')";
    $answerresult = db_execute_assoc($answerquery);
    if (!$answerresult) {
        return "Database Error";
    } else {
        while ($row = $answerresult->FetchRow()) {
            $insertarray = array();
            if (isset($aQIDReplacements[$row['qid'] . '_' . $row['code']])) {
                $insertarray['qid'] = $aQIDReplacements[$row['qid'] . '_' . $row['code']];
                db_switchIDInsert('questions', true);
            }
            $insertarray['sid'] = $row['sid'];
            $insertarray['gid'] = $row['gid'];
            $insertarray['parent_qid'] = $row['qid'];
            $insertarray['type'] = $row['type'];
            $insertarray['title'] = $row['code'];
            $insertarray['question'] = $row['answer'];
            $insertarray['question_order'] = $row['sortorder'];
            $insertarray['language'] = $row['language'];
            $tablename = "{$dbprefix}questions";
            $query = $connect->GetInsertSQL($tablename, $insertarray);
            modify_database("", $query);
            echo $modifyoutput;
            flush();
            ob_flush();
            if (!isset($insertarray['qid'])) {
                $aQIDReplacements[$row['qid'] . '_' . $row['code']] = $connect->Insert_ID("{$dbprefix}questions", "qid");
                $iSaveSQID = $aQIDReplacements[$row['qid'] . '_' . $row['code']];
            } else {
                $iSaveSQID = $insertarray['qid'];
                db_switchIDInsert('questions', false);
            }
            if (($row['type'] == 'M' || $row['type'] == 'P') && $row['default_value'] == 'Y') {
                modify_database("", "INSERT INTO {$dbprefix}defaultvalues (qid, sqid, scale_id,language,specialtype,defaultvalue) VALUES ({$row['qid']},{$iSaveSQID},0," . db_quoteall($row['language']) . ",'','Y')");
                echo $modifyoutput;
                flush();
                ob_flush();
            }
        }
    }
    modify_database("", "delete {$dbprefix}answers from {$dbprefix}answers LEFT join {$dbprefix}questions ON {$dbprefix}answers.qid={$dbprefix}questions.qid where {$dbprefix}questions.type in ('1','F','H','M','P','W','Z')");
    echo $modifyoutput;
    flush();
    ob_flush();
    // Convert labels to answers
    $answerquery = "select qid ,type ,lid ,lid1, language from {$dbprefix}questions where parent_qid=0 and type in ('1','F','H','M','P','W','Z')";
    $answerresult = db_execute_assoc($answerquery);
    if (!$answerresult) {
        return "Database Error";
    } else {
        while ($row = $answerresult->FetchRow()) {
            $labelquery = "Select * from {$dbprefix}labels where lid={$row['lid']} and language=" . db_quoteall($row['language']);
            $labelresult = db_execute_assoc($labelquery);
            while ($lrow = $labelresult->FetchRow()) {
                modify_database("", "INSERT INTO {$dbprefix}answers (qid, code, answer, sortorder, language, assessment_value) VALUES ({$row['qid']}," . db_quoteall($lrow['code']) . "," . db_quoteall($lrow['title']) . ",{$lrow['sortorder']}," . db_quoteall($lrow['language']) . ",{$lrow['assessment_value']})");
                echo $modifyoutput;
                flush();
                ob_flush();
                //$labelids[]
            }
            if ($row['type'] == '1') {
                $labelquery = "Select * from {$dbprefix}labels where lid={$row['lid1']} and language=" . db_quoteall($row['language']);
                $labelresult = db_execute_assoc($labelquery);
                while ($lrow = $labelresult->FetchRow()) {
                    modify_database("", "INSERT INTO {$dbprefix}answers (qid, code, answer, sortorder, language, scale_id, assessment_value) VALUES ({$row['qid']}," . db_quoteall($lrow['code']) . "," . db_quoteall($lrow['title']) . ",{$lrow['sortorder']}," . db_quoteall($lrow['language']) . ",1,{$lrow['assessment_value']})");
                    echo $modifyoutput;
                    flush();
                    ob_flush();
                }
            }
        }
    }
    // Convert labels to subquestions
    $answerquery = "select * from {$dbprefix}questions where parent_qid=0 and type in (';',':')";
    $answerresult = db_execute_assoc($answerquery);
    if (!$answerresult) {
        return "Database Error";
    } else {
        while ($row = $answerresult->FetchRow()) {
            $labelquery = "Select * from {$dbprefix}labels where lid={$row['lid']} and language=" . db_quoteall($row['language']);
            $labelresult = db_execute_assoc($labelquery);
            while ($lrow = $labelresult->FetchRow()) {
                $insertarray = array();
                if (isset($aQIDReplacements[$row['qid'] . '_' . $lrow['code'] . '_1'])) {
                    $insertarray['qid'] = $aQIDReplacements[$row['qid'] . '_' . $lrow['code'] . '_1'];
                    db_switchIDInsert('questions', true);
                }
                $insertarray['sid'] = $row['sid'];
                $insertarray['gid'] = $row['gid'];
                $insertarray['type'] = $row['type'];
                $insertarray['parent_qid'] = $row['qid'];
                $insertarray['title'] = $lrow['code'];
                $insertarray['question'] = $lrow['title'];
                $insertarray['question_order'] = $lrow['sortorder'];
                $insertarray['language'] = $lrow['language'];
                $insertarray['scale_id'] = 1;
                $tablename = "{$dbprefix}questions";
                $query = $connect->GetInsertSQL($tablename, $insertarray);
                modify_database("", $query);
                echo $modifyoutput;
                flush();
                ob_flush();
                if (isset($insertarray['qid'])) {
                    $aQIDReplacements[$row['qid'] . '_' . $lrow['code'] . '_1'] = $connect->Insert_ID("{$dbprefix}questions", "qid");
                    db_switchIDInsert('questions', false);
                }
            }
        }
    }
    $updatequery = "update {$dbprefix}questions set type='!' where type='W'";
    modify_database("", $updatequery);
    echo $modifyoutput;
    flush();
    ob_flush();
    $updatequery = "update {$dbprefix}questions set type='L' where type='Z'";
    modify_database("", $updatequery);
    echo $modifyoutput;
    flush();
    ob_flush();
    // Now move all non-standard templates to the /upload dir
    global $usertemplaterootdir, $standardtemplates, $standardtemplaterootdir;
    if (!$usertemplaterootdir) {
        die("gettemplatelist() no template directory");
    }
    if ($handle = opendir($standardtemplaterootdir)) {
        while (false !== ($file = readdir($handle))) {
            if (!is_file("{$standardtemplaterootdir}/{$file}") && $file != "." && $file != ".." && $file != ".svn" && !isStandardTemplate($file)) {
                if (!rename($standardtemplaterootdir . DIRECTORY_SEPARATOR . $file, $usertemplaterootdir . DIRECTORY_SEPARATOR . $file)) {
                    echo "There was a problem moving directory '" . $standardtemplaterootdir . DIRECTORY_SEPARATOR . $file . "' to '" . $usertemplaterootdir . DIRECTORY_SEPARATOR . $file . "' due to missing permissions. Please do this manually.<br />";
                }
            }
        }
        closedir($handle);
    }
}
    $clang = new limesurvey_lang($baselang);
} else {
    $clang = new limesurvey_lang($postlang);
    $baselang = $postlang;
}
$thissurvey = getSurveyInfo($surveyid, $baselang);
$html = '<div id="wrapper"><p id="optoutmessage">';
if ($thissurvey == false || !tableExists("tokens_{$surveyid}")) {
    $html .= $clang->gT('This survey does not seem to exist.');
} else {
    $usquery = "SELECT emailstatus from " . db_table_name("tokens_{$surveyid}") . " where token=" . db_quoteall($token, true);
    $usresult = $connect->GetOne($usquery);
    if ($usresult == false) {
        $html .= $clang->gT('You are not a participant in this survey.');
    } elseif ($usresult == 'OK') {
        $usquery = "Update " . db_table_name("tokens_{$surveyid}") . " set emailstatus='OptOut', usesleft=0 where token=" . db_quoteall($token, true);
        $usresult = $connect->Execute($usquery);
        $html .= $clang->gT('You have been successfully removed from this survey.');
    } else {
        $html .= $clang->gT('You have been already removed from this survey.');
    }
}
$html .= '</p></div>';
//PRINT COMPLETED PAGE
if (!$thissurvey['templatedir']) {
    $thistpl = sGetTemplatePath($defaulttemplate);
} else {
    $thistpl = sGetTemplatePath($thissurvey['templatedir']);
}
sendcacheheaders();
doHeader();
示例#29
0
/**
* This function set a question attribute to a certain value
*
* @param mixed $qid
* @param mixed $sAttributeName
* @param mixed $sAttributeValue
*/
function setQuestionAttribute($qid, $sAttributeName, $sAttributeValue)
{
    global $dbprefix, $connect;
    $tablename = $dbprefix . 'question_attributes';
    $aInsertArray = array('qid' => $qid, 'attribute' => $sAttributeName, 'value' => $sAttributeValue);
    $sQuery = $connect->GetInsertSQL($tablename, $aInsertArray);
    $connect->Execute('delete from ' . db_table_name('question_attributes') . " where qid={$qid} and attribute=" . db_quoteall($sAttributeName));
    $connect->Execute($sQuery);
}
示例#30
0
 /**
  * Deprecate obsolete question attributes.
  * @param boolean $changedb - if true, updates parameters and deletes old ones
  * @param type $surveyid - if set, then only for that survey
  * @param type $onlythisqid - if set, then only for this question ID
  */
 public static function UpgradeQuestionAttributes($changeDB = false, $surveyid = NULL, $onlythisqid = NULL)
 {
     $LEM =& LimeExpressionManager::singleton();
     $qattrs = $LEM->getQuestionAttributesForEM($surveyid, $onlythisqid);
     $qupdates = array();
     $attibutemap = array('max_num_value_sgqa' => 'max_num_value', 'min_num_value_sgqa' => 'min_num_value', 'num_value_equals_sgqa' => 'equals_num_value');
     $reverseAttributeMap = array_flip($attibutemap);
     foreach ($qattrs as $qid => $qattr) {
         $updates = array();
         foreach ($attibutemap as $src => $target) {
             if (isset($qattr[$src]) && trim($qattr[$src]) != '') {
                 $updates[$target] = $qattr[$src];
             }
         }
         if (count($updates) > 0) {
             $qupdates[$qid] = $updates;
         }
     }
     if ($changeDB) {
         $queries = array();
         foreach ($qupdates as $qid => $updates) {
             foreach ($updates as $key => $value) {
                 $query = "UPDATE " . db_table_name('question_attributes') . " SET value=" . db_quoteall($value) . " WHERE qid=" . $qid . " and attribute=" . db_quoteall($key);
                 $queries[] = $query;
                 $query = "DELETE FROM " . db_table_name('question_attributes') . " WHERE qid=" . $qid . " and attribute=" . db_quoteall($reverseAttributeMap[$key]);
                 $queries[] = $query;
             }
         }
         foreach ($queries as $query) {
             db_execute_assoc($query);
         }
         return $queries;
     } else {
         return $qupdates;
     }
 }