Since mysql_* is going deprecated, I was thinking of an easy way to replace all deprecated code.
Here is my regex; whereas find is what I want to find and repl is what I want to replace it with.
$__db is my declared mysqli_connect-variable
Change MySQL into MySQLi
--
find: mysql_select_db\(([\$"a-zA-Z0-9_]+)\)
repl: \$__db->select_db($1)
--
find: mysql_fetch_object\((\$[a-zA-Z0-9_]+)\)
repl: $1->fetch_object()
--
find: mysql_fetch_array\((\$[a-zA-Z0-9_]+)\)
repl: $1->fetch_array()
--
find: mysql_num_rows\((\$[a-zA-Z0-9_]+)\)
repl: $1->num_rows
--
find: mysql_free_result\((\$[a-zA-Z0-9_]+)\)
repl:
--
find: mysql_query
repl: \$__db->query
--
find: mysql_error\(\)
repl: mysqli_error\(\)
--
find: ([\$a-zA-Z0-9_]+) = mysql_result\(([\$a-zA-Z0-9_]+), (\d+)\)
repl: \$row = $2->fetch_array();\r\n$1 = \$row[$3]
And my question would be, can I run multiple regex-replaces (so that I can replace all code at the same time)?
I know that I can use pipe | to separate the find-part, but how does it work with the replace-part?
I haven't found a way to make a macro in Aptana Studio 3.
This became my solution, with tips from HamZa (Thanks!)
I created a script, that iterates over a directory of choosing (Specified in $dir)
We also get to say what we're looking for in the files with $lookFor
I added some comments in the code, so you can follow what I do. This WON'T solve function-db's though.
So if you have classes with DB-connections you'll have to add something for functions.
Right now this script won't change your files (I commented it out, so you can use it to just browse through your code with the "recommended" changes)
And also.. I haven't made it so the script prepares statements.
(That is step two, this was just to fix things that would break when mysql_* gets removed)
The result will look something like this: (Actually showing that missing function I talked about.. I'll have to add global $__db; into each function
And then finally! Here's the code.
<?
/*IGNORE-MYSQL*/
function startsWith($haystack, $needle)
{
return strpos($haystack, $needle) === 0;
}
function endsWith($haystack, $needle)
{
return substr($haystack, -strlen($needle)) == $needle;
}
function doFlush()
{
#flush();
#ob_flush();
}
function runMySQLToMySQLi_replace($str, $useBoldShow = false, $replace = true)
{
$catchVars = '\$"\'a-zA-Z0-9_\.\*\->,\[\] ';
$regexTests = Array();
$regexTests['(?:['.$catchVars.']+\s?=\s?)?mysql_connect\((['.$catchVars.']+),\s?(['.$catchVars.']+),\s?(['.$catchVars.']+)\)'] = '\$__db = mysqli_connect($1, $2, $3)';
$regexTests['mysql_select_db\((['.$catchVars.']+)(?:,\s?['.$catchVars.']+)?\)'] = '\$__db->select_db($1)';
$regexTests['mysql_query\((['.$catchVars.'\(\)=]+)(?:,\s?['.$catchVars.']+)?\)'] = '\$__db->query($1)';
$regexTests['mysql_errno\(\)'] = '\$__db->errno';
$regexTests['mysql_error\(\)'] = '\$__db->error';
$regexTests['mysql_error\((['.$catchVars.']+)\)'] = '\$__db->error';
$regexTests['mysql_fetch_object\((['.$catchVars.']+)\)'] = '$1->fetch_object()';
$regexTests['mysql_fetch_row\((['.$catchVars.']+)\)'] = '$1->fetch_array()';
$regexTests['mysql_fetch_array\((['.$catchVars.']+)\)'] = '$1->fetch_array()';
$regexTests['mysql_fetch_assoc\((['.$catchVars.']+)\)'] = '$1->fetch_assoc()';
$regexTests['mysql_num_rows\((['.$catchVars.']+)\)'] = '$1->num_rows';
$regexTests['mysql_free_result\((['.$catchVars.']+)\)'] = '$1->free()';
$regexTests['mysql_insert_id\(\)'] = '\$__db->insert_id';
$regexTests['(['.$catchVars.']+) = mysql_result\((['.$catchVars.']+), (\d+)\)'] = "\$row = $2->fetch_array(); $1 = \$row[$3]";
$tmpVal = $str;
foreach($regexTests as $reg => $rep)
{
$match = preg_match("/" . $reg . "/i", $tmpVal);
if($match)
{
if($replace)
$tmpVal = preg_replace("/" . $reg . "/i", ($useBoldShow ? "[{b}]" : "") . $rep . ($useBoldShow ? "[/{b}]" : ""), $tmpVal);
else
$tmpVal = preg_replace("/" . $reg . "/i", ($useBoldShow ? "[{b}]" : "") . "$0" . ($useBoldShow ? "[/{b}]" : ""), $tmpVal);
}
}
return $tmpVal;
}
?>
<html>
<head>
<style>
body { margin: 0; padding: 0; }
.mysql_found { background-color: mistyrose; padding: 10px; border: 1px solid #c9c9c9; border-radius: 5px; margin: 10px; }
.no_select {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: moz-none;
-ms-user-select: none;
user-select: none;
display: inline-block;
}
</style>
</head>
<body>
<pre><?
// Directory to search in
$dir = "/dir/to/search/in/";
$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir), RecursiveIteratorIterator::SELF_FIRST);
// What we are looking for in all files
$lookFor = "mysql_";
foreach($objects as $name => $object)
{
// Ensure that it is PHP-files we're going through
if(endsWith($object->getFilename(), '.php'))
{
// Get all contents
$contents = file_get_contents($object->getPathname());
// Split it into rows
$rowSplit = preg_split('/$\R?^/m', $contents);
// Check the contents for $lookFor
if(strpos($contents, $lookFor) > 0 && strpos($contents, "/*IGNORE-MYSQL*/") === false)
{
echo "<div class=\"mysql_found\">\"" . $lookFor . "\" found in: " . $object->getPathname() . "\n";
echo "<hr noshade=\"noshade\" />\n";
echo "Source code:\n";
$lCount = 1;
foreach($rowSplit as $row)
{
echo "<div class=\"no_select\" unselectable=\"on\">" . str_pad($lCount++, strlen(count($rowSplit)), " ", STR_PAD_LEFT) . ": </div>" . str_replace(Array("[{b}]", "[/{b}]"), Array("<b style=\"background-color: #cfaaaa;\">", "</b>"), htmlentities(runMySQLToMySQLi_replace($row, true, false))) . "\n";
}
echo "\n\n";
$lCount = 1;
echo "Fixed code:<br /><br />";
$doneCode = "";
foreach($rowSplit as $row)
{
echo "<div class=\"no_select\" unselectable=\"on\">" . str_pad($lCount++, strlen(count($rowSplit)), " ", STR_PAD_LEFT) . ": </div>" . str_replace(Array("[{b}]", "[/{b}]"), Array("<b style=\"background-color: #cfaaaa;\">", "</b>"), htmlentities(runMySQLToMySQLi_replace($row, true))) . "\n";
// This is the code that actually does the replacing.
$doneCode .= runMySQLToMySQLi_replace($row) . "\n";
}
// This is commented out, since I want to make sure it works before I accept some changes.
// I actually tried it on 3 files without problems.
//if(isset($_GET['Accepted']))
// file_put_contents($object->getPathname(), $doneCode);
echo "</div>";
}
}
doFlush();
}
?></pre>
</body>
</html>
If you want to ask me something about this code, do it. :)
Related
I am new to Vtiger CRM. I want to write php code in log4php.properties file and also it need to be executed.
I can write the code but it is not executing at all. So kindly help me with a way which will allow to execute the file.
Also this need to be executed dynamic with separate domains.
Thanks
Open your index.php file from crm root directory and Add this code
function replace_string_in_a_file($filepath, $search, $replace) {
if (#file_exists($filepath)) {
$file = file($filepath);
foreach ($file as $index => $string) {
if (strpos($string, $search) !== FALSE)
$file[$index] = "$replace\n";
}
$content = implode($file);
return $content;
}else {
return NULL;
}
}
$filepath = $root_directory . 'log4php.properties';
$search = 'log4php.appender.A1.File=';
$replace = 'log4php.appender.A1.File=' . DOMAIN_PATH . '/logs/vtigercrm.log';
$log_properties_content = replace_string_in_a_file($filepath, $search, $replace);
if (!empty($log_properties_content)) {
file_put_contents($filepath, $log_properties_content);
}
here is my code it is a text spinner (synonym)
public function fetchContent($keyword)
{
$customContent = $this->getOption('custom_content_text');
$this->_setHttpStatusCode(200);
if (!$customContent)
{
$this->_setContentStatus(self::CONTENT_STATUS_NO_RESULTS);
return false;
}
if (preg_match_all('/({\*)(.*?)(\*})/', $customContent, $result))
{
if (is_array($result[0]))
{
foreach ($result[0] as $index => $group_string)
{
//replace the first or next pattern match with a replaceable token
$customContent = preg_replace('/(\{\*)(.*?)(\*\})/', '{#'.$index.'#}', $customContent, 1);
$words = explode('|', $result[2][$index]);
//clean and trim all words
$finalPhrase = array();
foreach ($words as $word)
{
if (preg_match('/\S/', $word))
{
$word = preg_replace('/{%keyword%}/i', $keyword, $word);
$finalPhrase[] = trim($word);
}
}
$finalPhrase = $finalPhrase[rand(0, count($finalPhrase) - 1)];
//now inject it back to where the token was
$customContent = str_ireplace('{#' . $index . '#}', $finalPhrase, $customContent);
}
$this->_setContentStatus(self::CONTENT_STATUS_PASSED);
}
}
return $customContent;
}
}
there is regex that request bracket like this
{*spin1|spin2|spin3*}
here is the regex from the snippet above
if (preg_match_all('/({\*)(.*?)(\*})/', $customContent, $result))
$customContent = preg_replace('/(\{\*)(.*?)(\*\})/', '{#'.$index.'#}', $customContent, 1);
i would like to remove the * to format allow just {spin1|spin2|spin3} wich is more compatible with most spinner ,
i tried with some regex that i find online
i tried to remove the * from both regex without result
thanks you very much for your help
Remove \* instead of just * – Lucas Trzesniewski
I am currently trying to parse the keys in a Windows 7 registry containing the MRU lists for Microsoft Office 2013. However when I attempt to run the Perl script in RegRipper it says the plugin was not successfully run. Im not sure if there is a syntax error in my code or if it is unable to parse the registry as I have it written. The biggest problem is that one of the keys is named after the user's LiveId (it appear as LiveId_XXXXXXX) and this changes from user to user so i would like this plugin to work no matter what the user's LiveId is. Thanks!
my $reg = Parse::Win32Registry->new($ntuser);
my $root_key = $reg->get_root_key;
# ::rptMsg("officedocs2013_File_MRU v.".$VERSION); # 20110830 [fpi] - redundant
my $tag = 0;
my $key_path = "Software\\Microsoft\\Office\\15.0";
if (defined($root_key->get_subkey($key_path))) {
$tag = 1;
}
if ($tag) {
::rptMsg("MSOffice version 2013 located.");
my $key_path = "Software\\Microsoft\\Office\\15.0";
my $of_key = $root_key->get_subkey($key_path);
if ($of_key) {
# Attempt to retrieve Word docs
my $word_mru_key_path = 'Software\\Microsoft\\Office\\15.0\\Word\\User MRU';
my $word_mru_key = $of_key->get_subkey($word_mru_key_path);
foreach ($word_mru_key->get_list_of_subkeys())
{
if ($key->as_string() =~ /LiveId_\w+/)
{
$word = join($key->as_string(),'\\File MRU');
::rptMsg($key_path."\\".$word);
::rptMsg("LastWrite Time ".gmtime($word_key->get_timestamp())." (UTC)");
my #vals = $word_key->get_list_of_values();
if (scalar(#vals) > 0) {
my %files
# Retrieve values and load into a hash for sorting
foreach my $v (#vals) {
my $val = $v->get_name();
if ($val eq "Max Display") { next; }
my $data = getWinTS($v->get_data());
my $tag = (split(/Item/,$val))[1];
$files{$tag} = $val.":".$data;
}
# Print sorted content to report file
foreach my $u (sort {$a <=> $b} keys %files) {
my ($val,$data) = split(/:/,$files{$u},2);
::rptMsg(" ".$val." -> ".$data);
}
}
else {
::rptMsg($key_path.$word." has no values.");
}
else {
::rptMsg($key_path.$word." not found.");
}
::rptMsg("");
}
}
The regex
LiveId_(\w+)
will grab the string after LiveId_ and you can reference it with a \1 like this
How can I hide product description when the description is long in Opencart (product page) to reduce the load product page, but after clicking on the detail link then came out a full description.
In image you can see Example, Sorry for my bad english, Thanks!
Here is a link to example image example
Why not just truncate it? It will force it to be the right length for you every time!
Go to catalog/controller/product/category.php and when you see
foreach ($results as $result) {
if ($result['image']) {
$image = $this->model_tool_image->resize($result['image'], $this->config->get('config_image_product_width'), $this->config->get('config_image_product_height'));
} else {
$image = false;
}
Add this next:
function truncate($description, $tLimit="20", $break=" ", $pad="...")
{
if(strlen($string) <= $tlimit) return $string;
if(false !== ($breakpoint = strpos($string, $break, $tlimit))) {
if($breakpoint < strlen($string) - 1) {
$string = substr($string, 0, $breakpoint) . $pad;
}
}
return $description;
}
Feel free to change the variables:
$tLimit is how many letters you want to allow it.
$break is where you want it to cut off, right now it is set to cut off at the next space. You can have it interrupt words if you like by putting $break=""
$pad is what you want it to show after it cuts off the text.
If you really want no description to show at all Then I recommend still doing something similar to the original script.
function getDescriptionLength($description, $tLimit="20")
{
if(strlen($string) <= $tlimit) return $string;
else {
$description = NULL;
}
return $description;
}
I'm really REALLY bad at regular expressions. It just hasn't clicked yet. I'm trying to make small application that extracts all image tags of their src, width, and height attributes. This is what I have so far:
<?php
function print_links ($url)
{
$fp = fopen($url, "r") or die("Could not contact $url");
$page_contents = "";
while ($new_text = fread($fp, 100)) {
$page_contents .= $new_text;
}
$match_result =
preg_match_all( '/<img.*src=[\"\'](.*)[\"\'].*width=(\d+).*height=(\d+).*/>/i',
$page_contents,
$match_array,
PREG_SET_ORDER);
echo "number matched is: $match_result<br><br> ";
print_r($match_array);
foreach ($match_array as $entry) {
$tag = $entry[0];
$src = $entry[1];
$width = $entry[2];
$height = $entry[3];
print (" <b>src</b>: $src;
<b>width</b>: $width<br />
<b>height</b>: $height<br />
<b>tag</b>: $tag<br />"
);
}
}
print_links ("http://www.drudgereport.com/");
?>
but I get this little error:
Warning: preg_match_all(): Unknown modifier '>' in C:\Apache2.2\htdocs\it302\regex\regex.php on line 17 number matched is:
I'm not sure where I went wrong in my regexp. I've tried multiple things but have ended up just as confused.
Any suggestions?
In your regex the last .*/> is wrong.
no / there...
/<img.*src=[\"\'](.*)[\"\'].*width=(\d+).*height=(\d+).*>/i
or \/? escape and make it optional...
/<img.*src=[\"\'](.*)[\"\'].*width=(\d+).*height=(\d+).*\/?>/i
but this regex only works if src width height are in this given order within the img tag and width and height also allow quoted values and units. e.g. width="0.9em" is valid html... this are all reasons why you should not use regex to parse html (and many more...)
Do not use regex for this. Especially if you are REALLY bad :)
http://simplehtmldom.sourceforge.net/
foreach($html->find('img') as $element){
$src = $element->src;
$width = $element->width;
$height = $element->height;
print (" <b>src</b>: $src;
<b>width</b>: $width<br />
<b>height</b>: $height<br />
<b>tag</b>: $tag<br />"
);
}