예제 #1
0
 function index()
 {
     $aData = array();
     $needpermission = false;
     $aData['surveyid'] = $surveyid = sanitize_int(Yii::app()->request->getQuery('sid'));
     $aData['sa'] = $sa = sanitize_paranoid_string(Yii::app()->request->getQuery('sa', 'index'));
     if (($aData['sa'] == 'survey_logic_file' || $aData['sa'] == 'navigation_test') && $surveyid) {
         $needpermission = true;
     }
     if ($needpermission && !Permission::model()->hasSurveyPermission($surveyid, 'surveycontent', 'read')) {
         App()->getClientScript()->registerPackage('jquery-superfish');
         $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']}";
         //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);
         }
     }
 }
예제 #2
0
function globalsettingssave()
{
    global $action, $editsurvey, $connect, $scriptname, $clang;
    if (isset($action) && $action == "globalsettingssave") {
        if ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {
            if (sanitize_int($_POST['maxemails']) < 1) {
                $_POST['maxemails'] = 1;
            }
            setGlobalSetting('sitename', strip_tags($_POST['sitename']));
            setGlobalSetting('updatecheckperiod', (int) $_POST['updatecheckperiod']);
            setGlobalSetting('addTitleToLinks', sanitize_paranoid_string($_POST['addTitleToLinks']));
            setGlobalSetting('defaultlang', sanitize_languagecode($_POST['defaultlang']));
            setGlobalSetting('defaulthtmleditormode', sanitize_paranoid_string($_POST['defaulthtmleditormode']));
            setGlobalSetting('defaulttemplate', sanitize_paranoid_string($_POST['defaulttemplate']));
            setGlobalSetting('emailmethod', strip_tags($_POST['emailmethod']));
            setGlobalSetting('emailsmtphost', strip_tags(returnglobal('emailsmtphost')));
            if (returnglobal('emailsmtppassword') != 'somepassword') {
                setGlobalSetting('emailsmtppassword', strip_tags(returnglobal('emailsmtppassword')));
            }
            setGlobalSetting('emailsmtpssl', sanitize_paranoid_string(returnglobal('emailsmtpssl')));
            setGlobalSetting('emailsmtpdebug', sanitize_int(returnglobal('emailsmtpdebug')));
            setGlobalSetting('emailsmtpuser', strip_tags(returnglobal('emailsmtpuser')));
            setGlobalSetting('filterxsshtml', strip_tags($_POST['filterxsshtml']));
            setGlobalSetting('siteadminbounce', strip_tags($_POST['siteadminbounce']));
            setGlobalSetting('siteadminemail', strip_tags($_POST['siteadminemail']));
            setGlobalSetting('siteadminname', strip_tags($_POST['siteadminname']));
            setGlobalSetting('shownoanswer', sanitize_int($_POST['shownoanswer']));
            $repeatheadingstemp = (int) $_POST['repeatheadings'];
            if ($repeatheadingstemp == 0) {
                $repeatheadingstemp = 25;
            }
            setGlobalSetting('repeatheadings', $repeatheadingstemp);
            setGlobalSetting('maxemails', sanitize_int($_POST['maxemails']));
            $sessionlifetimetemp = (int) $_POST['sessionlifetime'];
            if ($sessionlifetimetemp == 0) {
                $sessionlifetimetemp = 3600;
            }
            setGlobalSetting('sessionlifetime', $sessionlifetimetemp);
            setGlobalSetting('surveyPreview_require_Auth', strip_tags($_POST['surveyPreview_require_Auth']));
            $savetime = trim(strip_tags((double) $_POST['timeadjust']) . ' hours');
            //makes sure it is a number, at least 0
            if (substr($savetime, 0, 1) != '-' && substr($savetime, 0, 1) != '+') {
                $savetime = '+' . $savetime;
            }
            setGlobalSetting('timeadjust', $savetime);
            setGlobalSetting('usepdfexport', strip_tags($_POST['usepdfexport']));
            setGlobalSetting('usercontrolSameGroupPolicy', strip_tags($_POST['usercontrolSameGroupPolicy']));
            $editsurvey .= "<div class='header'>" . $clang->gT("Global settings") . "</div>\n" . "<div class=\"messagebox\">\n" . "<br /><div class=\"successheader\">" . $clang->gT("Global settings were saved.") . "</div>\n" . "<br/><input type=\"submit\" onclick=\"window.open('admin.php', '_top')\" value=\"" . $clang->gT("Continue") . "\"/>\n" . "</div>\n";
        }
    }
}
예제 #3
0
 function index()
 {
     Yii::app()->loadHelper('admin/htmleditor');
     $aData = array('ckLanguage' => sTranslateLangCode2CK(Yii::app()->session['adminlang']), 'sFieldName' => sanitize_xss_string(App()->request->getQuery('name')), 'sFieldText' => sanitize_xss_string(App()->request->getQuery('text')), 'sFieldType' => sanitize_xss_string(App()->request->getQuery('type')), 'sAction' => sanitize_paranoid_string(App()->request->getQuery('action')), 'iSurveyId' => sanitize_int(App()->request->getQuery('sid', 0)), 'iGroupId' => sanitize_int(App()->request->getQuery('gid', 0)), 'iQuestionId' => sanitize_int(App()->request->getQuery('qid', 0)));
     if (!$aData['sFieldName']) {
         $this->getController()->render('/admin/htmleditor/pop_nofields_view', $aData);
     } else {
         $aData['sControlIdEna'] = $aData['sFieldName'] . '_popupctrlena';
         $aData['sControlIdDis'] = $aData['sFieldName'] . '_popupctrldis';
         $aData['toolbarname'] = 'popup';
         $aData['htmlformatoption'] = '';
         if (in_array($aData['sFieldType'], array('email-inv', 'email-reg', 'email-conf', 'email-rem'))) {
             $aData['htmlformatoption'] = ',fullPage:true';
         }
         $this->getController()->render('/admin/htmleditor/pop_editor_view', $aData);
     }
 }
예제 #4
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);
         }
     }
 }
예제 #5
0
 private function _saveSettings()
 {
     if ($_POST['action'] !== "globalsettingssave") {
         return;
     }
     if (!Permission::model()->hasGlobalPermission('settings', 'update')) {
         $this->getController()->redirect(array('/admin'));
     }
     Yii::app()->loadHelper('surveytranslator');
     $iPDFFontSize = sanitize_int($_POST['pdffontsize']);
     if ($iPDFFontSize < 1) {
         $iPDFFontSize = 9;
     }
     $iPDFLogoWidth = sanitize_int($_POST['pdflogowidth']);
     if ($iPDFLogoWidth < 1) {
         $iPDFLogoWidth = 50;
     }
     $maxemails = $_POST['maxemails'];
     if (sanitize_int($_POST['maxemails']) < 1) {
         $maxemails = 1;
     }
     $defaultlang = sanitize_languagecode($_POST['defaultlang']);
     $aRestrictToLanguages = explode(' ', sanitize_languagecodeS($_POST['restrictToLanguages']));
     if (!in_array($defaultlang, $aRestrictToLanguages)) {
         // Force default language in restrictToLanguages
         $aRestrictToLanguages[] = $defaultlang;
     }
     if (count(array_diff(array_keys(getLanguageData(false, Yii::app()->session['adminlang'])), $aRestrictToLanguages)) == 0) {
         $aRestrictToLanguages = '';
     } else {
         $aRestrictToLanguages = implode(' ', $aRestrictToLanguages);
     }
     setGlobalSetting('defaultlang', $defaultlang);
     setGlobalSetting('restrictToLanguages', trim($aRestrictToLanguages));
     setGlobalSetting('sitename', strip_tags($_POST['sitename']));
     setGlobalSetting('defaulthtmleditormode', sanitize_paranoid_string($_POST['defaulthtmleditormode']));
     setGlobalSetting('defaultquestionselectormode', sanitize_paranoid_string($_POST['defaultquestionselectormode']));
     setGlobalSetting('defaulttemplateeditormode', sanitize_paranoid_string($_POST['defaulttemplateeditormode']));
     if (!Yii::app()->getConfig('demoMode')) {
         $sTemplate = Yii::app()->getRequest()->getPost("defaulttemplate");
         if (array_key_exists($sTemplate, getTemplateList())) {
             setGlobalSetting('defaulttemplate', $sTemplate);
         }
     }
     setGlobalSetting('admintheme', sanitize_paranoid_string($_POST['admintheme']));
     setGlobalSetting('adminthemeiconsize', trim(file_get_contents(Yii::app()->getConfig("styledir") . DIRECTORY_SEPARATOR . sanitize_paranoid_string($_POST['admintheme']) . DIRECTORY_SEPARATOR . 'iconsize')));
     setGlobalSetting('emailmethod', strip_tags($_POST['emailmethod']));
     setGlobalSetting('emailsmtphost', strip_tags(returnGlobal('emailsmtphost')));
     if (returnGlobal('emailsmtppassword') != 'somepassword') {
         setGlobalSetting('emailsmtppassword', strip_tags(returnGlobal('emailsmtppassword')));
     }
     setGlobalSetting('bounceaccounthost', strip_tags(returnGlobal('bounceaccounthost')));
     setGlobalSetting('bounceaccounttype', strip_tags(returnGlobal('bounceaccounttype')));
     setGlobalSetting('bounceencryption', strip_tags(returnGlobal('bounceencryption')));
     setGlobalSetting('bounceaccountuser', strip_tags(returnGlobal('bounceaccountuser')));
     if (returnGlobal('bounceaccountpass') != 'enteredpassword') {
         setGlobalSetting('bounceaccountpass', strip_tags(returnGlobal('bounceaccountpass')));
     }
     setGlobalSetting('emailsmtpssl', sanitize_paranoid_string(Yii::app()->request->getPost('emailsmtpssl', '')));
     setGlobalSetting('emailsmtpdebug', sanitize_int(Yii::app()->request->getPost('emailsmtpdebug', '0')));
     setGlobalSetting('emailsmtpuser', strip_tags(returnGlobal('emailsmtpuser')));
     setGlobalSetting('filterxsshtml', strip_tags($_POST['filterxsshtml']));
     $warning = '';
     // make sure emails are valid before saving them
     if (Yii::app()->request->getPost('siteadminbounce', '') == '' || validateEmailAddress(Yii::app()->request->getPost('siteadminbounce'))) {
         setGlobalSetting('siteadminbounce', strip_tags(Yii::app()->request->getPost('siteadminbounce')));
     } else {
         $warning .= gT("Warning! Admin bounce email was not saved because it was not valid.") . '<br/>';
     }
     if (Yii::app()->request->getPost('siteadminemail', '') == '' || validateEmailAddress(Yii::app()->request->getPost('siteadminemail'))) {
         setGlobalSetting('siteadminemail', strip_tags(Yii::app()->request->getPost('siteadminemail')));
     } else {
         $warning .= gT("Warning! Admin email was not saved because it was not valid.") . '<br/>';
     }
     setGlobalSetting('siteadminname', strip_tags($_POST['siteadminname']));
     setGlobalSetting('shownoanswer', sanitize_int($_POST['shownoanswer']));
     setGlobalSetting('showxquestions', $_POST['showxquestions']);
     setGlobalSetting('showgroupinfo', $_POST['showgroupinfo']);
     setGlobalSetting('showqnumcode', $_POST['showqnumcode']);
     $repeatheadingstemp = (int) $_POST['repeatheadings'];
     if ($repeatheadingstemp == 0) {
         $repeatheadingstemp = 25;
     }
     setGlobalSetting('repeatheadings', $repeatheadingstemp);
     setGlobalSetting('maxemails', sanitize_int($maxemails));
     $iSessionExpirationTime = (int) $_POST['iSessionExpirationTime'];
     if ($iSessionExpirationTime == 0) {
         $iSessionExpirationTime = 7200;
     }
     setGlobalSetting('iSessionExpirationTime', $iSessionExpirationTime);
     setGlobalSetting('ipInfoDbAPIKey', $_POST['ipInfoDbAPIKey']);
     setGlobalSetting('pdffontsize', $iPDFFontSize);
     setGlobalSetting('pdfshowheader', $_POST['pdfshowheader']);
     setGlobalSetting('pdflogowidth', $iPDFLogoWidth);
     setGlobalSetting('pdfheadertitle', $_POST['pdfheadertitle']);
     setGlobalSetting('pdfheaderstring', $_POST['pdfheaderstring']);
     setGlobalSetting('googleMapsAPIKey', $_POST['googleMapsAPIKey']);
     setGlobalSetting('googleanalyticsapikey', $_POST['googleanalyticsapikey']);
     setGlobalSetting('googletranslateapikey', $_POST['googletranslateapikey']);
     setGlobalSetting('force_ssl', $_POST['force_ssl']);
     setGlobalSetting('surveyPreview_require_Auth', $_POST['surveyPreview_require_Auth']);
     setGlobalSetting('RPCInterface', $_POST['RPCInterface']);
     setGlobalSetting('rpc_publish_api', (bool) $_POST['rpc_publish_api']);
     $savetime = (double) $_POST['timeadjust'] * 60 . ' minutes';
     //makes sure it is a number, at least 0
     if (substr($savetime, 0, 1) != '-' && substr($savetime, 0, 1) != '+') {
         $savetime = '+' . $savetime;
     }
     setGlobalSetting('timeadjust', $savetime);
     setGlobalSetting('usercontrolSameGroupPolicy', strip_tags($_POST['usercontrolSameGroupPolicy']));
     Yii::app()->session['flashmessage'] = $warning . gT("Global settings were saved.");
     $url = htmlspecialchars_decode(Yii::app()->session['refurl']);
     if ($url) {
         Yii::app()->getController()->redirect($url);
     }
 }
예제 #6
0
 /**
  * Database::index()
  *
  * @param mixed $sa
  * @return
  */
 function index($sa = null)
 {
     $sAction = Yii::app()->request->getPost('action');
     $iSurveyID = isset($_POST['sid']) ? $_POST['sid'] : returnGlobal('sid');
     $iQuestionGroupID = returnGlobal('gid');
     $iQuestionID = returnGlobal('qid');
     // TODO: This variable seems to be never set or used in any function call?
     $sDBOutput = '';
     $oFixCKeditor = new LSYii_Validators();
     $oFixCKeditor->fixCKeditor = true;
     $oFixCKeditor->xssfilter = false;
     if ($sAction == "updatedefaultvalues" && Permission::model()->hasSurveyPermission($iSurveyID, 'surveycontent', 'update')) {
         $aSurveyLanguages = Survey::model()->findByPk($iSurveyID)->additionalLanguages;
         $sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language;
         array_unshift($aSurveyLanguages, $sBaseLanguage);
         Question::model()->updateAll(array('same_default' => Yii::app()->request->getPost('samedefault') ? 1 : 0), 'sid=:sid ANd qid=:qid', array(':sid' => $iSurveyID, ':qid' => $iQuestionID));
         $arQuestion = Question::model()->findByAttributes(array('qid' => $iQuestionID));
         $sQuestionType = $arQuestion['type'];
         $aQuestionTypeList = getQuestionTypeList('', 'array');
         if ($aQuestionTypeList[$sQuestionType]['answerscales'] > 0 && $aQuestionTypeList[$sQuestionType]['subquestions'] == 0) {
             for ($iScaleID = 0; $iScaleID < $aQuestionTypeList[$sQuestionType]['answerscales']; $iScaleID++) {
                 foreach ($aSurveyLanguages as $sLanguage) {
                     if (!is_null(Yii::app()->request->getPost('defaultanswerscale_' . $iScaleID . '_' . $sLanguage))) {
                         $this->_updateDefaultValues($iQuestionID, 0, $iScaleID, '', $sLanguage, Yii::app()->request->getPost('defaultanswerscale_' . $iScaleID . '_' . $sLanguage), true);
                     }
                     if (!is_null(Yii::app()->request->getPost('other_' . $iScaleID . '_' . $sLanguage))) {
                         $this->_updateDefaultValues($iQuestionID, 0, $iScaleID, 'other', $sLanguage, Yii::app()->request->getPost('other_' . $iScaleID . '_' . $sLanguage), true);
                     }
                 }
             }
         }
         if ($aQuestionTypeList[$sQuestionType]['subquestions'] > 0) {
             foreach ($aSurveyLanguages as $sLanguage) {
                 $arQuestions = Question::model()->findAllByAttributes(array('sid' => $iSurveyID, 'gid' => $iQuestionGroupID, 'parent_qid' => $iQuestionID, 'language' => $sLanguage, 'scale_id' => 0));
                 for ($iScaleID = 0; $iScaleID < $aQuestionTypeList[$sQuestionType]['subquestions']; $iScaleID++) {
                     foreach ($arQuestions as $aSubquestionrow) {
                         if (!is_null(Yii::app()->request->getPost('defaultanswerscale_' . $iScaleID . '_' . $sLanguage . '_' . $aSubquestionrow['qid']))) {
                             $this->_updateDefaultValues($iQuestionID, $aSubquestionrow['qid'], $iScaleID, '', $sLanguage, Yii::app()->request->getPost('defaultanswerscale_' . $iScaleID . '_' . $sLanguage . '_' . $aSubquestionrow['qid']), true);
                         }
                     }
                 }
             }
         }
         if ($aQuestionTypeList[$sQuestionType]['answerscales'] == 0 && $aQuestionTypeList[$sQuestionType]['subquestions'] == 0) {
             foreach ($aSurveyLanguages as $sLanguage) {
                 // Qick and dirty insert for yes/no defaul value
                 // write the the selectbox option, or if "EM" is slected, this value to table
                 if ($sQuestionType == 'Y') {
                     /// value for all langs
                     if (Yii::app()->request->getPost('samedefault') == 1) {
                         $sLanguage = $aSurveyLanguages[0];
                         // turn
                     } else {
                         $sCurrentLang = $sLanguage;
                         // edit the next lines
                     }
                     if (Yii::app()->request->getPost('defaultanswerscale_0_' . $sLanguage) == 'EM') {
                         // Case EM, write expression to database
                         $this->_updateDefaultValues($iQuestionID, 0, 0, '', $sLanguage, Yii::app()->request->getPost('defaultanswerscale_0_' . $sLanguage . '_EM'), true);
                     } else {
                         // Case "other", write list value to database
                         $this->_updateDefaultValues($iQuestionID, 0, 0, '', $sLanguage, Yii::app()->request->getPost('defaultanswerscale_0_' . $sLanguage), true);
                     }
                     ///// end yes/no
                 } else {
                     if (!is_null(Yii::app()->request->getPost('defaultanswerscale_0_' . $sLanguage . '_0'))) {
                         $this->_updateDefaultValues($iQuestionID, 0, 0, '', $sLanguage, Yii::app()->request->getPost('defaultanswerscale_0_' . $sLanguage . '_0'), true);
                     }
                 }
             }
         }
         Yii::app()->session['flashmessage'] = gT("Default value settings were successfully saved.");
         LimeExpressionManager::SetDirtyFlag();
         if ($sDBOutput != '') {
             echo $sDBOutput;
         } else {
             if (Yii::app()->request->getPost('close-after-save') === 'true') {
                 $this->getController()->redirect(array('admin/questions/sa/view/surveyid/' . $iSurveyID . '/gid/' . $iQuestionGroupID . '/qid/' . $iQuestionID));
             }
             $this->getController()->redirect(array('admin/questions/sa/editdefaultvalues/surveyid/' . $iSurveyID . '/gid/' . $iQuestionGroupID . '/qid/' . $iQuestionID));
         }
     }
     if ($sAction == "updateansweroptions" && Permission::model()->hasSurveyPermission($iSurveyID, 'surveycontent', 'update')) {
         Yii::app()->loadHelper('database');
         $aSurveyLanguages = Survey::model()->findByPk($iSurveyID)->additionalLanguages;
         $sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language;
         array_unshift($aSurveyLanguages, $sBaseLanguage);
         $arQuestion = Question::model()->findByAttributes(array('qid' => $iQuestionID));
         $sQuestionType = $arQuestion['type'];
         // Checked)
         $aQuestionTypeList = getQuestionTypeList('', 'array');
         $iScaleCount = $aQuestionTypeList[$sQuestionType]['answerscales'];
         //First delete all answers
         Answer::model()->deleteAllByAttributes(array('qid' => $iQuestionID));
         LimeExpressionManager::RevertUpgradeConditionsToRelevance($iSurveyID);
         for ($iScaleID = 0; $iScaleID < $iScaleCount; $iScaleID++) {
             $iMaxCount = (int) Yii::app()->request->getPost('answercount_' . $iScaleID);
             for ($iSortOrderID = 1; $iSortOrderID < $iMaxCount; $iSortOrderID++) {
                 $sCode = sanitize_paranoid_string(Yii::app()->request->getPost('code_' . $iSortOrderID . '_' . $iScaleID));
                 $iAssessmentValue = (int) Yii::app()->request->getPost('assessment_' . $iSortOrderID . '_' . $iScaleID);
                 foreach ($aSurveyLanguages as $sLanguage) {
                     $sAnswerText = Yii::app()->request->getPost('answer_' . $sLanguage . '_' . $iSortOrderID . '_' . $iScaleID);
                     // Fix bug with FCKEditor saving strange BR types
                     $sAnswerText = $oFixCKeditor->fixCKeditor($sAnswerText);
                     // Now we insert the answers
                     $iInsertCount = Answer::model()->insertRecords(array('code' => $sCode, 'answer' => $sAnswerText, 'qid' => $iQuestionID, 'sortorder' => $iSortOrderID, 'language' => $sLanguage, 'assessment_value' => $iAssessmentValue, 'scale_id' => $iScaleID));
                     if (!$iInsertCount) {
                         Yii::app()->setFlashMessage(gT("Failed to update answers"), 'error');
                     }
                 }
                 // Updating code (oldcode!==null) => update condition with the new code
                 $sOldCode = Yii::app()->request->getPost('oldcode_' . $iSortOrderID . '_' . $iScaleID);
                 if (isset($sOldCode) && $sCode !== $sOldCode) {
                     Condition::model()->updateAll(array('value' => $sCode), 'cqid=:cqid AND value=:value', array(':cqid' => $iQuestionID, ':value' => $sOldCode));
                 }
             }
             // for ($sortorderid=0;$sortorderid<$maxcount;$sortorderid++)
         }
         //  for ($scale_id=0;
         LimeExpressionManager::UpgradeConditionsToRelevance($iSurveyID);
         if (!Yii::app()->request->getPost('bFullPOST')) {
             Yii::app()->setFlashMessage(gT("Not all answer options were saved. This usually happens due to server limitations ( PHP setting max_input_vars) - please contact your system administrator."));
         } else {
             Yii::app()->session['flashmessage'] = gT("Answer options were successfully saved.");
         }
         LimeExpressionManager::SetDirtyFlag();
         if ($sDBOutput != '') {
             echo $sDBOutput;
         } else {
             if (Yii::app()->request->getPost('close-after-save') === 'true') {
                 $this->getController()->redirect(array('admin/questions/sa/view/surveyid/' . $iSurveyID . '/gid/' . $iQuestionGroupID . '/qid/' . $iQuestionID));
             }
             $this->getController()->redirect(array('/admin/questions/sa/answeroptions/surveyid/' . $iSurveyID . '/gid/' . $iQuestionGroupID . '/qid/' . $iQuestionID));
         }
     }
     if ($sAction == "updatesubquestions" && Permission::model()->hasSurveyPermission($iSurveyID, 'surveycontent', 'update')) {
         Yii::app()->loadHelper('database');
         $aSurveyLanguages = Survey::model()->findByPk($iSurveyID)->additionalLanguages;
         $sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language;
         array_unshift($aSurveyLanguages, $sBaseLanguage);
         $arQuestion = Question::model()->findByAttributes(array('qid' => $iQuestionID));
         $sQuestionType = $arQuestion['type'];
         // Checked
         $aQuestionTypeList = getQuestionTypeList('', 'array');
         $iScaleCount = $aQuestionTypeList[$sQuestionType]['subquestions'];
         // First delete any deleted ids
         $aDeletedQIDs = explode(' ', trim(Yii::app()->request->getPost('deletedqids')));
         LimeExpressionManager::RevertUpgradeConditionsToRelevance($iSurveyID);
         $aDeletedQIDs = array_unique($aDeletedQIDs, SORT_NUMERIC);
         foreach ($aDeletedQIDs as $iDeletedQID) {
             $iDeletedQID = (int) $iDeletedQID;
             if ($iDeletedQID > 0) {
                 // don't remove undefined
                 $iInsertCount = Question::model()->deleteAllByAttributes(array('qid' => $iDeletedQID));
                 if (!$iInsertCount) {
                     Yii::app()->setFlashMessage(gT("Failed to delete answer"), 'error');
                 }
             }
         }
         //Determine ids by evaluating the hidden field
         $aRows = array();
         $aCodes = array();
         $aOldCodes = array();
         $aRelevance = array();
         foreach ($_POST as $sPOSTKey => $sPOSTValue) {
             $sPOSTKey = explode('_', $sPOSTKey);
             if ($sPOSTKey[0] == 'answer') {
                 $aRows[$sPOSTKey[3]][$sPOSTKey[1]][$sPOSTKey[2]] = $sPOSTValue;
             }
             if ($sPOSTKey[0] == 'code') {
                 $aCodes[$sPOSTKey[2]][] = $sPOSTValue;
             }
             if ($sPOSTKey[0] == 'oldcode') {
                 $aOldCodes[$sPOSTKey[2]][] = $sPOSTValue;
             }
             if ($sPOSTKey[0] == 'relevance') {
                 $aRelevance[$sPOSTKey[2]][] = $sPOSTValue;
             }
         }
         $aInsertQID = array();
         for ($iScaleID = 0; $iScaleID < $iScaleCount; $iScaleID++) {
             foreach ($aSurveyLanguages as $sLanguage) {
                 $iPosition = 0;
                 foreach ($aRows[$iScaleID][$sLanguage] as $subquestionkey => $subquestionvalue) {
                     if (substr($subquestionkey, 0, 3) != 'new') {
                         $oSubQuestion = Question::model()->find("qid=:qid AND language=:language", array(":qid" => $subquestionkey, ':language' => $sLanguage));
                         if (!is_object($oSubQuestion)) {
                             throw new CHttpException(502, "could not find subquestion {$subquestionkey} !");
                         }
                         $oSubQuestion->question_order = $iPosition + 1;
                         $oSubQuestion->title = $aCodes[$iScaleID][$iPosition];
                         $oSubQuestion->question = $subquestionvalue;
                         $oSubQuestion->scale_id = $iScaleID;
                         $oSubQuestion->relevance = isset($aRelevance[$iScaleID][$iPosition]) ? $aRelevance[$iScaleID][$iPosition] : "";
                     } else {
                         if (!isset($aInsertQID[$iScaleID][$iPosition])) {
                             $oSubQuestion = new Question();
                             $oSubQuestion->sid = $iSurveyID;
                             $oSubQuestion->gid = $iQuestionGroupID;
                             $oSubQuestion->question_order = $iPosition + 1;
                             $oSubQuestion->title = $aCodes[$iScaleID][$iPosition];
                             $oSubQuestion->question = $subquestionvalue;
                             $oSubQuestion->parent_qid = $iQuestionID;
                             $oSubQuestion->language = $sLanguage;
                             $oSubQuestion->scale_id = $iScaleID;
                             $oSubQuestion->relevance = isset($aRelevance[$iScaleID][$iPosition]) ? $aRelevance[$iScaleID][$iPosition] : "";
                         } else {
                             $oSubQuestion = Question::model()->find("qid=:qid AND language=:language", array(":qid" => $aInsertQID[$iScaleID][$iPosition], ':language' => $sLanguage));
                             if (!$oSubQuestion) {
                                 $oSubQuestion = new Question();
                             }
                             $oSubQuestion->sid = $iSurveyID;
                             $oSubQuestion->qid = $aInsertQID[$iScaleID][$iPosition];
                             $oSubQuestion->gid = $iQuestionGroupID;
                             $oSubQuestion->question_order = $iPosition + 1;
                             $oSubQuestion->title = $aCodes[$iScaleID][$iPosition];
                             $oSubQuestion->question = $subquestionvalue;
                             $oSubQuestion->parent_qid = $iQuestionID;
                             $oSubQuestion->language = $sLanguage;
                             $oSubQuestion->scale_id = $iScaleID;
                             $oSubQuestion->relevance = isset($aRelevance[$iScaleID][$iPosition]) ? $aRelevance[$iScaleID][$iPosition] : "";
                         }
                     }
                     if ($oSubQuestion->qid) {
                         switchMSSQLIdentityInsert('questions', true);
                         $bSubQuestionResult = $oSubQuestion->save();
                         switchMSSQLIdentityInsert('questions', false);
                     } else {
                         $bSubQuestionResult = $oSubQuestion->save();
                     }
                     if ($bSubQuestionResult) {
                         if (substr($subquestionkey, 0, 3) != 'new' && isset($aOldCodes[$iScaleID][$iPosition]) && $aCodes[$iScaleID][$iPosition] !== $aOldCodes[$iScaleID][$iPosition]) {
                             Condition::model()->updateAll(array('cfieldname' => '+' . $iSurveyID . 'X' . $iQuestionGroupID . 'X' . $iQuestionID . $aCodes[$iScaleID][$iPosition], 'value' => $aCodes[$iScaleID][$iPosition]), 'cqid=:cqid AND cfieldname=:cfieldname AND value=:value', array(':cqid' => $iQuestionID, ':cfieldname' => $iSurveyID . 'X' . $iQuestionGroupID . 'X' . $iQuestionID, ':value' => $aOldCodes[$iScaleID][$iPosition]));
                         }
                         if (!isset($aInsertQID[$iScaleID][$iPosition])) {
                             $aInsertQID[$iScaleID][$iPosition] = $oSubQuestion->qid;
                         }
                     } else {
                         $aErrors = $oSubQuestion->getErrors();
                         if (count($aErrors)) {
                             //$sErrorMessage=gT("Question could not be updated with this errors:");
                             foreach ($aErrors as $sAttribute => $aStringErrors) {
                                 foreach ($aStringErrors as $sStringErrors) {
                                     Yii::app()->setFlashMessage(sprintf(gT("Error on %s for subquestion %s: %s"), $sAttribute, $aCodes[$iScaleID][$iPosition], $sStringErrors), 'error');
                                 }
                             }
                         } else {
                             Yii::app()->setFlashMessage(sprintf(gT("Subquestions %s could not be updated."), $aCodes[$iScaleID][$iPosition]), 'error');
                         }
                     }
                     $iPosition++;
                 }
             }
         }
         LimeExpressionManager::UpgradeConditionsToRelevance($iSurveyID);
         // Do it only if there are no error ?
         if (!isset($aErrors) || !count($aErrors)) {
             if (!Yii::app()->request->getPost('bFullPOST')) {
                 Yii::app()->session['flashmessage'] = gT("Not all subquestions were saved. This usually happens due to server limitations ( PHP setting max_input_vars) - please contact your system administrator.");
             } else {
                 Yii::app()->session['flashmessage'] = gT("Subquestions were successfully saved.");
             }
         }
         //$action='editsubquestions';
         LimeExpressionManager::SetDirtyFlag();
         if ($sDBOutput != '') {
             echo 'Problem in database controller: ' . $sDBOutput;
         } else {
             if (Yii::app()->request->getPost('close-after-save') === 'true') {
                 $this->getController()->redirect(array('/admin/questions/sa/view/surveyid/' . $iSurveyID . '/gid/' . $iQuestionGroupID . '/qid/' . $iQuestionID));
             }
             $this->getController()->redirect(array('/admin/questions/sa/subquestions/surveyid/' . $iSurveyID . '/gid/' . $iQuestionGroupID . '/qid/' . $iQuestionID));
         }
     }
     /**
      * Insert / Copy question
      */
     if (in_array($sAction, array('insertquestion', 'copyquestion')) && Permission::model()->hasSurveyPermission($iSurveyID, 'surveycontent', 'create')) {
         $survey = Survey::model()->findByPk($iSurveyID);
         $sBaseLanguage = $survey->language;
         // Abort if survey is active
         if ($survey->active !== 'N') {
             Yii::app()->setFlashMessage(gT("You can't insert a new question when the survey is active."), 'error');
             $this->getController()->redirect(array("/admin/survey/sa/view/surveyid/" . $survey->sid), "refresh");
         }
         if (strlen(Yii::app()->request->getPost('title')) < 1) {
             Yii::app()->setFlashMessage(gT("The question could not be added. You must enter at least a question code."), 'error');
         } else {
             // For Bootstrap Version usin YiiWheels switch :
             $_POST['mandatory'] = Yii::app()->request->getPost('mandatory') == '1' ? 'Y' : 'N';
             $_POST['other'] = Yii::app()->request->getPost('other') == '1' ? 'Y' : 'N';
             if (Yii::app()->request->getPost('questionposition', "") != "") {
                 $iQuestionOrder = intval(Yii::app()->request->getPost('questionposition'));
                 //Need to renumber all questions on or after this
                 $sQuery = "UPDATE {{questions}} SET question_order=question_order+1 WHERE gid=:gid AND question_order >= :order";
                 Yii::app()->db->createCommand($sQuery)->bindValues(array(':gid' => $iQuestionGroupID, ':order' => $iQuestionOrder))->query();
             } else {
                 $iQuestionOrder = getMaxQuestionOrder($iQuestionGroupID, $iSurveyID);
                 $iQuestionOrder++;
             }
             $sQuestionText = Yii::app()->request->getPost('question_' . $sBaseLanguage, '');
             $sQuestionHelp = Yii::app()->request->getPost('help_' . $sBaseLanguage, '');
             // Fix bug with FCKEditor saving strange BR types : in rules ?
             $sQuestionText = $oFixCKeditor->fixCKeditor($sQuestionText);
             $sQuestionHelp = $oFixCKeditor->fixCKeditor($sQuestionHelp);
             $iQuestionID = 0;
             $oQuestion = new Question();
             $oQuestion->sid = $iSurveyID;
             $oQuestion->gid = $iQuestionGroupID;
             $oQuestion->type = Yii::app()->request->getPost('type');
             $oQuestion->title = Yii::app()->request->getPost('title');
             $oQuestion->question = $sQuestionText;
             $oQuestion->preg = Yii::app()->request->getPost('preg');
             $oQuestion->help = $sQuestionHelp;
             $oQuestion->other = Yii::app()->request->getPost('other');
             // For Bootstrap Version usin YiiWheels switch :
             $oQuestion->mandatory = Yii::app()->request->getPost('mandatory');
             $oQuestion->other = Yii::app()->request->getPost('other');
             $oQuestion->relevance = Yii::app()->request->getPost('relevance');
             $oQuestion->question_order = $iQuestionOrder;
             $oQuestion->language = $sBaseLanguage;
             $oQuestion->save();
             if ($oQuestion) {
                 $iQuestionID = $oQuestion->qid;
             }
             $aErrors = $oQuestion->getErrors();
             if (count($aErrors)) {
                 foreach ($aErrors as $sAttribute => $aStringErrors) {
                     foreach ($aStringErrors as $sStringErrors) {
                         Yii::app()->setFlashMessage(sprintf(gT("Question could not be created with error on %s: %s"), $sAttribute, $sStringErrors), 'error');
                     }
                 }
             }
             // Add other languages
             if ($iQuestionID) {
                 $addlangs = Survey::model()->findByPk($iSurveyID)->additionalLanguages;
                 foreach ($addlangs as $alang) {
                     if ($alang != "") {
                         $langqid = 0;
                         $oQuestion = new Question();
                         $oQuestion->qid = $iQuestionID;
                         $oQuestion->sid = $iSurveyID;
                         $oQuestion->gid = $iQuestionGroupID;
                         $oQuestion->type = Yii::app()->request->getPost('type');
                         $oQuestion->title = Yii::app()->request->getPost('title');
                         $oQuestion->question = Yii::app()->request->getPost('question_' . $alang);
                         $oQuestion->preg = Yii::app()->request->getPost('preg');
                         $oQuestion->help = Yii::app()->request->getPost('help_' . $alang);
                         $oQuestion->other = Yii::app()->request->getPost('other');
                         $oQuestion->mandatory = Yii::app()->request->getPost('mandatory');
                         $oQuestion->relevance = Yii::app()->request->getPost('relevance');
                         $oQuestion->question_order = $iQuestionOrder;
                         $oQuestion->language = $alang;
                         switchMSSQLIdentityInsert('questions', true);
                         // Not sure for this one ?
                         $oQuestion->save();
                         switchMSSQLIdentityInsert('questions', false);
                         if ($oQuestion) {
                             $langqid = $oQuestion->qid;
                         }
                         $aErrors = $oQuestion->getErrors();
                         if (count($aErrors)) {
                             foreach ($aErrors as $sAttribute => $aStringErrors) {
                                 foreach ($aStringErrors as $sStringErrors) {
                                     Yii::app()->setFlashMessage(sprintf(gT("Question in language %s could not be created with error on %s: %s"), $alang, $sAttribute, $sStringErrors), 'error');
                                 }
                             }
                         }
                         #                            if (!$langqid)
                         #                            {
                         #                                Yii::app()->setFlashMessage(gT("Question in language %s could not be created."),'error');
                         #                            }
                     }
                 }
             }
             if (!$iQuestionID) {
                 Yii::app()->setFlashMessage(gT("Question could not be created."), 'error');
             } else {
                 /**
                  *
                  * Copy Question
                  *
                  */
                 if ($sAction == 'copyquestion') {
                     if (returnGlobal('copysubquestions') == "Y") {
                         $aSQIDMappings = array();
                         $r1 = Question::model()->getSubQuestions(returnGlobal('oldqid'));
                         $aSubQuestions = $r1->readAll();
                         foreach ($aSubQuestions as $qr1) {
                             $qr1['parent_qid'] = $iQuestionID;
                             if (isset($aSQIDMappings[$qr1['qid']])) {
                                 $qr1['qid'] = $aSQIDMappings[$qr1['qid']];
                             } else {
                                 $oldqid = $qr1['qid'];
                                 unset($qr1['qid']);
                             }
                             $qr1['gid'] = $iQuestionGroupID;
                             $iInsertID = Question::model()->insertRecords($qr1);
                             if (!isset($qr1['qid'])) {
                                 $aSQIDMappings[$oldqid] = $iInsertID;
                             }
                         }
                     }
                     if (returnGlobal('copyanswers') == "Y") {
                         $r1 = Answer::model()->getAnswers(returnGlobal('oldqid'));
                         $aAnswerOptions = $r1->readAll();
                         foreach ($aAnswerOptions as $qr1) {
                             Answer::model()->insertRecords(array('qid' => $iQuestionID, 'code' => $qr1['code'], 'answer' => $qr1['answer'], 'assessment_value' => $qr1['assessment_value'], 'sortorder' => $qr1['sortorder'], 'language' => $qr1['language'], 'scale_id' => $qr1['scale_id']));
                         }
                     }
                     /**
                      * Copy attribute
                      */
                     if (returnGlobal('copyattributes') == "Y") {
                         $oOldAttributes = QuestionAttribute::model()->findAll("qid=:qid", array("qid" => returnGlobal('oldqid')));
                         foreach ($oOldAttributes as $oOldAttribute) {
                             $attribute = new QuestionAttribute();
                             $attribute->qid = $iQuestionID;
                             $attribute->value = $oOldAttribute->value;
                             $attribute->attribute = $oOldAttribute->attribute;
                             $attribute->language = $oOldAttribute->language;
                             $attribute->save();
                         }
                     }
                     // Since 2.5, user can edit attribute while copying
                     $qattributes = questionAttributes();
                     $validAttributes = $qattributes[Yii::app()->request->getPost('type')];
                     $aLanguages = array_merge(array(Survey::model()->findByPk($iSurveyID)->language), Survey::model()->findByPk($iSurveyID)->additionalLanguages);
                     foreach ($validAttributes as $validAttribute) {
                         if ($validAttribute['i18n']) {
                             foreach ($aLanguages as $sLanguage) {
                                 $value = Yii::app()->request->getPost($validAttribute['name'] . '_' . $sLanguage);
                                 $iInsertCount = QuestionAttribute::model()->findAllByAttributes(array('attribute' => $validAttribute['name'], 'qid' => $iQuestionID, 'language' => $sLanguage));
                                 if (count($iInsertCount) > 0) {
                                     if ($value != '') {
                                         QuestionAttribute::model()->updateAll(array('value' => $value), 'attribute=:attribute AND qid=:qid AND language=:language', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID, ':language' => $sLanguage));
                                     } else {
                                         QuestionAttribute::model()->deleteAll('attribute=:attribute AND qid=:qid AND language=:language', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID, ':language' => $sLanguage));
                                     }
                                 } elseif ($value != '') {
                                     $attribute = new QuestionAttribute();
                                     $attribute->qid = $iQuestionID;
                                     $attribute->value = $value;
                                     $attribute->attribute = $validAttribute['name'];
                                     $attribute->language = $sLanguage;
                                     $attribute->save();
                                 }
                             }
                         } else {
                             $value = Yii::app()->request->getPost($validAttribute['name']);
                             if ($validAttribute['name'] == 'multiflexible_step' && trim($value) != '') {
                                 $value = floatval($value);
                                 if ($value == 0) {
                                     $value = 1;
                                 }
                             }
                             $iInsertCount = QuestionAttribute::model()->findAllByAttributes(array('attribute' => $validAttribute['name'], 'qid' => $iQuestionID));
                             if (count($iInsertCount) > 0) {
                                 if ($value != $validAttribute['default'] && trim($value) != "") {
                                     QuestionAttribute::model()->updateAll(array('value' => $value), 'attribute=:attribute AND qid=:qid', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID));
                                 } else {
                                     QuestionAttribute::model()->deleteAll('attribute=:attribute AND qid=:qid', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID));
                                 }
                             } elseif ($value != $validAttribute['default'] && trim($value) != "") {
                                 $attribute = new QuestionAttribute();
                                 $attribute->qid = $iQuestionID;
                                 $attribute->value = $value;
                                 $attribute->attribute = $validAttribute['name'];
                                 $attribute->save();
                             }
                         }
                     }
                 } else {
                     $qattributes = questionAttributes();
                     $validAttributes = $qattributes[Yii::app()->request->getPost('type')];
                     $aLanguages = array_merge(array(Survey::model()->findByPk($iSurveyID)->language), Survey::model()->findByPk($iSurveyID)->additionalLanguages);
                     foreach ($validAttributes as $validAttribute) {
                         if ($validAttribute['i18n']) {
                             foreach ($aLanguages as $sLanguage) {
                                 $value = Yii::app()->request->getPost($validAttribute['name'] . '_' . $sLanguage);
                                 $iInsertCount = QuestionAttribute::model()->findAllByAttributes(array('attribute' => $validAttribute['name'], 'qid' => $iQuestionID, 'language' => $sLanguage));
                                 if (count($iInsertCount) > 0) {
                                     if ($value != '') {
                                         QuestionAttribute::model()->updateAll(array('value' => $value), 'attribute=:attribute AND qid=:qid AND language=:language', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID, ':language' => $sLanguage));
                                     } else {
                                         QuestionAttribute::model()->deleteAll('attribute=:attribute AND qid=:qid AND language=:language', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID, ':language' => $sLanguage));
                                     }
                                 } elseif ($value != '') {
                                     $attribute = new QuestionAttribute();
                                     $attribute->qid = $iQuestionID;
                                     $attribute->value = $value;
                                     $attribute->attribute = $validAttribute['name'];
                                     $attribute->language = $sLanguage;
                                     $attribute->save();
                                 }
                             }
                         } else {
                             $value = Yii::app()->request->getPost($validAttribute['name']);
                             if ($validAttribute['name'] == 'multiflexible_step' && trim($value) != '') {
                                 $value = floatval($value);
                                 if ($value == 0) {
                                     $value = 1;
                                 }
                             }
                             $iInsertCount = QuestionAttribute::model()->findAllByAttributes(array('attribute' => $validAttribute['name'], 'qid' => $iQuestionID));
                             if (count($iInsertCount) > 0) {
                                 if ($value != $validAttribute['default'] && trim($value) != "") {
                                     QuestionAttribute::model()->updateAll(array('value' => $value), 'attribute=:attribute AND qid=:qid', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID));
                                 } else {
                                     QuestionAttribute::model()->deleteAll('attribute=:attribute AND qid=:qid', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID));
                                 }
                             } elseif ($value != $validAttribute['default'] && trim($value) != "") {
                                 $attribute = new QuestionAttribute();
                                 $attribute->qid = $iQuestionID;
                                 $attribute->value = $value;
                                 $attribute->attribute = $validAttribute['name'];
                                 $attribute->save();
                             }
                         }
                     }
                 }
                 Question::model()->updateQuestionOrder($iQuestionGroupID, $iSurveyID);
                 Yii::app()->session['flashmessage'] = gT("Question was successfully added.");
             }
         }
         LimeExpressionManager::SetDirtyFlag();
         // so refreshes syntax highlighting
         if ($sDBOutput != '') {
             echo $sDBOutput;
         } else {
             //admin/survey/sa/view/surveyid/
             $this->getController()->redirect(array('admin/questions/sa/view/surveyid/' . $iSurveyID . '/gid/' . $iQuestionGroupID . '/qid/' . $iQuestionID));
         }
     }
     /**
      * Update question
      */
     if ($sAction == "updatequestion" && Permission::model()->hasSurveyPermission($iSurveyID, 'surveycontent', 'update')) {
         LimeExpressionManager::RevertUpgradeConditionsToRelevance($iSurveyID);
         $cqr = Question::model()->findByAttributes(array('qid' => $iQuestionID));
         $oldtype = $cqr['type'];
         $oldgid = $cqr['gid'];
         $survey = Survey::model()->findByPk($iSurveyID);
         // If the survey is activate the question type may not be changed
         if ($survey->active !== 'N') {
             $sQuestionType = $oldtype;
         } else {
             $sQuestionType = Yii::app()->request->getPost('type');
         }
         // Remove invalid question attributes on saving
         $qattributes = questionAttributes();
         $criteria = new CDbCriteria();
         $criteria->compare('qid', $iQuestionID);
         if (isset($qattributes[$sQuestionType])) {
             $validAttributes = $qattributes[$sQuestionType];
             foreach ($validAttributes as $validAttribute) {
                 $criteria->compare('attribute', '<>' . $validAttribute['name']);
             }
         }
         QuestionAttribute::model()->deleteAll($criteria);
         $aLanguages = array_merge(array(Survey::model()->findByPk($iSurveyID)->language), Survey::model()->findByPk($iSurveyID)->additionalLanguages);
         //now save all valid attributes
         $validAttributes = $qattributes[$sQuestionType];
         foreach ($validAttributes as $validAttribute) {
             if ($validAttribute['i18n']) {
                 foreach ($aLanguages as $sLanguage) {
                     // TODO sanitise XSS
                     $value = Yii::app()->request->getPost($validAttribute['name'] . '_' . $sLanguage);
                     $iInsertCount = QuestionAttribute::model()->findAllByAttributes(array('attribute' => $validAttribute['name'], 'qid' => $iQuestionID, 'language' => $sLanguage));
                     if (count($iInsertCount) > 0) {
                         if ($value != '') {
                             QuestionAttribute::model()->updateAll(array('value' => $value), 'attribute=:attribute AND qid=:qid AND language=:language', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID, ':language' => $sLanguage));
                         } else {
                             QuestionAttribute::model()->deleteAll('attribute=:attribute AND qid=:qid AND language=:language', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID, ':language' => $sLanguage));
                         }
                     } elseif ($value != '') {
                         $attribute = new QuestionAttribute();
                         $attribute->qid = $iQuestionID;
                         $attribute->value = $value;
                         $attribute->attribute = $validAttribute['name'];
                         $attribute->language = $sLanguage;
                         $attribute->save();
                     }
                 }
             } else {
                 $value = Yii::app()->request->getPost($validAttribute['name']);
                 if ($validAttribute['name'] == 'multiflexible_step' && trim($value) != '') {
                     $value = floatval($value);
                     if ($value == 0) {
                         $value = 1;
                     }
                 }
                 $iInsertCount = QuestionAttribute::model()->findAllByAttributes(array('attribute' => $validAttribute['name'], 'qid' => $iQuestionID));
                 if (count($iInsertCount) > 0) {
                     if ($value != $validAttribute['default'] && trim($value) != "") {
                         QuestionAttribute::model()->updateAll(array('value' => $value), 'attribute=:attribute AND qid=:qid', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID));
                     } else {
                         QuestionAttribute::model()->deleteAll('attribute=:attribute AND qid=:qid', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID));
                     }
                 } elseif ($value != $validAttribute['default'] && trim($value) != "") {
                     $attribute = new QuestionAttribute();
                     $attribute->qid = $iQuestionID;
                     $attribute->value = $value;
                     $attribute->attribute = $validAttribute['name'];
                     $attribute->save();
                 }
             }
         }
         $aQuestionTypeList = getQuestionTypeList('', 'array');
         // These are the questions types that have no answers and therefore we delete the answer in that case
         $iAnswerScales = $aQuestionTypeList[$sQuestionType]['answerscales'];
         $iSubquestionScales = $aQuestionTypeList[$sQuestionType]['subquestions'];
         // These are the questions types that have the other option therefore we set everything else to 'No Other'
         if ($sQuestionType != "L" && $sQuestionType != "!" && $sQuestionType != "P" && $sQuestionType != "M") {
             $_POST['other'] = 'N';
         }
         // These are the questions types that have no validation - so zap it accordingly
         if ($sQuestionType == "!" || $sQuestionType == "L" || $sQuestionType == "M" || $sQuestionType == "P" || $sQuestionType == "F" || $sQuestionType == "H" || $sQuestionType == "X" || $sQuestionType == "") {
             $_POST['preg'] = '';
         }
         // For Bootstrap Version usin YiiWheels switch :
         $_POST['mandatory'] = Yii::app()->request->getPost('mandatory') == '1' ? 'Y' : 'N';
         $_POST['other'] = Yii::app()->request->getPost('other') == '1' ? 'Y' : 'N';
         // These are the questions types that have no mandatory property - so zap it accordingly
         if ($sQuestionType == "X" || $sQuestionType == "|") {
             $_POST['mandatory'] = 'N';
         }
         if ($oldtype != $sQuestionType) {
             // TMSW Condition->Relevance:  Do similar check via EM, but do allow such a change since will be easier to modify relevance
             //Make sure there are no conditions based on this question, since we are changing the type
             $ccresult = Condition::model()->findAllByAttributes(array('cqid' => $iQuestionID));
             $cccount = count($ccresult);
             foreach ($ccresult as $ccr) {
                 $qidarray[] = $ccr['qid'];
             }
             if (isset($qidarray) && $qidarray) {
                 $qidlist = implode(", ", $qidarray);
             }
         }
         if (isset($cccount) && $cccount) {
             Yii::app()->setFlashMessage(gT("Question could not be updated. There are conditions for other questions that rely on the answers to this question and changing the type will cause problems. You must delete these conditions  before you can change the type of this question."), 'error');
         } else {
             if (isset($iQuestionGroupID) && $iQuestionGroupID != "") {
                 //                    $array_result=checkMoveQuestionConstraintsForConditions(sanitize_int($surveyid),sanitize_int($qid), sanitize_int($gid));
                 //                    // If there is no blocking conditions that could prevent this move
                 //
                 //                    if (is_null($array_result['notAbove']) && is_null($array_result['notBelow']))
                 //                    {
                 $aSurveyLanguages = Survey::model()->findByPk($iSurveyID)->additionalLanguages;
                 $sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language;
                 array_push($aSurveyLanguages, $sBaseLanguage);
                 foreach ($aSurveyLanguages as $qlang) {
                     if (isset($qlang) && $qlang != "") {
                         // &eacute; to é and &amp; to & : really needed ? Why not for answers ? (130307)
                         $sQuestionText = Yii::app()->request->getPost('question_' . $qlang, '');
                         $sQuestionHelp = Yii::app()->request->getPost('help_' . $qlang, '');
                         // Fix bug with FCKEditor saving strange BR types : in rules ?
                         $sQuestionText = $oFixCKeditor->fixCKeditor($sQuestionText);
                         $sQuestionHelp = $oFixCKeditor->fixCKeditor($sQuestionHelp);
                         $udata = array('type' => $sQuestionType, 'title' => Yii::app()->request->getPost('title'), 'question' => $sQuestionText, 'preg' => Yii::app()->request->getPost('preg'), 'help' => $sQuestionHelp, 'gid' => $iQuestionGroupID, 'other' => Yii::app()->request->getPost('other'), 'mandatory' => Yii::app()->request->getPost('mandatory'), 'relevance' => Yii::app()->request->getPost('relevance'));
                         // Update question module
                         if (Yii::app()->request->getPost('module_name') != '') {
                             // The question module is not empty. So it's an external question module.
                             $udata['modulename'] = Yii::app()->request->getPost('module_name');
                         } else {
                             // If it was a module before, we must
                             $udata['modulename'] = '';
                         }
                         if ($oldgid != $iQuestionGroupID) {
                             if (getGroupOrder($iSurveyID, $oldgid) > getGroupOrder($iSurveyID, $iQuestionGroupID)) {
                                 // TMSW Condition->Relevance:  What is needed here?
                                 // Moving question to a 'upper' group
                                 // insert question at the end of the destination group
                                 // this prevent breaking conditions if the target qid is in the dest group
                                 $insertorder = getMaxQuestionOrder($iQuestionGroupID, $iSurveyID) + 1;
                                 $udata = array_merge($udata, array('question_order' => $insertorder));
                             } else {
                                 // Moving question to a 'lower' group
                                 // insert question at the beginning of the destination group
                                 shiftOrderQuestions($iSurveyID, $iQuestionGroupID, 1);
                                 // makes 1 spare room for new question at top of dest group
                                 $udata = array_merge($udata, array('question_order' => 0));
                             }
                         }
                         //$condn = array('sid' => $surveyid, 'qid' => $qid, 'language' => $qlang);
                         $oQuestion = Question::model()->findByPk(array("qid" => $iQuestionID, 'language' => $qlang));
                         foreach ($udata as $k => $v) {
                             $oQuestion->{$k} = $v;
                         }
                         $uqresult = $oQuestion->save();
                         //($uqquery); // or safeDie ("Error Update Question: ".$uqquery."<br />");  // Checked)
                         if (!$uqresult) {
                             $bOnError = true;
                             $aErrors = $oQuestion->getErrors();
                             if (count($aErrors)) {
                                 foreach ($aErrors as $sAttribute => $aStringErrors) {
                                     foreach ($aStringErrors as $sStringErrors) {
                                         Yii::app()->setFlashMessage(sprintf(gT("Question could not be updated with error on %s: %s"), $sAttribute, $sStringErrors), 'error');
                                     }
                                 }
                             } else {
                                 Yii::app()->setFlashMessage(gT("Question could not be updated."), 'error');
                             }
                         }
                     }
                 }
                 // Update the group ID on subquestions, too
                 if ($oldgid != $iQuestionGroupID) {
                     Question::model()->updateAll(array('gid' => $iQuestionGroupID), 'qid=:qid and parent_qid>0', array(':qid' => $iQuestionID));
                     // if the group has changed then fix the sortorder of old and new group
                     Question::model()->updateQuestionOrder($oldgid, $iSurveyID);
                     Question::model()->updateQuestionOrder($iQuestionGroupID, $iSurveyID);
                     // If some questions have conditions set on this question's answers
                     // then change the cfieldname accordingly
                     fixMovedQuestionConditions($iQuestionID, $oldgid, $iQuestionGroupID);
                 }
                 // Update subquestions
                 if ($oldtype != $sQuestionType) {
                     Question::model()->updateAll(array('type' => $sQuestionType), 'parent_qid=:qid', array(':qid' => $iQuestionID));
                 }
                 // Update subquestions if question module
                 if (Yii::app()->request->getPost('module_name') != '') {
                     // The question module is not empty. So it's an external question module.
                     Question::model()->updateAll(array('modulename' => Yii::app()->request->getPost('module_name')), 'parent_qid=:qid', array(':qid' => $iQuestionID));
                 } else {
                     // If it was a module before, we must
                     Question::model()->updateAll(array('modulename' => ''), 'parent_qid=:qid', array(':qid' => $iQuestionID));
                 }
                 Answer::model()->deleteAllByAttributes(array('qid' => $iQuestionID), 'scale_id >= :scale_id', array(':scale_id' => $iAnswerScales));
                 // Remove old subquestion scales
                 Question::model()->deleteAllByAttributes(array('parent_qid' => $iQuestionID), 'scale_id >= :scale_id', array(':scale_id' => $iSubquestionScales));
                 if (!isset($bOnError) || !$bOnError) {
                     // This really a quick hack and need a better system
                     Yii::app()->setFlashMessage(gT("Question was successfully saved."));
                 }
                 //                    }
                 //                    else
                 //                    {
                 //
                 //                        // There are conditions constraints: alert the user
                 //                        $errormsg="";
                 //                        if (!is_null($array_result['notAbove']))
                 //                        {
                 //                            $errormsg.=gT("This question relies on other question's answers and can't be moved above groupId:","js")
                 //                            . " " . $array_result['notAbove'][0][0] . " " . gT("in position","js")." ".$array_result['notAbove'][0][1]."\\n"
                 //                            . gT("See conditions:")."\\n";
                 //
                 //                            foreach ($array_result['notAbove'] as $notAboveCond)
                 //                            {
                 //                                $errormsg.="- cid:". $notAboveCond[3]."\\n";
                 //                            }
                 //
                 //                        }
                 //                        if (!is_null($array_result['notBelow']))
                 //                        {
                 //                            $errormsg.=gT("Some questions rely on this question's answers. You can't move this question below groupId:","js")
                 //                            . " " . $array_result['notBelow'][0][0] . " " . gT("in position","js")." ".$array_result['notBelow'][0][1]."\\n"
                 //                            . gT("See conditions:")."\\n";
                 //
                 //                            foreach ($array_result['notBelow'] as $notBelowCond)
                 //                            {
                 //                                $errormsg.="- cid:". $notBelowCond[3]."\\n";
                 //                            }
                 //                        }
                 //
                 //                        $databaseoutput .= "<script type=\"text/javascript\">\n<!--\n alert(\"$errormsg\")\n //-->\n</script>\n";
                 //                        $gid= $oldgid; // group move impossible ==> keep display on oldgid
                 //                    }
             } else {
                 Yii::app()->setFlashMessage(gT("Question could not be updated"), 'error');
             }
         }
         LimeExpressionManager::UpgradeConditionsToRelevance($iSurveyID);
         if ($sDBOutput != '') {
             echo $sDBOutput;
         } else {
             $closeAfterSave = Yii::app()->request->getPost('close-after-save') === 'true';
             if ($closeAfterSave) {
                 // Redirect to summary
                 $this->getController()->redirect(array('admin/questions/sa/view/surveyid/' . $iSurveyID . '/gid/' . $iQuestionGroupID . '/qid/' . $iQuestionID));
             } else {
                 // Redirect to edit
                 $this->getController()->redirect(array('admin/questions/sa/editquestion/surveyid/' . $iSurveyID . '/gid/' . $iQuestionGroupID . '/qid/' . $iQuestionID));
                 // This works too: $this->getController()->redirect(Yii::app()->request->urlReferrer);
             }
         }
     }
     /**
      * updatesurveylocalesettings
      */
     if ($sAction == "updatesurveylocalesettings" && Permission::model()->hasSurveyPermission($iSurveyID, 'surveylocale', 'update')) {
         $languagelist = Survey::model()->findByPk($iSurveyID)->additionalLanguages;
         $languagelist[] = Survey::model()->findByPk($iSurveyID)->language;
         Yii::app()->loadHelper('database');
         foreach ($languagelist as $langname) {
             if ($langname) {
                 $url = Yii::app()->request->getPost('url_' . $langname);
                 if ($url == 'http://') {
                     $url = "";
                 }
                 $sURLDescription = html_entity_decode(Yii::app()->request->getPost('urldescrip_' . $langname), ENT_QUOTES, "UTF-8");
                 $sURL = html_entity_decode(Yii::app()->request->getPost('url_' . $langname), ENT_QUOTES, "UTF-8");
                 // Fix bug with FCKEditor saving strange BR types
                 $short_title = Yii::app()->request->getPost('short_title_' . $langname);
                 $description = Yii::app()->request->getPost('description_' . $langname);
                 $welcome = Yii::app()->request->getPost('welcome_' . $langname);
                 $endtext = Yii::app()->request->getPost('endtext_' . $langname);
                 $short_title = $oFixCKeditor->fixCKeditor($short_title);
                 $description = $oFixCKeditor->fixCKeditor($description);
                 $welcome = $oFixCKeditor->fixCKeditor($welcome);
                 $endtext = $oFixCKeditor->fixCKeditor($endtext);
                 $data = array('surveyls_title' => $short_title, 'surveyls_description' => $description, 'surveyls_welcometext' => $welcome, 'surveyls_endtext' => $endtext, 'surveyls_url' => $sURL, 'surveyls_urldescription' => $sURLDescription, 'surveyls_dateformat' => Yii::app()->request->getPost('dateformat_' . $langname), 'surveyls_numberformat' => Yii::app()->request->getPost('numberformat_' . $langname));
                 $SurveyLanguageSetting = SurveyLanguageSetting::model()->findByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $langname));
                 $SurveyLanguageSetting->attributes = $data;
                 $SurveyLanguageSetting->save();
                 // save the change to database
             }
         }
         //Yii::app()->session['flashmessage'] = gT("Survey text elements successfully saved.");
         ////////////////////////////////////////////////////////////////////////////////////
         // General settings (copy / paste from surveyadmin::update)
         // Preload survey
         $oSurvey = Survey::model()->findByPk($iSurveyID);
         // Save plugin settings.
         $pluginSettings = App()->request->getPost('plugin', array());
         foreach ($pluginSettings as $plugin => $settings) {
             $settingsEvent = new PluginEvent('newSurveySettings');
             $settingsEvent->set('settings', $settings);
             $settingsEvent->set('survey', $iSurveyID);
             App()->getPluginManager()->dispatchEvent($settingsEvent, $plugin);
         }
         /* Start to fix some param before save (TODO : use models directly ?) */
         /* Date management */
         Yii::app()->loadHelper('surveytranslator');
         $formatdata = getDateFormatData(Yii::app()->session['dateformat']);
         Yii::app()->loadLibrary('Date_Time_Converter');
         $startdate = App()->request->getPost('startdate');
         if (trim($startdate) == "") {
             $startdate = null;
         } else {
             Yii::app()->loadLibrary('Date_Time_Converter');
             $datetimeobj = new date_time_converter($startdate, $formatdata['phpdate'] . ' H:i');
             //new Date_Time_Converter($startdate,$formatdata['phpdate'].' H:i');
             $startdate = $datetimeobj->convert("Y-m-d H:i:s");
         }
         $expires = App()->request->getPost('expires');
         if (trim($expires) == "") {
             $expires = null;
         } else {
             $datetimeobj = new date_time_converter($expires, $formatdata['phpdate'] . ' H:i');
             //new Date_Time_Converter($expires, $formatdata['phpdate'].' H:i');
             $expires = $datetimeobj->convert("Y-m-d H:i:s");
         }
         // We have $oSurvey : update and save it
         $oSurvey->owner_id = Yii::app()->request->getPost('owner_id');
         $oSurvey->admin = Yii::app()->request->getPost('admin');
         $oSurvey->expires = $expires;
         $oSurvey->startdate = $startdate;
         $oSurvey->faxto = App()->request->getPost('faxto');
         $oSurvey->format = App()->request->getPost('format');
         $oSurvey->template = Yii::app()->request->getPost('template');
         $oSurvey->assessments = App()->request->getPost('assessments');
         $oSurvey->additional_languages = Yii::app()->request->getPost('languageids');
         if ($oSurvey->active != 'Y') {
             $oSurvey->anonymized = App()->request->getPost('anonymized');
             $oSurvey->savetimings = App()->request->getPost('savetimings');
             $oSurvey->datestamp = App()->request->getPost('datestamp');
             $oSurvey->ipaddr = App()->request->getPost('ipaddr');
             $oSurvey->refurl = App()->request->getPost('refurl');
         }
         $oSurvey->publicgraphs = App()->request->getPost('publicgraphs');
         $oSurvey->usecookie = App()->request->getPost('usecookie');
         $oSurvey->allowregister = App()->request->getPost('allowregister');
         $oSurvey->allowsave = App()->request->getPost('allowsave');
         $oSurvey->navigationdelay = App()->request->getPost('navigationdelay');
         $oSurvey->printanswers = App()->request->getPost('printanswers');
         $oSurvey->publicstatistics = App()->request->getPost('publicstatistics');
         $oSurvey->autoredirect = App()->request->getPost('autoredirect');
         $oSurvey->showxquestions = App()->request->getPost('showxquestions');
         $oSurvey->showgroupinfo = App()->request->getPost('showgroupinfo');
         $oSurvey->showqnumcode = App()->request->getPost('showqnumcode');
         $oSurvey->shownoanswer = App()->request->getPost('shownoanswer');
         $oSurvey->showwelcome = App()->request->getPost('showwelcome');
         $oSurvey->allowprev = App()->request->getPost('allowprev');
         $oSurvey->questionindex = App()->request->getPost('questionindex');
         $oSurvey->nokeyboard = App()->request->getPost('nokeyboard');
         $oSurvey->showprogress = App()->request->getPost('showprogress');
         $oSurvey->listpublic = App()->request->getPost('public');
         $oSurvey->htmlemail = App()->request->getPost('htmlemail');
         $oSurvey->sendconfirmation = App()->request->getPost('sendconfirmation');
         $oSurvey->tokenanswerspersistence = App()->request->getPost('tokenanswerspersistence');
         $oSurvey->alloweditaftercompletion = App()->request->getPost('alloweditaftercompletion');
         $oSurvey->usecaptcha = Survey::transcribeCaptchaOptions();
         $oSurvey->emailresponseto = App()->request->getPost('emailresponseto');
         $oSurvey->emailnotificationto = App()->request->getPost('emailnotificationto');
         $oSurvey->googleanalyticsapikey = App()->request->getPost('googleanalyticsapikey');
         $oSurvey->googleanalyticsstyle = App()->request->getPost('googleanalyticsstyle');
         $oSurvey->tokenlength = App()->request->getPost('tokenlength');
         $oSurvey->adminemail = App()->request->getPost('adminemail');
         $oSurvey->bounce_email = App()->request->getPost('bounce_email');
         if ($oSurvey->save()) {
             Yii::app()->setFlashMessage(gT("Survey settings were successfully saved."));
         } else {
             Yii::app()->setFlashMessage(gT("Survey could not be updated."), "error");
             tracevar($oSurvey->getErrors());
         }
         /* Reload $oSurvey (language are fixed : need it ?) */
         $oSurvey = Survey::model()->findByPk($iSurveyID);
         /* Delete removed language cleanLanguagesFromSurvey do it already why redo it (cleanLanguagesFromSurvey must be moved to model) ?*/
         $aAvailableLanguage = $oSurvey->getAllLanguages();
         $oCriteria = new CDbCriteria();
         $oCriteria->compare('surveyls_survey_id', $iSurveyID);
         $oCriteria->addNotInCondition('surveyls_language', $aAvailableLanguage);
         SurveyLanguageSetting::model()->deleteAll($oCriteria);
         /* Add new language fixLanguageConsistency do it ?*/
         foreach ($oSurvey->additionalLanguages as $sLang) {
             if ($sLang) {
                 $oLanguageSettings = SurveyLanguageSetting::model()->find('surveyls_survey_id=:surveyid AND surveyls_language=:langname', array(':surveyid' => $iSurveyID, ':langname' => $sLang));
                 if (!$oLanguageSettings) {
                     $oLanguageSettings = new SurveyLanguageSetting();
                     $languagedetails = getLanguageDetails($sLang);
                     $oLanguageSettings->surveyls_survey_id = $iSurveyID;
                     $oLanguageSettings->surveyls_language = $sLang;
                     $oLanguageSettings->surveyls_title = '';
                     // Not in default model ?
                     $oLanguageSettings->surveyls_dateformat = $languagedetails['dateformat'];
                     if (!$oLanguageSettings->save()) {
                         Yii::app()->setFlashMessage(gT("Survey language could not be created."), "error");
                         tracevar($oLanguageSettings->getErrors());
                     }
                 }
             }
         }
         /* Language fix : remove and add question/group */
         cleanLanguagesFromSurvey($iSurveyID, implode(" ", $oSurvey->additionalLanguages));
         fixLanguageConsistency($iSurveyID, implode(" ", $oSurvey->additionalLanguages));
         // Url params in json
         $aURLParams = json_decode(Yii::app()->request->getPost('allurlparams'), true);
         SurveyURLParameter::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         if (isset($aURLParams)) {
             foreach ($aURLParams as $aURLParam) {
                 $aURLParam['parameter'] = trim($aURLParam['parameter']);
                 if ($aURLParam['parameter'] == '' || !preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $aURLParam['parameter']) || $aURLParam['parameter'] == 'sid' || $aURLParam['parameter'] == 'newtest' || $aURLParam['parameter'] == 'token' || $aURLParam['parameter'] == 'lang') {
                     continue;
                     // this parameter name seems to be invalid - just ignore it
                 }
                 unset($aURLParam['act']);
                 unset($aURLParam['title']);
                 unset($aURLParam['id']);
                 if ($aURLParam['targetqid'] == '') {
                     $aURLParam['targetqid'] = NULL;
                 }
                 if ($aURLParam['targetsqid'] == '') {
                     $aURLParam['targetsqid'] = NULL;
                 }
                 $aURLParam['sid'] = $iSurveyID;
                 $param = new SurveyURLParameter();
                 foreach ($aURLParam as $k => $v) {
                     $param->{$k} = $v;
                 }
                 $param->save();
             }
         }
         ////////////////////////////////////////
         if ($sDBOutput != '') {
             echo $sDBOutput;
         } else {
             if (Yii::app()->request->getPost('close-after-save') === 'true') {
                 $this->getController()->redirect(array('admin/survey/sa/view/surveyid/' . $iSurveyID));
             }
             $this->getController()->redirect(array('/admin/survey/sa/editlocalsettings/surveyid/' . $iSurveyID));
         }
     }
     $this->getController()->redirect(array("/admin"), "refresh");
 }
예제 #7
0
 private function _getAssessmentPostData($iSurveyID, $language)
 {
     if (!isset($_POST['gid'])) {
         $_POST['gid'] = 0;
     }
     return array('sid' => $iSurveyID, 'scope' => sanitize_paranoid_string($_POST['scope']), 'gid' => sanitize_int($_POST['gid']), 'minimum' => intval($_POST['minimum']), 'maximum' => intval($_POST['maximum']), 'name' => $_POST['name_' . $language], 'language' => $language, 'message' => $_POST['assessmentmessage_' . $language]);
 }
예제 #8
0
 private function _getUpdateKey($sSubAction)
 {
     $updatekey = getGlobalSetting("updatekey");
     if ($sSubAction == 'keyupdate') {
         $updatekey = sanitize_paranoid_string($_POST['updatekey']);
         setGlobalSetting('updatekey', $updatekey);
         Yii::app()->setConfig("updatekey", $updatekey);
         return $updatekey;
     }
     return $updatekey;
 }
예제 #9
0
     $importtemplateoutput .= "<div class=\"warningheader\">" . $clang->gT("Error") . "</div><br />\n";
     $importtemplateoutput .= sprintf($clang->gT("Demo mode: Uploading templates is disabled."), $basedestdir) . "<br/><br/>\n";
     $importtemplateoutput .= "<br/><input type=\"submit\" onclick=\"window.open('{$scriptname}?action=templates', '_top')\" value=\"" . $clang->gT("Template Editor") . "\"/>\n";
     $importtemplateoutput .= "</div>\n";
     return;
 }
 require "classes/phpzip/phpzip.inc.php";
 //$the_full_file_path = $tempdir . "/" . $_FILES['the_file']['name'];
 $zipfile = $_FILES['the_file']['tmp_name'];
 $z = new PHPZip();
 // Create temporary directory
 // If dangerous content is unzipped
 // then no one will know the path
 $extractdir = tempdir($tempdir);
 $basedestdir = $usertemplaterootdir;
 $newdir = str_replace('.', '', strip_ext(sanitize_paranoid_string($_FILES['the_file']['name'])));
 $destdir = $basedestdir . '/' . $newdir . '/';
 if (!is_writeable($basedestdir)) {
     $importtemplateoutput .= "<div class=\"warningheader\">" . $clang->gT("Error") . "</div><br />\n";
     $importtemplateoutput .= sprintf($clang->gT("Incorrect permissions in your %s folder."), $basedestdir) . "<br/><br/>\n";
     $importtemplateoutput .= "<br/><input type=\"submit\" onclick=\"window.open('{$scriptname}?action=templates', '_top')\" value=\"" . $clang->gT("Template Editor") . "\"/>\n";
     $importtemplateoutput .= "</div>\n";
     return;
 }
 if (!is_dir($destdir)) {
     mkdir($destdir);
 } else {
     $importtemplateoutput .= "<div class=\"warningheader\">" . $clang->gT("Error") . "</div><br />\n";
     $importtemplateoutput .= sprintf($clang->gT("Template '%s' does already exist."), $newdir) . "<br/><br/>\n";
     $importtemplateoutput .= "<br/><input type=\"submit\" onclick=\"window.open('{$scriptname}?action=templates', '_top')\" value=\"" . $clang->gT("Template Editor") . "\"/>\n";
     $importtemplateoutput .= "</div>\n";
예제 #10
0
 *      MA 02110-1301, USA.
 */
require_once "../functions.php";
global $DEBUG;
if ($DEBUG) {
    $starttime_main = microtime(true);
}
ini_set("session.cookie_httponly", 1);
session_start();
if ($_POST['submit'] == "submit") {
    if ($_POST['user'] == "" || $_POST['pass'] == "") {
        $emptyField = true;
    } else {
        $username = @sanitize_paranoid_string($_POST['user']);
        $password = $_POST['pass'];
        $ref = @sanitize_paranoid_string($_POST['ref']);
        $userlogon = checkUser($username, $password);
        if ($userlogon[0]['result']) {
            $_SESSION['login'] = true;
            $_SESSION['userName'] = ucfirst(strtolower($userlogon[0]['username']));
            $_SESSION['userID'] = $userlogon[0]['user_id'];
            $_SESSION['email'] = $userlogon[0]['email'];
            $_SESSION['LAST_ACTIVITY'] = time();
            // define first "last activity" timestamp
            $_SESSION['CREATED'] = time();
            // initialize the session create timestamp
            if ($userlogon[0]['changePass']) {
                $_SESSION['forceChangePass'] = true;
            }
            session_regenerate_id(true);
            // change session ID for the current session an invalidate old session ID
예제 #11
0
 public function vvexport()
 {
     $iSurveyID = sanitize_int(Yii::app()->request->getParam('surveyid'));
     $subaction = Yii::app()->request->getParam('subaction');
     //Exports all responses to a survey in special "Verified Voting" format.
     $clang = $this->getController()->lang;
     if (!hasSurveyPermission($iSurveyID, 'responses', 'export')) {
         return;
     }
     if ($subaction != "export") {
         $selecthide = "";
         $selectshow = "";
         $selectinc = "";
         if (incompleteAnsFilterState() == "incomplete") {
             $selectinc = "selected='selected'";
         } elseif (incompleteAnsFilterState() == "complete") {
             $selecthide = "selected='selected'";
         } else {
             $selectshow = "selected='selected'";
         }
         $data['selectinc'] = $selectinc;
         $data['selecthide'] = $selecthide;
         $data['selectshow'] = $selectshow;
         $data['surveyid'] = $iSurveyID;
         $data['display']['menu_bars']['browse'] = $clang->gT("Export VV file");
         $this->_renderWrappedTemplate('export', 'vv_view', $data);
     } elseif (isset($iSurveyID) && $iSurveyID) {
         //Export is happening
         $extension = sanitize_paranoid_string(returnGlobal('extension'));
         $fn = "vvexport_{$iSurveyID}." . $extension;
         $this->_addHeaders($fn, "text/comma-separated-values", 0, "cache");
         $s = "\t";
         $fieldmap = createFieldMap($iSurveyID, 'full', false, false, getBaseLanguageFromSurveyID($iSurveyID));
         $surveytable = "{{survey_{$iSurveyID}}}";
         Survey::model()->findByPk($iSurveyID)->language;
         $fieldnames = Yii::app()->db->schema->getTable($surveytable)->getColumnNames();
         //Create the human friendly first line
         $firstline = "";
         $secondline = "";
         foreach ($fieldnames as $field) {
             $fielddata = arraySearchByKey($field, $fieldmap, "fieldname", 1);
             if (count($fielddata) < 1) {
                 $firstline .= $field;
             } else {
                 $firstline .= preg_replace('/\\s+/', ' ', strip_tags($fielddata['question']));
             }
             $firstline .= $s;
             $secondline .= $field . $s;
         }
         $vvoutput = $firstline . "\n";
         $vvoutput .= $secondline . "\n";
         $query = "SELECT * FROM " . Yii::app()->db->quoteTableName($surveytable);
         if (incompleteAnsFilterState() == "incomplete") {
             $query .= " WHERE submitdate IS NULL ";
         } elseif (incompleteAnsFilterState() == "complete") {
             $query .= " WHERE submitdate >= '01/01/1980' ";
         }
         $result = Yii::app()->db->createCommand($query)->query();
         foreach ($result->readAll() as $row) {
             foreach ($fieldnames as $field) {
                 if (is_null($row[$field])) {
                     $value = '{question_not_shown}';
                 } else {
                     $value = trim($row[$field]);
                     // sunscreen for the value. necessary for the beach.
                     // careful about the order of these arrays:
                     // lbrace has to be substituted *first*
                     $value = str_replace(array("{", "\n", "\r", "\t"), array("{lbrace}", "{newline}", "{cr}", "{tab}"), $value);
                 }
                 // one last tweak: excel likes to quote values when it
                 // exports as tab-delimited (esp if value contains a comma,
                 // oddly enough).  So we're going to encode a leading quote,
                 // if it occurs, so that we can tell the difference between
                 // strings that "really are" quoted, and those that excel quotes
                 // for us.
                 $value = preg_replace('/^"/', '{quote}', $value);
                 // yay!  that nasty soab won't hurt us now!
                 if ($field == "submitdate" && !$value) {
                     $value = "NULL";
                 }
                 $sun[] = $value;
             }
             $beach = implode($s, $sun);
             $vvoutput .= $beach;
             unset($sun);
             $vvoutput .= "\n";
         }
         echo $vvoutput;
         exit;
     }
 }
 function attributeMapCSV()
 {
     $clang = $this->getController()->lang;
     $sRandomFileName = randomChars(20);
     $sFilePath = Yii::app()->getConfig('tempdir') . DIRECTORY_SEPARATOR . $sRandomFileName;
     $aPathinfo = pathinfo($_FILES['the_file']['name']);
     $sExtension = $aPathinfo['extension'];
     if (strtolower($sExtension) == 'csv') {
         $bMoveFileResult = @move_uploaded_file($_FILES['the_file']['tmp_name'], $sFilePath);
         $errorinupload = '';
         $filterblankemails = Yii::app()->request->getPost('filterbea');
     } else {
         $templateData['error_msg'] = sprintf($clang->gT("This is not a .csv file."), Yii::app()->getConfig('tempdir'));
         $errorinupload = array('error' => $this->upload->display_errors());
         Yii::app()->session['summary'] = array('errorinupload' => $errorinupload);
         $this->_renderWrappedTemplate('participants', array('participantsPanel', 'uploadSummary'), array('aAttributes' => ParticipantAttributeName::model()->getAllAttributes()));
     }
     if (!$bMoveFileResult) {
         $templateData['error_msg'] = sprintf($clang->gT("An error occurred uploading your file. This may be caused by incorrect permissions in your %s folder."), Yii::app()->getConfig('tempdir'));
         $errorinupload = array('error' => $this->upload->display_errors());
         Yii::app()->session['summary'] = array('errorinupload' => $errorinupload);
         $this->_renderWrappedTemplate('participants', array('participantsPanel', 'uploadSummary'), array('aAttributes' => ParticipantAttributeName::model()->getAllAttributes()));
     } else {
         $aData = array('upload_data' => $_FILES['the_file']);
         $sFileName = $_FILES['the_file']['name'];
         $regularfields = array('firstname', 'participant_id', 'lastname', 'email', 'language', 'blacklisted', 'owner_uid');
         $csvread = fopen($sFilePath, 'r');
         $separator = Yii::app()->request->getPost('separatorused');
         $firstline = fgetcsv($csvread, 1000, ',');
         $selectedcsvfields = array();
         foreach ($firstline as $key => $value) {
             $testvalue = preg_replace('/[^(\\x20-\\x7F)]*/', '', $value);
             //Remove invalid characters from string
             if (!in_array(strtolower($testvalue), $regularfields)) {
                 array_push($selectedcsvfields, $value);
             }
             $fieldlist[] = $value;
         }
         $linecount = count(file($sFilePath));
         $attributes = ParticipantAttributeName::model()->model()->getCPDBAttributes();
         $aData = array('attributes' => $attributes, 'firstline' => $selectedcsvfields, 'fullfilepath' => $sRandomFileName, 'linecount' => $linecount - 1, 'filterbea' => $filterblankemails, 'participant_id_exists' => in_array('participant_id', $fieldlist));
         App()->getClientScript()->registerCssFile(Yii::app()->getConfig('adminstyleurl') . "attributeMapCSV.css");
         App()->getClientScript()->registerPackage('qTip2');
         App()->getClientScript()->registerPackage('jquery-nestedSortable');
         App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('adminscripts') . "attributeMapCSV.js");
         $sAttributeMapJS = "var copyUrl = '" . App()->createUrl("admin/participants/sa/uploadCSV") . "';\n" . "var displayParticipants = '" . App()->createUrl("admin/participants/sa/displayParticipants") . "';\n" . "var mapCSVcancelled = '" . App()->createUrl("admin/participants/sa/mapCSVcancelled") . "';\n" . "var characterset = '" . sanitize_paranoid_string($_POST['characterset']) . "';\n" . "var okBtn = '" . $clang->gT("OK") . "';\n" . "var processed = '" . $clang->gT("Summary") . "';\n" . "var summary = '" . $clang->gT("Upload summary") . "';\n" . "var notPairedErrorTxt = '" . $clang->gT("You have to pair this field with an existing attribute.") . "';\n" . "var onlyOnePairedErrorTxt = '" . $clang->gT("Only one CSV attribute is mapped with central attribute.") . "';\n" . "var cannotAcceptErrorTxt='" . $clang->gT("This list cannot accept token attributes.") . "';\n" . "var separator = '" . sanitize_paranoid_string($_POST['separatorused']) . "';\n" . "var thefilepath = '" . $sRandomFileName . "';\n" . "var filterblankemails = '" . $filterblankemails . "';\n";
         App()->getClientScript()->registerScript("sAttributeMapJS", $sAttributeMapJS, CClientScript::POS_BEGIN);
         $this->_renderWrappedTemplate('participants', 'attributeMapCSV', $aData);
     }
 }
function check($input, $flags, $min = '', $max = '')
{
    $oldput = $input;
    if ($flags & UTF8) {
        $input = my_utf8_decode($input);
    }
    if ($flags & PARANOID) {
        $input = sanitize_paranoid_string($input, $min, $max);
    }
    if ($flags & INT) {
        $input = sanitize_int($input, $min, $max);
    }
    if ($flags & FLOAT) {
        $input = sanitize_float($input, $min, $max);
    }
    if ($flags & HTML) {
        $input = sanitize_html_string($input, $min, $max);
    }
    if ($flags & LDAP) {
        $input = sanitize_ldap_string($input, $min, $max);
    }
    if ($flags & SYSTEM) {
        $input = sanitize_system_string($input, $min, $max, TRUE);
    }
    if ($input != $oldput) {
        return FALSE;
    }
    return TRUE;
}
function hasTemplateManageRights($userid, $templatefolder)
{
    global $connect;
    global $dbprefix;
    $userid = sanitize_int($userid);
    $templatefolder = sanitize_paranoid_string($templatefolder);
    $query = "SELECT " . db_quote_id('use') . " FROM {$dbprefix}templates_rights WHERE uid=" . $userid . " AND folder LIKE '" . $templatefolder . "'";
    $result = db_execute_assoc($query) or safe_die($connect->ErrorMsg());
    //Safe
    if ($result->RecordCount() == 0) {
        return false;
    }
    $row = $result->FetchRow();
    return $row["use"];
}
예제 #15
0
 $count = 0;
 $invalidCode = 0;
 $duplicateCode = 0;
 require_once "../classes/inputfilter/class.inputfilter_clean.php";
 $myFilter = new InputFilter('', '', 1, 1, 1);
 //First delete all answers
 $query = "delete from " . db_table_name('answers') . " where qid=" . db_quote($qid);
 $result = $connect->Execute($query);
 // Checked
 LimeExpressionManager::RevertUpgradeConditionsToRelevance($surveyid);
 for ($scale_id = 0; $scale_id < $scalecount; $scale_id++) {
     $maxcount = (int) $_POST['answercount_' . $scale_id];
     for ($sortorderid = 1; $sortorderid < $maxcount; $sortorderid++) {
         $code = sanitize_paranoid_string($_POST['code_' . $sortorderid . '_' . $scale_id]);
         if (isset($_POST['oldcode_' . $sortorderid . '_' . $scale_id])) {
             $oldcode = sanitize_paranoid_string($_POST['oldcode_' . $sortorderid . '_' . $scale_id]);
             if ($code !== $oldcode) {
                 $query = 'UPDATE ' . db_table_name('conditions') . ' SET value=' . db_quoteall($code) . ' WHERE cqid=' . db_quote($qid) . ' AND value=' . db_quoteall($oldcode);
                 $connect->execute($query);
             }
         }
         $assessmentvalue = (int) $_POST['assessment_' . $sortorderid . '_' . $scale_id];
         foreach ($alllanguages as $language) {
             $answer = $_POST['answer_' . $language . '_' . $sortorderid . '_' . $scale_id];
             if ($filterxsshtml) {
                 //Sanitize input, strip XSS
                 $answer = $myFilter->process($answer);
             } else {
                 $answer = html_entity_decode($answer, ENT_QUOTES, "UTF-8");
             }
             // Fix bug with FCKEditor saving strange BR types
예제 #16
0
 public function vvexport()
 {
     $iSurveyId = sanitize_int(Yii::app()->request->getParam('surveyid'));
     $subaction = Yii::app()->request->getParam('subaction');
     //Exports all responses to a survey in special "Verified Voting" format.
     if (!Permission::model()->hasSurveyPermission($iSurveyId, 'responses', 'export')) {
         Yii::app()->session['flashmessage'] = gT("You do not have sufficient rights to access this page.");
         $this->getController()->redirect($this->getController()->createUrl("/admin/survey/sa/view/surveyid/{$iSurveyId}"));
     }
     if ($subaction != "export") {
         $aData['selectincansstate'] = incompleteAnsFilterState();
         $aData['surveyid'] = $iSurveyId;
         $aData['display']['menu_bars']['browse'] = gT("Export VV file");
         $fieldmap = createFieldMap($iSurveyId, 'full', false, false, getBaseLanguageFromSurveyID($iSurveyId));
         Survey::model()->findByPk($iSurveyId)->language;
         $surveytable = "{{survey_{$iSurveyId}}}";
         // Control if fieldcode are unique
         $fieldnames = Yii::app()->db->schema->getTable($surveytable)->getColumnNames();
         foreach ($fieldnames as $field) {
             $fielddata = arraySearchByKey($field, $fieldmap, "fieldname", 1);
             $fieldcode[] = viewHelper::getFieldCode($fielddata, array("LEMcompat" => true));
         }
         $aData['uniquefieldcode'] = count(array_unique($fieldcode)) == count($fieldcode);
         // Did we need more control ?
         $aData['vvversionseleted'] = $aData['uniquefieldcode'] ? 2 : 1;
         $this->_renderWrappedTemplate('export', 'vv_view', $aData);
     } elseif (isset($iSurveyId) && $iSurveyId) {
         //Export is happening
         $extension = sanitize_paranoid_string(returnGlobal('extension'));
         $vvVersion = (int) Yii::app()->request->getPost('vvversion');
         $vvVersion = in_array($vvVersion, array(1, 2)) ? $vvVersion : 2;
         // Only 2 version actually, default to 2
         $fn = "vvexport_{$iSurveyId}." . $extension;
         $this->_addHeaders($fn, "text/comma-separated-values", 0, "cache");
         $s = "\t";
         $fieldmap = createFieldMap($iSurveyId, 'full', false, false, getBaseLanguageFromSurveyID($iSurveyId));
         $surveytable = "{{survey_{$iSurveyId}}}";
         Survey::model()->findByPk($iSurveyId)->language;
         $fieldnames = Yii::app()->db->schema->getTable($surveytable)->getColumnNames();
         //Create the human friendly first line
         $firstline = "";
         $secondline = "";
         foreach ($fieldnames as $field) {
             $fielddata = arraySearchByKey($field, $fieldmap, "fieldname", 1);
             if (count($fielddata) < 1) {
                 $firstline .= $field;
             } else {
                 $firstline .= preg_replace('/\\s+/', ' ', strip_tags($fielddata['question']));
             }
             $firstline .= $s;
             if ($vvVersion == 2) {
                 $fieldcode = viewHelper::getFieldCode($fielddata, array("LEMcompat" => true));
                 $fieldcode = $fieldcode ? $fieldcode : $field;
                 // $fieldcode is empty for token if there are no token table
             } else {
                 $fieldcode = $field;
             }
             $secondline .= $fieldcode . $s;
         }
         $vvoutput = $firstline . "\n";
         $vvoutput .= $secondline . "\n";
         $query = "SELECT * FROM " . Yii::app()->db->quoteTableName($surveytable);
         if (incompleteAnsFilterState() == "incomplete") {
             $query .= " WHERE submitdate IS NULL ";
         } elseif (incompleteAnsFilterState() == "complete") {
             $query .= " WHERE submitdate >= '01/01/1980' ";
         }
         $result = Yii::app()->db->createCommand($query)->query();
         echo $vvoutput;
         foreach ($result as $row) {
             foreach ($fieldnames as $field) {
                 if (is_null($row[$field])) {
                     $value = '{question_not_shown}';
                 } else {
                     $value = trim($row[$field]);
                     // sunscreen for the value. necessary for the beach.
                     // careful about the order of these arrays:
                     // lbrace has to be substituted *first*
                     $value = str_replace(array("{", "\n", "\r", "\t"), array("{lbrace}", "{newline}", "{cr}", "{tab}"), $value);
                 }
                 // one last tweak: excel likes to quote values when it
                 // exports as tab-delimited (esp if value contains a comma,
                 // oddly enough).  So we're going to encode a leading quote,
                 // if it occurs, so that we can tell the difference between
                 // strings that "really are" quoted, and those that excel quotes
                 // for us.
                 $value = preg_replace('/^"/', '{quote}', $value);
                 // yay!  that nasty soab won't hurt us now!
                 if ($field == "submitdate" && !$value) {
                     $value = "NULL";
                 }
                 $sun[] = $value;
             }
             /* it is important here to stream output data, line by line
              * in order to avoid huge memory consumption when exporting large
              * quantities of answers */
             echo implode($s, $sun) . "\n";
             unset($sun);
         }
         exit;
     }
 }
예제 #17
0
 private function _getAssessmentPostData($iSurveyID, $language)
 {
     if (!isset($_POST['gid'])) {
         $_POST['gid'] = 0;
     }
     if (Yii::app()->getConfig('filterxsshtml')) {
         $_POST['name_' . $language] = htmlspecialchars($_POST['name_' . $language]);
         $_POST['assessmentmessage_' . $language] = htmlspecialchars($_POST['assessmentmessage_' . $language]);
     }
     return array('sid' => $iSurveyID, 'scope' => sanitize_paranoid_string($_POST['scope']), 'gid' => sanitize_int($_POST['gid']), 'minimum' => sanitize_paranoid_string($_POST['minimum']), 'maximum' => sanitize_paranoid_string($_POST['maximum']), 'name' => $_POST['name_' . $language], 'language' => $language, 'message' => $_POST['assessmentmessage_' . $language]);
 }
예제 #18
0
        public function beforeSurveyPage()
        {
            $oEvent = $this->event;
            $iSurveyId = $oEvent->get('surveyId');

            self::__init();
            $bUse=$this->get('bUse', 'Survey', $iSurveyId);
            if(is_null($bUse))
                $bUse=$this->bUse;
            if(!$bUse)
                return;

            $sToken= Yii::app()->request->getParam('token');
            if($iSurveyId && !$sToken)// Test invalid token ?
            {
                // Get the survey model
                $oSurvey=Survey::model()->find("sid=:sid",array(':sid'=>$iSurveyId));
                if($oSurvey && $oSurvey->active=="Y" && $oSurvey->allowregister=="Y" && tableExists("tokens_{$iSurveyId}"))
                {
                    // Fill parameters
                    $bShowTokenForm=$this->get('bShowTokenForm', 'Survey', $iSurveyId);
                    if(is_null($bShowTokenForm))
                        $bShowTokenForm=$this->bShowTokenForm;
                    $bShowTokenForm=$this->get('use', 'Survey', $iSurveyId);
                    if(is_null($bShowTokenForm))
                        $bShowTokenForm=$this->bUse;
                    Yii::app()->getClientScript()->registerCssFile(Yii::app()->getConfig('publicurl')."plugins/replaceRegister/css/register.css");
                    // We can go
                    $sLanguage = Yii::app()->request->getParam('lang','');
                    if ($sLanguage=="" )
                    {
                        $sLanguage = Survey::model()->findByPk($iSurveyId)->language;
                    }
                    $aSurveyInfo=getSurveyInfo($iSurveyId,$sLanguage);
                    $sAction= Yii::app()->request->getParam('action','view') ;
                    $sHtmlRegistererror="";
                    $sHtmlRegistermessage1=gT("You must be registered to complete this survey");;
                    $sHtmlRegistermessage2=gT("You may register for this survey if you wish to take part.")."<br />\n".gT("Enter your details below, and an email containing the link to participate in this survey will be sent immediately.");
                    $sHtmlRegisterform="";
                    $sHtml="";
                    $bShowForm=true;
                    $bValidMail=false;
                    $bTokenCreate=true;
                    $aExtraParams=array();
                    $aRegisterError=array();
                    $sR_email= Yii::app()->request->getPost('register_email');
                    $sR_firstname= sanitize_xss_string(Yii::app()->request->getPost('register_firstname',""));
                    $sR_lastname= sanitize_xss_string(Yii::app()->request->getPost('register_lastname',""));
                    $sR_lastname= sanitize_xss_string(Yii::app()->request->getPost('register_lastname',""));
                    $aR_attribute=array();
                    $aR_attributeGet=array();
                    $aExtraParams=array();
                    $aMail=array();
                    foreach ($aSurveyInfo['attributedescriptions'] as $field => $aAttribute)
                    {
                        if (!empty($aAttribute['show_register']) && $aAttribute['show_register'] == 'Y')
                        {
                            $aR_attribute[$field]= sanitize_xss_string(Yii::app()->request->getPost('register_'.$field),"");// Need to be filtered ?
                        }
                        elseif($aAttribute['description']==sanitize_paranoid_string($aAttribute['description']) && trim(Yii::app()->request->getQuery($aAttribute['description'],"")) )
                        {
                            $aR_attributeGet[$field]= sanitize_xss_string(trim(Yii::app()->request->getQuery($aAttribute['description'],"")));// Allow prefill with URL (TODO: add an option)
                            $aExtraParams[$aAttribute['description']]=sanitize_xss_string(trim(Yii::app()->request->getParam($aAttribute['description'],"")));
                        }
                    }
                    if($sAction=='register' && !is_null($sR_email) && Yii::app()->request->getPost('changelang')!='changelang')
                    {
                        $bShowForm=false;
                        // captcha
                        $sLoadsecurity=Yii::app()->request->getPost('loadsecurity');
                        $sSecAnswer=(isset($_SESSION['survey_'.$iSurveyId]['secanswer']))?$_SESSION['survey_'.$iSurveyId]['secanswer']:"";
                        $bShowForm=false;
                        $bNoError=true;
                        // Copy paste RegisterController
                        if($sR_email)
                        {
                            //Check that the email is a valid style addressattribute_2
                            if (!validateEmailAddress($sR_email))
                            {
                                $aRegisterError[]= gT("The email you used is not valid. Please try again.");
                            }
                        }
                        else
                        {
                            $aRegisterError[]= gT("The email you used is not valid. Please try again.");// Empty email
                        }
                        // Fill and validate mandatory extra attribute
                        foreach ($aSurveyInfo['attributedescriptions'] as $field => $aAttribute)
                        {
                            if (!empty($aAttribute['show_register']) && $aAttribute['show_register'] == 'Y' && $aAttribute['mandatory'] == 'Y' && ($aR_attribute[$field]=="" || is_null($aR_attribute[$field])) )
                            {
                                $aRegisterError[]= sprintf(gT("%s cannot be left empty").".", $aSurveyInfo['attributecaptions'][$field]);
                            }
                        }
                        // Check the security question's answer : at end because the security question is the last one
                        if (function_exists("ImageCreate") && isCaptchaEnabled('registrationscreen',$aSurveyInfo['usecaptcha']) )
                        {
                            if (!$sLoadsecurity || !$sSecAnswer || $sLoadsecurity != $sSecAnswer)
                            {
                                $aRegisterError[]= gT("The answer to the security question is incorrect.");
                            }
                        }
                        if(count($aRegisterError)==0)
                        {
                            //Check if this email already exists in token database
                            $oToken=TokenDynamic::model($iSurveyId)->find('email=:email',array(':email'=>$sR_email));
                            if ($oToken)
                            {
                                if($oToken->usesleft<1 && $aSurveyInfo['alloweditaftercompletion']!='Y')
                                {
                                    $aRegisterError="The e-mail address you have entered is already registered an the questionnaire has been completed.";
                                }
                                elseif(strtolower(substr(trim($oToken->emailstatus),0,6))==="optout")// And global blacklisting ?
                                {
                                    $aRegisterError="This email address is already registered but someone ask to don't receive new email again.";
                                }
                                elseif(!$oToken->emailstatus && $oToken->emailstatus!="OK")
                                {
                                    $aRegisterError="This email address is already registered but the email adress was bounced.";
                                }
                                else
                                {
                                    $iTokenId=$oToken->tid;
                                    $aMail['subject']=$aSurveyInfo['email_register_subj'];
                                    $aMail['message']=$aSurveyInfo['email_register'];
                                    $aMail['information']="The address you have entered is already registered. An email has been sent to this address with a link that gives you access to the survey.";
                                    // Did we update the token ? Setting ?
                                }
                            }
                            else
                            {
                                $oToken= Token::create($iSurveyId);
                                $oToken->firstname = $sR_firstname;
                                $oToken->lastname = $sR_lastname;
                                $oToken->email = $sR_email;
                                $oToken->emailstatus = 'OK';
                                $oToken->language = $sLanguage;
                                $oToken->setAttributes($aR_attribute);
                                $oToken->setAttributes($aR_attributeGet);// Need an option
                                if ($aSurveyInfo['startdate'])
                                {
                                    $oToken->validfrom = $aSurveyInfo['startdate'];
                                }
                                if ($aSurveyInfo['expires'])
                                {
                                    $oToken->validuntil = $aSurveyInfo['expires'];
                                }
                                $oToken->save();
                                $iTokenId=$oToken->tid;
                                TokenDynamic::model($iSurveyId)->createToken($iTokenId);// Review if really create a token
                                $aMail['subject']=$aSurveyInfo['email_register_subj'];
                                $aMail['message']=$aSurveyInfo['email_register'];
                                $aMail['information']=gT("An email has been sent to the address you provided with access details for this survey. Please follow the link in that email to proceed.");
                            }
                        }
                    }
                    if($aMail && $oToken)
                    {
                        $aReplacementFields=array();
                        $aReplacementFields["{ADMINNAME}"]=$aSurveyInfo['adminname'];
                        $aReplacementFields["{ADMINEMAIL}"]=$aSurveyInfo['adminemail'];
                        $aReplacementFields["{SURVEYNAME}"]=$aSurveyInfo['name'];
                        $aReplacementFields["{SURVEYDESCRIPTION}"]=$aSurveyInfo['description'];
                        $aReplacementFields["{EXPIRY}"]=$aSurveyInfo["expiry"];
                        $oToken=TokenDynamic::model($iSurveyId)->findByPk($iTokenId);
                        foreach($oToken->attributes as $attribute=>$value){
                            $aReplacementFields["{".strtoupper($attribute)."}"]=$value;
                        }
                        $sToken=$oToken->token;
                        $aMail['subject']=preg_replace("/{TOKEN:([A-Z0-9_]+)}/","{"."$1"."}",$aMail['subject']);
                        $aMail['message']=preg_replace("/{TOKEN:([A-Z0-9_]+)}/","{"."$1"."}",$aMail['message']);
                        $surveylink = App()->createAbsoluteUrl("/survey/index/sid/{$iSurveyId}",array('lang'=>$sLanguage,'token'=>$sToken));
                        $optoutlink = App()->createAbsoluteUrl("/optout/tokens/surveyid/{$iSurveyId}",array('langcode'=>$sLanguage,'token'=>$sToken));
                        $optinlink = App()->createAbsoluteUrl("/optin/tokens/surveyid/{$iSurveyId}",array('langcode'=>$sLanguage,'token'=>$sToken));
                        if (getEmailFormat($iSurveyId) == 'html')
                        {
                            $useHtmlEmail = true;
                            $aReplacementFields["{SURVEYURL}"]="<a href='$surveylink'>".$surveylink."</a>";
                            $aReplacementFields["{OPTOUTURL}"]="<a href='$optoutlink'>".$optoutlink."</a>";
                            $aReplacementFields["{OPTINURL}"]="<a href='$optinlink'>".$optinlink."</a>";
                        }
                        else
                        {
                            $useHtmlEmail = false;
                            $aReplacementFields["{SURVEYURL}"]= $surveylink;
                            $aReplacementFields["{OPTOUTURL}"]= $optoutlink;
                            $aReplacementFields["{OPTINURL}"]= $optinlink;
                        }
                        // Allow barebone link for all URL
                        $aMail['message'] = str_replace("@@SURVEYURL@@", $surveylink, $aMail['message']);
                        $aMail['message'] = str_replace("@@OPTOUTURL@@", $optoutlink, $aMail['message']);
                        $aMail['message'] = str_replace("@@OPTINURL@@", $optinlink, $aMail['message']);
                        // Replace the fields
                        $aMail['subject']=ReplaceFields($aMail['subject'], $aReplacementFields);
                        $aMail['message']=ReplaceFields($aMail['message'], $aReplacementFields);
                        
                        // We have it, then try to send the mail.
                        $from = "{$aSurveyInfo['adminname']} <{$aSurveyInfo['adminemail']}>";
                        $sitename =  Yii::app()->getConfig('sitename');
                        if (SendEmailMessage($aMail['message'], $aMail['subject'], $sR_email, $from, $sitename,$useHtmlEmail,getBounceEmail($iSurveyId)))
                        {
                            // TLR change to put date into sent
                            $today = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig('timeadjust'));
                            $oToken->sent=$today;
                            $oToken->save();
                            $sReturnHtml="<div id='wrapper' class='message tokenmessage'>"
                                . "<p>".gT("Thank you for registering to participate in this survey.")."</p>\n"
                                . "<p>".$aMail['information']."</p>\n"
                                . "<p>".gT("Survey administrator")." {ADMINNAME} ({ADMINEMAIL})</p>"
                                . "</div>\n";

                        }
                        else
                        {
                            $sReturnHtml="<div id='wrapper' class='message tokenmessage'>"
                                . "<p>".gT("Thank you for registering to participate in this survey.")."</p>\n"
                                . "<p>"."We can not sent you an email actually, please contact the survey administrator"."</p>\n"
                                . "<p>".gT("Survey administrator")." {ADMINNAME} ({ADMINEMAIL})</p>"
                                . "</div>\n";
                        
                        }
                        $sReturnHtml=ReplaceFields($sReturnHtml, $aReplacementFields);
                        $sTemplatePath=$aData['templatedir'] = getTemplatePath($aSurveyInfo['template']);
                        ob_start(function($buffer, $phase) {
                            App()->getClientScript()->render($buffer);
                            App()->getClientScript()->reset();
                            return $buffer;
                        });
                        ob_implicit_flush(false);
                        sendCacheHeaders();
                        doHeader();
                        $aData['thissurvey'] = $aSurveyInfo;
                        $aData['thissurvey'] = $aSurveyInfo;
                        echo templatereplace(file_get_contents($sTemplatePath.'/startpage.pstpl'),array(), $aData);
                        echo templatereplace(file_get_contents($sTemplatePath.'/survey.pstpl'),array(), $aData);
                        echo $sReturnHtml;
                        echo templatereplace(file_get_contents($sTemplatePath.'/endpage.pstpl'),array(), $aData);
                        doFooter();
                        ob_flush();
                        App()->end();
                    }
                    if($bShowForm || count($aRegisterError))
                    {
                        // Language ?
                        if(count($aRegisterError)==1){
                            $sHtmlRegistererror="<p class='error error-register'><strong>{$aRegisterError[0]}</strong></p>";
                        }elseif(count($aRegisterError)>1){
                            $sHtmlRegistererror="<ul class='error error-register error-list'>";
                            foreach ($aRegisterError as $sRegisterError)
                                $sHtmlRegistererror.="<li><strong>{$sRegisterError}</strong></li>";
                            $sHtmlRegistererror.="</ul>";
                        }
                        $aExtraParams['action']='register';
                        $aExtraParams['lang']=$sLanguage;
                        $sHtmlRegisterform = CHtml::form(Yii::app()->createUrl("/survey/index/sid/{$iSurveyId}",$aExtraParams), 'post');
                        $sHtmlRegisterform.="<table class='register'><tbody>\n";
                        $sHtmlRegisterform.=  "<tr><th><label for='register_firstname'>".gT("First name") . "</label></th><td>".CHtml::textField('register_firstname',htmlentities($sR_firstname, ENT_QUOTES, 'UTF-8'),array('class'=>'text'))."</td></tr>\n";
                        $sHtmlRegisterform.=  "<tr><th><label for='register_lastname'>".gT("Last name") . "</label></th><td>".CHtml::textField('register_lastname',htmlentities($sR_lastname, ENT_QUOTES, 'UTF-8'),array('class'=>'text'))."</td></tr>\n";
                        $sHtmlRegisterform.=  "<tr class='mandatory'><th><label for='register_email'>".gT("Email address") . "</label></th><td>".CHtml::textField('register_email',htmlentities($sR_email, ENT_QUOTES, 'UTF-8'),array('class'=>'text'))."</td></tr>\n";
                        // Extra attribute
                        foreach ($aSurveyInfo['attributedescriptions'] as $field => $aAttribute)
                        {
                            if (!empty($aAttribute['show_register']) && $aAttribute['show_register'] == 'Y')
                            {
                                $sHtmlRegisterform.=  "<tr".($aAttribute['mandatory'] == 'Y' ? " class='mandatory'" : '')."><th><label for='register_{$field}'>".$aSurveyInfo['attributecaptions'][$field].($aAttribute['mandatory'] == 'Y' ? ' *' : '')."</label></th><td>".CHtml::textField('register_'.$field,htmlentities($aR_attribute[$field], ENT_QUOTES, 'UTF-8'),array('class'=>'text'))."</td></tr>\n";
                            }
                        }
                        if (function_exists("ImageCreate") && isCaptchaEnabled('registrationscreen', $aSurveyInfo['usecaptcha']))
                            $sHtmlRegisterform.= "<tr><th><label for='loadsecurity'>" . gT("Security question") . "</label></th><td><img src='".Yii::app()->getController()->createUrl("/verification/image/sid/{$iSurveyId}")."' alt='' /><input type='text' size='5' maxlength='3' name='loadsecurity' id='loadsecurity' value='' /></td></tr>\n";
                        $sHtmlRegisterform.= "<tr><td></td><td>".CHtml::submitButton(gT("Continue"))."</td></tr>";
                        $sHtmlRegisterform.= "</tbody></table>\n";
                        $sHtmlRegisterform.= makeLanguageChangerSurvey($sLanguage);// Need to be inside the form
                        $sHtmlRegisterform.= CHtml::endForm();
                    }
                    $sTemplatePath=$aData['templatedir'] = getTemplatePath($aSurveyInfo['template']);
                    ob_start(function($buffer, $phase) {
                        App()->getClientScript()->render($buffer);
                        App()->getClientScript()->reset();
                        return $buffer;
                    });
                    ob_implicit_flush(false);
                    sendCacheHeaders();
                    doHeader();
                    // Get the register.pstpl file content, but remplace default by own string
                    $sHtmlRegister=file_get_contents($sTemplatePath.'/register.pstpl');
                    $sHtmlRegister= str_replace("{REGISTERERROR}",$sHtmlRegistererror,$sHtmlRegister);
                    $sHtmlRegister= str_replace("{REGISTERMESSAGE1}",$sHtmlRegistermessage1,$sHtmlRegister);
                    $sHtmlRegister= str_replace("{REGISTERMESSAGE2}",$sHtmlRegistermessage2,$sHtmlRegister);
                    $sHtmlRegister= str_replace("{REGISTERFORM}",$sHtmlRegisterform,$sHtmlRegister);

                    $aData['thissurvey'] = $aSurveyInfo;
                    echo templatereplace(file_get_contents($sTemplatePath.'/startpage.pstpl'),array(), $aData);
                    echo templatereplace(file_get_contents($sTemplatePath.'/survey.pstpl'),array(), $aData);
                    echo templatereplace($sHtmlRegister);
                    echo templatereplace(file_get_contents($sTemplatePath.'/endpage.pstpl'),array(), $aData);
                    doFooter();
                    ob_flush();
                    App()->end();
                }
            }
        }
예제 #19
0
 /**
  * Function that initialises all data and call other functions to load default view.
  *
  * @access protected
  * @param string $templatename
  * @param string $screenname
  * @param string $editfile
  * @param bool $showsummary
  * @return
  */
 protected function _initialise($templatename, $screenname, $editfile, $showsummary = true, $useindex = false)
 {
     // LimeSurvey style
     global $oEditedTemplate;
     $oEditedTemplate = Template::model()->getTemplateConfiguration($templatename);
     // In survey mode, bootstrap is loaded via the app init.
     // From template editor, we just add the bootstrap files to the js/css to load for template_helper::templatereplace()
     if ($oEditedTemplate->cssFramework == 'bootstrap') {
         // Core templates (are published only if exists)
         $oEditedTemplate->config->files->css->filename[] = "../../styles-public/bootstrap-for-template-editor.css";
         $oEditedTemplate->config->files->js->filename[] = "../../scripts/bootstrap-for-template-editor.js";
         // User templates (are published only if exists)
         $oEditedTemplate->config->files->css->filename[] = "../../../styles-public/bootstrap-for-template-editor.css";
         $oEditedTemplate->config->files->js->filename[] = "../../../scripts/bootstrap-for-template-editor.js";
     }
     //App()->getClientScript()->reset();
     Yii::app()->loadHelper('surveytranslator');
     Yii::app()->loadHelper('admin/template');
     $files = $this->_initfiles($templatename);
     $cssfiles = $this->_initcssfiles($oEditedTemplate);
     // Standard Support Files
     // These files may be edited or saved
     $supportfiles[] = array('name' => 'print_img_radio.png');
     $supportfiles[] = array('name' => 'print_img_checkbox.png');
     // Standard screens
     // Only these may be viewed
     $screens[] = array('name' => gT('Survey List Page'), 'id' => 'surveylist');
     $screens[] = array('name' => gT('Welcome Page'), 'id' => 'welcome');
     $screens[] = array('name' => gT('Question Page'), 'id' => 'question');
     $screens[] = array('name' => gT('Completed Page'), 'id' => 'completed');
     $screens[] = array('name' => gT('Clear All Page'), 'id' => 'clearall');
     $screens[] = array('name' => gT('Register Page'), 'id' => 'register');
     $screens[] = array('name' => gT('Load Page'), 'id' => 'load');
     $screens[] = array('name' => gT('Save Page'), 'id' => 'save');
     $screens[] = array('name' => gT('Print answers page'), 'id' => 'printanswers');
     $screens[] = array('name' => gT('Printable survey page'), 'id' => 'printablesurvey');
     // Page display blocks
     $SurveyList = array('startpage.pstpl', 'surveylist.pstpl', 'endpage.pstpl');
     $Welcome = array('startpage.pstpl', 'welcome.pstpl', 'privacy.pstpl', 'navigator.pstpl', 'endpage.pstpl');
     $Question = array('startpage.pstpl', 'survey.pstpl', 'startgroup.pstpl', 'groupdescription.pstpl', 'question.pstpl', 'endgroup.pstpl', 'navigator.pstpl', 'endpage.pstpl');
     $CompletedTemplate = array('startpage.pstpl', 'assessment.pstpl', 'completed.pstpl', 'endpage.pstpl');
     $Clearall = array('startpage.pstpl', 'clearall.pstpl', 'endpage.pstpl');
     $Register = array('startpage.pstpl', 'survey.pstpl', 'register.pstpl', 'endpage.pstpl');
     $Save = array('startpage.pstpl', 'save.pstpl', 'endpage.pstpl');
     $Load = array('startpage.pstpl', 'load.pstpl', 'endpage.pstpl');
     $printtemplate = array('startpage.pstpl', 'printanswers.pstpl', 'endpage.pstpl');
     $printablesurveytemplate = array('print_survey.pstpl', 'print_group.pstpl', 'print_question.pstpl');
     $file_version = "LimeSurvey template editor " . Yii::app()->getConfig('versionnumber');
     Yii::app()->session['s_lang'] = Yii::app()->session['adminlang'];
     $templatename = sanitize_dirname($templatename);
     $screenname = autoUnescape($screenname);
     // Checks if screen name is in the list of allowed screen names
     if (multiarray_search($screens, 'id', $screenname) === false) {
         Yii::app()->user->setFlash('error', gT('Invalid screen name'));
         $this->getController()->redirect(array("admin/templates/sa/upload"));
     }
     if (!isset($action)) {
         $action = sanitize_paranoid_string(returnGlobal('action'));
     }
     if (!isset($subaction)) {
         $subaction = sanitize_paranoid_string(returnGlobal('subaction'));
     }
     if (!isset($newname)) {
         $newname = sanitize_dirname(returnGlobal('newname'));
     }
     if (!isset($copydir)) {
         $copydir = sanitize_dirname(returnGlobal('copydir'));
     }
     if (is_file(Yii::app()->getConfig('usertemplaterootdir') . '/' . $templatename . '/question_start.pstpl')) {
         $files[] = array('name' => 'question_start.pstpl');
         $Question[] = 'question_start.pstpl';
     }
     $editfile = sanitize_filename($editfile);
     // Fixed with editable file after, but put in aData before fix
     $availableeditorlanguages = array('bg', 'cs', 'de', 'dk', 'en', 'eo', 'es', 'fi', 'fr', 'hr', 'it', 'ja', 'mk', 'nl', 'pl', 'pt', 'ru', 'sk', 'zh');
     // 2.06 way of doing.
     if (!$useindex) {
         $extension = substr(strrchr($editfile, "."), 1);
     } else {
         // The extension is now set as a prefix separated by a _
         $file_datas = explode("_", $editfile);
         $extension = $file_datas[0];
         // The file name is now based on the index of the oTemplate files
         $file_index = $file_datas[1];
         switch ($extension) {
             case 'css':
                 $aTemplateFiles = (array) $oEditedTemplate->config->files_editable->css->filename;
                 break;
             case 'js':
                 $aTemplateFiles = (array) $oEditedTemplate->config->files_editable->js->filename;
                 break;
             default:
                 $aTemplateFiles = (array) $oEditedTemplate->config->files_editable->css->filename;
                 break;
         }
         $editfile = $aTemplateFiles[$file_index];
     }
     if ($extension == 'css' || $extension == 'js') {
         $highlighter = $extension;
     } else {
         $highlighter = 'html';
     }
     if (in_array(Yii::app()->session['adminlang'], $availableeditorlanguages)) {
         $codelanguage = Yii::app()->session['adminlang'];
     } else {
         $codelanguage = 'en';
     }
     $templates = getTemplateList();
     if (!isset($templates[$templatename])) {
         $templatename = Yii::app()->getConfig('defaulttemplate');
     }
     $normalfiles = array("DUMMYENTRY", ".", "..", "preview.png");
     foreach ($files as $fl) {
         $normalfiles[] = $fl["name"];
     }
     foreach ($cssfiles as $fl) {
         $normalfiles[] = $fl["name"];
     }
     // Some global data
     $aData['sitename'] = Yii::app()->getConfig('sitename');
     $siteadminname = Yii::app()->getConfig('siteadminname');
     $siteadminemail = Yii::app()->getConfig('siteadminemail');
     // Set this so common.php doesn't throw notices about undefined variables
     $thissurvey['active'] = 'N';
     // FAKE DATA FOR TEMPLATES
     $thissurvey['name'] = gT("Template Sample");
     $thissurvey['description'] = "<p>" . gT('This is a sample survey description. It could be quite long.') . "</p>" . "<p>" . gT("But this one isn't.") . "<p>";
     $thissurvey['welcome'] = "<p>" . gT('Welcome to this sample survey') . "<p>" . "<p>" . gT('You should have a great time doing this') . "<p>";
     $thissurvey['allowsave'] = "Y";
     $thissurvey['active'] = "Y";
     $thissurvey['tokenanswerspersistence'] = "Y";
     $thissurvey['templatedir'] = $templatename;
     $thissurvey['format'] = "G";
     $thissurvey['surveyls_url'] = "http://www.limesurvey.org/";
     $thissurvey['surveyls_urldescription'] = gT("Some URL description");
     $thissurvey['usecaptcha'] = "A";
     $percentcomplete = makegraph(6, 10);
     $groupname = gT("Group 1: The first lot of questions");
     $groupdescription = gT("This group description is fairly vacuous, but quite important.");
     $navigator = $this->getController()->render('/admin/templates/templateeditor_navigator_view', array('screenname' => $screenname), true);
     $completed = $this->getController()->render('/admin/templates/templateeditor_completed_view', array(), true);
     $assessments = $this->getController()->render('/admin/templates/templateeditor_assessments_view', array(), true);
     $printoutput = $this->getController()->render('/admin/templates/templateeditor_printoutput_view', array(), true);
     $totalquestions = '10';
     $surveyformat = 'Format';
     $notanswered = '5';
     $privacy = '';
     $surveyid = '1295';
     $token = 1234567;
     $templatedir = $oEditedTemplate->viewPath;
     $templateurl = getTemplateURL($templatename);
     // Save these variables in an array
     $aData['thissurvey'] = $thissurvey;
     $aData['percentcomplete'] = $percentcomplete;
     $aData['groupname'] = $groupname;
     $aData['groupdescription'] = $groupdescription;
     $aData['navigator'] = $navigator;
     $aData['help'] = gT("This is some help text.");
     $aData['surveyformat'] = $surveyformat;
     $aData['totalquestions'] = $totalquestions;
     $aData['completed'] = $completed;
     $aData['notanswered'] = $notanswered;
     $aData['privacy'] = $privacy;
     $aData['surveyid'] = $surveyid;
     $aData['sid'] = $surveyid;
     $aData['token'] = $token;
     $aData['assessments'] = $assessments;
     $aData['printoutput'] = $printoutput;
     $aData['templatedir'] = $templatedir;
     $aData['templateurl'] = $templateurl;
     $aData['templatename'] = $templatename;
     $aData['screenname'] = $screenname;
     $aData['editfile'] = $editfile;
     $myoutput[] = "";
     switch ($screenname) {
         case 'surveylist':
             unset($files);
             $surveylist = array("nosid" => gT("You have not provided a survey identification number"), "contact" => sprintf(gT("Please contact %s ( %s ) for further assistance."), Yii::app()->getConfig("siteadminname"), Yii::app()->getConfig("siteadminemail")), "listheading" => gT("The following surveys are available:"), "list" => $this->getController()->render('/admin/templates/templateeditor_surveylist_view', array(), true));
             $aData['surveylist'] = $surveylist;
             $myoutput[] = "";
             //$myoutput[] = templatereplace(file_get_contents("$templatedir/startpage.pstpl"), array(), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate);
             foreach ($SurveyList as $qs) {
                 $files[] = array("name" => $qs);
                 $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath . "/{$qs}", $aData, $oEditedTemplate));
             }
             break;
         case 'question':
             unset($files);
             foreach ($Question as $qs) {
                 $files[] = array("name" => $qs);
             }
             $myoutput[] = $this->getController()->render('/admin/templates/templateeditor_question_meta_view', array(), true);
             $aData['aReplacements'] = array('SAVE_LINKS' => '<li><a href="#" id="saveallbtnlink">Resume later</a></li>', 'CLEARALL_LINKS' => '<li><a href="#" id="clearallbtnlink">' . gT("Exit and clear survey") . '</a></li>');
             $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath . "/startpage.pstpl", $aData, $oEditedTemplate));
             $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath . "/survey.pstpl", $aData, $oEditedTemplate));
             $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath . "/startgroup.pstpl", $aData, $oEditedTemplate));
             $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath . "/groupdescription.pstpl", $aData, $oEditedTemplate));
             $aReplacements = array('QUESTION_TEXT' => gT("How many roads must a man walk down?"), 'QUESTION_CODE' => '1a', 'QUESTIONHELP' => 'helpful text', 'QUESTION_MANDATORY' => gT("*"), 'QUESTION_MAN_CLASS' => ' mandatory', 'QUESTION_ESSENTIALS' => 'id="question1"', 'QUESTION_CLASS' => 'list-radio', 'QUESTION_NUMBER' => '1');
             $aReplacements['ANSWER'] = $this->getController()->render('/admin/templates/templateeditor_question_answer_view', array(), true);
             $aData['aReplacements'] = $aReplacements;
             $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath . "/question.pstpl", $aData, $oEditedTemplate));
             $aReplacements = array('QUESTION_TEXT' => gT('Please explain something in detail:'), 'QUESTION_CODE' => '2a', 'QUESTION_ESSENTIALS' => 'id="question2"', 'QUESTION_CLASS' => 'text-long', 'QUESTION_NUMBER' => '2');
             $aReplacements['ANSWER'] = $this->getController()->render('/admin/templates/templateeditor_question_answer_view', array('alt' => true), true);
             $aData['aReplacements'] = $aReplacements;
             $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath . "/question.pstpl", $aData, $oEditedTemplate));
             $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath . "/endgroup.pstpl", $aData, $oEditedTemplate));
             $aData['aReplacements'] = array('MOVEPREVBUTTON' => '<button type="submit" id="moveprevbtn" value="moveprev" name="moveprev" accesskey="p" class="submit button btn btn-default btn-lg ">Previous</button>', 'MOVENEXTBUTTON' => '<button type="submit" id="movenextbtn" value="movenext" name="movenext" accesskey="n" class="submit button btn btn-default btn-lg ">Next</button>');
             $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath . "/navigator.pstpl", $aData, $oEditedTemplate));
             $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath . "/endpage.pstpl", $aData, $oEditedTemplate));
             break;
         case 'welcome':
             unset($files);
             foreach ($Welcome as $qs) {
                 $files[] = array("name" => $qs);
                 $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath . "/{$qs}", $aData, $oEditedTemplate));
             }
             /*
             $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath  . "/startpage.pstpl", $aData, $oEditedTemplate));
             $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath  . "/welcome.pstpl", $aData, $oEditedTemplate));
             $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath  . "/privacy.pstpl", $aData, $oEditedTemplate));
             */
             $aData['aReplacements'] = array('MOVENEXTBUTTON' => '<button type="submit" id="movenextbtn" value="movenext" name="movenext" accesskey="n" class="submit button btn btn-default btn-lg">Next</button>');
             $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath . "/navigator.pstpl", $aData, $oEditedTemplate));
             $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath . "/endpage.pstpl", $aData, $oEditedTemplate));
             break;
         case 'register':
             unset($files);
             foreach ($Register as $qs) {
                 $files[] = array("name" => $qs);
             }
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/startpage.pstpl"), array(), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate);
             $aData = array('aReplacements' => array('SURVEYNAME' => 'Survey name'));
             $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath . "/survey.pstpl", $aData, $oEditedTemplate));
             $aData['aReplacements'] = array('REGISTERERROR' => 'Example error message', 'REGISTERMESSAGE1' => 'Register message 1', 'REGISTERMESSAGE2' => 'Register message 2', 'REGISTERFORM' => $this->getController()->render('/admin/templates/templateeditor_register_view', array('alt' => true), true));
             $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath . "/register.pstpl", $aData, $oEditedTemplate));
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/endpage.pstpl"), array(), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate);
             $myoutput[] = "\n";
             break;
         case 'save':
             unset($files);
             foreach ($Save as $qs) {
                 $files[] = array("name" => $qs);
             }
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/startpage.pstpl"), array(), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/save.pstpl"), array(), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/endpage.pstpl"), array(), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate);
             $myoutput[] = "\n";
             break;
         case 'load':
             unset($files);
             foreach ($Load as $qs) {
                 $files[] = array("name" => $qs);
             }
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/startpage.pstpl"), array(), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/load.pstpl"), array(), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/endpage.pstpl"), array(), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate);
             $myoutput[] = "\n";
             break;
         case 'clearall':
             unset($files);
             foreach ($Clearall as $qs) {
                 $files[] = array("name" => $qs);
             }
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/startpage.pstpl"), array(), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/clearall.pstpl"), array(), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/endpage.pstpl"), array(), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate);
             $myoutput[] = "\n";
             break;
         case 'completed':
             unset($files);
             $myoutput[] = "";
             foreach ($CompletedTemplate as $qs) {
                 $files[] = array("name" => $qs);
                 $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath . "/{$qs}", $aData, $oEditedTemplate));
             }
             break;
         case 'printablesurvey':
             unset($files);
             foreach ($printablesurveytemplate as $qs) {
                 $files[] = array("name" => $qs);
             }
             $questionoutput = array();
             foreach (file("{$templatedir}/print_question.pstpl") as $op) {
                 $questionoutput[] = templatereplace($op, array('QUESTION_NUMBER' => '1', 'QUESTION_CODE' => 'Q1', 'QUESTION_MANDATORY' => gT('*'), 'QUESTION_SCENARIO' => 'Only answer this if certain conditions are met.', 'QUESTION_CLASS' => ' mandatory list-radio', 'QUESTION_TYPE_HELP' => gT('Please choose *only one* of the following:'), 'QUESTION_MAN_MESSAGE' => '', 'QUESTION_VALID_MESSAGE' => '', 'QUESTION_FILE_VALID_MESSAGE' => '', 'QUESTION_TEXT' => gT('This is a sample question text. The user was asked to pick an entry.'), 'QUESTIONHELP' => gT('This is some help text for this question.'), 'ANSWER' => $this->getController()->render('/admin/templates/templateeditor_printablesurvey_quesanswer_view', array('templateurl' => $templateurl), true)), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate);
             }
             $groupoutput = array();
             $groupoutput[] = templatereplace(file_get_contents("{$templatedir}/print_group.pstpl"), array('QUESTIONS' => implode(' ', $questionoutput)), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/print_survey.pstpl"), array('GROUPS' => implode(' ', $groupoutput), 'FAX_TO' => gT("Please fax your completed survey to:") . " 000-000-000", 'SUBMIT_TEXT' => gT("Submit your survey."), 'HEADELEMENTS' => getPrintableHeader(), 'SUBMIT_BY' => sprintf(gT("Please submit by %s"), date('d.m.y')), 'THANKS' => gT('Thank you for completing this survey.'), 'END' => gT('This is the survey end message.')), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate);
             break;
         case 'printanswers':
             unset($files);
             foreach ($printtemplate as $qs) {
                 $files[] = array("name" => $qs);
             }
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/startpage.pstpl"), array(), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/printanswers.pstpl"), array('ANSWERTABLE' => $printoutput), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/endpage.pstpl"), array(), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate);
             $myoutput[] = "\n";
             break;
     }
     $myoutput[] = "</html>";
     $jsfiles = $this->_getEditableJsFiles($oEditedTemplate);
     if (is_array($files)) {
         $match = 0;
         foreach ($files as $f) {
             if ($editfile == $f["name"]) {
                 $match = 1;
             }
         }
         $aCssAndJsfiles = array_merge($cssfiles, $jsfiles);
         foreach ($aCssAndJsfiles as $f) {
             if ($editfile == $f["name"]) {
                 $match = 1;
             }
         }
         if ($match == 0) {
             if (count($files) > 0) {
                 $editfile = $files[0]["name"];
             } else {
                 $editfile = "";
             }
         }
     }
     // Get list of 'otherfiles'
     // We can't use $oTemplate->otherFiles, because of retrocompatibility with 2.06 template and the big mess of it mixing files
     $filesdir = $oEditedTemplate->filesPath != '' ? $oEditedTemplate->filesPath : $templatedir . '../files';
     $otherfiles = array();
     if (file_exists($filesdir) && ($handle = opendir($filesdir))) {
         while (false !== ($file = readdir($handle))) {
             if (!array_search($file, $normalfiles)) {
                 if (!is_dir($templatedir . DIRECTORY_SEPARATOR . $file)) {
                     $otherfiles[] = array("name" => $file);
                 }
             }
         }
         closedir($handle);
     }
     $aData['codelanguage'] = $codelanguage;
     $aData['highlighter'] = $highlighter;
     $aData['screens'] = $screens;
     $aData['templatename'] = $templatename;
     $aData['templates'] = $templates;
     $aData['editfile'] = $editfile;
     $aData['screenname'] = $screenname;
     $aData['tempdir'] = Yii::app()->getConfig('tempdir');
     $aData['usertemplaterootdir'] = Yii::app()->getConfig('usertemplaterootdir');
     $aViewUrls['templateeditorbar_view'][] = $aData;
     if ($showsummary) {
         //$aCssfileseditable = (array) $oEditedTemplate->config->files_editable->css->filename;
         $aViewUrls = array_merge($aViewUrls, $this->_templatesummary($templatename, $screenname, $editfile, $templates, $files, $cssfiles, $jsfiles, $otherfiles, $myoutput));
     }
     App()->getClientScript()->registerScriptFile(App()->getAssetManager()->publish(ADMIN_SCRIPT_PATH . 'admin_core.js'));
     return $aViewUrls;
 }
 public function set_question_answers($sSessionKey, $iSurveyID, $iQuestionID, $data)
 {
     Yii::app()->loadHelper('database');
     $aSurveyLanguages = Survey::model()->findByPk($iSurveyID)->additionalLanguages;
     $sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language;
     array_unshift($aSurveyLanguages, $sBaseLanguage);
     $arQuestion = Question::model()->findByAttributes(array('qid' => $iQuestionID));
     $sQuestionType = $arQuestion['type'];
     // Checked)
     $aQuestionTypeList = getQuestionTypeList('', 'array');
     $iScaleCount = $aQuestionTypeList[$sQuestionType]['answerscales'];
     //First delete all answers
     Answer::model()->deleteAllByAttributes(array('qid' => $iQuestionID));
     LimeExpressionManager::RevertUpgradeConditionsToRelevance($iSurveyID);
     for ($iScaleID = 0; $iScaleID < $iScaleCount; $iScaleID++) {
         $iMaxCount = (int) $data['answercount_' . $iScaleID];
         for ($iSortOrderID = 1; $iSortOrderID < $iMaxCount; $iSortOrderID++) {
             $sCode = sanitize_paranoid_string($data['code_' . $iSortOrderID . '_' . $iScaleID]);
             if ($data['oldcode_' . $iSortOrderID . '_' . $iScaleID]) {
                 $sOldCode = sanitize_paranoid_string($data['oldcode_' . $iSortOrderID . '_' . $iScaleID]);
                 if ($sCode !== $sOldCode) {
                     Condition::model()->updateAll(array('value' => $sCode), 'cqid=:cqid AND value=:value', array(':cqid' => $iQuestionID, ':value' => $sOldCode));
                 }
             }
             foreach ($aSurveyLanguages as $sLanguage) {
                 $sAnswerText = $data['answer_' . $sLanguage . '_' . $iSortOrderID . '_' . $iScaleID];
                 if ($bXSSFilter) {
                     $sAnswerText = $oPurifier->purify($sAnswerText);
                 } else {
                     $sAnswerText = html_entity_decode($sAnswerText, ENT_QUOTES, "UTF-8");
                 }
                 // Now we insert the answers
                 $iInsertCount = Answer::model()->insertRecords(array('code' => $sCode, 'answer' => $sAnswerText, 'qid' => $iQuestionID, 'sortorder' => $iSortOrderID, 'language' => $sLanguage, 'assessment_value' => '1', 'scale_id' => $iScaleID));
                 if (!$iInsertCount) {
                     //return "Error: code = " . $data['code_2_0'] . ", answer = " . $sAnswerText . ", qid = " . $iQuestionID . ", sortorder = " . $iSortOrderID . ", language = " . $sLanguage . ", scale_id = " . $iScaleID;
                     return "Error: Failed to update answers";
                 }
             }
             // if there has been any change on the relivance equation on the answer
             if (isset($sOldCode) && $sCode !== $sOldCode) {
                 Condition::model()->updateAll(array('value' => $sCode), 'cqid=:cqid AND value=:value', array(':cqid' => $iQuestionID, ':value' => $sOldCode));
             }
         }
     }
     LimeExpressionManager::UpgradeConditionsToRelevance($iSurveyID);
     return "Answer options were successfully saved";
 }
예제 #21
0
<li><input type='checkbox' name='LEM_DEBUG_VALIDATION_SUMMARY' id='LEM_DEBUG_VALIDATION_SUMMARY' value='Y' checked="checked"/>Validation Summary</li>
<li><input type='checkbox' name='LEM_DEBUG_VALIDATION_DETAIL' id='LEM_DEBUG_VALIDATION_DETAIL' value='Y' checked="checked"/>Validation Detail (Validation Summary must also be checked to see detail)</li>
<li><input type='checkbox' name='LEM_PRETTY_PRINT_ALL_SYNTAX' id='LEM_PRETTY_PRINT_ALL_SYNTAX' value='Y' checked="checked"/>Pretty Print Syntax</li>
<li><input type='checkbox' name='deletenonvalues' id='deletenonvalues' value='Y' checked="checked"/>Delete non-relevant values</li>
</ul></td>
</tr>
<tr><td colspan='2'><input type='submit'/></td></tr>
</table>
</form>
EOD;
    echo $form;
} else {
    $surveyInfo = explode('|', Yii::app()->request->getParam('sid'));
    $surveyid = sanitize_int($surveyInfo[0]);
    $assessments = $surveyInfo[1] == 'Y';
    $surveyMode = sanitize_paranoid_string(Yii::app()->request->getParam('surveyMode'));
    $LEMdebugLevel = (isset($_POST['LEM_DEBUG_TIMING']) && $_POST['LEM_DEBUG_TIMING'] == 'Y' ? LEM_DEBUG_TIMING : 0) + (isset($_POST['LEM_DEBUG_VALIDATION_SUMMARY']) && $_POST['LEM_DEBUG_VALIDATION_SUMMARY'] == 'Y' ? LEM_DEBUG_VALIDATION_SUMMARY : 0) + (isset($_POST['LEM_DEBUG_VALIDATION_DETAIL']) && $_POST['LEM_DEBUG_VALIDATION_DETAIL'] == 'Y' ? LEM_DEBUG_VALIDATION_DETAIL : 0) + (isset($_POST['LEM_PRETTY_PRINT_ALL_SYNTAX']) && $_POST['LEM_PRETTY_PRINT_ALL_SYNTAX'] == 'Y' ? LEM_PRETTY_PRINT_ALL_SYNTAX : 0);
    $deletenonvalues = isset($_POST['deletenonvalues']) && $_POST['deletenonvalues'] == 'Y' ? 1 : 0;
    $surveyOptions = array('active' => false, 'allowsave' => true, 'anonymized' => false, 'assessments' => $assessments, 'datestamp' => true, 'deletenonvalues' => $deletenonvalues, 'hyperlinkSyntaxHighlighting' => true, 'ipaddr' => true, 'rooturl' => '../../..');
    print '<h3>Starting survey ' . $surveyid . " using Survey Mode '" . $surveyMode . ($assessments ? "' [Uses Assessments]" : "'") . "</h3>";
    $now = microtime(true);
    LimeExpressionManager::StartSurvey($surveyid, $surveyMode, $surveyOptions, true, $LEMdebugLevel);
    print '<b>[StartSurvey() took ' . (microtime(true) - $now) . ' seconds]</b><br/>';
    while (true) {
        $now = microtime(true);
        $result = LimeExpressionManager::NavigateForwards(true);
        print $result['message'] . "<br/>";
        LimeExpressionManager::FinishProcessingPage();
        if (($LEMdebugLevel & LEM_DEBUG_TIMING) == LEM_DEBUG_TIMING) {
            print LimeExpressionManager::GetDebugTimingMessage();
        }
예제 #22
0
function hasTemplateManageRights($userid, $templatefolder)
{
    $userid = sanitize_int($userid);
    $templatefolder = sanitize_paranoid_string($templatefolder);
    $criteria = new CDbCriteria();
    $criteria->addColumnCondition(array('uid' => $userid));
    $criteria->addSearchCondition('folder', $templatefolder);
    $query = Templates_rights::model()->find($criteria);
    //if ($result->RecordCount() == 0)  return false;
    if (is_null($query)) {
        return false;
    }
    $row = $query;
    //$row = $result->FetchRow();
    return $row["use"];
}
예제 #23
0
파일: subs_edit.php 프로젝트: Karpec/gizd
         $frame = $_POST['frame'];
         $idflag = intval($_POST["flag"]);
         $ping = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT info_hash FROM {$TABLE_PREFIX}files WHERE info_hash='{$hash}'");
         $find = mysqli_fetch_assoc($ping);
         if ($hash > $find["info_hash"]) {
             stderr("Error", "No torrent matches this info hash");
             stdfoot();
             exit;
         }
         if (is_null($nume) || is_null($hash) || is_null($pic) || is_null($cds) || is_null($autor) || is_null($link) || is_null($frame)) {
             stderr("Error", "Please Complete all the fields!");
             stdfoot(false, false, true);
             die;
         }
         $cds = sanitize_paranoid_string($cds);
         $autor = sanitize_paranoid_string($autor);
         do_sqlquery("UPDATE {$TABLE_PREFIX}subtitles SET name='{$nume}', hash='{$hash}', pic='{$pic}', cds='{$cds}', author='{$autor}', imdb='{$link}', Framerate='{$frame}', flag='{$idflag}' WHERE id=" . $_GET['id']) or sqlerr();
         redirect("index.php?page=subtitles");
     }
 }
 $getname = do_sqlquery("select * from {$TABLE_PREFIX}countries where id=" . $arr["flag"]);
 $named = mysqli_fetch_assoc($getname);
 $fres = flag_list();
 $option = "\n<select name=\"flag\" size=\"1\">\n<option value='" . $arr["flag"] . "'>" . $named["name"] . "</option>";
 $thisip = $_SERVER["REMOTE_ADDR"];
 $remotedns = gethostbyaddr($thisip);
 if ($remotedns != $thisip) {
     $remotedns = strtoupper($remotedns);
     preg_match('/^(.+)\\.([A-Z]{2,3})$/', $remotedns, $tldm);
     if (isset($tldm[2])) {
         $remotedns = mysqli_real_escape_string($DBDT, $tldm[2]);
예제 #24
0
        $selecthide = "";
        $selectshow = "";
        $selectinc = "selected='selected'";
    } elseif (incompleteAnsFilterstate() == "filter") {
        $selecthide = "selected='selected'";
        $selectshow = "";
        $selectinc = "";
    } else {
        $selecthide = "";
        $selectshow = "selected='selected'";
        $selectinc = "";
    }
    $vvoutput = browsemenubar($clang->gT("Export VV file")) . "<form id='vvexport' method='post' action='admin.php?action=vvexport&amp;sid={$surveyid}'>" . "<div class='header ui-widget-header'>" . $clang->gT("Export a VV survey file") . "</div>" . "<ul>" . "<li>" . "<label for='sid'>" . $clang->gT("Export Survey") . ":</label>" . "<input type='text' size='10' value='{$surveyid}' id='sid' name='sid' readonly='readonly' />" . "</li>\n" . "<li>\n" . " <label for='filterinc'>" . $clang->gT("Export") . ":</label>" . " <select name='filterinc' id='filterinc'>\n" . "  <option value='filter' {$selecthide}>" . $clang->gT("Completed responses only") . "</option>\n" . "  <option value='show' {$selectshow}>" . $clang->gT("All responses") . "</option>\n" . "  <option value='incomplete' {$selectinc}>" . $clang->gT("Incomplete responses only") . "</option>\n" . " </select>\n" . "</li>\n" . "<li>\n" . " <label for='extension'>" . $clang->gT("File Extension") . ": </label>\n" . " <input type='text' id='extension' name='extension' size='3' value='csv' /><span style='font-size: 7pt'>*</span>\n" . "</li>\n" . "</ul>\n" . "<p><input type='submit' value='" . $clang->gT("Export results") . "' />&nbsp;" . "<input type='hidden' name='subaction' value='export' />" . "</form>" . "<p><span style='font-size: 7pt'>* " . $clang->gT("For easy opening in MS Excel, change the extension to 'tab' or 'txt'") . "</span><br />\n";
} elseif (isset($surveyid) && $surveyid) {
    //Export is happening
    $extension = sanitize_paranoid_string(returnglobal('extension'));
    header("Content-Disposition: attachment; filename=vvexport_{$surveyid}." . $extension);
    header("Content-type: text/comma-separated-values; charset=UTF-8");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Pragma: cache");
    $s = "\t";
    $fieldmap = createFieldMap($surveyid, "full");
    $surveytable = "{$dbprefix}survey_{$surveyid}";
    GetBaseLanguageFromSurveyID($surveyid);
    $fieldnames = array_values($connect->MetaColumnNames($surveytable, true));
    //Create the human friendly first line
    $firstline = "";
    $secondline = "";
    foreach ($fieldnames as $field) {
        $fielddata = arraySearchByKey($field, $fieldmap, "fieldname", 1);
        //$vvoutput .= "<pre>";print_r($fielddata);$vvoutput .= "</pre>";
예제 #25
0
 /**
  * Function that initialises all data and call other functions to load default view.
  *
  * @access protected
  * @param string $templatename
  * @param string $screenname
  * @param string $editfile
  * @param bool $showsummary
  * @return
  */
 protected function _initialise($templatename, $screenname, $editfile, $showsummary = true)
 {
     App()->getClientScript()->reset();
     $clang = $this->getController()->lang;
     Yii::app()->loadHelper('surveytranslator');
     Yii::app()->loadHelper('admin/template');
     $files = $this->_initfiles($templatename);
     $cssfiles = $this->_initcssfiles();
     // Standard Support Files
     // These files may be edited or saved
     $supportfiles[] = array('name' => 'print_img_radio.png');
     $supportfiles[] = array('name' => 'print_img_checkbox.png');
     // Standard screens
     // Only these may be viewed
     $screens[] = array('name' => $clang->gT('Survey List Page'), 'id' => 'surveylist');
     $screens[] = array('name' => $clang->gT('Welcome Page'), 'id' => 'welcome');
     $screens[] = array('name' => $clang->gT('Question Page'), 'id' => 'question');
     $screens[] = array('name' => $clang->gT('Completed Page'), 'id' => 'completed');
     $screens[] = array('name' => $clang->gT('Clear All Page'), 'id' => 'clearall');
     $screens[] = array('name' => $clang->gT('Register Page'), 'id' => 'register');
     $screens[] = array('name' => $clang->gT('Load Page'), 'id' => 'load');
     $screens[] = array('name' => $clang->gT('Save Page'), 'id' => 'save');
     $screens[] = array('name' => $clang->gT('Print answers page'), 'id' => 'printanswers');
     $screens[] = array('name' => $clang->gT('Printable survey page'), 'id' => 'printablesurvey');
     // Page display blocks
     $SurveyList = array('startpage.pstpl', 'surveylist.pstpl', 'endpage.pstpl');
     $Welcome = array('startpage.pstpl', 'welcome.pstpl', 'privacy.pstpl', 'navigator.pstpl', 'endpage.pstpl');
     $Question = array('startpage.pstpl', 'survey.pstpl', 'startgroup.pstpl', 'groupdescription.pstpl', 'question.pstpl', 'endgroup.pstpl', 'navigator.pstpl', 'endpage.pstpl');
     $CompletedTemplate = array('startpage.pstpl', 'assessment.pstpl', 'completed.pstpl', 'endpage.pstpl');
     $Clearall = array('startpage.pstpl', 'clearall.pstpl', 'endpage.pstpl');
     $Register = array('startpage.pstpl', 'survey.pstpl', 'register.pstpl', 'endpage.pstpl');
     $Save = array('startpage.pstpl', 'save.pstpl', 'endpage.pstpl');
     $Load = array('startpage.pstpl', 'load.pstpl', 'endpage.pstpl');
     $printtemplate = array('startpage.pstpl', 'printanswers.pstpl', 'endpage.pstpl');
     $printablesurveytemplate = array('print_survey.pstpl', 'print_group.pstpl', 'print_question.pstpl');
     $file_version = "LimeSurvey template editor " . Yii::app()->getConfig('versionnumber');
     Yii::app()->session['s_lang'] = Yii::app()->session['adminlang'];
     $templatename = sanitize_dirname($templatename);
     $screenname = autoUnescape($screenname);
     // Checks if screen name is in the list of allowed screen names
     if (multiarray_search($screens, 'id', $screenname) === false) {
         $this->getController()->error('Invalid screen name');
     }
     if (!isset($action)) {
         $action = sanitize_paranoid_string(returnGlobal('action'));
     }
     if (!isset($subaction)) {
         $subaction = sanitize_paranoid_string(returnGlobal('subaction'));
     }
     if (!isset($newname)) {
         $newname = sanitize_dirname(returnGlobal('newname'));
     }
     if (!isset($copydir)) {
         $copydir = sanitize_dirname(returnGlobal('copydir'));
     }
     if (is_file(Yii::app()->getConfig('usertemplaterootdir') . '/' . $templatename . '/question_start.pstpl')) {
         $files[] = array('name' => 'question_start.pstpl');
         $Question[] = 'question_start.pstpl';
     }
     $availableeditorlanguages = array('bg', 'cs', 'de', 'dk', 'en', 'eo', 'es', 'fi', 'fr', 'hr', 'it', 'ja', 'mk', 'nl', 'pl', 'pt', 'ru', 'sk', 'zh');
     $extension = substr(strrchr($editfile, "."), 1);
     if ($extension == 'css' || $extension == 'js') {
         $highlighter = $extension;
     } else {
         $highlighter = 'html';
     }
     if (in_array(Yii::app()->session['adminlang'], $availableeditorlanguages)) {
         $codelanguage = Yii::app()->session['adminlang'];
     } else {
         $codelanguage = 'en';
     }
     $templates = getTemplateList();
     if (!isset($templates[$templatename])) {
         $templatename = Yii::app()->getConfig('defaulttemplate');
     }
     $normalfiles = array("DUMMYENTRY", ".", "..", "preview.png");
     foreach ($files as $fl) {
         $normalfiles[] = $fl["name"];
     }
     foreach ($cssfiles as $fl) {
         $normalfiles[] = $fl["name"];
     }
     // Some global data
     $aData['sitename'] = Yii::app()->getConfig('sitename');
     $siteadminname = Yii::app()->getConfig('siteadminname');
     $siteadminemail = Yii::app()->getConfig('siteadminemail');
     // Set this so common.php doesn't throw notices about undefined variables
     $thissurvey['active'] = 'N';
     // FAKE DATA FOR TEMPLATES
     $thissurvey['name'] = $clang->gT("Template Sample");
     $thissurvey['description'] = "<p>" . $clang->gT('This is a sample survey description. It could be quite long.') . "</p>" . "<p>" . $clang->gT("But this one isn't.") . "<p>";
     $thissurvey['welcome'] = "<p>" . $clang->gT('Welcome to this sample survey') . "<p>" . "<p>" . $clang->gT('You should have a great time doing this') . "<p>";
     $thissurvey['allowsave'] = "Y";
     $thissurvey['active'] = "Y";
     $thissurvey['tokenanswerspersistence'] = "Y";
     $thissurvey['templatedir'] = $templatename;
     $thissurvey['format'] = "G";
     $thissurvey['surveyls_url'] = "http://www.limesurvey.org/";
     $thissurvey['surveyls_urldescription'] = $clang->gT("Some URL description");
     $thissurvey['usecaptcha'] = "A";
     $percentcomplete = makegraph(6, 10);
     $groupname = $clang->gT("Group 1: The first lot of questions");
     $groupdescription = $clang->gT("This group description is fairly vacuous, but quite important.");
     $navigator = $this->getController()->render('/admin/templates/templateeditor_navigator_view', array('screenname' => $screenname, 'clang' => $clang), true);
     $completed = $this->getController()->render('/admin/templates/templateeditor_completed_view', array('clang' => $clang), true);
     $assessments = $this->getController()->render('/admin/templates/templateeditor_assessments_view', array('clang' => $clang), true);
     $printoutput = $this->getController()->render('/admin/templates/templateeditor_printoutput_view', array('clang' => $clang), true);
     $totalquestions = '10';
     $surveyformat = 'Format';
     $notanswered = '5';
     $privacy = '';
     $surveyid = '1295';
     $token = 1234567;
     $templatedir = getTemplatePath($templatename);
     $templateurl = getTemplateURL($templatename);
     // Save these variables in an array
     $aData['thissurvey'] = $thissurvey;
     $aData['percentcomplete'] = $percentcomplete;
     $aData['groupname'] = $groupname;
     $aData['groupdescription'] = $groupdescription;
     $aData['navigator'] = $navigator;
     $aData['help'] = $clang->gT("This is some help text.");
     $aData['surveyformat'] = $surveyformat;
     $aData['totalquestions'] = $totalquestions;
     $aData['completed'] = $completed;
     $aData['notanswered'] = $notanswered;
     $aData['privacy'] = $privacy;
     $aData['surveyid'] = $surveyid;
     $aData['sid'] = $surveyid;
     $aData['token'] = $token;
     $aData['assessments'] = $assessments;
     $aData['printoutput'] = $printoutput;
     $aData['templatedir'] = $templatedir;
     $aData['templateurl'] = $templateurl;
     $aData['templatename'] = $templatename;
     $aData['screenname'] = $screenname;
     $aData['editfile'] = $editfile;
     $myoutput[] = "";
     switch ($screenname) {
         case 'surveylist':
             unset($files);
             $surveylist = array("nosid" => $clang->gT("You have not provided a survey identification number"), "contact" => sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), Yii::app()->getConfig("siteadminname"), Yii::app()->getConfig("siteadminemail")), "listheading" => $clang->gT("The following surveys are available:"), "list" => $this->getController()->render('/admin/templates/templateeditor_surveylist_view', array(), true));
             $aData['surveylist'] = $surveylist;
             $myoutput[] = "";
             foreach ($SurveyList as $qs) {
                 $files[] = array("name" => $qs);
                 $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/{$qs}", $aData));
             }
             break;
         case 'question':
             unset($files);
             foreach ($Question as $qs) {
                 $files[] = array("name" => $qs);
             }
             $myoutput[] = $this->getController()->render('/admin/templates/templateeditor_question_meta_view', array('clang' => $clang), true);
             $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/startpage.pstpl", $aData));
             $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/survey.pstpl", $aData));
             $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/startgroup.pstpl", $aData));
             $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/groupdescription.pstpl", $aData));
             $question = array('all' => $clang->gT("How many roads must a man walk down?"), 'text' => $clang->gT("How many roads must a man walk down?"), 'code' => '1a', 'help' => 'helpful text', 'mandatory' => $clang->gT("*"), 'man_class' => ' mandatory', 'man_message' => '', 'valid_message' => '', 'file_valid_message' => '', 'essentials' => 'id="question1"', 'class' => 'list-radio', 'input_error_class' => '', 'number' => '1', 'type' => 'L');
             $aData['question'] = $question;
             $answer = $this->getController()->render('/admin/templates/templateeditor_question_answer_view', array('clang' => $clang), true);
             $aData['answer'] = $answer;
             $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/question.pstpl", $aData));
             $answer = $this->getController()->render('/admin/templates/templateeditor_question_answer_view', array('alt' => true, 'clang' => $clang), true);
             $aData['answer'] = $answer;
             $question = array('all' => $clang->gT("Please explain something in detail:"), 'text' => $clang->gT('Please explain something in detail:'), 'code' => '2a', 'help' => '', 'mandatory' => '', 'man_message' => '', 'valid_message' => '', 'file_valid_message' => '', 'essentials' => 'id="question2"', 'class' => 'text-long', 'man_class' => 'mandatory', 'input_error_class' => '', 'number' => '2', 'type' => 'T');
             $aData['question'] = $question;
             $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/question.pstpl", $aData));
             $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/endgroup.pstpl", $aData));
             $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/navigator.pstpl", $aData));
             $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/endpage.pstpl", $aData));
             break;
         case 'welcome':
             unset($files);
             $myoutput[] = "";
             foreach ($Welcome as $qs) {
                 $files[] = array("name" => $qs);
                 $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/{$qs}", $aData));
             }
             break;
         case 'register':
             unset($files);
             foreach ($Register as $qs) {
                 $files[] = array("name" => $qs);
             }
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/startpage.pstpl"), array(), $aData);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/survey.pstpl"), array(), $aData);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/register.pstpl"), array(), $aData);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/endpage.pstpl"), array(), $aData);
             $myoutput[] = "\n";
             break;
         case 'save':
             unset($files);
             foreach ($Save as $qs) {
                 $files[] = array("name" => $qs);
             }
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/startpage.pstpl"), array(), $aData);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/save.pstpl"), array(), $aData);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/endpage.pstpl"), array(), $aData);
             $myoutput[] = "\n";
             break;
         case 'load':
             unset($files);
             foreach ($Load as $qs) {
                 $files[] = array("name" => $qs);
             }
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/startpage.pstpl"), array(), $aData);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/load.pstpl"), array(), $aData);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/endpage.pstpl"), array(), $aData);
             $myoutput[] = "\n";
             break;
         case 'clearall':
             unset($files);
             foreach ($Clearall as $qs) {
                 $files[] = array("name" => $qs);
             }
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/startpage.pstpl"), array(), $aData);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/clearall.pstpl"), array(), $aData);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/endpage.pstpl"), array(), $aData);
             $myoutput[] = "\n";
             break;
         case 'completed':
             unset($files);
             $myoutput[] = "";
             foreach ($CompletedTemplate as $qs) {
                 $files[] = array("name" => $qs);
                 $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/{$qs}", $aData));
             }
             break;
         case 'printablesurvey':
             unset($files);
             foreach ($printablesurveytemplate as $qs) {
                 $files[] = array("name" => $qs);
             }
             $questionoutput = array();
             foreach (file("{$templatedir}/print_question.pstpl") as $op) {
                 $questionoutput[] = templatereplace($op, array('QUESTION_NUMBER' => '1', 'QUESTION_CODE' => 'Q1', 'QUESTION_MANDATORY' => $clang->gT('*'), 'QUESTION_SCENARIO' => 'Only answer this if certain conditions are met.', 'QUESTION_CLASS' => ' mandatory list-radio', 'QUESTION_TYPE_HELP' => $clang->gT('Please choose *only one* of the following:'), 'QUESTION_MAN_MESSAGE' => '', 'QUESTION_VALID_MESSAGE' => '', 'QUESTION_FILE_VALID_MESSAGE' => '', 'QUESTION_TEXT' => $clang->gT('This is a sample question text. The user was asked to pick an entry.'), 'QUESTIONHELP' => $clang->gT('This is some help text for this question.'), 'ANSWER' => $this->getController()->render('/admin/templates/templateeditor_printablesurvey_quesanswer_view', array('templateurl' => $templateurl, 'clang' => $clang), true)), $aData);
             }
             $groupoutput = array();
             $groupoutput[] = templatereplace(file_get_contents("{$templatedir}/print_group.pstpl"), array('QUESTIONS' => implode(' ', $questionoutput)), $aData);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/print_survey.pstpl"), array('GROUPS' => implode(' ', $groupoutput), 'FAX_TO' => $clang->gT("Please fax your completed survey to:") . " 000-000-000", 'SUBMIT_TEXT' => $clang->gT("Submit your survey."), 'HEADELEMENTS' => getPrintableHeader(), 'SUBMIT_BY' => sprintf($clang->gT("Please submit by %s"), date('d.m.y')), 'THANKS' => $clang->gT('Thank you for completing this survey.'), 'END' => $clang->gT('This is the survey end message.')), $aData);
             break;
         case 'printanswers':
             unset($files);
             foreach ($printtemplate as $qs) {
                 $files[] = array("name" => $qs);
             }
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/startpage.pstpl"), array(), $aData);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/printanswers.pstpl"), array('ANSWERTABLE' => $printoutput), $aData);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/endpage.pstpl"), array(), $aData);
             $myoutput[] = "\n";
             break;
     }
     $myoutput[] = "</html>";
     if (is_array($files)) {
         $match = 0;
         foreach ($files as $f) {
             if ($editfile == $f["name"]) {
                 $match = 1;
             }
         }
         foreach ($cssfiles as $f) {
             if ($editfile == $f["name"]) {
                 $match = 1;
             }
         }
         if ($match == 0) {
             if (count($files) > 0) {
                 $editfile = $files[0]["name"];
             } else {
                 $editfile = "";
             }
         }
     }
     // Get list of 'otherfiles'
     $otherfiles = array();
     if ($handle = opendir($templatedir)) {
         while (false !== ($file = readdir($handle))) {
             if (!array_search($file, $normalfiles)) {
                 if (!is_dir($templatedir . DIRECTORY_SEPARATOR . $file)) {
                     $otherfiles[] = array("name" => $file);
                 }
             }
         }
         closedir($handle);
     }
     $aData['clang'] = $this->getController()->lang;
     $aData['codelanguage'] = $codelanguage;
     $aData['highlighter'] = $highlighter;
     $aData['screens'] = $screens;
     $aData['templatename'] = $templatename;
     $aData['templates'] = $templates;
     $aData['editfile'] = $editfile;
     $aData['screenname'] = $screenname;
     $aData['tempdir'] = Yii::app()->getConfig('tempdir');
     $aData['usertemplaterootdir'] = Yii::app()->getConfig('usertemplaterootdir');
     $aViewUrls['templateeditorbar_view'][] = $aData;
     if ($showsummary) {
         $aViewUrls = array_merge($aViewUrls, $this->_templatesummary($templatename, $screenname, $editfile, $templates, $files, $cssfiles, $otherfiles, $myoutput));
     }
     App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('adminscripts') . 'admin_core.js');
     return $aViewUrls;
 }
예제 #26
0
function UpdateStep1()
{
    global $clang, $scriptname, $updatekey, $subaction, $updatebuild, $homedir, $buildnumber, $tempdir, $rootdir;


    if ($subaction=='keyupdate')
    {
        setGlobalSetting('updatekey',sanitize_paranoid_string($_POST['updatekey']));
    }
    $error=false;
    echo '<div class="header ui-widget-header">'.$clang->gT('Welcome to the ComfortUpdate').'</div><div class="updater-background"><br />';
    echo $clang->gT('The LimeSurvey ComfortUpdate is an easy procedure to quickly update to the latest version of LimeSurvey.').'<br />';
    echo $clang->gT('The following steps will be done by this update:').'<br /><ul>';
    echo '<li>'.$clang->gT('Your LimeSurvey installation is checked if the update can be run successfully.').'</li>';
    echo '<li>'.$clang->gT('Your DB and any changed files will be backed up.').'</li>';
    echo '<li>'.$clang->gT('New files will be downloaded and installed.').'</li>';
    echo '<li>'.$clang->gT('If necessary the database will be updated.').'</li></ul>';
    echo '<h3>'.$clang->gT('Checking basic requirements...').'</h3>';
    if ($updatekey==''){
        echo $clang->gT('You need an update key to run the comfort update. During the beta test of this update feature the key "LIMESURVEYUPDATE" can be used.');
        echo "<br /><form id='keyupdate' method='post' action='$scriptname?action=update&amp;subaction=keyupdate'><label for='updatekey'>".$clang->gT('Please enter a valid update-key:').'</label>';
        echo '<input id="updatekey" name="updatekey" type="text" value="LIMESURVEYUPDATE" /> <input type="submit" value="'.$clang->gT('Save update key').'" /></form>';
    }
    else {
        echo "<ul><li class='successtitle'>".$clang->gT('Update key: Valid')."</li>";

        if (!is_writable($tempdir))
        {
            echo  "<li class='errortitle'>".sprintf($clang->gT("Tempdir %s is not writable"),$tempdir)."<li>";
            $error=true;
        }
        if (!is_writable($rootdir.DIRECTORY_SEPARATOR.'version.php'))
        {
            echo  "<li class='errortitle'>".sprintf($clang->gT("Version file is not writable (%s). Please set according file permissions."),$rootdir.DIRECTORY_SEPARATOR.'version.php')."</li>";
            $error=true;
        }
        echo '</ul><h3>'.$clang->gT('Change log').'</h3>';
        require_once($homedir."/classes/http/http.php");
        $updatekey=getGlobalSetting('updatekey');

        $http=new http_class;
        /* Connection timeout */
        $http->timeout=0;
        /* Data transfer timeout */
        $http->data_timeout=0;
        $http->user_agent="Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)";
        $http->GetRequestArguments("http://update.limesurvey.org/updates/changelog/$buildnumber/$updatebuild/$updatekey",$arguments);

        $updateinfo=false;
        $httperror=$http->Open($arguments);
        $httperror=$http->SendRequest($arguments);

        if($httperror=="") {
            $body=''; $full_body='';
            for(;;){
                $httperror = $http->ReadReplyBody($body,10000);
                if($httperror != "" || strlen($body)==0) break;
                $full_body .= $body;
            }
            $changelog=json_decode($full_body,true);
            echo '<textarea class="updater-changelog" readonly="readonly">'.htmlspecialchars($changelog['changelog']).'</textarea>';
        }
        else
        {
            print( $httperror );
        }
    }


    if ($error)
    {
        echo '<br /><br />'.$clang->gT('When checking your installation we found one or more problems. Please check for any error messages above and fix these before you can proceed.');
        echo "<p><button onclick=\"window.open('$scriptname?action=update&amp;subaction=step1', '_top')\"";
        echo ">".$clang->gT('Check again')."</button></p>";
    }
    else
    {
        echo '<br /><br />'.$clang->gT('Everything looks alright. Please proceed to the next step.');
        echo "<p><button onclick=\"window.open('$scriptname?action=update&amp;subaction=step2', '_top')\"";
        if ($updatekey==''){    echo "disabled='disabled'"; }
        echo ">".sprintf($clang->gT('Proceed to step %s'),'2')."</button></p>";
    }
    echo '</div>';
}
예제 #27
0
function hasTemplateManageRights($userid, $templatefolder)
{
    $userid = sanitize_int($userid);
    $templatefolder = sanitize_paranoid_string($templatefolder);
    return Permission::model()->hasTemplatePermission($templatefolder, 'read', $userid);
}
예제 #28
0
 /**
  * Database::index()
  *
  * @param mixed $sa
  * @return
  */
 function index($sa = null)
 {
     $sAction = Yii::app()->request->getPost('action');
     $iSurveyID = returnGlobal('sid');
     $iQuestionGroupID = returnGlobal('gid');
     $iQuestionID = returnGlobal('qid');
     $sDBOutput = '';
     $oFixCKeditor = new LSYii_Validators();
     $oFixCKeditor->fixCKeditor = true;
     $oFixCKeditor->xssfilter = false;
     if ($sAction == "updatedefaultvalues" && Permission::model()->hasSurveyPermission($iSurveyID, 'surveycontent', 'update')) {
         $aSurveyLanguages = Survey::model()->findByPk($iSurveyID)->additionalLanguages;
         $sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language;
         array_unshift($aSurveyLanguages, $sBaseLanguage);
         Question::model()->updateAll(array('same_default' => Yii::app()->request->getPost('samedefault') ? 1 : 0), 'sid=:sid ANd qid=:qid', array(':sid' => $iSurveyID, ':qid' => $iQuestionID));
         $arQuestion = Question::model()->findByAttributes(array('qid' => $iQuestionID));
         $sQuestionType = $arQuestion['type'];
         $aQuestionTypeList = getQuestionTypeList('', 'array');
         if ($aQuestionTypeList[$sQuestionType]['answerscales'] > 0 && $aQuestionTypeList[$sQuestionType]['subquestions'] == 0) {
             for ($iScaleID = 0; $iScaleID < $aQuestionTypeList[$sQuestionType]['answerscales']; $iScaleID++) {
                 foreach ($aSurveyLanguages as $sLanguage) {
                     if (!is_null(Yii::app()->request->getPost('defaultanswerscale_' . $iScaleID . '_' . $sLanguage))) {
                         $this->_updateDefaultValues($iQuestionID, 0, $iScaleID, '', $sLanguage, Yii::app()->request->getPost('defaultanswerscale_' . $iScaleID . '_' . $sLanguage), true);
                     }
                     if (!is_null(Yii::app()->request->getPost('other_' . $iScaleID . '_' . $sLanguage))) {
                         $this->_updateDefaultValues($iQuestionID, 0, $iScaleID, 'other', $sLanguage, Yii::app()->request->getPost('other_' . $iScaleID . '_' . $sLanguage), true);
                     }
                 }
             }
         }
         if ($aQuestionTypeList[$sQuestionType]['subquestions'] > 0) {
             foreach ($aSurveyLanguages as $sLanguage) {
                 $arQuestions = Question::model()->findAllByAttributes(array('sid' => $iSurveyID, 'gid' => $iQuestionGroupID, 'parent_qid' => $iQuestionID, 'language' => $sLanguage, 'scale_id' => 0));
                 for ($iScaleID = 0; $iScaleID < $aQuestionTypeList[$sQuestionType]['subquestions']; $iScaleID++) {
                     foreach ($arQuestions as $aSubquestionrow) {
                         if (!is_null(Yii::app()->request->getPost('defaultanswerscale_' . $iScaleID . '_' . $sLanguage . '_' . $aSubquestionrow['qid']))) {
                             $this->_updateDefaultValues($iQuestionID, $aSubquestionrow['qid'], $iScaleID, '', $sLanguage, Yii::app()->request->getPost('defaultanswerscale_' . $iScaleID . '_' . $sLanguage . '_' . $aSubquestionrow['qid']), true);
                         }
                     }
                 }
             }
         }
         if ($aQuestionTypeList[$sQuestionType]['answerscales'] == 0 && $aQuestionTypeList[$sQuestionType]['subquestions'] == 0) {
             foreach ($aSurveyLanguages as $sLanguage) {
                 // Qick and dirty insert for yes/no defaul value
                 // write the the selectbox option, or if "EM" is slected, this value to table
                 if ($sQuestionType == 'Y') {
                     /// value for all langs
                     if (Yii::app()->request->getPost('samedefault') == 1) {
                         $sLanguage = $aSurveyLanguages[0];
                         // turn
                     } else {
                         $sCurrentLang = $sLanguage;
                         // edit the next lines
                     }
                     if (Yii::app()->request->getPost('defaultanswerscale_0_' . $sLanguage) == 'EM') {
                         // Case EM, write expression to database
                         $this->_updateDefaultValues($iQuestionID, 0, 0, '', $sLanguage, Yii::app()->request->getPost('defaultanswerscale_0_' . $sLanguage . '_EM'), true);
                     } else {
                         // Case "other", write list value to database
                         $this->_updateDefaultValues($iQuestionID, 0, 0, '', $sLanguage, Yii::app()->request->getPost('defaultanswerscale_0_' . $sLanguage), true);
                     }
                     ///// end yes/no
                 } else {
                     if (!is_null(Yii::app()->request->getPost('defaultanswerscale_0_' . $sLanguage . '_0'))) {
                         $this->_updateDefaultValues($iQuestionID, 0, 0, '', $sLanguage, Yii::app()->request->getPost('defaultanswerscale_0_' . $sLanguage . '_0'), true);
                     }
                 }
             }
         }
         Yii::app()->session['flashmessage'] = gT("Default value settings were successfully saved.");
         LimeExpressionManager::SetDirtyFlag();
         if ($sDBOutput != '') {
             echo $sDBOutput;
         } else {
             $this->getController()->redirect(array('admin/survey/sa/view/surveyid/' . $iSurveyID . '/gid/' . $iQuestionGroupID . '/qid/' . $iQuestionID));
         }
     }
     if ($sAction == "updateansweroptions" && Permission::model()->hasSurveyPermission($iSurveyID, 'surveycontent', 'update')) {
         Yii::app()->loadHelper('database');
         $aSurveyLanguages = Survey::model()->findByPk($iSurveyID)->additionalLanguages;
         $sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language;
         array_unshift($aSurveyLanguages, $sBaseLanguage);
         $arQuestion = Question::model()->findByAttributes(array('qid' => $iQuestionID));
         $sQuestionType = $arQuestion['type'];
         // Checked)
         $aQuestionTypeList = getQuestionTypeList('', 'array');
         $iScaleCount = $aQuestionTypeList[$sQuestionType]['answerscales'];
         //First delete all answers
         Answer::model()->deleteAllByAttributes(array('qid' => $iQuestionID));
         LimeExpressionManager::RevertUpgradeConditionsToRelevance($iSurveyID);
         for ($iScaleID = 0; $iScaleID < $iScaleCount; $iScaleID++) {
             $iMaxCount = (int) Yii::app()->request->getPost('answercount_' . $iScaleID);
             for ($iSortOrderID = 1; $iSortOrderID < $iMaxCount; $iSortOrderID++) {
                 $sCode = sanitize_paranoid_string(Yii::app()->request->getPost('code_' . $iSortOrderID . '_' . $iScaleID));
                 $iAssessmentValue = (int) Yii::app()->request->getPost('assessment_' . $iSortOrderID . '_' . $iScaleID);
                 foreach ($aSurveyLanguages as $sLanguage) {
                     $sAnswerText = Yii::app()->request->getPost('answer_' . $sLanguage . '_' . $iSortOrderID . '_' . $iScaleID);
                     // Fix bug with FCKEditor saving strange BR types
                     $sAnswerText = $oFixCKeditor->fixCKeditor($sAnswerText);
                     // Now we insert the answers
                     $iInsertCount = Answer::model()->insertRecords(array('code' => $sCode, 'answer' => $sAnswerText, 'qid' => $iQuestionID, 'sortorder' => $iSortOrderID, 'language' => $sLanguage, 'assessment_value' => $iAssessmentValue, 'scale_id' => $iScaleID));
                     if (!$iInsertCount) {
                         Yii::app()->setFlashMessage(gT("Failed to update answers"), 'error');
                     }
                 }
                 // Updating code (oldcode!==null) => update condition with the new code
                 $sOldCode = Yii::app()->request->getPost('oldcode_' . $iSortOrderID . '_' . $iScaleID);
                 if (isset($sOldCode) && $sCode !== $sOldCode) {
                     Condition::model()->updateAll(array('value' => $sCode), 'cqid=:cqid AND value=:value', array(':cqid' => $iQuestionID, ':value' => $sOldCode));
                 }
             }
             // for ($sortorderid=0;$sortorderid<$maxcount;$sortorderid++)
         }
         //  for ($scale_id=0;
         LimeExpressionManager::UpgradeConditionsToRelevance($iSurveyID);
         if (!Yii::app()->request->getPost('bFullPOST')) {
             Yii::app()->setFlashMessage(gT("Not all answer options were saved. This usually happens due to server limitations ( PHP setting max_input_vars) - please contact your system administrator."));
         } else {
             Yii::app()->session['flashmessage'] = gT("Answer options were successfully saved.");
         }
         LimeExpressionManager::SetDirtyFlag();
         if ($sDBOutput != '') {
             echo $sDBOutput;
         } else {
             $this->getController()->redirect(array('/admin/questions/sa/answeroptions/surveyid/' . $iSurveyID . '/gid/' . $iQuestionGroupID . '/qid/' . $iQuestionID));
         }
     }
     if ($sAction == "updatesubquestions" && Permission::model()->hasSurveyPermission($iSurveyID, 'surveycontent', 'update')) {
         Yii::app()->loadHelper('database');
         $aSurveyLanguages = Survey::model()->findByPk($iSurveyID)->additionalLanguages;
         $sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language;
         array_unshift($aSurveyLanguages, $sBaseLanguage);
         $arQuestion = Question::model()->findByAttributes(array('qid' => $iQuestionID));
         $sQuestionType = $arQuestion['type'];
         // Checked
         $aQuestionTypeList = getQuestionTypeList('', 'array');
         $iScaleCount = $aQuestionTypeList[$sQuestionType]['subquestions'];
         // First delete any deleted ids
         $aDeletedQIDs = explode(' ', trim(Yii::app()->request->getPost('deletedqids')));
         LimeExpressionManager::RevertUpgradeConditionsToRelevance($iSurveyID);
         $aDeletedQIDs = array_unique($aDeletedQIDs, SORT_NUMERIC);
         foreach ($aDeletedQIDs as $iDeletedQID) {
             $iDeletedQID = (int) $iDeletedQID;
             if ($iDeletedQID > 0) {
                 // don't remove undefined
                 $iInsertCount = Question::model()->deleteAllByAttributes(array('qid' => $iDeletedQID));
                 if (!$iInsertCount) {
                     Yii::app()->setFlashMessage(gT("Failed to delete answer"), 'error');
                 }
             }
         }
         //Determine ids by evaluating the hidden field
         $aRows = array();
         $aCodes = array();
         $aOldCodes = array();
         $aRelevance = array();
         foreach ($_POST as $sPOSTKey => $sPOSTValue) {
             $sPOSTKey = explode('_', $sPOSTKey);
             if ($sPOSTKey[0] == 'answer') {
                 $aRows[$sPOSTKey[3]][$sPOSTKey[1]][$sPOSTKey[2]] = $sPOSTValue;
             }
             if ($sPOSTKey[0] == 'code') {
                 $aCodes[$sPOSTKey[2]][] = $sPOSTValue;
             }
             if ($sPOSTKey[0] == 'oldcode') {
                 $aOldCodes[$sPOSTKey[2]][] = $sPOSTValue;
             }
             if ($sPOSTKey[0] == 'relevance') {
                 $aRelevance[$sPOSTKey[2]][] = $sPOSTValue;
             }
         }
         $aInsertQID = array();
         for ($iScaleID = 0; $iScaleID < $iScaleCount; $iScaleID++) {
             foreach ($aSurveyLanguages as $sLanguage) {
                 $iPosition = 0;
                 foreach ($aRows[$iScaleID][$sLanguage] as $subquestionkey => $subquestionvalue) {
                     if (substr($subquestionkey, 0, 3) != 'new') {
                         $oSubQuestion = Question::model()->find("qid=:qid AND language=:language", array(":qid" => $subquestionkey, ':language' => $sLanguage));
                         $oSubQuestion->question_order = $iPosition + 1;
                         $oSubQuestion->title = $aCodes[$iScaleID][$iPosition];
                         $oSubQuestion->question = $subquestionvalue;
                         $oSubQuestion->scale_id = $iScaleID;
                         //dual matrix, text/number matrix: subQ relevance per line not per scale, so ScaleID is always 0
                         $oSubQuestion->relevance = $aRelevance[0][$iPosition];
                     } else {
                         if (!isset($aInsertQID[$iScaleID][$iPosition])) {
                             $oSubQuestion = new Question();
                             $oSubQuestion->sid = $iSurveyID;
                             $oSubQuestion->gid = $iQuestionGroupID;
                             $oSubQuestion->question_order = $iPosition + 1;
                             $oSubQuestion->title = $aCodes[$iScaleID][$iPosition];
                             $oSubQuestion->question = $subquestionvalue;
                             $oSubQuestion->parent_qid = $iQuestionID;
                             $oSubQuestion->language = $sLanguage;
                             $oSubQuestion->scale_id = $iScaleID;
                             $oSubQuestion->relevance = $aRelevance[0][$iPosition];
                         } else {
                             $oSubQuestion = Question::model()->find("qid=:qid AND language=:language", array(":qid" => $aInsertQID[$iScaleID][$iPosition], ':language' => $sLanguage));
                             if (!$oSubQuestion) {
                                 $oSubQuestion = new Question();
                             }
                             $oSubQuestion->sid = $iSurveyID;
                             $oSubQuestion->qid = $aInsertQID[$iScaleID][$iPosition];
                             $oSubQuestion->gid = $iQuestionGroupID;
                             $oSubQuestion->question_order = $iPosition + 1;
                             $oSubQuestion->title = $aCodes[$iScaleID][$iPosition];
                             $oSubQuestion->question = $subquestionvalue;
                             $oSubQuestion->parent_qid = $iQuestionID;
                             $oSubQuestion->language = $sLanguage;
                             $oSubQuestion->scale_id = $iScaleID;
                             $oSubQuestion->relevance = $aRelevance[$iScaleID][$iPosition];
                         }
                     }
                     if ($oSubQuestion->qid) {
                         switchMSSQLIdentityInsert('questions', true);
                         $bSubQuestionResult = $oSubQuestion->save();
                         switchMSSQLIdentityInsert('questions', false);
                     } else {
                         $bSubQuestionResult = $oSubQuestion->save();
                     }
                     if ($bSubQuestionResult) {
                         if (substr($subquestionkey, 0, 3) != 'new' && isset($aOldCodes[$iScaleID][$iPosition]) && $aCodes[$iScaleID][$iPosition] !== $aOldCodes[$iScaleID][$iPosition]) {
                             Condition::model()->updateAll(array('cfieldname' => '+' . $iSurveyID . 'X' . $iQuestionGroupID . 'X' . $iQuestionID . $aCodes[$iScaleID][$iPosition], 'value' => $aCodes[$iScaleID][$iPosition]), 'cqid=:cqid AND cfieldname=:cfieldname AND value=:value', array(':cqid' => $iQuestionID, ':cfieldname' => $iSurveyID . 'X' . $iQuestionGroupID . 'X' . $iQuestionID, ':value' => $aOldCodes[$iScaleID][$iPosition]));
                         }
                         if (!isset($aInsertQID[$iScaleID][$iPosition])) {
                             $aInsertQID[$iScaleID][$iPosition] = $oSubQuestion->qid;
                         }
                     } else {
                         $aErrors = $oSubQuestion->getErrors();
                         if (count($aErrors)) {
                             //$sErrorMessage=gT("Question could not be updated with this errors:");
                             foreach ($aErrors as $sAttribute => $aStringErrors) {
                                 foreach ($aStringErrors as $sStringErrors) {
                                     Yii::app()->setFlashMessage(sprintf(gT("Error on %s for subquestion %s: %s"), $sAttribute, $aCodes[$iScaleID][$iPosition], $sStringErrors), 'error');
                                 }
                             }
                         } else {
                             Yii::app()->setFlashMessage(sprintf(gT("Subquestions %s could not be updated."), $aCodes[$iScaleID][$iPosition]), 'error');
                         }
                     }
                     $iPosition++;
                 }
             }
         }
         LimeExpressionManager::UpgradeConditionsToRelevance($iSurveyID);
         // Do it only if there are no error ?
         if (!isset($aErrors) || !count($aErrors)) {
             if (!Yii::app()->request->getPost('bFullPOST')) {
                 Yii::app()->session['flashmessage'] = gT("Not all subquestions were saved. This usually happens due to server limitations ( PHP setting max_input_vars) - please contact your system administrator.");
             } else {
                 Yii::app()->session['flashmessage'] = gT("Subquestions were successfully saved.");
             }
         }
         //$action='editsubquestions';
         LimeExpressionManager::SetDirtyFlag();
         if ($sDBOutput != '') {
             echo $sDBOutput;
         } else {
             $this->getController()->redirect(array('/admin/questions/sa/subquestions/surveyid/' . $iSurveyID . '/gid/' . $iQuestionGroupID . '/qid/' . $iQuestionID));
         }
     }
     if (in_array($sAction, array('insertquestion', 'copyquestion')) && Permission::model()->hasSurveyPermission($iSurveyID, 'surveycontent', 'create')) {
         $sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language;
         if (strlen(Yii::app()->request->getPost('title')) < 1) {
             Yii::app()->setFlashMessage(gT("The question could not be added. You must enter at least a question code."), 'error');
         } else {
             if (Yii::app()->request->getPost('questionposition', "") != "") {
                 $iQuestionOrder = intval(Yii::app()->request->getPost('questionposition'));
                 //Need to renumber all questions on or after this
                 $sQuery = "UPDATE {{questions}} SET question_order=question_order+1 WHERE gid=:gid AND question_order >= :order";
                 Yii::app()->db->createCommand($sQuery)->bindValues(array(':gid' => $iQuestionGroupID, ':order' => $iQuestionOrder))->query();
             } else {
                 $iQuestionOrder = getMaxQuestionOrder($iQuestionGroupID, $iSurveyID);
                 $iQuestionOrder++;
             }
             $sQuestionText = Yii::app()->request->getPost('question_' . $sBaseLanguage, '');
             $sQuestionHelp = Yii::app()->request->getPost('help_' . $sBaseLanguage, '');
             // Fix bug with FCKEditor saving strange BR types : in rules ?
             $sQuestionText = $oFixCKeditor->fixCKeditor($sQuestionText);
             $sQuestionHelp = $oFixCKeditor->fixCKeditor($sQuestionHelp);
             $iQuestionID = 0;
             $oQuestion = new Question();
             $oQuestion->sid = $iSurveyID;
             $oQuestion->gid = $iQuestionGroupID;
             $oQuestion->type = Yii::app()->request->getPost('type');
             $oQuestion->title = Yii::app()->request->getPost('title');
             $oQuestion->question = $sQuestionText;
             $oQuestion->preg = Yii::app()->request->getPost('preg');
             $oQuestion->help = $sQuestionHelp;
             $oQuestion->other = Yii::app()->request->getPost('other');
             $oQuestion->mandatory = Yii::app()->request->getPost('mandatory');
             $oQuestion->relevance = Yii::app()->request->getPost('relevance');
             $oQuestion->question_order = $iQuestionOrder;
             $oQuestion->language = $sBaseLanguage;
             $oQuestion->save();
             if ($oQuestion) {
                 $iQuestionID = $oQuestion->qid;
             }
             $aErrors = $oQuestion->getErrors();
             if (count($aErrors)) {
                 foreach ($aErrors as $sAttribute => $aStringErrors) {
                     foreach ($aStringErrors as $sStringErrors) {
                         Yii::app()->setFlashMessage(sprintf(gT("Question could not be created with error on %s: %s"), $sAttribute, $sStringErrors), 'error');
                     }
                 }
             }
             // Add other languages
             if ($iQuestionID) {
                 $addlangs = Survey::model()->findByPk($iSurveyID)->additionalLanguages;
                 foreach ($addlangs as $alang) {
                     if ($alang != "") {
                         $langqid = 0;
                         $oQuestion = new Question();
                         $oQuestion->qid = $iQuestionID;
                         $oQuestion->sid = $iSurveyID;
                         $oQuestion->gid = $iQuestionGroupID;
                         $oQuestion->type = Yii::app()->request->getPost('type');
                         $oQuestion->title = Yii::app()->request->getPost('title');
                         $oQuestion->question = Yii::app()->request->getPost('question_' . $alang);
                         $oQuestion->preg = Yii::app()->request->getPost('preg');
                         $oQuestion->help = Yii::app()->request->getPost('help_' . $alang);
                         $oQuestion->other = Yii::app()->request->getPost('other');
                         $oQuestion->mandatory = Yii::app()->request->getPost('mandatory');
                         $oQuestion->relevance = Yii::app()->request->getPost('relevance');
                         $oQuestion->question_order = $iQuestionOrder;
                         $oQuestion->language = $alang;
                         switchMSSQLIdentityInsert('questions', true);
                         // Not sure for this one ?
                         $oQuestion->save();
                         switchMSSQLIdentityInsert('questions', false);
                         if ($oQuestion) {
                             $langqid = $oQuestion->qid;
                         }
                         $aErrors = $oQuestion->getErrors();
                         if (count($aErrors)) {
                             foreach ($aErrors as $sAttribute => $aStringErrors) {
                                 foreach ($aStringErrors as $sStringErrors) {
                                     Yii::app()->setFlashMessage(sprintf(gT("Question in language %s could not be created with error on %s: %s"), $alang, $sAttribute, $sStringErrors), 'error');
                                 }
                             }
                         }
                         #                            if (!$langqid)
                         #                            {
                         #                                Yii::app()->setFlashMessage(gT("Question in language %s could not be created."),'error');
                         #                            }
                     }
                 }
             }
             if (!$iQuestionID) {
                 Yii::app()->setFlashMessage(gT("Question could not be created."), 'error');
             } else {
                 if ($sAction == 'copyquestion') {
                     if (returnGlobal('copysubquestions') == "Y") {
                         $aSQIDMappings = array();
                         $r1 = Question::model()->getSubQuestions(returnGlobal('oldqid'));
                         $aSubQuestions = $r1->readAll();
                         foreach ($aSubQuestions as $qr1) {
                             $qr1['parent_qid'] = $iQuestionID;
                             if (isset($aSQIDMappings[$qr1['qid']])) {
                                 $qr1['qid'] = $aSQIDMappings[$qr1['qid']];
                             } else {
                                 $oldqid = $qr1['qid'];
                                 unset($qr1['qid']);
                             }
                             $qr1['gid'] = $iQuestionGroupID;
                             $iInsertID = Question::model()->insertRecords($qr1);
                             if (!isset($qr1['qid'])) {
                                 $aSQIDMappings[$oldqid] = $iInsertID;
                             }
                         }
                     }
                     if (returnGlobal('copyanswers') == "Y") {
                         $r1 = Answer::model()->getAnswers(returnGlobal('oldqid'));
                         $aAnswerOptions = $r1->readAll();
                         foreach ($aAnswerOptions as $qr1) {
                             Answer::model()->insertRecords(array('qid' => $iQuestionID, 'code' => $qr1['code'], 'answer' => $qr1['answer'], 'assessment_value' => $qr1['assessment_value'], 'sortorder' => $qr1['sortorder'], 'language' => $qr1['language'], 'scale_id' => $qr1['scale_id']));
                         }
                     }
                     if (returnGlobal('copyattributes') == "Y") {
                         $oOldAttributes = QuestionAttribute::model()->findAll("qid=:qid", array("qid" => returnGlobal('oldqid')));
                         foreach ($oOldAttributes as $oOldAttribute) {
                             $attribute = new QuestionAttribute();
                             $attribute->qid = $iQuestionID;
                             $attribute->value = $oOldAttribute->value;
                             $attribute->attribute = $oOldAttribute->attribute;
                             $attribute->language = $oOldAttribute->language;
                             $attribute->save();
                         }
                     }
                 } else {
                     $qattributes = questionAttributes();
                     $validAttributes = $qattributes[Yii::app()->request->getPost('type')];
                     $aLanguages = array_merge(array(Survey::model()->findByPk($iSurveyID)->language), Survey::model()->findByPk($iSurveyID)->additionalLanguages);
                     foreach ($validAttributes as $validAttribute) {
                         if ($validAttribute['i18n']) {
                             foreach ($aLanguages as $sLanguage) {
                                 $value = Yii::app()->request->getPost($validAttribute['name'] . '_' . $sLanguage);
                                 $iInsertCount = QuestionAttribute::model()->findAllByAttributes(array('attribute' => $validAttribute['name'], 'qid' => $iQuestionID, 'language' => $sLanguage));
                                 if (count($iInsertCount) > 0) {
                                     if ($value != '') {
                                         QuestionAttribute::model()->updateAll(array('value' => $value), 'attribute=:attribute AND qid=:qid AND language=:language', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID, ':language' => $sLanguage));
                                     } else {
                                         QuestionAttribute::model()->deleteAll('attribute=:attribute AND qid=:qid AND language=:language', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID, ':language' => $sLanguage));
                                     }
                                 } elseif ($value != '') {
                                     $attribute = new QuestionAttribute();
                                     $attribute->qid = $iQuestionID;
                                     $attribute->value = $value;
                                     $attribute->attribute = $validAttribute['name'];
                                     $attribute->language = $sLanguage;
                                     $attribute->save();
                                 }
                             }
                         } else {
                             $value = Yii::app()->request->getPost($validAttribute['name']);
                             if ($validAttribute['name'] == 'multiflexible_step' && trim($value) != '') {
                                 $value = floatval($value);
                                 if ($value == 0) {
                                     $value = 1;
                                 }
                             }
                             $iInsertCount = QuestionAttribute::model()->findAllByAttributes(array('attribute' => $validAttribute['name'], 'qid' => $iQuestionID));
                             if (count($iInsertCount) > 0) {
                                 if ($value != $validAttribute['default'] && trim($value) != "") {
                                     QuestionAttribute::model()->updateAll(array('value' => $value), 'attribute=:attribute AND qid=:qid', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID));
                                 } else {
                                     QuestionAttribute::model()->deleteAll('attribute=:attribute AND qid=:qid', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID));
                                 }
                             } elseif ($value != $validAttribute['default'] && trim($value) != "") {
                                 $attribute = new QuestionAttribute();
                                 $attribute->qid = $iQuestionID;
                                 $attribute->value = $value;
                                 $attribute->attribute = $validAttribute['name'];
                                 $attribute->save();
                             }
                         }
                     }
                 }
                 Question::model()->updateQuestionOrder($iQuestionGroupID, $iSurveyID);
                 Yii::app()->session['flashmessage'] = gT("Question was successfully added.");
             }
         }
         LimeExpressionManager::SetDirtyFlag();
         // so refreshes syntax highlighting
         if ($sDBOutput != '') {
             echo $sDBOutput;
         } else {
             $this->getController()->redirect(array('admin/survey/sa/view/surveyid/' . $iSurveyID . '/gid/' . $iQuestionGroupID . '/qid/' . $iQuestionID));
         }
     }
     if ($sAction == "updatequestion" && Permission::model()->hasSurveyPermission($iSurveyID, 'surveycontent', 'update')) {
         LimeExpressionManager::RevertUpgradeConditionsToRelevance($iSurveyID);
         $cqr = Question::model()->findByAttributes(array('qid' => $iQuestionID));
         $oldtype = $cqr['type'];
         $oldgid = $cqr['gid'];
         // Remove invalid question attributes on saving
         $qattributes = questionAttributes();
         $criteria = new CDbCriteria();
         $criteria->compare('qid', $iQuestionID);
         if (isset($qattributes[Yii::app()->request->getPost('type')])) {
             $validAttributes = $qattributes[Yii::app()->request->getPost('type')];
             foreach ($validAttributes as $validAttribute) {
                 $criteria->compare('attribute', '<>' . $validAttribute['name']);
             }
         }
         QuestionAttribute::model()->deleteAll($criteria);
         $aLanguages = array_merge(array(Survey::model()->findByPk($iSurveyID)->language), Survey::model()->findByPk($iSurveyID)->additionalLanguages);
         //now save all valid attributes
         $validAttributes = $qattributes[Yii::app()->request->getPost('type')];
         foreach ($validAttributes as $validAttribute) {
             if ($validAttribute['i18n']) {
                 foreach ($aLanguages as $sLanguage) {
                     // TODO sanitise XSS
                     $value = Yii::app()->request->getPost($validAttribute['name'] . '_' . $sLanguage);
                     $iInsertCount = QuestionAttribute::model()->findAllByAttributes(array('attribute' => $validAttribute['name'], 'qid' => $iQuestionID, 'language' => $sLanguage));
                     if (count($iInsertCount) > 0) {
                         if ($value != '') {
                             QuestionAttribute::model()->updateAll(array('value' => $value), 'attribute=:attribute AND qid=:qid AND language=:language', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID, ':language' => $sLanguage));
                         } else {
                             QuestionAttribute::model()->deleteAll('attribute=:attribute AND qid=:qid AND language=:language', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID, ':language' => $sLanguage));
                         }
                     } elseif ($value != '') {
                         $attribute = new QuestionAttribute();
                         $attribute->qid = $iQuestionID;
                         $attribute->value = $value;
                         $attribute->attribute = $validAttribute['name'];
                         $attribute->language = $sLanguage;
                         $attribute->save();
                     }
                 }
             } else {
                 $value = Yii::app()->request->getPost($validAttribute['name']);
                 if ($validAttribute['name'] == 'multiflexible_step' && trim($value) != '') {
                     $value = floatval($value);
                     if ($value == 0) {
                         $value = 1;
                     }
                 }
                 $iInsertCount = QuestionAttribute::model()->findAllByAttributes(array('attribute' => $validAttribute['name'], 'qid' => $iQuestionID));
                 if (count($iInsertCount) > 0) {
                     if ($value != $validAttribute['default'] && trim($value) != "") {
                         QuestionAttribute::model()->updateAll(array('value' => $value), 'attribute=:attribute AND qid=:qid', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID));
                     } else {
                         QuestionAttribute::model()->deleteAll('attribute=:attribute AND qid=:qid', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID));
                     }
                 } elseif ($value != $validAttribute['default'] && trim($value) != "") {
                     $attribute = new QuestionAttribute();
                     $attribute->qid = $iQuestionID;
                     $attribute->value = $value;
                     $attribute->attribute = $validAttribute['name'];
                     $attribute->save();
                 }
             }
         }
         $aQuestionTypeList = getQuestionTypeList('', 'array');
         // These are the questions types that have no answers and therefore we delete the answer in that case
         $iAnswerScales = $aQuestionTypeList[Yii::app()->request->getPost('type')]['answerscales'];
         $iSubquestionScales = $aQuestionTypeList[Yii::app()->request->getPost('type')]['subquestions'];
         // These are the questions types that have the other option therefore we set everything else to 'No Other'
         if (Yii::app()->request->getPost('type') != "L" && Yii::app()->request->getPost('type') != "!" && Yii::app()->request->getPost('type') != "P" && Yii::app()->request->getPost('type') != "M") {
             $_POST['other'] = 'N';
         }
         // These are the questions types that have no validation - so zap it accordingly
         if (Yii::app()->request->getPost('type') == "!" || Yii::app()->request->getPost('type') == "L" || Yii::app()->request->getPost('type') == "M" || Yii::app()->request->getPost('type') == "P" || Yii::app()->request->getPost('type') == "F" || Yii::app()->request->getPost('type') == "H" || Yii::app()->request->getPost('type') == "X" || Yii::app()->request->getPost('type') == "") {
             $_POST['preg'] = '';
         }
         // These are the questions types that have no mandatory property - so zap it accordingly
         if (Yii::app()->request->getPost('type') == "X" || Yii::app()->request->getPost('type') == "|") {
             $_POST['mandatory'] = 'N';
         }
         if ($oldtype != Yii::app()->request->getPost('type')) {
             // TMSW Condition->Relevance:  Do similar check via EM, but do allow such a change since will be easier to modify relevance
             //Make sure there are no conditions based on this question, since we are changing the type
             $ccresult = Condition::model()->findAllByAttributes(array('cqid' => $iQuestionID));
             $cccount = count($ccresult);
             foreach ($ccresult as $ccr) {
                 $qidarray[] = $ccr['qid'];
             }
             if (isset($qidarray) && $qidarray) {
                 $qidlist = implode(", ", $qidarray);
             }
         }
         if (isset($cccount) && $cccount) {
             Yii::app()->setFlashMessage(gT("Question could not be updated. There are conditions for other questions that rely on the answers to this question and changing the type will cause problems. You must delete these conditions  before you can change the type of this question."), 'error');
         } else {
             if (isset($iQuestionGroupID) && $iQuestionGroupID != "") {
                 //                    $array_result=checkMoveQuestionConstraintsForConditions(sanitize_int($surveyid),sanitize_int($qid), sanitize_int($gid));
                 //                    // If there is no blocking conditions that could prevent this move
                 //
                 //                    if (is_null($array_result['notAbove']) && is_null($array_result['notBelow']))
                 //                    {
                 $aSurveyLanguages = Survey::model()->findByPk($iSurveyID)->additionalLanguages;
                 $sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language;
                 array_push($aSurveyLanguages, $sBaseLanguage);
                 foreach ($aSurveyLanguages as $qlang) {
                     if (isset($qlang) && $qlang != "") {
                         // &eacute; to é and &amp; to & : really needed ? Why not for answers ? (130307)
                         $sQuestionText = Yii::app()->request->getPost('question_' . $qlang, '');
                         $sQuestionHelp = Yii::app()->request->getPost('help_' . $qlang, '');
                         // Fix bug with FCKEditor saving strange BR types : in rules ?
                         $sQuestionText = $oFixCKeditor->fixCKeditor($sQuestionText);
                         $sQuestionHelp = $oFixCKeditor->fixCKeditor($sQuestionHelp);
                         $udata = array('type' => Yii::app()->request->getPost('type'), 'title' => Yii::app()->request->getPost('title'), 'question' => $sQuestionText, 'preg' => Yii::app()->request->getPost('preg'), 'help' => $sQuestionHelp, 'gid' => $iQuestionGroupID, 'other' => Yii::app()->request->getPost('other'), 'mandatory' => Yii::app()->request->getPost('mandatory'), 'relevance' => Yii::app()->request->getPost('relevance'));
                         if ($oldgid != $iQuestionGroupID) {
                             if (getGroupOrder($iSurveyID, $oldgid) > getGroupOrder($iSurveyID, $iQuestionGroupID)) {
                                 // TMSW Condition->Relevance:  What is needed here?
                                 // Moving question to a 'upper' group
                                 // insert question at the end of the destination group
                                 // this prevent breaking conditions if the target qid is in the dest group
                                 $insertorder = getMaxQuestionOrder($iQuestionGroupID, $iSurveyID) + 1;
                                 $udata = array_merge($udata, array('question_order' => $insertorder));
                             } else {
                                 // Moving question to a 'lower' group
                                 // insert question at the beginning of the destination group
                                 shiftOrderQuestions($iSurveyID, $iQuestionGroupID, 1);
                                 // makes 1 spare room for new question at top of dest group
                                 $udata = array_merge($udata, array('question_order' => 0));
                             }
                         }
                         //$condn = array('sid' => $surveyid, 'qid' => $qid, 'language' => $qlang);
                         $oQuestion = Question::model()->findByPk(array("qid" => $iQuestionID, 'language' => $qlang));
                         foreach ($udata as $k => $v) {
                             $oQuestion->{$k} = $v;
                         }
                         $uqresult = $oQuestion->save();
                         //($uqquery); // or safeDie ("Error Update Question: ".$uqquery."<br />");  // Checked)
                         if (!$uqresult) {
                             $bOnError = true;
                             $aErrors = $oQuestion->getErrors();
                             if (count($aErrors)) {
                                 foreach ($aErrors as $sAttribute => $aStringErrors) {
                                     foreach ($aStringErrors as $sStringErrors) {
                                         Yii::app()->setFlashMessage(sprintf(gT("Question could not be updated with error on %s: %s"), $sAttribute, $sStringErrors), 'error');
                                     }
                                 }
                             } else {
                                 Yii::app()->setFlashMessage(gT("Question could not be updated."), 'error');
                             }
                         }
                     }
                 }
                 // Update the group ID on subquestions, too
                 if ($oldgid != $iQuestionGroupID) {
                     Question::model()->updateAll(array('gid' => $iQuestionGroupID), 'qid=:qid and parent_qid>0', array(':qid' => $iQuestionID));
                     // if the group has changed then fix the sortorder of old and new group
                     Question::model()->updateQuestionOrder($oldgid, $iSurveyID);
                     Question::model()->updateQuestionOrder($iQuestionGroupID, $iSurveyID);
                     // If some questions have conditions set on this question's answers
                     // then change the cfieldname accordingly
                     fixMovedQuestionConditions($iQuestionID, $oldgid, $iQuestionGroupID);
                 }
                 if ($oldtype != Yii::app()->request->getPost('type')) {
                     Question::model()->updateAll(array('type' => Yii::app()->request->getPost('type')), 'parent_qid=:qid', array(':qid' => $iQuestionID));
                 }
                 Answer::model()->deleteAllByAttributes(array('qid' => $iQuestionID), 'scale_id >= :scale_id', array(':scale_id' => $iAnswerScales));
                 // Remove old subquestion scales
                 Question::model()->deleteAllByAttributes(array('parent_qid' => $iQuestionID), 'scale_id >= :scale_id', array(':scale_id' => $iSubquestionScales));
                 if (!isset($bOnError) || !$bOnError) {
                     // This really a quick hack and need a better system
                     Yii::app()->setFlashMessage(gT("Question was successfully saved."));
                 }
                 //                    }
                 //                    else
                 //                    {
                 //
                 //                        // There are conditions constraints: alert the user
                 //                        $errormsg="";
                 //                        if (!is_null($array_result['notAbove']))
                 //                        {
                 //                            $errormsg.=gT("This question relies on other question's answers and can't be moved above groupId:","js")
                 //                            . " " . $array_result['notAbove'][0][0] . " " . gT("in position","js")." ".$array_result['notAbove'][0][1]."\\n"
                 //                            . gT("See conditions:")."\\n";
                 //
                 //                            foreach ($array_result['notAbove'] as $notAboveCond)
                 //                            {
                 //                                $errormsg.="- cid:". $notAboveCond[3]."\\n";
                 //                            }
                 //
                 //                        }
                 //                        if (!is_null($array_result['notBelow']))
                 //                        {
                 //                            $errormsg.=gT("Some questions rely on this question's answers. You can't move this question below groupId:","js")
                 //                            . " " . $array_result['notBelow'][0][0] . " " . gT("in position","js")." ".$array_result['notBelow'][0][1]."\\n"
                 //                            . gT("See conditions:")."\\n";
                 //
                 //                            foreach ($array_result['notBelow'] as $notBelowCond)
                 //                            {
                 //                                $errormsg.="- cid:". $notBelowCond[3]."\\n";
                 //                            }
                 //                        }
                 //
                 //                        $databaseoutput .= "<script type=\"text/javascript\">\n<!--\n alert(\"$errormsg\")\n //-->\n</script>\n";
                 //                        $gid= $oldgid; // group move impossible ==> keep display on oldgid
                 //                    }
             } else {
                 Yii::app()->setFlashMessage(gT("Question could not be updated"), 'error');
             }
         }
         LimeExpressionManager::UpgradeConditionsToRelevance($iSurveyID);
         if ($sDBOutput != '') {
             echo $sDBOutput;
         } else {
             if (Yii::app()->request->getPost('redirection') == "edit") {
                 $this->getController()->redirect(array('admin/questions/sa/editquestion/surveyid/' . $iSurveyID . '/gid/' . $iQuestionGroupID . '/qid/' . $iQuestionID));
             } else {
                 $this->getController()->redirect(array('admin/survey/sa/view/surveyid/' . $iSurveyID . '/gid/' . $iQuestionGroupID . '/qid/' . $iQuestionID));
             }
         }
     }
     if ($sAction == "updatesurveylocalesettings" && Permission::model()->hasSurveyPermission($iSurveyID, 'surveylocale', 'update')) {
         $languagelist = Survey::model()->findByPk($iSurveyID)->additionalLanguages;
         $languagelist[] = Survey::model()->findByPk($iSurveyID)->language;
         Yii::app()->loadHelper('database');
         foreach ($languagelist as $langname) {
             if ($langname) {
                 $url = Yii::app()->request->getPost('url_' . $langname);
                 if ($url == 'http://') {
                     $url = "";
                 }
                 $sURLDescription = html_entity_decode(Yii::app()->request->getPost('urldescrip_' . $langname), ENT_QUOTES, "UTF-8");
                 $sURL = html_entity_decode(Yii::app()->request->getPost('url_' . $langname), ENT_QUOTES, "UTF-8");
                 // Fix bug with FCKEditor saving strange BR types
                 $short_title = Yii::app()->request->getPost('short_title_' . $langname);
                 $description = Yii::app()->request->getPost('description_' . $langname);
                 $welcome = Yii::app()->request->getPost('welcome_' . $langname);
                 $endtext = Yii::app()->request->getPost('endtext_' . $langname);
                 $short_title = $oFixCKeditor->fixCKeditor($short_title);
                 $description = $oFixCKeditor->fixCKeditor($description);
                 $welcome = $oFixCKeditor->fixCKeditor($welcome);
                 $endtext = $oFixCKeditor->fixCKeditor($endtext);
                 $data = array('surveyls_title' => $short_title, 'surveyls_description' => $description, 'surveyls_welcometext' => $welcome, 'surveyls_endtext' => $endtext, 'surveyls_url' => $sURL, 'surveyls_urldescription' => $sURLDescription, 'surveyls_dateformat' => Yii::app()->request->getPost('dateformat_' . $langname), 'surveyls_numberformat' => Yii::app()->request->getPost('numberformat_' . $langname));
                 $SurveyLanguageSetting = SurveyLanguageSetting::model()->findByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $langname));
                 $SurveyLanguageSetting->attributes = $data;
                 $SurveyLanguageSetting->save();
                 // save the change to database
             }
         }
         Yii::app()->session['flashmessage'] = gT("Survey text elements successfully saved.");
         if ($sDBOutput != '') {
             echo $sDBOutput;
         } else {
             $this->getController()->redirect(array('admin/survey/sa/view/surveyid/' . $iSurveyID));
         }
     }
     $this->getController()->redirect(array("/admin"), "refresh");
 }
 private function _saveSettings()
 {
     if ($_POST['action'] !== "globalsettingssave") {
         return;
     }
     if (Yii::app()->session['USER_RIGHT_CONFIGURATOR'] != 1) {
         $this->getController()->redirect($this->getController()->createUrl('/admin'));
     }
     $clang = $this->getController()->lang;
     Yii::app()->loadHelper('surveytranslator');
     $maxemails = $_POST['maxemails'];
     if (sanitize_int($_POST['maxemails']) < 1) {
         $maxemails = 1;
     }
     $defaultlang = sanitize_languagecode($_POST['defaultlang']);
     $aRestrictToLanguages = explode(' ', sanitize_languagecodeS($_POST['restrictToLanguages']));
     if (!in_array($defaultlang, $aRestrictToLanguages)) {
         // Force default language in restrictToLanguages
         $aRestrictToLanguages[] = $defaultlang;
     }
     if (count(array_diff(array_keys(getLanguageData(false, Yii::app()->session['adminlang'])), $aRestrictToLanguages)) == 0) {
         $aRestrictToLanguages = '';
     } else {
         $aRestrictToLanguages = implode(' ', $aRestrictToLanguages);
     }
     setGlobalSetting('defaultlang', $defaultlang);
     setGlobalSetting('restrictToLanguages', trim($aRestrictToLanguages));
     setGlobalSetting('sitename', strip_tags($_POST['sitename']));
     setGlobalSetting('updatecheckperiod', (int) $_POST['updatecheckperiod']);
     setGlobalSetting('defaulthtmleditormode', sanitize_paranoid_string($_POST['defaulthtmleditormode']));
     setGlobalSetting('defaultquestionselectormode', sanitize_paranoid_string($_POST['defaultquestionselectormode']));
     setGlobalSetting('defaulttemplateeditormode', sanitize_paranoid_string($_POST['defaulttemplateeditormode']));
     setGlobalSetting('defaulttemplate', sanitize_paranoid_string($_POST['defaulttemplate']));
     setGlobalSetting('admintheme', sanitize_paranoid_string($_POST['admintheme']));
     setGlobalSetting('adminthemeiconsize', trim(file_get_contents(Yii::app()->getConfig("styledir") . DIRECTORY_SEPARATOR . sanitize_paranoid_string($_POST['admintheme']) . DIRECTORY_SEPARATOR . 'iconsize')));
     setGlobalSetting('emailmethod', strip_tags($_POST['emailmethod']));
     setGlobalSetting('emailsmtphost', strip_tags(returnGlobal('emailsmtphost')));
     if (returnGlobal('emailsmtppassword') != 'somepassword') {
         setGlobalSetting('emailsmtppassword', strip_tags(returnGlobal('emailsmtppassword')));
     }
     setGlobalSetting('bounceaccounthost', strip_tags(returnGlobal('bounceaccounthost')));
     setGlobalSetting('bounceaccounttype', strip_tags(returnGlobal('bounceaccounttype')));
     setGlobalSetting('bounceencryption', strip_tags(returnGlobal('bounceencryption')));
     setGlobalSetting('bounceaccountuser', strip_tags(returnGlobal('bounceaccountuser')));
     if (returnGlobal('bounceaccountpass') != 'enteredpassword') {
         setGlobalSetting('bounceaccountpass', strip_tags(returnGlobal('bounceaccountpass')));
     }
     setGlobalSetting('emailsmtpssl', sanitize_paranoid_string(Yii::app()->request->getPost('emailsmtpssl', '')));
     setGlobalSetting('emailsmtpdebug', sanitize_int(Yii::app()->request->getPost('emailsmtpdebug', '0')));
     setGlobalSetting('emailsmtpuser', strip_tags(returnGlobal('emailsmtpuser')));
     setGlobalSetting('filterxsshtml', strip_tags($_POST['filterxsshtml']));
     setGlobalSetting('siteadminbounce', strip_tags($_POST['siteadminbounce']));
     setGlobalSetting('siteadminemail', strip_tags($_POST['siteadminemail']));
     setGlobalSetting('siteadminname', strip_tags($_POST['siteadminname']));
     setGlobalSetting('shownoanswer', sanitize_int($_POST['shownoanswer']));
     setGlobalSetting('showxquestions', $_POST['showxquestions']);
     setGlobalSetting('showgroupinfo', $_POST['showgroupinfo']);
     setGlobalSetting('showqnumcode', $_POST['showqnumcode']);
     $repeatheadingstemp = (int) $_POST['repeatheadings'];
     if ($repeatheadingstemp == 0) {
         $repeatheadingstemp = 25;
     }
     setGlobalSetting('repeatheadings', $repeatheadingstemp);
     setGlobalSetting('maxemails', sanitize_int($maxemails));
     $iSessionExpirationTime = (int) $_POST['iSessionExpirationTime'];
     if ($iSessionExpirationTime == 0) {
         $iSessionExpirationTime = 7200;
     }
     setGlobalSetting('iSessionExpirationTime', $iSessionExpirationTime);
     setGlobalSetting('ipInfoDbAPIKey', $_POST['ipInfoDbAPIKey']);
     setGlobalSetting('googleMapsAPIKey', $_POST['googleMapsAPIKey']);
     setGlobalSetting('googleanalyticsapikey', $_POST['googleanalyticsapikey']);
     setGlobalSetting('googletranslateapikey', $_POST['googletranslateapikey']);
     setGlobalSetting('force_ssl', $_POST['force_ssl']);
     setGlobalSetting('surveyPreview_require_Auth', $_POST['surveyPreview_require_Auth']);
     setGlobalSetting('RPCInterface', $_POST['RPCInterface']);
     $savetime = (double) $_POST['timeadjust'] * 60 . ' minutes';
     //makes sure it is a number, at least 0
     if (substr($savetime, 0, 1) != '-' && substr($savetime, 0, 1) != '+') {
         $savetime = '+' . $savetime;
     }
     setGlobalSetting('timeadjust', $savetime);
     setGlobalSetting('usercontrolSameGroupPolicy', strip_tags($_POST['usercontrolSameGroupPolicy']));
     Yii::app()->session['flashmessage'] = $clang->gT("Global settings were saved.");
     $url = htmlspecialchars_decode(Yii::app()->session['refurl']);
     if ($url) {
         Yii::app()->getController()->redirect($url);
     }
 }
예제 #30
0
 /**
  * Show the drag-n-drop form for CSV attributes
  */
 public function attributeMapCSV()
 {
     if (!Permission::model()->hasGlobalPermission('participantpanel', 'import')) {
         die('No permission');
     }
     if ($_FILES['the_file']['name'] == '') {
         Yii::app()->setFlashMessage(gT('Please select a file to import!'), 'error');
         Yii::app()->getController()->redirect(array('admin/participants/sa/importCSV'));
     }
     $sRandomFileName = randomChars(20);
     $sFilePath = Yii::app()->getConfig('tempdir') . DIRECTORY_SEPARATOR . $sRandomFileName;
     $aPathinfo = pathinfo($_FILES['the_file']['name']);
     $sExtension = $aPathinfo['extension'];
     if ($_FILES['the_file']['error'] == 1 || $_FILES['the_file']['error'] == 2) {
         Yii::app()->setFlashMessage(sprintf(gT("Sorry, this file is too large. Only files up to %01.2f MB are allowed."), getMaximumFileUploadSize() / 1024 / 1024), 'error');
         Yii::app()->getController()->redirect(array('admin/participants/sa/importCSV'));
         exit;
     } elseif (strtolower($sExtension) == 'csv') {
         $bMoveFileResult = @move_uploaded_file($_FILES['the_file']['tmp_name'], $sFilePath);
         $filterblankemails = Yii::app()->request->getPost('filterbea');
     } else {
         Yii::app()->setFlashMessage(gT("This is not a .csv file."), 'error');
         Yii::app()->getController()->redirect(array('admin/participants/sa/importCSV'));
         exit;
     }
     if (!$bMoveFileResult) {
         Yii::app()->setFlashMessage(sprintf(gT("An error occurred uploading your file. This may be caused by incorrect permissions in your %s folder."), Yii::app()->getConfig('tempdir')), 'error');
         Yii::app()->getController()->redirect(array('admin/participants/sa/importCSV'));
         exit;
     } else {
         $regularfields = array('firstname', 'participant_id', 'lastname', 'email', 'language', 'blacklisted', 'owner_uid');
         $oCSVFile = fopen($sFilePath, 'r');
         $aFirstLine = fgets($oCSVFile);
         rewind($oCSVFile);
         $sSeparator = Yii::app()->request->getPost('separatorused');
         if ($sSeparator == 'auto') {
             $aCount = array();
             $aCount[','] = substr_count($aFirstLine, ',');
             $aCount[';'] = substr_count($aFirstLine, ';');
             $aCount['|'] = substr_count($aFirstLine, '|');
             $aResult = array_keys($aCount, max($aCount));
             $sSeparator = $aResult[0];
         }
         $firstline = fgetcsv($oCSVFile, 1000, $sSeparator[0]);
         $selectedcsvfields = array();
         $fieldlist = array();
         foreach ($firstline as $key => $value) {
             $testvalue = preg_replace('/[^(\\x20-\\x7F)]*/', '', $value);
             //Remove invalid characters from string
             if (!in_array(strtolower($testvalue), $regularfields)) {
                 array_push($selectedcsvfields, $value);
             }
             $fieldlist[] = $value;
         }
         $iLineCount = count(array_filter(array_filter(file($sFilePath), 'trim')));
         $attributes = ParticipantAttributeName::model()->model()->getCPDBAttributes();
         $aData = array('attributes' => $attributes, 'firstline' => $selectedcsvfields, 'fullfilepath' => $sRandomFileName, 'linecount' => $iLineCount - 1, 'filterbea' => $filterblankemails, 'participant_id_exists' => in_array('participant_id', $fieldlist));
         App()->getClientScript()->registerPackage('qTip2');
         App()->getClientScript()->registerPackage('jquery-nestedSortable');
         $this->registerScriptFile('ADMIN_SCRIPT_PATH', 'attributeMapCSV.js');
         $sAttributeMapJS = "var copyUrl = '" . App()->createUrl("admin/participants/sa/uploadCSV") . "';\n" . "var displayParticipants = '" . App()->createUrl("admin/participants/sa/displayParticipants") . "';\n" . "var mapCSVcancelled = '" . App()->createUrl("admin/participants/sa/mapCSVcancelled") . "';\n" . "var characterset = '" . sanitize_paranoid_string($_POST['characterset']) . "';\n" . "var okBtn = '" . gT("OK") . "';\n" . "var processed = '" . gT("Summary") . "';\n" . "var summary = '" . gT("Upload summary") . "';\n" . "var notPairedErrorTxt = '" . gT("You have to pair this field with an existing attribute.") . "';\n" . "var onlyOnePairedErrorTxt = '" . gT("Only one CSV attribute is mapped with central attribute.") . "';\n" . "var cannotAcceptErrorTxt='" . gT("This list cannot accept token attributes.") . "';\n" . "var separator = '" . sanitize_paranoid_string($_POST['separatorused']) . "';\n" . "var thefilepath = '" . $sRandomFileName . "';\n" . "var filterblankemails = '" . sanitize_paranoid_string($filterblankemails) . "';\n";
         App()->getClientScript()->registerScript("sAttributeMapJS", $sAttributeMapJS, CClientScript::POS_BEGIN);
         $this->_renderWrappedTemplate('participants', 'attributeMapCSV', $aData);
     }
 }