/** * Create a DB user * * @return unknown_type */ public function createNewUser() { // Do nothing if the user to be added is not DB type if (flattenText(Yii::app()->request->getPost('user_type')) != 'DB') { return; } $oEvent = $this->getEvent(); $new_user = flattenText(Yii::app()->request->getPost('new_user'), false, true); $new_email = flattenText(Yii::app()->request->getPost('new_email'), false, true); if (!validateEmailAddress($new_email)) { $oEvent->set('errorCode', self::ERROR_INVALID_EMAIL); $oEvent->set('errorMessageTitle', gT("Failed to add user")); $oEvent->set('errorMessageBody', gT("The email address is not valid.")); return; } $new_full_name = flattenText(Yii::app()->request->getPost('new_full_name'), false, true); $new_pass = createPassword(); $iNewUID = User::model()->insertUser($new_user, $new_pass, $new_full_name, Yii::app()->session['loginID'], $new_email); if (!$iNewUID) { $oEvent->set('errorCode', self::ERROR_ALREADY_EXISTING_USER); $oEvent->set('errorMessageTitle', ''); $oEvent->set('errorMessageBody', gT("Failed to add user")); return; } Permission::model()->setGlobalPermission($iNewUID, 'auth_db'); $oEvent->set('newUserID', $iNewUID); $oEvent->set('newPassword', $new_pass); $oEvent->set('newEmail', $new_email); $oEvent->set('newFullName', $new_full_name); $oEvent->set('errorCode', self::ERROR_NONE); }
function addmessage() { $clang = Yii::app()->lang; // if (!Permission::model()->hasGlobalPermission('Regions', 'create')) { // Yii::app()->setFlashMessage($clang->gT("You do not have sufficient rights to access this page."), 'error'); // $this->getController()->redirect(array("admin/country/index")); // } $email_to = (int) Yii::app()->request->getPost("email_to"); $subject = flattenText(Yii::app()->request->getPost('subject')); $message = flattenText(Yii::app()->request->getPost('message')); $parent = flattenText(Yii::app()->request->getPost('parent')); $chat = flattenText(Yii::app()->request->getPost('chat')); $aData = array(); $aViewUrls = array(); if (empty($email_to)) { $aViewUrls['message'] = array('title' => $clang->gT("Failed to send message"), 'message' => $clang->gT("Message was not supplied or the Message is invalid."), 'class' => 'warningheader'); } elseif (empty($subject)) { $aViewUrls['message'] = array('title' => $clang->gT("Failed to send message"), 'message' => $clang->gT("Subject was not supplied or the Subject is invalid."), 'class' => 'warningheader'); } elseif (empty($message)) { $aViewUrls['message'] = array('title' => $clang->gT("Failed to send message"), 'message' => $clang->gT("Message was not supplied or the Message is invalid."), 'class' => 'warningheader'); } else { $NewMessage = Supoort_center::model()->instAdminMessage($email_to, $subject, $message, $parent, $chat); if ($NewMessage) { Yii::app()->setFlashMessage($clang->gT("message send successfully")); $this->getController()->redirect(array("admin/message/index")); } else { $aViewUrls['mboxwithredirect'][] = $this->_messageBoxWithRedirect($clang->gT("Failed to send message"), $clang->gT("Error in sending message."), 'warningheader'); } } $this->_renderWrappedTemplate('message', $aViewUrls, $aData); }
/** * Strips html tags and replaces new lines * * @param $string * @return $string */ function stripTagsFull($string) { $string = html_entity_decode($string, ENT_QUOTES, "UTF-8"); //combining these into one mb_ereg_replace call ought to speed things up $string = str_replace(array("\r\n", "\r", "\n", '-oth-'), '', $string); //The backslashes must be escaped twice, once for php, and again for the regexp $string = str_replace("'|\\\\'", "'", $string); return flattenText($string); }
function mod() { $clang = Yii::app()->lang; if (!Permission::model()->hasGlobalPermission('panellist', 'update')) { Yii::app()->setFlashMessage($clang->gT("You do not have sufficient rights to access this page."), 'error'); $this->getController()->redirect(array("admin/index")); } $clang = Yii::app()->lang; $action = isset($_POST['action']) ? $_POST['action'] : ''; $aData = array(); $aViewUrls = array(); if (Permission::model()->hasGlobalPermission('', 'create')) { if ($action == "editcategory") { // Project details $category_id = (int) Yii::app()->request->getPost("category_id"); $category_title = flattenText($_POST['category_title'], false, true, 'UTF-8', true); $sort_order = flattenText($_POST['sort_order'], false, true, 'UTF-8', true); $IsActive = flattenText(Yii::app()->request->getPost("IsActive")); $is_Active = 0; if ($IsActive) { $is_Active = 1; } if ($category_title == '') { $aViewUrls['message'] = array('title' => $clang->gT("Failed to add Category"), 'message' => $clang->gT("Category Name is invalid."), 'class' => 'warningheader'); } else { $oUser = category::model()->findByPk($category_id); $oUser->title = $category_title; $oUser->sorder = $sort_order; $oUser->IsActive = $is_Active; $oUser->modified_date = Date('y-m-d h:i:s'); $NewCategory = $oUser->save(); if ($NewCategory) { Yii::app()->setFlashMessage($clang->gT("Profile Category Updated successfully")); $this->getController()->redirect(array("admin/profilecategory/index")); } } } else { if (isset($_POST['category_id'])) { $aData['row'] = 0; $aData['usr_arr'] = array(); // Project detail $category_id = (int) Yii::app()->request->getPost("category_id"); $action = Yii::app()->request->getPost("action"); $sresult = profilecategoryview($category_id); // only use in view_editcompany $aData['category_id'] = $category_id; $aData['mur'] = $sresult; $this->_renderWrappedTemplate('panellist/category', 'editcategory_view', $aData); return; } } } Yii::app()->setFlashMessage(Yii::app()->lang->gT("You do not have sufficient rights to access this page."), 'error'); $this->getController()->redirect(array("admin/profilecategory/index")); }
function insertlabelset() { $postlabel_name = flattenText(Yii::app()->getRequest()->getPost('label_name'), false, true, 'UTF-8', true); $data = array('label_name' => $postlabel_name, 'languages' => sanitize_languagecodeS(implode(' ', Yii::app()->getRequest()->getPost('languageids', array('en'))))); $result = LabelSet::model()->insertRecords($data); if (!$result) { Yii::app()->session['flashmessage'] = gT("Inserting the label set failed."); } else { return $result; } }
public function getAllSets() { $results = LabelSet::model()->findAll(); $output = array(); foreach ($results as $row) { $output[$row->lid] = flattenText($row->getAttribute('label_name')); } header('Content-type: application/json'); echo ls_json_encode($output); }
function mod() { $clang = Yii::app()->lang; $action = isset($_POST['action']) ? $_POST['action'] : ''; $aData = array(); $aViewUrls = array(); if (Permission::model()->hasGlobalPermission('panellist', 'update')) { $query_id = (int) Yii::app()->request->getPost("query_id"); if ($action == "editquery") { if (isquerysent($query_id)) { Yii::app()->setFlashMessage(Yii::app()->lang->gT("You can not update this query. This query has been sent."), 'error'); $this->getController()->redirect(array("admin/pquery/index")); return 1; } // $query_id = (int) Yii::app()->request->getPost("query_id"); $title = flattenText($_POST['query_title'], false, true, 'UTF-8', true); $project_id = (int) Yii::app()->request->getPost("project_id"); $qstring = addslashes($_POST['query_sql']); $zip = trim($_POST['zipcode']); $age = $_POST['toage'] . "," . $_POST['fromage']; $country = (int) Yii::app()->request->getPost("country"); $total_panellists = (int) Yii::app()->request->getPost("total_panellists"); $user_id = Yii::app()->user->id; $created_date = Date('y-m-d h:i:s'); $modified_date = Date('y-m-d h:i:s'); $sql_insert = "update {{query_master}} set\n name ='{$title}'\n ,qstring ='{$qstring}'\n ,project_id= {$project_id}\n ,zip='{$zip}'\n ,age ='{$age}'\n ,country={$country}\n ,total_panellists={$total_panellists}\n ,modified_date ='{$modified_date}'\n where id= {$query_id}"; $rString = Yii::app()->db->createCommand($sql_insert)->query(); $delquery = "Delete from {{query_detail}} where query_id = " . $query_id; $dString = Yii::app()->db->createCommand($delquery)->query(); if (isset($_POST['query_detail'])) { foreach ($_POST['query_detail'] as $question_id => $answer_id) { if (is_array($answer_id)) { foreach ($answer_id as $answer) { $insertQuery = "insert into {{query_detail}} set\n query_id = '" . $query_id . "',\n question_id = '" . $question_id . "',\n answer_id = '" . $answer . "'"; $rString = Yii::app()->db->createCommand($insertQuery)->query(); } } else { $insertQuery = "insert into {{query_detail}} set\n query_id = '" . $query_id . "',\n question_id = '" . $question_id . "',\n answer_id = '" . $answer_id . "'"; $rString = Yii::app()->db->createCommand($insertQuery)->query(); } } } Yii::app()->setFlashMessage($clang->gT("Query Updated successfully")); if ($_POST['pid'] != '') { $pid = $_POST['pid']; $vid = $_POST['vid']; //echo '<script>$.fancybox.close()</script>;'; $this->getController()->redirect(array("admin/project/sa/modifyproject/project_id/{$pid}/action/modifyvendor/vid/{$vid}")); } else { $this->getController()->redirect(array("admin/pquery/index")); } //$this->getController()->redirect(array("admin/pquery/index")); } else { if (isset($_POST['query_id'])) { $aData['row'] = 0; $aData['usr_arr'] = array(); $project_id = isset($_GET['prjid']) ? $_GET['prjid'] : ''; $aData['prjid'] = $project_id; $vid = isset($_GET['vid']) ? $_GET['vid'] : ''; $aData['vid'] = $vid; $query_id = (int) Yii::app()->request->getPost("query_id"); $action = Yii::app()->request->getPost("action"); $sresult = queryview($query_id); $aData['query_id'] = $query_id; $aData['mur'] = $sresult; $this->_renderWrappedTemplate('panellist/query', 'editquery_view', $aData); return; } } } Yii::app()->setFlashMessage(Yii::app()->lang->gT("You do not have sufficient rights to access this page."), 'error'); $this->getController()->redirect(array("admin/pquery/index")); }
/** * Create a LDAP user * * @param string $new_user * @return null|string New user ID */ private function _createNewUser($new_user) { $oEvent = $this->getEvent(); // Get configuration settings: $ldapserver = $this->get('server'); $ldapport = $this->get('ldapport'); $ldapmode = $this->get('ldapmode'); $searchuserattribute = $this->get('searchuserattribute'); $extrauserfilter = $this->get('extrauserfilter'); $usersearchbase = $this->get('usersearchbase'); $binddn = $this->get('binddn'); $bindpwd = $this->get('bindpwd'); $mailattribute = $this->get('mailattribute'); $fullnameattribute = $this->get('fullnameattribute'); // Try to connect $ldapconn = $this->createConnection(); if (!is_resource($ldapconn)) { $oEvent->set('errorCode', self::ERROR_LDAP_CONNECTION); $oEvent->set('errorMessageTitle', ''); $oEvent->set('errorMessageBody', $ldapconn['errorMessage']); return null; } if (empty($ldapmode) || $ldapmode == 'simplebind') { $oEvent->set('errorCode', self::ERROR_LDAP_MODE); $oEvent->set('errorMessageTitle', gT("Failed to add user")); $oEvent->set('errorMessageBody', gT("Simple bind LDAP configuration doesn't allow LDAP user creation")); return null; } // Search email address and full name if (empty($binddn)) { // There is no account defined to do the LDAP search, // let's use anonymous bind instead $ldapbindsearch = @ldap_bind($ldapconn); } else { // An account is defined to do the LDAP search, let's use it $ldapbindsearch = @ldap_bind($ldapconn, $binddn, $bindpwd); } if (!$ldapbindsearch) { $oEvent->set('errorCode', self::ERROR_LDAP_NO_BIND); $oEvent->set('errorMessageTitle', gT('Could not connect to LDAP server.')); $oEvent->set('errorMessageBody', gT(ldap_error($ldapconn))); ldap_close($ldapconn); // all done? close connection return null; } // Now prepare the search fitler if ($extrauserfilter != "") { $usersearchfilter = "(&({$searchuserattribute}={$new_user}){$extrauserfilter})"; } else { $usersearchfilter = "({$searchuserattribute}={$new_user})"; } // Search for the user $dnsearchres = ldap_search($ldapconn, $usersearchbase, $usersearchfilter, array($mailattribute, $fullnameattribute)); $rescount = ldap_count_entries($ldapconn, $dnsearchres); if ($rescount == 1) { $userentry = ldap_get_entries($ldapconn, $dnsearchres); $new_email = flattenText($userentry[0][$mailattribute][0]); $new_full_name = flattenText($userentry[0][strtolower($fullnameattribute)][0]); } else { $oEvent->set('errorCode', self::ERROR_LDAP_NO_SEARCH_RESULT); $oEvent->set('errorMessageTitle', gT('Username not found in LDAP server')); $oEvent->set('errorMessageBody', gT('Verify username and try again')); ldap_close($ldapconn); // all done? close connection return null; } if (!validateEmailAddress($new_email)) { $oEvent->set('errorCode', self::ERROR_INVALID_EMAIL); $oEvent->set('errorMessageTitle', gT("Failed to add user")); $oEvent->set('errorMessageBody', gT("The email address is not valid.")); return null; } $new_pass = createPassword(); // If user is being auto created we set parent ID to 1 (admin user) if (isset(Yii::app()->session['loginID'])) { $parentID = Yii::app()->session['loginID']; } else { $parentID = 1; } $iNewUID = User::model()->insertUser($new_user, $new_pass, $new_full_name, $parentID, $new_email); if (!$iNewUID) { $oEvent->set('errorCode', self::ERROR_ALREADY_EXISTING_USER); $oEvent->set('errorMessageTitle', ''); $oEvent->set('errorMessageBody', gT("Failed to add user")); return null; } Permission::model()->setGlobalPermission($iNewUID, 'auth_ldap'); $oEvent->set('newUserID', $iNewUID); $oEvent->set('newPassword', $new_pass); $oEvent->set('newEmail', $new_email); $oEvent->set('newFullName', $new_full_name); $oEvent->set('errorCode', self::ERROR_NONE); return $iNewUID; }
/** * @param $surveysToInclude the names of all the programs we want to generate reports for * @return array the data we need to generate a report */ private function getReportData($surveysToInclude, $featureYear) { //Array to hold all surveys to Return $surveys = array(); foreach ($surveysToInclude as $surveyID) { /**GENERAL SURVEY DATA**/ //Holds general data about current survey $surveyData = array(); //Get program associated with this survey $programEnrollment = $this->api->newModel($this, 'program_enrollment'); $surveyProgramData = $programEnrollment->find('survey_id=:sid', array(':sid' => $surveyID)); $surveyData['programTitle'] = $surveyProgramData["programName"]; //Get program title ready to pass to query $programTitle = $this->sanitizeForSql($surveyData['programTitle']); //Get program data $program = Yii::app()->db->createCommand("SELECT * FROM {{community_action_programs}}\n WHERE programName = '{$programTitle}'")->query()->read(); $surveyData['programDescription'] = $program["description"]; //Get surveys title $surveyData['title'] = $this->getSurveyTitle($surveyID); //Check for if this survey uses tokens if (!is_null(Yii::app()->db->schema->getTable("{{tokens_{$surveyID}}}"))) { //Get total # of tokens created for this survey $tokensCreated = Yii::app()->db->createCommand("Select COUNT(*) as tokensCreated\n FROM {{tokens_{$surveyID}}}\n WHERE sent NOT LIKE 'N'\n AND YEAR(sent) = {$featureYear}")->query()->read(); $surveyData['tokenCount'] = $tokensCreated["tokensCreated"]; } /**QUESTION GROUP DATA**/ $surveyData['questionGroups'] = array(); //Get all registered question groups and loop getting questions associated with it $registeredQuestionGroups = Yii::app()->db->createCommand("SELECT cg.group_name, cg.description, cg.include_in_report\n FROM {{community_action_report_question_groups}} cg")->query(); foreach ($registeredQuestionGroups->readAll() as $currentQuestionGroup) { //Check if registered question group should be included in report if ($currentQuestionGroup['include_in_report']) { //If question group is supposed to be included continue /**GENERAL Question Group Data**/ $currentQuestionGroupData = array(); $currentQuestionGroupData['questionGroupTitle'] = $currentQuestionGroup['group_name']; $currentQuestionGroupData['description'] = $currentQuestionGroup['description']; $currentQuestionGroupData['questions'] = array(); /** Question Group associated QUESTION and RESPONSES */ //Sanitize question group name before passing to query $currentQuestionGroupTitle = $this->sanitizeForSql($currentQuestionGroup['group_name']); //Get all questions associated with current survey and question group $query = "SELECT\n q.sid, q.gid, q.qid, q.question\n FROM {{questions}} q\n INNER JOIN {{groups}} g ON g.gid = q.gid\n WHERE q.sid = {$surveyID}\n AND g.group_name = '{$currentQuestionGroupTitle}'\n GROUP BY q.qid"; $results = Yii::app()->db->createCommand($query)->query(); // Loop through all questions for current Question Group foreach ($results->readAll() as $questionRow) { //This holds general information about each question $questionData = array(); $questionData['title'] = flattenText($questionRow['question']); $questionData['possibleAnswers'] = array(); //Determine this questions column name in DB $questionDBColumnName = $questionRow['sid'] . 'X' . $questionRow['gid'] . 'X' . $questionRow['qid']; //Figure out if question is optional $optionalAnswerCount = Yii::app()->db->createCommand("SELECT COUNT(*) AS 'count'\n FROM {{survey_{$surveyID}}}\n WHERE `{$questionDBColumnName}` = ''")->query()->read(); if ($optionalAnswerCount['count'] > 0) { $questionData['isOptional'] = 'true'; array_push($questionData['possibleAnswers'], 'No answer'); } else { $questionData['isOptional'] = 'false'; } //Get all years of valid data $yearsOfData = Yii::app()->db->createCommand("SELECT DISTINCT(year(submitdate)) as 'year' FROM {{survey_{$surveyID}}}")->query(); $firstYear = true; //Loop on each question for each valid year foreach ($yearsOfData->readAll() as $year) { //get current year $currentYear = $year['year']; // *** Get all possible answers for current question *** //TODO draw this out of year loop inefficient to do this every time $answersResults = Yii::app()->db->createCommand(" SELECT `code` AS AnswerValue, answer AS AnswerText\n FROM {{answers}}\n WHERE qid = " . $questionRow['qid'])->query(); //Read first result $currentAnswer = $answersResults->read(); // *** Get Survey Responses for this year *** $responsesResults = Yii::app()->db->createCommand("SELECT `" . $questionDBColumnName . "`AS AnswerValue, COUNT(*) AS `Count` FROM {{survey_{$surveyID}}}\n WHERE YEAR(submitdate) = {$currentYear}\n GROUP BY `" . $questionDBColumnName . "`")->query(); //Holds current questions response data by year in a graph-able format $answerCount = array(); //Loop through all returned user results $firstResponse = true; foreach ($responsesResults->readAll() as $responseRow) { // Must have this check for if the question was optional and has no answer result if ($responseRow['AnswerValue'] == "") { array_push($answerCount, array('A0' => (int) $responseRow['Count'])); } else { if ($questionData['isOptional'] == 'true' && $firstResponse) { array_push($answerCount, array('A0' => 0)); } //Fill Data Holes until next answer has value while ($responseRow['AnswerValue'] != $currentAnswer['AnswerValue'] && $currentAnswer) { array_push($answerCount, array($currentAnswer['AnswerValue'] => 0)); if ($firstYear) { array_push($questionData['possibleAnswers'], $currentAnswer['AnswerText']); } $currentAnswer = $answersResults->read(); } //Push valid answer count and value if it exists if ($currentAnswer) { array_push($answerCount, array($currentAnswer['AnswerValue'] => (int) $responseRow['Count'])); if ($firstYear) { array_push($questionData['possibleAnswers'], $currentAnswer['AnswerText']); } } // Move to next answer result $currentAnswer = $answersResults->read(); } $firstResponse = false; } //Fill trailing data holes if ($currentAnswer) { array_push($answerCount, array($currentAnswer['AnswerValue'] => 0)); if ($firstYear) { array_push($questionData['possibleAnswers'], $currentAnswer['AnswerText']); } $currentAnswer = $answersResults->read(); while ($currentAnswer) { array_push($answerCount, array($currentAnswer['AnswerValue'] => 0)); if ($firstYear) { array_push($questionData['possibleAnswers'], $currentAnswer['AnswerText']); } $currentAnswer = $answersResults->read(); } } //Update question and survey data arrays $questionData['answerCount'][$currentYear] = array(); $questionData['answerCount'][$currentYear]['year'] = $currentYear; array_push($questionData['answerCount'][$currentYear], $answerCount); $firstYear = false; } array_push($currentQuestionGroupData['questions'], $questionData); } array_push($surveyData['questionGroups'], $currentQuestionGroupData); } } //Get total survey responses $surveyData['totalResponses'] = 0; //Just look at how many responses there were to the first question $x = !is_null($surveyData['questions'][0]['answerCount'][$featureYear]['0']['0']['A0']) ? 0 : 1; foreach ($surveyData['questions'][0]['answerCount'][$featureYear]['0'] as $question) { $surveyData['totalResponses'] += (int) $question['A' . $x]; $x++; } //Push survey survey data array_push($surveys, $surveyData); } //uncomment lines below for helpful debugging view of data structure // print_r('<pre>'); // print_r($surveys); return $surveys; }
/** * Construction of replacement array, actually doing it with redata * * @param $aQuestionQanda : array from qanda helper * @return aray of replacement for question.psptl **/ public static function getQuestionReplacement($aQuestionQanda) { // Get the default replacement and set empty value by default $aReplacement = array("QID" => "", "SGQ" => "", "AID" => "", "QUESTION_CODE" => "", "QUESTION_NUMBER" => "", "QUESTION" => "", "QUESTION_TEXT" => "", "QUESTIONHELP" => "", "QUESTIONHELPPLAINTEXT" => "", "QUESTION_CLASS" => "", "QUESTION_MAN_CLASS" => "", "QUESTION_INPUT_ERROR_CLASS" => "", "ANSWER" => "", "QUESTION_HELP" => "", "QUESTION_VALID_MESSAGE" => "", "QUESTION_FILE_VALID_MESSAGE" => "", "QUESTION_MAN_MESSAGE" => "", "QUESTION_MANDATORY" => "", "QUESTION_ESSENTIALS" => ""); if (!is_array($aQuestionQanda) || empty($aQuestionQanda[0])) { return $aReplacement; } $iQid = $aQuestionQanda[4]; $lemQuestionInfo = LimeExpressionManager::GetQuestionStatus($iQid); $iSurveyId = Yii::app()->getConfig('surveyID'); // Or : by SGQA of question ? by Question::model($iQid)->sid; $oSurveyId = Survey::model()->findByPk($iSurveyId); $sType = $lemQuestionInfo['info']['type']; // Core value : not replaced $aReplacement['QID'] = $iQid; $aReplacement['GID'] = $aQuestionQanda[6]; // Not sure for aleatory : it's the real gid or the updated gid ? We need original gid or updated gid ? $aReplacement['SGQ'] = $aQuestionQanda[7]; $aReplacement['AID'] = isset($aQuestionQanda[0]['aid']) ? $aQuestionQanda[0]['aid'] : ""; $aReplacement['QUESTION_CODE'] = $aReplacement['QUESTION_NUMBER'] = ""; $sCode = $aQuestionQanda[5]; $iNumber = $aQuestionQanda[0]['number']; switch (Yii::app()->getConfig('showqnumcode')) { case 'both': $aReplacement['QUESTION_CODE'] = $sCode; $aReplacement['QUESTION_NUMBER'] = $iNumber; break; case 'number': $aReplacement['QUESTION_NUMBER'] = $iNumber; break; case 'number': $aReplacement['QUESTION_CODE'] = $sCode; break; case 'choose': default: switch ($oSurveyId->showqnumcode) { case 'B': // Both $aReplacement['QUESTION_CODE'] = $sCode; $aReplacement['QUESTION_NUMBER'] = $iNumber; break; case 'N': $aReplacement['QUESTION_NUMBER'] = $iNumber; break; case 'C': $aReplacement['QUESTION_CODE'] = $sCode; break; case 'X': default: break; } break; } $aReplacement['QUESTION'] = $aQuestionQanda[0]['all']; // Deprecated : only used in old template (very old) // Core value : user text $aReplacement['QUESTION_TEXT'] = $aQuestionQanda[0]['text']; $aReplacement['QUESTIONHELP'] = $lemQuestionInfo['info']['help']; // User help // To be moved in a extra plugin : QUESTIONHELP img adding $sTemplateDir = Template::model()->getTemplatePath($oSurveyId->template); $sTemplateUrl = Template::model()->getTemplateURL($oSurveyId->template); if (flattenText($aReplacement['QUESTIONHELP'], true, true) != '') { $aReplacement['QUESTIONHELP'] = Yii::app()->getController()->renderPartial('/survey/system/questionhelp/questionhelp', array('questionHelp' => $aReplacement['QUESTIONHELP']), true); } // Core value :the classes $aReplacement['QUESTION_CLASS'] = Question::getQuestionClass($sType); //get additional question classes from question attribute $aQuestionAttributes = getQuestionAttributeValues($aQuestionQanda[4]); //add additional classes if (isset($aQuestionAttributes['cssclass'])) { $aReplacement['QUESTION_CLASS'] .= " " . $aQuestionAttributes['cssclass']; } $aMandatoryClass = array(); if ($lemQuestionInfo['info']['mandatory'] == 'Y') { $aMandatoryClass[] = 'mandatory'; } if ($lemQuestionInfo['anyUnanswered'] && $_SESSION['survey_' . $iSurveyId]['maxstep'] != $_SESSION['survey_' . $iSurveyId]['step']) { $aMandatoryClass[] = 'missing'; } $aReplacement['QUESTION_MAN_CLASS'] = !empty($aMandatoryClass) ? " " . implode(" ", $aMandatoryClass) : ""; $aReplacement['QUESTION_INPUT_ERROR_CLASS'] = $aQuestionQanda[0]['input_error_class']; // Core value : LS text : EM and not $aReplacement['ANSWER'] = $aQuestionQanda[1]; $aReplacement['QUESTION_HELP'] = $aQuestionQanda[0]['help']; // Core help only, not EM $aReplacement['QUESTION_VALID_MESSAGE'] = $aQuestionQanda[0]['valid_message']; // $lemQuestionInfo['validTip'] $aReplacement['QUESTION_FILE_VALID_MESSAGE'] = $aQuestionQanda[0]['file_valid_message']; // $lemQuestionInfo['??'] $aReplacement['QUESTION_MAN_MESSAGE'] = $aQuestionQanda[0]['man_message']; $aReplacement['QUESTION_MANDATORY'] = $aQuestionQanda[0]['mandatory']; // For QUESTION_ESSENTIALS $aHtmlOptions = array(); if (!$lemQuestionInfo['relevant'] || $lemQuestionInfo['hidden']) { $aHtmlOptions['style'] = 'display: none;'; } // Launch the event $event = new PluginEvent('beforeQuestionRender'); // Some helper $event->set('surveyId', $iSurveyId); $event->set('type', $sType); $event->set('code', $sCode); $event->set('qid', $iQid); $event->set('gid', $aReplacement['GID']); // User text $event->set('text', $aReplacement['QUESTION_TEXT']); $event->set('questionhelp', $aReplacement['QUESTIONHELP']); // The classes $event->set('class', $aReplacement['QUESTION_CLASS']); $event->set('man_class', $aReplacement['QUESTION_MAN_CLASS']); $event->set('input_error_class', $aReplacement['QUESTION_INPUT_ERROR_CLASS']); // LS core text $event->set('answers', $aReplacement['ANSWER']); $event->set('help', $aReplacement['QUESTION_HELP']); $event->set('man_message', $aReplacement['QUESTION_MAN_MESSAGE']); $event->set('valid_message', $aReplacement['QUESTION_VALID_MESSAGE']); $event->set('file_valid_message', $aReplacement['QUESTION_FILE_VALID_MESSAGE']); // htmlOptions for container $event->set('aHtmlOptions', $aHtmlOptions); App()->getPluginManager()->dispatchEvent($event); // User text $aReplacement['QUESTION_TEXT'] = $event->get('text'); $aReplacement['QUESTIONHELP'] = $event->get('questionhelp'); $aReplacement['QUESTIONHELPPLAINTEXT'] = strip_tags(addslashes($aReplacement['QUESTIONHELP'])); // The classes $aReplacement['QUESTION_CLASS'] = $event->get('class'); $aReplacement['QUESTION_MAN_CLASS'] = $event->get('man_class'); $aReplacement['QUESTION_INPUT_ERROR_CLASS'] = $event->get('input_error_class'); // LS core text $aReplacement['ANSWER'] = $event->get('answers'); $aReplacement['QUESTION_HELP'] = $event->get('help'); $aReplacement['QUESTION_MAN_MESSAGE'] = $event->get('man_message'); $aReplacement['QUESTION_VALID_MESSAGE'] = $event->get('valid_message'); $aReplacement['QUESTION_FILE_VALID_MESSAGE'] = $event->get('file_valid_message'); $aReplacement['QUESTION_MANDATORY'] = $event->get('mandatory', $aReplacement['QUESTION_MANDATORY']); // Always add id for QUESTION_ESSENTIALS $aHtmlOptions['id'] = "question{$iQid}"; $aReplacement['QUESTION_ESSENTIALS'] = CHtml::renderAttributes($aHtmlOptions); return $aReplacement; }
/** * printanswers::view() * View answers at the end of a survey in one place. To export as pdf, set 'usepdfexport' = 1 in lsconfig.php and $printableexport='pdf'. * @param mixed $surveyid * @param bool $printableexport * @return */ function actionView($surveyid, $printableexport = FALSE) { Yii::app()->loadHelper("frontend"); Yii::import('application.libraries.admin.pdf'); $iSurveyID = (int) $surveyid; $sExportType = $printableexport; Yii::app()->loadHelper('database'); if (isset($_SESSION['survey_' . $iSurveyID]['sid'])) { $iSurveyID = $_SESSION['survey_' . $iSurveyID]['sid']; } else { //die('Invalid survey/session'); } // Get the survey inforamtion // Set the language for dispay if (isset($_SESSION['survey_' . $iSurveyID]['s_lang'])) { $sLanguage = $_SESSION['survey_' . $iSurveyID]['s_lang']; } elseif (Survey::model()->findByPk($iSurveyID)) { $sLanguage = Survey::model()->findByPk($iSurveyID)->language; } else { $iSurveyID = 0; $sLanguage = Yii::app()->getConfig("defaultlang"); } $clang = SetSurveyLanguage($iSurveyID, $sLanguage); $aSurveyInfo = getSurveyInfo($iSurveyID, $sLanguage); //SET THE TEMPLATE DIRECTORY if (!isset($aSurveyInfo['templatedir']) || !$aSurveyInfo['templatedir']) { $aSurveyInfo['templatedir'] = Yii::app()->getConfig('defaulttemplate'); } $sTemplate = validateTemplateDir($aSurveyInfo['templatedir']); //Survey is not finished or don't exist if (!isset($_SESSION['survey_' . $iSurveyID]['finished']) || !isset($_SESSION['survey_' . $iSurveyID]['srid'])) { sendCacheHeaders(); doHeader(); echo templatereplace(file_get_contents(getTemplatePath($sTemplate) . '/startpage.pstpl'), array()); echo "<center><br />\n" . "\t<font color='RED'><strong>" . $clang->gT("Error") . "</strong></font><br />\n" . "\t" . $clang->gT("We are sorry but your session has expired.") . "<br />" . $clang->gT("Either you have been inactive for too long, you have cookies disabled for your browser, or there were problems with your connection.") . "<br />\n" . "\t" . sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), Yii::app()->getConfig("siteadminname"), Yii::app()->getConfig("siteadminemail")) . "\n" . "</center><br />\n"; echo templatereplace(file_get_contents(getTemplatePath($sTemplate) . '/endpage.pstpl'), array()); doFooter(); exit; } //Fin session time out $sSRID = $_SESSION['survey_' . $iSurveyID]['srid']; //I want to see the answers with this id //Ensure script is not run directly, avoid path disclosure //if (!isset($rootdir) || isset($_REQUEST['$rootdir'])) {die( "browse - Cannot run this script directly");} if ($aSurveyInfo['printanswers'] == 'N') { die; //Die quietly if print answers is not permitted } //CHECK IF SURVEY IS ACTIVATED AND EXISTS $sSurveyName = $aSurveyInfo['surveyls_title']; $sAnonymized = $aSurveyInfo['anonymized']; //OK. IF WE GOT THIS FAR, THEN THE SURVEY EXISTS AND IT IS ACTIVE, SO LETS GET TO WORK. //SHOW HEADER $sOutput = CHtml::form(array("printanswers/view/surveyid/{$iSurveyID}/printableexport/pdf"), 'post') . "<center><input type='submit' value='" . $clang->gT("PDF export") . "'id=\"exportbutton\"/><input type='hidden' name='printableexport' /></center></form>"; if ($sExportType == 'pdf') { //require (Yii::app()->getConfig('rootdir').'/application/config/tcpdf.php'); Yii::import('application.libraries.admin.pdf', true); Yii::import('application.helpers.pdfHelper'); $aPdfLanguageSettings = pdfHelper::getPdfLanguageSettings($clang->langcode); $oPDF = new pdf(); $oPDF->SetTitle($clang->gT("Survey name (ID)", 'unescaped') . ": {$sSurveyName} ({$iSurveyID})"); $oPDF->SetSubject($sSurveyName); $oPDF->SetDisplayMode('fullpage', 'two'); $oPDF->setLanguageArray($aPdfLanguageSettings['lg']); $oPDF->setHeaderFont(array($aPdfLanguageSettings['pdffont'], '', PDF_FONT_SIZE_MAIN)); $oPDF->setFooterFont(array($aPdfLanguageSettings['pdffont'], '', PDF_FONT_SIZE_DATA)); $oPDF->SetFont($aPdfLanguageSettings['pdffont'], '', $aPdfLanguageSettings['pdffontsize']); $oPDF->AddPage(); $oPDF->titleintopdf($clang->gT("Survey name (ID)", 'unescaped') . ": {$sSurveyName} ({$iSurveyID})"); } $sOutput .= "\t<div class='printouttitle'><strong>" . $clang->gT("Survey name (ID):") . "</strong> {$sSurveyName} ({$iSurveyID})</div><p> \n"; LimeExpressionManager::StartProcessingPage(true); // means that all variables are on the same page // Since all data are loaded, and don't need JavaScript, pretend all from Group 1 LimeExpressionManager::StartProcessingGroup(1, $aSurveyInfo['anonymized'] != "N", $iSurveyID); $printanswershonorsconditions = Yii::app()->getConfig('printanswershonorsconditions'); $aFullResponseTable = getFullResponseTable($iSurveyID, $sSRID, $sLanguage, $printanswershonorsconditions); //Get the fieldmap @TODO: do we need to filter out some fields? if ($aSurveyInfo['datestamp'] != "Y" || $sAnonymized == 'Y') { unset($aFullResponseTable['submitdate']); } else { unset($aFullResponseTable['id']); } unset($aFullResponseTable['token']); unset($aFullResponseTable['lastpage']); unset($aFullResponseTable['startlanguage']); unset($aFullResponseTable['datestamp']); unset($aFullResponseTable['startdate']); $sOutput .= "<table class='printouttable' >\n"; foreach ($aFullResponseTable as $sFieldname => $fname) { if (substr($sFieldname, 0, 4) == 'gid_') { $sOutput .= "\t<tr class='printanswersgroup'><td colspan='2'>{$fname[0]}</td></tr>\n"; } elseif (substr($sFieldname, 0, 4) == 'qid_') { $sOutput .= "\t<tr class='printanswersquestionhead'><td colspan='2'>{$fname[0]}</td></tr>\n"; } elseif ($sFieldname == 'submitdate') { if ($sAnonymized != 'Y') { $sOutput .= "\t<tr class='printanswersquestion'><td>{$fname[0]} {$fname[1]} {$sFieldname}</td><td class='printanswersanswertext'>{$fname[2]}</td></tr>"; } } else { $sOutput .= "\t<tr class='printanswersquestion'><td>{$fname[0]} {$fname[1]}</td><td class='printanswersanswertext'>" . flattenText($fname[2]) . "</td></tr>"; } } $sOutput .= "</table>\n"; $sData['thissurvey'] = $aSurveyInfo; $sOutput = templatereplace($sOutput, array(), $sData, '', $aSurveyInfo['anonymized'] == "Y", NULL, array(), true); // Do a static replacement if ($sExportType == 'pdf') { $oPDF->writeHTML($sOutput); header("Pragma: public"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); $sExportFileName = sanitize_filename($sSurveyName); $oPDF->Output($sExportFileName . "-" . $iSurveyID . ".pdf", "D"); } else { ob_start(function ($buffer, $phase) { App()->getClientScript()->render($buffer); App()->getClientScript()->reset(); return $buffer; }); ob_implicit_flush(false); sendCacheHeaders(); doHeader(); echo templatereplace(file_get_contents(getTemplatePath($sTemplate) . '/startpage.pstpl'), array(), $sData); echo templatereplace(file_get_contents(getTemplatePath($sTemplate) . '/printanswers.pstpl'), array('ANSWERTABLE' => $sOutput), $sData); echo templatereplace(file_get_contents(getTemplatePath($sTemplate) . '/endpage.pstpl'), array(), $sData); echo "</body></html>"; ob_flush(); } LimeExpressionManager::FinishProcessingGroup(); LimeExpressionManager::FinishProcessingPage(); }
private function _showSpeaker($hinttext) { global $max; $clang = Yii::app()->lang; $imageurl = Yii::app()->getConfig("adminimageurl"); if (!isset($max)) { $max = 20; } $htmlhinttext = str_replace("'", ''', $hinttext); //the string is already HTML except for single quotes so we just replace these only $jshinttext = javascriptEscape($hinttext, true, true); if (strlen(html_entity_decode($hinttext, ENT_QUOTES, 'UTF-8')) > $max + 3) { $shortstring = flattenText($hinttext, true); $shortstring = htmlspecialchars(mb_strcut(html_entity_decode($shortstring, ENT_QUOTES, 'UTF-8'), 0, $max, 'UTF-8')); //output with hoover effect $reshtml = "<span style='cursor: hand' alt='" . $htmlhinttext . "' title='" . $htmlhinttext . "' " . " onclick=\"alert('" . $clang->gT("Question", "js") . ": {$jshinttext}')\" />" . " \"{$shortstring}...\" </span>" . "<img style='cursor: hand' src='{$imageurl}/speaker.png' align='bottom' alt='{$htmlhinttext}' title='{$htmlhinttext}' " . " onclick=\"alert('" . $clang->gT("Question", "js") . ": {$jshinttext}')\" />"; } else { $shortstring = flattenText($hinttext, true); $reshtml = "<span title='" . $shortstring . "'> \"{$shortstring}\"</span>"; } return $reshtml; }
<?php $clang->eT("To reorder questions/questiongroups just drag the question/group with your mouse to the desired position.");?><br /> <?php $clang->eT("After you are done please click the bottom 'Save' button to save your changes.");?> </p> <div class='movableList'> <ol class="organizer group-list" data-level='group'> <?php foreach ($aGroupsAndQuestions as $aGroupAndQuestions) {?> <li id='list_g<?php echo $aGroupAndQuestions['gid'];?>' class='group-item' data-level='group'><div class='ui-widget-header'> <?php echo flattenText($aGroupAndQuestions['group_name'],true);?></div> <?php if (isset ($aGroupAndQuestions['questions'])) {?> <ol class='question-list' data-level='question'> <?php foreach($aGroupAndQuestions['questions'] as $aQuestion) {?> <li id='list_q<?php echo $aQuestion['qid'];?>' class='question-item' data-level='question'><div><b><a href='<?php echo Yii::app()->getController()->createUrl('admin/questions/sa/editquestion/surveyid/'.$surveyid.'/gid/'.$aQuestion['gid'].'/qid/'.$aQuestion['qid']);?>'><?php echo $aQuestion['title'];?></a></b>: <?php echo flattenText($aQuestion['question'],true);?></div></li> <?php }?> </ol> <?php }?> </li> <?php }?> </ol> </div> <?php echo CHtml::form(array("admin/survey/sa/organize/surveyid/{$surveyid}"), 'post', array('id'=>'frmOrganize')); ?> <p> <input type='hidden' id='orgdata' name='orgdata' value='' /> <button id='btnSave'><?php echo $clang->eT('Save'); ?></button> </p> </form>
/** * * Add answer to PDF * * @param $sQuestion - Question field text array * @param $sResponse - Answer field text array * @param $bReplaceExpressions - Try to replace LimeSurvey Expressions. This is false when exporting answers PDF from admin GUI * because we can not interpret expressions so just purify. * TODO: Find a universal valid method to interpret expressions * @param $bAllowBreakPage - Allow break cell in two pages * @return unknown_type */ function addAnswer($sQuestion, $sResponse, $bReplaceExpressions = true, $bAllowBreakPage = false) { $oPurifier = new CHtmlPurifier(); $sQuestionHTML = str_replace('-oth-', '', $sQuestion); // Copied from Writer::stripTagsFull. Really necessary? $sQuestionHTML = html_entity_decode(stripJavaScript($oPurifier->purify($sQuestionHTML)), ENT_COMPAT); if ($bReplaceExpressions) { $sData['thissurvey'] = $this->_aSurveyInfo; $sQuestionHTML = templatereplace($sQuestionHTML, array(), $sData, '', $this->_aSurveyInfo['anonymized'] == "Y", NULL, array(), true); } $sResponse = flattenText($sResponse, false, true, 'UTF-8', false); $startPage = $this->getPage(); $this->startTransaction(); $this->SetFontSize($this->_ibaseAnswerFontSize); $this->WriteHTMLCell(0, $this->_iCellHeight, $this->getX(), $this->getY(), $sQuestionHTML, 1, 1, true, true, 'L'); $this->MultiCell(0, $this->_iCellHeight, $sResponse, 1, 'L', 0, 1, '', '', true); $this->ln(2); if ($this->getPage() != $startPage && !$bAllowBreakPage) { $this->rollbackTransaction(true); $this->AddPage(); $this->addAnswer($sQuestion, $sResponse, $bReplaceExpressions, true); // "Last param = true" prevents an endless loop if a cell is longer than a page } else { $this->commitTransaction(); } }
--> <div class="side-body"> <h3><?php eT("Data entry"); ?> </h3> <div class="row"> <div class="col-lg-12 content-right"> <!-- Survey name and description --> <div class="jumbotron "> <h2><?php echo stripJavaScript($thissurvey['name']); ?> </h2> <p><?php echo flattenText($thissurvey['description'], true); ?> </p> </div> <?php echo CHtml::form(array("admin/dataentry/sa/insert"), 'post', array('name' => 'addsurvey', 'id' => 'addsurvey', 'enctype' => 'multipart/form-data')); ?> <table class='data-entry-tbl table'> <tr class='data-entry-separator'> <td colspan='3'></td> </tr> <?php if (count(Survey::model()->findByPk($surveyid)->additionalLanguages) > 0) { ?>
<?php templatereplace(flattenText($surveyinfo['surveyls_welcometext'])); echo LimeExpressionManager::GetLastPrettyPrintExpression(); ?> </td> </tr> <tr> <td> <strong><?php $clang->eT("End message:"); ?> </strong> </td> <td> <?php templatereplace(flattenText($surveyinfo['surveyls_endtext'])); echo LimeExpressionManager::GetLastPrettyPrintExpression(); ?> </td> </tr> <tr> <td> <strong><?php $clang->eT("Administrator:"); ?> </strong> </td> <td> <?php echo "{$surveyinfo['admin']} ({$surveyinfo['adminemail']})"; ?>
/** * Constructor */ public function run($surveyid = 0, $subaction = null) { $surveyid = sanitize_int($surveyid); //TODO: Convert question types to views $clang = $this->getController()->lang; $imageurl = Yii::app()->getConfig("imageurl"); $aData = array('clang' => $clang, 'imageurl' => $imageurl); $aData['sql'] = ''; /* * We need this later: * 1 - Array Dual Scale * 5 - 5 Point Choice * A - Array (5 Point Choice) * B - Array (10 Point Choice) * C - Array (Yes/No/Uncertain) * D - Date * E - Array (Increase, Same, Decrease) * F - Array (Flexible Labels) * G - Gender * H - Array (Flexible Labels) by Column * I - Language Switch * K - Multiple Numerical Input * L - List (Radio) * M - Multiple choice * N - Numerical Input * O - List With Comment * P - Multiple choice with comments * Q - Multiple Short Text * R - Ranking * S - Short Free Text * T - Long Free Text * U - Huge Free Text * X - Boilerplate Question * Y - Yes/No * ! - List (Dropdown) * : - Array (Flexible Labels) multiple drop down * ; - Array (Flexible Labels) multiple texts * | - File Upload Debugging help: echo '<script language="javascript" type="text/javascript">alert("HI");</script>'; */ //split up results to extend statistics -> NOT WORKING YET! DO NOT ENABLE THIS! $showcombinedresults = 0; /* * this variable is used in the function shortencode() which cuts off a question/answer title * after $maxchars and shows the rest as tooltip */ $maxchars = 50; //we collect all the output within this variable $statisticsoutput = ''; //output for chosing questions to cross query $cr_statisticsoutput = ''; // This gets all the 'to be shown questions' from the POST and puts these into an array $summary = returnGlobal('summary'); $statlang = returnGlobal('statlang'); //if $summary isn't an array we create one if (isset($summary) && !is_array($summary)) { $summary = explode("+", $summary); } //no survey ID? -> come and get one if (!isset($surveyid)) { $surveyid = returnGlobal('sid'); } //still no survey ID -> error $aData['surveyid'] = $surveyid; // Set language for questions and answers to base language of this survey $language = Survey::model()->findByPk($surveyid)->language; $aData['language'] = $language; //Call the javascript file App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('adminscripts') . 'statistics.js'); App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('adminscripts') . 'json-js/json2.min.js'); $aData['display']['menu_bars']['browse'] = $clang->gT("Quick statistics"); //Select public language file $row = Survey::model()->find('sid = :sid', array(':sid' => $surveyid)); /* * check if there is a datestamp available for this survey * yes -> $datestamp="Y" * no -> $datestamp="N" */ $datestamp = $row->datestamp; // 1: Get list of questions from survey /* * We want to have the following data * a) "questions" -> all table namens, e.g. * qid * sid * gid * type * title * question * preg * help * other * mandatory * lid * lid1 * question_order * language * * b) "groups" -> group_name + group_order * */ //store all the data in $rows $rows = Question::model()->getQuestionList($surveyid, $language); //SORT IN NATURAL ORDER! usort($rows, 'groupOrderThenQuestionOrder'); //put the question information into the filter array $filters = array(); foreach ($rows as $row) { //store some column names in $filters array $filters[] = array($row['qid'], $row['gid'], $row['type'], $row['title'], $row['group_name'], flattenText($row['question'])); } $aData['filters'] = $filters; //var_dump($filters); // SHOW ID FIELD $grapherror = false; $error = ''; if (!function_exists("gd_info")) { $grapherror = true; $error .= '<br />' . $clang->gT('You do not have the GD Library installed. Showing charts requires the GD library to function properly.'); $error .= '<br />' . $clang->gT('visit http://us2.php.net/manual/en/ref.image.php for more information') . '<br />'; } elseif (!function_exists("imageftbbox")) { $grapherror = true; $error .= '<br />' . $clang->gT('You do not have the Freetype Library installed. Showing charts requires the Freetype library to function properly.'); $error .= '<br />' . $clang->gT('visit http://us2.php.net/manual/en/ref.image.php for more information') . '<br />'; } if ($grapherror) { unset($_POST['usegraph']); } //pre-selection of filter forms if (incompleteAnsFilterState() == "complete") { $selecthide = "selected='selected'"; $selectshow = ""; $selectinc = ""; } elseif (incompleteAnsFilterState() == "incomplete") { $selecthide = ""; $selectshow = ""; $selectinc = "selected='selected'"; } else { $selecthide = ""; $selectshow = "selected='selected'"; $selectinc = ""; } $aData['selecthide'] = $selecthide; $aData['selectshow'] = $selectshow; $aData['selectinc'] = $selectinc; $aData['error'] = $error; $survlangs = Survey::model()->findByPk($surveyid)->additionalLanguages; $survlangs[] = Survey::model()->findByPk($surveyid)->language; $aData['survlangs'] = $survlangs; $aData['datestamp'] = $datestamp; //if the survey contains timestamps you can filter by timestamp, too //Output selector //second row below options -> filter settings headline $filterchoice_state = returnGlobal('filterchoice_state'); $aData['filterchoice_state'] = $filterchoice_state; /* * let's go through the filter array which contains * ['qid'], ['gid'], ['type'], ['title'], ['group_name'], ['question'], ['lid'], ['lid1']); */ $currentgroup = ''; $counter = 0; foreach ($filters as $key1 => $flt) { //is there a previous question type set? /* * remember: $flt is structured like this * ['qid'], ['gid'], ['type'], ['title'], ['group_name'], ['question'], ['lid'], ['lid1']); */ //SGQ identifier //full question title /* * Check question type: This question types will be used (all others are separated in the if clause) * 5 - 5 Point Choice G - Gender I - Language Switch L - List (Radio) M - Multiple choice N - Numerical Input | - File Upload O - List With Comment P - Multiple choice with comments Y - Yes/No ! - List (Dropdown) ) */ ///////////////////////////////////////////////////////////////////////////////////////////////// //This section presents the filter list, in various different ways depending on the question type ///////////////////////////////////////////////////////////////////////////////////////////////// //let's switch through the question type for each question switch ($flt[2]) { case "K": // Multiple Numerical //get answers $result = Question::model()->getQuestionsForStatistics('title as code, question as answer', "parent_qid={$flt['0']} AND language = '{$language}'", 'question_order'); $aData['result'][$key1]['key1'] = $result; break; case "Q": // Multiple Short Text //get subqestions $result = Question::model()->getQuestionsForStatistics('title as code, question as answer', "parent_qid={$flt['0']} AND language = '{$language}'", 'question_order'); $aData['result'][$key1] = $result; break; //----------------------- ARRAYS -------------------------- //----------------------- ARRAYS -------------------------- case "A": // ARRAY OF 5 POINT CHOICE QUESTIONS //get answers $result = Question::model()->getQuestionsForStatistics('title, question', "parent_qid={$flt['0']} AND language = '{$language}'", 'question_order'); $aData['result'][$key1] = $result; break; //just like above only a different loop //just like above only a different loop case "B": // ARRAY OF 10 POINT CHOICE QUESTIONS $result = Question::model()->getQuestionsForStatistics('title, question', "parent_qid={$flt['0']} AND language = '{$language}'", 'question_order'); $aData['result'][$key1] = $result; break; case "C": // ARRAY OF YES\No\$clang->gT("Uncertain") QUESTIONS //get answers $result = Question::model()->getQuestionsForStatistics('title, question', "parent_qid={$flt['0']} AND language = '{$language}'", 'question_order'); $aData['result'][$key1] = $result; break; //similiar to the above one //similiar to the above one case "E": // ARRAY OF Increase/Same/Decrease QUESTIONS $result = Question::model()->getQuestionsForStatistics('title, question', "parent_qid={$flt['0']} AND language = '{$language}'", 'question_order'); $aData['result'][$key1] = $result; break; case ";": //ARRAY (Multi Flex) (Text) $result = Question::model()->getQuestionsForStatistics('title, question', "parent_qid={$flt['0']} AND language = '{$language}' AND scale_id = 0", 'question_order'); $aData['result'][$key1] = $result; foreach ($result as $key => $row) { $fresult = Question::model()->getQuestionsForStatistics('title, question', "parent_qid={$flt['0']} AND language = '{$language}' AND scale_id = 1", 'question_order'); $aData['fresults'][$key1][$key] = $fresult; } break; case ":": //ARRAY (Multi Flex) (Numbers) $result = Question::model()->getQuestionsForStatistics('title, question', "parent_qid={$flt['0']} AND language = '{$language}' AND scale_id = 0", 'question_order'); $aData['result'][$key1] = $result; foreach ($result as $row) { $fresult = Question::model()->getQuestionsForStatistics('*', "parent_qid={$flt['0']} AND language = '{$language}' AND scale_id = 1", 'question_order, title'); $aData['fresults'][$key1] = $fresult; } break; /* * For question type "F" and "H" you can use labels. * The only difference is that the labels are applied to column heading * or rows respectively */ /* * For question type "F" and "H" you can use labels. * The only difference is that the labels are applied to column heading * or rows respectively */ case "F": // FlEXIBLE ARRAY // FlEXIBLE ARRAY case "H": // ARRAY (By Column) //Get answers. We always use the answer code because the label might be too long elsewise $result = Question::model()->getQuestionsForStatistics('title, question', "parent_qid={$flt['0']} AND language = '{$language}'", 'question_order'); $aData['result'][$key1] = $result; //check all the answers foreach ($result as $row) { $fresult = Answer::model()->getQuestionsForStatistics('*', "qid={$flt['0']} AND language = '{$language}'", 'sortorder, code'); $aData['fresults'][$key1] = $fresult; } //$statisticsoutput .= "\t\t\t\t<td>\n"; $counter = 0; break; case "R": //RANKING //get some answers $result = Answer::model()->getQuestionsForStatistics('code, answer', "qid={$flt['0']} AND language = '{$language}'", 'sortorder, answer'); $aData['result'][$key1] = $result; break; case "1": // MULTI SCALE //get answers $result = Question::model()->getQuestionsForStatistics('title, question', "parent_qid={$flt['0']} AND language = '{$language}'", 'question_order'); $aData['result'][$key1] = $result; //loop through answers foreach ($result as $key => $row) { //check if there is a dualscale_headerA/B $dshresult = QuestionAttribute::model()->getQuestionsForStatistics('value', "qid={$flt['0']} AND attribute = 'dualscale_headerA'", ''); $aData['dshresults'][$key1][$key] = $dshresult; $fresult = Answer::model()->getQuestionsForStatistics('*', "qid={$flt['0']} AND language = '{$language}' AND scale_id = 0", 'sortorder, code'); $aData['fresults'][$key1][$key] = $fresult; $dshresult2 = QuestionAttribute::model()->getQuestionsForStatistics('value', "qid={$flt['0']} AND attribute = 'dualscale_headerB'", ''); $aData['dshresults2'][$key1][$key] = $dshresult2; } break; case "P": //P - Multiple choice with comments //P - Multiple choice with comments case "M": //M - Multiple choice //get answers $result = Question::model()->getQuestionsForStatistics('title, question', "parent_qid = {$flt['0']} AND language = '{$language}'", 'question_order'); $aData['result'][$key1] = $result; break; /* * This question types use the default settings: * L - List (Radio) O - List With Comment P - Multiple choice with comments ! - List (Dropdown) */ /* * This question types use the default settings: * L - List (Radio) O - List With Comment P - Multiple choice with comments ! - List (Dropdown) */ default: //get answers $result = Answer::model()->getQuestionsForStatistics('code, answer', "qid={$flt['0']} AND language = '{$language}'", 'sortorder, answer'); $aData['result'][$key1] = $result; break; } //end switch -> check question types and create filter forms $currentgroup = $flt[1]; $counter++; //temporary save the type of the previous question //used to adjust linebreaks $previousquestiontype = $flt[2]; } // ----------------------------------- END FILTER FORM --------------------------------------- Yii::app()->loadHelper('admin/statistics'); $showtextinline = isset($_POST['showtextinline']) ? 1 : 0; $aData['showtextinline'] = $showtextinline; //Show Summary results if (isset($summary) && $summary) { $usegraph = isset($_POST['usegraph']) ? 1 : 0; $aData['usegraph'] = $usegraph; $outputType = $_POST['outputtype']; $helper = new statistics_helper(); switch ($outputType) { case 'html': $statisticsoutput .= $helper->generate_statistics($surveyid, $summary, $summary, $usegraph, $outputType, 'DD', $statlang); break; case 'pdf': $helper->generate_statistics($surveyid, $summary, $summary, $usegraph, $outputType, 'I', $statlang); exit; break; case 'xls': $helper->generate_statistics($surveyid, $summary, $summary, $usegraph, $outputType, 'DD', $statlang); exit; break; default: break; } } //end if -> show summary results $aData['sStatisticsLanguage'] = $statlang; $aData['output'] = $statisticsoutput; $aData['summary'] = $summary; $this->_renderWrappedTemplate('export', 'statistics_view', $aData); }
?> <li> <?php echo flattenText($oSurvey->defaultlanguage->surveyls_title); ?> </li> <?php } else { ?> <li> <a href="<?php echo App()->createUrl('/admin/survey/sa/view/surveyid/' . $oSurvey->sid); ?> "> <?php echo flattenText($oSurvey->defaultlanguage->surveyls_title); ?> </a> </li> <li class="active"> <?php echo $active; ?> </li> <?php } ?> </ol> </div> <?php }
function getUrlParamsJSON($iSurveyID) { $iSurveyID = (int) $iSurveyID; $sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language; $sQuery = "select '' as act, up.*,q.title, sq.title as sqtitle, q.question, sq.question as sqquestion from {{survey_url_parameters}} up\n left join {{questions}} q on q.qid=up.targetqid\n left join {{questions}} sq on sq.qid=up.targetsqid\n where up.sid={$iSurveyID} and (q.language='{$sBaseLanguage}' or q.language is null) and (sq.language='{$sBaseLanguage}' or sq.language is null)"; $oResult = Yii::app()->db->createCommand($sQuery)->queryAll(); $i = 0; $aData = new stdClass(); foreach ($oResult as $oRow) { $aData->rows[$i]['id'] = $oRow['id']; if (!is_null($oRow['question'])) { $oRow['title'] .= ': ' . ellipsize(flattenText($oRow['question'], false, true), 43, 0.7); } else { $oRow['title'] = gT('(No target question)'); } if ($oRow['sqquestion'] != '') { $oRow['title'] .= ' - ' . ellipsize(flattenText($oRow['sqquestion'], false, true), 30, 0.75); } unset($oRow['sqquestion']); unset($oRow['sqtitle']); unset($oRow['question']); $aData->rows[$i]['cell'] = array_values($oRow); $i++; } $aData->page = 1; $aData->records = count($oResult); $aData->total = 1; echo ls_json_encode($aData); }
<div class='menubar'> <div class='menubar-title ui-widget-header'> <strong><?php echo $title; ?> </strong>: (<?php echo flattenText($thissurvey['surveyls_title']); ?> ) </div> <div class='menubar-main'> <div class='menubar-left'> <a href='<?php echo $this->createUrl("admin/survey/sa/view/surveyid/{$surveyid}"); ?> '> <img src='<?php echo $sImageURL; ?> home.png' title='' alt='<?php eT("Return to survey administration"); ?> ' /></a> <img src='<?php echo $sImageURL; ?> blank.gif' alt='' width='11' /> <img src='<?php echo $sImageURL; ?> separator.gif' class='separator' alt='' />
/** * getQuestions() queries the database for an list of all questions matching the current survey and group id * * @return This string is returned containing <option></option> formatted list of questions in the current survey and group */ function getQuestions($surveyid, $gid, $selectedqid) { $s_lang = Survey::model()->findByPk($surveyid)->language; $qrows = Question::model()->findAllByAttributes(array('sid' => $surveyid, 'gid' => $gid, 'language' => $s_lang, 'parent_qid' => 0), array('order' => 'question_order')); if (!isset($sQuestionselecter)) { $sQuestionselecter = ""; } foreach ($qrows as $qrow) { $qrow = $qrow->attributes; $qrow['title'] = strip_tags($qrow['title']); $link = Yii::app()->getController()->createUrl("/admin/survey/sa/view/surveyid/" . $surveyid . "/gid/" . $gid . "/qid/" . $qrow['qid']); $sQuestionselecter .= "<option value='{$link}'"; if ($selectedqid == $qrow['qid']) { $sQuestionselecter .= " selected='selected'"; $qexists = true; } $sQuestionselecter .= ">{$qrow['title']}:"; $sQuestionselecter .= " "; $question = flattenText($qrow['question']); if (strlen($question) < 35) { $sQuestionselecter .= $question; } else { $sQuestionselecter .= htmlspecialchars(mb_strcut(html_entity_decode($question, ENT_QUOTES, 'UTF-8'), 0, 35, 'UTF-8')) . "..."; } $sQuestionselecter .= "</option>\n"; } if (!isset($qexists)) { $sQuestionselecter = "<option selected='selected'>" . gT("Please choose...") . "</option>\n" . $sQuestionselecter; } else { $link = Yii::app()->getController()->createUrl("/admin/survey/sa/view/surveyid/" . $surveyid . "/gid/" . $gid); $sQuestionselecter = "<option value='{$link}'>" . gT("None") . "</option>\n" . $sQuestionselecter; } return $sQuestionselecter; }
function actionAction($surveyid, $language = null) { $sLanguage = $language; ob_start(function ($buffer, $phase) { App()->getClientScript()->render($buffer); App()->getClientScript()->reset(); return $buffer; }); ob_implicit_flush(false); $iSurveyID = (int) $surveyid; //$postlang = returnglobal('lang'); Yii::import('application.libraries.admin.progressbar', true); Yii::app()->loadHelper("admin/statistics"); Yii::app()->loadHelper('database'); Yii::app()->loadHelper('surveytranslator'); App()->getClientScript()->registerPackage('jqueryui'); App()->getClientScript()->registerPackage('jquery-touch-punch'); App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts') . "survey_runtime.js"); $data = array(); if (!isset($iSurveyID)) { $iSurveyID = returnGlobal('sid'); } else { $iSurveyID = (int) $iSurveyID; } if (!$iSurveyID) { //This next line ensures that the $iSurveyID value is never anything but a number. safeDie('You have to provide a valid survey ID.'); } if ($iSurveyID) { $actresult = Survey::model()->findAll('sid = :sid AND active = :active', array(':sid' => $iSurveyID, ':active' => 'Y')); //Checked if (count($actresult) == 0) { safeDie('You have to provide a valid survey ID.'); } else { $surveyinfo = getSurveyInfo($iSurveyID); // CHANGE JSW_NZ - let's get the survey title for display $thisSurveyTitle = $surveyinfo["name"]; // CHANGE JSW_NZ - let's get css from individual template.css - so define path $thisSurveyCssPath = getTemplateURL($surveyinfo["template"]); if ($surveyinfo['publicstatistics'] != 'Y') { safeDie('The public statistics for this survey are deactivated.'); } //check if graphs should be shown for this survey if ($surveyinfo['publicgraphs'] == 'Y') { $publicgraphs = 1; } else { $publicgraphs = 0; } } } //we collect all the output within this variable $statisticsoutput = ''; //for creating graphs we need some more scripts which are included here //True -> include //False -> forget about charts if (isset($publicgraphs) && $publicgraphs == 1) { require_once APPPATH . 'third_party/pchart/pchart/pChart.class'; require_once APPPATH . 'third_party/pchart/pchart/pData.class'; require_once APPPATH . 'third_party/pchart/pchart/pCache.class'; $MyCache = new pCache(Yii::app()->getConfig("tempdir") . DIRECTORY_SEPARATOR); //$currentuser is created as prefix for pchart files if (isset($_SERVER['REDIRECT_REMOTE_USER'])) { $currentuser = $_SERVER['REDIRECT_REMOTE_USER']; } else { if (session_id()) { $currentuser = substr(session_id(), 0, 15); } else { $currentuser = "******"; } } } // Set language for questions and labels to base language of this survey if ($sLanguage == null || !in_array($sLanguage, Survey::model()->findByPk($iSurveyID)->getAllLanguages())) { $sLanguage = Survey::model()->findByPk($iSurveyID)->language; } else { $sLanguage = sanitize_languagecode($sLanguage); } //set survey language for translations SetSurveyLanguage($iSurveyID, $sLanguage); //Create header sendCacheHeaders(); $condition = false; $sitename = Yii::app()->getConfig("sitename"); $data['surveylanguage'] = $sLanguage; $data['sitename'] = $sitename; $data['condition'] = $condition; $data['thisSurveyCssPath'] = $thisSurveyCssPath; /* * only show questions where question attribute "public_statistics" is set to "1" */ $query = "SELECT q.* , group_name, group_order FROM {{questions}} q, {{groups}} g, {{question_attributes}} qa\n WHERE g.gid = q.gid AND g.language = :lang1 AND q.language = :lang2 AND q.sid = :surveyid AND q.qid = qa.qid AND q.parent_qid = 0 AND qa.attribute = 'public_statistics'"; $databasetype = Yii::app()->db->getDriverName(); if ($databasetype == 'mssql' || $databasetype == "sqlsrv" || $databasetype == "dblib") { $query .= " AND CAST(CAST(qa.value as varchar) as int)='1'\n"; } else { $query .= " AND qa.value='1'\n"; } //execute query $result = Yii::app()->db->createCommand($query)->bindParam(":lang1", $sLanguage, PDO::PARAM_STR)->bindParam(":lang2", $sLanguage, PDO::PARAM_STR)->bindParam(":surveyid", $iSurveyID, PDO::PARAM_INT)->queryAll(); //store all the data in $rows $rows = $result; //SORT IN NATURAL ORDER! usort($rows, 'groupOrderThenQuestionOrder'); //put the question information into the filter array foreach ($rows as $row) { //store some column names in $filters array $filters[] = array($row['qid'], $row['gid'], $row['type'], $row['title'], $row['group_name'], flattenText($row['question'])); } //number of records for this survey $totalrecords = 0; //count number of answers $query = "SELECT count(*) FROM {{survey_" . intval($iSurveyID) . "}}"; //if incompleted answers should be filtert submitdate has to be not null //this setting is taken from config-defaults.php if (Yii::app()->getConfig("filterout_incomplete_answers") == true) { $query .= " WHERE {{survey_" . intval($iSurveyID) . "}}.submitdate is not null"; } $result = Yii::app()->db->createCommand($query)->queryAll(); //$totalrecords = total number of answers foreach ($result as $row) { $totalrecords = reset($row); } //this is the array which we need later... $summary = array(); //...while this is the array from copy/paste which we don't want to replace because this is a nasty source of error $allfields = array(); //---------- CREATE SGQA OF ALL QUESTIONS WHICH USE "PUBLIC_STATISTICS" ---------- /* * let's go through the filter array which contains * ['qid'], ['gid'], ['type'], ['title'], ['group_name'], ['question']; */ $currentgroup = ''; // use to check if there are any question with public statistics if (isset($filters)) { foreach ($filters as $flt) { //SGQ identifier $myfield = "{$iSurveyID}X{$flt[1]}X{$flt[0]}"; //let's switch through the question type for each question switch ($flt[2]) { case "K": // Multiple Numerical // Multiple Numerical case "Q": // Multiple Short Text //get answers $query = "SELECT title as code, question as answer FROM {{questions}} WHERE parent_qid=:flt_0 AND language = :lang ORDER BY question_order"; $result = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->queryAll(); //go through all the (multiple) answers foreach ($result as $row) { $myfield2 = $flt[2] . $myfield . reset($row); $allfields[] = $myfield2; } break; case "A": // ARRAY OF 5 POINT CHOICE QUESTIONS // ARRAY OF 5 POINT CHOICE QUESTIONS case "B": // ARRAY OF 10 POINT CHOICE QUESTIONS // ARRAY OF 10 POINT CHOICE QUESTIONS case "C": // ARRAY OF YES\No\gT("Uncertain") QUESTIONS // ARRAY OF YES\No\gT("Uncertain") QUESTIONS case "E": // ARRAY OF Increase/Same/Decrease QUESTIONS // ARRAY OF Increase/Same/Decrease QUESTIONS case "F": // FlEXIBLE ARRAY // FlEXIBLE ARRAY case "H": // ARRAY (By Column) //get answers $query = "SELECT title as code, question as answer FROM {{questions}} WHERE parent_qid=:flt_0 AND language = :lang ORDER BY question_order"; $result = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->queryAll(); //go through all the (multiple) answers foreach ($result as $row) { $myfield2 = $myfield . reset($row); $allfields[] = $myfield2; } break; // all "free text" types (T, U, S) get the same prefix ("T") // all "free text" types (T, U, S) get the same prefix ("T") case "T": // Long free text // Long free text case "U": // Huge free text // Huge free text case "S": // Short free text $myfield = "T{$myfield}"; $allfields[] = $myfield; break; case ";": //ARRAY (Multi Flex) (Text) //ARRAY (Multi Flex) (Text) case ":": //ARRAY (Multi Flex) (Numbers) $query = "SELECT title, question FROM {{questions}} WHERE parent_qid=:flt_0 AND language=:lang AND scale_id = 0 ORDER BY question_order"; $result = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->queryAll(); foreach ($result as $row) { $fquery = "SELECT * FROM {{questions}} WHERE parent_qid = :flt_0 AND language = :lang AND scale_id = 1 ORDER BY question_order, title"; $fresult = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->queryAll(); foreach ($fresult as $frow) { $myfield2 = $myfield . reset($row) . "_" . $frow['title']; $allfields[] = $myfield2; } } break; case "R": //RANKING //get some answers $query = "SELECT code, answer FROM {{answers}} WHERE qid = :flt_0 AND language = :lang ORDER BY sortorder, answer"; $result = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->queryAll(); //get number of answers $count = count($result); //loop through all answers. if there are 3 items to rate there will be 3 statistics for ($i = 1; $i <= $count; $i++) { $myfield2 = "R" . $myfield . $i . "-" . strlen($i); $allfields[] = $myfield2; } break; //Boilerplate questions are only used to put some text between other questions -> no analysis needed //Boilerplate questions are only used to put some text between other questions -> no analysis needed case "X": //This is a boilerplate question and it has no business in this script break; case "1": // MULTI SCALE //get answers $query = "SELECT title, question FROM {{questions}} WHERE parent_qid = :flt_0 AND language = :lang ORDER BY question_order"; $result = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->queryAll(); //loop through answers foreach ($result as $row) { //----------------- LABEL 1 --------------------- $myfield2 = $myfield . $row['title'] . "#0"; $allfields[] = $myfield2; //----------------- LABEL 2 --------------------- $myfield2 = $myfield . $row['title'] . "#1"; $allfields[] = $myfield2; } //end WHILE -> loop through all answers break; case "P": //P - Multiple choice with comments //P - Multiple choice with comments case "M": //M - Multiple choice //M - Multiple choice case "N": //N - Numerical input //N - Numerical input case "D": //D - Date $myfield2 = $flt[2] . $myfield; $allfields[] = $myfield2; break; default: //Default settings $allfields[] = $myfield; break; } //end switch -> check question types and create filter forms } //end foreach -> loop through all questions with "public_statistics" enabled } // end if -> for removing the error message in case there are no filters $summary = $allfields; // Get the survey inforamtion $thissurvey = getSurveyInfo($surveyid, $sLanguage); //SET THE TEMPLATE DIRECTORY $data['sTemplatePath'] = $surveyinfo['template']; // surveyinfo=getSurveyInfo and if survey don't exist : stop before. //---------- CREATE STATISTICS ---------- $redata = compact(array_keys(get_defined_vars())); doHeader(); echo templatereplace(file_get_contents(getTemplatePath($data['sTemplatePath']) . DIRECTORY_SEPARATOR . "startpage.pstpl"), array(), $redata); //some progress bar stuff // Create progress bar which is shown while creating the results $prb = new ProgressBar(); $prb->pedding = 2; // Bar Pedding $prb->brd_color = "#404040 #dfdfdf #dfdfdf #404040"; // Bar Border Color $prb->setFrame(); // set ProgressBar Frame $prb->frame['left'] = 50; // Frame position from left $prb->frame['top'] = 80; // Frame position from top $prb->addLabel('text', 'txt1', gT("Please wait ...")); // add Text as Label 'txt1' and value 'Please wait' $prb->addLabel('percent', 'pct1'); // add Percent as Label 'pct1' $prb->addButton('btn1', gT('Go back'), '?action=statistics&sid=' . $iSurveyID); // add Button as Label 'btn1' and action '?restart=1' //progress bar starts with 35% $process_status = 35; $prb->show(); // show the ProgressBar // 1: Get list of questions with answers chosen //"Getting Questions and Answer ..." is shown above the bar $prb->setLabelValue('txt1', gT('Getting questions and answers ...')); $prb->moveStep(5); // creates array of post variable names for (reset($_POST); $key = key($_POST); next($_POST)) { $postvars[] = $key; } $data['thisSurveyTitle'] = $thisSurveyTitle; $data['totalrecords'] = $totalrecords; $data['summary'] = $summary; //show some main data at the beginnung // CHANGE JSW_NZ - let's allow html formatted questions to show //push progress bar from 35 to 40 $process_status = 40; //Show Summary results if (isset($summary) && $summary) { //"Generating Summaries ..." is shown above the progress bar $prb->setLabelValue('txt1', gT('Generating summaries ...')); $prb->moveStep($process_status); //let's run through the survey // Fixed bug 3053 with array_unique $runthrough = array_unique($summary); //loop through all selected questions foreach ($runthrough as $rt) { //update progress bar if ($process_status < 100) { $process_status++; } $prb->moveStep($process_status); } // end foreach -> loop through all questions $helper = new statistics_helper(); $statisticsoutput .= $helper->generate_statistics($iSurveyID, $summary, $summary, $publicgraphs, 'html', null, $sLanguage, false); } //end if -> show summary results $data['statisticsoutput'] = $statisticsoutput; //done! set progress bar to 100% if (isset($prb)) { $prb->setLabelValue('txt1', gT('Completed')); $prb->moveStep(100); $prb->hide(); } $redata = compact(array_keys(get_defined_vars())); $data['redata'] = $redata; Yii::app()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts') . 'statistics_user.js'); $this->renderPartial('/statistics_user_view', $data); //output footer echo getFooter(); //Delete all Session Data Yii::app()->session['finished'] = true; }
function do_array_dual($ia) { global $thissurvey; $aLastMoveResult = LimeExpressionManager::GetLastMoveResult(); $aMandatoryViolationSubQ = $aLastMoveResult['mandViolation'] && $ia[6] == 'Y' ? explode("|", $aLastMoveResult['unansweredSQs']) : array(); $repeatheadings = Yii::app()->getConfig("repeatheadings"); $minrepeatheadings = Yii::app()->getConfig("minrepeatheadings"); $extraclass = ""; $answertypeclass = ""; // Maybe not $caption = ""; // Just leave empty, are replaced after $inputnames = array(); $labelans1 = array(); $labelans = array(); $aQuestionAttributes = getQuestionAttributeValues($ia[0]); if ($aQuestionAttributes['random_order'] == 1) { $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia['0']} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' and scale_id=0 ORDER BY " . dbRandom(); } else { $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia['0']} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' and scale_id=0 ORDER BY question_order"; } $ansresult = dbExecuteAssoc($ansquery); //Checked $aSubQuestions = $ansresult->readAll(); $anscount = count($aSubQuestions); $lquery = "SELECT * FROM {{answers}} WHERE scale_id=0 AND qid={$ia[0]} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' ORDER BY sortorder, code"; $lresult = dbExecuteAssoc($lquery); //Checked $aAnswersScale0 = $lresult->readAll(); $lquery1 = "SELECT * FROM {{answers}} WHERE scale_id=1 AND qid={$ia[0]} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' ORDER BY sortorder, code"; $lresult1 = dbExecuteAssoc($lquery1); //Checked $aAnswersScale1 = $lresult1->readAll(); if ($aQuestionAttributes['use_dropdown'] == 1) { $useDropdownLayout = true; $extraclass .= " dropdown-list"; $answertypeclass .= " dropdown"; $doDualScaleFunction = "doDualScaleDropDown"; // javascript funtion to lauch at end of answers $caption = gT("An array with sub-question on each line, with 2 answers to provide on each line. You have to select the answer."); } else { $useDropdownLayout = false; $extraclass .= " radio-list"; $answertypeclass .= " radio"; $doDualScaleFunction = "doDualScaleRadio"; $caption = gT("An array with sub-question on each line, with 2 answers to provide on each line. The answers are contained in the table header. "); } if (ctype_digit(trim($aQuestionAttributes['repeat_headings'])) && trim($aQuestionAttributes['repeat_headings'] != "")) { $repeatheadings = intval($aQuestionAttributes['repeat_headings']); $minrepeatheadings = 0; } if (trim($aQuestionAttributes['dualscale_headerA'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]) != '') { $leftheader = $aQuestionAttributes['dualscale_headerA'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]; } else { $leftheader = ''; } if (trim($aQuestionAttributes['dualscale_headerB'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]) != '') { $rightheader = $aQuestionAttributes['dualscale_headerB'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]; } else { $rightheader = ''; } if (trim($aQuestionAttributes['answer_width']) != '') { $answerwidth = $aQuestionAttributes['answer_width']; } else { $answerwidth = 20; } // Find if we have rigth and center text // TODO move "|" to attribute $sQuery = "SELECT count(question) FROM {{questions}} WHERE parent_qid=" . $ia[0] . " and scale_id=0 AND question like '%|%'"; $rigthCount = Yii::app()->db->createCommand($sQuery)->queryScalar(); $rightexists = $rigthCount > 0; // $right_exists: flag to find out if there are any right hand answer parts. leaving right column but don't force with $sQuery = "SELECT count(question) FROM {{questions}} WHERE parent_qid=" . $ia[0] . " and scale_id=0 AND question like '%|%|%'"; $centerCount = Yii::app()->db->createCommand($sQuery)->queryScalar(); $centerexists = $centerCount > 0; // $center_exists: flag to find out if there are any center hand answer parts. leaving center column but don't force with // Label and code for input foreach ($aAnswersScale0 as $lrow) { $labels0[] = array('code' => $lrow['code'], 'title' => $lrow['answer']); } foreach ($aAnswersScale1 as $lrow) { $labels1[] = array('code' => $lrow['code'], 'title' => $lrow['answer']); } if (count($aAnswersScale0) > 0 && $anscount) { $answer = ""; $fn = 1; // Used by repeat_heading if ($useDropdownLayout === false) { $columnswidth = 100 - $answerwidth; foreach ($aAnswersScale0 as $lrow) { $labelans0[] = $lrow['answer']; $labelcode0[] = $lrow['code']; } foreach ($aAnswersScale1 as $lrow) { $labelans1[] = $lrow['answer']; $labelcode1[] = $lrow['code']; } $numrows = count($labelans0) + count($labelans1); // Add needed row and fill some boolean: shownoanswer, rightexists, centerexists $shownoanswer = $ia[6] != "Y" && SHOW_NO_ANSWER == 1; if ($shownoanswer) { $numrows++; $caption .= gT("The last cell are for no answer. "); } if ($rightexists) { $numrows++; } if ($centerexists) { $numrows++; } $cellwidth = $columnswidth / $numrows; //$cellwidth=sprintf("%02d", $cellwidth); // No reason to do this, except to leave place for separator ? But then table can not be the same in all browser // Header row and colgroups $mycolumns = "\t<col class=\"col-answers\" width=\"{$answerwidth}%\" />\n"; $answer_head_line = "\t<th class=\"header_answer_text\"> </th>\n\n"; $mycolumns .= "\t<colgroup class=\"col-responses group-1\">\n"; $odd_even = ''; foreach ($labelans0 as $ld) { $answer_head_line .= "\t<th>" . $ld . "</th>\n"; $odd_even = alternation($odd_even); $mycolumns .= "<col class=\"{$odd_even}\" width=\"{$cellwidth}%\" />\n"; } $mycolumns .= "\t</colgroup>\n"; if (count($labelans1) > 0) { $separatorwidth = $centerexists ? "width=\"{$cellwidth}%\" " : ""; $mycolumns .= "\t<col class=\"separator\" {$separatorwidth}/>\n"; $mycolumns .= "\t<colgroup class=\"col-responses group-2\">\n"; $answer_head_line .= "\n\t<td class=\"header_separator\"> </td>\n\n"; // Separator : and No answer for accessibility for first colgroup foreach ($labelans1 as $ld) { $answer_head_line .= "\t<th>" . $ld . "</th>\n"; $odd_even = alternation($odd_even); $mycolumns .= "<col class=\"{$odd_even}\" width=\"{$cellwidth}%\" />\n"; } $mycolumns .= "\t</colgroup>\n"; } if ($shownoanswer || $rightexists) { $rigthwidth = $rightexists ? "width=\"{$cellwidth}%\" " : ""; $mycolumns .= "\t<col class=\"separator rigth_separator\" {$rigthwidth}/>\n"; $answer_head_line .= "\n\t<td class=\"header_separator rigth_separator\"> </td>\n"; } if ($shownoanswer) { $mycolumns .= "\t<col class=\"col-no-answer\" width=\"{$cellwidth}%\" />\n"; $answer_head_line .= "\n\t<th class=\"header_no_answer\">" . gT('No answer') . "</th>\n"; } $answer_head2 = "\n<tr class=\"array1 header_row dontread\">\n" . $answer_head_line . "</tr>\n"; // build first row of header if needed if ($leftheader != '' || $rightheader != '') { $answer_head1 = "<tr class=\"array1 groups header_row\">\n" . "\t<th class=\"header_answer_text\"> </th>\n" . "\t<th colspan=\"" . count($labelans0) . "\" class=\"dsheader\">{$leftheader}</th>\n"; if (count($labelans1) > 0) { $answer_head1 .= "\t<td class=\"header_separator\"> </td>\n" . "\t<th colspan=\"" . count($labelans1) . "\" class=\"dsheader\">{$rightheader}</th>\n"; } if ($shownoanswer || $rightexists) { $rigthclass = $rightexists ? " header_answer_text_right" : ""; $answer_head1 .= "\t<td class=\"header_separator {$rigthclass}\"> </td>\n"; if ($shownoanswer) { $answer_head1 .= "\t<th class=\"header_no_answer\"> </th>\n"; } } $answer_head1 .= "</tr>\n"; } else { $answer_head1 = ""; } $answer .= "\n<table class=\"question subquestions-list questions-list\" summary=\"{$caption}\">\n" . $mycolumns . "\n\t<thead>\n" . $answer_head1 . $answer_head2 . "\n\t</thead>\n" . "<tbody>\n"; // And no each line of body $trbc = ''; foreach ($aSubQuestions as $ansrow) { // Build repeat headings if needed if (isset($repeatheadings) && $repeatheadings > 0 && $fn - 1 > 0 && ($fn - 1) % $repeatheadings == 0) { if ($anscount - $fn + 1 >= $minrepeatheadings) { $answer .= "</tbody>\n<tbody>"; // Close actual body and open another one //$answer .= $answer_head1; $answer .= "\n<tr class=\"repeat headings\">\n" . $answer_head_line . "</tr>\n"; } } $trbc = alternation($trbc, 'row'); $answertext = $ansrow['question']; // rigth and center answertext: not explode for ? Why not if (strpos($answertext, '|')) { $answertextrigth = substr($answertext, strpos($answertext, '|') + 1); $answertext = substr($answertext, 0, strpos($answertext, '|')); } else { $answertextrigth = ""; } if ($centerexists) { $answertextcenter = substr($answertextrigth, 0, strpos($answertextrigth, '|')); $answertextrigth = substr($answertextrigth, strpos($answertextrigth, '|') + 1); } else { $answertextcenter = ""; } $myfname = $ia[1] . $ansrow['title']; $myfname0 = $ia[1] . $ansrow['title'] . '#0'; $myfid0 = $ia[1] . $ansrow['title'] . '_0'; $myfname1 = $ia[1] . $ansrow['title'] . '#1'; // new multi-scale-answer $myfid1 = $ia[1] . $ansrow['title'] . '_1'; /* Check the Sub Q mandatory violation */ if ($ia[6] == 'Y' && (in_array($myfname0, $aMandatoryViolationSubQ) || in_array($myfname1, $aMandatoryViolationSubQ))) { $answertext = "<span class='errormandatory'>{$answertext}</span>"; } // Get array_filter stuff list($htmltbody2, $hiddenfield) = return_array_filter_strings($ia, $aQuestionAttributes, $thissurvey, $ansrow, $myfname, $trbc, $myfname, "tr", "{$trbc} answers-list radio-list"); $answer .= $htmltbody2; array_push($inputnames, $myfname0); $answer .= "\t<th class=\"answertext\">\n" . $hiddenfield . "{$answertext}\n"; // Hidden answers used by EM: sure can be added in javascript $answer .= "<input type=\"hidden\" disabled=\"disabled\" name=\"java{$myfid0}\" id=\"java{$myfid0}\" value=\""; if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname0])) { $answer .= $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname0]; } $answer .= "\" />\n"; if (count($labelans1) > 0) { $answer .= "<input type=\"hidden\" disabled=\"disabled\" name=\"java{$myfid1}\" id=\"java{$myfid1}\" value=\""; if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1])) { $answer .= $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1]; } $answer .= "\" />\n"; } $answer .= "\t</th>\n"; $hiddenanswers = ''; $thiskey = 0; foreach ($labelcode0 as $ld) { $answer .= "\t<td class=\"answer_cell_1_00{$ld} answer-item {$answertypeclass}-item\">\n" . "\t<input class=\"radio\" type=\"radio\" name=\"{$myfname0}\" value=\"{$ld}\" id=\"answer{$myfid0}-{$ld}\" "; if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname0]) && $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname0] == $ld) { $answer .= CHECKED; } $answer .= " />\n" . "<label class=\"hide read\" for=\"answer{$myfid0}-{$ld}\">{$labelans0[$thiskey]}</label>\n" . "\n\t</td>\n"; $thiskey++; } if (count($labelans1) > 0) { $answer .= "\t<td class=\"dual_scale_separator information-item\">"; if ($shownoanswer) { $answer .= "\t<input class='radio jshide read' type='radio' name='{$myfname0}' value='' id='answer{$myfid0}-' "; if (!isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname0]) || $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname0] == "") { $answer .= CHECKED; } $answer .= " />\n"; } $answer .= "<label for='answer{$myfid0}-' class= \"hide read\">" . gT("No answer") . "</label>"; $answer .= "\t{$answertextcenter}</td>\n"; // separator array_push($inputnames, $myfname1); $thiskey = 0; foreach ($labelcode1 as $ld) { $answer .= "\t<td class=\"answer_cell_2_00{$ld} answer-item radio-item\">\n" . "\t<input class=\"radio\" type=\"radio\" name=\"{$myfname1}\" value=\"{$ld}\" id=\"answer{$myfid1}-{$ld}\" "; if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1]) && $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1] == $ld) { $answer .= CHECKED; } $answer .= " />\n" . "<label class=\"hide read\" for=\"answer{$myfid1}-{$ld}\">{$labelans1[$thiskey]}</label>\n" . "\t</td>\n"; $thiskey++; } } if ($shownoanswer || $rightexists) { $answer .= "\t<td class=\"answertextright dual_scale_separator information-item\">{$answertextrigth}</td>\n"; } if ($shownoanswer) { $answer .= "\t<td class=\"dual_scale_no_answer answer-item radio-item noanswer-item\">\n"; if (count($labelans1) > 0) { $answer .= "\t<input class='radio' type='radio' name='{$myfname1}' value='' id='answer{$myfid1}-' "; if (!isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1]) || $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1] == "") { $answer .= CHECKED; } // --> START NEW FEATURE - SAVE $answer .= " />\n"; $answer .= "<label class='hide read' for='answer{$myfid1}-'>" . gT("No answer") . "</label>"; } else { $answer .= "\t<input class='radio' type='radio' name='{$myfname0}' value='' id='answer{$myfid0}-' "; if (!isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname0]) || $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname0] == "") { $answer .= CHECKED; } $answer .= "<label class='hide read' for='answer{$myfid0}-'>" . gT("No answer") . "<label>\n"; $answer .= " />\n"; } $answer .= "\t</td>\n"; } $answer .= "</tr>\n"; $fn++; } $answer .= "</tbody>\n"; $answer .= "</table>"; } elseif ($useDropdownLayout === true) { $separatorwidth = (100 - $answerwidth) / 10; $cellwidth = (100 - $answerwidth - $separatorwidth) / 2; $answer = ""; // Get attributes for Headers and Prefix/Suffix if (trim($aQuestionAttributes['dropdown_prepostfix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]) != '') { list($ddprefix, $ddsuffix) = explode("|", $aQuestionAttributes['dropdown_prepostfix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]); $ddprefix = $ddprefix; $ddsuffix = $ddsuffix; } else { $ddprefix = ''; $ddsuffix = ''; } if (trim($aQuestionAttributes['dropdown_separators']) != '') { $aSeparator = explode('|', $aQuestionAttributes['dropdown_separators']); if (isset($aSeparator[1])) { $interddSep = $aSeparator[1]; } else { $interddSep = $aSeparator[0]; } } else { $interddSep = ''; } $colspan_1 = ''; $colspan_2 = ''; $suffix_cell = ''; $answer .= "\n<table class=\"question subquestion-list questions-list dropdown-list\" summary=\"{$caption}\">\n" . "\t<col class=\"answertext\" width=\"{$answerwidth}%\" />\n"; if ($ddprefix != '' || $ddsuffix != '') { $answer .= "\t<colgroup width=\"{$cellwidth}%\">\n"; } if ($ddprefix != '') { $answer .= "\t\t<col class=\"ddprefix\" />\n"; $colspan_1 = ' colspan="2"'; } $headcolwidth = $ddprefix != '' || $ddsuffix != '' ? "" : " width=\"{$cellwidth}%\""; $answer .= "\t<col class=\"dsheader\"{$headcolwidth} />\n"; if ($ddsuffix != '') { $answer .= "\t<col class=\"ddsuffix\" />\n"; } if ($ddprefix != '' || $ddsuffix != '') { $answer .= "\t</colgroup>\n"; } $answer .= "\t<col class=\"ddarrayseparator\" width=\"{$separatorwidth}%\" />\n"; if ($ddprefix != '' || $ddsuffix != '') { $answer .= "\t<colgroup width=\"{$cellwidth}%\">\n"; } if ($ddprefix != '') { $answer .= "\t\t<col class=\"ddprefix\" />\n"; } $answer .= "\t<col class=\"dsheader\"{$headcolwidth} />\n"; if ($ddsuffix != '') { $answer .= "\t<col class=\"ddsuffix\" />\n"; } if ($ddprefix != '' || $ddsuffix != '') { $answer .= "\t</colgroup>\n"; } // colspan : for header only if ($ddprefix != '' && $ddsuffix != '') { $colspan = ' colspan="3"'; } elseif ($ddprefix != '' || $ddsuffix != '') { $colspan = ' colspan="2"'; } else { $colspan = ""; } // headers $answer .= "\n\t<thead>\n" . "<tr>\n" . "\t<td> </td>\n" . "\t<th{$colspan}>{$leftheader}</th>\n" . "\t<td> </td>\n" . "\t<th{$colspan}>{$rightheader}</th>\n"; $answer .= "\t</tr>\n" . "\t</thead>\n"; $answer .= "\n<tbody>\n"; $trbc = ''; foreach ($aSubQuestions as $ansrow) { $myfname = $ia[1] . $ansrow['title']; $myfname0 = $ia[1] . $ansrow['title'] . "#0"; $myfid0 = $ia[1] . $ansrow['title'] . "_0"; $myfname1 = $ia[1] . $ansrow['title'] . "#1"; $myfid1 = $ia[1] . $ansrow['title'] . "_1"; $sActualAnswer0 = isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname0]) ? $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname0] : ""; $sActualAnswer1 = isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1]) ? $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1] : ""; if ($ia[6] == 'Y' && (in_array($myfname0, $aMandatoryViolationSubQ) || in_array($myfname1, $aMandatoryViolationSubQ))) { $answertext = "<span class='errormandatory'>" . $ansrow['question'] . "</span>"; } else { $answertext = $ansrow['question']; } list($htmltbody2, $hiddenfield) = return_array_filter_strings($ia, $aQuestionAttributes, $thissurvey, $ansrow, $myfname, $trbc, $myfname, "tr", "{$trbc} subquestion-list questions-list dropdown-list"); $answer .= $htmltbody2; $answer .= "\t<th class=\"answertext\">\n" . "<label for=\"answer{$myfid0}\">{$answertext}</label>\n"; // Hidden answers used by EM: sure can be added in javascript $answer .= "<input type=\"hidden\" disabled=\"disabled\" name=\"java{$myfid0}\" id=\"java{$myfid0}\" value=\"{$sActualAnswer0}\" />\n"; $answer .= "<input type=\"hidden\" disabled=\"disabled\" name=\"java{$myfid1}\" id=\"java{$myfid1}\" value=\"{$sActualAnswer1}\" />\n"; $answer . "\t</th>\n"; // Selector 0 if ($ddprefix != '') { $answer .= "\t<td class=\"ddprefix information-item\">{$ddprefix}</td>\n"; } $answer .= "\t<td class=\"answer-item dropdown-item\">\n" . "<select name=\"{$myfname0}\" id=\"answer{$myfid0}\">\n"; // Show the 'Please choose' if there are no answer actually if ($sActualAnswer0 == '') { $answer .= "\t<option value=\"\" " . SELECTED . ">" . gT('Please choose...') . "</option>\n"; } foreach ($labels0 as $lrow) { $answer .= "\t<option value=\"" . $lrow['code'] . '" '; if ($sActualAnswer0 == $lrow['code']) { $answer .= SELECTED; } $answer .= '>' . flattenText($lrow['title']) . "</option>\n"; } if ($sActualAnswer0 != '' && $ia[6] != 'Y' && SHOW_NO_ANSWER) { $answer .= "\t<option value=\"\">" . gT('No answer') . "</option>\n"; } $answer .= "</select>\n"; $answer .= "</td>\n"; if ($ddsuffix != '') { $answer .= "\t<td class=\"ddsuffix information-item\">{$ddsuffix}</td>\n"; } $inputnames[] = $myfname0; $answer .= "\t<td class=\"ddarrayseparator information-item\">{$interddSep}</td>\n"; //Separator // Selector 1 if ($ddprefix != '') { $answer .= "\t<td class='ddprefix information-item'>{$ddprefix}</td>\n"; } $answer .= "\t<td class=\"answer-item dropdown-item\">\n" . "<label class=\"hide read\" for=\"answer{$myfid1}\">{$answertext}</label>" . "<select name=\"{$myfname1}\" id=\"answer{$myfid1}\">\n"; // Show the 'Please choose' if there are no answer actually if ($sActualAnswer1 == '') { $answer .= "\t<option value=\"\" " . SELECTED . ">" . gT('Please choose...') . "</option>\n"; } foreach ($labels1 as $lrow1) { $answer .= "\t<option value=\"" . $lrow1['code'] . '" '; if ($sActualAnswer1 == $lrow1['code']) { $answer .= SELECTED; } $answer .= '>' . flattenText($lrow1['title']) . "</option>\n"; } if ($sActualAnswer1 != '' && $ia[6] != 'Y' && SHOW_NO_ANSWER) { $answer .= "\t<option value=\"\">" . gT('No answer') . "</option>\n"; } $answer .= "</select>\n"; $answer .= "</td>\n"; if ($ddsuffix != '') { $answer .= "\t<td class=\"ddsuffix information-item\">{$ddsuffix}</td>\n"; } $inputnames[] = $myfname1; $answer .= "</tr>\n"; } $answer .= "\t</tbody>\n"; $answer .= "</table>\n"; } } else { $answer = "<p class='error'>" . gT("Error: There are no answer options for this question and/or they don't exist in this language.") . "</p>\n"; $inputnames = ""; } Yii::app()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts') . "dualscale.js"); $answer .= "<script type='text/javascript'>\n" . " <!--\n" . " {$doDualScaleFunction}({$ia[0]});\n" . " -->\n" . "</script>\n"; return array($answer, $inputnames); }
/** * Modify User POST */ function modcountry() { $clang = Yii::app()->lang; $countries_id = (int) Yii::app()->request->getPost("country_id"); $countries_name = flattenText(Yii::app()->request->getPost("country_name")); $continent_name = flattenText(Yii::app()->request->getPost("continent_name")); $IsActive = flattenText(Yii::app()->request->getPost("IsActive")); $c_name = flattenText(Yii::app()->request->getPost("c_name")); $addsummary = ''; $aViewUrls = array(); $is_Active = 0; if ($IsActive) { $is_Active = 1; } $sresult = Country::model()->findAllByAttributes(array('country_id' => $countries_id)); $sresultcount = count($sresult); if (Permission::model()->hasGlobalPermission('superadmin', 'read') || $sresultcount > 0 && Permission::model()->hasGlobalPermission('Regions', 'update')) { if ($c_name == '') { $aViewUrls['mboxwithredirect'][] = $this->_messageBoxWithRedirect($clang->gT("Editing country"), $clang->gT("Could not modify country."), "warningheader", $clang->gT("Country name not be empty."), $this->getController()->createUrl('admin/country/modifycountry'), $clang->gT("Back"), array('country_id' => $countries_id)); } elseif (Country::model()->findByAttributes(array('country_name' => $c_name, 'continent' => $continent_name, 'IsActive' => $is_Active))) { $aViewUrls['message'] = array('title' => $clang->gT("Failed to add Contry"), 'message' => $clang->gT("The Country already exists."), 'class' => 'warningheader'); } else { $oRecord = Country::model()->findByPk($countries_id); $oRecord->country_name = $this->escape($c_name); $oRecord->continent = $this->escape($continent_name); $oRecord->IsActive = $this->escape($is_Active); $uresult = $oRecord->save(); // store result of save in uresult if ($uresult) { // When saved successfully Yii::app()->setFlashMessage($clang->gT("Country updated successfully")); $this->getController()->redirect(array("admin/country/index")); } else { //Saving the user failed for some reason, message about email is not helpful here // Username and/or email adress already exists. $aViewUrls['mboxwithredirect'][] = $this->_messageBoxWithRedirect($clang->gT("Editing country"), $clang->gT("Could not modify country."), 'warningheader'); } } } else { Yii::app()->setFlashMessage(Yii::app()->lang->gT("You do not have sufficient rights to access this page."), 'error'); $this->getController()->redirect(array("admin/index")); } $this->_renderWrappedTemplate('region/country', $aViewUrls); }
/** * This function replaces keywords in a text and is mainly intended for templates * If you use this functions put your replacement strings into the $replacements variable * instead of using global variables * NOTE - Don't do any embedded replacements in this function. Create the array of replacement values and * they will be done in batch at the end * * @param mixed $line Text to search in * @param mixed $replacements Array of replacements: Array( <stringtosearch>=><stringtoreplacewith> * @param boolean $anonymized Determines if token data is being used or just replaced with blanks * @param questionNum - needed to support dynamic JavaScript-based tailoring within questions * @return string Text with replaced strings */ function templatereplace($line, $replacements = array(), &$redata = array(), $debugSrc = 'Unspecified', $anonymized = false, $questionNum = NULL, $registerdata = array()) { /* global $clienttoken,$token,$sitename,$move,$showxquestions,$showqnumcode,$questioncode,$register_errormsg; global $s_lang,$errormsg,$saved_id, $relativeurl, $languagechanger,$captchapath,$loadname; */ /* $allowedvars = array('surveylist', 'sitename', 'clienttoken', 'rooturl', 'thissurvey', 'imageurl', 'defaulttemplate', 'percentcomplete', 'move', 'groupname', 'groupdescription', 'question', 'showxquestions', 'showgroupinfo', 'showqnumcode', 'questioncode', 'answer', 'navigator', 'help', 'totalquestions', 'surveyformat', 'completed', 'register_errormsg', 'notanswered', 'privacy', 'surveyid', 'publicurl', 'templatedir', 'token', 'assessments', 's_lang', 'errormsg', 'clang', 'saved_id', 'usertemplaterootdir', 'relativeurl', 'languagechanger', 'printoutput', 'captchapath', 'loadname'); */ $allowedvars = array('answer', 'assessments', 'captchapath', 'clienttoken', 'completed', 'errormsg', 'groupdescription', 'groupname', 'help', 'imageurl', 'languagechanger', 'loadname', 'move', 'navigator', 'percentcomplete', 'privacy', 'question', 'register_errormsg', 'relativeurl', 's_lang', 'saved_id', 'showgroupinfo', 'showqnumcode', 'showxquestions', 'sitename', 'surveylist', 'templatedir', 'thissurvey', 'token', 'totalBoilerplatequestions', 'totalquestions'); $varsPassed = array(); foreach ($allowedvars as $var) { if (isset($redata[$var])) { ${$var} = $redata[$var]; $varsPassed[] = $var; } } // if (count($varsPassed) > 0) { // log_message('debug', 'templatereplace() called from ' . $debugSrc . ' contains: ' . implode(', ', $varsPassed)); // } // if (isset($redata['question'])) { // LimeExpressionManager::ShowStackTrace('has QID and/or SGA',$allowedvars); // } // extract($redata); // creates variables for each of the keys in the array // Local over-rides in case not set above if (!isset($showgroupinfo)) { $showgroupinfo = Yii::app()->getConfig('showgroupinfo'); } if (!isset($showqnumcode)) { $showqnumcode = Yii::app()->getConfig('showqnumcode'); } $_surveyid = Yii::app()->getConfig('surveyID'); if (!isset($showxquestions)) { $showxquestions = Yii::app()->getConfig('showxquestions'); } if (!isset($s_lang)) { $s_lang = isset(Yii::app()->session['survey_' . $_surveyid]['s_lang']) ? Yii::app()->session['survey_' . $_surveyid]['s_lang'] : 'en'; } if (!isset($captchapath)) { $captchapath = ''; } $clang = Yii::app()->lang; Yii::app()->loadHelper('surveytranslator'); $questiondetails = array('sid' => 0, 'gid' => 0, 'qid' => 0, 'aid' => 0); if (isset($question) && isset($question['sgq'])) { $questiondetails = getSIDGIDQIDAIDType($question['sgq']); } //Gets an array containing SID, GID, QID, AID and Question Type) if (isset($thissurvey['sid'])) { $surveyid = $thissurvey['sid']; } // lets sanitize the survey template if (isset($thissurvey['templatedir'])) { $templatename = $thissurvey['templatedir']; } else { $templatename = Yii::app()->getConfig('defaulttemplate'); } if (!isset($templatedir)) { $templatedir = getTemplatePath($templatename); } if (!isset($templateurl)) { $templateurl = getTemplateURL($templatename) . "/"; } // TEMPLATECSS and TEMPLATEJS $_templatecss = ""; $_templatejs = ""; if (stripos($line, "{TEMPLATECSS}")) { $css_header_includes = Yii::app()->getConfig("css_header_includes"); if (file_exists($templatedir . DIRECTORY_SEPARATOR . 'jquery-ui-custom.css')) { $template_jqueryui_css = "<link rel='stylesheet' type='text/css' media='all' href='{$templateurl}jquery-ui-custom.css' />\n"; } elseif (file_exists($templatedir . DIRECTORY_SEPARATOR . 'jquery-ui.css')) { $template_jqueryui_css = "<link rel='stylesheet' type='text/css' media='all' href='{$templateurl}jquery-ui.css' />\n"; } else { $_templatecss .= "<link rel='stylesheet' type='text/css' media='all' href='" . Yii::app()->getConfig('publicstyleurl') . "jquery-ui.css' />\n"; // Remove it after corrected slider $template_jqueryui_css = ""; } if ($css_header_includes) { foreach ($css_header_includes as $cssinclude) { if (substr($cssinclude, 0, 4) == 'http' || substr($cssinclude, 0, strlen(Yii::app()->getConfig('publicurl'))) == Yii::app()->getConfig('publicurl')) { $_templatecss .= "<link rel='stylesheet' type='text/css' media='all' href='" . $cssinclude . "' />\n"; } else { if (file_exists($templatedir . DIRECTORY_SEPARATOR . $cssinclude)) { $_templatecss .= "<link rel='stylesheet' type='text/css' media='all' href='{$templateurl}{$cssinclude}' />\n"; } else { $_templatecss .= "<link rel='stylesheet' type='text/css' media='all' href='" . Yii::app()->getConfig('publicstyleurl') . $cssinclude . "' />\n"; } } } } $_templatecss .= $template_jqueryui_css; // Template jquery ui after default css $_templatecss .= "<link rel='stylesheet' type='text/css' media='all' href='{$templateurl}template.css' />\n"; if (getLanguageRTL($clang->langcode)) { $_templatecss .= "<link rel='stylesheet' type='text/css' media='all' href='{$templateurl}template-rtl.css' />\n"; } } if (stripos($line, "{TEMPLATEJS}")) { $js_header_includes = header_includes(false, 'js'); $_jqueryuijsurl = Yii::app()->getConfig('generalscripts') . "jquery/jquery-ui.js"; $_templatejs .= "<script type='text/javascript' src='" . Yii::app()->getConfig('generalscripts') . "jquery/jquery.js'></script>\n"; $_templatejs .= "<script type='text/javascript' src='{$_jqueryuijsurl}'></script>\n"; $_templatejs .= "<script type='text/javascript' src='" . Yii::app()->getConfig('generalscripts') . "jquery/jquery.ui.touch-punch.min.js'></script>\n"; if ($js_header_includes) { foreach ($js_header_includes as $jsinclude) { if (substr($jsinclude, 0, 4) == 'http' || substr($jsinclude, 0, strlen(Yii::app()->getConfig('publicurl'))) == Yii::app()->getConfig('publicurl')) { $_templatejs .= "<script type='text/javascript' src='{$jsinclude}'></script>\n"; } else { $_templatejs .= "<script type='text/javascript' src='" . Yii::app()->getConfig('generalscripts') . $jsinclude . "'></script>\n"; } } } $_templatejs .= "<script type='text/javascript' src='" . Yii::app()->getConfig('generalscripts') . "survey_runtime.js'></script>\n"; $_templatejs .= "<script type='text/javascript' src='{$templateurl}template.js'></script>\n"; $_templatejs .= useFirebug(); } // surveyformat if (isset($thissurvey['format'])) { $surveyformat = str_replace(array("A", "S", "G"), array("allinone", "questionbyquestion", "groupbygroup"), $thissurvey['format']); } else { $surveyformat = ""; } if (isset(Yii::app()->session['step']) && Yii::app()->session['step'] % 2 && $surveyformat != "allinone") { $surveyformat .= " page-odd"; } if (isset($thissurvey['allowjumps']) && $thissurvey['allowjumps'] == "Y" && $surveyformat != "allinone" && (isset(Yii::app()->session['step']) && Yii::app()->session['step'] > 0)) { $surveyformat .= " withindex"; } if (isset($thissurvey['showprogress']) && $thissurvey['showprogress'] == "Y") { $surveyformat .= " showprogress"; } if (isset($thissurvey['showqnumcode'])) { $surveyformat .= " showqnumcode-" . $thissurvey['showqnumcode']; } // real survey contact if (isset($surveylist) && isset($surveylist['contact'])) { $surveycontact = $surveylist['contact']; } elseif (isset($surveylist) && isset($thissurvey['admin']) && $thissurvey['admin'] != "") { $surveycontact = sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), $thissurvey['admin'], $thissurvey['adminemail']); } else { $surveycontact = ""; } // If there are non-bracketed replacements to be made do so above this line. // Only continue in this routine if there are bracketed items to replace {} if (strpos($line, "{") === false) { // process string anyway so that it can be pretty-printed return LimeExpressionManager::ProcessString($line, $questionNum, NULL, false, 1, 1, true); } if ($showgroupinfo == 'both' || $showgroupinfo == 'name' || $showgroupinfo == 'choose' && !isset($thissurvey['showgroupinfo']) || $showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'B' || $showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'N') { $_groupname = isset($groupname) ? $groupname : ''; } else { $_groupname = ''; } if ($showgroupinfo == 'both' || $showgroupinfo == 'description' || $showgroupinfo == 'choose' && !isset($thissurvey['showgroupinfo']) || $showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'B' || $showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'D') { $_groupdescription = isset($groupdescription) ? $groupdescription : ''; } else { $_groupdescription = ''; } if (isset($question) && is_array($question)) { $_question = $question['all']; $_question_text = $question['text']; $_question_help = $question['help']; $_question_mandatory = $question['mandatory']; $_question_man_message = $question['man_message']; $_question_valid_message = $question['valid_message']; $_question_file_valid_message = $question['file_valid_message']; $_question_sgq = isset($question['sgq']) ? $question['sgq'] : ''; $_question_essentials = $question['essentials']; $_getQuestionClass = $question['class']; $_question_man_class = $question['man_class']; $_question_input_error_class = $question['input_error_class']; $_question_number = $question['number']; $_question_code = $question['code']; $_question_type = $question['type']; } else { $_question = isset($question) ? $question : ''; $_question_text = ''; $_question_help = ''; $_question_mandatory = ''; $_question_man_message = ''; $_question_valid_message = ''; $_question_file_valid_message = ''; $_question_sgq = ''; $_question_essentials = ''; $_getQuestionClass = ''; $_question_man_class = ''; $_question_input_error_class = ''; $_question_number = ''; $_question_code = ''; $_question_type = ''; } if ($_question_type == '*') { $_question_text = '<div class="em_equation">' . $_question_text . '</div>'; } if (!($showqnumcode == 'both' || $showqnumcode == 'number' || $showqnumcode == 'choose' && !isset($thissurvey['showqnumcode']) || $showqnumcode == 'choose' && $thissurvey['showqnumcode'] == 'B' || $showqnumcode == 'choose' && $thissurvey['showqnumcode'] == 'N')) { $_question_number = ''; } if (!($showqnumcode == 'both' || $showqnumcode == 'code' || $showqnumcode == 'choose' && !isset($thissurvey['showqnumcode']) || $showqnumcode == 'choose' && $thissurvey['showqnumcode'] == 'B' || $showqnumcode == 'choose' && $thissurvey['showqnumcode'] == 'C')) { $_question_code = ''; } if (!isset($totalquestions)) { $totalquestions = 0; } $_totalquestionsAsked = $totalquestions; if ($showxquestions == 'show' || $showxquestions == 'choose' && !isset($thissurvey['showxquestions']) || $showxquestions == 'choose' && $thissurvey['showxquestions'] == 'Y') { if ($_totalquestionsAsked < 1) { $_therearexquestions = $clang->gT("There are no questions in this survey"); // Singular } elseif ($_totalquestionsAsked == 1) { $_therearexquestions = $clang->gT("There is 1 question in this survey"); //Singular } else { $_therearexquestions = $clang->gT("There are {NUMBEROFQUESTIONS} questions in this survey."); //Note this line MUST be before {NUMBEROFQUESTIONS} } } else { $_therearexquestions = ''; } if (isset($token)) { $_token = $token; } elseif (isset($clienttoken)) { $_token = htmlentities($clienttoken, ENT_QUOTES, 'UTF-8'); // or should it be URL-encoded? } else { $_token = ''; } // Expiry if (isset($thissurvey['expiry'])) { $dateformatdetails = getDateFormatData($thissurvey['surveyls_dateformat']); Yii::import('application.libraries.Date_Time_Converter', true); $datetimeobj = new Date_Time_Converter($thissurvey['expiry'], "Y-m-d"); $_dateoutput = $datetimeobj->convert($dateformatdetails['phpdate']); } else { $_dateoutput = '-'; } $_submitbutton = "<input class='submit' type='submit' value=' " . $clang->gT("Submit") . " ' name='move2' onclick=\"javascript:document.limesurvey.move.value = 'movesubmit';\" />"; if (isset($thissurvey['surveyls_url']) and $thissurvey['surveyls_url'] != "") { if (trim($thissurvey['surveyls_urldescription']) != '') { $_linkreplace = "<a href='{$thissurvey['surveyls_url']}'>{$thissurvey['surveyls_urldescription']}</a>"; } else { $_linkreplace = "<a href='{$thissurvey['surveyls_url']}'>{$thissurvey['surveyls_url']}</a>"; } } else { $_linkreplace = ''; } if (isset($thissurvey['sid']) && isset($_SESSION['survey_' . $thissurvey['sid']]['srid']) && $thissurvey['active'] == 'Y') { $iscompleted = Survey_dynamic::model($surveyid)->isCompleted($_SESSION['survey_' . $thissurvey['sid']]['srid']); } else { $iscompleted = false; } if (isset($surveyid) && !$iscompleted) { $_clearall = "<input type='button' name='clearallbtn' value='" . $clang->gT("Exit and clear survey") . "' class='clearall' " . "onclick=\"if (confirm('" . $clang->gT("Are you sure you want to clear all your responses?", 'js') . "')) {\nwindow.open('" . Yii::app()->getController()->createUrl("survey/index/sid/{$surveyid}", array('move' => 'clearall', 'lang' => $s_lang), '&'); if (returnGlobal('token')) { $_clearall .= "&token=" . urlencode(trim(sanitize_token(strip_tags(returnGlobal('token'))))); } $_clearall .= "', '_self')}\" />"; } else { $_clearall = ""; } if (isset(Yii::app()->session['datestamp'])) { $_datestamp = Yii::app()->session['datestamp']; } else { $_datestamp = '-'; } if (isset($thissurvey['allowsave']) and $thissurvey['allowsave'] == "Y") { // Find out if the user has any saved data if ($thissurvey['format'] == 'A') { if ($thissurvey['tokenanswerspersistence'] != 'Y' || !isset($surveyid) || !tableExists('tokens_' . $surveyid)) { $_saveall = "\t\t\t<input type='button' name='loadall' value='" . $clang->gT("Load unfinished survey") . "' class='saveall' onclick=\"javascript:addHiddenField(document.getElementById('limesurvey'),'loadall',this.value);document.getElementById('limesurvey').submit();\" " . ($thissurvey['active'] != "Y" ? "disabled='disabled'" : "") . "/>" . "\n\t\t\t<input type='button' name='saveallbtn' value='" . $clang->gT("Resume later") . "' class='saveall' onclick=\"javascript:document.limesurvey.move.value = this.value;addHiddenField(document.getElementById('limesurvey'),'saveall',this.value);document.getElementById('limesurvey').submit();\" " . ($thissurvey['active'] != "Y" ? "disabled='disabled'" : "") . "/>"; // Show Save So Far button } else { $_saveall = "\t\t\t<input type='button' name='saveallbtn' value='" . $clang->gT("Resume later") . "' class='saveall' onclick=\"javascript:document.limesurvey.move.value = this.value;addHiddenField(document.getElementById('limesurvey'),'saveall',this.value);document.getElementById('limesurvey').submit();\" " . ($thissurvey['active'] != "Y" ? "disabled='disabled'" : "") . "/>"; // Show Save So Far button } } elseif (isset($surveyid) && (!isset($_SESSION['survey_' . $surveyid]['step']) || !$_SESSION['survey_' . $surveyid]['step'])) { //First page, show LOAD if ($thissurvey['tokenanswerspersistence'] != 'Y' || !isset($surveyid) || !tableExists('tokens_' . $surveyid)) { $_saveall = "\t\t\t<input type='button' name='loadall' value='" . $clang->gT("Load unfinished survey") . "' class='saveall' onclick=\"javascript:addHiddenField(document.getElementById('limesurvey'),'loadall',this.value);document.getElementById('limesurvey').submit();\" " . ($thissurvey['active'] != "Y" ? "disabled='disabled'" : "") . "/>"; } else { $_saveall = ''; } } elseif (isset(Yii::app()->session['scid']) && (isset($move) && $move == "movelast")) { //Already saved and on Submit Page, dont show Save So Far button $_saveall = ''; } else { $_saveall = "<input type='button' name='saveallbtn' value='" . $clang->gT("Resume later") . "' class='saveall' onclick=\"javascript:document.limesurvey.move.value = this.value;addHiddenField(document.getElementById('limesurvey'),'saveall',this.value);document.getElementById('limesurvey').submit();\" " . ($thissurvey['active'] != "Y" ? "disabled='disabled'" : "") . "/>"; // Show Save So Far button } } else { $_saveall = ""; } if (!isset($help)) { $help = ""; } if (flattenText($help, true, true) != '') { if (!isset($helpicon)) { if (file_exists($templatedir . '/help.gif')) { $helpicon = $templateurl . 'help.gif'; } elseif (file_exists($templatedir . '/help.png')) { $helpicon = $templateurl . 'help.png'; } else { $helpicon = Yii::app()->getConfig('imageurl') . "/help.gif"; } } $_questionhelp = "<img src='{$helpicon}' alt='Help' align='left' />" . $help; } else { $_questionhelp = $help; } if (isset($thissurvey['allowprev']) && $thissurvey['allowprev'] == "N") { $_strreview = ""; } else { $_strreview = $clang->gT("If you want to check any of the answers you have made, and/or change them, you can do that now by clicking on the [<< prev] button and browsing through your responses."); } if (isset($thissurvey['active']) and $thissurvey['active'] == "N") { $_restart = "<a href='" . Yii::app()->getController()->createUrl("survey/index/sid/{$surveyid}/newtest/Y"); if (isset($s_lang) && $s_lang != '') { $_restart .= "/lang/" . $s_lang; } $_restart .= "'>" . $clang->gT("Restart this survey") . "</a>"; } else { if (isset($surveyid)) { $restart_extra = ""; $restart_token = returnGlobal('token'); if (!empty($restart_token)) { $restart_extra .= "/token/" . urlencode($restart_token); } else { $restart_extra = "/newtest/Y"; } if (!empty($_GET['lang'])) { $restart_extra .= "/lang/" . returnGlobal('lang'); } $_restart = "<a href='" . Yii::app()->getController()->createUrl("survey/index/sid/{$surveyid}{$restart_extra}") . "'>" . $clang->gT("Restart this Survey") . "</a>"; } else { $_restart = ""; } } if (isset($thissurvey['anonymized']) && $thissurvey['anonymized'] == 'Y') { $_savealert = $clang->gT("To remain anonymous please use a pseudonym as your username, also an email address is not required."); } else { $_savealert = ""; } if (isset($surveyid)) { $_return_to_survey = "<a href=" . Yii::app()->getController()->createUrl("survey/index/sid/{$surveyid}"); if (returnGlobal('token')) { $_return_to_survey .= "?amp;token=" . urlencode(trim(sanitize_xss_string(strip_tags(returnGlobal('token'))))); } $_return_to_survey .= "'>" . $clang->gT("Return to survey") . "</a>"; } else { $_return_to_survey = ""; } // Save Form $_saveform = "<table><tr><td align='right'>" . $clang->gT("Name") . ":</td><td><input type='text' name='savename' value='"; if (isset($_POST['savename'])) { $_saveform .= HTMLEscape(autoUnescape($_POST['savename'])); } $_saveform .= "' /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Password") . ":</td><td><input type='password' name='savepass' value='"; if (isset($_POST['savepass'])) { $_saveform .= HTMLEscape(autoUnescape($_POST['savepass'])); } $_saveform .= "' /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Repeat password") . ":</td><td><input type='password' name='savepass2' value='"; if (isset($_POST['savepass2'])) { $_saveform .= HTMLEscape(autoUnescape($_POST['savepass2'])); } $_saveform .= "' /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Your email address") . ":</td><td><input type='text' name='saveemail' value='"; if (isset($_POST['saveemail'])) { $_saveform .= HTMLEscape(autoUnescape($_POST['saveemail'])); } $_saveform .= "' /></td></tr>\n"; if (isset($thissurvey['usecaptcha']) && function_exists("ImageCreate") && isCaptchaEnabled('saveandloadscreen', $thissurvey['usecaptcha'])) { $_saveform .= "<tr><td align='right'>" . $clang->gT("Security question") . ":</td><td><table><tr><td valign='middle'><img src='" . Yii::app()->getController()->createUrl('/verification/image/sid/' . (isset($surveyid) ? $surveyid : '')) . "' alt6='' /></td><td valign='middle' style='text-align:left'><input type='text' size='5' maxlength='3' name='loadsecurity' value='' /></td></tr></table></td></tr>\n"; } $_saveform .= "<tr><td align='right'></td><td></td></tr>\n" . "<tr><td></td><td><input type='submit' id='savebutton' name='savesubmit' value='" . $clang->gT("Save Now") . "' /></td></tr>\n" . "</table>"; // Load Form $_loadform = "<table><tr><td align='right'>" . $clang->gT("Saved name") . ":</td><td><input type='text' name='loadname' value='"; if (isset($loadname)) { $_loadform .= HTMLEscape(autoUnescape($loadname)); } $_loadform .= "' /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Password") . ":</td><td><input type='password' name='loadpass' value='"; if (isset($loadpass)) { $_loadform .= HTMLEscape(autoUnescape($loadpass)); } $_loadform .= "' /></td></tr>\n"; if (isset($thissurvey['usecaptcha']) && function_exists("ImageCreate") && isCaptchaEnabled('saveandloadscreen', $thissurvey['usecaptcha'])) { $_loadform .= "<tr><td align='right'>" . $clang->gT("Security question") . ":</td><td><table><tr><td valign='middle'><img src='" . Yii::app()->getController()->createUrl('/verification/image/sid/' . $surveyid) . "' alt='' /></td><td valign='middle'><input type='text' size='5' maxlength='3' name='loadsecurity' value='' alt=''/></td></tr></table></td></tr>\n"; } $_loadform .= "<tr><td align='right'></td><td></td></tr>\n" . "<tr><td></td><td><input type='submit' id='loadbutton' value='" . $clang->gT("Load now") . "' /></td></tr></table>\n"; // Registration Form if (isset($surveyid) || isset($registerdata) && $debugSrc == 'register.php') { if (isset($surveyid)) { $tokensid = $surveyid; } else { $tokensid = $registerdata['sid']; } $_registerform = "<form method='post' action='" . Yii::app()->getController()->createUrl('/register/index/surveyid/' . $tokensid) . "'>\n"; if (!isset($_REQUEST['lang'])) { $_reglang = Survey::model()->findByPk($tokensid)->language; } else { $_reglang = returnGlobal('lang'); } $_registerform .= "<input type='hidden' name='lang' value='" . $_reglang . "' />\n"; $_registerform .= "<input type='hidden' name='sid' value='{$tokensid}' id='sid' />\n"; $_registerform .= "<table class='register' summary='Registrationform'>\n" . "<tr><td align='right'>" . $clang->gT("First name") . ":</td>" . "<td align='left'><input class='text' type='text' name='register_firstname'"; if (isset($_POST['register_firstname'])) { $_registerform .= " value='" . htmlentities(returnGlobal('register_firstname'), ENT_QUOTES, 'UTF-8') . "'"; } $_registerform .= " /></td></tr>" . "<tr><td align='right'>" . $clang->gT("Last name") . ":</td>\n" . "<td align='left'><input class='text' type='text' name='register_lastname'"; if (isset($_POST['register_lastname'])) { $_registerform .= " value='" . htmlentities(returnGlobal('register_lastname'), ENT_QUOTES, 'UTF-8') . "'"; } $_registerform .= " /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Email address") . ":</td>\n" . "<td align='left'><input class='text' type='text' name='register_email'"; if (isset($_POST['register_email'])) { $_registerform .= " value='" . htmlentities(returnGlobal('register_email'), ENT_QUOTES, 'UTF-8') . "'"; } $_registerform .= " /></td></tr>\n"; foreach ($thissurvey['attributedescriptions'] as $field => $attribute) { if (empty($attribute['show_register']) || $attribute['show_register'] != 'Y') { continue; } $_registerform .= ' <tr> <td align="right">' . $thissurvey['attributecaptions'][$field] . ($attribute['mandatory'] == 'Y' ? '*' : '') . ':</td> <td align="left"><input class="text" type="text" name="register_' . $field . '" /></td> </tr>'; } if ((count($registerdata) > 1 || isset($thissurvey['usecaptcha'])) && function_exists("ImageCreate") && isCaptchaEnabled('registrationscreen', $thissurvey['usecaptcha'])) { $_registerform .= "<tr><td align='right'>" . $clang->gT("Security Question") . ":</td><td><table><tr><td valign='middle'><img src='" . Yii::app()->getController()->createUrl('/verification/image/sid/' . $surveyid) . "' alt='' /></td><td valign='middle'><input type='text' size='5' maxlength='3' name='loadsecurity' value='' /></td></tr></table></td></tr>\n"; } $_registerform .= "<tr><td></td><td><input id='registercontinue' class='submit' type='submit' value='" . $clang->gT("Continue") . "' />" . "</td></tr>\n" . "</table>\n"; if (count($registerdata) > 1 && $registerdata['sid'] != NULL && $debugSrc == 'register.php') { $_registerform .= "<input name='startdate' type ='hidden' value='" . $registerdata['startdate'] . "' />"; $_registerform .= "<input name='enddate' type ='hidden' value='" . $registerdata['enddate'] . "' />"; } $_registerform .= "</form>\n"; } else { $_registerform = ""; } // Assessments $assessmenthtml = ""; if (isset($surveyid) && !is_null($surveyid) && function_exists('doAssessment')) { $assessmentdata = doAssessment($surveyid, true); $_assessment_current_total = $assessmentdata['total']; if (stripos($line, "{ASSESSMENTS}")) { $assessmenthtml = doAssessment($surveyid, false); } } else { $_assessment_current_total = ''; } if (isset($thissurvey['googleanalyticsapikey']) && trim($thissurvey['googleanalyticsapikey']) != '') { $_googleAnalyticsAPIKey = trim($thissurvey['googleanalyticsapikey']); } else { $_googleAnalyticsAPIKey = trim(getGlobalSetting('googleanalyticsapikey')); } $_googleAnalyticsStyle = isset($thissurvey['googleanalyticsstyle']) ? $thissurvey['googleanalyticsstyle'] : '0'; $_googleAnalyticsJavaScript = ''; if ($_googleAnalyticsStyle != '' && $_googleAnalyticsStyle != 0 && $_googleAnalyticsAPIKey != '') { switch ($_googleAnalyticsStyle) { case '1': // Default Google Tracking $_googleAnalyticsJavaScript = <<<EOD <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', '{$_googleAnalyticsAPIKey}']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> EOD; break; case '2': // SurveyName-[SID]/[GSEQ]-GroupName - create custom GSEQ based upon page step $moveInfo = LimeExpressionManager::GetLastMoveResult(); if (is_null($moveInfo)) { $gseq = 'welcome'; } else { if ($moveInfo['finished']) { $gseq = 'finished'; } else { if (isset($moveInfo['at_start']) && $moveInfo['at_start']) { $gseq = 'welcome'; } else { if (is_null($_groupname)) { $gseq = 'printanswers'; } else { $gseq = $moveInfo['gseq'] + 1; } } } } $_trackURL = htmlspecialchars($thissurvey['name'] . '-[' . $surveyid . ']/[' . $gseq . ']-' . $_groupname); $_googleAnalyticsJavaScript = <<<EOD <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', '{$_googleAnalyticsAPIKey}']); _gaq.push(['_trackPageview','{$_trackURL}']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> EOD; break; } } $_endtext = ''; if (isset($thissurvey['surveyls_endtext']) && trim($thissurvey['surveyls_endtext']) != '') { $_endtext = $thissurvey['surveyls_endtext']; } // Set the array of replacement variables here - don't include curly braces $coreReplacements = array(); $coreReplacements['ACTIVE'] = isset($thissurvey['active']) && !($thissurvey['active'] != "Y"); $coreReplacements['AID'] = isset($questiondetails['aid']) ? $questiondetails['aid'] : ''; $coreReplacements['ANSWER'] = isset($answer) ? $answer : ''; // global $coreReplacements['ANSWERSCLEARED'] = $clang->gT("Answers cleared"); $coreReplacements['ASSESSMENTS'] = $assessmenthtml; $coreReplacements['ASSESSMENT_CURRENT_TOTAL'] = $_assessment_current_total; $coreReplacements['ASSESSMENT_HEADING'] = $clang->gT("Your assessment"); $coreReplacements['CHECKJAVASCRIPT'] = "<noscript><span class='warningjs'>" . $clang->gT("Caution: JavaScript execution is disabled in your browser. You may not be able to answer all questions in this survey. Please, verify your browser parameters.") . "</span></noscript>"; $coreReplacements['CLEARALL'] = $_clearall; $coreReplacements['CLOSEWINDOW'] = "<a href='javascript:%20self.close()'>" . $clang->gT("Close this window") . "</a>"; $coreReplacements['COMPLETED'] = isset($redata['completed']) ? $redata['completed'] : ''; // global $coreReplacements['DATESTAMP'] = $_datestamp; $coreReplacements['ENDTEXT'] = $_endtext; $coreReplacements['EXPIRY'] = $_dateoutput; $coreReplacements['GID'] = isset($questiondetails['gid']) ? $questiondetails['gid'] : ''; $coreReplacements['GOOGLE_ANALYTICS_API_KEY'] = $_googleAnalyticsAPIKey; $coreReplacements['GOOGLE_ANALYTICS_JAVASCRIPT'] = $_googleAnalyticsJavaScript; $coreReplacements['GROUPDESCRIPTION'] = $_groupdescription; $coreReplacements['GROUPNAME'] = $_groupname; $coreReplacements['LANG'] = $clang->getlangcode(); $coreReplacements['LANGUAGECHANGER'] = isset($languagechanger) ? $languagechanger : ''; // global $coreReplacements['LOADERROR'] = isset($errormsg) ? $errormsg : ''; // global $coreReplacements['LOADFORM'] = $_loadform; $coreReplacements['LOADHEADING'] = $clang->gT("Load a previously saved survey"); $coreReplacements['LOADMESSAGE'] = $clang->gT("You can load a survey that you have previously saved from this screen.") . "<br />" . $clang->gT("Type in the 'name' you used to save the survey, and the password.") . "<br />"; $coreReplacements['NAVIGATOR'] = isset($navigator) ? $navigator : ''; // global $coreReplacements['NOSURVEYID'] = isset($surveylist) ? $surveylist['nosid'] : ''; $coreReplacements['NUMBEROFQUESTIONS'] = $_totalquestionsAsked; $coreReplacements['PERCENTCOMPLETE'] = isset($percentcomplete) ? $percentcomplete : ''; // global $coreReplacements['PRIVACY'] = isset($privacy) ? $privacy : ''; // global $coreReplacements['PRIVACYMESSAGE'] = "<span style='font-weight:bold; font-style: italic;'>" . $clang->gT("A Note On Privacy") . "</span><br />" . $clang->gT("This survey is anonymous.") . "<br />" . $clang->gT("The record kept of your survey responses does not contain any identifying information about you unless a specific question in the survey has asked for this. If you have responded to a survey that used an identifying token to allow you to access the survey, you can rest assured that the identifying token is not kept with your responses. It is managed in a separate database, and will only be updated to indicate that you have (or haven't) completed this survey. There is no way of matching identification tokens with survey responses in this survey."); $coreReplacements['QID'] = isset($questiondetails['qid']) ? $questiondetails['qid'] : ''; $coreReplacements['QUESTION'] = $_question; $coreReplacements['QUESTIONHELP'] = $_questionhelp; $coreReplacements['QUESTIONHELPPLAINTEXT'] = strip_tags(addslashes($help)); // global $coreReplacements['QUESTION_CLASS'] = $_getQuestionClass; $coreReplacements['QUESTION_CODE'] = $_question_code; $coreReplacements['QUESTION_ESSENTIALS'] = $_question_essentials; $coreReplacements['QUESTION_FILE_VALID_MESSAGE'] = $_question_file_valid_message; $coreReplacements['QUESTION_HELP'] = $_question_help; $coreReplacements['QUESTION_INPUT_ERROR_CLASS'] = $_question_input_error_class; $coreReplacements['QUESTION_MANDATORY'] = $_question_mandatory; $coreReplacements['QUESTION_MAN_CLASS'] = $_question_man_class; $coreReplacements['QUESTION_MAN_MESSAGE'] = $_question_man_message; $coreReplacements['QUESTION_NUMBER'] = $_question_number; $coreReplacements['QUESTION_TEXT'] = $_question_text; $coreReplacements['QUESTION_VALID_MESSAGE'] = $_question_valid_message; $coreReplacements['REGISTERERROR'] = isset($register_errormsg) ? $register_errormsg : ''; // global $coreReplacements['REGISTERFORM'] = $_registerform; $coreReplacements['REGISTERMESSAGE1'] = $clang->gT("You must be registered to complete this survey"); $coreReplacements['REGISTERMESSAGE2'] = $clang->gT("You may register for this survey if you wish to take part.") . "<br />\n" . $clang->gT("Enter your details below, and an email containing the link to participate in this survey will be sent immediately."); $coreReplacements['RESTART'] = $_restart; $coreReplacements['RETURNTOSURVEY'] = $_return_to_survey; $coreReplacements['SAVE'] = $_saveall; $coreReplacements['SAVEALERT'] = $_savealert; $coreReplacements['SAVEDID'] = isset($saved_id) ? $saved_id : ''; // global $coreReplacements['SAVEERROR'] = isset($errormsg) ? $errormsg : ''; // global - same as LOADERROR $coreReplacements['SAVEFORM'] = $_saveform; $coreReplacements['SAVEHEADING'] = $clang->gT("Save your unfinished survey"); $coreReplacements['SAVEMESSAGE'] = $clang->gT("Enter a name and password for this survey and click save below.") . "<br />\n" . $clang->gT("Your survey will be saved using that name and password, and can be completed later by logging in with the same name and password.") . "<br /><br />\n" . $clang->gT("If you give an email address, an email containing the details will be sent to you.") . "<br /><br />\n" . $clang->gT("After having clicked the save button you can either close this browser window or continue filling out the survey."); $coreReplacements['SGQ'] = $_question_sgq; $coreReplacements['SID'] = isset($surveyid) ? $surveyid : (isset($questiondetails['sid']) ? $questiondetails['sid'] : ''); $coreReplacements['SITENAME'] = isset($sitename) ? $sitename : ''; // global $coreReplacements['SUBMITBUTTON'] = $_submitbutton; $coreReplacements['SUBMITCOMPLETE'] = "<strong>" . $clang->gT("Thank you!") . "<br /><br />" . $clang->gT("You have completed answering the questions in this survey.") . "</strong><br /><br />" . $clang->gT("Click on 'Submit' now to complete the process and save your answers."); $coreReplacements['SUBMITREVIEW'] = $_strreview; $coreReplacements['SURVEYCONTACT'] = $surveycontact; $coreReplacements['SURVEYDESCRIPTION'] = isset($thissurvey['description']) ? $thissurvey['description'] : ''; $coreReplacements['SURVEYFORMAT'] = isset($surveyformat) ? $surveyformat : ''; // global $coreReplacements['SURVEYLANGAGE'] = $clang->langcode; $coreReplacements['SURVEYLANGUAGE'] = $clang->langcode; $coreReplacements['SURVEYLIST'] = isset($surveylist) ? $surveylist['list'] : ''; $coreReplacements['SURVEYLISTHEADING'] = isset($surveylist) ? $surveylist['listheading'] : ''; $coreReplacements['SURVEYNAME'] = isset($thissurvey['name']) ? $thissurvey['name'] : ''; $coreReplacements['TEMPLATECSS'] = $_templatecss; $coreReplacements['TEMPLATEJS'] = $_templatejs; $coreReplacements['TEMPLATEURL'] = $templateurl; $coreReplacements['THEREAREXQUESTIONS'] = $_therearexquestions; if (!$anonymized) { $coreReplacements['TOKEN'] = $_token; } $coreReplacements['URL'] = $_linkreplace; $coreReplacements['WELCOME'] = isset($thissurvey['welcome']) ? $thissurvey['welcome'] : ''; if (!is_null($replacements) && is_array($replacements)) { $doTheseReplacements = array_merge($coreReplacements, $replacements); // so $replacements overrides core values } else { $doTheseReplacements = $coreReplacements; } // Now do all of the replacements - In rare cases, need to do 3 deep recursion, that that is default $line = LimeExpressionManager::ProcessString($line, $questionNum, $doTheseReplacements, false, 3, 1); return $line; }
private function _array_filter_help($qidattributes, $surveyprintlang, $surveyid) { $clang = $this->getController()->lang; $output = ""; if (!empty($qidattributes['array_filter'])) { $newquestiontext = Questions::model()->findByAttributes(array('title' => $qidattributes['array_filter'], 'language' => $surveyprintlang, 'sid' => $surveyid))->getAttribute('question'); $output .= "\n<p class='extrahelp'>\n " . sprintf($clang->gT("Only answer this question for the items you selected in question %s ('%s')"), $qidattributes['array_filter'], flattenText(breakToNewline($newquestiontext['question']))) . "\n </p>\n"; } if (!empty($qidattributes['array_filter_exclude'])) { $newquestiontext = Questions::model()->findByAttributes(array('title' => $qidattributes['array_filter_exclude'], 'language' => $surveyprintlang, 'sid' => $surveyid))->getAttribute('question'); $output .= "\n <p class='extrahelp'>\n " . sprintf($clang->gT("Only answer this question for the items you did not select in question %s ('%s')"), $qidattributes['array_filter_exclude'], breakToNewline($newquestiontext['question'])) . "\n </p>\n"; } return $output; }
function adduser() { if (!Yii::app()->session['USER_RIGHT_CREATE_USER']) { die(accessDenied('adduser')); } $clang = Yii::app()->lang; $new_user = flattenText(Yii::app()->request->getPost('new_user'), false, true); $new_email = flattenText(Yii::app()->request->getPost('new_email'), false, true); $new_full_name = flattenText(Yii::app()->request->getPost('new_full_name'), false, true); $aViewUrls = array(); $valid_email = true; if (!validateEmailAddress($new_email)) { $valid_email = false; $aViewUrls['message'] = array('title' => $clang->gT("Failed to add user"), 'message' => $clang->gT("The email address is not valid."), 'class' => 'warningheader'); } if (empty($new_user)) { $aViewUrls['message'] = array('title' => $clang->gT("Failed to add user"), 'message' => $clang->gT("A username was not supplied or the username is invalid."), 'class' => 'warningheader'); } elseif (User::model()->find("users_name='{$new_user}'")) { $aViewUrls['message'] = array('title' => $clang->gT("Failed to add user"), 'message' => $clang->gT("The username already exists."), 'class' => 'warningheader'); } elseif ($valid_email) { $new_pass = createPassword(); $iNewUID = User::model()->insertUser($new_user, $new_pass, $new_full_name, Yii::app()->session['loginID'], $new_email); if ($iNewUID) { // add default template to template rights for user Templates_rights::model()->insertRecords(array('uid' => $iNewUID, 'folder' => 'default', 'use' => '1')); // add new user to userlist $sresult = User::model()->getAllRecords(array('uid' => $iNewUID)); $srow = count($sresult); $userlist = getUserList(); array_push($userlist, array("user" => $srow['users_name'], "uid" => $srow['uid'], "email" => $srow['email'], "password" => $srow["password"], "parent_id" => $srow['parent_id'], "create_survey" => $srow['create_survey'], "participant_panel" => $srow['participant_panel'], "configurator" => $srow['configurator'], "create_user" => $srow['create_user'], "delete_user" => $srow['delete_user'], "superadmin" => $srow['superadmin'], "manage_template" => $srow['manage_template'], "manage_label" => $srow['manage_label'])); // send Mail $body = sprintf($clang->gT("Hello %s,"), $new_full_name) . "<br /><br />\n"; $body .= sprintf($clang->gT("this is an automated email to notify that a user has been created for you on the site '%s'."), Yii::app()->getConfig("sitename")) . "<br /><br />\n"; $body .= $clang->gT("You can use now the following credentials to log into the site:") . "<br />\n"; $body .= $clang->gT("Username") . ": " . $new_user . "<br />\n"; if (Yii::app()->getConfig("useWebserverAuth") === false) { // authent is not delegated to web server // send password (if authorized by config) if (Yii::app()->getConfig("display_user_password_in_email") === true) { $body .= $clang->gT("Password") . ": " . $new_pass . "<br />\n"; } else { $body .= $clang->gT("Password") . ": " . $clang->gT("Please ask your password to your LimeSurvey administrator") . "<br />\n"; } } $body .= "<a href='" . $this->getController()->createAbsoluteUrl("/admin") . "'>" . $clang->gT("Click here to log in.") . "</a><br /><br />\n"; $body .= sprintf($clang->gT('If you have any questions regarding this mail please do not hesitate to contact the site administrator at %s. Thank you!'), Yii::app()->getConfig("siteadminemail")) . "<br />\n"; $subject = sprintf($clang->gT("User registration at '%s'", "unescaped"), Yii::app()->getConfig("sitename")); $to = $new_user . " <{$new_email}>"; $from = Yii::app()->getConfig("siteadminname") . " <" . Yii::app()->getConfig("siteadminemail") . ">"; $extra = ''; $classMsg = ''; if (SendEmailMessage($body, $subject, $to, $from, Yii::app()->getConfig("sitename"), true, Yii::app()->getConfig("siteadminbounce"))) { $extra .= "<br />" . $clang->gT("Username") . ": {$new_user}<br />" . $clang->gT("Email") . ": {$new_email}<br />"; $extra .= "<br />" . $clang->gT("An email with a generated password was sent to the user."); $classMsg = 'successheader'; $sHeader = $clang->gT("Success"); } else { // has to be sent again or no other way $tmp = str_replace("{NAME}", "<strong>" . $new_user . "</strong>", $clang->gT("Email to {NAME} ({EMAIL}) failed.")); $extra .= "<br />" . str_replace("{EMAIL}", $new_email, $tmp) . "<br />"; $classMsg = 'warningheader'; $sHeader = $clang->gT("Warning"); } $aViewUrls['mboxwithredirect'][] = $this->_messageBoxWithRedirect($clang->gT("Add user"), $sHeader, $classMsg, $extra, $this->getController()->createUrl("admin/user/setUserRights"), $clang->gT("Set user permissions"), array('action' => 'setUserRights', 'user' => $new_user, 'uid' => $iNewUID)); } else { $aViewUrls['mboxwithredirect'][] = $this->_messageBoxWithRedirect($clang->gT("Failed to add user"), $clang->gT("The user name already exists."), 'warningheader'); } } $this->_renderWrappedTemplate('user', $aViewUrls); }
$_REQUEST['assessments'] = 'Y'; } } $clang = Yii::app()->lang; Yii::app()->loadHelper('frontend'); if (empty($_REQUEST['sid'])) // || count($_REQUEST) == 0) { { $query = "select a.surveyls_survey_id as sid, a.surveyls_title as title, b.datecreated, b.assessments " . "from {{surveys_languagesettings}} as a join {{surveys}} as b on a.surveyls_survey_id = b.sid" . " where a.surveyls_language='en' order by a.surveyls_title, b.datecreated"; $data = dbExecuteAssoc($query); $surveyList=''; foreach($data->readAll() as $row) { $surveyList .= "<option value='" . $row['sid'] .'|' . $row['assessments'] . "'>#" . $row['sid'] . " [" . $row['datecreated'] . '] ' . flattenText($row['title']) . "</option>\n"; } $url = $this->createUrl('admin/expressions/survey_logic_file'); $form = <<< EOD <form method='post' action='$url'> <h3>Generate a logic file for the survey</h3> <table border='1'> <tr><th>Parameter</th><th>Value</th></tr> <tr><td>Survey ID (SID)</td> <td><select name='sid' id='sid'> $surveyList </select></td></tr> <tr><td>Debug Log Level</td> <td> Specify which debugging features to use <ul>
/** * checks questions in a survey for consistency * @param <type> $postsid * @param <type> $iSurveyID * @return array $faildcheck */ function checkQuestions($postsid, $iSurveyID, $qtypes) { //CHECK TO MAKE SURE ALL QUESTION TYPES THAT REQUIRE ANSWERS HAVE ACTUALLY GOT ANSWERS //THESE QUESTION TYPES ARE: // # "L" -> LIST // # "O" -> LIST WITH COMMENT // # "M" -> Multiple choice // # "P" -> Multiple choice with comments // # "A", "B", "C", "E", "F", "H", "^" -> Various Array Types // # "R" -> RANKING // # "U" -> FILE CSV MORE // # "I" -> LANGUAGE SWITCH // # ":" -> Array Multi Flexi Numbers // # ";" -> Array Multi Flexi Text // # "1" -> MULTI SCALE $chkquery = "SELECT qid, question, gid, type FROM {{questions}} WHERE sid={$iSurveyID} and parent_qid=0"; $chkresult = Yii::app()->db->createCommand($chkquery)->query()->readAll(); foreach ($chkresult as $chkrow) { if ($qtypes[$chkrow['type']]['subquestions'] > 0) { for ($i = 0; $i < $qtypes[$chkrow['type']]['subquestions']; $i++) { $chaquery = "SELECT * FROM {{questions}} WHERE parent_qid = {$chkrow['qid']} and scale_id={$i} ORDER BY question_order"; $charesult = Yii::app()->db->createCommand($chaquery)->query()->readAll(); $chacount = count($charesult); if ($chacount == 0) { $failedcheck[] = array($chkrow['qid'], flattenText($chkrow['question'], true, true, 'utf-8', true), ": " . gT("This question has missing subquestions."), $chkrow['gid']); } } } if ($qtypes[$chkrow['type']]['answerscales'] > 0) { for ($i = 0; $i < $qtypes[$chkrow['type']]['answerscales']; $i++) { $chaquery = "SELECT * FROM {{answers}} WHERE qid = {$chkrow['qid']} and scale_id={$i} ORDER BY sortorder, answer"; $charesult = Yii::app()->db->createCommand($chaquery)->query()->readAll(); $chacount = count($charesult); if ($chacount == 0) { $failedcheck[] = array($chkrow['qid'], flattenText($chkrow['question'], true, true, 'utf-8', true), ": " . gT("This question has missing answer options."), $chkrow['gid']); } } } } //NOW CHECK THAT ALL QUESTIONS HAVE A 'QUESTION TYPE' FIELD SET $chkquery = "SELECT qid, question, gid FROM {{questions}} WHERE sid={$iSurveyID} AND type = ''"; $chkresult = Yii::app()->db->createCommand($chkquery)->query()->readAll(); foreach ($chkresult as $chkrow) { $failedcheck[] = array($chkrow['qid'], $chkrow['question'], ": " . gT("This question does not have a question 'type' set."), $chkrow['gid']); } //Check that certain array question types have answers set $chkquery = "SELECT q.qid, question, gid FROM {{questions}} as q WHERE (select count(*) from {{answers}} as a where a.qid=q.qid and scale_id=0)=0 and sid={$iSurveyID} AND type IN ('F', 'H', 'W', 'Z', '1') and q.parent_qid=0"; $chkresult = Yii::app()->db->createCommand($chkquery)->query()->readAll(); foreach ($chkresult as $chkrow) { $failedcheck[] = array($chkrow['qid'], $chkrow['question'], ": " . gT("This question requires answers, but none are set."), $chkrow['gid']); } // while //CHECK THAT DUAL Array has answers set $chkquery = "SELECT q.qid, question, gid FROM {{questions}} as q WHERE (select count(*) from {{answers}} as a where a.qid=q.qid and scale_id=1)=0 and sid={$iSurveyID} AND type='1' and q.parent_qid=0"; $chkresult = Yii::app()->db->createCommand($chkquery)->query()->readAll(); foreach ($chkresult as $chkrow) { $failedcheck[] = array($chkrow['qid'], $chkrow['question'], ": " . gT("This question requires a second answer set but none is set."), $chkrow['gid']); } // while //TO AVOID NATURAL SORT ORDER ISSUES, FIRST GET ALL QUESTIONS IN NATURAL SORT ORDER, AND FIND OUT WHICH NUMBER IN THAT ORDER THIS QUESTION IS $qorderquery = "SELECT * FROM {{questions}} WHERE sid={$iSurveyID} AND type not in ('S', 'D', 'T', 'Q')"; $qorderresult = Yii::app()->db->createCommand($qorderquery)->query()->readAll(); $qrows = array(); //Create an empty array in case FetchRow does not return any rows foreach ($qorderresult as $qrow) { $qrows[] = $qrow; } // Get table output into array usort($qrows, 'groupOrderThenQuestionOrder'); // Perform a case insensitive natural sort on group name then question title of a multidimensional array $c = 0; foreach ($qrows as $qr) { $qidorder[] = array($c, $qrow['qid']); $c++; } $qordercount = ""; //1: Get each condition's question id $conquery = "SELECT {{conditions}}.qid, cqid, {{questions}}.question, " . "{{questions}}.gid " . "FROM {{conditions}}, {{questions}}, {{groups}} " . "WHERE {{questions}}.sid={$iSurveyID} " . "AND {{conditions}}.qid={{questions}}.qid " . "AND {{questions}}.gid={{groups}}.gid ORDER BY {{conditions}}.qid"; $conresult = Yii::app()->db->createCommand($conquery)->query()->readAll(); //2: Check each conditions cqid that it occurs later than the cqid foreach ($conresult as $conrow) { $cqidfound = 0; $qidfound = 0; $b = 0; while ($b < $qordercount) { if ($conrow['cqid'] == $qidorder[$b][1]) { $cqidfound = 1; $b = $qordercount; } if ($conrow['qid'] == $qidorder[$b][1]) { $qidfound = 1; $b = $qordercount; } if ($qidfound == 1) { $failedcheck[] = array($conrow['qid'], $conrow['question'], ": " . gT("This question has a condition set, however the condition is based on a question that appears after it."), $conrow['gid']); } $b++; } } //CHECK THAT ALL THE CREATED FIELDS WILL BE UNIQUE $fieldmap = createFieldMap($iSurveyID, 'full', true, false, getBaseLanguageFromSurveyID($iSurveyID), $aDuplicateQIDs); if (count($aDuplicateQIDs)) { foreach ($aDuplicateQIDs as $iQID => $aDuplicate) { $sFixLink = "[<a href='" . Yii::app()->getController()->createUrl("/admin/survey/sa/activate/surveyid/{$iSurveyID}/fixnumbering/{$iQID}") . "'>Click here to fix</a>]"; $failedcheck[] = array($iQID, $aDuplicate['question'], ": Bad duplicate fieldname {$sFixLink}", $aDuplicate['gid']); } } if (isset($failedcheck)) { return $failedcheck; } else { return false; } }
?> </td> </tr> <?php if (trim($surveyinfo['faxto']) != '') { ?> <tr> <td> <strong><?php $clang->eT("Fax to:"); ?> </strong> </td> <td> <?php echo flattenText($surveyinfo['faxto']); ?> </td> </tr> <?php } ?> <tr> <td> <strong><?php $clang->eT("Start date/time:"); ?> </strong> </td> <td> <?php