Skip to content

Commit

Permalink
Dev WIP Create survey session manager compoment.
Browse files Browse the repository at this point in the history
  • Loading branch information
SamMousa committed Apr 1, 2015
1 parent 9dbf6b6 commit 22a3e27
Show file tree
Hide file tree
Showing 18 changed files with 333 additions and 101 deletions.
32 changes: 32 additions & 0 deletions application/components/SurveySession.php
@@ -0,0 +1,32 @@
<?php

/**
* Class SurveySession
*/
class SurveySession extends CComponent {

protected $surveyId;
protected $responseId;
protected $finished = false;
/**
* @param int $surveyId
* @param int $responseId
*/
public function __construct($surveyId, $responseId)
{
$this->surveyId = $surveyId;
$this->responseId = $responseId;
}

public function getSurveyId() {
return $this->surveyId;
}

public function getResponseId() {
return $this->responseId;
}

public function getIsFinished() {
return $this->finished;
}
}
54 changes: 54 additions & 0 deletions application/components/SurveySessionManager.php
@@ -0,0 +1,54 @@
<?php

/**
* Class SurveySessionManager
* @property-read SurveySession $current
* @property-read SurveySession[] $sessions
*/
class SurveySessionManager extends CApplicationComponent
{
/**
* @var SurveySession
*/
protected $current;
/*
* @var \CTypedMap
*/
protected $sessions;


public function init()
{
$session = App()->session;
$this->sessions = $session->get('SSM', null);
if (!isset($this->sessions)) {
$session->add('SSM', $this->sessions = new CTypedMap('SurveySession'));
}
$current = App()->request->getPost('SSM', []);
}

public function getActive() {
return isset($this->current);
}

public function getCurrent() {
return $this->current;
}

/**
* @return SurveySession[]
*/
public function getSessions() {
return $this->sessions;
}

public function newSession($surveyId, $responseId)
{
if (isset($this->sessions["$surveyId.$responseId"])) {
throw new \Exception("Duplicate session detected.");
}
return $this->sessions["$surveyId.$responseId"] = new SurveySession($surveyId, $responseId);
}


}
3 changes: 3 additions & 0 deletions application/config/internal.php
Expand Up @@ -39,6 +39,9 @@
file_exists(__DIR__ . '/config.php') ? 'pluginManager' : null
],
'components' => [
'surveySessionManager' => [
'class' => SurveySessionManager::class
],
'migrationManager' => [
'class' => 'MigrationManager'
],
Expand Down
15 changes: 2 additions & 13 deletions application/controllers/PrintanswersController.php
Expand Up @@ -42,14 +42,6 @@ function actionView($surveyid,$printableexport=FALSE)

Yii::app()->loadHelper('database');

if (isset($_SESSION['survey_'.$iSurveyID]['sid']))
{
$iSurveyID = $_SESSION['survey_'.$iSurveyID]['sid'];
}
else
{
//die('Invalid survey/session');
}
// Get the survey inforamtion
// Set the language for dispay
if (isset($_SESSION['survey_'.$iSurveyID]['s_lang']))
Expand All @@ -70,7 +62,7 @@ function actionView($surveyid,$printableexport=FALSE)
//SET THE TEMPLATE DIRECTORY
$sTemplate = $aSurveyInfo['template'];
//Survey is not finished or don't exist
if (!isset($_SESSION['survey_'.$iSurveyID]['finished']) || !isset($_SESSION['survey_'.$iSurveyID]['srid']))
if (!App()->surveySessionManager->isActive || !App()->surveySessionManager->current->isFinished)
//display "sorry but your session has expired"
{
sendCacheHeaders();
Expand All @@ -86,10 +78,7 @@ function actionView($surveyid,$printableexport=FALSE)
exit;
}
//Fin session time out
$sSRID = $_SESSION['survey_'.$iSurveyID]['srid']; //I want to see the answers with this id
//Ensure script is not run directly, avoid path disclosure
//if (!isset($rootdir) || isset($_REQUEST['$rootdir'])) {die( "browse - Cannot run this script directly");}

$sSRID = App()->surveySessionManager->current->responseId;
//Ensure Participants printAnswer setting is set to true or that the logged user have read permissions over the responses.
if ($aSurveyInfo['printanswers'] == 'N' && !App()->user->checkAccess('responses', ['crud' => 'read', 'entity' => 'survey', 'entity_id' => $iSurveyID]))
{
Expand Down
19 changes: 12 additions & 7 deletions application/controllers/SurveysController.php
Expand Up @@ -106,10 +106,10 @@ protected function loadModel($id) {

/**
* This function starts the survey.
* If a welcome screen is active it redirects to the welcome action.
* If a welcome screen is active it shows the welcome screen.
* @param $id
*/
public function actionStart($id, $token = null, $skipWelcome = false)
public function actionStart($id, $token = null)
{
$survey = $this->loadModel($id);
$this->layout = 'bare';
Expand All @@ -126,9 +126,12 @@ public function actionStart($id, $token = null, $skipWelcome = false)
'surveyId' => $id,
];

if ($survey->bool_showwelcome && !$skipWelcome && $survey->format != 'A') {
$this->render('welcome', ['survey' => $survey]);
} else {
if (App()->request->isPostRequest || $survey->format == 'A' || !$survey->bool_showwelcome) {

// Create response.
/**
* @todo Check if we shoudl resume an existing response instead.
*/
$response = \Response::create($id);
if (isset($token)) {
/**
Expand All @@ -137,9 +140,11 @@ public function actionStart($id, $token = null, $skipWelcome = false)
$response->token = $token->token;
}
$response->save();
$this->redirect(['surveys/run', 'id' => $response->id, 'surveyId' => $id]);
}

$this->render('start', ['url' => ['surveys/run', 'id' => $response->id, 'surveyId' => $id]]);
} else {
$this->render('welcome', ['survey' => $survey, 'id' => 'test']);
}
}

public function actionRun($id, $surveyId)
Expand Down
121 changes: 121 additions & 0 deletions application/controllers/TokensController.php
@@ -0,0 +1,121 @@
<?php
namespace ls\controllers;
use Yii;
use ls\pluginmanager\PluginEvent;
class TokensController extends Controller
{
public function actions() {
return [
'captcha' => [
'class' => \CCaptchaAction::class,
'testLimit' => 1
]
];
}

public function actionRegister($surveyId)
{
$this->layout = 'minimal';
if (null === $survey = \Survey::model()->findByPk($surveyId)) {
throw new \CHttpException(404, "The survey in which you are trying to participate does not seem to exist. It may have been deleted or the link you were given is outdated or incorrect.");
} elseif (!$survey->bool_allowregister) {
throw new \CHttpException(403, "The survey in which you are trying to register does not allow registration. It may have been updated or the link you were given is outdated or incorrect.");
}
$token = \Token::create($survey->sid, 'register');
if (App()->request->isPostRequest) {
$token->setAttributes(App()->request->getPost(get_class($token)));
$token->generateToken();
if ($token->save()) {
$this->renderText($this->sendRegistrationEmail($token));
return;
}
}
$this->render('register', ['survey' => $survey, 'token' => $token]);
}

/**
* Send the register email with $_POST value
* @param $iSurveyId Survey Id to register
* @return boolean : if email is set to sent (before SMTP problem)
*/
protected function sendRegistrationEmail(\Token $token){

$sLanguage=App()->language;
$iSurveyId = $token->surveyId;
$aSurveyInfo=getSurveyInfo($iSurveyId ,$sLanguage);
$aMail['subject']=$aSurveyInfo['email_register_subj'];
$aMail['message']=$aSurveyInfo['email_register'];
$aReplacementFields=array();
$aReplacementFields["{ADMINNAME}"]=$aSurveyInfo['adminname'];
$aReplacementFields["{ADMINEMAIL}"]=$aSurveyInfo['adminemail'];
$aReplacementFields["{SURVEYNAME}"]=$aSurveyInfo['name'];
$aReplacementFields["{SURVEYDESCRIPTION}"]=$aSurveyInfo['description'];
$aReplacementFields["{EXPIRY}"]=$aSurveyInfo["expiry"];
foreach($token->attributes as $attribute=>$value){
$aReplacementFields["{".strtoupper($attribute)."}"]=$value;
}
$useHtmlEmail = (getEmailFormat($iSurveyId) == 'html');
$aMail['subject']=preg_replace("/{TOKEN:([A-Z0-9_]+)}/","{"."$1"."}",$aMail['subject']);
$aMail['message']=preg_replace("/{TOKEN:([A-Z0-9_]+)}/","{"."$1"."}",$aMail['message']);
$aReplacementFields["{SURVEYURL}"] = App()->createAbsoluteUrl("/survey/index/sid/{$iSurveyId}",array('lang'=>$sLanguage,'token'=> $token->token));
$aReplacementFields["{OPTOUTURL}"] = App()->createAbsoluteUrl("/optout/tokens/surveyid/{$iSurveyId}",array('langcode'=>$sLanguage,'token'=> $token->token));
$aReplacementFields["{OPTINURL}"] = App()->createAbsoluteUrl("/optin/tokens/surveyid/{$iSurveyId}",array('langcode'=>$sLanguage,'token'=> $token->token));
foreach(array('OPTOUT', 'OPTIN', 'SURVEY') as $key)
{
$url = $aReplacementFields["{{$key}URL}"];
if ($useHtmlEmail)
$aReplacementFields["{{$key}URL}"] = "<a href='{$url}'>" . htmlspecialchars($url) . '</a>';
$aMail['subject'] = str_replace("@@{$key}URL@@", $url, $aMail['subject']);
$aMail['message'] = str_replace("@@{$key}URL@@", $url, $aMail['message']);
}
// Replace the fields
$aMail['subject']=ReplaceFields($aMail['subject'], $aReplacementFields);
$aMail['message']=ReplaceFields($aMail['message'], $aReplacementFields);
$sFrom = "{$aSurveyInfo['adminname']} <{$aSurveyInfo['adminemail']}>";
$sBounce=getBounceEmail($iSurveyId);
$sTo=$token->email;
// Plugin event for email handling (Same than admin token but with register type)
$event = new PluginEvent('beforeTokenEmail');
$event->set('type', 'register');
$event->set('subject', $aMail['subject']);
$event->set('to', $sTo);
$event->set('body', $aMail['message']);
$event->set('from', $sFrom);
$event->set('bounce',$sBounce );
$event->set('token', $token->attributes);
$aMail['subject'] = $event->get('subject');
$aMail['message'] = $event->get('body');
$sTo = $event->get('to');
$sFrom = $event->get('from');
if ($event->get('send', true) == false)
{
$message = $event->get('message', '');
if($event->get('error')==null){// mimic token system, set send to today
$today = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig('timeadjust'));
$token->sent = $today;
$token->save();
}
}
elseif (SendEmailMessage($aMail['message'], $aMail['subject'], $sTo, $sFrom, Yii::app()->getConfig('sitename'),$useHtmlEmail,$sBounce))
{
// TLR change to put date into sent
$today = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig('timeadjust'));
$token->sent = $today;
$token->save();
$message = "<div id='wrapper' class='message tokenmessage'>"
. "<p>".gT("Thank you for registering to participate in this survey.")."</p>\n"
. "<p>{$this->sMailMessage}</p>\n"
. "<p>".sprintf(gT("Survey administrator %s (%s)"),$aSurveyInfo['adminname'],$aSurveyInfo['adminemail'])."</p>"
. "</div>\n";
}
else
{
$message = "<div id='wrapper' class='message tokenmessage'>"
. "<p>".gT("Thank you for registering to participate in this survey.")."</p>\n"
. "<p>".gT("You are registred but an error happen when trying to send the email, please contact the survey administrator.")."</p>\n"
. "<p>".sprintf(gT("Survey administrator %s (%s)"),$aSurveyInfo['adminname'],$aSurveyInfo['adminemail'])."</p>"
. "</div>\n";
}
return $message;
}
}
4 changes: 2 additions & 2 deletions application/controllers/UploaderController.php
Expand Up @@ -20,8 +20,8 @@
class UploaderController extends SurveyController {
function run($actionID)
{
if(isset($_SESSION['LEMsid']) && $oSurvey=Survey::model()->findByPk($_SESSION['LEMsid'])){
$surveyid= $_SESSION['LEMsid'];
if(isset(App()->surveySessionManager->current) && $oSurvey=Survey::model()->findByPk(App()->surveySessionManager->current->surveyId)){
$surveyid = App()->surveySessionManager->current->surveyId;
}else{
throw new CHttpException(400);// See for debug > 1
}
Expand Down
2 changes: 0 additions & 2 deletions application/controllers/admin/surveyadmin.php
Expand Up @@ -244,8 +244,6 @@ public function view($iSurveyID, $gid = null, $qid = null)
if (isset($qid))
$qid = sanitize_int($qid);

// Reinit LEMlang and LEMsid: ensure LEMlang are set to default lang, surveyid are set to this survey id
// Ensure Last GetLastPrettyPrintExpression get info from this sid and default lang
LimeExpressionManager::SetEMLanguage(Survey::model()->findByPk($iSurveyID)->language);
LimeExpressionManager::SetSurveyId($iSurveyID);
LimeExpressionManager::StartProcessingPage(false,true);
Expand Down
3 changes: 2 additions & 1 deletion application/core/WebApplication.php
Expand Up @@ -22,7 +22,8 @@
* @property LocalizedFormatter $format
* @property \ls\pluginmanager\PluginManager $pluginManager
* @property CDbConnection $db
* @property CHttpRequest $request;
* @property SurveySessionManager $surveySessionManager
* @property \CHttpRequest $request;
* @property WebUser $user
*/
class WebApplication extends CWebApplication
Expand Down
10 changes: 7 additions & 3 deletions application/helpers/SurveyRuntimeHelper.php
Expand Up @@ -429,9 +429,13 @@ function run($surveyid,$args) {

if ($surveyMode != 'survey' && $_SESSION[$LEMsessid]['step'] == 0)
{
$_SESSION[$LEMsessid]['test']=time();
display_first_page();
Yii::app()->end(); // So we can still see debug messages
// $_SESSION[$LEMsessid]['test']=time();

$moveResult = LimeExpressionManager::JumpTo(1, false, false, true);
$_SESSION[$LEMsessid]['step']=1;
// display_first_page();
// Yii::app()->end(); // So we can still see debug messages
// $_SESSION[$LEMsessid]['step']++;
}

// TODO FIXME
Expand Down
8 changes: 2 additions & 6 deletions application/helpers/common_helper.php
Expand Up @@ -1673,14 +1673,10 @@ function createCompleteSGQA($iSurveyID,$aFilters,$sLanguage) {
*/
function createFieldMap($surveyid, $style='short', $force_refresh=false, $questionid=false, $sLanguage) {
global $aDuplicateQIDs;

\Yii::beginProfile('fieldmap');
$sLanguage = sanitize_languagecode($sLanguage);
$surveyid = sanitize_int($surveyid);

//checks to see if fieldmap has already been built for this page.
if (isset(Yii::app()->session['fieldmap-' . $surveyid . $sLanguage]) && !$force_refresh && $questionid == false) {
return Yii::app()->session['fieldmap-' . $surveyid . $sLanguage];
}

App()->setLanguage($sLanguage);
$fieldmap["id"]=array("fieldname"=>"id", 'sid'=>$surveyid, 'type'=>"id", "gid"=>"", "qid"=>"", "aid"=>"");
Expand Down Expand Up @@ -2245,6 +2241,7 @@ function createFieldMap($surveyid, $style='short', $force_refresh=false, $questi
}
Yii::app()->session['fieldmap-' . $surveyid . $sLanguage]=$fieldmap;
}
\Yii::endProfile('fieldmap');
return $fieldmap;
}
}
Expand Down Expand Up @@ -3895,7 +3892,6 @@ function SendEmailMessage($body, $subject, $to, $from, $sitename, $ishtml=false,
}


require_once(APPPATH.'/third_party/phpmailer/class.phpmailer.php');
$mail = new PHPMailer;
if (!$mail->SetLanguage($defaultlang,APPPATH.'/third_party/phpmailer/language/'))
{
Expand Down

0 comments on commit 22a3e27

Please sign in to comment.