Escape Html Text in ZF2 - zend-framework2

I have a text like this:
<p><strong>Lorem</strong> ipsur </p>
To see a text without html tags in Zend Framework 2 how can I do?
I tried to put:
<?php echo $this->escapehtml($array['text']); ?>
I read that for security is not good to do:
<?php echo $array['descrizione']; ?>

Im not sure if i understand the question, since i dont know the contents of your arrays.
basicaly if you want to scape the contents of a variable, let's say, $input, you have to call, as you mentioned
$this>escapeHtml($input)
Actually, the PhpRenderer includes a selection of helpers you can use for this purpose: EscapeHtml, EscapeHtmlAttr, EscapeJs, EscapeCss, and EscapeUrl.
You can read about this here
Also, if you want more control, you can use Zend\Escaper, that in 2 lines of code allow you to escape html, like this
$escaper = new Zend\Escaper\Escaper('utf-8');
$output = $escaper->escapeHtml($input);
or escape attributes, like this
$escaper = new Zend\Escaper\Escaper('utf-8');
$output = $escaper->escapeHtmlAttr($input);
I recommend you read the 3 links, they are very short and would give you a better undestanding of what you are doing.

At this moment there is no option in escapeHtml to allow certain tags. What you have to do in these specific cases is to modify the returned value:
<?php
$str = $this->escapehtml($array['text']); ?>
$str = preg_replace(
array('#href="(.*)"#', '#<(/?(?:pre|a|b|br|em|u|ul|li|ol|p|strong)(\shref=".*")?/?)>#' ),
array( 'href="\1"', '<\1>' ),
$str
);
echo $str;
You can add/remove tags from the part pre|a|b|br|em|u|ul|li|ol|p|strong to your needs. Also this code will allow anchor tags with href only.

Related

How to insert '_' as htmlAttributes in razor?

This is probably a simple question, but to which I havent found an answer yet.
How to escape the ' _ ' when creating an HtmlElement in razor?
To render a '-' in the final Html we put an ' _ ', but to render an '_' (underscore), How do we escape it? I tryed '#:', but it didn't work, and didn't find any other options...
Example:
#Html.CheckBox("Access_Groups", false, new
{
#class = "input-control checkbox",
#data_group = "I', looking for data-group",
#Description_pt = "<----- I'm looking for Description_pt"
})
#data_group will render as data-group as expected, but...
#Description_pt will render as Description-pt, and that is not what is expected (don't know how to escape the _ for this)
thank you
If you look at the signature of Html.Checkbox, we can see that it takes an object for the htmlAttributes. Further, looking at the syntax, its actually a key based collection of objects. A Dictionary<string,object> fits that bill and allows you to absolutely specify the name of the html attributes that you want to add (note each key is typed exactly how we want it to display).
#Html.CheckBox("Access_Groups", false, new Dictionary<string,object>
{{"class", "input-control checkbox"},
{"data-group", "I', looking for data-group"},
{"Description_pt", "SomeValue"}})
This renders the following HTML
<input Description_pt="SomeValue" class="input-control checkbox"
data-group="I', looking for data-group" id="Access_Groups"
name="Access_Groups" type="checkbox" value="true" />
Have you tried the HTML character code for underscore, i.e., _?

Spaces being turned into in angular

I'm using ng_repeat to display text from an object. On the rails backend I call strip_tags(text) to remove html. When looking at the output it looks fine. Even when looking at the object in 'view source' it looks fine.
It only looks weird when you look at the text that is actually rendered from the ng_repeat - after a certain point (200 words in the example below) every space is replaced by an
This is causing the text to overflow the div. Any suggestions for dealing with this?
Edit: Some of the code (simplified)
JS:
$scope.init = function(id){
$scope.episodes = gon.episodes
Haml:
.episode-edit{ng_repeat:"episode in episodes"}
%p {{episode.sanitized_summary}}
You should try ng-bind-html. Your snippet would look like
<p ng-bind-html="YourObject"></p>
You can use it in ng-repeat as well.
If you want to secure the data first then include $sce service in your controller. Your snippet would be like
var ExampleCtrl = function($scope, $sce) {
$scope.YourObject = $sce.trustAsHtml($scope.YourObject); // that's it
}
Sorry, turns out it had nothing to do with angular, more to do with Ruby.
Ruby's whitespace regex doesn't capture unicode non-breaking space.
Instead of str.gsub(/\s/m, ' ') you have to use str.gsub(/[[:space:]]/m, ' ')

Call php function in view from mustache and pass a mustache array value into the function call

I would like to pass an array value to a view function so that it can send back some HTML based on that value sent. I want my system to either send back textarea, textbox or radio button.
On my mustache I have {{#get_question}}{{type}}{{/get_question}} where type can have any value from ["input","radio","comment"] The main headache I have is how to call this function and pass the parameter.
I would like to have a php function get_question which extracts the value passed in {{type}}, if type is not text, I would like to pass the value of type to my partial call {{>}} and dynamically load the partial represented by the {{type}}
I got this code sample from Kohana forums:
Hello, {{#caps }}{{ text }}{{/ caps }}!
$m = new Mustache_Engine(array(
'helpers' => array(
'caps' => function() {return function($text, $m) {
return strtoupper($m->render($text));
}}
)
));
I can't seem to get it to work from my view since I have to enclose it in another function(){} block.
How do I go about this?
It's a headache because you're fighting against the fundamentals of Mustache :)
This is a bit backwards from the "Mustache way". Instead of trying to shoehorn in logic via lambdas, you should extract the logic into your view/viewmodel/model, and limit your template to simple sections and string interpolations. Something like this would do the trick:
{{# questions }}
{{# is_input }}{{> input }}{{/ is_input }}
{{# is_radio }}{{> radio }}{{/ is_radio }}
{{# is_comment }}{{> comment }}{{/ is_comment }}
{{/ questions }}
Then each question view/viewmodel/model would answer to is_input(), is_radio() and is_comment().

Right way to attach a jQuery-UI dateselect to a Zend Framework 2 form element?

What would be the right way to attach a jQuery-UI dateselect to a Zend Framework 2 form element?
Would it be adding a appendScript so a javascript selector is added to the end of the layout that selects the class/id?
First of all, i strongly suggest to go with the time and to start using Zend\Form\Element\Date. All browsers who do not support the Date-Input will still render out a Input of type="text", so there is literally no loss in doing so.
The advantage you do get is that most modern browsers are able to render out there default Datepicker. Using the browsers defaults is preferred for users usability and comfort. Even IE10 does do a very good job of supporting the current neat stuff of CSS3 and HTML5. But of course you can't be sure and so you should always include a fallback for older browsers, too. For this, I strongly suggest that you run with Feature-Detection in favor of blindly overwriting the users defaults. The library that does the job the best probably is Modernizr. I will give you the JS for that at the end.
Another thing to note is that this kind of JavaScript belongs at the BOTTOM of your document. For this you have to print this right before closing your </body>-Tag
<?=$this->inlineScript();?>
Now print the script you want inside the right place like this inside your $action.phtml
<?php $this->inlineScript()->captureStart(); ?>
Modernizr.load({
test: Modernizr.inputtypes.date,
nope: [
'http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js',
'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.7/jquery-ui.min.js',
'jquery-ui.css'
],
complete: function () {
$('input[type=date]').datepicker({
dateFormat: 'yy-mm-dd'
});
}
});
<?php $this->inlineScript()->captureEnd(); ?>
What's happeing there is that the Modernizr-library will check for the browser support of the Date-Input of HTML5. If the browser is not able to render out a DateSelect, the appropriate JavaScript-Libraries will be loaded (jQuery, jQueryUI and CSS) and attached to the DOM and the jQueryUI.datepicker() will be called to your input-elements of type date.
In addition, all of this JS-Stuff will be captured and moved to the END of your DOM (where a script element will be added). Doing this you have the advantage that first the full DOM will be rendered and then the JS will be attached. Meaning your Form is usable sooner than in the example provided by Raj.
Based on the 2 answers, I did a bit more research and came up with my own approach...
Here is the top of my layout.phtml
$this->inlineScript()->offsetSetFile(10,$basePath . '/jquery/jquery-1.10.1.min.js');
$this->inlineScript()->offsetSetFile(12,$basePath . '/jquery-ui/ui/jquery-ui.min.js');
I have assigned all my javascripts with an ID so they are all loaded in the right order.
I then use this in my Form... by default it looks like any form element has the ID set to its name, this makes ite easy to style with input#name
$this->add(array(
'name' => 'start',
'type' => 'DateTime',
'options' => array(
'label' => 'Start Date',
'format' => 'Y-m-d H:i P',
),
));
Its then very easy to style with the following, here is my $action.phtml ...
echo $this->form($form);
# Decorations
$this->inlineScript()->offsetSetScript(99,"
$(function() {
$('input#start').datepicker({
dateFormat: 'yy-mm-dd',
showOtherMonths: true,
selectOtherMonths: true,
});
});
");
You can see here I have assigned it offset 99. This is what I use in all my templates.

Wordpress displaying custom post types and their fields

I have set up a Custom Post Type called 'RELEASES' - think music cd release.
This post type has fields named 'release_artist', 'release_title', 'release_date', 'release_artwork' and 'release_tracklisting' for entering all of the relevant music cd information.
I am having real trouble actually displaying this information in my Wordpress template.
I have really only had luck outputting a list of the titles and none of the other data.
Any idea what I put in the LOOP to display all of the information? Preferably each in its own LIST item so I can style each separately?
Any thoughts greatly appreciated.
You can use get_post_meta to pull in your fields as needed. Inside your loop, you can start with the following:
<?php
$release_artist = get_post_meta($post->ID, 'release_artist', true);
$release_title = get_post_meta($post->ID, 'release_title', true);
?>
<ul>
<li class="release_artist">
<?php echo $release_artist; ?>
</li>
<li class="release_title">
<?php echo $release_title; ?>
</li>
</ul>
Are those custom fields? If yes, try what codex.wordpress.org is saying. Better yet, try ACF plugin.
-- edit
If you want to display parts of your pages on other ones (eg. on your home), you need to use query_posts. This is fairly simple function. For your loop, try something like this:
<?php
global $wp_query;
query_posts(array(
'post_type' => 'releases'
));
while(have_posts()) : the_post(); ?>
<?php $key = get_post_meta($post->ID, 'Opis nazwy'); ?>
<li <?php post_class(); ?>><?php if($key) { echo $key[0]; } else { the_title(); }; ?></li>
<?php
endwhile;
wp_reset_query();
?>
$key is a single value, here set to release_artists. It's purely for testing. If it works - feel free to define your own variables.
You should use:
<?php the_field('field_name') ?>
inside your loop. Hope it helps!
From most of the documentation I've seen online, query_posts shouldn't be the go-to function for creating custom queries and loops. The following code snippet might be a good starting point. You should be able to use this inside or outside of the main loop of your themes template files.
$args = array(
'post_type' => 'release', //remember this is-case sensitive
'posts_per_page' => -1,
);
$releaseQuery = new WP_Query( $args );
if ( $releaseQuery->have_posts() ) :
while ( $releaseQuery->have_posts() ) :
$releaseQuery->the_post();
// Fetching the post ID for demonstration and for use later
$c_id = get_the_ID();
// After running the_post(), alot of the Wordpress functions (not all) can now be used without supplying the post ID.
echo get_the_title();
// You could also have used get_the_title($c_id);
// Then:
echo get_post_meta($c_id, 'release_title', true);
echo get_post_meta($c_id, 'release_artist', true);
endwhile;
endif;
// Return to the current page's main query
wp_reset_query();
// This should now display the page's title
the_title();
About your ID's question:
Every item, like posts and pages in WordPress have an "ID", but they are not normally shown in the lists of them. There are a number of plugins that will add an "ID" column in your admin. Search Wordpress.org for "show ids" and pick one you like. Install it. Activate it. You'll see the ids.
https://wordpress.org/plugins/search.php?q=show+id

Resources