<?php
$supported_scripts = array('wordpress', 'joomla');
function set_script_template($script, $template_name, $details) {
if (empty($script)) err(__FUNCTION__ . '() empty script parameter');
if (empty($template_name)) err(__FUNCTION__ . '() empty template_name parameter');
if (empty($details)) err(__FUNCTION__ . '() empty details parameter');
script_supported($script);
$db = get_ei_db($details, $script);
switch(strtolower($script)) {
case "joomla":
$queries = array(
"UPDATE `" . $details['prefix'] . "template_styles` SET home = 0",
"UPDATE `" . $details['prefix'] . "template_styles` SET home = 1 WHERE template = '{$template_name}'",
);
break;
case "wordpress":
$queries = array(
"UPDATE `" . $details['prefix'] . "options` SET `option_value` = '{$template_name}' WHERE `option_name` IN ('template', 'stylesheet')",
"DELETE FROM " . $details['prefix'] . "options WHERE option_name = 'current_theme'",
"INSERT INTO `" . $details['prefix'] . "options` (`option_name`,`option_value`,`autoload`) VALUES ('current_theme','{$template_name}','yes')",
);
break;
}
if (!$db->doTransactions($queries))
err($db->getLastError());
return true;
}
function script_config_file($script, $path) {
script_supported($script);
if (empty($path))
err(__FUNCTION__ . '() Missing path parameter.');
switch(strtolower($script)) {
case "wordpress":
$config_file = $path . 'wp-config.php';
break;
case "joomla":
$config_file = $path . 'configuration.php';
break;
}
return $config_file;
}
function script_supported($script) {
$debug = debug_backtrace();
if (empty($script)) err($debug['1'] . '() empty script parameter');
if (!in_array($script, $GLOBALS['supported_scripts']))
err($debug['1'] . '() script ' . $script . ' not supported.');
}
function set_script_password($script, $password, $details) {
if (empty($password)) err(__FUNCTION__ . '() empty password parameter');
if (empty($script)) err(__FUNCTION__ . '() empty script parameter');
script_supported($script);
$db = get_ei_db($details, $script);
switch(strtolower($script)) {
case "joomla":
$q = "UPDATE {$details['prefix']}users SET password = md5('" . $db->escape($password) . "') WHERE id = (SELECT MIN(user_id) FROM {$details['prefix']}user_usergroup_map WHERE group_id = 8)";
break;
case "wordpress":
$q = "UPDATE {$details['prefix']}users SET user_pass = md5('" . $db->escape($password) . "') WHERE ID = (SELECT MIN(user_id) FROM {$details['prefix']}usermeta WHERE meta_key = 'wp_capabilities' AND meta_value like '%s:13:\"administrator\"%')";
break;
}
if (!$db->query($q))
err($db->getLastError());
return true;
}
function get_script_config($script, $file) {
if (!file_exists($file))
err('Missing config file ' . $file);
if (!$data = file_get_contents($file))
err('Empty config file ' . $file);
script_supported($script);
$details = array('prefix' => '');
switch(strtolower($script)) {
case "joomla":
foreach(explode("\n", $data) as $line) {
if (preg_match('/public\s\$(host|user|password|db|dbprefix)((\s+)?)\=((\s+)?)(\'|")(.*)(\'|")/i', $line, $matches) && !empty($matches['1']) && !empty($matches['7'])) {
if (strtolower($matches['1']) == 'dbprefix')
$details['prefix'] = $matches['7'];
else
$details[strtolower($matches['1'])] = $matches['7'];
}
}
foreach(array('host', 'user', 'password', 'db') as $k)
if (empty($details[$k]))
err('[' . $script . '] ' . $k . ' could not be found');
break;
case "wordpress":
foreach(explode("\n", $data) as $line) {
// db settings
if (preg_match('/define\((\'|")DB_(name|user|password|host)(\'|"),(\s)?(\'|")(.*)(\'|")\);/i', $line, $matches) && !empty($matches['2']) && !empty($matches['6']))
$details[strtolower($matches['2'])] = $matches['6'];
elseif (preg_match('/^\$table_prefix((\s)+)?\=((\s)+)?(\'|")(.*)(\'|")\;$/i', $line, $matches) && !empty($matches['6']))
$details['prefix'] = $matches['6'];
}
foreach(array('host', 'user', 'password', 'name') as $k)
if (empty($details[$k]))
err('[' . $script . '] ' . $k . ' could not be found');
break;
}
return $details;
}
function get_ei_db($details, $script) {
script_supported($script);
switch(strtolower($script)) {
case "joomla":
foreach(array('host', 'user', 'password', 'db') as $k)
if (empty($details[$k]))
err('missing_db_' . $k);
return new SQL($details['host'], $details['user'], $details['password'], $details['db']);
break;
case "wordpress":
foreach(array('host', 'user', 'password', 'name') as $k)
if (empty($details[$k]))
err('missing_db_' . $k);
return new SQL($details['host'], $details['user'], $details['password'], $details['name']);
break;
}
if (!$db)
err($db->error);
return $db;
}
function pr($a) { echo print_r($a, true) . PHP_EOL; }
function err($msg, $code = 0) {
echo "\nERROR: " . $msg . "\n\n";
exit;
throw new Exception($msg, $code);
}
// SQL part
class sql {
private $conn = null;
function __construct($host, $user, $pass, $dbname, $debug = false, $persistent = false) {
// mysqli reconnect
ini_set('mysqli.reconnect', 1);
if ($persistent)
$host = 'p:' . $host;
$this->conn = new mysqli($host, $user, $pass, $dbname);
if ($this->conn != null)
$this->conn->query("SET NAMES utf8");
else {
err(mysqli_error($this->conn));
die("Unable to connect to database. \n " . mysqli_error($this->conn));
}
}
function __destruct() {
$this->conn->close();
}
function buildWhere($params) {
$where = array();
foreach($params as $k => $v) {
if (!is_string($v) && !is_numeric($v))
continue;
if (preg_match('/^@/', $k)) {
if (preg_match('/^@(OR|LIKE|ILIKE)@(.*)/i', $k, $matches)) {
pr($matches);
exit;
$where[] = array(
'condition' => preg_replace('/^@(.*)@/', '', $k) . " = " . $v,
'condition_key' => $matches[1],
);
} else {
$where[] = array(
'condition' => preg_replace('/^@/', '', $k) . " = " . $v,
);
}
} else {
$where[] = array(
'condition' => $k . " = '" . self::escape($v) . "'",
);
}
}
if (empty($where))
return '';
$return = '';
foreach($where as $k => $v)
$return .= $v['condition'] . (!empty($where[$k+1]) ? (empty($v['condition_key']) ? ' AND ' : $v['condition']) : '');
return ' WHERE ' . $return;
}
public function insert($table, $params, $return_query = false) {
if (empty($table) || empty($params) || !is_array($params))
return false;
$keys = $values = array();
foreach($params as $k => $v) {
if ($k == 'key') $k = '`' . $k . '`';
$keys[] = self::escape(preg_replace('/^@/', '', $k));
$values[] = preg_match('/^@/', $k) ? $v : "'" . self::escape($v) . "'";
}
$q = "INSERT INTO {$table}(" . implode(', ', $keys) . ") VALUES(" . implode(', ', $values) . ")";
if ($return_query)
return $q;
return self::query($q);
}
function update($table, $_set = array(), $_where = array(), $return_query = false) {
$where_keys = array_keys($_where);
$set_keys = array_keys($_set);
if (empty($table) || empty($_set) || empty($set_keys) || empty($_where) || empty($where_keys))
return false;
$table = $this->escape($table);
$set = array();
foreach($_set as $k => $v) {
$k = $this->escape($k);
$v = $this->escape($v);
if ($k == 'key') $k = '`' . $k . '`';
$set[] = "{$k} = " . (is_numeric($v) ? $v : "'" . $v . "'");
}
$where = array();
foreach($_where as $k => $v) {
$k = $this->escape($k);
$v = $this->escape($v);
if ($k == 'key') $k = '`' . $k . '`';
$where[] = "{$k} = " . (is_numeric($v) ? $v : "'" . $v . "'");
}
if (empty($set) || empty($where)) return false;
$q = "UPDATE {$table} SET " . implode(', ', $set) . ' WHERE ' . implode(' AND ', $where);
if ($return_query)
return $q;
if (!$this->query($q))
err($this->getLastError());
return true;
}
public function query($query) {
if (!$this->conn) {
$this->conn = new mysqli($this->db_host, $this->db_user, $this->db_pass, $this->db_name);
if ($this->conn != null)
$this->conn->query("SET NAMES utf8");
else {
die("Unable to connect to database. \n " . mysqli_connect_error($this->conn) . " | " . mysqli_error($this->conn) . "\n<br />");
}
}
$this->error = '';
if ($result = $this->conn->query($query)) {
if (preg_match('/^insert\ into/i', $query))
return !empty($this->conn->insert_id) ? $this->conn->insert_id : true;
if (preg_match('/^update\ /i', $query))
return (!empty($this->conn->affected_rows) ? $this->conn->affected_rows : true);
return $result;
}
$this->error = $this->getLastError();
return false;
}
public function count($q) {
$q = preg_replace("/SELECT(.*)FROM/i", "SELECT count(*) as count FROM", str_replace("\n", '', str_replace("\t", ' ', $q)));
return self::fetch_val($q, 'count');
}
public function fetch_array($query) {
$out = array();
if ($res = self::query($query)) {
while($row = $res->fetch_array(MYSQLI_ASSOC)) {
$out[] = $row;
}
return $out;
}
self::debug($query);
return false;
}
public function fetch_row($query) {
if ($res = self::fetch_array($query)) {
return current($res);
}
self::debug($query);
return false;
}
public function fetch_val($query, $key) {
if ($res = self::fetch_row($query)) {
if (isset($res[$key]))
return $res[$key];
}
self::debug($query);
return false;
}
public function escape($string) {
if (is_array($string) || is_object($string)) {
$return = array();
foreach($string as $k => $v) {
if (is_array($string))
$return[$k] = $this->escape($v);
elseif (is_object($string))
$return->{$k} = $this->escape($v);
}
return $return;
} else {
return $this->conn->real_escape_string(trim($string));
}
}
public function getLastError() {
return mysqli_error($this->conn);
}
public function debug($query) {
if ($this->debug) {
if ($err = mysqli_connect_error($this->conn))
die("Connection failed: <br />\n" . $err . "<br />");
if ($err = mysqli_error($this->conn))
pr("Query failed: $query<br />\n" . $err . "<br />");
}
}
public function doTransactions($queries) {
$this->query('BEGIN;');
foreach($queries as $q) {
if (!$this->query($q)) {
$this->query('ROLLBACK');
return false;
}
}
$this->query('COMMIT');
return true;
}
}