Ejemplo n.º 1
0
function initKcfinder()
{
    Yii::app()->session['KCFINDER'] = array();
    $sAllowedExtensions = implode(' ', array_map('trim', explode(',', Yii::app()->getConfig('allowedresourcesuploads'))));
    $_SESSION['KCFINDER']['types'] = array('files' => $sAllowedExtensions, 'flash' => $sAllowedExtensions, 'images' => $sAllowedExtensions);
    if (Yii::app()->getConfig('demoMode') === false && isset(Yii::app()->session['loginID']) && isset(Yii::app()->session['FileManagerContext'])) {
        // disable upload at survey creation time
        // because we don't know the sid yet
        if (preg_match('/^(create|edit):(question|group|answer)/', Yii::app()->session['FileManagerContext']) != 0 || preg_match('/^edit:survey/', Yii::app()->session['FileManagerContext']) != 0 || preg_match('/^edit:assessments/', Yii::app()->session['FileManagerContext']) != 0 || preg_match('/^edit:emailsettings/', Yii::app()->session['FileManagerContext']) != 0) {
            $contextarray = explode(':', Yii::app()->session['FileManagerContext'], 3);
            $surveyid = $contextarray[2];
            if (hasSurveyPermission($surveyid, 'surveycontent', 'update')) {
                $_SESSION['KCFINDER']['disabled'] = false;
                if (preg_match('/^edit:emailsettings/', $_SESSION['FileManagerContext']) != 0) {
                    $_SESSION['KCFINDER']['uploadURL'] = Yii::app()->getRequest()->getHostInfo() . Yii::app()->getConfig('uploadurl') . "/surveys/{$surveyid}/";
                } else {
                    $_SESSION['KCFINDER']['uploadURL'] = Yii::app()->getConfig('uploadurl') . "/surveys/{$surveyid}/";
                }
                $_SESSION['KCFINDER']['uploadDir'] = Yii::app()->getConfig('uploaddir') . DIRECTORY_SEPARATOR . 'surveys' . DIRECTORY_SEPARATOR . $surveyid . DIRECTORY_SEPARATOR;
            }
        } elseif (preg_match('/^edit:label/', Yii::app()->session['FileManagerContext']) != 0) {
            $contextarray = explode(':', Yii::app()->session['FileManagerContext'], 3);
            $labelid = $contextarray[2];
            // check if the user has label management right and labelid defined
            if (Yii::app()->session['USER_RIGHT_MANAGE_LABEL'] == 1 && isset($labelid) && $labelid != '') {
                $_SESSION['KCFINDER']['disabled'] = false;
                $_SESSION['KCFINDER']['uploadURL'] = Yii::app()->getConfig('uploadurl') . "/labels/{$labelid}/";
                $_SESSION['KCFINDER']['uploadDir'] = Yii::app()->getConfig('uploaddir') . DIRECTORY_SEPARATOR . 'labels' . DIRECTORY_SEPARATOR . $labelid . DIRECTORY_SEPARATOR;
            }
        }
    }
}
Ejemplo n.º 2
0
 /**
  * Function responsible to process any change in email template.
  * @return
  */
 function update($iSurveyId)
 {
     $clang = $this->getController()->lang;
     if (hasSurveyPermission($iSurveyId, 'surveylocale', 'update')) {
         $languagelist = Survey::model()->findByPk($iSurveyId)->additionalLanguages;
         $languagelist[] = Survey::model()->findByPk($iSurveyId)->language;
         array_filter($languagelist);
         foreach ($languagelist as $langname) {
             $attributes = array('surveyls_email_invite_subj' => $_POST['email_invite_subj_' . $langname], 'surveyls_email_invite' => $_POST['email_invite_' . $langname], 'surveyls_email_remind_subj' => $_POST['email_remind_subj_' . $langname], 'surveyls_email_remind' => $_POST['email_remind_' . $langname], 'surveyls_email_register_subj' => $_POST['email_register_subj_' . $langname], 'surveyls_email_register' => $_POST['email_register_' . $langname], 'surveyls_email_confirm_subj' => $_POST['email_confirm_subj_' . $langname], 'surveyls_email_confirm' => $_POST['email_confirm_' . $langname], 'email_admin_notification_subj' => $_POST['email_admin_notification_subj_' . $langname], 'email_admin_notification' => $_POST['email_admin_notification_' . $langname], 'email_admin_responses_subj' => $_POST['email_admin_responses_subj_' . $langname], 'email_admin_responses' => $_POST['email_admin_responses_' . $langname]);
             $usquery = Surveys_languagesettings::model()->updateAll($attributes, 'surveyls_survey_id = :ssid AND surveyls_language = :sl', array(':ssid' => $iSurveyId, ':sl' => $langname));
         }
         Yii::app()->session['flashmessage'] = $clang->gT("Email templates successfully saved.");
     }
     $this->getController()->redirect($this->getController()->createUrl('admin/survey/view/surveyid/' . $iSurveyId));
 }
Ejemplo n.º 3
0
 public function view($iSurveyId)
 {
     $iSurveyId = sanitize_int($iSurveyId);
     $clang = $this->getController()->lang;
     $aViewUrls = array();
     if (!hasSurveyPermission($iSurveyId, 'responses', 'read')) {
         die;
     }
     $this->getController()->_js_admin_includes(Yii::app()->getConfig('generalscripts') . 'jquery/jquery.tablesorter.min.js');
     $this->getController()->_js_admin_includes(Yii::app()->getConfig('adminscripts') . 'saved.js');
     $aThisSurvey = getSurveyInfo($iSurveyId);
     $aData['sSurveyName'] = $aThisSurvey['name'];
     $aData['iSurveyId'] = $iSurveyId;
     $aViewUrls[] = 'savedbar_view';
     $aViewUrls['savedlist_view'][] = $this->_showSavedList($iSurveyId);
     $this->_renderWrappedTemplate('saved', $aViewUrls, $aData);
 }
Ejemplo n.º 4
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;
     }
 }
Ejemplo n.º 5
0
 /**
  * RPC Routine to export submission timeline.
  * Returns an array of values (count and period)
  *
  * @access public
  * @param string $sSessionKey Auth credentials
  * @param int $iSurveyID Id of the Survey
  * @param string $sType (day|hour)
  * @param string $dStart
  * @param string $dEnd
  * @return array On success: The timeline. On failure array with error information
  * */
 public function export_timeline($sSessionKey, $iSurveyID, $sType, $dStart, $dEnd)
 {
     if (!$this->_checkSessionKey($sSessionKey)) {
         return array('status' => 'Invalid session key');
     }
     if (!in_array($sType, array('day', 'hour'))) {
         return array('status' => 'Invalid Period');
     }
     if (!hasSurveyPermission($iSurveyID, 'responses', 'read')) {
         return array('status' => 'No permission');
     }
     $oSurvey = Survey::model()->findByPk($iSurveyID);
     if (is_null($oSurvey)) {
         return array('status' => 'Error: Invalid survey ID');
     }
     if (!tableExists('{{survey_' . $iSurveyID . '}}')) {
         return array('status' => 'No available data');
     }
     $oResponses = SurveyDynamic::model($iSurveyID)->timeline($sType, $dStart, $dEnd);
     if (empty($oResponses)) {
         return array('status' => 'No valid Data');
     }
     return $oResponses;
 }
Ejemplo n.º 6
0
">
                    <img src='<?php 
    echo $imageurl;
    ?>
cpdb.png' alt='<?php 
    $clang->eT("Central participant database/panel");
    ?>
' />
                </a>
                <img src='<?php 
    echo $imageurl;
    ?>
separator.gif' class='separator' alt='' />
                <?php 
}
if (hasSurveyPermission($surveyid, 'surveyactivation', 'update') || HasSurveyPermission($surveyid, 'tokens', 'delete')) {
    ?>
                <a href="<?php 
    echo $this->createUrl("admin/tokens/sa/kill/surveyid/{$surveyid}");
    ?>
">
                    <img src='<?php 
    echo $imageurl;
    ?>
delete.png' alt='<?php 
    $clang->eT("Delete tokens table");
    ?>
' />
                </a>
                <?php 
}
    $clang->eT("Edit answer options for this question");
    ?>
' /></a>
            <?php 
} else {
    ?>
            <img src='<?php 
    echo $sImageURL;
    ?>
blank.gif' alt='' height="<?php 
    echo $iIconSize;
    ?>
" width='40' />
            <?php 
}
if (hasSurveyPermission($surveyid, 'surveycontent', 'read') && $qtypes[$qrrow['type']]['hasdefaultvalues'] > 0) {
    ?>
            <a href='<?php 
    echo $this->createUrl('admin/question/sa/editdefaultvalues/surveyid/' . $surveyid . '/gid/' . $gid . '/qid/' . $qid);
    ?>
'>
                <img src='<?php 
    echo $sImageURL;
    ?>
defaultanswers.png' alt='<?php 
    $clang->eT("Edit default answers for this question");
    ?>
' /></a>
            <?php 
}
?>
Ejemplo n.º 8
0
 /**
  * Show survey summary
  * @param int Survey id
  * @param string Action to be performed
  */
 function _surveysummary($iSurveyID, $action = null, $gid = null)
 {
     $clang = $this->getController()->lang;
     $baselang = Survey::model()->findByPk($iSurveyID)->language;
     $condition = array('sid' => $iSurveyID, 'language' => $baselang);
     $sumresult1 = Survey::model()->with(array('languagesettings' => array('condition' => 'surveyls_language=language')))->findByPk($iSurveyID);
     //$sumquery1, 1) ; //Checked
     if (is_null($sumresult1)) {
         Yii::app()->session['flashmessage'] = $clang->gT("Invalid survey ID");
         $this->getController()->redirect($this->getController()->createUrl("admin/index"));
     }
     //  if surveyid is invalid then die to prevent errors at a later time
     $surveyinfo = $sumresult1->attributes;
     $surveyinfo = array_merge($surveyinfo, $sumresult1->languagesettings[0]->attributes);
     $surveyinfo = array_map('flattenText', $surveyinfo);
     //$surveyinfo = array_map('htmlspecialchars', $surveyinfo);
     $activated = $surveyinfo['active'];
     $condition = array('sid' => $iSurveyID, 'parent_qid' => 0, 'language' => $baselang);
     $sumresult3 = Questions::model()->findAllByAttributes($condition);
     //Checked
     $sumcount3 = count($sumresult3);
     $condition = array('sid' => $iSurveyID, 'language' => $baselang);
     //$sumquery2 = "SELECT * FROM ".db_table_name('groups')." WHERE sid={$iSurveyID} AND language='".$baselang."'"; //Getting a count of groups for this survey
     $sumresult2 = Groups::model()->findAllByAttributes($condition);
     //Checked
     $sumcount2 = count($sumresult2);
     //SURVEY SUMMARY
     $aAdditionalLanguages = Survey::model()->findByPk($iSurveyID)->additionalLanguages;
     $surveysummary2 = "";
     if ($surveyinfo['anonymized'] != "N") {
         $surveysummary2 .= $clang->gT("Responses to this survey are anonymized.") . "<br />";
     } else {
         $surveysummary2 .= $clang->gT("Responses to this survey are NOT anonymized.") . "<br />";
     }
     if ($surveyinfo['format'] == "S") {
         $surveysummary2 .= $clang->gT("It is presented question by question.") . "<br />";
     } elseif ($surveyinfo['format'] == "G") {
         $surveysummary2 .= $clang->gT("It is presented group by group.") . "<br />";
     } else {
         $surveysummary2 .= $clang->gT("It is presented on one single page.") . "<br />";
     }
     if ($surveyinfo['allowjumps'] == "Y") {
         if ($surveyinfo['format'] == 'A') {
             $surveysummary2 .= $clang->gT("No question index will be shown with this format.") . "<br />";
         } else {
             $surveysummary2 .= $clang->gT("A question index will be shown; participants will be able to jump between viewed questions.") . "<br />";
         }
     }
     if ($surveyinfo['datestamp'] == "Y") {
         $surveysummary2 .= $clang->gT("Responses will be date stamped.") . "<br />";
     }
     if ($surveyinfo['ipaddr'] == "Y") {
         $surveysummary2 .= $clang->gT("IP Addresses will be logged") . "<br />";
     }
     if ($surveyinfo['refurl'] == "Y") {
         $surveysummary2 .= $clang->gT("Referrer URL will be saved.") . "<br />";
     }
     if ($surveyinfo['usecookie'] == "Y") {
         $surveysummary2 .= $clang->gT("It uses cookies for access control.") . "<br />";
     }
     if ($surveyinfo['allowregister'] == "Y") {
         $surveysummary2 .= $clang->gT("If tokens are used, the public may register for this survey") . "<br />";
     }
     if ($surveyinfo['allowsave'] == "Y" && $surveyinfo['tokenanswerspersistence'] == 'N') {
         $surveysummary2 .= $clang->gT("Participants can save partially finished surveys") . "<br />\n";
     }
     if ($surveyinfo['emailnotificationto'] != '') {
         $surveysummary2 .= $clang->gT("Basic email notification is sent to:") . " {$surveyinfo['emailnotificationto']}<br />\n";
     }
     if ($surveyinfo['emailresponseto'] != '') {
         $surveysummary2 .= $clang->gT("Detailed email notification with response data is sent to:") . " {$surveyinfo['emailresponseto']}<br />\n";
     }
     $dateformatdetails = getDateFormatData(Yii::app()->session['dateformat']);
     if (trim($surveyinfo['startdate']) != '') {
         Yii::import('application.libraries.Date_Time_Converter');
         $datetimeobj = new Date_Time_Converter($surveyinfo['startdate'], 'Y-m-d H:i:s');
         $aData['startdate'] = $datetimeobj->convert($dateformatdetails['phpdate'] . ' H:i');
     } else {
         $aData['startdate'] = "-";
     }
     if (trim($surveyinfo['expires']) != '') {
         //$constructoritems = array($surveyinfo['expires'] , "Y-m-d H:i:s");
         Yii::import('application.libraries.Date_Time_Converter');
         $datetimeobj = new Date_Time_Converter($surveyinfo['expires'], 'Y-m-d H:i:s');
         //$datetimeobj = new Date_Time_Converter($surveyinfo['expires'] , "Y-m-d H:i:s");
         $aData['expdate'] = $datetimeobj->convert($dateformatdetails['phpdate'] . ' H:i');
     } else {
         $aData['expdate'] = "-";
     }
     if (!$surveyinfo['language']) {
         $aData['language'] = getLanguageNameFromCode($currentadminlang, false);
     } else {
         $aData['language'] = getLanguageNameFromCode($surveyinfo['language'], false);
     }
     // get the rowspan of the Additionnal languages row
     // is at least 1 even if no additionnal language is present
     $additionnalLanguagesCount = count($aAdditionalLanguages);
     $first = true;
     $aData['additionnalLanguages'] = "";
     if ($additionnalLanguagesCount == 0) {
         $aData['additionnalLanguages'] .= "<td>-</td>\n";
     } else {
         foreach ($aAdditionalLanguages as $langname) {
             if ($langname) {
                 if (!$first) {
                     $aData['additionnalLanguages'] .= "<tr><td>&nbsp;</td>";
                 }
                 $first = false;
                 $aData['additionnalLanguages'] .= "<td>" . getLanguageNameFromCode($langname, false) . "</td></tr>\n";
             }
         }
     }
     if ($first) {
         $aData['additionnalLanguages'] .= "</tr>";
     }
     if ($surveyinfo['surveyls_urldescription'] == "") {
         $surveyinfo['surveyls_urldescription'] = htmlspecialchars($surveyinfo['surveyls_url']);
     }
     if ($surveyinfo['surveyls_url'] != "") {
         $aData['endurl'] = " <a target='_blank' href=\"" . htmlspecialchars($surveyinfo['surveyls_url']) . "\" title=\"" . htmlspecialchars($surveyinfo['surveyls_url']) . "\">{$surveyinfo['surveyls_urldescription']}</a>";
     } else {
         $aData['endurl'] = "-";
     }
     $aData['sumcount3'] = $sumcount3;
     $aData['sumcount2'] = $sumcount2;
     if ($activated == "N") {
         $aData['activatedlang'] = $clang->gT("No");
     } else {
         $aData['activatedlang'] = $clang->gT("Yes");
     }
     $aData['activated'] = $activated;
     if ($activated == "Y") {
         $aData['surveydb'] = Yii::app()->db->tablePrefix . "survey_" . $iSurveyID;
     }
     $aData['warnings'] = "";
     if ($activated == "N" && $sumcount3 == 0) {
         $aData['warnings'] = $clang->gT("Survey cannot be activated yet.") . "<br />\n";
         if ($sumcount2 == 0 && hasSurveyPermission($iSurveyID, 'surveycontent', 'create')) {
             $aData['warnings'] .= "<span class='statusentryhighlight'>[" . $clang->gT("You need to add question groups") . "]</span><br />";
         }
         if ($sumcount3 == 0 && hasSurveyPermission($iSurveyID, 'surveycontent', 'create')) {
             $aData['warnings'] .= "<span class='statusentryhighlight'>[" . $clang->gT("You need to add questions") . "]</span><br />";
         }
     }
     $aData['hints'] = $surveysummary2;
     //return (array('column'=>array($columns_used,$hard_limit) , 'size' => array($length, $size_limit) ));
     //        $aData['tableusage'] = getDBTableUsage($iSurveyID);
     // ToDo: Table usage is calculated on every menu display which is too slow with bug surveys.
     // Needs to be moved to a database field and only updated if there are question/subquestions added/removed (it's currently also not functional due to the port)
     //
     $aData['tableusage'] = false;
     if ($gid || $action !== true && in_array($action, array('deactivate', 'activate', 'surveysecurity', 'editdefaultvalues', 'editemailtemplates', 'surveyrights', 'addsurveysecurity', 'addusergroupsurveysecurity', 'setsurveysecurity', 'setusergroupsurveysecurity', 'delsurveysecurity', 'editsurveysettings', 'editsurveylocalesettings', 'updatesurveysettingsandeditlocalesettings', 'addgroup', 'importgroup', 'ordergroups', 'deletesurvey', 'resetsurveylogic', 'importsurveyresources', 'translate', 'emailtemplates', 'exportstructure', 'quotas', 'copysurvey', 'viewgroup', 'viewquestion'))) {
         $showstyle = "style='display: none'";
     } else {
         $showstyle = "";
     }
     $aData['showstyle'] = $showstyle;
     $aData['aAdditionalLanguages'] = $aAdditionalLanguages;
     $aData['clang'] = $clang;
     $aData['surveyinfo'] = $surveyinfo;
     $this->getController()->render("/admin/survey/surveySummary_view", $aData);
 }
            <a href='#'>
                <img src='<?php 
    echo $imageurl;
    ?>
add_disabled.png' title='' alt='<?php 
    echo $clang->gT("Disabled") . ' - ' . $clang->gT("This survey is currently active.");
    ?>
' width="<?php 
    echo $iIconSize;
    ?>
" height="<?php 
    echo $iIconSize;
    ?>
" /></a>
            <?php 
} elseif (hasSurveyPermission($surveyid, 'surveycontent', 'create')) {
    ?>
            <a href='<?php 
    echo $this->createUrl("admin/question/sa/addquestion/surveyid/" . $surveyid . "/gid/" . $gid);
    ?>
'>
                <img src='<?php 
    echo $imageurl;
    ?>
add.png' title='' alt='<?php 
    $clang->eT("Add new question to group");
    ?>
' width="<?php 
    echo $iIconSize;
    ?>
" height="<?php 
Ejemplo n.º 10
0
 function new_answer($iSurveyId, $sSubAction = 'new_answer')
 {
     $iSurveyId = sanitize_int($iSurveyId);
     $this->_checkPermissions($iSurveyId, 'create');
     $aData = $this->_getData($iSurveyId);
     $sBaseLang = $aData['sBaseLang'];
     $clang = $aData['clang'];
     $aViewUrls = array();
     if (($sSubAction == "new_answer" || $sSubAction == "new_answer_two" && !isset($_POST['quota_qid'])) && hasSurveyPermission($iSurveyId, 'quotas', 'create')) {
         $result = Quota::model()->findAllByPk(Yii::app()->request->getPost('quota_id'));
         foreach ($result as $aQuotaDetails) {
             $quota_name = $aQuotaDetails['name'];
         }
         $result = Questions::model()->findAllByAttributes(array('type' => array('G', 'M', 'Y', 'A', 'B', 'I', 'L', 'O', '!'), 'sid' => $iSurveyId, 'language' => $sBaseLang, 'parent_qid' => 0));
         if (empty($result)) {
             $aViewUrls[] = 'newanswererror_view';
         } else {
             $aData['newanswer_result'] = $result;
             $aData['quota_name'] = $quota_name;
             $aViewUrls[] = 'newanswer_view';
         }
     }
     if ($sSubAction == "new_answer_two" && isset($_POST['quota_qid']) && hasSurveyPermission($iSurveyId, 'quotas', 'create')) {
         $aResults = Quota::model()->findByPk(Yii::app()->request->getPost('quota_qid'));
         $sQuotaName = $aResults['name'];
         $aQuestionAnswers = self::getQuotaAnswers(Yii::app()->request->getPost('quota_qid'), $iSurveyId, Yii::app()->request->getPost('quota_id'));
         $x = 0;
         foreach ($aQuestionAnswers as $aQACheck) {
             if (isset($aQACheck['rowexists'])) {
                 $x++;
             }
         }
         reset($aQuestionAnswers);
         $aData['question_answers'] = $aQuestionAnswers;
         $aData['x'] = $x;
         $aData['quota_name'] = $sQuotaName;
         $aViewUrls[] = 'newanswertwo_view';
     }
     $this->_renderWrappedTemplate('quotas', $aViewUrls, $aData);
 }
/**
* Creates a query string with all fields for the export
* @param
* @return string
*/
function SPSSGetQuery($iSurveyID)
{
    $bDataAnonymized = Survey::model()->findByPk($iSurveyID)->anonymized == 'Y';
    $tokensexist = tableExists('tokens_' . $iSurveyID);
    #See if tokens are being used
    if (isset($tokensexist) && $tokensexist == true && !$bDataAnonymized && hasSurveyPermission($iSurveyID, 'tokens', 'read')) {
        $query = "SELECT ";
        $tokenattributes = array_keys(getTokenFieldsAndNames($iSurveyID, false));
        foreach ($tokenattributes as $attributefield) {
            //Drop the token field, since it is in the survey too
            if ($attributefield != 'token') {
                $query .= Yii::app()->db->quoteColumnName('t.' . $attributefield) . ',';
            }
        }
        $query .= "s.*\n        FROM {{survey_{$iSurveyID}}} s\n        LEFT JOIN {{tokens_{$iSurveyID}}} t ON s.token = t.token";
    } else {
        $query = "SELECT s.*\n        FROM {{survey_{$iSurveyID}}} s";
    }
    switch (incompleteAnsFilterState()) {
        case 'incomplete':
            //Inclomplete answers only
            $query .= ' WHERE s.submitdate is null ';
            break;
        case 'complete':
            //Inclomplete answers only
            $query .= ' WHERE s.submitdate is not null ';
            break;
    }
    return $query;
}
 /**
  * Loads results for the survey into the $survey->responses array.  The
  * results  begin from $minRecord and end with $maxRecord.  Either none,
  * or both,  the $minRecord and $maxRecord variables must be provided.
  * If none are then all responses are loaded.
  *
  * @param Survey $survey
  * @param int $iOffset 
  * @param int $iLimit 
  */
 public function loadSurveyResults(SurveyObj $survey, $iLimit, $iOffset, $iMaximum, $sFilter = '')
 {
     // Get info about the survey
     $aSelectFields = Yii::app()->db->schema->getTable('{{survey_' . $survey->id . '}}')->getColumnNames();
     $oRecordSet = Yii::app()->db->createCommand()->from('{{survey_' . $survey->id . '}}');
     if (tableExists('tokens_' . $survey->id) && array_key_exists('token', Survey_dynamic::model($survey->id)->attributes) && hasSurveyPermission($survey->id, 'tokens', 'read')) {
         $oRecordSet->leftJoin('{{tokens_' . $survey->id . '}} tokentable', 'tokentable.token={{survey_' . $survey->id . '}}.token');
         $aTokenFields = Yii::app()->db->schema->getTable('{{tokens_' . $survey->id . '}}')->getColumnNames();
         $aSelectFields = array_merge($aSelectFields, array_diff($aTokenFields, array('token')));
         $aSelectFields = array_diff($aSelectFields, array('token'));
         $aSelectFields[] = '{{survey_' . $survey->id . '}}.token';
     }
     if ($survey->info['savetimings'] == "Y") {
         $oRecordSet->leftJoin("{{survey_" . $survey->id . "_timings}} survey_timings", "{{survey_" . $survey->id . "}}.id = survey_timings.id");
         $aTimingFields = Yii::app()->db->schema->getTable("{{survey_" . $survey->id . "_timings}}")->getColumnNames();
         $aSelectFields = array_merge($aSelectFields, array_diff($aTimingFields, array('id')));
         $aSelectFields = array_diff($aSelectFields, array('id'));
         $aSelectFields[] = '{{survey_' . $survey->id . '}}.id';
     }
     if ($sFilter != '') {
         $oRecordSet->where($sFilter);
     }
     if ($iOffset + $iLimit > $iMaximum) {
         $iLimit = $iMaximum - $iOffset;
     }
     $survey->responses = $oRecordSet->select($aSelectFields)->order('{{survey_' . $survey->id . '}}.id')->limit($iLimit, $iOffset)->query()->readAll();
     return count($survey->responses);
 }
Ejemplo n.º 13
0
 /**
  * Show dialogs and create a new tokens table
  */
 function _newtokentable($iSurveyId)
 {
     $clang = $this->getController()->lang;
     Yii::import('application.helpers.admin.token_helper', true);
     if (Yii::app()->request->getPost('createtable') == "Y" && hasSurveyPermission($iSurveyId, 'surveyactivation', 'update')) {
         createTokenTable($iSurveyId);
         $this->_renderWrappedTemplate('token', array('message' => array('title' => $clang->gT("Token control"), 'message' => $clang->gT("A token table has been created for this survey.") . " (\"" . Yii::app()->db->tablePrefix . "tokens_{$iSurveyId}\")<br /><br />\n" . "<input type='submit' value='" . $clang->gT("Continue") . "' onclick=\"window.open('" . $this->getController()->createUrl("admin/tokens/index/surveyid/{$iSurveyId}") . "', '_top')\" />\n")));
     } elseif (returnGlobal('restoretable') == "Y" && Yii::app()->request->getPost('oldtable') && hasSurveyPermission($iSurveyId, 'surveyactivation', 'update')) {
         //Rebuild attributedescription value for the surveys table
         $table = Yii::app()->db->schema->getTable(Yii::app()->request->getPost('oldtable'));
         $fields = array_filter(array_keys($table->columns), 'filterForAttributes');
         foreach ($fields as $fieldname) {
             $name = $fieldname;
             if ($fieldname[10] == 'c') {
                 //This belongs to a cpdb attribute
                 $cpdbattid = substr($fieldname, 15);
                 $data = ParticipantAttributeNames::model()->getAttributeName($cpdbattid, Yii::app()->session['adminlang']);
                 $name = $data['attribute_name'];
             }
             $fieldcontents[$fieldname] = array('description' => $name, 'mandatory' => 'N', 'show_register' => 'N');
         }
         Survey::model()->updateByPk($iSurveyId, array('attributedescriptions' => serialize($fieldcontents)));
         Yii::app()->db->createCommand()->renameTable(Yii::app()->request->getPost('oldtable'), Yii::app()->db->tablePrefix . "tokens_" . intval($iSurveyId));
         //Add any survey_links from the renamed table
         Survey_links::model()->rebuildLinksFromTokenTable($iSurveyId);
         $this->_renderWrappedTemplate('token', array('message' => array('title' => $clang->gT("Import old tokens"), 'message' => $clang->gT("A token table has been created for this survey and the old tokens were imported.") . " (\"" . Yii::app()->db->tablePrefix . "tokens_{$iSurveyId}" . "\")<br /><br />\n" . "<input type='submit' value='" . $clang->gT("Continue") . "' onclick=\"window.open('" . $this->getController()->createUrl("admin/tokens/index/surveyid/{$iSurveyId}") . "', '_top')\" />\n")));
         LimeExpressionManager::SetDirtyFlag();
         // so that knows that token tables have changed
     } else {
         $this->getController()->loadHelper('database');
         $result = Yii::app()->db->createCommand(dbSelectTablesLike("{{old_tokens_" . intval($iSurveyId) . "_%}}"))->queryAll();
         $tcount = count($result);
         if ($tcount > 0) {
             foreach ($result as $rows) {
                 $oldlist[] = reset($rows);
             }
             $aData['oldlist'] = $oldlist;
         }
         $thissurvey = getSurveyInfo($iSurveyId);
         $aData['thissurvey'] = $thissurvey;
         $aData['surveyid'] = $iSurveyId;
         $aData['tcount'] = $tcount;
         $aData['databasetype'] = Yii::app()->db->getDriverName();
         $this->_renderWrappedTemplate('token', 'tokenwarning', $aData);
     }
 }
Ejemplo n.º 14
0
 public function time($iSurveyID)
 {
     $aData = $this->_getData(array('iSurveyId' => $iSurveyID));
     extract($aData);
     $aViewUrls = array();
     if ($aData['surveyinfo']['savetimings'] != "Y") {
         die;
     }
     if (Yii::app()->request->getPost('deleteanswer') && Yii::app()->request->getPost('deleteanswer') != '' && Yii::app()->request->getPost('deleteanswer') != 'marked' && hasSurveyPermission($iSurveyID, 'responses', 'delete')) {
         $iResponseID = (int) Yii::app()->request->getPost('deleteanswer');
         Survey_dynamic::model($iSurveyID)->deleteByPk($iResponseID);
         Survey_timings::model($iSurveyID)->deleteByPk($iResponseID);
     }
     if (Yii::app()->request->getPost('markedresponses') && count(Yii::app()->request->getPost('markedresponses')) > 0) {
         if (Yii::app()->request->getPost('deleteanswer') && Yii::app()->request->getPost('deleteanswer') === 'marked' && hasSurveyPermission($iSurveyID, 'responses', 'delete')) {
             foreach (Yii::app()->request->getPost('markedresponses') as $iResponseID) {
                 $iResponseID = (int) $iResponseID;
                 Survey_dynamic::model($iSurveyID)->deleteByPk($iResponseID);
                 Survey_timings::model($iSurveyID)->deleteByPk($iResponseID);
             }
         }
     }
     $fields = createTimingsFieldMap($iSurveyID, 'full', true, false, $aData['language']);
     $clang = $aData['clang'];
     foreach ($fields as $fielddetails) {
         // headers for answer id and time data
         if ($fielddetails['type'] == 'id') {
             $fnames[] = array($fielddetails['fieldname'], $fielddetails['question']);
         }
         if ($fielddetails['type'] == 'interview_time') {
             $fnames[] = array($fielddetails['fieldname'], $clang->gT('Total time'));
         }
         if ($fielddetails['type'] == 'page_time') {
             $fnames[] = array($fielddetails['fieldname'], $clang->gT('Group') . ": " . $fielddetails['group_name']);
         }
         if ($fielddetails['type'] == 'answer_time') {
             $fnames[] = array($fielddetails['fieldname'], $clang->gT('Question') . ": " . $fielddetails['title']);
         }
     }
     $fncount = count($fnames);
     //NOW LETS CREATE A TABLE WITH THOSE HEADINGS
     foreach ($fnames as $fn) {
         if (!isset($currentgroup)) {
             $currentgroup = $fn[1];
             $gbc = "oddrow";
         }
         if ($currentgroup != $fn[1]) {
             $currentgroup = $fn[1];
             if ($gbc == "oddrow") {
                 $gbc = "evenrow";
             } else {
                 $gbc = "oddrow";
             }
         }
     }
     $aData['fnames'] = $fnames;
     $start = Yii::app()->request->getParam('start', 0);
     $limit = Yii::app()->request->getParam('limit', 50);
     if (!$limit) {
         $limit = 50;
     }
     //LETS COUNT THE DATA
     $oCriteria = new CdbCriteria();
     $oCriteria->select = 'tid';
     $oCriteria->join = "INNER JOIN {{survey_{$iSurveyID}}} s ON t.id=s.id";
     $oCriteria->condition = 'submitdate IS NOT NULL';
     $dtcount = Survey_timings::model($iSurveyID)->count($oCriteria);
     // or die("Couldn't get response data");
     if ($limit > $dtcount) {
         $limit = $dtcount;
     }
     //NOW LETS SHOW THE DATA
     $oCriteria = new CdbCriteria();
     $oCriteria->join = "INNER JOIN {{survey_{$iSurveyID}}} s ON t.id=s.id";
     $oCriteria->condition = 'submitdate IS NOT NULL';
     $oCriteria->order = "s.id " . (Yii::app()->request->getParam('order') == 'desc' ? 'desc' : 'asc');
     $oCriteria->offset = $start;
     $oCriteria->limit = $limit;
     $dtresult = Survey_timings::model($iSurveyID)->findAllAsArray($oCriteria);
     $dtcount2 = count($dtresult);
     $cells = $fncount + 1;
     //CONTROL MENUBAR
     $last = $start - $limit;
     $next = $start + $limit;
     $end = $dtcount - $limit;
     if ($end < 0) {
         $end = 0;
     }
     if ($last < 0) {
         $last = 0;
     }
     if ($next >= $dtcount) {
         $next = $dtcount - $limit;
     }
     if ($end < 0) {
         $end = 0;
     }
     $aData['sCompletionStateValue'] = incompleteAnsFilterState();
     $aData['start'] = $start;
     $aData['limit'] = $limit;
     $aData['last'] = $last;
     $aData['next'] = $next;
     $aData['end'] = $end;
     $aViewUrls[] = 'browsetimeheader_view';
     $aData['fncount'] = $fncount;
     $bgcc = 'oddrow';
     foreach ($dtresult as $dtrow) {
         if ($bgcc == "evenrow") {
             $bgcc = "oddrow";
         } else {
             $bgcc = "evenrow";
         }
         $browsedatafield = array();
         for ($i = 0; $i < $fncount; $i++) {
             $browsedatafield[$i] = $dtrow[$fnames[$i][0]];
             // seconds -> minutes & seconds
             if (strtolower(substr($fnames[$i][0], -4)) == "time") {
                 $minutes = (int) ($browsedatafield[$i] / 60);
                 $seconds = $browsedatafield[$i] % 60;
                 $browsedatafield[$i] = '';
                 if ($minutes > 0) {
                     $browsedatafield[$i] .= "{$minutes} min ";
                 }
                 $browsedatafield[$i] .= "{$seconds} s";
             }
         }
         $aData['browsedatafield'] = $browsedatafield;
         $aData['bgcc'] = $bgcc;
         $aData['dtrow'] = $dtrow;
         $aViewUrls['browsetimerow_view'][] = $aData;
     }
     //interview Time statistics
     $aData['statistics'] = Survey_timings::model($iSurveyId)->statistics();
     $aData['num_total_answers'] = Survey_dynamic::model($iSurveyID)->count();
     $aData['num_completed_answers'] = Survey_dynamic::model($iSurveyID)->count('submitdate IS NOT NULL');
     $aViewUrls[] = 'browsetimefooter_view';
     $this->_renderWrappedTemplate('', $aViewUrls, $aData);
 }
Ejemplo n.º 15
0
<?php } else { ?>
	<td><?php $clang->eT("Question group");?></td>
	<td><?php echo $groups[$assess['gid']]." (".$assess['gid'].")";?></td>
<?php } ?>


<td><?php echo $assess['minimum'];?></td>
<td><?php echo $assess['maximum'];?></td>
<td><?php echo stripslashes($assess['name']);?></td>
<td><?php echo strip_tags(stripJavaScript($assess['message']));?></td>

</tr>
<?php } ?>
</tbody></table>

<?php if ((hasSurveyPermission($surveyid, 'assessments','update') && $actionvalue=="assessmentupdate") || (hasSurveyPermission($surveyid, 'assessments','create')&& $actionvalue=="assessmentadd")) { ?>
<br /><form method='post' class='form30' id='assessmentsform' name='assessmentsform' action='<?php echo $this->createUrl("admin/assessments/index/surveyid/$surveyid");?>'>
	<div class='header ui-widget-header'><?php echo $actiontitle;?></div>
	<ul class="assessmentscope"><li><label><?php $clang->eT("Scope");?></label>
	<input type='radio' id='radiototal' name='scope' value='T' <?php
    if (!isset($editdata) || $editdata['scope'] == "T") {echo "checked='checked' ";} ?>/>
    <label for='radiototal'><?php $clang->eT("Total");?></label>
    <input type='radio' id='radiogroup' name='scope' value='G' <?php
    if (isset($editdata) && $editdata['scope'] == "G") {echo " checked='checked' ";} ?>/>
    <label for='radiogroup'><?php $clang->eT("Group");?></label></li>
    <li><label for='gid'><?php $clang->eT("Question group");?></label>
        <?php 
        if (isset($groups))
        { ?>
	        <select name='gid' id='gid'>
	            <?php
        echo $this->createUrl("admin/dataentry/sa/editdata/subaction/edit/surveyid/{$surveyid}/id/{$id}/lang/{$rlanguage}");
        ?>
' title='<?php 
        $clang->eT("Edit this entry");
        ?>
'>
                        <img src='<?php 
        echo $sImageURL;
        ?>
edit.png' alt='<?php 
        $clang->gT("Edit this entry");
        ?>
' /></a>
                    <?php 
    }
    if (hasSurveyPermission($surveyid, 'responses', 'delete') && isset($rlanguage)) {
        ?>
                    <a href='#' title='<?php 
        $clang->eT("Delete this entry");
        ?>
' onclick="if (confirm('<?php 
        $clang->eT("Are you sure you want to delete this entry?", "js");
        ?>
')) { <?php 
        echo convertGETtoPOST($this->createUrl("admin/dataentry/sa/delete/id/{$id}/sid/{$surveyid}"));
        ?>
}">
                        <img src='<?php 
        echo $sImageURL;
        ?>
delete.png' alt='<?php 
Ejemplo n.º 17
0
 /**
  * Provides an interface for updating a group
  *
  * @access public
  * @param int $gid
  * @return void
  */
 public function update($gid)
 {
     $gid = (int) $gid;
     $group = Groups::model()->findByAttributes(array('gid' => $gid));
     $surveyid = $group->sid;
     if (hasSurveyPermission($surveyid, 'surveycontent', 'update')) {
         Yii::app()->loadHelper('surveytranslator');
         $grplangs = Survey::model()->findByPk($surveyid)->additionalLanguages;
         $baselang = Survey::model()->findByPk($surveyid)->language;
         array_push($grplangs, $baselang);
         foreach ($grplangs as $grplang) {
             if (isset($grplang) && $grplang != "") {
                 $group_name = $_POST['group_name_' . $grplang];
                 $group_description = $_POST['description_' . $grplang];
                 $group_name = html_entity_decode($group_name, ENT_QUOTES, "UTF-8");
                 $group_description = html_entity_decode($group_description, ENT_QUOTES, "UTF-8");
                 // Fix bug with FCKEditor saving strange BR types
                 $group_name = fixCKeditorText($group_name);
                 $group_description = fixCKeditorText($group_description);
                 $aData = array('group_name' => $group_name, 'description' => $group_description, 'randomization_group' => $_POST['randomization_group'], 'grelevance' => $_POST['grelevance']);
                 $condition = array('gid' => $gid, 'sid' => $surveyid, 'language' => $grplang);
                 $group = Groups::model()->findByAttributes($condition);
                 foreach ($aData as $k => $v) {
                     $group->{$k} = $v;
                 }
                 $ugresult = $group->save();
                 if ($ugresult) {
                     $groupsummary = getGroupList($gid, $surveyid);
                 }
             }
         }
         Yii::app()->session['flashmessage'] = Yii::app()->lang->gT("Question group successfully saved.");
         $this->getController()->redirect($this->getController()->createUrl('admin/survey/sa/view/surveyid/' . $surveyid . '/gid/' . $gid));
     }
 }
</td>
<td><?php 
    $aReplacementData = array();
    templatereplace($assess['message'], array(), $aReplacementData, 'Unspecified', false, $assess['sid']);
    echo FlattenText(LimeExpressionManager::GetLastPrettyPrintExpression(), true);
    ?>
</td>

</tr>
<?php 
}
?>
</tbody></table>

<?php 
if (hasSurveyPermission($surveyid, 'assessments', 'update') && $actionvalue == "assessmentupdate" || hasSurveyPermission($surveyid, 'assessments', 'create') && $actionvalue == "assessmentadd") {
    ?>
<br />
<?php 
    echo CHtml::form(array("admin/assessments/sa/index/surveyid/{$surveyid}"), 'post', array('class' => 'form30', 'id' => 'assessmentsform', 'name' => 'assessmentsform'));
    ?>
	<div class='header ui-widget-header'><?php 
    echo $actiontitle;
    ?>
</div>
	<ul class="assessmentscope"><li><label><?php 
    $clang->eT("Scope");
    ?>
</label>
	<input type='radio' id='radiototal' name='scope' value='T' <?php 
    if (!isset($editdata) || $editdata['scope'] == "T") {
Ejemplo n.º 19
0
                    </li>
                    <?php if ($grouplang==$baselang){?>
                        <li><label for='randomization_group'><?php $clang->eT("Randomization group:"); ?></label><input type='text' size='20' maxlength='20' name='randomization_group' id='randomization_group' /></li>
                        <li>
                            <label for='grelevance'><?php $clang->eT("Relevance equation:"); ?></label>
                            <textarea cols='50' rows='1' id='grelevance' name='grelevance'></textarea>
                        </li>
                        <?php } ?>
                </ul>
                <p><input type='submit' value='<?php $clang->eT("Save question group"); ?>' />
            </div>
            <?php } ?>

    </form>

    <?php if (hasSurveyPermission($surveyid,'surveycontent','import'))
        { ?>
        <div id="import">
            <form enctype='multipart/form-data' class='form30' id='importgroup' name='importgroup' action='<?php echo $this->createUrl('admin/questiongroup/import'); ?>' method='post' onsubmit='return validatefilename(this,"<?php $clang->eT('Please select a file to import!','js'); ?>");'>
                <ul>
                    <li>
                        <label for='the_file'><?php $clang->eT("Select question group file (*.lsg/*.csv):"); ?></label>
                        <input id='the_file' name="the_file" type="file" /></li>
                    <li><label for='translinksfields'><?php $clang->eT("Convert resource links?"); ?></label>
                        <input id='translinksfields' name="translinksfields" type="checkbox" checked="checked"/></li></ul>
                <p><input type='submit' value='<?php $clang->eT("Import question group"); ?>' />
                <input type='hidden' name='action' value='importgroup' />
                <input type='hidden' name='sid' value='<?php echo $surveyid; ?>' />
            </form>

        </div>
Ejemplo n.º 20
0
                {
                ?>
                <a href='<?php echo $this->createUrl("admin/dataentry/import/surveyid/$surveyid"); ?>'>
                    <img src='<?php echo $sImageURL; ?>importold.png' alt='<?php $clang->eT("Import responses from a deactivated survey table"); ?>' /></a>
                <?php } ?>
            <img src='<?php echo $sImageURL; ?>separator.gif' class='separator' alt='' />

            <?php if (hasSurveyPermission($surveyid, 'responses', 'read'))
                { ?>
                <a href='<?php echo $this->createUrl("admin/saved/view/surveyid/$surveyid"); ?>'>
                    <img src='<?php echo $sImageURL; ?>saved.png' title='' alt='<?php $clang->eT("View Saved but not submitted Responses"); ?>' /></a>
                <?php }
                if (hasSurveyPermission($surveyid, 'responses', 'import'))
                { ?>
                <a href='<?php echo $this->createUrl("admin/dataentry/vvimport/surveyid/$surveyid"); ?>'>
                    <img src='<?php echo $sImageURL; ?>importvv.png' alt='<?php $clang->eT("Import a VV survey file"); ?>' /></a>
                <?php }
                if (hasSurveyPermission($surveyid, 'responses', 'export'))
                { ?>
                <a href='<?php echo $this->createUrl("admin/export/vvexport/surveyid/$surveyid"); ?>'>
                    <img src='<?php echo $sImageURL; ?>exportvv.png' title='' alt='<?php $clang->eT("Export a VV survey file"); ?>' /></a>
                <?php }
                if (hasSurveyPermission($surveyid, 'responses', 'delete') && $thissurvey['anonymized'] == 'N' && $thissurvey['tokenanswerspersistence'] == 'Y')
                { ?>
                <a href='<?php echo $this->createUrl("admin/dataentry/iteratesurvey/surveyid/$surveyid"); ?>'>
                    <img src='<?php echo $sImageURL; ?>iterate.png' title='' alt='<?php $clang->eT("Iterate survey"); ?>' /></a>
                <?php } ?>
        </div>
    </div>
</div>
 /**
  * Receives an ajax call containing the participant id in the fourth segment of the url
  * Supplies list of survey links - surveys of which this participant is on the tokens table
  * URL: [localurl]/limesurvey/admin/participants/getSurveyInfo_json/pid/[participant_id]
  * RETURNS: json data containing linked survey information (Survey name, survey id, token_id and date_added)
  */
 function getSurveyInfo_json()
 {
     $participantid = Yii::app()->request->getQuery('pid');
     $records = Survey_links::model()->findAllByAttributes(array('participant_id' => $participantid));
     $aData = new stdClass();
     $aData->page = 1;
     $aData->records = count($records);
     $aData->total = ceil($aData->records / 10);
     $i = 0;
     foreach ($records as $row) {
         $oSurvey = Survey::model()->with(array('languagesettings' => array('condition' => 'surveyls_language=language')))->findByAttributes(array('sid' => $row['survey_id']));
         foreach ($oSurvey->languagesettings as $oLanguageSetting) {
             $surveyname = $oLanguageSetting->surveyls_title;
         }
         $surveylink = "";
         /* Check permissions of each survey before creating a link*/
         if (!hasSurveyPermission($row['survey_id'], 'tokens', 'read')) {
             $surveylink = $row['survey_id'];
         } else {
             $surveylink = '<a href=' . Yii::app()->getController()->createUrl("/admin/tokens/sa/browse/surveyid/{$row['survey_id']}") . '>' . $row['survey_id'] . '</a>';
         }
         $aData->rows[$i]['cell'] = array($surveyname, $surveylink, $row['token_id'], $row['date_created'], $row['date_invited'], $row['date_completed']);
         $i++;
     }
     echo ls_json_encode($aData);
 }
Ejemplo n.º 22
0
 function expire($iSurveyID)
 {
     $iSurveyID = (int) $iSurveyID;
     if (!hasSurveyPermission($iSurveyID, 'surveysettings', 'update')) {
         die;
     }
     $clang = $this->getController()->lang;
     Yii::app()->session['flashmessage'] = $clang->gT("The survey was successfully expired by setting an expiration date in the survey settings.");
     $this->_expireSurvey($iSurveyID);
     $dExpirationdate = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", Yii::app()->getConfig('timeadjust'));
     $dExpirationdate = dateShift($dExpirationdate, "Y-m-d H:i:s", '-1 day');
     Survey::model()->updateByPk($iSurveyID, array('expires' => $dExpirationdate));
     $this->getController()->redirect($this->getController()->createUrl('admin/survey/sa/view/surveyid/' . $iSurveyID));
 }
Ejemplo n.º 23
0
 /**
  * Function responsible for deleting a question.
  *
  * @access public
  * @param string $action
  * @param int $surveyid
  * @param int $gid
  * @param int $qid
  * @return void
  */
 public function delete($surveyid, $gid, $qid)
 {
     $clang = $this->getController()->lang;
     $surveyid = sanitize_int($surveyid);
     $gid = sanitize_int($gid);
     $qid = sanitize_int($qid);
     if (hasSurveyPermission($surveyid, 'surveycontent', 'delete')) {
         if (!isset($qid)) {
             $qid = returnGlobal('qid');
         }
         LimeExpressionManager::RevertUpgradeConditionsToRelevance(NULL, $qid);
         // Check if any other questions have conditions which rely on this question. Don't delete if there are.
         // TMSW Conditions->Relevance:  Allow such deletes - can warn about missing relevance separately.
         $ccresult = Conditions::model()->findAllByAttributes(array('cqid' => $qid));
         $cccount = count($ccresult);
         // There are conditions dependent on this question
         if ($cccount) {
             foreach ($ccresult as $ccr) {
                 $qidarray[] = $ccr->qid;
             }
             if (isset($qidarray)) {
                 $qidlist = implode(", ", $qidarray);
             }
             $message = $clang->gT("Question could not be deleted. There are conditions for other questions that rely on this question. You cannot delete this question until those conditions are removed.");
             $message .= "<br /><a href='" . $this->getController()->createUrl("admin/expressions/sa/survey_logic_file/sid/{$surveyid}") . "' >" . $clang->gT("Look at survey logic files") . "</a>.";
             $this->getController()->error($message, $this->getController()->createUrl("admin/survey/sa/view/surveyid/{$surveyid}/gid/{$gid}/qid/{$qid}"));
         } else {
             $row = Questions::model()->findByAttributes(array('qid' => $qid))->attributes;
             $gid = $row['gid'];
             // See if there are any conditions/attributes/answers/defaultvalues for this question,
             // and delete them now as well
             Conditions::model()->deleteAllByAttributes(array('qid' => $qid));
             Question_attributes::model()->deleteAllByAttributes(array('qid' => $qid));
             Answers::model()->deleteAllByAttributes(array('qid' => $qid));
             $criteria = new CDbCriteria();
             $criteria->addCondition('qid = :qid1 or parent_qid = :qid2');
             $criteria->params[':qid1'] = $qid;
             $criteria->params[':qid2'] = $qid;
             Questions::model()->deleteAll($criteria);
             Defaultvalues::model()->deleteAllByAttributes(array('qid' => $qid));
             Quota_members::model()->deleteAllByAttributes(array('qid' => $qid));
             Questions::model()->updateQuestionOrder($gid, $surveyid);
             $qid = "";
             $postqid = "";
             $_GET['qid'] = "";
         }
         Yii::app()->session['flashmessage'] = $clang->gT("Question was successfully deleted.");
         $this->getController()->redirect($this->getController()->createUrl('admin/survey/sa/view/surveyid/' . $surveyid . '/gid/' . $gid));
     } else {
         Yii::app()->session['flashmessage'] = $clang->gT("You are not authorized to delete questions.");
         $this->getController()->redirect($this->getController()->createUrl('admin/survey/sa/view/surveyid/' . $surveyid . '/gid/' . $gid));
     }
 }
Ejemplo n.º 24
0
 /**
  * Deletes an assessment.
  */
 private function _delete($iSurveyID, $assessmentId)
 {
     if (hasSurveyPermission($iSurveyID, 'assessments', 'delete')) {
         Assessment::model()->deleteAllByAttributes(array('id' => $assessmentId));
     }
 }
Ejemplo n.º 25
0
 /**
  * RPC Routine to export responses.
  * Returns the requested file as base64 encoded string
  *
  * @access public
  * @param string $sSessionKey Auth credentials 
  * @param int $iSurveyID Id of the Survey
  * @param string $sDocumentType pdf,csv,xls,doc
  * @param string $sLanguageCode The language to be used
  * @param string $sCompletionStatus Optional 'complete','incomplete' or 'all' - defaults to complete
  * @param string $sHeadingType 'code','full' or 'abbreviated' Optional defaults to 'code'
  * @param string $sResponseType 'short' or 'long' Optional defaults to 'short'
  * @param integer $iFromResponseID Optional
  * @param integer $iToResponseID Optional
  * @param array $aFields Optional Selected fields
  * @return array|string On success: Requested file as base 64-encoded string. On failure array with error information
  **/
 public function export_responses($sSessionKey, $iSurveyID, $sDocumentType, $sLanguageCode = null, $sCompletionStatus = 'all', $sHeadingType = 'code', $sResponseType = 'short', $iFromResponseID = null, $iToResponseID = null, $aFields = null)
 {
     if (!$this->_checkSessionKey($sSessionKey)) {
         return array('status' => 'Invalid session key');
     }
     Yii::app()->loadHelper('admin/exportresults');
     if (!hasSurveyPermission($iSurveyID, 'responses', 'export')) {
         return array('status' => 'No permission');
     }
     if (is_null($sLanguageCode)) {
         $sLanguageCode = getBaseLanguageFromSurveyID($iSurveyID);
     }
     if (is_null($aFields)) {
         $aFields = array_keys(createFieldMap($iSurveyID, 'full', true, false, $sLanguageCode));
     }
     if ($sDocumentType == 'xls') {
         // Cut down to the first 255 fields
         $aFields = array_slice($aFields, 0, 255);
     }
     $oFomattingOptions = new FormattingOptions();
     $oFomattingOptions->format = $sDocumentType;
     $oFomattingOptions->responseMinRecord = $iFromResponseID;
     $oFomattingOptions->responseMaxRecord = $iToResponseID;
     $oFomattingOptions->selectedColumns = $aFields;
     $oFomattingOptions->responseCompletionState = $sCompletionStatus;
     $oFomattingOptions->headingFormat = $sHeadingType;
     $oFomattingOptions->answerFormat = $sResponseType;
     $oExport = new ExportSurveyResultsService();
     $sFileData = $oExport->exportSurvey($iSurveyID, $sLanguageCode, $oFomattingOptions, 'return');
     return base64_encode($sFileData);
 }
<tr>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td><?php 
echo $totalcompleted;
?>
</td>
    <td><?php 
echo $totalquotas;
?>
</td>
    <td style="padding: 3px;">
        <?php 
if (hasSurveyPermission($iSurveyId, 'quotas', 'create')) {
    ?>
            <?php 
    echo CHtml::form(array("admin/quotas/sa/newquota/surveyid/{$iSurveyId}"), 'post');
    ?>
            <input name="submit" type="submit" class="quota_new" value="<?php 
    $clang->eT("Add New Quota");
    ?>
" />
            <input type="hidden" name="sid" value="<?php 
    echo $iSurveyId;
    ?>
" />
            <input type="hidden" name="action" value="quotas" />
            <input type="hidden" name="subaction" value="new_quota" />
            </form>
Ejemplo n.º 27
0
<tr class='<?php echo $bgcc; ?>' valign='top'>
    <td align='center'><input type='checkbox' class='cbResponseMarker' value='<?php echo $dtrow['id']; ?>' name='markedresponses[]' /></td>
    <td align='center'>
        <a href='<?php echo $this->createUrl("admin/responses/view/surveyid/$surveyid/id/{$dtrow['id']}"); ?>'><img src='<?php echo $sImageURL; ?>/token_viewanswer.png' alt='<?php $clang->eT('View response details'); ?>'/></a>
        <?php if (hasSurveyPermission($surveyid, 'responses', 'update'))
            { ?>
            <a href='<?php echo $this->createUrl("admin/dataentry/editdata/subaction/edit/surveyid/{$surveyid}/id/{$dtrow['id']}"); ?>'><img src='<?php echo $sImageURL; ?>/edit_16.png' alt='<?php $clang->eT('Edit this response'); ?>'/></a>
            <?php }
            if (hasFileUploadQuestion($surveyid))
            { ?>
            <a><img id='downloadfile_<?php echo $dtrow['id']; ?>' src='<?php echo $sImageURL; ?>down.png' alt='<?php $clang->eT('Download all files in this response as a zip file'); ?>' class='downloadfile'/></a>
            <?php }
            if (hasSurveyPermission($surveyid, 'responses', 'delete'))
            { ?>
            <a><img id='deleteresponse_<?php echo $dtrow['id']; ?>' src='<?php echo $sImageURL; ?>token_delete.png' alt='<?php $clang->eT('Delete this response'); ?>' class='deleteresponse'/></a>
            <?php } ?>
    </td>
    <?php
        $i = 0;
        $browsedatafield="";
        if ($surveyinfo['anonymized'] == "N" && $dtrow['token'])
        {
            if (isset($dtrow['tid']) && !empty($dtrow['tid']))
            {
                //If we have a token, create a link to edit it
                $browsedatafield .= "<a href='" . $this->createUrl("admin/tokens/edit/surveyid/$surveyid/tokenid/{$dtrow['tid']}/") . "' title='" . $clang->gT("Edit this token") . "'>";
                $browsedatafield .= "{$dtrow['token']}";
                $browsedatafield .= "</a>";
            }
            else
            {
Ejemplo n.º 28
0
 /**
  * surveypermission::set()
  * Function responsible to set permissions to a user/usergroup.
  * @param mixed $surveyid
  * @return void
  */
 function set($surveyid)
 {
     $aData['surveyid'] = $surveyid = sanitize_int($surveyid);
     $aViewUrls = array();
     $action = $_POST['action'];
     $clang = Yii::app()->lang;
     $imageurl = Yii::app()->getConfig('adminimageurl');
     $postuserid = !empty($_POST['uid']) ? $_POST['uid'] : null;
     $postusergroupid = !empty($_POST['ugid']) ? $_POST['ugid'] : null;
     if ($action == "setsurveysecurity" || $action == "setusergroupsurveysecurity") {
         $where = 'sid = :surveyid AND owner_id = :owner_id ';
         $params = array(':surveyid' => $surveyid, ':owner_id' => Yii::app()->session['loginID']);
         if ($action == "setsurveysecurity") {
             $where .= "AND owner_id != :postuserid";
             $params[':postuserid'] = $postuserid;
         }
         $result = Survey::model()->count($where, $params);
         if ($result > 0 || Yii::app()->session['USER_RIGHT_SUPERADMIN'] == 1) {
             //$js_admin_includes[]='../scripts/jquery/jquery.tablesorter.min.js';
             //$js_admin_includes[]='scripts/surveysecurity.js';
             $this->getController()->_js_admin_includes(Yii::app()->getConfig('generalscripts') . 'jquery/jquery.tablesorter.min.js');
             $this->getController()->_js_admin_includes(Yii::app()->getConfig('adminscripts') . 'surveysecurity.js');
             if ($action == "setsurveysecurity") {
                 $query = "select users_name from {{users}} where uid=:uid";
                 $resrow = Yii::app()->db->createCommand($query)->bindParam(":uid", $postuserid, PDO::PARAM_INT)->queryRow();
                 $sUsername = $resrow['users_name'];
                 $usersummary = "<div class='header ui-widget-header'>" . sprintf($clang->gT("Edit survey permissions for user %s"), "<span style='font-style:italic'>" . $sUsername . "</span>") . "</div>";
             } else {
                 $resrow = User_groups::model()->find('ugid = :ugid', array(':ugid' => $postusergroupid));
                 $sUsergroupName = $resrow['name'];
                 $usersummary = "<div class='header ui-widget-header'>" . sprintf($clang->gT("Edit survey permissions for group %s"), "<span style='font-style:italic'>" . $sUsergroupName . "</span>") . "</div>";
             }
             $usersummary .= "<br />" . CHtml::form(array("admin/surveypermission/sa/surveyright/surveyid/{$surveyid}"), 'post') . "<table style='margin:0 auto;' class='usersurveypermissions'><thead>\n";
             $usersummary .= "" . "<tr><th></th><th>" . $clang->gT("Permission") . "</th>\n" . "<th><input type='button' id='btnToggleAdvanced' value='<<' /></th>\n" . "<th class='extended'>" . $clang->gT("Create") . "</th>\n" . "<th class='extended'>" . $clang->gT("View/read") . "</th>\n" . "<th class='extended'>" . $clang->gT("Update") . "</th>\n" . "<th class='extended'>" . $clang->gT("Delete") . "</th>\n" . "<th class='extended'>" . $clang->gT("Import") . "</th>\n" . "<th class='extended'>" . $clang->gT("Export") . "</th>\n" . "</tr></thead>\n";
             //content
             $aBasePermissions = Survey_permissions::model()->getBasePermissions();
             $oddcolumn = false;
             foreach ($aBasePermissions as $sPermissionKey => $aCRUDPermissions) {
                 $oddcolumn = !$oddcolumn;
                 $usersummary .= "<tr><td><img src='{$imageurl}{$aCRUDPermissions['img']}_30.png' alt='{$aCRUDPermissions['description']}'/></td>";
                 $usersummary .= "<td>{$aCRUDPermissions['title']}</td>";
                 $usersummary .= "<td ><input type=\"checkbox\"  class=\"markrow\" name='all_{$sPermissionKey}' /></td>";
                 foreach ($aCRUDPermissions as $sCRUDKey => $CRUDValue) {
                     if (!in_array($sCRUDKey, array('create', 'read', 'update', 'delete', 'import', 'export'))) {
                         continue;
                     }
                     $usersummary .= "<td class='extended'>";
                     if ($CRUDValue) {
                         if (!($sPermissionKey == 'survey' && $sCRUDKey == 'read')) {
                             $usersummary .= "<input type=\"checkbox\"  class=\"checkboxbtn\" name='perm_{$sPermissionKey}_{$sCRUDKey}' ";
                             if ($action == 'setsurveysecurity' && hasSurveyPermission($surveyid, $sPermissionKey, $sCRUDKey, $postuserid)) {
                                 $usersummary .= ' checked="checked" ';
                             }
                             $usersummary .= " />";
                         }
                     }
                     $usersummary .= "</td>";
                 }
                 $usersummary .= "</tr>";
             }
             $usersummary .= "\n</table>" . "<p><input type='submit' value='" . $clang->gT("Save Now") . "' />" . "<input type='hidden' name='perm_survey_read' value='1' />" . "<input type='hidden' name='action' value='surveyrights' />";
             if ($action == 'setsurveysecurity') {
                 $usersummary .= "<input type='hidden' name='uid' value='{$postuserid}' />";
             } else {
                 $usersummary .= "<input type='hidden' name='ugid' value='{$postusergroupid}' />";
             }
             $usersummary .= "</form>\n";
             $aViewUrls['output'] = $usersummary;
         } else {
             include "accessDenied.php";
         }
     }
     $this->_renderWrappedTemplate('authentication', $aViewUrls, $aData);
 }
Ejemplo n.º 29
0
 /**
  * dataentry::view()
  * view a dataentry
  * @param mixed $surveyid
  * @param mixed $lang
  * @return
  */
 public function view($surveyid, $lang = NULL)
 {
     $surveyid = sanitize_int($surveyid);
     $lang = isset($_GET['lang']) ? $_GET['lang'] : NULL;
     if (isset($lang)) {
         $lang = sanitize_languagecode($lang);
     }
     $aViewUrls = array();
     if (hasSurveyPermission($surveyid, 'responses', 'read')) {
         $clang = Yii::app()->lang;
         $sDataEntryLanguage = Survey::model()->findByPk($surveyid)->language;
         $surveyinfo = getSurveyInfo($surveyid);
         $slangs = Survey::model()->findByPk($surveyid)->additionalLanguages;
         $baselang = Survey::model()->findByPk($surveyid)->language;
         array_unshift($slangs, $baselang);
         if (is_null($lang) || !in_array($lang, $slangs)) {
             $sDataEntryLanguage = $baselang;
             $blang = $clang;
         } else {
             Yii::app()->loadLibrary('Limesurvey_lang', array($lang));
             $blang = new Limesurvey_lang($lang);
             $sDataEntryLanguage = $lang;
         }
         $langlistbox = languageDropdown($surveyid, $sDataEntryLanguage);
         $thissurvey = getSurveyInfo($surveyid);
         //This is the default, presenting a blank dataentry form
         LimeExpressionManager::StartSurvey($surveyid, 'survey', NULL, false, LEM_PRETTY_PRINT_ALL_SYNTAX);
         $moveResult = LimeExpressionManager::NavigateForwards();
         $aData['thissurvey'] = $thissurvey;
         $aData['langlistbox'] = $langlistbox;
         $aData['surveyid'] = $surveyid;
         $aData['blang'] = $blang;
         $aData['site_url'] = Yii::app()->homeUrl;
         LimeExpressionManager::StartProcessingPage(true, Yii::app()->baseUrl);
         // means that all variables are on the same page
         $aViewUrls[] = 'caption_view';
         Yii::app()->loadHelper('database');
         // SURVEY NAME AND DESCRIPTION TO GO HERE
         $degquery = "SELECT * FROM {{groups}} WHERE sid={$surveyid} AND language='{$sDataEntryLanguage}' ORDER BY {{groups}}.group_order";
         $degresult = dbExecuteAssoc($degquery);
         // GROUP NAME
         $aDataentryoutput = '';
         foreach ($degresult->readAll() as $degrow) {
             LimeExpressionManager::StartProcessingGroup($degrow['gid'], $thissurvey['anonymized'] != "N", $surveyid);
             $deqquery = "SELECT * FROM {{questions}} WHERE sid={$surveyid} AND parent_qid=0 AND gid={$degrow['gid']} AND language='{$sDataEntryLanguage}'";
             $deqrows = (array) dbExecuteAssoc($deqquery)->readAll();
             $aDataentryoutput .= "\t<tr>\n" . "<td colspan='3' align='center'><strong>" . flattenText($degrow['group_name'], true) . "</strong></td>\n" . "\t</tr>\n";
             $gid = $degrow['gid'];
             $aDataentryoutput .= "\t<tr class='data-entry-separator'><td colspan='3'></td></tr>\n";
             // Perform a case insensitive natural sort on group name then question title of a multidimensional array
             usort($deqrows, 'groupOrderThenQuestionOrder');
             $bgc = 'odd';
             foreach ($deqrows as $deqrow) {
                 $qidattributes = getQuestionAttributeValues($deqrow['qid'], $deqrow['type']);
                 $cdata['qidattributes'] = $qidattributes;
                 $hidden = isset($qidattributes['hidden']) ? $qidattributes['hidden'] : 0;
                 // TODO - can questions be hidden?  Are JavaScript variables names used?  Consistently with everywhere else?
                 //                    LimeExpressionManager::ProcessRelevance($qidattributes['relevance'],$deqrow['qid'],NULL,$deqrow['type'],$hidden);
                 // TMSW Conditions->Relevance:  Show relevance equation instead of conditions here - better yet, have data entry use survey-at-a-time but with different view
                 $qinfo = LimeExpressionManager::GetQuestionStatus($deqrow['qid']);
                 $relevance = trim($qinfo['info']['relevance']);
                 $explanation = trim($qinfo['relEqn']);
                 $validation = trim($qinfo['prettyValidTip']);
                 $qidattributes = getQuestionAttributeValues($deqrow['qid']);
                 $array_filter_help = flattenText($this->_array_filter_help($qidattributes, $sDataEntryLanguage, $surveyid));
                 if ($relevance != '' && $relevance != '1' || $validation != '' || $array_filter_help != '') {
                     $showme = '';
                     if ($bgc == "even") {
                         $bgc = "odd";
                     } else {
                         $bgc = "even";
                     }
                     //Do no alternate on explanation row
                     if ($relevance != '' && $relevance != '1') {
                         $showme = "[" . $blang->gT("Only answer this if the following conditions are met:") . "]<br />{$explanation}\n";
                     }
                     if ($showme != '' && $validation != '') {
                         $showme .= '<br/>';
                     }
                     if ($validation != '') {
                         $showme .= "[" . $blang->gT("The answer(s) must meet these validation criteria:") . "]<br />{$validation}\n";
                     }
                     if ($showme != '' && $array_filter_help != '') {
                         $showme .= '<br/>';
                     }
                     if ($array_filter_help != '') {
                         $showme .= "[" . $blang->gT("The answer(s) must meet these array_filter criteria:") . "]<br />{$array_filter_help}\n";
                     }
                     $cdata['explanation'] = "<tr class ='data-entry-explanation'><td class='data-entry-small-text' colspan='3' align='left'>{$showme}</td></tr>\n";
                 }
                 //END OF GETTING CONDITIONS
                 //Alternate bgcolor for different groups
                 if (!isset($bgc)) {
                     $bgc = "even";
                 }
                 if ($bgc == "even") {
                     $bgc = "odd";
                 } else {
                     $bgc = "even";
                 }
                 $qid = $deqrow['qid'];
                 $fieldname = "{$surveyid}" . "X" . "{$gid}" . "X" . "{$qid}";
                 $cdata['bgc'] = $bgc;
                 $cdata['fieldname'] = $fieldname;
                 $cdata['deqrow'] = $deqrow;
                 $cdata['clang'] = $clang;
                 //DIFFERENT TYPES OF DATA FIELD HERE
                 $cdata['blang'] = $blang;
                 $cdata['thissurvey'] = $thissurvey;
                 if ($deqrow['help']) {
                     $hh = addcslashes($deqrow['help'], "..'\"");
                     //Escape ASCII decimal 0-32 plus single and double quotes to make JavaScript happy.
                     $hh = htmlspecialchars($hh, ENT_QUOTES);
                     //Change & " ' < > to HTML entities to make HTML happy.
                     $cdata['hh'] = $hh;
                     //$aDataentryoutput .= "\t<img src='$imageurl/help.gif' alt='".$blang->gT("Help about this question")."' align='right' onclick=\"javascript:alert('Question {$deqrow['title']} Help: $hh')\" />\n";
                 }
                 switch ($deqrow['type']) {
                     case "Q":
                         //MULTIPLE SHORT TEXT
                     //MULTIPLE SHORT TEXT
                     case "K":
                         $deaquery = "SELECT question,title FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $dearesult = dbExecuteAssoc($deaquery);
                         $cdata['dearesult'] = $dearesult->readAll();
                         break;
                     case "1":
                         // multi scale^
                         $deaquery = "SELECT * FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$baselang}' ORDER BY question_order";
                         $dearesult = dbExecuteAssoc($deaquery);
                         $cdata['dearesult'] = $dearesult->readAll();
                         $oquery = "SELECT other FROM {{questions}} WHERE qid={$deqrow['qid']} AND language='{$baselang}'";
                         $oresult = dbExecuteAssoc($oquery) or safeDie("Couldn't get other for list question<br />" . $oquery);
                         foreach ($oresult->readAll() as $orow) {
                             $cdata['fother'] = $orow['other'];
                         }
                         break;
                     case "L":
                         //LIST drop-down/radio-button list
                     //LIST drop-down/radio-button list
                     case "!":
                         //                            $qidattributes=getQuestionAttributeValues($deqrow['qid']);
                         if ($deqrow['type'] == '!' && trim($qidattributes['category_separator']) != '') {
                             $optCategorySeparator = $qidattributes['category_separator'];
                         } else {
                             unset($optCategorySeparator);
                         }
                         $defexists = "";
                         $deaquery = "SELECT * FROM {{answers}} WHERE qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY sortorder, answer";
                         $dearesult = dbExecuteAssoc($deaquery);
                         //$aDataentryoutput .= "\t<select name='$fieldname'>\n";
                         $aDatatemp = '';
                         if (!isset($optCategorySeparator)) {
                             foreach ($dearesult->readAll() as $dearow) {
                                 $aDatatemp .= "<option value='{$dearow['code']}'";
                                 //if ($dearow['default_value'] == "Y") {$aDatatemp .= " selected='selected'"; $defexists = "Y";}
                                 $aDatatemp .= ">{$dearow['answer']}</option>\n";
                             }
                         } else {
                             $defaultopts = array();
                             $optgroups = array();
                             foreach ($dearesult->readAll() as $dearow) {
                                 list($categorytext, $answertext) = explode($optCategorySeparator, $dearow['answer']);
                                 if ($categorytext == '') {
                                     $defaultopts[] = array('code' => $dearow['code'], 'answer' => $answertext, 'default_value' => $dearow['assessment_value']);
                                 } else {
                                     $optgroups[$categorytext][] = array('code' => $dearow['code'], 'answer' => $answertext, 'default_value' => $dearow['assessment_value']);
                                 }
                             }
                             foreach ($optgroups as $categoryname => $optionlistarray) {
                                 $aDatatemp .= "<optgroup class=\"dropdowncategory\" label=\"" . $categoryname . "\">\n";
                                 foreach ($optionlistarray as $optionarray) {
                                     $aDatatemp .= "\t<option value='{$optionarray['code']}'";
                                     //if ($optionarray['default_value'] == "Y") {$aDatatemp .= " selected='selected'"; $defexists = "Y";}
                                     $aDatatemp .= ">{$optionarray['answer']}</option>\n";
                                 }
                                 $aDatatemp .= "</optgroup>\n";
                             }
                             foreach ($defaultopts as $optionarray) {
                                 $aDatatemp .= "\t<option value='{$optionarray['code']}'";
                                 //if ($optionarray['default_value'] == "Y") {$aDatatemp .= " selected='selected'"; $defexists = "Y";}
                                 $aDatatemp .= ">{$optionarray['answer']}</option>\n";
                             }
                         }
                         $oquery = "SELECT other FROM {{questions}} WHERE qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}'";
                         $oresult = dbExecuteAssoc($oquery) or safeDie("Couldn't get other for list question<br />");
                         foreach ($oresult->readAll() as $orow) {
                             $fother = $orow['other'];
                         }
                         $cdata['fother'] = $fother;
                         $cdata['defexists'] = $defexists;
                         $cdata['datatemp'] = $aDatatemp;
                         break;
                     case "O":
                         //LIST WITH COMMENT drop-down/radio-button list + textarea
                         $defexists = "";
                         $deaquery = "SELECT * FROM {{answers}} WHERE qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY sortorder, answer";
                         $dearesult = dbExecuteAssoc($deaquery);
                         //$aDataentryoutput .= "\t<select name='$fieldname'>\n";
                         $aDatatemp = '';
                         foreach ($dearesult->readAll() as $dearow) {
                             $aDatatemp .= "<option value='{$dearow['code']}'";
                             //if ($dearow['default_value'] == "Y") {$aDatatemp .= " selected='selected'"; $defexists = "Y";}
                             $aDatatemp .= ">{$dearow['answer']}</option>\n";
                         }
                         $cdata['datatemp'] = $aDatatemp;
                         $cdata['defexists'] = $defexists;
                         break;
                     case "R":
                         //RANKING TYPE QUESTION
                         $thisqid = $deqrow['qid'];
                         $ansquery = "SELECT * FROM {{answers}} WHERE qid={$thisqid} AND language='{$sDataEntryLanguage}' ORDER BY sortorder, answer";
                         $ansresult = dbExecuteAssoc($ansquery);
                         $ansresult = $ansresult->readAll();
                         $anscount = count($ansresult);
                         $cdata['thisqid'] = $thisqid;
                         $cdata['anscount'] = $anscount;
                         foreach ($ansresult as $ansrow) {
                             $answers[] = array($ansrow['code'], $ansrow['answer']);
                         }
                         for ($i = 1; $i <= $anscount; $i++) {
                             if (isset($fname)) {
                                 $myfname = $fname . $i;
                             }
                             if (isset($myfname) && Yii::app()->session[$myfname]) {
                                 $existing++;
                             }
                         }
                         for ($i = 1; $i <= $anscount; $i++) {
                             if (isset($fname)) {
                                 $myfname = $fname . $i;
                             }
                             if (isset($myfname) && Yii::app()->session[$myfname]) {
                                 foreach ($answers as $ans) {
                                     if ($ans[0] == Yii::app()->session[$myfname]) {
                                         $thiscode = $ans[0];
                                         $thistext = $ans[1];
                                     }
                                 }
                             }
                             if (!isset($ranklist)) {
                                 $ranklist = "";
                             }
                             $ranklist .= "&nbsp;<font color='#000080'>{$i}:&nbsp;<input class='ranklist' type='text' name='RANK{$i}' id='RANK_{$thisqid}{$i}'";
                             if (isset($myfname) && Yii::app()->session[$myfname]) {
                                 $ranklist .= " value='";
                                 $ranklist .= $thistext;
                                 $ranklist .= "'";
                             }
                             $ranklist .= " onFocus=\"this.blur()\"  />\n";
                             $ranklist .= "<input type='hidden' id='d{$fieldname}{$i}' name='{$fieldname}{$i}' value='";
                             $chosen[] = "";
                             //create array
                             if (isset($myfname) && Yii::app()->session[$myfname]) {
                                 $ranklist .= $thiscode;
                                 $chosen[] = array($thiscode, $thistext);
                             }
                             $ranklist .= "' /></font>\n";
                             $ranklist .= "<img src='" . Yii::app()->getConfig('imageurl') . "/cut.gif' alt='" . $blang->gT("Remove this item") . "' title='" . $blang->gT("Remove this item") . "' ";
                             if (!isset($existing) || $i != $existing) {
                                 $ranklist .= "style='display:none'";
                             }
                             $mfn = $fieldname . $i;
                             $ranklist .= " id='cut_{$thisqid}{$i}' onclick=\"deletethis_{$thisqid}(document.addsurvey.RANK_{$thisqid}{$i}.value, document.addsurvey.d{$fieldname}{$i}.value, document.addsurvey.RANK_{$thisqid}{$i}.id, this.id)\" /><br />\n\n";
                         }
                         if (!isset($choicelist)) {
                             $choicelist = "";
                         }
                         $choicelist .= "<select size='{$anscount}' class='choicelist' name='CHOICES' id='CHOICES_{$thisqid}' onclick=\"rankthis_{$thisqid}(this.options[this.selectedIndex].value, this.options[this.selectedIndex].text)\" >\n";
                         foreach ($answers as $ans) {
                             if (!in_array($ans, $chosen)) {
                                 $choicelist .= "\t<option value='{$ans[0]}'>{$ans[1]}</option>\n";
                             }
                         }
                         $choicelist .= "</select>\n";
                         $cdata['choicelist'] = $choicelist;
                         $cdata['ranklist'] = $ranklist;
                         if (isset($multifields)) {
                             $cdata['multifields'] = $multifields;
                         }
                         $choicelist = "";
                         $ranklist = "";
                         unset($answers);
                         break;
                     case "M":
                         //Multiple choice checkbox (Quite tricky really!)
                         //                            $qidattributes=getQuestionAttributeValues($deqrow['qid']);
                         if (trim($qidattributes['display_columns']) != '') {
                             $dcols = $qidattributes['display_columns'];
                         } else {
                             $dcols = 0;
                         }
                         $meaquery = "SELECT title, question FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $mearesult = dbExecuteAssoc($meaquery);
                         $cdata['dcols'] = $dcols;
                         $cdata['meacount'] = $meacount;
                         $cdata['mearesult'] = $mearesult->readAll();
                         $meacount = count($cdata['mearesult']);
                         break;
                     case "I":
                         //Language Switch
                         $slangs = Survey::model()->findByPk($surveyid)->additionalLanguages;
                         $sbaselang = Survey::model()->findByPk($surveyid)->language;
                         array_unshift($slangs, $sbaselang);
                         $cdata['slangs'] = $slangs;
                         break;
                     case "P":
                         //Multiple choice with comments checkbox + text
                         //$aDataentryoutput .= "<table border='0'>\n";
                         $meaquery = "SELECT * FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY question_order, question";
                         $mearesult = dbExecuteAssoc($meaquery);
                         $cdata['mearesult'] = $mearesult->readAll();
                         break;
                     case "|":
                         //                            $qidattributes = getQuestionAttributeValues($deqrow['qid']);
                         $cdata['qidattributes'] = $qidattributes;
                         $maxfiles = $qidattributes['max_num_of_files'];
                         $cdata['maxfiles'] = $maxfiles;
                         break;
                     case "A":
                         //ARRAY (5 POINT CHOICE) radio-buttons
                         $meaquery = "SELECT title, question FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $mearesult = dbExecuteAssoc($meaquery);
                         $cdata['mearesult'] = $mearesult->readAll();
                         break;
                     case "B":
                         //ARRAY (10 POINT CHOICE) radio-buttons
                         $meaquery = "SELECT title, question FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $mearesult = dbExecuteAssoc($meaquery);
                         $cdata['mearesult'] = $mearesult->readAll();
                     case "C":
                         //ARRAY (YES/UNCERTAIN/NO) radio-buttons
                         $meaquery = "SELECT title, question FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $mearesult = dbExecuteAssoc($meaquery);
                         $cdata['mearesult'] = $mearesult->readAll();
                         break;
                     case "E":
                         //ARRAY (YES/UNCERTAIN/NO) radio-buttons
                         $meaquery = "SELECT title, question FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $mearesult = dbExecuteAssoc($meaquery) or safeDie("Couldn't get answers, Type \"E\"<br />{$meaquery}<br />");
                         $cdata['mearesult'] = $mearesult->readAll();
                         break;
                     case ":":
                         //ARRAY (Multi Flexi)
                         //                            $qidattributes=getQuestionAttributeValues($deqrow['qid']);
                         $minvalue = 1;
                         $maxvalue = 10;
                         if (trim($qidattributes['multiflexible_max']) != '' && trim($qidattributes['multiflexible_min']) == '') {
                             $maxvalue = $qidattributes['multiflexible_max'];
                             $minvalue = 1;
                         }
                         if (trim($qidattributes['multiflexible_min']) != '' && trim($qidattributes['multiflexible_max']) == '') {
                             $minvalue = $qidattributes['multiflexible_min'];
                             $maxvalue = $qidattributes['multiflexible_min'] + 10;
                         }
                         if (trim($qidattributes['multiflexible_min']) != '' && trim($qidattributes['multiflexible_max']) != '') {
                             if ($qidattributes['multiflexible_min'] < $qidattributes['multiflexible_max']) {
                                 $minvalue = $qidattributes['multiflexible_min'];
                                 $maxvalue = $qidattributes['multiflexible_max'];
                             }
                         }
                         if (trim($qidattributes['multiflexible_step']) != '') {
                             $stepvalue = $qidattributes['multiflexible_step'];
                         } else {
                             $stepvalue = 1;
                         }
                         if ($qidattributes['multiflexible_checkbox'] != 0) {
                             $minvalue = 0;
                             $maxvalue = 1;
                             $stepvalue = 1;
                         }
                         $cdata['minvalue'] = $minvalue;
                         $cdata['maxvalue'] = $maxvalue;
                         $cdata['stepvalue'] = $stepvalue;
                         $lquery = "SELECT question, title FROM {{questions}} WHERE parent_qid={$deqrow['qid']} and scale_id=1 and language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $lresult = dbExecuteAssoc($lquery) or die("Couldn't get labels, Type \":\"<br />{$lquery}<br />");
                         $cdata['lresult'] = $lresult->readAll();
                         $meaquery = "SELECT question, title FROM {{questions}} WHERE parent_qid={$deqrow['qid']} and scale_id=0 and language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $mearesult = dbExecuteAssoc($meaquery) or die("Couldn't get answers, Type \":\"<br />{$meaquery}<br />");
                         $cdata['mearesult'] = $mearesult->readAll();
                         break;
                     case ";":
                         //ARRAY (Multi Flexi)
                         $lquery = "SELECT * FROM {{questions}} WHERE scale_id=1 and parent_qid={$deqrow['qid']} and language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $lresult = dbExecuteAssoc($lquery) or die("Couldn't get labels, Type \":\"<br />{$lquery}<br />");
                         $cdata['lresult'] = $lresult->readAll();
                         $meaquery = "SELECT * FROM {{questions}} WHERE scale_id=0 and parent_qid={$deqrow['qid']} and language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $mearesult = dbExecuteAssoc($meaquery) or die("Couldn't get answers, Type \":\"<br />{$meaquery}<br />");
                         $cdata['mearesult'] = $mearesult->readAll();
                         break;
                     case "F":
                         //ARRAY (Flexible Labels)
                     //ARRAY (Flexible Labels)
                     case "H":
                         $meaquery = "SELECT * FROM {{questions}} WHERE parent_qid={$deqrow['qid']} and language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $mearesult = dbExecuteAssoc($meaquery) or safeDie("Couldn't get answers, Type \"E\"<br />{$meaquery}<br />");
                         $cdata['mearesult'] = $mearesult->readAll();
                         $fquery = "SELECT * FROM {{answers}} WHERE qid={$deqrow['qid']} and language='{$sDataEntryLanguage}' ORDER BY sortorder, code";
                         $fresult = dbExecuteAssoc($fquery);
                         $cdata['fresult'] = $fresult->readAll();
                         break;
                 }
                 $cdata['sDataEntryLanguage'] = $sDataEntryLanguage;
                 $viewdata = $this->getController()->render("/admin/dataentry/content_view", $cdata, TRUE);
                 $viewdata_em = LimeExpressionManager::ProcessString($viewdata, $deqrow['qid'], NULL, false, 1, 1);
                 $aDataentryoutput .= $viewdata_em;
             }
             LimeExpressionManager::FinishProcessingGroup();
         }
         LimeExpressionManager::FinishProcessingPage();
         $aDataentryoutput .= LimeExpressionManager::GetRelevanceAndTailoringJavaScript();
         $aViewUrls['output'] = $aDataentryoutput;
         $aData['thissurvey'] = $thissurvey;
         $aData['surveyid'] = $surveyid;
         $aData['sDataEntryLanguage'] = $sDataEntryLanguage;
         if ($thissurvey['active'] == "Y" && $thissurvey['allowsave'] == "Y") {
             $slangs = Survey::model()->findByPk($surveyid)->additionalLanguages;
             $sbaselang = Survey::model()->findByPk($surveyid)->language;
             array_unshift($slangs, $sbaselang);
             $aData['slangs'] = $slangs;
             $aData['baselang'] = $baselang;
         }
         $aViewUrls[] = 'active_html_view';
         $this->_renderWrappedTemplate('dataentry', $aViewUrls, $aData);
     }
 }
    if (hasSurveyPermission($iSurveyId, 'responses', 'update')) {
        ?>
                            <input style='height: 16; width: 16px; font-size: 8; font-family: verdana' type='image' src='<?php 
        echo $sImageURL;
        ?>
edit_16.png'
                                title='<?php 
        $clang->eT('Edit entry');
        ?>
' onclick="window.open('<?php 
        echo $this->createUrl("admin/dataentry/sa/editdata/subaction/edit/surveyid/{$iSurveyId}/id/{$oResult->srid}");
        ?>
', '_top')" />
                            <?php 
    }
    if (hasSurveyPermission($iSurveyId, 'responses', 'delete')) {
        ?>
                            <input style='height: 16; width: 16px; font-size: 8; font-family: verdana' type='image' src='<?php 
        echo $sImageURL;
        ?>
token_delete.png'
                                title='<?php 
        $clang->eT('Delete entry');
        ?>
' onclick="if (confirm('<?php 
        $clang->eT('Are you sure you want to delete this entry?', 'js');
        ?>
')) { window.open('<?php 
        echo $this->createUrl("admin/saved/delete/surveyid/{$iSurveyId}/srid/{$oResult->srid}/scid/{$oResult->scid}");
        ?>
', '_top'); }" />