/** * Creates a new model. * If creation is successful, the browser will be redirected to the 'view' page. */ public function actionCreate() { $model = new X2Leads(); $users = User::getNames(); foreach (Groups::model()->findAll() as $group) { $users[$group->id] = $group->name; } unset($users['admin']); unset($users['']); // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if (isset($_POST['X2Leads'])) { $temp = $model->attributes; $model->setX2Fields($_POST['X2Leads']); if (isset($_POST['x2ajax'])) { $ajaxErrors = $this->quickCreate($model); } else { if ($model->save()) { $this->redirect(array('view', 'id' => $model->id)); } } } if (isset($_POST['x2ajax'])) { $this->renderInlineCreateForm($model, isset($ajaxErrors) ? $ajaxErrors : false); } else { $this->render('create', array('model' => $model, 'users' => $users)); } }
/** * Picks the next asignee based on the routing type * * @return string Username that should be assigned the next lead */ public function getNextAssignee() { $admin =& Yii::app()->settings; $type = $admin->serviceDistribution; if ($type == "") { return "Anyone"; } elseif ($type == "evenDistro") { return $this->evenDistro(); } elseif ($type == "trueRoundRobin") { return $this->roundRobin(); } elseif ($type == 'singleUser') { $user = User::model()->findByPk($admin->srrId); if (isset($user)) { return $user->username; } else { return "Anyone"; } } elseif ($type == 'singleGroup') { $group = Groups::model()->findByPk($admin->sgrrId); if (isset($group)) { return $group->id; } else { return "Anyone"; } } }
public function actionProgress($id, $trackid) { $progress = array(); // получаем список пользователей // получаем задания по пользователю, сразу же с решениями $track = Tracks::model()->findByPk($trackid); $group = Groups::model()->with("Students")->findByPk($id); // пройдемся по всем студентам в группе foreach ($group->Students as $student) { // получим теперь таски и солюшны этого студента $students[$student->id] = $student; $tasks = Tasks::model()->with(array('Solutions' => array('on' => 'Solutions.student=' . $student->id)))->findAllByAttributes(array("track" => $trackid), array('order' => 't.order')); // продемся по всем задачам foreach ($tasks as $task) { if (isset($task->Solutions[0])) { // если у таска есть солюшн – возьмем $progress[$student->id][$task->id] = $task->Solutions[0]->status; } else { // если нет – запишем нейтральный статус $progress[$student->id][$task->id] = "undefined"; } } } $this->render('progress', array("group" => $group, "track" => $track, "students" => $students, "progress" => $progress)); }
/** * This function checks the LimeSurvey database for logical consistency and returns an according array * containing all issues in the particular tables. * @returns Array with all found issues. */ protected function _checkintegrity() { $clang = Yii::app()->lang; /*** Plainly delete survey permissions if the survey or user does not exist ***/ $users = User::model()->findAll(); $uids = array(); foreach ($users as $user) { $uids[] = $user['uid']; } $criteria = new CDbCriteria(); $criteria->addNotInCondition('uid', $uids, 'OR'); $surveys = Survey::model()->findAll(); $sids = array(); foreach ($surveys as $survey) { $sids[] = $survey['sid']; } $criteria->addNotInCondition('sid', $sids, 'OR'); Survey_permissions::model()->deleteAll($criteria); // Deactivate surveys that have a missing response table foreach ($surveys as $survey) { if ($survey['active'] == 'Y' && !tableExists("{{survey_{$survey['sid']}}}")) { Survey::model()->updateByPk($survey['sid'], array('active' => 'N')); } } // Fix subquestions fixSubquestions(); /*** Check for active survey tables with missing survey entry and rename them ***/ $sDBPrefix = Yii::app()->db->tablePrefix; $sQuery = dbSelectTablesLike('{{survey}}\\_%'); $aResult = dbQueryOrFalse($sQuery) or safeDie("Couldn't get list of conditions from database<br />{$sQuery}<br />"); foreach ($aResult->readAll() as $aRow) { $sTableName = substr(reset($aRow), strlen($sDBPrefix)); if ($sTableName == 'survey_permissions' || $sTableName == 'survey_links' || $sTableName == 'survey_url_parameters') { continue; } $aTableName = explode('_', $sTableName); if (isset($aTableName[1]) && ctype_digit($aTableName[1])) { $iSurveyID = $aTableName[1]; if (!in_array($iSurveyID, $sids)) { $sDate = date('YmdHis') . rand(1, 1000); $sOldTable = "survey_{$iSurveyID}"; $sNewTable = "old_survey_{$iSurveyID}_{$sDate}"; try { $deactivateresult = Yii::app()->db->createCommand()->renameTable("{{{$sOldTable}}}", "{{{$sNewTable}}}"); } catch (CDbException $e) { die('Couldn\'t make backup of the survey table. Please try again. The database reported the following error:<br />' . htmlspecialchars($e) . '<br />'); } } } } /*** Check for active token tables with missing survey entry ***/ $aResult = dbQueryOrFalse(dbSelectTablesLike('{{tokens}}\\_%')) or safeDie("Couldn't get list of conditions from database<br />{$sQuery}<br />"); foreach ($aResult->readAll() as $aRow) { $sTableName = substr(reset($aRow), strlen($sDBPrefix)); $iSurveyID = substr($sTableName, strpos($sTableName, '_') + 1); if (!in_array($iSurveyID, $sids)) { $sDate = date('YmdHis') . rand(1, 1000); $sOldTable = "tokens_{$iSurveyID}"; $sNewTable = "old_tokens_{$iSurveyID}_{$sDate}"; try { $deactivateresult = Yii::app()->db->createCommand()->renameTable("{{{$sOldTable}}}", "{{{$sNewTable}}}"); } catch (CDbException $e) { die('Couldn\'t make backup of the survey table. Please try again. The database reported the following error:<br />' . htmlspecialchars($e) . '<br />'); } } } /**********************************************************************/ /* Check conditions */ /**********************************************************************/ // TMSW Conditions->Relevance: Replace this with analysis of relevance $conditions = Conditions::model()->findAll(); if (Conditions::model()->hasErrors()) { safeDie(Conditions::model()->getError()); } $okQuestion = array(); foreach ($conditions as $condition) { if ($condition['cqid'] != 0) { // skip case with cqid=0 for codnitions on {TOKEN:EMAIL} for instance if (!array_key_exists($condition['cqid'], $okQuestion)) { $iRowCount = Questions::model()->countByAttributes(array('qid' => $condition['cqid'])); if (Questions::model()->hasErrors()) { safeDie(Questions::model()->getError()); } if (!$iRowCount) { $aDelete['conditions'][] = array('cid' => $condition['cid'], 'reason' => $clang->gT('No matching CQID')); } else { $okQuestion[$condition['cqid']] = $condition['cqid']; } } } if ($condition['cfieldname']) { if (preg_match('/^\\+{0,1}[0-9]+X[0-9]+X*$/', $condition['cfieldname'])) { // only if cfieldname isn't Tag such as {TOKEN:EMAIL} or any other token list($surveyid, $gid, $rest) = explode('X', $condition['cfieldname']); $iRowCount = count(Groups::model()->findAllByAttributes(array('gid' => $gid))); if (Groups::model()->hasErrors()) { safeDie(Groups::model()->getError()); } if (!$iRowCount) { $aDelete['conditions'][] = array('cid' => $condition['cid'], 'reason' => $clang->gT('No matching CFIELDNAME group!') . " ({$gid}) ({$condition['cfieldname']})"); } } } elseif (!$condition['cfieldname']) { $aDelete['conditions'][] = array('cid' => $condition['cid'], 'reason' => $clang->gT('No CFIELDNAME field set!') . " ({$condition['cfieldname']})"); } } /**********************************************************************/ /* Check question attributes */ /**********************************************************************/ $question_attributes = Question_attributes::model()->findAllBySql('select qid from {{question_attributes}} where qid not in (select qid from {{questions}})'); if (Question_attributes::model()->hasErrors()) { safeDie(Question_attributes::model()->getError()); } foreach ($question_attributes as $question_attribute) { $aDelete['questionattributes'][] = array('qid' => $question_attribute['qid']); } // foreach /**********************************************************************/ /* Check default values */ /**********************************************************************/ $questions = Questions::model()->findAll(); if (Questions::model()->hasErrors()) { safeDie(Questions::model()->getError()); } $qids = array(); foreach ($questions as $question) { $qids[] = $question['qid']; } $criteria = new CDbCriteria(); $criteria->addNotInCondition('qid', $qids); $aDelete['defaultvalues'] = count(Defaultvalues::model()->findAll($criteria)); if (Defaultvalues::model()->hasErrors()) { safeDie(Defaultvalues::model()->getError()); } /**********************************************************************/ /* Check quotas */ /**********************************************************************/ $surveys = Survey::model()->findAll(); if (Survey::model()->hasErrors()) { safeDie(Survey::model()->getError()); } $sids = array(); foreach ($surveys as $survey) { $sids[] = $survey['sid']; } $criteria = new CDbCriteria(); $criteria->addNotInCondition('sid', $sids); $aDelete['quotas'] = count(Quota::model()->findAll($criteria)); if (Quota::model()->hasErrors()) { safeDie(Quota::model()->getError()); } /**********************************************************************/ /* Check quota languagesettings */ /**********************************************************************/ $quotas = Quota::model()->findAll(); if (Quota::model()->hasErrors()) { safeDie(Quota::model()->getError()); } $ids = array(); foreach ($quotas as $quota) { $ids[] = $quota['id']; } $criteria = new CDbCriteria(); $criteria->addNotInCondition('quotals_quota_id', $ids); $aDelete['quotals'] = count(Quota_languagesettings::model()->findAll($criteria)); if (Quota_languagesettings::model()->hasErrors()) { safeDie(Quota_languagesettings::model()->getError()); } /**********************************************************************/ /* Check quota members */ /**********************************************************************/ $quotas = Quota::model()->findAll(); $quota_ids = array(); foreach ($quotas as $quota) { $quota_ids[] = $quota['id']; } $criteria = new CDbCriteria(); $criteria->addNotInCondition('quota_id', $quota_ids); $questions = Questions::model()->findAll(); $qids = array(); foreach ($questions as $question) { $qids[] = $question['qid']; } $criteria->addNotInCondition('qid', $qids, 'OR'); $surveys = Survey::model()->findAll(); $sids = array(); foreach ($surveys as $survey) { $sids[] = $survey['sid']; } $criteria->addNotInCondition('sid', $sids, 'OR'); $aDelete['quotamembers'] = count(Quota_members::model()->findAll($criteria)); if (Quota_members::model()->hasErrors()) { safeDie(Quota_members::model()->getError()); } /**********************************************************************/ /* Check assessments */ /**********************************************************************/ $criteria = new CDbCriteria(); $criteria->compare('scope', 'T'); $assessments = Assessment::model()->findAll($criteria); if (Assessment::model()->hasErrors()) { safeDie(Assessment::model()->getError()); } foreach ($assessments as $assessment) { $iAssessmentCount = count(Survey::model()->findAllByPk($assessment['sid'])); if (Survey::model()->hasErrors()) { safeDie(Survey::model()->getError()); } if (!$iAssessmentCount) { $aDelete['assessments'][] = array('id' => $assessment['id'], 'assessment' => $assessment['name'], 'reason' => $clang->gT('No matching survey')); } } $criteria = new CDbCriteria(); $criteria->compare('scope', 'G'); $assessments = Assessment::model()->findAll($criteria); if (Assessment::model()->hasErrors()) { safeDie(Assessment::model()->getError()); } foreach ($assessments as $assessment) { $iAssessmentCount = count(Groups::model()->findAllByPk(array('gid' => $assessment['gid'], 'language' => $assessment['language']))); if (Groups::model()->hasErrors()) { safeDie(Groups::model()->getError()); } if (!$iAssessmentCount) { $aDelete['assessments'][] = array('id' => $assessment['id'], 'assessment' => $assessment['name'], 'reason' => $clang->gT('No matching group')); } } /**********************************************************************/ /* Check answers */ /**********************************************************************/ $answers = Answers::model()->findAll(); if (Answers::model()->hasErrors()) { safeDie(Answers::model()->getError()); } $okQuestion = array(); foreach ($answers as $answer) { if (!array_key_exists($answer['qid'], $okQuestion)) { $iAnswerCount = Questions::model()->countByAttributes(array('qid' => $answer['qid'])); if (Questions::model()->hasErrors()) { safeDie(Questions::model()->getError()); } if (!$iAnswerCount) { $aDelete['answers'][] = array('qid' => $answer['qid'], 'code' => $answer['code'], 'reason' => $clang->gT('No matching question')); } else { $okQuestion[$answer['qid']] = $answer['qid']; } } } /***************************************************************************/ /* Check survey languagesettings and restore them if they don't exist */ /***************************************************************************/ $surveys = Survey::model()->findAll(); foreach ($surveys as $survey) { $aLanguages = $survey->additionalLanguages; $aLanguages[] = $survey->language; foreach ($aLanguages as $langname) { if ($langname) { $oLanguageSettings = Surveys_languagesettings::model()->find('surveyls_survey_id=:surveyid AND surveyls_language=:langname', array(':surveyid' => $survey->sid, ':langname' => $langname)); if (!$oLanguageSettings) { $oLanguageSettings = new Surveys_languagesettings(); $languagedetails = getLanguageDetails($langname); $insertdata = array('surveyls_survey_id' => $survey->sid, 'surveyls_language' => $langname, 'surveyls_title' => '', 'surveyls_dateformat' => $languagedetails['dateformat']); foreach ($insertdata as $k => $v) { $oLanguageSettings->{$k} = $v; } $usresult = $oLanguageSettings->save(); } } } } /**********************************************************************/ /* Check survey language settings */ /**********************************************************************/ $surveys = Survey::model()->findAll(); if (Survey::model()->hasErrors()) { safeDie(Survey::model()->getError()); } $sids = array(); foreach ($surveys as $survey) { $sids[] = $survey['sid']; } $criteria = new CDbCriteria(); $criteria->addNotInCondition('surveyls_survey_id', $sids); $surveys_languagesettings = Surveys_languagesettings::model()->findAll($criteria); if (Surveys_languagesettings::model()->hasErrors()) { safeDie(Surveys_languagesettings::model()->getError()); } foreach ($surveys_languagesettings as $surveys_languagesetting) { $aDelete['surveylanguagesettings'][] = array('slid' => $surveys_languagesetting['surveyls_survey_id'], 'reason' => $clang->gT('The related survey is missing.')); } /**********************************************************************/ /* Check questions */ /**********************************************************************/ $questions = Questions::model()->findAll(); if (Questions::model()->hasErrors()) { safeDie(Questions::model()->getError()); } $groups = Groups::model()->findAll(); if (Groups::model()->hasErrors()) { safeDie(Groups::model()->getError()); } $gids = array(); foreach ($groups as $group) { $gids[] = $group['gid']; } foreach ($questions as $question) { //Make sure the group exists if (!in_array($question['gid'], $gids)) { $aDelete['questions'][] = array('qid' => $question['qid'], 'reason' => $clang->gT('No matching group') . " ({$question['gid']})"); } //Make sure survey exists if (!in_array($question['sid'], $sids)) { $aDelete['questions'][] = array('qid' => $question['qid'], 'reason' => $clang->gT('There is no matching survey.') . " ({$question['sid']})"); } } /**********************************************************************/ /* Check groups */ /**********************************************************************/ $surveys = Survey::model()->findAll(); if (Survey::model()->hasErrors()) { safeDie(Survey::model()->getError()); } $sids = array(); foreach ($surveys as $survey) { $sids[] = $survey['sid']; } $criteria = new CDbCriteria(); $criteria->addNotInCondition('sid', $sids); $groups = Groups::model()->findAll($criteria); foreach ($groups as $group) { $aDelete['groups'][] = array('gid' => $group['gid'], 'reason' => $clang->gT('There is no matching survey.') . ' SID:' . $group['sid']); } /**********************************************************************/ /* Check old survey tables */ /**********************************************************************/ //1: Get list of 'old_survey' tables and extract the survey id //2: Check if that survey id still exists //3: If it doesn't offer it for deletion $sQuery = dbSelectTablesLike('{{old_survey}}%'); $aResult = dbQueryOrFalse($sQuery) or safeDie("Couldn't get list of conditions from database<br />{$sQuery}<br />"); $aTables = $aResult->readAll(); $aOldSIDs = array(); $aSIDs = array(); foreach ($aTables as $sTable) { $sTable = reset($sTable); list($sOldText, $SurveyText, $iSurveyID, $sDate) = explode('_', substr($sTable, strlen($sDBPrefix))); $aOldSIDs[] = $iSurveyID; $aFullOldSIDs[$iSurveyID][] = $sTable; } $aOldSIDs = array_unique($aOldSIDs); //$sQuery = 'SELECT sid FROM {{surveys}} ORDER BY sid'; //$oResult = dbExecuteAssoc($sQuery) or safeDie('Couldn\'t get unique survey ids'); $surveys = Survey::model()->findAll(); if (Survey::model()->hasErrors()) { safeDie(Survey::model()->getError()); } $aSIDs = array(); foreach ($surveys as $survey) { $aSIDs[] = $survey['sid']; } foreach ($aOldSIDs as $iOldSID) { if (!in_array($iOldSID, $aSIDs)) { foreach ($aFullOldSIDs[$iOldSID] as $sTableName) { $aDelete['orphansurveytables'][] = $sTableName; } } else { foreach ($aFullOldSIDs[$iOldSID] as $sTableName) { $aTableParts = explode('_', substr($sTableName, strlen($sDBPrefix))); if (count($aTableParts) == 4) { $sOldText = $aTableParts[0]; $SurveyText = $aTableParts[1]; $iSurveyID = $aTableParts[2]; $sDateTime = $aTableParts[3]; $sType = $clang->gT('responses'); } elseif (count($aTableParts) == 5) { //This is a timings table ( $sOldText = $aTableParts[0]; $SurveyText = $aTableParts[1]; $iSurveyID = $aTableParts[2]; $sDateTime = $aTableParts[4]; $sType = $clang->gT('timings'); } $iYear = substr($sDateTime, 0, 4); $iMonth = substr($sDateTime, 4, 2); $iDay = substr($sDateTime, 6, 2); $iHour = substr($sDateTime, 8, 2); $iMinute = substr($sDateTime, 10, 2); $sDate = date('d M Y H:i', mktime($iHour, $iMinute, 0, $iMonth, $iDay, $iYear)); $sQuery = 'SELECT count(*) as recordcount FROM ' . $sTableName; $aFirstRow = Yii::app()->db->createCommand($sQuery)->queryRow(); if ($aFirstRow['recordcount'] == 0) { // empty table - so add it to immediate deletion $aDelete['orphansurveytables'][] = $sTableName; } else { $aOldSurveyTableAsk[] = array('table' => $sTableName, 'details' => sprintf($clang->gT('Survey ID %d saved at %s containing %d record(s) (%s)'), $iSurveyID, $sDate, $aFirstRow['recordcount'], $sType)); } } } } /**********************************************************************/ /* CHECK OLD TOKEN TABLES */ /**********************************************************************/ //1: Get list of 'old_token' tables and extract the survey id //2: Check if that survey id still exists //3: If it doesn't offer it for deletion $aResult = dbQueryOrFalse(dbSelectTablesLike('{{old_token}}%')) or safeDie("Couldn't get list of conditions from database<br />{$sQuery}<br />"); $aTables = $aResult->readAll(); $aOldTokenSIDs = array(); $aTokenSIDs = array(); $aFullOldTokenSIDs = array(); foreach ($aTables as $sTable) { $sTable = reset($sTable); list($sOldText, $SurveyText, $iSurveyID, $sDateTime) = explode('_', substr($sTable, strlen($sDBPrefix))); $aTokenSIDs[] = $iSurveyID; $aFullOldTokenSIDs[$iSurveyID][] = $sTable; } $aOldTokenSIDs = array_unique($aTokenSIDs); $surveys = Survey::model()->findAll(); if (Survey::model()->hasErrors()) { safeDie(Survey::model()->getError()); } $aSIDs = array(); foreach ($surveys as $survey) { $aSIDs[] = $survey['sid']; } foreach ($aOldTokenSIDs as $iOldTokenSID) { if (!in_array($iOldTokenSID, $aOldTokenSIDs)) { foreach ($aFullOldTokenSIDs[$iOldTokenSID] as $sTableName) { $aDelete['orphantokentables'][] = $sTableName; } } else { foreach ($aFullOldTokenSIDs[$iOldTokenSID] as $sTableName) { list($sOldText, $sTokensText, $iSurveyID, $sDateTime) = explode('_', substr($sTableName, strlen($sDBPrefix))); $iYear = substr($sDateTime, 0, 4); $iMonth = substr($sDateTime, 4, 2); $iDay = substr($sDateTime, 6, 2); $iHour = substr($sDateTime, 8, 2); $iMinute = substr($sDateTime, 10, 2); $sDate = date('D, d M Y h:i a', mktime($iHour, $iMinute, 0, $iMonth, $iDay, $iYear)); $sQuery = 'SELECT count(*) as recordcount FROM ' . $sTableName; $aFirstRow = Yii::app()->db->createCommand($sQuery)->queryRow(); if ($aFirstRow['recordcount'] == 0) { // empty table - so add it to immediate deletion $aDelete['orphantokentables'][] = $sTableName; } else { $aOldTokenTableAsk[] = array('table' => $sTableName, 'details' => sprintf($clang->gT('Survey ID %d saved at %s containing %d record(s)'), $iSurveyID, $sDate, $aFirstRow['recordcount'])); } } } } if ($aDelete['defaultvalues'] == 0 && $aDelete['quotamembers'] == 0 && $aDelete['quotas'] == 0 && $aDelete['quotals'] == 0 && count($aDelete) == 4) { $aDelete['integrityok'] = true; } else { $aDelete['integrityok'] = false; } if (!isset($aOldTokenTableAsk) && !isset($aOldSurveyTableAsk)) { $aDelete['redundancyok'] = true; } else { $aDelete['redundancyok'] = false; $aDelete['redundanttokentables'] = array(); $aDelete['redundantsurveytables'] = array(); if (isset($aOldTokenTableAsk)) { $aDelete['redundanttokentables'] = $aOldTokenTableAsk; } if (isset($aOldSurveyTableAsk)) { $aDelete['redundantsurveytables'] = $aOldSurveyTableAsk; } } /**********************************************************************/ /* CHECK CPDB SURVEY_LINKS TABLE FOR REDUNDENT TOKEN TABLES */ /**********************************************************************/ //1: Get distinct list of survey_link survey ids, check if tokens // table still exists for each one, and remove if not /* TODO */ /**********************************************************************/ /* CHECK CPDB SURVEY_LINKS TABLE FOR REDUNDENT TOKEN ENTRIES */ /**********************************************************************/ //1: For each survey_link, see if the matching entry still exists in // the token table and remove if it doesn't. /* TODO */ return $aDelete; }
/** * Import survey from an TSV file template that does not require or allow assigning of GID or QID values. * NOTE: This currently only supports import of one language * @global type $connect * @global type $dbprefix * @global type $clang * @global type $timeadjust * @param type $sFullFilepath * @return type * * @author TMSWhite */ function TSVImportSurvey($sFullFilepath) { $clang = Yii::app()->lang; $insertdata = array(); $results = array(); $results['error'] = false; $baselang = 'en'; // TODO set proper default $encoding = ''; $handle = fopen($sFullFilepath, 'r'); $bom = fread($handle, 2); rewind($handle); // Excel tends to save CSV as UTF-16, which PHP does not properly detect if ($bom === chr(0xff) . chr(0xfe) || $bom === chr(0xfe) . chr(0xff)) { // UTF16 Byte Order Mark present $encoding = 'UTF-16'; } else { $file_sample = fread($handle, 1000) + 'e'; //read first 1000 bytes // + e is a workaround for mb_string bug rewind($handle); $encoding = mb_detect_encoding($file_sample, 'UTF-8, UTF-7, ASCII, EUC-JP,SJIS, eucJP-win, SJIS-win, JIS, ISO-2022-JP'); } if ($encoding && $encoding != 'UTF-8') { stream_filter_append($handle, 'convert.iconv.' . $encoding . '/UTF-8'); } $file = stream_get_contents($handle); fclose($handle); // fix Excel non-breaking space $file = str_replace("0xC20xA0", ' ', $file); $filelines = explode("\n", $file); $row = array_shift($filelines); $headers = explode("\t", $row); $rowheaders = array(); foreach ($headers as $header) { $rowheaders[] = trim($header); } // remove BOM from the first header cell, if needed $rowheaders[0] = preg_replace("/^\\W+/", "", $rowheaders[0]); if (preg_match('/class$/', $rowheaders[0])) { $rowheaders[0] = 'class'; // second attempt to remove BOM } $adata = array(); foreach ($filelines as $rowline) { $rowarray = array(); $row = explode("\t", $rowline); for ($i = 0; $i < count($rowheaders); ++$i) { $val = isset($row[$i]) ? $row[$i] : ''; // if Excel was used, it surrounds strings with quotes and doubles internal double quotes. Fix that. if (preg_match('/^".*"$/', $val)) { $val = str_replace('""', '"', substr($val, 1, -1)); } $rowarray[$rowheaders[$i]] = $val; } $adata[] = $rowarray; } $results['defaultvalues'] = 0; $results['answers'] = 0; $results['surveys'] = 0; $results['languages'] = 0; $results['questions'] = 0; $results['subquestions'] = 0; $results['question_attributes'] = 0; $results['groups'] = 0; $results['importwarnings'] = array(); // these aren't used here, but are needed to avoid errors in post-import display $results['assessments'] = 0; $results['quota'] = 0; $results['quotamembers'] = 0; $results['quotals'] = 0; // collect information about survey and its language settings $surveyinfo = array(); $surveyls = array(); foreach ($adata as $row) { switch ($row['class']) { case 'S': if (isset($row['text']) && $row['name'] != 'datecreated') { $surveyinfo[$row['name']] = $row['text']; } break; case 'SL': if (!isset($surveyls[$row['language']])) { $surveyls[$row['language']] = array(); } if (isset($row['text'])) { $surveyls[$row['language']][$row['name']] = $row['text']; } break; } } $iOldSID = 1; if (isset($surveyinfo['sid'])) { $iOldSID = (int) $surveyinfo['sid']; } // Create the survey entry $surveyinfo['startdate'] = NULL; $surveyinfo['active'] = 'N'; // unset($surveyinfo['datecreated']); switchMSSQLIdentityInsert('surveys', true); $iNewSID = Survey::model()->insertNewSurvey($surveyinfo); //or safeDie($clang->gT("Error").": Failed to insert survey<br />"); if ($iNewSID == false) { $results['error'] = Survey::model()->getErrors(); $results['bFailed'] = true; return $results; } $surveyinfo['sid'] = $iNewSID; $results['surveys']++; switchMSSQLIdentityInsert('surveys', false); $results['newsid'] = $iNewSID; $gid = 0; $gseq = 0; // group_order $qid = 0; $qseq = 0; // question_order $qtype = 'T'; $aseq = 0; // answer sortorder // set the language for the survey $_title = 'Missing Title'; foreach ($surveyls as $_lang => $insertdata) { $insertdata['surveyls_survey_id'] = $iNewSID; $insertdata['surveyls_language'] = $_lang; if (isset($insertdata['surveyls_title'])) { $_title = $insertdata['surveyls_title']; } else { $insertdata['surveyls_title'] = $_title; } $result = Surveys_languagesettings::model()->insertNewSurvey($insertdata); // if (!$result) { $results['error'][] = $clang->gT("Error") . " : " . $clang->gT("Failed to insert survey language"); break; } $results['languages']++; } $ginfo = array(); $qinfo = array(); $sqinfo = array(); if (isset($surveyinfo['language'])) { $baselang = $surveyinfo['language']; // the base language } $rownumber = 1; foreach ($adata as $row) { $rownumber += 1; switch ($row['class']) { case 'G': // insert group $insertdata = array(); $insertdata['sid'] = $iNewSID; $gname = isset($row['name']) ? $row['name'] : 'G' . $gseq; $insertdata['group_name'] = $gname; $insertdata['grelevance'] = isset($row['relevance']) ? $row['relevance'] : ''; $insertdata['description'] = isset($row['text']) ? $row['text'] : ''; $insertdata['language'] = isset($row['language']) ? $row['language'] : $baselang; // For multi numeric survey : same title if (isset($ginfo[$gname])) { $gseq = $ginfo[$gname]['group_order']; $gid = $ginfo[$gname]['gid']; $insertdata['gid'] = $gid; $insertdata['group_order'] = $gseq; } else { $insertdata['group_order'] = $gseq; } $newgid = Groups::model()->insertRecords($insertdata); if (!$newgid) { $results['error'][] = $clang->gT("Error") . " : " . $clang->gT("Failed to insert group") . ". " . $clang->gT("Text file row number ") . $rownumber . " (" . $gname . ")"; break; } if (!isset($ginfo[$gname])) { $results['groups']++; $gid = $newgid; // save this for later $ginfo[$gname]['gid'] = $gid; $ginfo[$gname]['group_order'] = $gseq++; } $qseq = 0; // reset the question_order break; case 'Q': // insert question $insertdata = array(); $insertdata['sid'] = $iNewSID; $qtype = isset($row['type/scale']) ? $row['type/scale'] : 'T'; $qname = isset($row['name']) ? $row['name'] : 'Q' . $qseq; $insertdata['gid'] = $gid; $insertdata['type'] = $qtype; $insertdata['title'] = $qname; $insertdata['question'] = isset($row['text']) ? $row['text'] : ''; $insertdata['relevance'] = isset($row['relevance']) ? $row['relevance'] : ''; $insertdata['preg'] = isset($row['validation']) ? $row['validation'] : ''; $insertdata['help'] = isset($row['help']) ? $row['help'] : ''; $insertdata['language'] = isset($row['language']) ? $row['language'] : $baselang; $insertdata['mandatory'] = isset($row['mandatory']) ? $row['mandatory'] : ''; $insertdata['other'] = isset($row['other']) ? $row['other'] : 'N'; $insertdata['same_default'] = isset($row['same_default']) ? $row['same_default'] : 0; $insertdata['parent_qid'] = 0; // For multi numeric survey : same name, add the gid to have same name on different gid. Bad for EM. $fullqname = "G{$gid}_" . $qname; if (isset($qinfo[$fullqname])) { $qseq = $qinfo[$fullqname]['question_order']; $qid = $qinfo[$fullqname]['qid']; $insertdata['qid'] = $qid; $insertdata['question_order'] = $qseq; } else { $insertdata['question_order'] = $qseq; } // Insert question and keep the qid for multi language survey $result = Questions::model()->insertRecords($insertdata); if (!$result) { $results['error'][] = $clang->gT("Error") . " : " . $clang->gT("Could not insert question") . ". " . $clang->gT("Text file row number ") . $rownumber . " (" . $qname . ")"; break; } $newqid = $result; if (!isset($qinfo[$fullqname])) { $results['questions']++; $qid = $newqid; // save this for later $qinfo[$fullqname]['qid'] = $qid; $qinfo[$fullqname]['question_order'] = $qseq++; } $aseq = 0; //reset the answer sortorder $sqseq = 0; //reset the sub question sortorder // insert question attributes foreach ($row as $key => $val) { switch ($key) { case 'class': case 'type/scale': case 'name': case 'text': case 'validation': case 'relevance': case 'help': case 'language': case 'mandatory': case 'other': case 'same_default': case 'default': break; default: if ($key != '' && $val != '') { $insertdata = array(); $insertdata['qid'] = $qid; $insertdata['language'] = isset($row['language']) ? $row['language'] : $baselang; $insertdata['attribute'] = $key; $insertdata['value'] = $val; $result = Question_attributes::model()->insertRecords($insertdata); // if (!$result) { $results['importwarnings'][] = $clang->gT("Warning") . " : " . $clang->gT("Failed to insert question attribute") . ". " . $clang->gT("Text file row number ") . $rownumber . " ({$key})"; break; } $results['question_attributes']++; } break; } } // insert default value if (isset($row['default'])) { $insertdata = array(); $insertdata['qid'] = $qid; $insertdata['language'] = isset($row['language']) ? $row['language'] : $baselang; $insertdata['defaultvalue'] = $row['default']; $result = Defaultvalues::model()->insertRecords($insertdata); if (!$result) { $results['importwarnings'][] = $clang->gT("Warning") . " : " . $clang->gT("Failed to insert default value") . ". " . $clang->gT("Text file row number ") . $rownumber; break; } $results['defaultvalues']++; } break; case 'SQ': $sqname = isset($row['name']) ? $row['name'] : 'SQ' . $sqseq; if ($qtype == 'O' || $qtype == '|') { // these are fake rows to show naming of comment and filecount fields } elseif ($sqname == 'other' && ($qtype == '!' || $qtype == 'L')) { // only want to set default value for 'other' in these cases - not a real SQ row // TODO - this isn't working if (isset($row['default'])) { $insertdata = array(); $insertdata['qid'] = $qid; $insertdata['specialtype'] = 'other'; $insertdata['language'] = isset($row['language']) ? $row['language'] : $baselang; $insertdata['defaultvalue'] = $row['default']; $result = Defaultvalues::model()->insertRecords($insertdata); if (!$result) { $results['importwarnings'][] = $clang->gT("Warning") . " : " . $clang->gT("Failed to insert default value") . ". " . $clang->gT("Text file row number ") . $rownumber; break; } $results['defaultvalues']++; } } else { $insertdata = array(); $scale_id = isset($row['type/scale']) ? $row['type/scale'] : 0; $insertdata['sid'] = $iNewSID; $insertdata['gid'] = $gid; $insertdata['parent_qid'] = $qid; $insertdata['type'] = $qtype; $insertdata['title'] = $sqname; $insertdata['question'] = isset($row['text']) ? $row['text'] : ''; $insertdata['relevance'] = isset($row['relevance']) ? $row['relevance'] : ''; $insertdata['preg'] = isset($row['validation']) ? $row['validation'] : ''; $insertdata['help'] = isset($row['help']) ? $row['help'] : ''; $insertdata['language'] = isset($row['language']) ? $row['language'] : $baselang; $insertdata['mandatory'] = isset($row['mandatory']) ? $row['mandatory'] : ''; $insertdata['scale_id'] = $scale_id; // For multi nueric language, qid is needed, why not gid. name is not unique. $fullsqname = "G{$gid}Q{$qid}_{$sqname}"; if (isset($sqinfo[$fullsqname])) { $qseq = $sqinfo[$fullsqname]['question_order']; $sqid = $sqinfo[$fullsqname]['sqid']; $insertdata['question_order'] = $qseq; $insertdata['qid'] = $sqid; } else { $insertdata['question_order'] = $qseq; } // Insert sub question and keep the sqid for multi language survey $newsqid = Questions::model()->insertRecords($insertdata); if (!$newsqid) { $results['error'][] = $clang->gT("Error") . " : " . $clang->gT("Could not insert sub question") . ". " . $clang->gT("Text file row number ") . $rownumber . " (" . $qname . ")"; break; } if (!isset($sqinfo[$fullsqname])) { $sqinfo[$fullsqname]['question_order'] = $qseq++; $sqid = $newsqid; // save this for later $sqinfo[$fullsqname]['sqid'] = $sqid; $results['subquestions']++; } // insert default value if (isset($row['default'])) { $insertdata = array(); $insertdata['qid'] = $qid; $insertdata['sqid'] = $sqid; $insertdata['scale_id'] = $scale_id; $insertdata['language'] = isset($row['language']) ? $row['language'] : $baselang; $insertdata['defaultvalue'] = $row['default']; $result = Defaultvalues::model()->insertRecords($insertdata); if (!$result) { $results['importwarnings'][] = $clang->gT("Warning") . " : " . $clang->gT("Failed to insert default value") . ". " . $clang->gT("Text file row number ") . $rownumber; break; } $results['defaultvalues']++; } } break; case 'A': $insertdata = array(); $insertdata['qid'] = $qid; $insertdata['code'] = isset($row['name']) ? $row['name'] : 'A' . $aseq; $insertdata['answer'] = isset($row['text']) ? $row['text'] : ''; $insertdata['scale_id'] = isset($row['type/scale']) ? $row['type/scale'] : 0; $insertdata['language'] = isset($row['language']) ? $row['language'] : $baselang; $insertdata['assessment_value'] = isset($row['relevance']) ? $row['relevance'] : ''; $insertdata['sortorder'] = ++$aseq; $result = Answers::model()->insertRecords($insertdata); // or safeDie("Error: Failed to insert answer<br />"); if (!$result) { $results['error'][] = $clang->gT("Error") . " : " . $clang->gT("Could not insert answer") . ". " . $clang->gT("Text file row number ") . $rownumber; } $results['answers']++; break; } } // Delete the survey if error found if (is_array($results['error'])) { $result = Survey::model()->deleteSurvey($iNewSID); } return $results; }
/** * RPC Routine to return the ids and info of questions of a survey/group. * Returns array of ids and info. * * @access public * @param string $sSessionKey Auth credentials * @param int $iSurveyID Id of the survey to list questions * @param int $iGroupID Optional id of the group to list questions * @param string $sLanguage Optional parameter language for multilingual questions * @return array The list of questions */ public function list_questions($sSessionKey, $iSurveyID, $iGroupID = NULL, $sLanguage = NULL) { if ($this->_checkSessionKey($sSessionKey)) { Yii::app()->loadHelper("surveytranslator"); $oSurvey = Survey::model()->findByPk($iSurveyID); if (!isset($oSurvey)) { return array('status' => 'Error: Invalid survey ID'); } if (hasSurveyPermission($iSurveyID, 'survey', 'read')) { if (is_null($sLanguage)) { $sLanguage = $oSurvey->language; } if (!array_key_exists($sLanguage, getLanguageDataRestricted())) { return array('status' => 'Error: Invalid language'); } if ($iGroupID != NULL) { $oGroup = Groups::model()->findByAttributes(array('gid' => $iGroupID)); $sGroupSurveyID = $oGroup['sid']; if ($sGroupSurveyID != $iSurveyID) { return array('status' => 'Error: IMissmatch in surveyid and groupid'); } else { $aQuestionList = Questions::model()->findAllByAttributes(array("sid" => $iSurveyID, "gid" => $iGroupID, "parent_qid" => "0", "language" => $sLanguage)); } } else { $aQuestionList = Questions::model()->findAllByAttributes(array("sid" => $iSurveyID, "parent_qid" => "0", "language" => $sLanguage)); } if (count($aQuestionList) == 0) { return array('status' => 'No questions found'); } foreach ($aQuestionList as $oQuestion) { $aData[] = array('id' => $oQuestion->primaryKey, 'type' => $oQuestion->attributes['type'], 'question' => $oQuestion->attributes['question']); } return $aData; } else { return array('status' => 'No permission'); } } else { return array('status' => 'Invalid session key'); } }
/** * This function builds all the required session variables when a survey is first started and * it loads any answer defaults from command line or from the table defaultvalues * It is called from the related format script (group.php, question.php, survey.php) * if the survey has just started. */ function buildsurveysession($surveyid, $preview = false) { global $secerror, $clienttoken; global $tokensexist; //global $surveyid; global $templang, $move, $rooturl; $clang = Yii::app()->lang; $thissurvey = getSurveyInfo($surveyid); if (empty($templang)) { $templang = $thissurvey['language']; } $_SESSION['survey_' . $surveyid]['templatename'] = validateTemplateDir($thissurvey['template']); $_SESSION['survey_' . $surveyid]['templatepath'] = getTemplatePath($_SESSION['survey_' . $surveyid]['templatename']) . DIRECTORY_SEPARATOR; $sTemplatePath = $_SESSION['survey_' . $surveyid]['templatepath']; $loadsecurity = returnGlobal('loadsecurity'); // NO TOKEN REQUIRED BUT CAPTCHA ENABLED FOR SURVEY ACCESS if ($tokensexist == 0 && isCaptchaEnabled('surveyaccessscreen', $thissurvey['usecaptcha'])) { // IF CAPTCHA ANSWER IS NOT CORRECT OR NOT SET if (!isset($loadsecurity) || !isset($_SESSION['survey_' . $surveyid]['secanswer']) || $loadsecurity != $_SESSION['survey_' . $surveyid]['secanswer']) { sendCacheHeaders(); doHeader(); // No or bad answer to required security question $redata = compact(array_keys(get_defined_vars())); echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'frontend_helper[1525]'); //echo makedropdownlist(); echo templatereplace(file_get_contents($sTemplatePath . "survey.pstpl"), array(), $redata, 'frontend_helper[1527]'); if (isset($loadsecurity)) { // was a bad answer echo "<font color='#FF0000'>" . $clang->gT("The answer to the security question is incorrect.") . "</font><br />"; } echo "<p class='captcha'>" . $clang->gT("Please confirm access to survey by answering the security question below and click continue.") . "</p>" . CHtml::form(array("/survey/index/sid/{$surveyid}"), 'post', array('class' => 'captcha')) . "\n <table align='center'>\n <tr>\n <td align='right' valign='middle'>\n <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n <input type='hidden' name='lang' value='" . $templang . "' id='lang' />"; // In case we this is a direct Reload previous answers URL, then add hidden fields if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) { echo "\n <input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n <input type='hidden' name='scid' value='" . returnGlobal('scid') . "' id='scid' />\n <input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n <input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />"; } echo "\n </td>\n </tr>"; if (function_exists("ImageCreate") && isCaptchaEnabled('surveyaccessscreen', $thissurvey['usecaptcha'])) { echo "<tr>\n <td align='center' valign='middle'><label for='captcha'>" . $clang->gT("Security question:") . "</label></td><td align='left' valign='middle'><table><tr><td valign='middle'><img src='" . Yii::app()->getController()->createUrl('/verification/image/sid/' . $surveyid) . "' alt='captcha' /></td>\n <td valign='middle'><input id='captcha' type='text' size='5' maxlength='3' name='loadsecurity' value='' /></td></tr></table>\n </td>\n </tr>"; } echo "<tr><td colspan='2' align='center'><input class='submit' type='submit' value='" . $clang->gT("Continue") . "' /></td></tr>\n </table>\n </form>"; echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata, 'frontend_helper[1567]'); doFooter(); exit; } } //BEFORE BUILDING A NEW SESSION FOR THIS SURVEY, LET'S CHECK TO MAKE SURE THE SURVEY SHOULD PROCEED! // TOKEN REQUIRED BUT NO TOKEN PROVIDED if ($tokensexist == 1 && !$clienttoken && !$preview) { if ($thissurvey['nokeyboard'] == 'Y') { includeKeypad(); $kpclass = "text-keypad"; } else { $kpclass = ""; } // DISPLAY REGISTER-PAGE if needed // DISPLAY CAPTCHA if needed sendCacheHeaders(); doHeader(); $redata = compact(array_keys(get_defined_vars())); echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'frontend_helper[1594]'); //echo makedropdownlist(); echo templatereplace(file_get_contents($sTemplatePath . "survey.pstpl"), array(), $redata, 'frontend_helper[1596]'); if (isset($thissurvey) && $thissurvey['allowregister'] == "Y") { echo templatereplace(file_get_contents($sTemplatePath . "register.pstpl"), array(), $redata, 'frontend_helper[1599]'); } else { // ->renderPartial('entertoken_view'); if (isset($secerror)) { echo "<span class='error'>" . $secerror . "</span><br />"; } echo '<div id="wrapper"><p id="tokenmessage">' . $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br />"; echo $clang->gT("If you have been issued a token, please enter it in the box below and click continue.") . "</p>\n <script type='text/javascript'>var focus_element='#token';</script>" . CHtml::form(array("/survey/index/sid/{$surveyid}"), 'post', array('id' => 'tokenform')) . "\n <ul>\n <li>"; ?> <label for='token'><?php $clang->eT("Token:"); ?> </label><input class='text <?php echo $kpclass; ?> ' id='token' type='text' name='token' /> <?php echo "<input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n <input type='hidden' name='lang' value='" . $templang . "' id='lang' />"; if (isset($_GET['newtest']) && $_GET['newtest'] == "Y") { echo " <input type='hidden' name='newtest' value='Y' id='newtest' />"; } // If this is a direct Reload previous answers URL, then add hidden fields if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) { echo "\n <input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n <input type='hidden' name='scid' value='" . returnGlobal('scid') . "' id='scid' />\n <input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n <input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />"; } echo "</li>"; if (function_exists("ImageCreate") && isCaptchaEnabled('surveyaccessscreen', $thissurvey['usecaptcha'])) { echo "<li>\n <label for='captchaimage'>" . $clang->gT("Security Question") . "</label><img id='captchaimage' src='" . Yii::app()->getController()->createUrl('/verification/image/sid/' . $surveyid) . "' alt='captcha' /><input type='text' size='5' maxlength='3' name='loadsecurity' value='' />\n </li>"; } echo "<li>\n <input class='submit' type='submit' value='" . $clang->gT("Continue") . "' />\n </li>\n </ul>\n </form></div>"; } echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata, 'frontend_helper[1645]'); doFooter(); exit; } elseif ($tokensexist == 1 && $clienttoken && !isCaptchaEnabled('surveyaccessscreen', $thissurvey['usecaptcha'])) { //check if tokens actually haven't been already used $areTokensUsed = usedTokens(trim(strip_tags($clienttoken)), $surveyid); //check if token actually does exist // check also if it is allowed to change survey after completion if ($thissurvey['alloweditaftercompletion'] == 'Y') { $oTokenEntry = Tokens_dynamic::model($surveyid)->find('token=:token', array(':token' => trim(strip_tags($clienttoken)))); } else { $oTokenEntry = Tokens_dynamic::model($surveyid)->find("token=:token AND (completed = 'N' or completed='')", array(':token' => trim(strip_tags($clienttoken)))); } if (is_null($oTokenEntry) || $areTokensUsed && $thissurvey['alloweditaftercompletion'] != 'Y') { //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT killSurveySession($surveyid); sendCacheHeaders(); doHeader(); $redata = compact(array_keys(get_defined_vars())); echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'frontend_helper[1676]'); echo templatereplace(file_get_contents($sTemplatePath . "survey.pstpl"), array(), $redata, 'frontend_helper[1677]'); echo '<div id="wrapper"><p id="tokenmessage">' . $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br /><br />\n" . "\t" . $clang->gT("The token you have provided is either not valid, or has already been used.") . "<br /><br />\n" . "\t" . sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname']) . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)</p></div>\n"; echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata, 'frontend_helper[1684]'); doFooter(); exit; } } elseif ($tokensexist == 1 && $clienttoken && isCaptchaEnabled('surveyaccessscreen', $thissurvey['usecaptcha'])) { // IF CAPTCHA ANSWER IS CORRECT if (isset($loadsecurity) && isset($_SESSION['survey_' . $surveyid]['secanswer']) && $loadsecurity == $_SESSION['survey_' . $surveyid]['secanswer']) { //check if tokens actually haven't been already used $areTokensUsed = usedTokens(trim(strip_tags($clienttoken)), $surveyid); //check if token actually does exist $oTokenEntry = Tokens_dynamic::model($surveyid)->find('token=:token', array(':token' => trim(strip_tags($clienttoken)))); if ($thissurvey['alloweditaftercompletion'] == 'Y') { $oTokenEntry = Tokens_dynamic::model($surveyid)->find('token=:token', array(':token' => trim(strip_tags($clienttoken)))); } else { $oTokenEntry = Tokens_dynamic::model($surveyid)->find("token=:token AND (completed = 'N' or completed='')", array(':token' => trim(strip_tags($clienttoken)))); } if (is_null($oTokenEntry) || $areTokensUsed && $thissurvey['alloweditaftercompletion'] != 'Y') { sendCacheHeaders(); doHeader(); //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT $redata = compact(array_keys(get_defined_vars())); echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'frontend_helper[1719]'); echo templatereplace(file_get_contents($sTemplatePath . "survey.pstpl"), array(), $redata, 'frontend_helper[1720]'); echo "\t<div id='wrapper'>\n" . "\t<p id='tokenmessage'>\n" . "\t" . $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br /><br />\n" . "\t" . $clang->gT("The token you have provided is either not valid, or has already been used.") . "<br/><br />\n" . "\t" . sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname']) . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)\n" . "\t</p>\n" . "\t</div>\n"; echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata, 'frontend_helper[1731]'); doFooter(); exit; } } else { if (!isset($move) || is_null($move)) { unset($_SESSION['survey_' . $surveyid]['srid']); $gettoken = $clienttoken; sendCacheHeaders(); doHeader(); // No or bad answer to required security question $redata = compact(array_keys(get_defined_vars())); echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'frontend_helper[1745]'); echo templatereplace(file_get_contents($sTemplatePath . "survey.pstpl"), array(), $redata, 'frontend_helper[1746]'); // If token wasn't provided and public registration // is enabled then show registration form if (!isset($gettoken) && isset($thissurvey) && $thissurvey['allowregister'] == "Y") { echo templatereplace(file_get_contents($sTemplatePath . "register.pstpl"), array(), $redata, 'frontend_helper[1751]'); } else { // only show CAPTCHA echo '<div id="wrapper"><p id="tokenmessage">'; if (isset($loadsecurity)) { // was a bad answer echo "<span class='error'>" . $clang->gT("The answer to the security question is incorrect.") . "</span><br />"; } echo $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br /><br />"; // IF TOKEN HAS BEEN GIVEN THEN AUTOFILL IT // AND HIDE ENTRY FIELD if (!isset($gettoken)) { echo $clang->gT("If you have been issued a token, please enter it in the box below and click continue.") . "</p>\n <form id='tokenform' method='get' action='" . Yii::app()->getController()->createUrl("/survey/index") . "'>\n <ul>\n <li>\n <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n <input type='hidden' name='lang' value='" . $templang . "' id='lang' />"; if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) { echo "<input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n <input type='hidden' name='scid' value='" . returnGlobal('scid') . "' id='scid' />\n <input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n <input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />"; } echo '<label for="token">' . $clang->gT("Token") . "</label><input class='text' type='text' id='token' name='token'></li>"; } else { echo $clang->gT("Please confirm the token by answering the security question below and click continue.") . "</p>\n <form id='tokenform' method='get' action='" . Yii::app()->getController()->createUrl("/survey/index") . "'>\n <ul>\n <li>\n <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n <input type='hidden' name='lang' value='" . $templang . "' id='lang' />"; if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) { echo "<input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n <input type='hidden' name='scid' value='" . returnGlobal('scid') . "' id='scid' />\n <input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n <input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />"; } echo '<label for="token">' . $clang->gT("Token:") . "</label><span id='token'>{$gettoken}</span>" . "<input type='hidden' name='token' value='{$gettoken}'></li>"; } if (function_exists("ImageCreate") && isCaptchaEnabled('surveyaccessscreen', $thissurvey['usecaptcha'])) { echo "<li>\n <label for='captchaimage'>" . $clang->gT("Security Question") . "</label><img id='captchaimage' src='" . Yii::app()->getController()->createUrl('/verification/image/sid/' . $surveyid) . "' alt='captcha' /><input type='text' size='5' maxlength='3' name='loadsecurity' value='' />\n </li>"; } echo "<li><input class='submit' type='submit' value='" . $clang->gT("Continue") . "' /></li>\n </ul>\n </form>\n </id>"; } echo '</div>' . templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata, 'frontend_helper[1817]'); doFooter(); exit; } } } //RESET ALL THE SESSION VARIABLES AND START AGAIN unset($_SESSION['survey_' . $surveyid]['grouplist']); unset($_SESSION['survey_' . $surveyid]['fieldarray']); unset($_SESSION['survey_' . $surveyid]['insertarray']); unset($_SESSION['survey_' . $surveyid]['thistoken']); unset($_SESSION['survey_' . $surveyid]['fieldnamesInfo']); unset($_SESSION['survey_' . $surveyid]['fieldmap-' . $surveyid . '-randMaster']); unset($_SESSION['survey_' . $surveyid]['groupReMap']); $_SESSION['survey_' . $surveyid]['fieldnamesInfo'] = array(); //RL: multilingual support if (isset($_GET['token']) && tableExists('{{tokens_' . $surveyid . '}}')) { //get language from token (if one exists) $tkquery2 = "SELECT * FROM {{tokens_" . $surveyid . "}} WHERE token='" . $clienttoken . "' AND (completed = 'N' or completed='')"; //echo $tkquery2; $result = dbExecuteAssoc($tkquery2) or safeDie("Couldn't get tokens<br />{$tkquery}<br />"); //Checked foreach ($result->readAll() as $rw) { $tklanguage = $rw['language']; } } if (returnGlobal('lang')) { $language_to_set = returnGlobal('lang'); } elseif (isset($tklanguage)) { $language_to_set = $tklanguage; } else { $language_to_set = $thissurvey['language']; } if (!isset($_SESSION['survey_' . $surveyid]['s_lang'])) { SetSurveyLanguage($surveyid, $language_to_set); } UpdateGroupList($surveyid, $_SESSION['survey_' . $surveyid]['s_lang']); $sQuery = "SELECT count(*)\n" . " FROM {{groups}} INNER JOIN {{questions}} ON {{groups}}.gid = {{questions}}.gid\n" . " WHERE {{questions}}.sid=" . $surveyid . "\n" . " AND {{groups}}.language='" . $_SESSION['survey_' . $surveyid]['s_lang'] . "'\n" . " AND {{questions}}.language='" . $_SESSION['survey_' . $surveyid]['s_lang'] . "'\n" . " AND {{questions}}.parent_qid=0\n"; $totalquestions = Yii::app()->db->createCommand($sQuery)->queryScalar(); // Fix totalquestions by substracting Test Display questions $iNumberofQuestions = dbExecuteAssoc("SELECT count(*)\n" . " FROM {{questions}}" . " WHERE type in ('X','*')\n" . " AND sid={$surveyid}" . " AND language='" . $_SESSION['survey_' . $surveyid]['s_lang'] . "'" . " AND parent_qid=0")->read(); $_SESSION['survey_' . $surveyid]['totalquestions'] = $totalquestions - (int) reset($iNumberofQuestions); //2. SESSION VARIABLE: totalsteps //The number of "pages" that will be presented in this survey //The number of pages to be presented will differ depending on the survey format switch ($thissurvey['format']) { case "A": $_SESSION['survey_' . $surveyid]['totalsteps'] = 1; break; case "G": if (isset($_SESSION['survey_' . $surveyid]['grouplist'])) { $_SESSION['survey_' . $surveyid]['totalsteps'] = count($_SESSION['survey_' . $surveyid]['grouplist']); } break; case "S": $_SESSION['survey_' . $surveyid]['totalsteps'] = $totalquestions; } if ($totalquestions == 0) { sendCacheHeaders(); doHeader(); $redata = compact(array_keys(get_defined_vars())); echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'frontend_helper[1914]'); echo templatereplace(file_get_contents($sTemplatePath . "survey.pstpl"), array(), $redata, 'frontend_helper[1915]'); echo "\t<div id='wrapper'>\n" . "\t<p id='tokenmessage'>\n" . "\t" . $clang->gT("This survey does not yet have any questions and cannot be tested or completed.") . "<br /><br />\n" . "\t" . sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname']) . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)<br /><br />\n" . "\t</p>\n" . "\t</div>\n"; echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata, 'frontend_helper[1925]'); doFooter(); exit; } //Perform a case insensitive natural sort on group name then question title of a multidimensional array // usort($arows, 'groupOrderThenQuestionOrder'); //3. SESSION VARIABLE - insertarray //An array containing information about used to insert the data into the db at the submit stage //4. SESSION VARIABLE - fieldarray //See rem at end.. $_SESSION['survey_' . $surveyid]['token'] = $clienttoken; if ($thissurvey['anonymized'] == "N") { $_SESSION['survey_' . $surveyid]['insertarray'][] = "token"; } if ($tokensexist == 1 && $thissurvey['anonymized'] == "N" && tableExists('{{tokens_' . $surveyid . '}}')) { //Gather survey data for "non anonymous" surveys, for use in presenting questions $_SESSION['survey_' . $surveyid]['thistoken'] = getTokenData($surveyid, $clienttoken); } $qtypes = getQuestionTypeList('', 'array'); $fieldmap = createFieldMap($surveyid, 'full', true, false, $_SESSION['survey_' . $surveyid]['s_lang']); // Randomization groups for groups $aRandomGroups = array(); $aGIDCompleteMap = array(); // first find all groups and their groups IDS $criteria = new CDbCriteria(); $criteria->addColumnCondition(array('sid' => $surveyid, 'language' => $_SESSION['survey_' . $surveyid]['s_lang'])); $criteria->addCondition("randomization_group != ''"); $oData = Groups::model()->findAll($criteria); foreach ($oData as $aGroup) { $aRandomGroups[$aGroup['randomization_group']][] = $aGroup['gid']; } // Shuffle each group and create a map for old GID => new GID foreach ($aRandomGroups as $sGroupName => $aGIDs) { $aShuffledIDs = $aGIDs; shuffle($aShuffledIDs); $aGIDCompleteMap = $aGIDCompleteMap + array_combine($aGIDs, $aShuffledIDs); } $_SESSION['survey_' . $surveyid]['groupReMap'] = $aGIDCompleteMap; $randomized = false; // So we can trigger reorder once for group and question randomization // Now adjust the grouplist if (count($aRandomGroups) > 0) { $randomized = true; // So we can trigger reorder once for group and question randomization // Now adjust the grouplist Yii::import('application.helpers.frontend_helper', true); // make sure frontend helper is loaded UpdateGroupList($surveyid, $_SESSION['survey_' . $surveyid]['s_lang']); // ... and the fieldmap // First create a fieldmap with GID as key foreach ($fieldmap as $aField) { if (isset($aField['gid'])) { $GroupFieldMap[$aField['gid']][] = $aField; } else { $GroupFieldMap['other'][] = $aField; } } // swap it foreach ($GroupFieldMap as $iOldGid => $fields) { $iNewGid = $iOldGid; if (isset($aGIDCompleteMap[$iOldGid])) { $iNewGid = $aGIDCompleteMap[$iOldGid]; } $newGroupFieldMap[$iNewGid] = $GroupFieldMap[$iNewGid]; } $GroupFieldMap = $newGroupFieldMap; // and convert it back to a fieldmap unset($fieldmap); foreach ($GroupFieldMap as $aGroupFields) { foreach ($aGroupFields as $aField) { if (isset($aField['fieldname'])) { $fieldmap[$aField['fieldname']] = $aField; // isset() because of the shuffled flag above } } } unset($GroupFieldMap); } // Randomization groups for questions // Find all defined randomization groups through question attribute values $randomGroups = array(); if (in_array(Yii::app()->db->getDriverName(), array('mssql', 'sqlsrv'))) { $rgquery = "SELECT attr.qid, CAST(value as varchar(255)) as value FROM {{question_attributes}} as attr right join {{questions}} as quests on attr.qid=quests.qid WHERE attribute='random_group' and CAST(value as varchar(255)) <> '' and sid={$surveyid} GROUP BY attr.qid, CAST(value as varchar(255))"; } else { $rgquery = "SELECT attr.qid, value FROM {{question_attributes}} as attr right join {{questions}} as quests on attr.qid=quests.qid WHERE attribute='random_group' and value <> '' and sid={$surveyid} GROUP BY attr.qid, value"; } $rgresult = dbExecuteAssoc($rgquery); foreach ($rgresult->readAll() as $rgrow) { // Get the question IDs for each randomization group $randomGroups[$rgrow['value']][] = $rgrow['qid']; } // If we have randomization groups set, then lets cycle through each group and // replace questions in the group with a randomly chosen one from the same group if (count($randomGroups) > 0) { $randomized = true; // So we can trigger reorder once for group and question randomization $copyFieldMap = array(); $oldQuestOrder = array(); $newQuestOrder = array(); $randGroupNames = array(); foreach ($randomGroups as $key => $value) { $oldQuestOrder[$key] = $randomGroups[$key]; $newQuestOrder[$key] = $oldQuestOrder[$key]; // We shuffle the question list to get a random key->qid which will be used to swap from the old key shuffle($newQuestOrder[$key]); $randGroupNames[] = $key; } // Loop through the fieldmap and swap each question as they come up foreach ($fieldmap as $fieldkey => $fieldval) { $found = 0; foreach ($randomGroups as $gkey => $gval) { // We found a qid that is in the randomization group if (isset($fieldval['qid']) && in_array($fieldval['qid'], $oldQuestOrder[$gkey])) { // Get the swapped question $idx = array_search($fieldval['qid'], $oldQuestOrder[$gkey]); foreach ($fieldmap as $key => $field) { if (isset($field['qid']) && $field['qid'] == $newQuestOrder[$gkey][$idx]) { $field['random_gid'] = $fieldval['gid']; // It is possible to swap to another group $copyFieldMap[$key] = $field; } } $found = 1; break; } else { $found = 2; } } if ($found == 2) { $copyFieldMap[$fieldkey] = $fieldval; } reset($randomGroups); } $fieldmap = $copyFieldMap; } if ($randomized === true) { // reset the sequencing counts $gseq = -1; $_gid = -1; $qseq = -1; $_qid = -1; $copyFieldMap = array(); foreach ($fieldmap as $key => $val) { if ($val['gid'] != '') { if (isset($val['random_gid'])) { $gid = $val['random_gid']; } else { $gid = $val['gid']; } if ($gid != $_gid) { $_gid = $gid; ++$gseq; } } if ($val['qid'] != '' && $val['qid'] != $_qid) { $_qid = $val['qid']; ++$qseq; } if ($val['gid'] != '' && $val['qid'] != '') { $val['groupSeq'] = $gseq; $val['questionSeq'] = $qseq; } $copyFieldMap[$key] = $val; } $fieldmap = $copyFieldMap; unset($copyFieldMap); $_SESSION['survey_' . $surveyid]['fieldmap-' . $surveyid . $_SESSION['survey_' . $surveyid]['s_lang']] = $fieldmap; $_SESSION['survey_' . $surveyid]['fieldmap-' . $surveyid . '-randMaster'] = 'fieldmap-' . $surveyid . $_SESSION['survey_' . $surveyid]['s_lang']; } // TMSW Conditions->Relevance: don't need hasconditions, or usedinconditions $_SESSION['survey_' . $surveyid]['fieldmap'] = $fieldmap; foreach ($fieldmap as $field) { if (isset($field['qid']) && $field['qid'] != '') { $_SESSION['survey_' . $surveyid]['fieldnamesInfo'][$field['fieldname']] = $field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']; $_SESSION['survey_' . $surveyid]['insertarray'][] = $field['fieldname']; //fieldarray ARRAY CONTENTS - // [0]=questions.qid, // [1]=fieldname, // [2]=questions.title, // [3]=questions.question // [4]=questions.type, // [5]=questions.gid, // [6]=questions.mandatory, // [7]=conditionsexist, // [8]=usedinconditions // [8]=usedinconditions // [9]=used in group.php for question count // [10]=new group id for question in randomization group (GroupbyGroup Mode) if (!isset($_SESSION['survey_' . $surveyid]['fieldarray'][$field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']])) { //JUST IN CASE : PRECAUTION! //following variables are set only if $style=="full" in createFieldMap() in common_helper. //so, if $style = "short", set some default values here! if (isset($field['title'])) { $title = $field['title']; } else { $title = ""; } if (isset($field['question'])) { $question = $field['question']; } else { $question = ""; } if (isset($field['mandatory'])) { $mandatory = $field['mandatory']; } else { $mandatory = 'N'; } if (isset($field['hasconditions'])) { $hasconditions = $field['hasconditions']; } else { $hasconditions = 'N'; } if (isset($field['usedinconditions'])) { $usedinconditions = $field['usedinconditions']; } else { $usedinconditions = 'N'; } $_SESSION['survey_' . $surveyid]['fieldarray'][$field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']] = array($field['qid'], $field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid'], $title, $question, $field['type'], $field['gid'], $mandatory, $hasconditions, $usedinconditions); } if (isset($field['random_gid'])) { $_SESSION['survey_' . $surveyid]['fieldarray'][$field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']][10] = $field['random_gid']; } } } // Prefill questions/answers from command line params $reservedGetValues = array('token', 'sid', 'gid', 'qid', 'lang', 'newtest', 'action'); $startingValues = array(); if (isset($_GET)) { foreach ($_GET as $k => $v) { if (!in_array($k, $reservedGetValues) && isset($_SESSION['survey_' . $surveyid]['fieldmap'][$k])) { $startingValues[$k] = $v; } } } $_SESSION['survey_' . $surveyid]['startingValues'] = $startingValues; if (isset($_SESSION['survey_' . $surveyid]['fieldarray'])) { $_SESSION['survey_' . $surveyid]['fieldarray'] = array_values($_SESSION['survey_' . $surveyid]['fieldarray']); } //Check if a passthru label and value have been included in the query url $oResult = Survey_url_parameters::model()->getParametersForSurvey($surveyid); foreach ($oResult->readAll() as $aRow) { if (isset($_GET[$aRow['parameter']]) && !$preview) { $_SESSION['survey_' . $surveyid]['urlparams'][$aRow['parameter']] = $_GET[$aRow['parameter']]; if ($aRow['targetqid'] != '') { foreach ($fieldmap as $sFieldname => $aField) { if ($aRow['targetsqid'] != '') { if ($aField['qid'] == $aRow['targetqid'] && $aField['sqid'] == $aRow['targetsqid']) { $_SESSION['survey_' . $surveyid]['startingValues'][$sFieldname] = $_GET[$aRow['parameter']]; $_SESSION['survey_' . $surveyid]['startingValues'][$aRow['parameter']] = $_GET[$aRow['parameter']]; } } else { if ($aField['qid'] == $aRow['targetqid']) { $_SESSION['survey_' . $surveyid]['startingValues'][$sFieldname] = $_GET[$aRow['parameter']]; $_SESSION['survey_' . $surveyid]['startingValues'][$aRow['parameter']] = $_GET[$aRow['parameter']]; } } } } } } }
* California 95067, USA. or at email address contact@x2engine.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Powered by * X2Engine" logo. If the display of the logo is not reasonably feasible for * technical reasons, the Appropriate Legal Notices must display the words * "Powered by X2Engine". *****************************************************************************************/ LoginThemeHelper::init(); Yii::app()->clientScript->registerCssFile($this->module->assetsUrl . '/css/users.css'); $groups = array(); foreach (Groups::model()->findAll() as $group) { $groups[$group->id] = $group->name; } $roles = array(); foreach (Roles::model()->findAll() as $role) { $roles[$role->id] = $role->name; } ?> <!--<div class="page-title icon users"><h2> <?php echo Yii::t('users', 'Create {user}', array('{user}' => Modules::displayName(false))); ?> </h2></div> --> <div id="container"> <div id="login-box-outer"> <div id="login-box">
/** * Updates a particular model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id the ID of the model to be updated */ public function actionUpdate($id) { $model = $this->loadModel($id); $users = User::getNames(); unset($users['admin']); unset($users['']); foreach (Groups::model()->findAll() as $group) { $users[$group->id] = $group->name; } if (isset($_POST['Services'])) { $temp = $model->attributes; foreach ($_POST['Services'] as $name => &$value) { if ($value == $model->getAttributeLabel($name)) { $value = null; } } $model->setX2Fields($_POST['Services']); if ($model->contactId != '' && !is_numeric($model->contactId)) { // make sure an existing contact is associated with this case, otherwise don't create it $model->addError('contactId', Yii::t('services', 'Contact does not exist')); } // $this->update($model,$temp,'0'); if ($model->save()) { $this->redirect(array('view', 'id' => $model->id)); } } $this->render('update', array('model' => $model, 'users' => $users)); }
private function _reorderGroup($iSurveyID) { $AOrgData = array(); parse_str($_POST['orgdata'], $AOrgData); $grouporder = 0; foreach ($AOrgData['list'] as $ID => $parent) { if ($parent == 'root' && $ID[0] == 'g') { Groups::model()->updateAll(array('group_order' => $grouporder), 'gid=:gid', array(':gid' => (int) substr($ID, 1))); $grouporder++; } elseif ($ID[0] == 'q') { if (!isset($questionorder[(int) substr($parent, 1)])) { $questionorder[(int) substr($parent, 1)] = 0; } Questions::model()->updateAll(array('question_order' => $questionorder[(int) substr($parent, 1)], 'gid' => (int) substr($parent, 1)), 'qid=:qid', array(':qid' => (int) substr($ID, 1))); Questions::model()->updateAll(array('gid' => (int) substr($parent, 1)), 'parent_qid=:parent_qid', array(':parent_qid' => (int) substr($ID, 1))); $questionorder[(int) substr($parent, 1)]++; } } LimeExpressionManager::SetDirtyFlag(); // so refreshes syntax highlighting Yii::app()->session['flashmessage'] = Yii::app()->lang->gT("The new question group/question order was successfully saved."); $this->getController()->redirect($this->getController()->createUrl('admin/survey/sa/view/surveyid/' . $iSurveyID)); }
public static function getUserLinks($users) { if (!is_array($users)) { /* x2temp */ if (is_numeric($users)) { $group = Groups::model()->findByPk($users); if (isset($group)) { $link = CHtml::link($group->name, array('/groups/default/view', 'id' => $group->id)); } else { $link = ""; } return $link; } /* end x2temp */ if ($users == '' || $users == "Anyone") { return Yii::t('app', 'Anyone'); } $users = explode(', ', $users); } $links = ''; foreach ($users as $user) { if ($user == 'Anyone' || $user == 'Email') { $link = ''; } else { if (is_numeric($user)) { $group = Groups::model()->findByPk($users); if (isset($group)) { $link = CHtml::link($group->name, array('/groups/default/view', 'id' => $group->id)); } else { $link = ''; } $links .= $link . ", "; } else { $model = CActiveRecord::model('User')->findByAttributes(array('username' => $user)); if (isset($model)) { $link = CHtml::link($model->name, array('/profile/view', 'id' => $model->id)); } else { $link = ''; } $links .= $link . ', '; } } } $links = substr($links, 0, strlen($links) - 2); return $links; }
/** * Generates a display-friendly list of assignees * * @param mixed $value If specified, use as the assignment instead of the * current model's assignment field. */ public function getAssigneeNames($value = false) { $assignment = !$value ? $this->owner->getAttribute($this->getAssignmentAttr()) : $value; $assignees = !is_array($assignment) ? explode(', ', $assignment) : $assignment; $groupIds = array_filter($assignees, 'ctype_digit'); $userNames = array_diff($assignees, $groupIds); $userNameParam = AuxLib::bindArray($userNames); $userFullNames = !empty($userNames) ? array_map(function ($u) { return Formatter::fullName($u['firstName'], $u['lastName']); }, Yii::app()->db->createCommand()->select('firstName,lastName')->from(User::model()->tableName())->where('username IN ' . AuxLib::arrToStrList(array_keys($userNameParam)), $userNameParam)->queryAll()) : array(); $groupIdParam = AuxLib::bindArray($groupIds); $groupNames = !empty($groupIds) ? Yii::app()->db->createCommand()->select('name')->from(Groups::model()->tableName())->where('id IN ' . AuxLib::arrToStrList(array_keys($groupIdParam)), $groupIdParam)->queryColumn() : array(); return array_merge($userFullNames, $groupNames); }
function group_export($action, $iSurveyID, $gid) { $fn = "limesurvey_group_{$gid}.lsg"; $xml = getXMLWriter(); header("Content-Type: text/html/force-download"); header("Content-Disposition: attachment; filename={$fn}"); header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Pragma: cache"); // HTTP/1.0 $xml->openUri('php://output'); $xml->setIndent(true); $xml->startDocument('1.0', 'UTF-8'); $xml->startElement('document'); $xml->writeElement('LimeSurveyDocType', 'Group'); $xml->writeElement('DBVersion', getGlobalSetting("DBVersion")); $xml->startElement('languages'); $lresult = Groups::model()->findAllByAttributes(array('gid' => $gid), array('select' => 'language', 'group' => 'language')); foreach ($lresult as $row) { $xml->writeElement('language', $row->language); } $xml->endElement(); groupGetXMLStructure($xml, $gid); $xml->endElement(); // close columns $xml->endDocument(); }
/** * Show printable survey */ function index($surveyid, $lang = null) { $surveyid = sanitize_int($surveyid); //echo '<pre>'.print_r($_SESSION,true).'</pre>'; // PRESENT SURVEY DATAENTRY SCREEN if (isset($_POST['printableexport'])) { Yii::import("application.libraries.admin.pdf"); $pdf = new PDF($pdforientation, 'mm', 'A4'); $pdf->SetFont($pdfdefaultfont, '', $pdffontsize); $pdf->AddPage(); } // Set the language of the survey, either from GET parameter of session var if (isset($lang)) { $lang = preg_replace("/[^a-zA-Z0-9-]/", "", $lang); if ($lang) { $surveyprintlang = $lang; } } else { $surveyprintlang = getBaseLanguageFromSurveyID((int) $surveyid); } $_POST['surveyprintlang'] = $surveyprintlang; // Setting the selected language for printout $clang = new limesurvey_lang($surveyprintlang); $desrow = Survey::model()->with(array('languagesettings' => array('condition' => 'surveyls_language=:language', 'params' => array(':language' => $surveyprintlang))))->findByAttributes(array('sid' => $surveyid)); if (is_null($desrow)) { $this->getController()->error('Invalid survey ID'); } $desrow = array_merge($desrow->attributes, $desrow->languagesettings[0]->attributes); //echo '<pre>'.print_r($desrow,true).'</pre>'; $template = $desrow['template']; $welcome = $desrow['surveyls_welcometext']; $end = $desrow['surveyls_endtext']; $surveyname = $desrow['surveyls_title']; $surveydesc = $desrow['surveyls_description']; $surveyactive = $desrow['active']; $surveytable = "{{survey_" . $desrow['sid'] . "}}"; $surveyexpirydate = $desrow['expires']; $surveystartdate = $desrow['startdate']; $surveyfaxto = $desrow['faxto']; $dateformattype = $desrow['surveyls_dateformat']; if (isset($_POST['printableexport'])) { $pdf->titleintopdf($surveyname, $surveydesc); } Yii::app()->loadHelper('surveytranslator'); $dformat = getDateFormatData($dateformattype); $dformat = $dformat['phpdate']; $expirytimestamp = strtotime($surveyexpirydate); $expirytimeofday_h = date('H', $expirytimestamp); $expirytimeofday_m = date('i', $expirytimestamp); $surveyexpirydate = date($dformat, $expirytimestamp); if (!empty($expirytimeofday_h) || !empty($expirytimeofday_m)) { $surveyexpirydate .= ' – ' . $expirytimeofday_h . ':' . $expirytimeofday_m; } //define('PRINT_TEMPLATE' , '/templates/print/' , true); if (is_file(Yii::app()->getConfig('usertemplaterootdir') . DIRECTORY_SEPARATOR . $template . DIRECTORY_SEPARATOR . 'print_survey.pstpl')) { define('PRINT_TEMPLATE_DIR', Yii::app()->getConfig('usertemplaterootdir') . DIRECTORY_SEPARATOR . $template . DIRECTORY_SEPARATOR, true); define('PRINT_TEMPLATE_URL', Yii::app()->getConfig('usertemplaterooturl') . '/' . $template . '/', true); } elseif (is_file(Yii::app()->getConfig('usertemplaterootdir') . '/' . $template . '/print_survey.pstpl')) { define('PRINT_TEMPLATE_DIR', Yii::app()->getConfig('standardtemplaterootdir') . DIRECTORY_SEPARATOR . $template . DIRECTORY_SEPARATOR, true); define('PRINT_TEMPLATE_URL', Yii::app()->getConfig('standardtemplaterooturl') . '/' . $template . '/', true); } else { define('PRINT_TEMPLATE_DIR', Yii::app()->getConfig('standardtemplaterootdir') . DIRECTORY_SEPARATOR . 'default' . DIRECTORY_SEPARATOR, true); define('PRINT_TEMPLATE_URL', Yii::app()->getConfig('standardtemplaterooturl') . '/default/', true); } LimeExpressionManager::StartSurvey($surveyid, 'survey', NULL, false, LEM_PRETTY_PRINT_ALL_SYNTAX); $moveResult = LimeExpressionManager::NavigateForwards(); $condition = "sid = '{$surveyid}' AND language = '{$surveyprintlang}'"; $degresult = Groups::model()->getAllGroups($condition, array('group_order')); //xiao, if (!isset($surveyfaxto) || !$surveyfaxto and isset($surveyfaxnumber)) { $surveyfaxto = $surveyfaxnumber; //Use system fax number if none is set in survey. } $headelements = getPrintableHeader(); //if $showsgqacode is enabled at config.php show table name for reference $showsgqacode = Yii::app()->getConfig("showsgqacode"); if (isset($showsgqacode) && $showsgqacode == true) { $surveyname = $surveyname . "<br />[" . $clang->gT('Database') . " " . $clang->gT('table') . ": {$surveytable}]"; } else { $surveyname = $surveyname; } $survey_output = array('SITENAME' => Yii::app()->getConfig("sitename"), 'SURVEYNAME' => $surveyname, 'SURVEYDESCRIPTION' => $surveydesc, 'WELCOME' => $welcome, 'END' => $end, 'THEREAREXQUESTIONS' => 0, 'SUBMIT_TEXT' => $clang->gT("Submit Your Survey."), 'SUBMIT_BY' => $surveyexpirydate, 'THANKS' => $clang->gT("Thank you for completing this survey."), 'HEADELEMENTS' => $headelements, 'TEMPLATEURL' => PRINT_TEMPLATE_URL, 'FAXTO' => $surveyfaxto, 'PRIVACY' => '', 'GROUPS' => ''); $survey_output['FAX_TO'] = ''; if (!empty($surveyfaxto) && $surveyfaxto != '000-00000000') { $survey_output['FAX_TO'] = $clang->gT("Please fax your completed survey to:") . " {$surveyfaxto}"; } if ($surveystartdate != '') { $survey_output['SUBMIT_BY'] = sprintf($clang->gT("Please submit by %s"), $surveyexpirydate); } /** * Output arrays: * $survey_output = final vaiables for whole survey * $survey_output['SITENAME'] = * $survey_output['SURVEYNAME'] = * $survey_output['SURVEY_DESCRIPTION'] = * $survey_output['WELCOME'] = * $survey_output['THEREAREXQUESTIONS'] = * $survey_output['PDF_FORM'] = * $survey_output['HEADELEMENTS'] = * $survey_output['TEMPLATEURL'] = * $survey_output['SUBMIT_TEXT'] = * $survey_output['SUBMIT_BY'] = * $survey_output['THANKS'] = * $survey_output['FAX_TO'] = * $survey_output['SURVEY'] = contains an array of all the group arrays * * $groups[] = an array of all the groups output * $group['GROUPNAME'] = * $group['GROUPDESCRIPTION'] = * $group['QUESTIONS'] = templated formatted content if $question is appended to this at the end of processing each question. * $group['ODD_EVEN'] = class to differentiate alternate groups * $group['SCENARIO'] = * * $questions[] = contains an array of all the questions within a group * $question['QUESTION_CODE'] = content of the question code field * $question['QUESTION_TEXT'] = content of the question field * $question['QUESTION_SCENARIO'] = if there are conditions on a question, list the conditions. * $question['QUESTION_MANDATORY'] = translated 'mandatory' identifier * $question['QUESTION_CLASS'] = classes to be added to wrapping question div * $question['QUESTION_TYPE_HELP'] = instructions on how to complete the question * $question['QUESTION_MAN_MESSAGE'] = (not sure if this is used) mandatory error * $question['QUESTION_VALID_MESSAGE'] = (not sure if this is used) validation error * $question['ANSWER'] = contains formatted HTML answer * $question['QUESTIONHELP'] = content of the question help field. * */ $total_questions = 0; $mapquestionsNumbers = array(); $answertext = ''; // otherwise can throw an error on line 1617 // ========================================================= // START doin the business: $pdfoutput = ''; foreach ($degresult->readAll() as $degrow) { // --------------------------------------------------- // START doing groups $deqresult = Questions::model()->getQuestions($surveyid, $degrow['gid'], $surveyprintlang, 0, '"I"'); $deqrows = array(); //Create an empty array in case FetchRow does not return any rows foreach ($deqresult->readAll() as $deqrow) { $deqrows[] = $deqrow; } // Get table output into array // Perform a case insensitive natural sort on group name then question title of a multidimensional array usort($deqrows, 'groupOrderThenQuestionOrder'); if ($degrow['description']) { $group_desc = $degrow['description']; } else { $group_desc = ''; } $group = array('GROUPNAME' => $degrow['group_name'], 'GROUPDESCRIPTION' => $group_desc, 'QUESTIONS' => ''); // A group can have only hidden questions. In that case you don't want to see the group's header/description either. $bGroupHasVisibleQuestions = false; if (isset($_POST['printableexport'])) { $pdf->titleintopdf($degrow['group_name'], $degrow['description']); } $gid = $degrow['gid']; //Alternate bgcolor for different groups if (!isset($group['ODD_EVEN']) || $group['ODD_EVEN'] == ' g-row-even') { $group['ODD_EVEN'] = ' g-row-odd'; } else { $group['ODD_EVEN'] = ' g-row-even'; } //Loop through questions foreach ($deqrows as $deqrow) { // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // START doing questions $qidattributes = getQuestionAttributeValues($deqrow['qid'], $deqrow['type']); if ($qidattributes['hidden'] == 1 && $deqrow['type'] != '*') { continue; } $bGroupHasVisibleQuestions = true; //GET ANY CONDITIONS THAT APPLY TO THIS QUESTION $printablesurveyoutput = ''; $explanation = ''; //reset conditions explanation $s = 0; // // TMSW Conditions->Relevance: show relevance instead of this whole section to create $explanation // // // $scenarioresult=Conditions::model()->getScenarios($deqrow['qid']); // $scenarioresult = $scenarioresult->readAll(); // //Loop through distinct scenarios, thus grouping them together. // foreach ($scenarioresult as $scenariorow) // { // if( $s == 0 && count($scenarioresult) > 1) // { // $explanation .= '<p class="scenario">'.self::_try_debug(__LINE__)." -------- Scenario {$scenariorow['scenario']} --------</p>\n\n"; // } // if($s > 0) // { // $explanation .= '<p class="scenario">'.self::_try_debug(__LINE__).' -------- '.$clang->gT("or")." Scenario {$scenariorow['scenario']} --------</p>\n\n"; // } // // $x=0; // // $conditions1="qid={$deqrow['qid']} AND scenario={$scenariorow['scenario']}"; // $distinctresult=Conditions::model()->getSomeConditions(array('cqid','method', 'cfieldname', 'value'), $conditions1, array('cqid'),array('cqid', 'method')); // // //Loop through each condition for a particular scenario. // foreach ($distinctresult->readAll() as $distinctrow) // { // $condition = "qid = '{$distinctrow['cqid']}' AND parent_qid = 0 AND language = '{$surveyprintlang}'"; // $subresult=Questions::model()->find($condition); // // if($x > 0) // { // $explanation .= ' <em class="scenario-and-seperator">'.$clang->gT('and').'</em> '; // } // if(trim($distinctrow['method'])=='') //If there is no method chosen assume "equals" // { // $distinctrow['method']='=='; // } // // if($distinctrow['cqid']){ // cqid != 0 ==> previous answer match // if($distinctrow['method']=='==') // { // $explanation .= $clang->gT("Answer was")." "; // } // elseif($distinctrow['method']=='!=') // { // $explanation .= $clang->gT("Answer was NOT")." "; // } // elseif($distinctrow['method']=='<') // { // $explanation .= $clang->gT("Answer was less than")." "; // } // elseif($distinctrow['method']=='<=') // { // $explanation .= $clang->gT("Answer was less than or equal to")." "; // } // elseif($distinctrow['method']=='>=') // { // $explanation .= $clang->gT("Answer was greater than or equal to")." "; // } // elseif($distinctrow['method']=='>') // { // $explanation .= $clang->gT("Answer was greater than")." "; // } // elseif($distinctrow['method']=='RX') // { // $explanation .= $clang->gT("Answer matched (regexp)")." "; // } // else // { // $explanation .= $clang->gT("Answer was")." "; // } // if($distinctrow['value'] == '') { // $explanation .= ' '.$clang->gT("Not selected").' '; // } // //If question type is numerical or multi-numerical, show the actual value - otherwise, don't. // if($subresult['type'] == 'N' || $subresult['type'] == 'K') { // $explanation .= ' '.$distinctrow['value']. ' '; // } // } // if(!$distinctrow['cqid']) { // cqid == 0 ==> token attribute match // $tokenData = getTokenFieldsAndNames($surveyid); // preg_match('/^{TOKEN:([^}]*)}$/',$distinctrow['cfieldname'],$extractedTokenAttr); // $explanation .= "Your ".$tokenData[strtolower($extractedTokenAttr[1])]." "; // if($distinctrow['method']=='==') // { // $explanation .= $clang->gT("is")." "; // } // elseif($distinctrow['method']=='!=') // { // $explanation .= $clang->gT("is NOT")." "; // } // elseif($distinctrow['method']=='<') // { // $explanation .= $clang->gT("is less than")." "; // } // elseif($distinctrow['method']=='<=') // { // $explanation .= $clang->gT("is less than or equal to")." "; // } // elseif($distinctrow['method']=='>=') // { // $explanation .= $clang->gT("is greater than or equal to")." "; // } // elseif($distinctrow['method']=='>') // { // $explanation .= $clang->gT("is greater than")." "; // } // elseif($distinctrow['method']=='RX') // { // $explanation .= $clang->gT("is matched (regexp)")." "; // } // else // { // $explanation .= $clang->gT("is")." "; // } // $answer_section = ' '.$distinctrow['value'].' '; // } // // $conresult=Conditions::model()->getConditionsQuestions($distinctrow['cqid'],$deqrow['qid'],$scenariorow['scenario'],$surveyprintlang); // // $conditions=array(); // foreach ($conresult->readAll() as $conrow) // { // // $postans=""; // $value=$conrow['value']; // switch($conrow['type']) // { // case "Y": // switch ($conrow['value']) // { // case "Y": $conditions[]=$clang->gT("Yes"); break; // case "N": $conditions[]=$clang->gT("No"); break; // } // break; // case "G": // switch($conrow['value']) // { // case "M": $conditions[]=$clang->gT("Male"); break; // case "F": $conditions[]=$clang->gT("Female"); break; // } // switch // break; // case "A": // case "B": // case ":": // case ";": // $conditions[]=$conrow['value']; // break; // case "C": // switch($conrow['value']) // { // case "Y": $conditions[]=$clang->gT("Yes"); break; // case "U": $conditions[]=$clang->gT("Uncertain"); break; // case "N": $conditions[]=$clang->gT("No"); break; // } // switch // break; // case "E": // switch($conrow['value']) // { // case "I": $conditions[]=$clang->gT("Increase"); break; // case "D": $conditions[]=$clang->gT("Decrease"); break; // case "S": $conditions[]=$clang->gT("Same"); break; // } // case "1": // $labelIndex=preg_match("/^[^#]+#([01]{1})$/",$conrow['cfieldname']); // if ($labelIndex == 0) // { // TIBO // // $condition="qid='{$conrow['cqid']}' AND code='{$conrow['value']}' AND scale_id=0 AND language='{$surveyprintlang}'"; // $fresult=Answers::model()->getAllRecords($condition); // // foreach($fresult->readAll() as $frow) // { // $postans=$frow['answer']; // $conditions[]=$frow['answer']; // } // while // } // elseif ($labelIndex == 1) // { // // $condition="qid='{$conrow['cqid']}' AND code='{$conrow['value']}' AND scale_id=1 AND language='{$surveyprintlang}'"; // $fresult=Answers::model()->getAllRecords($condition); // foreach($fresult->readAll() as $frow) // { // $postans=$frow['answer']; // $conditions[]=$frow['answer']; // } // while // } // break; // case "L": // case "!": // case "O": // case "R": // $condition="qid='{$conrow['cqid']}' AND code='{$conrow['value']}' AND language='{$surveyprintlang}'"; // $ansresult=Answers::model()->findAll($condition); // // foreach ($ansresult as $ansrow) // { // $conditions[]=$ansrow['answer']; // } // if($conrow['value'] == "-oth-") { // $conditions[]=$clang->gT("Other"); // } // $conditions = array_unique($conditions); // break; // case "M": // case "P": // $condition=" parent_qid='{$conrow['cqid']}' AND title='{$conrow['value']}' AND language='{$surveyprintlang}'"; // $ansresult=Questions::model()->findAll($condition); // foreach ($ansresult as $ansrow) // { // $conditions[]=$ansrow['question']; // } // $conditions = array_unique($conditions); // break; // case "N": // $conditions[]=$value; // break; // case "F": // case "H": // default: // $value=substr($conrow['cfieldname'], strpos($conrow['cfieldname'], "X".$conrow['cqid'])+strlen("X".$conrow['cqid']), strlen($conrow['cfieldname'])); // // $condition=" qid='{$conrow['cqid']}' AND code='{$conrow['value']}' AND language='{$surveyprintlang}'"; // // $fresult=Answers::model()->getAllRecords($condition); // foreach ($fresult->readAll() as $frow) // { // $postans=$frow['answer']; // $conditions[]=$frow['answer']; // } // while // break; // } // switch // // // Now let's complete the answer text with the answer_section // $answer_section=""; // switch($conrow['type']) // { // case "A": // case "B": // case "C": // case "E": // case "F": // case "H": // case "K": // $thiscquestion=$fieldmap[$conrow['cfieldname']]; // $condition="parent_qid='{$conrow['cqid']}' AND title='{$thiscquestion['aid']}' AND language='{$surveyprintlang}'"; // $ansresult= Questions::model()->findAll($condition); // // foreach ($ansresult as $ansrow) // { // $answer_section=" (".$ansrow['question'].")"; // } // break; // // case "1": // dual: (Label 1), (Label 2) // $labelIndex=substr($conrow['cfieldname'],-1); // $thiscquestion=$fieldmap[$conrow['cfieldname']]; // $condition="parent_qid='{$conrow['cqid']}' AND title='{$thiscquestion['aid']}' AND language='{$surveyprintlang}'"; // $ansresult= Questions::model()->findAll($condition); // $cqidattributes = getQuestionAttributeValues($conrow['cqid'], $conrow['type']); // if ($labelIndex == 0) // { // if (trim($cqidattributes['dualscale_headerA']) != '') { // $header = $clang->gT($cqidattributes['dualscale_headerA']); // } else { // $header = '1'; // } // } // elseif ($labelIndex == 1) // { // if (trim($cqidattributes['dualscale_headerB']) != '') { // $header = $clang->gT($cqidattributes['dualscale_headerB']); // } else { // $header = '2'; // } // } // foreach ($ansresult->readAll() as $ansrow) // { // $answer_section=" (".$ansrow['question']." ".sprintf($clang->gT("Label %s"),$header).")"; // } // break; // case ":": // case ";": //multi flexi: ( answer [label] ) // $thiscquestion=$fieldmap[$conrow['cfieldname']]; // $condition="parent_qid='{$conrow['cqid']}' AND title='{$thiscquestion['aid']}' AND language='{$surveyprintlang}'"; // $ansresult= Questions::model()->findAll($condition); // foreach ($ansresult as $ansrow) // { // // $condition = "qid = '{$conrow['cqid']}' AND code = '{$conrow['value']}' AND language= '{$surveyprintlang}'"; // $fresult= Answers::model()->findAll($condition); // foreach ($fresult as $frow) // { // //$conditions[]=$frow['title']; // $answer_section=" (".$ansrow['question']."[".$frow['answer']."])"; // } // while // } // break; // case "R": // (Rank 1), (Rank 2)... TIBO // $thiscquestion=$fieldmap[$conrow['cfieldname']]; // $rankid=$thiscquestion['aid']; // $answer_section=" (".$clang->gT("RANK")." $rankid)"; // break; // default: // nothing to add // break; // } // } // // if (count($conditions) > 1) // { // $explanation .= "'".implode("' <em class='scenario-or-seperator'>".$clang->gT("or")."</em> '", $conditions)."'"; // } // elseif (count($conditions) == 1) // { // $explanation .= "'".$conditions[0]."'"; // } // unset($conditions); // // Following line commented out because answer_section was lost, but is required for some question types // //$explanation .= " ".$clang->gT("to question")." '".$mapquestionsNumbers[$distinctrow['cqid']]."' $answer_section "; // if($distinctrow['cqid']){ // $explanation .= " <span class='scenario-at-seperator'>".$clang->gT("at question")."</span> '".$mapquestionsNumbers[$distinctrow['cqid']]." [".$subresult['title']."]' (".strip_tags($subresult['question'])."$answer_section)" ; // } // else{ // $explanation .= " ".$distinctrow['value'] ; // } // //$distinctrow // $x++; // } // $s++; // } $qinfo = LimeExpressionManager::GetQuestionStatus($deqrow['qid']); $relevance = trim($qinfo['info']['relevance']); $explanation = $qinfo['relEqn']; if (trim($relevance) != '' && trim($relevance) != '1') { $explanation = "<b>" . $clang->gT('Only answer this question if the following conditions are met:') . "</b>" . "<br/> ° " . $explanation; } else { $explanation = ''; } ++$total_questions; //TIBO map question qid to their q number $mapquestionsNumbers[$deqrow['qid']] = $total_questions; //END OF GETTING CONDITIONS $qid = $deqrow['qid']; $fieldname = "{$surveyid}" . "X" . "{$gid}" . "X" . "{$qid}"; if (isset($showsgqacode) && $showsgqacode == true) { $deqrow['question'] = $deqrow['question'] . "<br />" . $clang->gT("ID:") . " {$fieldname} <br />" . $clang->gT("Question code:") . " " . $deqrow['title']; } $question = array('QUESTION_NUMBER' => $total_questions, 'QUESTION_CODE' => $deqrow['title'], 'QUESTION_TEXT' => preg_replace('/(?:<br ?\\/?>|<\\/(?:p|h[1-6])>)$/is', '', $deqrow['question']), 'QUESTION_SCENARIO' => $explanation, 'QUESTION_MANDATORY' => '', 'QUESTION_ID' => $deqrow['qid'], 'QUESTION_CLASS' => getQuestionClass($deqrow['type']), 'QUESTION_TYPE_HELP' => $qinfo['validTip'], 'QUESTION_MAN_MESSAGE' => '', 'QUESTION_VALID_MESSAGE' => '', 'QUESTION_FILE_VALID_MESSAGE' => '', 'QUESTIONHELP' => '', 'ANSWER' => ''); if ($question['QUESTION_TYPE_HELP'] != "") { $question['QUESTION_TYPE_HELP'] .= "<br />\n"; } if ($deqrow['mandatory'] == 'Y') { $question['QUESTION_MANDATORY'] = $clang->gT('*'); $question['QUESTION_CLASS'] .= ' mandatory'; $pdfoutput .= $clang->gT("*"); } $pdfoutput = ''; //DIFFERENT TYPES OF DATA FIELD HERE if (isset($_POST['printableexport'])) { $pdf->intopdf($deqrow['title'] . " " . $deqrow['question']); } if ($deqrow['help']) { $hh = $deqrow['help']; $question['QUESTIONHELP'] = $hh; if (isset($_POST['printableexport'])) { $pdf->helptextintopdf($hh); } } if (!empty($qidattributes['page_break'])) { $question['QUESTION_CLASS'] .= ' breakbefore '; } if (isset($qidattributes['maximum_chars']) && $qidattributes['maximum_chars'] != '') { $question['QUESTION_CLASS'] = "max-chars-{$qidattributes['maximum_chars']} " . $question['QUESTION_CLASS']; } switch ($deqrow['type']) { // ================================================================== case "5": //5 POINT CHOICE $question['QUESTION_TYPE_HELP'] .= $clang->gT('Please choose *only one* of the following:'); if (isset($_POST['printableexport'])) { $pdf->intopdf($clang->gT("Please choose *only one* of the following:"), "U"); } $pdfoutput = ''; $question['ANSWER'] .= "\n\t<ul>\n"; for ($i = 1; $i <= 5; $i++) { $pdfoutput .= " o " . $i . " "; // $printablesurveyoutput .="\t\t\t<input type='checkbox' name='$fieldname' value='$i' readonly='readonly' />$i \n"; $question['ANSWER'] .= "\t\t<li>\n\t\t\t" . self::_input_type_image('radio', $i) . "\n\t\t\t{$i} " . self::_addsgqacode("({$i})") . "\n\t\t</li>\n"; } if (isset($_POST['printableexport'])) { $pdf->intopdf($pdfoutput); } $question['ANSWER'] .= "\t</ul>\n"; break; // ================================================================== // ================================================================== case "D": //DATE $question['QUESTION_TYPE_HELP'] .= $clang->gT('Please enter a date:'); $question['ANSWER'] .= "\t" . self::_input_type_image('text', $question['QUESTION_TYPE_HELP'], 30, 1); if (isset($_POST['printableexport'])) { $pdf->intopdf($clang->gT("Please enter a date:") . " ___________"); } break; // ================================================================== // ================================================================== case "G": //GENDER $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please choose *only one* of the following:"); $question['ANSWER'] .= "\n\t<ul>\n"; $question['ANSWER'] .= "\t\t<li>\n\t\t\t" . self::_input_type_image('radio', $clang->gT("Female")) . "\n\t\t\t" . $clang->gT("Female") . " " . self::_addsgqacode("(F)") . "\n\t\t</li>\n"; $question['ANSWER'] .= "\t\t<li>\n\t\t\t" . self::_input_type_image('radio', $clang->gT("Male")) . "\n\t\t\t" . $clang->gT("Male") . " " . self::_addsgqacode("(M)") . "\n\t\t</li>\n"; $question['ANSWER'] .= "\t</ul>\n"; if (isset($_POST['printableexport'])) { $pdf->intopdf($clang->gT("Please choose *only one* of the following:")); } if (isset($_POST['printableexport'])) { $pdf->intopdf(" o " . $clang->gT("Female") . " | o " . $clang->gT("Male")); } break; // ================================================================== // ================================================================== case "L": //LIST drop-down/radio-button list // ================================================================== //LIST drop-down/radio-button list // ================================================================== case "!": //List - dropdown if (isset($qidattributes['display_columns']) && trim($qidattributes['display_columns']) != '') { $dcols = $qidattributes['display_columns']; } else { $dcols = 0; } if (isset($qidattributes['category_separator']) && trim($qidattributes['category_separator']) != '') { $optCategorySeparator = $qidattributes['category_separator']; } else { unset($optCategorySeparator); } $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please choose *only one* of the following:"); $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $surveyprintlang, $surveyid); if (isset($_POST['printableexport'])) { $pdf->intopdf($clang->gT("Please choose *only one* of the following:")); } $dearesult = Answers::model()->getAllRecords(" qid='{$deqrow['qid']}' AND language='{$surveyprintlang}' ", array('sortorder', 'answer')); $dearesult = $dearesult->readAll(); $deacount = count($dearesult); if ($deqrow['other'] == "Y") { $deacount++; } $wrapper = setupColumns(0, $deacount); $question['ANSWER'] = $wrapper['whole-start']; $rowcounter = 0; $colcounter = 1; foreach ($dearesult as $dearow) { if (isset($optCategorySeparator)) { list($category, $answer) = explode($optCategorySeparator, $dearow['answer']); if ($category != '') { $dearow['answer'] = "({$category}) {$answer} " . self::_addsgqacode("(" . $dearow['code'] . ")"); } else { $dearow['answer'] = $answer . self::_addsgqacode(" (" . $dearow['code'] . ")"); } $question['ANSWER'] .= "\t" . $wrapper['item-start'] . "\t\t" . self::_input_type_image('radio', $dearow['answer']) . "\n\t\t\t" . $dearow['answer'] . "\n" . $wrapper['item-end']; } else { $question['ANSWER'] .= "\t" . $wrapper['item-start'] . "\t\t" . self::_input_type_image('radio', $dearow['answer']) . "\n\t\t\t" . $dearow['answer'] . self::_addsgqacode(" (" . $dearow['code'] . ")") . "\n" . $wrapper['item-end']; } if (isset($_POST['printableexport'])) { $pdf->intopdf(" o " . $dearow['answer']); } ++$rowcounter; if ($rowcounter == $wrapper['maxrows'] && $colcounter < $wrapper['cols']) { if ($colcounter == $wrapper['cols'] - 1) { $question['ANSWER'] .= $wrapper['col-devide-last']; } else { $question['ANSWER'] .= $wrapper['col-devide']; } $rowcounter = 0; ++$colcounter; } } if ($deqrow['other'] == 'Y') { if (trim($qidattributes["other_replace_text"][$surveyprintlang]) == '') { $qidattributes["other_replace_text"][$surveyprintlang] = "Other"; } // $printablesurveyoutput .="\t".$wrapper['item-start']."\t\t".self::_input_type_image('radio' , $clang->gT("Other"))."\n\t\t\t".$clang->gT("Other")."\n\t\t\t<input type='text' size='30' readonly='readonly' />\n".$wrapper['item-end']; $question['ANSWER'] .= $wrapper['item-start-other'] . self::_input_type_image('radio', $clang->gT($qidattributes["other_replace_text"][$surveyprintlang])) . ' ' . $clang->gT($qidattributes["other_replace_text"][$surveyprintlang]) . self::_addsgqacode(" (-oth-)") . "\n\t\t\t" . self::_input_type_image('other') . self::_addsgqacode(" (" . $deqrow['sid'] . "X" . $deqrow['gid'] . "X" . $deqrow['qid'] . "other)") . "\n" . $wrapper['item-end']; if (isset($_POST['printableexport'])) { $pdf->intopdf(" o " . $clang->gT($qidattributes["other_replace_text"][$surveyprintlang]) . ": ________"); } } $question['ANSWER'] .= $wrapper['whole-end']; //Let's break the presentation into columns. break; // ================================================================== // ================================================================== case "O": //LIST WITH COMMENT $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please choose *only one* of the following:"); if (isset($_POST['printableexport'])) { $pdf->intopdf($clang->gT("Please choose *only one* of the following:"), "U"); } $dearesult = Answers::model()->getAllRecords(" qid='{$deqrow['qid']}' AND language='{$surveyprintlang}'", array('sortorder', 'answer')); $question['ANSWER'] = "\t<ul>\n"; foreach ($dearesult->readAll() as $dearow) { $question['ANSWER'] .= "\t\t<li>\n\t\t\t" . self::_input_type_image('radio', $dearow['answer']) . "\n\t\t\t" . $dearow['answer'] . self::_addsgqacode(" (" . $dearow['code'] . ")") . "\n\t\t</li>\n"; if (isset($_POST['printableexport'])) { $pdf->intopdf($dearow['answer']); } } $question['ANSWER'] .= "\t</ul>\n"; $question['ANSWER'] .= "\t<p class=\"comment\">\n\t\t" . $clang->gT("Make a comment on your choice here:") . "\n"; if (isset($_POST['printableexport'])) { $pdf->intopdf("Make a comment on your choice here:"); } $question['ANSWER'] .= "\t\t" . self::_input_type_image('textarea', $clang->gT("Make a comment on your choice here:"), 50, 8) . self::_addsgqacode(" (" . $deqrow['sid'] . "X" . $deqrow['gid'] . "X" . $deqrow['qid'] . "comment)") . "\n\t</p>\n"; for ($i = 0; $i < 9; $i++) { if (isset($_POST['printableexport'])) { $pdf->intopdf("____________________"); } } break; // ================================================================== // ================================================================== case "R": //RANKING Type Question $rearesult = Answers::model()->getAllRecords(" qid='{$deqrow['qid']}' AND language='{$surveyprintlang}'", array('sortorder', 'answer')); $rearesult = $rearesult->readAll(); $reacount = count($rearesult); $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please number each box in order of preference from 1 to") . " {$reacount}"; $question['QUESTION_TYPE_HELP'] .= self::_min_max_answers_help($qidattributes, $surveyprintlang, $surveyid); if (isset($_POST['printableexport'])) { $pdf->intopdf($clang->gT("Please number each box in order of preference from 1 to ") . $reacount, "U"); } $question['ANSWER'] = "\n<ul>\n"; foreach ($rearesult as $rearow) { $question['ANSWER'] .= "\t<li>\n\t" . self::_input_type_image('rank', '', 4, 1) . "\n\t\t " . $rearow['answer'] . self::_addsgqacode(" (" . $fieldname . $rearow['code'] . ")") . "\n\t</li>\n"; if (isset($_POST['printableexport'])) { $pdf->intopdf("__ " . $rearow['answer']); } } $question['ANSWER'] .= "\n</ul>\n"; break; // ================================================================== // ================================================================== case "M": //Multiple choice (Quite tricky really!) if (trim($qidattributes['display_columns']) != '') { $dcols = $qidattributes['display_columns']; } else { $dcols = 0; } $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please choose *all* that apply:"); if (isset($_POST['printableexport'])) { $pdf->intopdf($clang->gT("Please choose *all* that apply:"), "U"); } $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $surveyprintlang, $surveyid); $mearesult = Questions::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' AND language='{$surveyprintlang}' ", array('question_order')); $mearesult = $mearesult->readAll(); $meacount = count($mearesult); if ($deqrow['other'] == 'Y') { $meacount++; } $wrapper = setupColumns($dcols, $meacount); $question['ANSWER'] = $wrapper['whole-start']; $rowcounter = 0; $colcounter = 1; foreach ($mearesult as $mearow) { $question['ANSWER'] .= $wrapper['item-start'] . self::_input_type_image('checkbox', $mearow['question']) . "\n\t\t" . $mearow['question'] . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ") ") . $wrapper['item-end']; if (isset($_POST['printableexport'])) { $pdf->intopdf(" o " . $mearow['answer']); } // $upto++; ++$rowcounter; if ($rowcounter == $wrapper['maxrows'] && $colcounter < $wrapper['cols']) { if ($colcounter == $wrapper['cols'] - 1) { $question['ANSWER'] .= $wrapper['col-devide-last']; } else { $question['ANSWER'] .= $wrapper['col-devide']; } $rowcounter = 0; ++$colcounter; } } if ($deqrow['other'] == "Y") { if (trim($qidattributes['other_replace_text'][$surveyprintlang]) == '') { $qidattributes["other_replace_text"][$surveyprintlang] = "Other"; } if (!isset($mearow['answer'])) { $mearow['answer'] = ""; } $question['ANSWER'] .= $wrapper['item-start-other'] . self::_input_type_image('checkbox', $mearow['answer']) . $clang->gT($qidattributes["other_replace_text"][$surveyprintlang]) . ":\n\t\t" . self::_input_type_image('other') . self::_addsgqacode(" (" . $fieldname . "other) ") . $wrapper['item-end']; if (isset($_POST['printableexport'])) { $pdf->intopdf(" o " . $clang->gT($qidattributes["other_replace_text"][$surveyprintlang]) . ": ________"); } } $question['ANSWER'] .= $wrapper['whole-end']; // } break; // ================================================================== // ================================================================== case "P": //Multiple choice with comments $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please choose all that apply and provide a comment:"); if (isset($_POST['printableexport'])) { $pdf->intopdf($clang->gT("Please choose all that apply and provide a comment:"), "U"); } $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $surveyprintlang, $surveyid); $mearesult = Questions::model()->getAllRecords("parent_qid='{$deqrow['qid']}' AND language='{$surveyprintlang}'", array('question_order')); // $printablesurveyoutput .="\t\t\t<u>".$clang->gT("Please choose all that apply and provide a comment:")."</u><br />\n"; $pdfoutput = array(); $j = 0; $longest_string = 0; foreach ($mearesult->readAll() as $mearow) { $longest_string = longestString($mearow['question'], $longest_string); $question['ANSWER'] .= "\t<li><span>\n\t\t" . self::_input_type_image('checkbox', $mearow['question']) . $mearow['question'] . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ") ") . "</span>\n\t\t" . self::_input_type_image('text', 'comment box', 60) . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . "comment) ") . "\n\t</li>\n"; $pdfoutput[$j] = array(" o " . $mearow['title'], " __________"); $j++; } if ($deqrow['other'] == "Y") { $question['ANSWER'] .= "\t<li class=\"other\">\n\t\t<div class=\"other-replacetext\">" . $clang->gT('Other:') . self::_input_type_image('other', '', 1) . "</div>" . self::_input_type_image('othercomment', 'comment box', 50) . self::_addsgqacode(" (" . $fieldname . "other) ") . "\n\t</li>\n"; // lemeur: PDFOUTPUT HAS NOT BEEN IMPLEMENTED for these fields // not sure who did implement this. $pdfoutput[$j][0] = array(" o " . "Other", " __________"); $pdfoutput[$j][1] = array(" o " . "OtherComment", " __________"); $j++; } $question['ANSWER'] = "\n<ul>\n" . $question['ANSWER'] . "</ul>\n"; if (isset($_POST['printableexport'])) { $pdf->tableintopdf($pdfoutput); } break; // ================================================================== // ================================================================== case "Q": //MULTIPLE SHORT TEXT $width = 60; // ================================================================== // ================================================================== case "K": //MULTIPLE NUMERICAL $question['QUESTION_TYPE_HELP'] = ""; $width = isset($width) ? $width : 16; if (isset($_POST['printableexport'])) { $pdf->intopdf($clang->gT("Please write your answer(s) here:"), "U"); } // if (!empty($qidattributes['equals_num_value'])) // { // $question['QUESTION_TYPE_HELP'] .= "* ".sprintf($clang->gT('Total of all entries must equal %d'),$qidattributes['equals_num_value'])."<br />\n"; // } // if (!empty($qidattributes['max_num_value'])) // { // $question['QUESTION_TYPE_HELP'] .= sprintf($clang->gT('Total of all entries must not exceed %d'), $qidattributes['max_num_value'])."<br />\n"; // } // if (!empty($qidattributes['min_num_value'])) // { // $question['QUESTION_TYPE_HELP'] .= sprintf($clang->gT('Total of all entries must be at least %s'),$qidattributes['min_num_value'])."<br />\n"; // } $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please write your answer(s) here:"); $mearesult = Questions::model()->getAllRecords("parent_qid='{$deqrow['qid']}' AND language='{$surveyprintlang}'", array('question_order')); $longest_string = 0; foreach ($mearesult->readAll() as $mearow) { $longest_string = longestString($mearow['question'], $longest_string); if (isset($qidattributes['slider_layout']) && $qidattributes['slider_layout'] == 1) { $mearow['question'] = explode(':', $mearow['question']); $mearow['question'] = $mearow['question'][0]; } $question['ANSWER'] .= "\t<li>\n\t\t<span>" . $mearow['question'] . "</span>\n\t\t" . self::_input_type_image('text', $mearow['question'], $width) . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ") ") . "\n\t</li>\n"; if (isset($_POST['printableexport'])) { $pdf->intopdf($mearow['question'] . ": ____________________"); } } $question['ANSWER'] = "\n<ul>\n" . $question['ANSWER'] . "</ul>\n"; break; // ================================================================== // ================================================================== case "S": //SHORT TEXT $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please write your answer here:"); $question['ANSWER'] = self::_input_type_image('text', $question['QUESTION_TYPE_HELP'], 50); if (isset($_POST['printableexport'])) { $pdf->intopdf($clang->gT("Please write your answer here:"), "U"); } if (isset($_POST['printableexport'])) { $pdf->intopdf("____________________"); } break; // ================================================================== // ================================================================== case "T": //LONG TEXT $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please write your answer here:"); $question['ANSWER'] = self::_input_type_image('textarea', $question['QUESTION_TYPE_HELP'], '100%', 8); if (isset($_POST['printableexport'])) { $pdf->intopdf($clang->gT("Please write your answer here:"), "U"); } for ($i = 0; $i < 9; $i++) { if (isset($_POST['printableexport'])) { $pdf->intopdf("____________________"); } } break; // ================================================================== // ================================================================== case "U": //HUGE TEXT $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please write your answer here:"); $question['ANSWER'] = self::_input_type_image('textarea', $question['QUESTION_TYPE_HELP'], '100%', 30); if (isset($_POST['printableexport'])) { $pdf->intopdf($clang->gT("Please write your answer here:"), "U"); } for ($i = 0; $i < 20; $i++) { if (isset($_POST['printableexport'])) { $pdf->intopdf("____________________"); } } break; // ================================================================== // ================================================================== case "N": //NUMERICAL $prefix = ""; $suffix = ""; if ($qidattributes['prefix'][$surveyprintlang] != "") { $prefix = $qidattributes['prefix'][$surveyprintlang]; print_r($prefix); } if ($qidattributes['suffix'][$surveyprintlang] != "") { $suffix = $qidattributes['suffix'][$surveyprintlang]; } $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please write your answer here:"); $question['ANSWER'] = "<ul>\n\t<li>\n\t\t<span>{$prefix}</span>\n\t\t" . self::_input_type_image('text', $question['QUESTION_TYPE_HELP'], 20) . "\n\t\t<span>{$suffix}</span>\n\t\t</li>\n\t</ul>"; if (isset($_POST['printableexport'])) { $pdf->intopdf($clang->gT("Please write your answer here:"), "U"); } if (isset($_POST['printableexport'])) { $pdf->intopdf("____________________"); } break; // ================================================================== // ================================================================== case "Y": //YES/NO $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please choose *only one* of the following:"); $question['ANSWER'] = "\n<ul>\n\t<li>\n\t\t" . self::_input_type_image('radio', $clang->gT('Yes')) . "\n\t\t" . $clang->gT('Yes') . self::_addsgqacode(" (Y)") . "\n\t</li>\n"; $question['ANSWER'] .= "\n\t<li>\n\t\t" . self::_input_type_image('radio', $clang->gT('No')) . "\n\t\t" . $clang->gT('No') . self::_addsgqacode(" (N)") . "\n\t</li>\n</ul>\n"; if (isset($_POST['printableexport'])) { $pdf->intopdf($clang->gT("Please choose *only one* of the following:"), "U"); } if (isset($_POST['printableexport'])) { $pdf->intopdf(" o " . $clang->gT("Yes")); } if (isset($_POST['printableexport'])) { $pdf->intopdf(" o " . $clang->gT("No")); } break; // ================================================================== // ================================================================== case "A": //ARRAY (5 POINT CHOICE) $condition = "parent_qid = '{$deqrow['qid']}' AND language= '{$surveyprintlang}'"; $mearesult = Questions::model()->getAllRecords($condition, array('question_order')); $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please choose the appropriate response for each item:"); $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $surveyprintlang, $surveyid); $question['ANSWER'] = "\n <table>\n <thead>\n <tr>\n <td> </td>\n <th style='font-family:Arial,helvetica,sans-serif;font-weight:normal;'>1 " . self::_addsgqacode(" (1)") . "</th>\n <th style='font-family:Arial,helvetica,sans-serif;font-weight:normal;'>2 " . self::_addsgqacode(" (2)") . "</th>\n <th style='font-family:Arial,helvetica,sans-serif;font-weight:normal;'>3 " . self::_addsgqacode(" (3)") . "</th>\n <th style='font-family:Arial,helvetica,sans-serif;font-weight:normal;'>4 " . self::_addsgqacode(" (4)") . "</th>\n <th style='font-family:Arial,helvetica,sans-serif;font-weight:normal;'>5" . self::_addsgqacode(" (5)") . "</th>\n </tr>\n </thead>\n <tbody>"; if (isset($_POST['printableexport'])) { $pdf->intopdf($clang->gT("Please choose the appropriate response for each item:"), "U"); } $pdfoutput = array(); $j = 0; $rowclass = 'array1'; foreach ($mearesult->readAll() as $mearow) { $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n"; $rowclass = alternation($rowclass, 'row'); //semantic differential question type? if (strpos($mearow['question'], '|')) { $answertext = substr($mearow['question'], 0, strpos($mearow['question'], '|')) . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")") . " "; } else { $answertext = $mearow['question'] . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")"); } $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$answertext}</th>\n"; $pdfoutput[$j][0] = $answertext; for ($i = 1; $i <= 5; $i++) { $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', $i) . "</td>\n"; $pdfoutput[$j][$i] = " o " . $i; } $answertext .= $mearow['question']; //semantic differential question type? if (strpos($mearow['question'], '|')) { $answertext2 = substr($mearow['question'], strpos($mearow['question'], '|') + 1); $question['ANSWER'] .= "\t\t\t<th class=\"answertextright\">{$answertext2}</td>\n"; } $question['ANSWER'] .= "\t\t</tr>\n"; $j++; } $question['ANSWER'] .= "\t</tbody>\n</table>\n"; if (isset($_POST['printableexport'])) { $pdf->tableintopdf($pdfoutput); } break; // ================================================================== // ================================================================== case "B": //ARRAY (10 POINT CHOICE) $mearesult = Questions::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' AND language='{$surveyprintlang}' ", array('question_order')); $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please choose the appropriate response for each item:"); $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $surveyprintlang, $surveyid); $question['ANSWER'] .= "\n<table>\n\t<thead>\n\t\t<tr>\n\t\t\t<td> </td>\n"; for ($i = 1; $i <= 10; $i++) { $question['ANSWER'] .= "\t\t\t<th>{$i}" . self::_addsgqacode(" ({$i})") . "</th>\n"; } $question['ANSWER'] .= "\t</thead>\n\n\t<tbody>\n"; if (isset($_POST['printableexport'])) { $pdf->intopdf($clang->gT("Please choose the appropriate response for each item:"), "U"); } $pdfoutput = array(); $j = 0; $rowclass = 'array1'; foreach ($mearesult->readAll() as $mearow) { $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n\t\t\t<th class=\"answertext\">{$mearow['question']}" . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")") . "</th>\n"; $rowclass = alternation($rowclass, 'row'); $pdfoutput[$j][0] = $mearow['question']; for ($i = 1; $i <= 10; $i++) { $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', $i) . "</td>\n"; $pdfoutput[$j][$i] = " o " . $i; } $question['ANSWER'] .= "\t\t</tr>\n"; $j++; } $question['ANSWER'] .= "\t</tbody>\n</table>\n"; if (isset($_POST['printableexport'])) { $pdf->tableintopdf($pdfoutput); } break; // ================================================================== // ================================================================== case "C": //ARRAY (YES/UNCERTAIN/NO) $mearesult = Questions::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' AND language='{$surveyprintlang}' ", array('question_order')); $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please choose the appropriate response for each item:"); $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $surveyprintlang, $surveyid); $question['ANSWER'] = ' <table> <thead> <tr> <td> </td> <th>' . $clang->gT("Yes") . self::_addsgqacode(" (Y)") . '</th> <th>' . $clang->gT("Uncertain") . self::_addsgqacode(" (U)") . '</th> <th>' . $clang->gT("No") . self::_addsgqacode(" (N)") . '</th> </tr> </thead> <tbody> '; if (isset($_POST['printableexport'])) { $pdf->intopdf($clang->gT("Please choose the appropriate response for each item:"), "U"); } $pdfoutput = array(); $j = 0; $rowclass = 'array1'; foreach ($mearesult->readAll() as $mearow) { $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n"; $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$mearow['question']}" . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")") . "</th>\n"; $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', $clang->gT("Yes")) . "</td>\n"; $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', $clang->gT("Uncertain")) . "</td>\n"; $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', $clang->gT("No")) . "</td>\n"; $question['ANSWER'] .= "\t\t</tr>\n"; $pdfoutput[$j] = array($mearow['question'], " o " . $clang->gT("Yes"), " o " . $clang->gT("Uncertain"), " o " . $clang->gT("No")); $j++; $rowclass = alternation($rowclass, 'row'); } $question['ANSWER'] .= "\t</tbody>\n</table>\n"; if (isset($_POST['printableexport'])) { $pdf->tableintopdf($pdfoutput); } break; case "E": //ARRAY (Increase/Same/Decrease) $mearesult = Questions::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' AND language='{$surveyprintlang}' ", array('question_order')); $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please choose the appropriate response for each item:"); $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $surveyprintlang, $surveyid); $question['ANSWER'] = ' <table> <thead> <tr> <td> </td> <th>' . $clang->gT("Increase") . self::_addsgqacode(" (I)") . '</th> <th>' . $clang->gT("Same") . self::_addsgqacode(" (S)") . '</th> <th>' . $clang->gT("Decrease") . self::_addsgqacode(" (D)") . '</th> </tr> </thead> <tbody> '; if (isset($_POST['printableexport'])) { $pdf->intopdf($clang->gT("Please choose the appropriate response for each item:"), "U"); } $pdfoutput = array(); $j = 0; $rowclass = 'array1'; foreach ($mearesult->readAll() as $mearow) { $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n"; $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$mearow['question']}" . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")") . "</th>\n"; $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', $clang->gT("Increase")) . "</td>\n"; $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', $clang->gT("Same")) . "</td>\n"; $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', $clang->gT("Decrease")) . "</td>\n"; $question['ANSWER'] .= "\t\t</tr>\n"; $pdfoutput[$j] = array($mearow['question'] . ":", " o " . $clang->gT("Increase"), " o " . $clang->gT("Same"), " o " . $clang->gT("Decrease")); $j++; $rowclass = alternation($rowclass, 'row'); } $question['ANSWER'] .= "\t</tbody>\n</table>\n"; if (isset($_POST['printableexport'])) { $pdf->tableintopdf($pdfoutput); } break; // ================================================================== // ================================================================== case ":": //ARRAY (Multi Flexible) (Numbers) $headstyle = "style='padding-left: 20px; padding-right: 7px'"; if (trim($qidattributes['multiflexible_max']) != '' && trim($qidattributes['multiflexible_min']) == '') { $maxvalue = $qidattributes['multiflexible_max']; $minvalue = 1; } if (trim($qidattributes['multiflexible_min']) != '' && trim($qidattributes['multiflexible_max']) == '') { $minvalue = $qidattributes['multiflexible_min']; $maxvalue = $qidattributes['multiflexible_min'] + 10; } if (trim($qidattributes['multiflexible_min']) == '' && trim($qidattributes['multiflexible_max']) == '') { $minvalue = 1; $maxvalue = 10; } if (trim($qidattributes['multiflexible_min']) != '' && trim($qidattributes['multiflexible_max']) != '') { if ($qidattributes['multiflexible_min'] < $qidattributes['multiflexible_max']) { $minvalue = $qidattributes['multiflexible_min']; $maxvalue = $qidattributes['multiflexible_max']; } } if (trim($qidattributes['multiflexible_step']) != '') { $stepvalue = $qidattributes['multiflexible_step']; } else { $stepvalue = 1; } if ($qidattributes['multiflexible_checkbox'] != 0) { $checkboxlayout = true; } else { $checkboxlayout = false; } $mearesult = Questions::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' and scale_id=0 AND language='{$surveyprintlang}' ", array('question_order')); // if ($checkboxlayout === false) // { // if ($stepvalue > 1) // { // $question['QUESTION_TYPE_HELP'] = sprintf($clang->gT("Please write a multiple of %d between (%s) and (%s) for each item:"),$stepvalue,$minvalue,$maxvalue); // if(isset($_POST['printableexport'])){$pdf->intopdf(sprintf($clang->gT("Please write a multiple of %d between (%s) and (%s) for each item:"),$stepvalue,$minvalue,$maxvalue),"U");} // } // else { // $question['QUESTION_TYPE_HELP'] = sprintf($clang->gT("Please enter a number between (%s) and (%s) for each item:"),$minvalue,$maxvalue); // if(isset($_POST['printableexport'])){$pdf->intopdf(sprintf($clang->gT("Please enter a number between (%s) and (%s) for each item:"),$minvalue,$maxvalue),"U");} // } // } // else // { // $question['QUESTION_TYPE_HELP'] .= $clang->gT("Check any that apply").":"; // if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Check any that apply"),"U");} // } $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $surveyprintlang, $surveyid); $question['ANSWER'] .= "\n<table>\n\t<thead>\n\t\t<tr>\n\t\t\t<td> </td>\n"; $fresult = Questions::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' and scale_id=1 AND language='{$surveyprintlang}' ", array('question_order')); $fresult = $fresult->readAll(); $fcount = count($fresult); $fwidth = "120"; $i = 0; $pdfoutput = array(); $pdfoutput[0][0] = ' '; //array to temporary store X axis question codes $xaxisarray = array(); foreach ($fresult as $frow) { $question['ANSWER'] .= "\t\t\t<th>{$frow['question']}</th>\n"; $i++; $pdfoutput[0][$i] = $frow['question']; //add current question code $xaxisarray[$i] = $frow['title']; } $question['ANSWER'] .= "\t\t</tr>\n\t</thead>\n\n\t<tbody>\n"; $a = 1; //Counter for pdfoutput $rowclass = 'array1'; $result = $mearesult->readAll(); foreach ($result as $frow) { $question['ANSWER'] .= "\t<tr class=\"{$rowclass}\">\n"; $rowclass = alternation($rowclass, 'row'); $answertext = $frow['question']; if (strpos($answertext, '|')) { $answertext = substr($answertext, 0, strpos($answertext, '|')); } $question['ANSWER'] .= "\t\t\t\t\t<th class=\"answertext\">{$answertext}</th>\n"; //$printablesurveyoutput .="\t\t\t\t\t<td>"; $pdfoutput[$a][0] = $answertext; for ($i = 1; $i <= $fcount; $i++) { $question['ANSWER'] .= "\t\t\t<td>\n"; if ($checkboxlayout === false) { $question['ANSWER'] .= "\t\t\t\t" . self::_input_type_image('text', '', 4) . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . "_" . $xaxisarray[$i] . ") ") . "\n"; $pdfoutput[$a][$i] = "__"; } else { $question['ANSWER'] .= "\t\t\t\t" . self::_input_type_image('checkbox') . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . "_" . $xaxisarray[$i] . ") ") . "\n"; $pdfoutput[$a][$i] = "o"; } $question['ANSWER'] .= "\t\t\t</td>\n"; } $answertext = $mearow['question']; if (strpos($answertext, '|')) { $answertext = substr($answertext, strpos($answertext, '|') + 1); $question['ANSWER'] .= "\t\t\t<th class=\"answertextright\">{$answertext}</th>\n"; //$pdfoutput[$a][$i]=$answertext; } $question['ANSWER'] .= "\t\t</tr>\n"; $a++; } $question['ANSWER'] .= "\t</tbody>\n</table>\n"; if (isset($_POST['printableexport'])) { $pdf->tableintopdf($pdfoutput); } break; // ================================================================== // ================================================================== case ";": //ARRAY (Multi Flexible) (text) $headstyle = "style='padding-left: 20px; padding-right: 7px'"; $mearesult = Questions::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' AND scale_id=0 AND language='{$surveyprintlang}' ", array('question_order')); $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $surveyprintlang, $surveyid); $question['ANSWER'] .= "\n<table>\n\t<thead>\n\t\t<tr>\n\t\t\t<td> </td>\n"; $fresult = Questions::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' AND scale_id=1 AND language='{$surveyprintlang}' ", array('question_order')); $fresult = $fresult->readAll(); $fcount = count($fresult); $fwidth = "120"; $i = 0; $pdfoutput = array(); $pdfoutput[0][0] = ''; //array to temporary store X axis question codes $xaxisarray = array(); foreach ($fresult as $frow) { $question['ANSWER'] .= "\t\t\t<th>{$frow['question']}</th>\n"; $i++; $pdfoutput[0][$i] = $frow['question']; //add current question code $xaxisarray[$i] = $frow['title']; } $question['ANSWER'] .= "\t\t</tr>\n\t</thead>\n\n<tbody>\n"; $a = 1; $rowclass = 'array1'; foreach ($mearesult->readAll() as $mearow) { $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n"; $rowclass = alternation($rowclass, 'row'); $answertext = $mearow['question']; if (strpos($answertext, '|')) { $answertext = substr($answertext, 0, strpos($answertext, '|')); } $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$answertext}</th>\n"; $pdfoutput[$a][0] = $answertext; //$printablesurveyoutput .="\t\t\t\t\t<td>"; for ($i = 1; $i <= $fcount; $i++) { $question['ANSWER'] .= "\t\t\t<td>\n"; $question['ANSWER'] .= "\t\t\t\t" . self::_input_type_image('text', '', 23) . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . "_" . $xaxisarray[$i] . ") ") . "\n"; $question['ANSWER'] .= "\t\t\t</td>\n"; $pdfoutput[$a][$i] = "_____________"; } $answertext = $mearow['question']; if (strpos($answertext, '|')) { $answertext = substr($answertext, strpos($answertext, '|') + 1); $question['ANSWER'] .= "\t\t\t\t<th class=\"answertextright\">{$answertext}</th>\n"; } $question['ANSWER'] .= "\t\t</tr>\n"; $a++; } $question['ANSWER'] .= "\t</tbody>\n</table>\n"; if (isset($_POST['printableexport'])) { $pdf->tableintopdf($pdfoutput); } break; // ================================================================== // ================================================================== case "F": //ARRAY (Flexible Labels) $mearesult = Questions::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' AND language='{$surveyprintlang}' ", array('question_order')); $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please choose the appropriate response for each item:"); $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $surveyprintlang, $surveyid); $fresult = Answers::model()->getAllRecords(" scale_id=0 AND qid='{$deqrow['qid']}' AND language='{$surveyprintlang}'", array('sortorder', 'code')); $fresult = $fresult->readAll(); $fcount = count($fresult); $fwidth = "120"; $i = 1; $pdfoutput = array(); $pdfoutput[0][0] = ''; if (isset($_POST['printableexport'])) { $pdf->intopdf($clang->gT("Please choose the appropriate response for each item:"), "U"); } $column_headings = array(); foreach ($fresult as $frow) { $column_headings[] = $frow['answer'] . self::_addsgqacode(" (" . $frow['code'] . ")"); } if (trim($qidattributes['answer_width']) != '') { $iAnswerWidth = 100 - $qidattributes['answer_width']; } else { $iAnswerWidth = 80; } if (count($column_headings) > 0) { $col_width = round($iAnswerWidth / count($column_headings)); } else { $heading = ''; } $question['ANSWER'] .= "\n<table>\n\t<thead>\n\t\t<tr>\n"; $question['ANSWER'] .= "\t\t\t<td> </td>\n"; foreach ($column_headings as $heading) { $question['ANSWER'] .= "\t\t\t<th style=\"width:{$col_width}%;\">{$heading}</th>\n"; } $pdfoutput[0][$i] = $heading; $i++; $question['ANSWER'] .= "\t\t</tr>\n\t</thead>\n\n\t<tbody>\n"; $counter = 1; $rowclass = 'array1'; foreach ($mearesult->readAll() as $mearow) { $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n"; $rowclass = alternation($rowclass, 'row'); if (trim($answertext) == '') { $answertext = ' '; } //semantic differential question type? if (strpos($mearow['question'], '|')) { $answertext = substr($mearow['question'], 0, strpos($mearow['question'], '|')) . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")") . " "; } else { $answertext = $mearow['question'] . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")"); } if (trim($qidattributes['answer_width']) != '') { $sInsertStyle = ' style="width:' . $qidattributes['answer_width'] . '%" '; } else { $sInsertStyle = ''; } $question['ANSWER'] .= "\t\t\t<th {$sInsertStyle} class=\"answertext\">{$answertext}</th>\n"; $pdfoutput[$counter][0] = $answertext; for ($i = 1; $i <= $fcount; $i++) { $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio') . "</td>\n"; $pdfoutput[$counter][$i] = "o"; } $counter++; $answertext = $mearow['question']; //semantic differential question type? if (strpos($mearow['question'], '|')) { $answertext2 = substr($mearow['question'], strpos($mearow['question'], '|') + 1); $question['ANSWER'] .= "\t\t\t<th class=\"answertextright\">{$answertext2}</th>\n"; } $question['ANSWER'] .= "\t\t</tr>\n"; } $question['ANSWER'] .= "\t</tbody>\n</table>\n"; if (isset($_POST['printableexport'])) { $pdf->tableintopdf($pdfoutput); } break; // ================================================================== // ================================================================== case "1": //ARRAY (Flexible Labels) multi scale $leftheader = $qidattributes['dualscale_headerA'][$surveyprintlang]; $rightheader = $qidattributes['dualscale_headerB'][$surveyprintlang]; $headstyle = 'style="padding-left: 20px; padding-right: 7px"'; //$meaquery = "SELECT * FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$surveyprintlang}' ORDER BY question_order"; //$mearesult = Yii::app()->db->createCommand($meaquery)->query(); $mearesult = Questions::model()->getAllRecords(" parent_qid={$deqrow['qid']} AND language='{$surveyprintlang}' ", array('question_order')); $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please choose the appropriate response for each item:"); $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $surveyprintlang, $surveyid); if (isset($_POST['printableexport'])) { $pdf->intopdf($clang->gT("Please choose the appropriate response for each item:"), "U"); } $question['ANSWER'] .= "\n<table>\n\t<thead>\n"; $condition = "qid= '{$deqrow['qid']}' AND language= '{$surveyprintlang}' AND scale_id=0"; $fresult = Answers::model()->getAllRecords($condition, array('sortorder', 'code')); $fresult = $fresult->readAll(); $fcount = count($fresult); $fwidth = "120"; $l1 = 0; $printablesurveyoutput2 = "\t\t\t<td> </td>\n"; $myheader2 = ''; $pdfoutput = array(); $pdfoutput[0][0] = ''; foreach ($fresult as $frow) { $printablesurveyoutput2 .= "\t\t\t<th>{$frow['answer']}" . self::_addsgqacode(" (" . $frow['code'] . ")") . "</th>\n"; $myheader2 .= "<td></td>"; $pdfoutput[0][$l1 + 1] = $frow['answer']; $l1++; } // second scale $printablesurveyoutput2 .= "\t\t\t<td> </td>\n"; //$fquery1 = "SELECT * FROM {{answers}} WHERE qid='{$deqrow['qid']}' AND language='{$surveyprintlang}' AND scale_id=1 ORDER BY sortorder, code"; // $fresult1 = Yii::app()->db->createCommand($fquery1)->query(); $fresult1 = Answers::model()->getAllRecords(" qid='{$deqrow['qid']}' AND language='{$surveyprintlang}' AND scale_id=1 ", array('sortorder', 'code')); $fresult1 = $fresult1->readAll(); $fcount1 = count($fresult1); $fwidth = "120"; $l2 = 0; //array to temporary store second scale question codes $scale2array = array(); foreach ($fresult1 as $frow1) { $printablesurveyoutput2 .= "\t\t\t<th>{$frow1['answer']}" . self::_addsgqacode(" (" . $frow1['code'] . ")") . "</th>\n"; $pdfoutput[1][$l2] = $frow['answer']; //add current question code $scale2array[$l2] = $frow1['code']; $l2++; } // build header if needed if ($leftheader != '' || $rightheader != '') { $myheader = "\t\t\t<td> </td>"; $myheader .= "\t\t\t<th colspan=\"" . $l1 . "\">{$leftheader}</th>\n"; if ($rightheader != '') { // $myheader .= "\t\t\t\t\t" .$myheader2; $myheader .= "\t\t\t<td> </td>"; $myheader .= "\t\t\t<th colspan=\"" . $l2 . "\">{$rightheader}</td>\n"; } $myheader .= "\t\t\t\t</tr>\n"; } else { $myheader = ''; } $question['ANSWER'] .= $myheader . "\t\t</tr>\n\n\t\t<tr>\n"; $question['ANSWER'] .= $printablesurveyoutput2; $question['ANSWER'] .= "\t\t</tr>\n\t</thead>\n\n\t<tbody>\n"; $rowclass = 'array1'; //counter for each subquestion $sqcounter = 0; foreach ($mearesult->readAll() as $mearow) { $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n"; $rowclass = alternation($rowclass, 'row'); $answertext = $mearow['question'] . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . "#0) / (" . $fieldname . $mearow['title'] . "#1)"); if (strpos($answertext, '|')) { $answertext = substr($answertext, 0, strpos($answertext, '|')); } $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$answertext}</th>\n"; for ($i = 1; $i <= $fcount; $i++) { $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio') . "</td>\n"; } $question['ANSWER'] .= "\t\t\t<td> </td>\n"; for ($i = 1; $i <= $fcount1; $i++) { $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio') . "</td>\n"; } $answertext = $mearow['question']; if (strpos($answertext, '|')) { $answertext = substr($answertext, strpos($answertext, '|') + 1); $question['ANSWER'] .= "\t\t\t<th class=\"answertextright\">{$answertext}</th>\n"; } $question['ANSWER'] .= "\t\t</tr>\n"; //increase subquestion counter $sqcounter++; } $question['ANSWER'] .= "\t</tbody>\n</table>\n"; if (isset($_POST['printableexport'])) { $pdf->tableintopdf($pdfoutput); } break; // ================================================================== // ================================================================== case "H": //ARRAY (Flexible Labels) by Column //$headstyle="style='border-left-style: solid; border-left-width: 1px; border-left-color: #AAAAAA'"; $headstyle = "style='padding-left: 20px; padding-right: 7px'"; $condition = "parent_qid= '{$deqrow['qid']}' AND language= '{$surveyprintlang}'"; $fresult = Questions::model()->getAllRecords($condition, array('question_order', 'title')); $fresult = $fresult->readAll(); $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please choose the appropriate response for each item:"); if (isset($_POST['printableexport'])) { $pdf->intopdf($clang->gT("Please choose the appropriate response for each item:"), "U"); } $question['ANSWER'] .= "\n<table>\n\t<thead>\n\t\t<tr>\n\t\t\t<td> </td>\n"; $mearesult = Answers::model()->getAllRecords(" qid='{$deqrow['qid']}' AND scale_id=0 AND language='{$surveyprintlang}' ", array('sortorder', 'code')); $fcount = count($fresult); $fwidth = "120"; $i = 0; $pdfoutput = array(); $pdfoutput[0][0] = ''; foreach ($fresult as $frow) { $question['ANSWER'] .= "\t\t\t<th>{$frow['question']}" . self::_addsgqacode(" (" . $fieldname . $frow['title'] . ")") . "</th>\n"; $i++; $pdfoutput[0][$i] = $frow['question']; } $question['ANSWER'] .= "\t\t</tr>\n\t</thead>\n\n\t<tbody>\n"; $a = 1; $rowclass = 'array1'; foreach ($mearesult->readAll() as $mearow) { //$_POST['type']=$type; $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n"; $rowclass = alternation($rowclass, 'row'); $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$mearow['answer']}" . self::_addsgqacode(" (" . $mearow['code'] . ")") . "</th>\n"; //$printablesurveyoutput .="\t\t\t\t\t<td>"; $pdfoutput[$a][0] = $mearow['answer']; for ($i = 1; $i <= $fcount; $i++) { $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio') . "</td>\n"; $pdfoutput[$a][$i] = "o"; } //$printablesurveyoutput .="\t\t\t\t\t</tr></table></td>\n"; $question['ANSWER'] .= "\t\t</tr>\n"; $a++; } $question['ANSWER'] .= "\t</tbody>\n</table>\n"; if (isset($_POST['printableexport'])) { $pdf->tableintopdf($pdfoutput); } break; case "|": // File Upload $question['QUESTION_TYPE_HELP'] .= "Kindly attach the aforementioned documents along with the survey"; break; // === END SWITCH =================================================== } if (isset($_POST['printableexport'])) { $pdf->ln(5); } $question['QUESTION_TYPE_HELP'] = self::_star_replace($question['QUESTION_TYPE_HELP']); $group['QUESTIONS'] .= self::_populate_template('question', $question); } if ($bGroupHasVisibleQuestions) { $survey_output['GROUPS'] .= self::_populate_template('group', $group); } } $survey_output['THEREAREXQUESTIONS'] = str_replace('{NUMBEROFQUESTIONS}', $total_questions, $clang->gT('There are {NUMBEROFQUESTIONS} questions in this survey')); // START recursive tag stripping. // PHP 5.1.0 introduced the count parameter for preg_replace() and thus allows this procedure to run with only one regular expression. // Previous version of PHP needs two regular expressions to do the same thing and thus will run a bit slower. $server_is_newer = version_compare(PHP_VERSION, '5.1.0', '>'); $rounds = 0; while ($rounds < 1) { $replace_count = 0; if ($server_is_newer) { $survey_output['GROUPS'] = preg_replace(array('/<td>(?: | | )?<\\/td>/isU', '/<th[^>]*>(?: | | )?<\\/th>/isU', '/<([^ >]+)[^>]*>(?: | |\\r\\n|\\n\\r|\\n|\\r|\\t| )*<\\/\\1>/isU'), array('[[EMPTY-TABLE-CELL]]', '[[EMPTY-TABLE-CELL-HEADER]]', ''), $survey_output['GROUPS'], -1, $replace_count); } else { $survey_output['GROUPS'] = preg_replace(array('/<td>(?: | | )?<\\/td>/isU', '/<th[^>]*>(?: | | )?<\\/th>/isU', '/<([^ >]+)[^>]*>(?: | |\\r\\n|\\n\\r|\\n|\\r|\\t| )*<\\/\\1>/isU'), array('[[EMPTY-TABLE-CELL]]', '[[EMPTY-TABLE-CELL-HEADER]]', ''), $survey_output['GROUPS']); $replace_count = preg_match('/<([^ >]+)[^>]*>(?: | |\\r\\n|\\n\\r|\\n|\\r|\\t| )*<\\/\\1>/isU', $survey_output['GROUPS']); } if ($replace_count == 0) { ++$rounds; $survey_output['GROUPS'] = preg_replace(array('/\\[\\[EMPTY-TABLE-CELL\\]\\]/', '/\\[\\[EMPTY-TABLE-CELL-HEADER\\]\\]/', '/\\n(?:\\t*\\n)+/'), array('<td> </td>', '<th> </th>', "\n"), $survey_output['GROUPS']); } } $survey_output['GROUPS'] = preg_replace('/(<div[^>]*>){NOTEMPTY}(<\\/div>)/', '\\1 \\2', $survey_output['GROUPS']); // END recursive empty tag stripping. if (isset($_POST['printableexport'])) { if ($surveystartdate != '') { if (isset($_POST['printableexport'])) { $pdf->intopdf(sprintf($clang->gT("Please submit by %s"), $surveyexpirydate)); } } if (!empty($surveyfaxto) && $surveyfaxto != '000-00000000') { if (isset($_POST['printableexport'])) { $pdf->intopdf(sprintf($clang->gT("Please fax your completed survey to: %s"), $surveyfaxto), 'B'); } } $pdf->titleintopdf($clang->gT("Submit Your Survey."), $clang->gT("Thank you for completing this survey.")); $pdf->write_out($clang->gT($surveyname) . " " . $surveyid . ".pdf"); } else { echo self::_populate_template('survey', $survey_output); } }
echo $form->labelEx($model, 'userID'); ?> <?php echo CHtml::activeDropDownList($model, 'userID', CHtml::listData(Users::model()->findAll(), 'userID', 'userName'), array('empty' => 'Select User')); ?> <?php echo $form->error($model, 'userID'); ?> </div> <div class="row"> <?php echo $form->labelEx($model, 'groupID'); ?> <?php echo CHtml::activeDropDownList($model, 'groupID', CHtml::listData(Groups::model()->findAll(), 'groupID', 'groupName'), array('empty' => 'Select a Group')); ?> <?php echo $form->error($model, 'groupID'); ?> </div> <div class="row"> <?php echo $form->labelEx($model, 'active'); ?> <?php echo $form->textField($model, 'active'); ?> <?php echo $form->error($model, 'active');
/** * Generate a link to a user or group. * * Creates a link or list of links to a user or group to be displayed on a record. * @param integer|array|string $users If array, links to a group; if integer, the group whose * ID is that value; if keyword "Anyone", not a link but simply displays "anyone". * @param boolean $makeLinks Can be set to False to disable creating links but still return the name of the linked-to object * @return string The rendered links */ public static function getUserLinks($users, $makeLinks = true, $useFullName = true) { if (Yii::app()->params->isMobileApp) { $makeGroupLinks = false; } else { $makeGroupLinks = $makeLinks; } if (!is_array($users)) { /* x2temp */ if (preg_match('/^\\d+$/', $users)) { $group = Groups::model()->findByPk($users); if (isset($group)) { //$link = $makeLinks ? CHtml::link($group->name, array('/groups/groups/view', 'id' => $group->id)) : $group->name; $link = $makeGroupLinks ? CHtml::link($group->name, Yii::app()->controller->createAbsoluteUrl('/groups/groups/view', array('id' => $group->id)), array('style' => 'text-decoration:none;')) : $group->name; } else { $link = ''; } return $link; } /* end x2temp */ if ($users == '' || $users == 'Anyone') { return Yii::t('app', 'Anyone'); } $users = explode(', ', $users); } $links = array(); $userCache = Yii::app()->params->userCache; foreach ($users as $user) { if ($user == 'Email') { // skip these, they aren't users continue; } elseif ($user == 'Anyone') { $links[] = Yii::t('app', 'Anyone'); } else { if (is_numeric($user)) { // this is a group if (isset($userCache[$user])) { $group = $userCache[$user]; //$links[] = $makeLinks ? CHtml::link($group->name, array('/groups/groups/view', 'id' => $group->id)) : $group->name; $links[] = $makeGroupLinks ? CHtml::link($group->name, Yii::app()->controller->createAbsoluteUrl('/groups/groups/view', array('id' => $group->id)), array('style' => 'text-decoration:none;')) : $group->name; } else { $group = Groups::model()->findByPk($user); // $group = Groups::model()->findByPk($users); if (isset($group)) { //$groupLink = $makeLinks ? CHtml::link($group->name, array('/groups/groups/view', 'id' => $group->id)) : $group->name; $groupLink = $makeGroupLinks ? CHtml::link($group->name, Yii::app()->controller->createAbsoluteUrl('/groups/groups/view', array('id' => $group->id)), array('style' => 'text-decoration:none;')) : $group->name; $userCache[$user] = $group; $links[] = $groupLink; } } } else { if (isset($userCache[$user])) { $model = $userCache[$user]; $linkText = $useFullName ? $model->fullName : $model->getAlias(); //$userLink = $makeLinks ? CHtml::link($linkText, array('/profile/view', 'id' => $model->id)) : $linkText; $userLink = $makeLinks ? $model->getLink(array('style' => 'text-decoration:none;')) : $linkText; $links[] = $userLink; } else { $model = X2Model::model('User')->findByAttributes(array('username' => $user)); if (isset($model)) { $linkText = $useFullName ? $model->fullName : $model->getAlias(); //$userLink = $makeLinks ? CHtml::link($linkText, array('/profile/view', 'id' => $model->id)) : $linkText; $userLink = $makeLinks ? $model->getLink(array('style' => 'text-decoration:none;')) : $linkText; $userCache[$user] = $model; $links[] = $userLink; } } } } } Yii::app()->params->userCache = $userCache; return implode(', ', $links); }
/** * This function replaces the old insertans tags with new ones across a survey * * @param string $newsid Old SID * @param string $oldsid New SID * @param mixed $fieldnames Array array('oldfieldname'=>'newfieldname') */ function translateInsertansTags($newsid, $oldsid, $fieldnames) { uksort($fieldnames, create_function('$a,$b', 'return strlen($a) < strlen($b);')); Yii::app()->loadHelper('database'); $newsid = sanitize_int($newsid); $oldsid = sanitize_int($oldsid); # translate 'surveyls_urldescription' and 'surveyls_url' INSERTANS tags in surveyls $sql = "SELECT surveyls_survey_id, surveyls_language, surveyls_urldescription, surveyls_url from {{surveys_languagesettings}}\n WHERE surveyls_survey_id=" . $newsid . " AND (surveyls_urldescription LIKE '%{$oldsid}X%' OR surveyls_url LIKE '%{$oldsid}X%')"; $result = dbExecuteAssoc($sql) or show_error("Can't read groups table in transInsertAns "); // Checked //while ($qentry = $res->FetchRow()) foreach ($result->readAll() as $qentry) { $urldescription = $qentry['surveyls_urldescription']; $endurl = $qentry['surveyls_url']; $language = $qentry['surveyls_language']; foreach ($fieldnames as $sOldFieldname => $sNewFieldname) { $pattern = $sOldFieldname; $replacement = $sNewFieldname; $urldescription = preg_replace('/' . $pattern . '/', $replacement, $urldescription); $endurl = preg_replace('/' . $pattern . '/', $replacement, $endurl); } if (strcmp($urldescription, $qentry['surveyls_urldescription']) != 0 || strcmp($endurl, $qentry['surveyls_url']) != 0) { // Update Field $data = array('surveyls_urldescription' => $urldescription, 'surveyls_url' => $endurl); $where = array('surveyls_survey_id' => $newsid, 'surveyls_language' => $language); Surveys_languagesettings::update($data, $where); } // Enf if modified } // end while qentry # translate 'quotals_urldescrip' and 'quotals_url' INSERTANS tags in quota_languagesettings $sql = "SELECT quotals_id, quotals_urldescrip, quotals_url from {{quota_languagesettings}} qls, {{quota}} q\n WHERE sid=" . $newsid . " AND q.id=qls.quotals_quota_id AND (quotals_urldescrip LIKE '%{$oldsid}X%' OR quotals_url LIKE '%{$oldsid}X%')"; $result = dbExecuteAssoc($sql) or safeDie("Can't read quota table in transInsertAns"); // Checked foreach ($result->readAll() as $qentry) { $urldescription = $qentry['quotals_urldescrip']; $endurl = $qentry['quotals_url']; foreach ($fieldnames as $sOldFieldname => $sNewFieldname) { $pattern = $sOldFieldname; $replacement = $sNewFieldname; $urldescription = preg_replace('/' . $pattern . '/', $replacement, $urldescription); $endurl = preg_replace('/' . $pattern . '/', $replacement, $endurl); } if (strcmp($urldescription, $qentry['quotals_urldescrip']) != 0 || strcmp($endurl, $qentry['quotals_url']) != 0) { // Update Field $sqlupdate = "UPDATE {{quota_languagesettings}} SET quotals_urldescrip='" . $urldescription . "', quotals_url='" . $endurl . "' WHERE quotals_id={$qentry['quotals_id']}"; $updateres = dbExecuteAssoc($sqlupdate) or safeDie("Couldn't update INSERTANS in quota_languagesettings<br />{$sqlupdate}<br />"); //Checked } // Enf if modified } // end while qentry # translate 'description' INSERTANS tags in groups $sql = "SELECT gid, language, group_name, description from {{groups}}\n WHERE sid=" . $newsid . " AND description LIKE '%{$oldsid}X%' OR group_name LIKE '%{$oldsid}X%'"; $res = dbExecuteAssoc($sql) or show_error("Can't read groups table in transInsertAns"); // Checked //while ($qentry = $res->FetchRow()) foreach ($res->readAll() as $qentry) { $gpname = $qentry['group_name']; $description = $qentry['description']; $gid = $qentry['gid']; $language = $qentry['language']; foreach ($fieldnames as $sOldFieldname => $sNewFieldname) { $pattern = $sOldFieldname; $replacement = $sNewFieldname; $gpname = preg_replace('/' . $pattern . '/', $replacement, $gpname); $description = preg_replace('/' . $pattern . '/', $replacement, $description); } if (strcmp($description, $qentry['description']) != 0 || strcmp($gpname, $qentry['group_name']) != 0) { // Update Fields $data = array('description' => $description, 'group_name' => $gpname); $where = array('gid' => $gid, 'language' => $language); Groups::model()->update($data, $where); } // Enf if modified } // end while qentry # translate 'question' and 'help' INSERTANS tags in questions $sql = "SELECT qid, language, question, help from {{questions}}\n WHERE sid=" . $newsid . " AND (question LIKE '%{$oldsid}X%' OR help LIKE '%{$oldsid}X%')"; $result = dbExecuteAssoc($sql) or die("Can't read question table in transInsertAns "); // Checked //while ($qentry = $res->FetchRow()) $aResultData = $result->readAll(); foreach ($aResultData as $qentry) { $question = $qentry['question']; $help = $qentry['help']; $qid = $qentry['qid']; $language = $qentry['language']; foreach ($fieldnames as $sOldFieldname => $sNewFieldname) { $pattern = $sOldFieldname; $replacement = $sNewFieldname; $question = preg_replace('/' . $pattern . '/', $replacement, $question); $help = preg_replace('/' . $pattern . '/', $replacement, $help); } if (strcmp($question, $qentry['question']) != 0 || strcmp($help, $qentry['help']) != 0) { // Update Field $data = array('question' => $question, 'help' => $help); $where = array('qid' => $qid, 'language' => $language); Questions::model()->updateByPk($where, $data); } // Enf if modified } // end while qentry # translate 'answer' INSERTANS tags in answers $result = Answers::model()->oldNewInsertansTags($newsid, $oldsid); //while ($qentry = $res->FetchRow()) foreach ($result as $qentry) { $answer = $qentry['answer']; $code = $qentry['code']; $qid = $qentry['qid']; $language = $qentry['language']; foreach ($fieldnames as $sOldFieldname => $sNewFieldname) { $pattern = $sOldFieldname; $replacement = $sNewFieldname; $answer = preg_replace('/' . $pattern . '/', $replacement, $answer); } if (strcmp($answer, $qentry['answer']) != 0) { // Update Field $data = array('answer' => $answer, 'qid' => $qid); $where = array('code' => $code, 'language' => $language); Answers::model()->update($data, $where); } // Enf if modified } // end while qentry }
private function _collectGroupData($iSurveyID) { $aData = array(); $groups = Groups::model()->findAllByAttributes(array('sid' => $iSurveyID)); foreach ($groups as $group) { $groupId = $group->attributes['gid']; $groupName = $group->attributes['group_name']; $aData['groups'][$groupId] = $groupName; } return $aData; }
public function actionAddContact($id) { $users = User::getNames(); unset($users['admin']); unset($users['']); foreach (Groups::model()->findAll() as $group) { $users[$group->id] = $group->name; } $contacts = Contacts::getAllNames(); unset($contacts['0']); $model = $this->loadModel($id); $contacts = Sales::editContactArray($contacts, $model); // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if (isset($_POST['Sales'])) { $temp = $model->associatedContacts; $tempArr = $model->attributes; $model->attributes = $_POST['Sales']; $arr = $_POST['Sales']['associatedContacts']; foreach ($arr as $contactId) { $rel = new Relationships(); $rel->firstType = 'Contacts'; $rel->firstId = $contactId; $rel->secondType = 'Sales'; $rel->secondId = $model->id; $rel->save(); } $model->associatedContacts = Sales::parseContacts($arr); $temp .= " " . $model->associatedContacts; $model->associatedContacts = $temp; $changes = $this->calculateChanges($tempArr, $model->attributes); $model = $this->updateChangelog($model, $changes); if ($model->save()) { $this->redirect(array('view', 'id' => $model->id)); } } $this->render('addContact', array('model' => $model, 'users' => $users, 'contacts' => $contacts, 'action' => 'Add')); }
//} //",'screen, projection'); Yii::app()->clientScript->registerScript('renderMultiSelect', "\n\$(document).ready(function() {\n\t \$('.multiselect').multiselect();\n});\n", CClientScript::POS_HEAD); $selected = array(); $unselected = array(); $fields = Fields::model()->findAllBySql("SELECT * FROM x2_fields ORDER BY modelName ASC"); foreach ($fields as $field) { $unselected[$field->id] = X2Model::getModelTitle($field->modelName) . " - " . $field->attributeLabel; } $users = User::getNames(); unset($users['']); unset($users['Anyone']); unset($users['admin']); $users = array_map(array('CHtml', 'encode'), $users); /* x2temp */ $groups = Groups::model()->findAll(); foreach ($groups as $group) { $users[$group->id] = CHtml::encode($group->name); } /* end x2temp */ ?> <div class="page-title rounded-top"><h2><?php echo Yii::t('admin', 'Add Role'); ?> </h2></div> <div class="form"> <div style="max-width:600px"> <?php echo Yii::t('admin', 'Roles allow you to control which fields are editable on a record and by whom. To add a role, enter the name, a list of users, and a list of fields they are allowed to view or edit. Any field not included will be assumed to be unavailable to users of that Role.'); ?> </div>
/** * Provides an interface for updating a group * * @access public * @param int $gid * @return void */ public function update($gid) { $gid = (int) $gid; $group = Groups::model()->findByAttributes(array('gid' => $gid)); $surveyid = $group->sid; if (hasSurveyPermission($surveyid, 'surveycontent', 'update')) { Yii::app()->loadHelper('surveytranslator'); $grplangs = Survey::model()->findByPk($surveyid)->additionalLanguages; $baselang = Survey::model()->findByPk($surveyid)->language; array_push($grplangs, $baselang); foreach ($grplangs as $grplang) { if (isset($grplang) && $grplang != "") { $group_name = $_POST['group_name_' . $grplang]; $group_description = $_POST['description_' . $grplang]; $group_name = html_entity_decode($group_name, ENT_QUOTES, "UTF-8"); $group_description = html_entity_decode($group_description, ENT_QUOTES, "UTF-8"); // Fix bug with FCKEditor saving strange BR types $group_name = fixCKeditorText($group_name); $group_description = fixCKeditorText($group_description); $aData = array('group_name' => $group_name, 'description' => $group_description, 'randomization_group' => $_POST['randomization_group'], 'grelevance' => $_POST['grelevance']); $condition = array('gid' => $gid, 'sid' => $surveyid, 'language' => $grplang); $group = Groups::model()->findByAttributes($condition); foreach ($aData as $k => $v) { $group->{$k} = $v; } $ugresult = $group->save(); if ($ugresult) { $groupsummary = getGroupList($gid, $surveyid); } } } Yii::app()->session['flashmessage'] = Yii::app()->lang->gT("Question group successfully saved."); $this->getController()->redirect($this->getController()->createUrl('admin/survey/sa/view/surveyid/' . $surveyid . '/gid/' . $gid)); } }
/** * Echo out a series of inputs for a role editor page. * * This method is called via AJAX from the "Edit Role" portion of the "Manage Roles" * page. Upon selection of a role in the dropdown on that page, this method * finds all relevant information about the role and echoes it back as a form * to allow for editing of the role. */ public function actionGetRole() { if (isset($_POST['Roles'])) { $id = $_POST['Roles']['name']; $role = Roles::model()->findByAttributes(array('name' => $id)); if (!$role) { echo ""; exit; } $id = $role->id; $roles = RoleToUser::model()->findAllByAttributes(array('roleId' => $id)); $users = array(); foreach ($roles as $link) { if ($link->type == 'user') { $user = User::model()->findByPk($link->userId); if (isset($user)) { $users[] = $user->username; } } else { $group = Groups::model()->findByPk($link->userId); if (isset($group)) { $users[] = $group->id; } } /* end x2temp */ } $allUsers = User::model()->findAll('status="1"'); $selected = array(); $unselected = array(); foreach ($users as $user) { $selected[] = $user; } foreach ($allUsers as $user) { $unselected[CHtml::encode($user->username)] = CHtml::encode($user->firstName . " " . $user->lastName); } /* x2temp */ $groups = Groups::model()->findAll(); foreach ($groups as $group) { $unselected[$group->id] = CHtml::encode($group->name); } /* end x2temp */ unset($unselected['admin']); $sliderId = 'editTimeoutSlider'; $textfieldId = 'editTimeout'; if (isset($_GET['mode']) && in_array($_GET['mode'], array('edit', 'exception'))) { // Handle whether this was called from editRole or roleException, they // need different IDs to work on the same page. $sliderId .= "-" . $_GET['mode']; $textfieldId .= "-" . $_GET['mode']; } $timeoutSet = $role->timeout !== null; echo "\n <div class='row' id='set-session-timeout-row'>\n <input id='set-session-timeout' type='checkbox' class='left' " . ($timeoutSet ? 'checked="checked"' : '') . ">\n <label>" . Yii::t('admin', 'Enable Session Timeout') . "</label>\n </div>\n "; echo "<div id='timeout-row' class='row' " . ($timeoutSet ? '' : "style='display: none;'") . ">"; echo Yii::t('admin', 'Set role session expiration time (in minutes).'); echo "<br />"; $this->widget('zii.widgets.jui.CJuiSlider', array('value' => $role->timeout / 60, 'options' => array('min' => 5, 'max' => 1440, 'step' => 5, 'change' => "js:function(event,ui) {\n \$('#" . $textfieldId . "').val(ui.value);\n \$('#save-button').addClass('highlight');\n }", 'slide' => "js:function(event,ui) {\n \$('#" . $textfieldId . "').val(ui.value);\n }"), 'htmlOptions' => array('style' => 'width:340px;margin:10px 9px;', 'id' => $sliderId))); echo CHtml::activeTextField($role, 'timeout', array('id' => $textfieldId, 'disabled' => $role->timeout !== null ? '' : 'disabled')); echo "</div>"; Yii::app()->clientScript->registerScript('timeoutScript', "\n \$('#set-session-timeout').change (function () {\n if (\$(this).is (':checked')) {\n \$('#timeout-row').slideDown ();\n \$('#" . $textfieldId . "').removeAttr ('disabled');\n } else {\n \$('#timeout-row').slideUp ();\n \$('#" . $textfieldId . "').attr ('disabled', 'disabled');\n }\n });\n \$('#" . $textfieldId . "').val( \$('#" . $sliderId . "').slider('value') );\n ", CClientScript::POS_READY); echo "<script>"; Yii::app()->clientScript->echoScripts(); echo "</script>"; echo "<div id='users'><label>Users</label>"; echo CHtml::dropDownList('users[]', $selected, $unselected, array('class' => 'multiselect', 'multiple' => 'multiple', 'size' => 8)); echo "</div>"; $fields = Fields::model()->findAllBySql("SELECT * FROM x2_fields ORDER BY modelName ASC"); $viewSelected = array(); $editSelected = array(); $fieldUnselected = array(); $fieldPerms = RoleToPermission::model()->findAllByAttributes(array('roleId' => $role->id)); foreach ($fieldPerms as $perm) { if ($perm->permission == 2) { $viewSelected[] = $perm->fieldId; $editSelected[] = $perm->fieldId; } else { if ($perm->permission == 1) { $viewSelected[] = $perm->fieldId; } } } foreach ($fields as $field) { $fieldUnselected[$field->id] = X2Model::getModelTitle($field->modelName) . " - " . $field->attributeLabel; } echo "<br /><label>View Permissions</label>"; echo CHtml::dropDownList('viewPermissions[]', $viewSelected, $fieldUnselected, array('class' => 'multiselect', 'multiple' => 'multiple', 'size' => 8)); echo "<br /><label>Edit Permissions</label>"; echo CHtml::dropDownList('editPermissions[]', $editSelected, $fieldUnselected, array('class' => 'multiselect', 'multiple' => 'multiple', 'size' => 8)); } }
/** * Show survey summary * @param int Survey id * @param string Action to be performed */ function _surveysummary($iSurveyID, $action = null, $gid = null) { $clang = $this->getController()->lang; $baselang = Survey::model()->findByPk($iSurveyID)->language; $condition = array('sid' => $iSurveyID, 'language' => $baselang); $sumresult1 = Survey::model()->with(array('languagesettings' => array('condition' => 'surveyls_language=language')))->findByPk($iSurveyID); //$sumquery1, 1) ; //Checked if (is_null($sumresult1)) { Yii::app()->session['flashmessage'] = $clang->gT("Invalid survey ID"); $this->getController()->redirect($this->getController()->createUrl("admin/index")); } // if surveyid is invalid then die to prevent errors at a later time $surveyinfo = $sumresult1->attributes; $surveyinfo = array_merge($surveyinfo, $sumresult1->languagesettings[0]->attributes); $surveyinfo = array_map('flattenText', $surveyinfo); //$surveyinfo = array_map('htmlspecialchars', $surveyinfo); $activated = $surveyinfo['active']; $condition = array('sid' => $iSurveyID, 'parent_qid' => 0, 'language' => $baselang); $sumresult3 = Questions::model()->findAllByAttributes($condition); //Checked $sumcount3 = count($sumresult3); $condition = array('sid' => $iSurveyID, 'language' => $baselang); //$sumquery2 = "SELECT * FROM ".db_table_name('groups')." WHERE sid={$iSurveyID} AND language='".$baselang."'"; //Getting a count of groups for this survey $sumresult2 = Groups::model()->findAllByAttributes($condition); //Checked $sumcount2 = count($sumresult2); //SURVEY SUMMARY $aAdditionalLanguages = Survey::model()->findByPk($iSurveyID)->additionalLanguages; $surveysummary2 = ""; if ($surveyinfo['anonymized'] != "N") { $surveysummary2 .= $clang->gT("Responses to this survey are anonymized.") . "<br />"; } else { $surveysummary2 .= $clang->gT("Responses to this survey are NOT anonymized.") . "<br />"; } if ($surveyinfo['format'] == "S") { $surveysummary2 .= $clang->gT("It is presented question by question.") . "<br />"; } elseif ($surveyinfo['format'] == "G") { $surveysummary2 .= $clang->gT("It is presented group by group.") . "<br />"; } else { $surveysummary2 .= $clang->gT("It is presented on one single page.") . "<br />"; } if ($surveyinfo['allowjumps'] == "Y") { if ($surveyinfo['format'] == 'A') { $surveysummary2 .= $clang->gT("No question index will be shown with this format.") . "<br />"; } else { $surveysummary2 .= $clang->gT("A question index will be shown; participants will be able to jump between viewed questions.") . "<br />"; } } if ($surveyinfo['datestamp'] == "Y") { $surveysummary2 .= $clang->gT("Responses will be date stamped.") . "<br />"; } if ($surveyinfo['ipaddr'] == "Y") { $surveysummary2 .= $clang->gT("IP Addresses will be logged") . "<br />"; } if ($surveyinfo['refurl'] == "Y") { $surveysummary2 .= $clang->gT("Referrer URL will be saved.") . "<br />"; } if ($surveyinfo['usecookie'] == "Y") { $surveysummary2 .= $clang->gT("It uses cookies for access control.") . "<br />"; } if ($surveyinfo['allowregister'] == "Y") { $surveysummary2 .= $clang->gT("If tokens are used, the public may register for this survey") . "<br />"; } if ($surveyinfo['allowsave'] == "Y" && $surveyinfo['tokenanswerspersistence'] == 'N') { $surveysummary2 .= $clang->gT("Participants can save partially finished surveys") . "<br />\n"; } if ($surveyinfo['emailnotificationto'] != '') { $surveysummary2 .= $clang->gT("Basic email notification is sent to:") . " {$surveyinfo['emailnotificationto']}<br />\n"; } if ($surveyinfo['emailresponseto'] != '') { $surveysummary2 .= $clang->gT("Detailed email notification with response data is sent to:") . " {$surveyinfo['emailresponseto']}<br />\n"; } $dateformatdetails = getDateFormatData(Yii::app()->session['dateformat']); if (trim($surveyinfo['startdate']) != '') { Yii::import('application.libraries.Date_Time_Converter'); $datetimeobj = new Date_Time_Converter($surveyinfo['startdate'], 'Y-m-d H:i:s'); $aData['startdate'] = $datetimeobj->convert($dateformatdetails['phpdate'] . ' H:i'); } else { $aData['startdate'] = "-"; } if (trim($surveyinfo['expires']) != '') { //$constructoritems = array($surveyinfo['expires'] , "Y-m-d H:i:s"); Yii::import('application.libraries.Date_Time_Converter'); $datetimeobj = new Date_Time_Converter($surveyinfo['expires'], 'Y-m-d H:i:s'); //$datetimeobj = new Date_Time_Converter($surveyinfo['expires'] , "Y-m-d H:i:s"); $aData['expdate'] = $datetimeobj->convert($dateformatdetails['phpdate'] . ' H:i'); } else { $aData['expdate'] = "-"; } if (!$surveyinfo['language']) { $aData['language'] = getLanguageNameFromCode($currentadminlang, false); } else { $aData['language'] = getLanguageNameFromCode($surveyinfo['language'], false); } // get the rowspan of the Additionnal languages row // is at least 1 even if no additionnal language is present $additionnalLanguagesCount = count($aAdditionalLanguages); $first = true; $aData['additionnalLanguages'] = ""; if ($additionnalLanguagesCount == 0) { $aData['additionnalLanguages'] .= "<td>-</td>\n"; } else { foreach ($aAdditionalLanguages as $langname) { if ($langname) { if (!$first) { $aData['additionnalLanguages'] .= "<tr><td> </td>"; } $first = false; $aData['additionnalLanguages'] .= "<td>" . getLanguageNameFromCode($langname, false) . "</td></tr>\n"; } } } if ($first) { $aData['additionnalLanguages'] .= "</tr>"; } if ($surveyinfo['surveyls_urldescription'] == "") { $surveyinfo['surveyls_urldescription'] = htmlspecialchars($surveyinfo['surveyls_url']); } if ($surveyinfo['surveyls_url'] != "") { $aData['endurl'] = " <a target='_blank' href=\"" . htmlspecialchars($surveyinfo['surveyls_url']) . "\" title=\"" . htmlspecialchars($surveyinfo['surveyls_url']) . "\">{$surveyinfo['surveyls_urldescription']}</a>"; } else { $aData['endurl'] = "-"; } $aData['sumcount3'] = $sumcount3; $aData['sumcount2'] = $sumcount2; if ($activated == "N") { $aData['activatedlang'] = $clang->gT("No"); } else { $aData['activatedlang'] = $clang->gT("Yes"); } $aData['activated'] = $activated; if ($activated == "Y") { $aData['surveydb'] = Yii::app()->db->tablePrefix . "survey_" . $iSurveyID; } $aData['warnings'] = ""; if ($activated == "N" && $sumcount3 == 0) { $aData['warnings'] = $clang->gT("Survey cannot be activated yet.") . "<br />\n"; if ($sumcount2 == 0 && hasSurveyPermission($iSurveyID, 'surveycontent', 'create')) { $aData['warnings'] .= "<span class='statusentryhighlight'>[" . $clang->gT("You need to add question groups") . "]</span><br />"; } if ($sumcount3 == 0 && hasSurveyPermission($iSurveyID, 'surveycontent', 'create')) { $aData['warnings'] .= "<span class='statusentryhighlight'>[" . $clang->gT("You need to add questions") . "]</span><br />"; } } $aData['hints'] = $surveysummary2; //return (array('column'=>array($columns_used,$hard_limit) , 'size' => array($length, $size_limit) )); // $aData['tableusage'] = getDBTableUsage($iSurveyID); // ToDo: Table usage is calculated on every menu display which is too slow with bug surveys. // Needs to be moved to a database field and only updated if there are question/subquestions added/removed (it's currently also not functional due to the port) // $aData['tableusage'] = false; if ($gid || $action !== true && in_array($action, array('deactivate', 'activate', 'surveysecurity', 'editdefaultvalues', 'editemailtemplates', 'surveyrights', 'addsurveysecurity', 'addusergroupsurveysecurity', 'setsurveysecurity', 'setusergroupsurveysecurity', 'delsurveysecurity', 'editsurveysettings', 'editsurveylocalesettings', 'updatesurveysettingsandeditlocalesettings', 'addgroup', 'importgroup', 'ordergroups', 'deletesurvey', 'resetsurveylogic', 'importsurveyresources', 'translate', 'emailtemplates', 'exportstructure', 'quotas', 'copysurvey', 'viewgroup', 'viewquestion'))) { $showstyle = "style='display: none'"; } else { $showstyle = ""; } $aData['showstyle'] = $showstyle; $aData['aAdditionalLanguages'] = $aAdditionalLanguages; $aData['clang'] = $clang; $aData['surveyinfo'] = $surveyinfo; $this->getController()->render("/admin/survey/surveySummary_view", $aData); }
/** * Deletes a survey and all its data * * @access public * @param int $iSurveyID * @param bool @recursive * @return void */ public function deleteSurvey($iSurveyID, $recursive = true) { Survey::model()->deleteByPk($iSurveyID); if ($recursive == true) { if (tableExists("{{survey_" . intval($iSurveyID) . "}}")) { Yii::app()->db->createCommand()->dropTable("{{survey_" . intval($iSurveyID) . "}}"); } if (tableExists("{{survey_" . intval($iSurveyID) . "_timings}}")) { Yii::app()->db->createCommand()->dropTable("{{survey_" . intval($iSurveyID) . "_timings}}"); } if (tableExists("{{tokens_" . intval($iSurveyID) . "}}")) { Yii::app()->db->createCommand()->dropTable("{{tokens_" . intval($iSurveyID) . "}}"); } $oResult = Questions::model()->findAllByAttributes(array('sid' => $iSurveyID)); foreach ($oResult as $aRow) { Answers::model()->deleteAllByAttributes(array('qid' => $aRow['qid'])); Conditions::model()->deleteAllByAttributes(array('qid' => $aRow['qid'])); Question_attributes::model()->deleteAllByAttributes(array('qid' => $aRow['qid'])); Defaultvalues::model()->deleteAllByAttributes(array('qid' => $aRow['qid'])); } Questions::model()->deleteAllByAttributes(array('sid' => $iSurveyID)); Assessment::model()->deleteAllByAttributes(array('sid' => $iSurveyID)); Groups::model()->deleteAllByAttributes(array('sid' => $iSurveyID)); Surveys_languagesettings::model()->deleteAllByAttributes(array('surveyls_survey_id' => $iSurveyID)); Survey_permissions::model()->deleteAllByAttributes(array('sid' => $iSurveyID)); Saved_control::model()->deleteAllByAttributes(array('sid' => $iSurveyID)); Survey_url_parameters::model()->deleteAllByAttributes(array('sid' => $iSurveyID)); Quota::model()->deleteQuota(array('sid' => $iSurveyID), true); } }
public function actionAddUser($id) { $users = User::getNames(); unset($users['admin']); unset($users['']); foreach (Groups::model()->findAll() as $group) { $users[$group->id] = $group->name; } //$contacts = Contacts::getAllNames(); // very inefficient with large table $model = $this->loadModel($id); $users = Accounts::editUserArray($users, $model); // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if (isset($_POST['Accounts'])) { $temp = $model->assignedTo; $tempArr = $model->attributes; $model->attributes = $_POST['Accounts']; $arr = $_POST['Accounts']['assignedTo']; $model->assignedTo = Fields::parseUsers($arr); if ($temp != "") { $temp .= ", " . $model->assignedTo; } else { $temp = $model->assignedTo; } $model->assignedTo = $temp; // $changes=$this->calculateChanges($tempArr,$model->attributes); // $model=$this->updateChangelog($model,$changes); if ($model->save()) { $this->redirect(array('view', 'id' => $model->id)); } } $this->render('addUser', array('model' => $model, 'users' => $users, 'action' => 'Add')); }
/** * Updates a particular model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id the ID of the model to be updated */ public function actionUpdate($id) { $model = $this->loadModel($id); $groups = array(); foreach (Groups::model()->findAll() as $group) { $groups[$group->id] = CHtml::encode($group->name); } $selectedGroups = array(); foreach (GroupToUser::model()->findAllByAttributes(array('userId' => $model->id)) as $link) { $selectedGroups[] = $link->groupId; } $roles = array(); foreach (Roles::model()->findAll() as $role) { $roles[$role->id] = CHtml::encode($role->name); } $selectedRoles = array(); foreach (RoleToUser::model()->findAllByAttributes(array('userId' => $model->id)) as $link) { $selectedRoles[] = $link->roleId; } // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if (!isset($model->userAlias)) { $model->userAlias = $model->username; } if (isset($_POST['User'])) { $old = $model->attributes; $temp = $model->password; $model->attributes = $_POST['User']; if ($model->password != "") { $model->password = PasswordUtil::createHash($model->password); } else { $model->password = $temp; } if (empty($model->userKey)) { $model->userKey = substr(str_shuffle(str_repeat('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789', 32)), 0, 32); } if ($model->save()) { $profile = $model->profile; if (!empty($profile)) { $profile->emailAddress = $model->emailAddress; $profile->fullName = $model->firstName . ' ' . $model->lastName; $profile->save(); } if ($old['username'] != $model->username) { $fieldRecords = Fields::model()->findAllByAttributes(array('fieldName' => 'assignedTo')); $modelList = array(); foreach ($fieldRecords as $record) { $modelList[$record->modelName] = $record->linkType; } foreach ($modelList as $modelName => $type) { if ($modelName == 'Quotes') { $modelName = "Quote"; } if ($modelName == 'Products') { $modelName = 'Product'; } if (empty($type)) { $list = X2Model::model($modelName)->findAllByAttributes(array('assignedTo' => $old['username'])); foreach ($list as $item) { $item->assignedTo = $model->username; $item->save(); } } else { $list = X2Model::model($modelName)->findAllBySql("SELECT * FROM " . X2Model::model($modelName)->tableName() . " WHERE assignedTo LIKE '%" . $old['username'] . "%'"); foreach ($list as $item) { $assignedTo = explode(", ", $item->assignedTo); $key = array_search($old['username'], $assignedTo); if ($key >= 0) { $assignedTo[$key] = $model->username; } $item->assignedTo = implode(", ", $assignedTo); $item->save(); } } } $profile = Profile::model()->findByAttributes(array('username' => $old['username'])); if (isset($profile)) { $profile->username = $model->username; $profile->save(); } } foreach (RoleToUser::model()->findAllByAttributes(array('userId' => $model->id)) as $link) { $link->delete(); } foreach (GroupToUser::model()->findAllByAttributes(array('userId' => $model->id)) as $link) { $link->delete(); } if (isset($_POST['roles'])) { $roles = $_POST['roles']; foreach ($roles as $role) { $link = new RoleToUser(); $link->roleId = $role; $link->type = "user"; $link->userId = $model->id; $link->save(); } } if (isset($_POST['groups'])) { $groups = $_POST['groups']; foreach ($groups as $group) { $link = new GroupToUser(); $link->groupId = $group; $link->userId = $model->id; $link->username = $model->username; $link->save(); } } $this->redirect(array('view', 'id' => $model->id)); } } $this->render('update', array('model' => $model, 'groups' => $groups, 'roles' => $roles, 'selectedGroups' => $selectedGroups, 'selectedRoles' => $selectedRoles)); }
public static function editUsersInverse($arr) { $data = array(); foreach ($arr as $username) { if ($username != '' && !is_numeric($username)) { $data[] = User::model()->findByAttributes(array('username' => $username)); } elseif (is_numeric($username)) { $data[] = Groups::model()->findByPK($username); } } $temp = array(); if (isset($data)) { foreach ($data as $item) { if (isset($item)) { if ($item instanceof User) { $temp[$item->username] = $item->firstName . ' ' . $item->lastName; } else { $temp[$item->id] = $item->name; } } } } return $temp; }
public function afterDelete() { // Roles have been updated, clear the cached roles for the corresponding // user (or for all group members, if a group) if ($this->type == 'user') { Roles::clearCachedUserRoles($this->userId); } elseif ($this->type == 'group') { // Clear the role cache for all users who were in the group $group = Groups::model()->findByPk($this->userId); if (!empty($group)) { if (count($group->users) > 0) { foreach ($group->users as $user) { Roles::clearCachedUserRoles($user->id); } } } } parent::afterSave(); }
public static function deleteWithDependency($groupId, $surveyId) { $questionIds = Groups::getQuestionIdsInGroup($groupId); Questions::deleteAllById($questionIds); Assessment::model()->deleteAllByAttributes(array('sid' => $surveyId, 'gid' => $groupId)); return Groups::model()->deleteAllByAttributes(array('sid' => $surveyId, 'gid' => $groupId)); }
protected function compareAssignment($data) { if (is_null($data)) { return null; } if (is_numeric($data)) { $models = Groups::model()->findAllBySql("SELECT * FROM x2_groups WHERE name LIKE '%{$data}%'"); $arr = array(); foreach ($models as $model) { $arr[] = $model->id; } return count($arr) > 0 ? $arr : -1; } else { $models = User::model()->findAllBySql("SELECT * FROM x2_users WHERE CONCAT(firstName,' ',lastName) LIKE '%{$data}%'"); $arr = array(); foreach ($models as $model) { $arr[] = $model->username; } return count($arr) > 0 ? $arr : -1; } }