PHP not executing the same function a second time - php

I have a function that I call using Config::save('key', $value);
public static function save($params, $value)
{
$parts = explode('.', $params);
$count = count($parts);
$mainFile = PANEL_PATH.'/conf.php';
$mainConfig = include $mainFile;
if($count == 1)
{
if(isset($mainConfig[$parts[0]]))
{
$mainConfig[$parts[0]] = $value;
}
}
elseif($count == 2)
{
if(isset($mainConfig[$parts[0]][$parts[1]]))
{
$mainConfig[$parts[0]][$parts[1]] = $value;
}
}
elseif($count == 3)
{
if(isset($mainConfig[$parts[0]][$parts[1]][$parts[2]]))
{
$mainConfig[$parts[0]][$parts[1]][$parts[2]] = $value;
}
}
elseif($count == 4)
{
if(isset($mainConfig[$parts[0]][$parts[1]][$parts[2]][$parts[3]]))
{
$mainConfig[$parts[0]][$parts[1]][$parts[2]][$parts[3]] = $value;
}
}
ob_start();
echo var_export($mainConfig);
$content = ob_get_contents();
ob_end_clean();
$content = str_replace(" ", "\t", $content);
$content = str_replace("\n\tarray (", "array(", $content);
$content = str_replace("\n\t\tarray (", "array(", $content);
$content = str_replace("\n\t\t\tarray (", "array(", $content);
$mainFileHandler = fopen($mainFile, 'w+');
$mainFileWrite = fwrite($mainFileHandler, "<?php\n\nreturn " . $content . ";");
if($mainFileWrite > 0)
{
return true;
}
else
{
return false;
}
fclose($mainFileHandler);
}
And the conf.php file looks like this:
<?php
return array (
'name' => '<NAME>',
'license' => '<LICENSE>',
'url' => '<URL>',
'usage_id' => '<USAGE_ID>',
'installed' => '<INSTALLED>'
);
So when I do this statement
if (Config::save('usage_id', 'USAGE_ID') && Config::save('license', 'LICENSE'))
{
echo "Reset License";
}
It only resets the license variable, it seems like it skips over the first one. Is there something wrong with the code that's making it act like this?
If anymore code is needed let me know and I'll be glad to provide it.

Related

Function/filter/action to replace product title for woocommerce

I have this function
function my_product_title($title, $id)
{
if(in_the_loop() && is_product())
{
return '<span class="border">FooBar</span>';
}
return $title;
}
add_filter( 'the_title', 'my_product_title', 5, 2);
and it can replace the product title with return '<span class="border">FooBar</span>';.
I also have a custom script in "mycustomtitle.php" that can modify the products titles and my script can echo that modified title as $mycustomtitle
I want to replace the original product title with my $mycustomtitle without changing anything in the core files.
I've tried to just change return '<span class="border">FooBar</span>'; to $mycustomtitle but it only removes the original title and gives no output at all...
Thanks!
UPDATE 2016-10-20 With custom code:
<?php
include $_SERVER['DOCUMENT_ROOT'] . '/wp-content/plugins/seo-controlpanel/seo-engine/explode.php';
$tit1 = $boomprint[array_rand($boomprint)].' '.file_get_contents($_SERVER['DOCUMENT_ROOT'] . '/wp-content/plugins/seo-controlpanel/write-to/product-title-h1.php');
$tit2 = $boomprint[array_rand($boomprint)].' '.file_get_contents($_SERVER['DOCUMENT_ROOT'] . '/wp-content/plugins/seo-controlpanel/write-to/product-title-h1.php');
$title_keys = array($tit1,$tit2);
$title_key11 = $title_keys[array_rand($title_keys)];
if(!function_exists(spin11)){
function spin11($string11) {
while(true) {
if(!preg_match_all('/({([^\{]*?)\})/', $string11, $matches))
break;
foreach($matches[2] as $i => $match) {
$parts = explode('|', $match);
$string11 = str_replace_once11($matches[0][$i], $parts[mt_rand(0, count($parts)-1)], $string11);
}
}
return $string11;
}
}
if(!function_exists(str_replace_once11)){
function str_replace_once11($from,$to,$str)
{
$str = explode($from,$str,2);
return $str[0].$to.$str[1];
}
$title_id11 = get_the_ID();
$fileLocation11 = getenv("DOCUMENT_ROOT") . '/wp-content/plugins/seo-controlpanel/seo-cache/product-title-h1/'.$title_id11.'.txt';
if(!file_exists($fileLocation11)){
$file11 = fopen($fileLocation11,"w");
$content11 = spin11($title_key11);
fwrite($file11,$content11);
fclose($file11);
}
if(file_exists($fileLocation11)){
$myFile11 = $fileLocation11;
$fh11 = fopen($myFile11, 'r');
$theData11 = fread($fh11, filesize($myFile11));
fclose($fh11);
}
}
?>
Insert your custom code in your function.
function my_product_title($title, $id) {
include $_SERVER['DOCUMENT_ROOT'] . '/wp-content/plugins/seo-controlpanel/seo-engine/explode.php';
$tit1 = $boomprint[array_rand($boomprint)].' '.file_get_contents($_SERVER['DOCUMENT_ROOT'] . '/wp-content/plugins/seo-controlpanel/write-to/product-title-h1.php');
$tit2 = $boomprint[array_rand($boomprint)].' '.file_get_contents($_SERVER['DOCUMENT_ROOT'] . '/wp-content/plugins/seo-controlpanel/write-to/product-title-h1.php');
$title_keys = array($tit1,$tit2);
$title_key11 = $title_keys[array_rand($title_keys)];
if(!function_exists(spin11)){
function spin11($string11) {
while(true) {
if(!preg_match_all('/({([^\{]*?)\})/', $string11, $matches))
break;
foreach($matches[2] as $i => $match) {
$parts = explode('|', $match);
$string11 = str_replace_once11($matches[0][$i], $parts[mt_rand(0, count($parts)-1)], $string11);
}
}
return $string11;
}
}
if(!function_exists(str_replace_once11)){
function str_replace_once11($from,$to,$str)
{
$str = explode($from,$str,2);
return $str[0].$to.$str[1];
}
$title_id11 = get_the_ID();
$fileLocation11 = getenv("DOCUMENT_ROOT") . '/wp-content/plugins/seo-controlpanel/seo-cache/product-title-h1/'.$title_id11.'.txt';
if(!file_exists($fileLocation11)){
$file11 = fopen($fileLocation11,"w");
$content11 = spin11($title_key11);
fwrite($file11,$content11);
fclose($file11);
}
if(file_exists($fileLocation11)){
$myFile11 = $fileLocation11;
$fh11 = fopen($myFile11, 'r');
$theData11 = fread($fh11, filesize($myFile11));
fclose($fh11);
}
}
if(in_the_loop() && is_product()) {
return $theData11;
}
return $title;
}
add_filter( 'the_title', 'my_product_title', 5, 2);
Is $mycustomtitle global variable or it is defined inside another function/method/class?
If it is global variable this may help:
function my_product_title($title, $id)
{
global $mycustomtitle;
if(in_the_loop() && is_product())
{
return $mycustomtitle;
}
return $title;
}
<?php
include $_SERVER['DOCUMENT_ROOT'] . '/wp-content/plugins/seo-controlpanel/seo-engine/explode.php';
$tit1 = $boomprint[array_rand($boomprint)].' '.file_get_contents($_SERVER['DOCUMENT_ROOT'] . '/wp-content/plugins/seo-controlpanel/write-to/product-title-h1.php');
$tit2 = $boomprint[array_rand($boomprint)].' '.file_get_contents($_SERVER['DOCUMENT_ROOT'] . '/wp-content/plugins/seo-controlpanel/write-to/product-title-h1.php');
$title_keys = array($tit1,$tit2);
$title_key11 = $title_keys[array_rand($title_keys)];
if(!function_exists(spin11)){
function spin11($string11) {
while(true) {
if(!preg_match_all('/({([^\{]*?)\})/', $string11, $matches))
break;
foreach($matches[2] as $i => $match) {
$parts = explode('|', $match);
$string11 = str_replace_once11($matches[0][$i], $parts[mt_rand(0, count($parts)-1)], $string11);
}
}
return $string11;
}
}
if(!function_exists(str_replace_once11)){
function str_replace_once11($from,$to,$str)
{
$str = explode($from,$str,2);
return $str[0].$to.$str[1];
}
$title_id11 = get_the_ID();
$fileLocation11 = getenv("DOCUMENT_ROOT") . '/wp-content/plugins/seo-controlpanel/seo-cache/product-title-h1/'.$title_id11.'.txt';
if(!file_exists($fileLocation11)){
$file11 = fopen($fileLocation11,"w");
$content11 = spin11($title_key11);
fwrite($file11,$content11);
fclose($file11);
}
if(file_exists($fileLocation11)){
$myFile11 = $fileLocation11;
$fh11 = fopen($myFile11, 'r');
$theData11 = fread($fh11, filesize($myFile11));
fclose($fh11);
}
}
//echo $theData11;
?>

Create recursive function from array in php

I have a situation showed in the PHP code below, and I want to make a recursive function called check_recursive().
I have made the check_recursive() function below, but I want a recursive function, if it is possible.
Thank You!
$menu = '[{"id":"3|case_studies","children":[{"id":"2|case_studies","children":[{"id":"1|custom_links","children":[{"id":"2|faqe"}]}]}]},{"id":"11|klientet","children":[{"id":"8|klientet","children":[{"id":"7|klientet"}]}]},{"id":"9|klientet","children":[{"id":"10|klientet"}]},{"id":"4|klientet"}]';
$old_menu = json_decode($menu, true);
$new_menu = $this->check_recursive($old_menu);
function check_recursive($old_menu)
{
$i = 0;
$new_menu = [];
foreach ($old_menu as $menu_item)
{
if($name = $this->check_menu($menu_item['id']))
{
$new_menu[$i]['id'] = $menu_item['id'] . '|' . $name;
if(isset($menu_item['children']))
{
$e = 0;
foreach ($menu_item['children'] as $menu_item)
{
if($name = $this->check_menu($menu_item['id']))
{
$new_menu[$i]['children'][$e]['id'] = $menu_item['id'] . '|' . $name;
if(isset($menu_item['children']))
{
$y = 0;
foreach ($menu_item['children'] as $menu_item)
{
if($name = $this->check_menu($menu_item['id']))
{
$new_menu[$i]['children'][$e]['children'][$y]['id'] = $menu_item['id'] . '|' . $name;
if(isset($menu_item['children']))
{
$a = 0;
foreach ($menu_item['children'] as $menu_item)
{
if($name = $this->check_menu($menu_item['id']))
{
$new_menu[$i]['children'][$e]['children'][$y]['children'][$a]['id'] = $menu_item['id'] . '|' . $name;
}
$a++;
}
}
}
$y++;
}
}
}
$e++;
}
}
}
$i++;
}
return $new_menu;
}
function check_menu($string){
//Check if string exists in database
if($string){
return 'String exists';
}
return false;
}
I came up with this :
$menu = '[{"id":"3|case_studies","children":[{"id":"2|case_studies","children":[{"id":"1|custom_links","children":[{"id":"2|faqe"}]}]}]},{"id":"11|klientet","children":[{"id":"8|klientet","children":[{"id":"7|klientet"}]}]},{"id":"9|klientet","children":[{"id":"10|klientet"}]},{"id":"4|klientet"}]';
$old_menu = json_decode($menu, true);
$new_menu = check_recursive($old_menu);
function check_recursive($old_menu)
{
$new_menu = array();
foreach ($old_menu as $item) {
$name = check_menu($item['id']);
if($name){
$new_item = array(
'id' => $item['id'] . '|' . $name,
);
if(isset($item['children'])){
$new_item['children'] = check_recursive($item['children']);
}
$new_menu[] = $new_item;
}
}
return $new_menu;
}
function check_menu($string)
{
//Check if string exists in database
if ($string) {
return 'String exists';
}
return false;
}
Let me know if it suits your needs.

Upload csv files to database

HI Guys I have A problem I want to upload csv files and store to database
But doesn't work..
I tried to debug it several times but not working hope you help me guys.
I Have a csv file containing..
firstname lastname middlename gender
test test test male
Then when I upload this csv file doesn't work.
This is my code..
<?php
session_start();
include ("config.php");
$extension = end(explode(".",basename($_FILES['file']['name'])));
if (isset($_FILES['file']) && $_FILES['file']['size'] < 10485760 && $extension== 'csv')
{
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file, "r");
try
{
$connection = new pdo("mysql:host=$hostname;dbname=upload",$username,$password);
if
$upload = $connection->prepare("INSERT INTO tbl_upload(firstname,lastname,middlename,gender)
VALUES (?,?,?,?)");
if($handle !== false)
{
fgets($handle);
while (($data = fgetcsv($handle, 10000, ',') !== false))
{
$upload->execute($data);
}
fclose($handle);
$connection = null;
echo "<p class='bg-success'>Upload Success</p>";
header ("location: index.php");
}
}
catch(pdoExecption $e)
{
die($e->getmessage());
}
}
else
{
header("location:config.php");
}
?>
thanks for the help..
Your method is not viable.
To import CSV you can either use the mysqlimport utility or you have to split the csv records in separate fields to match your INSERT statement. You cannot just feed CSV to the insert statement and hope that it sorts out things for itself.
I can give you a little CsvImport class I wrote some time ago make importing CSV a little bit easier
<?php
final class CsvImport {
private $file = "";
private $fields = array(); //array("field1", "field2", "field3"); ...
private $data = array(); //array([1] => array("value", "value", "value") ...
private $delimiter = "";
private $fieldCount = 0;
private $rowCount = 0;
private $internalCounter = 0;
private $loaded = false;
public function __construct($_file, $_delimiter = "") {
$this->file = $_file;
if(is_file($this->file) == true) {
if(($handle = fopen($this->file, "r")) !== false) {
//If the delimiter is not set try to suggest it
if(strlen($_delimiter) == 0) {
$this->delimiter = $this->suggestDelimiter();
} else {
$this->delimiter = $_delimiter;
}
if(strlen($this->delimiter) > 0) {
$row = 0;
while(($data = fgetcsv($handle, 0, $this->delimiter)) !== false) {
if($row == 0) {
$this->fieldCount = count($data);
}
if($this->fieldCount > 0) {
for($c = 0; $c < $this->fieldCount; $c++) {
if($row == 0) {
$this->fieldCount = count($data);
$this->fields[] = $data[$c];
} else {
$this->data[$row][$this->fields[$c]] = utf8_encode($data[$c]);
}
}
}
$row++;
}
$this->rowCount = $row;
if($this->fieldCount > 0) {
$this->loaded = true;
}
}
}
}
}
public function getNextRow() {
$retVal = false;
if($this->loaded == true) {
if($this->internalCounter < $this->rowCount) {
$this->internalCounter++;
$retVal = true;
} else {
$this->internalCounter = 0;
}
}
return $retVal;
}
public function readField($field) {
$retVal = false;
if($this->isLoaded() == true) {
if(isset($this->data[$this->internalCounter][$field]) == true) {
$retVal = $this->data[$this->internalCounter][$field];
}
}
return $retVal;
}
public function resetInternalCounter() {
$this->internalCounter = 0;
}
public function getFieldCount() {
return $this->fieldCount;
}
public function getRowCount() {
return $this->rowCount;
}
public function getFieldList() {
return $this->fields;
}
public function getDelimiter() {
return $this->delimiter;
}
public function isLoaded() {
return $this->loaded;
}
private function suggestDelimiter() {
$retVal = "";
$file = fopen($this->file, 'r');
$content = fgets($file);
fclose($file);
if(strlen($content) > 0) {
$list = array(
"," => substr_count($content, ","),
"." => substr_count($content, "."),
"&" => substr_count($content, "&"),
"%" => substr_count($content, "%"),
"-" => substr_count($content, "-"),
";" => substr_count($content, ";"),
"'" => substr_count($content, "'"),
"\"" => substr_count($content, "\""),
);
$maxCount = 0;
foreach($list as $key => $value) {
if($value > 0) {
if($value > $maxCount) {
$retVal = $key;
$maxCount = $value;
}
}
}
}
return $retVal;
}
private function __clone() { }
}
?>
The usage is as simple as this:
$file = "/path/to/file.csv";
$import = new CsvImport($file);
if($import->isLoaded() == true) {
while($import->getNextRow()) {
foreach($import->getFieldList() as $fieldName) {
$value = $import->readField($fieldName);
echo $fieldName . " => " . $value . "<br />";
}
}
}
I am sure you can build your queries with all field names in the foreach loop and fire each query in the while loop.

Corrupt .docx files when using a PHP IMAP class

I'm Using this PHP IMAP Class: http://code.google.com/p/php-imap/source/browse/trunk/ImapMailbox.php on a current project. After a few modifications the class is working. However whenever the class downloads .docx files they are always corrupt and have to be recovered by office.
protected function initMailPart(IncomingMail $mail, $partStruct, $partNum) {
$data = $partNum ? $this->imap_fetchbody($this->mbox, $mail->mId, $partNum, FT_UID) : $this->imap_body($this->mbox, $mail->mId, FT_UID);
if($partStruct->encoding == 1) {
$data = $this->imap_utf8($data);
}
elseif($partStruct->encoding == 2) {
$data = $this->imap_binary($data);
}
elseif($partStruct->encoding == 3) {
$data = $this->imap_base64($data);
}
elseif($partStruct->encoding == 4) {
$data = $this->imap_qprint($data);
}
$data = trim($data);
$params = array();
if(!empty($partStruct->parameters)) {
foreach($partStruct->parameters as $param) {
$params[strtolower($param->attribute)] = $param->value;
}
}
if(!empty($partStruct->dparameters)) {
foreach($partStruct->dparameters as $param) {
$params[strtolower($param->attribute)] = $param->value;
}
}
if(!empty($params['charset'])) {
$data = iconv($params['charset'], $this->serverEncoding, $data);
}
// attachments
if($this->attachmentsDir) {
$filename = false;
$attachmentId = $partStruct->ifid ? trim($partStruct->id, " <>") : null;
if(empty($params['filename']) && empty($params['name']) && $attachmentId) {
$filename = $attachmentId . '.' . strtolower($partStruct->subtype);
}
elseif(!empty($params['filename']) || !empty($params['name'])) {
$filename = !empty($params['filename']) ? $params['filename'] : $params['name'];
$filename = $this->decodeMimeStr($filename);
$filename = $this->quoteAttachmentFilename($filename);
}
if($filename) {
if($this->attachmentsDir) {
$filepath = rtrim($this->attachmentsDir, '/\\') . DIRECTORY_SEPARATOR . $filename;
file_put_contents($filepath, $data);
$mail->attachments[$filename] = $filepath;
}
else {
$mail->attachments[$filename] = $filename;
}
if($attachmentId) {
$mail->attachmentsIds[$filename] = $attachmentId;
}
}
}
if($partStruct->type == 0 && $data) {
if(strtolower($partStruct->subtype) == 'plain') {
$mail->textPlain .= $data;
}
else {
$mail->textHtml .= $data;
}
}
elseif($partStruct->type == 2 && $data) {
$mail->textPlain .= trim($data);
}
if(!empty($partStruct->parts)) {
foreach($partStruct->parts as $subpartNum => $subpartStruct) {
$this->initMailPart($mail, $subpartStruct, $partNum . '.' . ($subpartNum + 1));
}
}
}
protected function decodeMimeStr($string, $charset = 'UTF-8') {
$newString = '';
$elements = $this->imap_mime_header_decode($string);
for($i = 0; $i < count($elements); $i++) {
if($elements[$i]->charset == 'default') {
$elements[$i]->charset = 'iso-8859-1';
}
$newString .= iconv($elements[$i]->charset, $charset, $elements[$i]->text);
}
return $newString;
}
Try wading into the binary files with a good editor, both before and after the round-trip from IMAP, to see if there's something obvious. I've had similar problems where whitespace made its way into the PHP script (e.g. at the end of a file after the close ?> tag); most formats won't blink but .docx may get kicked into a recovery if there's whitespace left over at the end.

bad words filter integration

I am trying to integrate php bad words filter
The input is taken through $_REQUEST['qtitle'] and $_REQUEST['question']
But I am failed to do so
$USERID = intval($_SESSION['USERID']);
if ($USERID > 0)
{
$sess_ver = intval($_SESSION[VERIFIED]);
$verify_asker = intval($config['verify_asker']);
if($verify_asker == "1" && $sess_ver == "0")
{
$error = $lang['225'];
$theme = "error.tpl";
}
else
{
$theme = "ask.tpl";
STemplate::assign('qtitle',htmlentities(strip_tags($_REQUEST['qtitle']), ENT_COMPAT, "UTF-8"));
STemplate::assign('question',htmlentities(strip_tags($_REQUEST['question']), ENT_COMPAT, "UTF-8"));
if($_REQUEST['subform'] != "")
{
$qtitle = htmlentities(strip_tags($_REQUEST['qtitle']), ENT_COMPAT, "UTF-8");
$question = htmlentities(strip_tags($_REQUEST['question']), ENT_COMPAT, "UTF-8");
$category = intval($_REQUEST['category']);
if($qtitle == "")
{
$error = $lang['3'];
}
elseif($category <= "0")
{
$error = $lang['4'];
}
else
{
if($config['approve_stories'] == "1")
{
$addtosql = ", active='0'";
}
$query="INSERT INTO posts SET USERID='".mysql_real_escape_string($USERID)."', title='".mysql_real_escape_string($qtitle)."',question='".mysql_real_escape_string($question)."', tags='".mysql_real_escape_string($qtitle)."', category='".mysql_real_escape_string($category)."', time_added='".time()."', date_added='".date("Y-m-d")."' $addtosql";
$result=$conn->execute($query);
$userid = mysql_insert_id();
$message = $lang['5'];
}
}
}
}
else
{
$question = htmlentities(strip_tags($_REQUEST['qtitle']), ENT_COMPAT, "UTF-8");
$redirect = base64_encode($thebaseurl."/ask?qtitle=".$question);
header("Location:$config[baseurl]/login?redirect=$redirect");exit;
}
I am trying the following code but this code replaces every word (which is not included in the array)
FUNCTION BadWordFilter(&$text, $replace){
$bads = ARRAY (
ARRAY("butt","b***"),
ARRAY("poop","p***"),
ARRAY("crap","c***")
);
IF($replace==1) { //we are replacing
$remember = $text;
FOR($i=0;$i<sizeof($bads);$i++) { //go through each bad word
$text = EREGI_REPLACE($bads[$i][0],$bads[$i][1],$text); //replace it
}
IF($remember!=$text) RETURN 1; //if there are any changes, return 1
} ELSE { //we are just checking
FOR($i=0;$i<sizeof($bads);$i++) { //go through each bad word
IF(EREGI($bads[$i][0],$text)) RETURN 1; //if we find any, return 1
}
}
}
$qtitle = BadWordFilter($wordsToFilter,0);
$qtitle = BadWordFilter($wordsToFilter,1);
What I am missing here?
I agree with #Gordon that this is reinventing the wheel, but if you really want to do it, here's a better start:
function badWordFilter(&$text, $replace)
{
$patterns = array(
'/butt/i',
'/poop/i',
'/crap/i'
);
$replaces = array(
'b***',
'p***',
'c***'
);
$count = 0;
if($replace){
$text = preg_replace($patterns, $replaces, $text, -1, $count);
} else {
foreach($patterns as $pattern){
$count = preg_match($pattern, $text);
if($count > 0){
break;
}
}
}
return $count;
}
There are lots of inherent issues, though. For instance, run the filter on the text How do you like my buttons? ... You'll end up with How do you like my b***ons?
I think you should use this kind of function :
function badWordsFilter(&$text){
$excluded_words = array( 'butt', 'poop', 'crap' );
$replacements = array();
$i = count($excluded_words);
while($i--){
$tmp = $excluded_words{0};
for($i=0;$i<(strlen($excluded_words)-1);$i++){
$tmp .= '*';
}
$replacements[] = $tmp;
}
str_replace($excluded_words, $replacements, $text);
}

Categories