Example #1
0
 /**
  * Base function
  *
  * This functions receives the request to generate a dump file for the
  * database and does so! Only superadmins are allowed to do this!
  */
 public function index()
 {
     $sFileName = 'LimeSurvey_' . $sDbName . '_dump_' . dateShift(date('Y-m-d H:i:s'), 'Y-m-d', Yii::app()->getConfig('timeadjust')) . '.sql';
     $this->_outputHeaders($sFileName);
     Yii::app()->loadHelper("admin/backupdb");
     outputDatabase();
     exit;
 }
function _outputDBDescription($sDbName, $bAllowExportAllDb)
{
    $sOutput = '--' . "\n";
    $sOutput .= '-- LimeSurvey Database Dump of `' . $sDbName . '`' . "\n";
    if (!$bAllowExportAllDb) {
        $sOutput = '-- Only prefixed tables with: ' . Yii::app()->db->tablePrefix . "\n";
    }
    $sOutput .= '-- Date of Dump: ' . dateShift(date('d-M-Y'), 'd-M-Y', Yii::app()->getConfig('timeadjust')) . "\n";
    $sOutput .= '--' . "\n";
    return $sOutput;
}
Example #3
0
 /**
  * Initialises this controller, does some basic checks and setups
  *
  * @access protected
  * @return void
  */
 protected function _init()
 {
     parent::_init();
     App()->getComponent('bootstrap');
     $sUpdateLastCheck = getGlobalSetting('updatelastcheck');
     // echo "111111";
     $this->_sessioncontrol();
     if (Yii::app()->getConfig('buildnumber') != "" && Yii::app()->getConfig('updatecheckperiod') > 0 && $sUpdateLastCheck < dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", "-" . Yii::app()->getConfig('updatecheckperiod') . " days")) {
         updateCheck();
     }
     //unset(Yii::app()->session['FileManagerContext']);
     App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('adminscripts') . "admin_core.js");
     $this->user_id = Yii::app()->user->getId();
     if (!Yii::app()->getConfig("surveyid")) {
         Yii::app()->setConfig("surveyid", returnGlobal('sid'));
     }
     //SurveyID
     if (!Yii::app()->getConfig("ugid")) {
         Yii::app()->setConfig("ugid", returnGlobal('ugid'));
     }
     //Usergroup-ID
     if (!Yii::app()->getConfig("gid")) {
         Yii::app()->setConfig("gid", returnGlobal('gid'));
     }
     //GroupID
     if (!Yii::app()->getConfig("qid")) {
         Yii::app()->setConfig("qid", returnGlobal('qid'));
     }
     //QuestionID
     if (!Yii::app()->getConfig("lid")) {
         Yii::app()->setConfig("lid", returnGlobal('lid'));
     }
     //LabelID
     if (!Yii::app()->getConfig("code")) {
         Yii::app()->setConfig("code", returnGlobal('code'));
     }
     // ??
     if (!Yii::app()->getConfig("action")) {
         Yii::app()->setConfig("action", returnGlobal('action'));
     }
     //Desired action
     if (!Yii::app()->getConfig("subaction")) {
         Yii::app()->setConfig("subaction", returnGlobal('subaction'));
     }
     //Desired subaction
     if (!Yii::app()->getConfig("editedaction")) {
         Yii::app()->setConfig("editedaction", returnGlobal('editedaction'));
     }
     // for html editor integration
 }
Example #4
0
 /**
  * Initialises this controller, does some basic checks and setups
  *
  * @access protected
  * @return void
  */
 protected function _init()
 {
     parent::_init();
     $updatelastcheck = '';
     $this->_sessioncontrol();
     if (Yii::app()->getConfig('buildnumber') != "" && Yii::app()->getConfig('updatecheckperiod') > 0 && $updatelastcheck < dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", "-" . Yii::app()->getConfig('updatecheckperiod') . " days")) {
         updateCheck();
     }
     //unset(Yii::app()->session['FileManagerContext']);
     $this->user_id = Yii::app()->user->getId();
     Yii::app()->setConfig('adminimageurl', Yii::app()->getConfig('styleurl') . Yii::app()->getConfig('admintheme') . '/images/');
     Yii::app()->setConfig('adminstyleurl', Yii::app()->getConfig('styleurl') . Yii::app()->getConfig('admintheme') . '/');
     if (!Yii::app()->getConfig("surveyid")) {
         Yii::app()->setConfig("surveyid", returnGlobal('sid'));
     }
     //SurveyID
     if (!Yii::app()->getConfig("ugid")) {
         Yii::app()->setConfig("ugid", returnGlobal('ugid'));
     }
     //Usergroup-ID
     if (!Yii::app()->getConfig("gid")) {
         Yii::app()->setConfig("gid", returnGlobal('gid'));
     }
     //GroupID
     if (!Yii::app()->getConfig("qid")) {
         Yii::app()->setConfig("qid", returnGlobal('qid'));
     }
     //QuestionID
     if (!Yii::app()->getConfig("lid")) {
         Yii::app()->setConfig("lid", returnGlobal('lid'));
     }
     //LabelID
     if (!Yii::app()->getConfig("code")) {
         Yii::app()->setConfig("code", returnGlobal('code'));
     }
     // ??
     if (!Yii::app()->getConfig("action")) {
         Yii::app()->setConfig("action", returnGlobal('action'));
     }
     //Desired action
     if (!Yii::app()->getConfig("subaction")) {
         Yii::app()->setConfig("subaction", returnGlobal('subaction'));
     }
     //Desired subaction
     if (!Yii::app()->getConfig("editedaction")) {
         Yii::app()->setConfig("editedaction", returnGlobal('editedaction'));
     }
     // for html editor integration
 }
 private function _displaySettings()
 {
     Yii::app()->loadHelper('surveytranslator');
     // Save refurl from where global settings screen is called!
     // Unless it's called from global settings...
     $refurl = Yii::app()->getRequest()->getUrlReferrer();
     // Some URLs are not to be allowed to refered back to.
     // These exceptions can be added to the $aReplacements array
     $aReplacements = array('admin/update/sa/step4b' => 'admin/sa/index', 'admin/user/sa/adduser' => 'admin/user/sa/index', 'admin/user/sa/setusertemplates' => 'admin/user/sa/index');
     $refurl = str_replace(array_keys($aReplacements), array_values($aReplacements), $refurl);
     // Don't update session variable if refurl is empty (happens when user clicks Save)
     if ($refurl !== "") {
         Yii::app()->session['refurl'] = htmlspecialchars($refurl);
         //just to be safe!
     }
     $data['title'] = "hi";
     $data['message'] = "message";
     foreach ($this->_checkSettings() as $key => $row) {
         $data[$key] = $row;
     }
     Yii::app()->loadLibrary('Date_Time_Converter');
     $dateformatdetails = getDateFormatData(Yii::app()->session['dateformat']);
     $datetimeobj = new date_time_converter(dateShift(getGlobalSetting("updatelastcheck"), 'Y-m-d H:i:s', getGlobalSetting('timeadjust')), 'Y-m-d H:i:s');
     $data['updatelastcheck'] = $datetimeobj->convert($dateformatdetails['phpdate'] . " H:i:s");
     $data['updateavailable'] = getGlobalSetting("updateavailable") && Yii::app()->getConfig("updatable");
     $data['updatable'] = Yii::app()->getConfig("updatable");
     $data['updateinfo'] = getGlobalSetting("updateinfo");
     $data['updatebuild'] = getGlobalSetting("updatebuild");
     $data['updateversion'] = getGlobalSetting("updateversion");
     $data['aUpdateVersions'] = json_decode(getGlobalSetting("updateversions"), true);
     $data['allLanguages'] = getLanguageData(false, Yii::app()->session['adminlang']);
     if (trim(Yii::app()->getConfig('restrictToLanguages')) == '') {
         $data['restrictToLanguages'] = array_keys($data['allLanguages']);
         $data['excludedLanguages'] = array();
     } else {
         $data['restrictToLanguages'] = explode(' ', trim(Yii::app()->getConfig('restrictToLanguages')));
         $data['excludedLanguages'] = array_diff(array_keys($data['allLanguages']), $data['restrictToLanguages']);
     }
     $data['fullpagebar']['savebutton']['form'] = 'frmglobalsettings';
     $data['fullpagebar']['saveandclosebutton']['form'] = 'frmglobalsettings';
     $data['fullpagebar']['closebutton']['url'] = 'admin/';
     $this->_renderWrappedTemplate('', 'globalSettings_view', $data);
 }
Example #6
0
 private function _displaySettings()
 {
     Yii::app()->loadHelper('surveytranslator');
     // Save refurl from where global settings screen is called!
     $refurl = Yii::app()->getRequest()->getUrlReferrer(Yii::app()->createUrl('admin'), array('globalsettings'));
     // Some URLs are not to be allowed to refered back to.
     // These exceptions can be added to the $aReplacements array
     $aReplacements = array('admin/update/sa/step4b' => 'admin/sa/index', 'admin/user/sa/adduser' => 'admin/user/sa/index', 'admin/user/sa/setusertemplates' => 'admin/user/sa/index');
     $data['title'] = "hi";
     $data['message'] = "message";
     foreach ($this->_checkSettings() as $key => $row) {
         $data[$key] = $row;
     }
     Yii::app()->loadLibrary('Date_Time_Converter');
     $dateformatdetails = getDateFormatData(Yii::app()->session['dateformat']);
     $datetimeobj = new date_time_converter(dateShift(getGlobalSetting("updatelastcheck"), 'Y-m-d H:i:s', getGlobalSetting('timeadjust')), 'Y-m-d H:i:s');
     $data['updatelastcheck'] = $datetimeobj->convert($dateformatdetails['phpdate'] . " H:i:s");
     $data['updateavailable'] = getGlobalSetting("updateavailable") && Yii::app()->getConfig("updatable");
     $data['updatable'] = Yii::app()->getConfig("updatable");
     $data['updateinfo'] = getGlobalSetting("updateinfo");
     $data['updatebuild'] = getGlobalSetting("updatebuild");
     $data['updateversion'] = getGlobalSetting("updateversion");
     $data['aUpdateVersions'] = json_decode(getGlobalSetting("updateversions"), true);
     $data['allLanguages'] = getLanguageData(false, Yii::app()->session['adminlang']);
     if (trim(Yii::app()->getConfig('restrictToLanguages')) == '') {
         $data['restrictToLanguages'] = array_keys($data['allLanguages']);
         $data['excludedLanguages'] = array();
     } else {
         $data['restrictToLanguages'] = explode(' ', trim(Yii::app()->getConfig('restrictToLanguages')));
         $data['excludedLanguages'] = array_diff(array_keys($data['allLanguages']), $data['restrictToLanguages']);
     }
     $data['fullpagebar']['savebutton']['form'] = 'frmglobalsettings';
     $data['fullpagebar']['saveandclosebutton']['form'] = 'frmglobalsettings';
     $data['fullpagebar']['closebutton']['url'] = 'admin/';
     // Close button
     // List of available encodings
     $data['aEncodings'] = aEncodingsArray();
     // Get current setting from DB
     $data['thischaracterset'] = getGlobalSetting('characterset');
     $data['sideMenuBehaviour'] = getGlobalSetting('sideMenuBehaviour');
     $data['aListOfThemeObjects'] = AdminTheme::getAdminThemeList();
     $this->_renderWrappedTemplate('', 'globalSettings_view', $data);
 }
?>
</option>
                    </select></li>
                <?php 
$dateformatdata = getDateFormatData(Yii::app()->session['dateformat']);
?>
                <li><label for='timeadjust'><?php 
$clang->eT("Time difference (in hours):");
?>
</label>
                    <span><input type='text' size='10' id='timeadjust' name='timeadjust' value="<?php 
echo htmlspecialchars(str_replace(array('+', ' hours'), array('', ''), getGlobalSetting('timeadjust')));
?>
" />
                        <?php 
echo $clang->gT("Server time:") . ' ' . convertDateTimeFormat(date('Y-m-d H:i:s'), 'Y-m-d H:i:s', $dateformatdata['phpdate'] . ' H:i') . " - " . $clang->gT("Corrected time :") . ' ' . convertDateTimeFormat(dateShift(date("Y-m-d H:i:s"), 'Y-m-d H:i:s', getGlobalSetting('timeadjust')), 'Y-m-d H:i:s', $dateformatdata['phpdate'] . ' H:i');
?>
                    </span></li>

                <li><label for='iSessionExpirationTime'><?php 
$clang->eT("Session lifetime (seconds):");
?>
</label>
                    <input type='text' size='10' id='iSessionExpirationTime' name='iSessionExpirationTime' value="<?php 
echo htmlspecialchars(getGlobalSetting('iSessionExpirationTime'));
?>
" /></li>
                <li><label for='ipInfoDbAPIKey'><?php 
$clang->eT("IP Info DB API Key:");
?>
</label>
                    {
                        $('#submitdata').button("option", "disabled", false);
                        $('#save-button').prop('disabled', false);
                    }
                    else
                    {
                        $('#submitdata').button("option", "disabled", true);
                        $('#save-button').prop('disabled', true);
                    }
                }
                //--></script>
                </td></tr>
            <?php 
}
if ($thissurvey['datestamp'] == "Y") {
    $localtimedate = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig('timeadjust'));
    ?>
                <tr>
                <td valign='top' width='1%'></td>
                <td valign='top' align='right' width='30%'><strong>
                <?php 
    echo gT("Datestamp", 'html', $sDataEntryLanguage);
    ?>
:</strong></td>
                <td valign='top'  align='left' style='padding-left: 20px'>
                <input type='text' name='datestamp' value='<?php 
    echo $localtimedate;
    ?>
' />
                </td>
                </tr>
/**
* Marks a tokens as completed and sends a confirmation email to the participiant.
* If $quotaexit is set to true then the user exited the survey due to a quota
* restriction and the according token is only marked as 'Q'
*
* @param mixed $quotaexit
*/
function submittokens($quotaexit = false)
{
    $surveyid = Yii::app()->getConfig('surveyID');
    if (isset($_SESSION['survey_' . $surveyid]['s_lang'])) {
        $thissurvey = getSurveyInfo($surveyid, $_SESSION['survey_' . $surveyid]['s_lang']);
    } else {
        $thissurvey = getSurveyInfo($surveyid);
    }
    $clienttoken = $_SESSION['survey_' . $surveyid]['token'];
    $sitename = Yii::app()->getConfig("sitename");
    $emailcharset = Yii::app()->getConfig("emailcharset");
    // Shift the date due to global timeadjust setting
    $today = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig("timeadjust"));
    // check how many uses the token has left
    $token = Token::model($surveyid)->findByAttributes(array('token' => $clienttoken));
    if ($quotaexit == true) {
        $token->completed = 'Q';
        $token->usesleft--;
    } else {
        if ($token->usesleft <= 1) {
            // Finish the token
            if (isTokenCompletedDatestamped($thissurvey)) {
                $token->completed = $today;
            } else {
                $token->completed = 'Y';
            }
            if (isset($token->participant_id)) {
                $slquery = SurveyLink::model()->find('participant_id = :pid AND survey_id = :sid AND token_id = :tid', array(':pid' => $token->participant_id, ':sid' => $surveyid, ':tid' => $token->tid));
                if ($slquery) {
                    if (isTokenCompletedDatestamped($thissurvey)) {
                        $slquery->date_completed = $today;
                    } else {
                        // Update the survey_links table if necessary, to protect anonymity, use the date_created field date
                        $slquery->date_completed = $slquery->date_created;
                    }
                    $slquery->save();
                }
            }
        }
        $token->usesleft--;
    }
    $token->save();
    if ($quotaexit == false) {
        if ($token && trim(strip_tags($thissurvey['email_confirm'])) != "" && $thissurvey['sendconfirmation'] == "Y") {
            //   if($token->completed == "Y" || $token->completed == $today)
            //            {
            $from = "{$thissurvey['adminname']} <{$thissurvey['adminemail']}>";
            $subject = $thissurvey['email_confirm_subj'];
            $aReplacementVars = array();
            $aReplacementVars["ADMINNAME"] = $thissurvey['admin'];
            $aReplacementVars["ADMINEMAIL"] = $thissurvey['adminemail'];
            $aReplacementVars['ADMINEMAIL'] = $thissurvey['adminemail'];
            //Fill with token info, because user can have his information with anonimity control
            $aReplacementVars["FIRSTNAME"] = $token->firstname;
            $aReplacementVars["LASTNAME"] = $token->lastname;
            $aReplacementVars["TOKEN"] = $token->token;
            // added survey url in replacement vars
            $surveylink = Yii::app()->createAbsoluteUrl("/survey/index/sid/{$surveyid}", array('lang' => $_SESSION['survey_' . $surveyid]['s_lang'], 'token' => $token->token));
            $aReplacementVars['SURVEYURL'] = $surveylink;
            $attrfieldnames = getAttributeFieldNames($surveyid);
            foreach ($attrfieldnames as $attr_name) {
                $aReplacementVars[strtoupper($attr_name)] = $token->{$attr_name};
            }
            $dateformatdatat = getDateFormatData($thissurvey['surveyls_dateformat']);
            $numberformatdatat = getRadixPointData($thissurvey['surveyls_numberformat']);
            $redata = array('thissurvey' => $thissurvey);
            $subject = templatereplace($subject, $aReplacementVars, $redata, '', false, null, array(), true);
            $subject = html_entity_decode($subject, ENT_QUOTES, $emailcharset);
            if (getEmailFormat($surveyid) == 'html') {
                $ishtml = true;
            } else {
                $ishtml = false;
            }
            $message = $thissurvey['email_confirm'];
            //$message=ReplaceFields($message, $fieldsarray, true);
            $message = templatereplace($message, $aReplacementVars, $redata, '', false, null, array(), true);
            if (!$ishtml) {
                $message = strip_tags(breakToNewline(html_entity_decode($message, ENT_QUOTES, $emailcharset)));
            } else {
                $message = html_entity_decode($message, ENT_QUOTES, $emailcharset);
            }
            //Only send confirmation email if there is a valid email address
            $sToAddress = validateEmailAddresses($token->email);
            if ($sToAddress) {
                $aAttachments = unserialize($thissurvey['attachments']);
                $aRelevantAttachments = array();
                /*
                 * Iterate through attachments and check them for relevance.
                 */
                if (isset($aAttachments['confirmation'])) {
                    foreach ($aAttachments['confirmation'] as $aAttachment) {
                        $relevance = $aAttachment['relevance'];
                        // If the attachment is relevant it will be added to the mail.
                        if (LimeExpressionManager::ProcessRelevance($relevance) && file_exists($aAttachment['url'])) {
                            $aRelevantAttachments[] = $aAttachment['url'];
                        }
                    }
                }
                SendEmailMessage($message, $subject, $sToAddress, $from, $sitename, $ishtml, null, $aRelevantAttachments);
            }
            //   } else {
            // Leave it to send optional confirmation at closed token
            //          }
        }
    }
}
Example #10
0
 function action()
 {
     global $surveyid;
     global $thissurvey, $thisstep;
     global $clienttoken, $tokensexist, $token;
     // only attempt to change session lifetime if using a DB backend
     // with file based sessions, it's up to the admin to configure maxlifetime
     if (isset(Yii::app()->session->connectionID)) {
         @ini_set('session.gc_maxlifetime', Yii::app()->getConfig('iSessionExpirationTime'));
     }
     $this->_loadRequiredHelpersAndLibraries();
     $param = $this->_getParameters(func_get_args(), $_POST);
     $surveyid = $param['sid'];
     Yii::app()->setConfig('surveyID', $surveyid);
     $thisstep = $param['thisstep'];
     $move = getMove();
     Yii::app()->setConfig('move', $move);
     $clienttoken = trim($param['token']);
     $standardtemplaterootdir = Yii::app()->getConfig('standardtemplaterootdir');
     if (is_null($thissurvey) && !is_null($surveyid)) {
         $thissurvey = getSurveyInfo($surveyid);
     }
     // unused vars in this method (used in methods using compacted method vars)
     @($loadname = $param['loadname']);
     @($loadpass = $param['loadpass']);
     $sitename = Yii::app()->getConfig('sitename');
     if (isset($param['newtest']) && $param['newtest'] == "Y") {
         killSurveySession($surveyid);
     }
     $surveyExists = $surveyid && Survey::model()->findByPk($surveyid);
     $isSurveyActive = $surveyExists && Survey::model()->findByPk($surveyid)->active == "Y";
     // collect all data in this method to pass on later
     $redata = compact(array_keys(get_defined_vars()));
     $this->_loadLimesurveyLang($surveyid);
     if ($this->_isClientTokenDifferentFromSessionToken($clienttoken, $surveyid)) {
         $sReloadUrl = $this->getController()->createUrl("/survey/index/sid/{$surveyid}", array('token' => $clienttoken, 'lang' => App()->language, 'newtest' => 'Y'));
         $asMessage = array(gT('Token mismatch'), gT('The token you provided doesn\'t match the one in your session.'), "<a class='reloadlink newsurvey' href={$sReloadUrl}>" . gT("Click here to start the survey.") . "</a>");
         $this->_createNewUserSessionAndRedirect($surveyid, $redata, __LINE__, $asMessage);
     }
     if ($this->_isSurveyFinished($surveyid) && ($thissurvey['alloweditaftercompletion'] != 'Y' || $thissurvey['tokenanswerspersistence'] != 'Y')) {
         $aReloadUrlParam = array('lang' => App()->language, 'newtest' => 'Y');
         if ($clienttoken) {
             $aReloadUrlParam['token'] = $clienttoken;
         }
         $sReloadUrl = $this->getController()->createUrl("/survey/index/sid/{$surveyid}", $aReloadUrlParam);
         $asMessage = array(gT('Previous session is set to be finished.'), gT('Your browser reports that it was used previously to answer this survey. We are resetting the session so that you can start from the beginning.'), "<a class='reloadlink newsurvey' href={$sReloadUrl}>" . gT("Click here to start the survey.") . "</a>");
         $this->_createNewUserSessionAndRedirect($surveyid, $redata, __LINE__, $asMessage);
     }
     $previewmode = false;
     if (isset($param['action']) && in_array($param['action'], array('previewgroup', 'previewquestion'))) {
         if (!$this->_canUserPreviewSurvey($surveyid)) {
             $asMessage = array(gT('Error'), gT("We are sorry but you don't have permissions to do this."));
             $this->_niceExit($redata, __LINE__, null, $asMessage);
         } else {
             if (intval($param['qid']) && $param['action'] == 'previewquestion') {
                 $previewmode = 'question';
             }
             if (intval($param['gid']) && $param['action'] == 'previewgroup') {
                 $previewmode = 'group';
             }
         }
     }
     Yii::app()->setConfig('previewmode', $previewmode);
     if ($this->_surveyCantBeViewedWithCurrentPreviewAccess($surveyid, $isSurveyActive, $surveyExists)) {
         $bPreviewRight = $this->_userHasPreviewAccessSession($surveyid);
         if ($bPreviewRight === false) {
             $asMessage = array(gT("Error"), gT("We are sorry but you don't have permissions to do this."), sprintf(gT("Please contact %s ( %s ) for further assistance."), $thissurvey['adminname'], $thissurvey['adminemail']));
             $this->_niceExit($redata, __LINE__, null, $asMessage);
         }
     }
     // TODO can this be moved to the top?
     // (Used to be global, used in ExpressionManager, merged into amVars. If not filled in === '')
     // can this be added in the first computation of $redata?
     if (isset($_SESSION['survey_' . $surveyid]['srid'])) {
         $saved_id = $_SESSION['survey_' . $surveyid]['srid'];
     }
     // recompute $redata since $saved_id used to be a global
     $redata = compact(array_keys(get_defined_vars()));
     if ($this->_didSessionTimeOut($surveyid)) {
         // @TODO is this still required ?
         $asMessage = array(gT("Error"), gT("We are sorry but your session has expired."), gT("Either you have been inactive for too long, you have cookies disabled for your browser, or there were problems with your connection."), sprintf(gT("Please contact %s ( %s ) for further assistance."), $thissurvey['adminname'], $thissurvey['adminemail']));
         $this->_niceExit($redata, __LINE__, null, $asMessage);
     }
     // Set the language of the survey, either from POST, GET parameter of session var
     // Keep the old value, because SetSurveyLanguage update $_SESSION
     $sOldLang = isset($_SESSION['survey_' . $surveyid]['s_lang']) ? $_SESSION['survey_' . $surveyid]['s_lang'] : "";
     // Keep the old value, because SetSurveyLanguage update $_SESSION
     if (!empty($param['lang'])) {
         $sDisplayLanguage = $param['lang'];
         // $param take lang from returnGlobal and returnGlobal sanitize langagecode
     } elseif (isset($_SESSION['survey_' . $surveyid]['s_lang'])) {
         $sDisplayLanguage = $_SESSION['survey_' . $surveyid]['s_lang'];
     } elseif (Survey::model()->findByPk($surveyid)) {
         $sDisplayLanguage = Survey::model()->findByPk($surveyid)->language;
     } else {
         $sDisplayLanguage = Yii::app()->getConfig('defaultlang');
     }
     //CHECK FOR REQUIRED INFORMATION (sid)
     if ($surveyid && $surveyExists) {
         LimeExpressionManager::SetSurveyId($surveyid);
         // must be called early - it clears internal cache if a new survey is being used
         SetSurveyLanguage($surveyid, $sDisplayLanguage);
         if ($previewmode) {
             LimeExpressionManager::SetPreviewMode($previewmode);
         }
         if (App()->language != $sOldLang) {
             UpdateGroupList($surveyid, App()->language);
             // to refresh the language strings in the group list session variable
             UpdateFieldArray();
             // to refresh question titles and question text
         }
     } else {
         throw new CHttpException(404, "The survey in which you are trying to participate does not seem to exist. It may have been deleted or the link you were given is outdated or incorrect.");
     }
     // Get token
     if (!isset($token)) {
         $token = $clienttoken;
     }
     //GET BASIC INFORMATION ABOUT THIS SURVEY
     $thissurvey = getSurveyInfo($surveyid, $_SESSION['survey_' . $surveyid]['s_lang']);
     $event = new PluginEvent('beforeSurveyPage');
     $event->set('surveyId', $surveyid);
     App()->getPluginManager()->dispatchEvent($event);
     if (!is_null($event->get('template'))) {
         $thissurvey['templatedir'] = $event->get('template');
     }
     //SEE IF SURVEY USES TOKENS
     if ($surveyExists == 1 && tableExists('{{tokens_' . $thissurvey['sid'] . '}}')) {
         $tokensexist = 1;
     } else {
         $tokensexist = 0;
         unset($_POST['token']);
         unset($param['token']);
         unset($token);
         unset($clienttoken);
     }
     //SET THE TEMPLATE DIRECTORY
     global $oTemplate;
     $thistpl = $oTemplate->viewPath;
     $timeadjust = Yii::app()->getConfig("timeadjust");
     //MAKE SURE SURVEY HASN'T EXPIRED
     if ($thissurvey['expiry'] != '' and dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust) > $thissurvey['expiry'] && $thissurvey['active'] != 'N' && !$previewmode) {
         $redata = compact(array_keys(get_defined_vars()));
         $asMessage = array(gT("Error"), gT("This survey is no longer available."), sprintf(gT("Please contact %s ( %s ) for further assistance."), $thissurvey['adminname'], $thissurvey['adminemail']));
         $this->_niceExit($redata, __LINE__, $thissurvey['templatedir'], $asMessage);
     }
     //MAKE SURE SURVEY IS ALREADY VALID
     if ($thissurvey['startdate'] != '' and dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust) < $thissurvey['startdate'] && $thissurvey['active'] != 'N' && !$previewmode) {
         $redata = compact(array_keys(get_defined_vars()));
         $asMessage = array(gT("Error"), gT("This survey is not yet started."), sprintf(gT("Please contact %s ( %s ) for further assistance."), $thissurvey['adminname'], $thissurvey['adminemail']));
         $this->_niceExit($redata, __LINE__, $thissurvey['templatedir'], $asMessage);
     }
     //CHECK FOR PREVIOUSLY COMPLETED COOKIE
     //If cookies are being used, and this survey has been completed, a cookie called "PHPSID[sid]STATUS" will exist (ie: SID6STATUS) and will have a value of "COMPLETE"
     $sCookieName = "LS_" . $surveyid . "_STATUS";
     if (isset($_COOKIE[$sCookieName]) && $_COOKIE[$sCookieName] == "COMPLETE" && $thissurvey['usecookie'] == "Y" && $tokensexist != 1 && (!isset($param['newtest']) || $param['newtest'] != "Y")) {
         $redata = compact(array_keys(get_defined_vars()));
         $asMessage = array(gT("Error"), gT("You have already completed this survey."), sprintf(gT("Please contact %s ( %s ) for further assistance."), $thissurvey['adminname'], $thissurvey['adminemail']));
         $this->_niceExit($redata, __LINE__, $thissurvey['templatedir'], $asMessage);
     }
     //LOAD SAVED SURVEY
     if (Yii::app()->request->getParam('loadall') == "reload") {
         $errormsg = "";
         $sLoadName = Yii::app()->request->getParam('loadname');
         $sLoadPass = Yii::app()->request->getParam('loadpass');
         if (isset($sLoadName) && !$sLoadName) {
             $errormsg .= gT("You did not provide a name") . "<br />\n";
         }
         if (isset($sLoadPass) && !$sLoadPass) {
             $errormsg .= gT("You did not provide a password") . "<br />\n";
         }
         // if security question answer is incorrect
         // Not called if scid is set in GET params (when using email save/reload reminder URL)
         if (function_exists("ImageCreate") && isCaptchaEnabled('saveandloadscreen', $thissurvey['usecaptcha']) && is_null(Yii::app()->request->getQuery('scid'))) {
             $sLoadSecurity = Yii::app()->request->getPost('loadsecurity');
             if (empty($sLoadSecurity)) {
                 $errormsg .= gT("You did not answer to the security question.") . "<br />\n";
             } elseif (!isset($_SESSION['survey_' . $surveyid]['secanswer']) || $sLoadSecurity != $_SESSION['survey_' . $surveyid]['secanswer']) {
                 $errormsg .= gT("The answer to the security question is incorrect.") . "<br />\n";
             }
         }
         if ($errormsg == "") {
             LimeExpressionManager::SetDirtyFlag();
             buildsurveysession($surveyid);
             if (loadanswers()) {
                 Yii::app()->setConfig('move', 'reload');
                 $move = "reload";
                 // veyRunTimeHelper use $move in $arg
             } else {
                 $errormsg .= gT("There is no matching saved survey");
             }
         }
         if ($errormsg) {
             Yii::app()->setConfig('move', "loadall");
             // Show loading form
         }
     }
     //Allow loading of saved survey
     if (Yii::app()->getConfig('move') == "loadall") {
         $redata = compact(array_keys(get_defined_vars()));
         Yii::import("application.libraries.Load_answers");
         $tmp = new Load_answers();
         $tmp->run($redata);
     }
     //Check if TOKEN is used for EVERY PAGE
     //This function fixes a bug where users able to submit two surveys/votes
     //by checking that the token has not been used at each page displayed.
     // bypass only this check at first page (Step=0) because
     // this check is done in buildsurveysession and error message
     // could be more interresting there (takes into accound captcha if used)
     if ($tokensexist == 1 && isset($token) && $token != "" && isset($_SESSION['survey_' . $surveyid]['step']) && $_SESSION['survey_' . $surveyid]['step'] > 0 && tableExists("tokens_{$surveyid}}}")) {
         // check also if it is allowed to change survey after completion
         if ($thissurvey['alloweditaftercompletion'] == 'Y') {
             $tokenInstance = Token::model($surveyid)->findByAttributes(array('token' => $token));
         } else {
             $tokenInstance = Token::model($surveyid)->usable()->incomplete()->findByAttributes(array('token' => $token));
         }
         if (!isset($tokenInstance) && !$previewmode) {
             //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT
             $asMessage = array(null, gT("This is a controlled survey. You need a valid token to participate."), sprintf(gT("For further information please contact %s"), $thissurvey['adminname'] . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)"));
             $this->_niceExit($redata, __LINE__, $thistpl, $asMessage, true);
         }
     }
     if ($tokensexist == 1 && isset($token) && $token != "" && tableExists("{{tokens_" . $surveyid . "}}") && !$previewmode) {
         // check also if it is allowed to change survey after completion
         if ($thissurvey['alloweditaftercompletion'] == 'Y') {
             $tokenInstance = Token::model($surveyid)->editable()->findByAttributes(array('token' => $token));
         } else {
             $tokenInstance = Token::model($surveyid)->usable()->incomplete()->findByAttributes(array('token' => $token));
         }
         if (!isset($tokenInstance)) {
             $oToken = Token::model($surveyid)->findByAttributes(array('token' => $token));
             if ($oToken) {
                 $now = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", Yii::app()->getConfig("timeadjust"));
                 if ($oToken->completed != 'N' && !empty($oToken->completed)) {
                     $sError = gT("This invitation has already been used.");
                 } elseif (strtotime($now) < strtotime($oToken->validfrom)) {
                     $sError = gT("This invitation is not valid yet.");
                 } elseif (strtotime($now) > strtotime($oToken->validuntil)) {
                     $sError = gT("This invitation is not valid anymore.");
                 } else {
                     $sError = gT("This is a controlled survey. You need a valid token to participate.");
                 }
             } else {
                 $sError = gT("This is a controlled survey. You need a valid token to participate.");
             }
             $asMessage = array($sError, gT("We are sorry but you are not allowed to enter this survey."), sprintf(gT("For further information please contact %s"), $thissurvey['adminname'] . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)"));
             $this->_niceExit($redata, __LINE__, $thistpl, $asMessage, true);
         }
     }
     //Clear session and remove the incomplete response if requested.
     if (isset($move) && $move == "clearall") {
         // delete the response but only if not already completed
         $s_lang = $_SESSION['survey_' . $surveyid]['s_lang'];
         if (isset($_SESSION['survey_' . $surveyid]['srid']) && !SurveyDynamic::model($surveyid)->isCompleted($_SESSION['survey_' . $surveyid]['srid'])) {
             // delete the response but only if not already completed
             $result = dbExecuteAssoc('DELETE FROM {{survey_' . $surveyid . '}} WHERE id=' . $_SESSION['survey_' . $surveyid]['srid'] . " AND submitdate IS NULL");
             if ($result->count() > 0) {
                 // Using count() here *should* be okay for MSSQL because it is a delete statement
                 // find out if there are any fuqt questions - checked
                 $fieldmap = createFieldMap($surveyid, 'short', false, false, $s_lang);
                 foreach ($fieldmap as $field) {
                     if ($field['type'] == "|" && !strpos($field['fieldname'], "_filecount")) {
                         if (!isset($qid)) {
                             $qid = array();
                         }
                         $qid[] = $field['fieldname'];
                     }
                 }
                 // if yes, extract the response json to those questions
                 if (isset($qid)) {
                     $query = "SELECT * FROM {{survey_" . $surveyid . "}} WHERE id=" . $_SESSION['survey_' . $surveyid]['srid'];
                     $result = dbExecuteAssoc($query);
                     foreach ($result->readAll() as $row) {
                         foreach ($qid as $question) {
                             $json = $row[$question];
                             if ($json == "" || $json == NULL) {
                                 continue;
                             }
                             // decode them
                             $phparray = json_decode($json);
                             foreach ($phparray as $metadata) {
                                 $target = Yii::app()->getConfig("uploaddir") . "/surveys/" . $surveyid . "/files/";
                                 // delete those files
                                 unlink($target . $metadata->filename);
                             }
                         }
                     }
                 }
                 // done deleting uploaded files
             }
             // also delete a record from saved_control when there is one
             dbExecuteAssoc('DELETE FROM {{saved_control}} WHERE srid=' . $_SESSION['survey_' . $surveyid]['srid'] . ' AND sid=' . $surveyid);
         }
         killSurveySession($surveyid);
         sendCacheHeaders();
         doHeader();
         $redata = compact(array_keys(get_defined_vars()));
         $this->_printTemplateContent($thistpl . '/startpage.pstpl', $redata, __LINE__);
         echo "\n\n<!-- JAVASCRIPT FOR CONDITIONAL QUESTIONS -->\n" . "\t<script type='text/javascript'>\n" . "\t<!--\n" . "function checkconditions(value, name, type, evt_type)\n" . "\t{\n" . "\t}\n" . "\t//-->\n" . "\t</script>\n\n";
         //Present the clear all page using clearall.pstpl template
         $this->_printTemplateContent($thistpl . '/clearall.pstpl', $redata, __LINE__);
         $this->_printTemplateContent($thistpl . '/endpage.pstpl', $redata, __LINE__);
         doFooter();
         exit;
     }
     //Check to see if a refering URL has been captured.
     if (!isset($_SESSION['survey_' . $surveyid]['refurl'])) {
         $_SESSION['survey_' . $surveyid]['refurl'] = GetReferringUrl();
         // do not overwrite refurl
     }
     // Let's do this only if
     //  - a saved answer record hasn't been loaded through the saved feature
     //  - the survey is not anonymous
     //  - the survey is active
     //  - a token information has been provided
     //  - the survey is setup to allow token-response-persistence
     if (!isset($_SESSION['survey_' . $surveyid]['srid']) && $thissurvey['anonymized'] == "N" && $thissurvey['active'] == "Y" && isset($token) && $token != '') {
         // load previous answers if any (dataentry with nosubmit)
         $oResponses = Response::model($surveyid)->findAllByAttributes(array('token' => $token), array('order' => 'id DESC'));
         if (!empty($oResponses)) {
             /**
              * We fire the response selection event when at least 1 response was found.
              * If there is just 1 response the plugin still has to option to choose
              * NOT to use it.
              */
             $event = new PluginEvent('beforeLoadResponse');
             $event->set('responses', $oResponses);
             $event->set('surveyId', $surveyid);
             App()->pluginManager->dispatchEvent($event);
             $oResponse = $event->get('response');
             // If $oResponse is false we act as if no response was found.
             // This allows a plugin to deny continuing a response.
             if ($oResponse !== false) {
                 // If plugin does not set a response we use the first one found, (this replicates pre-plugin behavior)
                 if (!isset($oResponse) && (!isset($oResponses[0]->submitdate) || $thissurvey['alloweditaftercompletion'] == 'Y') && $thissurvey['tokenanswerspersistence'] == 'Y') {
                     $oResponse = $oResponses[0];
                 }
                 if (isset($oResponse)) {
                     $_SESSION['survey_' . $surveyid]['srid'] = $oResponse->id;
                     if (!empty($oResponse->lastpage)) {
                         $_SESSION['survey_' . $surveyid]['LEMtokenResume'] = true;
                         // If the response was completed and user is allowed to edit after completion start at the beginning and not at the last page - just makes more sense
                         if (!($oResponse->submitdate && $thissurvey['alloweditaftercompletion'] == 'Y')) {
                             $_SESSION['survey_' . $surveyid]['step'] = $oResponse->lastpage;
                         }
                     }
                     buildsurveysession($surveyid);
                     if (!empty($oResponse->submitdate)) {
                         $_SESSION['survey_' . $surveyid]['maxstep'] = $_SESSION['survey_' . $surveyid]['totalsteps'];
                     }
                     loadanswers();
                 }
             }
         }
     }
     // Preview action : Preview right already tested before
     if ($previewmode) {
         // Unset all SESSION: be sure to have the last version
         unset($_SESSION['fieldmap-' . $surveyid . App()->language]);
         // Needed by createFieldMap: else fieldmap can be outdated
         unset($_SESSION['survey_' . $surveyid]);
         if ($param['action'] == 'previewgroup') {
             $thissurvey['format'] = 'G';
         } elseif ($param['action'] == 'previewquestion') {
             $thissurvey['format'] = 'S';
         }
         buildsurveysession($surveyid, true);
     }
     sendCacheHeaders();
     //Send local variables to the appropriate survey type
     unset($redata);
     $redata = compact(array_keys(get_defined_vars()));
     Yii::import('application.helpers.SurveyRuntimeHelper');
     $tmp = new SurveyRuntimeHelper();
     $tmp->run($surveyid, $redata);
     if (isset($_POST['saveall']) || isset($flashmessage)) {
         echo "<script type='text/javascript'> \$(document).ready( function() { alert('" . gT("Your responses were successfully saved.", "js") . "');}) </script>";
     }
 }
 /**
  * RPC Routine to send reminder for participants in a survey
  * Returns array of results of sending
  *
  * @access public
  * @param string $sSessionKey Auth credentials
  * @param int $iSurveyID ID of the survey that participants belong
  * @param int $iMinDaysBetween Optional parameter days from last reminder
  * @param int $iMaxReminders Optional parameter Maximum reminders count
  * @return array Result of the action
  */
 public function remind_participants($sSessionKey, $iSurveyID, $iMinDaysBetween = null, $iMaxReminders = null)
 {
     Yii::app()->loadHelper('admin/token');
     if (!$this->_checkSessionKey($sSessionKey)) {
         return array('status' => 'Invalid session key');
     }
     $oSurvey = Survey::model()->findByPk($iSurveyID);
     if (!isset($oSurvey)) {
         return array('status' => 'Error: Invalid survey ID');
     }
     if (Permission::model()->hasSurveyPermission($iSurveyID, 'tokens', 'update')) {
         $timeadjust = Yii::app()->getConfig("timeadjust");
         if (!tableExists("{{tokens_{$iSurveyID}}}")) {
             return array('status' => 'Error: No token table');
         }
         if (getEmailFormat($iSurveyID) == 'html') {
             $bHtml = true;
         } else {
             $bHtml = false;
         }
         $SQLemailstatuscondition = "emailstatus = 'OK'";
         $SQLremindercountcondition = '';
         $SQLreminderdelaycondition = '';
         $iMaxEmails = (int) Yii::app()->getConfig("maxemails");
         if (!is_null($iMinDaysBetween)) {
             $compareddate = dateShift(date("Y-m-d H:i:s", time() - 86400 * $iMinDaysBetween), "Y-m-d H:i", $timeadjust);
             $SQLreminderdelaycondition = " ((remindersent = 'N' AND sent < '" . $compareddate . "')  OR  (remindersent < '" . $compareddate . "'))";
         }
         if (!is_null($iMaxReminders)) {
             $SQLremindercountcondition = "remindercount < " . $iMaxReminders;
         }
         $oTokens = TokenDynamic::model($iSurveyID);
         $aAllTokens = $oTokens->findUninvitedIDs(false, 0, false, $SQLemailstatuscondition, $SQLremindercountcondition, $SQLreminderdelaycondition);
         $iAllTokensCount = count($aAllTokens);
         unset($aAllTokens);
         // save some memory before the next query
         $aResultTokens = $oTokens->findUninvited(false, $iMaxEmails, false, $SQLemailstatuscondition, $SQLremindercountcondition, $SQLreminderdelaycondition);
         if (empty($aResultTokens)) {
             return array('status' => 'Error: No candidate tokens');
         }
         $aResult = emailTokens($iSurveyID, $aResultTokens, 'remind');
         $iLeft = $iAllTokensCount - count($aResultTokens);
         $aResult['status'] = $iLeft . " left to send";
         return $aResult;
     } else {
         return array('status' => 'No permission');
     }
 }
 /**
  * Returns this model's scopes
  *
  * @access public
  * @return array
  */
 public function scopes()
 {
     return array('active' => array('condition' => "active = 'Y'"), 'open' => array('condition' => '(startdate <= :now1 OR startdate IS NULL) AND (expires >= :now2 OR expires IS NULL)', 'params' => array(':now1' => dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", Yii::app()->getConfig("timeadjust")), ':now2' => dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", Yii::app()->getConfig("timeadjust")))), 'public' => array('condition' => "listpublic = 'Y'"), 'registration' => array('condition' => "allowregister = 'Y' AND startdate > :now3 AND (expires < :now4 OR expires IS NULL)", 'params' => array(':now3' => dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", Yii::app()->getConfig("timeadjust")), ':now4' => dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", Yii::app()->getConfig("timeadjust")))));
 }
Example #13
0
 /**
  * Create a backup of the DataBase
  * @return array result of backup
  */
 private function _createDbBackup()
 {
     Yii::app()->loadHelper("admin/backupdb");
     $backupDb = new stdClass();
     $basefilename = dateShift(date("Y-m-d H:i:s"), "Y-m-d", Yii::app()->getConfig('timeadjust')) . '_' . md5(uniqid(rand(), true));
     $sfilename = $this->tempdir . DIRECTORY_SEPARATOR . "backup_db_" . randomChars(20) . "_" . dateShift(date("Y-m-d H:i:s"), "Y-m-d", Yii::app()->getConfig('timeadjust')) . ".sql";
     $dfilename = $this->tempdir . DIRECTORY_SEPARATOR . "LimeSurvey_database_backup_" . $basefilename . ".zip";
     outputDatabase('', false, $sfilename);
     if (is_file($sfilename) && filesize($sfilename)) {
         $archive = new PclZip($dfilename);
         $v_list = $archive->add(array($sfilename), PCLZIP_OPT_REMOVE_PATH, $this->tempdir, PCLZIP_OPT_ADD_TEMP_FILE_ON);
         unlink($sfilename);
         if ($v_list == 0) {
             $backupDb->result = FALSE;
             $backupDb->message = 'db_backup_zip_failed';
         } else {
             $backupDb->result = TRUE;
             $backupDb->message = htmlspecialchars($dfilename);
         }
     } else {
         $backupDb->result = FALSE;
         $backupDb->message = htmlspecialchars(db_backup_failed);
     }
     return $backupDb;
 }
Example #14
0
 protected function menuMain()
 {
     $title = CHtml::tag('strong', array(), gT('Administration'));
     if (Yii::app()->session['loginID']) {
         $title .= ' -- ' . gT("Logged in as:");
         $text = ' ' . Yii::app()->session['user'] . ' ' . CHtml::image(Yii::app()->getConfig('adminimageurl') . 'profile_edit.png', gT("Edit your personal preferences"));
         $title .= CHtml::tag('strong', array(), CHtml::link($text, array('admin/user', 'sa' => 'personalsettings')));
     }
     $menu['title'] = CHtml::tag('div', array('class' => 'menubar-title-left'), $title);
     $menu['role'] = 'main';
     $menu['imageUrl'] = App()->getConfig('adminimageurl');
     $menu['items']['left'][] = array('href' => array('admin/survey'), 'alt' => gT('Default administration page'), 'image' => 'home.png');
     $menu['items']['left'][] = 'separator';
     if (Permission::model()->hasGlobalPermission('users', 'read')) {
         $menu['items']['left'][] = array('href' => array('admin/user'), 'alt' => gT('Manage survey administrators'), 'image' => 'security.png');
     }
     $menu['items']['left'][] = $this->userGroups();
     $menu['items']['left'][] = $this->globalSettings();
     $menu['items']['left'][] = 'separator';
     $menu['items']['left'][] = $this->checkIntegrity();
     $menu['items']['left'][] = $this->dumpDatabase();
     $menu['items']['left'][] = 'separator';
     $menu['items']['left'][] = $this->editLabels();
     $menu['items']['left'][] = 'separator';
     $menu['items']['left'][] = $this->editTemplates();
     $menu['items']['left'][] = 'separator';
     $menu['items']['left'][] = $this->participantDatabase();
     $menu['items']['left'][] = $this->pluginManager();
     $surveys = getSurveyList(true);
     $tmpList = array();
     $timeadjust = getGlobalSetting('timeadjust');
     foreach ($surveys as $survey) {
         if ($survey['active'] != 'Y') {
             $group = gT("Inactive");
             $list = 'inactive';
         } elseif ($survey['expires'] != '' && $survey['expires'] < dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust)) {
             $group = gT("Expired");
             $list = 'expired';
         } else {
             $group = gT("Active");
             $list = 'active';
         }
         $tmpList[$list][] = array('id' => $survey['sid'], 'title' => $survey['surveyls_title'], 'group' => $group);
     }
     $surveyList = array();
     if (array_key_exists('active', $tmpList)) {
         $surveyList = array_merge($surveyList, $tmpList['active']);
     }
     if (array_key_exists('expired', $tmpList)) {
         $surveyList = array_merge($surveyList, $tmpList['expired']);
     }
     if (array_key_exists('inactive', $tmpList)) {
         $surveyList = array_merge($surveyList, $tmpList['inactive']);
     }
     $menu['items']['right'][] = array('title' => gT('Surveys:'), 'type' => 'select', 'name' => 'surveyid', 'route' => 'admin/survey/sa/view', 'param' => 'surveyid', 'empty' => gT('No surveys available.'), 'values' => $surveyList, 'value' => $this->surveyId);
     $menu['items']['right'][] = array('href' => array('admin/survey', 'sa' => 'index'), 'alt' => gT('Detailed list of surveys'), 'image' => 'surveylist.png');
     $menu['items']['right'][] = $this->createSurvey();
     $menu['items']['right'][] = 'separator';
     $menu['items']['right'][] = array('href' => array('admin/authentication', 'sa' => 'logout'), 'alt' => gT('Logout'), 'image' => 'logout.png');
     $menu['items']['right'][] = array('href' => "http://docs.limesurvey.org", 'alt' => gT('LimeSurvey online manual'), 'image' => 'showhelp.png');
     $event = new PluginEvent('afterAdminMenuLoad', $this);
     $event->set('menu', $menu);
     $result = App()->getPluginManager()->dispatchEvent($event);
     $menu = $result->get('menu');
     return $menu;
 }
    							{
    							document.getElementById("saveoptions").style.display="none";
    							 document.getElementById("closerecord").disabled=false;
    							}
    						}
    				  //-->
    				  </script>
                <tr>
                <td colspan='3' align='center'>
                <table><tr><td align='left'>
                <input type='checkbox' class='checkboxbtn' name='closerecord' id='closerecord' checked='checked'/><label for='closerecord'><?php 
    eT("Finalize response submission");
    ?>
</label></td></tr>
                <input type='hidden' name='closedate' value='<?php 
    echo dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $yii->getConfig('timeadjust'));
    ?>
' />

                <?php 
    if ($thissurvey['allowsave'] == "Y") {
        ?>

                    <tr><td align='left'><input type='checkbox' class='checkboxbtn' name='save' id='save' onclick='saveshow(this.id)' /><label for='save'><?php 
        eT("Save for further completion by survey user");
        ?>
</label>
                    </td></tr></table>
                    <div name='saveoptions' id='saveoptions' style='display: none'>
                    <table align='center' class='outlinetable'>
    					  <tr><td align='right'><?php 
 /**
  * Shows admin menu for surveys
  * @param int Survey id
  */
 function _surveybar($aData)
 {
     if (isset($aData['surveybar'])) {
         $iSurveyID = $aData['surveyid'];
         $oSurvey = $aData['oSurvey'];
         $gid = isset($aData['gid']) ? $aData['gid'] : null;
         $surveyinfo = isset($aData['surveyinfo']) ? $aData['surveyinfo'] : $oSurvey->surveyinfo;
         $baselang = $surveyinfo['language'];
         $activated = $surveyinfo['active'] == 'Y';
         App()->getClientScript()->registerPackage('jquery-cookie');
         App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('adminscripts') . 'surveytoolbar.js');
         //Parse data to send to view
         $aData['surveyinfo'] = $surveyinfo;
         // ACTIVATE SURVEY BUTTON
         $aData['activated'] = $activated;
         $condition = array('sid' => $iSurveyID, 'parent_qid' => 0, 'language' => $baselang);
         //$sumquery3 =  "SELECT * FROM ".db_table_name('questions')." WHERE sid={$iSurveyID} AND parent_qid=0 AND language='".$baselang."'"; //Getting a count of questions for this survey
         $sumresult3 = Question::model()->findAllByAttributes($condition);
         //Checked
         $sumcount3 = count($sumresult3);
         $aData['canactivate'] = $sumcount3 > 0 && Permission::model()->hasSurveyPermission($iSurveyID, 'surveyactivation', 'update');
         $aData['candeactivate'] = Permission::model()->hasSurveyPermission($iSurveyID, 'surveyactivation', 'update');
         $aData['expired'] = $surveyinfo['expires'] != '' && $surveyinfo['expires'] < dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig('timeadjust'));
         $aData['notstarted'] = $surveyinfo['startdate'] != '' && $surveyinfo['startdate'] > dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig('timeadjust'));
         // Start of suckerfish menu
         // TEST BUTTON
         if (!$activated) {
             $aData['icontext'] = gT("Test this survey");
         } else {
             $aData['icontext'] = gT("Execute this survey");
         }
         $aData['baselang'] = $oSurvey->language;
         $aData['additionallanguages'] = $oSurvey->getAdditionalLanguages();
         $aData['languagelist'] = $oSurvey->getAllLanguages();
         $aData['onelanguage'] = count($aData['languagelist']) == 1;
         $aData['hasadditionallanguages'] = count($aData['additionallanguages']) > 0;
         // EDIT SURVEY TEXT ELEMENTS BUTTON
         $aData['surveylocale'] = Permission::model()->hasSurveyPermission($iSurveyID, 'surveylocale', 'read');
         // EDIT SURVEY SETTINGS BUTTON
         $aData['surveysettings'] = Permission::model()->hasSurveyPermission($iSurveyID, 'surveysettings', 'read');
         // Survey permission item
         $aData['surveysecurity'] = Permission::model()->hasSurveyPermission($iSurveyID, 'surveysecurity', 'read');
         // CHANGE QUESTION GROUP ORDER BUTTON
         $aData['surveycontent'] = Permission::model()->hasSurveyPermission($iSurveyID, 'surveycontent', 'read');
         $aData['groupsum'] = getGroupSum($iSurveyID, $surveyinfo['language']) > 1;
         // SET SURVEY QUOTAS BUTTON
         $aData['quotas'] = Permission::model()->hasSurveyPermission($iSurveyID, 'quotas', 'read');
         // Assessment menu item
         $aData['assessments'] = Permission::model()->hasSurveyPermission($iSurveyID, 'assessments', 'read');
         // EDIT SURVEY TEXT ELEMENTS BUTTON
         // End if survey properties
         // Tools menu item
         // Delete survey item
         $aData['surveydelete'] = Permission::model()->hasSurveyPermission($iSurveyID, 'survey', 'delete');
         // Translate survey item
         $aData['surveytranslate'] = Permission::model()->hasSurveyPermission($iSurveyID, 'translations', 'read');
         // RESET SURVEY LOGIC BUTTON
         //$sumquery6 = "SELECT count(*) FROM ".db_table_name('conditions')." as c, ".db_table_name('questions')."
         // as q WHERE c.qid = q.qid AND q.sid=$iSurveyID"; //Getting a count of conditions for this survey
         // TMSW Condition->Relevance:  How is conditionscount used?  Should Relevance do the same?
         $iConditionCount = Condition::model()->with(array('questions' => array('condition' => 'sid =' . $iSurveyID)))->count();
         $aData['surveycontent'] = Permission::model()->hasSurveyPermission($iSurveyID, 'surveycontent', 'update');
         $aData['conditionscount'] = $iConditionCount > 0;
         // Eport menu item
         $aData['surveyexport'] = Permission::model()->hasSurveyPermission($iSurveyID, 'surveycontent', 'export');
         // PRINTABLE VERSION OF SURVEY BUTTON
         // SHOW PRINTABLE AND SCANNABLE VERSION OF SURVEY BUTTON
         //browse responses menu item
         $aData['respstatsread'] = Permission::model()->hasSurveyPermission($iSurveyID, 'responses', 'read') || Permission::model()->hasSurveyPermission($iSurveyID, 'statistics', 'read') || Permission::model()->hasSurveyPermission($iSurveyID, 'responses', 'export');
         // Data entry screen menu item
         $aData['responsescreate'] = Permission::model()->hasSurveyPermission($iSurveyID, 'responses', 'create');
         $aData['responsesread'] = Permission::model()->hasSurveyPermission($iSurveyID, 'responses', 'read');
         // TOKEN MANAGEMENT BUTTON
         $bTokenExists = tableExists('{{tokens_' . $iSurveyID . '}}');
         if (!$bTokenExists) {
             $aData['tokenmanagement'] = Permission::model()->hasSurveyPermission($iSurveyID, 'surveysettings', 'update') || Permission::model()->hasSurveyPermission($iSurveyID, 'tokens', 'create');
         } else {
             $aData['tokenmanagement'] = Permission::model()->hasSurveyPermission($iSurveyID, 'surveysettings', 'update') || Permission::model()->hasSurveyPermission($iSurveyID, 'tokens', 'create') || Permission::model()->hasSurveyPermission($iSurveyID, 'tokens', 'read') || Permission::model()->hasSurveyPermission($iSurveyID, 'tokens', 'export') || Permission::model()->hasSurveyPermission($iSurveyID, 'tokens', 'import');
             // and export / import ?
         }
         $aData['gid'] = $gid;
         // = $this->input->post('gid');
         if (Permission::model()->hasSurveyPermission($iSurveyID, 'surveycontent', 'read')) {
             $aData['permission'] = true;
         } else {
             $aData['gid'] = $gid = null;
             $qid = null;
             $aData['permission'] = false;
         }
         if (getGroupListLang($gid, $baselang, $iSurveyID)) {
             $aData['groups'] = getGroupListLang($gid, $baselang, $iSurveyID);
         } else {
             $aData['groups'] = "<option>" . gT("None") . "</option>";
         }
         $aData['GidPrev'] = $GidPrev = getGidPrevious($iSurveyID, $gid);
         $aData['GidNext'] = $GidNext = getGidNext($iSurveyID, $gid);
         $aData['iIconSize'] = Yii::app()->getConfig('adminthemeiconsize');
         if ($aData['gid'] == null) {
             $this->getController()->renderPartial("/admin/survey/surveybar_view", $aData);
         }
     }
 }
Example #17
0
 function savedcontrol()
 {
     //This data will be saved to the "saved_control" table with one row per response.
     // - a unique "saved_id" value (autoincremented)
     // - the "sid" for this survey
     // - the "srid" for the survey_x row id
     // - "saved_thisstep" which is the step the user is up to in this survey
     // - "saved_ip" which is the ip address of the submitter
     // - "saved_date" which is the date ofthe saved response
     // - an "identifier" which is like a username
     // - a "password"
     // - "fieldname" which is the fieldname of the saved response
     // - "value" which is the value of the response
     //We start by generating the first 5 values which are consistent for all rows.
     global $surveyid, $thissurvey, $errormsg, $publicurl, $sitename, $clang, $clienttoken, $thisstep;
     $timeadjust = getGlobalSetting('timeadjust');
     //Check that the required fields have been completed.
     $errormsg = '';
     if (empty($_POST['savename'])) {
         $errormsg .= $clang->gT("You must supply a name for this saved session.") . "<br />\n";
     }
     if (empty($_POST['savepass'])) {
         $errormsg .= $clang->gT("You must supply a password for this saved session.") . "<br />\n";
     }
     if (empty($_POST['savepass']) || empty($_POST['savepass2']) || $_POST['savepass'] != $_POST['savepass2']) {
         $errormsg .= $clang->gT("Your passwords do not match.") . "<br />\n";
     }
     // if security question asnwer is incorrect
     if (function_exists("ImageCreate") && isCaptchaEnabled('saveandloadscreen', $thissurvey['usecaptcha'])) {
         if (empty($_POST['loadsecurity']) || !isset($_SESSION['survey_' . $surveyid]['secanswer']) || $_POST['loadsecurity'] != $_SESSION['survey_' . $surveyid]['secanswer']) {
             $errormsg .= $clang->gT("The answer to the security question is incorrect.") . "<br />\n";
         }
     }
     if (!empty($errormsg)) {
         return;
     }
     $duplicate = SavedControl::model()->findByAttributes(array('sid' => $surveyid, 'identifier' => $_POST['savename']));
     if (!empty($duplicate) && $duplicate->count() > 0) {
         $errormsg .= $clang->gT("This name has already been used for this survey. You must use a unique save name.") . "<br />\n";
         return;
     } else {
         //INSERT BLANK RECORD INTO "survey_x" if one doesn't already exist
         if (!isset($_SESSION['survey_' . $surveyid]['srid'])) {
             $today = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust);
             $sdata = array("datestamp" => $today, "ipaddr" => getIPAddress(), "startlanguage" => $_SESSION['survey_' . $surveyid]['s_lang'], "refurl" => getenv("HTTP_REFERER"));
             if (SurveyDynamic::model($thissurvey['sid'])->insert($sdata)) {
                 $srid = getLastInsertID('{{survey_' . $surveyid . '}}');
                 $_SESSION['survey_' . $surveyid]['srid'] = $srid;
             } else {
                 safeDie("Unable to insert record into survey table.<br /><br />");
             }
         }
         //CREATE ENTRY INTO "saved_control"
         $today = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust);
         $saved_control = new SavedControl();
         $saved_control->sid = $surveyid;
         $saved_control->srid = $_SESSION['survey_' . $surveyid]['srid'];
         $saved_control->identifier = $_POST['savename'];
         // Binding does escape, so no quoting/escaping necessary
         $saved_control->access_code = md5($_POST['savepass']);
         $saved_control->email = $_POST['saveemail'];
         $saved_control->ip = getIPAddress();
         $saved_control->saved_thisstep = $thisstep;
         $saved_control->status = 'S';
         $saved_control->saved_date = $today;
         $saved_control->refurl = getenv('HTTP_REFERER');
         if ($saved_control->save()) {
             $scid = getLastInsertID('{{saved_control}}');
             $_SESSION['survey_' . $surveyid]['scid'] = $scid;
         } else {
             safeDie("Unable to insert record into saved_control table.<br /><br />");
         }
         $_SESSION['survey_' . $surveyid]['holdname'] = $_POST['savename'];
         //Session variable used to load answers every page. Unsafe - so it has to be taken care of on output
         $_SESSION['survey_' . $surveyid]['holdpass'] = $_POST['savepass'];
         //Session variable used to load answers every page. Unsafe - so it has to be taken care of on output
         //Email if needed
         if (isset($_POST['saveemail']) && validateEmailAddress($_POST['saveemail'])) {
             $subject = $clang->gT("Saved Survey Details") . " - " . $thissurvey['name'];
             $message = $clang->gT("Thank you for saving your survey in progress.  The following details can be used to return to this survey and continue where you left off.  Please keep this e-mail for your reference - we cannot retrieve the password for you.");
             $message .= "\n\n" . $thissurvey['name'] . "\n\n";
             $message .= $clang->gT("Name") . ": " . $_POST['savename'] . "\n";
             $message .= $clang->gT("Password") . ": " . $_POST['savepass'] . "\n\n";
             $message .= $clang->gT("Reload your survey by clicking on the following link (or pasting it into your browser):") . "\n";
             $message .= Yii::app()->getController()->createAbsoluteUrl("/survey/index/sid/{$surveyid}/loadall/reload/scid/{$scid}/loadname/" . rawurlencode($_POST['savename']) . "/loadpass/" . rawurlencode($_POST['savepass']) . "/lang/" . rawurlencode($clang->langcode));
             if ($clienttoken) {
                 $message .= "/token/" . rawurlencode($clienttoken);
             }
             $from = "{$thissurvey['adminname']} <{$thissurvey['adminemail']}>";
             if (SendEmailMessage($message, $subject, $_POST['saveemail'], $from, $sitename, false, getBounceEmail($surveyid))) {
                 $emailsent = "Y";
             } else {
                 $errormsg .= $clang->gT('Error: Email failed, this may indicate a PHP Mail Setup problem on the server. Your survey details have still been saved, however you will not get an email with the details. You should note the "name" and "password" you just used for future reference.');
                 if (trim($thissurvey['adminemail']) == '') {
                     $errormsg .= $clang->gT('(Reason: Admin email address empty)');
                 }
             }
         }
         return $clang->gT('Your survey was successfully saved.');
     }
 }
Example #18
0
/**
* getSurveyList() Queries the database (survey table) for a list of existing surveys
*
* @param boolean $returnarray if set to true an array instead of an HTML option list is given back
* @return string This string is returned containing <option></option> formatted list of existing surveys
*
*/
function getSurveyList($returnarray = false, $returnwithouturl = false, $surveyid = false)
{
    $cached = null;
    $timeadjust = getGlobalSetting('timeadjust');
    $clang = new Limesurvey_lang(Yii::app()->session['adminlang']);
    if (is_null($cached)) {
        if (!hasGlobalPermission('USER_RIGHT_SUPERADMIN')) {
            $surveyidresult = Survey::model()->permission(Yii::app()->user->getId())->with(array('languagesettings' => array('condition' => 'surveyls_language=language')))->findAll();
        } else {
            $surveyidresult = Survey::model()->with(array('languagesettings' => array('condition' => 'surveyls_language=language')))->findAll();
        }
        $surveynames = array();
        foreach ($surveyidresult as $result) {
            $surveynames[] = array_merge($result->attributes, $result->languagesettings[0]->attributes);
        }
        $cached = $surveynames;
    } else {
        $surveynames = $cached;
    }
    $surveyselecter = "";
    if ($returnarray === true) {
        return $surveynames;
    }
    $activesurveys = '';
    $inactivesurveys = '';
    $expiredsurveys = '';
    if ($surveynames) {
        foreach ($surveynames as $sv) {
            $surveylstitle = flattenText($sv['surveyls_title']);
            if (strlen($surveylstitle) > 45) {
                $surveylstitle = htmlspecialchars(mb_strcut(html_entity_decode($surveylstitle, ENT_QUOTES, 'UTF-8'), 0, 45, 'UTF-8')) . "...";
            }
            if ($sv['active'] != 'Y') {
                $inactivesurveys .= "<option ";
                if (Yii::app()->user->getId() == $sv['owner_id']) {
                    $inactivesurveys .= " style=\"font-weight: bold;\"";
                }
                if ($sv['sid'] == $surveyid) {
                    $inactivesurveys .= " selected='selected'";
                    $svexist = 1;
                }
                if ($returnwithouturl === false) {
                    $inactivesurveys .= " value='" . Yii::app()->getController()->createUrl("/admin/survey/view/surveyid/" . $sv['sid']) . "'>{$surveylstitle}</option>\n";
                } else {
                    $inactivesurveys .= " value='{$sv['sid']}'>{$surveylstitle}</option>\n";
                }
            } elseif ($sv['expires'] != '' && $sv['expires'] < dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust)) {
                $expiredsurveys .= "<option ";
                if (Yii::app()->user->getId() == $sv['owner_id']) {
                    $expiredsurveys .= " style=\"font-weight: bold;\"";
                }
                if ($sv['sid'] == $surveyid) {
                    $expiredsurveys .= " selected='selected'";
                    $svexist = 1;
                }
                if ($returnwithouturl === false) {
                    $expiredsurveys .= " value='" . Yii::app()->getController()->createUrl("/admin/survey/view/surveyid/" . $sv['sid']) . "'>{$surveylstitle}</option>\n";
                } else {
                    $expiredsurveys .= " value='{$sv['sid']}'>{$surveylstitle}</option>\n";
                }
            } else {
                $activesurveys .= "<option ";
                if (Yii::app()->user->getId() == $sv['owner_id']) {
                    $activesurveys .= " style=\"font-weight: bold;\"";
                }
                if ($sv['sid'] == $surveyid) {
                    $activesurveys .= " selected='selected'";
                    $svexist = 1;
                }
                if ($returnwithouturl === false) {
                    $activesurveys .= " value='" . Yii::app()->getController()->createUrl("/admin/survey/view/surveyid/" . $sv['sid']) . "'>{$surveylstitle}</option>\n";
                } else {
                    $activesurveys .= " value='{$sv['sid']}'>{$surveylstitle}</option>\n";
                }
            }
        }
        // End Foreach
    }
    //Only show each activesurvey group if there are some
    if ($activesurveys != '') {
        $surveyselecter .= "<optgroup label='" . $clang->gT("Active") . "' class='activesurveyselect'>\n";
        $surveyselecter .= $activesurveys . "</optgroup>";
    }
    if ($expiredsurveys != '') {
        $surveyselecter .= "<optgroup label='" . $clang->gT("Expired") . "' class='expiredsurveyselect'>\n";
        $surveyselecter .= $expiredsurveys . "</optgroup>";
    }
    if ($inactivesurveys != '') {
        $surveyselecter .= "<optgroup label='" . $clang->gT("Inactive") . "' class='inactivesurveyselect'>\n";
        $surveyselecter .= $inactivesurveys . "</optgroup>";
    }
    if (!isset($svexist)) {
        $surveyselecter = "<option selected='selected' value=''>" . $clang->gT("Please choose...") . "</option>\n" . $surveyselecter;
    } else {
        if ($returnwithouturl === false) {
            $surveyselecter = "<option value='" . Yii::app()->getController()->createUrl("/admin") . "'>" . $clang->gT("None") . "</option>\n" . $surveyselecter;
        } else {
            $surveyselecter = "<option value=''>" . $clang->gT("None") . "</option>\n" . $surveyselecter;
        }
    }
    return $surveyselecter;
}
 /**
  * register::index()
  * Process register form data and take appropriate action
  * @return
  */
 function actionIndex($surveyid = null)
 {
     Yii::app()->loadHelper('database');
     Yii::app()->loadHelper('replacements');
     $postlang = Yii::app()->request->getPost('lang');
     if ($surveyid == null) {
         $surveyid = Yii::app()->request->getPost('sid');
     }
     if (!$surveyid) {
         Yii::app()->request->redirect(Yii::app()->baseUrl);
     }
     // Get passed language from form, so that we dont loose this!
     if (!isset($postlang) || $postlang == "" || !$postlang) {
         $baselang = Survey::model()->findByPk($surveyid)->language;
         Yii::import('application.libraries.Limesurvey_lang');
         Yii::app()->lang = new Limesurvey_lang($baselang);
         $clang = Yii::app()->lang;
     } else {
         Yii::import('application.libraries.Limesurvey_lang');
         Yii::app()->lang = new Limesurvey_lang($postlang);
         $clang = Yii::app()->lang;
         $baselang = $postlang;
     }
     $thissurvey = getSurveyInfo($surveyid, $baselang);
     $register_errormsg = "";
     // Check the security question's answer
     if (function_exists("ImageCreate") && isCaptchaEnabled('registrationscreen', $thissurvey['usecaptcha'])) {
         if (!isset($_POST['loadsecurity']) || !isset($_SESSION['survey_' . $surveyid]['secanswer']) || Yii::app()->request->getPost('loadsecurity') != $_SESSION['survey_' . $surveyid]['secanswer']) {
             $register_errormsg .= $clang->gT("The answer to the security question is incorrect.") . "<br />\n";
         }
     }
     //Check that the email is a valid style address
     if (!validateEmailAddress(Yii::app()->request->getPost('register_email'))) {
         $register_errormsg .= $clang->gT("The email you used is not valid. Please try again.");
     }
     // Check for additional fields
     $attributeinsertdata = array();
     foreach (GetParticipantAttributes($surveyid) as $field => $data) {
         if (empty($data['show_register']) || $data['show_register'] != 'Y') {
             continue;
         }
         $value = sanitize_xss_string(Yii::app()->request->getPost('register_' . $field));
         if (trim($value) == '' && $data['mandatory'] == 'Y') {
             $register_errormsg .= sprintf($clang->gT("%s cannot be left empty"), $thissurvey['attributecaptions'][$field]);
         }
         $attributeinsertdata[$field] = $value;
     }
     if ($register_errormsg != "") {
         $_SESSION['survey_' . $surveyid]['register_errormsg'] = $register_errormsg;
         Yii::app()->request->redirect(Yii::app()->createUrl('survey/index/sid/' . $surveyid));
     }
     //Check if this email already exists in token database
     $query = "SELECT email FROM {{tokens_{$surveyid}}}\n" . "WHERE email = '" . sanitize_email(Yii::app()->request->getPost('register_email')) . "'";
     $usrow = Yii::app()->db->createCommand($query)->queryRow();
     if ($usrow) {
         $register_errormsg = $clang->gT("The email you used has already been registered.");
         $_SESSION['survey_' . $surveyid]['register_errormsg'] = $register_errormsg;
         Yii::app()->request->redirect(Yii::app()->createUrl('survey/index/sid/' . $surveyid));
         //include "index.php";
         //exit;
     }
     $mayinsert = false;
     // Get the survey settings for token length
     //$this->load->model("surveys_model");
     $tlresult = Survey::model()->findAllByAttributes(array("sid" => $surveyid));
     if (isset($tlresult[0])) {
         $tlrow = $tlresult[0];
     } else {
         $tlrow = $tlresult;
     }
     $tokenlength = $tlrow['tokenlength'];
     //if tokenlength is not set or there are other problems use the default value (15)
     if (!isset($tokenlength) || $tokenlength == '') {
         $tokenlength = 15;
     }
     while ($mayinsert != true) {
         $newtoken = randomChars($tokenlength);
         $ntquery = "SELECT * FROM {{tokens_{$surveyid}}} WHERE token='{$newtoken}'";
         $usrow = Yii::app()->db->createCommand($ntquery)->queryRow();
         if (!$usrow) {
             $mayinsert = true;
         }
     }
     $postfirstname = sanitize_xss_string(strip_tags(Yii::app()->request->getPost('register_firstname')));
     $postlastname = sanitize_xss_string(strip_tags(Yii::app()->request->getPost('register_lastname')));
     $starttime = sanitize_xss_string(Yii::app()->request->getPost('startdate'));
     $endtime = sanitize_xss_string(Yii::app()->request->getPost('enddate'));
     /*$postattribute1=sanitize_xss_string(strip_tags(returnGlobal('register_attribute1')));
       $postattribute2=sanitize_xss_string(strip_tags(returnGlobal('register_attribute2')));   */
     // Insert new entry into tokens db
     Tokens_dynamic::sid($thissurvey['sid']);
     $token = new Tokens_dynamic();
     $token->firstname = $postfirstname;
     $token->lastname = $postlastname;
     $token->email = Yii::app()->request->getPost('register_email');
     $token->emailstatus = 'OK';
     $token->token = $newtoken;
     if ($starttime && $endtime) {
         $token->validfrom = $starttime;
         $token->validuntil = $endtime;
     }
     foreach ($attributeinsertdata as $k => $v) {
         $token->{$k} = $v;
     }
     $result = $token->save();
     /**
     $result = $connect->Execute($query, array($postfirstname,
     $postlastname,
     returnGlobal('register_email'),
     'OK',
     $newtoken)
     
     //                             $postattribute1,   $postattribute2)
     ) or safeDie ($query."<br />".$connect->ErrorMsg());  //Checked - According to adodb docs the bound variables are quoted automatically
     */
     $tid = getLastInsertID($token->tableName());
     $fieldsarray["{ADMINNAME}"] = $thissurvey['adminname'];
     $fieldsarray["{ADMINEMAIL}"] = $thissurvey['adminemail'];
     $fieldsarray["{SURVEYNAME}"] = $thissurvey['name'];
     $fieldsarray["{SURVEYDESCRIPTION}"] = $thissurvey['description'];
     $fieldsarray["{FIRSTNAME}"] = $postfirstname;
     $fieldsarray["{LASTNAME}"] = $postlastname;
     $fieldsarray["{EXPIRY}"] = $thissurvey["expiry"];
     $message = $thissurvey['email_register'];
     $subject = $thissurvey['email_register_subj'];
     $from = "{$thissurvey['adminname']} <{$thissurvey['adminemail']}>";
     if (getEmailFormat($surveyid) == 'html') {
         $useHtmlEmail = true;
         $surveylink = $this->createAbsoluteUrl($surveyid . '/lang-' . $baselang . '/tk-' . $newtoken);
         $optoutlink = $this->createAbsoluteUrl('optout/local/' . $surveyid . '/' . $baselang . '/' . $newtoken);
         $optinlink = $this->createAbsoluteUrl('optin/local/' . $surveyid . '/' . $baselang . '/' . $newtoken);
         $fieldsarray["{SURVEYURL}"] = "<a href='{$surveylink}'>" . $surveylink . "</a>";
         $fieldsarray["{OPTOUTURL}"] = "<a href='{$optoutlink}'>" . $optoutlink . "</a>";
         $fieldsarray["{OPTINURL}"] = "<a href='{$optinlink}'>" . $optinlink . "</a>";
     } else {
         $useHtmlEmail = false;
         $fieldsarray["{SURVEYURL}"] = $this->createAbsoluteUrl('' . $surveyid . '/lang-' . $baselang . '/tk-' . $newtoken);
         $fieldsarray["{OPTOUTURL}"] = $this->createAbsoluteUrl('optout/local/' . $surveyid . '/' . $baselang . '/' . $newtoken);
         $fieldsarray["{OPTINURL}"] = $this->createAbsoluteUrl('optin/local/' . $surveyid . '/' . $baselang . '/' . $newtoken);
     }
     $message = ReplaceFields($message, $fieldsarray);
     $subject = ReplaceFields($subject, $fieldsarray);
     $html = "";
     //Set variable
     $sitename = Yii::app()->getConfig('sitename');
     if (SendEmailMessage($message, $subject, Yii::app()->request->getPost('register_email'), $from, $sitename, $useHtmlEmail, getBounceEmail($surveyid))) {
         // TLR change to put date into sent
         $today = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig('timeadjust'));
         $query = "UPDATE {{tokens_{$surveyid}}}\n" . "SET sent='{$today}' WHERE tid={$tid}";
         $result = dbExecuteAssoc($query) or show_error("Unable to execute this query : {$query}<br />");
         //Checked
         $html = "<center>" . $clang->gT("Thank you for registering to participate in this survey.") . "<br /><br />\n" . $clang->gT("An email has been sent to the address you provided with access details for this survey. Please follow the link in that email to proceed.") . "<br /><br />\n" . $clang->gT("Survey administrator") . " {ADMINNAME} ({ADMINEMAIL})";
         $html = ReplaceFields($html, $fieldsarray);
         $html .= "<br /><br /></center>\n";
     } else {
         $html = "Email Error";
     }
     //PRINT COMPLETED PAGE
     if (!$thissurvey['template']) {
         $thistpl = getTemplatePath(validateTemplateDir('default'));
     } else {
         $thistpl = getTemplatePath(validateTemplateDir($thissurvey['template']));
     }
     sendCacheHeaders();
     doHeader();
     Yii::app()->lang = $clang;
     // fetch the defined variables and pass it to the header footer templates.
     $redata = compact(array_keys(get_defined_vars()));
     $this->_printTemplateContent($thistpl . '/startpage.pstpl', $redata, __LINE__);
     $this->_printTemplateContent($thistpl . '/survey.pstpl', $redata, __LINE__);
     echo $html;
     $this->_printTemplateContent($thistpl . '/endpage.pstpl', $redata, __LINE__);
     doFooter();
 }
Example #20
0
 /**
  * Handle email action
  */
 function email($iSurveyId, $tokenids = null)
 {
     $clang = $this->getController()->lang;
     $iSurveyId = sanitize_int($iSurveyId);
     if (!Permission::model()->hasSurveyPermission($iSurveyId, 'tokens', 'update')) {
         Yii::app()->session['flashmessage'] = $clang->gT("You do not have sufficient rights to access this page.");
         $this->getController()->redirect(array("/admin/survey/sa/view/surveyid/{$iSurveyId}"));
     }
     // CHECK TO SEE IF A TOKEN TABLE EXISTS FOR THIS SURVEY
     $bTokenExists = tableExists('{{tokens_' . $iSurveyId . '}}');
     if (!$bTokenExists) {
         self::_newtokentable($iSurveyId);
     }
     $aTokenIds = $tokenids;
     if (empty($tokenids)) {
         $aTokenIds = Yii::app()->request->getPost('tokenids', false);
     }
     if (!empty($aTokenIds)) {
         $aTokenIds = explode('|', $aTokenIds);
         $aTokenIds = array_filter($aTokenIds);
         $aTokenIds = array_map('sanitize_int', $aTokenIds);
     }
     $aTokenIds = array_unique(array_filter((array) $aTokenIds));
     $sSubAction = Yii::app()->request->getParam('action');
     $sSubAction = !in_array($sSubAction, array('email', 'remind')) ? 'email' : $sSubAction;
     $bEmail = $sSubAction == 'email';
     Yii::app()->loadHelper('surveytranslator');
     Yii::app()->loadHelper('/admin/htmleditor');
     Yii::app()->loadHelper('replacements');
     $token = Token::model($iSurveyId)->find();
     $aExampleRow = isset($token) ? $token->attributes : array();
     $aSurveyLangs = Survey::model()->findByPk($iSurveyId)->additionalLanguages;
     $sBaseLanguage = Survey::model()->findByPk($iSurveyId)->language;
     array_unshift($aSurveyLangs, $sBaseLanguage);
     $aTokenFields = getTokenFieldsAndNames($iSurveyId, true);
     $iAttributes = 0;
     $bHtml = getEmailFormat($iSurveyId) == 'html';
     $timeadjust = Yii::app()->getConfig("timeadjust");
     $aData['thissurvey'] = getSurveyInfo($iSurveyId);
     foreach ($aSurveyLangs as $sSurveyLanguage) {
         $aData['thissurvey'][$sSurveyLanguage] = getSurveyInfo($iSurveyId, $sSurveyLanguage);
     }
     $aData['surveyid'] = $iSurveyId;
     $aData['sSubAction'] = $sSubAction;
     $aData['bEmail'] = $bEmail;
     $aData['aSurveyLangs'] = $aData['surveylangs'] = $aSurveyLangs;
     $aData['baselang'] = $sBaseLanguage;
     $aData['tokenfields'] = array_keys($aTokenFields);
     $aData['nrofattributes'] = $iAttributes;
     $aData['examplerow'] = $aExampleRow;
     $aData['tokenids'] = $aTokenIds;
     $aData['ishtml'] = $bHtml;
     $iMaxEmails = Yii::app()->getConfig('maxemails');
     if (Yii::app()->request->getPost('bypassbademails') == 'Y') {
         $SQLemailstatuscondition = "emailstatus = 'OK'";
     } else {
         $SQLemailstatuscondition = "emailstatus <> 'OptOut'";
     }
     if (!Yii::app()->request->getPost('ok')) {
         if (empty($aData['tokenids'])) {
             $aTokens = TokenDynamic::model($iSurveyId)->findUninvitedIDs($aTokenIds, 0, $bEmail, $SQLemailstatuscondition);
             foreach ($aTokens as $aToken) {
                 $aData['tokenids'][] = $aToken;
             }
         }
         $this->_renderWrappedTemplate('token', array('tokenbar', $sSubAction), $aData);
     } else {
         $SQLremindercountcondition = "";
         $SQLreminderdelaycondition = "";
         if (!$bEmail) {
             if (Yii::app()->request->getPost('maxremindercount') && Yii::app()->request->getPost('maxremindercount') != '' && intval(Yii::app()->request->getPost('maxremindercount')) != 0) {
                 $SQLremindercountcondition = "remindercount < " . intval(Yii::app()->request->getPost('maxremindercount'));
             }
             if (Yii::app()->request->getPost('minreminderdelay') && Yii::app()->request->getPost('minreminderdelay') != '' && intval(Yii::app()->request->getPost('minreminderdelay')) != 0) {
                 // Yii::app()->request->getPost('minreminderdelay') in days (86400 seconds per day)
                 $compareddate = dateShift(date("Y-m-d H:i:s", time() - 86400 * intval(Yii::app()->request->getPost('minreminderdelay'))), "Y-m-d H:i", $timeadjust);
                 $SQLreminderdelaycondition = " ( " . " (remindersent = 'N' AND sent < '" . $compareddate . "') " . " OR " . " (remindersent < '" . $compareddate . "'))";
             }
         }
         $ctresult = TokenDynamic::model($iSurveyId)->findUninvitedIDs($aTokenIds, 0, $bEmail, $SQLemailstatuscondition, $SQLremindercountcondition, $SQLreminderdelaycondition);
         $ctcount = count($ctresult);
         $emresult = TokenDynamic::model($iSurveyId)->findUninvited($aTokenIds, $iMaxEmails, $bEmail, $SQLemailstatuscondition, $SQLremindercountcondition, $SQLreminderdelaycondition);
         $emcount = count($emresult);
         foreach ($aSurveyLangs as $language) {
             // See #08683 : this allow use of {TOKEN:ANYTHING}, directly replaced by {ANYTHING}
             $sSubject[$language] = preg_replace("/{TOKEN:([A-Z0-9_]+)}/", "{" . "\$1" . "}", Yii::app()->request->getPost('subject_' . $language));
             $sMessage[$language] = preg_replace("/{TOKEN:([A-Z0-9_]+)}/", "{" . "\$1" . "}", Yii::app()->request->getPost('message_' . $language));
             if ($bHtml) {
                 $sMessage[$language] = html_entity_decode($sMessage[$language], ENT_QUOTES, Yii::app()->getConfig("emailcharset"));
             }
         }
         $attributes = array_keys(getTokenFieldsAndNames($iSurveyId, true));
         $tokenoutput = "";
         if ($emcount > 0) {
             foreach ($emresult as $emrow) {
                 $to = $fieldsarray = array();
                 $aEmailaddresses = explode(';', $emrow['email']);
                 foreach ($aEmailaddresses as $sEmailaddress) {
                     $to[] = $emrow['firstname'] . " " . $emrow['lastname'] . " <{$sEmailaddress}>";
                 }
                 $fieldsarray["{EMAIL}"] = $emrow['email'];
                 $fieldsarray["{FIRSTNAME}"] = $emrow['firstname'];
                 $fieldsarray["{LASTNAME}"] = $emrow['lastname'];
                 $fieldsarray["{TOKEN}"] = $emrow['token'];
                 $fieldsarray["{LANGUAGE}"] = $emrow['language'];
                 foreach ($attributes as $attributefield) {
                     $fieldsarray['{' . strtoupper($attributefield) . '}'] = $emrow[$attributefield];
                     $fieldsarray['{TOKEN:' . strtoupper($attributefield) . '}'] = $emrow[$attributefield];
                 }
                 $emrow['language'] = trim($emrow['language']);
                 $found = array_search($emrow['language'], $aSurveyLangs);
                 if ($emrow['language'] == '' || $found == false) {
                     $emrow['language'] = $sBaseLanguage;
                 }
                 $from = Yii::app()->request->getPost('from_' . $emrow['language']);
                 $fieldsarray["{OPTOUTURL}"] = $this->getController()->createAbsoluteUrl("/optout/tokens/langcode/" . trim($emrow['language']) . "/surveyid/{$iSurveyId}/token/{$emrow['token']}");
                 $fieldsarray["{OPTINURL}"] = $this->getController()->createAbsoluteUrl("/optin/tokens/langcode/" . trim($emrow['language']) . "/surveyid/{$iSurveyId}/token/{$emrow['token']}");
                 $fieldsarray["{SURVEYURL}"] = $this->getController()->createAbsoluteUrl("/survey/index/sid/{$iSurveyId}/token/{$emrow['token']}/lang/" . trim($emrow['language']) . "/");
                 foreach (array('OPTOUT', 'OPTIN', 'SURVEY') as $key) {
                     $url = $fieldsarray["{{$key}URL}"];
                     if ($bHtml) {
                         $fieldsarray["{{$key}URL}"] = "<a href='{$url}'>" . htmlspecialchars($url) . '</a>';
                     }
                     if ($key == 'SURVEY') {
                         $barebone_link = $url;
                     }
                 }
                 $customheaders = array('1' => "X-surveyid: " . $iSurveyId, '2' => "X-tokenid: " . $fieldsarray["{TOKEN}"]);
                 global $maildebug;
                 $modsubject = Replacefields($sSubject[$emrow['language']], $fieldsarray);
                 $modmessage = Replacefields($sMessage[$emrow['language']], $fieldsarray);
                 if (isset($barebone_link)) {
                     $modsubject = str_replace("@@SURVEYURL@@", $barebone_link, $modsubject);
                     $modmessage = str_replace("@@SURVEYURL@@", $barebone_link, $modmessage);
                 }
                 if (trim($emrow['validfrom']) != '' && convertDateTimeFormat($emrow['validfrom'], 'Y-m-d H:i:s', 'U') * 1 > date('U') * 1) {
                     $tokenoutput .= $emrow['tid'] . " " . ReplaceFields($clang->gT("Email to {FIRSTNAME} {LASTNAME} ({EMAIL}) delayed: Token is not yet valid.") . "<br />", $fieldsarray);
                 } elseif (trim($emrow['validuntil']) != '' && convertDateTimeFormat($emrow['validuntil'], 'Y-m-d H:i:s', 'U') * 1 < date('U') * 1) {
                     $tokenoutput .= $emrow['tid'] . " " . ReplaceFields($clang->gT("Email to {FIRSTNAME} {LASTNAME} ({EMAIL}) skipped: Token is not valid anymore.") . "<br />", $fieldsarray);
                 } else {
                     /*
                      * Get attachments.
                      */
                     if ($sSubAction == 'email') {
                         $sTemplate = 'invitation';
                     } elseif ($sSubAction == 'remind') {
                         $sTemplate = 'reminder';
                     }
                     $aRelevantAttachments = array();
                     if (isset($aData['thissurvey'][$emrow['language']]['attachments'])) {
                         $aAttachments = unserialize($aData['thissurvey'][$emrow['language']]['attachments']);
                         if (!empty($aAttachments)) {
                             if (isset($aAttachments[$sTemplate])) {
                                 LimeExpressionManager::singleton()->loadTokenInformation($aData['thissurvey']['sid'], $emrow['token']);
                                 foreach ($aAttachments[$sTemplate] as $aAttachment) {
                                     if (LimeExpressionManager::singleton()->ProcessRelevance($aAttachment['relevance'])) {
                                         $aRelevantAttachments[] = $aAttachment['url'];
                                     }
                                 }
                             }
                         }
                     }
                     /**
                      * Event for email handling.
                      * Parameter    type    description:
                      * subject      rw      Body of the email
                      * to           rw      Recipient(s)
                      * from         rw      Sender(s)
                      * type         r       "invitation" or "reminder"
                      * send         w       If true limesurvey will send the email. Setting this to false will cause limesurvey to assume the mail has been sent by the plugin.
                      * error        w       If set and "send" is true, log the error as failed email attempt.
                      * token        r       Raw token data.
                      */
                     $event = new PluginEvent('beforeTokenEmail');
                     $event->set('type', $sTemplate);
                     $event->set('subject', $modsubject);
                     $event->set('to', $to);
                     $event->set('body', $modmessage);
                     $event->set('from', $from);
                     $event->set('bounce', getBounceEmail($iSurveyId));
                     $event->set('token', $emrow);
                     App()->getPluginManager()->dispatchEvent($event);
                     $modsubject = $event->get('subject');
                     $modmessage = $event->get('body');
                     $to = $event->get('to');
                     $from = $event->get('from');
                     if ($event->get('send', true) == false) {
                         // This is some ancient global used for error reporting instead of a return value from the actual mail function..
                         $maildebug = $event->get('error', $maildebug);
                         $success = $event->get('error') == null;
                     } else {
                         $success = SendEmailMessage($modmessage, $modsubject, $to, $from, Yii::app()->getConfig("sitename"), $bHtml, getBounceEmail($iSurveyId), $aRelevantAttachments, $customheaders);
                     }
                     if ($success) {
                         // Put date into sent
                         $token = Token::model($iSurveyId)->findByPk($emrow['tid']);
                         if ($bEmail) {
                             $tokenoutput .= $clang->gT("Invitation sent to:");
                             $token->sent = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig("timeadjust"));
                         } else {
                             $tokenoutput .= $clang->gT("Reminder sent to:");
                             $token->remindersent = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig("timeadjust"));
                             $token->remindercount++;
                         }
                         $token->save();
                         //Update central participant survey_links
                         if (!empty($emrow['participant_id'])) {
                             $slquery = SurveyLink::model()->find('participant_id = :pid AND survey_id = :sid AND token_id = :tid', array(':pid' => $emrow['participant_id'], ':sid' => $iSurveyId, ':tid' => $emrow['tid']));
                             if (!is_null($slquery)) {
                                 $slquery->date_invited = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig("timeadjust"));
                                 $slquery->save();
                             }
                         }
                         $tokenoutput .= "{$emrow['tid']}: {$emrow['firstname']} {$emrow['lastname']} ({$emrow['email']})<br />\n";
                         if (Yii::app()->getConfig("emailsmtpdebug") == 2) {
                             $tokenoutput .= $maildebug;
                         }
                     } else {
                         $tokenoutput .= ReplaceFields($clang->gT("Email to {FIRSTNAME} {LASTNAME} ({EMAIL}) failed. Error Message:") . " " . $maildebug . "<br />", $fieldsarray);
                     }
                 }
                 unset($fieldsarray);
             }
             $aViewUrls = array('tokenbar', 'emailpost');
             $aData['tokenoutput'] = $tokenoutput;
             if ($ctcount > $emcount) {
                 $i = 0;
                 if (isset($aTokenIds)) {
                     while ($i < $iMaxEmails) {
                         array_shift($aTokenIds);
                         $i++;
                     }
                     $aData['tids'] = implode('|', $aTokenIds);
                 }
                 $aData['lefttosend'] = $ctcount - $iMaxEmails;
                 $aViewUrls[] = 'emailwarning';
             } else {
                 $aData['tokenoutput'] .= "<strong class='result success text-success'>" . gT("All emails were sent.") . "<strong>";
             }
             $this->_renderWrappedTemplate('token', $aViewUrls, $aData);
         } else {
             $this->_renderWrappedTemplate('token', array('tokenbar', 'message' => array('title' => $clang->gT("Warning"), 'message' => $clang->gT("There were no eligible emails to send. This will be because none satisfied the criteria of:") . "<br/>&nbsp;<ul><li>" . $clang->gT("having a valid email address") . "</li>" . "<li>" . $clang->gT("not having been sent an invitation already") . "</li>" . "<li>" . $clang->gT("having already completed the survey") . "</li>" . "<li>" . $clang->gT("having a token") . "</li></ul>")), $aData);
         }
     }
 }
Example #21
0
 public function scopes()
 {
     $now = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", Yii::app()->getConfig("timeadjust"));
     return array('incomplete' => array('condition' => "completed = 'N'"), 'usable' => array('condition' => "COALESCE(validuntil, '{$now}') >= '{$now}' AND COALESCE(validfrom, '{$now}') <= '{$now}'"), 'editable' => array('condition' => "COALESCE(validuntil, '{$now}') >= '{$now}' AND COALESCE(validfrom, '{$now}') <= '{$now}'"), 'empty' => array('condition' => 'token is null or token = ""'));
 }
Example #22
0
/**
* Sends email to tokens - invitation and reminders
*
* @param mixed $iSurveyID
* @param array  $aResultTokens
* @param string $sType type of notification invite|register|remind
* @return array of results
*/
function emailTokens($iSurveyID, $aResultTokens, $sType)
{
    Yii::app()->loadHelper('common');
    $oSurvey = Survey::model()->findByPk($iSurveyID);
    if (getEmailFormat($iSurveyID) == 'html') {
        $bHtml = true;
    } else {
        $bHtml = false;
    }
    $attributes = array_keys(getTokenFieldsAndNames($iSurveyID));
    $oSurveyLocale = SurveyLanguageSetting::model()->findAllByAttributes(array('surveyls_survey_id' => $iSurveyID));
    $oTokens = Token::model($iSurveyID);
    $aSurveyLangs = $oSurvey->additionalLanguages;
    array_unshift($aSurveyLangs, $oSurvey->language);
    //Convert result to associative array to minimize SurveyLocale access attempts
    foreach ($oSurveyLocale as $rows) {
        $oTempObject = array();
        foreach ($rows as $k => $v) {
            $oTempObject[$k] = $v;
        }
        $aSurveyLocaleData[$rows['surveyls_language']] = $oTempObject;
    }
    foreach ($aResultTokens as $aTokenRow) {
        //Select language
        $aTokenRow['language'] = trim($aTokenRow['language']);
        $found = array_search($aTokenRow['language'], $aSurveyLangs);
        if ($aTokenRow['language'] == '' || $found == false) {
            $aTokenRow['language'] = $oSurvey['language'];
        }
        $sTokenLanguage = $aTokenRow['language'];
        //Build recipient
        $to = array();
        $aEmailaddresses = explode(';', $aTokenRow['email']);
        foreach ($aEmailaddresses as $sEmailaddress) {
            $to[] = $aTokenRow['firstname'] . " " . $aTokenRow['lastname'] . " <{$sEmailaddress}>";
        }
        //Populate attributes
        $fieldsarray["{SURVEYNAME}"] = $aSurveyLocaleData[$sTokenLanguage]['surveyls_title'];
        if ($fieldsarray["{SURVEYNAME}"] == '') {
            $fieldsarray["{SURVEYNAME}"] = $aSurveyLocaleData[$oSurvey['language']]['surveyls_title'];
        }
        $fieldsarray["{SURVEYDESCRIPTION}"] = $aSurveyLocaleData[$sTokenLanguage]['surveyls_description'];
        if ($fieldsarray["{SURVEYDESCRIPTION}"] == '') {
            $fieldsarray["{SURVEYDESCRIPTION}"] = $aSurveyLocaleData[$oSurvey['language']]['surveyls_description'];
        }
        $fieldsarray["{ADMINNAME}"] = $oSurvey['admin'];
        $fieldsarray["{ADMINEMAIL}"] = $oSurvey['adminemail'];
        $from = $fieldsarray["{ADMINNAME}"] . ' <' . $fieldsarray["{ADMINEMAIL}"] . '>';
        if ($from == '') {
            $from = Yii::app()->getConfig('siteadminemail');
        }
        foreach ($attributes as $attributefield) {
            $fieldsarray['{' . strtoupper($attributefield) . '}'] = $aTokenRow[$attributefield];
            $fieldsarray['{TOKEN:' . strtoupper($attributefield) . '}'] = $aTokenRow[$attributefield];
        }
        //create urls
        $fieldsarray["{OPTOUTURL}"] = Yii::app()->getController()->createAbsoluteUrl("/optout/tokens/langcode/" . trim($aTokenRow['language']) . "/surveyid/{$iSurveyID}/token/{$aTokenRow['token']}");
        $fieldsarray["{OPTINURL}"] = Yii::app()->getController()->createAbsoluteUrl("/optin/tokens/langcode/" . trim($aTokenRow['language']) . "/surveyid/{$iSurveyID}/token/{$aTokenRow['token']}");
        $fieldsarray["{SURVEYURL}"] = Yii::app()->getController()->createAbsoluteUrl("/survey/index/sid/{$iSurveyID}/token/{$aTokenRow['token']}/lang/" . trim($aTokenRow['language']) . "/");
        if ($bHtml) {
            foreach (array('OPTOUT', 'OPTIN', 'SURVEY') as $key) {
                $url = $fieldsarray["{{$key}URL}"];
                $fieldsarray["{{$key}URL}"] = "<a href='{$url}'>" . htmlspecialchars($url) . '</a>';
                if ($key == 'SURVEY') {
                    $barebone_link = $url;
                }
            }
        }
        //mail headers
        $customheaders = array('1' => "X-surveyid: " . $iSurveyID, '2' => "X-tokenid: " . $fieldsarray["{TOKEN}"]);
        global $maildebug;
        //choose appriopriate email message
        if ($sType == 'invite') {
            $sSubject = $aSurveyLocaleData[$sTokenLanguage]['surveyls_email_invite_subj'];
            $sMessage = $aSurveyLocaleData[$sTokenLanguage]['surveyls_email_invite'];
        } else {
            if ($sType == 'register') {
                $sSubject = $aSurveyLocaleData[$sTokenLanguage]['surveyls_email_register_subj'];
                $sMessage = $aSurveyLocaleData[$sTokenLanguage]['surveyls_email_register'];
            } else {
                $sSubject = $aSurveyLocaleData[$sTokenLanguage]['surveyls_email_remind_subj'];
                $sMessage = $aSurveyLocaleData[$sTokenLanguage]['surveyls_email_remind'];
            }
        }
        $modsubject = Replacefields($sSubject, $fieldsarray);
        $modmessage = Replacefields($sMessage, $fieldsarray);
        if (isset($barebone_link)) {
            $modsubject = str_replace("@@SURVEYURL@@", $barebone_link, $modsubject);
            $modmessage = str_replace("@@SURVEYURL@@", $barebone_link, $modmessage);
        }
        if (isset($aTokenRow['validfrom']) && trim($aTokenRow['validfrom']) != '' && convertDateTimeFormat($aTokenRow['validfrom'], 'Y-m-d H:i:s', 'U') * 1 > date('U') * 1) {
            $aResult[$aTokenRow['tid']] = array('name' => $fieldsarray["{FIRSTNAME}"] . " " . $fieldsarray["{LASTNAME}"], 'email' => $fieldsarray["{EMAIL}"], 'status' => 'fail', 'error' => 'Token not valid yet');
        } elseif (isset($aTokenRow['validuntil']) && trim($aTokenRow['validuntil']) != '' && convertDateTimeFormat($aTokenRow['validuntil'], 'Y-m-d H:i:s', 'U') * 1 < date('U') * 1) {
            $aResult[$aTokenRow['tid']] = array('name' => $fieldsarray["{FIRSTNAME}"] . " " . $fieldsarray["{LASTNAME}"], 'email' => $fieldsarray["{EMAIL}"], 'status' => 'fail', 'error' => 'Token not valid anymore');
        } else {
            if (SendEmailMessage($modmessage, $modsubject, $to, $from, Yii::app()->getConfig("sitename"), $bHtml, getBounceEmail($iSurveyID), null, $customheaders)) {
                $aResult[$aTokenRow['tid']] = array('name' => $fieldsarray["{FIRSTNAME}"] . " " . $fieldsarray["{LASTNAME}"], 'email' => $fieldsarray["{EMAIL}"], 'status' => 'OK');
                if ($sType == 'invite' || $sType == 'register') {
                    $oTokens->updateByPk($aTokenRow['tid'], array('sent' => dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig("timeadjust"))));
                }
                if ($sType == 'remind') {
                    $iRCount = $oTokens->findByPk($aTokenRow['tid'])->remindercount + 1;
                    $oTokens->updateByPk($aTokenRow['tid'], array('remindersent' => dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig("timeadjust"))));
                    $oTokens->updateByPk($aTokenRow['tid'], array('remindercount' => $iRCount));
                }
            } else {
                $aResult[$aTokenRow['tid']] = array('name' => $fieldsarray["{FIRSTNAME}"] . " " . $fieldsarray["{LASTNAME}"], 'email' => $fieldsarray["{EMAIL}"], 'status' => 'fail', 'error' => $maildebug);
            }
        }
        unset($fieldsarray);
    }
    return $aResult;
}
Example #23
0
 /**
  * Returns surveys in json format
  *
  * @access public
  * @return void
  */
 public function getSurveys_json()
 {
     $this->getController()->loadHelper('surveytranslator');
     $dateformatdetails = getDateFormatData(Yii::app()->session['dateformat']);
     $oSurvey = new Survey();
     $oSurvey->permission(Yii::app()->user->getId());
     $aSurveys = $oSurvey->with(array('languagesettings' => array('condition' => 'surveyls_language=language'), 'owner'))->findAll();
     $aSurveyEntries = new stdClass();
     $aSurveyEntries->page = 1;
     foreach ($aSurveys as $rows) {
         if (!isset($rows->owner->attributes)) {
             $aOwner = array('users_name' => gT('(None)'));
         } else {
             $aOwner = $rows->owner->attributes;
         }
         $rows = array_merge($rows->attributes, $rows->defaultlanguage->attributes, $aOwner);
         $aSurveyEntry = array();
         // Set status
         if ($rows['active'] == "Y" && $rows['expires'] != '' && $rows['expires'] < dateShift(date("Y-m-d H:i:s"), "Y-m-d", Yii::app()->getConfig('timeadjust'))) {
             $aSurveyEntry[] = '<!--a--><img src="' . Yii::app()->getConfig('adminimageurl') . 'expired.png" alt="' . gT("This survey is active but expired.") . '" />';
         } elseif ($rows['active'] == "Y" && $rows['startdate'] != '' && $rows['startdate'] > dateShift(date("Y-m-d H:i:s"), "Y-m-d", Yii::app()->getConfig('timeadjust'))) {
             $aSurveyEntry[] = '<!--b--><img src="' . Yii::app()->getConfig('adminimageurl') . 'notyetstarted.png" alt="' . gT("This survey is active but has a start date.") . '" />';
         } elseif ($rows['active'] == "Y") {
             if (Permission::model()->hasSurveyPermission($rows['sid'], 'surveyactivation', 'update')) {
                 $aSurveyEntry[] = '<!--c--><a href="' . $this->getController()->createUrl('admin/survey/sa/deactivate/surveyid/' . $rows['sid']) . '"><img src="' . Yii::app()->getConfig('adminimageurl') . 'active.png" alt="' . gT("This survey is active - click here to stop this survey.") . '"/></a>';
             } else {
                 $aSurveyEntry[] = '<!--d--><img src="' . Yii::app()->getConfig('adminimageurl') . 'active.png" alt="' . gT("This survey is currently active.") . '" />';
             }
         } else {
             $condition = "sid={$rows['sid']} AND language='" . $rows['language'] . "'";
             $questionsCountResult = Question::model()->count($condition);
             if ($questionsCountResult > 0 && Permission::model()->hasSurveyPermission($rows['sid'], 'surveyactivation', 'update')) {
                 $aSurveyEntry[] = '<!--e--><a href="' . $this->getController()->createUrl('admin/survey/sa/activate/surveyid/' . $rows['sid']) . '"><img src="' . Yii::app()->getConfig('adminimageurl') . 'inactive.png" title="" alt="' . gT("This survey is currently not active - click here to activate this survey.") . '" /></a>';
             } else {
                 $aSurveyEntry[] = '<!--f--><img src="' . Yii::app()->getConfig('adminimageurl') . 'inactive.png" title="' . gT("This survey is currently not active.") . '" alt="' . gT("This survey is currently not active.") . '" />';
             }
         }
         //Set SID
         $aSurveyEntry[] = $rows['sid'];
         '<a href="' . $this->getController()->createUrl("/admin/survey/sa/view/surveyid/" . $rows['sid']) . '">' . $rows['sid'] . '</a>';
         //Set Title
         $aSurveyEntry[] = '<a href="' . $this->getController()->createUrl("/admin/survey/sa/view/surveyid/" . $rows['sid']) . '">' . CHtml::encode($rows['surveyls_title']) . '</a>';
         //Set Date
         Yii::import('application.libraries.Date_Time_Converter', true);
         $datetimeobj = new Date_Time_Converter($rows['datecreated'], "Y-m-d H:i:s");
         $aSurveyEntry[] = '<!--' . $rows['datecreated'] . '-->' . $datetimeobj->convert($dateformatdetails['phpdate']);
         //Set Owner
         if (Permission::model()->hasGlobalPermission('superadmin', 'read') || Yii::app()->session['loginID'] == $rows['owner_id']) {
             $aSurveyEntry[] = $rows['users_name'] . ' (<a class="ownername_edit" translate_to="' . gT('Edit') . '" id="ownername_edit_' . $rows['sid'] . '">' . gT('Edit') . '</a>)';
         } else {
             $aSurveyEntry[] = $rows['users_name'];
         }
         //Set Access
         if (tableExists('tokens_' . $rows['sid'])) {
             $aSurveyEntry[] = gT("Closed");
         } else {
             $aSurveyEntry[] = gT("Open");
         }
         //Set Anonymous
         if ($rows['anonymized'] == "Y") {
             $aSurveyEntry[] = gT("Yes");
         } else {
             $aSurveyEntry[] = gT("No");
         }
         //Set Responses
         if ($rows['active'] == "Y") {
             $cntResult = SurveyDynamic::countAllAndPartial($rows['sid']);
             $all = $cntResult['cntall'];
             $partial = $cntResult['cntpartial'];
             $aSurveyEntry[] = $all - $partial;
             $aSurveyEntry[] = $partial;
             $aSurveyEntry[] = $all;
             $aSurveyEntry['viewurl'] = $this->getController()->createUrl("/admin/survey/sa/view/surveyid/" . $rows['sid']);
             if (tableExists('tokens_' . $rows['sid'])) {
                 $summary = Token::model($rows['sid'])->summary();
                 $tokens = $summary['count'];
                 $tokenscompleted = $summary['completed'];
                 $aSurveyEntry[] = $tokens;
                 $aSurveyEntry[] = $tokens == 0 ? 0 : round($tokenscompleted / $tokens * 100, 1) . ' %';
             } else {
                 $aSurveyEntry[] = $aSurveyEntry[] = '';
             }
         } else {
             $aSurveyEntry[] = $aSurveyEntry[] = $aSurveyEntry[] = $aSurveyEntry[] = $aSurveyEntry[] = '';
         }
         $aSurveyEntries->rows[] = array('id' => $rows['sid'], 'cell' => $aSurveyEntry);
     }
     header('Content-type: application/json');
     echo ls_json_encode($aSurveyEntries);
 }
Example #24
0
    function action()
    {
        global $surveyid;
        global $thissurvey, $thisstep;
        global $clienttoken, $tokensexist, $token;
        global $clang;
        $clang = Yii::app()->lang;
        @ini_set('session.gc_maxlifetime', Yii::app()->getConfig('iSessionExpirationTime'));
        $this->_loadRequiredHelpersAndLibraries();
        $param = $this->_getParameters(func_get_args(), $_POST);
        $surveyid = $param['sid'];
        Yii::app()->setConfig('surveyID', $surveyid);
        $thisstep = $param['thisstep'];
        $move = $param['move'];
        $clienttoken = $param['token'];
        $standardtemplaterootdir = Yii::app()->getConfig('standardtemplaterootdir');
        // unused vars in this method (used in methods using compacted method vars)
        @($loadname = $param['loadname']);
        @($loadpass = $param['loadpass']);
        $sitename = Yii::app()->getConfig('sitename');
        if (isset($param['newtest']) && $param['newtest'] == "Y") {
            killSurveySession($surveyid);
        }
        list($surveyExists, $isSurveyActive) = $this->_surveyExistsAndIsActive($surveyid);
        // collect all data in this method to pass on later
        $redata = compact(array_keys(get_defined_vars()));
        $clang = $this->_loadLimesurveyLang($surveyid);
        if ($this->_isClientTokenDifferentFromSessionToken($clienttoken, $surveyid)) {
            $asMessage = array($clang->gT('Token mismatch'), $clang->gT('The token you provided doesn\'t match the one in your session.'), $clang->gT('Please wait to begin with a new session.'));
            $this->_createNewUserSessionAndRedirect($surveyid, $redata, __LINE__, $asMessage);
        }
        if ($this->_isSurveyFinished($surveyid)) {
            $asMessage = array($clang->gT('Previous session is set to be finished.'), $clang->gT('Your browser reports that it was used previously to answer this survey. We are resetting the session so that you can start from the beginning.'), $clang->gT('Please wait to begin with a new session.'));
            $this->_createNewUserSessionAndRedirect($surveyid, $redata, __LINE__, $asMessage);
        }
        if ($this->_isPreviewAction($param) && !$this->_canUserPreviewSurvey($surveyid)) {
            $asMessage = array($clang->gT('Error'), $clang->gT('We are sorry but you don\'t have permissions to do this.'));
            $this->_niceExit($redata, __LINE__, null, $asMessage);
        }
        if ($this->_surveyCantBeViewedWithCurrentPreviewAccess($surveyid, $isSurveyActive, $surveyExists)) {
            $bPreviewRight = $this->_userHasPreviewAccessSession($surveyid);
            if ($bPreviewRight === false) {
                $asMessage = array($clang->gT("Error"), $clang->gT("We are sorry but you don't have permissions to do this."), sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), $thissurvey['adminname'], $thissurvey['adminemail']));
                $this->_niceExit($redata, __LINE__, null, $asMessage);
            }
        }
        // TODO can this be moved to the top?
        // (Used to be global, used in ExpressionManager, merged into amVars. If not filled in === '')
        // can this be added in the first computation of $redata?
        if (isset($_SESSION['survey_' . $surveyid]['srid'])) {
            $saved_id = $_SESSION['survey_' . $surveyid]['srid'];
        }
        // recompute $redata since $saved_id used to be a global
        $redata = compact(array_keys(get_defined_vars()));
        /*if ( $this->_didSessionTimeOut() )
          {
          // @TODO is this still required ?
          $asMessage = array(
          $clang->gT("Error"),
          $clang->gT("We are sorry but your session has expired."),
          $clang->gT("Either you have been inactive for too long, you have cookies disabled for your browser, or there were problems with your connection."),
          sprintf($clang->gT("Please contact %s ( %s ) for further assistance."),$thissurvey['adminname'],$thissurvey['adminemail'])
          );
          $this->_niceExit($redata, __LINE__, null, $asMessage);
          };*/
        // Set the language of the survey, either from POST, GET parameter of session var
        if (!empty($_REQUEST['lang'])) {
            $sTempLanguage = sanitize_languagecode($_REQUEST['lang']);
        } elseif (!empty($param['lang'])) {
            $sTempLanguage = sanitize_languagecode($param['lang']);
        } elseif (isset($_SESSION['survey_' . $surveyid]['s_lang'])) {
            $sTempLanguage = $_SESSION['survey_' . $surveyid]['s_lang'];
        } else {
            $sTempLanguage = '';
        }
        //CHECK FOR REQUIRED INFORMATION (sid)
        if ($surveyid && $surveyExists) {
            LimeExpressionManager::SetSurveyId($surveyid);
            // must be called early - it clears internal cache if a new survey is being used
            $clang = SetSurveyLanguage($surveyid, $sTempLanguage);
            UpdateSessionGroupList($surveyid, $sTempLanguage);
            // to refresh the language strings in the group list session variable
            UpdateFieldArray();
            // to refresh question titles and question text
        } else {
            if (!is_null($param['lang'])) {
                $sDisplayLanguage = $param['lang'];
            } else {
                $sDisplayLanguage = Yii::app()->getConfig('defaultlang');
            }
            $clang = $this->_loadLimesurveyLang($sDisplayLanguage);
            $languagechanger = makeLanguageChanger($sDisplayLanguage);
            //Find out if there are any publicly available surveys
            $query = "SELECT sid, surveyls_title, publicstatistics, language\n            FROM {{surveys}}\n            INNER JOIN {{surveys_languagesettings}}\n            ON ( surveyls_survey_id = sid  )\n            AND (surveyls_language=language)\n            WHERE\n            active='Y'\n            AND listpublic='Y'\n            AND ((expires >= '" . date("Y-m-d H:i") . "') OR (expires is null))\n            AND ((startdate <= '" . date("Y-m-d H:i") . "') OR (startdate is null))\n            ORDER BY surveyls_title";
            $result = dbExecuteAssoc($query, false, true) or safeDie("Could not connect to database. If you try to install LimeSurvey please refer to the <a href='http://docs.limesurvey.org'>installation docs</a> and/or contact the system administrator of this webpage.");
            //Checked
            $list = array();
            foreach ($result->readAll() as $rows) {
                $querylang = "SELECT surveyls_title\n                FROM {{surveys_languagesettings}}\n                WHERE surveyls_survey_id={$rows['sid']}\n                AND surveyls_language='{$sDisplayLanguage}'";
                $resultlang = Yii::app()->db->createCommand($querylang)->queryRow();
                if ($resultlang['surveyls_title']) {
                    $rows['surveyls_title'] = $resultlang['surveyls_title'];
                    $langtag = "";
                } else {
                    $langtag = "lang=\"{$rows['language']}\"";
                }
                $link = "<li><a href='" . $this->getController()->createUrl('/survey/index/sid/' . $rows['sid']);
                if (isset($param['lang']) && $langtag == "") {
                    $link .= "/lang-" . sanitize_languagecode($param['lang']);
                }
                $link .= "' {$langtag} class='surveytitle'>" . $rows['surveyls_title'] . "</a>\n";
                if ($rows['publicstatistics'] == 'Y') {
                    $link .= "<a href='" . $this->getController()->createUrl("/statistics_user/action/surveyid/" . $rows['sid']) . "/language/" . $sDisplayLanguage . "'>(" . $clang->gT('View statistics') . ")</a>";
                }
                $link .= "</li>\n";
                $list[] = $link;
            }
            //Check for inactive surveys which allow public registration.
            // TODO add a new template replace {SURVEYREGISTERLIST} ?
            $squery = "SELECT sid, surveyls_title, publicstatistics, language\n            FROM {{surveys}}\n            INNER JOIN {{surveys_languagesettings}}\n            ON (surveyls_survey_id = sid)\n            AND (surveyls_language=language)\n            WHERE allowregister='Y'\n            AND active='Y'\n            AND listpublic='Y'\n            AND ((expires >= '" . date("Y-m-d H:i") . "') OR (expires is null))\n            AND (startdate >= '" . date("Y-m-d H:i") . "')\n            ORDER BY surveyls_title";
            $sresult = dbExecuteAssoc($squery) or safeDie("Couldn't execute {$squery}");
            $aRows = $sresult->readAll();
            if (count($aRows) > 0) {
                $list[] = "</ul>" . " <div class=\"survey-list-heading\">" . $clang->gT("Following survey(s) are not yet active but you can register for them.") . "</div>" . " <ul>";
                // TODO give it to template
                foreach ($aRows as $rows) {
                    $querylang = "SELECT surveyls_title\n                    FROM {{surveys_languagesettings}}\n                    WHERE surveyls_survey_id={$rows['sid']}\n                    AND surveyls_language='{$sDisplayLanguage}'";
                    $resultlang = Yii::app()->db->createCommand($querylang)->queryRow();
                    if ($resultlang['surveyls_title']) {
                        $rows['surveyls_title'] = $resultlang['surveyls_title'];
                        $langtag = "";
                    } else {
                        $langtag = "lang=\"{$rows['language']}\"";
                    }
                    $link = "<li><a href=\"#\" id='inactivesurvey' onclick = 'sendreq(" . $rows['sid'] . ");' ";
                    //$link = "<li><a href=\"#\" id='inactivesurvey' onclick = 'convertGETtoPOST(".$this->getController()->createUrl('survey/send/')."?sid={$rows['sid']}&amp;)sendreq(".$rows['sid'].",".$rows['startdate'].",".$rows['expires'].");' ";
                    $link .= " {$langtag} class='surveytitle'>" . $rows['surveyls_title'] . "</a>\n";
                    $link .= "</li><div id='regform'></div>\n";
                    $list[] = $link;
                }
            }
            if (count($list) < 1) {
                $list[] = "<li class='surveytitle'>" . $clang->gT("No available surveys") . "</li>";
            }
            if (!$surveyid) {
                $thissurvey['name'] = Yii::app()->getConfig("sitename");
                $nosid = $clang->gT("You have not provided a survey identification number");
            } else {
                $thissurvey['name'] = $clang->gT("The survey identification number is invalid");
                $nosid = $clang->gT("The survey identification number is invalid");
            }
            $surveylist = array("nosid" => $nosid, "contact" => sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), Yii::app()->getConfig("siteadminname"), encodeEmail(Yii::app()->getConfig("siteadminemail"))), "listheading" => $clang->gT("The following surveys are available:"), "list" => implode("\n", $list));
            $data['thissurvey'] = $thissurvey;
            //$data['privacy'] = $privacy;
            $data['surveylist'] = $surveylist;
            $data['surveyid'] = $surveyid;
            $data['templatedir'] = getTemplatePath(Yii::app()->getConfig("defaulttemplate"));
            $data['templateurl'] = getTemplateURL(Yii::app()->getConfig("defaulttemplate")) . "/";
            $data['templatename'] = Yii::app()->getConfig("defaulttemplate");
            $data['sitename'] = Yii::app()->getConfig("sitename");
            $data['languagechanger'] = $languagechanger;
            //A nice exit
            sendCacheHeaders();
            doHeader();
            $this->_printTemplateContent(getTemplatePath(Yii::app()->getConfig("defaulttemplate")) . "/startpage.pstpl", $data, __LINE__);
            $this->_printTemplateContent(getTemplatePath(Yii::app()->getConfig("defaulttemplate")) . "/surveylist.pstpl", $data, __LINE__);
            echo '<script type="text/javascript" >
            function sendreq(surveyid)
            {

            $.ajax({
            type: "GET",
            url: "' . $this->getController()->createUrl("/register/ajaxregisterform/surveyid") . '/" + surveyid,
            }).done(function(msg) {
            document.getElementById("regform").innerHTML = msg;
            });
            }
            </script>';
            $this->_printTemplateContent(getTemplatePath(Yii::app()->getConfig("defaulttemplate")) . "/endpage.pstpl", $data, __LINE__);
            doFooter();
            exit;
        }
        // Get token
        if (!isset($token)) {
            $token = $clienttoken;
        }
        //GET BASIC INFORMATION ABOUT THIS SURVEY
        $thissurvey = getSurveyInfo($surveyid, $_SESSION['survey_' . $surveyid]['s_lang']);
        //SEE IF SURVEY USES TOKENS
        if ($surveyExists == 1 && tableExists('{{tokens_' . $thissurvey['sid'] . '}}')) {
            $tokensexist = 1;
        } else {
            $tokensexist = 0;
            unset($_POST['token']);
            unset($param['token']);
            unset($token);
            unset($clienttoken);
        }
        //SET THE TEMPLATE DIRECTORY
        $thistpl = getTemplatePath($thissurvey['templatedir']);
        $timeadjust = Yii::app()->getConfig("timeadjust");
        //MAKE SURE SURVEY HASN'T EXPIRED
        if ($thissurvey['expiry'] != '' and dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust) > $thissurvey['expiry'] && $thissurvey['active'] != 'N') {
            $redata = compact(array_keys(get_defined_vars()));
            $asMessage = array($clang->gT("Error"), $clang->gT("This survey is no longer available."), sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), $thissurvey['adminname'], $thissurvey['adminemail']));
            $this->_niceExit($redata, __LINE__, $thistpl, $asMessage);
        }
        //MAKE SURE SURVEY IS ALREADY VALID
        if ($thissurvey['startdate'] != '' and dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust) < $thissurvey['startdate'] && $thissurvey['active'] != 'N') {
            $redata = compact(array_keys(get_defined_vars()));
            $asMessage = array($clang->gT("Error"), $clang->gT("This survey is not yet started."), sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), $thissurvey['adminname'], $thissurvey['adminemail']));
            $this->_niceExit($redata, __LINE__, $thistpl, $asMessage);
        }
        //CHECK FOR PREVIOUSLY COMPLETED COOKIE
        //If cookies are being used, and this survey has been completed, a cookie called "PHPSID[sid]STATUS" will exist (ie: SID6STATUS) and will have a value of "COMPLETE"
        $sCookieName = "LS_" . $surveyid . "_STATUS";
        if (isset($_COOKIE[$sCookieName]) && $_COOKIE[$sCookieName] == "COMPLETE" && $thissurvey['usecookie'] == "Y" && $tokensexist != 1 && (!isset($param['newtest']) || $param['newtest'] != "Y")) {
            $redata = compact(array_keys(get_defined_vars()));
            $asMessage = array($clang->gT("Error"), $clang->gT("You have already completed this survey."), sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), $thissurvey['adminname'], $thissurvey['adminemail']));
            $this->_niceExit($redata, __LINE__, $thistpl, $asMessage);
        }
        if (isset($_GET['loadall']) && $_GET['loadall'] == "reload") {
            if (returnGlobal('loadname') && returnGlobal('loadpass')) {
                $_POST['loadall'] = "reload";
            }
        }
        //LOAD SAVED SURVEY
        if (isset($_POST['loadall']) && $_POST['loadall'] == "reload") {
            $errormsg = "";
            if (!isset($param['loadname']) || $param['loadname'] == null) {
                $errormsg .= $clang->gT("You did not provide a name") . "<br />\n";
            }
            if (!isset($param['loadpass']) || $param['loadpass'] == null) {
                $errormsg .= $clang->gT("You did not provide a password") . "<br />\n";
            }
            // if security question answer is incorrect
            // Not called if scid is set in GET params (when using email save/reload reminder URL)
            if (function_exists("ImageCreate") && isCaptchaEnabled('saveandloadscreen', $thissurvey['usecaptcha'])) {
                if ((!isset($_POST['loadsecurity']) || !isset($_SESSION['survey_' . $surveyid]['secanswer']) || $_POST['loadsecurity'] != $_SESSION['survey_' . $surveyid]['secanswer']) && !isset($_GET['scid'])) {
                    $errormsg .= $clang->gT("The answer to the security question is incorrect.") . "<br />\n";
                }
            }
            // Load session before loading the values from the saved data
            if (isset($_GET['loadall'])) {
                buildsurveysession($surveyid);
            }
            $_SESSION['survey_' . $surveyid]['holdname'] = $param['loadname'];
            //Session variable used to load answers every page.
            $_SESSION['survey_' . $surveyid]['holdpass'] = $param['loadpass'];
            //Session variable used to load answers every page.
            if ($errormsg == "") {
                loadanswers();
            }
            $move = "movenext";
            if ($errormsg) {
                $_POST['loadall'] = $clang->gT("Load unfinished survey");
            }
        }
        //Allow loading of saved survey
        if (isset($_POST['loadall']) && $_POST['loadall'] == $clang->gT("Load unfinished survey")) {
            $redata = compact(array_keys(get_defined_vars()));
            Yii::import("application.libraries.Load_answers");
            $tmp = new Load_answers();
            $tmp->run($redata);
        }
        //Check if TOKEN is used for EVERY PAGE
        //This function fixes a bug where users able to submit two surveys/votes
        //by checking that the token has not been used at each page displayed.
        // bypass only this check at first page (Step=0) because
        // this check is done in buildsurveysession and error message
        // could be more interresting there (takes into accound captcha if used)
        if ($tokensexist == 1 && isset($token) && $token && isset($_SESSION['survey_' . $surveyid]['step']) && $_SESSION['survey_' . $surveyid]['step'] > 0 && tableExists("tokens_{$surveyid}}}")) {
            //check if tokens actually haven't been already used
            $areTokensUsed = usedTokens(trim(strip_tags(returnGlobal('token'))), $surveyid);
            // check if token actually does exist
            // check also if it is allowed to change survey after completion
            if ($thissurvey['alloweditaftercompletion'] == 'Y') {
                $sQuery = "SELECT * FROM {{tokens_" . $surveyid . "}} WHERE token='" . $token . "'";
            } else {
                $sQuery = "SELECT * FROM {{tokens_" . $surveyid . "}} WHERE token='" . $token . "' AND (completed = 'N' or completed='')";
            }
            $aRow = Yii::app()->db->createCommand($sQuery)->queryRow();
            $tokendata = $aRow;
            if (!$aRow || $areTokensUsed && $thissurvey['alloweditaftercompletion'] != 'Y') {
                sendCacheHeaders();
                doHeader();
                //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT
                $redata = compact(array_keys(get_defined_vars()));
                $this->_printTemplateContent($thistpl . '/startpage.pstpl', $redata, __LINE__);
                $this->_printTemplateContent($thistpl . '/survey.pstpl', $redata, __LINE__);
                $asMessage = array(null, $clang->gT("This is a controlled survey. You need a valid token to participate."), sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname'] . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)"));
                $this->_niceExit($redata, __LINE__, $thistpl, $asMessage, true);
            }
        }
        if ($tokensexist == 1 && isset($token) && $token && tableExists("{{tokens_" . $surveyid . "}}")) {
            // check also if it is allowed to change survey after completion
            if ($thissurvey['alloweditaftercompletion'] == 'Y') {
                $tkquery = "SELECT * FROM {{tokens_" . $surveyid . "}} WHERE token='" . $token . "'";
            } else {
                $tkquery = "SELECT * FROM {{tokens_" . $surveyid . "}} WHERE token='" . $token . "' AND (completed = 'N' or completed='')";
            }
            $tkresult = dbExecuteAssoc($tkquery);
            //Checked
            $tokendata = $tkresult->read();
            if (isset($tokendata['validfrom']) && (trim($tokendata['validfrom']) != '' && $tokendata['validfrom'] > dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust)) || isset($tokendata['validuntil']) && (trim($tokendata['validuntil']) != '' && $tokendata['validuntil'] < dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust))) {
                sendCacheHeaders();
                doHeader();
                //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT
                $redata = compact(array_keys(get_defined_vars()));
                $this->_printTemplateContent($thistpl . '/startpage.pstpl', $redata, __LINE__);
                $this->_printTemplateContent($thistpl . '/survey.pstpl', $redata, __LINE__);
                $asMessage = array(null, $clang->gT("We are sorry but you are not allowed to enter this survey."), $clang->gT("Your token seems to be valid but can be used only during a certain time period."), sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname'] . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)"));
                $this->_niceExit($redata, __LINE__, $thistpl, $asMessage, true);
            }
        }
        //Clear session and remove the incomplete response if requested.
        if (isset($move) && $move == "clearall") {
            // delete the response but only if not already completed
            $s_lang = $_SESSION['survey_' . $surveyid]['s_lang'];
            if (isset($_SESSION['survey_' . $surveyid]['srid']) && !Survey_dynamic::model($surveyid)->isCompleted($_SESSION['survey_' . $surveyid]['srid'])) {
                // delete the response but only if not already completed
                $result = dbExecuteAssoc('DELETE FROM {{survey_' . $surveyid . '}} WHERE id=' . $_SESSION['survey_' . $surveyid]['srid'] . " AND submitdate IS NULL");
                if ($result->count() > 0) {
                    // Using count() here *should* be okay for MSSQL because it is a delete statement
                    // find out if there are any fuqt questions - checked
                    $fieldmap = createFieldMap($surveyid, 'short', false, false, $s_lang);
                    foreach ($fieldmap as $field) {
                        if ($field['type'] == "|" && !strpos($field['fieldname'], "_filecount")) {
                            if (!isset($qid)) {
                                $qid = array();
                            }
                            $qid[] = $field['fieldname'];
                        }
                    }
                    // if yes, extract the response json to those questions
                    if (isset($qid)) {
                        $query = "SELECT * FROM {{survey_" . $surveyid . "}} WHERE id=" . $_SESSION['survey_' . $surveyid]['srid'];
                        $result = dbExecuteAssoc($query);
                        foreach ($result->readAll() as $row) {
                            foreach ($qid as $question) {
                                $json = $row[$question];
                                if ($json == "" || $json == NULL) {
                                    continue;
                                }
                                // decode them
                                $phparray = json_decode($json);
                                foreach ($phparray as $metadata) {
                                    $target = Yii::app()->getConfig("uploaddir") . "/surveys/" . $surveyid . "/files/";
                                    // delete those files
                                    unlink($target . $metadata->filename);
                                }
                            }
                        }
                    }
                    // done deleting uploaded files
                }
                // also delete a record from saved_control when there is one
                dbExecuteAssoc('DELETE FROM {{saved_control}} WHERE srid=' . $_SESSION['survey_' . $surveyid]['srid'] . ' AND sid=' . $surveyid);
            }
            killSurveySession($surveyid);
            sendCacheHeaders();
            doHeader();
            $redata = compact(array_keys(get_defined_vars()));
            $this->_printTemplateContent($thistpl . '/startpage.pstpl', $redata, __LINE__);
            echo "\n\n<!-- JAVASCRIPT FOR CONDITIONAL QUESTIONS -->\n" . "\t<script type='text/javascript'>\n" . "\t<!--\n" . "function checkconditions(value, name, type, evt_type)\n" . "\t{\n" . "\t}\n" . "\t//-->\n" . "\t</script>\n\n";
            //Present the clear all page using clearall.pstpl template
            $this->_printTemplateContent($thistpl . '/clearall.pstpl', $redata, __LINE__);
            $this->_printTemplateContent($thistpl . '/endpage.pstpl', $redata, __LINE__);
            doFooter();
            exit;
        }
        //Check to see if a refering URL has been captured.
        if (!isset($_SESSION['survey_' . $surveyid]['refurl'])) {
            $_SESSION['survey_' . $surveyid]['refurl'] = GetReferringUrl();
            // do not overwrite refurl
        }
        // Let's do this only if
        //  - a saved answer record hasn't been loaded through the saved feature
        //  - the survey is not anonymous
        //  - the survey is active
        //  - a token information has been provided
        //  - the survey is setup to allow token-response-persistence
        if (!isset($_SESSION['survey_' . $surveyid]['srid']) && $thissurvey['anonymized'] == "N" && $thissurvey['active'] == "Y" && isset($token) && $token != '') {
            // load previous answers if any (dataentry with nosubmit)
            $sQuery = "SELECT id,submitdate,lastpage FROM {$thissurvey['tablename']} WHERE {$thissurvey['tablename']}.token='{$token}' order by id desc";
            $aRow = Yii::app()->db->createCommand($sQuery)->queryRow();
            if ($aRow) {
                if ($aRow['submitdate'] == '' && $thissurvey['tokenanswerspersistence'] == 'Y' || $aRow['submitdate'] != '' && $thissurvey['alloweditaftercompletion'] == 'Y') {
                    $_SESSION['survey_' . $surveyid]['srid'] = $aRow['id'];
                    if (!is_null($aRow['lastpage']) && $aRow['submitdate'] == '') {
                        $_SESSION['survey_' . $surveyid]['LEMtokenResume'] = true;
                        $_SESSION['survey_' . $surveyid]['step'] = $aRow['lastpage'];
                    }
                }
                buildsurveysession($surveyid);
                loadanswers();
            }
        }
        //        // SAVE POSTED ANSWERS TO DATABASE IF MOVE (NEXT,PREV,LAST, or SUBMIT) or RETURNING FROM SAVE FORM
        //        if (isset($move) || isset($_POST['saveprompt']))
        //        {
        //            $redata = compact(array_keys(get_defined_vars()));
        //            //save.php
        //            Yii::import("application.libraries.Save");
        //            $tmp = new Save();
        //            $tmp->run($redata);
        //
        //            // RELOAD THE ANSWERS INCASE SOMEONE ELSE CHANGED THEM
        //            if ($thissurvey['active'] == "Y" &&
        //            ( $thissurvey['allowsave'] == "Y" || $thissurvey['tokenanswerspersistence'] == "Y") )
        //            {
        //                loadanswers();
        //            }
        //        }
        if (isset($param['action']) && $param['action'] == 'previewgroup') {
            $thissurvey['format'] = 'G';
            buildsurveysession($surveyid, true);
        }
        if (isset($param['action']) && $param['action'] == 'previewquestion') {
            $thissurvey['format'] = 'S';
            buildsurveysession($surveyid, true);
        }
        sendCacheHeaders();
        //Send local variables to the appropriate survey type
        unset($redata);
        $redata = compact(array_keys(get_defined_vars()));
        Yii::import('application.helpers.SurveyRuntimeHelper');
        $tmp = new SurveyRuntimeHelper();
        $tmp->run($surveyid, $redata);
        if (isset($_POST['saveall']) || isset($flashmessage)) {
            echo "<script type='text/javascript'> \$(document).ready( function() { alert('" . $clang->gT("Your responses were successfully saved.", "js") . "');}) </script>";
        }
    }
Example #25
0
    							document.getElementById("closerecord").disabled=true;
    							document.getElementById("saveoptions").style.display="";
    							}
    						else
    							{
    							document.getElementById("saveoptions").style.display="none";
    							 document.getElementById("closerecord").disabled=false;
    							}
    						}
    				  //-->
    				  </script>
                <tr>
                <td colspan='3' align='center'>
                <table><tr><td align='left'>
                <input type='checkbox' class='checkboxbtn' name='closerecord' id='closerecord' checked='checked'/><label for='closerecord'><?php $clang->eT("Finalize response submission"); ?></label></td></tr>
                <input type='hidden' name='closedate' value='<?php echo dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $yii->getConfig('timeadjust')); ?>' />

                <?php if ($thissurvey['allowsave'] == "Y")
                { ?>

                    <tr><td align='left'><input type='checkbox' class='checkboxbtn' name='save' id='save' onclick='saveshow(this.id)' /><label for='save'><?php $clang->eT("Save for further completion by survey user"); ?></label>
                    </td></tr></table>
                    <div name='saveoptions' id='saveoptions' style='display: none'>
                    <table align='center' class='outlinetable'>
    					  <tr><td align='right'><?php $clang->eT("Identifier:"); ?></td>
    					  <td><input type='text' name='save_identifier' /></td></tr>
    					  <tr><td align='right'><?php $clang->eT("Password:"******"Confirm Password:"******"Email:"); ?></td>
 /**
  * Write values to database.
  * @param <type> $updatedValues
  * @param <boolean> $finished - true if the survey needs to be finalized
  */
 private function _UpdateValuesInDatabase($updatedValues, $finished = false)
 {
     //  TODO - now that using $this->updatedValues, may be able to remove local copies of it (unless needed by other sub-systems)
     $updatedValues = $this->updatedValues;
     $message = '';
     if (!$this->surveyOptions['active'] || $this->sPreviewMode) {
         return $message;
     }
     if (!isset($_SESSION[$this->sessid]['srid'])) {
         $_SESSION[$this->sessid]['datestamp'] = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $this->surveyOptions['timeadjust']);
         // Create initial insert row for this record
         $today = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $this->surveyOptions['timeadjust']);
         $sdata = array("startlanguage" => $this->surveyOptions['startlanguage']);
         if ($this->surveyOptions['anonymized'] == false) {
             $sdata['token'] = $this->surveyOptions['token'];
         }
         if ($this->surveyOptions['datestamp'] == true) {
             $sdata['datestamp'] = $_SESSION[$this->sessid]['datestamp'];
             $sdata['startdate'] = $_SESSION[$this->sessid]['datestamp'];
         }
         if ($this->surveyOptions['ipaddr'] == true) {
             $sdata['ipaddr'] = getIPAddress();
         }
         if ($this->surveyOptions['refurl'] == true) {
             if (isset($_SESSION[$this->sessid]['refurl'])) {
                 $sdata['refurl'] = $_SESSION[$this->sessid]['refurl'];
             } else {
                 $sdata['refurl'] = getenv("HTTP_REFERER");
             }
         }
         $sdata = array_filter($sdata);
         SurveyDynamic::sid($this->sid);
         $oSurvey = new SurveyDynamic();
         $iNewID = $oSurvey->insertRecords($sdata);
         if ($iNewID) {
             $srid = $iNewID;
             $_SESSION[$this->sessid]['srid'] = $iNewID;
         } else {
             $message .= $this->gT("Unable to insert record into survey table");
             // TODO - add SQL error?
             echo submitfailed('');
             // TODO - report SQL error?
         }
         //Insert Row for Timings, if needed
         if ($this->surveyOptions['savetimings']) {
             SurveyTimingDynamic::sid($this->sid);
             $oSurveyTimings = new SurveyTimingDynamic();
             $tdata = array('id' => $srid, 'interviewtime' => 0);
             switchMSSQLIdentityInsert("survey_{$this->sid}_timings", true);
             $iNewID = $oSurveyTimings->insertRecords($tdata);
             switchMSSQLIdentityInsert("survey_{$this->sid}_timings", false);
         }
     }
     if (count($updatedValues) > 0 || $finished) {
         $query = 'UPDATE ' . $this->surveyOptions['tablename'] . ' SET ';
         $setter = array();
         switch ($this->surveyMode) {
             case 'question':
                 $thisstep = $this->currentQuestionSeq;
                 break;
             case 'group':
                 $thisstep = $this->currentGroupSeq;
                 break;
             case 'survey':
                 $thisstep = 1;
                 break;
         }
         $setter[] = dbQuoteID('lastpage') . "=" . dbQuoteAll($thisstep);
         if ($this->surveyOptions['datestamp'] && isset($_SESSION[$this->sessid]['datestamp'])) {
             $_SESSION[$this->sessid]['datestamp'] = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $this->surveyOptions['timeadjust']);
             $setter[] = dbQuoteID('datestamp') . "=" . dbQuoteAll(dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $this->surveyOptions['timeadjust']));
         }
         if ($this->surveyOptions['ipaddr']) {
             $setter[] = dbQuoteID('ipaddr') . "=" . dbQuoteAll(getIPAddress());
         }
         foreach ($updatedValues as $key => $value) {
             $val = is_null($value) ? NULL : $value['value'];
             $type = is_null($value) ? NULL : $value['type'];
             // Clean up the values to cope with database storage requirements
             switch ($type) {
                 case 'D':
                     //DATE
                     if (trim($val) == '' || $val == "INVALID") {
                         $val = NULL;
                         // since some databases can't store blanks in date fields
                     }
                     // otherwise will already be in yyyy-mm-dd format after ProcessCurrentResponses()
                     break;
                 case '|':
                     //File upload
                     // This block can be removed once we require 5.3 or later
                     if (function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) {
                         $val = addslashes($val);
                     }
                     break;
                 case 'N':
                     //NUMERICAL QUESTION TYPE
                 //NUMERICAL QUESTION TYPE
                 case 'K':
                     //MULTIPLE NUMERICAL QUESTION
                     if (trim($val) == '') {
                         $val = NULL;
                         // since some databases can't store blanks in numerical inputs
                     }
                     break;
                 default:
                     break;
             }
             if (is_null($val)) {
                 $setter[] = dbQuoteID($key) . "=NULL";
             } else {
                 $setter[] = dbQuoteID($key) . "=" . dbQuoteAll($val);
             }
         }
         $query .= implode(', ', $setter);
         $query .= " WHERE ID=";
         if (isset($_SESSION[$this->sessid]['srid']) && $this->surveyOptions['active']) {
             $query .= $_SESSION[$this->sessid]['srid'];
             if (!dbExecuteAssoc($query)) {
                 echo submitfailed('');
                 // TODO - report SQL error?
                 if (($this->debugLevel & LEM_DEBUG_VALIDATION_SUMMARY) == LEM_DEBUG_VALIDATION_SUMMARY) {
                     $message .= $this->gT('Error in SQL update');
                     // TODO - add  SQL error?
                 }
             } elseif ($this->surveyOptions['savetimings']) {
                 Yii::import("application.libraries.Save");
                 $cSave = new Save();
                 $cSave->set_answer_time();
             }
             if ($finished) {
                 // Delete the save control record if successfully finalize the submission
                 $query = "DELETE FROM {{saved_control}} where srid=" . $_SESSION[$this->sessid]['srid'] . ' and sid=' . $this->sid;
                 Yii::app()->db->createCommand($query)->execute();
                 if (($this->debugLevel & LEM_DEBUG_VALIDATION_SUMMARY) == LEM_DEBUG_VALIDATION_SUMMARY) {
                     $message .= ';<br />' . $query;
                 }
             } else {
                 if ($this->surveyOptions['allowsave'] && isset($_SESSION[$this->sessid]['scid'])) {
                     SavedControl::model()->updateByPk($_SESSION[$this->sessid]['scid'], array('saved_thisstep' => $thisstep));
                 }
             }
             // Check Quotas
             $aQuotas = checkCompletedQuota($this->sid, 'return');
             if ($aQuotas && !empty($aQuotas)) {
                 checkCompletedQuota($this->sid);
                 // will create a page and quit: why not use it directly ?
             } else {
                 if ($finished) {
                     $sQuery = 'UPDATE ' . $this->surveyOptions['tablename'] . " SET ";
                     if ($this->surveyOptions['datestamp']) {
                         // Replace with date("Y-m-d H:i:s") ? See timeadjust
                         $sQuery .= dbQuoteID('submitdate') . "=" . dbQuoteAll(dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $this->surveyOptions['timeadjust']));
                     } else {
                         $sQuery .= dbQuoteID('submitdate') . "=" . dbQuoteAll(date("Y-m-d H:i:s", mktime(0, 0, 0, 1, 1, 1980)));
                     }
                     $sQuery .= " WHERE ID=" . $_SESSION[$this->sessid]['srid'];
                     dbExecuteAssoc($sQuery);
                     // Checked
                 }
             }
         }
         if (($this->debugLevel & LEM_DEBUG_VALIDATION_SUMMARY) == LEM_DEBUG_VALIDATION_SUMMARY) {
             $message .= $query;
         }
     }
     return $message;
 }
/**
* getSurveyList() Queries the database (survey table) for a list of existing surveys
*
* @param boolean $returnarray if set to true an array instead of an HTML option list is given back
* @return string This string is returned containing <option></option> formatted list of existing surveys
*
*/
function getSurveyList($returnarray = false, $surveyid = false)
{
    static $cached = null;
    $timeadjust = getGlobalSetting('timeadjust');
    App()->setLanguage(isset(Yii::app()->session['adminlang']) ? Yii::app()->session['adminlang'] : 'en');
    if (is_null($cached)) {
        $surveyidresult = Survey::model()->permission(Yii::app()->user->getId())->with('defaultlanguage')->findAll(array('order' => 'surveyls_title'));
        $surveynames = array();
        foreach ($surveyidresult as $result) {
            if (!empty($result->defaultlanguage)) {
                $surveynames[] = array_merge($result->attributes, $result->defaultlanguage->attributes);
            } elseif (empty($bCheckIntegrity)) {
                $bCheckIntegrity = true;
                Yii::app()->setFlashMessage(CHtml::link(gT("One or more surveys seem to be broken, please check data integrity of the LimeSurvey database."), array("admin/checkintegrity")), 'error');
            }
        }
        $cached = $surveynames;
    } else {
        $surveynames = $cached;
    }
    $surveyselecter = "";
    if ($returnarray === true) {
        return $surveynames;
    }
    $activesurveys = '';
    $inactivesurveys = '';
    $expiredsurveys = '';
    if ($surveynames) {
        foreach ($surveynames as $sv) {
            $surveylstitle = flattenText($sv['surveyls_title']);
            if (strlen($surveylstitle) > 45) {
                $surveylstitle = htmlspecialchars(mb_strcut(html_entity_decode($surveylstitle, ENT_QUOTES, 'UTF-8'), 0, 45, 'UTF-8')) . "...";
            }
            if ($sv['active'] != 'Y') {
                $inactivesurveys .= "<option ";
                if (Yii::app()->user->getId() == $sv['owner_id']) {
                    $inactivesurveys .= " class='mysurvey emphasis'";
                }
                if ($sv['sid'] == $surveyid) {
                    $inactivesurveys .= " selected='selected'";
                    $svexist = 1;
                }
                $inactivesurveys .= " value='{$sv['sid']}'>{$surveylstitle}</option>\n";
            } elseif ($sv['expires'] != '' && $sv['expires'] < dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust)) {
                $expiredsurveys .= "<option ";
                if (Yii::app()->user->getId() == $sv['owner_id']) {
                    $expiredsurveys .= " class='mysurvey emphasis'";
                }
                if ($sv['sid'] == $surveyid) {
                    $expiredsurveys .= " selected='selected'";
                    $svexist = 1;
                }
                $expiredsurveys .= " value='{$sv['sid']}'>{$surveylstitle}</option>\n";
            } else {
                $activesurveys .= "<option ";
                if (Yii::app()->user->getId() == $sv['owner_id']) {
                    $activesurveys .= " class='mysurvey emphasis'";
                }
                if ($sv['sid'] == $surveyid) {
                    $activesurveys .= " selected='selected'";
                    $svexist = 1;
                }
                $activesurveys .= " value='{$sv['sid']}'>{$surveylstitle}</option>\n";
            }
        }
        // End Foreach
    }
    //Only show each activesurvey group if there are some
    if ($activesurveys != '') {
        $surveyselecter .= "<optgroup label='" . gT("Active") . "' class='activesurveyselect'>\n";
        $surveyselecter .= $activesurveys . "</optgroup>";
    }
    if ($expiredsurveys != '') {
        $surveyselecter .= "<optgroup label='" . gT("Expired") . "' class='expiredsurveyselect'>\n";
        $surveyselecter .= $expiredsurveys . "</optgroup>";
    }
    if ($inactivesurveys != '') {
        $surveyselecter .= "<optgroup label='" . gT("Inactive") . "' class='inactivesurveyselect'>\n";
        $surveyselecter .= $inactivesurveys . "</optgroup>";
    }
    if (!isset($svexist)) {
        $surveyselecter = "<option selected='selected' value=''>" . gT("Please choose...") . "</option>\n" . $surveyselecter;
    } else {
        $surveyselecter = "<option value=''>" . gT("None") . "</option>\n" . $surveyselecter;
    }
    return $surveyselecter;
}
 /**
  * Shows admin menu for surveys
  * @param int Survey id
  */
 function _surveybar($iSurveyID, $gid = null)
 {
     //$this->load->helper('surveytranslator');
     $clang = $this->getController()->lang;
     //echo Yii::app()->getConfig('gid');
     $baselang = Survey::model()->findByPk($iSurveyID)->language;
     $condition = array('sid' => $iSurveyID, 'language' => $baselang);
     //$sumquery1 = "SELECT * FROM ".db_table_name('surveys')." inner join ".db_table_name('surveys_languagesettings')." on (surveyls_survey_id=sid and surveyls_language=language) WHERE sid=$iSurveyID"; //Getting data for this survey
     $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'] == 'Y';
     $js_admin_includes[] = Yii::app()->getConfig('generalscripts') . 'jquery/jquery.coookie.js';
     $js_admin_includes[] = Yii::app()->getConfig('generalscripts') . 'jquery/superfish.js';
     $js_admin_includes[] = Yii::app()->getConfig('generalscripts') . 'jquery/hoverIntent.js';
     $js_admin_includes[] = Yii::app()->getConfig('adminscripts') . 'surveytoolbar.js';
     $this->getController()->_js_admin_includes($js_admin_includes);
     //Parse data to send to view
     $aData['clang'] = $clang;
     $aData['surveyinfo'] = $surveyinfo;
     $aData['surveyid'] = $iSurveyID;
     // ACTIVATE SURVEY BUTTON
     $aData['activated'] = $activated;
     $condition = array('sid' => $iSurveyID, 'parent_qid' => 0, 'language' => $baselang);
     //$sumquery3 =  "SELECT * FROM ".db_table_name('questions')." WHERE sid={$iSurveyID} AND parent_qid=0 AND language='".$baselang."'"; //Getting a count of questions for this survey
     $sumresult3 = Questions::model()->findAllByAttributes($condition);
     //Checked
     $sumcount3 = count($sumresult3);
     $aData['canactivate'] = $sumcount3 > 0 && hasSurveyPermission($iSurveyID, 'surveyactivation', 'update');
     $aData['candeactivate'] = hasSurveyPermission($iSurveyID, 'surveyactivation', 'update');
     $aData['expired'] = $surveyinfo['expires'] != '' && $surveyinfo['expires'] < dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig('timeadjust'));
     $aData['notstarted'] = $surveyinfo['startdate'] != '' && $surveyinfo['startdate'] > dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig('timeadjust'));
     // Start of suckerfish menu
     // TEST BUTTON
     if (!$activated) {
         $aData['icontext'] = $clang->gT("Test this survey");
     } else {
         $aData['icontext'] = $clang->gT("Execute this survey");
     }
     $aData['baselang'] = Survey::model()->findByPk($iSurveyID)->language;
     $tmp_survlangs = Survey::model()->findByPk($iSurveyID)->getAdditionalLanguages();
     $aData['onelanguage'] = count($tmp_survlangs) == 0;
     $aData['additionallanguages'] = $tmp_survlangs;
     $tmp_survlangs[] = $aData['baselang'];
     rsort($tmp_survlangs);
     $aData['languagelist'] = $tmp_survlangs;
     $aData['hasadditionallanguages'] = count($aData['additionallanguages']) > 0;
     // EDIT SURVEY TEXT ELEMENTS BUTTON
     $aData['surveylocale'] = hasSurveyPermission($iSurveyID, 'surveylocale', 'read');
     // EDIT SURVEY SETTINGS BUTTON
     $aData['surveysettings'] = hasSurveyPermission($iSurveyID, 'surveysettings', 'read');
     // Survey permission item
     $aData['surveysecurity'] = Yii::app()->session['USER_RIGHT_SUPERADMIN'] == 1 || $surveyinfo['owner_id'] == Yii::app()->session['loginID'] || hasSurveyPermission($iSurveyID, 'surveysecurity', 'read');
     // CHANGE QUESTION GROUP ORDER BUTTON
     $aData['surveycontent'] = hasSurveyPermission($iSurveyID, 'surveycontent', 'read');
     $aData['groupsum'] = getGroupSum($iSurveyID, $surveyinfo['language']) > 1;
     // SET SURVEY QUOTAS BUTTON
     $aData['quotas'] = hasSurveyPermission($iSurveyID, 'quotas', 'read');
     // Assessment menu item
     $aData['assessments'] = hasSurveyPermission($iSurveyID, 'assessments', 'read');
     // EDIT SURVEY TEXT ELEMENTS BUTTON
     // End if survey properties
     // Tools menu item
     // Delete survey item
     $aData['surveydelete'] = hasSurveyPermission($iSurveyID, 'survey', 'delete');
     // Translate survey item
     $aData['surveytranslate'] = hasSurveyPermission($iSurveyID, 'translations', 'read');
     // RESET SURVEY LOGIC BUTTON
     //$sumquery6 = "SELECT count(*) FROM ".db_table_name('conditions')." as c, ".db_table_name('questions')." as q WHERE c.qid = q.qid AND q.sid=$iSurveyID"; //Getting a count of conditions for this survey
     // TMSW Conditions->Relevance:  How is conditionscount used?  Should Relevance do the same?
     $iConditionCount = Conditions::model()->with(array('questions' => array('condition' => 'sid =' . $iSurveyID)))->count();
     $aData['surveycontent'] = hasSurveyPermission($iSurveyID, 'surveycontent', 'update');
     $aData['conditionscount'] = $iConditionCount > 0;
     // Eport menu item
     $aData['surveyexport'] = hasSurveyPermission($iSurveyID, 'surveycontent', 'export');
     // PRINTABLE VERSION OF SURVEY BUTTON
     // SHOW PRINTABLE AND SCANNABLE VERSION OF SURVEY BUTTON
     //browse responses menu item
     $aData['respstatsread'] = hasSurveyPermission($iSurveyID, 'responses', 'read') || hasSurveyPermission($iSurveyID, 'statistics', 'read') || hasSurveyPermission($iSurveyID, 'responses', 'export');
     // Data entry screen menu item
     $aData['responsescreate'] = hasSurveyPermission($iSurveyID, 'responses', 'create');
     $aData['responsesread'] = hasSurveyPermission($iSurveyID, 'responses', 'read');
     // TOKEN MANAGEMENT BUTTON
     $aData['tokenmanagement'] = hasSurveyPermission($iSurveyID, 'surveysettings', 'update') || hasSurveyPermission($iSurveyID, 'tokens', 'read');
     $aData['gid'] = $gid;
     // = $this->input->post('gid');
     if (hasSurveyPermission($iSurveyID, 'surveycontent', 'read')) {
         $aData['permission'] = true;
     } else {
         $aData['gid'] = $gid = null;
         $qid = null;
         $aData['permission'] = false;
     }
     if (getGroupListLang($gid, $baselang, $iSurveyID)) {
         $aData['groups'] = getGroupListLang($gid, $baselang, $iSurveyID);
     } else {
         $aData['groups'] = "<option>" . $clang->gT("None") . "</option>";
     }
     $aData['GidPrev'] = $GidPrev = getGidPrevious($iSurveyID, $gid);
     $aData['GidNext'] = $GidNext = getGidNext($iSurveyID, $gid);
     $aData['iIconSize'] = Yii::app()->getConfig('adminthemeiconsize');
     $aData['sImageURL'] = Yii::app()->getConfig('adminimageurl');
     $this->getController()->render("/admin/survey/surveybar_view", $aData);
 }
Example #29
0
 /**
  * dataentry::insert()
  * insert new dataentry
  * @return
  */
 public function insert()
 {
     $clang = Yii::app()->lang;
     $subaction = Yii::app()->request->getPost('subaction');
     $surveyid = Yii::app()->request->getPost('sid');
     $lang = isset($_POST['lang']) ? Yii::app()->request->getPost('lang') : NULL;
     $aData = array('surveyid' => $surveyid, 'lang' => $lang, 'clang' => $clang);
     if (hasSurveyPermission($surveyid, 'responses', 'read')) {
         if ($subaction == "insert" && hasSurveyPermission($surveyid, 'responses', 'create')) {
             $surveytable = "{{survey_{$surveyid}}}";
             $thissurvey = getSurveyInfo($surveyid);
             $errormsg = "";
             Yii::app()->loadHelper("database");
             $aViewUrls['display']['menu_bars']['browse'] = $clang->gT("Data entry");
             $aDataentryoutput = '';
             $aDataentrymsgs = array();
             $hiddenfields = '';
             $lastanswfortoken = '';
             // check if a previous answer has been submitted or saved
             $rlanguage = '';
             if (isset($_POST['token'])) {
                 $tokencompleted = "";
                 $tcquery = "SELECT completed from {{tokens_{$surveyid}}} WHERE token='{$_POST['token']}'";
                 //dbQuoteAll($_POST['token'],true);
                 $tcresult = dbExecuteAssoc($tcquery);
                 $tcresult = $tcresult->readAll();
                 $tccount = count($tcresult);
                 foreach ($tcresult as $tcrow) {
                     $tokencompleted = $tcrow['completed'];
                 }
                 if ($tccount < 1) {
                     // token doesn't exist in token table
                     $lastanswfortoken = 'UnknownToken';
                 } elseif ($thissurvey['anonymized'] == "Y") {
                     // token exist but survey is anonymous, check completed state
                     if ($tokencompleted != "" && $tokencompleted != "N") {
                         // token is completed
                         $lastanswfortoken = 'PrivacyProtected';
                     }
                 } else {
                     // token is valid, survey not anonymous, try to get last recorded response id
                     $aquery = "SELECT id,startlanguage FROM {$surveytable} WHERE token='" . $_POST['token'] . "'";
                     //dbQuoteAll($_POST['token'],true);
                     $aresult = dbExecuteAssoc($aquery);
                     foreach ($aresult->readAll() as $arow) {
                         if ($tokencompleted != "N") {
                             $lastanswfortoken = $arow['id'];
                         }
                         $rlanguage = $arow['startlanguage'];
                     }
                 }
             }
             // First Check if the survey uses tokens and if a token has been provided
             if (tableExists('{{tokens_' . $thissurvey['sid'] . '}}') && !$_POST['token']) {
                 $errormsg = CHtml::tag('div', array('class' => 'warningheader'), $clang->gT("Error"));
                 $errormsg .= CHtml::tag('p', array(), $clang->gT("This is a closed-access survey, so you must supply a valid token.  Please contact the administrator for assistance."));
             } elseif (tableExists('{{tokens_' . $thissurvey['sid'] . '}}') && $lastanswfortoken == 'UnknownToken') {
                 $errormsg = CHtml::tag('div', array('class' => 'warningheader'), $clang->gT("Error"));
                 $errormsg .= CHtml::tag('p', array(), $clang->gT("The token you have provided is not valid or has already been used."));
             } elseif (tableExists('{{tokens_' . $thissurvey['sid'] . '}}') && $lastanswfortoken != '') {
                 $errormsg = CHtml::tag('div', array('class' => 'warningheader'), $clang->gT("Error"));
                 $errormsg .= CHtml::tag('p', array(), $clang->gT("There is already a recorded answer for this token"));
                 if ($lastanswfortoken != 'PrivacyProtected') {
                     $errormsg .= "<br /><br />" . $clang->gT("Follow the following link to update it") . ":\n";
                     $errormsg .= CHtml::link("[id:{$lastanswfortoken}]", Yii::app()->baseUrl . ('/admin/dataentry/editdata/subaction/edit/id/' . $lastanswfortoken . '/surveyid/' . $surveyid . '/lang/' . $rlanguage), array('title' => $clang->gT("Edit this entry")));
                 } else {
                     $errormsg .= "<br /><br />" . $clang->gT("This surveys uses anonymized responses, so you can't update your response.") . "\n";
                 }
             } else {
                 $last_db_id = 0;
                 if (isset($_POST['save']) && $_POST['save'] == "on") {
                     $aData['save'] = TRUE;
                     $saver['identifier'] = $_POST['save_identifier'];
                     $saver['language'] = $_POST['save_language'];
                     $saver['password'] = $_POST['save_password'];
                     $saver['passwordconfirm'] = $_POST['save_confirmpassword'];
                     $saver['email'] = $_POST['save_email'];
                     if (!returnGlobal('redo')) {
                         $password = md5($saver['password']);
                     } else {
                         $password = $saver['password'];
                     }
                     $errormsg = "";
                     if (!$saver['identifier']) {
                         $errormsg .= $clang->gT("Error") . ": " . $clang->gT("You must supply a name for this saved session.");
                     }
                     if (!$saver['password']) {
                         $errormsg .= $clang->gT("Error") . ": " . $clang->gT("You must supply a password for this saved session.");
                     }
                     if ($saver['password'] != $saver['passwordconfirm']) {
                         $errormsg .= $clang->gT("Error") . ": " . $clang->gT("Your passwords do not match.");
                     }
                     $aData['errormsg'] = $errormsg;
                     if ($errormsg) {
                         foreach ($_POST as $key => $val) {
                             if (substr($key, 0, 4) != "save" && $key != "action" && $key != "sid" && $key != "datestamp" && $key != "ipaddr") {
                                 $hiddenfields .= CHtml::hiddenField($key, $val);
                                 //$aDataentryoutput .= "<input type='hidden' name='$key' value='$val' />\n";
                             }
                         }
                     }
                 }
                 //BUILD THE SQL TO INSERT RESPONSES
                 $baselang = Survey::model()->findByPk($surveyid)->language;
                 $fieldmap = createFieldMap($surveyid, 'full', false, false, getBaseLanguageFromSurveyID($surveyid));
                 $insert_data = array();
                 $_POST['startlanguage'] = $baselang;
                 if ($thissurvey['datestamp'] == "Y") {
                     $_POST['startdate'] = $_POST['datestamp'];
                 }
                 if (isset($_POST['closerecord'])) {
                     if ($thissurvey['datestamp'] == "Y") {
                         $_POST['submitdate'] = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", Yii::app()->getConfig('timeadjust'));
                     } else {
                         $_POST['submitdate'] = date("Y-m-d H:i:s", mktime(0, 0, 0, 1, 1, 1980));
                     }
                 }
                 foreach ($fieldmap as $irow) {
                     $fieldname = $irow['fieldname'];
                     if (isset($_POST[$fieldname])) {
                         if ($_POST[$fieldname] == "" && ($irow['type'] == 'D' || $irow['type'] == 'N' || $irow['type'] == 'K')) {
                             // can't add '' in Date column
                             // Do nothing
                         } else {
                             if ($irow['type'] == '|') {
                                 if (!strpos($irow['fieldname'], "_filecount")) {
                                     $json = $_POST[$fieldname];
                                     $phparray = json_decode(stripslashes($json));
                                     $filecount = 0;
                                     for ($i = 0; $filecount < count($phparray); $i++) {
                                         if ($_FILES[$fieldname . "_file_" . $i]['error'] != 4) {
                                             $target = Yii::app()->getConfig('uploaddir') . "/surveys/" . $thissurvey['sid'] . "/files/" . randomChars(20);
                                             $size = 0.001 * $_FILES[$fieldname . "_file_" . $i]['size'];
                                             $name = rawurlencode($_FILES[$fieldname . "_file_" . $i]['name']);
                                             if (move_uploaded_file($_FILES[$fieldname . "_file_" . $i]['tmp_name'], $target)) {
                                                 $phparray[$filecount]->filename = basename($target);
                                                 $phparray[$filecount]->name = $name;
                                                 $phparray[$filecount]->size = $size;
                                                 $pathinfo = pathinfo($_FILES[$fieldname . "_file_" . $i]['name']);
                                                 $phparray[$filecount]->ext = $pathinfo['extension'];
                                                 $filecount++;
                                             }
                                         }
                                     }
                                     $insert_data[$fieldname] = ls_json_encode($phparray);
                                 } else {
                                     $insert_data[$fieldname] = count($phparray);
                                 }
                             } elseif ($irow['type'] == 'D') {
                                 Yii::app()->loadLibrary('Date_Time_Converter');
                                 $qidattributes = getQuestionAttributeValues($irow['qid'], $irow['type']);
                                 $dateformatdetails = getDateFormatDataForQID($qidattributes, $thissurvey);
                                 $datetimeobj = new Date_Time_Converter($_POST[$fieldname], $dateformatdetails['phpdate']);
                                 $insert_data[$fieldname] = $datetimeobj->convert("Y-m-d H:i:s");
                             } else {
                                 $insert_data[$fieldname] = $_POST[$fieldname];
                             }
                         }
                     }
                 }
                 Survey_dynamic::sid($surveyid);
                 $new_response = new Survey_dynamic();
                 foreach ($insert_data as $column => $value) {
                     $new_response->{$column} = $value;
                 }
                 $new_response->save();
                 $last_db_id = $new_response->getPrimaryKey();
                 if (isset($_POST['closerecord']) && isset($_POST['token']) && $_POST['token'] != '') {
                     // get submit date
                     if (isset($_POST['closedate'])) {
                         $submitdate = $_POST['closedate'];
                     } else {
                         $submitdate = dateShift(date("Y-m-d H:i:s"), "Y-m-d", $timeadjust);
                     }
                     // check how many uses the token has left
                     $usesquery = "SELECT usesleft FROM {{tokens_}}{$surveyid} WHERE token='" . $_POST['token'] . "'";
                     $usesresult = dbExecuteAssoc($usesquery);
                     $usesrow = $usesresult->readAll();
                     //$usesresult->row_array()
                     if (isset($usesrow)) {
                         $usesleft = $usesrow[0]['usesleft'];
                     }
                     // query for updating tokens
                     $utquery = "UPDATE {{tokens_{$surveyid}}}\n";
                     if (isTokenCompletedDatestamped($thissurvey)) {
                         if (isset($usesleft) && $usesleft <= 1) {
                             $utquery .= "SET usesleft=usesleft-1, completed='{$submitdate}'\n";
                         } else {
                             $utquery .= "SET usesleft=usesleft-1\n";
                         }
                     } else {
                         if (isset($usesleft) && $usesleft <= 1) {
                             $utquery .= "SET usesleft=usesleft-1, completed='Y'\n";
                         } else {
                             $utquery .= "SET usesleft=usesleft-1\n";
                         }
                     }
                     $utquery .= "WHERE token='" . $_POST['token'] . "'";
                     $utresult = dbExecuteAssoc($utquery);
                     //Yii::app()->db->Execute($utquery) or safeDie ("Couldn't update tokens table!<br />\n$utquery<br />\n".Yii::app()->db->ErrorMsg());
                     // save submitdate into survey table
                     $srid = Yii::app()->db->getLastInsertID();
                     // Yii::app()->db->getLastInsertID();
                     $sdquery = "UPDATE {{survey_{$surveyid}}} SET submitdate='" . $submitdate . "' WHERE id={$srid}\n";
                     $sdresult = dbExecuteAssoc($sdquery) or safeDie("Couldn't set submitdate response in survey table!<br />\n{$sdquery}<br />\n");
                     $last_db_id = Yii::app()->db->getLastInsertID();
                 }
                 if (isset($_POST['save']) && $_POST['save'] == "on") {
                     $srid = Yii::app()->db->getLastInsertID();
                     //Yii::app()->db->getLastInsertID();
                     $aUserData = Yii::app()->session;
                     //CREATE ENTRY INTO "saved_control"
                     $saved_control_table = '{{saved_control}}';
                     $columns = array("sid", "srid", "identifier", "access_code", "email", "ip", "refurl", 'saved_thisstep', "status", "saved_date");
                     $values = array("'" . $surveyid . "'", "'" . $srid . "'", "'" . $saver['identifier'] . "'", "'" . $password . "'", "'" . $saver['email'] . "'", "'" . $aUserData['ip_address'] . "'", "'" . getenv("HTTP_REFERER") . "'", 0, "'" . "S" . "'", "'" . dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", "'" . Yii::app()->getConfig('timeadjust')) . "'");
                     $SQL = "INSERT INTO {$saved_control_table}\n                        (" . implode(',', $columns) . ")\n                        VALUES\n                        (" . implode(',', $values) . ")";
                     /*$scdata = array("sid"=>$surveyid,
                       "srid"=>$srid,
                       "identifier"=>$saver['identifier'],
                       "access_code"=>$password,
                       "email"=>$saver['email'],
                       "ip"=>$aUserData['ip_address'],
                       "refurl"=>getenv("HTTP_REFERER"),
                       'saved_thisstep' => 0,
                       "status"=>"S",
                       "saved_date"=>dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", Yii::app()->getConfig('timeadjust')));
                       $this->load->model('saved_control_model');*/
                     if (dbExecuteAssoc($SQL)) {
                         $scid = Yii::app()->db->getLastInsertID();
                         // Yii::app()->db->getLastInsertID("{{saved_control}}","scid");
                         $aDataentrymsgs[] = CHtml::tag('font', array('class' => 'successtitle'), $clang->gT("Your survey responses have been saved successfully.  You will be sent a confirmation e-mail. Please make sure to save your password, since we will not be able to retrieve it for you."));
                         //$aDataentryoutput .= "<font class='successtitle'></font><br />\n";
                         $tokens_table = "{{tokens_{$surveyid}}}";
                         $last_db_id = Yii::app()->db->getLastInsertID();
                         if (tableExists($tokens_table)) {
                             $tkquery = "SELECT * FROM {$tokens_table}";
                             $tkresult = dbExecuteAssoc($tkquery);
                             /*$tokendata = array (
                               "firstname"=> $saver['identifier'],
                               "lastname"=> $saver['identifier'],
                               "email"=>$saver['email'],
                               "token"=>randomChars(15),
                               "language"=>$saver['language'],
                               "sent"=>dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", $timeadjust),
                               "completed"=>"N");*/
                             $columns = array("firstname", "lastname", "email", "token", "language", "sent", "completed");
                             $values = array("'" . $saver['identifier'] . "'", "'" . $saver['identifier'] . "'", "'" . $saver['email'] . "'", "'" . $password . "'", "'" . randomChars(15) . "'", "'" . $saver['language'] . "'", "'" . "N" . "'");
                             $SQL = "INSERT INTO {$token_table}\n                                (" . implode(',', $columns) . ")\n                                VALUES\n                                (" . implode(',', $values) . ")";
                             //$this->tokens_dynamic_model->insertToken($surveyid,$tokendata);
                             dbExecuteAssoc($SQL);
                             //Yii::app()->db->AutoExecute(db_table_name("tokens_".$surveyid), $tokendata,'INSERT');
                             $aDataentrymsgs[] = CHtml::tag('font', array('class' => 'successtitle'), $clang->gT("A token entry for the saved survey has been created too."));
                             //$aDataentryoutput .= "<font class='successtitle'></font><br />\n";
                             $last_db_id = Yii::app()->db->getLastInsertID();
                         }
                         if ($saver['email']) {
                             //Send email
                             if (validateEmailAddress($saver['email']) && !returnGlobal('redo')) {
                                 $subject = $clang->gT("Saved Survey Details");
                                 $message = $clang->gT("Thank you for saving your survey in progress.  The following details can be used to return to this survey and continue where you left off.  Please keep this e-mail for your reference - we cannot retrieve the password for you.");
                                 $message .= "\n\n" . $thissurvey['name'] . "\n\n";
                                 $message .= $clang->gT("Name") . ": " . $saver['identifier'] . "\n";
                                 $message .= $clang->gT("Password") . ": " . $saver['password'] . "\n\n";
                                 $message .= $clang->gT("Reload your survey by clicking on the following link (or pasting it into your browser):") . ":\n";
                                 $message .= Yii::app()->getConfig('publicurl') . "/index.php?sid={$surveyid}&loadall=reload&scid=" . $scid . "&lang=" . urlencode($saver['language']) . "&loadname=" . urlencode($saver['identifier']) . "&loadpass="******"&token=" . $tokendata['token'];
                                 }
                                 $from = $thissurvey['adminemail'];
                                 if (SendEmailMessage($message, $subject, $saver['email'], $from, $sitename, false, getBounceEmail($surveyid))) {
                                     $emailsent = "Y";
                                     $aDataentrymsgs[] = CHtml::tag('font', array('class' => 'successtitle'), $clang->gT("An email has been sent with details about your saved survey"));
                                 }
                             }
                         }
                     } else {
                         safeDie("Unable to insert record into saved_control table.<br /><br />");
                     }
                 }
                 $aData['thisid'] = $last_db_id;
             }
             $aData['errormsg'] = $errormsg;
             $aData['dataentrymsgs'] = $aDataentrymsgs;
             $this->_renderWrappedTemplate('dataentry', 'insert', $aData);
         }
     }
 }
Example #30
0
 function step3()
 {
     $clang = $this->getController()->lang;
     $buildnumber = Yii::app()->getConfig("buildnumber");
     $tempdir = Yii::app()->getConfig("tempdir");
     $updatebuild = getGlobalSetting("updatebuild");
     //$_POST=$this->input->post();
     $rootdir = Yii::app()->getConfig("rootdir");
     $publicdir = Yii::app()->getConfig("publicdir");
     $tempdir = Yii::app()->getConfig("tempdir");
     $aDatabasetype = Yii::app()->db->getDriverName();
     $aData = array('clang' => $clang);
     // Request the list with changed files from the server
     if (!isset(Yii::app()->session['updateinfo'])) {
         if ($updateinfo['error'] == 1) {
         }
     } else {
         $updateinfo = Yii::app()->session['updateinfo'];
     }
     $aData['updateinfo'] = $updateinfo;
     // okay, updateinfo now contains all necessary updateinformation
     // Create DB and file backups now
     $basefilename = dateShift(date("Y-m-d H:i:s"), "Y-m-d", Yii::app()->getConfig('timeadjust')) . '_' . md5(uniqid(rand(), true));
     //Now create a backup of the files to be delete or modified
     $filestozip = array();
     foreach ($updateinfo['files'] as $file) {
         if (is_file($publicdir . $file['file']) === true) {
             $filestozip[] = $publicdir . $file['file'];
         }
     }
     Yii::app()->loadLibrary("admin/pclzip");
     $archive = new PclZip($tempdir . DIRECTORY_SEPARATOR . 'LimeSurvey_files_backup_' . $basefilename . '.zip');
     $v_list = $archive->add($filestozip, PCLZIP_OPT_REMOVE_PATH, $publicdir);
     if ($v_list == 0) {
         $aFileBackup = array('class' => 'error', 'text' => sprintf($clang->gT("Error on file backup: %s"), $archive->errorInfo(true)));
     } else {
         $aFileBackup = array('class' => 'success', 'text' => sprintf($clang->gT("File backup created: %s"), $tempdir . DIRECTORY_SEPARATOR . 'LimeSurvey_files_backup_' . $basefilename . '.zip'));
     }
     $aData['aFileBackup'] = $aFileBackup;
     $aData['databasetype'] = $aDatabasetype;
     //TODO: Yii provides no function to backup the database. To be done after dumpdb is ported
     if (in_array($aDatabasetype, array('mysql', 'mysqli'))) {
         if (in_array($aDatabasetype, array('mysql', 'mysqli')) && Yii::app()->getConfig('demoMode') != true) {
             Yii::app()->loadHelper("admin/backupdb");
             $sfilename = $tempdir . DIRECTORY_SEPARATOR . "backup_db_" . randomChars(20) . "_" . dateShift(date("Y-m-d H:i:s"), "Y-m-d", Yii::app()->getConfig('timeadjust')) . ".sql";
             $dfilename = $tempdir . DIRECTORY_SEPARATOR . "LimeSurvey_database_backup_" . $basefilename . ".zip";
             outputDatabase('', false, $sfilename);
             // Before try to zip: test size of file
             if (is_file($sfilename) && filesize($sfilename)) {
                 $archive = new PclZip($dfilename);
                 $v_list = $archive->add(array($sfilename), PCLZIP_OPT_REMOVE_PATH, $tempdir, PCLZIP_OPT_ADD_TEMP_FILE_ON);
                 unlink($sfilename);
                 if ($v_list == 0) {
                     // Unknow reason because backup of DB work ?
                     $aSQLBackup = array('class' => 'warning', 'text' => $clang->gT("Unable to backup your database for unknow reason. Before proceeding please backup your database using a backup tool!"));
                 } else {
                     $aSQLBackup = array('class' => 'success', 'text' => sprintf($clang->gT('DB backup created: %s'), htmlspecialchars($dfilename)));
                 }
             } else {
                 $aSQLBackup = array('class' => 'warning', 'text' => $clang->gT("Unable to backup your database for unknow reason. Before proceeding please backup your database using a backup tool!"));
             }
         }
     } else {
         $aSQLBackup = array('class' => 'warning', 'text' => $clang->gT('Database backup functionality is currently not available for your database type. Before proceeding please backup your database using a backup tool!'));
     }
     $aData['aSQLBackup'] = $aSQLBackup;
     if ($aFileBackup['class'] == "success" && $aSQLBackup['class'] == "success") {
         $aData['result'] = "success";
     } elseif ($aFileBackup['class'] == "error" || $aSQLBackup['class'] == "error") {
         $aData['result'] = "error";
     } else {
         $aData['result'] = "warning";
     }
     $this->_renderWrappedTemplate('update', 'step3', $aData);
 }