Error on specific search query - php

I have a website ongrounds.com there is a search bar on top when ever I search for word "best" it generates following error
Warning: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s) AS relevance FROM hotaru_posts WHERE (post_status = %s OR post_status = %s)' at line 1 in /home2/onground/public_html/libs/extensions/ezSQL/mysql/ez_sql_mysql.php on line 264
Notice: Trying to get property of non-object in /home2/onground/public_html/content/plugins/bookmarking/libs/BookmarkingFunctions.php on line 132
But when I search any other word except "best" the search plugin works fine and it shows results. I do not know why it is showing error on word "best". Please help.
SEARCH PLUGIN CODE:
class Search
{
/**
* Add permissions and register search widget
*/
public function install_plugin($h)
{
// Permissions
$site_perms = $h->getDefaultPermissions('all');
if (!isset($site_perms['can_search'])) {
$perms['options']['can_search'] = array('yes', 'no');
$perms['can_search']['default'] = 'yes';
$h->updateDefaultPermissions($perms);
}
// widget
$h->addWidget('search', 'search', ''); // plugin name, function name, optional arguments
}
/**
* Get search results
*/
public function theme_index_top($h)
{
// Get page title
if ($h->cage->get->keyExists('search')) {
$title = stripslashes(htmlentities($h->cage->get->sanitizeTags('search'),ENT_QUOTES,'UTF-8'));
$h->pageTitle = make_name($title);
$h->subPage = 'search';
$h->pageType = 'list';
$h->pageName = 'search';
}
}
/**
* Displays "Search!" wherever the plugin hook is.
*/
public function search_box($h)
{
$h->displayTemplate('search_box', 'search');
}
/**
* Displays "Search!" wherever the plugin hook is.
*/
public function widget_search($h)
{
$h->displayTemplate('search_box', 'search');
}
/**
* Use the search terms to build a filter
*/
public function bookmarking_functions_preparelist($h, $vars)
{
if ($h->cage->get->keyExists('search'))
{
$return = $vars['return']; // are we getting the count or the result set?
$orig_search_terms = stripslashes($h->cage->get->sanitizeTags('search'));
$search_terms = $orig_search_terms;
if ($search_terms)
{
// fetch select, orderby and filter...
$prepared_search = $this->prepareSearchFilter($h, $search_terms, $return);
extract($prepared_search);
$h->vars['orig_search'] = $orig_search_terms; // use this to re-fill the search box after a search
$h->vars['orig_search_terms'] = $orig_search_terms; // used in the breadcrumbs function
return true;
}
}
return false;
}
/**
* Prepare search filter
*/
public function prepareSearchFilter($h, $search, $return = 'posts')
{
$search_terms = strtolower($search);
$search_terms = explode(" ", $search_terms);
$search_terms = array_iunique($search_terms);
$search_terms_clean = '';
$full_text = true; // Do a full text (better) search if all terms are longer than 3 characters
foreach($search_terms as $search_term) {
if ($this->isStopword($search_term)) {
continue; // don't include this in $search_terms_clean
}
if (strlen(trim($search_term)) < 4) {
$full_text = false;
}
$search_term = trim($h->db->escape($search_term));
// if the urlencoded term contains a percent sign, we can't use a full text search
if (strpos(urlencode($search_term), '%') !== false) {
$full_text = false;
}
$search_terms_clean .= $search_term . " ";
}
// Undo the filter that limits results to either 'top', 'new' or archived (See submit.php -> sub_prepare_list())
if (isset($h->vars['filter']['post_status = %s'])) { unset($h->vars['filter']['post_status = %s']); }
if (isset($h->vars['filter']['post_archived = %s'])) { unset($h->vars['filter']['post_archived = %s']); }
// filter to top or new stories only:
$h->vars['filter']['(post_status = %s OR post_status = %s)'] = array('top', 'new');
$select = ($return == 'count') ? "count(*) AS number " : "*";
if ($full_text) {
$h->vars['select'] = array($select . ", MATCH(post_title, post_domain, post_url, post_content, post_tags) AGAINST (%s) AS relevance" => trim($search_terms_clean));
$h->vars['orderby'] = "relevance DESC";
$h->vars['filter']["MATCH (post_title, post_domain, post_url, post_content, post_tags) AGAINST (%s IN BOOLEAN MODE)"] = trim($search_terms_clean);
} else {
$h->vars['select'] = $select;
$h->vars['orderby'] = "post_date DESC";
$h->vars['filter_vars'] = array();
$where = $this->explodeSearch($h, 'post_title', $search_terms_clean) . " OR ";
$where .= $this->explodeSearch($h, 'post_url', $search_terms_clean) . " OR ";
$where .= $this->explodeSearch($h, 'post_content', $search_terms_clean);
$where = '(' . $where . ')';
$h->vars['filter'][$where] = $h->vars['filter_vars'];
}
$prepared_search = array('select' => $h->vars['select'], 'orderby' => $h->vars['orderby'], 'filter' => $h->vars['filter']);
return $prepared_search;
}
/** Explode search for short words
*
* #param string $column
* #param string $search_terms
* #return string (with " OR " stripped off the end)
*/
public function explodeSearch($h, $column, $search_terms)
{
$query = '';
foreach(explode(' ', trim($search_terms)) as $word){
if ($word) {
$query .= $column . " LIKE %s OR ";
$search_term = urlencode(" " . trim($h->db->escape($word)) . " ");
// escape all percent signs for use in LIKE query:
$search_term = str_replace('%', '\%', $search_term);
array_push($h->vars['filter_vars'], "%" . $search_term . "%");
}
}
return substr($query, 0, -4);
}
/**
* Is it a stopword?
*
*#return bool
*/
public function isStopword($word)
{
$word_array = array();
// list came from http://meta.wikimedia.org/wiki/MySQL_4.0.20_stop_word_list
$stopwordlist = "things ii iii a able about above according accordingly across actually after afterwards again against ain't all allow allows almost alone along already also although always am among amongst an and another any anybody anyhow anyone anything anyway anyways anywhere apart appear appreciate appropriate are aren't around as aside ask asking associated at available away awfully be became because become becomes becoming been before beforehand behind being believe below beside besides best better between beyond both brief but by c'mon c's came can can't cannot cant cause causes certain certainly changes clearly co com come comes concerning consequently consider considering contain containing contains corresponding could couldn't course currently definitely described despite did didn't different do does doesn't doing don't done down downwards during each edu eg eight either else elsewhere enough entirely especially et etc even ever every everybody everyone everything everywhere ex exactly example except far few fifth first five followed following follows for former formerly forth four from further furthermore get gets getting given gives go goes going gone got gotten greetings had hadn't happens hardly has hasn't have haven't having he he's help hence her here here's hereafter hereby herein hereupon hers herself hi him himself his hither hopefully how howbeit however i'd i'll i'm i've ie if ignored immediate in inasmuch inc indeed indicate indicated indicates inner insofar instead into inward is isn't it it'd it'll it's its itself just keep keeps kept know knows known last lately later latter latterly least less lest let let's like liked likely little look looking looks ltd mainly many may maybe me mean meanwhile merely might more moreover most mostly much must my myself name namely nd near nearly necessary need needs neither never nevertheless new next nine no nobody non none noone nor normally not nothing novel now nowhere obviously of off often oh ok okay old on once one ones only onto or other others otherwise ought our ours ourselves out outside over overall own part particular particularly per perhaps placed please plus possible presumably probably provides que quite qv rather rd re really reasonably regarding regardless regards relatively respectively right said same saw say saying says second secondly see seeing seem seemed seeming seems seen self selves sensible sent serious seriously seven several shall she should shouldn't since six so some somebody somehow someone something sometime sometimes somewhat somewhere soon sorry specified specify specifying still sub such sup sure t's take taken tell tends th than thank thanks thanx that that's thats the their theirs them themselves then thence there there's thereafter thereby therefore therein theres thereupon these they they'd they'll they're they've think third this thorough thoroughly those though three through throughout thru thus to together too took toward towards tried tries truly try trying twice two un under unfortunately unless unlikely until unto up upon us use used useful uses using usually value various very via viz vs want wants was wasn't way we we'd we'll we're we've welcome well went were weren't what what's whatever when whence whenever where where's whereafter whereas whereby wherein whereupon wherever whether which while whither who who's whoever whole whom whose why will willing wish with within without won't wonder would would wouldn't yes yet you you'd you'll you're you've your yours yourself yourselves zero";
$word_array = explode(' ', $stopwordlist);
if (array_search($word, $word_array) == true) {
return true;
} else {
return false;
}
}
/**
* Add RSS link to breadcrumbs
*/
public function breadcrumbs($h)
{
if ($h->subPage != 'search') { return false; }
$crumbs = "<a href='" . $h->url(array('search'=>urlencode($h->vars['orig_search_terms']))) . "'>\n";
$crumbs .= $h->vars['orig_search_terms'] . "</a>\n ";
return $crumbs . $h->rssBreadcrumbsLink('', array('search'=>urlencode($h->vars['orig_search_terms'])));
}
/**
* If a search feed, set it up
*/
public function post_rss_feed($h)
{
Thank you

It looks like this error will occur if the searched word ist a Fulltext-stopword.
I cant tell you why this results in an error, but maybe this knowledge leads you into successfull investigations.

Related

PHP detect SQL injection attempt

My code is already safe, using parameters in SQL queries, but, I would like to detect if anyone attempts to inject something into a submit form.
I found Snort, but I would need something that would be at PHP script level, not the whole network.
This is for a site that contains personal information for students and thus, we will warn (or even take action against) anyone that even tries an attack.
I have created a very basic and simple PHP class for checking / detecting SQL injection attempts.
<?php
/**
* simpleSQLinjectionDetect Class
* #link https://github.com/bs4creations/simpleSQLinjectionDetect
* #version 1.1
*/
class simpleSQLinjectionDetect
{
protected $_method = array();
protected $_suspect = null;
public $_options = array(
'log' => true,
'unset' => true,
'exit' => true,
'errMsg' => 'Not allowed',
);
public function detect()
{
self::setMethod();
if(!empty($this->_method))
{
$result = self::parseQuery();
if ($result)
{
if ($this->_options['log']) {
self::logQuery();
}
if ($this->_options['unset']){
unset($_GET, $_POST);
}
if ($this->_options['exit']){
exit($this->_options['errMsg']);
}
}
}
}
private function setMethod()
{
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$this->_method = $_GET;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$this->_method = $_POST;
}
}
private function parseQuery()
{
$operators = array(
'select * ',
'select ',
'union all ',
'union ',
' all ',
' where ',
' and 1 ',
' and ',
' or ',
' 1=1 ',
' 2=2 ',
' -- ',
);
foreach($this->_method as $key => $val)
{
$k = urldecode(strtolower($key));
$v = urldecode(strtolower($val));
foreach($operators as $operator)
{
if (preg_match("/".$operator."/i", $k)) {
$this->_suspect = "operator: '".$operator."', key: '".$k."'";
return true;
}
if (preg_match("/".$operator."/i", $v)) {
$this->_suspect = "operator: '".$operator."', val: '".$v."'";
return true;
}
}
}
}
private function logQuery()
{
$data = date('d-m-Y H:i:s') . ' - ';
$data .= $_SERVER['REMOTE_ADDR'] . ' - ';
$data .= 'Suspect: ['.$this->_suspect.'] ';
$data .= json_encode($_SERVER);
#file_put_contents('./logs/sql.injection.txt', $data . PHP_EOL, FILE_APPEND);
}
}
/* then call it in your app...
*********************************************/
$inj = new simpleSQLinjectionDetect();
$inj->detect();
You can check it on github also
This is a very simple and basic class. Any suggestions for improvements / updates are welcome :)
This is actually quite a hard topic. BillyK may have a semi-viable approach but it's better to let MySQL do the hard work for you; therefore:
1) Run the user-constructed (ie unsafe) query in a MySQL Transaction.
2) How many results does it give? (Check for both rows returned and rows affected)
3) Record any MySQL error warning logs.
4) Cancel / rollback the Transaction. So that nothing has changed on your database.
5) Re-run the query with the paramaterised variable (ie safe)
6) How many results does it give? (Check for both rows returned and rows affected)
7) Check if (6) gives a different number of results to (2) or if (5) gives any SQL error warnings. You can also use PHP array comparison features to check if the result sets are equal.
8) Any positives come up, such as differences in result counts, result set eqauality or SQL warnings, then record that query string into a save file for human review.
Concept Thoughts:
With a properly implemented system of Prepared Statements it is not possible for SQL injection to occur from user variables as data strings. Therefore, rather like people throwing water balloons at tanks; it's also pretty worthless to try and "detect" these infractions; they in themselves don't show you anything more than someone read some website that offers such methods.
Therefore, as long as you have built your PHP/SQL correctly then any number or any quality of SQL injecton attempts are just water off a ducks back, and you cumulatively waste more processing power and time and effort trying to detect and record them than you would simply to ignore them.

Database search like google [duplicate]

This question already has answers here:
Google-like Search Engine in PHP/mySQL [closed]
(9 answers)
Closed 1 year ago.
I currently have a search option on my PHP+MYSQL website.
The MYSQL query is currently something like "SELECT pageurl WHERE name LIKE '%$query%'.
The reason I posted here is because I noticed that if the name of one of my products is "Blue Bike" and someone looks for "Bike Blue", no results are returned.
I am looking for a solution to this because I know that if I type on google same word, something appears.
I was thinking to create a PHP function to mix up all the words from the query if the query is having 4 or fewer words, generating around 24 queries.
Is there an easier solution to this?
Thanks for your time
As to not let this go without a working answer:
<?php
$search = 'this is my search';
$searchSplit = explode(' ', $search);
$searchQueryItems = array();
foreach ($searchSplit as $searchTerm) {
/*
* NOTE: Check out the DB connections escaping part
* below for the one you should use.
*/
$searchQueryItems[] = "name LIKE '%" . mysqli_real_escape_string($searchTerm) . "%'";
}
$query = 'SELECT pageurl FROM names' . (!empty($searchQueryItems) ? ' WHERE ' . implode(' AND ', $searchQueryItems) : '');
?>
DB connections escaping
mysqli_:
Keep using mysqli_real_escape_string or use $mysqli->real_escape_string($searchTerm).
mysql_:
if you use mysql_ you should use mysql_real_escape_string($searchTerm) (and think about changing as it's deprecated).
PDO:
If you use PDO, you should use trim($pdo->quote($searchTerm), "'").
use full text search instead of like
full text search based on indexed text and is very faster and beter than using like.
see this article for more information about full text search
What you are looking for is fulltext search.
Try Sphinx, it is very fast and integrates well with MySQL.
Sphinx website
I wrote a function that approaches Google's operation taking into account the double quotes for the elements to search as a whole block. It does NOT take into account the - or * instructions.
table: MySQL table to consider
cols: array of column to parse
searchParams: search to process. For example: red mustang "Florida 90210"
function naturalQueryConstructor($table, $cols, $searchParams) {
// Basic processing and controls
$searchParams = strip_tags($searchParams);
if( (!$table) or (!is_array($cols)) or (!$searchParams) ) {
return NULL;
}
// Start query
$query = "SELECT * FROM $table WHERE ";
// Explode search criteria taking into account the double quotes
$searchParams = str_getcsv($searchParams, ' ');
// Query writing
foreach($searchParams as $param) {
if(strpos($param, ' ') or (strlen($param)<4)) {
// Elements with space were between double quotes and must be processed with LIKE.
// Also for the elements with less than 4 characters. (red and "Florida 90210")
$query .= "(";
// Add each column
foreach($cols as $col) {
if($col) {
$query .= $col." LIKE '%".$param."%' OR ";
}
}
// Remove last ' OR ' sequence
$query = substr($query, 0, strlen($query)-4);
// Following criteria will added with an AND
$query .= ") AND ";
} else {
// Other criteria processed with MATCH AGAINST (mustang)
$query .= "(MATCH (";
foreach($cols as $col) {
if($col) {
$query .= $col.",";
}
}
// Remove the last ,
$query = substr($query, 0, strlen($query)-1);
// Following criteria will added with an AND
$query .= ") AGAINST ('".$param."' IN NATURAL LANGUAGE MODE)) AND ";
}
}
// Remove last ' AND ' sequence
$query = substr($query, 0, strlen($query)-5);
return $query;
}
Thanks to the stackoverflow community where I found parts of this function!
To have a google like search you'd need many database and index nodes, crazy algorithms.. now you come up with a SELECT LIKE ... lol :D
MySQL is slow in searching, you'd need fulltext and index set properly (MyISAM or Aria Engine). Combinations or different entities to search for are almost not implementable properly AND fast.
I'd suggest to setup an Elasticsearch server which is based on Apache's Lucene.
This searchs very fast and is easy to maintain. And you would not have to care about SQL injection and can still use the mysql server fast.
Elasticsearch (or other Lucene based search engines like SolR) can easily be installed on any server because they are written in Java.
Good documentation:
http://www.elasticsearch.org/guide/en/elasticsearch/client/php-api/current/
I would do an explode first:
$queryArray = explode(" ", $query);
and then generate the SQL query something like:
for ($i=0; $i< count($queryArray); $i++) {
$filter += " LIKE '%" + $queryArray[$i] + "%' AND" ;
}
$filter = rtrim ($filter, " AND");
$sql = "SELECT pageurl FROM ... WHERE name " + $filter
(note: haven't tested/run this code)

Recursive function returns nothing [duplicate]

This question already has answers here:
How to use return inside a recursive function in PHP
(4 answers)
Closed 9 months ago.
I have a database full of autopart numbers that needs old part numbers prices updated. Each row features a part number (field name "master") a price and a field with superseded (newer) part numbers (field name "pnc"). The script needs to check if the "pnc" field isn't empty. If it's not, it should go and grab the price for that number. Easy enough.
However, some part numbers have an unknown level of numbers to go through until it reaches the most current part number and price. So, I figured a recursive function would be the best solution. However, it's not working correctly. Here's the code:
public function updatePricing()
{
//method to update pricing by referencing supersession prices
$sql = "SELECT * FROM prices";
$result = mysql_query($sql);
$num_rows = mysql_num_rows($result);
for($i=0;$i<2000;$i++) //using 2000 for testing, use $num_rows after
{
$row = mysql_fetch_array($result);
$id = $row['id'];
$super_num = $row['pnc'];
//if there is a supersession in this row find original
if(!empty($super_num))
{
$final_super_price = $this->findSuperPrice($super_num);
echo "partnum: " . $row['master'];
echo " ";
echo "price: " . $final_super_price . "<br /><br />";
}
}
}
public function findSuperPrice($part_num)
{
$sql = "SELECT * FROM prices WHERE master='" . $part_num . "'";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
if (empty($row['pnc'])) //if there aren't any supersession numbers
{
$final_price = $row['list'];
return $final_price;
}
else //recursively call itself until we find the last number
{
$this->findSuperPrice($row['pnc']);
}
}
What's happening is the updatePricing() function runs until it finds a row that has an entry in the "pnc" field. When it does, the findSuperPrice() function is called. The findSuperPrice() function should run recursively until the "pnc" field is empty. When that happens a number is returned.
However, if it actually reaches the else part of the if statment in findSuperPrice(), it doesn't return anything. Basically, if it's more than one level deep. I'm not getting any errors, it's just returning a blank statement. I've verified there is information there that it should be returning also. Thanks.
Also, I should mention this is inside of a larger class. The rest of the class has no bearing on these two methods.
You need to return a value. Change this code:
else //recursively call itself until we find the last number
{
$this->findSuperPrice($row['pnc']);
}
To this:
else //recursively call itself until we find the last number
{
return $this->findSuperPrice($row['pnc']);
}
You currently do not get a return value because the result of findSuperPrice is ignored if $row['pnc'] is not empty. Correctly return the value of the recursive calls:
return $this->findSuperPrice($row['pnc']);
You are missing a return statement in the else case inside findSuperPrice.
But... it looks like you are pumping a whole lot of data to look at/manipulate only a single field. You could also write function in mysql, similar to the one I posted here: MySQL: Get Root Node of Parent-Child Structure
That could enable you to query the required value directly from the database. If you have the structure for your tables I'd be happy to help out.

BBCode, preg_replace, and named capturing groups

What I thought was going to be an easy implementation of two lines of code and a function, turned out to be made of fail.
On my webpage, I want to be able to type [text]1[/text], and what it will do is pull the title of that ID.
function textFormat($text) {
$raw = array(
'\'\[text\](?P<id>.*?)\[/text\]\'is'
);
$out = array (
'<a href="index.php?function=getData&reference=text&id=$1">' . getTextTitle() . '</a>'
);
preg_replace($raw, $out, $text);
return $text;
}
function getTextTitle($id) {
$sql = mysql_query("SELECT title FROM text WHERE id = $id");
return mysql_result($sql);
}
So, here's the lovely little problem: As one can tell, I'm calling a function with a numeric-titled variable, which works great in the quotation marks, but as we know, PHP doesn't like that. So, I opted for a named group. Using $regs['id'] fails to work.
Am I doing something wrong?
Am I going about this the wrong way?
Well, you're certainly doing it in a radically different way than I ever would, but I think something not too far off from what you're attempting may possibly work. Try this:
function textFormat($text) {
$raw = array(
'\'\[text\](?P<id>.*?)\[/text\]\'ise'
);
$out = array (
'\'<a href="index.php?function=getData&reference=text&id=$1">\' . getTextTitle(\'$1\') . \'</a>\''
);
preg_replace($raw, $out, $text);
return $text;
}
function getTextTitle($id) {
$sql = mysql_query("SELECT title FROM text WHERE id = '" . mysql_real_escape_string($id) . "'");
$res = mysql_result($sql);
$row = mysql_fetch_array($res);
return $row ? $row[0] : 'invalid ID';
}
Your original getTextTitle() would, unless something else is going on I'm not aware of, let anyone do anything they liked to your database via SQL injection, by the way. You're welcome.
Also, I don't know what that (?P<id> noise is about in the regex, so I'm assuming it's needed for some reason and leaving it alone. I do not know whether this is correct.

How do I print a single comment in drupal?

I want to print a individual comment in drupal based on it's comment ID. How can I do this? Google and other sources have yielded me nothing. Thank you.
Eaton's suggestion is good (except it's {comments}, not {comment}) if you need to display the comment like core does it, including the info coming from the node. Except the default theme_comment implementation in modules/comment/comment.tpl.php makes no use of $node.
However, I'd do it slightly differently, because if you need to extract a single comment, displaying it with the normal content formatting provided by comment.tpl.php is likely to be inappropriate.
function print_comment($cid) {
$sql = "SELECT * FROM {comment} c WHERE c.cid = %d";
if ($comment = db_fetch_object(db_rewrite_sql(db_query($sql, $cid), 'c'))) {
return theme('my_special_comment_formatting', $comment);
}
}
And of course, define this special commment formatting in your module's hook_theme() implementation, inspired by what comment.tpl.php does.
2014-02 UPDATE: note that this is a 2009 question/answer. In Drupal 8, you just don't want to access the hypothetical underlying SQL database (and would not do it like this anyway, but use DBTNG), but just use something like:
if ($comment = entity_load('comment', $cid)) {
return entity_view($comment, $view_mode);
}
function print_comment($cid) {
$sql = "SELECT * FROM {comments} WHERE cid = %d";
if ($comment = db_fetch_object(db_query($sql, $cid))) {
$node = node_load($comment->nid);
return theme('comment', $comment, $node);
}
}
No reason to use any sql to do this, two drupal api function calls is all it takes.
function print_comment($cid)
{
$comment = _comment_load($cid);
return theme('comment',$comment);
}

Categories