public function actionPublicList($lang = null)
 {
     if (!empty($lang)) {
         App()->setLanguage($lang);
     } else {
         App()->setLanguage(App()->getConfig('defaultlang'));
     }
     $oTemplate = Template::model()->getInstance(Yii::app()->getConfig("defaulttemplate"));
     if ($oTemplate->cssFramework == 'bootstrap') {
         // We now use the bootstrap package isntead of the Yiistrap TbApi::register() method
         // Then instead of using the composer dependency system for templates
         // We can use the package dependency system
         Yii::app()->getClientScript()->registerMetaTag('width=device-width, initial-scale=1.0', 'viewport');
         App()->bootstrap->registerAllScripts();
     }
     $aData = array('publicSurveys' => Survey::model()->active()->open()->public()->with('languagesettings')->findAll(), 'futureSurveys' => Survey::model()->active()->registration()->public()->with('languagesettings')->findAll());
     $htmlOut = $this->render('publicSurveyList', $aData, true);
     $event = new PluginEvent('beforeSurveysStartpageRender', $this);
     $event->set('aData', $aData);
     App()->getPluginManager()->dispatchEvent($event);
     if ($event->get('result')) {
         $htmlFromEvent = $event->get('result');
         $htmlOut = $htmlFromEvent['html'];
     }
     echo $htmlOut;
 }
Beispiel #2
0
 public function run()
 {
     App()->loadHelper('surveytranslator');
     $aData['issuperadmin'] = false;
     if (Permission::model()->hasGlobalPermission('superadmin', 'read')) {
         $aData['issuperadmin'] = true;
     }
     // We get the last survey visited by user
     $setting_entry = 'last_survey_' . Yii::app()->user->getId();
     $lastsurvey = getGlobalSetting($setting_entry);
     $survey = Survey::model()->findByPk($lastsurvey);
     if ($lastsurvey != null && $survey) {
         $aData['showLastSurvey'] = true;
         $iSurveyID = $lastsurvey;
         $surveyinfo = $survey->surveyinfo;
         $aData['surveyTitle'] = $surveyinfo['surveyls_title'] . "(" . gT("ID") . ":" . $iSurveyID . ")";
         $aData['surveyUrl'] = $this->getController()->createUrl("admin/survey/sa/view/surveyid/{$iSurveyID}");
     } else {
         $aData['showLastSurvey'] = false;
     }
     // We get the last question visited by user
     $setting_entry = 'last_question_' . Yii::app()->user->getId();
     $lastquestion = getGlobalSetting($setting_entry);
     // the question group of this question
     $setting_entry = 'last_question_gid_' . Yii::app()->user->getId();
     $lastquestiongroup = getGlobalSetting($setting_entry);
     // the sid of this question : last_question_sid_1
     $setting_entry = 'last_question_sid_' . Yii::app()->user->getId();
     $lastquestionsid = getGlobalSetting($setting_entry);
     $survey = Survey::model()->findByPk($lastquestionsid);
     if ($lastquestion && $lastquestiongroup && $survey) {
         $baselang = $survey->language;
         $aData['showLastQuestion'] = true;
         $qid = $lastquestion;
         $gid = $lastquestiongroup;
         $sid = $lastquestionsid;
         $qrrow = Question::model()->findByAttributes(array('qid' => $qid, 'gid' => $gid, 'sid' => $sid, 'language' => $baselang));
         if ($qrrow) {
             $aData['last_question_name'] = $qrrow['title'];
             if ($qrrow['question']) {
                 $aData['last_question_name'] .= ' : ' . $qrrow['question'];
             }
             $aData['last_question_link'] = $this->getController()->createUrl("admin/questions/sa/view/surveyid/{$sid}/gid/{$gid}/qid/{$qid}");
         } else {
             $aData['showLastQuestion'] = false;
         }
     } else {
         $aData['showLastQuestion'] = false;
     }
     $aData['countSurveyList'] = count(getSurveyList(true));
     // We get the home page display setting
     $aData['bShowSurveyList'] = getGlobalSetting('show_survey_list') == "show";
     $aData['bShowSurveyListSearch'] = getGlobalSetting('show_survey_list_search') == "show";
     $aData['bShowLogo'] = getGlobalSetting('show_logo') == "show";
     $aData['oSurveySearch'] = new Survey('search');
     $aData['bShowLastSurveyAndQuestion'] = getGlobalSetting('show_last_survey_and_question') == "show";
     $aData['iBoxesByRow'] = (int) getGlobalSetting('boxes_by_row');
     $aData['sBoxesOffSet'] = (string) getGlobalSetting('boxes_offset');
     $this->_renderWrappedTemplate('super', 'welcome', $aData);
 }
 public function actionPublicList($sLanguage = null)
 {
     if (isset($sLanguage)) {
         App()->setLanguage($sLanguage);
     }
     $this->render('publicSurveyList', array('publicSurveys' => Survey::model()->active()->open()->public()->with('languagesettings')->findAll(), 'futureSurveys' => Survey::model()->active()->registration()->public()->with('languagesettings')->findAll()));
 }
Beispiel #4
0
 /**
  * Routes to the correct sub-action
  *
  * @access public
  * @param int $iSurveyID
  * @return void
  */
 public function index($iSurveyID)
 {
     $iSurveyID = sanitize_int($iSurveyID);
     $sAction = Yii::app()->request->getPost('action');
     $languages = Survey::model()->findByPk($iSurveyID)->additionalLanguages;
     $surveyLanguage = Survey::model()->findByPk($iSurveyID)->language;
     Yii::app()->session['FileManagerContext'] = "edit:assessments:{$iSurveyID}";
     array_unshift($languages, $surveyLanguage);
     // makes an array with ALL the languages supported by the survey -> $assessmentlangs
     Yii::app()->setConfig("baselang", $surveyLanguage);
     Yii::app()->setConfig("assessmentlangs", $languages);
     if ($sAction == "assessmentadd") {
         $this->_add($iSurveyID);
     }
     if ($sAction == "assessmentupdate") {
         $this->_update($iSurveyID);
     }
     if ($sAction == "assessmentdelete") {
         $this->_delete($iSurveyID, $_POST['id']);
     }
     if (Permission::model()->hasSurveyPermission($iSurveyID, 'assessments', 'read')) {
         if ($iSurveyID == '') {
             show_error(gT("No SID Provided"));
             die;
         }
         $this->_showAssessments($iSurveyID, $sAction, $surveyLanguage);
     }
 }
 /**
  * Check the Expression in quota
  * @param integer $iSurveyId : the survey id : can be sid/surveyid url GET parameters
  * @param integer $quota : the quota id
  * @param string $lang : the survey language, optional : if not set get all language of survey
  * 
  * @author Denis Chenu
  * @version 1.0
  */
 public function quota($iSurveyId, $quota, $lang = null)
 {
     if (!Permission::model()->hasSurveyPermission($iSurveyId, 'quotas', 'read')) {
         throw new CHttpException(401, "401 Unauthorized");
     }
     $iQuotaId = $quota;
     if (is_string($lang)) {
         $oValidator = new LSYii_Validators();
         $aLangs = array($oValidator->languageFilter($lang));
     } else {
         $aLangs = Survey::model()->findByPk($iSurveyId)->getAllLanguages();
     }
     $aExpressions = array();
     $this->iSurveyId = $iSurveyId;
     foreach ($aLangs as $sLang) {
         $oQuotaLanguageSetting = QuotaLanguageSetting::model()->find("quotals_quota_id =:quota_id and quotals_language=:language", array(':quota_id' => $iQuotaId, ':language' => $sLang));
         // We don't need to go to step since new feature #8823, maybe need to be fixed ?
         if ($oQuotaLanguageSetting) {
             $this->sLang = $sLang;
             $aExpressions['name_' . $sLang] = array('title' => sprintf("Quota name (%s)", $sLang), 'expression' => $this->getHtmlExpression($oQuotaLanguageSetting->quotals_name, array(), __METHOD__));
             $aExpressions['message_' . $sLang] = array('title' => sprintf("Quota message (%s)", $sLang), 'expression' => $this->getHtmlExpression($oQuotaLanguageSetting->quotals_message, array(), __METHOD__));
             $aExpressions['url_' . $sLang] = array('title' => sprintf("URL (%s)", $sLang), 'expression' => $this->getHtmlExpression($oQuotaLanguageSetting->quotals_url, array(), __METHOD__));
             $aExpressions['urldescrip_' . $sLang] = array('title' => sprintf("URL description (%s)", $sLang), 'expression' => $this->getHtmlExpression($oQuotaLanguageSetting->quotals_urldescrip, array(), __METHOD__));
         }
     }
     $aData = array('aExpressions' => $aExpressions);
     $this->getController()->layout = $this->layout;
     $this->getController()->pageTitle = gt("Validate quota");
     $this->getController()->render("/admin/expressions/validationList", $aData);
 }
 public function actionPublicList($lang = null)
 {
     $this->sessioncontrol();
     if (isset($lang)) {
         App()->setLang(new Limesurvey_lang($lang));
     }
     $this->render('publicSurveyList', array('publicSurveys' => Survey::model()->active()->open()->public()->with('languagesettings')->findAll(), 'futureSurveys' => Survey::model()->active()->registration()->public()->with('languagesettings')->findAll()));
 }
 public function actionPublicList($lang = null)
 {
     if (!empty($lang)) {
         App()->setLanguage(sanitize_languagecode($lang));
     } else {
         App()->setLanguage(App()->getConfig('defaultlang'));
     }
     $this->render('publicSurveyList', array('publicSurveys' => Survey::model()->active()->open()->public()->with('languagesettings')->findAll(), 'futureSurveys' => Survey::model()->active()->registration()->public()->with('languagesettings')->findAll()));
 }
 function actionLocal($surveyid, $token, $langcode = '')
 {
     Yii::app()->loadHelper('database');
     Yii::app()->loadHelper('sanitize');
     $sLanguageCode = $langcode;
     $iSurveyID = $surveyid;
     $sToken = $token;
     $sToken = sanitize_token($sToken);
     if (!$iSurveyID) {
         $this->redirect($this->getController()->createUrl('/'));
     }
     $iSurveyID = (int) $iSurveyID;
     //Check that there is a SID
     // Get passed language from form, so that we dont loose this!
     if (!isset($sLanguageCode) || $sLanguageCode == "" || !$sLanguageCode) {
         $baselang = Survey::model()->findByPk($iSurveyID)->language;
         Yii::import('application.libraries.Limesurvey_lang', true);
         $clang = new Limesurvey_lang($baselang);
     } else {
         $sLanguageCode = sanitize_languagecode($sLanguageCode);
         Yii::import('application.libraries.Limesurvey_lang', true);
         $clang = new Limesurvey_lang($sLanguageCode);
         $baselang = $sLanguageCode;
     }
     Yii::app()->lang = $clang;
     $thissurvey = getSurveyInfo($iSurveyID, $baselang);
     if ($thissurvey == false || Yii::app()->db->schema->getTable("{{tokens_{$iSurveyID}}}") == null) {
         $html = $clang->gT('This survey does not seem to exist.');
     } else {
         $row = Tokens_dynamic::getEmailStatus($iSurveyID, $sToken);
         if ($row == false) {
             $html = $clang->gT('You are not a participant in this survey.');
         } else {
             $usresult = $row['emailstatus'];
             if ($usresult == 'OptOut') {
                 $usresult = Tokens_dynamic::updateEmailStatus($iSurveyID, $sToken, 'OK');
                 $html = $clang->gT('You have been successfully added back to this survey.');
             } else {
                 if ($usresult == 'OK') {
                     $html = $clang->gT('You are already a part of this survey.');
                 } else {
                     $html = $clang->gT('You have been already removed from this survey.');
                 }
             }
         }
     }
     //PRINT COMPLETED PAGE
     if (!$thissurvey['templatedir']) {
         $thistpl = getTemplatePath(Yii::app()->getConfig("defaulttemplate"));
     } else {
         $thistpl = getTemplatePath($thissurvey['templatedir']);
     }
     $this->_renderHtml($html, $thistpl, $clang);
 }
Beispiel #9
0
 private function _getData($params)
 {
     if (is_numeric($params)) {
         $iSurveyId = $params;
     } elseif (is_array($params)) {
         extract($params);
     }
     $aData = array();
     // Set the variables in an array
     $aData['surveyid'] = $aData['iSurveyId'] = (int) $iSurveyId;
     if (!empty($iId)) {
         $aData['iId'] = (int) $iId;
     }
     $aData['clang'] = $clang = $this->getController()->lang;
     $aData['imageurl'] = Yii::app()->getConfig('imageurl');
     $aData['action'] = Yii::app()->request->getParam('action');
     $aData['all'] = Yii::app()->request->getParam('all');
     $oCriteria = new CDbCriteria();
     $oCriteria->select = 'sid, active';
     $oCriteria->join = 'INNER JOIN {{surveys_languagesettings}} as b on (b.surveyls_survey_id=sid and b.surveyls_language=language)';
     $oCriteria->condition = 'sid=:survey';
     $oCriteria->params = array('survey' => $iSurveyId);
     $actresult = Survey::model()->findAll($oCriteria);
     if (count($actresult) > 0) {
         foreach ($actresult as $actrow) {
             if ($actrow['active'] == 'N') {
                 Yii::app()->session['flashmessage'] = $clang->gT("This survey has not been activated. There are no results to browse.");
                 $this->getController()->redirect($this->getController()->createUrl("/admin/survey/sa/view/surveyid/{$iSurveyId}"));
             }
         }
     } else {
         Yii::app()->session['flashmessage'] = $clang->gT("Invalid survey ID");
         $this->getController()->redirect($this->getController()->createUrl("admin/index"));
     }
     //OK. IF WE GOT THIS FAR, THEN THE SURVEY EXISTS AND IT IS ACTIVE, SO LETS GET TO WORK.
     $aData['surveyinfo'] = getSurveyInfo($iSurveyId);
     if (isset($browselang) && $browselang != '') {
         Yii::app()->session['browselang'] = $browselang;
         $aData['language'] = Yii::app()->session['browselang'];
     } elseif (isset(Yii::app()->session['browselang'])) {
         $aData['language'] = Yii::app()->session['browselang'];
         $aData['languagelist'] = $languagelist = Survey::model()->findByPk($iSurveyId)->additionalLanguages;
         $aData['languagelist'][] = Survey::model()->findByPk($iSurveyId)->language;
         if (!in_array($aData['language'], $languagelist)) {
             $aData['language'] = Survey::model()->findByPk($iSurveyId)->language;
         }
     } else {
         $aData['language'] = Survey::model()->findByPk($iSurveyId)->language;
     }
     $aData['qulanguage'] = Survey::model()->findByPk($iSurveyId)->language;
     $aData['surveyoptions'] = '';
     $aData['browseoutput'] = '';
     return $aData;
 }
Beispiel #10
0
 /**
  * Renders template(s) wrapped in header and footer
  *
  * @param string $sAction Current action, the folder to fetch views from
  * @param string|array $aViewUrls View url(s)
  * @param array $aData Data to be passed on. Optional.
  */
 protected function _renderWrappedTemplate($sAction = 'assessments', $aViewUrls = array(), $aData = array())
 {
     $aData['sidebar']['state'] = "close";
     $iSurveyID = $aData['surveyid'];
     $surveyinfo = Survey::model()->findByPk($iSurveyID)->surveyinfo;
     $aData['title_bar']['title'] = $surveyinfo['surveyls_title'] . "(" . gT("ID") . ":" . $iSurveyID . ")";
     $aData['surveybar']['savebutton']['form'] = true;
     $aData['surveybar']['closebutton']['url'] = 'admin/survey/sa/view/surveyid/' . $iSurveyID;
     $aData['gid'] = null;
     App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('adminscripts') . 'assessments.js');
     parent::_renderWrappedTemplate($sAction, $aViewUrls, $aData);
 }
Beispiel #11
0
 /**
  * Renders template(s) wrapped in header and footer
  *
  * @param string $sAction Current action, the folder to fetch views from
  * @param string|array $aViewUrls View url(s)
  * @param array $aData Data to be passed on. Optional.
  */
 protected function _renderWrappedTemplate($sAction = 'saved', $aViewUrls = array(), $aData = array())
 {
     $aData['display']['menu_bars']['browse'] = gT('Browse responses');
     // browse is independent of the above
     $aData['surveyid'] = $iSurveyId = $aData['iSurveyId'];
     $surveyinfo = Survey::model()->findByPk($iSurveyId)->surveyinfo;
     $aData["surveyinfo"] = $surveyinfo;
     $aData['title_bar']['title'] = gT('Browse responses') . ': ' . $surveyinfo['surveyls_title'];
     $aData['menu']['close'] = true;
     $aData['menu']['edition'] = false;
     parent::_renderWrappedTemplate($sAction, $aViewUrls, $aData);
 }
 function actiontokens($surveyid, $token, $langcode = '')
 {
     Yii::app()->loadHelper('database');
     Yii::app()->loadHelper('sanitize');
     $sLanguageCode = $langcode;
     $iSurveyID = $surveyid;
     $sToken = $token;
     $sToken = sanitize_token($sToken);
     if (!$iSurveyID) {
         $this->redirect(array('/'));
     }
     $iSurveyID = (int) $iSurveyID;
     //Check that there is a SID
     // Get passed language from form, so that we dont loose this!
     if (!isset($sLanguageCode) || $sLanguageCode == "" || !$sLanguageCode) {
         $sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language;
         Yii::import('application.libraries.Limesurvey_lang', true);
         $clang = new Limesurvey_lang($sBaseLanguage);
     } else {
         $sLanguageCode = sanitize_languagecode($sLanguageCode);
         Yii::import('application.libraries.Limesurvey_lang', true);
         $clang = new Limesurvey_lang($sLanguageCode);
         $sBaseLanguage = $sLanguageCode;
     }
     Yii::app()->lang = $clang;
     $aSurveyInfo = getSurveyInfo($iSurveyID, $sBaseLanguage);
     if ($aSurveyInfo == false || !tableExists("{{tokens_{$iSurveyID}}}")) {
         $sMessage = $clang->gT('This survey does not seem to exist.');
     } else {
         $oToken = Token::model($iSurveyID)->findByAttributes(array('token' => $token));
         if (!isset($oToken)) {
             $sMessage = $clang->gT('You are not a participant in this survey.');
         } else {
             if ($oToken->emailstatus == 'OptOut') {
                 $oToken->emailstatus = 'OK';
                 $oToken->save();
                 $sMessage = $clang->gT('You have been successfully added back to this survey.');
             } elseif ($oToken->emailstatus == 'OK') {
                 $sMessage = $clang->gT('You are already a part of this survey.');
             } else {
                 $sMessage = $clang->gT('You have been already removed from this survey.');
             }
         }
     }
     //PRINT COMPLETED PAGE
     if (!$aSurveyInfo['templatedir']) {
         $sTemplate = getTemplatePath(Yii::app()->getConfig("defaulttemplate"));
     } else {
         $sTemplate = getTemplatePath($aSurveyInfo['templatedir']);
     }
     $this->_renderHtml($sMessage, $sTemplate, $clang, $aSurveyInfo);
 }
 /**
  * Defines the customs validation rule lsdefault
  *
  * @param mixed $attribute
  * @param mixed $params
  */
 public function lsdefault($attribute, $params)
 {
     $oSurvey = Survey::model()->findByPk($this->surveyls_survey_id);
     $sEmailFormat = $oSurvey->htmlemail == 'Y' ? 'html' : '';
     $aDefaultTexts = templateDefaultTexts($this->surveyls_language, 'unescaped', $sEmailFormat);
     $aDefaultTextData = array('surveyls_email_invite_subj' => $aDefaultTexts['invitation_subject'], 'surveyls_email_invite' => $aDefaultTexts['invitation'], 'surveyls_email_remind_subj' => $aDefaultTexts['reminder_subject'], 'surveyls_email_remind' => $aDefaultTexts['reminder'], 'surveyls_email_confirm_subj' => $aDefaultTexts['confirmation_subject'], 'surveyls_email_confirm' => $aDefaultTexts['confirmation'], 'surveyls_email_register_subj' => $aDefaultTexts['registration_subject'], 'surveyls_email_register' => $aDefaultTexts['registration'], 'email_admin_notification_subj' => $aDefaultTexts['admin_notification_subject'], 'email_admin_notification' => $aDefaultTexts['admin_notification'], 'email_admin_responses_subj' => $aDefaultTexts['admin_detailed_notification_subject'], 'email_admin_responses' => $aDefaultTexts['admin_detailed_notification']);
     if ($sEmailFormat == "html") {
         $aDefaultTextData['admin_detailed_notification'] = $aDefaultTexts['admin_detailed_notification_css'] . $aDefaultTexts['admin_detailed_notification'];
     }
     if (empty($this->{$attribute})) {
         $this->{$attribute} = $aDefaultTextData[$attribute];
     }
 }
 /**
  * Renders template(s) wrapped in header and footer
  *
  * @param string $sAction Current action, the folder to fetch views from
  * @param string|array $aViewUrls View url(s)
  * @param array $aData Data to be passed on. Optional.
  */
 protected function _renderWrappedTemplate($sAction = 'assessments', $aViewUrls = array(), $aData = array())
 {
     $aData['sidemenu']['state'] = false;
     $iSurveyID = $aData['surveyid'];
     $surveyinfo = Survey::model()->findByPk($iSurveyID)->surveyinfo;
     $aData['surveybar']['closebutton']['url'] = 'admin/survey/sa/view/surveyid/' . $iSurveyID;
     // Close button
     $aData['title_bar']['title'] = $surveyinfo['surveyls_title'] . "(" . gT("ID") . ":" . $iSurveyID . ")";
     $aData['surveybar']['savebutton']['form'] = TRUE;
     $aData['gid'] = null;
     App()->getClientScript()->registerScriptFile(App()->getAssetManager()->publish(ADMIN_SCRIPT_PATH . 'assessments.js'));
     parent::_renderWrappedTemplate($sAction, $aViewUrls, $aData);
 }
 public function actionPublicList($lang = null)
 {
     if (!empty($lang)) {
         App()->setLanguage($lang);
     } else {
         App()->setLanguage(App()->getConfig('defaultlang'));
     }
     $oTemplate = Template::model()->getInstance(Yii::app()->getConfig("defaulttemplate"));
     if ($oTemplate->cssFramework == 'bootstrap') {
         App()->bootstrap->register();
     }
     $this->render('publicSurveyList', array('publicSurveys' => Survey::model()->active()->open()->public()->with('languagesettings')->findAll(), 'futureSurveys' => Survey::model()->active()->registration()->public()->with('languagesettings')->findAll()));
 }
Beispiel #16
0
 /**
  * Loads a survey from the database that has the given ID.  If no matching
  * survey is found then null is returned.  Note that no results are loaded
  * from this function call, only survey structure/definition.
  *
  * In the future it would be nice to load all languages from the db at
  * once and have the infrastructure be able to return responses based
  * on language codes.
  *
  * @param int $id
  * @return SurveyObj
  */
 public function loadSurveyById($id, $lang = null)
 {
     $survey = new SurveyObj();
     $clang = Yii::app()->lang;
     $intId = sanitize_int($id);
     $survey->id = $intId;
     $survey->info = getSurveyInfo($survey->id);
     $availableLanguages = Survey::model()->findByPk($intId)->getAllLanguages();
     if (is_null($lang) || in_array($lang, $availableLanguages) === false) {
         // use base language when requested language is not found or no specific language is requested
         $lang = Survey::model()->findByPk($intId)->language;
     }
     $clang = new limesurvey_lang($lang);
     $survey->fieldMap = createFieldMap($intId, 'full', true, false, $lang);
     // Check to see if timings are present and add to fieldmap if needed
     if ($survey->info['savetimings'] == "Y") {
         $survey->fieldMap = $survey->fieldMap + createTimingsFieldMap($intId, 'full', true, false, $lang);
     }
     if (empty($intId)) {
         //The id given to us is not an integer, croak.
         safeDie("An invalid survey ID was encountered: {$sid}");
     }
     //Load groups
     $sQuery = 'SELECT g.* FROM {{groups}} AS g ' . 'WHERE g.sid = ' . $intId . ' AND g.language = \'' . $lang . '\' ' . 'ORDER BY g.group_order;';
     $recordSet = Yii::app()->db->createCommand($sQuery)->query()->readAll();
     $survey->groups = $recordSet;
     //Load questions
     $sQuery = 'SELECT q.* FROM {{questions}} AS q ' . 'JOIN {{groups}} AS g ON (q.gid = g.gid and q.language = g.language) ' . 'WHERE q.sid = ' . $intId . ' AND q.language = \'' . $lang . '\' ' . 'ORDER BY g.group_order, q.question_order;';
     $survey->questions = Yii::app()->db->createCommand($sQuery)->query()->readAll();
     //Load answers
     $sQuery = 'SELECT DISTINCT a.* FROM {{answers}} AS a ' . 'JOIN {{questions}} AS q ON a.qid = q.qid ' . 'WHERE q.sid = ' . $intId . ' AND a.language = \'' . $lang . '\' ' . 'ORDER BY a.qid, a.sortorder;';
     //$survey->answers = Yii::app()->db->createCommand($sQuery)->queryAll();
     $aAnswers = Yii::app()->db->createCommand($sQuery)->queryAll();
     foreach ($aAnswers as $aAnswer) {
         if (Yii::app()->controller->action->id != 'remotecontrol') {
             $aAnswer['answer'] = stripTagsFull($aAnswer['answer']);
         }
         $survey->answers[$aAnswer['qid']][$aAnswer['scale_id']][$aAnswer['code']] = $aAnswer;
     }
     //Load language settings for requested language
     $sQuery = 'SELECT * FROM {{surveys_languagesettings}} WHERE surveyls_survey_id = ' . $intId . ' AND surveyls_language = \'' . $lang . '\';';
     $recordSet = Yii::app()->db->createCommand($sQuery)->query();
     $survey->languageSettings = $recordSet->read();
     $recordSet->close();
     if (tableExists('tokens_' . $survey->id) && array_key_exists('token', SurveyDynamic::model($survey->id)->attributes) && Permission::model()->hasSurveyPermission($survey->id, 'tokens', 'read')) {
         // Now add the tokenFields
         $survey->tokenFields = getTokenFieldsAndNames($survey->id);
         unset($survey->tokenFields['token']);
     }
     return $survey;
 }
Beispiel #17
0
 /**
  * Function responsible to process any change in email template.
  * @return
  */
 function update($iSurveyId)
 {
     $clang = $this->getController()->lang;
     if (hasSurveyPermission($iSurveyId, 'surveylocale', 'update')) {
         $languagelist = Survey::model()->findByPk($iSurveyId)->additionalLanguages;
         $languagelist[] = Survey::model()->findByPk($iSurveyId)->language;
         array_filter($languagelist);
         foreach ($languagelist as $langname) {
             $attributes = array('surveyls_email_invite_subj' => $_POST['email_invite_subj_' . $langname], 'surveyls_email_invite' => $_POST['email_invite_' . $langname], 'surveyls_email_remind_subj' => $_POST['email_remind_subj_' . $langname], 'surveyls_email_remind' => $_POST['email_remind_' . $langname], 'surveyls_email_register_subj' => $_POST['email_register_subj_' . $langname], 'surveyls_email_register' => $_POST['email_register_' . $langname], 'surveyls_email_confirm_subj' => $_POST['email_confirm_subj_' . $langname], 'surveyls_email_confirm' => $_POST['email_confirm_' . $langname], 'email_admin_notification_subj' => $_POST['email_admin_notification_subj_' . $langname], 'email_admin_notification' => $_POST['email_admin_notification_' . $langname], 'email_admin_responses_subj' => $_POST['email_admin_responses_subj_' . $langname], 'email_admin_responses' => $_POST['email_admin_responses_' . $langname]);
             $usquery = Surveys_languagesettings::model()->updateAll($attributes, 'surveyls_survey_id = :ssid AND surveyls_language = :sl', array(':ssid' => $iSurveyId, ':sl' => $langname));
         }
         Yii::app()->session['flashmessage'] = $clang->gT("Email templates successfully saved.");
     }
     $this->getController()->redirect($this->getController()->createUrl('admin/survey/view/surveyid/' . $iSurveyId));
 }
Beispiel #18
0
 public function run()
 {
     App()->loadHelper('surveytranslator');
     App()->getClientScript()->registerPackage('panel-clickable');
     App()->getClientScript()->registerPackage('panels-animation');
     $aData['issuperadmin'] = false;
     if (Permission::model()->hasGlobalPermission('superadmin', 'read')) {
         $aData['issuperadmin'] = true;
     }
     // We get the last survey visited by user
     $setting_entry = 'last_survey_' . Yii::app()->user->getId();
     $lastsurvey = getGlobalSetting($setting_entry);
     if ($lastsurvey != null) {
         $aData['showLastSurvey'] = true;
         $iSurveyID = $lastsurvey;
         $surveyinfo = Survey::model()->findByPk($iSurveyID)->surveyinfo;
         $aData['surveyTitle'] = $surveyinfo['surveyls_title'] . "(" . gT("ID") . ":" . $iSurveyID . ")";
         $aData['surveyUrl'] = $this->getController()->createUrl("admin/survey/sa/view/surveyid/{$iSurveyID}");
     } else {
         $aData['showLastSurvey'] = false;
     }
     // We get the last question visited by user
     $setting_entry = 'last_question_' . Yii::app()->user->getId();
     $lastquestion = getGlobalSetting($setting_entry);
     // the question group of this question
     $setting_entry = 'last_question_gid_' . Yii::app()->user->getId();
     $lastquestiongroup = getGlobalSetting($setting_entry);
     // the sid of this question : last_question_sid_1
     $setting_entry = 'last_question_sid_' . Yii::app()->user->getId();
     $lastquestionsid = getGlobalSetting($setting_entry);
     if ($lastquestion != null && $lastquestiongroup != null) {
         $baselang = Survey::model()->findByPk($iSurveyID)->language;
         $aData['showLastQuestion'] = true;
         $qid = $lastquestion;
         $gid = $lastquestiongroup;
         $sid = $lastquestionsid;
         $qrrow = Question::model()->findByAttributes(array('qid' => $qid, 'gid' => $gid, 'sid' => $sid, 'language' => $baselang));
         $aData['last_question_name'] = $qrrow['title'];
         if ($qrrow['question']) {
             $aData['last_question_name'] .= ' : ' . $qrrow['question'];
         }
         $aData['last_question_link'] = $this->getController()->createUrl("admin/questions/sa/view/surveyid/{$iSurveyID}/gid/{$gid}/qid/{$qid}");
     } else {
         $aData['showLastQuestion'] = false;
     }
     $aData['countSurveyList'] = count(getSurveyList(true));
     $this->_renderWrappedTemplate('super', 'welcome', $aData);
 }
 function actiontokens($surveyid, $token, $langcode = '')
 {
     Yii::app()->loadHelper('database');
     Yii::app()->loadHelper('sanitize');
     $sLanguageCode = $langcode;
     $iSurveyID = $surveyid;
     $sToken = $token;
     $sToken = sanitize_token($sToken);
     if (!$iSurveyID) {
         $this->redirect(array('/'));
     }
     $iSurveyID = (int) $iSurveyID;
     //Check that there is a SID
     // Get passed language from form, so that we dont loose this!
     if (!isset($sLanguageCode) || $sLanguageCode == "" || !$sLanguageCode) {
         $sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language;
     } else {
         $sBaseLanguage = sanitize_languagecode($sLanguageCode);
     }
     Yii::app()->setLanguage($sBaseLanguage);
     $aSurveyInfo = getSurveyInfo($iSurveyID, $sBaseLanguage);
     if ($aSurveyInfo == false || !tableExists("{{tokens_{$iSurveyID}}}")) {
         throw new CHttpException(404, "This survey does not seem to exist. It may have been deleted or the link you were given is outdated or incorrect.");
     } else {
         LimeExpressionManager::singleton()->loadTokenInformation($iSurveyID, $token, false);
         $oToken = Token::model($iSurveyID)->findByAttributes(array('token' => $token));
         if (!isset($oToken)) {
             $sMessage = gT('You are not a participant in this survey.');
         } else {
             if ($oToken->emailstatus == 'OptOut') {
                 $oToken->emailstatus = 'OK';
                 $oToken->save();
                 $sMessage = gT('You have been successfully added back to this survey.');
             } elseif ($oToken->emailstatus == 'OK') {
                 $sMessage = gT('You are already a part of this survey.');
             } else {
                 $sMessage = gT('You have been already removed from this survey.');
             }
         }
     }
     //PRINT COMPLETED PAGE
     if (!$aSurveyInfo['templatedir']) {
         $sTemplate = getTemplatePath(Yii::app()->getConfig("defaulttemplate"));
     } else {
         $sTemplate = getTemplatePath($aSurveyInfo['templatedir']);
     }
     $this->_renderHtml($sMessage, $sTemplate, $aSurveyInfo);
 }
 public function actionPublicList($lang = null)
 {
     if (!empty($lang)) {
         App()->setLanguage($lang);
     } else {
         App()->setLanguage(App()->getConfig('defaultlang'));
     }
     $oTemplate = Template::model()->getInstance(Yii::app()->getConfig("defaulttemplate"));
     if ($oTemplate->cssFramework == 'bootstrap') {
         // We now use the bootstrap package isntead of the Yiistrap TbApi::register() method
         // Then instead of using the composer dependency system for templates
         // We can use the package dependency system
         Yii::app()->getClientScript()->registerMetaTag('width=device-width, initial-scale=1.0', 'viewport');
         App()->bootstrap->registerAllScripts();
     }
     $this->render('publicSurveyList', array('publicSurveys' => Survey::model()->active()->open()->public()->with('languagesettings')->findAll(), 'futureSurveys' => Survey::model()->active()->registration()->public()->with('languagesettings')->findAll()));
 }
Beispiel #21
0
 /**
  * Function responsible to process any change in email template.
  * @return
  */
 function update($iSurveyId)
 {
     $uploadUrl = Yii::app()->getBaseUrl(true) . substr(Yii::app()->getConfig('uploadurl'), strlen(Yii::app()->getConfig('publicurl')) - 1);
     // We need the real path since we check that the resolved file name starts with this path.
     $uploadDir = realpath(Yii::app()->getConfig('uploaddir'));
     $sSaveMethod = Yii::app()->request->getPost('save', '');
     $clang = $this->getController()->lang;
     if (Permission::model()->hasSurveyPermission($iSurveyId, 'surveylocale', 'update') && $sSaveMethod != '') {
         $languagelist = Survey::model()->findByPk($iSurveyId)->additionalLanguages;
         $languagelist[] = Survey::model()->findByPk($iSurveyId)->language;
         array_filter($languagelist);
         foreach ($languagelist as $langname) {
             if (isset($_POST['attachments'][$langname])) {
                 foreach ($_POST['attachments'][$langname] as $template => &$attachments) {
                     foreach ($attachments as $index => &$attachment) {
                         // We again take the real path.
                         $localName = realpath(urldecode(str_replace($uploadUrl, $uploadDir, $attachment['url'])));
                         if ($localName !== false) {
                             if (strpos($localName, $uploadDir) === 0) {
                                 $attachment['url'] = $localName;
                                 $attachment['size'] = filesize($localName);
                             } else {
                                 unset($attachments[$index]);
                             }
                         } else {
                             unset($attachments[$index]);
                         }
                     }
                     unset($attachments);
                 }
             } else {
                 $_POST['attachments'][$langname] = array();
             }
             $attributes = array('surveyls_email_invite_subj' => $_POST['email_invitation_subj_' . $langname], 'surveyls_email_invite' => $_POST['email_invitation_' . $langname], 'surveyls_email_remind_subj' => $_POST['email_reminder_subj_' . $langname], 'surveyls_email_remind' => $_POST['email_reminder_' . $langname], 'surveyls_email_register_subj' => $_POST['email_registration_subj_' . $langname], 'surveyls_email_register' => $_POST['email_registration_' . $langname], 'surveyls_email_confirm_subj' => $_POST['email_confirmation_subj_' . $langname], 'surveyls_email_confirm' => $_POST['email_confirmation_' . $langname], 'email_admin_notification_subj' => $_POST['email_admin_notification_subj_' . $langname], 'email_admin_notification' => $_POST['email_admin_notification_' . $langname], 'email_admin_responses_subj' => $_POST['email_admin_detailed_notification_subj_' . $langname], 'email_admin_responses' => $_POST['email_admin_detailed_notification_' . $langname], 'attachments' => serialize($_POST['attachments'][$langname]));
             $usquery = SurveyLanguageSetting::model()->updateAll($attributes, 'surveyls_survey_id = :ssid AND surveyls_language = :sl', array(':ssid' => $iSurveyId, ':sl' => $langname));
         }
         Yii::app()->session['flashmessage'] = $clang->gT("Email templates successfully saved.");
         $this->getController()->redirect(array('admin/emailtemplates/sa/index/surveyid/' . $iSurveyId));
     }
     if ($sSaveMethod == 'saveclose') {
         $this->getController()->redirect(array('admin/survey/sa/view/surveyid/' . $iSurveyId));
     } else {
         self::index($iSurveyId);
     }
 }
 /**
  * This method construct a template object, having all the needed configuration datas.
  * It checks if the required template is a core one or a user one.
  * If it's a user template, it will check if it's an old 2.0x template to provide default configuration values corresponding to the old template system
  * If it's not an old template, it will check if it has a configuration file to load its datas.
  * If it's not the case (template probably doesn't exist), it will load the default template configuration
  * TODO : more tests should be done, with a call to private function _is_valid_template(), testing not only if it has a config.xml, but also id this file is correct, if it has the needed pstpl files, if the files refered in css exist, etc.
  *
  * @param string $sTemplateName     the name of the template to load. The string come from the template selector in survey settings
  * @param integer $iSurveyId        the id of the survey. If
  */
 public function setTemplateConfiguration($sTemplateName = '', $iSurveyId = '')
 {
     if ($sTemplateName == '' && $iSurveyId == '') {
         throw new TemplateException("Template needs either template name or survey id");
     }
     $this->sTemplateName = $sTemplateName;
     $this->iSurveyId = $iSurveyId;
     if ($sTemplateName == '') {
         $this->oSurvey = Survey::model()->findByPk($iSurveyId);
         $this->sTemplateName = $this->oSurvey->template;
     }
     $this->isStandard = $this->setIsStandard();
     // If the template is standard, its root is based on standardtemplaterootdir
     if ($this->isStandard) {
         $this->path = Yii::app()->getConfig("standardtemplaterootdir") . DIRECTORY_SEPARATOR . $this->sTemplateName;
     } else {
         $this->path = Yii::app()->getConfig("usertemplaterootdir") . DIRECTORY_SEPARATOR . $this->sTemplateName;
     }
     // If the template don't have a config file (maybe it has been deleted, or whatever),
     // then, we load the default template
     $this->hasConfigFile = is_file($this->path . DIRECTORY_SEPARATOR . 'config.xml');
     $this->isOldTemplate = !$this->hasConfigFile && is_file($this->path . DIRECTORY_SEPARATOR . 'startpage.pstpl');
     if (!$this->hasConfigFile) {
         // If it's an imported template from 2.06, we return default values
         if ($this->isOldTemplate) {
             $this->xmlFile = Yii::app()->getConfig("standardtemplaterootdir") . DIRECTORY_SEPARATOR . 'minimal-config.xml';
         } else {
             $this->path = Yii::app()->getConfig("standardtemplaterootdir") . DIRECTORY_SEPARATOR . $this->sTemplateName;
             $this->xmlFile = $this->path . DIRECTORY_SEPARATOR . 'config.xml';
         }
     } else {
         $this->xmlFile = $this->path . DIRECTORY_SEPARATOR . 'config.xml';
     }
     //var_dump(realpath ($this->xmlFile)); die();
     $this->config = simplexml_load_file(realpath($this->xmlFile));
     // The template configuration.
     $this->viewPath = $this->path . DIRECTORY_SEPARATOR . $this->config->engine->pstpldirectory . DIRECTORY_SEPARATOR;
     $this->siteLogo = isset($this->config->files->logo) ? $this->config->files->logo->filename : '';
     // condition for user's template prior to 160219
     $this->filesPath = isset($this->config->engine->filesdirectory) ? $this->path . DIRECTORY_SEPARATOR . $this->config->engine->filesdirectory . DIRECTORY_SEPARATOR : $this->path . '/files/';
     $this->cssFramework = $this->config->engine->cssframework;
     $this->packages = (array) $this->config->engine->packages->package;
     $this->otherFiles = $this->setOtherFiles();
     return $this;
 }
Beispiel #23
0
 function index()
 {
     $aData = array();
     $needpermission = false;
     $aData['surveyid'] = $surveyid = $iSurveyID = sanitize_int(Yii::app()->request->getQuery('sid'));
     $aData['sa'] = $sa = sanitize_paranoid_string(Yii::app()->request->getQuery('sa', 'index'));
     $aData['fullpagebar']['closebutton']['url'] = 'admin/';
     if (($aData['sa'] == 'survey_logic_file' || $aData['sa'] == 'navigation_test') && $surveyid) {
         $needpermission = true;
     }
     if ($needpermission && !Permission::model()->hasSurveyPermission($surveyid, 'surveycontent', 'read')) {
         $message['title'] = gT('Access denied!');
         $message['message'] = gT('You do not have sufficient rights to access this page.');
         $message['class'] = "error";
         $this->_renderWrappedTemplate('survey', array("message" => $message), $aData);
     } else {
         App()->getClientScript()->registerPackage('jqueryui');
         App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts') . "survey_runtime.js");
         App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts') . "expressions/em_javascript.js");
         //App()->getClientScript()->registerCssFile(Yii::app()->getConfig('adminstyleurl') . "adminstyle.css" );
         $this->_printOnLoad(Yii::app()->request->getQuery('sa', 'index'));
         $aData['pagetitle'] = "ExpressionManager:  {$aData['sa']}";
         if (isset($iSurveyID)) {
             $aData['sidebar']['state'] = "close";
             $surveyinfo = Survey::model()->findByPk($iSurveyID)->surveyinfo;
             $aData['title_bar']['title'] = $surveyinfo['surveyls_title'] . "(" . gT("ID") . ":" . $iSurveyID . ")";
             if (Yii::app()->request->getQuery('gid') != '') {
                 $aData['questiongroupbar']['closebutton']['url'] = 'admin/questiongroups/sa/view/surveyid/' . $aData['surveyid'] . '/gid/' . sanitize_int(Yii::app()->request->getQuery('gid'));
             } else {
                 $aData['surveybar']['closebutton']['url'] = 'admin/survey/sa/view/surveyid/' . $aData['surveyid'];
             }
             if (Yii::app()->request->getQuery('qid') != '') {
                 $aData['questiongroupbar']['closebutton']['url'] = 'admin/questions/sa/view/surveyid/' . $aData['surveyid'] . '/gid/' . sanitize_int(Yii::app()->request->getQuery('gid')) . '/qid/' . sanitize_int(Yii::app()->request->getQuery('qid'));
                 $aData['gid'] = sanitize_int(Yii::app()->request->getQuery('gid'));
             }
         }
         //header("Content-type: text/html; charset=UTF-8"); // needed for correct UTF-8 encoding
         if (isset($_GET['sa'])) {
             $this->test($aData['sa'], $aData);
         } else {
             $this->_renderWrappedTemplate('expressions', 'test_view', $aData);
         }
     }
 }
Beispiel #24
0
 private function _getData($params)
 {
     if (is_numeric($params)) {
         $iSurveyId = $params;
     } elseif (is_array($params)) {
         extract($params);
     }
     $aData = array();
     // Set the variables in an array
     $aData['surveyid'] = $aData['iSurveyId'] = (int) $iSurveyId;
     if (!empty($iId)) {
         $aData['iId'] = (int) $iId;
     }
     $aData['clang'] = $clang = $this->getController()->lang;
     $aData['imageurl'] = Yii::app()->getConfig('imageurl');
     $aData['action'] = Yii::app()->request->getParam('action');
     $aData['all'] = Yii::app()->request->getParam('all');
     $thissurvey = getSurveyInfo($iSurveyId);
     if (!$thissurvey) {
         Yii::app()->session['flashmessage'] = $clang->gT("Invalid survey ID");
         $this->getController()->redirect(array("admin/index"));
     } elseif ($thissurvey['active'] != 'Y') {
         Yii::app()->session['flashmessage'] = $clang->gT("This survey has not been activated. There are no results to browse.");
         $this->getController()->redirect(array("/admin/survey/sa/view/surveyid/{$iSurveyId}"));
     }
     //OK. IF WE GOT THIS FAR, THEN THE SURVEY EXISTS AND IT IS ACTIVE, SO LETS GET TO WORK.
     $aData['surveyinfo'] = $thissurvey;
     if (Yii::app()->request->getParam('browselang')) {
         $aData['language'] = Yii::app()->request->getParam('browselang');
         $aData['languagelist'] = $languagelist = Survey::model()->findByPk($iSurveyId)->additionalLanguages;
         $aData['languagelist'][] = Survey::model()->findByPk($iSurveyId)->language;
         if (!in_array($aData['language'], $languagelist)) {
             $aData['language'] = $thissurvey['language'];
         }
     } else {
         $aData['language'] = $thissurvey['language'];
     }
     $aData['qulanguage'] = Survey::model()->findByPk($iSurveyId)->language;
     $aData['surveyoptions'] = '';
     $aData['browseoutput'] = '';
     return $aData;
 }
 /**
  * Default action register
  * Process register form data and take appropriate action
  * @param $sid Survey Id to register
  * @param $aRegisterErrors array of errors when try to register
  * @return
  */
 public function actionIndex($sid = null)
 {
     if (!is_null($sid)) {
         $iSurveyId = $sid;
     } else {
         $iSurveyId = Yii::app()->request->getPost('sid');
     }
     $oSurvey = Survey::model()->find("sid=:sid", array(':sid' => $iSurveyId));
     $sLanguage = Yii::app()->request->getParam('lang');
     if (!$sLanguage) {
         $sLanguage = Survey::model()->findByPk($iSurveyId)->language;
     }
     if (!$oSurvey) {
         throw new CHttpException(404, "The survey in which you are trying to participate does not seem to exist. It may have been deleted or the link you were given is outdated or incorrect.");
     } elseif ($oSurvey->allowregister != 'Y' || !tableExists("{{tokens_{$iSurveyId}}}")) {
         throw new CHttpException(404, "The survey in which you are trying to register don't accept registration. It may have been updated or the link you were given is outdated or incorrect.");
     } elseif (!is_null($oSurvey->expires) && $oSurvey->expires < dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig('timeadjust'))) {
         $this->redirect(array('survey/index', 'sid' => $iSurveyId, 'lang' => $sLanguage));
     }
     Yii::app()->setLanguage($sLanguage);
     $event = new PluginEvent('beforeRegister');
     $event->set('surveyid', $iSurveyId);
     $event->set('lang', $sLanguage);
     App()->getPluginManager()->dispatchEvent($event);
     $this->sMessage = $event->get('sMessage');
     $this->aRegisterErrors = $event->get('aRegisterErrors');
     $iTokenId = $event->get('iTokenId');
     // Test if we come from register form (and submit)
     if (Yii::app()->request->getPost('register') && !$iTokenId) {
         self::getRegisterErrors($iSurveyId);
         if (empty($this->aRegisterErrors)) {
             $iTokenId = self::getTokenId($iSurveyId);
         }
     }
     if (empty($this->aRegisterErrors) && $iTokenId && $this->sMessage === null) {
         self::sendRegistrationEmail($iSurveyId, $iTokenId);
     }
     // Display the page
     self::display($iSurveyId);
 }
 private function _checkSettings()
 {
     $surveycount = Survey::model()->count();
     $activesurveycount = Survey::model()->active()->count();
     $usercount = User::model()->count();
     if ($activesurveycount == false) {
         $activesurveycount = 0;
     }
     if ($surveycount == false) {
         $surveycount = 0;
     }
     $tablelist = Yii::app()->db->schema->getTableNames();
     foreach ($tablelist as $table) {
         if (strpos($table, Yii::app()->db->tablePrefix . "old_tokens_") !== false) {
             $oldtokenlist[] = $table;
         } elseif (strpos($table, Yii::app()->db->tablePrefix . "tokens_") !== false) {
             $tokenlist[] = $table;
         } elseif (strpos($table, Yii::app()->db->tablePrefix . "old_survey_") !== false) {
             $oldresultslist[] = $table;
         }
     }
     if (isset($oldresultslist) && is_array($oldresultslist)) {
         $deactivatedsurveys = count($oldresultslist);
     } else {
         $deactivatedsurveys = 0;
     }
     if (isset($oldtokenlist) && is_array($oldtokenlist)) {
         $deactivatedtokens = count($oldtokenlist);
     } else {
         $deactivatedtokens = 0;
     }
     if (isset($tokenlist) && is_array($tokenlist)) {
         $activetokens = count($tokenlist);
     } else {
         $activetokens = 0;
     }
     return array('usercount' => $usercount, 'surveycount' => $surveycount, 'activesurveycount' => $activesurveycount, 'deactivatedsurveys' => $deactivatedsurveys, 'activetokens' => $activetokens, 'deactivatedtokens' => $deactivatedtokens);
 }
/**
* Function to activate a survey
* @param int $iSurveyID The Survey ID
* @param bool $simulate
* @return string
*/
function activateSurvey($iSurveyID, $simulate = false)
{
    $createsurvey = '';
    $activateoutput = '';
    $createsurveytimings = '';
    $fieldstiming = array();
    $createsurveydirectory = false;
    //Check for any additional fields for this survey and create necessary fields (token and datestamp)
    $prow = Survey::model()->findByAttributes(array('sid' => $iSurveyID));
    //Get list of questions for the base language
    $fieldmap = createFieldMap($iSurveyID, 'full', true, false, getBaseLanguageFromSurveyID($iSurveyID));
    $createsurvey = array();
    foreach ($fieldmap as $j => $arow) {
        switch ($arow['type']) {
            case 'startlanguage':
                $createsurvey[$arow['fieldname']] = "string(20) NOT NULL";
                break;
            case 'id':
                $createsurvey[$arow['fieldname']] = "pk";
                break;
            case "startdate":
            case "datestamp":
                $createsurvey[$arow['fieldname']] = "datetime NOT NULL";
                break;
            case "submitdate":
                $createsurvey[$arow['fieldname']] = "datetime";
                break;
            case "lastpage":
                $createsurvey[$arow['fieldname']] = "integer";
                break;
            case "N":
                //Numerical
            //Numerical
            case "K":
                //Multiple Numerical
                $createsurvey[$arow['fieldname']] = "decimal (30,10)";
                break;
            case "S":
                //SHORT TEXT
                $createsurvey[$arow['fieldname']] = "text";
                break;
            case "L":
                //LIST (RADIO)
            //LIST (RADIO)
            case "!":
                //LIST (DROPDOWN)
            //LIST (DROPDOWN)
            case "M":
                //Multiple choice
            //Multiple choice
            case "P":
                //Multiple choice with comment
            //Multiple choice with comment
            case "O":
                //DROPDOWN LIST WITH COMMENT
                if ($arow['aid'] != 'other' && strpos($arow['aid'], 'comment') === false && strpos($arow['aid'], 'othercomment') === false) {
                    $createsurvey[$arow['fieldname']] = "string(5)";
                } else {
                    $createsurvey[$arow['fieldname']] = "text";
                }
                break;
            case "U":
                //Huge text
            //Huge text
            case "Q":
                //Multiple short text
            //Multiple short text
            case "T":
                //LONG TEXT
            //LONG TEXT
            case ";":
                //Multi Flexi
            //Multi Flexi
            case ":":
                //Multi Flexi
                $createsurvey[$arow['fieldname']] = "text";
                break;
            case "D":
                //DATE
                $createsurvey[$arow['fieldname']] = "datetime";
                break;
            case "5":
                //5 Point Choice
            //5 Point Choice
            case "G":
                //Gender
            //Gender
            case "Y":
                //YesNo
            //YesNo
            case "X":
                //Boilerplate
                $createsurvey[$arow['fieldname']] = "string(1)";
                break;
            case "I":
                //Language switch
                $createsurvey[$arow['fieldname']] = "string(20)";
                break;
            case "|":
                $createsurveydirectory = true;
                if (strpos($arow['fieldname'], "_")) {
                    $createsurvey[$arow['fieldname']] = "integer";
                } else {
                    $createsurvey[$arow['fieldname']] = "text";
                }
                break;
            case "ipaddress":
                if ($prow->ipaddr == "Y") {
                    $createsurvey[$arow['fieldname']] = "string";
                }
                break;
            case "url":
                if ($prow->refurl == "Y") {
                    $createsurvey[$arow['fieldname']] = "string";
                }
                break;
            case "token":
                // Specify case sensitive collations for the token
                $sCollation = '';
                if (Yii::app()->db->driverName == 'mysqli' | Yii::app()->db->driverName == 'mysqli') {
                    $sCollation = " COLLATE 'utf8_bin'";
                }
                if (Yii::app()->db->driverName == 'sqlsrv' | Yii::app()->db->driverName == 'dblib' | Yii::app()->db->driverName == 'mssql') {
                    $sCollation = " COLLATE SQL_Latin1_General_CP1_CS_AS";
                }
                $createsurvey[$arow['fieldname']] = 'string(35)' . $sCollation;
                break;
            case '*':
                // Equation
                $createsurvey[$arow['fieldname']] = "text";
                break;
            default:
                $createsurvey[$arow['fieldname']] = "string(5)";
        }
        if ($prow->anonymized == 'N' && !array_key_exists('token', $createsurvey)) {
            $createsurvey['token'] = "string(36)";
        }
        if ($simulate) {
            $tempTrim = trim($createsurvey);
            $brackets = strpos($tempTrim, "(");
            if ($brackets === false) {
                $type = substr($tempTrim, 0, 2);
            } else {
                $type = substr($tempTrim, 0, 2);
            }
            $arrSim[] = array($type);
        }
    }
    if ($simulate) {
        return array('dbengine' => $CI->db->databasetabletype, 'dbtype' => Yii::app()->db->driverName, 'fields' => $arrSim);
    }
    // If last question is of type MCABCEFHP^QKJR let's get rid of the ending coma in createsurvey
    //$createsurvey = rtrim($createsurvey, ",\n")."\n"; // Does nothing if not ending with a comma
    $tabname = "{{survey_{$iSurveyID}}}";
    Yii::app()->loadHelper("database");
    try {
        $execresult = Yii::app()->db->createCommand()->createTable($tabname, $createsurvey);
        Yii::app()->db->schema->getTable($tabname, true);
        // Refresh schema cache just in case the table existed in the past
    } catch (CDbException $e) {
        return array('error' => 'surveytablecreation');
    }
    try {
        if (isset($createsurvey['token'])) {
            Yii::app()->db->createCommand()->createIndex("idx_survey_token_{$iSurveyID}_" . rand(1, 50000), $tabname, 'token');
        }
    } catch (CDbException $e) {
    }
    $anquery = "SELECT autonumber_start FROM {{surveys}} WHERE sid={$iSurveyID}";
    $iAutoNumberStart = Yii::app()->db->createCommand($anquery)->queryScalar();
    //if there is an autonumber_start field, start auto numbering here
    if ($iAutoNumberStart !== false && $iAutoNumberStart > 0) {
        if (Yii::app()->db->driverName == 'mssql' || Yii::app()->db->driverName == 'sqlsrv' || Yii::app()->db->driverName == 'dblib') {
            mssql_drop_primary_index('survey_' . $iSurveyID);
            mssql_drop_constraint('id', 'survey_' . $iSurveyID);
            $sQuery = "ALTER TABLE {{survey_{$iSurveyID}}} drop column id ";
            Yii::app()->db->createCommand($sQuery)->execute();
            $sQuery = "ALTER TABLE {{survey_{$iSurveyID}}} ADD [id] int identity({$iAutoNumberStart},1)";
            Yii::app()->db->createCommand($sQuery)->execute();
            // Add back the primaryKey
            Yii::app()->db->createCommand()->addPrimaryKey('PRIMARY', '{{survey_' . $iSurveyID . '}}', 'id');
        } elseif (Yii::app()->db->driverName == 'pgsql') {
            $sQuery = "SELECT setval(pg_get_serial_sequence('{{survey_{$iSurveyID}}}', 'id'),{$iAutoNumberStart},false);";
            $result = @Yii::app()->db->createCommand($sQuery)->execute();
        } else {
            $sQuery = "ALTER TABLE {{survey_{$iSurveyID}}} AUTO_INCREMENT = {$iAutoNumberStart}";
            $result = @Yii::app()->db->createCommand($sQuery)->execute();
        }
    }
    if ($prow->savetimings == "Y") {
        $timingsfieldmap = createTimingsFieldMap($iSurveyID, "full", false, false, getBaseLanguageFromSurveyID($iSurveyID));
        $column = array();
        $column['id'] = $createsurvey['id'];
        foreach ($timingsfieldmap as $field => $fielddata) {
            $column[$field] = 'FLOAT';
        }
        $tabname = "{{survey_{$iSurveyID}_timings}}";
        try {
            $execresult = Yii::app()->db->createCommand()->createTable($tabname, $column);
            Yii::app()->db->schema->getTable($tabname, true);
            // Refresh schema cache just in case the table existed in the past
        } catch (CDbException $e) {
            return array('error' => 'timingstablecreation');
        }
    }
    $aResult = array('status' => 'OK');
    // create the survey directory where the uploaded files can be saved
    if ($createsurveydirectory) {
        if (!file_exists(Yii::app()->getConfig('uploaddir') . "/surveys/" . $iSurveyID . "/files")) {
            if (!mkdir(Yii::app()->getConfig('uploaddir') . "/surveys/" . $iSurveyID . "/files", 0777, true)) {
                $aResult['warning'] = 'nouploadsurveydir';
            } else {
                file_put_contents(Yii::app()->getConfig('uploaddir') . "/surveys/" . $iSurveyID . "/files/index.html", '<html><head></head><body></body></html>');
            }
        }
    }
    $acquery = "UPDATE {{surveys}} SET active='Y' WHERE sid=" . $iSurveyID;
    $acresult = Yii::app()->db->createCommand($acquery)->query();
    return $aResult;
}
Beispiel #28
0
 /**
  * dataentry::view()
  * view a dataentry
  * @param mixed $surveyid
  * @param mixed $lang
  * @return
  */
 public function view($surveyid, $lang = NULL)
 {
     $surveyid = sanitize_int($surveyid);
     $lang = isset($_GET['lang']) ? $_GET['lang'] : NULL;
     if (isset($lang)) {
         $lang = sanitize_languagecode($lang);
     }
     $aViewUrls = array();
     if (hasSurveyPermission($surveyid, 'responses', 'read')) {
         $clang = Yii::app()->lang;
         $sDataEntryLanguage = Survey::model()->findByPk($surveyid)->language;
         $surveyinfo = getSurveyInfo($surveyid);
         $slangs = Survey::model()->findByPk($surveyid)->additionalLanguages;
         $baselang = Survey::model()->findByPk($surveyid)->language;
         array_unshift($slangs, $baselang);
         if (is_null($lang) || !in_array($lang, $slangs)) {
             $sDataEntryLanguage = $baselang;
             $blang = $clang;
         } else {
             Yii::app()->loadLibrary('Limesurvey_lang', array($lang));
             $blang = new Limesurvey_lang($lang);
             $sDataEntryLanguage = $lang;
         }
         $langlistbox = languageDropdown($surveyid, $sDataEntryLanguage);
         $thissurvey = getSurveyInfo($surveyid);
         //This is the default, presenting a blank dataentry form
         LimeExpressionManager::StartSurvey($surveyid, 'survey', NULL, false, LEM_PRETTY_PRINT_ALL_SYNTAX);
         $moveResult = LimeExpressionManager::NavigateForwards();
         $aData['thissurvey'] = $thissurvey;
         $aData['langlistbox'] = $langlistbox;
         $aData['surveyid'] = $surveyid;
         $aData['blang'] = $blang;
         $aData['site_url'] = Yii::app()->homeUrl;
         LimeExpressionManager::StartProcessingPage(true, Yii::app()->baseUrl);
         // means that all variables are on the same page
         $aViewUrls[] = 'caption_view';
         Yii::app()->loadHelper('database');
         // SURVEY NAME AND DESCRIPTION TO GO HERE
         $degquery = "SELECT * FROM {{groups}} WHERE sid={$surveyid} AND language='{$sDataEntryLanguage}' ORDER BY {{groups}}.group_order";
         $degresult = dbExecuteAssoc($degquery);
         // GROUP NAME
         $aDataentryoutput = '';
         foreach ($degresult->readAll() as $degrow) {
             LimeExpressionManager::StartProcessingGroup($degrow['gid'], $thissurvey['anonymized'] != "N", $surveyid);
             $deqquery = "SELECT * FROM {{questions}} WHERE sid={$surveyid} AND parent_qid=0 AND gid={$degrow['gid']} AND language='{$sDataEntryLanguage}'";
             $deqrows = (array) dbExecuteAssoc($deqquery)->readAll();
             $aDataentryoutput .= "\t<tr>\n" . "<td colspan='3' align='center'><strong>" . flattenText($degrow['group_name'], true) . "</strong></td>\n" . "\t</tr>\n";
             $gid = $degrow['gid'];
             $aDataentryoutput .= "\t<tr class='data-entry-separator'><td colspan='3'></td></tr>\n";
             // Perform a case insensitive natural sort on group name then question title of a multidimensional array
             usort($deqrows, 'groupOrderThenQuestionOrder');
             $bgc = 'odd';
             foreach ($deqrows as $deqrow) {
                 $qidattributes = getQuestionAttributeValues($deqrow['qid'], $deqrow['type']);
                 $cdata['qidattributes'] = $qidattributes;
                 $hidden = isset($qidattributes['hidden']) ? $qidattributes['hidden'] : 0;
                 // TODO - can questions be hidden?  Are JavaScript variables names used?  Consistently with everywhere else?
                 //                    LimeExpressionManager::ProcessRelevance($qidattributes['relevance'],$deqrow['qid'],NULL,$deqrow['type'],$hidden);
                 // TMSW Conditions->Relevance:  Show relevance equation instead of conditions here - better yet, have data entry use survey-at-a-time but with different view
                 $qinfo = LimeExpressionManager::GetQuestionStatus($deqrow['qid']);
                 $relevance = trim($qinfo['info']['relevance']);
                 $explanation = trim($qinfo['relEqn']);
                 $validation = trim($qinfo['prettyValidTip']);
                 $qidattributes = getQuestionAttributeValues($deqrow['qid']);
                 $array_filter_help = flattenText($this->_array_filter_help($qidattributes, $sDataEntryLanguage, $surveyid));
                 if ($relevance != '' && $relevance != '1' || $validation != '' || $array_filter_help != '') {
                     $showme = '';
                     if ($bgc == "even") {
                         $bgc = "odd";
                     } else {
                         $bgc = "even";
                     }
                     //Do no alternate on explanation row
                     if ($relevance != '' && $relevance != '1') {
                         $showme = "[" . $blang->gT("Only answer this if the following conditions are met:") . "]<br />{$explanation}\n";
                     }
                     if ($showme != '' && $validation != '') {
                         $showme .= '<br/>';
                     }
                     if ($validation != '') {
                         $showme .= "[" . $blang->gT("The answer(s) must meet these validation criteria:") . "]<br />{$validation}\n";
                     }
                     if ($showme != '' && $array_filter_help != '') {
                         $showme .= '<br/>';
                     }
                     if ($array_filter_help != '') {
                         $showme .= "[" . $blang->gT("The answer(s) must meet these array_filter criteria:") . "]<br />{$array_filter_help}\n";
                     }
                     $cdata['explanation'] = "<tr class ='data-entry-explanation'><td class='data-entry-small-text' colspan='3' align='left'>{$showme}</td></tr>\n";
                 }
                 //END OF GETTING CONDITIONS
                 //Alternate bgcolor for different groups
                 if (!isset($bgc)) {
                     $bgc = "even";
                 }
                 if ($bgc == "even") {
                     $bgc = "odd";
                 } else {
                     $bgc = "even";
                 }
                 $qid = $deqrow['qid'];
                 $fieldname = "{$surveyid}" . "X" . "{$gid}" . "X" . "{$qid}";
                 $cdata['bgc'] = $bgc;
                 $cdata['fieldname'] = $fieldname;
                 $cdata['deqrow'] = $deqrow;
                 $cdata['clang'] = $clang;
                 //DIFFERENT TYPES OF DATA FIELD HERE
                 $cdata['blang'] = $blang;
                 $cdata['thissurvey'] = $thissurvey;
                 if ($deqrow['help']) {
                     $hh = addcslashes($deqrow['help'], "..'\"");
                     //Escape ASCII decimal 0-32 plus single and double quotes to make JavaScript happy.
                     $hh = htmlspecialchars($hh, ENT_QUOTES);
                     //Change & " ' < > to HTML entities to make HTML happy.
                     $cdata['hh'] = $hh;
                     //$aDataentryoutput .= "\t<img src='$imageurl/help.gif' alt='".$blang->gT("Help about this question")."' align='right' onclick=\"javascript:alert('Question {$deqrow['title']} Help: $hh')\" />\n";
                 }
                 switch ($deqrow['type']) {
                     case "Q":
                         //MULTIPLE SHORT TEXT
                     //MULTIPLE SHORT TEXT
                     case "K":
                         $deaquery = "SELECT question,title FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $dearesult = dbExecuteAssoc($deaquery);
                         $cdata['dearesult'] = $dearesult->readAll();
                         break;
                     case "1":
                         // multi scale^
                         $deaquery = "SELECT * FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$baselang}' ORDER BY question_order";
                         $dearesult = dbExecuteAssoc($deaquery);
                         $cdata['dearesult'] = $dearesult->readAll();
                         $oquery = "SELECT other FROM {{questions}} WHERE qid={$deqrow['qid']} AND language='{$baselang}'";
                         $oresult = dbExecuteAssoc($oquery) or safeDie("Couldn't get other for list question<br />" . $oquery);
                         foreach ($oresult->readAll() as $orow) {
                             $cdata['fother'] = $orow['other'];
                         }
                         break;
                     case "L":
                         //LIST drop-down/radio-button list
                     //LIST drop-down/radio-button list
                     case "!":
                         //                            $qidattributes=getQuestionAttributeValues($deqrow['qid']);
                         if ($deqrow['type'] == '!' && trim($qidattributes['category_separator']) != '') {
                             $optCategorySeparator = $qidattributes['category_separator'];
                         } else {
                             unset($optCategorySeparator);
                         }
                         $defexists = "";
                         $deaquery = "SELECT * FROM {{answers}} WHERE qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY sortorder, answer";
                         $dearesult = dbExecuteAssoc($deaquery);
                         //$aDataentryoutput .= "\t<select name='$fieldname'>\n";
                         $aDatatemp = '';
                         if (!isset($optCategorySeparator)) {
                             foreach ($dearesult->readAll() as $dearow) {
                                 $aDatatemp .= "<option value='{$dearow['code']}'";
                                 //if ($dearow['default_value'] == "Y") {$aDatatemp .= " selected='selected'"; $defexists = "Y";}
                                 $aDatatemp .= ">{$dearow['answer']}</option>\n";
                             }
                         } else {
                             $defaultopts = array();
                             $optgroups = array();
                             foreach ($dearesult->readAll() as $dearow) {
                                 list($categorytext, $answertext) = explode($optCategorySeparator, $dearow['answer']);
                                 if ($categorytext == '') {
                                     $defaultopts[] = array('code' => $dearow['code'], 'answer' => $answertext, 'default_value' => $dearow['assessment_value']);
                                 } else {
                                     $optgroups[$categorytext][] = array('code' => $dearow['code'], 'answer' => $answertext, 'default_value' => $dearow['assessment_value']);
                                 }
                             }
                             foreach ($optgroups as $categoryname => $optionlistarray) {
                                 $aDatatemp .= "<optgroup class=\"dropdowncategory\" label=\"" . $categoryname . "\">\n";
                                 foreach ($optionlistarray as $optionarray) {
                                     $aDatatemp .= "\t<option value='{$optionarray['code']}'";
                                     //if ($optionarray['default_value'] == "Y") {$aDatatemp .= " selected='selected'"; $defexists = "Y";}
                                     $aDatatemp .= ">{$optionarray['answer']}</option>\n";
                                 }
                                 $aDatatemp .= "</optgroup>\n";
                             }
                             foreach ($defaultopts as $optionarray) {
                                 $aDatatemp .= "\t<option value='{$optionarray['code']}'";
                                 //if ($optionarray['default_value'] == "Y") {$aDatatemp .= " selected='selected'"; $defexists = "Y";}
                                 $aDatatemp .= ">{$optionarray['answer']}</option>\n";
                             }
                         }
                         $oquery = "SELECT other FROM {{questions}} WHERE qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}'";
                         $oresult = dbExecuteAssoc($oquery) or safeDie("Couldn't get other for list question<br />");
                         foreach ($oresult->readAll() as $orow) {
                             $fother = $orow['other'];
                         }
                         $cdata['fother'] = $fother;
                         $cdata['defexists'] = $defexists;
                         $cdata['datatemp'] = $aDatatemp;
                         break;
                     case "O":
                         //LIST WITH COMMENT drop-down/radio-button list + textarea
                         $defexists = "";
                         $deaquery = "SELECT * FROM {{answers}} WHERE qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY sortorder, answer";
                         $dearesult = dbExecuteAssoc($deaquery);
                         //$aDataentryoutput .= "\t<select name='$fieldname'>\n";
                         $aDatatemp = '';
                         foreach ($dearesult->readAll() as $dearow) {
                             $aDatatemp .= "<option value='{$dearow['code']}'";
                             //if ($dearow['default_value'] == "Y") {$aDatatemp .= " selected='selected'"; $defexists = "Y";}
                             $aDatatemp .= ">{$dearow['answer']}</option>\n";
                         }
                         $cdata['datatemp'] = $aDatatemp;
                         $cdata['defexists'] = $defexists;
                         break;
                     case "R":
                         //RANKING TYPE QUESTION
                         $thisqid = $deqrow['qid'];
                         $ansquery = "SELECT * FROM {{answers}} WHERE qid={$thisqid} AND language='{$sDataEntryLanguage}' ORDER BY sortorder, answer";
                         $ansresult = dbExecuteAssoc($ansquery);
                         $ansresult = $ansresult->readAll();
                         $anscount = count($ansresult);
                         $cdata['thisqid'] = $thisqid;
                         $cdata['anscount'] = $anscount;
                         foreach ($ansresult as $ansrow) {
                             $answers[] = array($ansrow['code'], $ansrow['answer']);
                         }
                         for ($i = 1; $i <= $anscount; $i++) {
                             if (isset($fname)) {
                                 $myfname = $fname . $i;
                             }
                             if (isset($myfname) && Yii::app()->session[$myfname]) {
                                 $existing++;
                             }
                         }
                         for ($i = 1; $i <= $anscount; $i++) {
                             if (isset($fname)) {
                                 $myfname = $fname . $i;
                             }
                             if (isset($myfname) && Yii::app()->session[$myfname]) {
                                 foreach ($answers as $ans) {
                                     if ($ans[0] == Yii::app()->session[$myfname]) {
                                         $thiscode = $ans[0];
                                         $thistext = $ans[1];
                                     }
                                 }
                             }
                             if (!isset($ranklist)) {
                                 $ranklist = "";
                             }
                             $ranklist .= "&nbsp;<font color='#000080'>{$i}:&nbsp;<input class='ranklist' type='text' name='RANK{$i}' id='RANK_{$thisqid}{$i}'";
                             if (isset($myfname) && Yii::app()->session[$myfname]) {
                                 $ranklist .= " value='";
                                 $ranklist .= $thistext;
                                 $ranklist .= "'";
                             }
                             $ranklist .= " onFocus=\"this.blur()\"  />\n";
                             $ranklist .= "<input type='hidden' id='d{$fieldname}{$i}' name='{$fieldname}{$i}' value='";
                             $chosen[] = "";
                             //create array
                             if (isset($myfname) && Yii::app()->session[$myfname]) {
                                 $ranklist .= $thiscode;
                                 $chosen[] = array($thiscode, $thistext);
                             }
                             $ranklist .= "' /></font>\n";
                             $ranklist .= "<img src='" . Yii::app()->getConfig('imageurl') . "/cut.gif' alt='" . $blang->gT("Remove this item") . "' title='" . $blang->gT("Remove this item") . "' ";
                             if (!isset($existing) || $i != $existing) {
                                 $ranklist .= "style='display:none'";
                             }
                             $mfn = $fieldname . $i;
                             $ranklist .= " id='cut_{$thisqid}{$i}' onclick=\"deletethis_{$thisqid}(document.addsurvey.RANK_{$thisqid}{$i}.value, document.addsurvey.d{$fieldname}{$i}.value, document.addsurvey.RANK_{$thisqid}{$i}.id, this.id)\" /><br />\n\n";
                         }
                         if (!isset($choicelist)) {
                             $choicelist = "";
                         }
                         $choicelist .= "<select size='{$anscount}' class='choicelist' name='CHOICES' id='CHOICES_{$thisqid}' onclick=\"rankthis_{$thisqid}(this.options[this.selectedIndex].value, this.options[this.selectedIndex].text)\" >\n";
                         foreach ($answers as $ans) {
                             if (!in_array($ans, $chosen)) {
                                 $choicelist .= "\t<option value='{$ans[0]}'>{$ans[1]}</option>\n";
                             }
                         }
                         $choicelist .= "</select>\n";
                         $cdata['choicelist'] = $choicelist;
                         $cdata['ranklist'] = $ranklist;
                         if (isset($multifields)) {
                             $cdata['multifields'] = $multifields;
                         }
                         $choicelist = "";
                         $ranklist = "";
                         unset($answers);
                         break;
                     case "M":
                         //Multiple choice checkbox (Quite tricky really!)
                         //                            $qidattributes=getQuestionAttributeValues($deqrow['qid']);
                         if (trim($qidattributes['display_columns']) != '') {
                             $dcols = $qidattributes['display_columns'];
                         } else {
                             $dcols = 0;
                         }
                         $meaquery = "SELECT title, question FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $mearesult = dbExecuteAssoc($meaquery);
                         $cdata['dcols'] = $dcols;
                         $cdata['meacount'] = $meacount;
                         $cdata['mearesult'] = $mearesult->readAll();
                         $meacount = count($cdata['mearesult']);
                         break;
                     case "I":
                         //Language Switch
                         $slangs = Survey::model()->findByPk($surveyid)->additionalLanguages;
                         $sbaselang = Survey::model()->findByPk($surveyid)->language;
                         array_unshift($slangs, $sbaselang);
                         $cdata['slangs'] = $slangs;
                         break;
                     case "P":
                         //Multiple choice with comments checkbox + text
                         //$aDataentryoutput .= "<table border='0'>\n";
                         $meaquery = "SELECT * FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY question_order, question";
                         $mearesult = dbExecuteAssoc($meaquery);
                         $cdata['mearesult'] = $mearesult->readAll();
                         break;
                     case "|":
                         //                            $qidattributes = getQuestionAttributeValues($deqrow['qid']);
                         $cdata['qidattributes'] = $qidattributes;
                         $maxfiles = $qidattributes['max_num_of_files'];
                         $cdata['maxfiles'] = $maxfiles;
                         break;
                     case "A":
                         //ARRAY (5 POINT CHOICE) radio-buttons
                         $meaquery = "SELECT title, question FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $mearesult = dbExecuteAssoc($meaquery);
                         $cdata['mearesult'] = $mearesult->readAll();
                         break;
                     case "B":
                         //ARRAY (10 POINT CHOICE) radio-buttons
                         $meaquery = "SELECT title, question FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $mearesult = dbExecuteAssoc($meaquery);
                         $cdata['mearesult'] = $mearesult->readAll();
                     case "C":
                         //ARRAY (YES/UNCERTAIN/NO) radio-buttons
                         $meaquery = "SELECT title, question FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $mearesult = dbExecuteAssoc($meaquery);
                         $cdata['mearesult'] = $mearesult->readAll();
                         break;
                     case "E":
                         //ARRAY (YES/UNCERTAIN/NO) radio-buttons
                         $meaquery = "SELECT title, question FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $mearesult = dbExecuteAssoc($meaquery) or safeDie("Couldn't get answers, Type \"E\"<br />{$meaquery}<br />");
                         $cdata['mearesult'] = $mearesult->readAll();
                         break;
                     case ":":
                         //ARRAY (Multi Flexi)
                         //                            $qidattributes=getQuestionAttributeValues($deqrow['qid']);
                         $minvalue = 1;
                         $maxvalue = 10;
                         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']) != '') {
                             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) {
                             $minvalue = 0;
                             $maxvalue = 1;
                             $stepvalue = 1;
                         }
                         $cdata['minvalue'] = $minvalue;
                         $cdata['maxvalue'] = $maxvalue;
                         $cdata['stepvalue'] = $stepvalue;
                         $lquery = "SELECT question, title FROM {{questions}} WHERE parent_qid={$deqrow['qid']} and scale_id=1 and language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $lresult = dbExecuteAssoc($lquery) or die("Couldn't get labels, Type \":\"<br />{$lquery}<br />");
                         $cdata['lresult'] = $lresult->readAll();
                         $meaquery = "SELECT question, title FROM {{questions}} WHERE parent_qid={$deqrow['qid']} and scale_id=0 and language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $mearesult = dbExecuteAssoc($meaquery) or die("Couldn't get answers, Type \":\"<br />{$meaquery}<br />");
                         $cdata['mearesult'] = $mearesult->readAll();
                         break;
                     case ";":
                         //ARRAY (Multi Flexi)
                         $lquery = "SELECT * FROM {{questions}} WHERE scale_id=1 and parent_qid={$deqrow['qid']} and language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $lresult = dbExecuteAssoc($lquery) or die("Couldn't get labels, Type \":\"<br />{$lquery}<br />");
                         $cdata['lresult'] = $lresult->readAll();
                         $meaquery = "SELECT * FROM {{questions}} WHERE scale_id=0 and parent_qid={$deqrow['qid']} and language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $mearesult = dbExecuteAssoc($meaquery) or die("Couldn't get answers, Type \":\"<br />{$meaquery}<br />");
                         $cdata['mearesult'] = $mearesult->readAll();
                         break;
                     case "F":
                         //ARRAY (Flexible Labels)
                     //ARRAY (Flexible Labels)
                     case "H":
                         $meaquery = "SELECT * FROM {{questions}} WHERE parent_qid={$deqrow['qid']} and language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $mearesult = dbExecuteAssoc($meaquery) or safeDie("Couldn't get answers, Type \"E\"<br />{$meaquery}<br />");
                         $cdata['mearesult'] = $mearesult->readAll();
                         $fquery = "SELECT * FROM {{answers}} WHERE qid={$deqrow['qid']} and language='{$sDataEntryLanguage}' ORDER BY sortorder, code";
                         $fresult = dbExecuteAssoc($fquery);
                         $cdata['fresult'] = $fresult->readAll();
                         break;
                 }
                 $cdata['sDataEntryLanguage'] = $sDataEntryLanguage;
                 $viewdata = $this->getController()->render("/admin/dataentry/content_view", $cdata, TRUE);
                 $viewdata_em = LimeExpressionManager::ProcessString($viewdata, $deqrow['qid'], NULL, false, 1, 1);
                 $aDataentryoutput .= $viewdata_em;
             }
             LimeExpressionManager::FinishProcessingGroup();
         }
         LimeExpressionManager::FinishProcessingPage();
         $aDataentryoutput .= LimeExpressionManager::GetRelevanceAndTailoringJavaScript();
         $aViewUrls['output'] = $aDataentryoutput;
         $aData['thissurvey'] = $thissurvey;
         $aData['surveyid'] = $surveyid;
         $aData['sDataEntryLanguage'] = $sDataEntryLanguage;
         if ($thissurvey['active'] == "Y" && $thissurvey['allowsave'] == "Y") {
             $slangs = Survey::model()->findByPk($surveyid)->additionalLanguages;
             $sbaselang = Survey::model()->findByPk($surveyid)->language;
             array_unshift($slangs, $sbaselang);
             $aData['slangs'] = $slangs;
             $aData['baselang'] = $baselang;
         }
         $aViewUrls[] = 'active_html_view';
         $this->_renderWrappedTemplate('dataentry', $aViewUrls, $aData);
     }
 }
Beispiel #29
0
 function deleteFinalUser($result, $transfer_surveys_to)
 {
     $clang = Yii::app()->lang;
     $postuserid = Yii::app()->request->getPost("uid");
     $postuser = Yii::app()->request->getPost("user");
     if (isset($_POST['transfer_surveys_to'])) {
         $transfer_surveys_to = sanitize_int($_POST['transfer_surveys_to']);
     }
     if ($transfer_surveys_to > 0) {
         $iSurveysTransferred = Survey::model()->updateAll(array('owner_id' => $transfer_surveys_to), 'owner_id=' . $postuserid);
     }
     $sresult = User::model()->findByAttributes(array('uid' => $postuserid));
     $fields = $sresult;
     if (isset($fields['parent_id'])) {
         $uresult = User::model()->updateAll(array('parent_id' => $fields['parent_id']), 'parent_id=' . $postuserid);
     }
     //DELETE USER FROM TABLE
     $dresult = User::model()->deleteUser($postuserid);
     // Delete user rights
     $dresult = Survey_permissions::model()->deleteAllByAttributes(array('uid' => $postuserid));
     if ($postuserid == Yii::app()->session['loginID']) {
         session_destroy;
         // user deleted himself
         $this->redirect($this->getController()->createUrl('/admin'));
         die;
     }
     $extra = "<br />" . sprintf($clang->gT("User '%s' was successfully deleted."), $postuser) . "<br /><br />\n";
     if ($transfer_surveys_to > 0 && $iSurveysTransferred > 0) {
         $user = User::model()->findByPk($transfer_surveys_to);
         $sTransferred_to = $user->users_name;
         //$sTransferred_to = $this->getController()->_getUserNameFromUid($transfer_surveys_to);
         $extra = sprintf($clang->gT("All of the user's surveys were transferred to %s."), $sTransferred_to);
     }
     $aViewUrls['mboxwithredirect'][] = $this->_messageBoxWithRedirect("", $clang->gT("Success!"), "successheader", $extra);
     $this->_renderWrappedTemplate('user', $aViewUrls);
 }
Beispiel #30
0
 /**
  * Renders template(s) wrapped in header and footer
  *
  * @param string $sAction Current action, the folder to fetch views from
  * @param string|array $aViewUrls View url(s)
  * @param array $aData Data to be passed on. Optional.
  */
 protected function _renderWrappedTemplate($sAction = 'dataentry', $aViewUrls = array(), $aData = array())
 {
     if (!isset($aData['display']['menu_bars']['browse'])) {
         if (isset($aData['surveyid'])) {
             $iSurveyId = $aData['surveyid'];
         }
         if (isset($_POST['sid'])) {
             $iSurveyId = $_POST['sid'];
         }
         $aData['display']['menu_bars']['browse'] = gT("Data entry");
         $surveyinfo = Survey::model()->findByPk($iSurveyId)->surveyinfo;
         $aData["surveyinfo"] = $surveyinfo;
         $aData['title_bar']['title'] = gT("Data entry");
     }
     parent::_renderWrappedTemplate($sAction, $aViewUrls, $aData);
 }