Чтение RSS каналов

Форум

Открыть Ответить

Установка кода биржи статей liex.ru

0

0
1
13.04.2009 14:07:34
Кто нибудь знает как установить на Slaed код биржи Liex?
2
13.04.2009 17:11:5213.04.2009 21:06:01
Приведи тут сам код.
4

4
3
14.04.2009 09:18:10
Клиентский код:

<?php

/**
* @author Eugen Malov
* @copyright 2007
*/

/////////////// config

$cms = ''; // valid values are: Joomla, WordPress, DLE

if($cms == '') {
$cms = autoDetectCms();
if($cms == null) {
echo 'Cannot detect CMS type, please assign $cms variable in cms_importer.php';
return;
}
}

/////////////// code

ini_set('display_errors', '1');
error_reporting(E_NOTICE);

$ip_checker_url = "http://server.liex.ru/isvalidip/";
$valid_ip_addr = array('85.17.208.112');
$url_template = $_SERVER['HTTP_HOST'] . "/?q={num}";

$cms = autoDetectCms();


ProcessHttpRequest();

//ф-я обрабатывает запрос
function ProcessHttpRequest()
{
global $cms;
$secret_key = "skey";

if(!check_valid_ip()) {
$_REQUEST["action"] = 'test';
print "bad ip<br>\n";
}

if (!isset($_REQUEST["action"]))
{
print "Не задано действие. ";
return false;
}

$action = $_REQUEST["action"];
// if ($action = 'article_add')
// $action = 'article_update';

switch ($action):

case 'initialize':

if(isset($_POST['code']) && $_POST['code']!="cms") {
print 'wrong script (upload vs. sms_importer)';
break;
}

//запишем статью
$data["title"] = "test_title";
$data["text"] = "test_text";
$data["lat"] = "alt_text";
$r = UpdateCMS($cms, 'update', 0, $data);
if (substr($r, 0, 2) != "OK")
{
print $r;
UpdateCMS($cms, 'delete', 0);
break;
}
//отредактируем
$data["title"] = "test_title_edit";
$data["text"] = "test_text_edit";
$r = UpdateCMS($cms, 'update', 0, $data);
if (substr($r, 0, 2) != "OK")
{
print $r;
UpdateCMS($cms, 'delete', 0);
break;
}
//удалим
$r = UpdateCMS($cms, 'delete', 0);
if ($r != "OK")
{
print $r;
break;
}
print "OK";
break;

case 'test':
$rez = UpdateCMS($cms, 'test');
print "DB test: " . $rez;
if($rez=='ok') {
$my_ids = UpdateCMS($cms, 'all_ids');
if(is_array($my_ids)) print "<br>Articles found: " . count($my_ids);
} else {
print ' (' . mysql_error() . ')';
}
break;

case 'script_update':
$params = array("data");
foreach ($params as $v)
if (!isset($_REQUEST[$v]))
{
print "Не задан " . $v . ".";
return false;
}

$data = $_REQUEST["data"];
$crc = md5($action . $data . $secret_key);

$cur_md5 = md5($action . file_get_contents('cms_importer.php') . $secret_key);
//если текущее значение не сопадает - обновим
if ($cur_md5 != $crc)
{
if (file_exists('cms_importer.php'))
if (!unlink('cms_importer.php'))
{
print "Не могу удалить прошлый скрипт.";
}
if (file_put_contents('cms_importer.php', $data))
print "OK";
else
{
print "Не могу записать в файл.";
}
}
break;

case 'article_update':


$params = array("id", "text", "title");
foreach ($params as $v)
if (!isset($_REQUEST[$v]))
{
print "Не задан " . $v . ".";
return false;
}


$id = $_REQUEST["id"];
$text = $_REQUEST["text"];
$title = $_REQUEST["title"];
$lat = $_REQUEST["lat"];
$crc = md5($action . $id . $title . $text . $secret_key);

$data["text"] = $text;
$data["title"] = $title;
$data["lat"] = $lat;
print UpdateCMS($cms, 'update', $id, $data);

break;

case 'pause':
case 'unpause':

$params = array("id");
foreach ($params as $v)
if (!isset($_REQUEST[$v]))
{
print "Не задан " . $v . ".";
return false;
}


$id = $_REQUEST["id"];

$data["id"] = $id;
print UpdateCMS($cms, $action, $id, $data);

break;


case 'article_delete':

$params = array("id");
foreach ($params as $v)
if (!isset($_REQUEST[$v]))
{
print "Не задан " . $v . ".";
return false;
}
$id = $_REQUEST["id"];
$crc = md5($action . $id . $secret_key);
print UpdateCMS($cms, 'delete', $id);

break;

case 'extra_delete':

$params = array("all");
foreach ($params as $v)
if (!isset($_REQUEST[$v]))
{
print "Не задан " . $v . ".";
return false;
}
$all = $_REQUEST["all"];

$a = explode(",", $all);
for($i=0;$i<count($a);$i++) {
$srv_urls[$a[$i]] = 1;
}

$my_ids = UpdateCMS($cms, 'all_ids');

for($i=0;$i<count($my_ids);$i++) {
if(!$srv_urls[$my_ids[$i]] || !UpdateCMS($cms, 'check', $my_ids[$i])) {
UpdateCMS($cms, 'delete', $my_ids[$i]);
}
}

print "ok";
break;

default:
echo "Ошибка: Неизвестный тип запроса: " . $action;

endswitch;





}

//функция разбивает статью на заголовок и данные
function ParseArticle(&$data)
{

/*
//извлечем из хтмл колда данные
preg_match('|<title>(.*)</title>|Uis', $data, $out);
preg_match('|<body>(.*)</body>|Uis', $data, $out2);
if (isset($out[1]))
$r["title"] = addslashes($out[1]);
else
$r["title"] = "no data!";
if (isset($out[2]))
$r["text"] = addslashes($out2[1]);
else
$r["text"] = "no data!";
return $r;
*/
return $data;
}

//возвращзает id записи в таблице
//$id - глобальный ид статьи
function GetTableId($id)
{
//если нету создать таблицу
$t = getLinkerTable();
if (!CheckTableExist($t))
{
$sql = "CREATE TABLE `" . $t . "` (
`id` int(11) NOT NULL auto_increment,
`global_id` int(11) default NULL,
`table_id` int(11) default NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=cp1251";
Execute($sql);
if (!CheckTableExist($t))
{
die('Cannot create liex relationship table.');
}
}
//таблица которая содержит отображения ID реальных статей - на id их отображении в таблице КМС


$sql = "select table_id from {$t} where global_id={$id}";
$r = Execute($sql);
if ($r->RecordCount() <= 0)
{
return null;
}

$i = $r->FetchRow();
return $i["table_id"];
}

function GetAllIds() {
$t = getLinkerTable();
$sql = "select global_id from {$t} ";
GetTableId(0);

$r = Execute($sql);

$a = array();

for($i=0;$i<$r->RecordCount();$i++) {
$v = $r->FetchRow();
array_push($a, $v['global_id']);
}

return $a;
}

//устанавливает привязку того id что присвоен в таблице кмс с глобальным id
function SetIdLink($gid, $cms_id)
{

$sql = "insert into " . getLinkerTable() . " (global_id,table_id) values ({$gid},{$cms_id})";
if (Execute($sql) == false)
{
return false;
}
return true;
}


function UpdateCMS($cms, $action, $id = null, $data = null)
{


//распарсим входные парамтеры и соберем их в один объект


$r = array();
if ($action == "update")
{
$d = ParseArticle($data);
$r["title"] = $d["title"];
$r["text"] = $d["text"];
$r["lat"] = $d["lat"];
}
$r["id"] = $id;
$r["action"] = $action;
//print_r($r);
switch ($cms):
case "WordPress":
if(file_exists('WordPress.php')) {
include_once 'WordPress.php';
return WordPressImporter($r);
} else print "file WordPress.php not found";
break;

case "DLE":
if(file_exists('DLE.php')) {
include_once 'DLE.php';
return DleImporter($r);
} else print "file DLE.php not found";
break;

case "Joomla":
if(file_exists('Joomla.php')) {
include_once 'Joomla.php';
return JoomlaImporter($r);
} else print "file Joomla.php not found";
break;

default:

endswitch;

}



//НЕБОЛЬШАЯ ПРОСЛОЕЧКА К БАЗЕ

/**
* Execute SQL query
*
* @param string $sql - SQL query
* @return object Recordset
*/
$link = null;
function connect($dbhost, $user, $pwd)
{
return mysql_connect($dbhost, $user, $pwd);

}
function disconnect()
{
mysql_close(link);
}

function select($bd)
{
mysql_select_db($bd) or die('Can\'t use : ' . mysql_error());
}



function Execute($sql)
{
// print $sql;print "<br>";
// $res = mysql_query($sql, $this->conn);
$res = mysql_query($sql);
if (false === $res)
{
return false;
}
//print_r($res);
$r = new recordset($res, $sql);
return $r;
}

function get_last_id()
{
return mysql_insert_id();
}

/** EugenMalov
* функция проверяет есть ли таблицы в бд
* @param string $table - таблица для проверки
* @return boolean
*/

function CheckTableExist($table)
{
$sql = "select * from {$table}";
//print $sql;
//print "<br>";
mysql_query($sql);
if (mysql_error() != "")
{
//print 'faild';
return false;
}
else
{
//print 'succs';
return true;
}

}

class recordset
{
/**
* Recordset resource.
*
* @var resource
*/
var $recordset;

/**
* SQL query
*
* @var string
*/
var $sql;

/**
* Constructor.
*
* @param resource $recordset
* @return recordset object
*/
function recordset($recordset, $sql)
{
$this->recordset = $recordset;
$this->sql = $sql;
}

/**
* Returns amount of lines in result.
*
* @return integer
*/
function RecordCount()
{
return mysql_num_rows($this->recordset);
}

/**
* Returns the current row
* @return array
*/
function FetchRow()
{
return mysql_fetch_array($this->recordset, MYSQL_ASSOC);
}

//-----------Вспомогательная функция генерации кода

}

function getip()
{
if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"),"unknown"))
$ip = getenv("HTTP_CLIENT_IP");

elseif (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
$ip = getenv("HTTP_X_FORWARDED_FOR");

elseif (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
$ip = getenv("REMOTE_ADDR");

elseif (!empty($_SERVER['REMOTE_ADDR']) && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
$ip = $_SERVER['REMOTE_ADDR'];

elseif (!empty($_SERVER['HTTP_X_REAL_IP']) && strcasecmp($_SERVER['HTTP_X_REAL_IP'], "unknown"))
$ip = $_SERVER['HTTP_X_REAL_IP'];

else
$ip = "unknown";
$n = strpos($ip, ",");
if($n) $ip = substr($ip, 0, $n);

return($ip);
}

function check_valid_ip() {
global $ip_checker_url, $valid_ip_addr;
$ip = getip();

$fh = fopen($ip_checker_url . $ip, "r");
if ($fh) {
$r = fgets($fh);
fclose($fh);
return $r=='true';
}

foreach($valid_ip_addr as $a) {
if($a==$ip) return true;
}
return false;
}


function buildCmsData($cms) {

if($cms=='DLE') {
$dle = array();
$dle['config'] = 'engine/data/dbconfig.php';
$dle['db_host'] = 'DBHOST';
$dle['db_name'] = 'DBNAME';
$dle['db_user'] = 'DBUSER';
$dle['db_pass'] = 'DBPASS';
$dle['db_prefix'] = 'PREFIX';
return $dle;
}

if($cms=='WordPress') {
$wp = array();
$wp['config'] = 'wp-config.php';
$wp['db_host'] = 'DB_HOST';
$wp['db_name'] = 'DB_NAME';
$wp['db_user'] = 'DB_USER';
$wp['db_pass'] = 'DB_PASSWORD';
$wp['db_prefix'] = 'table_prefix';
return $wp;
}

if($cms=='JoomlaOld') {
$j = array();
$j['config'] = 'configuration.php';
$j['db_host'] = 'mosConfig_host';
$j['db_name'] = 'mosConfig_db';
$j['db_user'] = 'mosConfig_user';
$j['db_pass'] = 'mosConfig_password';
$j['db_prefix'] = 'mosConfig_dbprefix';
return $j;
}

if($cms=='Joomla') {
$j = array();
$j['config'] = 'configuration.php';
$j['db_host'] = '\$host';
$j['db_name'] = '\$db';
$j['db_user'] = '\$user';
$j['db_pass'] = '\$password';
$j['db_prefix'] = '\$dbprefix';
return $j;
}


return null;
}


function ConnectBD($cdata)
{

if (connect($cdata["DB_HOST"], $cdata["DB_USER"], $cdata["DB_PASSWORD"]) == false)
{
return false;
}
select($cdata["DB_NAME"]);

global $bd_prefix;
$bd_prefix = $cdata["table_prefix"];

return true;
}

function CheckAndConnect()
{
global $cms;
// look it up in the local config file
$cf = 'config.php';
if (file_exists($cf))
{
//попробуем извлечь параметры из нашего файла буффера
$data = ExtractConfigParameters($cf, buildCmsData('WordPress'));
if ($data != null)
{
if (ConnectBD($data)) return true;
}
}
// bad luck with config, search the server

$data = SearchAndGetParameters($cms);

if ($data != null)
{
if (ConnectBD($data)) return true;
}

echo "Cannot connect to database. Set params in config.php";
return false;
}

function SearchAndGetParameters($cms, $load = true)
{
$cms_data = buildCmsData($cms);
if($cms_data==null) return null;

$config_file = FindConfig($cms_data['config']);
if ($config_file)
{
$data = $load ? ExtractConfigParameters($config_file, $cms_data) : $config_file;
return $data;
}
else
{
return null;
}
}

function ExtractConfigParameters($config_file, $cms_data)
{
$data = array();
$str = file_get_contents($config_file);
$str = str_replace('"', "'", $str);

if(strpos($str, "mosConfig")) $cms_data = buildCmsData("JoomlaOld");

$pattern = "/'?" . $cms_data['db_name'] . "'?\s*[,=]\s*'(.*)'.*;/";
preg_match($pattern, $str, $matches);

if (!isset($matches[1]))
{
return null;
}

$data["DB_NAME"] = $matches[1];
$pattern = "/'?" . $cms_data['db_user'] . "'?\s*[,=]\s*'(.*)'.*;/";
preg_match($pattern, $str, $matches);

if (!isset($matches[1]))
{
return null;
}
$data["DB_USER"] = $matches[1];

$pattern = "/'?" . $cms_data['db_pass'] . "'?\s*[,=]\s*'(.*)'.*;/";
preg_match($pattern, $str, $matches);

if (!isset($matches[1]))
{
return null;
}
$data["DB_PASSWORD"] = $matches[1];

$pattern = "/'?" . $cms_data['db_host'] . "'?\s*[,=]\s*'(.*)'.*;/";
preg_match($pattern, $str, $matches);

if (!isset($matches[1]))
{
return null;
}
$data["DB_HOST"] = $matches[1];

$pattern = "/'?" . $cms_data['db_prefix'] . "'?\s*[,=]\s*'(.*)'.*;/";
preg_match($pattern, $str, $matches);

if (!isset($matches[1]))
{
return null;
}
$data["table_prefix"] = $matches[1];

return $data;
}

function FindConfig($f) {
$f = "./" . $f;
for($i=0;$i<2;$i++) {
if(file_exists($f)) return $f;
$f = "../" . $f;
}
return null;
}

function autoDetectCms() {
$a = array("WordPress", "DLE", "Joomla");
foreach($a as $cms) {
$rez[$cms] = SearchAndGetParameters($cms, false);
}
$loop = true;
while($loop) {
$loop = false;
foreach($a as $cms) {
if($rez[$cms]==null) continue;
if(substr($rez[$cms],0,3)=="../") $rez[$cms] = substr($rez[$cms], 3);
else return $cms;
$loop = true;
}
}
return null;
}


?>

И код модуля для CMS DLE:

<?php

/**
* @author Eugen Malov
* @copyright 2007
*/

global $bd_prefix;
global $connect;
global $url_template;
global $cat_id;
global $cat_name;
global $index_publish;
global $pml;

$url_template = "/index.php?newsid={num}";
//$url_template = "/{date}/{num}.html";
//$url_template = "/liex/{num}-{postname}.html";
//$url_template = "/{date}/{postname}.html";
//$url_template = "/main/{num}-{postname}.html";

////// признак вывода на главную страницу: 0 - не выводить, 1 - выводить
$index_publish = 0;

// id категории, куда будут добавляться статьи
// значение id можно взять из таблицы категорий на странице /admin.php?mod=categories
$cat_id = 1;


// длина текста для краткого текста новости
$short_len = 300;

// 1 = попытаться автоматически определить вид ЧПУ (url_template)
// 0 = не пытаться, использовать настройки пользователя url_template
$pml = 1;


////////////////////////////
// code below

$connect = CheckAndConnect();

if($connect) mysql_query("SET NAMES cp1251");

if($pml) {
$fc = FindConfig("engine/data/config.php");

if ($fc) {
include($fc);
if($config['allow_alt_url']=='no') {
$pml = "/index.php?newsid=%post_id%";
} else {
if(!isset($config['seo_type'])) $config['seo_type'] = '2';
if($config['seo_type']=='1') $pml = "/%post_id%-%postname%.html";
if($config['seo_type']=='2') {
$cat_tab = $bd_prefix . "_category";
$rd = Execute("SELECT alt_name FROM {$cat_tab} WHERE id = '{$cat_id}'");
if ($rd->RecordCount() > 0) {
$row = $rd->FetchRow();
$cat_name = $row['alt_name'];
$pml = "/%category%/%post_id%-%postname%.html";
} else $pml = '';
}
if($config['seo_type']=='0') $pml = "/%year%/%monthnum%/%day%/%postname%.html";
}
} else $pml = '';
}

//echo 'pml=' . $pml;

if(!isset($url_template)) $url_template = "/index.php?newsid={num}";

function getLinkerTable() {
global $bd_prefix;
return $bd_prefix . "_liex_id_linker";
}

function split_text($text) {
global $short_len;
$a = array();
if($short_len > 2*strlen($text)/3) {
$a[0] = '';
$a[1] = $text;
} else {
$spl = split('\. ', $text);
$r = '';
for($i=0;$i<count($spl);$i++) {
$r .= $spl[$i] . ". ";
if(strlen($r) > $short_len) break;
}
if(strlen($r) >= strlen($text)) {
$a[0] = '';
$a[1] = $text;
} else {
$a[0] = $r;
$a[1] = $text;
}
}
return $a;
}

//функция отвеающая за импорт в DLE
function DleImporter($data)
{
global $bd_prefix, $pml;
global $connect, $url_template, $cat_id, $cat_name, $index_publish;
if (!$connect) return "db connection error";

$t = $bd_prefix . "_post";


if ($data["action"] == "update")
{
$text = $data["text"];
$title = $data["title"];
$post_name = $data["lat"];

$text = str_replace("'", "\'", $text);
$title = str_replace("'", "\'", $title);

$tid = GetTableId($data["id"]);

list($tshort, $tfull) = split_text($text);

if ($tid == null)
{

$sql = "INSERT INTO {$t} (title,alt_name,short_story,full_story,date,approve,autor,allow_main, category) VALUES ('{$title}','{$post_name}','{$tshort}','{$tfull}',now(),1,'', {$index_publish}, {$cat_id})";
//print $sql;
if (Execute($sql) == false)
{
return "Error creating article: " . mysql_error();
}

$cms_id = get_last_id();
if(SetIdLink($data["id"], $cms_id)==false) {
return "Error setting liex relation: " . mysql_error();
}
$tid = $cms_id;
}
else
{

$sql = "update {$t} set title='{$title}', short_story='{$tshort}', full_story='{$tfull}', alt_name='{$post_name}', allow_main='{$index_publish}', category='{$cat_id}' where id={$tid}";
//print $sql;
if (Execute($sql) == false)
{
return "Error updating data: " . mysql_error();
}

}
$r = Execute("SELECT date FROM {$t} WHERE id = {$tid} ");
if ($r->RecordCount()>0){
$row = $r->FetchRow();
$d = $row['date'];

if($pml) {
$d = strtotime($d);

$pml = str_replace("%year%", date('Y', $d), $pml);
$pml = str_replace("%monthnum%", date('m', $d), $pml);
$pml = str_replace("%day%", date('d', $d), $pml);
$pml = str_replace("%hour%", date('G', $d), $pml);
$pml = str_replace("%minute%", date('i', $d), $pml);
$pml = str_replace("%second%", date('s', $d), $pml);
$pml = str_replace("%postname%", $post_name, $pml);
$pml = str_replace("%post_id%", $tid, $pml);
$pml = str_replace("%author%", '', $pml);
$pml = str_replace("%category%", $cat_name, $pml);

$url = $pml;
} else {
$url = $url_template;
$url = str_replace("{date}", str_replace("-","/", substr($row['date'],0,10)), $url);
$url = str_replace("{num}", $tid, $url);
$url = str_replace("{postname}", $post_name, $url);
}
return "OK " . $_SERVER['HTTP_HOST'] . $url;
} else {
return "Error: " . mysql_error();
}
}

if ($data["action"] == "pause" || $data["action"] == "unpause")
{

$tid = GetTableId($data["id"]);
if($tid == null) return "not found";

$val = $data["action"] == "pause"?0:1;
$sql = "UPDATE {$t} set approve = $val where id={$tid}";
//print $sql;
if (Execute($sql) == false)
{
return "Error pausing or activating article";
}

return "OK";
}

if ($data["action"] == "delete")
{
$tid = GetTableId($data["id"]);
$sql = "DELETE FROM {$t} where id={$tid}";
if(Execute($sql)==false) {
return "Error deleting relation";
}
$sql = "DELETE FROM " . getLinkerTable() . " where table_id={$tid}";
if(Execute($sql)==false) {
return "Error deleting liex relation";
}

return 'OK';
}

if ($data["action"] == "all_ids")
{
return GetAllIds();
}

if ($data["action"] == "test")
{
$sql = "select title,alt_name,short_story,full_story,date,approve,autor,allow_main, category from {$t} where id = 777";
if (Execute($sql) == false) {
return 'failed';
}
return 'ok';
}

if ($data["action"] == "check")
{

$tid = GetTableId($data["id"]);

//если связки нету знаичт и нечего удалять - а значит все ок
if ($tid == null) return 0;

$r = Execute("SELECT * FROM {$t} where id={$tid}");
if ($r == false)
{
return 0;
}

return $r->RecordCount()>0;
}


return "Unknown action for DLE importer: " . $data["action"];
}
?>
4
14.04.2009 09:26:56
В виде модуля это будет так:

<?
if (!defined('MODULE_FILE')) {
Header("Location: ../../index.php");
exit;
}
$module_name = basename(dirname(__FILE__));

include("header.php");
Open();

/////////////// config

$cms = ''; // valid values are: Joomla, WordPress, DLE

if($cms == '') {
$cms = autoDetectCms();
if($cms == null) {
echo 'Cannot detect CMS type, please assign $cms variable in cms_importer.php';
return;
}
}

/////////////// code

ini_set('display_errors', '1');
error_reporting(E_NOTICE);

$ip_checker_url = "http://server.liex.ru/isvalidip/";
$valid_ip_addr = array('85.17.208.112');
$url_template = $_SERVER['HTTP_HOST'] . "/?q={num}";

$cms = autoDetectCms();


ProcessHttpRequest();

//ф-я обрабатывает запрос
function ProcessHttpRequest()
{
global $cms;
$secret_key = "skey";

if(!check_valid_ip()) {
$_REQUEST["action"] = 'test';
print "bad ip<br>\n";
}

if (!isset($_REQUEST["action"]))
{
print "Не задано действие. ";
return false;
}

$action = $_REQUEST["action"];
// if ($action = 'article_add')
// $action = 'article_update';

switch ($action):

case 'initialize':

if(isset($_POST['code']) && $_POST['code']!="cms") {
print 'wrong script (upload vs. sms_importer)';
break;
}

//запишем статью
$data["title"] = "test_title";
$data["text"] = "test_text";
$data["lat"] = "alt_text";
$r = UpdateCMS($cms, 'update', 0, $data);
if (substr($r, 0, 2) != "OK")
{
print $r;
UpdateCMS($cms, 'delete', 0);
break;
}
//отредактируем
$data["title"] = "test_title_edit";
$data["text"] = "test_text_edit";
$r = UpdateCMS($cms, 'update', 0, $data);
if (substr($r, 0, 2) != "OK")
{
print $r;
UpdateCMS($cms, 'delete', 0);
break;
}
//удалим
$r = UpdateCMS($cms, 'delete', 0);
if ($r != "OK")
{
print $r;
break;
}
print "OK";
break;

case 'test':
$rez = UpdateCMS($cms, 'test');
print "DB test: " . $rez;
if($rez=='ok') {
$my_ids = UpdateCMS($cms, 'all_ids');
if(is_array($my_ids)) print "<br>Articles found: " . count($my_ids);
} else {
print ' (' . mysql_error() . ')';
}
break;

case 'script_update':
$params = array("data");
foreach ($params as $v)
if (!isset($_REQUEST[$v]))
{
print "Не задан " . $v . ".";
return false;
}

$data = $_REQUEST["data"];
$crc = md5($action . $data . $secret_key);

$cur_md5 = md5($action . file_get_contents('cms_importer.php') . $secret_key);
//если текущее значение не сопадает - обновим
if ($cur_md5 != $crc)
{
if (file_exists('cms_importer.php'))
if (!unlink('cms_importer.php'))
{
print "Не могу удалить прошлый скрипт.";
}
if (file_put_contents('cms_importer.php', $data))
print "OK";
else
{
print "Не могу записать в файл.";
}
}
break;

case 'article_update':


$params = array("id", "text", "title");
foreach ($params as $v)
if (!isset($_REQUEST[$v]))
{
print "Не задан " . $v . ".";
return false;
}


$id = $_REQUEST["id"];
$text = $_REQUEST["text"];
$title = $_REQUEST["title"];
$lat = $_REQUEST["lat"];
$crc = md5($action . $id . $title . $text . $secret_key);

$data["text"] = $text;
$data["title"] = $title;
$data["lat"] = $lat;
print UpdateCMS($cms, 'update', $id, $data);

break;

case 'pause':
case 'unpause':

$params = array("id");
foreach ($params as $v)
if (!isset($_REQUEST[$v]))
{
print "Не задан " . $v . ".";
return false;
}


$id = $_REQUEST["id"];

$data["id"] = $id;
print UpdateCMS($cms, $action, $id, $data);

break;


case 'article_delete':

$params = array("id");
foreach ($params as $v)
if (!isset($_REQUEST[$v]))
{
print "Не задан " . $v . ".";
return false;
}
$id = $_REQUEST["id"];
$crc = md5($action . $id . $secret_key);
print UpdateCMS($cms, 'delete', $id);

break;

case 'extra_delete':

$params = array("all");
foreach ($params as $v)
if (!isset($_REQUEST[$v]))
{
print "Не задан " . $v . ".";
return false;
}
$all = $_REQUEST["all"];

$a = explode(",", $all);
for($i=0;$i<count($a);$i++) {
$srv_urls[$a[$i]] = 1;
}

$my_ids = UpdateCMS($cms, 'all_ids');

for($i=0;$i<count($my_ids);$i++) {
if(!$srv_urls[$my_ids[$i]] || !UpdateCMS($cms, 'check', $my_ids[$i])) {
UpdateCMS($cms, 'delete', $my_ids[$i]);
}
}

print "ok";
break;

default:
echo "Ошибка: Неизвестный тип запроса: " . $action;

endswitch;





}

//функция разбивает статью на заголовок и данные
function ParseArticle(&$data)
{

/*
//извлечем из хтмл колда данные
preg_match('|<title>(.*)</title>|Uis', $data, $out);
preg_match('|<body>(.*)</body>|Uis', $data, $out2);
if (isset($out[1]))
$r["title"] = addslashes($out[1]);
else
$r["title"] = "no data!";
if (isset($out[2]))
$r["text"] = addslashes($out2[1]);
else
$r["text"] = "no data!";
return $r;
*/
return $data;
}

//возвращзает id записи в таблице
//$id - глобальный ид статьи
function GetTableId($id)
{
//если нету создать таблицу
$t = getLinkerTable();
if (!CheckTableExist($t))
{
$sql = "CREATE TABLE `" . $t . "` (
`id` int(11) NOT NULL auto_increment,
`global_id` int(11) default NULL,
`table_id` int(11) default NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=cp1251";
Execute($sql);
if (!CheckTableExist($t))
{
die('Cannot create liex relationship table.');
}
}
//таблица которая содержит отображения ID реальных статей - на id их отображении в таблице КМС


$sql = "select table_id from {$t} where global_id={$id}";
$r = Execute($sql);
if ($r->RecordCount() <= 0)
{
return null;
}

$i = $r->FetchRow();
return $i["table_id"];
}

function GetAllIds() {
$t = getLinkerTable();
$sql = "select global_id from {$t} ";
GetTableId(0);

$r = Execute($sql);

$a = array();

for($i=0;$i<$r->RecordCount();$i++) {
$v = $r->FetchRow();
array_push($a, $v['global_id']);
}

return $a;
}

//устанавливает привязку того id что присвоен в таблице кмс с глобальным id
function SetIdLink($gid, $cms_id)
{

$sql = "insert into " . getLinkerTable() . " (global_id,table_id) values ({$gid},{$cms_id})";
if (Execute($sql) == false)
{
return false;
}
return true;
}


function UpdateCMS($cms, $action, $id = null, $data = null)
{


//распарсим входные парамтеры и соберем их в один объект


$r = array();
if ($action == "update")
{
$d = ParseArticle($data);
$r["title"] = $d["title"];
$r["text"] = $d["text"];
$r["lat"] = $d["lat"];
}
$r["id"] = $id;
$r["action"] = $action;
//print_r($r);
switch ($cms):
case "WordPress":
if(file_exists('WordPress.php')) {
include_once 'WordPress.php';
return WordPressImporter($r);
} else print "file WordPress.php not found";
break;

case "DLE":
if(file_exists('DLE.php')) {
include_once 'DLE.php';
return DleImporter($r);
} else print "file DLE.php not found";
break;

case "Joomla":
if(file_exists('Joomla.php')) {
include_once 'Joomla.php';
return JoomlaImporter($r);
} else print "file Joomla.php not found";
break;

default:

endswitch;

}



//НЕБОЛЬШАЯ ПРОСЛОЕЧКА К БАЗЕ

/**
* Execute SQL query
*
* @param string $sql - SQL query
* @return object Recordset
*/
$link = null;
function connect($dbhost, $user, $pwd)
{
return mysql_connect($dbhost, $user, $pwd);

}
function disconnect()
{
mysql_close(link);
}

function select($bd)
{
mysql_select_db($bd) or die('Can\'t use : ' . mysql_error());
}



function Execute($sql)
{
// print $sql;print "<br>";
// $res = mysql_query($sql, $this->conn);
$res = mysql_query($sql);
if (false === $res)
{
return false;
}
//print_r($res);
$r = new recordset($res, $sql);
return $r;
}

function get_last_id()
{
return mysql_insert_id();
}

/** EugenMalov
* функция проверяет есть ли таблицы в бд
* @param string $table - таблица для проверки
* @return boolean
*/

function CheckTableExist($table)
{
$sql = "select * from {$table}";
//print $sql;
//print "<br>";
mysql_query($sql);
if (mysql_error() != "")
{
//print 'faild';
return false;
}
else
{
//print 'succs';
return true;
}

}

class recordset
{
/**
* Recordset resource.
*
* @var resource
*/
var $recordset;

/**
* SQL query
*
* @var string
*/
var $sql;

/**
* Constructor.
*
* @param resource $recordset
* @return recordset object
*/
function recordset($recordset, $sql)
{
$this->recordset = $recordset;
$this->sql = $sql;
}

/**
* Returns amount of lines in result.
*
* @return integer
*/
function RecordCount()
{
return mysql_num_rows($this->recordset);
}

/**
* Returns the current row
* @return array
*/
function FetchRow()
{
return mysql_fetch_array($this->recordset, MYSQL_ASSOC);
}

//-----------Вспомогательная функция генерации кода

}

function getip()
{
if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"),"unknown"))
$ip = getenv("HTTP_CLIENT_IP");

elseif (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
$ip = getenv("HTTP_X_FORWARDED_FOR");

elseif (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
$ip = getenv("REMOTE_ADDR");

elseif (!empty($_SERVER['REMOTE_ADDR']) && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
$ip = $_SERVER['REMOTE_ADDR'];

elseif (!empty($_SERVER['HTTP_X_REAL_IP']) && strcasecmp($_SERVER['HTTP_X_REAL_IP'], "unknown"))
$ip = $_SERVER['HTTP_X_REAL_IP'];

else
$ip = "unknown";
$n = strpos($ip, ",");
if($n) $ip = substr($ip, 0, $n);

return($ip);
}

function check_valid_ip() {
global $ip_checker_url, $valid_ip_addr;
$ip = getip();

$fh = fopen($ip_checker_url . $ip, "r");
if ($fh) {
$r = fgets($fh);
fclose($fh);
return $r=='true';
}

foreach($valid_ip_addr as $a) {
if($a==$ip) return true;
}
return false;
}


function buildCmsData($cms) {

if($cms=='DLE') {
$dle = array();
$dle['config'] = 'engine/data/dbconfig.php';
$dle['db_host'] = 'DBHOST';
$dle['db_name'] = 'DBNAME';
$dle['db_user'] = 'DBUSER';
$dle['db_pass'] = 'DBPASS';
$dle['db_prefix'] = 'PREFIX';
return $dle;
}

if($cms=='WordPress') {
$wp = array();
$wp['config'] = 'wp-config.php';
$wp['db_host'] = 'DB_HOST';
$wp['db_name'] = 'DB_NAME';
$wp['db_user'] = 'DB_USER';
$wp['db_pass'] = 'DB_PASSWORD';
$wp['db_prefix'] = 'table_prefix';
return $wp;
}

if($cms=='JoomlaOld') {
$j = array();
$j['config'] = 'configuration.php';
$j['db_host'] = 'mosConfig_host';
$j['db_name'] = 'mosConfig_db';
$j['db_user'] = 'mosConfig_user';
$j['db_pass'] = 'mosConfig_password';
$j['db_prefix'] = 'mosConfig_dbprefix';
return $j;
}

if($cms=='Joomla') {
$j = array();
$j['config'] = 'configuration.php';
$j['db_host'] = '\$host';
$j['db_name'] = '\$db';
$j['db_user'] = '\$user';
$j['db_pass'] = '\$password';
$j['db_prefix'] = '\$dbprefix';
return $j;
}


return null;
}


function ConnectBD($cdata)
{

if (connect($cdata["DB_HOST"], $cdata["DB_USER"], $cdata["DB_PASSWORD"]) == false)
{
return false;
}
select($cdata["DB_NAME"]);

global $bd_prefix;
$bd_prefix = $cdata["table_prefix"];

return true;
}

function CheckAndConnect()
{
global $cms;
// look it up in the local config file
$cf = 'config.php';
if (file_exists($cf))
{
//попробуем извлечь параметры из нашего файла буффера
$data = ExtractConfigParameters($cf, buildCmsData('WordPress'));
if ($data != null)
{
if (ConnectBD($data)) return true;
}
}
// bad luck with config, search the server

$data = SearchAndGetParameters($cms);

if ($data != null)
{
if (ConnectBD($data)) return true;
}

echo "Cannot connect to database. Set params in config.php";
return false;
}

function SearchAndGetParameters($cms, $load = true)
{
$cms_data = buildCmsData($cms);
if($cms_data==null) return null;

$config_file = FindConfig($cms_data['config']);
if ($config_file)
{
$data = $load ? ExtractConfigParameters($config_file, $cms_data) : $config_file;
return $data;
}
else
{
return null;
}
}

function ExtractConfigParameters($config_file, $cms_data)
{
$data = array();
$str = file_get_contents($config_file);
$str = str_replace('"', "'", $str);

if(strpos($str, "mosConfig")) $cms_data = buildCmsData("JoomlaOld");

$pattern = "/'?" . $cms_data['db_name'] . "'?\s*[,=]\s*'(.*)'.*;/";
preg_match($pattern, $str, $matches);

if (!isset($matches[1]))
{
return null;
}

$data["DB_NAME"] = $matches[1];
$pattern = "/'?" . $cms_data['db_user'] . "'?\s*[,=]\s*'(.*)'.*;/";
preg_match($pattern, $str, $matches);

if (!isset($matches[1]))
{
return null;
}
$data["DB_USER"] = $matches[1];

$pattern = "/'?" . $cms_data['db_pass'] . "'?\s*[,=]\s*'(.*)'.*;/";
preg_match($pattern, $str, $matches);

if (!isset($matches[1]))
{
return null;
}
$data["DB_PASSWORD"] = $matches[1];

$pattern = "/'?" . $cms_data['db_host'] . "'?\s*[,=]\s*'(.*)'.*;/";
preg_match($pattern, $str, $matches);

if (!isset($matches[1]))
{
return null;
}
$data["DB_HOST"] = $matches[1];

$pattern = "/'?" . $cms_data['db_prefix'] . "'?\s*[,=]\s*'(.*)'.*;/";
preg_match($pattern, $str, $matches);

if (!isset($matches[1]))
{
return null;
}
$data["table_prefix"] = $matches[1];

return $data;
}

function FindConfig($f) {
$f = "./" . $f;
for($i=0;$i<2;$i++) {
if(file_exists($f)) return $f;
$f = "../" . $f;
}
return null;
}

function autoDetectCms() {
$a = array("WordPress", "DLE", "Joomla");
foreach($a as $cms) {
$rez[$cms] = SearchAndGetParameters($cms, false);
}
$loop = true;
while($loop) {
$loop = false;
foreach($a as $cms) {
if($rez[$cms]==null) continue;
if(substr($rez[$cms],0,3)=="../") $rez[$cms] = substr($rez[$cms], 3);
else return $cms;
$loop = true;
}
}
return null;
}


?>

И код модуля для CMS DLE:

<?php

/**
* @author Eugen Malov
* @copyright 2007
*/

global $bd_prefix;
global $connect;
global $url_template;
global $cat_id;
global $cat_name;
global $index_publish;
global $pml;

$url_template = "/index.php?newsid={num}";
//$url_template = "/{date}/{num}.html";
//$url_template = "/liex/{num}-{postname}.html";
//$url_template = "/{date}/{postname}.html";
//$url_template = "/main/{num}-{postname}.html";

////// признак вывода на главную страницу: 0 - не выводить, 1 - выводить
$index_publish = 0;

// id категории, куда будут добавляться статьи
// значение id можно взять из таблицы категорий на странице /admin.php?mod=categories
$cat_id = 1;


// длина текста для краткого текста новости
$short_len = 300;

// 1 = попытаться автоматически определить вид ЧПУ (url_template)
// 0 = не пытаться, использовать настройки пользователя url_template
$pml = 1;


////////////////////////////
// code below

$connect = CheckAndConnect();

if($connect) mysql_query("SET NAMES cp1251");

if($pml) {
$fc = FindConfig("engine/data/config.php");

if ($fc) {
include($fc);
if($config['allow_alt_url']=='no') {
$pml = "/index.php?newsid=%post_id%";
} else {
if(!isset($config['seo_type'])) $config['seo_type'] = '2';
if($config['seo_type']=='1') $pml = "/%post_id%-%postname%.html";
if($config['seo_type']=='2') {
$cat_tab = $bd_prefix . "_category";
$rd = Execute("SELECT alt_name FROM {$cat_tab} WHERE id = '{$cat_id}'");
if ($rd->RecordCount() > 0) {
$row = $rd->FetchRow();
$cat_name = $row['alt_name'];
$pml = "/%category%/%post_id%-%postname%.html";
} else $pml = '';
}
if($config['seo_type']=='0') $pml = "/%year%/%monthnum%/%day%/%postname%.html";
}
} else $pml = '';
}

//echo 'pml=' . $pml;

if(!isset($url_template)) $url_template = "/index.php?newsid={num}";

function getLinkerTable() {
global $bd_prefix;
return $bd_prefix . "_liex_id_linker";
}

function split_text($text) {
global $short_len;
$a = array();
if($short_len > 2*strlen($text)/3) {
$a[0] = '';
$a[1] = $text;
} else {
$spl = split('\. ', $text);
$r = '';
for($i=0;$i<count($spl);$i++) {
$r .= $spl[$i] . ". ";
if(strlen($r) > $short_len) break;
}
if(strlen($r) >= strlen($text)) {
$a[0] = '';
$a[1] = $text;
} else {
$a[0] = $r;
$a[1] = $text;
}
}
return $a;
}

//функция отвеающая за импорт в DLE
function DleImporter($data)
{
global $bd_prefix, $pml;
global $connect, $url_template, $cat_id, $cat_name, $index_publish;
if (!$connect) return "db connection error";

$t = $bd_prefix . "_post";


if ($data["action"] == "update")
{
$text = $data["text"];
$title = $data["title"];
$post_name = $data["lat"];

$text = str_replace("'", "\'", $text);
$title = str_replace("'", "\'", $title);

$tid = GetTableId($data["id"]);

list($tshort, $tfull) = split_text($text);

if ($tid == null)
{

$sql = "INSERT INTO {$t} (title,alt_name,short_story,full_story,date,approve,autor,allow_main, category) VALUES ('{$title}','{$post_name}','{$tshort}','{$tfull}',now(),1,'', {$index_publish}, {$cat_id})";
//print $sql;
if (Execute($sql) == false)
{
return "Error creating article: " . mysql_error();
}

$cms_id = get_last_id();
if(SetIdLink($data["id"], $cms_id)==false) {
return "Error setting liex relation: " . mysql_error();
}
$tid = $cms_id;
}
else
{

$sql = "update {$t} set title='{$title}', short_story='{$tshort}', full_story='{$tfull}', alt_name='{$post_name}', allow_main='{$index_publish}', category='{$cat_id}' where id={$tid}";
//print $sql;
if (Execute($sql) == false)
{
return "Error updating data: " . mysql_error();
}

}
$r = Execute("SELECT date FROM {$t} WHERE id = {$tid} ");
if ($r->RecordCount()>0){
$row = $r->FetchRow();
$d = $row['date'];

if($pml) {
$d = strtotime($d);

$pml = str_replace("%year%", date('Y', $d), $pml);
$pml = str_replace("%monthnum%", date('m', $d), $pml);
$pml = str_replace("%day%", date('d', $d), $pml);
$pml = str_replace("%hour%", date('G', $d), $pml);
$pml = str_replace("%minute%", date('i', $d), $pml);
$pml = str_replace("%second%", date('s', $d), $pml);
$pml = str_replace("%postname%", $post_name, $pml);
$pml = str_replace("%post_id%", $tid, $pml);
$pml = str_replace("%author%", '', $pml);
$pml = str_replace("%category%", $cat_name, $pml);

$url = $pml;
} else {
$url = $url_template;
$url = str_replace("{date}", str_replace("-","/", substr($row['date'],0,10)), $url);
$url = str_replace("{num}", $tid, $url);
$url = str_replace("{postname}", $post_name, $url);
}
return "OK " . $_SERVER['HTTP_HOST'] . $url;
} else {
return "Error: " . mysql_error();
}
}

if ($data["action"] == "pause" || $data["action"] == "unpause")
{

$tid = GetTableId($data["id"]);
if($tid == null) return "not found";

$val = $data["action"] == "pause"?0:1;
$sql = "UPDATE {$t} set approve = $val where id={$tid}";
//print $sql;
if (Execute($sql) == false)
{
return "Error pausing or activating article";
}

return "OK";
}

if ($data["action"] == "delete")
{
$tid = GetTableId($data["id"]);
$sql = "DELETE FROM {$t} where id={$tid}";
if(Execute($sql)==false) {
return "Error deleting relation";
}
$sql = "DELETE FROM " . getLinkerTable() . " where table_id={$tid}";
if(Execute($sql)==false) {
return "Error deleting liex relation";
}

return 'OK';
}

if ($data["action"] == "all_ids")
{
return GetAllIds();
}

if ($data["action"] == "test")
{
$sql = "select title,alt_name,short_story,full_story,date,approve,autor,allow_main, category from {$t} where id = 777";
if (Execute($sql) == false) {
return 'failed';
}
return 'ok';
}

if ($data["action"] == "check")
{

$tid = GetTableId($data["id"]);

//если связки нету знаичт и нечего удалять - а значит все ок
if ($tid == null) return 0;

$r = Execute("SELECT * FROM {$t} where id={$tid}");
if ($r == false)
{
return 0;
}

return $r->RecordCount()>0;
}


return "Unknown action for DLE importer: " . $data["action"];
}

Close();
include("footer.php");
?>
4

4
5
14.04.2009 09:29:09
Но обратите внимание код требует доработки тк вы дали под dle, а это slaed. Выше лишь пример как реализовать в виде модуля.
4

4
6
14.04.2009 20:49:27
Неужели никто из пользователей Slaed не работает с биржой Liex! В инете пишут что эта очень выгодная и перспективная биржа.
7
15.04.2009 07:12:5915.04.2009 07:14:18
samandar, ну вам же дали готовый вариант. Не помогло ?
Что за система такая вобще ?
$pml = str_replace("%year%", date('Y', $d), $pml);
$pml = str_replace("%monthnum%", date('m', $d), $pml);
$pml = str_replace("%day%", date('d', $d), $pml);
$pml = str_replace("%hour%", date('G', $d), $pml);
$pml = str_replace("%minute%", date('i', $d), $pml);
$pml = str_replace("%second%", date('s', $d), $pml);

этот участок кода на просто ржачку пробивает
3.91

3.91
Открыть Ответить
Хотите опробовать SLAED CMS в действии?

Технологии

PHP MySQL HTML 5 CSS 3 jQuery jQuery UI

Контакты

  • D-49179, Deutschland
    Ostercappeln, Im Siek 6
  • +49 176 61966679

  • https://slaed.net
Идеи и предложения
Обратная связь