• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2877
  • Last Modified:

mod rewrite - htaccess - strip characters (i.e. "?") from URL

Hello,

Is it possible to strip characters in my htaccess file  for mod rewrite purposes?

here's a line from htacesss:

RewriteRule ^(.+)/(.+)\.html$ index.php?page=$1&subpage=$2 [NC,L,QSA]

Specifically - I've got dynamic link text:

Offset of Future Claims: Wave of the Future?

this is what the resulting URL looks like:
http://mysite.com/resources/articles/offset-of-future-claims%3A-wave-of-the-future%3F.html
<a href="<? echo menus::checksef($url); ?>" tabindex="<? echo $ak->tabindex($key); ?>"><? echo $news_array[$j]['title']; ?></a>

Open in new window

0
phillystyle123
Asked:
phillystyle123
  • 9
  • 2
  • 2
1 Solution
 
caterham_wwwCommented:
Strip them in your function/class checksef since your rewrite rule is only involved, when s/o requested such a URL, i.e. it's too late.

You could replace everything e.g. via [1].

But you'd have to change the function which compares an incoming request and evaluates the variable $_GET['subpage'] as well.
[1]
 
$string = preg_replace('%[^a-zA-Z0-9_/-]%', '', $string);

Open in new window

0
 
phillystyle123Author Commented:
ahh - so this:

function stripcharacters( str ) {
$string = preg_replace('%[^a-zA-Z0-9_/-]%', '', $string);
}

and then how do i call it here? :

<a href="<? echo menus::checksef($url); ?>" tabindex="<? echo $ak->tabindex($key); ?>"><? echo $news_array[$j]['title']; ?></a>
0
 
caterham_wwwCommented:
I thought about placing it in the class/function menus::checksef but calling your function should work this way, too:

<? echo stripcharacters(menus::checksef($url)); ?>

Anyway, since those characters are striped now your function which re-translates a request for, e.g., /resources/articles/offset-of-future-claims%3A-wave-of-the-future%3F.html into some id may expect the special characters to fetch the correct subpage from a database. If the characters are missing, that might fail.
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
phillystyle123Author Commented:
hmm - i've got this in functions.js:

function stripcharacters( str ) {
$string = preg_replace('%[^a-zA-Z0-9_/-]%', '', $string);
}

and this in my page code:

<? echo menus::checksef (stripcharacters($url)); ?>

there's no error - but the list of articles don't load - no error in the source code either - any suggestions?
0
 
phillystyle123Author Commented:
I tried this as well:

//Only execute if sef is enabled for the site.
            if (ENABLE_SEF):
                  //Take the querystring passed in and create SEF-equivalent url for it
                  //First, make sure XHTML compliant ampersands are in effect
                  $url = str_replace('&amp;', '&', $url); //Remove any xhtml versions first
                  $url_trim = str_replace('index.php?', '', $url); //Strip out static portion of url
                  $url_parts = explode('&', $url_trim); //Break apart url string based on ampersands
                  $url = preg_replace('%[^a-zA-Z0-9_/-]%', '', $url);
I'm not getting any changes in the URL
0
 
phillystyle123Author Commented:
any ideas as to why this isn't working???

here's the code (how would i build this into the code)??

 $url = preg_replace('%[^a-zA-Z0-9_/-]%', '', $url);
<?
//Manage tab index values
class ak {
	var $keyValue = 0;
	function tabindex($key) {
		return $this->keyValue += 1;
	}
}
$ak = new ak;
$key = $ak->keyValue;
 
//Manage all validation, some PHP errors (static class)
class err {
	function dbError($msg, $error = "") {
		print "<p>$msg: <strong>$error</strong></p>\n";
		exit;
	}
	
	function validationError( $errors ) {
		if (count($errors)) {
			html::openList('errors');
			foreach ($errors as $e) {
				echo "\n\t<li>" . stripslashes($e) . "</li>";
			}
			html::closeList();
		}
	}
	
	function dbWriteError() {
		$e_list = (isset($_GET['errors'])) ? urldecode($_GET['errors']) : '';
		if (strlen($e_list)) {
			html::openList('errors');
			echo "\n<li>" . stripslashes($e_list) . "</li>";
			html::closeList();
		}
	}
}
 
//Escape text, but check if magic quotes is enabled first
function escape( $text ) {
	return (get_magic_quotes_gpc()) ? $text : addslashes($text);
}
 
// Format date by passing in output style
function dateFormat($format, $date) {
	return strftime($format, strtotime($date));
}
 
// Clean up string for passing into url
function scrubURL( $text, $dir = 'encode' ) {
 
	//Ignore if numeric in nature
	if (is_numeric($text))
		return $text;
 
	if ($dir == 'encode'):
		$text = str_replace(' ', '-', $text);
		return urlencode(strtolower($text));
	else:
		$text = str_replace('-', ' ', $text);
		return urldecode($text);
	endif;
}
 
//Define constants for certain configuration files and viewable options
function getConfig() {
	global $d;
	
	$result = $d->dbQuery("SELECT * FROM _config LIMIT 1");
	$rec = $d->dbFetchObject($result);
 
	define('CONTACT_EMAIL', $rec->contact_email);
	define('RECORDS_PER_PAGE', $rec->records_per_page);
	define('CLIENT', $rec->client_name);
	define('SITE_NAME_SIMPLE', $rec->site_header);
	define('GMAP_KEY', $rec->google_map_key);
	define('ALLOW_FONT_CHANGE', $rec->allow_font_change);
	define('HOMEPAGE_LEFT', stripslashes($rec->boilerplate_homepage));
	define('ENABLE_SEF', $rec->enable_sef);
	define('DEBUG', $rec->debug_frontend);
 
	//Establish user session
	if (!count($_SESSION['clientuser'])):	
		//Default value for user session
		$_SESSION['clientuser'] = array();
		userLogin();
	endif;
}
 
//Redirect to a selected page
function redirect($action) {
	echo "<script>window.location.href='$action';</script>";
	exit;
}
 
//If user attempted to log in, validate account
function userLogin() {
	global $d;
 
	if (isset($_POST['username'])):
		$username = escape($_POST['username']);
		$password = escape($_POST['password']);
		$sql = sprintf("SELECT username, password FROM customer_accounts WHERE username = '%s' AND password = '%s' AND is_active = 1 LIMIT 1", $username, md5($password));
		$result = $d->dbQuery($sql);
 
		if ($d->dbNumRows($result)):
			$sql = sprintf("UPDATE customer_accounts SET last_login = '%s' WHERE username = '%s'", date("Y-m-d"), $username);
			$d->dbQuery($sql);
 
			$_SESSION['clientuser'][] = array('username' => $username, 'isloggedin' => 1, 'tstamp' => time());
			return true;
		else:
			echo "<script>alert('Your account was not found.');</script>";
			$_SESSION['clientuser'] = array();
		endif;
	else:
		return false;
	endif;
}
 
//Check if menu being called as any elements.  If not, then remove
function hasItems( $menuname, $toplevel = 0 ) {
	global $d, $page, $page_id;
	if ($toplevel):
		$sql = sprintf("SELECT m.id FROM menu_items m
			\n INNER JOIN menu_position mp ON m.menu_position_id = mp.id AND m.is_active = 1
			\n AND LCASE(mp.menu_title) = '%s' AND m.page_parent_id = 0 ORDER BY m.oindex", $menuname);
	else:
		$sql = sprintf("SELECT m.id FROM menu_items m
			\n INNER JOIN menu_position mp ON m.menu_position_id = mp.id AND m.is_active = 1
			\n AND LCASE(mp.menu_title) = '%s' AND m.page_parent_id = (SELECT id FROM menu_items WHERE menu_item_link = '%s') ORDER BY m.oindex", $menuname, $page);
	endif;
	$result = $d->dbQuery($sql);
	return ($d->dbNumRows($result)) ? 1 : 0;
}
 
//Call the selected menu
function loadMenu( $menuname, $toplevel = 0 ) {
	global $page;
 
	return menus::getMenu(strtolower($menuname), $toplevel);
}
 
//Static class for all menu functions
class menus {
 
	//Get menu elements
	function getMenu( $menulocation, $toplevel=0 ) {
		global $d, $page, $parent_id, $subpage;
 
		//Determine type of menu to call
		$menu_array = array();
		if ($toplevel):
			$filter = sprintf("AND LCASE(mp.menu_title) = '%s' AND m.page_parent_id = 0", $menulocation);
		else:
			$filter = sprintf("AND LCASE(mp.menu_title) = '%s' AND m.page_parent_id = (SELECT id FROM menu_items WHERE menu_item_link = '%s')", $menulocation, $page);
		endif;
		$sql = "SELECT m.id, m.menu_item_title, m.menu_item_link, m.browser_target,
				p.module_id FROM menu_items m
				INNER JOIN menu_position mp ON m.menu_position_id = mp.id AND m.is_active = 1
				INNER JOIN pages p ON p.id = m.page_id $filter ORDER BY m.oindex";
		$result = $d->dbQuery($sql);
		if ($d->dbNumRows($result)):
			while($r = $d->dbFetchObject($result)):
				$menu_array[] = array(
						'id' => $r->id,
						'title' => $r->menu_item_title,
						'link' => $r->menu_item_link,
						'target' => $r->browser_target,
						'module_id' => $r->module_id
					);
			endwhile;
		endif;
		
		html::showMenu($menu_array, $toplevel, $page, $subpage);
	}
 
	/*  Check if the current url has an sef alternate, and if so, use that instead of the default querystring style */
	function checksef( $url ) {
		global $d;
 
		//Only execute if sef is enabled for the site.
		if (ENABLE_SEF):
			//Take the querystring passed in and create SEF-equivalent url for it
			//First, make sure XHTML compliant ampersands are in effect
			 $url = str_replace('&amp;', '&', $url); //Remove any xhtml versions first
		
			$url_trim = str_replace('index.php?', '', $url); //Strip out static portion of url
			$url_parts = explode('&', $url_trim); //Break apart url string based on ampersands
		
			//Loop through each possible section, assessing the querystring variable and applying necessary SEF translation
			switch (count($url_parts)):
				case 1: //page=$val
					$tmp1 = explode('=', $url_parts[0]);
					$url = $tmp1[1] . '.html';
					break;
				case 2: //page=$val, (category|subpage)=$val
					$tmp1 = explode('=', $url_parts[0]);
					$tmp2 = explode('=', $url_parts[1]);
 
					$url = $tmp1[1] . '/' . $tmp2[1] . '.html';
					break;
				case 3: //page=$val, subpage=$val, id=$val
					$tmp1 = explode('=', $url_parts[0]);
					$tmp2 = explode('=', $url_parts[1]);
					$tmp3 = explode('=', $url_parts[2]);
 
					//If blog or news article link, generate unique url format
					if (strstr($url, 'news')):
						$url = 'news/' . $tmp3[1] . '.html';
					elseif (strstr($url, 'blog')):
						if (strstr($url, 'keyword')):
							$url = 'blog/keywords/' . $tmp3[1];
						elseif (strstr($url, 'archive')):
							$url = 'blog/archive/' . $tmp3[1];
						else:
							$url = 'blog/' . $tmp3[1] . '.html';
						endif;
					else:
						$url = $tmp1[1] . '/' . $tmp2[1] . '/' . $tmp3[1] . '.html';
					endif;
					break;
				default:
					break;
			endswitch;
		endif;
 
		return SITE_NAME_FULL . "/$url";
	}
	
	/*Creates heirarchy trail of links so user visually knows where they are located in site
	* $pagetext (array) - All content from selected page
	* $page (string) - Current parent page called
	* $subpage (string) - Current child page called (optional)
	*/
	function breadcrumbs( $pagetext, $page, $subpage ) {
		global $d;
 
		$sql = sprintf("SELECT page_parent_id FROM menu_items WHERE menu_item_link = '%s'", (strlen($subpage) ? $subpage : $page));
		$result = $d->dbQuery($sql);
		$item = $d->dbFetchObject($result);
 
		$url = (strlen($subpage)) ? "index.php?page=$page&amp;subpage=$subpage" : "index.php?page=$page";
		//Append to array
		$list .= "breadcrumbs.push('" . menus::checksef($url) . "::" . $pagetext['title'] .  "');\n";
 
		//If current page is child record, call to its parent
		if ($item->page_parent_id):
			$list .= menus::getBreadcrumbParent($item->page_parent_id);
		endif;
		return $list;
	}
 
	/*Gets the parent item of current page (and recursively checks until there are no more)
	* $page_id (int) - Current ID of page called
	*/
	function getBreadcrumbParent( $page_id ) {
		global $d;
 
		$sql = sprintf("SELECT id AS page, menu_item_title, menu_item_link, page_parent_id FROM menu_items WHERE id = %u", $page_id);
		$result = $d->dbQuery($sql);
		$subitem = $d->dbFetchObject($result);
		$url = "index.php?page=" . $subitem->menu_item_link;
		//Append to array
		$sublist = "breadcrumbs.push('" . menus::checksef($url) . "::" . $subitem->menu_item_title .  "');\n";
		if ($subitem->page_parent_id):
			$sublist .= menus::getBreadcrumbParent($subitem->page_parent_id);
		endif;
		
		return $sublist;
	}
 
	/*Load all top-level portfolio categories
	* $page (string) - Current page called (in this case, Portfolio)
	*/
	function loadCategories($page, $category) {
		global $d, $ak;
 
		$cat_array = array();
		$result = $d->dbQuery("SELECT id, category FROM portfolio_categories WHERE is_active = 1 ORDER BY oindex");
		if ($d->dbNumRows($result)):
			while($r = $d->dbFetchObject($result)):
				$cat_array[] = array(
						'id' => $r->id,
						'title' => $r->category,
						'link' => strtolower($r->category)
					);
			endwhile;
		endif;
		
		echo "<ul>\n";
		$count = 0;
		foreach($cat_array as $key => $value):
			$url = ($toplevel) ? "index.php?page=" . urlencode($value['link']) : "index.php?page=$page&amp;category=" . urlencode($value['link']);
			$active = ($category == $value['link']) ? "class=\"active\"" : "";
			echo "\t<li><a href=\"" . menus::checksef($url) . "\" $active tabindex=\"" . $ak->tabindex($key) . "\">" . $value['title'] . "</a></li>\n";
			$count++;
		endforeach;
		echo "</ul>\n";
	}
 
	/*Create the necessary HTML to create a different browser target if necessary
	$target (string) - The type of target required
	$url (string) - Destination of the link
	*/
	function getTarget( $target, $url ) {
		switch ($target) {
			case 'pa':
				return '';
				break;
			case 'nn':
				return 'target="_blank"';
				break;
			case 'ny':
				return 'onClick="window.open(\'' . $url . '\', \'_new\',\'toobar=0,location=0,directory=0\');"';
				break;
			default:
				return '';
				break;
		}
	}
}
 
//A static class to output all the content on the page.
class html {
	/**
	 * Returns the open list tag
	 * @param[$class] string - Name of CSS class to pass in (optional)
	 */
	function openList( $class = '' ) {
		echo "\n<ul class=\"$class\">";
	}
	
	/**
	 * Returns the close list tag for error display
	 */
	function closeList() {
		echo "\n</ul>";
	}
	
	/**
	 * Make ampersand XHTML valid
	 */
	function fixAmpersand( $text ) {
		return str_replace('&', '&amp;', $text);
	}
	
	/**
	 * Remove full ASCII amersand syntax, leaving only the character
	 */
	function truncateAmpersand( $text ) {
		return str_replace('&amp;', '&', $text);
	}
 
	/*Output the menu to browser
	$menu_array (array) - The menu data itself
	$toplevel (bool) - Whether or not menu items are a top level (parent) element
	$page ($string) - The currently selected page
	$subpage ($string) - The currently selected subpage (based on $page value, optional)
	*/
	function showMenu ( $menu_array, $toplevel, $page, $subpage ) {
                global $d, $ak;
                
                //Display the top level elements.
                echo "<ul>\n";
                foreach($menu_array as $key => $value):
                        if ($toplevel):
                                $url = "index.php?page=" . $value['link'];
                                $active = ($page == $value['link']) ? "class=\"active\"" : "";
                        else:
                                $url = "index.php?page=$page&amp;subpage=" . $value['link'];
                                $active = ($subpage == $value['link']) ? "class=\"active\"" : "";
                        endif;
                        $target = menus::getTarget($value['target'], $url);
 
                        //If user is logged in, change login page link to read logout
                        if (count($_SESSION['clientuser']) && strcmp(strtolower($value['link']), 'sign_in') == 0)
                                $value['title'] = 'Logout';
 
                        //Do not show item if it is restricted in access and user is not logged in.
                        if ($value['restricted'] && !count($_SESSION['clientuser'])):
                        else:
                                echo "\t<li  $target $active class=\"transOFF\"  onmouseover=\"this.className='transON'\"  onmouseout=\"this.className='$active transOFF'\" " . ($value['link']=="blog" ? "style=\"padding:0 2px 0 2px;\"": "")."><a href=\"" . menus::checksef($url) . "\" $target $active tabindex=\"" . $ak->tabindex($key) . "\">". $value['title'] ."</a></li>\n";
                        endif;
                endforeach;
                echo "</ul>\n";
				
				
        }
 
	/*Get content from database
	$pagetext (array) - All content from selected page
	*/
	function showDbContentMain( $pagetext ) {
		global $d, $page;
 
		include('includes/dbcontent.html.php');
	}
 
	/*Get content from selected module
	$pagetext (array) - All content from selected page
	$module_id (int) - Unique ID of the module being called
	*/
	function showModuleContentMain( $pagetext, $module_id ) {
		global $d, $item_id, $category, $ak, $page, $subpage;
		//Retrieve the module's information, and include the appropriate file
		echo "<h2>" . $pagetext['title'] . "</h2>\n";//UNCOMMENTED to display title BEFORE intro
		if ($_POST['firstname']=="") {echo "<div class=\"intro\">" . stripslashes($pagetext['intro']) . "</div>\n\n";}
		else 
		echo "";
		$sql = sprintf("SELECT module_name FROM module_list WHERE id = %s", $module_id);
		$result = $d->dbQuery($sql);
		if ($d->dbNumRows($result)) {
			$f = $d->dbFetchObject($result);
			//Use for include path shortcut for modules
			define('MPATH', 'modules/' . strtolower($f->module_name) . '/');
			if (file_exists(MPATH . 'index.php')) {
				include(MPATH . 'index.php');
			} else
				echo '<p>Module for ' . $f->module_name . ' not found.</p>';
		}
	}
 
	/*Get content from selected module
	$pagetext (array) - All content from selected page
	$module_id (int) - Unique ID of the module being called
	*/
	function showModuleContentSide( $pagetext, $module_id ) {
		global $d, $item_id, $ak, $page, $subpage;
		//Retrieve the module's information, and include the appropriate file
		$sql = sprintf("SELECT module_name FROM module_list WHERE id = %s", $module_id);
		$result = $d->dbQuery($sql);
		if ($d->dbNumRows($result)) {
			$f = $d->dbFetchObject($result);
			//Use for include path shortcut for modules
			define('MPATH', 'modules/' . strtolower($f->module_name) . '/');
			if (file_exists(MPATH . 'rightcontent.php')):
				include(MPATH . 'rightcontent.php');
			endif;
		}
	}
 
	/*Checks if current browser is IE, and which version.  Returns the version of IE being used, otherwise is 0 */
	function ieCheck() {
		$browser = $_SERVER['HTTP_USER_AGENT'];
		$ver = 0;
		if (strstr($browser, "MSIE 6")) $ver = 6;
		if (strstr($browser, "MSIE 7")) $ver = 7;
 
		return $ver;
	}
	
	/*Allow user to change font size of content area */
	function fontSizeChange( $pagetext ) {
		global $ak;
 
		if (ALLOW_FONT_CHANGE && $pagetext['allow_fontchange']):
			include('fontSizes.html.php');
		endif;
	}
	
	/*Allow user to either print current page, or view text-only version */
	function printTextIcons() {
		global $ak;
 
		if (ALLOW_FONT_CHANGE):
			include('altIcons.html.php');
		endif;
	}
	
	/*Generates homepage image. */
	function showHomepageSlideshow() {
		global $d;
		
		$result = $d->dbQuery("SELECT image, caption, portfolio_url FROM frontpage_images ORDER BY oindex LIMIT 1");
		if ($d->dbNumRows($result)):
			$rec = $d->dbFetchObject($result);
			$url = menus::checksef($rec->portfolio_url);
			echo "<div id=\"homepage\" style=\"background:url(uploads/frontpage images/" . $rec->image . ") no-repeat top left;\">\n";
			echo "\t<div id=\"homepage_caption\"><a href=\"$url\">&gt; " . $rec->caption . "</a></div>\n";
			echo "</div>\n";
        endif;
	}
 
}
 
//Static class for specific database calls
class db {
 
	/*Get the parent and child id for the called module dropdown
	$module (string) - Name of the module
	*/
	function getHrefStruct( $module ) {
		global $d;
		
		$item_link_href = '';
		$parent_link_href = '';
 
		//Get item's link value
		$sql = sprintf("SELECT m.menu_item_link, m.page_parent_id FROM menu_items m
			\n INNER JOIN pages p ON p.id = m.page_id
			\n INNER JOIN module_list ml ON ml.id = p.module_id
			\n AND ml.module_name = '%s'", $module);
		$s_result = $d->dbQuery($sql);
		if ($d->dbNumRows($s_result)) {
			$item_link = $d->dbFetchObject($s_result);
 
			$item_link_href = $item_link->menu_item_link;
		}
			
		if ($d->dbNumRows($s_result) && ($item_link->page_parent_id > 0)) {
			//Get item's parent link value (if it exists)
			$sql = sprintf("SELECT menu_item_link FROM menu_items WHERE id = %u", $item_link->page_parent_id);
			$p_result = $d->dbQuery($sql);
			if ($d->dbNumRows($p_result)) {
				$parent_link = $d->dbFetchObject($p_result);
			
				$parent_link_href = $parent_link->menu_item_link;
			}
		}
		
		$url = "index.php?page=$item_link_href";
		
		return $url;
	}
 
	/* Get selected page content.  If top level page, get first child
	$page_id (int) - ID of the page being called
	$parent_id (int) - Whether current record is a parent record or not
	$pagetext (array) - Pre-defined assoc. array of output for page
	*/
	function getContent( $page_id, $parent_id, $pagetext ) {
		global $d, $page;
 
		//If top level page (except for root home), show first child by default
		$sql = sprintf("SELECT p.id, p.page_name, p.has_quote, p.has_blogs, p.allow_fontchange, c.css_internal, c.js_internal,
				\n c.intro_text, c.body_text, c.imagefile1, c.imagealt1, c.imagefile2, c.imagealt2 FROM pages p 
				\n INNER JOIN page_content c ON c.page_id = p.id AND p.id = %u AND p.is_active = 1 LIMIT 1", $page_id);
		$result = $d->dbQuery($sql);
		if ($d->dbNumRows($result)) {
			$rec = $d->dbFetchObject($result);
			$pagetext['id'] 			= $rec->id;
			$pagetext['title'] 			= $rec->page_name;
			$pagetext['intro'] 			= stripslashes($rec->intro_text);
			$pagetext['body'] 			= emailformat::scrambleEmail(stripslashes($rec->body_text));
			$pagetext['css_scripts']	= $rec->css_internal;
			$pagetext['js_scripts']		= $rec->js_internal;
			$pagetext['pageimage_1'] 	= $rec->imagefile1;
			$pagetext['pageimagealt_1'] = $rec->imagealt1;
			$pagetext['pageimage_2'] 	= $rec->imagefile2;
			$pagetext['pageimagealt_2'] = $rec->imagealt2;
			$pagetext['has_blogs']		= $rec->has_blogs;
			$pagetext['has_quote'] 		= $rec->has_quote;
			$pagetext['allow_fontchange']= $rec->allow_fontchange;
		} else {
			//If page not found, redirect to 404 page
			$result = $d->dbQuery("SELECT p.id, p.page_name, c.intro_text, c.body_text, c.imagefile1 FROM pages p INNER JOIN page_content c ON c.page_id = p.id AND p.page_name LIKE '404%' AND p.is_active = 1 LIMIT 1");
			$rec = $d->dbFetchObject($result);
			$pagetext['id'] 		= $rec->id;
			$pagetext['title'] 		= $rec->page_name;
			$pagetext['intro'] 		= stripslashes($rec->intro_text);
			$pagetext['pageimage_1']= $rec->imagefile1;
		}
 
		return $pagetext;
	}
 
 
	/* Get the parent item of selected record (used mostly for generating URLs)
	$parent_menu_id (int) - Menu ID of the parent page being called
	*/
	function getParentMenu( $parent_menu_id ) {
		global $d;
 
		$sql = sprintf("SELECT menu_item_link FROM menu_items WHERE id = %u", $parent_menu_id);
		$result = $d->dbQuery($sql);
		$menu = $d->dbFetchObject($result);
		return $menu->menu_item_link;
	}
	
	/* Retrieve content for related item list based on page
	$page_id (int) - ID of the selected page
	$has_related_items (bool) - Whether or not to show this sidebar of content
	*/
	function getRelatedItems( $page_id, $has_related_items ) {
		global $d;
 
		//Leave function if no related items for current page.
		if (!$has_related_items)
			return false;
 
		//Get the portfolio category selected and the sorting method
		$sql = sprintf("SELECT LCASE(c.category) AS category, r.category_id, r.sortby FROM related_items r INNER JOIN portfolio_categories c ON c.id = r.category_id AND r.page_id = %u", $page_id);
		$result = $d->dbQuery($sql);
		
		if ($d->dbNumRows($result)):
			$tmp = $d->dbFetchHash($result);
			extract($tmp);
 
			$sql = sprintf("SELECT id, name FROM portfolio WHERE category_id = %u AND is_active = 1 ", $category_id);
			switch($sortby):
				case 'alpha':
					$sql .= sprintf("ORDER BY name LIMIT %u", RELATED_ITEMS_COUNT);
					break;
				case 'random':
					$sql .= sprintf("ORDER BY RAND() LIMIT %u", RELATED_ITEMS_COUNT);
					break;
				case 'entrydate':
					$sql .= sprintf("ORDER BY id DESC LIMIT %u", RELATED_ITEMS_COUNT);
					break;
				case 'usersort':
					$sql .= sprintf("ORDER BY oindex LIMIT %u", RELATED_ITEMS_COUNT);
					break;
				default:
					$sql .= sprintf("ORDER BY oindex LIMIT %u", RELATED_ITEMS_COUNT);
					break;
			endswitch;
			$result = $d->dbQuery($sql);
			
			if ($d->dbNumRows($result)):
				$result_array = array();
				while($row = $d->dbFetchObject($result)):
					$result_array[] = array('id' => $row->id, 'name' => $row->name);
				endwhile;
				
				html::outputRelatedItems($result_array, urlencode($category));
			endif;
			
			return false;
		else:
			return false;
		endif;
	}
	
	/* Retrieve latest blogs for linking
	$has_recent_blogs (bool) - Whether or not to show this sidebar of content
	*/
	function getLatestBlogs( $has_recent_blogs ) {
		global $d;
 
		//Leave function if no blog posts for current page.
		if (!$has_recent_blogs)
			return false;
 
		$sql = "SELECT id, title FROM blog WHERE is_active = 1 ORDER BY pubdate DESC LIMIT " . RELATED_ITEMS_COUNT;
		$result = $d->dbQuery($sql);
 
		if ($d->dbNumRows($result)):
			$result_array = array();
			while($row = $d->dbFetchObject($result)):
				$result_array[] = array('id' => $row->id, 'title' => $row->title);
			endwhile;
 
			include('latestblogs.html.php');
		endif;
	}
 
	/* Get all blogs older than 6 months and list them on the side
	*/
	function getBlogArchive() {
		global $d, $page, $subpage;
 
		if ($subpage != 'blog')
			return false;
 
		$calendar_order = array();
		$current_month = date("n"); // Get Current Month
		
		//Loop from current month to end of the year.
		for($m=$current_month; $m<=12; $m++):
			//If month index is greater than current month, subtract year by one.
			$year = ($m > date("n")) ? strftime("%Y", strtotime("-1 year")) : date("Y");
			$monthstamp = mktime(0, 0, 0, $m, 1, $year);
			$monthendstamp = mktime(0, 0, 0, $m, date("t"), $year);
			
			//Retrieve number of blogs each month/year combination has for visual identification.
			$current_date_start = date("Y-m-d", $monthstamp);
			$current_date_end = date("Y-m-d", $monthendstamp);
			$sql = sprintf("SELECT id, title FROM blog WHERE pubdate BETWEEN '%s' AND '%s' AND is_active = 1 ORDER BY pubdate", $current_date_start, $current_date_end);
			$result = $d->dbQuery($sql);
			
			$calendar_order[] = array(
				'month_int' => date("n", $monthstamp),
				'month_text' => date("F", $monthstamp),
				'year' => $year,
				'blog_count' => $d->dbNumRows($result)
			);
		endfor;
		//Take difference from starting month and get remainder from start of year
		for($m=1; $m<$current_month; $m++):
			//If month index is greater than current month, subtract year by one.
			$year = ($m > date("n")) ? strftime("%Y", strtotime("-1 year")) : date("Y");
			$monthstamp = mktime(0, 0, 0, $m, 1, $year);
			$monthendstamp = mktime(0, 0, 0, $m, date("t"), $year);
			
			//Retrieve number of blogs each month/year combination has for visual identification.
			$current_date_start = date("Y-m-d", $monthstamp);
			$current_date_end = date("Y-m-d", $monthendstamp);
			$sql = sprintf("SELECT id, title FROM blog WHERE pubdate BETWEEN '%s' AND '%s' AND is_active = 1 ORDER BY pubdate", $current_date_start, $current_date_end);
			$result = $d->dbQuery($sql);			
			
			$calendar_order[] = array(
				'month_int' => date("n", $monthstamp),
				'month_text' => date("F", $monthstamp),
				'year' => $year,
				'blog_count' => $d->dbNumRows($result)
			);
		endfor;
 
		include('archiveblogs.html.php');
	}
}
 
//Used for query load times
class benchmark {
	function start_clock() {
		$time = microtime();
		$time = explode(' ', $time);
		$time = $time[1] + $time[0];
		return $time;
	}
	
	function end_clock() {
		$time = microtime();
		$time = explode(' ', $time);
		$time = $time[1] + $time[0];
		return $time;
	}
	
	function show_time() {
		global $start_time, $end_time;
		echo "\n<!-- Page generated in " . round(($end_time - $start_time), 4) . ' seconds.-->';
	}
}
 
/* Handle file downloads and uploads */
class files {
	function base64_url_encode($text) {
		return strtr(base64_encode($text), '+/=', '-_,');
	}
 
	function base64_url_decode($text) {
    	return base64_decode(strtr($text, '-_,', '+/='));
	}
}
 
function sendEmail( $recipient, $sender, $subject, $body, $attachment = '', $Cc = "", $Bcc = "" ) {
 
	include('class.email.php');
 
	$msg = new Email($recipient, $sender, $subject); 
	$msg->Cc = $Cc;
	$msg->Bcc = $Bcc;
	$msg->TextOnly = true;
	$msg->Content = strip_tags($body);
	//Append url to attachment into e-mail body if it exists as a backup precaution.
	if (strlen($attachment) && file_exists(EMAILTMP_F . FS . $attachment)):
		$msg->Content .= "\n\nYou can also download the attachment in the CMS.";
		$msg->Attach($emailfolder . $attachment['name'], $attachment['type']);
	endif;
 
	$SendSuccess = $msg->Send();
	
	return ($SendSuccess) ? true : false;
}
 
class emailformat {
 
	/*Checks to make sure e-mail is properly formatted */
	function checkEmail( $email ) {
		return preg_match('/^[A-Z0-9._%-]+@[A-Z0-9.-]+\.(?:[A-Z]{2}|com|org|net|biz|info|name|aero|biz|info|jobs|museum|name)$/i', $email);
	}
 
	function emailCloaking( $mail, $mailto=1, $text='', $email=1 ) {
		// convert text
		$mail 			= emailformat::encoding_converter( $mail );
		// split email by @ symbol
		$mail			= explode( '@', $mail );
		$mail_parts		= explode( '.', $mail[1] );
		// random number
		$rand			= rand( 1, 100000 );
	
		$replacement 	= "\n <script language='JavaScript' type='text/javascript'>";
		$replacement 	.= "\n <!--";
		$replacement 	.= "\n var prefix = '&#109;a' + 'i&#108;' + '&#116;o';";
		$replacement 	.= "\n var path = 'hr' + 'ef' + '=';";
		$replacement 	.= "\n var addy". $rand ." = '". @$mail[0] ."' + '&#64;';";
		$replacement 	.= "\n addy". $rand ." = addy". $rand ." + '". implode( "' + '&#46;' + '", $mail_parts ) ."';";
 
		if ( $mailto ) {
			// special handling when mail text is different from mail addy
			if ( $text ) {
				if ( $email ) {
					// convert text
					$text 			= emailformat::encoding_converter( $text );
					// split email by @ symbol
					$text 			= explode( '@', $text );
					$text_parts		= explode( '.', $text[1] );
					$replacement 	.= "\n var addy_text". $rand ." = '". @$text[0] ."' + '&#64;' + '". implode( "' + '&#46;' + '", @$text_parts ) ."';";
				} else {
					$replacement 	.= "\n var addy_text". $rand ." = '". $text ."';";
				}
				$replacement 	.= "\n document.write( '<a ' + path + '\'' + prefix + ':' + addy". $rand ." + '\'>' );";
				$replacement 	.= "\n document.write( addy_text". $rand ." );";
				$replacement 	.= "\n document.write( '<\/a>' );";
			} else {
				$replacement 	.= "\n document.write( '<a ' + path + '\'' + prefix + ':' + addy". $rand ." + '\'>' );";
				$replacement 	.= "\n document.write( addy". $rand ." );";
				$replacement 	.= "\n document.write( '<\/a>' );";
			}
		} else {
			$replacement 	.= "\n document.write( addy". $rand ." );";
		}
		$replacement 	.= "\n //-->";
		$replacement 	.= '\n </script>';
	
		// XHTML compliance `No Javascript` text handling
		$replacement 	.= "<script language='JavaScript' type='text/javascript'>";
		$replacement 	.= "\n <!--";
		$replacement 	.= "\n document.write( '<span style=\'display: none;\'>' );";
		$replacement 	.= "\n //-->";
		$replacement 	.= "\n </script>";
		//$replacement 	.= _CLOAKING;
		$replacement 	.= "\n <script language='JavaScript' type='text/javascript'>";
		$replacement 	.= "\n <!--";
		$replacement 	.= "\n document.write( '</' );";
		$replacement 	.= "\n document.write( 'span>' );";
		$replacement 	.= "\n //-->";
		$replacement 	.= "\n </script>";
	
		return $replacement;
	}
	
	function botMosEmailCloak_searchPattern ( $link, $text ) {	
		// <a href="mailto:anyLink">anyText</a>
		$pattern = "(<a [[:alnum:] _\"\'=\@\.\-]*href=[\"\']mailto:". $link	."[\"\'][[:alnum:] _\"\'=\@\.\-]*)>". $text ."</a>";
		return $pattern;
	}
	
	function encoding_converter( $text ) {
		// replace vowels with character encoding
		$text 	= str_replace( 'a', '&#97;', $text );
		$text 	= str_replace( 'e', '&#101;', $text );
		$text 	= str_replace( 'i', '&#105;', $text );
		$text 	= str_replace( 'o', '&#111;', $text );
		$text	= str_replace( 'u', '&#117;', $text );
	
		return $text;
	}
	
	function scrambleEmail( $text ) {
		if ( strpos( $text, '@' ) === false )
			return $text;
 
		$mode = 1;
		// any@email.address.com
		$search_email		= "([[:alnum:]_\.\-]+)(\@[[:alnum:]\.\-]+\.+)([[:alnum:]\.\-]+)";
		// any@email.address.com?subject=anyText
		$search_email_msg   = "([[:alnum:]_\.\-]+)(\@[[:alnum:]\.\-]+\.+)([[:alnum:]\.\-]+)([[:alnum:][:space:][:punct:]][^\"<>]+)";
		// anyText
		$search_text 		= "([[:alnum:][:space:][:punct:]][^<>]+)";
		$pattern = emailformat::botMosEmailCloak_searchPattern( $search_email, $search_email );
		while( eregi( $pattern, $text, $regs ) ) {	
			$mail 		= $regs[2] . $regs[3] . $regs[4];
			$mail_text 	= $regs[5] . $regs[6] . $regs[7];
		
			// check to see if mail text is different from mail addy
			if ($mail_text)
				$replacement = emailformat::emailCloaking( $mail, $mode, $mail_text );
			else
				$replacement = emailformat::emailCloaking( $mail, $mode );
		
			// replace the found address with the js cloacked email
			$text 	= str_replace( $regs[0], $replacement, $text );
		}
		
		// search for derivativs of link code <a href="mailto:email@amail.com">anytext</a>
		$pattern = emailformat::botMosEmailCloak_searchPattern( $search_email, $search_text );
		while( eregi( $pattern, $text, $regs ) ) {		
			$mail 		= $regs[2] . $regs[3] . $regs[4];
			$mail_text 	= $regs[5];
		
			$replacement = emailformat::emailCloaking( $mail, $mode, $mail_text, 0 );
		
			// replace the found address with the js cloacked email
			$text 	= str_replace( $regs[0], $replacement, $text );
		}
		
		// search for derivativs of link code <a href="mailto:email@amail.com?subject=Text&body=Text">email@amail.com</a>
		$pattern = emailformat::botMosEmailCloak_searchPattern( $search_email_msg, $search_email );
		while( eregi( $pattern, $text, $regs ) ) {		
			$mail		= $regs[2] . $regs[3] . $regs[4] . $regs[5];
			$mail_text	= $regs[6] . $regs[7]. $regs[8];
			//needed for handling of Body parameter
			$mail 		= str_replace( '&amp;', '&', $mail );
		
			// check to see if mail text is different from mail addy
			if ($mail_text)
				$replacement = emailformat::emailCloaking( $mail, $mode, $mail_text );
			else
				$replacement = emailformat::emailCloaking( $mail, $mode );
		
			// replace the found address with the js cloacked email
			$text     = str_replace( $regs[0], $replacement, $text );
		}
		
		// search for derivativs of link code <a href="mailto:email@amail.com?subject=Text&body=Text">anytext</a>
		$pattern = emailformat::botMosEmailCloak_searchPattern( $search_email_msg, $search_text );
		while( eregi( $pattern, $text, $regs ) ) {		
			$mail		= $regs[2] . $regs[3] . $regs[4] . $regs[5];
			$mail_text	= $regs[6];
			//needed for handling of Body parameter
			$mail 		= str_replace( '&amp;', '&', $mail );
		
			$replacement = emailformat::emailCloaking( $mail, $mode, $mail_text, 0 );
		
			// replace the found address with the js cloacked email
			$text     = str_replace( $regs[0], $replacement, $text );
		}
		
		// search for plain text email@amail.com
		while( eregi( $search_email, $text, $regs ) ) {
			$mail = $regs[0];
		
			$replacement = emailformat::emailCloaking( $mail, $mode );
		
			// replace the found address with the js cloacked email
			$text = str_replace( $regs[0], $replacement, $text );
		}
		
		return $text;
	}
	
}
 
//Homepage-only functions
class homepage {
 
	//Get top 2 news articles for display
	function getTopNews() {
		global $d, $ak;
		
		$result = $d->dbQuery("SELECT id, title, filename FROM news WHERE is_active = 1 ORDER BY leadpost DESC, start_date DESC LIMIT 2");
		$news_array = array();
		while ($row = $d->dbFetchObject($result)):
			$news_array[] = array(
				'id' => $row->id,
				'title' => $row->title,
				'filename' => $row->filename
			);
		endwhile;
 
		include('newshomepage.html.php');
	}
	
	//Get top 2 blogs for display
	function getTopBlogs() {
		global $d, $ak;
		
		$result = $d->dbQuery("SELECT id, title FROM blog WHERE is_active = 1 ORDER BY pubdate DESC LIMIT 2");
		$news_array = array();
		while ($row = $d->dbFetchObject($result)):
			$blog_array[] = array(
				'id' => $row->id,
				'title' => $row->title
			);
		endwhile;
 
		include('bloghomepage.html.php');
	}
}
?>

Open in new window

0
 
phillystyle123Author Commented:
Found this for the .htaccess part but doesn't have any effect - i'm still getting a page not found error:

http://www.srpsubro.com/resources/articles/offset-of-future-claims%3A-wave-of-the-future%3F.html
# If the rewriteRule applies, check if the query string is a single trailing question mark or only the 'ref' element
rewriteCond %{THE_REQUEST} \?(ref=([_0-9a-z-])*)?\ HTTP [NC]
# Any request matches, so if either condition above is true, then strip the entire query string and do a redirect
rewriteRule .? http://www.mysite.com%{REQUEST_URI}? [R=301,L]

Open in new window

0
 
phillystyle123Author Commented:
Man - this thing is killing me:

just added this to my .htaccess and still getting the error:

RewriteCond %{QUERY_STRING} \?\ HTTP [NC]
RewriteRule .? http://www.srpsubro.com%{REQUEST_URI}? [R=301,L]

this is what the failed URL looks like:

http://www.srpsubro.com/resources/articles/offset-of-future-claims%3A-wave-of-the-future%3F.html

error says:
The requested URL /resources/articles/offset-of-future-claims:-wave-of-the-future?.html was not found on this server
0
 
Steve BinkCommented:
What do you want the final URL to look like?  It can't be with the %3F in it, since filenames can't use the '?' character.
0
 
phillystyle123Author Commented:
0
 
phillystyle123Author Commented:
also routinet - this URL only currently works because i frankenstiened a questionmark into the title and got rid of it in the actual title field in the database - so i'm still looking for a soloution.

thanks in advance!
0
 
Steve BinkCommented:
You could use back-references to remove a character, but because the check is not recursive, you'll only get a single match.  For example:

RewriteRule (.*)\?(.*) $1$2

That will remove a single question mark from the URL, though you might need to check for \%3[fF] instead, or even a variety of characters to prevent the necessity of multiple rules.  To make it recursive, you can use the [N] flag on the rule, but you should keep in mind that the [N] flag restarts the ENTIRE rewrite process, not just the last rule.  If this rule is listed first, though, it shouldn't be too bad on response time.

RewriteRule (.*)\?(.*) $1$2 [N]

Otherwise, I'm afraid you'll need to go with caterham_www's suggestion: handle it in the class.  The downside here is that the user will still see the original 'mal-formed' URL unless you do a header() redirect from the code.

I think the absolute best suggestion is to keep the character limitations of URLs in mind when creating the titles of your articles.  I understand punctuation can be pretty necessary, but that is what presentation is for.  The URL naming convention is not about presentation - it's about finding resources.  Allowing special characters in your URL, as you are seeing here, just leads to trouble.
0
 
phillystyle123Author Commented:
thanks routinet  - i do need to find a more flexible solution to this though -

forgive my ignorance but can i use anything else here like scrubURL or something like that???

 $url = preg_replace('%[^a-zA-Z0-9_/-]%', '', $url);
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 9
  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now