Skip to content

Commit

Permalink
Fixed Issue: force_xmlsettings_for_survey_rendering not taken in account
Browse files Browse the repository at this point in the history
  • Loading branch information
LouisGac committed Sep 11, 2019
1 parent dc1cde6 commit 115256d
Show file tree
Hide file tree
Showing 8 changed files with 124 additions and 53 deletions.
8 changes: 5 additions & 3 deletions application/commands/TwigCommand.php
Expand Up @@ -18,22 +18,24 @@ public function actionGenerateTwigTmpFiles( ) {
Yii::import('application.helpers.expressions.em_manager_helper', true);
Yii::app()->assetManager->setBasePath(realpath(__DIR__.'/../../tmp/'));

Yii::app()->setConfig('force_xmlsettings_for_survey_rendering', true);

$aLogs = array();

// TODO: make this a parameter so the command line can be used for custom themes, question themes, etc; or create subfunctions ; or both

$sThemeDir = dirname(__FILE__).'/../../themes/survey';

$oThemeDir = new DirectoryIterator($sThemeDir);

foreach ($oThemeDir as $fileinfo) {
if ($fileinfo->getFilename() != ".." && $fileinfo->getFilename() != "."){

if ($fileinfo->getFilename() != ".." && $fileinfo->getFilename() != "." && $fileinfo->getFilename() != "index.html"){
$templatename = $fileinfo->getFilename();

$oTemplateForPreview = Template::getInstance($templatename, null, null, true, true)->prepareTemplateRendering($templatename, null, true);
$thissurvey = $oTemplateForPreview->getDefaultDataForRendering();
$thissurvey['templatedir'] = $templatename;

// TODO : for each screen
$aScreenList = $oTemplateForPreview->getScreenListWithLayoutAndContent();

foreach($aScreenList as $sScreenName => $aLayoutAndContent){
Expand Down
75 changes: 45 additions & 30 deletions application/core/LSETwigViewRenderer.php
Expand Up @@ -79,7 +79,7 @@ public function renderTemplateFromFile($sLayout, $aDatas, $bReturn)
* Extendable to use admin templates in the future currently running on pathes, like the yii render methods go.
* @param string $sLayout the name of the layout to render
* @param array $aDatas the datas needed to fill the layout
* @param boolean $bReturn if true, it will return the html string without rendering the whole page.
* @param boolean $bReturn if true, it will return the html string without rendering the whole page.
* Usefull for debuging, and used for Print Answers
* @param boolean $bUseRootDir Prepend application root dir to sLayoutFilePath if true.
* @return string HTML
Expand Down Expand Up @@ -150,7 +150,7 @@ public function renderQuestion($sView, $aData)
// current controller properties will be accessible as {{ this.property }}
// aData and surveyInfo variables are accessible from question type twig files
$aData['aData'] = $aData;

// check if this method is called from theme editor
if (empty($aData['bIsThemeEditor'])){
$aData['question_template_attribute'] = $oQuestionTemplate->getCustomAttributes();
Expand Down Expand Up @@ -206,13 +206,13 @@ public function renderAnswerOptions($sView, $aData)
if (file_exists($requiredView.'.twig')) {
// We're not using the Yii Theming system, so we don't use parent::renderFile
// current controller properties will be accessible as {{ this.property }}

// aData and surveyInfo variables are accessible from question type twig files
$aData['aData'] = $aData;
$sBaseLanguage = Survey::model()->findByPk($_SESSION['LEMsid'])->language;
$aData['surveyInfo'] = getSurveyInfo($_SESSION['LEMsid'], $sBaseLanguage);
$aData['this'] = Yii::app()->getController();

$aData['question_template_attribute'] = null;

$template = $this->_twig->loadTemplate($sView.'.twig')->render($aData);
Expand Down Expand Up @@ -246,7 +246,7 @@ public function renderTemplateForTemplateEditor($sView, $aDatas, $oEditedTemplat
/**
* Render the option page of a template for the admin interface
* @param Template $oTemplate the template where the custom option page should be looked for
* @param array $renderArray Array that will be passed to the options.twig as variables.
* @param array $renderArray Array that will be passed to the options.twig as variables.
* @return string
*/
public function renderOptionPage($oTemplate, $renderArray = array())
Expand All @@ -255,10 +255,10 @@ public function renderOptionPage($oTemplate, $renderArray = array())
$sOptionFile = 'options/options.twig';
$sOptionJS = 'options/options.js';
$sOptionsPath = $oRTemplate->sTemplateurl.'options';

// We get the options twig file from the right template (local or mother template)
while (!file_exists($oRTemplate->path.$sOptionFile)) {

$oMotherTemplate = $oRTemplate->oMotherTemplate;
if (!($oMotherTemplate instanceof TemplateConfiguration)) {
return sprintf(gT('%s not found!', $oRTemplate->path.$sOptionFile));
Expand Down Expand Up @@ -320,8 +320,9 @@ public function renderHtmlPage($sHtml, $oTemplate)
* @param TemplateConfiguration|null $oTemplate
* @return string
*/
public function convertTwigToHtml($sString, $aDatas, $oTemplate = null)
public function convertTwigToHtml($sString, $aDatas=array(), $oTemplate = null)
{

// Twig init
$this->_twig = $twig = parent::getTwig();

Expand All @@ -334,7 +335,10 @@ public function convertTwigToHtml($sString, $aDatas, $oTemplate = null)
$this->addRecursiveTemplatesPath($oTemplate);

// Plugin for blocks replacement
list($sString, $aDatas) = $this->getPluginsData($sString, $aDatas);

list($sString, $aDatas) = $this->getPluginsData($sString, $aDatas);


}

// Twig rendering
Expand Down Expand Up @@ -377,17 +381,22 @@ private function addRecursiveTemplatesPath($oTemplate,$extraPaths=array(),$dirNa
$loader = $this->_twig->getLoader();
$loader->setPaths(array()); /* Always reset (needed for Question template / $extraPaths, maybe in some other situation) */
/* Event to add or replace twig views */
$oEvent = new PluginEvent('getPluginTwigPath');
App()->getPluginManager()->dispatchEvent($oEvent);
$configTwigExtendsAdd = (array) $oEvent->get("add");
$configTwigExtendsReplace = (array) $oEvent->get("replace");

/* Forced twig by plugins (used to replace vanilla or core template … don't like to force on user template, but else can extend current core twig) */
foreach($configTwigExtendsReplace as $configTwigExtendReplace) {
if(is_string($configTwigExtendReplace)) { // Need more control ?
$loader->addPath($configTwigExtendReplace);
}


if (! App()->getConfig('force_xmlsettings_for_survey_rendering')){
$oEvent = new PluginEvent('getPluginTwigPath');
App()->getPluginManager()->dispatchEvent($oEvent);
$configTwigExtendsAdd = (array) $oEvent->get("add");
$configTwigExtendsReplace = (array) $oEvent->get("replace");

/* Forced twig by plugins (used to replace vanilla or core template … don't like to force on user template, but else can extend current core twig) */
foreach($configTwigExtendsReplace as $configTwigExtendReplace) {
if(is_string($configTwigExtendReplace)) { // Need more control ?
$loader->addPath($configTwigExtendReplace);
}
}
}

if(!empty($dirName)) {

This comment has been minimized.

Copy link
@Shnoulle

Shnoulle Sep 12, 2019

Collaborator

We need a new feature force_xml_rendering_by_plugins_or_by_survey_theme_is_pugin_force_it TODO : find a better name………………

/* This template for dirName template*/
if(is_dir($oRTemplate->viewPath.$dirName)) {
Expand Down Expand Up @@ -416,11 +425,14 @@ private function addRecursiveTemplatesPath($oTemplate,$extraPaths=array(),$dirNa
$loader->addPath($oRTemplate->viewPath);
}
/* Added twig by plugins, replaced by any template file or question template file*/
foreach($configTwigExtendsAdd as $configTwigExtendAdd) {
if(is_string($configTwigExtendAdd)) {
$loader->addPath($configTwigExtendAdd);
}
if (isset($configTwigExtendsAdd)){
foreach($configTwigExtendsAdd as $configTwigExtendAdd) {
if(is_string($configTwigExtendAdd)) {
$loader->addPath($configTwigExtendAdd);
}
}
}

$loader->addPath(App()->getBasePath().'/views/'); // Core views path
}

Expand All @@ -437,7 +449,7 @@ private function getPluginsData($sString, $aDatas)
$surveyid = $aDatas['aSurveyInfo']['sid'];
$event->set('surveyId', $aDatas['aSurveyInfo']['sid']);

// show "Exit and clear survey" button whenever there is 'srid' key set,
// show "Exit and clear survey" button whenever there is 'srid' key set,
// button won't be rendered on welcome and final page because 'srid' key doesn't exist on those pages
// additionally checks for submit page to compensate when srid is needed to render other views
if (
Expand All @@ -450,12 +462,15 @@ private function getPluginsData($sString, $aDatas)
}
}

App()->getPluginManager()->dispatchEvent($event);
$aPluginContent = $event->getAllContent();
if (!empty($aPluginContent['sTwigBlocks'])) {
$sString = $sString.$aPluginContent['sTwigBlocks'];
if (!App()->getConfig('force_xmlsettings_for_survey_rendering')){
App()->getPluginManager()->dispatchEvent($event);
$aPluginContent = $event->getAllContent();
if (!empty($aPluginContent['sTwigBlocks'])) {
$sString = $sString.$aPluginContent['sTwigBlocks'];
}
}


return array($sString, $aDatas);
}

Expand Down Expand Up @@ -490,7 +505,7 @@ private function getAdditionalInfos($aDatas, $oTemplate)
if (isset($_SESSION['survey_'.$aDatas['aSurveyInfo']['sid']]) && isset($_SESSION['survey_'.$aDatas['aSurveyInfo']['sid']]['totalquestions'])) {
$aDatas["aSurveyInfo"]['iTotalquestions'] = $_SESSION['survey_'.$aDatas['aSurveyInfo']['sid']]['totalquestions'];
}

// Add the survey theme options
if ($oTemplate->oOptions) {
foreach ($oTemplate->oOptions as $key => $value) {
Expand All @@ -499,7 +514,7 @@ private function getAdditionalInfos($aDatas, $oTemplate)
}
} else {
// Add the global theme options
$oTemplateConfigurationCurrent = TemplateConfiguration::getInstance($oTemplate->sTemplateName);
$oTemplateConfigurationCurrent = Template::getInstance($oTemplate->sTemplateName);
$aDatas["aSurveyInfo"]["options"] = isJson($oTemplateConfigurationCurrent['options'])?(array)json_decode($oTemplateConfigurationCurrent['options']):$oTemplateConfigurationCurrent['options'];
}

Expand Down
2 changes: 1 addition & 1 deletion application/core/LS_Twig_Extension.php
Expand Up @@ -313,7 +313,7 @@ public static function imageSrc($sImagePath, $default = false)
*/
public static function getTemplateForRessource($sRessource)
{
$oRTemplate = Template::model()->getInstance();
$oRTemplate = Template::getInstance();

while (!file_exists($oRTemplate->path.$sRessource)) {

Expand Down
27 changes: 12 additions & 15 deletions application/models/Template.php
Expand Up @@ -316,7 +316,7 @@ public static function getTemplateConfiguration($sTemplateName = null, $iSurveyI
{

// First we try to get a confifuration row from DB
if (!$bForceXML) {
if (!$bForceXML ) {
// The name need to be filtred only for DB version. From TemplateEditor, the template is not installed.
$sTemplateName = (empty($sTemplateName)) ? null : self::templateNameFilter($sTemplateName);
$oTemplateConfigurationModel = TemplateConfiguration::getInstance($sTemplateName, $iSurveyGroupId, $iSurveyId, $abstractInstance);
Expand All @@ -325,9 +325,9 @@ public static function getTemplateConfiguration($sTemplateName = null, $iSurveyI

// If no row found, or if the template folder for this configuration row doesn't exist we load the XML config (which will load the default XML)
if ($bForceXML || !is_a($oTemplateConfigurationModel, 'TemplateConfiguration') || !$oTemplateConfigurationModel->checkTemplate()) {
$oTemplateConfigurationModel = new TemplateManifest;
$oTemplateConfigurationModel->setBasics($sTemplateName, $iSurveyId);

$oTemplateConfigurationModel = new TemplateManifest(null);
$oTemplateConfigurationModel->setBasics($sTemplateName, $iSurveyId);
}

//$oTemplateConfigurationModel->prepareTemplateRendering($sTemplateName, $iSurveyId);
Expand Down Expand Up @@ -482,20 +482,17 @@ public static function isStandardTemplate($sTemplateName)
*/
public static function getInstance($sTemplateName = null, $iSurveyId = null, $iSurveyGroupId = null, $bForceXML = null, $abstractInstance = false)
{

if ($bForceXML === null) {
// Template developper could prefer to work with XML rather than DB as a first step, for quick and easy changes
$bForceXML = (App()->getConfig('force_xmlsettings_for_survey_rendering'))?true:false;
}

// The error page from default template can be called when no survey found with a specific ID.
if ($sTemplateName === null && $iSurveyId === null) {
$sTemplateName = App()->getConfig('defaulttheme');
}

if ($bForceXML === null) {
// Template developper could prefer to work with XML rather than DB as a first step, for quick and easy changes
if (App()->getConfig('force_xmlsettings_for_survey_rendering') && YII_DEBUG) {
$bForceXML = true;
} elseif (App()->getConfig('force_xmlsettings_for_survey_rendering') && YII_DEBUG) {
$bForceXML = false;
}
}

if($abstractInstance === true) {
return self::getTemplateConfiguration($sTemplateName, $iSurveyId, $iSurveyGroupId, $bForceXML, true);
}
Expand All @@ -517,17 +514,17 @@ public static function resetInstance()
{
self::$instance = null;
}

/**
* Alias function for resetAssetVersion()
* Don't delete this one to maintain updgrade compatibilty
* @return void
*/
public function forceAssets()
{
$this->resetAssetVersion();
$this->resetAssetVersion();
}

/**
* Reset assets for this template
* Using DB only
Expand Down
2 changes: 1 addition & 1 deletion application/models/TemplateConfig.php
Expand Up @@ -267,7 +267,7 @@ protected function createTemplatePackage($oTemplate)
$aJsFiles = array_merge($aJsFiles, $aTJsFiles);

// Remove/Replace mother template files
if ( ( $this->template instanceof Template && $this->template->extends) || !empty($this->config->metadata->extends) || Yii::app()->getConfig('force_xmlsettings_for_survey_rendering') ){
if ( Yii::app()->getConfig('force_xmlsettings_for_survey_rendering') || ( $this->template instanceof Template && $this->template->extends) || !empty($this->config->metadata->extends) ){
$aCssFiles = $this->changeMotherConfiguration('css', $aCssFiles);
$aJsFiles = $this->changeMotherConfiguration('js', $aJsFiles);
}
Expand Down
4 changes: 3 additions & 1 deletion application/models/TemplateConfiguration.php
Expand Up @@ -364,6 +364,8 @@ public static function checkAndcreateSurveyConfig($iSurveyId)

/**
* Get an instance of a fitting TemplateConfiguration
* NOTE: for rendering prupose, you should never call this function directly, but rather Template::getInstance.
* if force_xmlsettings_for_survey_rendering is on, then the configuration from the XML file should be loaded, not the one from database
*
* @param string $sTemplateName
* @param integer $iSurveyGroupId
Expand Down Expand Up @@ -440,7 +442,7 @@ public function searchGrid()
$criteria = new CDbCriteria;

$criteria->join = 'INNER JOIN {{templates}} AS template ON '.Yii::app()->db->quoteColumnName("t.template_name").' = template.name';
$criteria->together = true;
$criteria->together = true;
//Don't show surveyspecifi settings on the overview
$criteria->addCondition('t.sid IS NULL');
$criteria->addCondition('t.gsid IS NULL');
Expand Down
27 changes: 26 additions & 1 deletion application/models/TemplateManifest.php
Expand Up @@ -529,7 +529,15 @@ public function getOtherFiles()
*/
public function getTemplateURL()
{
return Template::getTemplateURL($this->sTemplateName);

// By default, theme folder is always the folder name. @See:TemplateConfig::importManifest().
if (Template::isStandardTemplate($this->sTemplateName)) {
return Yii::app()->getConfig("standardthemerooturl").'/'.$this->sTemplateName.'/';
} else {
return Yii::app()->getConfig("userthemerooturl").'/'.$this->sTemplateName.'/';
}

// return Template::getTemplateURL($this->sTemplateName);
}


Expand Down Expand Up @@ -1235,4 +1243,21 @@ public function getTemplateAndMotherNames()

return $sTemplateNames;
}



/**
* PHP getter magic method.
* This method is overridden so that AR attributes can be accessed like properties.
* @param string $name property name
* @return mixed property value
* @see getAttribute
*/
public function __get($name)
{
if ($name=="options"){
return json_encode( $this->config->options);
}
return parent::__get($name);
}
}
32 changes: 31 additions & 1 deletion themes/survey/bootswatch/config.xml
Expand Up @@ -42,7 +42,7 @@
'force_xmlsettings_for_survey_rendering' => true,
Then, you will not need anymore to reset your theme each time you change the config file.
But, once turning the setting off, You will still must reset the theme to the changes are pushed to DB
But, once turning the setting off, You will still must reset the theme to the changes are pushed to DB
-->
<files>
<css>
Expand Down Expand Up @@ -256,6 +256,36 @@
</navigation>

</screens>

<!-- Data for preview in Theme Editor and Twig Cache command line generator -->
<default_data>
<survey>
<name type="data" twig="on"><![CDATA[ {{ gT("Template Sample") }} ]]></name>
<description type="data" twig="on"><![CDATA[<p>{{ gT('This is a sample survey description. It could be quite long.') }}</p><p>{{ gT("But this one isn't.") }}<p>]]></description>
<welcome type="data" twig="on"><![CDATA[<p>{{ gT('Welcome to this sample survey')}} <p> <p> {{ gT('You should have a great time doing this') }} <p> ]]></welcome>
<therearexquestions type="data" twig="on"><![CDATA[gT('There is 2 question in this survey'])]]></therearexquestions>
<surveyls_url type="data" twig="on">"https://www.limesurvey.org/"</surveyls_url>
<surveyls_urldescription type="data" twig="on"><![CDATA[ gT("Some URL description") ]]></surveyls_urldescription>
</survey>
<group>
<name type="data" twig="on"><![CDATA[ {{ gT("Group 1: The first lot of questions") }} ]]></name>
<description type="data" twig="on"><![CDATA[ {{ gT("This group description is fairly vacuous, but quite important.") }} ]]></description>
</group>
<question_1>
<code type="data" >'Q1 '</code>
<text type="data" twig="on"><![CDATA[ {{ gT("How many roads must a man walk down?") }} ]]></text>
<valid_message type="data" twig="on"><![CDATA[ <div id="vmsg_4496_num_answers" class="em_num_answers emtip error"><span class="fa fa-exclamation-circle" aria-hidden="true"></span> {{ gT("Choose one of the following answers") }} </div> ]]></valid_message>
</question_1>
<question_2>
<code type="data" >'Q2 '</code>
<text type="data" twig="on"><![CDATA[ {{ gT("Please explain something in detail:") }} ]]></text>
<valid_message type="data" twig="on"><![CDATA[<div id="vmsg_4496_num_answers" class="em_num_answers emtip error"><span class="fa fa-exclamation-circle" aria-hidden="true"></span> {{ gT("Hint when response is not valid") }} </div> ]]></valid_message>
</question_2>
<assessments>
<name type="data" twig="on"><![CDATA[ {{ gT("Welcome to the Assessment") }} ]]></name>
<message type="data" twig="on"><![CDATA[ {{ gT("You got {TOTAL} points out of 3 possible points.") }} ]]></message>
</assessments>
</default_data>
</template_editor>
</engine>

Expand Down

0 comments on commit 115256d

Please sign in to comment.