Dealing with NL2BR from Database to HTML with Javascript - php

I am having difficulty with displaying HTML it seems. haha, let me explain.
I have 1 template file for "comments"... and it tells things where to go and such in the html. When Adding, Updating and Selecting any of the "comments"
IE:
<div class='comment'>
<div>{$name}</div>
<div>{$comment}</div>
</div>
So within my comment I need to pull the COMMENT from the database which includes, \n
So I go like this.
$comment = nl2br($comment);
<div class='comment'>
<div>{$name}</div>
<div>{$comment}</div>
</div>
And this does work... But when I do an UPDATE via jQuery I use,
$("#"+ target +"").replaceWith(responseText);
And the responseText includes all HTML... but some reason, it still is including the \n... and not
I don't know if this is a limitation with Javascript, or rendering issues. Just not sure where else to go here...Any thoughts?

In the php file you are getting the comments with using jQuery try doing the following before echoing the data back
$comment=str_replace('\n\r', '<br />', $comment);
$comment=str_replace('\n', '<br />', $comment);
echo $comment;

Well this was a tad strange, there was some issues that I didn't fully test and sorry for maybe not clarifying. But mysql_real_escape_string() was causing issues with the \n being stored in the database.
There for I am looking at using this function instead. Found on php.net's website
function mysql_escape_mimic($value) {
if(isset($value))
{
if(is_array($value)) {
return array_map(__METHOD__, $value);
}
if(!empty($value) && is_string($value)) {
//return str_replace( array('\\', "\0", "\n", "\r", "'", '"', "\x1a"),
// array('\\\\', '\\0', '\\n', '\\r', "\\'", '\\"', '\\Z'), $value);
return str_replace( array('\\', "\0", "\r", "'", '"', "\x1a"),
array('\\\\', '\\0', '\\r', "\\'", '\\"', '\\Z'), $value);
}
return $value;
}
}

Related

Wordpress filter: `content_save_pre` hook fails to replace content only with `preg_replace` function

I need to replace code block fencing within post_content before save. The post content is written in markdown locally, pushed to github and then Wordpress.
I need the markdown fencing ```js <some code> ``` to be replaced with: [js] <some code> [/js] before saving to Wordpress.
See my working repl: https://repl.it/KDz2/1 My function works perfectly fine outside of Wordpress.
Wordpress is invoking the function, but for some reason the replace is failing. I know this because I can get a simple str_replace to work just fine within Wordpress.
Issue;
preg_replace is failing to return the replaced content within Wordpress filter. No errors thrown. Why is this failing?
For reference, my functions.php file includes:
add_filter( 'content_save_pre', 'markdown_code_highlight_fence');
function markdown_code_highlight_fence( $content ) {
$newContent = preg_replace('/^ *(`{3,}|~{3,}) *(\S+)? *\n([\s\S]+?)\s*\1 *(?:\n+|$)/m', '
[${2}]
$3
[\\\${2}]
', $content);
return $newContent;
}
Also tried this
function markdown_code_highlight_fence( $content ) {
$newContent = preg_replace_callback('/^ *(`{3,}|~{3,}) *(\S+)? *\n([\s\S]+?)\s*\1 *(?:\n+|$)/m', function($match){
$lang = $match[2] == '' ? 'js' : $match[2];
return '
['.$lang.']'
.' '.
$match[3]
.' '.
'[\\'.$lang.']'; }, $content);
return $newContent;
}
Not sure why preg_replace isn't working within Wordpress. If anyone can help shed some light, please do.
In the interim, I have a working solution as follows:
add_filter( 'content_save_pre', 'markdown_code_highlight_fence_replace', 1, 1);
function markdown_code_highlight_fence_replace( $content ) {
preg_match_all('/`{3,}(\S+)?/', $content, $matches);
foreach ($matches[1] as $key=>$match) {
if($match === '') continue;
$content = preg_replace('/`{3,}/', '[/'.$match.']', $content, 2);
$content = str_replace('[/'.$match.']'.$match, '['.$match.']', $content);
}
return $content;
}

Convert \n in a clear space

i have a problem with a function in php i want to convert all the "\n" in a clear space, i've tried with this, but it doesn't work
function clean($text) {
if ($text === null) return null;
if (strstr($text, "\xa7") || strstr($text, "&")) {
$text = preg_replace("/(?i)(\x{00a7}|&)[0-9A-FK-OR]/u", "", $text);
}
$text = htmlspecialchars($text, ENT_QUOTES, "UTF-8");
if (strstr($text, "\n")) {
$text = preg_replace("\n", "", $text);
}
return $text;
}
This is wat i want remove
The site: click here
If you literally have "\n" in your text, which appears to be the case from your screenshots, then do the following:
$text = str_replace("\\n", '', $text);
\n is a special character in PHP that creates new lines, so we need to add the escape character \ in front of it in order to remove text instances of "\n".
preg_replace() seems to work better this way:
$text = preg_replace('/\n/',"",$text);
Single quotes enforce no substitution when sending your pattern to the parser.

do I need to sanitize input displayed to the user?

I'm learning about making my site more secure and am using mysqli's escape function to sanitize input going into SQL queries and am using htmlspecialchars() on input coming from the database (or get/post requests) echoing out onto the page.
But, any text coming from the database to display to the user looks bad because certain characters are escaped with slashes and it shows <br /> or \r\n instead of doing a line break. I can strip the slashes, of course, but shouldn't the mysqli string escape function change the escaped characters back once it is put into the database?
Am I not supposed to use htmlspecialchars to sanitize output being displayed to the user? Or should this not be happening (in which case there must be something weird going on to the data going in)?
I still want line breaks so I'm having to do a string replace. I made the function below as a replacement for just htmlspecialchars(). But I'm not seeing anything about having to do this online anywhere so I'm afraid maybe I'm doing something wrong. :-/
function display($data) {
$new = str_replace('\r\n',"<br />",$data);
$new = str_replace('\n',"<br />",$new);
$new = str_replace('\r',"<br />",$new);
$new = stripslashes($new);
$newer = htmlspecialchars($new);
$search = array('<b>', '</b>', '<i>', '</i>', '<u>', '</u>', '\r\n', '<br />');
$replace = array('<b>', '</b>', '<i>', '</i>', '<u>', '</u>', '<br />', '<br />');
$newest = str_replace($search, $replace, $newer);
return $newest;
}
Here's what I'm using to sanitize the input going into the database:
function escape($data) {
global $conn;
connect();
$data = stripslashes($data);
$data = $conn->real_escape_string($data);
$conn->close();
$data = str_replace(chr(0), '', $data);
return $data;
}
function sanitize($data) {
$data = trim($data);
$data = strip_tags($data);
$data = escape($data);
$data = htmlspecialchars($data);
return $data;
}

str_replace doesn't work with slash

For some reason str_replace() does not work with /. I am creating a function to accept a unique linking style in input and text area forms for a blog CMS that I am making. For instance, [{http://brannondorsey.com}My Website] will be translated to <a href='http://brannondorsey.com'>My Website</a> when passed through make_link($string);. Here is my code:
function make_link($input){
$double = str_replace( '"', '&#34', $input);
$single = str_replace("'", "&#39", $double);
$bracket_erase = str_replace('[', "", $single);
$link_open = str_replace('{', '<a href="', $bracket_erase);
$link_close = str_replace("}", ">", $link_open);
$link_value = str_replace(']', "</a>", $link_close);
echo $link_value;
}
Everything works correctly except for ] is not replaced with </a>. If I remove the slash it will successfully replace ] with <a>, however, as we all know, that does not properly close an anchor tag and therefor makes all html content between the {and the next closing anchor tag in my webpage a link.
You might want to go down the regular expression route for this.
function make_link($link){
return preg_replace('/\[{(.*?)}(.*?)\]/i', '$2', $link);
}
I personally suggest the preg_replace answer of Marcus Recck below rather than mine here.
its there just not seen because the browser wont show html, but you can use the below to see it, and\or use the browsers view source option
$link_close ="]";
$link_value = str_replace(']', "</a>", $link_close);
echo htmlspecialchars($link_value);//= </a>
var_dump ($link_value); //=string(4) "" [invisible due to browser, but the 4 tells you its there]
the finial version of the OP's function:
function make_link($input){
$double = str_replace( '"', '&#34', $input);
$single = str_replace("'", "&#39", $double);
$bracket_erase = str_replace('[', "", $single);
$link_open = str_replace('{', '<a href="', $bracket_erase);
$link_close = str_replace("}", '">', $link_open);
$link_value = str_replace(']', "</a>", $link_close);
return $link_value;
}
echo htmlspecialchars(make_link('[{http://brannondorsey.com}My Website]'));

arguments] Problem Objective-C

I am having trouble with NSProcessInfo's arguments property. I am creating a command line tool that needs to decode base64 code that it has been passed from the internet using a PHP script, along with some other arguments. The data is passed fine, but for some reason. [[NSProcessInfo processInfo] arguments] returns 21 arguments, even though I pass just one base64 string.
Here's the objective-c side of it:
NSArray *arguments = [[NSProcessInfo processInfo] arguments];
if ([[arguments objectAtIndex:1] isEqualToString:#"-s"])
{
if ([arguments objectAtIndex:2] == nil)
{
printf("Error: No data\n");
[pool drain];
return 0;
}
NSString*data = [arguments objectAtIndex:2];
if ([data length] == 0)
{
printf("Error: No data\n");
[pool drain];
return 0;
}
NSString*password = #"";
if ([[arguments objectAtIndex:3] isEqualToString:#"-p"])
{
if ([arguments objectAtIndex:4] == nil)
{
printf("Error: No password\n");
[pool drain];
return 0;
}
else
{
password = [NSString stringWithString:[arguments lastObject]];
}
}
NSLog(#"Args: %i\n\n",[arguments count]); //returns 21? I expect 3.
The base64 code is a bit long, so I've put it here. Does anyone know why this code returns this many arguments? It's supposed to be just one string?
Edit: I am stripping whitespaces in my PHP script. See here:
<?php
$url = $_GET['data'];
$query = "/Library/WebServer/email/emailsender -s";
$password = "-p somePassword";
$commandStr = trim("$query $url $password");
$commandStr = removeNewLines($commandStr);
echo $commandStr;
$output = shell_exec($commandStr);
echo "<pre>Output: $output</pre>";
function removeNewLines($string) {
$string = str_replace( "\t", ' ', $string );
$string = str_replace( "\n", ' ', $string );
$string = str_replace( "\r", ' ', $string );
$string = str_replace( "\0", ' ', $string );
$string = str_replace( "\x0B", ' ', $string );
return $string;
}
?>
When you send arguments to a program through the command-line, each argument is separated by a whitespace character. This means that if you post a string that contains spaces, your program will interpret it as many arguments. To prevent this behavior, you need to quote your strings.
When I display the Base64 string on your pastie page as "raw" I see a lot of spaces in it. So most likely the arguments is correct and your PHP script is calling the Objective-C program the wrong way. An easy fix might be to just strip out any whitespace before passing the string, or properly escape it.

Categories