Ejemplo n.º 1
0
 /**
  * dataentry::insert()
  * insert new dataentry
  * @return
  */
 public function insert()
 {
     $clang = Yii::app()->lang;
     $subaction = Yii::app()->request->getPost('subaction');
     $surveyid = Yii::app()->request->getPost('sid');
     $lang = isset($_POST['lang']) ? Yii::app()->request->getPost('lang') : NULL;
     $aData = array('surveyid' => $surveyid, 'lang' => $lang, 'clang' => $clang);
     if (hasSurveyPermission($surveyid, 'responses', 'read')) {
         if ($subaction == "insert" && hasSurveyPermission($surveyid, 'responses', 'create')) {
             $surveytable = "{{survey_{$surveyid}}}";
             $thissurvey = getSurveyInfo($surveyid);
             $errormsg = "";
             Yii::app()->loadHelper("database");
             $aViewUrls['display']['menu_bars']['browse'] = $clang->gT("Data entry");
             $aDataentryoutput = '';
             $aDataentrymsgs = array();
             $hiddenfields = '';
             $lastanswfortoken = '';
             // check if a previous answer has been submitted or saved
             $rlanguage = '';
             if (isset($_POST['token'])) {
                 $tokencompleted = "";
                 $tcquery = "SELECT completed from {{tokens_{$surveyid}}} WHERE token='{$_POST['token']}'";
                 //dbQuoteAll($_POST['token'],true);
                 $tcresult = dbExecuteAssoc($tcquery);
                 $tcresult = $tcresult->readAll();
                 $tccount = count($tcresult);
                 foreach ($tcresult as $tcrow) {
                     $tokencompleted = $tcrow['completed'];
                 }
                 if ($tccount < 1) {
                     // token doesn't exist in token table
                     $lastanswfortoken = 'UnknownToken';
                 } elseif ($thissurvey['anonymized'] == "Y") {
                     // token exist but survey is anonymous, check completed state
                     if ($tokencompleted != "" && $tokencompleted != "N") {
                         // token is completed
                         $lastanswfortoken = 'PrivacyProtected';
                     }
                 } else {
                     // token is valid, survey not anonymous, try to get last recorded response id
                     $aquery = "SELECT id,startlanguage FROM {$surveytable} WHERE token='" . $_POST['token'] . "'";
                     //dbQuoteAll($_POST['token'],true);
                     $aresult = dbExecuteAssoc($aquery);
                     foreach ($aresult->readAll() as $arow) {
                         if ($tokencompleted != "N") {
                             $lastanswfortoken = $arow['id'];
                         }
                         $rlanguage = $arow['startlanguage'];
                     }
                 }
             }
             // First Check if the survey uses tokens and if a token has been provided
             if (tableExists('{{tokens_' . $thissurvey['sid'] . '}}') && !$_POST['token']) {
                 $errormsg = CHtml::tag('div', array('class' => 'warningheader'), $clang->gT("Error"));
                 $errormsg .= CHtml::tag('p', array(), $clang->gT("This is a closed-access survey, so you must supply a valid token.  Please contact the administrator for assistance."));
             } elseif (tableExists('{{tokens_' . $thissurvey['sid'] . '}}') && $lastanswfortoken == 'UnknownToken') {
                 $errormsg = CHtml::tag('div', array('class' => 'warningheader'), $clang->gT("Error"));
                 $errormsg .= CHtml::tag('p', array(), $clang->gT("The token you have provided is not valid or has already been used."));
             } elseif (tableExists('{{tokens_' . $thissurvey['sid'] . '}}') && $lastanswfortoken != '') {
                 $errormsg = CHtml::tag('div', array('class' => 'warningheader'), $clang->gT("Error"));
                 $errormsg .= CHtml::tag('p', array(), $clang->gT("There is already a recorded answer for this token"));
                 if ($lastanswfortoken != 'PrivacyProtected') {
                     $errormsg .= "<br /><br />" . $clang->gT("Follow the following link to update it") . ":\n";
                     $errormsg .= CHtml::link("[id:{$lastanswfortoken}]", Yii::app()->baseUrl . ('/admin/dataentry/editdata/subaction/edit/id/' . $lastanswfortoken . '/surveyid/' . $surveyid . '/lang/' . $rlanguage), array('title' => $clang->gT("Edit this entry")));
                 } else {
                     $errormsg .= "<br /><br />" . $clang->gT("This surveys uses anonymized responses, so you can't update your response.") . "\n";
                 }
             } else {
                 $last_db_id = 0;
                 if (isset($_POST['save']) && $_POST['save'] == "on") {
                     $aData['save'] = TRUE;
                     $saver['identifier'] = $_POST['save_identifier'];
                     $saver['language'] = $_POST['save_language'];
                     $saver['password'] = $_POST['save_password'];
                     $saver['passwordconfirm'] = $_POST['save_confirmpassword'];
                     $saver['email'] = $_POST['save_email'];
                     if (!returnGlobal('redo')) {
                         $password = md5($saver['password']);
                     } else {
                         $password = $saver['password'];
                     }
                     $errormsg = "";
                     if (!$saver['identifier']) {
                         $errormsg .= $clang->gT("Error") . ": " . $clang->gT("You must supply a name for this saved session.");
                     }
                     if (!$saver['password']) {
                         $errormsg .= $clang->gT("Error") . ": " . $clang->gT("You must supply a password for this saved session.");
                     }
                     if ($saver['password'] != $saver['passwordconfirm']) {
                         $errormsg .= $clang->gT("Error") . ": " . $clang->gT("Your passwords do not match.");
                     }
                     $aData['errormsg'] = $errormsg;
                     if ($errormsg) {
                         foreach ($_POST as $key => $val) {
                             if (substr($key, 0, 4) != "save" && $key != "action" && $key != "sid" && $key != "datestamp" && $key != "ipaddr") {
                                 $hiddenfields .= CHtml::hiddenField($key, $val);
                                 //$aDataentryoutput .= "<input type='hidden' name='$key' value='$val' />\n";
                             }
                         }
                     }
                 }
                 //BUILD THE SQL TO INSERT RESPONSES
                 $baselang = Survey::model()->findByPk($surveyid)->language;
                 $fieldmap = createFieldMap($surveyid, 'full', false, false, getBaseLanguageFromSurveyID($surveyid));
                 $insert_data = array();
                 $_POST['startlanguage'] = $baselang;
                 if ($thissurvey['datestamp'] == "Y") {
                     $_POST['startdate'] = $_POST['datestamp'];
                 }
                 if (isset($_POST['closerecord'])) {
                     if ($thissurvey['datestamp'] == "Y") {
                         $_POST['submitdate'] = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", Yii::app()->getConfig('timeadjust'));
                     } else {
                         $_POST['submitdate'] = date("Y-m-d H:i:s", mktime(0, 0, 0, 1, 1, 1980));
                     }
                 }
                 foreach ($fieldmap as $irow) {
                     $fieldname = $irow['fieldname'];
                     if (isset($_POST[$fieldname])) {
                         if ($_POST[$fieldname] == "" && ($irow['type'] == 'D' || $irow['type'] == 'N' || $irow['type'] == 'K')) {
                             // can't add '' in Date column
                             // Do nothing
                         } else {
                             if ($irow['type'] == '|') {
                                 if (!strpos($irow['fieldname'], "_filecount")) {
                                     $json = $_POST[$fieldname];
                                     $phparray = json_decode(stripslashes($json));
                                     $filecount = 0;
                                     for ($i = 0; $filecount < count($phparray); $i++) {
                                         if ($_FILES[$fieldname . "_file_" . $i]['error'] != 4) {
                                             $target = Yii::app()->getConfig('uploaddir') . "/surveys/" . $thissurvey['sid'] . "/files/" . randomChars(20);
                                             $size = 0.001 * $_FILES[$fieldname . "_file_" . $i]['size'];
                                             $name = rawurlencode($_FILES[$fieldname . "_file_" . $i]['name']);
                                             if (move_uploaded_file($_FILES[$fieldname . "_file_" . $i]['tmp_name'], $target)) {
                                                 $phparray[$filecount]->filename = basename($target);
                                                 $phparray[$filecount]->name = $name;
                                                 $phparray[$filecount]->size = $size;
                                                 $pathinfo = pathinfo($_FILES[$fieldname . "_file_" . $i]['name']);
                                                 $phparray[$filecount]->ext = $pathinfo['extension'];
                                                 $filecount++;
                                             }
                                         }
                                     }
                                     $insert_data[$fieldname] = ls_json_encode($phparray);
                                 } else {
                                     $insert_data[$fieldname] = count($phparray);
                                 }
                             } elseif ($irow['type'] == 'D') {
                                 Yii::app()->loadLibrary('Date_Time_Converter');
                                 $qidattributes = getQuestionAttributeValues($irow['qid'], $irow['type']);
                                 $dateformatdetails = getDateFormatDataForQID($qidattributes, $thissurvey);
                                 $datetimeobj = new Date_Time_Converter($_POST[$fieldname], $dateformatdetails['phpdate']);
                                 $insert_data[$fieldname] = $datetimeobj->convert("Y-m-d H:i:s");
                             } else {
                                 $insert_data[$fieldname] = $_POST[$fieldname];
                             }
                         }
                     }
                 }
                 Survey_dynamic::sid($surveyid);
                 $new_response = new Survey_dynamic();
                 foreach ($insert_data as $column => $value) {
                     $new_response->{$column} = $value;
                 }
                 $new_response->save();
                 $last_db_id = $new_response->getPrimaryKey();
                 if (isset($_POST['closerecord']) && isset($_POST['token']) && $_POST['token'] != '') {
                     // get submit date
                     if (isset($_POST['closedate'])) {
                         $submitdate = $_POST['closedate'];
                     } else {
                         $submitdate = dateShift(date("Y-m-d H:i:s"), "Y-m-d", $timeadjust);
                     }
                     // check how many uses the token has left
                     $usesquery = "SELECT usesleft FROM {{tokens_}}{$surveyid} WHERE token='" . $_POST['token'] . "'";
                     $usesresult = dbExecuteAssoc($usesquery);
                     $usesrow = $usesresult->readAll();
                     //$usesresult->row_array()
                     if (isset($usesrow)) {
                         $usesleft = $usesrow[0]['usesleft'];
                     }
                     // query for updating tokens
                     $utquery = "UPDATE {{tokens_{$surveyid}}}\n";
                     if (isTokenCompletedDatestamped($thissurvey)) {
                         if (isset($usesleft) && $usesleft <= 1) {
                             $utquery .= "SET usesleft=usesleft-1, completed='{$submitdate}'\n";
                         } else {
                             $utquery .= "SET usesleft=usesleft-1\n";
                         }
                     } else {
                         if (isset($usesleft) && $usesleft <= 1) {
                             $utquery .= "SET usesleft=usesleft-1, completed='Y'\n";
                         } else {
                             $utquery .= "SET usesleft=usesleft-1\n";
                         }
                     }
                     $utquery .= "WHERE token='" . $_POST['token'] . "'";
                     $utresult = dbExecuteAssoc($utquery);
                     //Yii::app()->db->Execute($utquery) or safeDie ("Couldn't update tokens table!<br />\n$utquery<br />\n".Yii::app()->db->ErrorMsg());
                     // save submitdate into survey table
                     $srid = Yii::app()->db->getLastInsertID();
                     // Yii::app()->db->getLastInsertID();
                     $sdquery = "UPDATE {{survey_{$surveyid}}} SET submitdate='" . $submitdate . "' WHERE id={$srid}\n";
                     $sdresult = dbExecuteAssoc($sdquery) or safeDie("Couldn't set submitdate response in survey table!<br />\n{$sdquery}<br />\n");
                     $last_db_id = Yii::app()->db->getLastInsertID();
                 }
                 if (isset($_POST['save']) && $_POST['save'] == "on") {
                     $srid = Yii::app()->db->getLastInsertID();
                     //Yii::app()->db->getLastInsertID();
                     $aUserData = Yii::app()->session;
                     //CREATE ENTRY INTO "saved_control"
                     $saved_control_table = '{{saved_control}}';
                     $columns = array("sid", "srid", "identifier", "access_code", "email", "ip", "refurl", 'saved_thisstep', "status", "saved_date");
                     $values = array("'" . $surveyid . "'", "'" . $srid . "'", "'" . $saver['identifier'] . "'", "'" . $password . "'", "'" . $saver['email'] . "'", "'" . $aUserData['ip_address'] . "'", "'" . getenv("HTTP_REFERER") . "'", 0, "'" . "S" . "'", "'" . dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", "'" . Yii::app()->getConfig('timeadjust')) . "'");
                     $SQL = "INSERT INTO {$saved_control_table}\n                        (" . implode(',', $columns) . ")\n                        VALUES\n                        (" . implode(',', $values) . ")";
                     /*$scdata = array("sid"=>$surveyid,
                       "srid"=>$srid,
                       "identifier"=>$saver['identifier'],
                       "access_code"=>$password,
                       "email"=>$saver['email'],
                       "ip"=>$aUserData['ip_address'],
                       "refurl"=>getenv("HTTP_REFERER"),
                       'saved_thisstep' => 0,
                       "status"=>"S",
                       "saved_date"=>dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", Yii::app()->getConfig('timeadjust')));
                       $this->load->model('saved_control_model');*/
                     if (dbExecuteAssoc($SQL)) {
                         $scid = Yii::app()->db->getLastInsertID();
                         // Yii::app()->db->getLastInsertID("{{saved_control}}","scid");
                         $aDataentrymsgs[] = CHtml::tag('font', array('class' => 'successtitle'), $clang->gT("Your survey responses have been saved successfully.  You will be sent a confirmation e-mail. Please make sure to save your password, since we will not be able to retrieve it for you."));
                         //$aDataentryoutput .= "<font class='successtitle'></font><br />\n";
                         $tokens_table = "{{tokens_{$surveyid}}}";
                         $last_db_id = Yii::app()->db->getLastInsertID();
                         if (tableExists($tokens_table)) {
                             $tkquery = "SELECT * FROM {$tokens_table}";
                             $tkresult = dbExecuteAssoc($tkquery);
                             /*$tokendata = array (
                               "firstname"=> $saver['identifier'],
                               "lastname"=> $saver['identifier'],
                               "email"=>$saver['email'],
                               "token"=>randomChars(15),
                               "language"=>$saver['language'],
                               "sent"=>dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", $timeadjust),
                               "completed"=>"N");*/
                             $columns = array("firstname", "lastname", "email", "token", "language", "sent", "completed");
                             $values = array("'" . $saver['identifier'] . "'", "'" . $saver['identifier'] . "'", "'" . $saver['email'] . "'", "'" . $password . "'", "'" . randomChars(15) . "'", "'" . $saver['language'] . "'", "'" . "N" . "'");
                             $SQL = "INSERT INTO {$token_table}\n                                (" . implode(',', $columns) . ")\n                                VALUES\n                                (" . implode(',', $values) . ")";
                             //$this->tokens_dynamic_model->insertToken($surveyid,$tokendata);
                             dbExecuteAssoc($SQL);
                             //Yii::app()->db->AutoExecute(db_table_name("tokens_".$surveyid), $tokendata,'INSERT');
                             $aDataentrymsgs[] = CHtml::tag('font', array('class' => 'successtitle'), $clang->gT("A token entry for the saved survey has been created too."));
                             //$aDataentryoutput .= "<font class='successtitle'></font><br />\n";
                             $last_db_id = Yii::app()->db->getLastInsertID();
                         }
                         if ($saver['email']) {
                             //Send email
                             if (validateEmailAddress($saver['email']) && !returnGlobal('redo')) {
                                 $subject = $clang->gT("Saved Survey Details");
                                 $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.");
                                 $message .= "\n\n" . $thissurvey['name'] . "\n\n";
                                 $message .= $clang->gT("Name") . ": " . $saver['identifier'] . "\n";
                                 $message .= $clang->gT("Password") . ": " . $saver['password'] . "\n\n";
                                 $message .= $clang->gT("Reload your survey by clicking on the following link (or pasting it into your browser):") . ":\n";
                                 $message .= Yii::app()->getConfig('publicurl') . "/index.php?sid={$surveyid}&loadall=reload&scid=" . $scid . "&lang=" . urlencode($saver['language']) . "&loadname=" . urlencode($saver['identifier']) . "&loadpass="******"&token=" . $tokendata['token'];
                                 }
                                 $from = $thissurvey['adminemail'];
                                 if (SendEmailMessage($message, $subject, $saver['email'], $from, $sitename, false, getBounceEmail($surveyid))) {
                                     $emailsent = "Y";
                                     $aDataentrymsgs[] = CHtml::tag('font', array('class' => 'successtitle'), $clang->gT("An email has been sent with details about your saved survey"));
                                 }
                             }
                         }
                     } else {
                         safeDie("Unable to insert record into saved_control table.<br /><br />");
                     }
                 }
                 $aData['thisid'] = $last_db_id;
             }
             $aData['errormsg'] = $errormsg;
             $aData['dataentrymsgs'] = $aDataentrymsgs;
             $this->_renderWrappedTemplate('dataentry', 'insert', $aData);
         }
     }
 }
Ejemplo n.º 2
0
/**
* @param integer $iSurveyID The Survey ID
* @param string $sFieldCode Field code of the particular field
* @param string $sValue The stored response value
* @param string $sLanguage Initialized limesurvey_lang object for the resulting response data
* @return string
*/
function getExtendedAnswer($iSurveyID, $sFieldCode, $sValue, $sLanguage)
{
    if ($sValue == null || $sValue == '') {
        return '';
    }
    //Fieldcode used to determine question, $sValue used to match against answer code
    //Returns NULL if question type does not suit
    if (strpos($sFieldCode, "{$iSurveyID}X") === 0) {
        $fieldmap = createFieldMap($iSurveyID, 'short', false, false, $sLanguage);
        if (isset($fieldmap[$sFieldCode])) {
            $fields = $fieldmap[$sFieldCode];
        } else {
            return false;
        }
        // If it is a comment field there is nothing to convert here
        if ($fields['aid'] == 'comment') {
            return $sValue;
        }
        //Find out the question type
        $this_type = $fields['type'];
        switch ($this_type) {
            case 'D':
                if (trim($sValue) != '') {
                    $qidattributes = getQuestionAttributeValues($fields['qid']);
                    $dateformatdetails = getDateFormatDataForQID($qidattributes, $iSurveyID);
                    $sValue = convertDateTimeFormat($sValue, "Y-m-d H:i:s", $dateformatdetails['phpdate']);
                }
                break;
            case 'N':
                if (trim($sValue) != '') {
                    if (strpos($sValue, ".") !== false) {
                        $sValue = rtrim(rtrim($sValue, "0"), ".");
                    }
                    $qidattributes = getQuestionAttributeValues($fields['qid']);
                    if ($qidattributes['num_value_int_only']) {
                        $sValue = number_format($sValue, 0, '', '');
                    }
                }
                break;
            case "L":
            case "!":
            case "O":
            case "^":
            case "I":
            case "R":
                $result = Answer::model()->getAnswerFromCode($fields['qid'], $sValue, $sLanguage);
                foreach ($result as $row) {
                    $this_answer = $row['answer'];
                }
                // while
                if ($sValue == "-oth-") {
                    $this_answer = gT("Other", null, $sLanguage);
                }
                break;
            case "M":
            case "J":
            case "P":
                switch ($sValue) {
                    case "Y":
                        $this_answer = gT("Yes", null, $sLanguage);
                        break;
                }
                break;
            case "Y":
                switch ($sValue) {
                    case "Y":
                        $this_answer = gT("Yes", null, $sLanguage);
                        break;
                    case "N":
                        $this_answer = gT("No", null, $sLanguage);
                        break;
                    default:
                        $this_answer = gT("No answer", null, $sLanguage);
                }
                break;
            case "G":
                switch ($sValue) {
                    case "M":
                        $this_answer = gT("Male", null, $sLanguage);
                        break;
                    case "F":
                        $this_answer = gT("Female", null, $sLanguage);
                        break;
                    default:
                        $this_answer = gT("No answer", null, $sLanguage);
                }
                break;
            case "C":
                switch ($sValue) {
                    case "Y":
                        $this_answer = gT("Yes", null, $sLanguage);
                        break;
                    case "N":
                        $this_answer = gT("No", null, $sLanguage);
                        break;
                    case "U":
                        $this_answer = gT("Uncertain", null, $sLanguage);
                        break;
                }
                break;
            case "E":
                switch ($sValue) {
                    case "I":
                        $this_answer = gT("Increase", null, $sLanguage);
                        break;
                    case "D":
                        $this_answer = gT("Decrease", null, $sLanguage);
                        break;
                    case "S":
                        $this_answer = gT("Same", null, $sLanguage);
                        break;
                }
                break;
            case "F":
            case "H":
            case "1":
                $aConditions = array('qid' => $fields['qid'], 'code' => $sValue, 'language' => $sLanguage);
                if (isset($fields['scale_id'])) {
                    $iScaleID = $fields['scale_id'];
                } else {
                    $iScaleID = 0;
                }
                $result = Answer::model()->getAnswerFromCode($fields['qid'], $sValue, $sLanguage, $iScaleID);
                foreach ($result as $row) {
                    $this_answer = $row['answer'];
                }
                // while
                if ($sValue == "-oth-") {
                    $this_answer = gT("Other", null, $sLanguage);
                }
                break;
            case "|":
                //File upload
                if (substr($sFieldCode, -9) != 'filecount') {
                    //Show the filename, size, title and comment -- no link!
                    $files = json_decode($sValue);
                    $sValue = '';
                    if (is_array($files)) {
                        foreach ($files as $file) {
                            $sValue .= rawurldecode($file->name) . ' (' . round($file->size) . 'KB) ' . strip_tags($file->title);
                            if (trim(strip_tags($file->comment)) != "") {
                                $sValue .= ' - ' . strip_tags($file->comment);
                            }
                        }
                    }
                }
                break;
            default:
        }
        // switch
    }
    switch ($sFieldCode) {
        case 'submitdate':
        case 'startdate':
        case 'datestamp':
            if (trim($sValue) != '') {
                $dateformatdetails = getDateFormatDataForQID(null, $iSurveyID);
                $sValue = convertDateTimeFormat($sValue, "Y-m-d H:i:s", $dateformatdetails['phpdate'] . ' H:i:s');
            }
            break;
    }
    if (isset($this_answer)) {
        return $this_answer . " [{$sValue}]";
    } else {
        return $sValue;
    }
}
Ejemplo n.º 3
0
function do_date($ia)
{
    global $thissurvey;
    $aQuestionAttributes = getQuestionAttributeValues($ia[0], $ia[4]);
    $sDateLangvarJS = " translt = {\n         alertInvalidDate: '" . gT('Date entered is invalid!', 'js') . "',\n         infoCompleteAll: '" . gT('Please complete all parts of the date!', 'js') . "'\n        };";
    App()->getClientScript()->registerScript("sDateLangvarJS", $sDateLangvarJS, CClientScript::POS_HEAD);
    App()->getClientScript()->registerScriptFile(Yii::app()->getConfig("generalscripts") . 'date.js');
    App()->getClientScript()->registerScriptFile(Yii::app()->getConfig("third_party") . 'jstoolbox/date.js');
    $checkconditionFunction = "checkconditions";
    $dateformatdetails = getDateFormatDataForQID($aQuestionAttributes, $thissurvey);
    $numberformatdatat = getRadixPointData($thissurvey['surveyls_numberformat']);
    $sMindatetailor = '';
    $sMaxdatetailor = '';
    // date_min: Determine whether we have an expression, a full date (YYYY-MM-DD) or only a year(YYYY)
    if (trim($aQuestionAttributes['date_min']) != '') {
        $date_min = $aQuestionAttributes['date_min'];
        if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/", $date_min)) {
            $mindate = $date_min;
        } elseif (strlen($date_min) == 4 && $date_min >= 1900 && $date_min <= 2099) {
            // backward compatibility: if only a year is given, add month and day
            $mindate = $date_min . '-01-01';
        } else {
            $mindate = '{' . $aQuestionAttributes['date_min'] . '}';
            // get the LEMtailor ID, remove the span tags
            $sMindatespan = LimeExpressionManager::ProcessString($mindate, $ia[0], NULL, false, 1, 1);
            preg_match("/LEMtailor_Q_[0-9]{1,7}_[0-9]{1,3}/", $sMindatespan, $matches);
            if (isset($matches[0])) {
                $sMindatetailor = $matches[0];
            }
        }
    } else {
        $mindate = '1900-01-01';
    }
    // date_max: Determine whether we have an expression, a full date (YYYY-MM-DD) or only a year(YYYY)
    if (trim($aQuestionAttributes['date_max']) != '') {
        $date_max = $aQuestionAttributes['date_max'];
        if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/", $date_max)) {
            $maxdate = $date_max;
        } elseif (strlen($date_max) == 4 && $date_max >= 1900 && $date_max <= 2099) {
            // backward compatibility: if only a year is given, add month and day
            $maxdate = $date_max . '-12-31';
        } else {
            $maxdate = '{' . $aQuestionAttributes['date_max'] . '}';
            // get the LEMtailor ID, remove the span tags
            $sMaxdatespan = LimeExpressionManager::ProcessString($maxdate, $ia[0], NULL, false, 1, 1);
            preg_match("/LEMtailor_Q_[0-9]{1,7}_[0-9]{1,3}/", $sMaxdatespan, $matches);
            if (isset($matches[0])) {
                $sMaxdatetailor = $matches[0];
            }
        }
    } else {
        $maxdate = '2037-12-31';
    }
    if (trim($aQuestionAttributes['dropdown_dates']) == 1) {
        if (!empty($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]]) & $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]] != 'INVALID') {
            $datetimeobj = new Date_Time_Converter($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]], "Y-m-d H:i:s");
            $currentyear = $datetimeobj->years;
            $currentmonth = $datetimeobj->months;
            $currentdate = $datetimeobj->days;
            $currenthour = $datetimeobj->hours;
            $currentminute = $datetimeobj->minutes;
        } else {
            $currentdate = '';
            $currentmonth = '';
            $currentyear = '';
            $currenthour = '';
            $currentminute = '';
        }
        $dateorder = preg_split('/([-\\.\\/ :])/', $dateformatdetails['phpdate'], -1, PREG_SPLIT_DELIM_CAPTURE);
        $answer = '<p class="question answer-item dropdown-item date-item">';
        foreach ($dateorder as $datepart) {
            switch ($datepart) {
                // Show day select box
                case 'j':
                case 'd':
                    $answer .= '<label for="day' . $ia[1] . '" class="hide">' . gT('Day') . '</label><select id="day' . $ia[1] . '" name="day' . $ia[1] . '" class="day">
                    <option value="">' . gT('Day') . "</option>\n";
                    for ($i = 1; $i <= 31; $i++) {
                        if ($i == $currentdate) {
                            $i_date_selected = SELECTED;
                        } else {
                            $i_date_selected = '';
                        }
                        $answer .= '<option value="' . sprintf('%02d', $i) . '"' . $i_date_selected . '>' . sprintf('%02d', $i) . "</option>\n";
                    }
                    $answer .= '</select>';
                    break;
                    // Show month select box
                // Show month select box
                case 'n':
                case 'm':
                    $answer .= '<label for="month' . $ia[1] . '" class="hide">' . gT('Month') . '</label><select id="month' . $ia[1] . '" name="month' . $ia[1] . '" class="month">
                    <option value="">' . gT('Month') . "</option>\n";
                    switch ((int) trim($aQuestionAttributes['dropdown_dates_month_style'])) {
                        case 0:
                            $montharray = array(gT('Jan'), gT('Feb'), gT('Mar'), gT('Apr'), gT('May'), gT('Jun'), gT('Jul'), gT('Aug'), gT('Sep'), gT('Oct'), gT('Nov'), gT('Dec'));
                            break;
                        case 1:
                            $montharray = array(gT('January'), gT('February'), gT('March'), gT('April'), gT('May'), gT('June'), gT('July'), gT('August'), gT('September'), gT('October'), gT('November'), gT('December'));
                            break;
                        case 2:
                            $montharray = array('01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12');
                            break;
                    }
                    for ($i = 1; $i <= 12; $i++) {
                        if ($i == $currentmonth) {
                            $i_date_selected = SELECTED;
                        } else {
                            $i_date_selected = '';
                        }
                        $answer .= '<option value="' . sprintf('%02d', $i) . '"' . $i_date_selected . '>' . $montharray[$i - 1] . '</option>';
                    }
                    $answer .= '</select>';
                    break;
                    // Show year select box
                // Show year select box
                case 'y':
                case 'Y':
                    $answer .= '<label for="year' . $ia[1] . '" class="hide">' . gT('Year') . '</label><select id="year' . $ia[1] . '" name="year' . $ia[1] . '" class="year">
                    <option value="">' . gT('Year') . '</option>';
                    /*
                     * yearmin = Minimum year value for dropdown list, if not set default is 1900
                     * yearmax = Maximum year value for dropdown list, if not set default is 2037
                     * if full dates (format: YYYY-MM-DD) are given, only the year is used
                     * expressions are not supported because contents of dropbox cannot be easily updated dynamically
                     */
                    $yearmin = (int) substr($mindate, 0, 4);
                    if (!isset($yearmin) || $yearmin < 1900 || $yearmin > 2037) {
                        $yearmin = 1900;
                    }
                    $yearmax = (int) substr($maxdate, 0, 4);
                    if (!isset($yearmax) || $yearmax < 1900 || $yearmax > 2037) {
                        $yearmax = 2037;
                    }
                    if ($yearmin > $yearmax) {
                        $yearmin = 1900;
                        $yearmax = 2037;
                    }
                    if ($aQuestionAttributes['reverse'] == 1) {
                        $tmp = $yearmin;
                        $yearmin = $yearmax;
                        $yearmax = $tmp;
                        $step = 1;
                        $reverse = true;
                    } else {
                        $step = -1;
                        $reverse = false;
                    }
                    for ($i = $yearmax; $reverse ? $i <= $yearmin : $i >= $yearmin; $i += $step) {
                        if ($i == $currentyear) {
                            $i_date_selected = SELECTED;
                        } else {
                            $i_date_selected = '';
                        }
                        $answer .= '<option value="' . $i . '"' . $i_date_selected . '>' . $i . '</option>';
                    }
                    $answer .= '</select>';
                    break;
                case 'H':
                case 'h':
                case 'g':
                case 'G':
                    $answer .= '<label for="hour' . $ia[1] . '" class="hide">' . gT('Hour') . '</label><select id="hour' . $ia[1] . '" name="hour' . $ia[1] . '" class="hour"><option value="">' . gT('Hour') . '</option>';
                    for ($i = 0; $i < 24; $i++) {
                        if ($i === (int) $currenthour && is_numeric($currenthour)) {
                            $i_date_selected = SELECTED;
                        } else {
                            $i_date_selected = '';
                        }
                        if ($datepart == 'H') {
                            $answer .= '<option value="' . $i . '"' . $i_date_selected . '>' . sprintf('%02d', $i) . '</option>';
                        } else {
                            $answer .= '<option value="' . $i . '"' . $i_date_selected . '>' . $i . '</option>';
                        }
                    }
                    $answer .= '</select>';
                    break;
                case 'i':
                    $answer .= '<label for="minute' . $ia[1] . '" class="hide">' . gT('Minute') . '</label><select id="minute' . $ia[1] . '" name="minute' . $ia[1] . '" class="minute">
                    <option value="">' . gT('Minute') . '</option>';
                    for ($i = 0; $i < 60; $i += $aQuestionAttributes['dropdown_dates_minute_step']) {
                        if ($i === (int) $currentminute && is_numeric($currentminute)) {
                            $i_date_selected = SELECTED;
                        } else {
                            $i_date_selected = '';
                        }
                        if ($datepart == 'i') {
                            $answer .= '<option value="' . $i . '"' . $i_date_selected . '>' . sprintf('%02d', $i) . '</option>';
                        } else {
                            $answer .= '<option value="' . $i . '"' . $i_date_selected . '>' . $i . '</option>';
                        }
                    }
                    $answer .= '</select>';
                    break;
                default:
                    $answer .= $datepart;
            }
        }
        // Format the date  for output
        $dateoutput = trim($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]]);
        if ($dateoutput != '' & $dateoutput != 'INVALID') {
            $datetimeobj = new Date_Time_Converter($dateoutput, "Y-m-d H:i");
            $dateoutput = $datetimeobj->convert($dateformatdetails['phpdate']);
        }
        $answer .= '<input class="text" type="text" size="10" name="' . $ia[1] . '" style="display: none" id="answer' . $ia[1] . '" value="' . htmlspecialchars($dateoutput, ENT_QUOTES, 'utf-8') . '" maxlength="10" alt="' . gT('Answer') . '" onchange="' . $checkconditionFunction . '(this.value, this.name, this.type)" title="' . sprintf(gT('Date in the format : %s'), $dateformatdetails['dateformat']) . '" />
        </p>';
        $answer .= '
        <input type="hidden" id="qattribute_answer' . $ia[1] . '" name="qattribute_answer' . $ia[1] . '" value="' . $ia[1] . '"/>
        <input type="hidden" id="dateformat' . $ia[1] . '" value="' . $dateformatdetails['jsdate'] . '"/>';
        App()->getClientScript()->registerScript("doDropDownDate{$ia[0]}", "doDropDownDate({$ia[0]});", CClientScript::POS_HEAD);
        // MayDo:
        // add js code to
        //        - fill dropdown boxes according to min/max
        //        - if one datefield box is changed update all others
        //        - would need a LOT of JS
    } else {
        //register timepicker extension
        App()->getClientScript()->registerPackage('jqueryui-timepicker');
        // Locale for datepicker and timpicker extension
        if (App()->language !== 'en') {
            Yii::app()->getClientScript()->registerScriptFile(App()->getConfig('third_party') . "/jqueryui/development-bundle/ui/i18n/jquery.ui.datepicker-{App()->language}.js");
            Yii::app()->getClientScript()->registerScriptFile(App()->getConfig('third_party') . "/jquery-ui-timepicker-addon/i18n/jquery-ui-timepicker-{App()->language}.js");
        }
        // Format the date  for output
        $dateoutput = trim($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]]);
        if ($dateoutput != '' & $dateoutput != 'INVALID') {
            $datetimeobj = new Date_Time_Converter($dateoutput, "Y-m-d H:i");
            $dateoutput = $datetimeobj->convert($dateformatdetails['phpdate']);
        }
        $goodchars = str_replace(array("m", "d", "y"), "", $dateformatdetails['jsdate']);
        $goodchars = "0123456789" . substr($goodchars, 0, 1);
        // Max length of date : Get the date of 1999-12-30 at 32:59:59 to be sure to have space with non leading 0 format
        // "+1" makes room for a trailing space in date/time values
        $iLength = strlen(date($dateformatdetails['phpdate'], mktime(23, 59, 59, 12, 30, 1999))) + 1;
        // HTML for date question using datepicker
        $answer = "<p class='question answer-item text-item date-item'><label for='answer{$ia[1]}' class='hide label'>" . sprintf(gT('Date in the format: %s'), $dateformatdetails['dateformat']) . "</label>\n        <input class='popupdate' type=\"text\" size=\"{$iLength}\" name=\"{$ia[1]}\" id=\"answer{$ia[1]}\" value=\"{$dateoutput}\" maxlength=\"{$iLength}\" onkeypress=\"return goodchars(event,'" . $goodchars . "')\" onchange=\"{$checkconditionFunction}(this.value, this.name, this.type)\" />\n        <input  type='hidden' name='dateformat{$ia[1]}' id='dateformat{$ia[1]}' value='{$dateformatdetails['jsdate']}'  />\n        <input  type='hidden' name='datelanguage{$ia[1]}' id='datelanguage{$ia[1]}' value='" . App()->language . "'  />\n        <input  type='hidden' name='datemin{$ia[1]}' id='datemin{$ia[1]}' value=\"{$mindate}\"    />\n        <input  type='hidden' name='datemax{$ia[1]}' id='datemax{$ia[1]}' value=\"{$maxdate}\"   />\n        </p>";
        // adds min and max date as a hidden element to the page so EM creates the needed LEM_tailor_Q_XX sections
        $sHiddenHtml = "";
        if (!empty($sMindatetailor)) {
            $sHiddenHtml .= $sMindatespan;
        }
        if (!empty($sMaxdatetailor)) {
            $sHiddenHtml .= $sMaxdatespan;
        }
        if (!empty($sHiddenHtml)) {
            $answer .= "<div class='hidden nodisplay' style='display:none'>{$sHiddenHtml}</div>";
        }
        // following JS is for setting datepicker limits on-the-fly according to variables given in date_min/max attributes
        // works with full dates (format: YYYY-MM-DD, js not needed), only a year, for backward compatibility (YYYY, js not needed),
        // variable names which refer to another date question or expressions.
        // Actual conversion of date formats is handled in LEMval()
        if (!empty($sMindatetailor) || !empty($sMaxdatetailor)) {
            $answer .= "<script>\n                \$(document).ready(function() {\n                        \$('.popupdate').change(function() {\n\n                            ";
            if (!empty($sMindatetailor)) {
                $answer .= "\n                        \$('#datemin{$ia[1]}').attr('value',\n                        document.getElementById('{$sMindatetailor}').innerHTML);\n                    ";
            }
            if (!empty($sMaxdatetailor)) {
                $answer .= "\n                        \$('#datemax{$ia[1]}').attr('value',\n                        document.getElementById('{$sMaxdatetailor}').innerHTML);\n                    ";
            }
            $answer .= "\n                        });\n                    });\n                </script>";
        }
        if (trim($aQuestionAttributes['hide_tip']) == 0) {
            $answer .= "<p class=\"tip\">" . sprintf(gT('Format: %s'), $dateformatdetails['dateformat']) . "</p>";
        }
        //App()->getClientScript()->registerScript("doPopupDate{$ia[0]}","doPopupDate({$ia[0]})",CClientScript::POS_END);// Beter if just afetre answers part
        $answer .= "<script type='text/javascript'>\n" . "  /*<![CDATA[*/\n" . " doPopupDate({$ia[0]});\n" . " /*]]>*/\n" . "</script>\n";
    }
    $inputnames[] = $ia[1];
    return array($answer, $inputnames);
}
Ejemplo n.º 4
0
function do_date($ia)
{
    global $thissurvey;
    $aQuestionAttributes = QuestionAttribute::model()->getQuestionAttributes($ia[0]);
    $checkconditionFunction = "checkconditions";
    $dateformatdetails = getDateFormatDataForQID($aQuestionAttributes, $thissurvey);
    $numberformatdatat = getRadixPointData($thissurvey['surveyls_numberformat']);
    $inputnames = array();
    $sDateLangvarJS = " translt = {\n         alertInvalidDate: '" . gT('Date entered is invalid!', 'js') . "',\n        };";
    App()->getClientScript()->registerScript("sDateLangvarJS", $sDateLangvarJS, CClientScript::POS_HEAD);
    App()->getClientScript()->registerScriptFile(Yii::app()->getConfig("generalscripts") . 'date.js');
    App()->getClientScript()->registerPackage('moment');
    // date_min: Determine whether we have an expression, a full date (YYYY-MM-DD) or only a year(YYYY)
    if (trim($aQuestionAttributes['date_min']) != '') {
        $date_min = trim($aQuestionAttributes['date_min']);
        $date_time_em = strtotime(LimeExpressionManager::ProcessString("{" . $date_min . "}", $ia[0]));
        if (ctype_digit($date_min) && strlen($date_min) == 4 && $date_min >= 1900 && $date_min <= 2099) {
            $mindate = $date_min . '-01-01';
            // backward compatibility: if only a year is given, add month and day
        } elseif (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/", $date_min)) {
            $mindate = $date_min;
        } elseif ($date_time_em) {
            $mindate = date("Y-m-d", $date_time_em);
        } else {
            $mindate = '{' . $aQuestionAttributes['date_min'] . '}';
        }
    } else {
        $mindate = '1900-01-01';
        // Why 1900 ?
    }
    // date_max: Determine whether we have an expression, a full date (YYYY-MM-DD) or only a year(YYYY)
    if (trim($aQuestionAttributes['date_max']) != '') {
        $date_max = trim($aQuestionAttributes['date_max']);
        $date_time_em = strtotime(LimeExpressionManager::ProcessString("{" . $date_max . "}", $ia[0]));
        if (ctype_digit($date_max) && strlen($date_max) == 4 && $date_max >= 1900 && $date_max <= 2099) {
            $maxdate = $date_max . '-12-31';
            // backward compatibility: if only a year is given, add month and day
        } elseif (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/", $date_max)) {
            $maxdate = $date_max;
        } elseif ($date_time_em) {
            $maxdate = date("Y-m-d", $date_time_em);
        } else {
            $maxdate = '{' . $aQuestionAttributes['date_max'] . '}';
        }
    } else {
        $maxdate = '2037-12-31';
        // Why 2037 ?
    }
    if (trim($aQuestionAttributes['dropdown_dates']) == 1) {
        if (!empty($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]]) && $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]] != 'INVALID') {
            $datetimeobj = new Date_Time_Converter($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]], "Y-m-d H:i:s");
            $currentyear = $datetimeobj->years;
            $currentmonth = $datetimeobj->months;
            $currentdate = $datetimeobj->days;
            $currenthour = $datetimeobj->hours;
            $currentminute = $datetimeobj->minutes;
        } else {
            // If date is invalid get the POSTED value
            $currentdate = App()->request->getPost("day{$ia[1]}", '');
            $currentmonth = App()->request->getPost("month{$ia[1]}", '');
            $currentyear = App()->request->getPost("year{$ia[1]}", '');
            $currenthour = App()->request->getPost("hour{$ia[1]}", '');
            $currentminute = App()->request->getPost("minute{$ia[1]}", '');
        }
        $dateorder = preg_split('/([-\\.\\/ :])/', $dateformatdetails['phpdate'], -1, PREG_SPLIT_DELIM_CAPTURE);
        $sRows = '';
        $montharray = array();
        foreach ($dateorder as $datepart) {
            switch ($datepart) {
                // Show day select box
                case 'j':
                case 'd':
                    $sRows .= doRender('/survey/questions/date/dropdown/rows/day', array('dayId' => $ia[1], 'currentdate' => $currentdate), true);
                    break;
                    // Show month select box
                // Show month select box
                case 'n':
                case 'm':
                    switch ((int) trim($aQuestionAttributes['dropdown_dates_month_style'])) {
                        case 0:
                            $montharray = array(gT('Jan'), gT('Feb'), gT('Mar'), gT('Apr'), gT('May'), gT('Jun'), gT('Jul'), gT('Aug'), gT('Sep'), gT('Oct'), gT('Nov'), gT('Dec'));
                            break;
                        case 1:
                            $montharray = array(gT('January'), gT('February'), gT('March'), gT('April'), gT('May'), gT('June'), gT('July'), gT('August'), gT('September'), gT('October'), gT('November'), gT('December'));
                            break;
                        case 2:
                            $montharray = array('01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12');
                            break;
                    }
                    $sRows .= doRender('/survey/questions/date/dropdown/rows/month', array('monthId' => $ia[1], 'currentmonth' => $currentmonth, 'montharray' => $montharray), true);
                    break;
                    // Show year select box
                // Show year select box
                case 'y':
                case 'Y':
                    /*
                     * yearmin = Minimum year value for dropdown list, if not set default is 1900
                     * yearmax = Maximum year value for dropdown list, if not set default is 2037
                     * if full dates (format: YYYY-MM-DD) are given, only the year is used
                     * expressions are not supported because contents of dropbox cannot be easily updated dynamically
                     */
                    $yearmin = (int) substr($mindate, 0, 4);
                    if (!isset($yearmin) || $yearmin < 1900 || $yearmin > 2037) {
                        $yearmin = 1900;
                    }
                    $yearmax = (int) substr($maxdate, 0, 4);
                    if (!isset($yearmax) || $yearmax < 1900 || $yearmax > 2037) {
                        $yearmax = 2037;
                    }
                    if ($yearmin > $yearmax) {
                        $yearmin = 1900;
                        $yearmax = 2037;
                    }
                    if ($aQuestionAttributes['reverse'] == 1) {
                        $tmp = $yearmin;
                        $yearmin = $yearmax;
                        $yearmax = $tmp;
                        $step = 1;
                        $reverse = true;
                    } else {
                        $step = -1;
                        $reverse = false;
                    }
                    $sRows .= doRender('/survey/questions/date/dropdown/rows/year', array('yearId' => $ia[1], 'currentyear' => $currentyear, 'yearmax' => $yearmax, 'reverse' => $reverse, 'yearmin' => $yearmin, 'step' => $step), true);
                    break;
                case 'H':
                case 'h':
                case 'g':
                case 'G':
                    $sRows .= doRender('/survey/questions/date/dropdown/rows/hour', array('hourId' => $ia[1], 'currenthour' => $currenthour, 'datepart' => $datepart), true);
                    break;
                case 'i':
                    $sRows .= doRender('/survey/questions/date/dropdown/rows/minute', array('minuteId' => $ia[1], 'currentminute' => $currenthour, 'dropdown_dates_minute_step' => $aQuestionAttributes['dropdown_dates_minute_step'], 'datepart' => $datepart), true);
                    break;
                default:
                    $sRows .= doRender('/survey/questions/date/dropdown/rows/datepart', array('datepart' => $datepart), true);
            }
        }
        // Format the date  for output
        $dateoutput = trim($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]]);
        if ($dateoutput != '' & $dateoutput != 'INVALID') {
            $datetimeobj = new Date_Time_Converter($dateoutput, "Y-m-d H:i");
            $dateoutput = $datetimeobj->convert($dateformatdetails['phpdate']);
        }
        // ==> answer
        $answer = doRender('/survey/questions/date/dropdown/answer', array('sRows' => $sRows, 'name' => $ia[1], 'dateoutput' => htmlspecialchars($dateoutput, ENT_QUOTES, 'utf-8'), 'checkconditionFunction' => $checkconditionFunction . '(this.value, this.name, this.type)', 'dateformatdetails' => $dateformatdetails['jsdate'], 'dateformat' => $dateformatdetails['jsdate']), true);
        App()->getClientScript()->registerScript("doDropDownDate{$ia[0]}", "doDropDownDate({$ia[0]});", CClientScript::POS_HEAD);
    } else {
        // Format the date  for output
        $dateoutput = trim($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]]);
        if ($dateoutput != '' & $dateoutput != 'INVALID') {
            $datetimeobj = new Date_Time_Converter($dateoutput, "Y-m-d H:i");
            $dateoutput = $datetimeobj->convert($dateformatdetails['phpdate']);
        }
        $goodchars = str_replace(array("m", "d", "y"), "", $dateformatdetails['jsdate']);
        $goodchars = "0123456789" . substr($goodchars, 0, 1);
        // Max length of date : Get the date of 1999-12-30 at 32:59:59 to be sure to have space with non leading 0 format
        // "+1" makes room for a trailing space in date/time values
        $iLength = strlen(date($dateformatdetails['phpdate'], mktime(23, 59, 59, 12, 30, 1999))) + 1;
        // Hide calendar (but show hour/minute) if there's no year, month or day in format
        $hideCalendar = strpos($dateformatdetails['jsdate'], 'Y') === false && strpos($dateformatdetails['jsdate'], 'D') === false && strpos($dateformatdetails['jsdate'], 'M') === false;
        // HTML for date question using datepicker
        $answer = doRender('/survey/questions/date/selector/answer', array('name' => $ia[1], 'iLength' => $iLength, 'mindate' => $mindate, 'maxdate' => $maxdate, 'dateformatdetails' => $dateformatdetails['dateformat'], 'dateformatdetailsjs' => $dateformatdetails['jsdate'], 'goodchars' => "", 'checkconditionFunction' => $checkconditionFunction . '(this.value, this.name, this.type)', 'language' => App()->language, 'hidetip' => trim($aQuestionAttributes['hide_tip']) == 0, 'dateoutput' => $dateoutput, 'qid' => $ia[0], 'hideCalendar' => $hideCalendar), true);
    }
    $inputnames[] = $ia[1];
    return array($answer, $inputnames);
}
 private function _GetVarAttribute($name, $attr, $default, $gseq, $qseq)
 {
     $args = explode(".", $name);
     $varName = $args[0];
     $varName = preg_replace("/^(?:INSERTANS:)?(.*?)\$/", "\$1", $varName);
     if (isset($this->knownVars[$varName])) {
         $var = $this->knownVars[$varName];
     } else {
         if (isset($this->qcode2sgqa[$varName])) {
             $var = $this->knownVars[$this->qcode2sgqa[$varName]];
         } else {
             if (isset($this->tempVars[$varName])) {
                 $var = $this->tempVars[$varName];
             } else {
                 return '{' . $name . '}';
             }
         }
     }
     $sgqa = isset($var['sgqa']) ? $var['sgqa'] : NULL;
     if (is_null($attr)) {
         // then use the requested attribute, if any
         $_attr = 'code';
         if (preg_match("/INSERTANS:/", $args[0])) {
             $_attr = 'shown';
         }
         $attr = count($args) == 2 ? $args[1] : $_attr;
     }
     // Like JavaScript, if an answer is irrelevant, always return ''
     if (preg_match('/^code|NAOK|shown|valueNAOK|value$/', $attr) && isset($var['qid']) && $var['qid'] != '') {
         if (!$this->_GetVarAttribute($varName, 'relevanceStatus', false, $gseq, $qseq)) {
             return '';
         }
     }
     switch ($attr) {
         case 'varName':
             return $name;
             break;
         case 'code':
         case 'NAOK':
             if (isset($var['code'])) {
                 return $var['code'];
                 // for static values like TOKEN
             } else {
                 if (isset($_SESSION[$this->sessid][$sgqa])) {
                     $type = $var['type'];
                     switch ($type) {
                         case 'Q':
                             //MULTIPLE SHORT TEXT
                         //MULTIPLE SHORT TEXT
                         case ';':
                             //ARRAY (Multi Flexi) Text
                         //ARRAY (Multi Flexi) Text
                         case 'S':
                             //SHORT FREE TEXT
                         //SHORT FREE TEXT
                         case 'D':
                             //DATE
                         //DATE
                         case 'T':
                             //LONG FREE TEXT
                         //LONG FREE TEXT
                         case 'U':
                             //HUGE FREE TEXT
                             return htmlspecialchars($_SESSION[$this->sessid][$sgqa], ENT_NOQUOTES);
                             // Minimum sanitizing the string entered by user
                         // Minimum sanitizing the string entered by user
                         case '!':
                             //List - dropdown
                         //List - dropdown
                         case 'L':
                             //LIST drop-down/radio-button list
                         //LIST drop-down/radio-button list
                         case 'O':
                             //LIST WITH COMMENT drop-down/radio-button list + textarea
                         //LIST WITH COMMENT drop-down/radio-button list + textarea
                         case 'M':
                             //Multiple choice checkbox
                         //Multiple choice checkbox
                         case 'P':
                             //Multiple choice with comments checkbox + text
                             if (preg_match('/comment$/', $sgqa) || preg_match('/other$/', $sgqa) || preg_match('/_other$/', $name)) {
                                 return htmlspecialchars($_SESSION[$this->sessid][$sgqa], ENT_NOQUOTES);
                                 // Minimum sanitizing the string entered by user
                             } else {
                                 return $_SESSION[$this->sessid][$sgqa];
                             }
                         default:
                             return $_SESSION[$this->sessid][$sgqa];
                     }
                 } elseif (isset($var['default']) && !is_null($var['default'])) {
                     return $var['default'];
                 }
                 return $default;
             }
             break;
         case 'value':
         case 'valueNAOK':
             $type = $var['type'];
             $code = $this->_GetVarAttribute($name, 'code', $default, $gseq, $qseq);
             switch ($type) {
                 case '!':
                     //List - dropdown
                 //List - dropdown
                 case 'L':
                     //LIST drop-down/radio-button list
                 //LIST drop-down/radio-button list
                 case 'O':
                     //LIST WITH COMMENT drop-down/radio-button list + textarea
                 //LIST WITH COMMENT drop-down/radio-button list + textarea
                 case '1':
                     //Array (Flexible Labels) dual scale  // need scale
                 //Array (Flexible Labels) dual scale  // need scale
                 case 'H':
                     //ARRAY (Flexible) - Column Format
                 //ARRAY (Flexible) - Column Format
                 case 'F':
                     //ARRAY (Flexible) - Row Format
                 //ARRAY (Flexible) - Row Format
                 case 'R':
                     //RANKING STYLE
                     if ($type == 'O' && preg_match('/comment\\.value/', $name)) {
                         $value = $code;
                     } else {
                         if (($type == 'L' || $type == '!') && preg_match('/_other\\.value/', $name)) {
                             $value = $code;
                         } else {
                             $scale_id = $this->_GetVarAttribute($name, 'scale_id', '0', $gseq, $qseq);
                             $which_ans = $scale_id . '~' . $code;
                             $ansArray = $var['ansArray'];
                             if (is_null($ansArray)) {
                                 $value = $default;
                             } else {
                                 if (isset($ansArray[$which_ans])) {
                                     $answerInfo = explode('|', $ansArray[$which_ans]);
                                     $answer = $answerInfo[0];
                                 } else {
                                     $answer = $default;
                                 }
                                 $value = $answer;
                             }
                         }
                     }
                     break;
                 default:
                     $value = $code;
                     break;
             }
             return $value;
             break;
         case 'jsName':
             if ($this->surveyMode == 'survey' || $this->surveyMode == 'group' && $gseq != -1 && isset($var['gseq']) && $gseq == $var['gseq'] || $this->surveyMode == 'question' && $qseq != -1 && isset($var['qseq']) && $qseq == $var['qseq']) {
                 return isset($var['jsName_on']) ? $var['jsName_on'] : isset($var['jsName']) ? $var['jsName'] : $default;
             } else {
                 return isset($var['jsName']) ? $var['jsName'] : $default;
             }
             break;
         case 'sgqa':
         case 'mandatory':
         case 'qid':
         case 'gid':
         case 'grelevance':
         case 'question':
         case 'readWrite':
         case 'relevance':
         case 'rowdivid':
         case 'type':
         case 'qcode':
         case 'gseq':
         case 'qseq':
         case 'ansList':
         case 'scale_id':
             return isset($var[$attr]) ? $var[$attr] : $default;
         case 'shown':
             if (isset($var['shown'])) {
                 return $var['shown'];
                 // for static values like TOKEN
             } else {
                 $type = $var['type'];
                 $code = $this->_GetVarAttribute($name, 'code', $default, $gseq, $qseq);
                 switch ($type) {
                     case '!':
                         //List - dropdown
                     //List - dropdown
                     case 'L':
                         //LIST drop-down/radio-button list
                     //LIST drop-down/radio-button list
                     case 'O':
                         //LIST WITH COMMENT drop-down/radio-button list + textarea
                     //LIST WITH COMMENT drop-down/radio-button list + textarea
                     case '1':
                         //Array (Flexible Labels) dual scale  // need scale
                     //Array (Flexible Labels) dual scale  // need scale
                     case 'H':
                         //ARRAY (Flexible) - Column Format
                     //ARRAY (Flexible) - Column Format
                     case 'F':
                         //ARRAY (Flexible) - Row Format
                     //ARRAY (Flexible) - Row Format
                     case 'R':
                         //RANKING STYLE
                         if ($type == 'O' && preg_match('/comment$/', $name)) {
                             $shown = $code;
                         } else {
                             if (($type == 'L' || $type == '!') && preg_match('/_other$/', $name)) {
                                 $shown = $code;
                             } else {
                                 $scale_id = $this->_GetVarAttribute($name, 'scale_id', '0', $gseq, $qseq);
                                 $which_ans = $scale_id . '~' . $code;
                                 $ansArray = $var['ansArray'];
                                 if (is_null($ansArray)) {
                                     $shown = $code;
                                 } else {
                                     if (isset($ansArray[$which_ans])) {
                                         $answerInfo = explode('|', $ansArray[$which_ans]);
                                         array_shift($answerInfo);
                                         $answer = join('|', $answerInfo);
                                     } else {
                                         $answer = $code;
                                     }
                                     $shown = $answer;
                                 }
                             }
                         }
                         break;
                     case 'A':
                         //ARRAY (5 POINT CHOICE) radio-buttons
                     //ARRAY (5 POINT CHOICE) radio-buttons
                     case 'B':
                         //ARRAY (10 POINT CHOICE) radio-buttons
                     //ARRAY (10 POINT CHOICE) radio-buttons
                     case ':':
                         //ARRAY (Multi Flexi) 1 to 10
                     //ARRAY (Multi Flexi) 1 to 10
                     case '5':
                         //5 POINT CHOICE radio-buttons
                         $shown = $code;
                         break;
                     case 'D':
                         //DATE
                         $LEM =& LimeExpressionManager::singleton();
                         $aAttributes = $LEM->getQuestionAttributesForEM($LEM->sid, $var['qid'], $_SESSION['LEMlang']);
                         $aDateFormatData = getDateFormatDataForQID($aAttributes[$var['qid']], $LEM->surveyOptions);
                         $shown = '';
                         if (strtotime($code)) {
                             $shown = date($aDateFormatData['phpdate'], strtotime($code));
                         }
                         break;
                     case 'N':
                         //NUMERICAL QUESTION TYPE
                     //NUMERICAL QUESTION TYPE
                     case 'K':
                         //MULTIPLE NUMERICAL QUESTION
                     //MULTIPLE NUMERICAL QUESTION
                     case 'Q':
                         //MULTIPLE SHORT TEXT
                     //MULTIPLE SHORT TEXT
                     case ';':
                         //ARRAY (Multi Flexi) Text
                     //ARRAY (Multi Flexi) Text
                     case 'S':
                         //SHORT FREE TEXT
                     //SHORT FREE TEXT
                     case 'T':
                         //LONG FREE TEXT
                     //LONG FREE TEXT
                     case 'U':
                         //HUGE FREE TEXT
                     //HUGE FREE TEXT
                     case '*':
                         //Equation
                     //Equation
                     case 'I':
                         //Language Question
                     //Language Question
                     case '|':
                         //File Upload
                     //File Upload
                     case 'X':
                         //BOILERPLATE QUESTION
                         $shown = $code;
                         break;
                     case 'M':
                         //Multiple choice checkbox
                     //Multiple choice checkbox
                     case 'P':
                         //Multiple choice with comments checkbox + text
                         if ($code == 'Y' && isset($var['question']) && !preg_match('/comment$/', $sgqa)) {
                             $shown = $var['question'];
                         } elseif (preg_match('/comment$/', $sgqa)) {
                             $shown = $code;
                             // This one return sgqa.code
                         } else {
                             $shown = $default;
                         }
                         break;
                     case 'G':
                         //GENDER drop-down list
                     //GENDER drop-down list
                     case 'Y':
                         //YES/NO radio-buttons
                     //YES/NO radio-buttons
                     case 'C':
                         //ARRAY (YES/UNCERTAIN/NO) radio-buttons
                     //ARRAY (YES/UNCERTAIN/NO) radio-buttons
                     case 'E':
                         //ARRAY (Increase/Same/Decrease) radio-buttons
                         $ansArray = $var['ansArray'];
                         if (is_null($ansArray)) {
                             $shown = $default;
                         } else {
                             if (isset($ansArray[$code])) {
                                 $answer = $ansArray[$code];
                             } else {
                                 $answer = $default;
                             }
                             $shown = $answer;
                         }
                         break;
                 }
                 return $shown;
             }
         case 'relevanceStatus':
             $gseq = isset($var['gseq']) ? $var['gseq'] : -1;
             $qid = isset($var['qid']) ? $var['qid'] : -1;
             $rowdivid = isset($var['rowdivid']) && $var['rowdivid'] != '' ? $var['rowdivid'] : -1;
             if ($qid == -1 || $gseq == -1) {
                 return 1;
             }
             if (isset($args[1]) && $args[1] == 'NAOK') {
                 return 1;
             }
             $grel = isset($_SESSION[$this->sessid]['relevanceStatus']['G' . $gseq]) ? $_SESSION[$this->sessid]['relevanceStatus']['G' . $gseq] : 1;
             // true by default
             $qrel = isset($_SESSION[$this->sessid]['relevanceStatus'][$qid]) ? $_SESSION[$this->sessid]['relevanceStatus'][$qid] : 0;
             $sqrel = isset($_SESSION[$this->sessid]['relevanceStatus'][$rowdivid]) ? $_SESSION[$this->sessid]['relevanceStatus'][$rowdivid] : 1;
             // true by default - only want false if a subquestion is irrelevant
             return $grel && $qrel && $sqrel;
         case 'onlynum':
             if (isset($args[1]) && ($args[1] == 'value' || $args[1] == 'valueNAOK')) {
                 return 1;
             }
             return isset($var[$attr]) ? $var[$attr] : $default;
             break;
         default:
             print 'UNDEFINED ATTRIBUTE: ' . $attr . "<br />\n";
             return $default;
     }
     return $default;
     // and throw and error?
 }
Ejemplo n.º 6
0
/**
*
* @param type $iSurveyID The Survey ID
* @param type $sFieldCode Field code of the particular field
* @param type $sValue The stored response value
* @param object $oLanguage Initialized limesurvey_lang object for the resulting response data
* @return string
*/
function getExtendedAnswer($iSurveyID, $sFieldCode, $sValue, $oLanguage)
{
    if (is_null($sValue) || $sValue == '') {
        return '';
    }
    $sLanguage = $oLanguage->langcode;
    //Fieldcode used to determine question, $sValue used to match against answer code
    //Returns NULL if question type does not suit
    if (strpos($sFieldCode, "{$iSurveyID}X") === 0) {
        $fieldmap = createFieldMap($iSurveyID, 'short', false, false, $sLanguage);
        if (isset($fieldmap[$sFieldCode])) {
            $fields = $fieldmap[$sFieldCode];
        } else {
            return false;
        }
        //Find out the question type
        $this_type = $fields['type'];
        switch ($this_type) {
            case 'D':
                if (trim($sValue) != '') {
                    $qidattributes = getQuestionAttributeValues($fields['qid']);
                    $dateformatdetails = getDateFormatDataForQID($qidattributes, $iSurveyID);
                    $sValue = convertDateTimeFormat($sValue, "Y-m-d H:i:s", $dateformatdetails['phpdate']);
                }
                break;
            case "L":
            case "!":
            case "O":
            case "^":
            case "I":
            case "R":
                $result = Answers::model()->getAnswerFromCode($fields['qid'], $sValue, $sLanguage) or die("Couldn't get answer type L - getAnswerCode()");
                //Checked
                foreach ($result as $row) {
                    $this_answer = $row['answer'];
                }
                // while
                if ($sValue == "-oth-") {
                    $this_answer = $oLanguage->gT("Other");
                }
                break;
            case "M":
            case "J":
            case "P":
                switch ($sValue) {
                    case "Y":
                        $this_answer = $oLanguage->gT("Yes");
                        break;
                }
                break;
            case "Y":
                switch ($sValue) {
                    case "Y":
                        $this_answer = $oLanguage->gT("Yes");
                        break;
                    case "N":
                        $this_answer = $oLanguage->gT("No");
                        break;
                    default:
                        $this_answer = $oLanguage->gT("No answer");
                }
                break;
            case "G":
                switch ($sValue) {
                    case "M":
                        $this_answer = $oLanguage->gT("Male");
                        break;
                    case "F":
                        $this_answer = $oLanguage->gT("Female");
                        break;
                    default:
                        $this_answer = $oLanguage->gT("No answer");
                }
                break;
            case "C":
                switch ($sValue) {
                    case "Y":
                        $this_answer = $oLanguage->gT("Yes");
                        break;
                    case "N":
                        $this_answer = $oLanguage->gT("No");
                        break;
                    case "U":
                        $this_answer = $oLanguage->gT("Uncertain");
                        break;
                }
                break;
            case "E":
                switch ($sValue) {
                    case "I":
                        $this_answer = $oLanguage->gT("Increase");
                        break;
                    case "D":
                        $this_answer = $oLanguage->gT("Decrease");
                        break;
                    case "S":
                        $this_answer = $oLanguage->gT("Same");
                        break;
                }
                break;
            case "F":
            case "H":
            case "1":
                $aConditions = array('qid' => $fields['qid'], 'code' => $sValue, 'language' => $sLanguage);
                if (isset($fields['scale_id'])) {
                    $iScaleID = $fields['scale_id'];
                } else {
                    $iScaleID = 0;
                }
                $result = Answers::model()->getAnswerFromCode($fields['qid'], $sValue, $sLanguage, $iScaleID) or die("Couldn't get answer type L - getAnswerCode()");
                //Checked
                foreach ($result as $row) {
                    $this_answer = $row['answer'];
                }
                // while
                $this_answer = $row['answer'];
                if ($sValue == "-oth-") {
                    $this_answer = $oLanguage->gT("Other");
                }
                break;
            case "|":
                //File upload
                if (substr($sFieldCode, -9) == 'filecount') {
                    $this_answer = $oLanguage->gT("File count");
                } else {
                    //Show the filename, size, title and comment -- no link!
                    $files = json_decode($sValue);
                    $sValue = '';
                    if (is_array($files)) {
                        foreach ($files as $file) {
                            $sValue .= $file->name . ' (' . $file->size . 'KB) ' . strip_tags($file->title) . ' - ' . strip_tags($file->comment) . "<br/>";
                        }
                    }
                }
                break;
            default:
        }
        // switch
    }
    switch ($sFieldCode) {
        case 'submitdate':
            if (trim($sValue) != '') {
                $dateformatdetails = getDateFormatDataForQID(array('date_format' => ''), $iSurveyID);
                $sValue = convertDateTimeFormat($sValue, "Y-m-d H:i:s", $dateformatdetails['phpdate'] . ' H:i:s');
            }
            break;
    }
    if (isset($this_answer)) {
        return $this_answer . " [{$sValue}]";
    } else {
        return $sValue;
    }
}
 /**
  * Cleanse the $_POSTed data and update $_SESSION variables accordingly
  */
 static function ProcessCurrentResponses()
 {
     $LEM =& LimeExpressionManager::singleton();
     if (!isset($LEM->currentQset)) {
         return array();
     }
     $updatedValues = array();
     $radixchange = $LEM->surveyOptions['radix'] == ',' ? true : false;
     foreach ($LEM->currentQset as $qinfo) {
         $relevant = false;
         $qid = $qinfo['info']['qid'];
         $gseq = $qinfo['info']['gseq'];
         $relevant = isset($_POST['relevance' . $qid]) ? $_POST['relevance' . $qid] == 1 : false;
         $grelevant = isset($_POST['relevanceG' . $gseq]) ? $_POST['relevanceG' . $gseq] == 1 : false;
         $_SESSION[$LEM->sessid]['relevanceStatus'][$qid] = $relevant;
         $_SESSION[$LEM->sessid]['relevanceStatus']['G' . $gseq] = $grelevant;
         foreach (explode('|', $qinfo['sgqa']) as $sq) {
             $sqrelevant = true;
             if (isset($LEM->subQrelInfo[$qid][$sq]['rowdivid'])) {
                 $rowdivid = $LEM->subQrelInfo[$qid][$sq]['rowdivid'];
                 if ($rowdivid != '' && isset($_POST['relevance' . $rowdivid])) {
                     $sqrelevant = $_POST['relevance' . $rowdivid] == 1;
                     $_SESSION[$LEM->sessid]['relevanceStatus'][$rowdivid] = $sqrelevant;
                 }
             }
             $type = $qinfo['info']['type'];
             if ($relevant && $grelevant && $sqrelevant || !$LEM->surveyOptions['deletenonvalues']) {
                 if ($qinfo['info']['hidden'] && !isset($_POST[$sq])) {
                     $value = isset($_SESSION[$LEM->sessid][$sq]) ? $_SESSION[$LEM->sessid][$sq] : '';
                     // if always hidden, use the default value, if any
                 } else {
                     $value = isset($_POST[$sq]) ? $_POST[$sq] : '';
                 }
                 if ($radixchange && isset($LEM->knownVars[$sq]['onlynum']) && $LEM->knownVars[$sq]['onlynum'] == '1') {
                     // convert from comma back to decimal
                     $value = implode('.', explode(',', $value));
                 }
                 switch ($type) {
                     case 'D':
                         //DATE
                         if (trim($value) == "") {
                             $value = "";
                         } else {
                             $aAttributes = $LEM->getQuestionAttributesForEM($LEM->sid, $qid, $_SESSION['LEMlang']);
                             if (!isset($aAttributes[$qid])) {
                                 $aAttributes[$qid] = array();
                             }
                             $aDateFormatData = getDateFormatDataForQID($aAttributes[$qid], $LEM->surveyOptions);
                             $oDateTimeConverter = new Date_Time_Converter($value, $aDateFormatData['phpdate']);
                             $value = $oDateTimeConverter->convert("Y-m-d H:i");
                         }
                         break;
                     case 'N':
                         //NUMERICAL QUESTION TYPE
                     //NUMERICAL QUESTION TYPE
                     case 'K':
                         //MULTIPLE NUMERICAL QUESTION
                         if (trim($value) == "") {
                             $value = "";
                         } else {
                             $value = sanitize_float($value);
                         }
                         break;
                     case '|':
                         //File Upload
                         if (!preg_match('/_filecount$/', $sq)) {
                             $json = $value;
                             $phparray = json_decode(stripslashes($json));
                             // if the files have not been saved already,
                             // move the files from tmp to the files folder
                             $tmp = $LEM->surveyOptions['tempdir'] . 'upload' . DIRECTORY_SEPARATOR;
                             if (!is_null($phparray) && count($phparray) > 0) {
                                 // Move the (unmoved, temp) files from temp to files directory.
                                 // Check all possible file uploads
                                 for ($i = 0; $i < count($phparray); $i++) {
                                     if (file_exists($tmp . $phparray[$i]->filename)) {
                                         $sDestinationFileName = 'fu_' . randomChars(15);
                                         if (!is_dir($LEM->surveyOptions['target'])) {
                                             mkdir($LEM->surveyOptions['target'], 0777, true);
                                         }
                                         if (!rename($tmp . $phparray[$i]->filename, $LEM->surveyOptions['target'] . $sDestinationFileName)) {
                                             echo "Error moving file to target destination";
                                         }
                                         $phparray[$i]->filename = $sDestinationFileName;
                                     }
                                 }
                                 $value = ls_json_encode($phparray);
                                 // so that EM doesn't try to parse it.
                             }
                         }
                         break;
                 }
                 $_SESSION[$LEM->sessid][$sq] = $value;
                 $_update = array('type' => $type, 'value' => $value);
                 $updatedValues[$sq] = $_update;
                 $LEM->updatedValues[$sq] = $_update;
             } else {
                 // irrelevant, so database will be NULLed separately
                 // Must unset the value, rather than setting to '', so that EM can re-use the default value as needed.
                 unset($_SESSION[$LEM->sessid][$sq]);
                 $_update = array('type' => $type, 'value' => NULL);
                 $updatedValues[$sq] = $_update;
                 $LEM->updatedValues[$sq] = $_update;
             }
         }
     }
     if (isset($_POST['timerquestion'])) {
         $_SESSION[$LEM->sessid][$_POST['timerquestion']] = sanitize_float($_POST[$_POST['timerquestion']]);
     }
     return $updatedValues;
 }
Ejemplo n.º 8
0
            echo $x;
            ?>
'><?php 
            echo $x;
            ?>
</option>
                    <?php 
        }
        ?>
            </select>
            <?php 
        break;
    case "D":
        //DATE
        //                            $qidattributes = getQuestionAttributeValues($deqrow['qid'], $deqrow['type']);
        $dateformatdetails = getDateFormatDataForQID($qidattributes, $thissurvey);
        if (canShowDatePicker($dateformatdetails)) {
            $goodchars = str_replace(array("m", "d", "y", "H", "M"), "", $dateformatdetails['dateformat']);
            $goodchars = "0123456789" . $goodchars[0];
            ?>
                <input type='text' class='popupdate' size='12' name='<?php 
            echo $fieldname;
            ?>
' onkeypress="return goodchars(event,'<?php 
            echo $goodchars;
            ?>
')"/>
                <input type='hidden' name='dateformat<?php 
            echo $fieldname;
            ?>
' id='dateformat<?php 
Ejemplo n.º 9
0
function aCheckInput($surveyid, $move, $backok = null)
{
    global $thisstep, $thissurvey;
    if (!isset($backok) || $backok != "Y") {
        $fieldmap = createFieldMap($surveyid, 'full', false, false, $_SESSION['survey_' . $surveyid]['s_lang']);
        if (isset($_POST['fieldnames'])) {
            $fields = explode("|", $_POST['fieldnames']);
            foreach ($fields as $field) {
                //Get question information
                if (isset($_POST[$field]) && isset($_SESSION['survey_' . $surveyid]['s_lang']) && ($_POST[$field] == "0" || $_POST[$field])) {
                    $fieldinfo = $fieldmap[$field];
                    $pregquery = "SELECT preg\n" . "FROM {{questions}}\n" . "WHERE qid=" . $fieldinfo['qid'] . " " . "AND language='" . $_SESSION['survey_' . $surveyid]['s_lang'] . "'";
                    $pregresult = dbExecuteAssoc($pregquery) or safeDie("ERROR: {$pregquery}<br />");
                    //Checked
                    foreach ($pregresult->readAll() as $pregrow) {
                        $preg = trim($pregrow['preg']);
                    }
                    // while
                    if (isset($preg) && $preg) {
                        if (!@preg_match($preg, $_POST[$field])) {
                            $notvalidated[] = $field;
                            continue;
                        }
                    }
                    // check for other question attributes
                    $qidattributes = getQuestionAttributeValues($fieldinfo['qid'], $fieldinfo['type']);
                    if ($fieldinfo['type'] == 'N') {
                        $neg = true;
                        if (trim($qidattributes['max_num_value_n']) != '' && $qidattributes['max_num_value_n'] >= 0) {
                            $neg = false;
                        }
                        if (trim($qidattributes['num_value_int_only']) == 1 && !preg_match("/^" . ($neg ? "-?" : "") . "[0-9]+\$/", $_POST[$field])) {
                            $notvalidated[] = $field;
                            continue;
                        }
                        if (trim($qidattributes['max_num_value_n']) != '' && $_POST[$field] > $qidattributes['max_num_value_n']) {
                            $notvalidated[] = $field;
                            continue;
                        }
                        if (trim($qidattributes['min_num_value_n']) != '' && $_POST[$field] < $qidattributes['min_num_value_n']) {
                            $notvalidated[] = $field;
                            continue;
                        }
                    } elseif ($fieldinfo['type'] == 'D') {
                        // $_SESSION['survey_'.$surveyid][$fieldinfo['fieldname']] now contains the crappy value parsed by
                        // Date_Time_Converter in save.php. We can leave it there. We just do validation here.
                        $dateformatdetails = getDateFormatDataForQID($qidattributes, $thissurvey);
                        $datetimeobj = DateTime::createFromFormat($dateformatdetails['phpdate'], $_POST[$field]);
                        if (!$datetimeobj) {
                            $notvalidated[] = $field;
                            continue;
                        }
                    }
                }
            }
        }
        //The following section checks for question attribute validation, looking for values in a particular field
        if (isset($_POST['qattribute_answer'])) {
            foreach ($_POST['qattribute_answer'] as $maxvalueanswer) {
                //$maxvalue_answername="maxvalue_answer".$maxvalueanswer;
                if (!empty($_POST['qattribute_answer' . $maxvalueanswer]) && $_POST['display' . $maxvalueanswer] == "on") {
                    $_SESSION['survey_' . $surveyid]['step'] = $thisstep;
                    $notvalidated[] = $maxvalueanswer;
                    return $notvalidated;
                }
            }
        }
        if (isset($notvalidated) && is_array($notvalidated)) {
            if (isset($move) && $move == "moveprev") {
                $_SESSION['survey_' . $surveyid]['step'] = $thisstep;
            }
            if (isset($move) && $move == "movenext") {
                $_SESSION['survey_' . $surveyid]['step'] = $thisstep;
            }
            return $notvalidated;
        }
    }
}
Ejemplo n.º 10
0
function do_date($ia)
{
    global $thissurvey;
    header_includes(Yii::app()->getConfig("generalscripts") . 'date.js', 'js');
    $clang = Yii::app()->lang;
    $aQuestionAttributes = getQuestionAttributeValues($ia[0], $ia[4]);
    $checkconditionFunction = "checkconditions";
    $dateformatdetails = getDateFormatDataForQID($aQuestionAttributes, $thissurvey);
    $numberformatdatat = getRadixPointData($thissurvey['surveyls_numberformat']);
    if (trim($aQuestionAttributes['dropdown_dates']) == 1) {
        if (!empty($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]])) {
            $datetimeobj = getdate(DateTime::createFromFormat("Y-m-d H:i:s", $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]])->getTimeStamp());
            $currentyear = $datetimeobj['year'];
            $currentmonth = $datetimeobj['mon'];
            $currentdate = $datetimeobj['mday'];
            $currenthour = $datetimeobj['hours'];
            $currentminute = $datetimeobj['minutes'];
        } else {
            $currentdate = '';
            $currentmonth = '';
            $currentyear = '';
            $currenthour = '';
            $currentminute = '';
        }
        $dateorder = preg_split('/([-\\.\\/ :])/', $dateformatdetails['phpdate'], -1, PREG_SPLIT_DELIM_CAPTURE);
        $answer = '<p class="question answer-item dropdown-item date-item">';
        foreach ($dateorder as $datepart) {
            switch ($datepart) {
                // Show day select box
                case 'j':
                case 'd':
                    $answer .= '<label for="day' . $ia[1] . '" class="hide">' . $clang->gT('Day') . '</label><select id="day' . $ia[1] . '" name="day' . $ia[1] . '" class="day">
                    <option value="">' . $clang->gT('Day') . "</option>\n";
                    for ($i = 1; $i <= 31; $i++) {
                        if ($i == $currentdate) {
                            $i_date_selected = SELECTED;
                        } else {
                            $i_date_selected = '';
                        }
                        $answer .= '<option value="' . sprintf('%02d', $i) . '"' . $i_date_selected . '>' . sprintf('%02d', $i) . "</option>\n";
                    }
                    $answer .= '</select>';
                    break;
                    // Show month select box
                // Show month select box
                case 'n':
                case 'm':
                    $answer .= '<label for="month' . $ia[1] . '" class="hide">' . $clang->gT('Month') . '</label><select id="month' . $ia[1] . '" name="month' . $ia[1] . '" class="month">
                    <option value="">' . $clang->gT('Month') . "</option>\n";
                    $montharray = array($clang->gT('Jan'), $clang->gT('Feb'), $clang->gT('Mar'), $clang->gT('Apr'), $clang->gT('May'), $clang->gT('Jun'), $clang->gT('Jul'), $clang->gT('Aug'), $clang->gT('Sep'), $clang->gT('Oct'), $clang->gT('Nov'), $clang->gT('Dec'));
                    for ($i = 1; $i <= 12; $i++) {
                        if ($i == $currentmonth) {
                            $i_date_selected = SELECTED;
                        } else {
                            $i_date_selected = '';
                        }
                        $answer .= '<option value="' . sprintf('%02d', $i) . '"' . $i_date_selected . '>' . $montharray[$i - 1] . '</option>';
                    }
                    $answer .= '</select>';
                    break;
                    // Show year select box
                // Show year select box
                case 'Y':
                    $answer .= '<label for="year' . $ia[1] . '" class="hide">' . $clang->gT('Year') . '</label><select id="year' . $ia[1] . '" name="year' . $ia[1] . '" class="year">
                    <option value="">' . $clang->gT('Year') . '</option>';
                    /*
                     *  New question attributes used only if question attribute
                     * "dropdown_dates" is used (see IF(...) above).
                     *
                     * yearmin = Minimum year value for dropdown list, if not set default is 1900
                     * yearmax = Maximum year value for dropdown list, if not set default is 2020
                     */
                    if (trim($aQuestionAttributes['dropdown_dates_year_min']) != '') {
                        $yearmin = $aQuestionAttributes['dropdown_dates_year_min'];
                    } else {
                        $yearmin = 1900;
                    }
                    if (trim($aQuestionAttributes['dropdown_dates_year_max']) != '') {
                        $yearmax = $aQuestionAttributes['dropdown_dates_year_max'];
                    } else {
                        $yearmax = 2020;
                    }
                    if ($yearmin > $yearmax) {
                        $yearmin = 1900;
                        $yearmax = 2020;
                    }
                    if ($aQuestionAttributes['reverse'] == 1) {
                        $tmp = $yearmin;
                        $yearmin = $yearmax;
                        $yearmax = $tmp;
                        $step = 1;
                        $reverse = true;
                    } else {
                        $step = -1;
                        $reverse = false;
                    }
                    for ($i = $yearmax; $reverse ? $i <= $yearmin : $i >= $yearmin; $i += $step) {
                        if ($i == $currentyear) {
                            $i_date_selected = SELECTED;
                        } else {
                            $i_date_selected = '';
                        }
                        $answer .= '<option value="' . $i . '"' . $i_date_selected . '>' . $i . '</option>';
                    }
                    $answer .= '</select>';
                    break;
                case 'H':
                case 'h':
                case 'g':
                case 'G':
                    $answer .= '<label for="hour' . $ia[1] . '" class="hide">' . $clang->gT('Hour') . '</label><select id="hour' . $ia[1] . '" name="hour' . $ia[1] . '" class="hour"><option value="">' . $clang->gT('Hour') . '</option>';
                    for ($i = 0; $i < 24; $i++) {
                        if ($i === $currenthour) {
                            $i_date_selected = SELECTED;
                        } else {
                            $i_date_selected = '';
                        }
                        if ($datepart == 'H') {
                            $answer .= '<option value="' . $i . '"' . $i_date_selected . '>' . sprintf('%02d', $i) . '</option>';
                        } else {
                            $answer .= '<option value="' . $i . '"' . $i_date_selected . '>' . $i . '</option>';
                        }
                    }
                    $answer .= '</select>';
                    break;
                case 'i':
                    $answer .= '<label for="minute' . $ia[1] . '" class="hide">' . $clang->gT('Minute') . '</label><select id="minute' . $ia[1] . '" name="minute' . $ia[1] . '" class="minute">
                    <option value="">' . $clang->gT('Minute') . '</option>';
                    for ($i = 0; $i < 60; $i += $aQuestionAttributes['dropdown_dates_minute_step']) {
                        if ($i === $currentminute) {
                            $i_date_selected = SELECTED;
                        } else {
                            $i_date_selected = '';
                        }
                        if ($datepart == 'i') {
                            $answer .= '<option value="' . $i . '"' . $i_date_selected . '>' . sprintf('%02d', $i) . '</option>';
                        } else {
                            $answer .= '<option value="' . $i . '"' . $i_date_selected . '>' . $i . '</option>';
                        }
                    }
                    $answer .= '</select>';
                    break;
                default:
                    $answer .= $datepart;
            }
        }
        $answer .= '<input class="text" type="text" size="10" name="' . $ia[1] . '" style="display: none" id="answer' . $ia[1] . '" value="' . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]] . '" maxlength="10" alt="' . $clang->gT('Answer') . '" onchange="' . $checkconditionFunction . '(this.value, this.name, this.type)" />
        </p>';
        $answer .= '<input type="hidden" name="qattribute_answer[]" value="' . $ia[1] . '" />
        <input type="hidden" id="qattribute_answer' . $ia[1] . '" name="qattribute_answer' . $ia[1] . '" />
        <input type="hidden" id="dateformat' . $ia[1] . '" value="' . $dateformatdetails['jsdate'] . '"/>';
    } else {
        header_includes(Yii::app()->getConfig("generalscripts") . 'jquery/lime-calendar.js');
        if ($clang->langcode !== 'en') {
            header_includes(Yii::app()->getConfig("generalscripts") . 'jquery/locale/jquery.ui.datepicker-' . $clang->langcode . '.js');
        }
        // Format the date  for output
        if (trim($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]]) != '') {
            $datetimeobj = new Date_Time_Converter($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]], "Y-m-d");
            $dateoutput = $datetimeobj->convert($dateformatdetails['phpdate']);
        } else {
            $dateoutput = '';
        }
        if (trim($aQuestionAttributes['dropdown_dates_year_min']) != '') {
            $minyear = $aQuestionAttributes['dropdown_dates_year_min'];
        } else {
            $minyear = '1980';
        }
        if (trim($aQuestionAttributes['dropdown_dates_year_max']) != '') {
            $maxyear = $aQuestionAttributes['dropdown_dates_year_max'];
        } else {
            $maxyear = '2020';
        }
        $goodchars = str_replace(array("m", "d", "y"), "", $dateformatdetails['jsdate']);
        $goodchars = "0123456789" . $goodchars[0];
        $answer = "<p class='question answer-item text-item date-item'><label for='answer{$ia[1]}' class='hide label'>{$clang->gT('Date picker')}</label>\n        <input class='popupdate' type=\"text\" size=\"10\" name=\"{$ia[1]}\" title='" . sprintf($clang->gT('Format: %s'), $dateformatdetails['dateformat']) . "' id=\"answer{$ia[1]}\" value=\"{$dateoutput}\" maxlength=\"10\" onkeypress=\"return goodchars(event,'" . $goodchars . "')\" onchange=\"{$checkconditionFunction}(this.value, this.name, this.type)\" />\n        <input  type='hidden' name='dateformat{$ia[1]}' id='dateformat{$ia[1]}' value='{$dateformatdetails['jsdate']}'  />\n        <input  type='hidden' name='datelanguage{$ia[1]}' id='datelanguage{$ia[1]}' value='{$clang->langcode}'  />\n        <input  type='hidden' name='dateyearrange{$ia[1]}' id='dateyearrange{$ia[1]}' value='{$minyear}:{$maxyear}'  />\n\n        </p>";
        if (trim($aQuestionAttributes['hide_tip']) == 1) {
            $answer .= "<p class=\"tip\">" . sprintf($clang->gT('Format: %s'), $dateformatdetails['dateformat']) . "</p>";
        }
    }
    $inputnames[] = $ia[1];
    return array($answer, $inputnames);
}