<?php
if (!defined('MOD')) die("access die");
purviewCheck('str_replace', 'plugin');
if ($_POST['str_replace'] && AJAX) {
	$c = 0;
	$tables = trim($_POST['tables']);
	$f = trim($_POST['f']);
	$search = trim($_POST['search']);
	$replace = trim($_POST['replace']);
	$p = intval($_POST['p']) < 1 ? 1 : intval($_POST['p']);
	$limit = 200;
	$offset = ($p - 1) * $limit;
	if ($_POST['condition']) $condition = " and " . trim($_POST['condition']);
	$keys_field = qdb::fetchAll("show keys from $tables");
	$arr_keys = array();
	foreach($keys_field as $val){
		if($val['Key_name'] == 'PRIMARY'){
			$arr_keys = $val;
		}
	}
	if (!empty($arr_keys)) {
		$key_field = $arr_keys['Column_name'];
		$temp = qdb::fetchAll("select {$key_field} , {$f} from {$tables} where {$f} LIKE '%" . $search . "%'  {$condition} order by {$key_field} asc  limit {$offset}, {$limit}");
		foreach ($temp as $d) {
			$s = str_replace($search, $replace, $d[$f]);
			if($d[$f] != $s){
				$s = addslashes($s);
				$sql = "update {$tables} set {$f}='{$s}' where {$key_field}='{$d[$key_field]}'";
				qdb::Query($sql);
				$c++;
			}
		} 
		$status = array('status'=>200, 'more'=>count($temp), 'success'=>$c);
	} else {
		$status = array('status'=>404);
	} 
	die(qbase::xmlPrint(qbase::jsonencode($status)));
} else if ($_POST['type'] == 'ajax' && AJAX) {
	$tablename = $_POST['tablename'];
	if($tablename){
		$j = 0;
		$name = array();
		$field_result = qdb::fetchAll("show fields from $tablename");
		foreach ($field_result as $s_r) {
			$name[] = $s_r['Field'];
		} 
	}else{
		$name = array();
	}
	die(qbase::xmlPrint(qbase::jsonencode($name)));
} else {
	$l = array();
	$lists = array();
	$r = qdb::fetchAll("SHOW TABLES LIKE '".TABLEPRE."%'");
	foreach ($r as $list) {
		$table = array_shift($list);
		if(has_primary($table)) $lists[] = $table;
	} 
	include qbase::template($path . 'plugin/str_replace');
} 

function has_primary($table){
	$keys_field = qdb::fetchAll("show keys from $table");
	$arr_keys = array();
	foreach($keys_field as $val){
		if($val['Key_name'] == 'PRIMARY'){
			return true;
		}
	}
	return false;
}
?>