String containing {{calendar}} but need it to call calendar.php - php

I'm storing HTML content in a MySQL field with a text data type, and I'm using ckeditor as a WYSIWYG editor to create the HTML that is being stored in MySQL. I'm looking for a way for a user to put some kind of string that I could look for and replace with calling an include file. For example:
// This string contains the text pulled from mysql
$pageContent = "<p>This page contains a calendar of events</p> {{calendar}} <p>Choose a date or scroll through days to view events.</p>";
// Function needed that changes {{calendar}} to bring in my script calendar.php like include('calendar.php');
// Note that in this example I want to call my script that does the calendar stuff, but maybe I have a script to do a photo gallery which could be {{photogallery}}, or news {{news}}, or whatever...
// Print the $pageContent including the calendar.php contents here
print $pageContent;

Here's a little something that will take your text (in this case, $pageContent) and an array of parameters (ie array('calendar' => 'calendar.php')) and include the necessary file. It is currently untested, but should get you in the right direction.
function parseTemplate($templateText, $params)
{
foreach ($params as $key => $value)
{
ob_start();
include($value);
$includeContents = ob_get_contents();
ob_end_clean();
$templateText = str_replace('{{'.$key.'}}', $includeContents, $templateText);
}
return $templateText;
}
Usage in your case would be the following:
// This string contains the text pulled from mysql
$pageContent = "<p>This page contains a calendar of events</p> {{calendar}} <p>Choose a date or scroll through days to view events.</p>";
$params = array('calendar' => 'calendar.php');
$pageContent = parseTemplate($pageContent, $params);
// print the $pageContent including the calendar.php contents here
print $pageContent;
You could also use the same idea for simply replacing text instead of including files:
function parseTemplateText($templateText, $params)
{
foreach ($params as $key => $value)
{
$templateText = str_replace('{{'.$key.'}}', $value, $templateText);
}
return $templateText;
}

Related

Emoji name "family_mothers_one_boy" or "woman-woman-boy"?

I have a reference emojis file used by my php code. Inside there is for example "woman-woman-boy", but the browser (chrome) replaces this name by "family_mothers_one_boy"...
Why are there two versions of emojis' names?
Is there en (some) error(s) in my file, or should I have to do something in my code to avoid the conversion?
NOTE:
The code related to this emoji is:
1F469;‍👩‍&#x1F466
Here are the two functions I'm using to manage the emojis:
1. When I display the emoji, I replace the tage :name: by the HTML rendering (using unicode)
function replaceEmojiNameByUnicode($inputText){
$emoji_unicode = getTabEmojiUnicode();
preg_match_all("/:([a-zA-Z0-9'_+-]+):/", $inputText, $emojis);
foreach ($emojis[1] as $emojiname) {
if (isset($emoji_unicode[$emojiname])) {
$inputText = str_replace(":".$emojiname.":", "&#x".$emoji_unicode[$emojiname].";", $inputText);
}
else {
$inputText = str_replace(":".$emojiname.":", "(:".$emojiname.":)", $inputText);
}
}
return $inputText;
}
2. When I want to propose the list of emoji I display an HTML SELECT in the page. Teh following function return the list of option to add inside:
/* Display the options in the HTML select */
function displayEmojisOptions(){
$emoji_unicode = getTabEmojiUnicode();
foreach ($emoji_unicode as $name => $unicode) {
echo '<option value="&#x'.$unicode.';">'.$name.' => &#x'.$unicode.';</option>';
}
}
In the array $emoji_unicode there is one entry (with 3 semi-column removed to not display emoji here):
'family_one_girl' => '1F468;&#x200D&#x1F469&#x200D&#x1F467',
For example: In order to make it works, I have to replace the line 'thinking_face' => '1F914', by 'thinking' => '1F914',
My question is: why ??
Thank you
Nop, the emoji text was changed by no code... I guess it was due to a wrong emoji file I used... I correct all the emoji manually and now I did not see the mismatch anymore...
If someone need the corrected file, I can provide it.

get all categories listing from database

Main purpose is to get all categories listing from database by passing variables to url and show it to the main page.here i have omitted some code bt i tried to clarify.
1.can I exclude encodeHtml() method, too difficult for me to understand
2.i am not getting specially this part of code and having my head for 4 days
foreach($cats as $cat) {
echo "<li><a href=\"/?page=catalogue&category=".$cat['id']."\"";//here id is 'category id' from database. this full line will echo what?
echo Helper::getActive(array('category' => $cat['id']));//it will output what ?
echo ">";
echo Helper::encodeHtml($cat['name']);//as from ur answer can we omit encodeHTML() method and use htmlspecialchars($cat['name']); instead ?
echo "</a>
3.any easier solution will be more appreciated
in our database we have 'id' and 'name' of catagory listing
please check below for reference
/*below is the code in header section of template */
<?php
$objCatalogue = new Catalogue();// creating object of Catalogue class
$cats = $objCatalogue->getCategories(); // this gets all categories from database
<h2>Categories</h2>
<?php
foreach($cats as $cat) {
echo "<li><a href=\"/?page=catalogue&category=".$cat['id']."\"";
echo Helper::getActive(array('category' => $cat['id']));
echo ">";
echo Helper::encodeHtml($cat['name']);
echo "</a></li>";
}
?>
/*below is the helper class which is Helper.php */
public static function getActive($page = null) {
if(!empty($page)) {
if(is_array($page)) {
$error = array();
foreach($page as $key => $value) {
if(Url::getParam($key) != $value) //getParam takes name of the parameter and returns us the value by $_GET
{
array_push($error, $key);
}
}
return empty($error) ? " class=\"act\"" : null;
}
}
//CHECK THIS LINE BROTHER
return $page == Url::currentPage() ? " class=\"act\"" : null;// url::currentPage returns the current page but what is 'class =act ' :(
}
public static function encodeHTML($string, $case = 2) {
switch($case) {
case 1:
return htmlentities($string, ENT_NOQUOTES, 'UTF-8', false);
break;
case 2:
$pattern = '<([a-zA-Z0-9\.\, "\'_\/\-\+~=;:\(\)?&#%![\]#]+)>';
// put text only, devided with html tags into array
$textMatches = preg_split('/' . $pattern . '/', $string);
// array for sanitised output
$textSanitised = array();
foreach($textMatches as $key => $value) {
$textSanitised[$key] = htmlentities(html_entity_decode($value, ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8');
}
foreach($textMatches as $key => $value) {
$string = str_replace($value, $textSanitised[$key], $string);
}
return $string;
break;
}
}
Firstly, in your URL (/?page=catalogue&category=) you don't need to put &, as this is an HTML entity for actually displaying an ampersand in a web page. Just use /?page=catalogue&category=.
Secondly, you can use urlencode() to prepare strings for sending in the URL, and urldecode() on the other end.
In answer to your first point you just need to make sure that ANYTHING from the user (whether via $_POST or $_GET) is sanitized, prior to being used in code, output to a web page, or used in database queries. Use htmlspecialchars() for cleaning before outputting to a web page, and prepared statements prior to entering user input into a query.
In answer to your second point please read the documentation in the links I have provided above. Just reading the documentation on htmlspecialchars() will help you a lot.
Hope this helps.
Alright then.
<?php
foreach($cats as $cat) {
echo "<li><a href=\"/?page=catalogue&category=".$cat['id']."\"";
echo Helper::getActive(array('category' => $cat['id']));
echo ">";
echo Helper::encodeHtml($cat['name']);
echo "</a></li>";
}
?>
Im just going to kindof skim through it, because honestly if you really want to learn all this you should probably google the shit out of every piece of code you don't understand, it's the way we all learn things.
< ?php announces some php script to follow. And as you can see, there does follow some php code after.
foreach is a way of getting each element from an array or list and doing something to that element.
echo sends whatever string comes after it to the page, or whatever is listening to its output. In this case, it looks like the echo's are printing some <li> list item with an <a> anchor in it.
Helper::getActive(): Helper is some class that is defined somewhere, :: is syntax for calling a static function that belongs to the class (Helper in this case). getActive is the function name.
array('category' => $cat['id'] is a piece of code that creates an array with 1 element in it, being one with key 'category' and a value of whatever is in $cat['id'].
By looking at getActive: it looks like it's a function that checks the url for some value so it can determine which page to display. It also checks if the url contains errors.
By lookingat encodeHtml(): it looks like it's a function that makes sure that whatever text you're trying to put on the screen, isn't something that could cause harm. In some situations, people will try to make your server print javascript that could harm the user (by sending personal data to somewhere). The encodeHtml() will ensure that no such thing can be done by stripping certain characters from the text you're about to send to the page.
USE GOOGLE.

Alternatives to eval() - Shortcodes in text input

in a CMS I want the user to be able to include blocks of php code like a contact form, a search form.
Something like
<? include 'contact.inc.php' ?>
Now, Wordpress does this by using Shortcodes, ie
[contact-form] [search form]
How can I do this easily?
I have a limited number of includes
I could use
eval('?> ' . $database_query . ' <?php ');
and put
<? include('contact.inc.php') ; ?>
in the contents of $database_query
but eval() in this situation is dangerous
so how can I make a simple shortcode system ?
I would avoid eval all together if you can. The issue with eval, particularly with form inputs is that if exploited, you are giving an attacker access to your entire web server. I would suggest using some server-side script that is looking for explicit shortcodes. You can even use the Wordpress function that they use as a starting point. You can also use a preg_match to search for your shortcodes in the text and parse them that way. Either option would be better than eval()
Assuming you've loaded some HTML with your shortcodes from somewhere (database for example) and you want to echo it's contents with your forms inside, I would do the following:
// Define known shortcodes
$shortcodes = array(
"[contact-form]" => "contact.inc.php",
"[search-form]" => "search.inc.php"
);
// Load HTML with shortcodes from wherever you want
$source = load_template_from_somewhere();
// Now let's find the shortcodes in your source
$replace_points = array();
foreach($shortcodes as $code => $include_me){
$offset = 0;
while(TRUE){
$index = strpos($source, $code, $offset);
if($index === FALSE){
// No more shortcodes of this type found
break;
};
// Save the position and name of shortcode
$replace_points[$index] = $code;
// Update offset to scan the source search the remaining part of the string
$offset = $index + strlen($code);
};
};
// Sort the array because we've been searching by shortcode names
// And now we need to include forms in the correct order
ksort($replace_points);
$offset = 0;
foreach($replace_points as $index => $code){
// Echo raw HTML part of the string
echo substr($source, $offset, $index);
// Then include the form
include($shortcodes[$code]);
// Update the offset to move towards the end of the string
$offset = $index + strlen($code);
};
// Echo the remaining part of raw HTML string
echo substr($source, $offset);

Executing a PHP page after search + replacing keywords for language translation in the HTML

I am translating my website into different languages and I have over 130 pages so i want to pass my .php files through a function that will replace keywords
IE: Accessories = อุปกรณ์
Which is English to Thai.
I can get it to work using my method however... I have php (obviously) in these pages, and the output only displays the html and not executing the php
Is there a header method or something I have to pass at the start of my php pages..
here is the function I'm using to find text results and then replace them from my php files..
<?php
// lang.php
function get_lang($file)
{
// Include a language file
include 'lang_thai.php';
// Get the data from the HTML
$html = file_get_contents($file);
// Create an empty array for the language variables
$vars = array();
// Scroll through each variable
foreach($lang as $key => $value)
{
// Finds the array results in my lang_thai.php file (listed below)
$vars[$key] = $value;
}
// Finally convert the strings
$html = strtr($html, $vars);
// Return the data
echo $html;
}
?>
//This is the lang_thai.php file
<?php
$lang = array(
'Hot Items' => 'รายการสินค้า',
'Accessories' => 'อุปกรณ์'
);
?>
A lot of frameworks use a function to translate as it goes instead of replacing after the fact using .pot files. The function would look like this:
<h1><?php echo _('Hello, World') ?>!</h1>
So if it was English and not translated that function would just return the string untranslated. If it was to be translated then it would return the translated string.
If you want to continue with your route which is definitely faster to implement try this:
<?php
function translate($buffer) {
$translation = include ('lang_tai.php');
$keys = array_keys($translation);
$vals = array_values($translation);
return str_replace($keys, $vals, $buffer);
}
ob_start('translate');
// ... all of your html stuff
Your language file is:
<?php
return array(
'Hot Items' => 'รายการสินค้า',
'Accessories' => 'อุปกรณ์'
);
One cool thing is include can return values! So this is a good way to pass values from a file. Also the ob_start is an output buffer with a callback. So what happens is after you echo all of your html to the screen, right before it actually displays to the screen it passes all of that data to the translate function and we then translate all of the data!

PHP Tag system without database (plain text files)

I want to implement a tag system on my website. The website is made in PHP, but uses NO database (sql) system. It reads the files from plain text files and includes them.
The pages are in a file, if a page is requested that file is read, and if the page is in there the site returns it. If the page is not in there it gives an error (so no path traversal issues, I can let page "blablabla" go to "other-page.inc.php").
The page list is a big case statement, like this:
case "faq":
$s_inc_page= $s_contentdir . "static/faq.php";
$s_pagetitle="FAQ";
$s_pagetype="none";
break;
($s_pageype is for the css theme).
What I want is something like this:
case "article-about-cars":
$s_inc_page= $s_contentdir . "article/vehicles/about-cars.php";
$s_pagetitle="Article about Cars";
$s_pagetype="article";
$s_tags=array("car","mercedes","volvo","gmc");
break;
And a tag page which takes a tag as get variable, checks which cases have that tag in the $s_tag array and then returns those cases.
Is this possible, or am I thinking in the wrong direction?
I would do this by keeping your page details in an array such as:
$pages['faq']['s_inc_page'] = $s_contentdir . "static/faq.php";
$pages['faq']['s_pagetitle'] = "FAQ";
$pages['faq']['s_pagetype'] = "none";
$pages['faq']['s_tags'] = array("car","mercedes","volvo","gmc");
You could then use a foreach loop to go through this array and pull out the items with matching tags:
$tag = "car";
foreach($pages as $page) {
if (in_array($tag, $page['s_tags'])) {
//do whatever you want to do with the matches
echo $page['s_pagetitle'];
}
}
It's possible, but you may need to think outside your current structure.
Something like this will work:
$pages = array(
"article-about-cars" => array ("car", "mercedes", "volvo"),
"article-about-planes" => array ("757", "747", "737")
); //an array containing page names and tags
foreach ($pages as $key => $value) {
if (in_array($_GET['tag'], $value)) {
$found_pages[] = $key;
}
}
return $found_pages; //returns an array of pages that include the tag

Categories