Smarty Forum Index Smarty
WARNING: All discussion is moving to https://reddit.com/r/smarty, please go there! This forum will be closing soon.

New variable modifier: Rewrite_URL

 
This forum is locked: you cannot post, reply to, or edit topics.   This topic is locked: you cannot edit posts or make replies.    Smarty Forum Index -> Plugins
View previous topic :: View next topic  
Author Message
Itlan
Smarty n00b


Joined: 22 Apr 2010
Posts: 4

PostPosted: Thu Apr 22, 2010 6:20 am    Post subject: New variable modifier: Rewrite_URL Reply with quote

This plugin will modify an url to remove and replace a specific parameter while removing only certain ones and keeping all others.

This plugin is useful if you use a lot of $_GET parameters and need to dynamically change these in your templates. The benefit of using this plugin is that if the parameter already exists it will replace it.

Code:
<?php
/**
 * This plugin will modify an url to remove and replace a specific
 * parameter while removing all others or keeping only certain ones.
 *
 * Note, any parameters not listed in the $remove_params_arr will
 * not be removed (they will be kept). To keep all parameters, pass
 * an empty string "" for the $remove_params_arr.
 *
 * @author  Jim Smith (admin@itlan.kicks-ass.org)
 *
 * @param string $url               The url to change (REQUIRED).
 * @param string $insert_param      The current parameter you wish to
 *                                  change or insert, optionally this
 *                                  could be a query string (REQUIRED).
 * @param string $param_value       The value of the parameter you wish
 *                                  to change or insert (REQUIRED or
 *                                  OPTIONAL if $insert_param is a query
 *                                  string).
 *                                  $insert_param and $param_value can be
 *                                  multiple values by separating each
 *                                  pair by comma. The same number of
 *                                  values should be in each variable.
 * @param string $remove_params_arr A list of parameters (and values)
 *                                  which will be removed (OPTIONAL).
 *
 * @return string The modified url
 * @version 1.86 - Added ISSET to some IF statements
*/

function smarty_modifier_rewrite_url($url,$insert_param,$param_value=NULL,$remove_params_arr="") {
//echo "<br /><br /><br />smarty_modifier_rewrite_url(url=$url,insert_param=$insert_param,param_value=$param_value,remove_params_arr=$remove_params_arr)";

  //parse $insert_param if it is a query string
  if (preg_match("/.+=(\w|%|,|-)*/",$insert_param)) {
    parse_str($insert_param,$insert_arr);
    $insert_param = array_keys($insert_arr);
    $param_value = array_values($insert_arr);
  }

  //split $url and parse into array
  if (preg_match("/\w+\.\w+/",$url)) {
   //assume full url
    $newurl_arr = parse_url($url);
    $newurl = "";
    if (isset($newurl_arr['scheme'])) $newurl = $newurl_arr['scheme']."://";
    if ((isset($newurl_arr['username'])) && (isset($newurl_arr['password']))) $newurl .= $newurl_arr['username'].":".$newurl_arr['password']."@";
    else if (isset($newurl_arr['username'])) $newurl .= $newurl_arr['username']."@";
    if (isset($newurl_arr['host'])) $newurl .= $newurl_arr['host'];
    if (isset($newurl_arr['port'])) $newurl .= ":".$newurl_arr['port'];
    if (isset($newurl_arr['path'])) $newurl .= $newurl_arr['path'];
    $newurl .= "?";
    parse_str($newurl_arr['query'],$url_arr);

  } else {
   //assume just query string
    if (preg_match("/#/",$url)) {
      $temp_arr = explode("#",$url);
      $newurl_arr['fragment'] = $temp_arr[1];
      $url = $temp_arr[0];
    }
    $newurl = "";
    parse_str($url,$url_arr);
  }

  //remove params from array
  if (isset($remove_params_arr) && ($remove_params_arr != "")) {
    !is_array($remove_params_arr) ? $remove_params_arr=preg_split("/,/",$remove_params_arr):"";
    foreach($remove_params_arr as $param) {
      unset($url_arr[$param]);
    }
    unset($param);
  }

  //add current param to array, params separated by semi-colon
  if (isset($insert_param) && ($insert_param != "")) {
    !is_array($insert_param) ? $insert_param=preg_split("/,/",$insert_param):"";
    !is_array($param_value) ? $param_value=preg_split("/,/",$param_value):"";
    for ($i = 0, $size = count($param_value); $i < $size; $i++) {
      if (trim($param_value[$i]) != "") $url_arr[trim($insert_param[$i])] = trim($param_value[$i]);
    }
  }

  //assemble the url string from the array
  $newurl .= implode_query("=","&",$url_arr);

  //clean up '?&' which should just be '?'
  $newurl = preg_replace("/\?(&amp;|&)/","?",$newurl);

  //clean up trailing '?' or '&' at end of url
  $newurl = preg_replace("/(\?|(&amp;|&))$/","",$newurl);

  //clean up leading '&'
  $newurl = preg_replace("/^(\(&amp;|&)/","",$newurl);

  //attach anchor fragment to end of url
  if (isset($newurl_arr['fragment'])) $newurl .= "#".$newurl_arr['fragment'];

  return $newurl;
}

/**
 * Implode Array with Keys (useful for assembling query strings from arrays)
 * http://us.php.net/manual/en/function.implode.php#44836
 * @param $inner_glue Inserted between the [key] and [value] (i.e. key=value)
 * @param $outer_glue Inserted between each [key\value] pair (i.e. key=value&key=value)
 * @param $pieces The array to parse
 * @return string
 */
function implode_query($inner_glue,$outer_glue,$pieces) {
  $result = array();
  foreach($pieces as $key => $item) {
    $result[] = $key . $inner_glue . $item;
  }
  unset($key,$item);
  return implode($outer_glue,$result);
}
?>


Examples
You can use it to replace or add a single parameter (adds 'client_city'):
Code:
{$cur_page|cat:"?$query"|rewrite_url:"client_city":"Chicago":""}


You can use it to remove parameters (removes 'client_city'):
Code:
{$cur_page|cat:"?$query"|rewrite_url:"":"":"client_city"}


You can do both in the same operation (adds 'client_city', removes 'next'):
Code:
{$cur_page|cat:"?$query"|rewrite_url:"client_city":"Chicago":"next"}


You can, of course, use $smarty variables (inserts the 'client_city' with value stored in $client.city):
Code:
{$cur_page|cat:"?$query"|rewrite_url:"client_city":$client.city:""}


You can specify a list of parameters to add and to remove (this eliminates the need to make separate calls to rewrite_url if you want to add more than one parameter).
Inserts 'client_city', removes both 'next' and 'client_state':
Code:
{$cur_page|cat:"?$query"|rewrite_url:"client_city":"Chicago":"next,client_state"}

Inserts both 'client_city=Chicago' and 'client_state=Illinois', removes 'next':
Code:
{$cur_page|cat:"?$query"|rewrite_url:"client_city,client_state":"Chicago,Illinois":"next"}


Sometimes you need to call it twice. For instance if a variable contains the parameters you want to replace ($special_query). In this case you have to apply rewrite_url twice because the parameters do not exist in the URL until you apply the first rewrite_url. Then your second rewrite_url can modify your new URL:
Code:
{$cur_page|cat:"?$query"|rewrite_url:$special_query:"":""|rewrite_url:"":"":"next"}


If you already have the insert parameter as a parameter=value pair (inserts the pair 'client_city=Chicago'):
Code:
{$cur_page|cat:"?$query"|rewrite_url:"client_city=Chicago":"":""}


You can also use this inside PHP files by using the alternative syntax (removes 'next'):
Code:
$url = smarty_modifier_rewrite_url("$cur_page?$query","","","next");


I wrote this a while back and use it a lot in my templates. Much easier than trying to get all my URLs ready inside my PHP files. I can do it all dynamically in my templates!

Comments and questions are appreciated. Comments asking why this plugin is needed should be prefaced with an actual trial of the plugin first.


Last edited by Itlan on Sun May 25, 2014 4:03 pm; edited 3 times in total
Back to top
View user's profile Send private message Visit poster's website
chukdocs
Smarty Rookie


Joined: 20 Sep 2007
Posts: 9

PostPosted: Sat May 24, 2014 11:32 am    Post subject: Useful plugin Reply with quote

Hi Itlan

Thanks for making this useful plugin. I have been using it, and have a couple of problems with.

1. Have you updated the modifier since version 1.7?
2. The current file is always returned as filename_php, instead of filename.php

Regards

Ian
Back to top
View user's profile Send private message
douglassdavis
Smarty Junkie


Joined: 21 Jan 2008
Posts: 541

PostPosted: Sat May 24, 2014 3:55 pm    Post subject: Re: Useful plugin Reply with quote

See also comment at bottom here:

http://www.smarty.net/forums/viewtopic.php?t=4356
Back to top
View user's profile Send private message
Itlan
Smarty n00b


Joined: 22 Apr 2010
Posts: 4

PostPosted: Sun May 25, 2014 3:51 am    Post subject: Reply with quote

I've updated the code above with the latest which is 1.85. It's been at least 2 years since I've looked at the code, so I don't remember specifically what's been changed other than I changed the way the parameters are parsed. I found a bug when I copied the code to a new server.

HTH,
Itlan
Back to top
View user's profile Send private message Visit poster's website
Itlan
Smarty n00b


Joined: 22 Apr 2010
Posts: 4

PostPosted: Sun May 25, 2014 4:06 pm    Post subject: Reply with quote

Updated code (v1.86) with slight improvement to the IF statements. I added ISSET instead of relying on the implied form.

This should remove any error notices about undefined indexes.

- Itlan
Back to top
View user's profile Send private message Visit poster's website
chukdocs
Smarty Rookie


Joined: 20 Sep 2007
Posts: 9

PostPosted: Sun Apr 05, 2015 4:10 am    Post subject: Reply with quote

Code:

<?php
/**
 * This plugin will modify an url to remove and replace a specific
 * parameter while removing all others or keeping only certain ones.
 *
 * Note, any parameters not listed in the $remove_params_arr will
 * not be removed (they will be kept). To keep all parameters, pass
 * an empty string "" for the $remove_params_arr.
 *
 * @author  Jim Smith (admin@itlan.kicks-ass.org principal author)
 * @author  Ian Short (ian.short@live.co.uk - Made modifications to V1.86)
 *
 * @param string $url               The url to change (REQUIRED).
 * @param string $insert_param      The current parameter you wish to
 *                                  change or insert, optionally this
 *                                  could be a query string (REQUIRED).
 * @param string $param_value       The value of the parameter you wish
 *                                  to change or insert (REQUIRED or
 *                                  OPTIONAL if $insert_param is a query
 *                                  string).
 *                                  $insert_param and $param_value can be
 *                                  multiple values by separating each
 *                                  pair by comma. The same number of
 *                                  values should be in each variable.
 * @param string $remove_params_arr A list of parameters (and values)
 *                                  which will be removed (OPTIONAL).
 *
 * @return string The modified url
 * @version 1.9 - Added remove duplicates from $url_arr. Replaced function implode_query with http_build_query. Removed code error checks, now handled by http_build_query.
*/

function smarty_modifier_rewrite_url($url,$insert_param,$param_value=NULL,$remove_params_arr="") {

  //parse $insert_param if it is a query string
  if (preg_match("/.+=(\w|%|,|-)*/",$insert_param)) {
    parse_str($insert_param,$insert_arr);
    $insert_param = array_keys($insert_arr);
    $param_value = array_values($insert_arr);
  }

  //split $url and parse into array
  if (preg_match("/\w+\.\w+/",$url)) {
   //assume full url
    $newurl_arr = parse_url($url);
    $newurl = "";
    if (isset($newurl_arr['scheme'])) $newurl = $newurl_arr['scheme']."://";
    if ((isset($newurl_arr['username'])) && (isset($newurl_arr['password']))) $newurl .= $newurl_arr['username'].":".$newurl_arr['password']."@";
    else if (isset($newurl_arr['username'])) $newurl .= $newurl_arr['username']."@";
    if (isset($newurl_arr['host'])) $newurl .= $newurl_arr['host'];
    if (isset($newurl_arr['port'])) $newurl .= ":".$newurl_arr['port'];
    if (isset($newurl_arr['path'])) $newurl .= $newurl_arr['path'];
    $newurl .= "?";
    if (isset($newurl_arr['query'])) parse_str($newurl_arr['query'],$url_arr);

  } else {
   //assume just query string
    if (preg_match("/#/",$url)) {
      $temp_arr = explode("#",$url);
      $newurl_arr['fragment'] = $temp_arr[1];
      $url = $temp_arr[0];
    }
    $newurl = "";
    parse_str($url,$url_arr);
  }

  //remove params from array
  if (isset($remove_params_arr) && ($remove_params_arr != "")) {
    !is_array($remove_params_arr) ? $remove_params_arr=preg_split("/,/",$remove_params_arr):"";
    foreach($remove_params_arr as $param) {
      unset($url_arr[$param]);
    }
    unset($param);
  }

  //add current param to array, params separated by semi-colon
  if (isset($insert_param) && ($insert_param != "")) {
    !is_array($insert_param) ? $insert_param=preg_split("/,/",$insert_param):"";
    !is_array($param_value) ? $param_value=preg_split("/,/",$param_value):"";
    for ($i = 0, $size = count($param_value); $i < $size; $i++) {
      if (trim($param_value[$i]) != "") $url_arr[trim($insert_param[$i])] = trim($param_value[$i]);
    }
  }

  // Remove any duplicate array elements
  $url_arr = array_unique($url_arr);
   
  //assemble the url string from the array
  $newurl .= http_build_query($url_arr);
 
  //attach anchor fragment to end of url
  if (isset($newurl_arr['fragment'])) $newurl .= "#".$newurl_arr['fragment'];

  return $newurl;
}
?>
Back to top
View user's profile Send private message
robbo2000
Smarty Rookie


Joined: 02 Nov 2016
Posts: 14

PostPosted: Fri Dec 02, 2016 9:30 am    Post subject: Reply with quote

Hello,
unfortunatelly i don't get it to work. Is it correct to call the function within the template-file? While doing so, i get a modified url as text output in the template, but no effects to the URL.
What further steps are necessary to change the real URL?
Back to top
View user's profile Send private message
AnrDaemon
Administrator


Joined: 03 Dec 2012
Posts: 1785

PostPosted: Fri Dec 02, 2016 3:28 pm    Post subject: Reply with quote

robbo2000 wrote:
Hello,
unfortunatelly i don't get it to work.
An example of your code demonstrating the issue would tell more than a lengthy description.
Back to top
View user's profile Send private message
robbo2000
Smarty Rookie


Joined: 02 Nov 2016
Posts: 14

PostPosted: Tue Dec 06, 2016 10:19 pm    Post subject: Reply with quote

Good Evening,

for my first test i used the code from above without any modifications. My Point is: can i modify the url with this code or do i need a htaccess-file with additional rewrite rules?
Back to top
View user's profile Send private message
AnrDaemon
Administrator


Joined: 03 Dec 2012
Posts: 1785

PostPosted: Wed Dec 07, 2016 1:12 am    Post subject: Reply with quote

An example of your code… and a short summary of your desired effect. Not a lengthy description.
Back to top
View user's profile Send private message
robbo2000
Smarty Rookie


Joined: 02 Nov 2016
Posts: 14

PostPosted: Tue Dec 13, 2016 1:11 pm    Post subject: Reply with quote

Hello,
I have learned in the meantime that I have to deal again with the topic in more depth and that I have overseen a few aspects like e.g. Routing
Thanks for the answers and nice holidays, when it is so far.
Back to top
View user's profile Send private message
Display posts from previous:   
This forum is locked: you cannot post, reply to, or edit topics.   This topic is locked: you cannot edit posts or make replies.    Smarty Forum Index -> Plugins All times are GMT
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2005 phpBB Group
Protected by Anti-Spam ACP