Typo3: Disable caching for viewhelper inside gridelements fluid template - caching

I have an inherited typo3 website (running 10.4.31 now) that must have been created in 2016 or so, and it contains a custom ViewHelper that has some time-based logic (you can set a countdown and once it's elapsed, something is supposed to happen). The problem is that it only works if you're logged in, in dev environments or when you have the cache disabled globally.
the setup is something like this:
TypoScript:
tt_content.gridelements_pi1.20.10.setup {
37 < lib.gridelements.defaultGridSetup
37 {
cObject = FLUIDTEMPLATE
cObject {
file = EXT:myext/Resources/Private/Templates/gridelements/ce/countdown.html
}
}
}
Template
<div class="countdown-container">
{namespace content=My\Ext\ViewHelpers}
<content:Countdown time="{data.flexform_date}" image="{data.flexform_image}" />
</div>
and then the aforementioned custom Viewhelper.
The question is: Is there any way to tell typo3 to execute the ViewHelper's PHP code every time instead of caching? I have googled a lot, but none of the solutions I've found work. Things I have tried include:
adding <f:cache.disable /> to the HTML template: no effect
throwing StopCompilingException from the ViewHelper's compile method: no effect (but I can see that the exception gets thrown and caught)
adding COA_INT or USER_INT to the typoscript: no effect (I can see them in the object browser, but honestly I don't know if I put them in the right place)

You can disable the cache for this specific Gridelement by using a COA_INT container as surrounding cObject:
tt_content.gridelements_pi1.20.10.setup {
37 < lib.gridelements.defaultGridSetup
37 {
cObject = COA_INT
cObject {
10 = FLUIDTEMPLATE
10.file = EXT:myext/Resources/Private/Templates/gridelements/ce/countdown.html
}
}
}

Related

Add dataProcessor to ckeditor yaml configuration in TYPO3

I'm wondering how to add a rule to the dataProcessor like it was possible in the old htmlarea.
In my case I want to add a fixed class to the "ul"-tag.
I tried something like that (tried to adapt the js configuration from ckeditor)
editor:
config:
format_p:
- { element : 'p', attributes : { 'class' : 'ul' }}
...but it does not work.
I did it now via TypoScript like this:
### Set default class for ul from rte
lib.parseFunc_RTE {
externalBlocks := addToList(ul)
externalBlocks {
ul.stripNL = 1
ul.callRecursive = 1
ul.callRecursive.tagStdWrap.HTMLparser = 1
ul.callRecursive.tagStdWrap.HTMLparser.tags.ul {
fixAttrib.class.default = ul
}
}
}
It does basically what I want, BUT still I think this is not optimal. The class is not stored in the DataBase, so if you need to export the content for some reason you will loose this class. And you can not style it in the BE RTE-field (at least not without providing some extra hack css)
So I'm still interested if there is a proper way of doing it in the ckeditor-config.

Ckeditor plugin configuration not working

I have tried to add justify plugin to be able to align text right, left or centre. But after following the instructions in the documentation (http://apostrophecms.org/docs/tutorials/howtos/ckeditor.html), I wonder if the plugin should be located in a specific folder (mine is at public/modules/apostrophe-areas/js/ckeditorPlugins/justify/), as it disappears when the site is loaded, but if I include it in some other folder such as public/plugins/justify still doesn't work.
This is my code just in case: (located at lib/modules/apostrophe-areas/public/js/user.js)
apos.define('apostrophe-areas', {
construct: function(self, options) {
// Use the super pattern - don't forget to call the original method
var superEnableCkeditor = self.enableCkeditor;
self.enableCkeditor = function() {
superEnableCkeditor();
// Now do as we please
CKEDITOR.plugins.addExternal('justify', '/modules/apostrophe-areas/js/ckeditorPlugins/justify/', 'plugin.js');
};
}
});
Also, it would be nice to know how the plugin should be called at the Toolbar settings for editable widgets.
Thanks!
The URL you need is:
/modules/my-apostrophe-areas/js/ckeditorPlugins/justify/
The my- prefix is automatically prepended so that the public folders of both the original apostrophe-areas module and your project-level extension of it can have a distinct URL. Otherwise there would be no way for both to access their user.js, for instance.
I'll add this note to the HOWTO in question, which currently handwaves the issue by stubbing in a made-up URL.
As for how the plugin should be called, use the toolbar control name exported by that plugin — that part is a ckeditor question, not really an Apostrophe one. But looking at the source code of that plugin they are probably JustifyLeft, JustifyCenter, JustifyRight and JustifyBlock.
It turns out that it's not enough to simply call CKEDITOR.plugins.addExternal inside apostophe-areas. You also need to override self.beforeCkeditorInline of the apostrophe-rich-text-widgets-editor module and explicitly call self.config.extraPlugins = 'your_plugin_name';.
Here's what I ended up with:
In lib/modules/apostrophe-areas/public/js/user.js:
apos.define('apostrophe-areas', {
construct: function(self, options) {
// Use the super pattern - don't forget to call the original method
var superEnableCkeditor = self.enableCkeditor;
self.enableCkeditor = function() {
superEnableCkeditor();
// Now do as we please
CKEDITOR.plugins.addExternal('justify', '/modules/my-apostrophe-areas/js/ckeditorPlugins/justify/', 'plugin.js');
};
}
});
then in in lib/modules/apostrophe-rich-text-widgets/public/js/editor.js:
apos.define('apostrophe-rich-text-widgets-editor', {
construct: function(self, options) {
self.beforeCkeditorInline = function() {
self.config.extraPlugins = 'justify';
};
}
});
For some reason doing CKEDITOR.config.extraPlugins = 'justify' inside apostrophe-areas does not work, probably due to the way how CKEDITOR is initialized;
One more thing: this particular plug-in (justify, that is) does not seem to follow the button definition logic. It has button icons defined as images, whereas CKEditor 4.6 used in Apostrophe CMS 2.3 uses font-awesome to display icons. It means that the icons that ship with the justify module won't be displayed and you'll have to write your own css for each button individually.
There is another issue which you'll probably face when you finally enable the justify buttons. The built-in html sanitizer will be strip off the styles justify adds to align the content.
Apostrophe CMS seems to be using sanitize-html to sanitize the input, so changing CKEditor settings won't have any effect. To solve the issue, add the following to your app.js:
'apostrophe-rich-text-widgets': {
// The standard list copied from the module, plus sup and sub
sanitizeHtml: {
allowedAttributes: {
a: ['href', 'name', 'target'],
img: ['src'],
'*': ['style'] //this will make sure the style attribute is not stripped off
}
}
}
Thank you both for your help. After following both approaches of: locating the plugin at my-apostrophe-areas folder as well as editing editor.js on the apostrophe-rich-text widget (the sanitize.html file was already using that configuration), I got the plugin working. However, I was still having the issue with the icons.
I fixed that adding the Font Awesome icons that correspond to align-justify, align-right, align-left and align-center at the end of public/modules/apostrophe-areas/js/vendor/ckeditor/skins/apostrophe/editor.less

ckeditor how to allow for .insertHtml("<customTag myAttr='value'"></customTag>")

var currentDialog = CKEDITOR.dialog.getCurrent();
currentDialog._.editor.insertHtml("<customTag myAttr='var'></customTag>");
Throws an error, TypeError: Cannot read property 'isBlock' of undefined
If I try .insertHtml("<span>hello</span>") it works just fine.
How can I change ckeditor to allow me to specify my own custom html tags via .insertHtml()? I'd love to just change it to be something like <span class='custom'... or something like that, but I'm having to deal with legacy CMS articles. Using latest ckeditor. Thanks.
You need to modify CKEDITOR.dtd object so editor will know this tag and correctly parse HTML and process DOM:
CKEDITOR.dtd.customtag = { em:1 }; // List of tag names it can contain.
CKEDITOR.dtd.$block.customtag = 1; // Choose $block or $inline.
CKEDITOR.dtd.body.customtag = 1; // Body may contain customtag.
You need to allow for this tag and its styles/attrs/classes in Advanced Content Filter:
editor.filter.allow( 'customtag[myattr]', 'myfeature' );
Unfortunately, due to some caching, in certain situations you cannot modify DTD object after CKEditor is loaded - you need to modify it when it is created. So to do that:
Clone the CKEditor repository or CKEditor presets repository.
Modify core/dtd.js code.
And build your minified package following instructions in README.md - the only requirements are Java (sorry - Google Closure Compiler :P) and Bash.
PS. That error should not be thrown when unknown element is inserted, so I reported http://dev.ckeditor.com/ticket/10339 and to solve this inconvenience http://dev.ckeditor.com/ticket/10340.
I worked around this issue with a combination of createFromHtml() and insertElement()
CKEDITOR.replace('summary', { ... });
var editor = CKEDITOR.instances.summary;
editor.on('key', function(ev) {
if (ev.data.keyCode == 9) { // TAB
var tabHtml = '<span style="white-space:pre"> </span>';
var tabElement = CKEDITOR.dom.element.createFromHtml(tabHtml, editor.document);
editor.insertElement(tabElement);
}
}

AngularJS disable partial caching on dev machine

I have problem with caching partials in AngularJS.
In my HTML page I have:
<body>
<div ng-view></div>
<body>
where my partials are loaded.
When I change HTML code in my partial, browser still load old data.
Is there any workaround?
For Development you can also deactivate the browser cache - In Chrome Dev Tools on the bottom right click on the gear and tick the option
Disable cache (while DevTools is open)
Update: In Firefox there is the same option in Debugger -> Settings -> Advanced Section (checked for Version 33)
Update 2: Although this option appears in Firefox some report it doesn't work. I suggest using firebug and following hadaytullah answer.
Building on #Valentyn's answer a bit, here's one way to always automatically clear the cache whenever the ng-view content changes:
myApp.run(function($rootScope, $templateCache) {
$rootScope.$on('$viewContentLoaded', function() {
$templateCache.removeAll();
});
});
As mentioned in the other answers, here and here, the cache can be cleared by using:
$templateCache.removeAll();
However as suggested by gatoatigrado in the comment, this only appears to work if the html template was served without any cache headers.
So this works for me:
In angular:
app.run(['$templateCache', function ( $templateCache ) {
$templateCache.removeAll(); }]);
You may be adding cache headers in a variety of ways but here are a couple of solutions that work for me.
If using IIS, add this to your web.config:
<location path="scripts/app/views">
<system.webServer>
<staticContent>
<clientCache cacheControlMode="DisableCache" />
</staticContent>
</system.webServer>
</location>
If using Nginx, you can add this to your config:
location ^~ /scripts/app/views/ {
expires -1;
}
Edit
I just realised that the question mentioned dev machine but hopefully this may still help somebody...
If you are talking about cache that is been used for caching of templates without reloading whole page, then you can empty it by something like:
.controller('mainCtrl', function($scope, $templateCache) {
$scope.clearCache = function() {
$templateCache.removeAll();
}
});
And in markup:
<button ng-click='clearCache()'>Clear cache</button>
And press this button to clear cache.
Solution For Firefox (33.1.1) using Firebug (22.0.6)
Tools > Web-Tools > Firebug > Open Firebug.
In the Firebug views go to the "Net" view.
A drop down menu symbol will appear next to "Net" (title of the view).
Select "Disable Browser Cache" from the drop down menu.
This snippet helped me in getting rid of template caching
app.run(function($rootScope, $templateCache) {
$rootScope.$on('$routeChangeStart', function(event, next, current) {
if (typeof(current) !== 'undefined'){
$templateCache.remove(current.templateUrl);
}
});
});
The details of following snippet can be found on this link:
http://oncodesign.io/2014/02/19/safely-prevent-template-caching-in-angularjs/
I'm posting this just to cover all possibilities since neither of the other solutions worked for me (they threw errors due angular-bootstrap template dependencies, among others).
While you are developing/debugging a specific template, you can ensure it always refreshes by included a timestamp in the path, like this:
$modal.open({
// TODO: Only while dev/debug. Remove later.
templateUrl: 'core/admin/organizations/modal-selector/modal-selector.html?nd=' + Date.now(),
controller : function ($scope, $modalInstance) {
$scope.ok = function () {
$modalInstance.close();
};
}
});
Note the final ?nd=' + Date.now() in the templateUrl variable.
As others have said, defeating caching completely for dev purposes can be done easily without changing code: use a browser setting or a plugin. Outside of dev, to defeat Angular template caching of route-based templates, remove the template URL from the cache during $routeChangeStart (or $stateChangeStart, for UI Router) as Shayan showed. However, that does NOT affect the caching of templates loaded by ng-include, because those templates are not loaded through the router.
I wanted to be able to hotfix any template, including those loaded by ng-include, in production and have users receive the hotfix in their browser quickly, without having to reload the entire page. I'm also not concerned about defeating HTTP caching for templates. The solution is to intercept every HTTP request that the app makes, ignore those that are not for my app's .html templates, then add a param to the template's URL that changes every minute. Note that the path-checking is specific to the path of your app's templates. To get a different interval, change the math for the param, or remove the % completely to get no caching.
// this defeats Angular's $templateCache on a 1-minute interval
// as a side-effect it also defeats HTTP (browser) caching
angular.module('myApp').config(function($httpProvider, ...) {
$httpProvider.interceptors.push(function() {
return {
'request': function(config) {
config.url = getTimeVersionedUrl(config.url);
return config;
}
};
});
function getTimeVersionedUrl(url) {
// only do for html templates of this app
// NOTE: the path to test for is app dependent!
if (!url || url.indexOf('a/app/') < 0 || url.indexOf('.html') < 0) return url;
// create a URL param that changes every minute
// and add it intelligently to the template's previous url
var param = 'v=' + ~~(Date.now() / 60000) % 10000; // 4 unique digits every minute
if (url.indexOf('?') > 0) {
if (url.indexOf('v=') > 0) return url.replace(/v=[0-9](4)/, param);
return url + '&' + param;
}
return url + '?' + param;
}
If you are using UI router then you can use a decorator and update $templateFactory service and append a query string parameter to templateUrl, and the browser will always load the new template from the server.
function configureTemplateFactory($provide) {
// Set a suffix outside the decorator function
var cacheBust = Date.now().toString();
function templateFactoryDecorator($delegate) {
var fromUrl = angular.bind($delegate, $delegate.fromUrl);
$delegate.fromUrl = function (url, params) {
if (url !== null && angular.isDefined(url) && angular.isString(url)) {
url += (url.indexOf("?") === -1 ? "?" : "&");
url += "v=" + cacheBust;
}
return fromUrl(url, params);
};
return $delegate;
}
$provide.decorator('$templateFactory', ['$delegate', templateFactoryDecorator]);
}
app.config(['$provide', configureTemplateFactory]);
I am sure you can achieve the same result by decorating the "when" method in $routeProvider.
I found that the HTTP interceptor method works pretty nicely, and allows additional flexibility & control. Additionally, you can cache-bust for each production release by using a release hash as the buster variable.
Here is what the dev cachebusting method looks like using Date.
app.factory('cachebustInjector', function(conf) {
var cachebustInjector = {
request: function(config) {
// new timestamp will be appended to each new partial .html request to prevent caching in a dev environment
var buster = new Date().getTime();
if (config.url.indexOf('static/angular_templates') > -1) {
config.url += ['?v=', buster].join('');
}
return config;
}
};
return cachebustInjector;
});
app.config(['$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push('cachebustInjector');
}]);
Here is another option in Chrome.
Hit F12 to open developer tools. Then Resources > Cache Storage > Refresh Caches.
I like this option because I don't have to disable cache as in other answers.
There is no solution to prevent browser/proxy caching since you cannot have the control on it.
The other way to force fresh content to your users it to rename the HTML file! Exactly like https://www.npmjs.com/package/grunt-filerev does for assets.

Is There an Editable File in Cognos For Importing Stylesheets or Javascript?

I have recently asked where global stylesheets are for editing Cognos 10 styles (Here).
After some discussions with our team we would like to find the CGI or base imported file that Cognos uses to construct it's report viewer pages and dashboard widget holders.
The reason we want to do this is so that we can include all our custom style and javascript in one location. When/If we upgrade Cognos we can be sure of one point of failure with our reports. This would solve our problem of having to re-edit multiple stylesheets (and javascript).
I'm normally familiar with ASP.NET and not CGI-BIN. Is there something akin to a Master page where styles and basic imports are done for a Cognos page? Ideally editing this file would allow us to continue our customizations.
Can this be done? Or are we just insane? We understand the risks concerning upgrades, but are OK with the risks (unless someone can provide a good example of how this technique would not be replicated via version changes).
I think it's fairly common that BI professionals with more traditional web development backgrounds like me and you have no qualms with making changes to the global CSS files and bringing in more JS.
I've explained to you how I run JS in a report - I'd love to add jQuery to our global libraries, but I haven't drummed up enough support for it yet. I can help with the CSS portion though.
In 8.4.1, there's a ton of CSS files referenced by the report viewer. If I were you, I'd render a sample report with the default styling and use Firebug or similar to trace the CSS files being called. You'll find that server/cognos8/schemas/GlobalReportStyles.css is commonly referenced, with some help from server/cognos8/skins/corporate/viewer/QSRVCommon.css - there's also some other files in there that are imported.
I'd imagine you could grep -R '<link rel=\"stylesheet\" type=\"text/css\" href=\"../schemas/GlobalReportStyles.css\"> in the COGNOS directory to see where the file is being called, and either edit that file directly, or create a link to your own JS. Personally, I'd just backup the existing stylesheet and modify the one that is already there.
I'd imagine you could do something similar for the JS - find where it's being called in the template (using grep) and just create a new reference to the file you'd like to create. In my case, I'd do a backflip if I could get jQuery loaded into every report.
Just realized this is a year old. :-( Sorry, first time here. I'll leave it in case anyone is still interested in the topic.
Here is the documentation on customizing Cognos on several levels:
We used an alternative to modifying the system files. We have a shared component "report" containing an HTML object with our particular CSS overrides on it, and/or a link to a custom stylesheet. We then add this on each report with a "Layout Component Reference" from the toolbox. If we want a global change, just change the one item in the component report or custom stylesheet. This works very well for us.
I up-voted both the previous answers to this question. I'll admit I kind of forgot about this question till someone put some activity on it.
We ended up doing a combination of the above techniques. I was able to find the global stylesheets as suggested. What I ended up doing was copying out all the styles that were in that stylesheet and created a new sheet suffixed with *_SystemSytles.css*. I created a second sheet and suffixed it with *_Custom.css*. Then in the original sheet I placed two imports, first importing the system styles and then the custom styles.
For certain reports we have a custom object that is dropped on that brings in its own styles (and JavaScript). This utilizes a similar technique to the second question.
However, what I had to do for import the JavaScript for general use within the entire Cognos site was difficult.
In the core webcontent folder I created a js folder that contained the jQuery and our custom JavaScript files. Then in a series of JavaScript files I included code similar to the following:
/************************
JQUERY UTIL INCLUDE
************************/
function loadjscssfile(filename, filetype, id) {
if (filetype == "js") { //if filename is a external JavaScript file
var fileref = document.createElement('script')
fileref.setAttribute("type", "text/javascript")
fileref.setAttribute("src", filename)
if (id)
fileref.setAttribute("OurCompanyNameAsAnID", id)
}
else if (filetype == "css") { //if filename is an external CSS file
var fileref = document.createElement("link")
fileref.setAttribute("rel", "stylesheet")
fileref.setAttribute("type", "text/css")
fileref.setAttribute("href", filename)
}
if (typeof fileref != "undefined") {
var headTag = document.head || document.getElementsByTagName('head')[0];
headTag.appendChild(fileref);
}
}
function _PortalLoadJS() {
if (!window._PortalScriptsLoaded) {
var pathParams = [];
var path = location.href;
(function () {
var e,
r = /([^/]+)[/]?/g,
p = path;
while (e = r.exec(p)) {
pathParams.push(e[1]);
}
})();
var baseURL = location.protocol + '//';
for(var i = 1; i < pathParams.length; i++) {
if(pathParams[i] == 'cgi-bin')
break;
baseURL += pathParams[i] + '/';
}
loadjscssfile(baseURL + "js/jquery-1.6.1.min.js", "js");
loadjscssfile(baseURL + "js/Custom.js?pageType=COGNOS_CONNECTION", "js", "SumTotalUtil");
window._PortalScriptsLoaded = true;
}
}
if(!window.$CustomGlobal) {
window.$CustomGlobal= function(func) {
if (!window.$A) {
if (!window.__CustomExecStack) {
window.__CustomExecStack= new Array();
}
window.__CustomExecStack.push(func);
}
else
$A._executeCustomItem(func);
}
}
try {
// Catch cases where $(document).ready() is called after the
// browser event has already occurred.
if (document.readyState === "complete") {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout(_PortalLoadJS, 10);
}
// Mozilla, Opera and webkit nightlies currently support this event
if (document.addEventListener) {
// Use the handy event callback
document.addEventListener("DOMContentLoaded", function() { _PortalLoadJS(); }, false);
// A fallback to window.onload, that will always work
window.addEventListener("load", _PortalLoadJS, false);
// If IE event model is used
} else if (document.attachEvent) {
// ensure firing before onload,
// maybe late but safe also for iframes
document.attachEvent("onreadystatechange", function() { _PortalLoadJS(); });
// A fallback to window.onload, that will always work
window.attachEvent("onload", _PortalLoadJS);
}
}
catch (ex) { }
The $A item is an item that I create when the Custom.js file is loaded.
Here are the list of files that I've included this code (at the vary end of the JavaScript):
webcontent\icd\bux\js\bux\bux.core.js
webcontent\ps\portal\js\cc.js
webcontent\rv\CCognosViewer.js
webcontent\rv\GUtil.js
webcontent\rv\viewer.standalone.core.js
These files should cover the Cognos Connection, Report Viewer, and the Dashboards area. If any more are found please let me know and I can update this list.
When linking to the Custom.js file I put a query string on the external resource that the Custom.js file picks up: pageType=COGNOS_CONNECTION. This allows me to do specific load code for the Cognos Connection, Report Viewer, or the Dashboards.
Here is the code in the Custom.js class that inits the $A object:
function _CustomUtilInit() {
try {
if (!window.$j) {
window.setTimeout(_CustomUtilInit, 1);
return;
}
var jScriptTags = $j('SCRIPT[' + Analytics.SCRIPT_ATTR_NAME + '= ' + Analytics.SCRIPT_ATTR_VALUE + ']');
jScriptTags.each( function(i, scriptElem) {
var tag = $j(scriptElem);
if(tag.attr(Analytics.LOADED_SCRIPT_KEY))
return;
var scriptURL = new URI(tag.attr('src'));
var analyticsPageType = scriptURL.getQueryStringValue(Analytics.PAGE_TYPE_QUERY_KEY, Analytics.PageType.REPORT_VIEWER);
if(!window.$A) {
window.$A = new Analytics();
}
window.$A.init(analyticsPageType);
tag.attr(Analytics.LOADED_SCRIPT_KEY, 'true');
});
} catch (e) {
}
}
_CustomUtilInit();
Of course this expects that the jQuery libraries were included before the Custom.js files in each of the previously mentioned JavaScript files.
The URI class is something that I've found on the internet and tweaked for our use. If you have any questions regarding the custom JavaScript loading please leave a comment and I'll do my best to elaborate some more.

Resources