Example #1
0
 function actionLocal($surveyid, $token, $langcode = '')
 {
     Yii::app()->loadHelper('database');
     Yii::app()->loadHelper('sanitize');
     $sLanguageCode = $langcode;
     $iSurveyID = $surveyid;
     $sToken = $token;
     $sToken = sanitize_token($sToken);
     if (!$iSurveyID) {
         $this->redirect($this->getController()->createUrl('/'));
     }
     $iSurveyID = (int) $iSurveyID;
     //Check that there is a SID
     // Get passed language from form, so that we dont loose this!
     if (!isset($sLanguageCode) || $sLanguageCode == "" || !$sLanguageCode) {
         $baselang = Survey::model()->findByPk($iSurveyID)->language;
         Yii::import('application.libraries.Limesurvey_lang', true);
         $clang = new Limesurvey_lang($baselang);
     } else {
         $sLanguageCode = sanitize_languagecode($sLanguageCode);
         Yii::import('application.libraries.Limesurvey_lang', true);
         $clang = new Limesurvey_lang($sLanguageCode);
         $baselang = $sLanguageCode;
     }
     Yii::app()->lang = $clang;
     $thissurvey = getSurveyInfo($iSurveyID, $baselang);
     if ($thissurvey == false || Yii::app()->db->schema->getTable("{{tokens_{$iSurveyID}}}") == null) {
         $html = $clang->gT('This survey does not seem to exist.');
     } else {
         $row = Tokens_dynamic::getEmailStatus($iSurveyID, $sToken);
         if ($row == false) {
             $html = $clang->gT('You are not a participant in this survey.');
         } else {
             $usresult = $row['emailstatus'];
             if ($usresult == 'OptOut') {
                 $usresult = Tokens_dynamic::updateEmailStatus($iSurveyID, $sToken, 'OK');
                 $html = $clang->gT('You have been successfully added back to this survey.');
             } else {
                 if ($usresult == 'OK') {
                     $html = $clang->gT('You are already a part of this survey.');
                 } else {
                     $html = $clang->gT('You have been already removed from this survey.');
                 }
             }
         }
     }
     //PRINT COMPLETED PAGE
     if (!$thissurvey['templatedir']) {
         $thistpl = getTemplatePath(Yii::app()->getConfig("defaulttemplate"));
     } else {
         $thistpl = getTemplatePath($thissurvey['templatedir']);
     }
     $this->_renderHtml($html, $thistpl, $clang);
 }
Example #2
0
function XMLImportTokens($sFullFilepath, $iSurveyID, $sCreateMissingAttributeFields = true)
{
    Yii::app()->loadHelper('database');
    $clang = Yii::app()->lang;
    $xml = simplexml_load_file($sFullFilepath);
    if ($xml->LimeSurveyDocType != 'Tokens') {
        $results['error'] = $clang->gT("This is not a valid token data XML file.");
        return $results;
    }
    $results['tokens'] = 0;
    $results['tokenfieldscreated'] = 0;
    $aLanguagesSupported = array();
    foreach ($xml->languages->language as $language) {
        $aLanguagesSupported[] = (string) $language;
    }
    $results['languages'] = count($aLanguagesSupported);
    if ($sCreateMissingAttributeFields) {
        // Get a list with all fieldnames in the XML
        $aXLMFieldNames = array();
        foreach ($xml->tokens->fields->fieldname as $sFieldName) {
            $aXLMFieldNames[] = (string) $sFieldName;
        }
        // Get a list of all fieldnames in the token table
        $aTokenFieldNames = Yii::app()->db->getSchema()->getTable("{{tokens_{$iSurveyID}}}", true);
        $aTokenFieldNames = array_keys($aTokenFieldNames->columns);
        $aFieldsToCreate = array_diff($aXLMFieldNames, $aTokenFieldNames);
        Yii::app()->loadHelper('update/updatedb');
        foreach ($aFieldsToCreate as $sField) {
            if (strpos($sField, 'attribute') !== false) {
                addColumn('{{tokens_' . $iSurveyID . '}}', $sField, 'string');
            }
        }
    }
    switchMSSQLIdentityInsert('tokens_' . $iSurveyID, true);
    foreach ($xml->tokens->rows->row as $row) {
        $insertdata = array();
        foreach ($row as $key => $value) {
            $insertdata[(string) $key] = (string) $value;
        }
        $result = Tokens_dynamic::model($iSurveyID)->insertToken($iSurveyID, $insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />");
        $results['tokens']++;
    }
    switchMSSQLIdentityInsert('tokens_' . $iSurveyID, false);
    return $results;
}
 /**
  * register::index()
  * Process register form data and take appropriate action
  * @return
  */
 function actionIndex($surveyid = null)
 {
     Yii::app()->loadHelper('database');
     Yii::app()->loadHelper('replacements');
     $postlang = Yii::app()->request->getPost('lang');
     if ($surveyid == null) {
         $surveyid = Yii::app()->request->getPost('sid');
     }
     if (!$surveyid) {
         Yii::app()->request->redirect(Yii::app()->baseUrl);
     }
     // Get passed language from form, so that we dont loose this!
     if (!isset($postlang) || $postlang == "" || !$postlang) {
         $baselang = Survey::model()->findByPk($surveyid)->language;
         Yii::import('application.libraries.Limesurvey_lang');
         Yii::app()->lang = new Limesurvey_lang($baselang);
         $clang = Yii::app()->lang;
     } else {
         Yii::import('application.libraries.Limesurvey_lang');
         Yii::app()->lang = new Limesurvey_lang($postlang);
         $clang = Yii::app()->lang;
         $baselang = $postlang;
     }
     $thissurvey = getSurveyInfo($surveyid, $baselang);
     $register_errormsg = "";
     // Check the security question's answer
     if (function_exists("ImageCreate") && isCaptchaEnabled('registrationscreen', $thissurvey['usecaptcha'])) {
         if (!isset($_POST['loadsecurity']) || !isset($_SESSION['survey_' . $surveyid]['secanswer']) || Yii::app()->request->getPost('loadsecurity') != $_SESSION['survey_' . $surveyid]['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 (!validateEmailAddress(Yii::app()->request->getPost('register_email'))) {
         $register_errormsg .= $clang->gT("The email you used is not valid. Please try again.");
     }
     // Check for additional fields
     $attributeinsertdata = array();
     foreach (GetParticipantAttributes($surveyid) as $field => $data) {
         if (empty($data['show_register']) || $data['show_register'] != 'Y') {
             continue;
         }
         $value = sanitize_xss_string(Yii::app()->request->getPost('register_' . $field));
         if (trim($value) == '' && $data['mandatory'] == 'Y') {
             $register_errormsg .= sprintf($clang->gT("%s cannot be left empty"), $thissurvey['attributecaptions'][$field]);
         }
         $attributeinsertdata[$field] = $value;
     }
     if ($register_errormsg != "") {
         $_SESSION['survey_' . $surveyid]['register_errormsg'] = $register_errormsg;
         Yii::app()->request->redirect(Yii::app()->createUrl('survey/index/sid/' . $surveyid));
     }
     //Check if this email already exists in token database
     $query = "SELECT email FROM {{tokens_{$surveyid}}}\n" . "WHERE email = '" . sanitize_email(Yii::app()->request->getPost('register_email')) . "'";
     $usrow = Yii::app()->db->createCommand($query)->queryRow();
     if ($usrow) {
         $register_errormsg = $clang->gT("The email you used has already been registered.");
         $_SESSION['survey_' . $surveyid]['register_errormsg'] = $register_errormsg;
         Yii::app()->request->redirect(Yii::app()->createUrl('survey/index/sid/' . $surveyid));
         //include "index.php";
         //exit;
     }
     $mayinsert = false;
     // Get the survey settings for token length
     //$this->load->model("surveys_model");
     $tlresult = Survey::model()->findAllByAttributes(array("sid" => $surveyid));
     if (isset($tlresult[0])) {
         $tlrow = $tlresult[0];
     } else {
         $tlrow = $tlresult;
     }
     $tokenlength = $tlrow['tokenlength'];
     //if tokenlength is not set or there are other problems use the default value (15)
     if (!isset($tokenlength) || $tokenlength == '') {
         $tokenlength = 15;
     }
     while ($mayinsert != true) {
         $newtoken = randomChars($tokenlength);
         $ntquery = "SELECT * FROM {{tokens_{$surveyid}}} WHERE token='{$newtoken}'";
         $usrow = Yii::app()->db->createCommand($ntquery)->queryRow();
         if (!$usrow) {
             $mayinsert = true;
         }
     }
     $postfirstname = sanitize_xss_string(strip_tags(Yii::app()->request->getPost('register_firstname')));
     $postlastname = sanitize_xss_string(strip_tags(Yii::app()->request->getPost('register_lastname')));
     $starttime = sanitize_xss_string(Yii::app()->request->getPost('startdate'));
     $endtime = sanitize_xss_string(Yii::app()->request->getPost('enddate'));
     /*$postattribute1=sanitize_xss_string(strip_tags(returnGlobal('register_attribute1')));
       $postattribute2=sanitize_xss_string(strip_tags(returnGlobal('register_attribute2')));   */
     // Insert new entry into tokens db
     Tokens_dynamic::sid($thissurvey['sid']);
     $token = new Tokens_dynamic();
     $token->firstname = $postfirstname;
     $token->lastname = $postlastname;
     $token->email = Yii::app()->request->getPost('register_email');
     $token->emailstatus = 'OK';
     $token->token = $newtoken;
     if ($starttime && $endtime) {
         $token->validfrom = $starttime;
         $token->validuntil = $endtime;
     }
     foreach ($attributeinsertdata as $k => $v) {
         $token->{$k} = $v;
     }
     $result = $token->save();
     /**
     $result = $connect->Execute($query, array($postfirstname,
     $postlastname,
     returnGlobal('register_email'),
     'OK',
     $newtoken)
     
     //                             $postattribute1,   $postattribute2)
     ) or safeDie ($query."<br />".$connect->ErrorMsg());  //Checked - According to adodb docs the bound variables are quoted automatically
     */
     $tid = getLastInsertID($token->tableName());
     $fieldsarray["{ADMINNAME}"] = $thissurvey['adminname'];
     $fieldsarray["{ADMINEMAIL}"] = $thissurvey['adminemail'];
     $fieldsarray["{SURVEYNAME}"] = $thissurvey['name'];
     $fieldsarray["{SURVEYDESCRIPTION}"] = $thissurvey['description'];
     $fieldsarray["{FIRSTNAME}"] = $postfirstname;
     $fieldsarray["{LASTNAME}"] = $postlastname;
     $fieldsarray["{EXPIRY}"] = $thissurvey["expiry"];
     $message = $thissurvey['email_register'];
     $subject = $thissurvey['email_register_subj'];
     $from = "{$thissurvey['adminname']} <{$thissurvey['adminemail']}>";
     if (getEmailFormat($surveyid) == 'html') {
         $useHtmlEmail = true;
         $surveylink = $this->createAbsoluteUrl($surveyid . '/lang-' . $baselang . '/tk-' . $newtoken);
         $optoutlink = $this->createAbsoluteUrl('optout/local/' . $surveyid . '/' . $baselang . '/' . $newtoken);
         $optinlink = $this->createAbsoluteUrl('optin/local/' . $surveyid . '/' . $baselang . '/' . $newtoken);
         $fieldsarray["{SURVEYURL}"] = "<a href='{$surveylink}'>" . $surveylink . "</a>";
         $fieldsarray["{OPTOUTURL}"] = "<a href='{$optoutlink}'>" . $optoutlink . "</a>";
         $fieldsarray["{OPTINURL}"] = "<a href='{$optinlink}'>" . $optinlink . "</a>";
     } else {
         $useHtmlEmail = false;
         $fieldsarray["{SURVEYURL}"] = $this->createAbsoluteUrl('' . $surveyid . '/lang-' . $baselang . '/tk-' . $newtoken);
         $fieldsarray["{OPTOUTURL}"] = $this->createAbsoluteUrl('optout/local/' . $surveyid . '/' . $baselang . '/' . $newtoken);
         $fieldsarray["{OPTINURL}"] = $this->createAbsoluteUrl('optin/local/' . $surveyid . '/' . $baselang . '/' . $newtoken);
     }
     $message = ReplaceFields($message, $fieldsarray);
     $subject = ReplaceFields($subject, $fieldsarray);
     $html = "";
     //Set variable
     $sitename = Yii::app()->getConfig('sitename');
     if (SendEmailMessage($message, $subject, Yii::app()->request->getPost('register_email'), $from, $sitename, $useHtmlEmail, getBounceEmail($surveyid))) {
         // TLR change to put date into sent
         $today = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig('timeadjust'));
         $query = "UPDATE {{tokens_{$surveyid}}}\n" . "SET sent='{$today}' WHERE tid={$tid}";
         $result = dbExecuteAssoc($query) or show_error("Unable to execute this query : {$query}<br />");
         //Checked
         $html = "<center>" . $clang->gT("Thank you for registering to participate in this survey.") . "<br /><br />\n" . $clang->gT("An email has been sent to the address you provided with access details for this survey. Please follow the link in that email to proceed.") . "<br /><br />\n" . $clang->gT("Survey administrator") . " {ADMINNAME} ({ADMINEMAIL})";
         $html = ReplaceFields($html, $fieldsarray);
         $html .= "<br /><br /></center>\n";
     } else {
         $html = "Email Error";
     }
     //PRINT COMPLETED PAGE
     if (!$thissurvey['template']) {
         $thistpl = getTemplatePath(validateTemplateDir('default'));
     } else {
         $thistpl = getTemplatePath(validateTemplateDir($thissurvey['template']));
     }
     sendCacheHeaders();
     doHeader();
     Yii::app()->lang = $clang;
     // fetch the defined variables and pass it to the header footer templates.
     $redata = compact(array_keys(get_defined_vars()));
     $this->_printTemplateContent($thistpl . '/startpage.pstpl', $redata, __LINE__);
     $this->_printTemplateContent($thistpl . '/survey.pstpl', $redata, __LINE__);
     echo $html;
     $this->_printTemplateContent($thistpl . '/endpage.pstpl', $redata, __LINE__);
     doFooter();
 }
 function actionparticipants()
 {
     $surveyid = Yii::app()->request->getQuery('surveyid');
     $langcode = Yii::app()->request->getQuery('langcode');
     $token = Yii::app()->request->getQuery('token');
     Yii::app()->loadHelper('database');
     Yii::app()->loadHelper('sanitize');
     $sLanguageCode = $langcode;
     $iSurveyID = $surveyid;
     $sToken = $token;
     $sToken = sanitize_token($sToken);
     if (!$iSurveyID) {
         $this->redirect(Yii::app()->getController()->createUrl('/'));
     }
     $iSurveyID = (int) $iSurveyID;
     //Make sure it's an integer (protect from SQL injects)
     //Check that there is a SID
     // Get passed language from form, so that we dont lose this!
     if (!isset($sLanguageCode) || $sLanguageCode == "" || !$sLanguageCode) {
         $baselang = Survey::model()->findByPk($iSurveyID)->language;
         Yii::import('application.libraries.Limesurvey_lang', true);
         $clang = new Limesurvey_lang($baselang);
     } else {
         $sLanguageCode = sanitize_languagecode($sLanguageCode);
         Yii::import('application.libraries.Limesurvey_lang', true);
         $clang = new Limesurvey_lang($sLanguageCode);
         $baselang = $sLanguageCode;
     }
     Yii::app()->lang = $clang;
     $thissurvey = getSurveyInfo($iSurveyID, $baselang);
     if ($thissurvey == false || !tableExists("{{tokens_{$iSurveyID}}}")) {
         $html = $clang->gT('This survey does not seem to exist.');
     } else {
         $row = Tokens_dynamic::getEmailStatus($iSurveyID, $sToken);
         $datas = Tokens_dynamic::model($iSurveyID)->find('token = :token', array(":token" => $sToken));
         if ($row == false) {
             $html = $clang->gT('You are not a participant in this survey.');
         } else {
             $usresult = $row['emailstatus'];
             if ($usresult == 'OK') {
                 $usresult = Tokens_dynamic::updateEmailStatus($iSurveyID, $sToken, 'OptOut');
                 $html = $clang->gT('You have been successfully removed from this survey.');
             } else {
                 $html = $clang->gT('You have been already removed from this survey.');
             }
             if (!empty($datas->participant_id) && $datas->participant_id != "") {
                 //Participant also exists in central db
                 $cpdb = Participants::model()->find('participant_id = :participant_id', array(":participant_id" => $datas->participant_id));
                 if ($cpdb->blacklisted == "Y") {
                     $html .= "<br />";
                     $html .= $clang->gt("You have already been removed from the central participants list for this site");
                 } else {
                     $cpdb->blacklisted = 'Y';
                     $cpdb->save();
                     $html .= "<br />";
                     $html .= $clang->gT("You have been removed from the central participants list for this site");
                 }
             }
         }
     }
     //PRINT COMPLETED PAGE
     if (!$thissurvey['templatedir']) {
         $thistpl = getTemplatePath(Yii::app()->getConfig("defaulttemplate"));
     } else {
         $thistpl = getTemplatePath($thissurvey['templatedir']);
     }
     $this->_renderHtml($html, $thistpl);
 }
Example #5
0
 /**
  * RPC Routine to send reminder for participants in a survey 
  * Returns array of results of sending
  *
  * @access public
  * @param string $sSessionKey Auth credentials
  * @param int $iSurveyID ID of the survey that participants belong
  * @param int $iMinDaysBetween Optional parameter days from last reminder
  * @param int $iMaxReminders Optional parameter Maximum reminders count
  * @return array Result of the action
  */
 public function remind_participants($sSessionKey, $iSurveyID, $iMinDaysBetween = null, $iMaxReminders = null)
 {
     Yii::app()->loadHelper('admin/token');
     if (!$this->_checkSessionKey($sSessionKey)) {
         return array('status' => 'Invalid session key');
     }
     $oSurvey = Survey::model()->findByPk($iSurveyID);
     if (!isset($oSurvey)) {
         return array('status' => 'Error: Invalid survey ID');
     }
     if (hasSurveyPermission($iSurveyID, 'tokens', 'update')) {
         $timeadjust = Yii::app()->getConfig("timeadjust");
         if (!tableExists("{{tokens_{$iSurveyID}}}")) {
             return array('status' => 'Error: No token table');
         }
         if (getEmailFormat($iSurveyID) == 'html') {
             $bHtml = true;
         } else {
             $bHtml = false;
         }
         $SQLemailstatuscondition = "emailstatus = 'OK'";
         $SQLremindercountcondition = '';
         $SQLreminderdelaycondition = '';
         $attributes = getTokenFieldsAndNames($iSurveyID);
         $iMaxEmails = (int) Yii::app()->getConfig("maxemails");
         if (!is_null($iMinDaysBetween)) {
             $compareddate = dateShift(date("Y-m-d H:i:s", time() - 86400 * $iMinDaysBetween), "Y-m-d H:i", $timeadjust);
             $SQLreminderdelaycondition = " ((remindersent = 'N' AND sent < '" . $compareddate . "')  OR  (remindersent < '" . $compareddate . "'))";
         }
         if (!is_null($iMaxReminders)) {
             $SQLremindercountcondition = "remindercount < " . $iMaxReminders;
         }
         $oTokens = Tokens_dynamic::model($iSurveyID);
         $aResultTokens = $oTokens->findUninvited(false, $iMaxEmails, false, $SQLemailstatuscondition, $SQLremindercountcondition, $SQLreminderdelaycondition);
         $aAllTokens = $oTokens->findUninvited(false, 0, false, $SQLemailstatuscondition, $SQLremindercountcondition, $SQLreminderdelaycondition);
         if (empty($aResultTokens)) {
             return array('status' => 'Error: No candidate tokens');
         }
         $aResult = emailTokens($iSurveyID, $aResultTokens, 'remind');
         $iLeft = count($aAllTokens) - count($aResultTokens);
         $aResult['status'] = $iLeft . " left to send";
         return $aResult;
     } else {
         return array('status' => 'No permission');
     }
 }
/**
 * This function builds all the required session variables when a survey is first started and
 * it loads any answer defaults from command line or from the table defaultvalues
 * It is called from the related format script (group.php, question.php, survey.php)
 * if the survey has just started.
 */
function buildsurveysession($surveyid, $preview = false)
{
    global $secerror, $clienttoken;
    global $tokensexist;
    //global $surveyid;
    global $templang, $move, $rooturl;
    $clang = Yii::app()->lang;
    $thissurvey = getSurveyInfo($surveyid);
    if (empty($templang)) {
        $templang = $thissurvey['language'];
    }
    $_SESSION['survey_' . $surveyid]['templatename'] = validateTemplateDir($thissurvey['template']);
    $_SESSION['survey_' . $surveyid]['templatepath'] = getTemplatePath($_SESSION['survey_' . $surveyid]['templatename']) . DIRECTORY_SEPARATOR;
    $sTemplatePath = $_SESSION['survey_' . $surveyid]['templatepath'];
    $loadsecurity = returnGlobal('loadsecurity');
    // NO TOKEN REQUIRED BUT CAPTCHA ENABLED FOR SURVEY ACCESS
    if ($tokensexist == 0 && isCaptchaEnabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
        // IF CAPTCHA ANSWER IS NOT CORRECT OR NOT SET
        if (!isset($loadsecurity) || !isset($_SESSION['survey_' . $surveyid]['secanswer']) || $loadsecurity != $_SESSION['survey_' . $surveyid]['secanswer']) {
            sendCacheHeaders();
            doHeader();
            // No or bad answer to required security question
            $redata = compact(array_keys(get_defined_vars()));
            echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'frontend_helper[1525]');
            //echo makedropdownlist();
            echo templatereplace(file_get_contents($sTemplatePath . "survey.pstpl"), array(), $redata, 'frontend_helper[1527]');
            if (isset($loadsecurity)) {
                // was a bad answer
                echo "<font color='#FF0000'>" . $clang->gT("The answer to the security question is incorrect.") . "</font><br />";
            }
            echo "<p class='captcha'>" . $clang->gT("Please confirm access to survey by answering the security question below and click continue.") . "</p>" . CHtml::form(array("/survey/index/sid/{$surveyid}"), 'post', array('class' => 'captcha')) . "\n                <table align='center'>\n                <tr>\n                <td align='right' valign='middle'>\n                <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n                <input type='hidden' name='lang' value='" . $templang . "' id='lang' />";
            // In case we this is a direct Reload previous answers URL, then add hidden fields
            if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) {
                echo "\n                    <input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n                    <input type='hidden' name='scid' value='" . returnGlobal('scid') . "' id='scid' />\n                    <input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n                    <input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />";
            }
            echo "\n                </td>\n                </tr>";
            if (function_exists("ImageCreate") && isCaptchaEnabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
                echo "<tr>\n                    <td align='center' valign='middle'><label for='captcha'>" . $clang->gT("Security question:") . "</label></td><td align='left' valign='middle'><table><tr><td valign='middle'><img src='" . Yii::app()->getController()->createUrl('/verification/image/sid/' . $surveyid) . "' alt='captcha' /></td>\n                    <td valign='middle'><input id='captcha' type='text' size='5' maxlength='3' name='loadsecurity' value='' /></td></tr></table>\n                    </td>\n                    </tr>";
            }
            echo "<tr><td colspan='2' align='center'><input class='submit' type='submit' value='" . $clang->gT("Continue") . "' /></td></tr>\n                </table>\n                </form>";
            echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata, 'frontend_helper[1567]');
            doFooter();
            exit;
        }
    }
    //BEFORE BUILDING A NEW SESSION FOR THIS SURVEY, LET'S CHECK TO MAKE SURE THE SURVEY SHOULD PROCEED!
    // TOKEN REQUIRED BUT NO TOKEN PROVIDED
    if ($tokensexist == 1 && !$clienttoken && !$preview) {
        if ($thissurvey['nokeyboard'] == 'Y') {
            includeKeypad();
            $kpclass = "text-keypad";
        } else {
            $kpclass = "";
        }
        // DISPLAY REGISTER-PAGE if needed
        // DISPLAY CAPTCHA if needed
        sendCacheHeaders();
        doHeader();
        $redata = compact(array_keys(get_defined_vars()));
        echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'frontend_helper[1594]');
        //echo makedropdownlist();
        echo templatereplace(file_get_contents($sTemplatePath . "survey.pstpl"), array(), $redata, 'frontend_helper[1596]');
        if (isset($thissurvey) && $thissurvey['allowregister'] == "Y") {
            echo templatereplace(file_get_contents($sTemplatePath . "register.pstpl"), array(), $redata, 'frontend_helper[1599]');
        } else {
            // ->renderPartial('entertoken_view');
            if (isset($secerror)) {
                echo "<span class='error'>" . $secerror . "</span><br />";
            }
            echo '<div id="wrapper"><p id="tokenmessage">' . $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br />";
            echo $clang->gT("If you have been issued a token, please enter it in the box below and click continue.") . "</p>\n                <script type='text/javascript'>var focus_element='#token';</script>" . CHtml::form(array("/survey/index/sid/{$surveyid}"), 'post', array('id' => 'tokenform')) . "\n                <ul>\n                <li>";
            ?>
            <label for='token'><?php 
            $clang->eT("Token:");
            ?>
</label><input class='text <?php 
            echo $kpclass;
            ?>
' id='token' type='text' name='token' />
            <?php 
            echo "<input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n            <input type='hidden' name='lang' value='" . $templang . "' id='lang' />";
            if (isset($_GET['newtest']) && $_GET['newtest'] == "Y") {
                echo "  <input type='hidden' name='newtest' value='Y' id='newtest' />";
            }
            // If this is a direct Reload previous answers URL, then add hidden fields
            if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) {
                echo "\n                <input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n                <input type='hidden' name='scid' value='" . returnGlobal('scid') . "' id='scid' />\n                <input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n                <input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />";
            }
            echo "</li>";
            if (function_exists("ImageCreate") && isCaptchaEnabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
                echo "<li>\n                <label for='captchaimage'>" . $clang->gT("Security Question") . "</label><img id='captchaimage' src='" . Yii::app()->getController()->createUrl('/verification/image/sid/' . $surveyid) . "' alt='captcha' /><input type='text' size='5' maxlength='3' name='loadsecurity' value='' />\n                </li>";
            }
            echo "<li>\n            <input class='submit' type='submit' value='" . $clang->gT("Continue") . "' />\n            </li>\n            </ul>\n            </form></div>";
        }
        echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata, 'frontend_helper[1645]');
        doFooter();
        exit;
    } elseif ($tokensexist == 1 && $clienttoken && !isCaptchaEnabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
        //check if tokens actually haven't been already used
        $areTokensUsed = usedTokens(trim(strip_tags($clienttoken)), $surveyid);
        //check if token actually does exist
        // check also if it is allowed to change survey after completion
        if ($thissurvey['alloweditaftercompletion'] == 'Y') {
            $oTokenEntry = Tokens_dynamic::model($surveyid)->find('token=:token', array(':token' => trim(strip_tags($clienttoken))));
        } else {
            $oTokenEntry = Tokens_dynamic::model($surveyid)->find("token=:token AND (completed = 'N' or completed='')", array(':token' => trim(strip_tags($clienttoken))));
        }
        if (is_null($oTokenEntry) || $areTokensUsed && $thissurvey['alloweditaftercompletion'] != 'Y') {
            //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT
            killSurveySession($surveyid);
            sendCacheHeaders();
            doHeader();
            $redata = compact(array_keys(get_defined_vars()));
            echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'frontend_helper[1676]');
            echo templatereplace(file_get_contents($sTemplatePath . "survey.pstpl"), array(), $redata, 'frontend_helper[1677]');
            echo '<div id="wrapper"><p id="tokenmessage">' . $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br /><br />\n" . "\t" . $clang->gT("The token you have provided is either not valid, or has already been used.") . "<br /><br />\n" . "\t" . sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname']) . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)</p></div>\n";
            echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata, 'frontend_helper[1684]');
            doFooter();
            exit;
        }
    } elseif ($tokensexist == 1 && $clienttoken && isCaptchaEnabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
        // IF CAPTCHA ANSWER IS CORRECT
        if (isset($loadsecurity) && isset($_SESSION['survey_' . $surveyid]['secanswer']) && $loadsecurity == $_SESSION['survey_' . $surveyid]['secanswer']) {
            //check if tokens actually haven't been already used
            $areTokensUsed = usedTokens(trim(strip_tags($clienttoken)), $surveyid);
            //check if token actually does exist
            $oTokenEntry = Tokens_dynamic::model($surveyid)->find('token=:token', array(':token' => trim(strip_tags($clienttoken))));
            if ($thissurvey['alloweditaftercompletion'] == 'Y') {
                $oTokenEntry = Tokens_dynamic::model($surveyid)->find('token=:token', array(':token' => trim(strip_tags($clienttoken))));
            } else {
                $oTokenEntry = Tokens_dynamic::model($surveyid)->find("token=:token  AND (completed = 'N' or completed='')", array(':token' => trim(strip_tags($clienttoken))));
            }
            if (is_null($oTokenEntry) || $areTokensUsed && $thissurvey['alloweditaftercompletion'] != 'Y') {
                sendCacheHeaders();
                doHeader();
                //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT
                $redata = compact(array_keys(get_defined_vars()));
                echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'frontend_helper[1719]');
                echo templatereplace(file_get_contents($sTemplatePath . "survey.pstpl"), array(), $redata, 'frontend_helper[1720]');
                echo "\t<div id='wrapper'>\n" . "\t<p id='tokenmessage'>\n" . "\t" . $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br /><br />\n" . "\t" . $clang->gT("The token you have provided is either not valid, or has already been used.") . "<br/><br />\n" . "\t" . sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname']) . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)\n" . "\t</p>\n" . "\t</div>\n";
                echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata, 'frontend_helper[1731]');
                doFooter();
                exit;
            }
        } else {
            if (!isset($move) || is_null($move)) {
                unset($_SESSION['survey_' . $surveyid]['srid']);
                $gettoken = $clienttoken;
                sendCacheHeaders();
                doHeader();
                // No or bad answer to required security question
                $redata = compact(array_keys(get_defined_vars()));
                echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'frontend_helper[1745]');
                echo templatereplace(file_get_contents($sTemplatePath . "survey.pstpl"), array(), $redata, 'frontend_helper[1746]');
                // If token wasn't provided and public registration
                // is enabled then show registration form
                if (!isset($gettoken) && isset($thissurvey) && $thissurvey['allowregister'] == "Y") {
                    echo templatereplace(file_get_contents($sTemplatePath . "register.pstpl"), array(), $redata, 'frontend_helper[1751]');
                } else {
                    // only show CAPTCHA
                    echo '<div id="wrapper"><p id="tokenmessage">';
                    if (isset($loadsecurity)) {
                        // was a bad answer
                        echo "<span class='error'>" . $clang->gT("The answer to the security question is incorrect.") . "</span><br />";
                    }
                    echo $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br /><br />";
                    // IF TOKEN HAS BEEN GIVEN THEN AUTOFILL IT
                    // AND HIDE ENTRY FIELD
                    if (!isset($gettoken)) {
                        echo $clang->gT("If you have been issued a token, please enter it in the box below and click continue.") . "</p>\n                        <form id='tokenform' method='get' action='" . Yii::app()->getController()->createUrl("/survey/index") . "'>\n                        <ul>\n                        <li>\n                        <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n                        <input type='hidden' name='lang' value='" . $templang . "' id='lang' />";
                        if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) {
                            echo "<input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n                            <input type='hidden' name='scid' value='" . returnGlobal('scid') . "' id='scid' />\n                            <input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n                            <input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />";
                        }
                        echo '<label for="token">' . $clang->gT("Token") . "</label><input class='text' type='text' id='token' name='token'></li>";
                    } else {
                        echo $clang->gT("Please confirm the token by answering the security question below and click continue.") . "</p>\n                    <form id='tokenform' method='get' action='" . Yii::app()->getController()->createUrl("/survey/index") . "'>\n                    <ul>\n                    <li>\n                    <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n                    <input type='hidden' name='lang' value='" . $templang . "' id='lang' />";
                        if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) {
                            echo "<input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n                        <input type='hidden' name='scid' value='" . returnGlobal('scid') . "' id='scid' />\n                        <input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n                        <input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />";
                        }
                        echo '<label for="token">' . $clang->gT("Token:") . "</label><span id='token'>{$gettoken}</span>" . "<input type='hidden' name='token' value='{$gettoken}'></li>";
                    }
                    if (function_exists("ImageCreate") && isCaptchaEnabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
                        echo "<li>\n                    <label for='captchaimage'>" . $clang->gT("Security Question") . "</label><img id='captchaimage' src='" . Yii::app()->getController()->createUrl('/verification/image/sid/' . $surveyid) . "' alt='captcha' /><input type='text' size='5' maxlength='3' name='loadsecurity' value='' />\n                    </li>";
                    }
                    echo "<li><input class='submit' type='submit' value='" . $clang->gT("Continue") . "' /></li>\n                </ul>\n                </form>\n                </id>";
                }
                echo '</div>' . templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata, 'frontend_helper[1817]');
                doFooter();
                exit;
            }
        }
    }
    //RESET ALL THE SESSION VARIABLES AND START AGAIN
    unset($_SESSION['survey_' . $surveyid]['grouplist']);
    unset($_SESSION['survey_' . $surveyid]['fieldarray']);
    unset($_SESSION['survey_' . $surveyid]['insertarray']);
    unset($_SESSION['survey_' . $surveyid]['thistoken']);
    unset($_SESSION['survey_' . $surveyid]['fieldnamesInfo']);
    unset($_SESSION['survey_' . $surveyid]['fieldmap-' . $surveyid . '-randMaster']);
    unset($_SESSION['survey_' . $surveyid]['groupReMap']);
    $_SESSION['survey_' . $surveyid]['fieldnamesInfo'] = array();
    //RL: multilingual support
    if (isset($_GET['token']) && tableExists('{{tokens_' . $surveyid . '}}')) {
        //get language from token (if one exists)
        $tkquery2 = "SELECT * FROM {{tokens_" . $surveyid . "}} WHERE token='" . $clienttoken . "' AND (completed = 'N' or completed='')";
        //echo $tkquery2;
        $result = dbExecuteAssoc($tkquery2) or safeDie("Couldn't get tokens<br />{$tkquery}<br />");
        //Checked
        foreach ($result->readAll() as $rw) {
            $tklanguage = $rw['language'];
        }
    }
    if (returnGlobal('lang')) {
        $language_to_set = returnGlobal('lang');
    } elseif (isset($tklanguage)) {
        $language_to_set = $tklanguage;
    } else {
        $language_to_set = $thissurvey['language'];
    }
    if (!isset($_SESSION['survey_' . $surveyid]['s_lang'])) {
        SetSurveyLanguage($surveyid, $language_to_set);
    }
    UpdateGroupList($surveyid, $_SESSION['survey_' . $surveyid]['s_lang']);
    $sQuery = "SELECT count(*)\n" . " FROM {{groups}} INNER JOIN {{questions}} ON {{groups}}.gid = {{questions}}.gid\n" . " WHERE {{questions}}.sid=" . $surveyid . "\n" . " AND {{groups}}.language='" . $_SESSION['survey_' . $surveyid]['s_lang'] . "'\n" . " AND {{questions}}.language='" . $_SESSION['survey_' . $surveyid]['s_lang'] . "'\n" . " AND {{questions}}.parent_qid=0\n";
    $totalquestions = Yii::app()->db->createCommand($sQuery)->queryScalar();
    // Fix totalquestions by substracting Test Display questions
    $iNumberofQuestions = dbExecuteAssoc("SELECT count(*)\n" . " FROM {{questions}}" . " WHERE type in ('X','*')\n" . " AND sid={$surveyid}" . " AND language='" . $_SESSION['survey_' . $surveyid]['s_lang'] . "'" . " AND parent_qid=0")->read();
    $_SESSION['survey_' . $surveyid]['totalquestions'] = $totalquestions - (int) reset($iNumberofQuestions);
    //2. SESSION VARIABLE: totalsteps
    //The number of "pages" that will be presented in this survey
    //The number of pages to be presented will differ depending on the survey format
    switch ($thissurvey['format']) {
        case "A":
            $_SESSION['survey_' . $surveyid]['totalsteps'] = 1;
            break;
        case "G":
            if (isset($_SESSION['survey_' . $surveyid]['grouplist'])) {
                $_SESSION['survey_' . $surveyid]['totalsteps'] = count($_SESSION['survey_' . $surveyid]['grouplist']);
            }
            break;
        case "S":
            $_SESSION['survey_' . $surveyid]['totalsteps'] = $totalquestions;
    }
    if ($totalquestions == 0) {
        sendCacheHeaders();
        doHeader();
        $redata = compact(array_keys(get_defined_vars()));
        echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'frontend_helper[1914]');
        echo templatereplace(file_get_contents($sTemplatePath . "survey.pstpl"), array(), $redata, 'frontend_helper[1915]');
        echo "\t<div id='wrapper'>\n" . "\t<p id='tokenmessage'>\n" . "\t" . $clang->gT("This survey does not yet have any questions and cannot be tested or completed.") . "<br /><br />\n" . "\t" . sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname']) . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)<br /><br />\n" . "\t</p>\n" . "\t</div>\n";
        echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata, 'frontend_helper[1925]');
        doFooter();
        exit;
    }
    //Perform a case insensitive natural sort on group name then question title of a multidimensional array
    //	usort($arows, 'groupOrderThenQuestionOrder');
    //3. SESSION VARIABLE - insertarray
    //An array containing information about used to insert the data into the db at the submit stage
    //4. SESSION VARIABLE - fieldarray
    //See rem at end..
    $_SESSION['survey_' . $surveyid]['token'] = $clienttoken;
    if ($thissurvey['anonymized'] == "N") {
        $_SESSION['survey_' . $surveyid]['insertarray'][] = "token";
    }
    if ($tokensexist == 1 && $thissurvey['anonymized'] == "N" && tableExists('{{tokens_' . $surveyid . '}}')) {
        //Gather survey data for "non anonymous" surveys, for use in presenting questions
        $_SESSION['survey_' . $surveyid]['thistoken'] = getTokenData($surveyid, $clienttoken);
    }
    $qtypes = getQuestionTypeList('', 'array');
    $fieldmap = createFieldMap($surveyid, 'full', true, false, $_SESSION['survey_' . $surveyid]['s_lang']);
    // Randomization groups for groups
    $aRandomGroups = array();
    $aGIDCompleteMap = array();
    // first find all groups and their groups IDS
    $criteria = new CDbCriteria();
    $criteria->addColumnCondition(array('sid' => $surveyid, 'language' => $_SESSION['survey_' . $surveyid]['s_lang']));
    $criteria->addCondition("randomization_group != ''");
    $oData = Groups::model()->findAll($criteria);
    foreach ($oData as $aGroup) {
        $aRandomGroups[$aGroup['randomization_group']][] = $aGroup['gid'];
    }
    // Shuffle each group and create a map for old GID => new GID
    foreach ($aRandomGroups as $sGroupName => $aGIDs) {
        $aShuffledIDs = $aGIDs;
        shuffle($aShuffledIDs);
        $aGIDCompleteMap = $aGIDCompleteMap + array_combine($aGIDs, $aShuffledIDs);
    }
    $_SESSION['survey_' . $surveyid]['groupReMap'] = $aGIDCompleteMap;
    $randomized = false;
    // So we can trigger reorder once for group and question randomization
    // Now adjust the grouplist
    if (count($aRandomGroups) > 0) {
        $randomized = true;
        // So we can trigger reorder once for group and question randomization
        // Now adjust the grouplist
        Yii::import('application.helpers.frontend_helper', true);
        // make sure frontend helper is loaded
        UpdateGroupList($surveyid, $_SESSION['survey_' . $surveyid]['s_lang']);
        // ... and the fieldmap
        // First create a fieldmap with GID as key
        foreach ($fieldmap as $aField) {
            if (isset($aField['gid'])) {
                $GroupFieldMap[$aField['gid']][] = $aField;
            } else {
                $GroupFieldMap['other'][] = $aField;
            }
        }
        // swap it
        foreach ($GroupFieldMap as $iOldGid => $fields) {
            $iNewGid = $iOldGid;
            if (isset($aGIDCompleteMap[$iOldGid])) {
                $iNewGid = $aGIDCompleteMap[$iOldGid];
            }
            $newGroupFieldMap[$iNewGid] = $GroupFieldMap[$iNewGid];
        }
        $GroupFieldMap = $newGroupFieldMap;
        // and convert it back to a fieldmap
        unset($fieldmap);
        foreach ($GroupFieldMap as $aGroupFields) {
            foreach ($aGroupFields as $aField) {
                if (isset($aField['fieldname'])) {
                    $fieldmap[$aField['fieldname']] = $aField;
                    // isset() because of the shuffled flag above
                }
            }
        }
        unset($GroupFieldMap);
    }
    // Randomization groups for questions
    // Find all defined randomization groups through question attribute values
    $randomGroups = array();
    if (in_array(Yii::app()->db->getDriverName(), array('mssql', 'sqlsrv'))) {
        $rgquery = "SELECT attr.qid, CAST(value as varchar(255)) as value FROM {{question_attributes}} as attr right join {{questions}} as quests on attr.qid=quests.qid WHERE attribute='random_group' and CAST(value as varchar(255)) <> '' and sid={$surveyid} GROUP BY attr.qid, CAST(value as varchar(255))";
    } else {
        $rgquery = "SELECT attr.qid, value FROM {{question_attributes}} as attr right join {{questions}} as quests on attr.qid=quests.qid WHERE attribute='random_group' and value <> '' and sid={$surveyid} GROUP BY attr.qid, value";
    }
    $rgresult = dbExecuteAssoc($rgquery);
    foreach ($rgresult->readAll() as $rgrow) {
        // Get the question IDs for each randomization group
        $randomGroups[$rgrow['value']][] = $rgrow['qid'];
    }
    // If we have randomization groups set, then lets cycle through each group and
    // replace questions in the group with a randomly chosen one from the same group
    if (count($randomGroups) > 0) {
        $randomized = true;
        // So we can trigger reorder once for group and question randomization
        $copyFieldMap = array();
        $oldQuestOrder = array();
        $newQuestOrder = array();
        $randGroupNames = array();
        foreach ($randomGroups as $key => $value) {
            $oldQuestOrder[$key] = $randomGroups[$key];
            $newQuestOrder[$key] = $oldQuestOrder[$key];
            // We shuffle the question list to get a random key->qid which will be used to swap from the old key
            shuffle($newQuestOrder[$key]);
            $randGroupNames[] = $key;
        }
        // Loop through the fieldmap and swap each question as they come up
        foreach ($fieldmap as $fieldkey => $fieldval) {
            $found = 0;
            foreach ($randomGroups as $gkey => $gval) {
                // We found a qid that is in the randomization group
                if (isset($fieldval['qid']) && in_array($fieldval['qid'], $oldQuestOrder[$gkey])) {
                    // Get the swapped question
                    $idx = array_search($fieldval['qid'], $oldQuestOrder[$gkey]);
                    foreach ($fieldmap as $key => $field) {
                        if (isset($field['qid']) && $field['qid'] == $newQuestOrder[$gkey][$idx]) {
                            $field['random_gid'] = $fieldval['gid'];
                            // It is possible to swap to another group
                            $copyFieldMap[$key] = $field;
                        }
                    }
                    $found = 1;
                    break;
                } else {
                    $found = 2;
                }
            }
            if ($found == 2) {
                $copyFieldMap[$fieldkey] = $fieldval;
            }
            reset($randomGroups);
        }
        $fieldmap = $copyFieldMap;
    }
    if ($randomized === true) {
        // reset the sequencing counts
        $gseq = -1;
        $_gid = -1;
        $qseq = -1;
        $_qid = -1;
        $copyFieldMap = array();
        foreach ($fieldmap as $key => $val) {
            if ($val['gid'] != '') {
                if (isset($val['random_gid'])) {
                    $gid = $val['random_gid'];
                } else {
                    $gid = $val['gid'];
                }
                if ($gid != $_gid) {
                    $_gid = $gid;
                    ++$gseq;
                }
            }
            if ($val['qid'] != '' && $val['qid'] != $_qid) {
                $_qid = $val['qid'];
                ++$qseq;
            }
            if ($val['gid'] != '' && $val['qid'] != '') {
                $val['groupSeq'] = $gseq;
                $val['questionSeq'] = $qseq;
            }
            $copyFieldMap[$key] = $val;
        }
        $fieldmap = $copyFieldMap;
        unset($copyFieldMap);
        $_SESSION['survey_' . $surveyid]['fieldmap-' . $surveyid . $_SESSION['survey_' . $surveyid]['s_lang']] = $fieldmap;
        $_SESSION['survey_' . $surveyid]['fieldmap-' . $surveyid . '-randMaster'] = 'fieldmap-' . $surveyid . $_SESSION['survey_' . $surveyid]['s_lang'];
    }
    // TMSW Conditions->Relevance:  don't need hasconditions, or usedinconditions
    $_SESSION['survey_' . $surveyid]['fieldmap'] = $fieldmap;
    foreach ($fieldmap as $field) {
        if (isset($field['qid']) && $field['qid'] != '') {
            $_SESSION['survey_' . $surveyid]['fieldnamesInfo'][$field['fieldname']] = $field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid'];
            $_SESSION['survey_' . $surveyid]['insertarray'][] = $field['fieldname'];
            //fieldarray ARRAY CONTENTS -
            //            [0]=questions.qid,
            //			[1]=fieldname,
            //			[2]=questions.title,
            //			[3]=questions.question
            //                 	[4]=questions.type,
            //			[5]=questions.gid,
            //			[6]=questions.mandatory,
            //			[7]=conditionsexist,
            //			[8]=usedinconditions
            //			[8]=usedinconditions
            //			[9]=used in group.php for question count
            //			[10]=new group id for question in randomization group (GroupbyGroup Mode)
            if (!isset($_SESSION['survey_' . $surveyid]['fieldarray'][$field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']])) {
                //JUST IN CASE : PRECAUTION!
                //following variables are set only if $style=="full" in createFieldMap() in common_helper.
                //so, if $style = "short", set some default values here!
                if (isset($field['title'])) {
                    $title = $field['title'];
                } else {
                    $title = "";
                }
                if (isset($field['question'])) {
                    $question = $field['question'];
                } else {
                    $question = "";
                }
                if (isset($field['mandatory'])) {
                    $mandatory = $field['mandatory'];
                } else {
                    $mandatory = 'N';
                }
                if (isset($field['hasconditions'])) {
                    $hasconditions = $field['hasconditions'];
                } else {
                    $hasconditions = 'N';
                }
                if (isset($field['usedinconditions'])) {
                    $usedinconditions = $field['usedinconditions'];
                } else {
                    $usedinconditions = 'N';
                }
                $_SESSION['survey_' . $surveyid]['fieldarray'][$field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']] = array($field['qid'], $field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid'], $title, $question, $field['type'], $field['gid'], $mandatory, $hasconditions, $usedinconditions);
            }
            if (isset($field['random_gid'])) {
                $_SESSION['survey_' . $surveyid]['fieldarray'][$field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']][10] = $field['random_gid'];
            }
        }
    }
    // Prefill questions/answers from command line params
    $reservedGetValues = array('token', 'sid', 'gid', 'qid', 'lang', 'newtest', 'action');
    $startingValues = array();
    if (isset($_GET)) {
        foreach ($_GET as $k => $v) {
            if (!in_array($k, $reservedGetValues) && isset($_SESSION['survey_' . $surveyid]['fieldmap'][$k])) {
                $startingValues[$k] = $v;
            }
        }
    }
    $_SESSION['survey_' . $surveyid]['startingValues'] = $startingValues;
    if (isset($_SESSION['survey_' . $surveyid]['fieldarray'])) {
        $_SESSION['survey_' . $surveyid]['fieldarray'] = array_values($_SESSION['survey_' . $surveyid]['fieldarray']);
    }
    //Check if a passthru label and value have been included in the query url
    $oResult = Survey_url_parameters::model()->getParametersForSurvey($surveyid);
    foreach ($oResult->readAll() as $aRow) {
        if (isset($_GET[$aRow['parameter']]) && !$preview) {
            $_SESSION['survey_' . $surveyid]['urlparams'][$aRow['parameter']] = $_GET[$aRow['parameter']];
            if ($aRow['targetqid'] != '') {
                foreach ($fieldmap as $sFieldname => $aField) {
                    if ($aRow['targetsqid'] != '') {
                        if ($aField['qid'] == $aRow['targetqid'] && $aField['sqid'] == $aRow['targetsqid']) {
                            $_SESSION['survey_' . $surveyid]['startingValues'][$sFieldname] = $_GET[$aRow['parameter']];
                            $_SESSION['survey_' . $surveyid]['startingValues'][$aRow['parameter']] = $_GET[$aRow['parameter']];
                        }
                    } else {
                        if ($aField['qid'] == $aRow['targetqid']) {
                            $_SESSION['survey_' . $surveyid]['startingValues'][$sFieldname] = $_GET[$aRow['parameter']];
                            $_SESSION['survey_' . $surveyid]['startingValues'][$aRow['parameter']] = $_GET[$aRow['parameter']];
                        }
                    }
                }
            }
        }
    }
}
Example #7
0
 function deleteRecords($iTokenIds)
 {
     foreach ($iTokenIds as &$currentrow) {
         $currentrow = Yii::app()->db->quoteValue($currentrow);
     }
     $dlquery = "DELETE FROM " . Tokens_dynamic::tableName() . " WHERE tid IN (" . implode(", ", $iTokenIds) . ")";
     return Yii::app()->db->createCommand($dlquery)->query();
 }
Example #8
0
/**
* Returns true when a token can not be used (either doesn't exist, has less then one usage left )
*
* @param mixed $tid Token
*/
function usedTokens($token, $surveyid)
{
    $utresult = true;
    Tokens_dynamic::sid($surveyid);
    $query = Tokens_dynamic::model()->findAllByAttributes(array("token" => $token));
    if (count($query) > 0) {
        $row = $query[0];
        if ($row->usesleft > 0) {
            $utresult = false;
        }
    }
    return $utresult;
}
 /**
  * Returns surveys in json format
  *
  * @access public
  * @return void
  */
 public function getSurveys_json()
 {
     $this->getController()->loadHelper('surveytranslator');
     $clang = $this->getController()->lang;
     $dateformatdetails = getDateFormatData(Yii::app()->session['dateformat']);
     $surveys = Survey::model();
     //!!! Is this even possible to execute?
     if (empty(Yii::app()->session['USER_RIGHT_SUPERADMIN'])) {
         $surveys->permission(Yii::app()->user->getId());
     }
     $surveys = $surveys->with(array('languagesettings' => array('condition' => 'surveyls_language=language'), 'owner'))->findAll();
     $aSurveyEntries = new stdClass();
     $aSurveyEntries->page = 1;
     foreach ($surveys as $rows) {
         if (!isset($rows->owner->attributes)) {
             $aOwner = array('users_name' => $clang->gT('(None)'));
         } else {
             $aOwner = $rows->owner->attributes;
         }
         $rows = array_merge($rows->attributes, $rows->languagesettings[0]->attributes, $aOwner);
         $aSurveyEntry = array();
         // Set status
         if ($rows['active'] == "Y" && $rows['expires'] != '' && $rows['expires'] < dateShift(date("Y-m-d H:i:s"), "Y-m-d", Yii::app()->getConfig('timeadjust'))) {
             $aSurveyEntry[] = '<!--a--><img src="' . Yii::app()->getConfig('adminimageurl') . 'expired.png" alt="' . $clang->gT("This survey is active but expired.") . '" />';
         } elseif ($rows['active'] == "Y" && $rows['startdate'] != '' && $rows['startdate'] > dateShift(date("Y-m-d H:i:s"), "Y-m-d", Yii::app()->getConfig('timeadjust'))) {
             $aSurveyEntry[] = '<!--b--><img src="' . Yii::app()->getConfig('adminimageurl') . 'notyetstarted.png" alt="' . $clang->gT("This survey is active but has a start date.") . '" />';
         } elseif ($rows['active'] == "Y") {
             if (hasSurveyPermission($rows['sid'], 'surveyactivation', 'update')) {
                 $aSurveyEntry[] = '<!--c--><a href="' . $this->getController()->createUrl('admin/survey/sa/deactivate/surveyid/' . $rows['sid']) . '"><img src="' . Yii::app()->getConfig('adminimageurl') . 'active.png" alt="' . $clang->gT("This survey is active - click here to stop this survey.") . '"/></a>';
             } else {
                 $aSurveyEntry[] = '<!--d--><img src="' . Yii::app()->getConfig('adminimageurl') . 'active.png" alt="' . $clang->gT("This survey is currently active.") . '" />';
             }
         } else {
             $condition = "sid={$rows['sid']} AND language='" . $rows['language'] . "'";
             $questionsCountResult = Questions::model()->count($condition);
             if ($questionsCountResult > 0 && hasSurveyPermission($rows['sid'], 'surveyactivation', 'update')) {
                 $aSurveyEntry[] = '<!--e--><a href="' . $this->getController()->createUrl('admin/survey/sa/activate/surveyid/' . $rows['sid']) . '"><img src="' . Yii::app()->getConfig('adminimageurl') . 'inactive.png" title="" alt="' . $clang->gT("This survey is currently not active - click here to activate this survey.") . '" /></a>';
             } else {
                 $aSurveyEntry[] = '<!--f--><img src="' . Yii::app()->getConfig('adminimageurl') . 'inactive.png" title="' . $clang->gT("This survey is currently not active.") . '" alt="' . $clang->gT("This survey is currently not active.") . '" />';
             }
         }
         //Set SID
         $aSurveyEntry[] = $rows['sid'];
         '<a href="' . $this->getController()->createUrl("/admin/survey/sa/view/surveyid/" . $rows['sid']) . '">' . $rows['sid'] . '</a>';
         //Set Title
         $aSurveyEntry[] = '<!--' . $rows['surveyls_title'] . '--><a href="' . $this->getController()->createUrl("/admin/survey/sa/view/surveyid/" . $rows['sid']) . '" title="' . $rows['surveyls_title'] . '">' . $rows['surveyls_title'] . '</a>';
         //Set Date
         Yii::import('application.libraries.Date_Time_Converter', true);
         $datetimeobj = new Date_Time_Converter($rows['datecreated'], "Y-m-d H:i:s");
         $aSurveyEntry[] = '<!--' . $rows['datecreated'] . '-->' . $datetimeobj->convert($dateformatdetails['phpdate']);
         //Set Owner
         if (Yii::app()->session['USER_RIGHT_SUPERADMIN'] || Yii::app()->session['loginID'] == $rows['owner_id']) {
             $aSurveyEntry[] = $rows['users_name'] . ' (<a class="ownername_edit" translate_to="' . $clang->gT('Edit') . '" id="ownername_edit_' . $rows['sid'] . '">' . $clang->gT('Edit') . '</a>)';
         } else {
             $aSurveyEntry[] = $rows['users_name'];
         }
         //Set Access
         if (tableExists('tokens_' . $rows['sid'])) {
             $aSurveyEntry[] = $clang->gT("Closed");
         } else {
             $aSurveyEntry[] = $clang->gT("Open");
         }
         //Set Anonymous
         if ($rows['anonymized'] == "Y") {
             $aSurveyEntry[] = $clang->gT("Yes");
         } else {
             $aSurveyEntry[] = $clang->gT("No");
         }
         //Set Responses
         if ($rows['active'] == "Y") {
             $cntResult = Survey_dynamic::countAllAndPartial($rows['sid']);
             $all = $cntResult['cntall'];
             $partial = $cntResult['cntpartial'];
             $aSurveyEntry[] = $all - $partial;
             $aSurveyEntry[] = $partial;
             $aSurveyEntry[] = $all;
             $aSurveyEntry['viewurl'] = $this->getController()->createUrl("/admin/survey/sa/view/surveyid/" . $rows['sid']);
             if (tableExists('tokens_' . $rows['sid'])) {
                 $cntResult = Tokens_dynamic::countAllAndCompleted($rows['sid']);
                 $tokens = $cntResult['cntall'];
                 $tokenscompleted = $cntResult['cntcompleted'];
                 $aSurveyEntry[] = $tokens;
                 $aSurveyEntry[] = $tokens == 0 ? 0 : round($tokenscompleted / $tokens * 100, 1);
             } else {
                 $aSurveyEntry[] = $aSurveyEntry[] = '';
             }
         } else {
             $aSurveyEntry[] = $aSurveyEntry[] = $aSurveyEntry[] = $aSurveyEntry[] = $aSurveyEntry[] = '';
         }
         $aSurveyEntries->rows[] = array('id' => $rows['sid'], 'cell' => $aSurveyEntry);
     }
     echo ls_json_encode($aSurveyEntries);
 }
function tokensExport($iSurveyID)
{
    $bquery = "SELECT * FROM {{tokens_{$iSurveyID}}} where 1=1";
    $databasetype = Yii::app()->db->getDriverName();
    if (trim($_POST['filteremail']) != '') {
        if (in_array($databasetype, array('mssql', 'sqlsrv'))) {
            $bquery .= ' and CAST(email as varchar) like ' . dbQuoteAll('%' . $_POST['filteremail'] . '%', true);
        } else {
            $bquery .= ' and email like ' . dbQuoteAll('%' . $_POST['filteremail'] . '%', true);
        }
    }
    if ($_POST['tokenstatus'] == 1) {
        $bquery .= " and completed<>'N'";
    }
    if ($_POST['tokenstatus'] == 2) {
        $bquery .= " and completed='N'";
        if ($thissurvey['anonymized'] == 'N') {
            $bquery .= " and token not in (select token from {{survey_{$iSurveyID}}} group by token)";
        }
    }
    if ($_POST['tokenstatus'] == 3 && $thissurvey['anonymized'] == 'N') {
        $bquery .= " and completed='N' and token in (select token from {{survey_{$iSurveyID}}} group by token)";
    }
    if ($_POST['invitationstatus'] == 1) {
        $bquery .= " and sent<>'N'";
    }
    if ($_POST['invitationstatus'] == 2) {
        $bquery .= " and sent='N'";
    }
    if ($_POST['reminderstatus'] == 1) {
        $bquery .= " and remindersent<>'N'";
    }
    if ($_POST['reminderstatus'] == 2) {
        $bquery .= " and remindersent='N'";
    }
    if ($_POST['tokenlanguage'] != '') {
        $bquery .= " and language=" . dbQuoteAll($_POST['tokenlanguage']);
    }
    $bquery .= " ORDER BY tid";
    Yii::app()->loadHelper('database');
    $bresult = Yii::app()->db->createCommand($bquery)->query()->readAll();
    //dbExecuteAssoc($bquery) is faster but deprecated!
    //HEADERS should be after the above query else timeout errors in case there are lots of tokens!
    header("Content-Disposition: attachment; filename=tokens_" . $iSurveyID . ".csv");
    header("Content-type: text/comma-separated-values; charset=UTF-8");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Pragma: cache");
    $bfieldcount = count($bresult);
    // Export UTF8 WITH BOM
    $tokenoutput = chr(hexdec('EF')) . chr(hexdec('BB')) . chr(hexdec('BF'));
    $tokenoutput .= "tid,firstname,lastname,email,emailstatus,token,language,validfrom,validuntil,invited,reminded,remindercount,completed,usesleft";
    $attrfieldnames = getAttributeFieldNames($iSurveyID);
    $attrfielddescr = getTokenFieldsAndNames($iSurveyID, true);
    foreach ($attrfieldnames as $attr_name) {
        $tokenoutput .= ", {$attr_name}";
        if (isset($attrfielddescr[$attr_name])) {
            $tokenoutput .= " <" . str_replace(",", " ", $attrfielddescr[$attr_name]['description']) . ">";
        }
    }
    $tokenoutput .= "\n";
    Yii::import('application.libraries.Date_Time_Converter', true);
    $aExportedTokens = array();
    foreach ($bresult as $brow) {
        if (trim($brow['validfrom'] != '')) {
            $datetimeobj = new Date_Time_Converter($brow['validfrom'], "Y-m-d H:i:s");
            $brow['validfrom'] = $datetimeobj->convert('Y-m-d H:i');
        }
        if (trim($brow['validuntil'] != '')) {
            $datetimeobj = new Date_Time_Converter($brow['validuntil'], "Y-m-d H:i:s");
            $brow['validuntil'] = $datetimeobj->convert('Y-m-d H:i');
        }
        $tokenoutput .= '"' . trim($brow['tid']) . '",';
        $tokenoutput .= '"' . trim($brow['firstname']) . '",';
        $tokenoutput .= '"' . trim($brow['lastname']) . '",';
        $tokenoutput .= '"' . trim($brow['email']) . '",';
        $tokenoutput .= '"' . trim($brow['emailstatus']) . '",';
        $tokenoutput .= '"' . trim($brow['token']) . '",';
        $tokenoutput .= '"' . trim($brow['language']) . '",';
        $tokenoutput .= '"' . trim($brow['validfrom']) . '",';
        $tokenoutput .= '"' . trim($brow['validuntil']) . '",';
        $tokenoutput .= '"' . trim($brow['sent']) . '",';
        $tokenoutput .= '"' . trim($brow['remindersent']) . '",';
        $tokenoutput .= '"' . trim($brow['remindercount']) . '",';
        $tokenoutput .= '"' . trim($brow['completed']) . '",';
        $tokenoutput .= '"' . trim($brow['usesleft']) . '",';
        foreach ($attrfieldnames as $attr_name) {
            $tokenoutput .= '"' . trim($brow[$attr_name]) . '",';
        }
        $tokenoutput = substr($tokenoutput, 0, -1);
        // remove last comma
        $tokenoutput .= "\n";
        $aExportedTokens[] = $brow['tid'];
    }
    echo $tokenoutput;
    if (Yii::app()->request->getPost('tokendeleteexported') && !empty($aExportedTokens)) {
        Tokens_dynamic::model($iSurveyID)->deleteByPk($aExportedTokens);
    }
}
Example #11
0
 /**
  * Handle token form for addnew/edit actions
  */
 function _handletokenform($iSurveyId, $subaction, $iTokenId = "")
 {
     // CHECK TO SEE IF A TOKEN TABLE EXISTS FOR THIS SURVEY
     $bTokenExists = tableExists('{{tokens_' . $iSurveyId . '}}');
     if (!$bTokenExists) {
         self::_newtokentable($iSurveyId);
     }
     $clang = $this->getController()->lang;
     Yii::app()->loadHelper("surveytranslator");
     if ($subaction == "edit") {
         $aData['tokenid'] = $iTokenId;
         $aData['tokendata'] = Tokens_dynamic::model($iSurveyId)->findByPk($iTokenId);
     }
     $thissurvey = getSurveyInfo($iSurveyId);
     $aAdditionalAttributeFields = $thissurvey['attributedescriptions'];
     $aTokenFieldNames = Yii::app()->db->getSchema()->getTable("{{tokens_{$iSurveyId}}}", true);
     $aTokenFieldNames = array_keys($aTokenFieldNames->columns);
     $aData['attrfieldnames'] = array();
     foreach ($aAdditionalAttributeFields as $sField => $aAttrData) {
         if (in_array($sField, $aTokenFieldNames)) {
             if ($aAttrData['description'] == '') {
                 $aAttrData['description'] = $sField;
             }
             $aData['attrfieldnames'][(string) $sField] = $aAttrData;
         }
     }
     foreach ($aTokenFieldNames as $sTokenFieldName) {
         if (strpos($sTokenFieldName, 'attribute_') === 0 && (!isset($aData['attrfieldnames']) || !isset($aData['attrfieldnames'][$sTokenFieldName]))) {
             $aData['attrfieldnames'][$sTokenFieldName] = array('description' => $sTokenFieldName, 'mandatory' => 'N');
         }
     }
     $aData['thissurvey'] = $thissurvey;
     $aData['surveyid'] = $iSurveyId;
     $aData['subaction'] = $subaction;
     $aData['dateformatdetails'] = getDateFormatData(Yii::app()->session['dateformat']);
     $this->_renderWrappedTemplate('token', array('tokenbar', 'tokenform'), $aData);
 }
Example #12
0
 public function index($iSurveyID)
 {
     $aData = $this->_getData($iSurveyID);
     extract($aData);
     $aViewUrls = array();
     $oBrowseLanguage = new Limesurvey_lang($aData['language']);
     /**
      * fnames is used as informational array
      * it containts
      *             $fnames[] = array(<dbfieldname>, <some strange title>, <questiontext>, <group_id>, <questiontype>);
      */
     if (Yii::app()->request->getPost('sql')) {
         $aViewUrls[] = 'browseallfiltered_view';
     }
     $clang = $aData['clang'];
     $aData['num_total_answers'] = Survey_dynamic::model($iSurveyID)->count();
     $aData['num_completed_answers'] = Survey_dynamic::model($iSurveyID)->count('submitdate IS NOT NULL');
     if (tableExists('{{tokens_' . $iSurveyID . '}}')) {
         $aData['with_token'] = Yii::app()->db->schema->getTable('{{tokens_' . $iSurveyID . '}}');
         $aData['tokeninfo'] = Tokens_dynamic::model($iSurveyID)->summary();
     }
     $aViewUrls[] = 'browseindex_view';
     $this->_renderWrappedTemplate('', $aViewUrls, $aData);
 }
 /**
  * Show dialogs and create a new tokens table
  */
 function _newtokentable($iSurveyId)
 {
     $clang = $this->getController()->lang;
     $aSurveyInfo = getSurveyInfo($iSurveyId);
     if (!hasSurveyPermission($iSurveyId, 'surveysettings', 'update') && !HasSurveyPermission($iSurveyId, 'tokens', 'create')) {
         Yii::app()->session['flashmessage'] = $clang->gT("Tokens have not been initialised for this survey.");
         $this->getController()->redirect($this->getController()->createUrl("/admin/survey/sa/view/surveyid/{$iSurveyId}"));
     }
     $bTokenExists = tableExists('{{tokens_' . $iSurveyId . '}}');
     if ($bTokenExists) {
         Yii::app()->session['flashmessage'] = $clang->gT("Tokens already exist for this survey.");
         $this->getController()->redirect($this->getController()->createUrl("/admin/survey/sa/view/surveyid/{$iSurveyId}"));
     }
     // The user have rigth to create token, then don't test right after
     Yii::import('application.helpers.admin.token_helper', true);
     if (Yii::app()->request->getQuery('createtable') == "Y") {
         createTokenTable($iSurveyId);
         $this->_renderWrappedTemplate('token', array('message' => array('title' => $clang->gT("Token control"), 'message' => $clang->gT("A token table has been created for this survey.") . " (\"" . Yii::app()->db->tablePrefix . "tokens_{$iSurveyId}\")<br /><br />\n" . "<input type='submit' value='" . $clang->gT("Continue") . "' onclick=\"window.open('" . $this->getController()->createUrl("admin/tokens/sa/index/surveyid/{$iSurveyId}") . "', '_top')\" />\n")));
     } elseif (returnGlobal('restoretable') == "Y" && Yii::app()->request->getPost('oldtable')) {
         //Rebuild attributedescription value for the surveys table
         $table = Yii::app()->db->schema->getTable(Yii::app()->request->getPost('oldtable'));
         $fields = array_filter(array_keys($table->columns), 'filterForAttributes');
         $fieldcontents = $aSurveyInfo['attributedescriptions'];
         if (!is_array($fieldcontents)) {
             $fieldcontents = array();
         }
         foreach ($fields as $fieldname) {
             $name = $fieldname;
             if ($fieldname[10] == 'c') {
                 //This belongs to a cpdb attribute
                 $cpdbattid = substr($fieldname, 15);
                 $data = ParticipantAttributeNames::model()->getAttributeName($cpdbattid, Yii::app()->session['adminlang']);
                 $name = $data['attribute_name'];
             }
             if (!isset($fieldcontents[$fieldname])) {
                 $fieldcontents[$fieldname] = array('description' => $name, 'mandatory' => 'N', 'show_register' => 'N');
             }
         }
         Survey::model()->updateByPk($iSurveyId, array('attributedescriptions' => serialize($fieldcontents)));
         Yii::app()->db->createCommand()->renameTable(Yii::app()->request->getPost('oldtable'), Yii::app()->db->tablePrefix . "tokens_" . intval($iSurveyId));
         //Check that the tokens table has the required fields
         Tokens_dynamic::model($iSurveyId)->checkColumns();
         //Add any survey_links from the renamed table
         Survey_links::model()->rebuildLinksFromTokenTable($iSurveyId);
         $this->_renderWrappedTemplate('token', array('message' => array('title' => $clang->gT("Import old tokens"), 'message' => $clang->gT("A token table has been created for this survey and the old tokens were imported.") . " (\"" . Yii::app()->db->tablePrefix . "tokens_{$iSurveyId}" . "\")<br /><br />\n" . "<input type='submit' value='" . $clang->gT("Continue") . "' onclick=\"window.open('" . $this->getController()->createUrl("admin/tokens/sa/index/surveyid/{$iSurveyId}") . "', '_top')\" />\n")));
         LimeExpressionManager::SetDirtyFlag();
         // so that knows that token tables have changed
     } else {
         $this->getController()->loadHelper('database');
         $result = Yii::app()->db->createCommand(dbSelectTablesLike("{{old_tokens_" . intval($iSurveyId) . "_%}}"))->queryAll();
         $tcount = count($result);
         if ($tcount > 0) {
             foreach ($result as $rows) {
                 $oldlist[] = reset($rows);
             }
             $aData['oldlist'] = $oldlist;
         }
         $thissurvey = getSurveyInfo($iSurveyId);
         $aData['thissurvey'] = $thissurvey;
         $aData['surveyid'] = $iSurveyId;
         $aData['tcount'] = $tcount;
         $aData['databasetype'] = Yii::app()->db->getDriverName();
         $this->_renderWrappedTemplate('token', 'tokenwarning', $aData);
     }
 }
Example #14
0
/**
* Sends email to tokens - invitation and reminders
*
* @param mixed $iSurveyID
* @param array  $aResultTokens
* @param string $sType type of notification invite|remind
* @return array of results
*/
function emailTokens($iSurveyID, $aResultTokens, $sType)
{
    Yii::app()->loadHelper('common');
    $oSurvey = Survey::model()->findByPk($iSurveyID);
    if (getEmailFormat($iSurveyID) == 'html') {
        $bHtml = true;
    } else {
        $bHtml = false;
    }
    $attributes = array_keys(getTokenFieldsAndNames($iSurveyID));
    $oSurveyLocale = Surveys_languagesettings::model()->findAllByAttributes(array('surveyls_survey_id' => $iSurveyID));
    $oTokens = Tokens_dynamic::model($iSurveyID);
    $aSurveyLangs = $oSurvey->additionalLanguages;
    array_unshift($aSurveyLangs, $oSurvey->language);
    //Convert result to associative array to minimize SurveyLocale access attempts
    foreach ($oSurveyLocale as $rows) {
        $oTempObject = array();
        foreach ($rows as $k => $v) {
            $oTempObject[$k] = $v;
        }
        $aSurveyLocaleData[$rows['surveyls_language']] = $oTempObject;
    }
    foreach ($aResultTokens as $aTokenRow) {
        //Select language
        $aTokenRow['language'] = trim($aTokenRow['language']);
        $found = array_search($aTokenRow['language'], $aSurveyLangs);
        if ($aTokenRow['language'] == '' || $found == false) {
            $aTokenRow['language'] = $oSurvey['language'];
        }
        $sTokenLanguage = $aTokenRow['language'];
        //Build recipient
        $to = array();
        $aEmailaddresses = explode(';', $aTokenRow['email']);
        foreach ($aEmailaddresses as $sEmailaddress) {
            $to[] = $aTokenRow['firstname'] . " " . $aTokenRow['lastname'] . " <{$sEmailaddress}>";
        }
        //Populate attributes
        $fieldsarray["{SURVEYNAME}"] = $aSurveyLocaleData[$sTokenLanguage]['surveyls_title'];
        if ($fieldsarray["{SURVEYNAME}"] == '') {
            $fieldsarray["{SURVEYNAME}"] = $aSurveyLocaleData[$oSurvey['language']]['surveyls_title'];
        }
        $fieldsarray["{SURVEYDESCRIPTION}"] = $aSurveyLocaleData[$sTokenLanguage]['surveyls_description'];
        if ($fieldsarray["{SURVEYDESCRIPTION}"] == '') {
            $fieldsarray["{SURVEYDESCRIPTION}"] = $aSurveyLocaleData[$oSurvey['language']]['surveyls_description'];
        }
        $fieldsarray["{ADMINNAME}"] = $oSurvey['admin'];
        $fieldsarray["{ADMINEMAIL}"] = $oSurvey['adminemail'];
        $from = $fieldsarray["{ADMINEMAIL}"];
        if ($from == '') {
            $from = Yii::app()->getConfig('siteadminemail');
        }
        foreach ($attributes as $attributefield) {
            $fieldsarray['{' . strtoupper($attributefield) . '}'] = $aTokenRow[$attributefield];
            $fieldsarray['{TOKEN:' . strtoupper($attributefield) . '}'] = $aTokenRow[$attributefield];
        }
        //create urls
        $fieldsarray["{OPTOUTURL}"] = Yii::app()->getController()->createAbsoluteUrl("/optout/tokens/langcode/" . trim($aTokenRow['language']) . "/surveyid/{$iSurveyID}/token/{$aTokenRow['token']}");
        $fieldsarray["{OPTINURL}"] = Yii::app()->getController()->createAbsoluteUrl("/optin/tokens/langcode/" . trim($aTokenRow['language']) . "/surveyid/{$iSurveyID}/token/{$aTokenRow['token']}");
        $fieldsarray["{SURVEYURL}"] = Yii::app()->getController()->createAbsoluteUrl("/survey/index/sid/{$iSurveyID}/token/{$aTokenRow['token']}/lang/" . trim($aTokenRow['language']) . "/");
        if ($bEmail == true) {
            foreach (array('OPTOUT', 'OPTIN', 'SURVEY') as $key) {
                $url = $fieldsarray["{{$key}URL}"];
                $fieldsarray["{{$key}URL}"] = "<a href='{$url}'>" . htmlspecialchars($url) . '</a>';
                if ($key == 'SURVEY') {
                    $barebone_link = $url;
                }
            }
        }
        //mail headers
        $customheaders = array('1' => "X-surveyid: " . $iSurveyID, '2' => "X-tokenid: " . $fieldsarray["{TOKEN}"]);
        global $maildebug;
        //choose appriopriate email message
        if ($sType == 'invite') {
            $sSubject = $aSurveyLocaleData[$sTokenLanguage]['surveyls_email_invite_subj'];
            $sMessage = $aSurveyLocaleData[$sTokenLanguage]['surveyls_email_invite'];
        } else {
            $sSubject = $aSurveyLocaleData[$sTokenLanguage]['surveyls_email_remind_subj'];
            $sMessage = $aSurveyLocaleData[$sTokenLanguage]['surveyls_email_remind'];
        }
        $modsubject = Replacefields($sSubject, $fieldsarray);
        $modmessage = Replacefields($sMessage, $fieldsarray);
        if (isset($barebone_link)) {
            $modsubject = str_replace("@@SURVEYURL@@", $barebone_link, $modsubject);
            $modmessage = str_replace("@@SURVEYURL@@", $barebone_link, $modmessage);
        }
        if (isset($aTokenRow['validfrom']) && trim($aTokenRow['validfrom']) != '' && convertDateTimeFormat($aTokenRow['validfrom'], 'Y-m-d H:i:s', 'U') * 1 > date('U') * 1) {
            $aResult[$aTokenRow['tid']] = array('name' => $fieldsarray["{FIRSTNAME}"] . " " . $fieldsarray["{LASTNAME}"], 'email' => $fieldsarray["{EMAIL}"], 'status' => 'fail', 'error' => 'Token not valid yet');
        } elseif (isset($aTokenRow['validuntil']) && trim($aTokenRow['validuntil']) != '' && convertDateTimeFormat($aTokenRow['validuntil'], 'Y-m-d H:i:s', 'U') * 1 < date('U') * 1) {
            $aResult[$aTokenRow['tid']] = array('name' => $fieldsarray["{FIRSTNAME}"] . " " . $fieldsarray["{LASTNAME}"], 'email' => $fieldsarray["{EMAIL}"], 'status' => 'fail', 'error' => 'Token not valid anymore');
        } else {
            if (SendEmailMessage($modmessage, $modsubject, $to, $from, Yii::app()->getConfig("sitename"), $bHtml, getBounceEmail($iSurveyID), null, $customheaders)) {
                $aResult[$aTokenRow['tid']] = array('name' => $fieldsarray["{FIRSTNAME}"] . " " . $fieldsarray["{LASTNAME}"], 'email' => $fieldsarray["{EMAIL}"], 'status' => 'OK');
                if ($sType == 'invite') {
                    $oTokens->updateByPk($aTokenRow['tid'], array('sent' => dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig("timeadjust"))));
                }
                if ($sType == 'remind') {
                    $iRCount = $oTokens->findByPk($aTokenRow['tid'])->remindercount + 1;
                    $oTokens->updateByPk($aTokenRow['tid'], array('remindersent' => dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig("timeadjust"))));
                    $oTokens->updateByPk($aTokenRow['tid'], array('remindercount' => $iRCount));
                }
            } else {
                $aResult[$aTokenRow['tid']] = array('name' => $fieldsarray["{FIRSTNAME}"] . " " . $fieldsarray["{LASTNAME}"], 'email' => $fieldsarray["{EMAIL}"], 'status' => 'fail', 'error' => $maildebug);
            }
        }
        unset($fieldsarray);
    }
    return $aResult;
}