/**
  *  提交消息信息
  */
 public function actionPostNoticeReturn()
 {
     if (!isset($_REQUEST['userId']) || !isset($_REQUEST['token']) || !isset($_REQUEST['noticeId']) || !isset($_REQUEST['status'])) {
         $this->_return('MSG_ERR_LESS_PARAM');
     }
     $user_id = trim(Yii::app()->request->getParam('userId'));
     $token = trim(Yii::app()->request->getParam('token'));
     $noticeId = trim(Yii::app()->request->getParam('noticeId'));
     $status = trim(Yii::app()->request->getParam('status'));
     if (!ctype_digit($user_id) || $user_id < 1) {
         $this->_return('MSG_ERR_NO_USER');
     }
     if (!ctype_digit($noticeId) || $noticeId < 1 || !Notice::model()->isExistNoticeId($noticeId, $user_id)) {
         $this->_return('MSG_ERR_FAIL_NOTICE');
     }
     if (!ctype_digit($status) || !in_array($status, array(1, 2, 3, 4))) {
         $this->_return('MSG_ERR_FAIL_NOTICE_STATUS');
     }
     // 验证token
     if (Token::model()->verifyToken($user_id, $token)) {
         $data = Notice::model()->postNoticeReturn($noticeId, $status);
         $this->_return('MSG_SUCCESS', $data);
     } else {
         $this->_return('MSG_ERR_TOKEN');
     }
 }
 /**
  * 日历课程接口
  */
 public function actionGetSubjectSchedule()
 {
     if (!isset($_REQUEST['teacherId']) || !isset($_REQUEST['token']) || !isset($_REQUEST['date'])) {
         $this->_return('MSG_ERR_LESS_PARAM');
     }
     $user_id = trim(Yii::app()->request->getParam('teacherId', null));
     $token = trim(Yii::app()->request->getParam('token', null));
     $date = trim(Yii::app()->request->getParam('date', null));
     if (!ctype_digit($user_id)) {
         $this->_return('MSG_ERR_FAIL_PARAM');
     }
     // 用户名不存在,返回错误
     if ($user_id < 1) {
         $this->_return('MSG_ERR_NO_USER');
     }
     // 验证日期格式合法
     if (!$this->isDate($date)) {
         $this->_return('MSG_ERR_FAIL_DATE_FORMAT');
     }
     $year = mb_substr($date, 0, 4, 'utf8');
     $month = mb_substr($date, 5, 2, 'utf8');
     $day = mb_substr($date, 8, 2, 'utf8');
     if (empty($year) || empty($month) || empty($day)) {
         $this->_return('MSG_ERR_FAIL_DATE_LESS');
     }
     // 验证token
     if (Token::model()->verifyToken($user_id, $token)) {
         // 获取日历课程
         $data = Lesson::model()->getSubjectSchedule($user_id, $year, $month, $day, $date);
         $this->_return('MSG_SUCCESS', $data);
     } else {
         $this->_return('MSG_ERR_TOKEN');
     }
 }
 /**
  * 获取学员详细信息
  */
 public function actionGetStudentInfo()
 {
     if (!isset($_REQUEST['teacherId']) || !isset($_REQUEST['token']) || !isset($_REQUEST['studentId'])) {
         $this->_return('MSG_ERR_LESS_PARAM');
     }
     $user_id = trim(Yii::app()->request->getParam('teacherId', null));
     $token = trim(Yii::app()->request->getParam('token', null));
     $studentId = trim(Yii::app()->request->getParam('studentId', null));
     if (!ctype_digit($user_id)) {
         $this->_return('MSG_ERR_FAIL_PARAM');
     }
     //用户名不存在,返回错误
     if ($user_id < 1) {
         $this->_return('MSG_ERR_NO_USER');
     }
     if (empty($studentId) || $studentId <= 0) {
         $this->_return('MSG_ERR_FAIL_STUDENT');
     }
     // 验证token
     if (Token::model()->verifyToken($user_id, $token)) {
         // 获取学员详细信息
         $data = Student::model()->getStudentInfo($studentId);
         if (!$data) {
             $this->_return('MSG_NO_STUDENT');
         }
         $this->_return('MSG_SUCCESS', $data);
     } else {
         $this->_return('MSG_ERR_TOKEN');
     }
 }
 public function beforeAction($action)
 {
     $must_no_token_action = array('checkkey', 'resetpassword', 'lostpassword', 'getcourier', 'setdriverlocation', 'getcountry', 'uploadbarang', 'logindriver', 'login', 'register', 'logout', 'checkawb', 'suggestarea', 'suggestpostal', 'suggestdistrict', 'insertlocation');
     $can_no_token_action = array('getRates', 'requestOrder', 'getGroceryRate', 'requestPickUp');
     if (in_array($action->getId(), $must_no_token_action)) {
     } else {
         if (in_array($action->getId(), $can_no_token_action)) {
             if (isset($_REQUEST['key'])) {
                 $key = $_REQUEST['key'];
                 $token = Token::model()->findByAttributes(array('token' => $key));
                 if (!$token instanceof Token) {
                     echo CJSON::encode($this->statusError('wrong authentication key'));
                     Yii::app()->end();
                 }
                 $this->token = $token;
                 $customer = Customer::model()->findByPk($token->customer_id, 'is_allow_api = 1');
                 if (!$customer instanceof Customer) {
                     echo CJSON::encode($this->statusError('you\'re not permitted to this action'));
                     Yii::app()->end();
                 }
             }
         } else {
             if (!isset($_REQUEST['key'])) {
                 echo CJSON::encode($this->statusError('Key not found'));
                 Yii::app()->end();
             }
             $key = $_REQUEST['key'];
             if (!isset($key)) {
                 echo CJSON::encode($this->statusError('Please insert token'));
                 Yii::app()->end();
             }
             $token = Token::model()->findByAttributes(array('token' => $key));
             if ($token == null) {
                 echo CJSON::encode($this->statusError('Token Error'));
                 Yii::app()->end();
             } else {
                 $this->token = $token;
             }
             $token = Token::model()->findByAttributes(array('token' => $key));
             if (!$token instanceof Token) {
                 echo CJSON::encode($this->statusError('wrong authentication key'));
                 Yii::app()->end();
             }
             $this->token = $token;
             $customer = Customer::model()->findByPk($token->customer_id, 'is_allow_api = 1');
             if (!$customer instanceof Customer) {
                 echo CJSON::encode($this->statusError('you\'re not permitted to this action'));
                 Yii::app()->end();
             }
         }
     }
     return parent::beforeAction($action);
 }
 function actiontokens($surveyid, $token, $langcode = '')
 {
     Yii::app()->loadHelper('database');
     Yii::app()->loadHelper('sanitize');
     $sLanguageCode = $langcode;
     $iSurveyID = $surveyid;
     $sToken = $token;
     $sToken = sanitize_token($sToken);
     if (!$iSurveyID) {
         $this->redirect(array('/'));
     }
     $iSurveyID = (int) $iSurveyID;
     //Check that there is a SID
     // Get passed language from form, so that we dont loose this!
     if (!isset($sLanguageCode) || $sLanguageCode == "" || !$sLanguageCode) {
         $sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language;
         Yii::import('application.libraries.Limesurvey_lang', true);
         $clang = new Limesurvey_lang($sBaseLanguage);
     } else {
         $sLanguageCode = sanitize_languagecode($sLanguageCode);
         Yii::import('application.libraries.Limesurvey_lang', true);
         $clang = new Limesurvey_lang($sLanguageCode);
         $sBaseLanguage = $sLanguageCode;
     }
     Yii::app()->lang = $clang;
     $aSurveyInfo = getSurveyInfo($iSurveyID, $sBaseLanguage);
     if ($aSurveyInfo == false || !tableExists("{{tokens_{$iSurveyID}}}")) {
         $sMessage = $clang->gT('This survey does not seem to exist.');
     } else {
         $oToken = Token::model($iSurveyID)->findByAttributes(array('token' => $token));
         if (!isset($oToken)) {
             $sMessage = $clang->gT('You are not a participant in this survey.');
         } else {
             if ($oToken->emailstatus == 'OptOut') {
                 $oToken->emailstatus = 'OK';
                 $oToken->save();
                 $sMessage = $clang->gT('You have been successfully added back to this survey.');
             } elseif ($oToken->emailstatus == 'OK') {
                 $sMessage = $clang->gT('You are already a part of this survey.');
             } else {
                 $sMessage = $clang->gT('You have been already removed from this survey.');
             }
         }
     }
     //PRINT COMPLETED PAGE
     if (!$aSurveyInfo['templatedir']) {
         $sTemplate = getTemplatePath(Yii::app()->getConfig("defaulttemplate"));
     } else {
         $sTemplate = getTemplatePath($aSurveyInfo['templatedir']);
     }
     $this->_renderHtml($sMessage, $sTemplate, $clang, $aSurveyInfo);
 }
 function actiontokens($surveyid, $token, $langcode = '')
 {
     Yii::app()->loadHelper('database');
     Yii::app()->loadHelper('sanitize');
     $sLanguageCode = $langcode;
     $iSurveyID = $surveyid;
     $sToken = $token;
     $sToken = sanitize_token($sToken);
     if (!$iSurveyID) {
         $this->redirect(array('/'));
     }
     $iSurveyID = (int) $iSurveyID;
     //Check that there is a SID
     // Get passed language from form, so that we dont loose this!
     if (!isset($sLanguageCode) || $sLanguageCode == "" || !$sLanguageCode) {
         $sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language;
     } else {
         $sBaseLanguage = sanitize_languagecode($sLanguageCode);
     }
     Yii::app()->setLanguage($sBaseLanguage);
     $aSurveyInfo = getSurveyInfo($iSurveyID, $sBaseLanguage);
     if ($aSurveyInfo == false || !tableExists("{{tokens_{$iSurveyID}}}")) {
         throw new CHttpException(404, "This survey does not seem to exist. It may have been deleted or the link you were given is outdated or incorrect.");
     } else {
         LimeExpressionManager::singleton()->loadTokenInformation($iSurveyID, $token, false);
         $oToken = Token::model($iSurveyID)->findByAttributes(array('token' => $token));
         if (!isset($oToken)) {
             $sMessage = gT('You are not a participant in this survey.');
         } else {
             if ($oToken->emailstatus == 'OptOut') {
                 $oToken->emailstatus = 'OK';
                 $oToken->save();
                 $sMessage = gT('You have been successfully added back to this survey.');
             } elseif ($oToken->emailstatus == 'OK') {
                 $sMessage = gT('You are already a part of this survey.');
             } else {
                 $sMessage = gT('You have been already removed from this survey.');
             }
         }
     }
     //PRINT COMPLETED PAGE
     if (!$aSurveyInfo['templatedir']) {
         $sTemplate = getTemplatePath(Yii::app()->getConfig("defaulttemplate"));
     } else {
         $sTemplate = getTemplatePath($aSurveyInfo['templatedir']);
     }
     $this->_renderHtml($sMessage, $sTemplate, $aSurveyInfo);
 }
 public static function getUser()
 {
     $headers = apache_request_headers();
     if (!isset($headers['Authorization'])) {
         Helper::renderJSONErorr("Authorization is required");
     }
     $auth = $headers['Authorization'];
     $access_token = explode(' ', $auth);
     $access_token = end($access_token);
     $token = Token::model()->find('token=:token', array(':token' => $access_token));
     if (!$token) {
         Helper::renderJSONErorr("Bad access_token");
     }
     $user = User::model()->find('id=:id', array(':id' => $token->user));
     return $user;
 }
 /**
  * 获取学员详细信息
  */
 public function actionGetStudentInfo()
 {
     if (!isset($_REQUEST['userId']) || !isset($_REQUEST['token']) || !isset($_REQUEST['memberId'])) {
         $this->_return('MSG_ERR_LESS_PARAM');
     }
     $user_id = trim(Yii::app()->request->getParam('userId', null));
     $token = trim(Yii::app()->request->getParam('token', null));
     $memberId = trim(Yii::app()->request->getParam('memberId', null));
     // 用户ID格式错误
     if (!ctype_digit($user_id)) {
         $this->_return('MSG_ERR_FAIL_USER');
     }
     // 用户不存在,返回错误
     if ($user_id < 1) {
         $this->_return('MSG_ERR_NO_USER');
     }
     if (empty($memberId) || $memberId <= 0) {
         $this->_return('MSG_ERR_FAIL_STUDENT');
     }
     // 验证要添加的memberId是否和userId有绑定关系存在
     $existMemberId = User::model()->existUserIdMemberId($user_id, $memberId);
     if (!$existMemberId) {
         $this->_return('MSG_ERR_FAIL_MEMBER');
     }
     // 验证token
     if (Token::model()->verifyToken($user_id, $token)) {
         // 获取学员详细信息
         $data = Student::model()->getStudentInfo($memberId);
         if (!$data) {
             $this->_return('MSG_NO_MEMBER');
         }
         // 增加用户操作log
         $action_id = 2301;
         $params = '';
         foreach ($_REQUEST as $key => $value) {
             $params .= $key . '=' . $value . '&';
         }
         $params = substr($params, 0, -1);
         Log::model()->action_log($user_id, $action_id, $params);
         $this->_return('MSG_SUCCESS', $data);
     } else {
         $this->_return('MSG_ERR_TOKEN');
     }
 }
 /**
  * 拒绝/接受 好友邀请
  *
  * @param string $user_id
  * @param string $token
  * @param string $friend_id
  * @param string $status   1-已确认, 2-拒绝, 3-取消
  */
 public function actionInviting()
 {
     // 参数检查
     if (!isset($_REQUEST['user_id']) || !isset($_REQUEST['token']) || !isset($_REQUEST['friend_id']) || !isset($_REQUEST['status'])) {
         $this->_return('MSG_ERR_LESS_PARAM');
     }
     $user_id = trim(Yii::app()->request->getParam('user_id'));
     $token = trim(Yii::app()->request->getParam('token'));
     $status = trim(Yii::app()->request->getParam('status'));
     $friend_id = trim(Yii::app()->request->getParam('friend_id'));
     if ($status != 1 && $status != 2 && $status != 3) {
         $this->_return('MSG_ERR_FAIL_PARAM');
     }
     if (!is_numeric($user_id) || !is_numeric($friend_id)) {
         $this->_return('MSG_ERR_FAIL_PARAM');
     }
     //用户不存在 返回错误
     if ($user_id < 1) {
         $this->_return('MSG_ERR_NO_USER');
     }
     //用户不存在 返回错误
     if ($friend_id < 1) {
         $this->_return('MSG_ERR_NO_USER');
     }
     //验证token
     if (!Token::model()->verifyToken($user_id, $token, $GLOBALS['__APPID'])) {
         $this->_return('MSG_ERR_TOKEN');
     }
     $ids = array();
     $ids = UserFriend::model()->newFriendMess($user_id);
     $friend = array();
     foreach ($ids as $id) {
         $friend[] = $id['friend_user_id'];
     }
     if (!in_array($friend_id, $friend)) {
         $this->_return('MSG_ERR_NO_FRIEND_REQ');
     }
     $friend_transaction = Yii::app()->db_friend->beginTransaction();
     try {
         UserFriend::model()->updateFriend($user_id, $friend_id, $status);
         $friend_transaction->commit();
         //log 日志
         $memo = $user_id . '|' . $friend_id . '|' . $status;
         Log::model()->_user_log($user_id, 'REPLY_INVITATION', date("Y-m-d H:i:s"), $memo);
     } catch (Exception $e) {
         error_log($e);
         $friend_transaction->rollback();
         $this->_return('MSG_ERR_UNKOWN');
     }
     $this->_return('MSG_SUCCESS');
 }
/**
* Retrieves the token attribute value from the related token table
*
* @param mixed $surveyid  The survey ID
* @param mixed $attrName  The token-attribute field name
* @param mixed $token  The token code
* @return string The token attribute value (or null on error)
*/
function getAttributeValue($surveyid, $attrName, $token)
{
    $attrName = strtolower($attrName);
    if (!tableExists('tokens_' . $surveyid)) {
        return null;
    }
    $token = Token::model($surveyid)->findByAttributes(array("token" => $token));
    return isset($token->{$attrName}) ? $token->{$attrName} : null;
}
Exemple #11
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);
 }
function tokensExport($iSurveyID)
{
    $sEmailFiter = trim(App()->request->getPost('filteremail'));
    $iTokenStatus = App()->request->getPost('tokenstatus');
    $iInvitationStatus = App()->request->getPost('invitationstatus');
    $iReminderStatus = App()->request->getPost('reminderstatus');
    $sTokenLanguage = App()->request->getPost('tokenlanguage');
    $oSurvey = Survey::model()->findByPk($iSurveyID);
    $bIsNotAnonymous = $oSurvey->anonymized == 'N' && $oSurvey->active == 'Y';
    // db table exist (survey_$iSurveyID) ?
    $bquery = "SELECT * FROM {{tokens_{$iSurveyID}}} where 1=1";
    $databasetype = Yii::app()->db->getDriverName();
    if (trim($sEmailFiter) != '') {
        if (in_array($databasetype, array('mssql', 'sqlsrv', 'dblib'))) {
            $bquery .= ' and CAST(email as varchar) like ' . dbQuoteAll('%' . $_POST['filteremail'] . '%', true);
        } else {
            $bquery .= ' and email like ' . dbQuoteAll('%' . $_POST['filteremail'] . '%', true);
        }
    }
    if ($_POST['tokenstatus'] == 1) {
        $bquery .= " and completed<>'N'";
    } elseif ($iTokenStatus == 2) {
        $bquery .= " and completed='N'";
    } elseif ($iTokenStatus == 3 && $bIsNotAnonymous) {
        $bquery .= " and completed='N' and token not in (select token from {{survey_{$iSurveyID}}} group by token)";
    } elseif ($iTokenStatus == 4 && $bIsNotAnonymous) {
        $bquery .= " and completed='N' and token in (select token from {{survey_{$iSurveyID}}} group by token)";
    }
    if ($iInvitationStatus == 1) {
        $bquery .= " and sent<>'N'";
    }
    if ($iInvitationStatus == 2) {
        $bquery .= " and sent='N'";
    }
    if ($iReminderStatus == 1) {
        $bquery .= " and remindersent<>'N'";
    }
    if ($iReminderStatus == 2) {
        $bquery .= " and remindersent='N'";
    }
    if ($sTokenLanguage != '') {
        $bquery .= " and language=" . dbQuoteAll($sTokenLanguage);
    }
    $bquery .= " ORDER BY tid";
    Yii::app()->loadHelper('database');
    $bresult = Yii::app()->db->createCommand($bquery)->query();
    //dbExecuteAssoc($bquery) is faster but deprecated!
    //HEADERS should be after the above query else timeout errors in case there are lots of tokens!
    header("Content-Disposition: attachment; filename=tokens_" . $iSurveyID . ".csv");
    header("Content-type: text/comma-separated-values; charset=UTF-8");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Pragma: cache");
    // Export UTF8 WITH BOM
    $tokenoutput = chr(hexdec('EF')) . chr(hexdec('BB')) . chr(hexdec('BF'));
    $tokenoutput .= "tid,firstname,lastname,email,emailstatus,token,language,validfrom,validuntil,invited,reminded,remindercount,completed,usesleft";
    $attrfieldnames = getAttributeFieldNames($iSurveyID);
    $attrfielddescr = getTokenFieldsAndNames($iSurveyID, true);
    foreach ($attrfieldnames as $attr_name) {
        $tokenoutput .= ", {$attr_name}";
        if (isset($attrfielddescr[$attr_name])) {
            $tokenoutput .= " <" . str_replace(",", " ", $attrfielddescr[$attr_name]['description']) . ">";
        }
    }
    $tokenoutput .= "\n";
    echo $tokenoutput;
    $tokenoutput = "";
    // Export token line by line and fill $aExportedTokens with token exported
    Yii::import('application.libraries.Date_Time_Converter', true);
    $aExportedTokens = array();
    while ($brow = $bresult->read()) {
        if (trim($brow['validfrom'] != '')) {
            $datetimeobj = new Date_Time_Converter($brow['validfrom'], "Y-m-d H:i:s");
            $brow['validfrom'] = $datetimeobj->convert('Y-m-d H:i');
        }
        if (trim($brow['validuntil'] != '')) {
            $datetimeobj = new Date_Time_Converter($brow['validuntil'], "Y-m-d H:i:s");
            $brow['validuntil'] = $datetimeobj->convert('Y-m-d H:i');
        }
        $tokenoutput .= '"' . trim($brow['tid']) . '",';
        $tokenoutput .= '"' . trim($brow['firstname']) . '",';
        $tokenoutput .= '"' . trim($brow['lastname']) . '",';
        $tokenoutput .= '"' . trim($brow['email']) . '",';
        $tokenoutput .= '"' . trim($brow['emailstatus']) . '",';
        $tokenoutput .= '"' . trim($brow['token']) . '",';
        $tokenoutput .= '"' . trim($brow['language']) . '",';
        $tokenoutput .= '"' . trim($brow['validfrom']) . '",';
        $tokenoutput .= '"' . trim($brow['validuntil']) . '",';
        $tokenoutput .= '"' . trim($brow['sent']) . '",';
        $tokenoutput .= '"' . trim($brow['remindersent']) . '",';
        $tokenoutput .= '"' . trim($brow['remindercount']) . '",';
        $tokenoutput .= '"' . trim($brow['completed']) . '",';
        $tokenoutput .= '"' . trim($brow['usesleft']) . '",';
        foreach ($attrfieldnames as $attr_name) {
            $tokenoutput .= '"' . trim($brow[$attr_name]) . '",';
        }
        $tokenoutput = substr($tokenoutput, 0, -1);
        // remove last comma
        $tokenoutput .= "\n";
        echo $tokenoutput;
        $tokenoutput = '';
        $aExportedTokens[] = $brow['tid'];
    }
    if (Yii::app()->request->getPost('tokendeleteexported') && !empty($aExportedTokens)) {
        Token::model($iSurveyID)->deleteByPk($aExportedTokens);
    }
}
Exemple #13
0
 /**
  * IOS IAP 支付验证
  * $uid
  * $token
  * $item_id
  * $receipt
  */
 public function actionIosVerify()
 {
     // error_log(json_encode($_POST));
     if (!isset($_REQUEST['receipt']) || !isset($_REQUEST['uid']) || !isset($_REQUEST['token']) || !isset($_REQUEST['trade_no'])) {
         $this->_return('MSG_ERR_LESS_PARAM');
     }
     /*沙盒测试开关,正式发布时,需置为false**********************************/
     $isSandbox = true;
     /********************************************************************/
     $receipt = Yii::app()->request->getParam('receipt');
     $uid = trim(Yii::app()->request->getParam('uid'));
     $token = trim(Yii::app()->request->getParam('token'));
     $trade_no = Yii::app()->request->getParam('trade_no');
     $now = date('Y-m-d H:i:s');
     if (!Token::model()->verifyToken($uid, $token, $GLOBALS['__APPID'])) {
         $this->_return('MSG_ERR_TOKEN');
         //#token 错误
     }
     $param = array('uid' => $uid, 'receipt' => $receipt, 'create_ts' => $now, 'trade_no' => $trade_no);
     $trade_info = Pay::model()->getTradeInfo($trade_no);
     if ($trade_info['uid'] != $uid || $trade_info['status'] != 0) {
         Pay::model()->recordIOSIAPInfo($param);
         Log::model()->_pay_log($uid, 'ORDER_IOS_IAP_VERIFY_WRONG', $now, $trade_no, "无效或重复的订单");
         $this->_return('MSG_ISO_PAY_WRONG');
     }
     if ($isSandbox) {
         $endpoint = 'https://sandbox.itunes.apple.com/verifyReceipt';
     } else {
         $endpoint = 'https://buy.itunes.apple.com/verifyReceipt';
     }
     $postData = json_encode(array('receipt-data' => $receipt));
     $ch = curl_init($endpoint);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($ch, CURLOPT_POST, true);
     //curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
     //curl_setopt($ch, CURLOPT_TIMEOUT, 30);
     curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
     //这两行一定要加,不加会报SSL 错误
     curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
     $response = curl_exec($ch);
     $errno = curl_errno($ch);
     $errmsg = curl_error($ch);
     curl_close($ch);
     if ($errno != 0) {
         Log::model()->_pay_log($uid, 'ORDER_IOS_IAP_VERIFY_WRONG', $now, trade_no, $errno . ">" . $errmsg);
         Pay::model()->recordIOSIAPInfo($param);
         $this->_return('MSG_ISO_PAY_WRONG');
     }
     $param['verify_data'] = $response;
     $data = json_decode($response);
     if (!is_object($data)) {
         Log::model()->_pay_log($uid, 'ORDER_IOS_IAP_VERIFY_WRONG', $now, $trade_no, '不能解析返回数据>' . $response);
         Pay::model()->recordIOSIAPInfo($param);
         $this->_return('MSG_ISO_PAY_WRONG');
         //throw new Exception('Invalid response data');
     }
     if (!isset($data->status) || $data->status != 0) {
         Log::model()->_pay_log($uid, 'ORDER_IOS_IAP_VERIFY_FAIL', $now, $trade_no);
         Pay::model()->recordIOSIAPInfo($param);
         $this->_return('MSG_ISO_PAY_FAIL');
     }
     $add_coin = $trade_info['coin'] + $trade_info['free'];
     Pay::model()->iosPaySuccess($uid, $trade_no, $add_coin);
     Pay::model()->recordIOSIAPInfo($param);
     Log::model()->_pay_log($uid, 'ORDER_IOS_IAP_VERIFY_OK', $now, $trade_no);
     $res = array('gold' => $add_coin);
     $this->_return('MSG_SUCCESS', $res);
 }
 /**
  * RPC Routine to return the ids and info  of token/participants of a survey.
  * if $bUnused is true, user will get the list of not completed tokens (token_return functionality).
  * Parameters iStart and ilimit are used to limit the number of results of this call.
  * Parameter aAttributes is an optional array containing more attribute that may be requested
  *
  * @access public
  * @param string $sSessionKey Auth credentials
  * @param int $iSurveyID Id of the survey to list participants
  * @param int $iStart Start id of the token list
  * @param int  $iLimit Number of participants to return
  * @param bool $bUnused If you want unused tokens, set true
  * @param bool|array $aAttributes The extented attributes that we want
  * @return array The list of tokens
  */
 public function list_participants($sSessionKey, $iSurveyID, $iStart = 0, $iLimit = 10, $bUnused = false, $aAttributes = false)
 {
     if ($this->_checkSessionKey($sSessionKey)) {
         $oSurvey = Survey::model()->findByPk($iSurveyID);
         if (!isset($oSurvey)) {
             return array('status' => 'Error: Invalid survey ID');
         }
         if (Permission::model()->hasSurveyPermission($iSurveyID, 'tokens', 'read')) {
             if (!tableExists("{{tokens_{$iSurveyID}}}")) {
                 return array('status' => 'Error: No token table');
             }
             if ($bUnused) {
                 $oTokens = Token::model($iSurveyID)->incomplete()->findAll(array('limit' => $iLimit, 'offset' => $iStart));
             } else {
                 $oTokens = Token::model($iSurveyID)->findAll(array('limit' => $iLimit, 'offset' => $iStart));
             }
             if (count($oTokens) == 0) {
                 return array('status' => 'No Tokens found');
             }
             if ($aAttributes) {
                 $aBasicDestinationFields = Token::model($iSurveyID)->tableSchema->columnNames;
                 $aTokenProperties = array_intersect($aAttributes, $aBasicDestinationFields);
                 $currentAttributes = array('tid', 'token', 'firstname', 'lastname', 'email');
                 $extendedAttributes = array_diff($aTokenProperties, $currentAttributes);
             }
             foreach ($oTokens as $token) {
                 $aTempData = array('tid' => $token->primarykey, 'token' => $token->attributes['token'], 'participant_info' => array('firstname' => $token->attributes['firstname'], 'lastname' => $token->attributes['lastname'], 'email' => $token->attributes['email']));
                 foreach ($extendedAttributes as $sAttribute) {
                     $aTempData[$sAttribute] = $token->attributes[$sAttribute];
                 }
                 $aData[] = $aTempData;
             }
             return $aData;
         } else {
             return array('status' => 'No permission');
         }
     } else {
         return array('status' => 'Invalid Session Key');
     }
 }
 /**
  * RPC Routine to return the ids and info  of token/participants of a survey.
  * if $bUnused is true, user will get the list of not completed tokens (token_return functionality).
  * Parameters iStart and ilimit are used to limit the number of results of this call.
  *
  * @access public
  * @param string $sSessionKey Auth credentials
  * @param int $iSurveyID Id of the survey to list participants
  * @param int $iStart Start id of the token list
  * @param int  $iLimit Number of participants to return
  * @param bool $bUnused If you want unused tokensm, set true
  * @return array The list of tokens
  */
 public function list_participants($sSessionKey, $iSurveyID, $iStart = 0, $iLimit = 10, $bUnused = false)
 {
     if ($this->_checkSessionKey($sSessionKey)) {
         $oSurvey = Survey::model()->findByPk($iSurveyID);
         if (!isset($oSurvey)) {
             return array('status' => 'Error: Invalid survey ID');
         }
         if (Permission::model()->hasSurveyPermission($iSurveyID, 'tokens', 'read')) {
             if (!tableExists("{{tokens_{$iSurveyID}}}")) {
                 return array('status' => 'Error: No token table');
             }
             if ($bUnused) {
                 $oTokens = Token::model($iSurveyID)->incomplete()->findAll(array('limit' => $iLimit, 'offset' => $iStart));
             } else {
                 $oTokens = Token::model($iSurveyID)->findAll(array('limit' => $iLimit, 'offset' => $iStart));
             }
             if (count($oTokens) == 0) {
                 return array('status' => 'No Tokens found');
             }
             // Author: LS Dev Tw@s
             // DON'T USE THIS! IT DOESN'T WORK!!!
             //return array('status' => 'Tokens not found');
             //return array('status' => json_encode($oTokens));
             foreach ($oTokens as $token) {
                 $aData[] = array('tid' => $token->primarykey, 'token' => $token->attributes['token'], 'participant_info' => array('firstname' => $token->attributes['firstname'], 'lastname' => $token->attributes['lastname'], 'email' => $token->attributes['email'], 'usesleft' => $token->attributes['usesleft'], 'sent' => $token->attributes['sent'], 'remindedsent' => $token->attributes['remindersent'], 'remindercount' => $token->attributes['remindercount'], 'completed' => $token->attributes['completed']));
             }
             return $aData;
         } else {
             return array('status' => 'No permission');
         }
     } else {
         return array('status' => 'Invalid Session Key');
     }
 }
 /**
  * This function loads the relevant data about tokens for a survey.
  * If specific token is not given it loads empty values, this is used for
  * question previewing and the like.
  *
  * @param int $iSurveyId
  * @param string $sToken
  * @param boolean $bAnonymize
  * @return void
  */
 public function loadTokenInformation($iSurveyId, $sToken = null, $bAnonymize = false)
 {
     if (!Survey::model()->hasTokens($iSurveyId)) {
         return;
     }
     if ($sToken === null && isset($_SESSION[$this->sessid]['token'])) {
         $sToken = $_SESSION[$this->sessid]['token'];
     }
     $oToken = Token::model($iSurveyId)->findByAttributes(array('token' => $sToken));
     if ($oToken) {
         foreach ($oToken->attributes as $attribute => $value) {
             if ($bAnonymize) {
                 $value = "";
             }
             $this->knownVars["TOKEN:" . strtoupper($attribute)] = array('code' => $value, 'jsName_on' => '', 'jsName' => '', 'readWrite' => 'N');
         }
     } else {
         // Read list of available tokens from the tokens table so that preview and error checking works correctly
         $blankVal = array('code' => '', 'jsName_on' => '', 'jsName' => '', 'readWrite' => 'N');
         foreach (Token::model($iSurveyId)->tableSchema->columnNames as $attribute) {
             $this->knownVars['TOKEN:' . strtoupper($attribute)] = $blankVal;
         }
     }
 }
Exemple #17
0
 public function index($iSurveyID)
 {
     $aData = $this->_getData($iSurveyID);
     extract($aData);
     $aViewUrls = array();
     $sBrowseLanguage = $aData['language'];
     /**
      * fnames is used as informational array
      * it containts
      *             $fnames[] = array(<dbfieldname>, <some strange title>, <questiontext>, <group_id>, <questiontype>);
      */
     if (Yii::app()->request->getPost('sql')) {
         $aViewUrls[] = 'browseallfiltered_view';
     }
     $aData['num_total_answers'] = SurveyDynamic::model($iSurveyID)->count();
     $aData['num_completed_answers'] = SurveyDynamic::model($iSurveyID)->count('submitdate IS NOT NULL');
     if (tableExists('{{tokens_' . $iSurveyID . '}}') && Permission::model()->hasSurveyPermission($iSurveyID, 'tokens', 'read')) {
         $aData['with_token'] = Yii::app()->db->schema->getTable('{{tokens_' . $iSurveyID . '}}');
         $aData['tokeninfo'] = Token::model($iSurveyID)->summary();
     }
     $aData['menu']['edition'] = false;
     $aViewUrls[] = 'browseindex_view';
     $this->_renderWrappedTemplate('', $aViewUrls, $aData);
 }
Exemple #18
0
 /**
  * Handle token form for addnew/edit actions
  * @param string $subaction
  */
 public function _handletokenform($iSurveyId, $subaction, $iTokenId = "", $ajax = false)
 {
     // CHECK TO SEE IF A TOKEN TABLE EXISTS FOR THIS SURVEY
     $bTokenExists = tableExists('{{tokens_' . $iSurveyId . '}}');
     if (!$bTokenExists) {
         self::_newtokentable($iSurveyId);
     }
     Yii::app()->loadHelper("surveytranslator");
     if ($subaction == "edit") {
         $aData['tokenid'] = $iTokenId;
         $aData['tokendata'] = Token::model($iSurveyId)->findByPk($iTokenId);
     } else {
         $aData['completed'] = null;
         $aData['sent'] = null;
         $aData['remindersent'] = null;
     }
     $aData['iTokenLength'] = !empty(Token::model($iSurveyId)->survey->tokenlength) ? Token::model($iSurveyId)->survey->tokenlength : 15;
     $thissurvey = getSurveyInfo($iSurveyId);
     $aAdditionalAttributeFields = $thissurvey['attributedescriptions'];
     $aTokenFieldNames = Yii::app()->db->getSchema()->getTable("{{tokens_{$iSurveyId}}}", true);
     $aTokenFieldNames = array_keys($aTokenFieldNames->columns);
     $aData['attrfieldnames'] = array();
     foreach ($aAdditionalAttributeFields as $sField => $aAttrData) {
         if (in_array($sField, $aTokenFieldNames)) {
             if ($aAttrData['description'] == '') {
                 $aAttrData['description'] = $sField;
             }
             $aData['attrfieldnames'][(string) $sField] = $aAttrData;
         }
     }
     foreach ($aTokenFieldNames as $sTokenFieldName) {
         if (strpos($sTokenFieldName, 'attribute_') === 0 && (!isset($aData['attrfieldnames']) || !isset($aData['attrfieldnames'][$sTokenFieldName]))) {
             $aData['attrfieldnames'][$sTokenFieldName] = array('description' => $sTokenFieldName, 'mandatory' => 'N');
         }
     }
     $aData['thissurvey'] = $thissurvey;
     $aData['surveyid'] = $iSurveyId;
     $aData['subaction'] = $subaction;
     $aData['dateformatdetails'] = getDateFormatData(Yii::app()->session['dateformat']);
     $oSurvey = Survey::model()->findByPk($iSurveyId);
     $surveyinfo = $oSurvey->surveyinfo;
     $aData['sidemenu']['state'] = false;
     $aData["surveyinfo"] = $surveyinfo;
     $aData['title_bar']['title'] = $surveyinfo['surveyls_title'] . "(" . gT("ID") . ":" . $iSurveyId . ")";
     $aData['sidemenu']["token_menu"] = TRUE;
     $aData['token_bar']['savebutton']['form'] = TRUE;
     $aData['token_bar']['closebutton']['url'] = 'admin/tokens/sa/index/surveyid/' . $iSurveyId;
     if ($ajax) {
         $aData['oSurvey'] = $oSurvey;
         $aData['ajax'] = true;
         $this->getController()->renderPartial('/admin/token/tokenform', $aData, false, false);
     } else {
         $this->_renderWrappedTemplate('token', array('tokenform'), $aData);
     }
 }
Exemple #19
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>";
     }
 }
 function actionparticipants()
 {
     $iSurveyID = Yii::app()->request->getQuery('surveyid');
     $sLanguageCode = Yii::app()->request->getQuery('langcode');
     $sToken = sanitize_token(Yii::app()->request->getQuery('token'));
     Yii::app()->loadHelper('database');
     Yii::app()->loadHelper('sanitize');
     if (!$iSurveyID) {
         $this->redirect(array('/'));
     }
     $iSurveyID = (int) $iSurveyID;
     //Make sure it's an integer (protect from SQL injects)
     //Check that there is a SID
     // Get passed language from form, so that we dont lose this!
     if (!isset($sLanguageCode) || $sLanguageCode == "" || !$sLanguageCode) {
         $sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language;
         Yii::import('application.libraries.Limesurvey_lang', true);
         $clang = new Limesurvey_lang($sBaseLanguage);
     } else {
         $sLanguageCode = sanitize_languagecode($sLanguageCode);
         Yii::import('application.libraries.Limesurvey_lang', true);
         $clang = new Limesurvey_lang($sLanguageCode);
         $sBaseLanguage = $sLanguageCode;
     }
     Yii::app()->lang = $clang;
     $aSurveyInfo = getSurveyInfo($iSurveyID, $sBaseLanguage);
     if ($aSurveyInfo == false || !tableExists("{{tokens_{$iSurveyID}}}")) {
         $sMessage = $clang->gT('This survey does not seem to exist.');
     } else {
         $oToken = Token::model($iSurveyID)->findByAttributes(array('token' => $sToken));
         if (!isset($oToken)) {
             $sMessage = $clang->gT('You are not a participant in this survey.');
         } else {
             if (substr($oToken->emailstatus, 0, strlen('OptOut')) !== 'OptOut') {
                 $oToken->emailstatus = 'OptOut';
                 $oToken->save();
                 $sMessage = $clang->gT('You have been successfully removed from this survey.');
             } else {
                 $sMessage = $clang->gT('You have been already removed from this survey.');
             }
             if (!empty($oToken->participant_id)) {
                 //Participant also exists in central db
                 $oParticipant = Participant::model()->findByPk($oToken->participant_id);
                 if ($oParticipant->blacklisted == "Y") {
                     $sMessage .= "<br />";
                     $sMessage .= $clang->gT("You have already been removed from the central participants list for this site");
                 } else {
                     $oParticipant->blacklisted = 'Y';
                     $oParticipant->save();
                     $sMessage .= "<br />";
                     $sMessage .= $clang->gT("You have been removed from the central participants list for this site");
                 }
             }
         }
     }
     //PRINT COMPLETED PAGE
     if (!$aSurveyInfo['templatedir']) {
         $sTemplate = getTemplatePath(Yii::app()->getConfig("defaulttemplate"));
     } else {
         $sTemplate = getTemplatePath($aSurveyInfo['templatedir']);
     }
     $this->_renderHtml($sMessage, $sTemplate, $aSurveyInfo);
 }
/**
* This function builds all the required session variables when a survey is first started and
* it loads any answer defaults from command line or from the table defaultvalues
* It is called from the related format script (group.php, question.php, survey.php)
* if the survey has just started.
*/
function buildsurveysession($surveyid, $preview = false)
{
    Yii::trace('start', 'survey.buildsurveysession');
    global $secerror, $clienttoken;
    global $tokensexist;
    //global $surveyid;
    global $move, $rooturl;
    $clang = Yii::app()->lang;
    $sLangCode = $clang->langcode;
    $languagechanger = makeLanguageChangerSurvey($sLangCode);
    if (!$preview) {
        $preview = Yii::app()->getConfig('previewmode');
    }
    $thissurvey = getSurveyInfo($surveyid, $sLangCode);
    $_SESSION['survey_' . $surveyid]['templatename'] = validateTemplateDir($thissurvey['template']);
    $_SESSION['survey_' . $surveyid]['templatepath'] = getTemplatePath($_SESSION['survey_' . $surveyid]['templatename']) . DIRECTORY_SEPARATOR;
    $sTemplatePath = $_SESSION['survey_' . $surveyid]['templatepath'];
    $loadsecurity = returnGlobal('loadsecurity', true);
    // NO TOKEN REQUIRED BUT CAPTCHA ENABLED FOR SURVEY ACCESS
    if ($tokensexist == 0 && isCaptchaEnabled('surveyaccessscreen', $thissurvey['usecaptcha']) && !isset($_SESSION['survey_' . $surveyid]['captcha_surveyaccessscreen']) && !$preview) {
        // IF CAPTCHA ANSWER IS NOT CORRECT OR NOT SET
        if (!isset($loadsecurity) || !isset($_SESSION['survey_' . $surveyid]['secanswer']) || $loadsecurity != $_SESSION['survey_' . $surveyid]['secanswer']) {
            sendCacheHeaders();
            doHeader();
            // No or bad answer to required security question
            $redata = compact(array_keys(get_defined_vars()));
            echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'frontend_helper[875]');
            //echo makedropdownlist();
            echo templatereplace(file_get_contents($sTemplatePath . "survey.pstpl"), array(), $redata, 'frontend_helper[877]');
            if (isset($loadsecurity)) {
                // was a bad answer
                echo "<font color='#FF0000'>" . $clang->gT("The answer to the security question is incorrect.") . "</font><br />";
            }
            echo "<p class='captcha'>" . $clang->gT("Please confirm access to survey by answering the security question below and click continue.") . "</p>" . CHtml::form(array("/survey/index/sid/{$surveyid}"), 'post', array('class' => 'captcha')) . "\n            <table align='center'>\n            <tr>\n            <td align='right' valign='middle'>\n            <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n            <input type='hidden' name='lang' value='" . $sLangCode . "' id='lang' />";
            // In case we this is a direct Reload previous answers URL, then add hidden fields
            if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) {
                echo "\n                <input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n                <input type='hidden' name='scid' value='" . returnGlobal('scid', true) . "' id='scid' />\n                <input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n                <input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />";
            }
            echo "\n            </td>\n            </tr>";
            if (function_exists("ImageCreate") && isCaptchaEnabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
                echo "<tr>\n                <td align='center' valign='middle'><label for='captcha'>" . $clang->gT("Security question:") . "</label></td><td align='left' valign='middle'><table><tr><td valign='middle'><img src='" . Yii::app()->getController()->createUrl('/verification/image/sid/' . $surveyid) . "' alt='captcha' /></td>\n                <td valign='middle'><input id='captcha' type='text' size='5' maxlength='3' name='loadsecurity' value='' /></td></tr></table>\n                </td>\n                </tr>";
            }
            echo "<tr><td colspan='2' align='center'><input class='submit' type='submit' value='" . $clang->gT("Continue") . "' /></td></tr>\n            </table>\n            </form>";
            echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata, 'frontend_helper[1567]');
            doFooter();
            exit;
        } else {
            $_SESSION['survey_' . $surveyid]['captcha_surveyaccessscreen'] = true;
        }
    }
    //BEFORE BUILDING A NEW SESSION FOR THIS SURVEY, LET'S CHECK TO MAKE SURE THE SURVEY SHOULD PROCEED!
    // TOKEN REQUIRED BUT NO TOKEN PROVIDED
    if ($tokensexist == 1 && !$clienttoken && !$preview) {
        if ($thissurvey['nokeyboard'] == 'Y') {
            includeKeypad();
            $kpclass = "text-keypad";
        } else {
            $kpclass = "";
        }
        // DISPLAY REGISTER-PAGE if needed
        // DISPLAY CAPTCHA if needed
        sendCacheHeaders();
        doHeader();
        $redata = compact(array_keys(get_defined_vars()));
        echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'frontend_helper[1594]');
        //echo makedropdownlist();
        echo templatereplace(file_get_contents($sTemplatePath . "survey.pstpl"), array(), $redata, 'frontend_helper[1596]');
        if (isset($thissurvey) && $thissurvey['allowregister'] == "Y") {
            echo templatereplace(file_get_contents($sTemplatePath . "register.pstpl"), array(), $redata, 'frontend_helper[1599]');
        } else {
            // ->renderPartial('entertoken_view');
            if (isset($secerror)) {
                echo "<span class='error'>" . $secerror . "</span><br />";
            }
            echo '<div id="wrapper"><p id="tokenmessage">' . $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br />";
            echo $clang->gT("If you have been issued a token, please enter it in the box below and click continue.") . "</p>\n            <script type='text/javascript'>var focus_element='#token';</script>" . CHtml::form(array("/survey/index/sid/{$surveyid}"), 'post', array('id' => 'tokenform', 'autocomplete' => 'off')) . "\n            <ul>\n            <li>";
            ?>
            <label for='token'><?php 
            $clang->eT("Token:");
            ?>
</label><input class='text <?php 
            echo $kpclass;
            ?>
' id='token' type='password' name='token' value='' />
            <?php 
            echo "<input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n            <input type='hidden' name='lang' value='" . $sLangCode . "' id='lang' />";
            if (isset($_GET['newtest']) && $_GET['newtest'] == "Y") {
                echo "  <input type='hidden' name='newtest' value='Y' id='newtest' />";
            }
            // If this is a direct Reload previous answers URL, then add hidden fields
            if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) {
                echo "\n                <input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n                <input type='hidden' name='scid' value='" . returnGlobal('scid', true) . "' id='scid' />\n                <input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n                <input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />";
            }
            echo "</li>";
            if (function_exists("ImageCreate") && isCaptchaEnabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
                echo "<li>\n                <label for='captchaimage'>" . $clang->gT("Security Question") . "</label><img id='captchaimage' src='" . Yii::app()->getController()->createUrl('/verification/image/sid/' . $surveyid) . "' alt='captcha' /><input type='text' size='5' maxlength='3' name='loadsecurity' value='' />\n                </li>";
            }
            echo "<li>\n            <input class='submit button' type='submit' value='" . $clang->gT("Continue") . "' />\n            </li>\n            </ul>\n            </form></div>";
        }
        echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata, 'frontend_helper[1645]');
        doFooter();
        exit;
    } elseif ($tokensexist == 1 && $clienttoken && !isCaptchaEnabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
        //check if token actually does exist
        // check also if it is allowed to change survey after completion
        if ($thissurvey['alloweditaftercompletion'] == 'Y') {
            $oTokenEntry = Token::model($surveyid)->findByAttributes(array('token' => $clienttoken));
        } else {
            $oTokenEntry = Token::model($surveyid)->usable()->incomplete()->findByAttributes(array('token' => $clienttoken));
        }
        if (!isset($oTokenEntry)) {
            //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT
            killSurveySession($surveyid);
            sendCacheHeaders();
            doHeader();
            $redata = compact(array_keys(get_defined_vars()));
            echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'frontend_helper[1676]');
            echo templatereplace(file_get_contents($sTemplatePath . "survey.pstpl"), array(), $redata, 'frontend_helper[1677]');
            echo '<div id="wrapper"><p id="tokenmessage">' . $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br /><br />\n" . "\t" . $clang->gT("The token you have provided is either not valid, or has already been used.") . "<br /><br />\n" . "\t" . sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname']) . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)</p></div>\n";
            echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata, 'frontend_helper[1684]');
            doFooter();
            exit;
        }
    } elseif ($tokensexist == 1 && $clienttoken && isCaptchaEnabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
        // IF CAPTCHA ANSWER IS CORRECT
        if (isset($loadsecurity) && isset($_SESSION['survey_' . $surveyid]['secanswer']) && $loadsecurity == $_SESSION['survey_' . $surveyid]['secanswer']) {
            if ($thissurvey['alloweditaftercompletion'] == 'Y') {
                $oTokenEntry = Token::model($surveyid)->findByAttributes(array('token' => $clienttoken));
            } else {
                $oTokenEntry = Token::model($surveyid)->incomplete()->findByAttributes(array('token' => $clienttoken));
            }
            if (!isset($oTokenEntry)) {
                sendCacheHeaders();
                doHeader();
                //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT
                $redata = compact(array_keys(get_defined_vars()));
                echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'frontend_helper[1719]');
                echo templatereplace(file_get_contents($sTemplatePath . "survey.pstpl"), array(), $redata, 'frontend_helper[1720]');
                echo "\t<div id='wrapper'>\n" . "\t<p id='tokenmessage'>\n" . "\t" . $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br /><br />\n" . "\t" . $clang->gT("The token you have provided is either not valid, or has already been used.") . "<br/><br />\n" . "\t" . sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname']) . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)\n" . "\t</p>\n" . "\t</div>\n";
                echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata, 'frontend_helper[1731]');
                doFooter();
                exit;
            }
        } else {
            if (!isset($move) || is_null($move)) {
                unset($_SESSION['survey_' . $surveyid]['srid']);
                $gettoken = $clienttoken;
                sendCacheHeaders();
                doHeader();
                // No or bad answer to required security question
                $redata = compact(array_keys(get_defined_vars()));
                echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'frontend_helper[1745]');
                echo templatereplace(file_get_contents($sTemplatePath . "survey.pstpl"), array(), $redata, 'frontend_helper[1746]');
                // If token wasn't provided and public registration
                // is enabled then show registration form
                if (!isset($gettoken) && isset($thissurvey) && $thissurvey['allowregister'] == "Y") {
                    echo templatereplace(file_get_contents($sTemplatePath . "register.pstpl"), array(), $redata, 'frontend_helper[1751]');
                } else {
                    // only show CAPTCHA
                    echo '<div id="wrapper"><p id="tokenmessage">';
                    if (isset($loadsecurity)) {
                        // was a bad answer
                        echo "<span class='error'>" . $clang->gT("The answer to the security question is incorrect.") . "</span><br />";
                    }
                    echo $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br /><br />";
                    // IF TOKEN HAS BEEN GIVEN THEN AUTOFILL IT
                    // AND HIDE ENTRY FIELD
                    if (!isset($gettoken)) {
                        echo $clang->gT("If you have been issued a token, please enter it in the box below and click continue.") . "</p>\n                        <form id='tokenform' method='get' action='" . Yii::app()->getController()->createUrl("/survey/index") . "'>\n                        <ul>\n                        <li>\n                        <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n                        <input type='hidden' name='lang' value='" . $sLangCode . "' id='lang' />";
                        if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) {
                            echo "<input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n                            <input type='hidden' name='scid' value='" . returnGlobal('scid', true) . "' id='scid' />\n                            <input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n                            <input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />";
                        }
                        echo '<label for="token">' . $clang->gT("Token") . "</label><input class='text' type='password' id='token' name='token'></li>";
                    } else {
                        echo $clang->gT("Please confirm the token by answering the security question below and click continue.") . "</p>\n                    <form id='tokenform' method='get' action='" . Yii::app()->getController()->createUrl("/survey/index") . "'>\n                    <ul>\n                    <li>\n                    <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n                    <input type='hidden' name='lang' value='" . $sLangCode . "' id='lang' />";
                        if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) {
                            echo "<input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n                        <input type='hidden' name='scid' value='" . returnGlobal('scid', true) . "' id='scid' />\n                        <input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n                        <input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />";
                        }
                        echo '<label for="token">' . $clang->gT("Token:") . "</label><span id='token'>{$gettoken}</span>" . "<input type='hidden' name='token' value='{$gettoken}'></li>";
                    }
                    if (function_exists("ImageCreate") && isCaptchaEnabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
                        echo "<li>\n                    <label for='captchaimage'>" . $clang->gT("Security Question") . "</label><img id='captchaimage' src='" . Yii::app()->getController()->createUrl('/verification/image/sid/' . $surveyid) . "' alt='captcha' /><input type='text' size='5' maxlength='3' name='loadsecurity' value='' />\n                    </li>";
                    }
                    echo "<li><input class='submit' type='submit' value='" . $clang->gT("Continue") . "' /></li>\n                </ul>\n                </form>\n                </id>";
                }
                echo '</div>' . templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata, 'frontend_helper[1817]');
                doFooter();
                exit;
            }
        }
    }
    //RESET ALL THE SESSION VARIABLES AND START AGAIN
    unset($_SESSION['survey_' . $surveyid]['grouplist']);
    unset($_SESSION['survey_' . $surveyid]['fieldarray']);
    unset($_SESSION['survey_' . $surveyid]['insertarray']);
    unset($_SESSION['survey_' . $surveyid]['fieldnamesInfo']);
    unset($_SESSION['survey_' . $surveyid]['fieldmap-' . $surveyid . '-randMaster']);
    unset($_SESSION['survey_' . $surveyid]['groupReMap']);
    $_SESSION['survey_' . $surveyid]['fieldnamesInfo'] = array();
    // Multi lingual support order : by REQUEST, if not by Token->language else by survey default language
    if (returnGlobal('lang', true)) {
        $language_to_set = returnGlobal('lang', true);
    } elseif (isset($oTokenEntry) && $oTokenEntry) {
        // If survey have token : we have a $oTokenEntry
        // Can use $oTokenEntry = Token::model($surveyid)->findByAttributes(array('token'=>$clienttoken)); if we move on another function : this par don't validate the token validity
        $language_to_set = $oTokenEntry->language;
    } else {
        $language_to_set = $thissurvey['language'];
    }
    if (!isset($_SESSION['survey_' . $surveyid]['s_lang'])) {
        SetSurveyLanguage($surveyid, $language_to_set);
    }
    UpdateGroupList($surveyid, $_SESSION['survey_' . $surveyid]['s_lang']);
    $sQuery = "SELECT count(*)\n" . " FROM {{groups}} INNER JOIN {{questions}} ON {{groups}}.gid = {{questions}}.gid\n" . " WHERE {{questions}}.sid=" . $surveyid . "\n" . " AND {{groups}}.language='" . $_SESSION['survey_' . $surveyid]['s_lang'] . "'\n" . " AND {{questions}}.language='" . $_SESSION['survey_' . $surveyid]['s_lang'] . "'\n" . " AND {{questions}}.parent_qid=0\n";
    $totalquestions = Yii::app()->db->createCommand($sQuery)->queryScalar();
    // Fix totalquestions by substracting Test Display questions
    $iNumberofQuestions = dbExecuteAssoc("SELECT count(*)\n" . " FROM {{questions}}" . " WHERE type in ('X','*')\n" . " AND sid={$surveyid}" . " AND language='" . $_SESSION['survey_' . $surveyid]['s_lang'] . "'" . " AND parent_qid=0")->read();
    $_SESSION['survey_' . $surveyid]['totalquestions'] = $totalquestions - (int) reset($iNumberofQuestions);
    //2. SESSION VARIABLE: totalsteps
    //The number of "pages" that will be presented in this survey
    //The number of pages to be presented will differ depending on the survey format
    switch ($thissurvey['format']) {
        case "A":
            $_SESSION['survey_' . $surveyid]['totalsteps'] = 1;
            break;
        case "G":
            if (isset($_SESSION['survey_' . $surveyid]['grouplist'])) {
                $_SESSION['survey_' . $surveyid]['totalsteps'] = count($_SESSION['survey_' . $surveyid]['grouplist']);
            }
            break;
        case "S":
            $_SESSION['survey_' . $surveyid]['totalsteps'] = $totalquestions;
    }
    if ($totalquestions == 0) {
        sendCacheHeaders();
        doHeader();
        $redata = compact(array_keys(get_defined_vars()));
        echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'frontend_helper[1914]');
        echo templatereplace(file_get_contents($sTemplatePath . "survey.pstpl"), array(), $redata, 'frontend_helper[1915]');
        echo "\t<div id='wrapper'>\n" . "\t<p id='tokenmessage'>\n" . "\t" . $clang->gT("This survey does not yet have any questions and cannot be tested or completed.") . "<br /><br />\n" . "\t" . sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname']) . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)<br /><br />\n" . "\t</p>\n" . "\t</div>\n";
        echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata, 'frontend_helper[1925]');
        doFooter();
        exit;
    }
    //Perform a case insensitive natural sort on group name then question title of a multidimensional array
    //    usort($arows, 'groupOrderThenQuestionOrder');
    //3. SESSION VARIABLE - insertarray
    //An array containing information about used to insert the data into the db at the submit stage
    //4. SESSION VARIABLE - fieldarray
    //See rem at end..
    if ($tokensexist == 1 && $clienttoken) {
        $_SESSION['survey_' . $surveyid]['token'] = $clienttoken;
    }
    if ($thissurvey['anonymized'] == "N") {
        $_SESSION['survey_' . $surveyid]['insertarray'][] = "token";
    }
    $qtypes = getQuestionTypeList('', 'array');
    $fieldmap = createFieldMap($surveyid, 'full', true, false, $_SESSION['survey_' . $surveyid]['s_lang']);
    // Randomization groups for groups
    $aRandomGroups = array();
    $aGIDCompleteMap = array();
    // first find all groups and their groups IDS
    $criteria = new CDbCriteria();
    $criteria->addColumnCondition(array('sid' => $surveyid, 'language' => $_SESSION['survey_' . $surveyid]['s_lang']));
    $criteria->addCondition("randomization_group != ''");
    $oData = QuestionGroup::model()->findAll($criteria);
    foreach ($oData as $aGroup) {
        $aRandomGroups[$aGroup['randomization_group']][] = $aGroup['gid'];
    }
    // Shuffle each group and create a map for old GID => new GID
    foreach ($aRandomGroups as $sGroupName => $aGIDs) {
        $aShuffledIDs = $aGIDs;
        shuffle($aShuffledIDs);
        $aGIDCompleteMap = $aGIDCompleteMap + array_combine($aGIDs, $aShuffledIDs);
    }
    $_SESSION['survey_' . $surveyid]['groupReMap'] = $aGIDCompleteMap;
    $randomized = false;
    // So we can trigger reorder once for group and question randomization
    // Now adjust the grouplist
    if (count($aRandomGroups) > 0 && !$preview) {
        $randomized = true;
        // So we can trigger reorder once for group and question randomization
        // Now adjust the grouplist
        Yii::import('application.helpers.frontend_helper', true);
        // make sure frontend helper is loaded
        UpdateGroupList($surveyid, $_SESSION['survey_' . $surveyid]['s_lang']);
        // ... and the fieldmap
        // First create a fieldmap with GID as key
        foreach ($fieldmap as $aField) {
            if (isset($aField['gid'])) {
                $GroupFieldMap[$aField['gid']][] = $aField;
            } else {
                $GroupFieldMap['other'][] = $aField;
            }
        }
        // swap it
        foreach ($GroupFieldMap as $iOldGid => $fields) {
            $iNewGid = $iOldGid;
            if (isset($aGIDCompleteMap[$iOldGid])) {
                $iNewGid = $aGIDCompleteMap[$iOldGid];
            }
            $newGroupFieldMap[$iNewGid] = $GroupFieldMap[$iNewGid];
        }
        $GroupFieldMap = $newGroupFieldMap;
        // and convert it back to a fieldmap
        unset($fieldmap);
        foreach ($GroupFieldMap as $aGroupFields) {
            foreach ($aGroupFields as $aField) {
                if (isset($aField['fieldname'])) {
                    $fieldmap[$aField['fieldname']] = $aField;
                    // isset() because of the shuffled flag above
                }
            }
        }
        unset($GroupFieldMap);
    }
    // Randomization groups for questions
    // Find all defined randomization groups through question attribute values
    $randomGroups = array();
    if (in_array(Yii::app()->db->getDriverName(), array('mssql', 'sqlsrv', 'dblib'))) {
        $rgquery = "SELECT attr.qid, CAST(value as varchar(255)) as value FROM {{question_attributes}} as attr right join {{questions}} as quests on attr.qid=quests.qid WHERE attribute='random_group' and CAST(value as varchar(255)) <> '' and sid={$surveyid} GROUP BY attr.qid, CAST(value as varchar(255))";
    } else {
        $rgquery = "SELECT attr.qid, value FROM {{question_attributes}} as attr right join {{questions}} as quests on attr.qid=quests.qid WHERE attribute='random_group' and value <> '' and sid={$surveyid} GROUP BY attr.qid, value";
    }
    $rgresult = dbExecuteAssoc($rgquery);
    foreach ($rgresult->readAll() as $rgrow) {
        // Get the question IDs for each randomization group
        $randomGroups[$rgrow['value']][] = $rgrow['qid'];
    }
    // If we have randomization groups set, then lets cycle through each group and
    // replace questions in the group with a randomly chosen one from the same group
    if (count($randomGroups) > 0 && !$preview) {
        $randomized = true;
        // So we can trigger reorder once for group and question randomization
        $copyFieldMap = array();
        $oldQuestOrder = array();
        $newQuestOrder = array();
        $randGroupNames = array();
        foreach ($randomGroups as $key => $value) {
            $oldQuestOrder[$key] = $randomGroups[$key];
            $newQuestOrder[$key] = $oldQuestOrder[$key];
            // We shuffle the question list to get a random key->qid which will be used to swap from the old key
            shuffle($newQuestOrder[$key]);
            $randGroupNames[] = $key;
        }
        // Loop through the fieldmap and swap each question as they come up
        foreach ($fieldmap as $fieldkey => $fieldval) {
            $found = 0;
            foreach ($randomGroups as $gkey => $gval) {
                // We found a qid that is in the randomization group
                if (isset($fieldval['qid']) && in_array($fieldval['qid'], $oldQuestOrder[$gkey])) {
                    // Get the swapped question
                    $idx = array_search($fieldval['qid'], $oldQuestOrder[$gkey]);
                    foreach ($fieldmap as $key => $field) {
                        if (isset($field['qid']) && $field['qid'] == $newQuestOrder[$gkey][$idx]) {
                            $field['random_gid'] = $fieldval['gid'];
                            // It is possible to swap to another group
                            $copyFieldMap[$key] = $field;
                        }
                    }
                    $found = 1;
                    break;
                } else {
                    $found = 2;
                }
            }
            if ($found == 2) {
                $copyFieldMap[$fieldkey] = $fieldval;
            }
            reset($randomGroups);
        }
        $fieldmap = $copyFieldMap;
    }
    if ($randomized === true) {
        // reset the sequencing counts
        $gseq = -1;
        $_gid = -1;
        $qseq = -1;
        $_qid = -1;
        $copyFieldMap = array();
        foreach ($fieldmap as $key => $val) {
            if ($val['gid'] != '') {
                if (isset($val['random_gid'])) {
                    $gid = $val['random_gid'];
                } else {
                    $gid = $val['gid'];
                }
                if ($gid != $_gid) {
                    $_gid = $gid;
                    ++$gseq;
                }
            }
            if ($val['qid'] != '' && $val['qid'] != $_qid) {
                $_qid = $val['qid'];
                ++$qseq;
            }
            if ($val['gid'] != '' && $val['qid'] != '') {
                $val['groupSeq'] = $gseq;
                $val['questionSeq'] = $qseq;
            }
            $copyFieldMap[$key] = $val;
        }
        $fieldmap = $copyFieldMap;
        unset($copyFieldMap);
        $_SESSION['survey_' . $surveyid]['fieldmap-' . $surveyid . $_SESSION['survey_' . $surveyid]['s_lang']] = $fieldmap;
        $_SESSION['survey_' . $surveyid]['fieldmap-' . $surveyid . '-randMaster'] = 'fieldmap-' . $surveyid . $_SESSION['survey_' . $surveyid]['s_lang'];
    }
    // TMSW Condition->Relevance:  don't need hasconditions, or usedinconditions
    $_SESSION['survey_' . $surveyid]['fieldmap'] = $fieldmap;
    foreach ($fieldmap as $field) {
        if (isset($field['qid']) && $field['qid'] != '') {
            $_SESSION['survey_' . $surveyid]['fieldnamesInfo'][$field['fieldname']] = $field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid'];
            $_SESSION['survey_' . $surveyid]['insertarray'][] = $field['fieldname'];
            //fieldarray ARRAY CONTENTS -
            //            [0]=questions.qid,
            //            [1]=fieldname,
            //            [2]=questions.title,
            //            [3]=questions.question
            //                     [4]=questions.type,
            //            [5]=questions.gid,
            //            [6]=questions.mandatory,
            //            [7]=conditionsexist,
            //            [8]=usedinconditions
            //            [8]=usedinconditions
            //            [9]=used in group.php for question count
            //            [10]=new group id for question in randomization group (GroupbyGroup Mode)
            if (!isset($_SESSION['survey_' . $surveyid]['fieldarray'][$field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']])) {
                //JUST IN CASE : PRECAUTION!
                //following variables are set only if $style=="full" in createFieldMap() in common_helper.
                //so, if $style = "short", set some default values here!
                if (isset($field['title'])) {
                    $title = $field['title'];
                } else {
                    $title = "";
                }
                if (isset($field['question'])) {
                    $question = $field['question'];
                } else {
                    $question = "";
                }
                if (isset($field['mandatory'])) {
                    $mandatory = $field['mandatory'];
                } else {
                    $mandatory = 'N';
                }
                if (isset($field['hasconditions'])) {
                    $hasconditions = $field['hasconditions'];
                } else {
                    $hasconditions = 'N';
                }
                if (isset($field['usedinconditions'])) {
                    $usedinconditions = $field['usedinconditions'];
                } else {
                    $usedinconditions = 'N';
                }
                $_SESSION['survey_' . $surveyid]['fieldarray'][$field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']] = array($field['qid'], $field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid'], $title, $question, $field['type'], $field['gid'], $mandatory, $hasconditions, $usedinconditions);
            }
            if (isset($field['random_gid'])) {
                $_SESSION['survey_' . $surveyid]['fieldarray'][$field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']][10] = $field['random_gid'];
            }
        }
    }
    // Prefill questions/answers from command line params
    $reservedGetValues = array('token', 'sid', 'gid', 'qid', 'lang', 'newtest', 'action');
    $startingValues = array();
    if (isset($_GET)) {
        foreach ($_GET as $k => $v) {
            if (!in_array($k, $reservedGetValues) && isset($_SESSION['survey_' . $surveyid]['fieldmap'][$k])) {
                $startingValues[$k] = $v;
            } else {
                // Search question codes to use those for prefilling.
                foreach ($_SESSION['survey_' . $surveyid]['fieldmap'] as $sgqa => $details) {
                    if ($details['title'] == $k) {
                        $startingValues[$sgqa] = $v;
                    }
                }
            }
        }
    }
    $_SESSION['survey_' . $surveyid]['startingValues'] = $startingValues;
    if (isset($_SESSION['survey_' . $surveyid]['fieldarray'])) {
        $_SESSION['survey_' . $surveyid]['fieldarray'] = array_values($_SESSION['survey_' . $surveyid]['fieldarray']);
    }
    //Check if a passthru label and value have been included in the query url
    $oResult = SurveyURLParameter::model()->getParametersForSurvey($surveyid);
    foreach ($oResult->readAll() as $aRow) {
        if (isset($_GET[$aRow['parameter']]) && !$preview) {
            $_SESSION['survey_' . $surveyid]['urlparams'][$aRow['parameter']] = $_GET[$aRow['parameter']];
            if ($aRow['targetqid'] != '') {
                foreach ($fieldmap as $sFieldname => $aField) {
                    if ($aRow['targetsqid'] != '') {
                        if ($aField['qid'] == $aRow['targetqid'] && $aField['sqid'] == $aRow['targetsqid']) {
                            $_SESSION['survey_' . $surveyid]['startingValues'][$sFieldname] = $_GET[$aRow['parameter']];
                            $_SESSION['survey_' . $surveyid]['startingValues'][$aRow['parameter']] = $_GET[$aRow['parameter']];
                        }
                    } else {
                        if ($aField['qid'] == $aRow['targetqid']) {
                            $_SESSION['survey_' . $surveyid]['startingValues'][$sFieldname] = $_GET[$aRow['parameter']];
                            $_SESSION['survey_' . $surveyid]['startingValues'][$aRow['parameter']] = $_GET[$aRow['parameter']];
                        }
                    }
                }
            }
        }
    }
    Yii::trace('end', 'survey.buildsurveysession');
}
Exemple #22
0
 public static function deleteByToken($token)
 {
     $token = Token::model()->findByAttributes(array('token' => $token));
     if ($token == null) {
         throw new CHttpException(400, 'Invalid request. Token Failed.');
     }
     if ($token->delete()) {
         return true;
     }
     return false;
 }
 public function getToken($surveyId, $token)
 {
     return Token::model($surveyId)->findByAttributes(array('token' => $token));
 }
 /**
  * 金币解锁照片
  *
  * @param int $user_id
  * @param int $goddess_id
  * @param int $token
  * @param int $image_id
  *
  */
 public function actionGoldUnlockPhoto()
 {
     // 参数检查
     if (!isset($_REQUEST['user_id']) || !isset($_REQUEST['token']) || !isset($_REQUEST['goddess_id']) || !isset($_REQUEST['image_id'])) {
         $this->_return('MSG_ERR_LESS_PARAM');
     }
     $user_id = trim(Yii::app()->request->getParam('user_id'));
     $token = trim(Yii::app()->request->getParam('token'));
     $goddess_id = trim(Yii::app()->request->getParam('goddess_id'));
     $image_id = trim(Yii::app()->request->getParam('image_id'));
     $now = date("Y-m-d H:i:s");
     if (!is_numeric($user_id)) {
         $this->_return('MSG_ERR_FAIL_PARAM');
     }
     //用户不存在 返回错误
     if ($user_id < 1) {
         $this->_return('MSG_ERR_NO_USER');
     }
     if (!Goddess::model()->isExitsGoddess($goddess_id)) {
         //不存在此女神
         $this->_return("MSG_ERR_NO_EXIST_GODDESS");
     }
     //验证token
     if (Token::model()->verifyToken($user_id, $token, $GLOBALS['__APPID'])) {
         //金币解锁照片
         $res = Goddess::model()->GoldUnlockPhoto($user_id, $goddess_id, $image_id);
         switch ($res) {
             case -1:
                 $this->_return('MSG_ERR_NO_FOUND_IMG');
             case -2:
                 $this->_return('MSG_ERR_FAIL_UNLOCKED');
             case -3:
                 $this->_return('MSG_ERR_NO_GOLD');
             default:
                 break;
         }
         $memo = $res['log']['gold'];
         //记录日志 金币解锁照片
         Log::model()->_photo_log($user_id, $goddess_id, $image_id, 'GOLD_UNLOCK_IMG', date('Y-m-d H:i:s'), $memo);
     } else {
         $this->_return('MSG_ERR_TOKEN');
     }
     // 发送返回值
     $this->_return('MSG_SUCCESS', $res['result']);
 }
 /**
  * RPC Routine to send register mails to 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 array $overrideAllConditions replace the default conditions, like this:
  *   $overrideAllConditions = Array();
  *   $overrideAllConditions[] = 'tid = 2';
  *   $response = $myJSONRPCClient->mail_registered_participants( $sessionKey, $survey_id, $overrideAllConditions );
  * @return array Result of the action
  */
 public function mail_registered_participants($sSessionKey, $iSurveyID, $overrideAllConditions = array())
 {
     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')) {
         if (!tableExists("{{tokens_{$iSurveyID}}}")) {
             return array('status' => 'Error: No token table');
         }
         $command = new CDbCriteria();
         $command->condition = '';
         if (count($overrideAllConditions)) {
             foreach ($overrideAllConditions as $condition) {
                 $command->addCondition($condition);
             }
         } else {
             $command->addCondition('usesleft > 0');
             $command->addCondition("sent = 'N'");
             $command->addCondition("remindersent = 'N'");
             $command->addCondition("(completed ='N') or (completed='')");
             $command->addCondition('ISNULL(validfrom) OR validfrom < NOW()');
             $command->addCondition('ISNULL(validuntil) OR validuntil > NOW()');
             $command->addCondition('emailstatus = "OK"');
         }
         $command->order = 'tid';
         $aAllTokens = Token::model($iSurveyID)->findAll($command);
         $iAllTokensCount = count($aAllTokens);
         unset($aAllTokens);
         $iMaxEmails = (int) Yii::app()->getConfig("maxemails");
         $command->limit = $iMaxEmails;
         $aResultTokens = Token::model($iSurveyID)->findAll($command);
         if (empty($aResultTokens)) {
             return array('status' => 'Error: No candidate tokens');
         }
         foreach ($aResultTokens as $key => $oToken) {
             //pattern taken from php_filter_validate_email PHP_5_4/ext/filter/logical_filters.c
             $pattern = '/^(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){255,})(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){65,}@)(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22))(?:\\.(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22)))*@(?:(?:(?!.*[^.]{64,})(?:(?:(?:xn--)?[a-z0-9]+(?:-+[a-z0-9]+)*\\.){1,126}){1,}(?:(?:[a-z][a-z0-9]*)|(?:(?:xn--)[a-z0-9]+))(?:-+[a-z0-9]+)*)|(?:\\[(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7})|(?:(?!(?:.*[a-f0-9][:\\]]){7,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?)))|(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){5}:)|(?:(?!(?:.*[a-f0-9]:){5,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3}:)?)))?(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))(?:\\.(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))){3}))\\]))$/iD';
             //if(!filter_var($emailaddress, FILTER_VALIDATE_EMAIL))
             if (preg_match($pattern, $oToken['email']) !== 1) {
                 unset($aResultTokens[$key]);
                 //subtract from 'left to send'
                 $iAllTokensCount--;
             }
         }
         if (empty($aResultTokens)) {
             return array('status' => 'Error: No candidate tokens');
         }
         $aResult = emailTokens($iSurveyID, $aResultTokens, 'register');
         $iLeft = $iAllTokensCount - count($aResultTokens);
         $aResult['status'] = $iLeft . " left to send";
         return $aResult;
     } else {
         return array('status' => 'No permission');
     }
 }
 function actionparticipants()
 {
     $iSurveyID = Yii::app()->request->getQuery('surveyid');
     $sLanguageCode = Yii::app()->request->getQuery('langcode');
     $sToken = sanitize_token(Yii::app()->request->getQuery('token'));
     Yii::app()->loadHelper('database');
     Yii::app()->loadHelper('sanitize');
     if (!$iSurveyID) {
         $this->redirect(array('/'));
     }
     $iSurveyID = (int) $iSurveyID;
     //Make sure it's an integer (protect from SQL injects)
     //Check that there is a SID
     // Get passed language from form, so that we dont lose this!
     if (!isset($sLanguageCode) || $sLanguageCode == "" || !$sLanguageCode) {
         $sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language;
     } else {
         $sBaseLanguage = sanitize_languagecode($sLanguageCode);
     }
     Yii::app()->setLanguage($sBaseLanguage);
     $aSurveyInfo = getSurveyInfo($iSurveyID, $sBaseLanguage);
     if ($aSurveyInfo == false || !tableExists("{{tokens_{$iSurveyID}}}")) {
         throw new CHttpException(404, "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.");
     } else {
         LimeExpressionManager::singleton()->loadTokenInformation($iSurveyID, $sToken, false);
         $oToken = Token::model($iSurveyID)->findByAttributes(array('token' => $sToken));
         if (!isset($oToken)) {
             $sMessage = gT('You are not a participant in this survey.');
         } else {
             if (substr($oToken->emailstatus, 0, strlen('OptOut')) !== 'OptOut') {
                 $oToken->emailstatus = 'OptOut';
                 $oToken->save();
                 $sMessage = gT('You have been successfully removed from this survey.');
             } else {
                 $sMessage = gT('You have been already removed from this survey.');
             }
             if (!empty($oToken->participant_id)) {
                 //Participant also exists in central db
                 $oParticipant = Participant::model()->findByPk($oToken->participant_id);
                 if ($oParticipant->blacklisted == "Y") {
                     $sMessage .= "<br />";
                     $sMessage .= gT("You have already been removed from the central participants list for this site");
                 } else {
                     $oParticipant->blacklisted = 'Y';
                     $oParticipant->save();
                     $sMessage .= "<br />";
                     $sMessage .= gT("You have been removed from the central participants list for this site");
                 }
             }
         }
     }
     //PRINT COMPLETED PAGE
     if (!$aSurveyInfo['templatedir']) {
         $sTemplate = getTemplatePath(Yii::app()->getConfig("defaulttemplate"));
     } else {
         $sTemplate = getTemplatePath($aSurveyInfo['templatedir']);
     }
     $this->_renderHtml($sMessage, $sTemplate, $aSurveyInfo);
 }
Exemple #27
0
 /**
  * Handle token form for addnew/edit actions
  */
 function _handletokenform($iSurveyId, $subaction, $iTokenId = "")
 {
     // CHECK TO SEE IF A TOKEN TABLE EXISTS FOR THIS SURVEY
     $bTokenExists = tableExists('{{tokens_' . $iSurveyId . '}}');
     if (!$bTokenExists) {
         self::_newtokentable($iSurveyId);
     }
     $clang = $this->getController()->lang;
     Yii::app()->loadHelper("surveytranslator");
     if ($subaction == "edit") {
         $aData['tokenid'] = $iTokenId;
         $aData['tokendata'] = Token::model($iSurveyId)->findByPk($iTokenId);
     }
     $thissurvey = getSurveyInfo($iSurveyId);
     $aAdditionalAttributeFields = $thissurvey['attributedescriptions'];
     $aTokenFieldNames = Yii::app()->db->getSchema()->getTable("{{tokens_{$iSurveyId}}}", true);
     $aTokenFieldNames = array_keys($aTokenFieldNames->columns);
     $aData['attrfieldnames'] = array();
     foreach ($aAdditionalAttributeFields as $sField => $aAttrData) {
         if (in_array($sField, $aTokenFieldNames)) {
             if ($aAttrData['description'] == '') {
                 $aAttrData['description'] = $sField;
             }
             $aData['attrfieldnames'][(string) $sField] = $aAttrData;
         }
     }
     foreach ($aTokenFieldNames as $sTokenFieldName) {
         if (strpos($sTokenFieldName, 'attribute_') === 0 && (!isset($aData['attrfieldnames']) || !isset($aData['attrfieldnames'][$sTokenFieldName]))) {
             $aData['attrfieldnames'][$sTokenFieldName] = array('description' => $sTokenFieldName, 'mandatory' => 'N');
         }
     }
     $aData['thissurvey'] = $thissurvey;
     $aData['surveyid'] = $iSurveyId;
     $aData['subaction'] = $subaction;
     $aData['dateformatdetails'] = getDateFormatData(Yii::app()->session['dateformat']);
     $this->_renderWrappedTemplate('token', array('tokenbar', 'tokenform'), $aData);
 }
 /**
  * This function loads the relevant data about tokens for a survey.
  * If specific token is not given it loads empty values, this is used for
  * question previewing and the like.
  *
  * @param int $iSurveyId
  * @param string $sToken
  * @param boolean $bAnonymize
  * @return void
  */
 public function loadTokenInformation($iSurveyId, $sToken = null, $bAnonymize = false)
 {
     if (!Survey::model()->hasTokens($iSurveyId)) {
         return;
     }
     if ($sToken == null && isset($_SESSION[$this->sessid]['token'])) {
         $sToken = $_SESSION[$this->sessid]['token'];
     }
     $token = Token::model($iSurveyId)->findByAttributes(array('token' => $sToken));
     $this->knownVars['TOKEN:TOKEN'] = array('code' => $sToken, 'jsName_on' => '', 'jsName' => '', 'readWrite' => 'N');
     if (isset($token)) {
         foreach ($token->attributes as $key => $val) {
             if ($bAnonymize) {
                 $val = "";
             }
             $key = "TOKEN:" . strtoupper($key);
             $this->knownVars[$key] = array('code' => $val, 'jsName_on' => '', 'jsName' => '', 'readWrite' => 'N');
         }
     } else {
         // Read list of available tokens from the tokens table so that preview and error checking works correctly
         $blankVal = array('code' => '', 'jsName_on' => '', 'jsName' => '', 'readWrite' => 'N');
         foreach (getTokenFieldsAndNames($surveyId) as $field => $details) {
             if (preg_match('/^(firstname|lastname|email|usesleft|token|attribute_\\d+)$/', $field)) {
                 $this->knownVars['TOKEN:' . strtoupper($field)] = $blankVal;
             }
         }
     }
 }
Exemple #29
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;
}
 /**
  * Get the token id according to filled values
  * @param $iSurveyId
  * @return integer : the token id created
  */
 public function getTokenId($iSurveyId)
 {
     $sLanguage = App()->language;
     $aSurveyInfo = getSurveyInfo($iSurveyId, $sLanguage);
     $aFieldValue = $this->getFieldValue($iSurveyId);
     // Now construct the text returned
     $oToken = Token::model($iSurveyId)->findByAttributes(array('email' => $aFieldValue['sEmail']));
     if ($oToken) {
         if ($oToken->usesleft < 1 && $aSurveyInfo['alloweditaftercompletion'] != 'Y') {
             $this->aRegisterErrors[] = gT("The email address you have entered is already registered and the survey has been completed.");
         } elseif (strtolower(substr(trim($oToken->emailstatus), 0, 6)) === "optout") {
             $this->aRegisterErrors[] = gT("This email address cannot be used because it was opted out of this survey.");
         } elseif (!$oToken->emailstatus && $oToken->emailstatus != "OK") {
             $this->aRegisterErrors[] = gT("This email address is already registered but the email adress was bounced.");
         } else {
             $this->sMailMessage = gT("The address you have entered is already registered. An email has been sent to this address with a link that gives you access to the survey.");
             return $oToken->tid;
         }
     } else {
         // TODO : move xss filtering in model
         $oToken = Token::create($iSurveyId);
         $oToken->firstname = sanitize_xss_string($aFieldValue['sFirstName']);
         $oToken->lastname = sanitize_xss_string($aFieldValue['sLastName']);
         $oToken->email = $aFieldValue['sEmail'];
         $oToken->emailstatus = 'OK';
         $oToken->language = $sLanguage;
         $aFieldValue['aAttribute'] = array_map('sanitize_xss_string', $aFieldValue['aAttribute']);
         $oToken->setAttributes($aFieldValue['aAttribute']);
         if ($aSurveyInfo['startdate']) {
             $oToken->validfrom = $aSurveyInfo['startdate'];
         }
         if ($aSurveyInfo['expires']) {
             $oToken->validuntil = $aSurveyInfo['expires'];
         }
         $oToken->generateToken();
         $oToken->save();
         $this->sMailMessage = 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.");
         return $oToken->tid;
     }
 }