本文整理汇总了PHP中SurveyDynamic::model方法的典型用法代码示例。如果您正苦于以下问题:PHP SurveyDynamic::model方法的具体用法?PHP SurveyDynamic::model怎么用?PHP SurveyDynamic::model使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类SurveyDynamic
的用法示例。
在下文中一共展示了SurveyDynamic::model方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: CSVImportResponses
/**
* This function import CSV file to responses table
*
* @param string $sFullFilePath
* @param integer $iSurveyId
* @param array $aOptions
* Return array $result ("errors","warnings","success")
*/
function CSVImportResponses($sFullFilePath, $iSurveyId, $aOptions = array())
{
$clang = Yii::app()->lang;
// Default optional
if (!isset($aOptions['bDeleteFistLine'])) {
$aOptions['bDeleteFistLine'] = true;
}
// By default delete first line (vvimport)
if (!isset($aOptions['sExistingId'])) {
$aOptions['sExistingId'] = "ignore";
}
// By default exclude existing id
if (!isset($aOptions['bNotFinalized'])) {
$aOptions['bNotFinalized'] = false;
}
// By default don't change finalized part
if (!isset($aOptions['sCharset']) || !$aOptions['sCharset']) {
$aOptions['sCharset'] = "utf8";
}
if (!isset($aOptions['sSeparator'])) {
$aOptions['sSeparator'] = "\t";
}
if (!isset($aOptions['sQuoted'])) {
$aOptions['sQuoted'] = "\"";
}
// Fix some part
if (!array_key_exists($aOptions['sCharset'], aEncodingsArray())) {
$aOptions['sCharset'] = "utf8";
}
// Prepare an array of sentence for result
$CSVImportResult = array();
// Read the file
$handle = fopen($sFullFilePath, "r");
// Need to be adapted for Mac ? in options ?
while (!feof($handle)) {
$buffer = fgets($handle);
//To allow for very long lines . Another option is fgetcsv (0 to length), but need mb_convert_encoding
$aFileResponses[] = mb_convert_encoding($buffer, "UTF-8", $aOptions['sCharset']);
}
// Close the file
fclose($handle);
if ($aOptions['bDeleteFistLine']) {
array_shift($aFileResponses);
}
$aRealFieldNames = Yii::app()->db->getSchema()->getTable(SurveyDynamic::model($iSurveyId)->tableName())->getColumnNames();
//$aCsvHeader=array_map("trim",explode($aOptions['sSeparator'], trim(array_shift($aFileResponses))));
$aCsvHeader = str_getcsv(array_shift($aFileResponses), $aOptions['sSeparator'], $aOptions['sQuoted']);
$aLemFieldNames = LimeExpressionManager::getLEMqcode2sgqa($iSurveyId);
$aKeyForFieldNames = array();
// An array assicated each fieldname with corresponding responses key
if (!$aCsvHeader) {
$CSVImportResult['errors'][] = $clang->gT("File seems empty or has only one line");
return $CSVImportResult;
}
// Assign fieldname with $aFileResponses[] key
foreach ($aRealFieldNames as $sFieldName) {
if (in_array($sFieldName, $aCsvHeader)) {
// First pass : simple associated
$aKeyForFieldNames[$sFieldName] = array_search($sFieldName, $aCsvHeader);
} elseif (in_array($sFieldName, $aLemFieldNames)) {
// Second pass : LEM associated
$sLemFieldName = array_search($sFieldName, $aLemFieldNames);
if (in_array($sLemFieldName, $aCsvHeader)) {
$aKeyForFieldNames[$sFieldName] = array_search($sLemFieldName, $aCsvHeader);
} elseif ($aOptions['bForceImport']) {
// as fallback just map questions in order of apperance
// find out where the answer data columns start in CSV
if (!isset($csv_ans_start_index)) {
foreach ($aCsvHeader as $i => $name) {
if (preg_match('/^\\d+X\\d+X\\d+/', $name)) {
$csv_ans_start_index = $i;
break;
}
}
}
// find out where the answer data columns start in destination table
if (!isset($table_ans_start_index)) {
foreach ($aRealFieldNames as $i => $name) {
if (preg_match('/^\\d+X\\d+X\\d+/', $name)) {
$table_ans_start_index = $i;
break;
}
}
}
// map answers in order
if (isset($table_ans_start_index, $csv_ans_start_index)) {
$csv_index = array_search($sFieldName, $aRealFieldNames) - $table_ans_start_index + $csv_ans_start_index;
if ($csv_index < sizeof($aCsvHeader)) {
$aKeyForFieldNames[$sFieldName] = $csv_index;
} else {
$force_import_failed = true;
break;
//.........这里部分代码省略.........
示例2: templatereplace
//.........这里部分代码省略.........
//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 = SurveyDynamic::model($surveyid)->isCompleted($_SESSION['survey_' . $thissurvey['sid']]['srid']);
} else {
$iscompleted = false;
}
if (isset($surveyid) && !$iscompleted) {
$_clearall = CHtml::htmlButton($clang->gT("Exit and clear survey"), array('type' => 'submit', 'id' => "clearall", 'value' => 'clearall', 'name' => 'clearall', 'class' => 'clearall button', 'data-confirmedby' => 'confirm-clearall', 'title' => $clang->gT("This action need confirmation.")));
$_clearall .= CHtml::checkBox("confirm-clearall", false, array('id' => 'confirm-clearall', 'value' => 'confirm', 'class' => 'hide jshide'));
$_clearall .= CHtml::label($clang->gT("Are you sure you want to clear all your responses?"), 'confirm-clearall', array('class' => 'hide jshide'));
} else {
$_clearall = "";
}
if (isset(Yii::app()->session['datestamp'])) {
$_datestamp = Yii::app()->session['datestamp'];
} else {
$_datestamp = '-';
}
if (isset($thissurvey['allowsave']) and $thissurvey['allowsave'] == "Y") {
$_saveall = doHtmlSaveAll(isset($move) ? $move : NULL);
} 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";
}
示例3: 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;
}
示例4: upgradeSurveyTables164
/**
* Make sure all active tables have the right sized token field
*
* During a small period in the 2.0 cycle some survey tables got no
* token field or a token field that was too small. This patch makes
* sure all surveys that are not anonymous have a token field with the
* right size
*
* @return void
*/
function upgradeSurveyTables164()
{
$sQuery = "SELECT sid FROM {{surveys}} WHERE active='Y' and anonymized='N'";
$aResult = Yii::app()->getDb()->createCommand($sQuery)->queryAll();
if (!$aResult) {
return "Database Error";
} else {
foreach ($aResult as $sv) {
$token = SurveyDynamic::model($sv['sid'])->getTableSchema()->getColumn('token');
if (is_null($token)) {
addColumn('{{survey_' . $sv['sid'] . '}}', 'token', 'string(36)');
} elseif ($token->size < 36) {
alterColumn('{{survey_' . $sv['sid'] . '}}', 'token', 'string(36)');
}
}
}
}
示例5: templatereplace
//.........这里部分代码省略.........
$saved_id = Yii::app()->session['survey_' . $_surveyid]['srid'];
}
Yii::app()->loadHelper('surveytranslator');
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) . "/";
}
if (!$anonymized && isset($thissurvey['anonymized'])) {
$anonymized = $thissurvey['anonymized'] == "Y";
}
// TEMPLATECSS
$_templatecss = "";
$_templatejs = "";
/**
* Template css/js files from the template config files are loaded.
* It use the asset manager (so user never need to empty the cache, even if template is updated)
* If debug mode is on, no asset manager is used.
*
* oTemplate is defined in controller/survey/index
*
* If templatereplace is called from the template editor, a $oTemplate is provided.
*/
$oTemplate = Template::model()->getInstance($templatename);
$aCssFiles = $oTemplate->config->files->css->filename;
$aJsFiles = $oTemplate->config->files->js->filename;
$aOtherFiles = $oTemplate->otherFiles;
//var_dump($aOtherFiles); die();
if (stripos($line, "{TEMPLATECSS}")) {
// If the template has files for css, we can't publish the files one by one, but we must publish them as a whole directory
// TODO : extend asset manager so it check for file modification even in directory mode
if (!YII_DEBUG || count($aOtherFiles) < 0) {
foreach ($aCssFiles as $sCssFile) {
if (file_exists($oTemplate->path . DIRECTORY_SEPARATOR . $sCssFile)) {
Yii::app()->getClientScript()->registerCssFile(App()->getAssetManager()->publish($oTemplate->path . DIRECTORY_SEPARATOR . $sCssFile), $sCssFile['media']);
}
}
} else {
foreach ($aCssFiles as $sCssFile) {
if (file_exists($oTemplate->path . DIRECTORY_SEPARATOR . $sCssFile)) {
Yii::app()->getClientScript()->registerCssFile("{$templateurl}{$sCssFile}", $sCssFile['media']);
}
}
}
/* RTL CSS */
if (getLanguageRTL(App()->language)) {
$aCssFiles = (array) $oTemplate->config->files->rtl->css->filename;
if (!YII_DEBUG) {
foreach ($aCssFiles as $sCssFile) {
if (file_exists($oTemplate->path . DIRECTORY_SEPARATOR . $sCssFile)) {
Yii::app()->getClientScript()->registerCssFile(App()->getAssetManager()->publish($oTemplate->path . DIRECTORY_SEPARATOR . $sCssFile), $sCssFile['media']);
}
}
} else {
foreach ($aCssFiles as $sCssFile) {
if (file_exists($oTemplate->path . DIRECTORY_SEPARATOR . $sCssFile)) {
示例6: getResponse
/**
* Gets the response for the current response id.
* @return type
*/
public function getResponse()
{
if (isset($this->responseId)) {
$surveyId = Question::model()->findFieldByPk($this->questionId, 'sid');
$response = SurveyDynamic::model($surveyId)->findByPk($this->responseId);
$columns = $this->getColumns();
foreach ($columns as &$column) {
if (isset($response->{$column})) {
$column['response'] = $response->{$column};
}
}
return $columns;
}
}
示例7: time
public function time($iSurveyID)
{
$aData = $this->_getData(array('iSurveyId' => $iSurveyID));
extract($aData);
$aViewUrls = array();
if ($aData['surveyinfo']['savetimings'] != "Y") {
die;
}
if (Yii::app()->request->getPost('deleteanswer') && Yii::app()->request->getPost('deleteanswer') != '' && Yii::app()->request->getPost('deleteanswer') != 'marked' && Permission::model()->hasSurveyPermission($iSurveyID, 'responses', 'delete')) {
$iResponseID = (int) Yii::app()->request->getPost('deleteanswer');
SurveyDynamic::model($iSurveyID)->deleteByPk($iResponseID);
SurveyTimingDynamic::model($iSurveyID)->deleteByPk($iResponseID);
}
if (Yii::app()->request->getPost('markedresponses') && count(Yii::app()->request->getPost('markedresponses')) > 0) {
if (Yii::app()->request->getPost('deleteanswer') && Yii::app()->request->getPost('deleteanswer') === 'marked' && Permission::model()->hasSurveyPermission($iSurveyID, 'responses', 'delete')) {
foreach (Yii::app()->request->getPost('markedresponses') as $iResponseID) {
$iResponseID = (int) $iResponseID;
SurveyDynamic::model($iSurveyID)->deleteByPk($iResponseID);
SurveyTimingDynamic::model($iSurveyID)->deleteByPk($iResponseID);
}
}
}
$fields = createTimingsFieldMap($iSurveyID, 'full', true, false, $aData['language']);
foreach ($fields as $fielddetails) {
// headers for answer id and time data
if ($fielddetails['type'] == 'id') {
$fnames[] = array($fielddetails['fieldname'], $fielddetails['question']);
}
if ($fielddetails['type'] == 'interview_time') {
$fnames[] = array($fielddetails['fieldname'], gT('Total time'));
}
if ($fielddetails['type'] == 'page_time') {
$fnames[] = array($fielddetails['fieldname'], gT('Group') . ": " . $fielddetails['group_name']);
}
if ($fielddetails['type'] == 'answer_time') {
$fnames[] = array($fielddetails['fieldname'], gT('Question') . ": " . $fielddetails['title']);
}
}
$fncount = count($fnames);
//NOW LETS CREATE A TABLE WITH THOSE HEADINGS
foreach ($fnames as $fn) {
if (!isset($currentgroup)) {
$currentgroup = $fn[1];
$gbc = "oddrow";
}
if ($currentgroup != $fn[1]) {
$currentgroup = $fn[1];
if ($gbc == "oddrow") {
$gbc = "evenrow";
} else {
$gbc = "oddrow";
}
}
}
$aData['fnames'] = $fnames;
$start = Yii::app()->request->getParam('start', 0);
$limit = Yii::app()->request->getParam('limit', 50);
if (!$limit) {
$limit = 50;
}
//LETS COUNT THE DATA
$oCriteria = new CdbCriteria();
$oCriteria->select = 'tid';
$oCriteria->join = "INNER JOIN {{survey_{$iSurveyID}}} s ON t.id=s.id";
$oCriteria->condition = 'submitdate IS NOT NULL';
$dtcount = SurveyTimingDynamic::model($iSurveyID)->count($oCriteria);
// or die("Couldn't get response data");
if ($limit > $dtcount) {
$limit = $dtcount;
}
//NOW LETS SHOW THE DATA
$oCriteria = new CdbCriteria();
$oCriteria->join = "INNER JOIN {{survey_{$iSurveyID}}} s ON t.id=s.id";
$oCriteria->condition = 'submitdate IS NOT NULL';
$oCriteria->order = "s.id " . (Yii::app()->request->getParam('order') == 'desc' ? 'desc' : 'asc');
$oCriteria->offset = $start;
$oCriteria->limit = $limit;
$dtresult = SurveyTimingDynamic::model($iSurveyID)->findAllAsArray($oCriteria);
$dtcount2 = count($dtresult);
$cells = $fncount + 1;
//CONTROL MENUBAR
$last = $start - $limit;
$next = $start + $limit;
$end = $dtcount - $limit;
if ($end < 0) {
$end = 0;
}
if ($last < 0) {
$last = 0;
}
if ($next >= $dtcount) {
$next = $dtcount - $limit;
}
if ($end < 0) {
$end = 0;
}
$aData['sCompletionStateValue'] = incompleteAnsFilterState();
$aData['start'] = $start;
$aData['limit'] = $limit;
$aData['last'] = $last;
//.........这里部分代码省略.........
示例8: 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;
}
示例9: savedcontrol
function savedcontrol()
{
//This data will be saved to the "saved_control" table with one row per response.
// - a unique "saved_id" value (autoincremented)
// - the "sid" for this survey
// - the "srid" for the survey_x row id
// - "saved_thisstep" which is the step the user is up to in this survey
// - "saved_ip" which is the ip address of the submitter
// - "saved_date" which is the date ofthe saved response
// - an "identifier" which is like a username
// - a "password"
// - "fieldname" which is the fieldname of the saved response
// - "value" which is the value of the response
//We start by generating the first 5 values which are consistent for all rows.
global $surveyid, $thissurvey, $errormsg, $publicurl, $sitename, $clang, $clienttoken, $thisstep;
$timeadjust = getGlobalSetting('timeadjust');
//Check that the required fields have been completed.
$errormsg = '';
if (empty($_POST['savename'])) {
$errormsg .= $clang->gT("You must supply a name for this saved session.") . "<br />\n";
}
if (empty($_POST['savepass'])) {
$errormsg .= $clang->gT("You must supply a password for this saved session.") . "<br />\n";
}
if (empty($_POST['savepass']) || empty($_POST['savepass2']) || $_POST['savepass'] != $_POST['savepass2']) {
$errormsg .= $clang->gT("Your passwords do not match.") . "<br />\n";
}
// if security question asnwer is incorrect
if (function_exists("ImageCreate") && isCaptchaEnabled('saveandloadscreen', $thissurvey['usecaptcha'])) {
if (empty($_POST['loadsecurity']) || !isset($_SESSION['survey_' . $surveyid]['secanswer']) || $_POST['loadsecurity'] != $_SESSION['survey_' . $surveyid]['secanswer']) {
$errormsg .= $clang->gT("The answer to the security question is incorrect.") . "<br />\n";
}
}
if (!empty($errormsg)) {
return;
}
$duplicate = SavedControl::model()->findByAttributes(array('sid' => $surveyid, 'identifier' => $_POST['savename']));
if (!empty($duplicate) && $duplicate->count() > 0) {
$errormsg .= $clang->gT("This name has already been used for this survey. You must use a unique save name.") . "<br />\n";
return;
} else {
//INSERT BLANK RECORD INTO "survey_x" if one doesn't already exist
if (!isset($_SESSION['survey_' . $surveyid]['srid'])) {
$today = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust);
$sdata = array("datestamp" => $today, "ipaddr" => getIPAddress(), "startlanguage" => $_SESSION['survey_' . $surveyid]['s_lang'], "refurl" => getenv("HTTP_REFERER"));
if (SurveyDynamic::model($thissurvey['sid'])->insert($sdata)) {
$srid = getLastInsertID('{{survey_' . $surveyid . '}}');
$_SESSION['survey_' . $surveyid]['srid'] = $srid;
} else {
safeDie("Unable to insert record into survey table.<br /><br />");
}
}
//CREATE ENTRY INTO "saved_control"
$today = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust);
$saved_control = new SavedControl();
$saved_control->sid = $surveyid;
$saved_control->srid = $_SESSION['survey_' . $surveyid]['srid'];
$saved_control->identifier = $_POST['savename'];
// Binding does escape, so no quoting/escaping necessary
$saved_control->access_code = md5($_POST['savepass']);
$saved_control->email = $_POST['saveemail'];
$saved_control->ip = getIPAddress();
$saved_control->saved_thisstep = $thisstep;
$saved_control->status = 'S';
$saved_control->saved_date = $today;
$saved_control->refurl = getenv('HTTP_REFERER');
if ($saved_control->save()) {
$scid = getLastInsertID('{{saved_control}}');
$_SESSION['survey_' . $surveyid]['scid'] = $scid;
} else {
safeDie("Unable to insert record into saved_control table.<br /><br />");
}
$_SESSION['survey_' . $surveyid]['holdname'] = $_POST['savename'];
//Session variable used to load answers every page. Unsafe - so it has to be taken care of on output
$_SESSION['survey_' . $surveyid]['holdpass'] = $_POST['savepass'];
//Session variable used to load answers every page. Unsafe - so it has to be taken care of on output
//Email if needed
if (isset($_POST['saveemail']) && validateEmailAddress($_POST['saveemail'])) {
$subject = $clang->gT("Saved Survey Details") . " - " . $thissurvey['name'];
$message = $clang->gT("Thank you for saving your survey in progress. The following details can be used to return to this survey and continue where you left off. Please keep this e-mail for your reference - we cannot retrieve the password for you.");
$message .= "\n\n" . $thissurvey['name'] . "\n\n";
$message .= $clang->gT("Name") . ": " . $_POST['savename'] . "\n";
$message .= $clang->gT("Password") . ": " . $_POST['savepass'] . "\n\n";
$message .= $clang->gT("Reload your survey by clicking on the following link (or pasting it into your browser):") . "\n";
$message .= Yii::app()->getController()->createAbsoluteUrl("/survey/index/sid/{$surveyid}/loadall/reload/scid/{$scid}/loadname/" . rawurlencode($_POST['savename']) . "/loadpass/" . rawurlencode($_POST['savepass']) . "/lang/" . rawurlencode($clang->langcode));
if ($clienttoken) {
$message .= "/token/" . rawurlencode($clienttoken);
}
$from = "{$thissurvey['adminname']} <{$thissurvey['adminemail']}>";
if (SendEmailMessage($message, $subject, $_POST['saveemail'], $from, $sitename, false, getBounceEmail($surveyid))) {
$emailsent = "Y";
} else {
$errormsg .= $clang->gT('Error: Email failed, this may indicate a PHP Mail Setup problem on the server. Your survey details have still been saved, however you will not get an email with the details. You should note the "name" and "password" you just used for future reference.');
if (trim($thissurvey['adminemail']) == '') {
$errormsg .= $clang->gT('(Reason: Admin email address empty)');
}
}
}
return $clang->gT('Your survey was successfully saved.');
}
//.........这里部分代码省略.........
示例10: import
/**
* dataentry::import()
* Function responsible to import responses from old survey table(s).
* @param int $iSurveyId
* @return void
*/
public function import($surveyid)
{
$iSurveyId = sanitize_int($surveyid);
if (Permission::model()->hasSurveyPermission($iSurveyId, 'responses', 'create')) {
if (!App()->getRequest()->isPostRequest || App()->getRequest()->getPost('table') == 'none') {
// Schema that serves as the base for compatibility checks.
$baseSchema = SurveyDynamic::model($iSurveyId)->getTableSchema();
$tables = App()->getApi()->getOldResponseTables($iSurveyId);
$compatible = array();
$coercible = array();
foreach ($tables as $table) {
$schema = PluginDynamic::model($table)->getTableSchema();
if (PluginDynamic::model($table)->count() > 0) {
if ($this->isCompatible($baseSchema, $schema)) {
$compatible[] = $table;
} elseif ($this->isCompatible($baseSchema, $schema, false)) {
$coercible[] = $table;
}
}
}
$aData = array();
$aData['surveyid'] = $iSurveyId;
$aData['settings']['table'] = array('label' => gT('Source table'), 'type' => 'select', 'options' => array(gT('Compatible') => $this->tableList($compatible), gT('Compatible with type coercion') => $this->tableList($coercible)));
$aData['settings']['timings'] = array('type' => 'checkbox', 'label' => gT('Import timings (if exist)'));
//Get the menubar
$aData['display']['menu_bars']['browse'] = gT("Quick statistics");
$this->_renderWrappedTemplate('dataentry', 'import', $aData);
} else {
$targetSchema = SurveyDynamic::model($iSurveyId)->getTableSchema();
$sourceTable = PluginDynamic::model($_POST['table']);
$sourceSchema = $sourceTable->getTableSchema();
$fieldMap = array();
$pattern = '/([\\d]+)X([\\d]+)X([\\d]+.*)/';
foreach ($sourceSchema->getColumnNames() as $name) {
// Skip id field.
if ($name == 'id') {
continue;
}
$sourceColumn = $sourceSchema->getColumn($name);
$matches = array();
// Exact match.
if ($targetSchema->getColumn($name)) {
$fieldMap[$name] = $name;
} elseif (preg_match($pattern, $name, $matches)) {
$qid = $matches[3];
$targetColumn = $this->getQidColumn($targetSchema, $qid);
if (isset($targetColumn)) {
$fieldMap[$name] = $targetColumn->name;
}
}
}
$imported = 0;
$sourceResponses = new CDataProviderIterator(new CActiveDataProvider($sourceTable), 500);
foreach ($sourceResponses as $sourceResponse) {
// Using plugindynamic model because I dont trust surveydynamic.
$targetResponse = new PluginDynamic("{{survey_{$iSurveyId}}}");
foreach ($fieldMap as $sourceField => $targetField) {
$targetResponse[$targetField] = $sourceResponse[$sourceField];
}
$imported++;
$targetResponse->save();
unset($targetResponse);
}
Yii::app()->session['flashmessage'] = sprintf(gT("%s old response(s) were successfully imported."), $imported);
$sOldTimingsTable = substr($sourceTable->tableName(), 0, strrpos($sourceTable->tableName(), '_')) . '_timings' . substr($sourceTable->tableName(), strrpos($sourceTable->tableName(), '_'));
$sNewTimingsTable = "survey_{$surveyid}_timings";
if (isset($_POST['timings']) && $_POST['timings'] == 1 && tableExists($sOldTimingsTable) && tableExists($sNewTimingsTable)) {
// Import timings
$aFieldsOldTimingTable = array_values($schema->getTable($sOldTimingsTable)->columnNames);
$aFieldsNewTimingTable = array_values($schema->getTable($sNewTimingsTable)->columnNames);
$aValidTimingFields = array_intersect($aFieldsOldTimingTable, $aFieldsNewTimingTable);
$queryOldValues = "SELECT " . implode(", ", $aValidTimingFields) . " FROM {$sOldTimingsTable} ";
$resultOldValues = dbExecuteAssoc($queryOldValues) or show_error("Error:<br />{$queryOldValues}<br />");
$iRecordCountT = 0;
$aSRIDConversions = array();
foreach ($resultOldValues->readAll() as $sTable) {
if (isset($aSRIDConversions[$sTable['id']])) {
$sTable['id'] = $aSRIDConversions[$sTable['id']];
} else {
continue;
}
//$sInsertSQL=Yii::app()->db->GetInsertSQL($sNewTimingsTable,$row);
$sInsertSQL = "INSERT into {$sNewTimingsTable} (" . implode(",", array_map("dbQuoteID", array_keys($sTable))) . ") VALUES (" . implode(",", array_map("dbQuoteAll", array_values($sTable))) . ")";
$aTables = dbExecuteAssoc($sInsertSQL) or show_error("Error:<br />{$sInsertSQL}<br />");
$iRecordCountT++;
}
Yii::app()->session['flashmessage'] = sprintf(gT("%s old response(s) and according timings were successfully imported."), $imported, $iRecordCountT);
}
$this->getController()->redirect(array("/admin/responses/sa/index/", 'surveyid' => $surveyid));
}
}
}
示例11: exportresults
public function exportresults()
{
$iSurveyID = sanitize_int(Yii::app()->request->getParam('surveyid'));
if (!isset($imageurl)) {
$imageurl = "./images";
}
if (!isset($iSurveyID)) {
$iSurveyID = returnGlobal('sid');
}
if (!isset($convertyto1)) {
$convertyto1 = returnGlobal('convertyto1');
}
if (!isset($convertnto2)) {
$convertnto2 = returnGlobal('convertnto2');
}
if (!isset($convertyto)) {
$convertyto = returnGlobal('convertyto');
}
if (!isset($convertnto)) {
$convertnto = returnGlobal('convertnto');
}
if (!Permission::model()->hasSurveyPermission($iSurveyID, 'responses', 'export')) {
$this->getController()->error('Access denied!');
}
Yii::app()->loadHelper("admin/exportresults");
App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts') . "expressions/em_javascript.js");
App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('adminscripts') . '/exportresults.js');
$sExportType = Yii::app()->request->getPost('type');
$sHeadingFormat = Yii::app()->request->getPost('headstyle');
$sAnswerFormat = Yii::app()->request->getPost('answers');
$bHeaderSpacesToUnderscores = Yii::app()->request->getPost('headspacetounderscores');
$bConvertY = Yii::app()->request->getPost('converty');
$bConvertN = Yii::app()->request->getPost('convertn');
$sYValue = Yii::app()->request->getPost('convertyto');
$sNValue = Yii::app()->request->getPost('convertnto');
$surveybaselang = Survey::model()->findByPk($iSurveyID)->language;
$exportoutput = "";
// Get info about the survey
$thissurvey = getSurveyInfo($iSurveyID);
// Load ExportSurveyResultsService so we know what exports are available
$resultsService = new ExportSurveyResultsService();
$exports = $resultsService->getExports();
if (!$sExportType) {
//FIND OUT HOW MANY FIELDS WILL BE NEEDED - FOR 255 COLUMN LIMIT
$aFieldMap = createFieldMap($iSurveyID, 'full', false, false, getBaseLanguageFromSurveyID($iSurveyID));
if ($thissurvey['savetimings'] === "Y") {
//Append survey timings to the fieldmap array
$aFieldMap = $aFieldMap + createTimingsFieldMap($iSurveyID, 'full', false, false, getBaseLanguageFromSurveyID($iSurveyID));
}
$iFieldCount = count($aFieldMap);
$selecthide = "";
$selectshow = "";
$selectinc = "";
if (incompleteAnsFilterState() == "complete") {
$selecthide = "selected='selected'";
} elseif (incompleteAnsFilterState() == "incomplete") {
$selectinc = "selected='selected'";
} else {
$selectshow = "selected='selected'";
}
$aFields = array();
foreach ($aFieldMap as $sFieldName => $fieldinfo) {
$sCode = viewHelper::getFieldCode($fieldinfo);
$aFields[$sFieldName] = $sCode . ' - ' . htmlspecialchars(ellipsize(html_entity_decode(viewHelper::getFieldText($fieldinfo)), 30, 0.6, '...'));
$aFieldsOptions[$sFieldName] = array('title' => viewHelper::getFieldText($fieldinfo), 'data-fieldname' => $fieldinfo['fieldname'], 'data-emcode' => viewHelper::getFieldCode($fieldinfo, array('LEMcompat' => true)));
// No need to filter title : Yii do it (remove all tag)
}
$data['SingleResponse'] = (int) returnGlobal('id');
$data['selecthide'] = $selecthide;
$data['selectshow'] = $selectshow;
$data['selectinc'] = $selectinc;
$data['afieldcount'] = $iFieldCount;
$data['aFields'] = $aFields;
$data['aFieldsOptions'] = $aFieldsOptions;
//get max number of datasets
$iMaximum = SurveyDynamic::model($iSurveyID)->getMaxId();
$data['max_datasets'] = $iMaximum;
$data['surveyid'] = $iSurveyID;
$data['imageurl'] = Yii::app()->getConfig('imageurl');
$data['thissurvey'] = $thissurvey;
$data['display']['menu_bars']['browse'] = gT("Export results");
// Export plugins, leave out all entries that are not plugin
$exports = array_filter($exports);
$exportData = array();
foreach ($exports as $key => $plugin) {
$event = new PluginEvent('listExportOptions');
$event->set('type', $key);
$oPluginManager = App()->getPluginManager();
$oPluginManager->dispatchEvent($event, $plugin);
$exportData[$key] = array('onclick' => $event->get('onclick'), 'label' => $event->get('label'), 'checked' => $event->get('default', false), 'tooltip' => $event->get('tooltip', null));
}
$data['exports'] = $exportData;
// Pass available exports
$data['headexports'] = array('code' => array('label' => gT("Question code"), 'help' => null, 'checked' => false), 'abbreviated' => array('label' => gT("Abbreviated question text"), 'help' => null, 'checked' => false), 'full' => array('label' => gT("Full question text"), 'help' => null, 'checked' => true), 'codetext' => array('label' => gT("Question code and question text"), 'help' => null, 'checked' => false));
// Add a plugin for adding headexports : a public function getRegistereddPlugins($event) can help here.
$aLanguagesCode = Survey::model()->findByPk($iSurveyID)->getAllLanguages();
$aLanguages = array();
foreach ($aLanguagesCode as $sLanguage) {
$aLanguages[$sLanguage] = getLanguageNameFromCode($sLanguage, false);
}
//.........这里部分代码省略.........
示例12: loadSurveyResults
/**
* Loads results for the survey into the $survey->responses array. The
* results begin from $minRecord and end with $maxRecord. Either none,
* or both, the $minRecord and $maxRecord variables must be provided.
* If none are then all responses are loaded.
*
* @param Survey $survey
* @param int $iMinimum
* @param int $iMaximum
* @param string $sFilter An optional filter for the results
* @param string $completionState all, complete or incomplete
*/
public function loadSurveyResults(SurveyObj $survey, $iMinimum, $iMaximum, $sFilter = '', $completionState = 'all')
{
// Get info about the survey
$aSelectFields = Yii::app()->db->schema->getTable('{{survey_' . $survey->id . '}}')->getColumnNames();
// Allways add Table prefix : see bug #08396 . Don't use array_walk for PHP < 5.3 compatibility
foreach ($aSelectFields as &$sField) {
$sField = "{{survey_{$survey->id}}}." . $sField;
}
$oRecordSet = Yii::app()->db->createCommand()->from('{{survey_' . $survey->id . '}}');
if (tableExists('tokens_' . $survey->id) && array_key_exists('token', SurveyDynamic::model($survey->id)->attributes) && Permission::model()->hasSurveyPermission($survey->id, 'tokens', 'read')) {
$oRecordSet->leftJoin('{{tokens_' . $survey->id . '}} tokentable', 'tokentable.token={{survey_' . $survey->id . '}}.token');
$aTokenFields = Yii::app()->db->schema->getTable('{{tokens_' . $survey->id . '}}')->getColumnNames();
foreach ($aTokenFields as &$sField) {
$sField = "tokentable." . $sField;
}
$aSelectFields = array_merge($aSelectFields, array_diff($aTokenFields, array('tokentable.token')));
//$aSelectFields=array_diff($aSelectFields, array('{{survey_{$survey->id}}}.token'));
//$aSelectFields[]='{{survey_' . $survey->id . '}}.token';
}
if ($survey->info['savetimings'] == "Y") {
$oRecordSet->leftJoin("{{survey_" . $survey->id . "_timings}} survey_timings", "{{survey_" . $survey->id . "}}.id = survey_timings.id");
$aTimingFields = Yii::app()->db->schema->getTable("{{survey_" . $survey->id . "_timings}}")->getColumnNames();
foreach ($aTimingFields as &$sField) {
$sField = "survey_timings." . $sField;
}
$aSelectFields = array_merge($aSelectFields, array_diff($aTimingFields, array('survey_timings.id')));
//$aSelectFields=array_diff($aSelectFields, array('{{survey_{$survey->id}}}.id'));
//$aSelectFields[]='{{survey_' . $survey->id . '}}.id';
}
$aParams = array('min' => $iMinimum, 'max' => $iMaximum);
$selection = '{{survey_' . $survey->id . '}}.id >= :min AND {{survey_' . $survey->id . '}}.id <= :max';
$oRecordSet->where($selection, $aParams);
if ($sFilter != '') {
$oRecordSet->andWhere($sFilter);
}
switch ($completionState) {
case 'incomplete':
$oRecordSet->andWhere('submitdate IS NULL');
break;
case 'complete':
$oRecordSet->andWhere('submitdate IS NOT NULL');
break;
case 'all':
default:
// Do nothing, all responses
break;
}
$survey->responses = $oRecordSet->select($aSelectFields)->query();
}
示例13: 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');
}
if (!Permission::model()->hasSurveyPermission($iSurveyID, 'responses', 'export')) {
return array('status' => 'No permission');
}
if (!tableExists('{{survey_' . $iSurveyID . '}}')) {
return array('status' => 'No Data');
}
if (!($oResult = SurveyDynamic::model($iSurveyID)->findByAttributes(array('token' => $sToken)))) {
return array('status' => 'No Response found for Token');
}
if ($oResult['id']) {
return $this->export_responses($sSessionKey, $iSurveyID, $sDocumentType, $sLanguageCode, $sCompletionStatus, $sHeadingType, $sResponseType, $oResult['id'], $oResult['id'], $aFields);
}
}
示例14: 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');
}
示例15: _listcolumn
/**
* Returns a simple list of values in a particular column, that meet the requirements of the SQL
*/
function _listcolumn($surveyid, $column, $sortby = "", $sortmethod = "", $sorttype = "")
{
$search['condition'] = Yii::app()->db->quoteColumnName($column) . " != ''";
$sDBDriverName = Yii::app()->db->getDriverName();
if ($sDBDriverName == 'sqlsrv' || $sDBDriverName == 'mssql' || $sDBDriverName == 'dblib') {
$search['condition'] = "CAST(" . Yii::app()->db->quoteColumnName($column) . " as varchar) != ''";
}
//filter incomplete answers if set
if (incompleteAnsFilterState() == "incomplete") {
$search['condition'] .= " AND submitdate is null";
} elseif (incompleteAnsFilterState() == "complete") {
$search['condition'] .= " AND submitdate is not null";
}
//Look for any selects/filters set in the original statistics query, and apply them to the column listing
if (isset(Yii::app()->session['statistics_selects_' . $surveyid]) && is_array(Yii::app()->session['statistics_selects_' . $surveyid])) {
foreach (Yii::app()->session['statistics_selects_' . $surveyid] as $sql) {
$search['condition'] .= " AND {$sql}";
}
}
if ($sortby != '') {
if ($sDBDriverName == 'sqlsrv' || $sDBDriverName == 'mssql' || $sDBDriverName == 'dblib') {
$sortby = "CAST(" . Yii::app()->db->quoteColumnName($sortby) . " as varchar)";
} else {
$sortby = Yii::app()->db->quoteColumnName($sortby);
}
if ($sorttype == 'N') {
$sortby = "({$sortby} * 1)";
}
//Converts text sorting into numerical sorting
$search['order'] = $sortby . ' ' . $sortmethod;
}
$results = SurveyDynamic::model($surveyid)->findAll($search);
$output = array();
foreach ($results as $row) {
$output[] = array("id" => $row['id'], "value" => $row[$column]);
}
return $output;
}