Salesforce: utility to escape char from vf page? - salesforce

When passing value from salesforce to javascript I can simple do
var test = '{!myname}';
But how can i escape this so that I can take care of name with symbol like single quote?
I noticed String.escapeSingleQuote exists but can only be used in class not in vfpage

Check the range of "encoding functions" (bottom of the page).
var test = '{!JSENCODE(myname)}';
will be probably best. The help reference of these functions says that they work only in buttons/links but I've used them several times on VF pages. In fact they're recommended way of strengthening your code against XSS etc attacks.
You could also use <apex:outputField> everywhere and fetch the content of fields by id for example. By default most tags that output text data have escape="true" set.

Related

Injecting snippets into a Wagtail StreamField interface

My company is using Wagtail to build robust pages for our website, likely using the StreamField component. We're wondering if Wagtail allows the possibility of us creating reusable parts (perhaps in a snippet), and injecting them into a page.
I'm including a simple diagram of what I'd like to do. Note that while snippets are one possible suggestion, it doesn't need to the specific solution.
The goal of course is to create an element which can be embedded in another page, but can be updated in a single place and cascade everywhere it's used.
Wordpress for example, has a plugin which offers this functionality in short code format:
[embed id=123456]
You can create new block for stream field, let's say MySnippetBlock and then use SnippetChooserBlock to choose the snippet you want.
MySnippetBlock(StructBlock):
title = CharBlock()
snippet = SnippetChooserBlock()
Then in your StreamBlock field you can use above custom block:
MyPage(Page):
stream_field_content = StreamField([('snippet_block', MySnippetBlock())])
...
Or you can use SnippetChooserBlock directly within StreamField if there is no need for additional info attached to it.
stream_field_content = StreamField([('snippet_block', SnippetChooserBlock())])

How to translate role in Drupal?

If I want to translate the role to other language, how do I do it?
I can change that to other language as the default but I would like to use English so I don't have to deal with UTF8 issue in my code with Asian charactors.
if(in_array("administer nodes", $user->roles))
I have tried to find it from translation module but this seems not translatable as other text in Drupal.
So I'm assuming you've already tried using the t() or st() functions?
If that's so, you may need to try a client-side AJAX translation solution. One way you might do this is to create a vocabulary of terms (corresponding to the English role names), and have the Asian character translation as a secondary field. Then use views to create a view of this vocabulary, and create a lightweight module that:
1) loads a Drupal AJAX script on every page (or every page where role names might be utilized)
2) the script looks for a list of specified containers by id that you know will contain role names
3) searches the view you created for the English pattern, and replaces it in the container with any positive matches
Drupal API's example AJAX module
You could then expand the module/AJAX script to solve other similar translate fails on your site.

with HTMLpurifier, how to add a couple attributes to the default whitelist, e.g. 'onclick'

Two questions:
I have been reading docs and SO posts.. and know how to do it the long way (defining each and every element and attribute myself), but all I want to do is add 2 or 3 attributes to the default whitelist.. so that I do not have to constantly find and add more elements/attributes to, e.g., HTML.AllowedElements and/or HTML.AllowedAttributes.
Specifically, now, (for internal trusted users) I need to allow javascript attributes (input from tinymce). Question #1.) Is there a way to just add an attribute (to what HTMLpurifier allows) without causing the whole default sets of allowed elements/attributes to be effectively wiped out (overwritten by ONLY what is explicitly written in HTML.AllowedElements or HTML.AllowedAttributes)?
For what I need right now (the javascript attributes), I got excited when I saw in this thread:
Whitelist Forms in HTML Purifier Configuration
...where Edward Z. Yang says, "... [$config->set('HTML.Trusted', true);] allows JavaScript."
...but even after setting this: $config->set('HTML.Trusted', true);, HTMLpurifier 4.4.0 is still stripping e.g. any input onclick="dostuff();" attribute. Why? Question #2.) Is there a quick way to add just the javascript attributes to the allowed list?
You're losing onclick because HTML Purifier doesn't know about that attribute, and if HTML Purifier passed everything through when you turned on %HTML.Trusted you might as well just not use HTML Purifier at all.
HTML Purifier has attribute collections for just this case; 'Common' is probably the right one to insert them into.
But... why? The real name of %HTML.Trusted really should be %HTML.UnsafeMakeMyApplicationVulnerable
HTMLPurifier does not support onClick and similar java script related attributes to any HTML element as a default behaviour.So if you wish to allow such attribute any way, you may add such attribute to specific element in following way.
$config = HTMLPurifier_Config::createDefault();
$def = $config->maybeGetRawHTMLDefinition()
$def->addAttribute('a', 'onclick', 'Text');
But be careful, this may lead to xss attack as you are allowing any java script code to be there in that attribute.

Drupal: D7 rewriting values returned by views

I have a requirement to perform an indexed search across content which must include a couple of tags in the result. The tags must be a random selection. The platform is Drupal 7.12
I have created a view that manages the results of a SOLR search through the search_api. The view returns the required content and seems to work as intended. I have included a couple of Global: custom text fields as placeholders for the tag entries.
I am now looking for a solution to manage the requirement to randomise the tag values. The randomisation is not the issue, the issue is how to include the random values into the view result.
My current approach is to write a views_pre_render hook to intercept the placeholders which appear as fields ([nothing] and [nothing_1]). The test code looks like the following
function MODULE_views_pre_render( &$view )
{
$view_display = $view->display['default'];
$display_option = $view_display->display_options;
$fields = $display_option['fields'];
foreach( $view->result as $result )
{
$fields['nothing']['alter']['text'] = sprintf("test %d", rand(1,9));
}
}
I am currently not seeing any change in the placeholder when the view is rendered.
Any pointers to approach, alternate solutions etc would be gratefully received as this is consuming a lot of scarce time at the moment. Calling print_r( $view ) from within the hook dumps over 46M into a log file for a result set of 2 items.
There are two possible solutions for your task.
First approach is do everything on the template level. Define a template for the view field you want to randomize. In advanced settings of your display go to Theme: Information. Make sure that the proper theme is selected and find the template suggestions for your field. They are listed starting from most general to the most specific and you can choose whatever suits you better.
I guess the most specific template suggestion for your field would be something like this: views-view-field--[YOR VIEW NAME]--[YOUR DISPLAY NAME]--nothing.tpl.php. Create the file with that name in the theme templates directory and in this template you can render what ever you want.
By default this template has only one line:
print $output;
you can change this to:
print sprintf("test %d", rand(1,9));
or to anything else, whatsoever :)
Second approach is to go with Views PHP module. WIth this module you can add a custom PHP field in which you can do whatever you want. Even though the module hasn't been released it seems to work quite well for the most of the tasks and most certainly for such a simple task as randomizing numbers it will work out for sure.
I stumbled upon this while searching for another issue and thought I would contribute.
Instead of adding another module or modifying a template, just add a views "sort criteria" of "Global: Random".

App Engine - why are there PhoneNumber, Link, Rating etc classes?

I haven't found any reason for the existence of a few of the App Engine classes. There's a PhoneNumber, a Link, a PostalAddress, a GeoPt, a Rating, etc. Why are these given special treatment? They don't seem to have any smarts - e.g. geo searching. I know Link has more space than a String property, but the rest?
See:
http://code.google.com/appengine/docs/java/datastore/dataclasses.html
Those types are 'semantic' types. They're present in the Java API for parity with the Python API. In the Python API, they define special behaviour with regards to the .to_xml() method - for example, a PhoneNumberProperty serializes like this:
<property name="foo" type="gd:phonenumber"><gd:phoneNumber>12345-678</gd:phoneNumber></property>
I think they're mostly just there to cover common cases and save developers time. If a lot of apps use a phone number field, why require each developer to have to write them? A developer can still write their own if they need/want to.
Not sure about java, but in python the following model/code (tested on dev server) will throw BadValueError, with the message "Invalid URL: stackoverflow.com"
class foo(db.model):
link = db.LinkProperty()
bar = foo()
bar.link = 'stackoverflow.com'
While:
bar.link = 'http://stackoverflow.com'
Works fine.
I haven't tested, but the other properties may or may not also do validation.
Basically using this types in your models allows to add indirect meta data to your code. This may be useful if you are working with any kind of universal renderer for your model classes or if you are performing validation of user input on your models.
For example if you are using PhoneNumber type for a field named userNumber you reflection based renderer may understand that it should automatically assign corresponding validator to text field which will represent it.
Regards,
Pavel.

Resources