Drupal - Add a class to an existing button based on URL - php

I have a Book Now button on each page of my website. I would like to know which button is selected and don't really want to add 25+ blocks to the site to add the class manually. I can use Google Analytics if I can make the button unique (add an additional class based on the page URL). But I'm not a coder although I'm familiar with both PHP and jQuery.

Hye Michael, after reading your question i have tested your scenario on my local test drupal site. And it's really easy to achieve it. Here is a piece of PHP code you need to put into your block you created.
<?php
$url = current_path();
$class_from_url = explode("/", $url);
echo "<a href=[link_to_whatever] class='". $class_from_url[0] ."'>[Link Title]</a>";
?>
Make sure your "PHP filter" module is enabled which will allow you to select PHP code from "Text formats" under the block body.

For Drupal 7, the best way to accomplish your goal would be to copy the theme_button() function to your theme's template.php file and add some custom code to check the URL and add the class.
YOURTHEME_button($vars) {
$element = $variables ['element'];
$element ['#attributes']['type'] = 'submit';
element_set_attributes($element, array('id', 'name', 'value'));
$element ['#attributes']['class'][] = 'form-' . $element ['#button_type'];
if (!empty($element ['#attributes']['disabled'])) {
$element ['#attributes']['class'][] = 'form-button-disabled';
}
// Check URL to determine what button class to add
$button_class = null;
$current_path = base_path() . request_path();
switch ($current_path) {
'/form1':
$button_class = 'button-for-form1';
break;
'/form2':
$button_class = 'button-for-form2';
break;
}
if ($button_class !== null) {
$element ['#attributes']['class'][] = $button_class;
}
return '<input' . drupal_attributes($element ['#attributes']) . ' />';
}
Note that this method will add the class only for URLs that you explicitly specify, and it ignores any user-supplied parameters that might be included as part of the URL.

Related

Is it possible to print html from an external page by replacing strings?

I was wandering if it were possible to store a html schema page with special strings to replace with variable and how to do it.
In an external file, I would like to put the html structure of a product, let's call it schema.php:
<span id="{% id %}">{%= name %}</span>
<span>{%= imageURL() %}</span>
The example above is just a simpler example. In the external file, the html would be more complex. I know that if there were just few lines I could just echo them with a simple function but this is not the case.
In another file I have a class that handle products, let's call it class.php:
class Product {
//logic that is useless to post here.
public function imageURL() {
return "/some/url".$this->id."jpg";
}
}
In this class I would like to add a function that take the content from schema.php and then echo it in the public file for users.
I tried with file_get_contents() and file_put_contents() but it just doesn't work:
$path_to_file = 'data/prodotti/scheda.inc';
$file_contents = file_get_contents($path_to_file);
$file_contents = str_replace(
"{%= ",
"<?php echo $this->",
$file_contents
);
$file_contents = str_replace(
" }",
"; ?>",
$file_contents
);
file_put_contents($path_to_file, $file_contents);
is it possible to call schema.php page and print it with custom variables?
By "schema page" I think you mean "template" and yes, but the best way to do it is to use an existing templating engine such as Smarty or a Mustache implementation like https://github.com/bobthecow/mustache.php instead of implementing it yourself because of the risks of XSS, HTML-injection, and how you'll eventually want features like looping and conditionals.
you can do it normaly with php require func. without any strings to replace, if you just want to use that file as "template" then:
in schema.php:
<?php
echo'<span id="'.$id.'">'.$name.'</span>
<span>'.$imageURL.'</span>';
?>
in class.php:
<?php
class Product {
//logic that is useless to post here.
public function imageURL() {
return "/some/url".$this->id."jpg";
}
}
$imageURL = imageURL(); ?>
Index.php or whatever the main page that handles class.php and temp.php(schema)
<?php
//avoid undefined variables on errors
//in case that you don't check for values submitted
$id = 0;
$name = 0;
$imageURL = '';
//set vars values
$id = /*something*/;
$name = /*something 2*/;
$imageURL = /*something3*/;
//all date will be replaced is ready, oky nothing to wait for
require('path/to/schema.php');
Note: If you gets these data from user, then you should validate with if(isset()).
hope that helps,

Laravel 5 Include blade templates dynamically (replace div)

I have a CMS where users can create and edit their own content in their websites. I also provide the possibility to include forms and galleries by simply replacing specific Div's in their content.
In the past I simply exploded the content on these Div's to an array, replaced the whole Div's with the needed html code (by using PHP's include) to show the form or gallery at that exact position, imploded the whole array to a string again (html) and used in the website.
Now I am trying to achieve the same in Laravel 5:
// example plugins div in HTML
// ******************************
<div class="plugin form"></div>
// PageController.php
// ******************************
$page = Page::where(('url', '=', "home")->first();
$page->text = Helpers::getPlugins($page->text);
// Helpers.php (a non default custom class with functions)
// ******************************
public static function getPlugins($page)
{
$dom = new DOMDocument();
$dom->loadHTML($page, LIBXML_HTML_NOIMPLIED);
$x = $dom->getElementsByTagName("div");
foreach ($x as $node)
{
if (strstr($node->getAttribute('class'), "plugin"))
{
$plugin = explode(" ",$node->getAttribute('class'));
$filename = base_path() . "/resources/views/plugins/" . trim($plugin[1]) . ".blade.php";
if (is_file($filename))
{
ob_start();
include($filename);
ob_get_contents();
$node->nodeValue = ob_get_clean();
}
else
{
$node->nodeValue = "Plugin <strong>".$node->getAttribute('class')."</strong> Not found</div>";
}
}
}
return $dom->saveHTML();
}
Sofar so good, the content is returned but what I get is all the pure text blade markup instead of the Laravel generated html which I want to use.
I think there is a way this could work but I cannot come to think of it.
Try manually building the template by using the method BladeCompiler->compile(), read more here
Edit: I think the facade Blade::compile() will give you access to this function too, just add use Blade at the top of the file.

URL Cloaking in WordPress Plugin

I'm planning to obscure link urls with the following way. It stores urls in an array and then if it detects the parameter in the $_GET array, it redirects to the saved url.
<?
/* Plugin Name: Sample Link Cloak */
add_action('admin_menu', 'sample_link_cloak');
function sample_link_cloak() {
add_options_page(
'Sample Link Cloak',
'Sample Link Cloak',
'manage_options',
'sample_link_cloak',
'sample_link_cloak_admin');
}
function sample_link_cloak_admin() {
?>
<div class="wrap">
<?php
$links = '<p>google.com</p>' . PHP_EOL
. '<p>wordpress.org</p>' . PHP_EOL
. '<p>stackoverflow.com</p>' . PHP_EOL;
$doc = new DOMDocument();
#$doc->loadHTML($links);
$array_urls = array();
foreach ($doc->getElementsByTagName('a') as $node) {
$url = $node->getAttribute('href');
$hash = md5($url);
$array_urls[$hash] = $url;
$url = site_url('?urlcloak=' . $hash);
$node->setAttribute('href', $url);
}
echo $doc->saveXML();
update_option('sample_urlcloak', $array_urls);
?>
</div>
<?php
}
add_action('init', 'cloakurls');
function cloakurls() {
if (isset($_GET['urlcloak'])) {
$array_urls = get_option('sample_urlcloak');
wp_redirect($array_urls[$_GET['urlcloak']]);
exit;
}
}
There is a problem I can predict with this method. The number of links increases day by day so the stored data have to be deleted when they reach to some extent. But if the visitor saves the web page on the local drive and read the contents later on and click the link, at this point if the server does not store the url, it won't redirect.
I think it is pretty much the same issue described here. Looking for more efficient way to serve numerous link redirects? but for a distributed plugin, is it realistic/practical to edit the .htaccess file? I guess not all users have the right access to modify .htaccess. I'm not sure.
I'm wondering if somebody can direct me to the right direction.
It depends on your application. Usually you can do what the other SO post describes, but if it really is random; or you don't have control over the redirected site - use a database. It's function is to quickly find what you are looking for on a hard drive.
Now to wonder a bit further than your current approach - what about two-way obfuscation? If it's just obfuscation (not security) use such an algorithm that you could both encrypt and decrypt the url. That way you wouldn't need to store any data.

codeigniter url suffix .html + hashtag

I want to build an url with hashtag on codeigniter. Example:
"http://www.example.com/blog/post/title.html#comments"
The url_config in my config.php is this:
$config['url_suffix'] = ".html";
And I used the following code to build the anchor:
anchor('blog/post/'.url_title($post->title, 'dash', TRUE).'#comments', 'comments', 'title="'.$post->title.'"');
If you know any solution please let me know it. Thanks
How about this?
anchor(site_url('blog/post/'.$post->title)."#comments");
It returns an url like this: http://example.org/blog/post/stackoverflowRocks.html#comments
If you want to use hash tags without having to pass 'site_url()' to the anchor method you can extend the CodeIgniter Config library class fairly easily.
The CodeIgniter Config library class has a method called site_url that runs when you use the anchor method. site_url, by default, adds the url_suffix after any uri you pass to it without any care or knowledge of hash tags. Fortunately, you can simply extend the Config library class to modify site_url to check for hash tags and add them to the end of the URI after the url_suffix is added.
If you feel so compelled, copy the code below and save it under '/system/application/libraries/MY_Config.php'. You may have to open up '/system/application/config/autoload.php' and add 'My_Config.php' to the autoload library array.
<?php
class MY_Config extends CI_Config {
function site_url($uri = '')
{
if (is_array($uri))
{
$uri = implode('/', $uri);
}
if ($uri == '')
{
return $this->slash_item('base_url').$this->item('index_page');
}
else
{
$suffix = ($this->item('url_suffix') == FALSE) ? '' : $this->item('url_suffix');
$hash = '';
if(substr_count($uri,'#') == 1)
{
list($uri,$hash) = explode('#',$uri);
$hash = '#'.$hash;
}
return $this->slash_item('base_url').$this->slash_item('index_page').trim($uri, '/').$suffix.$hash;
}
}
}
?>
The new site_url method sets $hash to an empty string. If a hash tag is found in the link you pass in, the link is split into an array and passed into variables. site_url will now return the link with the hash tag appended at the end (if hash code is present) after the url_suffix.

Is there a Symfony helper for getting the current action URL and changing one or more of the query parameters?

What I'd like to do is take the route for the current action along with any and all of the route and query string parameters, and change a single query string parameter to something else. If the parameter is set in the current request, I'd like it replaced. If not, I'd like it added. Is there a helper for something like this, or do I need to write my own?
Thanks!
[edit:] Man, I was unclear on what I actually want to do. I want to generate the URL for "this page", but change one of the variables. Imagine the page I'm on is a search results page that says "no results, but try one of these", followed by a bunch of links. The links would contain all the search parameters, except the one I would change per-link.
Edit:
Ok I got a better idea now what you want. I don't know whether it is the best way but you could try this (in the view):
url_for('foo',
array_merge($sf_request->getParameterHolder()->getAll(),
array('bar' => 'barz'))
)
If you use this very often I suggest to create your own helper that works like a wrapper for url_for.
Or if you only want a subset of the request parameters, do this:
url_for('foo',
array_merge($sf_request->extractParameters(array('parameter1', 'parameter3')),
array('bar' => 'barz'))
)
(I formated the code this way for better readability)
Original Answer:
I don't know where you want to change a parameter (in the controller?), but if you have access to the current sfRequest object, this should do it:
$request->setParameter('key', 'value')
You can obtain the request object by either defining your action this way:
public function executeIndex($request) {
// ...
}
or this
public function executeIndex() {
$request = $this->getRequest();
}
For symfony 1.4 I used:
$current_uri = sfContext::getInstance()->getRouting()->getCurrentInternalUri();
$uri_params = $sf_request->getParameterHolder()->getAll();
$url = url_for($current_uri.'?'.http_build_query(array_merge($uri_params, array('page' => $page))));
echo link_to($page, $url);
Felix's suggestion is good, however, it'd require you to hard core the "current route"..
You can get the name of the current route by using:
sfRouting::getInstance()->getCurrentRouteName()
and you can plug that directly in url_for, like so:
url_for(sfRouting::getInstance()->getCurrentRouteName(),
array_merge($sf_request->extractParameters(array('parameter1', 'parameter3')),
array('bar' => 'barz'))
)
Hope that helps.
With the same concept than Erq, and thanks to his code, I have made the same with some small changes, since my URL needs to convert some characters. Its generic though and should work with most forms, in order to save the parameters the user has chosen to search for.
public function executeSaveFormQuery(sfWebRequest $request)
{
$sURLServer = "http://";
$sURLInternalUri = "";
$page = "";
$sURLInternalUri = sfContext::getInstance()->getRouting()->getCurrentInternalUri();
$suri_params = $request->getParameterHolder()->getAll();
$sParams = http_build_query(array_merge($suri_params));
$dpos = strpos($sURLInternalUri, "?");
$sURLConsulta[$dpos] = '/';
$sURL = substr($sURLInternalUri, $dpos);
$dpos = strpos($sURL, "=");
$sURL[$dpos] = '/';
$sURLFinal = $sURLServer . $sURL . '?' . $sParams;
//$this->redirect($this->module_name . '/new');
self::executeNew($request, $sURLFinal);
//echo "var_dump(sURLFinal): ";
//var_dump($sURLFinal);
//echo "<br></br>";
//return sfView::NONE;
}
In executeNew, as easy as:
public function executeNew(sfWebRequest $request, $sURLQuery)
{
//$sURLQuery= "http://";
if ($sURLQuery!= "")
{
$this->form = new sfGuardQueryForm();
//echo "var_dump(sURLQuery)";
//var_dump($sURLQuery);
//echo "<br></br>";
$this->form->setDefault('surl', $sURLQuery);
}
else
{
$this->form = new sfGuardQueryForm();
}
}
echo $sf_context->getRequest()->getUri();

Categories