本文整理汇总了PHP中createFieldMap函数的典型用法代码示例。如果您正苦于以下问题:PHP createFieldMap函数的具体用法?PHP createFieldMap怎么用?PHP createFieldMap使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了createFieldMap函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: index
public function index()
{
$surveyid = intval(App()->request->getQuery('surveyid'));
$gid = intval(App()->request->getQuery('gid'));
$qid = intval(App()->request->getQuery('qid'));
$fieldtype = sanitize_xss_string(App()->request->getQuery('fieldtype'));
$action = sanitize_xss_string(App()->request->getQuery('action'));
if (!Yii::app()->session['loginID']) {
throw new CHttpException(401);
}
list($replacementFields, $isInstertAnswerEnabled) = $this->_getReplacementFields($fieldtype, $surveyid);
if ($isInstertAnswerEnabled === true) {
//2: Get all other questions that occur before this question that are pre-determined answer types
$fieldmap = createFieldMap($surveyid, 'full', false, false, getBaseLanguageFromSurveyID($surveyid));
$surveyInfo = getSurveyInfo($surveyid);
$surveyformat = $surveyInfo['format'];
// S, G, A
//Go through each question until we reach the current one
//error_log(print_r($qrows,true));
$questionlist = $this->_getQuestionList($action, $gid, $qid, $fieldmap, $fieldtype, $surveyformat);
$childQuestions = $this->_getChildQuestions($questionlist);
}
$data['countfields'] = count($replacementFields);
$data['replFields'] = $replacementFields;
if (isset($childQuestions)) {
$data['cquestions'] = $childQuestions;
}
if (isset($surveyformat)) {
$data['surveyformat'] = $surveyformat;
}
$this->getController()->render('/admin/limeReplacementFields_view', $data);
}
示例2: loadSurveyById
/**
* Loads a survey from the database that has the given ID. If no matching
* survey is found then null is returned. Note that no results are loaded
* from this function call, only survey structure/definition.
*
* In the future it would be nice to load all languages from the db at
* once and have the infrastructure be able to return responses based
* on language codes.
*
* @param int $id
* @return SurveyObj
*/
public function loadSurveyById($id, $lang = null)
{
$survey = new SurveyObj();
$clang = Yii::app()->lang;
$intId = sanitize_int($id);
$survey->id = $intId;
$survey->info = getSurveyInfo($survey->id);
$availableLanguages = Survey::model()->findByPk($intId)->getAllLanguages();
if (is_null($lang) || in_array($lang, $availableLanguages) === false) {
// use base language when requested language is not found or no specific language is requested
$lang = Survey::model()->findByPk($intId)->language;
}
$clang = new limesurvey_lang($lang);
$survey->fieldMap = createFieldMap($intId, 'full', true, false, $lang);
// Check to see if timings are present and add to fieldmap if needed
if ($survey->info['savetimings'] == "Y") {
$survey->fieldMap = $survey->fieldMap + createTimingsFieldMap($intId, 'full', true, false, $lang);
}
if (empty($intId)) {
//The id given to us is not an integer, croak.
safeDie("An invalid survey ID was encountered: {$sid}");
}
//Load groups
$sQuery = 'SELECT g.* FROM {{groups}} AS g ' . 'WHERE g.sid = ' . $intId . ' AND g.language = \'' . $lang . '\' ' . 'ORDER BY g.group_order;';
$recordSet = Yii::app()->db->createCommand($sQuery)->query()->readAll();
$survey->groups = $recordSet;
//Load questions
$sQuery = 'SELECT q.* FROM {{questions}} AS q ' . 'JOIN {{groups}} AS g ON (q.gid = g.gid and q.language = g.language) ' . 'WHERE q.sid = ' . $intId . ' AND q.language = \'' . $lang . '\' ' . 'ORDER BY g.group_order, q.question_order;';
$survey->questions = Yii::app()->db->createCommand($sQuery)->query()->readAll();
//Load answers
$sQuery = 'SELECT DISTINCT a.* FROM {{answers}} AS a ' . 'JOIN {{questions}} AS q ON a.qid = q.qid ' . 'WHERE q.sid = ' . $intId . ' AND a.language = \'' . $lang . '\' ' . 'ORDER BY a.qid, a.sortorder;';
//$survey->answers = Yii::app()->db->createCommand($sQuery)->queryAll();
$aAnswers = Yii::app()->db->createCommand($sQuery)->queryAll();
foreach ($aAnswers as $aAnswer) {
if (Yii::app()->controller->action->id != 'remotecontrol') {
$aAnswer['answer'] = stripTagsFull($aAnswer['answer']);
}
$survey->answers[$aAnswer['qid']][$aAnswer['scale_id']][$aAnswer['code']] = $aAnswer;
}
//Load language settings for requested language
$sQuery = 'SELECT * FROM {{surveys_languagesettings}} WHERE surveyls_survey_id = ' . $intId . ' AND surveyls_language = \'' . $lang . '\';';
$recordSet = Yii::app()->db->createCommand($sQuery)->query();
$survey->languageSettings = $recordSet->read();
$recordSet->close();
if (tableExists('tokens_' . $survey->id) && array_key_exists('token', SurveyDynamic::model($survey->id)->attributes) && Permission::model()->hasSurveyPermission($survey->id, 'tokens', 'read')) {
// Now add the tokenFields
$survey->tokenFields = getTokenFieldsAndNames($survey->id);
unset($survey->tokenFields['token']);
}
return $survey;
}
示例3: index
public function index()
{
if (isset($_GET['surveyid'])) {
$surveyid = sanitize_int($_GET['surveyid']);
}
if (isset($_GET['gid'])) {
$gid = sanitize_int($_GET['gid']);
}
if (isset($_GET['qid'])) {
$qid = sanitize_int($_GET['qid']);
}
if (isset($_GET['fieldtype'])) {
$fieldtype = $_GET['fieldtype'];
}
if (isset($_GET['action'])) {
$action = $_GET['action'];
}
$clang = Yii::app()->lang;
if (!Yii::app()->session['loginID']) {
die("Unauthenticated Access Forbiden");
}
list($replacementFields, $isInstertAnswerEnabled) = $this->_getReplacementFields($fieldtype, $surveyid);
if ($isInstertAnswerEnabled === true) {
if (empty($surveyid)) {
safeDie("No SID provided.");
}
//2: Get all other questions that occur before this question that are pre-determined answer types
$fieldmap = createFieldMap($surveyid, 'full', false, false, getBaseLanguageFromSurveyID($surveyid));
$surveyInfo = getSurveyInfo($surveyid);
$surveyformat = $surveyInfo['format'];
// S, G, A
//Go through each question until we reach the current one
//error_log(print_r($qrows,true));
$questionlist = $this->_getQuestionList($action, $gid, $qid, $fieldmap, $fieldtype, $surveyformat);
$childQuestions = $this->_getChildQuestions($questionlist);
}
$data['countfields'] = count($replacementFields);
$data['replFields'] = $replacementFields;
$data['clang'] = $clang;
if (isset($childQuestions)) {
$data['cquestions'] = $childQuestions;
}
if (isset($surveyformat)) {
$data['surveyformat'] = $surveyformat;
}
$this->getController()->render('/admin/limeReplacementFields_view', $data);
}
示例4: insert
//.........这里部分代码省略.........
$aData['save'] = TRUE;
$saver['identifier'] = $_POST['save_identifier'];
$saver['language'] = $_POST['save_language'];
$saver['password'] = $_POST['save_password'];
$saver['passwordconfirm'] = $_POST['save_confirmpassword'];
$saver['email'] = $_POST['save_email'];
if (!returnGlobal('redo')) {
$password = md5($saver['password']);
} else {
$password = $saver['password'];
}
$errormsg = "";
if (!$saver['identifier']) {
$errormsg .= $clang->gT("Error") . ": " . $clang->gT("You must supply a name for this saved session.");
}
if (!$saver['password']) {
$errormsg .= $clang->gT("Error") . ": " . $clang->gT("You must supply a password for this saved session.");
}
if ($saver['password'] != $saver['passwordconfirm']) {
$errormsg .= $clang->gT("Error") . ": " . $clang->gT("Your passwords do not match.");
}
$aData['errormsg'] = $errormsg;
if ($errormsg) {
foreach ($_POST as $key => $val) {
if (substr($key, 0, 4) != "save" && $key != "action" && $key != "sid" && $key != "datestamp" && $key != "ipaddr") {
$hiddenfields .= CHtml::hiddenField($key, $val);
//$aDataentryoutput .= "<input type='hidden' name='$key' value='$val' />\n";
}
}
}
}
//BUILD THE SQL TO INSERT RESPONSES
$baselang = Survey::model()->findByPk($surveyid)->language;
$fieldmap = createFieldMap($surveyid, 'full', false, false, getBaseLanguageFromSurveyID($surveyid));
$insert_data = array();
$_POST['startlanguage'] = $baselang;
if ($thissurvey['datestamp'] == "Y") {
$_POST['startdate'] = $_POST['datestamp'];
}
if (isset($_POST['closerecord'])) {
if ($thissurvey['datestamp'] == "Y") {
$_POST['submitdate'] = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", Yii::app()->getConfig('timeadjust'));
} else {
$_POST['submitdate'] = date("Y-m-d H:i:s", mktime(0, 0, 0, 1, 1, 1980));
}
}
foreach ($fieldmap as $irow) {
$fieldname = $irow['fieldname'];
if (isset($_POST[$fieldname])) {
if ($_POST[$fieldname] == "" && ($irow['type'] == 'D' || $irow['type'] == 'N' || $irow['type'] == 'K')) {
// can't add '' in Date column
// Do nothing
} else {
if ($irow['type'] == '|') {
if (!strpos($irow['fieldname'], "_filecount")) {
$json = $_POST[$fieldname];
$phparray = json_decode(stripslashes($json));
$filecount = 0;
for ($i = 0; $filecount < count($phparray); $i++) {
if ($_FILES[$fieldname . "_file_" . $i]['error'] != 4) {
$target = Yii::app()->getConfig('uploaddir') . "/surveys/" . $thissurvey['sid'] . "/files/" . randomChars(20);
$size = 0.001 * $_FILES[$fieldname . "_file_" . $i]['size'];
$name = rawurlencode($_FILES[$fieldname . "_file_" . $i]['name']);
if (move_uploaded_file($_FILES[$fieldname . "_file_" . $i]['tmp_name'], $target)) {
$phparray[$filecount]->filename = basename($target);
$phparray[$filecount]->name = $name;
示例5: bHasFileUploadQuestion
/**
* Returns true if the given survey has a File Upload Question Type
* @param $surveyid The survey ID
* @return bool
*/
function bHasFileUploadQuestion($surveyid)
{
$fieldmap = createFieldMap($surveyid);
foreach ($fieldmap as $field) {
if (isset($field['type']) && $field['type'] === '|') {
return true;
}
}
}
示例6: getFullResponseTable
/**
* Creates an array with details on a particular response for display purposes
* Used in Print answers, Detailed response view and Detailed admin notification email
*
* @param mixed $iSurveyID
* @param mixed $iResponseID
* @param mixed $sLanguageCode
* @param boolean $bHonorConditions Apply conditions
*/
function getFullResponseTable($iSurveyID, $iResponseID, $sLanguageCode, $bHonorConditions = true)
{
$aFieldMap = createFieldMap($iSurveyID, 'full', false, false, $sLanguageCode);
//Get response data
$idrow = SurveyDynamic::model($iSurveyID)->findByAttributes(array('id' => $iResponseID));
// Create array of non-null values - those are the relevant ones
$aRelevantFields = array();
foreach ($aFieldMap as $sKey => $fname) {
if (LimeExpressionManager::QuestionIsRelevant($fname['qid']) || $bHonorConditions == false) {
$aRelevantFields[$sKey] = $fname;
}
}
$aResultTable = array();
$oldgid = 0;
$oldqid = 0;
foreach ($aRelevantFields as $sKey => $fname) {
if (!empty($fname['qid'])) {
$attributes = getQuestionAttributeValues($fname['qid']);
if (getQuestionAttributeValue($attributes, 'hidden') == 1) {
continue;
}
}
$question = $fname['question'];
$subquestion = '';
if (isset($fname['gid']) && !empty($fname['gid'])) {
//Check to see if gid is the same as before. if not show group name
if ($oldgid !== $fname['gid']) {
$oldgid = $fname['gid'];
if (LimeExpressionManager::GroupIsRelevant($fname['gid']) || $bHonorConditions == false) {
$aResultTable['gid_' . $fname['gid']] = array($fname['group_name'], QuestionGroup::model()->getGroupDescription($fname['gid'], $sLanguageCode));
}
}
}
if (!empty($fname['qid'])) {
if ($oldqid !== $fname['qid']) {
$oldqid = $fname['qid'];
if (isset($fname['subquestion']) || isset($fname['subquestion1']) || isset($fname['subquestion2'])) {
$aResultTable['qid_' . $fname['sid'] . 'X' . $fname['gid'] . 'X' . $fname['qid']] = array($fname['question'], '', '');
} else {
$answer = getExtendedAnswer($iSurveyID, $fname['fieldname'], $idrow[$fname['fieldname']], $sLanguageCode);
$aResultTable[$fname['fieldname']] = array($question, '', $answer);
continue;
}
}
} else {
$answer = getExtendedAnswer($iSurveyID, $fname['fieldname'], $idrow[$fname['fieldname']], $sLanguageCode);
$aResultTable[$fname['fieldname']] = array($question, '', $answer);
continue;
}
if (isset($fname['subquestion'])) {
$subquestion = "[{$fname['subquestion']}]";
}
if (isset($fname['subquestion1'])) {
$subquestion = "[{$fname['subquestion1']}]";
}
if (isset($fname['subquestion2'])) {
$subquestion .= "[{$fname['subquestion2']}]";
}
$answer = getExtendedAnswer($iSurveyID, $fname['fieldname'], $idrow[$fname['fieldname']], $sLanguageCode);
$aResultTable[$fname['fieldname']] = array($question, $subquestion, $answer);
}
return $aResultTable;
}
示例7: export_responses_by_token
/**
* RPC Routine to export token response in a survey.
* Returns the requested file as base64 encoded string
*
* @access public
* @param string $sSessionKey Auth credentials
* @param int $iSurveyID Id of the Survey
* @param string $sDocumentType pdf,csv,xls,doc,json
* @param string $sToken The token for which responses needed
* @param string $sLanguageCode The language to be used
* @param string $sCompletionStatus Optional 'complete','incomplete' or 'all' - defaults to 'all'
* @param string $sHeadingType 'code','full' or 'abbreviated' Optional defaults to 'code'
* @param string $sResponseType 'short' or 'long' Optional defaults to 'short'
* @param array $aFields Optional Selected fields
* @return array|string On success: Requested file as base 64-encoded string. On failure array with error information
*
*/
public function export_responses_by_token($sSessionKey, $iSurveyID, $sDocumentType, $sToken, $sLanguageCode = null, $sCompletionStatus = 'all', $sHeadingType = 'code', $sResponseType = 'short', $aFields = null)
{
if (!$this->_checkSessionKey($sSessionKey)) {
return array('status' => 'Invalid session key');
}
Yii::app()->loadHelper('admin/exportresults');
if (!tableExists('{{survey_' . $iSurveyID . '}}')) {
return array('status' => 'No Data, survey table does not exist.');
}
if (!($maxId = SurveyDynamic::model($iSurveyID)->getMaxId())) {
return array('status' => 'No Data, could not get max id.');
}
if (!empty($sLanguageCode) && !in_array($sLanguageCode, Survey::model()->findByPk($iSurveyID)->getAllLanguages())) {
return array('status' => 'Language code not found for this survey.');
}
if (!SurveyDynamic::model($iSurveyID)->findByAttributes(array('token' => $sToken))) {
return array('status' => 'No Response found for Token');
}
if (!Permission::model()->hasSurveyPermission($iSurveyID, 'responses', 'export')) {
return array('status' => 'No permission');
}
if (empty($sLanguageCode)) {
$sLanguageCode = getBaseLanguageFromSurveyID($iSurveyID);
}
if (is_null($aFields)) {
$aFields = array_keys(createFieldMap($iSurveyID, 'full', true, false, $sLanguageCode));
}
if ($sDocumentType == 'xls') {
// Cut down to the first 255 fields
$aFields = array_slice($aFields, 0, 255);
}
$oFormattingOptions = new FormattingOptions();
$oFormattingOptions->responseMinRecord = 1;
$oFormattingOptions->responseMaxRecord = $maxId;
$oFormattingOptions->selectedColumns = $aFields;
$oFormattingOptions->responseCompletionState = $sCompletionStatus;
$oFormattingOptions->headingFormat = $sHeadingType;
$oFormattingOptions->answerFormat = $sResponseType;
$oFormattingOptions->output = 'file';
$oExport = new ExportSurveyResultsService();
$sTableName = Yii::app()->db->tablePrefix . 'survey_' . $iSurveyID;
$sTempFile = $oExport->exportSurvey($iSurveyID, $sLanguageCode, $sDocumentType, $oFormattingOptions, "{$sTableName}.token='{$sToken}'");
return new BigFile($sTempFile, true, 'base64');
}
示例8: activateSurvey
/**
* Function to activate a survey
* @param int $iSurveyID The Survey ID
* @param bool $simulate
* @return string
*/
function activateSurvey($iSurveyID, $simulate = false)
{
$createsurvey = '';
$activateoutput = '';
$createsurveytimings = '';
$fieldstiming = array();
$createsurveydirectory = false;
//Check for any additional fields for this survey and create necessary fields (token and datestamp)
$prow = Survey::model()->findByAttributes(array('sid' => $iSurveyID));
//Get list of questions for the base language
$fieldmap = createFieldMap($iSurveyID, 'full', true, false, getBaseLanguageFromSurveyID($iSurveyID));
$createsurvey = array();
foreach ($fieldmap as $j => $arow) {
switch ($arow['type']) {
case 'startlanguage':
$createsurvey[$arow['fieldname']] = "VARCHAR(20) NOT NULL";
break;
case 'id':
$createsurvey[$arow['fieldname']] = "pk";
break;
case "startdate":
case "datestamp":
$createsurvey[$arow['fieldname']] = "datetime NOT NULL";
break;
case "submitdate":
$createsurvey[$arow['fieldname']] = "datetime";
break;
case "lastpage":
$createsurvey[$arow['fieldname']] = "integer";
break;
case "N":
//NUMERICAL
$createsurvey[$arow['fieldname']] = "decimal (30,10)";
break;
case "S":
//SHORT TEXT
if (Yii::app()->db->driverName == 'mysql' || Yii::app()->db->driverName == 'mysqli') {
$createsurvey[$arow['fieldname']] = "text";
} else {
$createsurvey[$arow['fieldname']] = "string";
}
break;
case "L":
//LIST (RADIO)
//LIST (RADIO)
case "!":
//LIST (DROPDOWN)
//LIST (DROPDOWN)
case "M":
//Multiple choice
//Multiple choice
case "P":
//Multiple choice with comment
//Multiple choice with comment
case "O":
//DROPDOWN LIST WITH COMMENT
if ($arow['aid'] != 'other' && strpos($arow['aid'], 'comment') === false && strpos($arow['aid'], 'othercomment') === false) {
$createsurvey[$arow['fieldname']] = "VARCHAR(5)";
} else {
$createsurvey[$arow['fieldname']] = "text";
}
break;
case "K":
// Multiple Numerical
$createsurvey[$arow['fieldname']] = "float";
break;
case "U":
//Huge text
//Huge text
case "Q":
//Multiple short text
//Multiple short text
case "T":
//LONG TEXT
//LONG TEXT
case ";":
//Multi Flexi
//Multi Flexi
case ":":
//Multi Flexi
$createsurvey[$arow['fieldname']] = "text";
break;
case "D":
//DATE
$createsurvey[$arow['fieldname']] = "datetime";
break;
case "5":
//5 Point Choice
//5 Point Choice
case "G":
//Gender
//Gender
case "Y":
//YesNo
//.........这里部分代码省略.........
示例9: getResponse
/**
* Gets a survey response from the database.
*
* @param int $surveyId
* @param int $responseId
*/
public function getResponse($surveyId, $responseId)
{
$response = SurveyDynamic::model($surveyId)->findByPk($responseId)->attributes;
// Now map the response to the question codes if possible, duplicate question codes will result in the
// old sidXgidXqid code for the second time the code is found
$fieldmap = createFieldMap($surveyId, 'full', null, false, $response['startlanguage']);
$output = array();
foreach ($response as $key => $value) {
$newKey = $key;
if (array_key_exists($key, $fieldmap)) {
if (array_key_exists('title', $fieldmap[$key])) {
$code = $fieldmap[$key]['title'];
// Add subquestion code if needed
if (array_key_exists('aid', $fieldmap[$key]) && isset($fieldmap[$key]['aid']) && $fieldmap[$key]['aid'] != '') {
$code .= '_' . $fieldmap[$key]['aid'];
}
// Only add if the code does not exist yet and is not empty
if (!empty($code) && !array_key_exists($code, $output)) {
$newKey = $code;
}
}
}
$output[$newKey] = $value;
}
// And return the mapped response, to further enhance we could add a method to the api that provides a
// simple sort of fieldmap that returns qcode index array with group, question, subquestion,
// possible answers, maybe even combined with relevance info so a plugin can handle display of the response
return $output;
}
示例10: run
//.........这里部分代码省略.........
doHeader();
echo $content;
}
$redata['completed'] = $completed;
echo templatereplace(file_get_contents($sTemplatePath . "completed.pstpl"), array('completed' => $completed), $redata);
echo "\n<br />\n";
if (($LEMdebugLevel & LEM_DEBUG_TIMING) == LEM_DEBUG_TIMING) {
echo LimeExpressionManager::GetDebugTimingMessage();
}
if (($LEMdebugLevel & LEM_DEBUG_VALIDATION_SUMMARY) == LEM_DEBUG_VALIDATION_SUMMARY) {
echo "<table><tr><td align='left'><b>Group/Question Validation Results:</b>" . $moveResult['message'] . "</td></tr></table>\n";
}
echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"));
doFooter();
// The session cannot be killed until the page is completely rendered
if ($thissurvey['printanswers'] != 'Y') {
killSurveySession($surveyid);
}
exit;
}
}
$redata = compact(array_keys(get_defined_vars()));
// IF GOT THIS FAR, THEN DISPLAY THE ACTIVE GROUP OF QUESTIONSs
//SEE IF $surveyid EXISTS ####################################################################
if ($surveyExists < 1) {
//SURVEY DOES NOT EXIST. POLITELY EXIT.
echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata);
echo "\t<center><br />\n";
echo "\t" . $clang->gT("Sorry. There is no matching survey.") . "<br /></center> \n";
echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata);
doFooter();
exit;
}
createFieldMap($surveyid, 'full', false, false, $_SESSION[$LEMsessid]['s_lang']);
//GET GROUP DETAILS
if ($surveyMode == 'group' && $previewgrp) {
// setcookie("limesurvey_timers", "0"); //@todo fix - sometimes results in headers already sent error
$_gid = sanitize_int($param['gid']);
LimeExpressionManager::StartSurvey($thissurvey['sid'], 'group', $surveyOptions, false, $LEMdebugLevel);
$gseq = LimeExpressionManager::GetGroupSeq($_gid);
if ($gseq == -1) {
echo $clang->gT('Invalid group number for this survey: ') . $_gid;
exit;
}
$moveResult = LimeExpressionManager::JumpTo($gseq + 1, true);
if (is_null($moveResult)) {
echo $clang->gT('This group contains no questions. You must add questions to this group before you can preview it');
exit;
}
if (isset($moveResult)) {
$_SESSION[$LEMsessid]['step'] = $moveResult['seq'] + 1;
// step is index base 1?
}
$stepInfo = LimeExpressionManager::GetStepIndexInfo($moveResult['seq']);
$gid = $stepInfo['gid'];
$groupname = $stepInfo['gname'];
$groupdescription = $stepInfo['gtext'];
} else {
if ($show_empty_group || !isset($_SESSION[$LEMsessid]['grouplist'])) {
$gid = -1;
// Make sure the gid is unused. This will assure that the foreach (fieldarray as ia) has no effect.
$groupname = $clang->gT("Submit your answers");
$groupdescription = $clang->gT("There are no more questions. Please press the <Submit> button to finish this survey.");
} else {
if ($surveyMode != 'survey') {
if ($previewquestion) {
示例11: zipFiles
/**
* Supply an array with the responseIds and all files will be added to the zip
* and it will be be spit out on success
*
* @param array $responseIds
* @return ZipArchive
*/
function zipFiles($responseIds, $zipfilename)
{
global $uploaddir, $surveyid, $surveytable;
require_once 'classes/pclzip/pclzip.lib.php';
$tmpdir = $uploaddir . "/surveys/" . $surveyid . "/files/";
$filelist = array();
$fieldmap = createFieldMap($surveyid, 'full');
foreach ($fieldmap as $field) {
if ($field['type'] == "|" && $field['aid'] !== 'filecount') {
$filequestion[] = $field['fieldname'];
}
}
$filequestion = array_map('db_quote_id', $filequestion);
$initquery = "SELECT " . implode(', ', $filequestion);
foreach ((array) $responseIds as $responseId) {
$responseId = (int) $responseId;
// sanitize the value
$query = $initquery . " FROM {$surveytable} WHERE id={$responseId}";
$filearray = db_execute_assoc($query) or safe_die("Could not download response<br />{$query}<br />" . $connect->ErrorMsg());
$metadata = array();
$filecount = 0;
while ($metadata = $filearray->FetchRow()) {
foreach ($metadata as $data) {
$phparray = json_decode($data, true);
if (is_array($phparray)) {
foreach ($phparray as $file) {
$filecount++;
$file['responseid'] = $responseId;
$file['name'] = rawurldecode($file['name']);
$file['index'] = $filecount;
/*
* Now add the file to the archive, prefix files with responseid_index to keep them
* unique. This way we can have 234_1_image1.gif, 234_2_image1.gif as it could be
* files from a different source with the same name.
*/
$filelist[] = array(PCLZIP_ATT_FILE_NAME => $tmpdir . $file['filename'], PCLZIP_ATT_FILE_NEW_FULL_NAME => sprintf("%05s_%02s_%s", $file['responseid'], $file['index'], $file['name']));
}
}
}
}
}
if (count($filelist) > 0) {
$zip = new PclZip($tmpdir . $zipfilename);
if ($zip->create($filelist) === 0) {
//Oops something has gone wrong!
}
if (file_exists($tmpdir . "/" . $zipfilename)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . basename($zipfilename));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($tmpdir . "/" . $zipfilename));
ob_clean();
flush();
readfile($tmpdir . "/" . $zipfilename);
unlink($tmpdir . "/" . $zipfilename);
exit;
}
}
}
示例12: oldbrowse
/**
* @deprecated
* */
function oldbrowse($iSurveyID)
{
$aData = $this->_getData($iSurveyID);
extract($aData);
$aViewUrls = array();
$sBrowseLanguage = $aData['language'];
$tokenRequest = Yii::app()->request->getParam('token', null);
/**
* fnames is used as informational array
* it containts
* $fnames[] = array(<dbfieldname>, <some strange title>, <questiontext>, <group_id>, <questiontype>);
*/
if (Permission::model()->hasSurveyPermission($iSurveyID, 'responses', 'read')) {
if (Yii::app()->request->getPost('sql')) {
$aViewUrls[] = 'browseallfiltered_view';
}
//add token to top of list if survey is not private
if ($aData['surveyinfo']['anonymized'] == "N" && tableExists('tokens_' . $iSurveyID)) {
if (Permission::model()->hasSurveyPermission($iSurveyID, 'tokens', 'read')) {
$fnames[] = array("token", gT("Token ID"), 'code' => 'token');
$fnames[] = array("firstname", gT("First name"), 'code' => 'firstname');
// or token:firstname ?
$fnames[] = array("lastname", gT("Last name"), 'code' => 'lastname');
$fnames[] = array("email", gT("Email"), 'code' => 'email');
}
}
$fnames[] = array("submitdate", gT("Completed"), gT("Completed"), "0", 'D');
$fields = createFieldMap($iSurveyID, 'full', false, false, $aData['language']);
foreach ($fields as $fielddetails) {
if ($fielddetails['fieldname'] == 'lastpage' || $fielddetails['fieldname'] == 'submitdate') {
continue;
}
$question = $fielddetails['question'];
if ($fielddetails['type'] != "|") {
if ($fielddetails['fieldname'] == 'lastpage' || $fielddetails['fieldname'] == 'submitdate' || $fielddetails['fieldname'] == 'token') {
continue;
}
// no headers for time data
if ($fielddetails['type'] == 'interview_time') {
continue;
}
if ($fielddetails['type'] == 'page_time') {
continue;
}
if ($fielddetails['type'] == 'answer_time') {
continue;
}
$fnames[] = array($fielddetails['fieldname'], viewHelper::getFieldText($fielddetails), 'code' => viewHelper::getFieldCode($fielddetails, array('LEMcompat' => true)));
} elseif ($fielddetails['aid'] !== 'filecount') {
$qidattributes = getQuestionAttributeValues($fielddetails['qid']);
for ($i = 0; $i < $qidattributes['max_num_of_files']; $i++) {
$filenum = sprintf(gT("File %s"), $i + 1);
if ($qidattributes['show_title'] == 1) {
$fnames[] = array($fielddetails['fieldname'], "{$filenum} - {$question} (" . gT('Title') . ")", 'code' => viewHelper::getFieldCode($fielddetails) . '(title)', "type" => "|", "metadata" => "title", "index" => $i);
}
if ($qidattributes['show_comment'] == 1) {
$fnames[] = array($fielddetails['fieldname'], "{$filenum} - {$question} (" . gT('Comment') . ")", 'code' => viewHelper::getFieldCode($fielddetails) . '(comment)', "type" => "|", "metadata" => "comment", "index" => $i);
}
$fnames[] = array($fielddetails['fieldname'], "{$filenum} - {$question} (" . gT('File name') . ")", 'code' => viewHelper::getFieldCode($fielddetails) . '(name)', "type" => "|", "metadata" => "name", "index" => $i);
$fnames[] = array($fielddetails['fieldname'], "{$filenum} - {$question} (" . gT('File size') . ")", 'code' => viewHelper::getFieldCode($fielddetails) . '(size)', "type" => "|", "metadata" => "size", "index" => $i);
//$fnames[] = array($fielddetails['fieldname'], "File ".($i+1)." - ".$fielddetails['question']."(extension)", "type"=>"|", "metadata"=>"ext", "index"=>$i);
}
} else {
$fnames[] = array($fielddetails['fieldname'], gT("File count"), 'code' => viewHelper::getFieldCode($fielddetails));
}
}
$fncount = count($fnames);
$start = (int) Yii::app()->request->getParam('start', 0);
$limit = (int) Yii::app()->request->getParam('limit', 50);
$order = Yii::app()->request->getParam('order', 'asc');
if (!$limit) {
$limit = 50;
}
$oCriteria = new CDbCriteria();
//Create the query
if ($aData['surveyinfo']['anonymized'] == "N" && tableExists("{{tokens_{$iSurveyID}}}") && Permission::model()->hasSurveyPermission($iSurveyID, 'tokens', 'read')) {
$oCriteria = SurveyDynamic::model($iSurveyID)->addTokenCriteria($oCriteria);
}
if (incompleteAnsFilterState() == "incomplete") {
$oCriteria->addCondition("submitdate IS NULL");
} elseif (incompleteAnsFilterState() == "complete") {
$oCriteria->addCondition("submitdate IS NOT NULL");
}
$dtcount = SurveyDynamic::model($iSurveyID)->count($oCriteria);
// or die("Couldn't get response data<br />");
if ($limit > $dtcount) {
$limit = $dtcount;
}
//NOW LETS SHOW THE DATA
if (Yii::app()->request->getPost('sql') && stripcslashes(Yii::app()->request->getPost('sql')) !== "" && Yii::app()->request->getPost('sql') != "NULL") {
$oCriteria->addCondition(stripcslashes(Yii::app()->request->getPost('sql')));
}
if (!is_null($tokenRequest)) {
$oCriteria->addCondition('t.token = ' . Yii::app()->db->quoteValue($tokenRequest));
}
$oCriteria->order = 'id ' . ($order == 'desc' ? 'desc' : 'asc');
$oCriteria->offset = $start;
//.........这里部分代码省略.........
示例13: setVariableAndTokenMappingsForExpressionManager
/**
* Create the arrays needed by ExpressionManager to process LimeSurvey strings.
* The long part of this function should only be called once per page display (e.g. only if $fieldMap changes)
*
* @param <integer> $surveyid
* @param <Boolean> $forceRefresh
* @param <Boolean> $anonymized
* @param <Boolean> $allOnOnePage - if true (like for survey_format), uses certain optimizations
* @return boolean - true if $fieldmap had been re-created, so ExpressionManager variables need to be re-set
*/
private function setVariableAndTokenMappingsForExpressionManager($surveyid, $forceRefresh = false, $anonymized = false, $allOnOnePage = false)
{
if (isset($_SESSION['LEMforceRefresh'])) {
unset($_SESSION['LEMforceRefresh']);
$forceRefresh = true;
} else {
if (!$forceRefresh && isset($this->knownVars) && !$this->sPreviewMode) {
return false;
// means that those variables have been cached and no changes needed
}
}
$now = microtime(true);
$this->em->SetSurveyMode($this->surveyMode);
// TODO - do I need to force refresh, or trust that createFieldMap will cache langauges properly?
$fieldmap = createFieldMap($surveyid, $style = 'full', $forceRefresh, false, $_SESSION['LEMlang']);
$this->sid = $surveyid;
$this->runtimeTimings[] = array(__METHOD__ . '.createFieldMap', microtime(true) - $now);
// LimeExpressionManager::ShowStackTrace();
$now = microtime(true);
if (!isset($fieldmap)) {
return false;
// implies an error occurred
}
$this->knownVars = array();
// mapping of VarName to Value
$this->qcode2sgqa = array();
$this->tempVars = array();
$this->qid2code = array();
// List of codes for each question - needed to know which to NULL if a question is irrelevant
$this->jsVar2qid = array();
$this->qcode2sgq = array();
$this->alias2varName = array();
$this->varNameAttr = array();
$this->questionId2questionSeq = array();
$this->questionId2groupSeq = array();
$this->questionSeq2relevance = array();
$this->groupId2groupSeq = array();
$this->qid2validationEqn = array();
$this->groupSeqInfo = array();
$this->gseq2relevanceStatus = array();
// Since building array of allowable answers, need to know preset values for certain question types
$presets = array();
$presets['G'] = array('M' => $this->gT("Male"), 'F' => $this->gT("Female"));
$presets['Y'] = array('Y' => $this->gT("Yes"), 'N' => $this->gT("No"));
$presets['C'] = array('Y' => $this->gT("Yes"), 'N' => $this->gT("No"), 'U' => $this->gT("Uncertain"));
$presets['E'] = array('I' => $this->gT("Increase"), 'S' => $this->gT("Same"), 'D' => $this->gT("Decrease"));
$this->gseq2info = $this->getGroupInfoForEM($surveyid, $_SESSION['LEMlang']);
foreach ($this->gseq2info as $aGroupInfo) {
$this->groupId2groupSeq[$aGroupInfo['gid']] = $aGroupInfo['group_order'];
}
$qattr = $this->getQuestionAttributesForEM($surveyid, 0, $_SESSION['LEMlang']);
$this->qattr = $qattr;
$this->runtimeTimings[] = array(__METHOD__ . ' - question_attributes_model->getQuestionAttributesForEM', microtime(true) - $now);
$now = microtime(true);
$this->qans = $this->getAnswerSetsForEM($surveyid, NULL, $_SESSION['LEMlang']);
$this->runtimeTimings[] = array(__METHOD__ . ' - answers_model->getAnswerSetsForEM', microtime(true) - $now);
$now = microtime(true);
$q2subqInfo = array();
$this->multiflexiAnswers = array();
foreach ($fieldmap as $fielddata) {
if (!isset($fielddata['fieldname']) || !preg_match('#^\\d+X\\d+X\\d+#', $fielddata['fieldname'])) {
continue;
// not an SGQA value
}
$sgqa = $fielddata['fieldname'];
$type = $fielddata['type'];
$mandatory = $fielddata['mandatory'];
$fieldNameParts = explode('X', $sgqa);
$groupNum = $fieldNameParts[1];
$aid = isset($fielddata['aid']) ? $fielddata['aid'] : '';
$sqid = isset($fielddata['sqid']) ? $fielddata['sqid'] : '';
if ($this->sPreviewMode == 'question') {
$fielddata['relevance'] = 1;
}
if ($this->sPreviewMode == 'group') {
$fielddata['grelevance'] = 1;
}
$questionId = $fieldNameParts[2];
$questionNum = $fielddata['qid'];
$relevance = isset($fielddata['relevance']) ? $fielddata['relevance'] : 1;
$SQrelevance = isset($fielddata['SQrelevance']) ? $fielddata['SQrelevance'] : 1;
$grelevance = isset($fielddata['grelevance']) ? $fielddata['grelevance'] : 1;
$hidden = isset($qattr[$questionNum]['hidden']) ? $qattr[$questionNum]['hidden'] == '1' : false;
$scale_id = isset($fielddata['scale_id']) ? $fielddata['scale_id'] : '0';
$preg = isset($fielddata['preg']) ? $fielddata['preg'] : NULL;
// a perl regular exrpession validation function
$defaultValue = isset($fielddata['defaultvalue']) ? $fielddata['defaultvalue'] : NULL;
if (trim($preg) == '') {
$preg = NULL;
}
//.........这里部分代码省略.........
示例14: browse
//.........这里部分代码省略.........
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
} else {
Yii::app()->session['flashmessage'] = gT("The requested file does not exist on the server.");
}
break;
}
}
}
}
/**
* fnames is used as informational array
* it containts
* $fnames[] = array(<dbfieldname>, <some strange title>, <questiontext>, <group_id>, <questiontype>);
*/
if (Permission::model()->hasSurveyPermission($iSurveyID, 'responses', 'read')) {
if (Yii::app()->request->getPost('sql')) {
$aViewUrls[] = 'browseallfiltered_view';
}
//add token to top of list if survey is not private
if ($aData['surveyinfo']['anonymized'] == "N" && tableExists('tokens_' . $iSurveyID)) {
if (Permission::model()->hasSurveyPermission($iSurveyID, 'tokens', 'read')) {
$fnames[] = array("token", $clang->gT("Token ID"), 'code' => 'token');
$fnames[] = array("firstname", $clang->gT("First name"), 'code' => 'firstname');
// or token:firstname ?
$fnames[] = array("lastname", $clang->gT("Last name"), 'code' => 'lastname');
$fnames[] = array("email", $clang->gT("Email"), 'code' => 'email');
}
}
$fnames[] = array("submitdate", $clang->gT("Completed"), $clang->gT("Completed"), "0", 'D');
$fields = createFieldMap($iSurveyID, 'full', false, false, $aData['language']);
foreach ($fields as $fielddetails) {
if ($fielddetails['fieldname'] == 'lastpage' || $fielddetails['fieldname'] == 'submitdate') {
continue;
}
$question = $fielddetails['question'];
if ($fielddetails['type'] != "|") {
if ($fielddetails['fieldname'] == 'lastpage' || $fielddetails['fieldname'] == 'submitdate' || $fielddetails['fieldname'] == 'token') {
continue;
}
// no headers for time data
if ($fielddetails['type'] == 'interview_time') {
continue;
}
if ($fielddetails['type'] == 'page_time') {
continue;
}
if ($fielddetails['type'] == 'answer_time') {
continue;
}
$fnames[] = array($fielddetails['fieldname'], viewHelper::getFieldText($fielddetails), 'code' => viewHelper::getFieldCode($fielddetails, array('LEMcompat' => true)));
} elseif ($fielddetails['aid'] !== 'filecount') {
$qidattributes = getQuestionAttributeValues($fielddetails['qid']);
for ($i = 0; $i < $qidattributes['max_num_of_files']; $i++) {
$filenum = sprintf($clang->gT("File %s"), $i + 1);
if ($qidattributes['show_title'] == 1) {
$fnames[] = array($fielddetails['fieldname'], "{$filenum} - {$question} (" . $clang->gT('Title') . ")", 'code' => viewHelper::getFieldCode($fielddetails) . '(title)', "type" => "|", "metadata" => "title", "index" => $i);
}
if ($qidattributes['show_comment'] == 1) {
$fnames[] = array($fielddetails['fieldname'], "{$filenum} - {$question} (" . $clang->gT('Comment') . ")", 'code' => viewHelper::getFieldCode($fielddetails) . '(comment)', "type" => "|", "metadata" => "comment", "index" => $i);
}
$fnames[] = array($fielddetails['fieldname'], "{$filenum} - {$question} (" . $clang->gT('File name') . ")", 'code' => viewHelper::getFieldCode($fielddetails) . '(name)', "type" => "|", "metadata" => "name", "index" => $i);
$fnames[] = array($fielddetails['fieldname'], "{$filenum} - {$question} (" . $clang->gT('File size') . ")", 'code' => viewHelper::getFieldCode($fielddetails) . '(size)', "type" => "|", "metadata" => "size", "index" => $i);
示例15: surveyCreateTable
/**
* Creates the initial survey table with columns for selected survey settings
* Returns true if successful and database error if not
* @param surveyid
* @return mixed
*/
function surveyCreateTable($surveyid)
{
global $dbprefix, $databasetabletype, $connect;
$createsurvey = '';
//Check for any additional fields for this survey and create necessary fields (token and datestamp)
$pquery = "SELECT anonymized, allowregister, datestamp, ipaddr, refurl FROM {$dbprefix}surveys WHERE sid={$surveyid}";
$presult = db_execute_assoc($pquery);
$prow = $presult->FetchRow();
//Get list of questions for the base language
$fieldmap = createFieldMap($surveyid);
foreach ($fieldmap as $arow) {
$createsurvey .= " `{$arow['fieldname']}`";
switch ($arow['type']) {
case 'id':
$createsurvey .= " I NOTNULL AUTO PRIMARY";
break;
case 'token':
$createsurvey .= " C(36)";
break;
case 'startlanguage':
$createsurvey .= " C(20) NOTNULL";
break;
case "startdate":
case "datestamp":
$createsurvey .= " T NOTNULL";
break;
case "submitdate":
$createsurvey .= " T";
break;
case "lastpage":
$createsurvey .= " I";
break;
case "ipaddress":
if ($prow['ipaddr'] == "Y") {
$createsurvey .= " X";
}
break;
case "url":
if ($prow['refurl'] == "Y") {
$createsurvey .= " X";
}
break;
}
$createsurvey .= ",\n";
}
//strip trailing comma and new line feed (if any)
$createsurvey = rtrim($createsurvey, ",\n");
$tabname = "{$dbprefix}survey_{$surveyid}";
# not using db_table_name as it quotes the table name (as does CreateTableSQL)
$taboptarray = array('mysql' => 'ENGINE=' . $databasetabletype . ' CHARACTER SET utf8 COLLATE utf8_unicode_ci', 'mysqli' => 'ENGINE=' . $databasetabletype . ' CHARACTER SET utf8 COLLATE utf8_unicode_ci');
$dict = NewDataDictionary($connect);
$sqlarray = $dict->CreateTableSQL($tabname, $createsurvey, $taboptarray);
$execresult = $dict->ExecuteSQLArray($sqlarray, 1);
if ($execresult == 0 || $execresult == 1) {
return $connect->ErrorMsg();
} elseif ($execresult != 0 && $execresult != 1) {
// Set Auto Increment value if specified
$anquery = "SELECT autonumber_start FROM {$dbprefix}surveys WHERE sid={$surveyid}";
if ($anresult = db_execute_assoc($anquery)) {
//if there is an autonumber_start field, start auto numbering here
while ($row = $anresult->FetchRow()) {
if ($row['autonumber_start'] > 0) {
$autonumberquery = "ALTER TABLE {$dbprefix}survey_{$surveyid} AUTO_INCREMENT = " . $row['autonumber_start'];
$result = $connect->Execute($autonumberquery);
}
}
}
return true;
}
}