From 1ab4e7c71a540160fd055e2c0e2dc24fde23962a Mon Sep 17 00:00:00 2001 From: kaliostro Date: Thu, 4 Feb 2016 01:12:26 +0300 Subject: [PATCH] init --- .../engine/data/dle_xen_conf.php | 21 + .../modules/XenIntegration/PasswordHash.php | 267 ++++ .../modules/XenIntegration/XenIntegration.php | 932 +++++++++++++ .../XenIntegration/last_topic_block.php | 3 + .../XenIntegration/xen_default_config.php | 58 + .../language/Russian/dle_xen.lng | 6 + .../engine/data/dle_xen_conf.php | 21 + .../modules/XenIntegration/PasswordHash.php | 267 ++++ .../modules/XenIntegration/XenIntegration.php | 932 +++++++++++++ .../XenIntegration/last_topic_block.php | 3 + .../XenIntegration/xen_default_config.php | 58 + .../language/Russian/dle_xen.lng | 6 + README.txt | 82 ++ .../ControllerPublic/Logout.php | 19 + .../ControllerPublic/Register.php | 18 + .../library/DLEIntegration/DLE.php | 345 +++++ .../DLEIntegration/DataWriter/User.php | 66 + .../library/DLEIntegration/Listener.php | 34 + .../library/DLEIntegration/Model/User.php | 63 + .../DLEIntegration/Model/UserConfirmation.php | 21 + .../library/DLEIntegration/ParseFilter.php | 1215 +++++++++++++++++ .../DLEIntegration/config/dle_config.php | 18 + addon-DLEIntegration.xml | 32 + templates_utf-8/block_forum_posts.tpl | 13 + templates_windows-1251/block_forum_posts.tpl | 13 + 25 files changed, 4513 insertions(+) create mode 100644 DLE_uploads_utf-8/engine/data/dle_xen_conf.php create mode 100644 DLE_uploads_utf-8/engine/modules/XenIntegration/PasswordHash.php create mode 100644 DLE_uploads_utf-8/engine/modules/XenIntegration/XenIntegration.php create mode 100644 DLE_uploads_utf-8/engine/modules/XenIntegration/last_topic_block.php create mode 100644 DLE_uploads_utf-8/engine/modules/XenIntegration/xen_default_config.php create mode 100644 DLE_uploads_utf-8/language/Russian/dle_xen.lng create mode 100644 DLE_uploads_windows-1251/engine/data/dle_xen_conf.php create mode 100644 DLE_uploads_windows-1251/engine/modules/XenIntegration/PasswordHash.php create mode 100644 DLE_uploads_windows-1251/engine/modules/XenIntegration/XenIntegration.php create mode 100644 DLE_uploads_windows-1251/engine/modules/XenIntegration/last_topic_block.php create mode 100644 DLE_uploads_windows-1251/engine/modules/XenIntegration/xen_default_config.php create mode 100644 DLE_uploads_windows-1251/language/Russian/dle_xen.lng create mode 100644 README.txt create mode 100644 XenForo_uploads/library/DLEIntegration/ControllerPublic/Logout.php create mode 100644 XenForo_uploads/library/DLEIntegration/ControllerPublic/Register.php create mode 100644 XenForo_uploads/library/DLEIntegration/DLE.php create mode 100644 XenForo_uploads/library/DLEIntegration/DataWriter/User.php create mode 100644 XenForo_uploads/library/DLEIntegration/Listener.php create mode 100644 XenForo_uploads/library/DLEIntegration/Model/User.php create mode 100644 XenForo_uploads/library/DLEIntegration/Model/UserConfirmation.php create mode 100644 XenForo_uploads/library/DLEIntegration/ParseFilter.php create mode 100644 XenForo_uploads/library/DLEIntegration/config/dle_config.php create mode 100644 addon-DLEIntegration.xml create mode 100644 templates_utf-8/block_forum_posts.tpl create mode 100644 templates_windows-1251/block_forum_posts.tpl diff --git a/DLE_uploads_utf-8/engine/data/dle_xen_conf.php b/DLE_uploads_utf-8/engine/data/dle_xen_conf.php new file mode 100644 index 0000000..861fb90 --- /dev/null +++ b/DLE_uploads_utf-8/engine/data/dle_xen_conf.php @@ -0,0 +1,21 @@ + 1, // включить интеграцию + 'allow_reg' => 1, // включить общую регистрацию + 'allow_login' => 1, // включить общую авторизацию + 'allow_logout' => 1, // включить общий выход + 'allow_profile' => 1, // включить изменение профеля + 'allow_lostpass' => 1, // включить восстановление пароля + 'allow_forum_block' => 1, // включить блок последних сообщений с форума + 'block_cache_time' => 600, //Время в секундах для кеширование блока последних сообщений, 0 - без кеширования + 'bad_forum_for_block' => '', //IDs форумов которые не нужно показывать в блоке, указываются через запятую, если не заполненно показываются темы со всех форумов + 'good_forum_for_block' => '', //IDs форумов которые нужно показывать в блоке, указываются через запятую (не работает если заполнена предыдущая опция + 'count_post' => 10, // количество сообщений в блоке + 'block_rewrite_url' => true, // использовать или нет ЧПУ в ссылках + 'length_name' => 0, // максимальнаядлина имени, остальные символы обрезаются, 0 - не обрезать + + + +); \ No newline at end of file diff --git a/DLE_uploads_utf-8/engine/modules/XenIntegration/PasswordHash.php b/DLE_uploads_utf-8/engine/modules/XenIntegration/PasswordHash.php new file mode 100644 index 0000000..4ffebb2 --- /dev/null +++ b/DLE_uploads_utf-8/engine/modules/XenIntegration/PasswordHash.php @@ -0,0 +1,267 @@ + in 2004-2006 and placed in +# the public domain. Revised in subsequent years, still public domain. +# +# There's absolutely no warranty. +# +# The homepage URL for this framework is: +# +# http://www.openwall.com/phpass/ +# +# Please be sure to update the Version line if you edit this file in any way. +# It is suggested that you leave the main version number intact, but indicate +# your project name (after the slash) and add your own revision information. +# +# Please do not change the "private" password hashing method implemented in +# here, thereby making your hashes incompatible. However, if you must, please +# change the hash type identifier (the "$P$") to something different. +# +# Obviously, since this code is in the public domain, the above are not +# requirements (there can be none), but merely suggestions. +# +class XenForo_PasswordHash { + var $itoa64; + var $iteration_count_log2; + var $portable_hashes; + var $random_state; + + public function __construct($iteration_count_log2, $portable_hashes) + { + $this->itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; + + if ($iteration_count_log2 < 4 || $iteration_count_log2 > 31) + $iteration_count_log2 = 8; + $this->iteration_count_log2 = $iteration_count_log2; + + $this->portable_hashes = $portable_hashes; + + $this->random_state = microtime(); + if (function_exists('getmypid')) + $this->random_state .= getmypid(); + } + + function get_random_bytes($count) + { + $output = ''; + + if (function_exists('openssl_random_pseudo_bytes') + && (substr(PHP_OS, 0, 3) != 'WIN' || version_compare(phpversion(), '5.3.4', '>=')) + ) + { + $output = openssl_random_pseudo_bytes($count); + } + else if (function_exists('mcrypt_create_iv') && version_compare(phpversion(), '5.3.0', '>=')) + { + $output = mcrypt_create_iv($count, MCRYPT_DEV_URANDOM); + } + else if (@is_readable('/dev/urandom') && + ($fh = @fopen('/dev/urandom', 'rb'))) { + $output = fread($fh, $count); + fclose($fh); + } + + if (strlen($output) < $count) { + $output = ''; + for ($i = 0; $i < $count; $i += 16) { + $this->random_state = + md5(microtime() . $this->random_state); + $output .= + pack('H*', md5($this->random_state)); + } + $output = substr($output, 0, $count); + } + + return $output; + } + + function encode64($input, $count) + { + $output = ''; + $i = 0; + do { + $value = ord($input[$i++]); + $output .= $this->itoa64[$value & 0x3f]; + if ($i < $count) + $value |= ord($input[$i]) << 8; + $output .= $this->itoa64[($value >> 6) & 0x3f]; + if ($i++ >= $count) + break; + if ($i < $count) + $value |= ord($input[$i]) << 16; + $output .= $this->itoa64[($value >> 12) & 0x3f]; + if ($i++ >= $count) + break; + $output .= $this->itoa64[($value >> 18) & 0x3f]; + } while ($i < $count); + + return $output; + } + + protected function gensalt_private($input) + { + $output = '$P$'; + $output .= $this->itoa64[min($this->iteration_count_log2 + + ((PHP_VERSION >= '5') ? 5 : 3), 30)]; + $output .= $this->encode64($input, 6); + + return $output; + } + + protected function crypt_private($password, $setting) + { + $output = '*0'; + if (substr($setting, 0, 2) == $output) + $output = '*1'; + + $id = substr($setting, 0, 3); + # We use "$P$", phpBB3 uses "$H$" for the same thing + if ($id != '$P$' && $id != '$H$') + return $output; + + $count_log2 = strpos($this->itoa64, $setting[3]); + if ($count_log2 < 7 || $count_log2 > 30) + return $output; + + $count = 1 << $count_log2; + + $salt = substr($setting, 4, 8); + if (strlen($salt) != 8) + return $output; + + # We're kind of forced to use MD5 here since it's the only + # cryptographic primitive available in all versions of PHP + # currently in use. To implement our own low-level crypto + # in PHP would result in much worse performance and + # consequently in lower iteration counts and hashes that are + # quicker to crack (by non-PHP code). + if (PHP_VERSION >= '5') { + $hash = md5($salt . $password, TRUE); + do { + $hash = md5($hash . $password, TRUE); + } while (--$count); + } else { + $hash = pack('H*', md5($salt . $password)); + do { + $hash = pack('H*', md5($hash . $password)); + } while (--$count); + } + + $output = substr($setting, 0, 12); + $output .= $this->encode64($hash, 16); + + return $output; + } + + function gensalt_extended($input) + { + $count_log2 = min($this->iteration_count_log2 + 8, 24); + # This should be odd to not reveal weak DES keys, and the + # maximum valid value is (2**24 - 1) which is odd anyway. + $count = (1 << $count_log2) - 1; + + $output = '_'; + $output .= $this->itoa64[$count & 0x3f]; + $output .= $this->itoa64[($count >> 6) & 0x3f]; + $output .= $this->itoa64[($count >> 12) & 0x3f]; + $output .= $this->itoa64[($count >> 18) & 0x3f]; + + $output .= $this->encode64($input, 3); + + return $output; + } + + function gensalt_blowfish($input) + { + # This one needs to use a different order of characters and a + # different encoding scheme from the one in encode64() above. + # We care because the last character in our encoded string will + # only represent 2 bits. While two known implementations of + # bcrypt will happily accept and correct a salt string which + # has the 4 unused bits set to non-zero, we do not want to take + # chances and we also do not want to waste an additional byte + # of entropy. + $itoa64 = './ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; + + $output = '$2a$'; + $output .= chr(ord('0') + $this->iteration_count_log2 / 10); + $output .= chr(ord('0') + $this->iteration_count_log2 % 10); + $output .= '$'; + + $i = 0; + do { + $c1 = ord($input[$i++]); + $output .= $itoa64[$c1 >> 2]; + $c1 = ($c1 & 0x03) << 4; + if ($i >= 16) { + $output .= $itoa64[$c1]; + break; + } + + $c2 = ord($input[$i++]); + $c1 |= $c2 >> 4; + $output .= $itoa64[$c1]; + $c1 = ($c2 & 0x0f) << 2; + + $c2 = ord($input[$i++]); + $c1 |= $c2 >> 6; + $output .= $itoa64[$c1]; + $output .= $itoa64[$c2 & 0x3f]; + } while (1); + + return $output; + } + + function HashPassword($password) + { + $random = ''; + + if (CRYPT_BLOWFISH == 1 && !$this->portable_hashes) { + $random = $this->get_random_bytes(16); + $hash = + crypt($password, $this->gensalt_blowfish($random)); + if (strlen($hash) == 60) + return $hash; + } + + if (CRYPT_EXT_DES == 1 && !$this->portable_hashes) { + if (strlen($random) < 3) + $random = $this->get_random_bytes(3); + $hash = + crypt($password, $this->gensalt_extended($random)); + if (strlen($hash) == 20) + return $hash; + } + + if (strlen($random) < 6) + $random = $this->get_random_bytes(6); + $hash = + $this->crypt_private($password, + $this->gensalt_private($random)); + if (strlen($hash) == 34) + return $hash; + + # Returning '*' on error is safe here, but would _not_ be safe + # in a crypt(3)-like function used _both_ for generating new + # hashes and for validating passwords against existing hashes. + return '*'; + } + + function CheckPassword($password, $stored_hash) + { + $hash = $this->crypt_private($password, $stored_hash); + if ($hash[0] == '*') + $hash = crypt($password, $stored_hash); + + return $hash == $stored_hash; + } + + public function reverseItoA64($char) + { + return strpos($this->itoa64, $char); + } +} \ No newline at end of file diff --git a/DLE_uploads_utf-8/engine/modules/XenIntegration/XenIntegration.php b/DLE_uploads_utf-8/engine/modules/XenIntegration/XenIntegration.php new file mode 100644 index 0000000..ef5ca27 --- /dev/null +++ b/DLE_uploads_utf-8/engine/modules/XenIntegration/XenIntegration.php @@ -0,0 +1,932 @@ +displayAndExit( + "Вы используете не лицензионную версию модуля DLE + XenForo.
+ За информацией обращайтесь на форум http://forum.kaliostro.net/
+ You are not using licensed version of the module DLE + XenForo.
+ For information, visit the forum http://forum.kaliostro.net/"); + } + + $forumConfigFile = dirname(__FILE__) . "/config.php"; + if (!file_exists($forumConfigFile)) { + $this->displayAndExit("Вы должны скопировать файл конфигурации %s с форума в папку с модулем интеграции %s", 'library/config.php', $forumConfigFile); + } + + $config = require dirname(__FILE__) . "/xen_default_config.php"; + require $forumConfigFile; + $this->XenConfig = $config; + + if (empty($this->XenConfig['globalSalt'])) { + $this->displayAndExit("Значение для globalSalt не установлено в конфиге %s", $forumConfigFile); + } + + $this->DLEConfig = $GLOBALS['config']; + + define('F_PREFIX', 'xf_'); + + if (!defined('F_CHARSET')) + { + define('F_CHARSET', 'UTF-8'); + } + + $configFile = ENGINE_DIR . "/data/dle_xen_conf.php"; + if (!file_exists($configFile)) + { + $this->displayAndExit("Не найден конфиг интеграции. Пройдите процесс установки"); + } + $this->config = require $configFile; + + $this->lang = require ROOT_DIR . '/language/Russian/dle_xen.lng'; + $lngFile = ROOT_DIR . '/language/' . $GLOBALS['config']['langs'] . '/dle_xen.lng'; + if (file_exists($lngFile)) { + $this->lang = array_merge($this->lang, include $lngFile); + } + } + + protected function displayAndExit($text) + { + $params = func_get_args(); + array_shift($params); + + @header("Content-type: text/html; charset=UTF-8"); + call_user_func_array('printf', array($text) + $params); + exit(); + } + + /** + * + * @return self + */ + static public function getInstance() + { + if (!self::$_instance) + { + self::$_instance = new self(); + } + + return self::$_instance; + } + + /** + * + * @staticvar PDO $dbh + * @return \PDO + */ + protected function _getDb() + { + static $dbh; + + if (!$dbh) + { + $dbh = new PDO("mysql:host={$this->XenConfig['db']['host']};port={$this->XenConfig['db']['port']};dbname=" . $this->XenConfig['db']['dbname'], $this->XenConfig['db']['username'], $this->XenConfig['db']['password']); + $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT); + $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); + $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + + $dbh->exec('SET SQL_MODE=""'); + $dbh->exec('SET NAMES `utf8`'); + } + + return $dbh; + } + + protected function _getConfigForum() + { + static $config = array(); + + if ($config) + { + return $config; + } + + if (!function_exists("dle_cache") || !($cache = dle_cache("config_xen"))) + { + $sth = $this->_getdb()->query("SELECT + option_id, + option_value, + data_type + FROM xf_option WHERE option_id IN ('boardUrl', 'registrationDefaults', 'guestTimeZone')"); + + while ($row = $sth->fetch(PDO::FETCH_ASSOC)) + { + if ($row['data_type'] == "array"){ + $config[$row['option_id']] = unserialize($row['option_value']); + } + else { + $config[$row['option_id']] = $row['option_value']; + } + } + + if (function_exists("create_cache")) + { + create_cache("config_xen", serialize($config)); + } + + return $config; + } + elseif ($cache) + { + $config = unserialize($cache); + } + + return $config; + } + + protected function _init_parse() + { + if (!$this->_parse) + { + if (empty($GLOBALS['parse']) || !($GLOBALS['parse'] instanceof ParseFilter)) + { + if (!class_exists('ParseFilter')) + { + require_once(ENGINE_DIR . "/classes/parse.class.php"); + } + $this->_parse = new ParseFilter(); + } + else + { + $this->_parse = $GLOBALS['parse']; + } + } + + return $this->_parse; + } + + protected function _getPasswordGenerator() + { + static $password; + + if (!$password) { + require_once dirname(__FILE__) . "/PasswordHash.php"; + $password = new XenForo_PasswordHash($this->XenConfig['passwordIterations'], false); + } + + return $password; + } + + protected function getDLEAPI() + { + global $config, $db; + static $dle_api; + + if (!$dle_api) { + + if (!empty($GLOBALS['dle_api'])) { + $dle_api = $GLOBALS['dle_api']; + } + else { + require_once ENGINE_DIR . "/api/api.class.php"; + } + } + + return $dle_api; + } + + protected function convertIpStringToBinary($ip) + { + $originalIp = $ip; + $ip = trim($ip); + + if (strpos($ip, ':') !== false) + { + // IPv6 + if (preg_match('#:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$#', $ip, $match)) + { + // embedded IPv4 + $long = ip2long($match[1]); + if (!$long) + { + return false; + } + + $hex = str_pad(dechex($long), 8, '0', STR_PAD_LEFT); + $v4chunks = str_split($hex, 4); + $ip = str_replace($match[0], ":$v4chunks[0]:$v4chunks[1]", $ip); + } + + if (strpos($ip, '::') !== false) + { + if (substr_count($ip, '::') > 1) + { + // ambiguous + return false; + } + + $delims = substr_count($ip, ':'); + if ($delims > 7) + { + return false; + } + + $ip = str_replace('::', str_repeat(':0', 8 - $delims) . ':', $ip); + if ($ip[0] == ':') + { + $ip = '0' . $ip; + } + } + + $ip = strtolower($ip); + + $parts = explode(':', $ip); + if (count($parts) != 8) + { + return false; + } + + foreach ($parts AS &$part) + { + $len = strlen($part); + if ($len > 4 || preg_match('/[^0-9a-f]/', $part)) + { + return false; + } + + if ($len < 4) + { + $part = str_repeat('0', 4 - $len) . $part; + } + } + + $hex = implode('', $parts); + if (strlen($hex) != 32) + { + return false; + } + + return $this->convertHexToBin($hex); + } + else if (strpos($ip, '.')) + { + // IPv4 + if (!preg_match('#(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})#', $ip, $match)) + { + return false; + } + + $long = ip2long($match[1]); + if (!$long) + { + return false; + } + + return $this->convertHexToBin( + str_pad(dechex($long), 8, '0', STR_PAD_LEFT) + ); + } + else if (strlen($ip) == 4 || strlen($ip) == 16) + { + // already binary encoded + return $ip; + } + else if (is_numeric($originalIp) && $originalIp < pow(2, 32)) + { + // IPv4 as integer + return $this->convertHexToBin( + str_pad(dechex($originalIp), 8, '0', STR_PAD_LEFT) + ); + } + else + { + return false; + } + } + + protected function convertHexToBin($hex) + { + if (function_exists('hex2bin')) + { + return hex2bin($hex); + } + + $len = strlen($hex); + + if ($len % 2) + { + trigger_error('Hexadecimal input string must have an even length', E_USER_WARNING); + } + + if (strspn($hex, '0123456789abcdefABCDEF') != $len) + { + trigger_error('Input string must be hexadecimal string', E_USER_WARNING); + } + + return pack('H*', $hex); + } + + protected function createDLEUser(stdClass $user, $password) + { + /** @var $db \db */ + $db = $GLOBALS['db']; + + $statusCode = $this->dleAPI->external_register( + $this->_convert_encoding($user->username, true), + $password, + $this->_convert_encoding($user->email, true), + $this->DLEConfig['reg_group'] + ); + + if ($statusCode !== 1) { + return false; + } + $user_id = $db->insert_id(); + + $stm = $this->db->prepare("SELECT location, about, signature FROM " . F_PREFIX . "user_profile WHERE user_id=?"); + $stm->execute(array($user->user_id)); + + $profile = $stm->fetchObject(); + + $info = $db->safesql($this->_convert_encoding($profile->about, true)); + $land = $db->safesql($this->_convert_encoding($profile->location, true)); + $signature = $db->safesql($this->_convert_encoding($profile->signature, true)); + + $db->query("UPDATE " . USERPREFIX . "_users SET info='$info', land='$land', signature='$signature', reg_date={$user->register_date}, lastdate={$user->last_activity} WHERE user_id=" . $user_id); + + $GLOBALS['member_id'] = $member_id = $db->super_query("SELECT * FROM " . USERPREFIX . "_users WHERE user_id=" . $user_id); + + set_cookie( "dle_user_id", $member_id['user_id'], 365 ); + set_cookie( "dle_password", $_POST['login_password'], 365 ); + $_SESSION['dle_user_id'] = $member_id['user_id']; + $_SESSION['dle_password'] = $_POST['login_password']; + $_SESSION['member_lasttime'] = $member_id['lastdate']; + + $GLOBALS['is_logged'] = true; + $GLOBALS['tpl']->result['info'] = ''; + + return $member_id; + } + + public function findXenUser($username, $email, $password = null) + { + $email = $this->_convert_encoding($email); + $username = $this->_convert_encoding($username); + $password = $this->_convert_encoding($password); + + $sth = $this->_getDb()->prepare("SELECT * FROM " . F_PREFIX . "user_authenticate a + LEFT JOIN " . F_PREFIX ."user u + ON u.user_id=a.user_id + WHERE u.username=? AND u.email=?"); + + $sth->execute(array($username, $email)); + $user = $sth->fetchObject(); + + if ($user) + { + $authData = unserialize($user->data); + if (!$password || $this->passwordGenerator->CheckPassword($password, $authData['hash'])) { + return $user; + } + } + + return false; + } + + #region Public function + + public function login($member_id, $force = false) + { + if (!$this->config['allow_module'] || !$this->config['allow_login']) + { + return false; + } + + if(!$force && !(isset($_POST['login']) AND $_POST['login_name'] AND $_POST['login_password'] AND $_POST['login'] == "submit")) { + return false; + } + + if (empty($member_id['user_id'])) { + $sth = $this->_getDb()->prepare("SELECT * FROM " . F_PREFIX . "user_authenticate a + LEFT JOIN " . F_PREFIX ."user u + ON u.user_id=a.user_id + WHERE u." . ($this->DLEConfig['auth_metod']?"email":"username") . "=?"); + + $sth->execute(array($_POST['login_name'])); + $auth = $sth->fetchObject(); + + if (!$auth) { + return true; + } + $authData = unserialize($auth->data); + if (!$this->passwordGenerator->CheckPassword($this->_convert_encoding($_REQUEST['login_password']), $authData['hash'])) { + return true; + } + + if (!($member_id = $this->createDLEUser($auth, $_REQUEST['login_password']))) { + return true; + } + } + else { + $auth = $this->findXenUser($member_id['name'], $member_id['email'], $_REQUEST['login_password']); + } + + if (!$auth) { + return true; + } + + $this->doLogin($auth->user_id, $auth->remember_key, $auth->last_activity); + + return false; + } + + public function logout() + { + if (!$this->config['allow_module'] || !$this->config['allow_logout']) + { + return false; + } + + $domain = $this->_getCookieDomain(); + $sessionCookieName = $this->XenConfig['cookie']['prefix'] . "session"; + + setcookie($sessionCookieName, "", time() - 31536000, $this->XenConfig['cookie']['path'], $domain); + setcookie($this->XenConfig['cookie']['prefix'] . "user", "", time() - 31536000, $this->XenConfig['cookie']['path'], $domain); + + return false; + } + + public function createMember($name, $passwordMD5, $email) + { + if (!$this->config['allow_module'] || !$this->config['allow_reg']) { + return false; + } + + $username = $this->_convert_encoding($name); + $email = $this->_convert_encoding($email); + + $stm = $this->db->prepare("SELECT * FROM " . F_PREFIX . "user WHERE username=? OR email=?"); + $stm->execute(array($username, $email)); + + if ($stm->rowCount()) { + return true; + } + + $registrationDefaults = $this->options['registrationDefaults']; + function mergeWithDefault($data, $registrationDefaults) { + return array_merge($data, array_intersect_key($registrationDefaults, $data)); + } + + $data = array( + 'username' => $username, + 'email' => $email, + 'gender' => '', + 'language_id' => 0, + 'style_id' => 0, + 'timezone' => $this->options['guestTimeZone'], + 'user_group_id' => 2, + 'display_style_group_id' => 2, + 'permission_combination_id' => 2, + 'register_date' => time(), + 'last_activity' => time(), + 'visible' => 1, + ); + + $this->db->prepare("INSERT INTO " . F_PREFIX . "user (" . implode(", ", array_keys($data)) . ") VALUES (" . implode(", ", $this->_getDBPrepareKeys($data)) . ")") + ->execute(mergeWithDefault($data, $registrationDefaults)); + + $user_id = $this->db->lastInsertId(); + + $this->db->prepare("INSERT INTO " . F_PREFIX . "user_profile (user_id, csrf_token) VALUES (?, ?)") + ->execute(array($user_id, substr(sha1(time() . uniqid()), 0, 40))); + + $data = array( + 'user_id' => $user_id, + 'show_dob_year' => 1, + 'show_dob_date' => 1, + 'content_show_signature' => 1, + 'receive_admin_email' => 1, + 'email_on_conversation' => 1, + 'is_discouraged' => 0, + 'default_watch_state' => '', + 'alert_optout' => '', + 'enable_rte' => 'watch_email', + 'enable_flash_uploader' => 'watch_email', + ); + + $this->db->prepare("INSERT INTO " . F_PREFIX . "user_option (" . implode(", ", array_keys($data)) . ") VALUES (" . implode(", ", $this->_getDBPrepareKeys($data)) . ")") + ->execute(mergeWithDefault($data, $registrationDefaults)); + + $data = array( + 'user_id' => $user_id, + 'allow_view_profile' => 'everyone', + 'allow_post_profile' => 'everyone', + 'allow_send_personal_conversation' => 'everyone', + 'allow_view_identities' => 'everyone', + 'allow_receive_news_feed' => 'everyone', + ); + + $this->db->prepare("INSERT INTO " . F_PREFIX . "user_privacy (" . implode(", ", array_keys($data)) . ") VALUES (" . implode(", ", $this->_getDBPrepareKeys($data)) . ")") + ->execute(mergeWithDefault($data, $registrationDefaults)); + + $remember_key = substr(sha1(time() . uniqid()), 0, 40); + $this->db->prepare("INSERT INTO " . F_PREFIX . "user_authenticate (user_id, scheme_class, data, remember_key) VALUES (?, ?, ?, ?)") + ->execute(array( + $user_id, + empty($_POST['password1'])? + 'XenForo_Authentication_vBulletin': + 'XenForo_Authentication_Core12', + empty($_POST['password1'])? + serialize(array('hash' => md5($passwordMD5), 'salt' => '')): + serialize(array('hash' => $this->passwordGenerator->HashPassword($this->_convert_encoding($_POST['password1'])))), + $remember_key + )); + + $this->doLogin($user_id, $remember_key, time()); + + return false; + } + + public function updateMember($member, $land, $info) + { + if (!$this->config['allow_module'] || !$this->config['allow_reg']) { + return false; + } + + $user = $this->findXenUser($member['name'], $member['email']); + if (!$user) { + return true; + } + + $data = array( + 'location' => $this->_convert_encoding(strip_tags($land)), + 'about' => $this->_convert_encoding(strip_tags($info)), + 'user_id' => $user->user_id + ); + + $this->db->prepare("UPDATE " . F_PREFIX . "user_profile SET location = :location, about = :about WHERE user_id = :user_id LIMIT 1") + ->execute($data); + + return false; + } + + public function updateProfile($member, $email, $password, $land, $info) + { + if (!$this->config['allow_module'] || !$this->config['allow_profile']) { + return false; + } + + if (!$user = $this->findXenUser($member['name'], $member['email'])) { + return true; + } + + $sign = strip_tags($this->_init_parse()->process($_POST['signature'])); + + $ProfileData = array( + 'location' => $this->_convert_encoding(strip_tags($land)), + 'about' => $this->_convert_encoding(strip_tags($info)), + 'signature' => $this->_convert_encoding($sign) + ); + + $this->db->prepare("UPDATE " . F_PREFIX . "user_profile SET " . implode(", ", $this->_getDBPrepareKeysForUpdate($ProfileData)) . " WHERE user_id=:user_id") + ->execute(array_merge($ProfileData, array('user_id' => $user->user_id))); + + if ($email != $member['email']) { + $this->db->prepare("UPDATE " . F_PREFIX . "user SET email=? WHERE user_id=?") + ->execute(array($this->_convert_encoding($email), $user->user_id)); + } + + if (strlen(trim($password)) > 0) { + $this->db->prepare("UPDATE " . F_PREFIX . "user_authenticate SET scheme_class=?, data=? WHERE user_id=?") + ->execute(array( + 'XenForo_Authentication_Core12', + serialize(array( + 'hash' => $this->passwordGenerator->HashPassword($this->_convert_encoding($password)) + )), + $user->user_id + )); + } + + return false; + } + + public function lostPassword($member, $new_pass) + { + if (!$this->config['allow_module'] || !$this->config['allow_lostpass']) { + return false; + } + + if (!$user = $this->findXenUser($member['name'], $member['email'])) { + return true; + } + + $this->db->prepare("UPDATE " . F_PREFIX . "user_authenticate SET scheme_class=?, data=? WHERE user_id=?") + ->execute(array( + 'XenForo_Authentication_Core12', + serialize(array( + 'hash' => $this->passwordGenerator->HashPassword($this->_convert_encoding($new_pass)) + )), + $user->user_id + )); + + return false; + } + + public function lastTopics(dle_template $tpl) + { + if (!$this->config['allow_forum_block'] || !$this->config['allow_module']) { + return ''; + } + + if ((int)$this->config['block_cache_time']) { + $cache = dle_cache('xen_block_cache_time'); + if ($cache) { + $cache = unserialize($cache); + if (!empty($cache['time']) && $cache['time'] > (time() - $this->config['block_cache_time'])) { + return $cache['data']; + } + } + } + + $forum_id = ""; + if ($this->config['bad_forum_for_block'] && !$this->config['good_forum_for_block']) + { + $forum_bad = explode(",", $this->config['bad_forum_for_block']); + $forum_id = " AND t.node_id NOT IN('". implode("','", $forum_bad) ."')"; + } + elseif (!$this->config['bad_forum_for_block'] && $this->config['good_forum_for_block']) + { + $forum_good = explode(",", $this->config['good_forum_for_block']); + $forum_id = " AND t.node_id IN('". implode("','", $forum_good) ."')"; + } + + if (!(int)$this->config['count_post']) { + $this->config['count_post'] = 10; + } + + $sth = $this->db->query('SELECT t.title, t.thread_id, t.last_post_date, t.reply_count, t.view_count, f.title as forum_title, t.node_id, t.last_post_username, t.last_post_user_id + FROM ' . F_PREFIX . 'thread AS t + LEFT JOIN ' . F_PREFIX . 'node AS f + ON f.node_id = t.node_id + WHERE discussion_state="visible"' . $forum_id . ' + ORDER BY t.last_post_date DESC + LIMIT 0, ' . intval($this->config['count_post'])); + + + $forum_url = rtrim($this->options['boardUrl'], "/") . "/"; + + if (!$this->config['block_rewrite_url']) { + $forum_url .= "index.php?"; + } + + $tpl->load_template('block_forum_posts.tpl'); + preg_match("'\[row\](.*?)\[/row\]'si", $tpl->copy_template, $matches); + + $block_content = ''; + while ($row = $sth->fetch(PDO::FETCH_ASSOC)) + { + $short_name = $title = $this->_convert_encoding($row["title"], true); + $row['last_post_username'] = $this->_convert_encoding($row['last_post_username'], true); + + if ( + !empty($this->config['length_name']) && + dle_strlen($title, $this->DLEConfig['charset']) > $this->config['length_name'] + ) + { + $short_name = dle_substr($title, 0, $this->config['length_name'], $this->DLEConfig['charset']) . " ..."; + } + + switch (date("d.m.Y", $row["last_post_date"])) + { + case date("d.m.Y"): + $date = date($this->lang['today_in'] . "H:i", $row["last_post_date"]); + break; + + case date("d.m.Y", time() - 86400): + $date = date($this->lang['yesterday_in'] . "H:i", $row["last_post_date"]); + break; + + default: + $date = date("d.m.Y H:i", $row["last_post_date"]); + } + + $replace = array( + '{user}' => $this->_convert_encoding($row['last_post_username'], true), + '{user_url}' => $forum_url . "members/" . $this->getTitleForUrl($row['last_post_username']) ."." . $row['last_post_user_id'] . "/", + '{reply_count}' => $row["reply_count"], + '{view_count}' => $row["view_count"], + '{full_name}' => $title, + '{post_url}' => $forum_url . "threads/" . $this->getTitleForUrl($row['title']) ."." . $row["thread_id"] . "/", + '{shot_name_post}' => $short_name, + '{forum_name}' => $this->_convert_encoding($row['forum_title'], true), + '{forum_url}' => $forum_url . "forums/" . $this->getTitleForUrl($row['forum_title']) ."." . $row["node_id"] . "/", + '{date}' => $date + ); + + $block_content .= strtr($matches[1], $replace); + } + $tpl->set_block("'\[row\](.*?)\[/row\]'si", $block_content); + $tpl->compile('block_forum_posts'); + $tpl->clear(); + + if ((int)$this->config['block_cache_time']) + { + create_cache('xen_block_cache_time', serialize(array('time' => time(), 'data' => $tpl->result['block_forum_posts']))); + } + + return $tpl->result['block_forum_posts']; + } + + protected function doLogin($user_id, $remember_key, $last_activity) + { + $domain = $this->_getCookieDomain(); + if (empty($_POST['login_not_save'])) { + $value = intval($user_id) . ',' . sha1($this->XenConfig['globalSalt'] . $remember_key); + setcookie($this->XenConfig['cookie']['prefix'] . 'user', $value, time() + 30 * 86400, $this->XenConfig['cookie']['path'], $domain, false, true); + } + + $sessionCookieName = $this->XenConfig['cookie']['prefix'] . "session"; + + if (!empty($_COOKIE[$sessionCookieName]) && strlen($_COOKIE[$sessionCookieName]) == 32) { + $this->db->prepare("DELETE FROM " . F_PREFIX . "session WHERE session_id=?")->execute(array($_COOKIE[$sessionCookieName])); + } + + $sessionId = md5(uniqid(time())); + $sessionData = array( + 'sessionStart' => time(), + 'user_id' => $user_id, + 'ip' => $this->convertIpStringToBinary($_SERVER['REMOTE_ADDR']), + 'previousActivity' => $last_activity + ); + + if (!empty($_SERVER['HTTP_USER_AGENT'])) + { + $sessionData['userAgent'] = $_SERVER['HTTP_USER_AGENT']; + $sessionData['robotId'] = ''; + } + + if (!empty($_SERVER['HTTP_REFERER'])) + { + $sessionData['referer'] = $_SERVER['HTTP_REFERER']; + $sessionData['fromSearch'] = ''; + } + + setcookie($sessionCookieName, $sessionId, false, $this->XenConfig['cookie']['path'], $domain, false, true); + + $this->db->prepare("REPLACE INTO " . F_PREFIX . "session (session_id, session_data, expiry_date) VALUES (?, ?, ?)")->execute(array( + $sessionId, + serialize($sessionData), + time() + 3600 + )); + } + + protected function getTitleForUrl($title) + { + $title = strval($title); + + $title = strtr( + $title, + '`!"$%^&*()-+={}[]<>;:@#~,./?|' . "\r\n\t\\", + ' ' . ' ' + ); + $title = strtr($title, array('"' => '', "'" => '')); + + $title = preg_replace('/[ ]+/', '-', trim($title)); + $title = strtr($title, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'); + + return urlencode($title); + } + + protected function _getDBPrepareKeys(array $array) + { + $return = array(); + foreach (array_keys($array) as $key) + { + $return[] = ":" . $key; + } + + return $return; + } + + protected function _getDBPrepareKeysForUpdate(array $array) + { + $return = array(); + foreach (array_keys($array) as $key) + { + $return[] = "`{$key}`=:" . $key; + } + + return $return; + } + + protected function _getCookieDomain() + { + if (!empty($this->XenConfig['cookie']['domain'])) + { + return $this->XenConfig['cookie']['domain']; + } + else + { + return "." . $this->_clean_url($this->options['boardUrl']); + } + } + + protected function _clean_url($url) + { + if (!$url) + { + return false; + } + + $url = str_replace("http://", "", $url); + if (strtolower(substr($url, 0, 4)) == 'www.') $url = substr($url, 4); + $url = explode('/', $url); + $url = reset($url); + $url = explode(':', $url); + $url = reset($url); + + return $url; + } + + protected function _convert_encoding($text, $revert = false) + { + if (strtoupper($this->DLEConfig['charset']) == strtoupper(F_CHARSET)) { + return $text; + } + + if (is_array($text)) + { + foreach($text as $k => $t) + { + $text[$k] = $this->_convert_encoding($t); + } + } + else + { + if ($revert) { + $text = iconv(F_CHARSET, $this->DLEConfig['charset'], $text); + } + else { + $text = iconv($this->DLEConfig['charset'], F_CHARSET, $text); + } + } + + return $text; + } + + protected function __get($varname) + { + switch ($varname) + { + case 'options': + return $this->_getConfigForum(); + break; + + case 'passwordGenerator': + return $this->_getPasswordGenerator(); + break; + + case 'db': + return $this->_getDb(); + break; + + case 'dleAPI': + return $this->getDLEAPI(); + break; + + default: + throw new Exception('Property "' . $varname . '"not found'); + break; + } + } + + public function __desctruct() + { + + } +} + + +?> \ No newline at end of file diff --git a/DLE_uploads_utf-8/engine/modules/XenIntegration/last_topic_block.php b/DLE_uploads_utf-8/engine/modules/XenIntegration/last_topic_block.php new file mode 100644 index 0000000..3aba210 --- /dev/null +++ b/DLE_uploads_utf-8/engine/modules/XenIntegration/last_topic_block.php @@ -0,0 +1,3 @@ +lastTopics($tpl); diff --git a/DLE_uploads_utf-8/engine/modules/XenIntegration/xen_default_config.php b/DLE_uploads_utf-8/engine/modules/XenIntegration/xen_default_config.php new file mode 100644 index 0000000..4e2e7ef --- /dev/null +++ b/DLE_uploads_utf-8/engine/modules/XenIntegration/xen_default_config.php @@ -0,0 +1,58 @@ + array( + 'adapter' => 'mysqli', + 'host' => 'localhost', + 'port' => '3306', + 'username' => '', + 'password' => '', + 'dbname' => '', + 'adapterNamespace' => 'Zend_Db_Adapter' + ), + 'cache' => array( + 'enabled' => false, + 'cacheSessions' => false, + 'frontend' => 'core', + 'frontendOptions' => array( + 'caching' => true, + 'cache_id_prefix' => 'xf_' + ), + 'backend' => 'file', + 'backendOptions' => array( + 'file_name_prefix' => 'xf_' + ) + ), + 'debug' => false, + 'enableListeners' => true, + 'development' => array( + 'directory' => '', // relative to the configuration directory + 'default_addon' => '' + ), + 'superAdmins' => '1', + 'globalSalt' => 'ae5a99d00f58945a30b1ce054a1e89ef', + 'jsVersion' => '', + 'cookie' => array( + 'prefix' => 'xf_', + 'path' => '/', + 'domain' => '' + ), + 'enableMail' => true, + 'enableMailQueue' => true, + 'internalDataPath' => 'internal_data', + 'externalDataPath' => 'data', + 'externalDataUrl' => 'data', + 'javaScriptUrl' => 'js', + 'checkVersion' => true, + 'enableGzip' => true, + 'enableContentLength' => true, + 'adminLogLength' => 60, // number of days to keep admin log entries + 'chmodWritableValue' => 0, + 'rebuildMaxExecution' => 8, + 'passwordIterations' => 10, + 'enableTemplateModificationCallbacks' => true, + 'enableClickjackingProtection' => true, + 'maxImageResizePixelCount' => 20000000 +); + +?> \ No newline at end of file diff --git a/DLE_uploads_utf-8/language/Russian/dle_xen.lng b/DLE_uploads_utf-8/language/Russian/dle_xen.lng new file mode 100644 index 0000000..a2f5db4 --- /dev/null +++ b/DLE_uploads_utf-8/language/Russian/dle_xen.lng @@ -0,0 +1,6 @@ + 'Сегодня в ', + 'yesterday_in' => 'Вчера в ', +); \ No newline at end of file diff --git a/DLE_uploads_windows-1251/engine/data/dle_xen_conf.php b/DLE_uploads_windows-1251/engine/data/dle_xen_conf.php new file mode 100644 index 0000000..861fb90 --- /dev/null +++ b/DLE_uploads_windows-1251/engine/data/dle_xen_conf.php @@ -0,0 +1,21 @@ + 1, // включить интеграцию + 'allow_reg' => 1, // включить общую регистрацию + 'allow_login' => 1, // включить общую авторизацию + 'allow_logout' => 1, // включить общий выход + 'allow_profile' => 1, // включить изменение профеля + 'allow_lostpass' => 1, // включить восстановление пароля + 'allow_forum_block' => 1, // включить блок последних сообщений с форума + 'block_cache_time' => 600, //Время в секундах для кеширование блока последних сообщений, 0 - без кеширования + 'bad_forum_for_block' => '', //IDs форумов которые не нужно показывать в блоке, указываются через запятую, если не заполненно показываются темы со всех форумов + 'good_forum_for_block' => '', //IDs форумов которые нужно показывать в блоке, указываются через запятую (не работает если заполнена предыдущая опция + 'count_post' => 10, // количество сообщений в блоке + 'block_rewrite_url' => true, // использовать или нет ЧПУ в ссылках + 'length_name' => 0, // максимальнаядлина имени, остальные символы обрезаются, 0 - не обрезать + + + +); \ No newline at end of file diff --git a/DLE_uploads_windows-1251/engine/modules/XenIntegration/PasswordHash.php b/DLE_uploads_windows-1251/engine/modules/XenIntegration/PasswordHash.php new file mode 100644 index 0000000..4ffebb2 --- /dev/null +++ b/DLE_uploads_windows-1251/engine/modules/XenIntegration/PasswordHash.php @@ -0,0 +1,267 @@ + in 2004-2006 and placed in +# the public domain. Revised in subsequent years, still public domain. +# +# There's absolutely no warranty. +# +# The homepage URL for this framework is: +# +# http://www.openwall.com/phpass/ +# +# Please be sure to update the Version line if you edit this file in any way. +# It is suggested that you leave the main version number intact, but indicate +# your project name (after the slash) and add your own revision information. +# +# Please do not change the "private" password hashing method implemented in +# here, thereby making your hashes incompatible. However, if you must, please +# change the hash type identifier (the "$P$") to something different. +# +# Obviously, since this code is in the public domain, the above are not +# requirements (there can be none), but merely suggestions. +# +class XenForo_PasswordHash { + var $itoa64; + var $iteration_count_log2; + var $portable_hashes; + var $random_state; + + public function __construct($iteration_count_log2, $portable_hashes) + { + $this->itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; + + if ($iteration_count_log2 < 4 || $iteration_count_log2 > 31) + $iteration_count_log2 = 8; + $this->iteration_count_log2 = $iteration_count_log2; + + $this->portable_hashes = $portable_hashes; + + $this->random_state = microtime(); + if (function_exists('getmypid')) + $this->random_state .= getmypid(); + } + + function get_random_bytes($count) + { + $output = ''; + + if (function_exists('openssl_random_pseudo_bytes') + && (substr(PHP_OS, 0, 3) != 'WIN' || version_compare(phpversion(), '5.3.4', '>=')) + ) + { + $output = openssl_random_pseudo_bytes($count); + } + else if (function_exists('mcrypt_create_iv') && version_compare(phpversion(), '5.3.0', '>=')) + { + $output = mcrypt_create_iv($count, MCRYPT_DEV_URANDOM); + } + else if (@is_readable('/dev/urandom') && + ($fh = @fopen('/dev/urandom', 'rb'))) { + $output = fread($fh, $count); + fclose($fh); + } + + if (strlen($output) < $count) { + $output = ''; + for ($i = 0; $i < $count; $i += 16) { + $this->random_state = + md5(microtime() . $this->random_state); + $output .= + pack('H*', md5($this->random_state)); + } + $output = substr($output, 0, $count); + } + + return $output; + } + + function encode64($input, $count) + { + $output = ''; + $i = 0; + do { + $value = ord($input[$i++]); + $output .= $this->itoa64[$value & 0x3f]; + if ($i < $count) + $value |= ord($input[$i]) << 8; + $output .= $this->itoa64[($value >> 6) & 0x3f]; + if ($i++ >= $count) + break; + if ($i < $count) + $value |= ord($input[$i]) << 16; + $output .= $this->itoa64[($value >> 12) & 0x3f]; + if ($i++ >= $count) + break; + $output .= $this->itoa64[($value >> 18) & 0x3f]; + } while ($i < $count); + + return $output; + } + + protected function gensalt_private($input) + { + $output = '$P$'; + $output .= $this->itoa64[min($this->iteration_count_log2 + + ((PHP_VERSION >= '5') ? 5 : 3), 30)]; + $output .= $this->encode64($input, 6); + + return $output; + } + + protected function crypt_private($password, $setting) + { + $output = '*0'; + if (substr($setting, 0, 2) == $output) + $output = '*1'; + + $id = substr($setting, 0, 3); + # We use "$P$", phpBB3 uses "$H$" for the same thing + if ($id != '$P$' && $id != '$H$') + return $output; + + $count_log2 = strpos($this->itoa64, $setting[3]); + if ($count_log2 < 7 || $count_log2 > 30) + return $output; + + $count = 1 << $count_log2; + + $salt = substr($setting, 4, 8); + if (strlen($salt) != 8) + return $output; + + # We're kind of forced to use MD5 here since it's the only + # cryptographic primitive available in all versions of PHP + # currently in use. To implement our own low-level crypto + # in PHP would result in much worse performance and + # consequently in lower iteration counts and hashes that are + # quicker to crack (by non-PHP code). + if (PHP_VERSION >= '5') { + $hash = md5($salt . $password, TRUE); + do { + $hash = md5($hash . $password, TRUE); + } while (--$count); + } else { + $hash = pack('H*', md5($salt . $password)); + do { + $hash = pack('H*', md5($hash . $password)); + } while (--$count); + } + + $output = substr($setting, 0, 12); + $output .= $this->encode64($hash, 16); + + return $output; + } + + function gensalt_extended($input) + { + $count_log2 = min($this->iteration_count_log2 + 8, 24); + # This should be odd to not reveal weak DES keys, and the + # maximum valid value is (2**24 - 1) which is odd anyway. + $count = (1 << $count_log2) - 1; + + $output = '_'; + $output .= $this->itoa64[$count & 0x3f]; + $output .= $this->itoa64[($count >> 6) & 0x3f]; + $output .= $this->itoa64[($count >> 12) & 0x3f]; + $output .= $this->itoa64[($count >> 18) & 0x3f]; + + $output .= $this->encode64($input, 3); + + return $output; + } + + function gensalt_blowfish($input) + { + # This one needs to use a different order of characters and a + # different encoding scheme from the one in encode64() above. + # We care because the last character in our encoded string will + # only represent 2 bits. While two known implementations of + # bcrypt will happily accept and correct a salt string which + # has the 4 unused bits set to non-zero, we do not want to take + # chances and we also do not want to waste an additional byte + # of entropy. + $itoa64 = './ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; + + $output = '$2a$'; + $output .= chr(ord('0') + $this->iteration_count_log2 / 10); + $output .= chr(ord('0') + $this->iteration_count_log2 % 10); + $output .= '$'; + + $i = 0; + do { + $c1 = ord($input[$i++]); + $output .= $itoa64[$c1 >> 2]; + $c1 = ($c1 & 0x03) << 4; + if ($i >= 16) { + $output .= $itoa64[$c1]; + break; + } + + $c2 = ord($input[$i++]); + $c1 |= $c2 >> 4; + $output .= $itoa64[$c1]; + $c1 = ($c2 & 0x0f) << 2; + + $c2 = ord($input[$i++]); + $c1 |= $c2 >> 6; + $output .= $itoa64[$c1]; + $output .= $itoa64[$c2 & 0x3f]; + } while (1); + + return $output; + } + + function HashPassword($password) + { + $random = ''; + + if (CRYPT_BLOWFISH == 1 && !$this->portable_hashes) { + $random = $this->get_random_bytes(16); + $hash = + crypt($password, $this->gensalt_blowfish($random)); + if (strlen($hash) == 60) + return $hash; + } + + if (CRYPT_EXT_DES == 1 && !$this->portable_hashes) { + if (strlen($random) < 3) + $random = $this->get_random_bytes(3); + $hash = + crypt($password, $this->gensalt_extended($random)); + if (strlen($hash) == 20) + return $hash; + } + + if (strlen($random) < 6) + $random = $this->get_random_bytes(6); + $hash = + $this->crypt_private($password, + $this->gensalt_private($random)); + if (strlen($hash) == 34) + return $hash; + + # Returning '*' on error is safe here, but would _not_ be safe + # in a crypt(3)-like function used _both_ for generating new + # hashes and for validating passwords against existing hashes. + return '*'; + } + + function CheckPassword($password, $stored_hash) + { + $hash = $this->crypt_private($password, $stored_hash); + if ($hash[0] == '*') + $hash = crypt($password, $stored_hash); + + return $hash == $stored_hash; + } + + public function reverseItoA64($char) + { + return strpos($this->itoa64, $char); + } +} \ No newline at end of file diff --git a/DLE_uploads_windows-1251/engine/modules/XenIntegration/XenIntegration.php b/DLE_uploads_windows-1251/engine/modules/XenIntegration/XenIntegration.php new file mode 100644 index 0000000..47893e6 --- /dev/null +++ b/DLE_uploads_windows-1251/engine/modules/XenIntegration/XenIntegration.php @@ -0,0 +1,932 @@ +displayAndExit( + " DLE + XenForo.
+ http://forum.kaliostro.net/
+ You are not using licensed version of the module DLE + XenForo.
+ For information, visit the forum http://forum.kaliostro.net/"); + } + + $forumConfigFile = dirname(__FILE__) . "/config.php"; + if (!file_exists($forumConfigFile)) { + $this->displayAndExit(" %s %s", 'library/config.php', $forumConfigFile); + } + + $config = require dirname(__FILE__) . "/xen_default_config.php"; + require $forumConfigFile; + $this->XenConfig = $config; + + if (empty($this->XenConfig['globalSalt'])) { + $this->displayAndExit(" globalSalt %s", $forumConfigFile); + } + + $this->DLEConfig = $GLOBALS['config']; + + define('F_PREFIX', 'xf_'); + + if (!defined('F_CHARSET')) + { + define('F_CHARSET', 'UTF-8'); + } + + $configFile = ENGINE_DIR . "/data/dle_xen_conf.php"; + if (!file_exists($configFile)) + { + $this->displayAndExit(" . "); + } + $this->config = require $configFile; + + $this->lang = require ROOT_DIR . '/language/Russian/dle_xen.lng'; + $lngFile = ROOT_DIR . '/language/' . $GLOBALS['config']['langs'] . '/dle_xen.lng'; + if (file_exists($lngFile)) { + $this->lang = array_merge($this->lang, include $lngFile); + } + } + + protected function displayAndExit($text) + { + $params = func_get_args(); + array_shift($params); + + @header("Content-type: text/html; charset=UTF-8"); + call_user_func_array('printf', array($text) + $params); + exit(); + } + + /** + * + * @return self + */ + static public function getInstance() + { + if (!self::$_instance) + { + self::$_instance = new self(); + } + + return self::$_instance; + } + + /** + * + * @staticvar PDO $dbh + * @return \PDO + */ + protected function _getDb() + { + static $dbh; + + if (!$dbh) + { + $dbh = new PDO("mysql:host={$this->XenConfig['db']['host']};port={$this->XenConfig['db']['port']};dbname=" . $this->XenConfig['db']['dbname'], $this->XenConfig['db']['username'], $this->XenConfig['db']['password']); + $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT); + $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); + $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + + $dbh->exec('SET SQL_MODE=""'); + $dbh->exec('SET NAMES `utf8`'); + } + + return $dbh; + } + + protected function _getConfigForum() + { + static $config = array(); + + if ($config) + { + return $config; + } + + if (!function_exists("dle_cache") || !($cache = dle_cache("config_xen"))) + { + $sth = $this->_getdb()->query("SELECT + option_id, + option_value, + data_type + FROM xf_option WHERE option_id IN ('boardUrl', 'registrationDefaults', 'guestTimeZone')"); + + while ($row = $sth->fetch(PDO::FETCH_ASSOC)) + { + if ($row['data_type'] == "array"){ + $config[$row['option_id']] = unserialize($row['option_value']); + } + else { + $config[$row['option_id']] = $row['option_value']; + } + } + + if (function_exists("create_cache")) + { + create_cache("config_xen", serialize($config)); + } + + return $config; + } + elseif ($cache) + { + $config = unserialize($cache); + } + + return $config; + } + + protected function _init_parse() + { + if (!$this->_parse) + { + if (empty($GLOBALS['parse']) || !($GLOBALS['parse'] instanceof ParseFilter)) + { + if (!class_exists('ParseFilter')) + { + require_once(ENGINE_DIR . "/classes/parse.class.php"); + } + $this->_parse = new ParseFilter(); + } + else + { + $this->_parse = $GLOBALS['parse']; + } + } + + return $this->_parse; + } + + protected function _getPasswordGenerator() + { + static $password; + + if (!$password) { + require_once dirname(__FILE__) . "/PasswordHash.php"; + $password = new XenForo_PasswordHash($this->XenConfig['passwordIterations'], false); + } + + return $password; + } + + protected function getDLEAPI() + { + global $config, $db; + static $dle_api; + + if (!$dle_api) { + + if (!empty($GLOBALS['dle_api'])) { + $dle_api = $GLOBALS['dle_api']; + } + else { + require_once ENGINE_DIR . "/api/api.class.php"; + } + } + + return $dle_api; + } + + protected function convertIpStringToBinary($ip) + { + $originalIp = $ip; + $ip = trim($ip); + + if (strpos($ip, ':') !== false) + { + // IPv6 + if (preg_match('#:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$#', $ip, $match)) + { + // embedded IPv4 + $long = ip2long($match[1]); + if (!$long) + { + return false; + } + + $hex = str_pad(dechex($long), 8, '0', STR_PAD_LEFT); + $v4chunks = str_split($hex, 4); + $ip = str_replace($match[0], ":$v4chunks[0]:$v4chunks[1]", $ip); + } + + if (strpos($ip, '::') !== false) + { + if (substr_count($ip, '::') > 1) + { + // ambiguous + return false; + } + + $delims = substr_count($ip, ':'); + if ($delims > 7) + { + return false; + } + + $ip = str_replace('::', str_repeat(':0', 8 - $delims) . ':', $ip); + if ($ip[0] == ':') + { + $ip = '0' . $ip; + } + } + + $ip = strtolower($ip); + + $parts = explode(':', $ip); + if (count($parts) != 8) + { + return false; + } + + foreach ($parts AS &$part) + { + $len = strlen($part); + if ($len > 4 || preg_match('/[^0-9a-f]/', $part)) + { + return false; + } + + if ($len < 4) + { + $part = str_repeat('0', 4 - $len) . $part; + } + } + + $hex = implode('', $parts); + if (strlen($hex) != 32) + { + return false; + } + + return $this->convertHexToBin($hex); + } + else if (strpos($ip, '.')) + { + // IPv4 + if (!preg_match('#(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})#', $ip, $match)) + { + return false; + } + + $long = ip2long($match[1]); + if (!$long) + { + return false; + } + + return $this->convertHexToBin( + str_pad(dechex($long), 8, '0', STR_PAD_LEFT) + ); + } + else if (strlen($ip) == 4 || strlen($ip) == 16) + { + // already binary encoded + return $ip; + } + else if (is_numeric($originalIp) && $originalIp < pow(2, 32)) + { + // IPv4 as integer + return $this->convertHexToBin( + str_pad(dechex($originalIp), 8, '0', STR_PAD_LEFT) + ); + } + else + { + return false; + } + } + + protected function convertHexToBin($hex) + { + if (function_exists('hex2bin')) + { + return hex2bin($hex); + } + + $len = strlen($hex); + + if ($len % 2) + { + trigger_error('Hexadecimal input string must have an even length', E_USER_WARNING); + } + + if (strspn($hex, '0123456789abcdefABCDEF') != $len) + { + trigger_error('Input string must be hexadecimal string', E_USER_WARNING); + } + + return pack('H*', $hex); + } + + protected function createDLEUser(stdClass $user, $password) + { + /** @var $db \db */ + $db = $GLOBALS['db']; + + $statusCode = $this->dleAPI->external_register( + $this->_convert_encoding($user->username, true), + $password, + $this->_convert_encoding($user->email, true), + $this->DLEConfig['reg_group'] + ); + + if ($statusCode !== 1) { + return false; + } + $user_id = $db->insert_id(); + + $stm = $this->db->prepare("SELECT location, about, signature FROM " . F_PREFIX . "user_profile WHERE user_id=?"); + $stm->execute(array($user->user_id)); + + $profile = $stm->fetchObject(); + + $info = $db->safesql($this->_convert_encoding($profile->about, true)); + $land = $db->safesql($this->_convert_encoding($profile->location, true)); + $signature = $db->safesql($this->_convert_encoding($profile->signature, true)); + + $db->query("UPDATE " . USERPREFIX . "_users SET info='$info', land='$land', signature='$signature', reg_date={$user->register_date}, lastdate={$user->last_activity} WHERE user_id=" . $user_id); + + $GLOBALS['member_id'] = $member_id = $db->super_query("SELECT * FROM " . USERPREFIX . "_users WHERE user_id=" . $user_id); + + set_cookie( "dle_user_id", $member_id['user_id'], 365 ); + set_cookie( "dle_password", $_POST['login_password'], 365 ); + $_SESSION['dle_user_id'] = $member_id['user_id']; + $_SESSION['dle_password'] = $_POST['login_password']; + $_SESSION['member_lasttime'] = $member_id['lastdate']; + + $GLOBALS['is_logged'] = true; + $GLOBALS['tpl']->result['info'] = ''; + + return $member_id; + } + + public function findXenUser($username, $email, $password = null) + { + $email = $this->_convert_encoding($email); + $username = $this->_convert_encoding($username); + $password = $this->_convert_encoding($password); + + $sth = $this->_getDb()->prepare("SELECT * FROM " . F_PREFIX . "user_authenticate a + LEFT JOIN " . F_PREFIX ."user u + ON u.user_id=a.user_id + WHERE u.username=? AND u.email=?"); + + $sth->execute(array($username, $email)); + $user = $sth->fetchObject(); + + if ($user) + { + $authData = unserialize($user->data); + if (!$password || $this->passwordGenerator->CheckPassword($password, $authData['hash'])) { + return $user; + } + } + + return false; + } + + #region Public function + + public function login($member_id, $force = false) + { + if (!$this->config['allow_module'] || !$this->config['allow_login']) + { + return false; + } + + if(!$force && !(isset($_POST['login']) AND $_POST['login_name'] AND $_POST['login_password'] AND $_POST['login'] == "submit")) { + return false; + } + + if (empty($member_id['user_id'])) { + $sth = $this->_getDb()->prepare("SELECT * FROM " . F_PREFIX . "user_authenticate a + LEFT JOIN " . F_PREFIX ."user u + ON u.user_id=a.user_id + WHERE u." . ($this->DLEConfig['auth_metod']?"email":"username") . "=?"); + + $sth->execute(array($_POST['login_name'])); + $auth = $sth->fetchObject(); + + if (!$auth) { + return true; + } + $authData = unserialize($auth->data); + if (!$this->passwordGenerator->CheckPassword($this->_convert_encoding($_REQUEST['login_password']), $authData['hash'])) { + return true; + } + + if (!($member_id = $this->createDLEUser($auth, $_REQUEST['login_password']))) { + return true; + } + } + else { + $auth = $this->findXenUser($member_id['name'], $member_id['email'], $_REQUEST['login_password']); + } + + if (!$auth) { + return true; + } + + $this->doLogin($auth->user_id, $auth->remember_key, $auth->last_activity); + + return false; + } + + public function logout() + { + if (!$this->config['allow_module'] || !$this->config['allow_logout']) + { + return false; + } + + $domain = $this->_getCookieDomain(); + $sessionCookieName = $this->XenConfig['cookie']['prefix'] . "session"; + + setcookie($sessionCookieName, "", time() - 31536000, $this->XenConfig['cookie']['path'], $domain); + setcookie($this->XenConfig['cookie']['prefix'] . "user", "", time() - 31536000, $this->XenConfig['cookie']['path'], $domain); + + return false; + } + + public function createMember($name, $passwordMD5, $email) + { + if (!$this->config['allow_module'] || !$this->config['allow_reg']) { + return false; + } + + $username = $this->_convert_encoding($name); + $email = $this->_convert_encoding($email); + + $stm = $this->db->prepare("SELECT * FROM " . F_PREFIX . "user WHERE username=? OR email=?"); + $stm->execute(array($username, $email)); + + if ($stm->rowCount()) { + return true; + } + + $registrationDefaults = $this->options['registrationDefaults']; + function mergeWithDefault($data, $registrationDefaults) { + return array_merge($data, array_intersect_key($registrationDefaults, $data)); + } + + $data = array( + 'username' => $username, + 'email' => $email, + 'gender' => '', + 'language_id' => 0, + 'style_id' => 0, + 'timezone' => $this->options['guestTimeZone'], + 'user_group_id' => 2, + 'display_style_group_id' => 2, + 'permission_combination_id' => 2, + 'register_date' => time(), + 'last_activity' => time(), + 'visible' => 1, + ); + + $this->db->prepare("INSERT INTO " . F_PREFIX . "user (" . implode(", ", array_keys($data)) . ") VALUES (" . implode(", ", $this->_getDBPrepareKeys($data)) . ")") + ->execute(mergeWithDefault($data, $registrationDefaults)); + + $user_id = $this->db->lastInsertId(); + + $this->db->prepare("INSERT INTO " . F_PREFIX . "user_profile (user_id, csrf_token) VALUES (?, ?)") + ->execute(array($user_id, substr(sha1(time() . uniqid()), 0, 40))); + + $data = array( + 'user_id' => $user_id, + 'show_dob_year' => 1, + 'show_dob_date' => 1, + 'content_show_signature' => 1, + 'receive_admin_email' => 1, + 'email_on_conversation' => 1, + 'is_discouraged' => 0, + 'default_watch_state' => '', + 'alert_optout' => '', + 'enable_rte' => 'watch_email', + 'enable_flash_uploader' => 'watch_email', + ); + + $this->db->prepare("INSERT INTO " . F_PREFIX . "user_option (" . implode(", ", array_keys($data)) . ") VALUES (" . implode(", ", $this->_getDBPrepareKeys($data)) . ")") + ->execute(mergeWithDefault($data, $registrationDefaults)); + + $data = array( + 'user_id' => $user_id, + 'allow_view_profile' => 'everyone', + 'allow_post_profile' => 'everyone', + 'allow_send_personal_conversation' => 'everyone', + 'allow_view_identities' => 'everyone', + 'allow_receive_news_feed' => 'everyone', + ); + + $this->db->prepare("INSERT INTO " . F_PREFIX . "user_privacy (" . implode(", ", array_keys($data)) . ") VALUES (" . implode(", ", $this->_getDBPrepareKeys($data)) . ")") + ->execute(mergeWithDefault($data, $registrationDefaults)); + + $remember_key = substr(sha1(time() . uniqid()), 0, 40); + $this->db->prepare("INSERT INTO " . F_PREFIX . "user_authenticate (user_id, scheme_class, data, remember_key) VALUES (?, ?, ?, ?)") + ->execute(array( + $user_id, + empty($_POST['password1'])? + 'XenForo_Authentication_vBulletin': + 'XenForo_Authentication_Core12', + empty($_POST['password1'])? + serialize(array('hash' => md5($passwordMD5), 'salt' => '')): + serialize(array('hash' => $this->passwordGenerator->HashPassword($this->_convert_encoding($_POST['password1'])))), + $remember_key + )); + + $this->doLogin($user_id, $remember_key, time()); + + return false; + } + + public function updateMember($member, $land, $info) + { + if (!$this->config['allow_module'] || !$this->config['allow_reg']) { + return false; + } + + $user = $this->findXenUser($member['name'], $member['email']); + if (!$user) { + return true; + } + + $data = array( + 'location' => $this->_convert_encoding(strip_tags($land)), + 'about' => $this->_convert_encoding(strip_tags($info)), + 'user_id' => $user->user_id + ); + + $this->db->prepare("UPDATE " . F_PREFIX . "user_profile SET location = :location, about = :about WHERE user_id = :user_id LIMIT 1") + ->execute($data); + + return false; + } + + public function updateProfile($member, $email, $password, $land, $info) + { + if (!$this->config['allow_module'] || !$this->config['allow_profile']) { + return false; + } + + if (!$user = $this->findXenUser($member['name'], $member['email'])) { + return true; + } + + $sign = strip_tags($this->_init_parse()->process($_POST['signature'])); + + $ProfileData = array( + 'location' => $this->_convert_encoding(strip_tags($land)), + 'about' => $this->_convert_encoding(strip_tags($info)), + 'signature' => $this->_convert_encoding($sign) + ); + + $this->db->prepare("UPDATE " . F_PREFIX . "user_profile SET " . implode(", ", $this->_getDBPrepareKeysForUpdate($ProfileData)) . " WHERE user_id=:user_id") + ->execute(array_merge($ProfileData, array('user_id' => $user->user_id))); + + if ($email != $member['email']) { + $this->db->prepare("UPDATE " . F_PREFIX . "user SET email=? WHERE user_id=?") + ->execute(array($this->_convert_encoding($email), $user->user_id)); + } + + if (strlen(trim($password)) > 0) { + $this->db->prepare("UPDATE " . F_PREFIX . "user_authenticate SET scheme_class=?, data=? WHERE user_id=?") + ->execute(array( + 'XenForo_Authentication_Core12', + serialize(array( + 'hash' => $this->passwordGenerator->HashPassword($this->_convert_encoding($password)) + )), + $user->user_id + )); + } + + return false; + } + + public function lostPassword($member, $new_pass) + { + if (!$this->config['allow_module'] || !$this->config['allow_lostpass']) { + return false; + } + + if (!$user = $this->findXenUser($member['name'], $member['email'])) { + return true; + } + + $this->db->prepare("UPDATE " . F_PREFIX . "user_authenticate SET scheme_class=?, data=? WHERE user_id=?") + ->execute(array( + 'XenForo_Authentication_Core12', + serialize(array( + 'hash' => $this->passwordGenerator->HashPassword($this->_convert_encoding($new_pass)) + )), + $user->user_id + )); + + return false; + } + + public function lastTopics(dle_template $tpl) + { + if (!$this->config['allow_forum_block'] || !$this->config['allow_module']) { + return ''; + } + + if ((int)$this->config['block_cache_time']) { + $cache = dle_cache('xen_block_cache_time'); + if ($cache) { + $cache = unserialize($cache); + if (!empty($cache['time']) && $cache['time'] > (time() - $this->config['block_cache_time'])) { + return $cache['data']; + } + } + } + + $forum_id = ""; + if ($this->config['bad_forum_for_block'] && !$this->config['good_forum_for_block']) + { + $forum_bad = explode(",", $this->config['bad_forum_for_block']); + $forum_id = " AND t.node_id NOT IN('". implode("','", $forum_bad) ."')"; + } + elseif (!$this->config['bad_forum_for_block'] && $this->config['good_forum_for_block']) + { + $forum_good = explode(",", $this->config['good_forum_for_block']); + $forum_id = " AND t.node_id IN('". implode("','", $forum_good) ."')"; + } + + if (!(int)$this->config['count_post']) { + $this->config['count_post'] = 10; + } + + $sth = $this->db->query('SELECT t.title, t.thread_id, t.last_post_date, t.reply_count, t.view_count, f.title as forum_title, t.node_id, t.last_post_username, t.last_post_user_id + FROM ' . F_PREFIX . 'thread AS t + LEFT JOIN ' . F_PREFIX . 'node AS f + ON f.node_id = t.node_id + WHERE discussion_state="visible"' . $forum_id . ' + ORDER BY t.last_post_date DESC + LIMIT 0, ' . intval($this->config['count_post'])); + + + $forum_url = rtrim($this->options['boardUrl'], "/") . "/"; + + if (!$this->config['block_rewrite_url']) { + $forum_url .= "index.php?"; + } + + $tpl->load_template('block_forum_posts.tpl'); + preg_match("'\[row\](.*?)\[/row\]'si", $tpl->copy_template, $matches); + + $block_content = ''; + while ($row = $sth->fetch(PDO::FETCH_ASSOC)) + { + $short_name = $title = $this->_convert_encoding($row["title"], true); + $row['last_post_username'] = $this->_convert_encoding($row['last_post_username'], true); + + if ( + !empty($this->config['length_name']) && + dle_strlen($title, $this->DLEConfig['charset']) > $this->config['length_name'] + ) + { + $short_name = dle_substr($title, 0, $this->config['length_name'], $this->DLEConfig['charset']) . " ..."; + } + + switch (date("d.m.Y", $row["last_post_date"])) + { + case date("d.m.Y"): + $date = date($this->lang['today_in'] . "H:i", $row["last_post_date"]); + break; + + case date("d.m.Y", time() - 86400): + $date = date($this->lang['yesterday_in'] . "H:i", $row["last_post_date"]); + break; + + default: + $date = date("d.m.Y H:i", $row["last_post_date"]); + } + + $replace = array( + '{user}' => $this->_convert_encoding($row['last_post_username'], true), + '{user_url}' => $forum_url . "members/" . $this->getTitleForUrl($row['last_post_username']) ."." . $row['last_post_user_id'] . "/", + '{reply_count}' => $row["reply_count"], + '{view_count}' => $row["view_count"], + '{full_name}' => $title, + '{post_url}' => $forum_url . "threads/" . $this->getTitleForUrl($row['title']) ."." . $row["thread_id"] . "/", + '{shot_name_post}' => $short_name, + '{forum_name}' => $this->_convert_encoding($row['forum_title'], true), + '{forum_url}' => $forum_url . "forums/" . $this->getTitleForUrl($row['forum_title']) ."." . $row["node_id"] . "/", + '{date}' => $date + ); + + $block_content .= strtr($matches[1], $replace); + } + $tpl->set_block("'\[row\](.*?)\[/row\]'si", $block_content); + $tpl->compile('block_forum_posts'); + $tpl->clear(); + + if ((int)$this->config['block_cache_time']) + { + create_cache('xen_block_cache_time', serialize(array('time' => time(), 'data' => $tpl->result['block_forum_posts']))); + } + + return $tpl->result['block_forum_posts']; + } + + protected function doLogin($user_id, $remember_key, $last_activity) + { + $domain = $this->_getCookieDomain(); + if (empty($_POST['login_not_save'])) { + $value = intval($user_id) . ',' . sha1($this->XenConfig['globalSalt'] . $remember_key); + setcookie($this->XenConfig['cookie']['prefix'] . 'user', $value, time() + 30 * 86400, $this->XenConfig['cookie']['path'], $domain, false, true); + } + + $sessionCookieName = $this->XenConfig['cookie']['prefix'] . "session"; + + if (!empty($_COOKIE[$sessionCookieName]) && strlen($_COOKIE[$sessionCookieName]) == 32) { + $this->db->prepare("DELETE FROM " . F_PREFIX . "session WHERE session_id=?")->execute(array($_COOKIE[$sessionCookieName])); + } + + $sessionId = md5(uniqid(time())); + $sessionData = array( + 'sessionStart' => time(), + 'user_id' => $user_id, + 'ip' => $this->convertIpStringToBinary($_SERVER['REMOTE_ADDR']), + 'previousActivity' => $last_activity + ); + + if (!empty($_SERVER['HTTP_USER_AGENT'])) + { + $sessionData['userAgent'] = $_SERVER['HTTP_USER_AGENT']; + $sessionData['robotId'] = ''; + } + + if (!empty($_SERVER['HTTP_REFERER'])) + { + $sessionData['referer'] = $_SERVER['HTTP_REFERER']; + $sessionData['fromSearch'] = ''; + } + + setcookie($sessionCookieName, $sessionId, false, $this->XenConfig['cookie']['path'], $domain, false, true); + + $this->db->prepare("REPLACE INTO " . F_PREFIX . "session (session_id, session_data, expiry_date) VALUES (?, ?, ?)")->execute(array( + $sessionId, + serialize($sessionData), + time() + 3600 + )); + } + + protected function getTitleForUrl($title) + { + $title = strval($title); + + $title = strtr( + $title, + '`!"$%^&*()-+={}[]<>;:@#~,./?|' . "\r\n\t\\", + ' ' . ' ' + ); + $title = strtr($title, array('"' => '', "'" => '')); + + $title = preg_replace('/[ ]+/', '-', trim($title)); + $title = strtr($title, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'); + + return urlencode($title); + } + + protected function _getDBPrepareKeys(array $array) + { + $return = array(); + foreach (array_keys($array) as $key) + { + $return[] = ":" . $key; + } + + return $return; + } + + protected function _getDBPrepareKeysForUpdate(array $array) + { + $return = array(); + foreach (array_keys($array) as $key) + { + $return[] = "`{$key}`=:" . $key; + } + + return $return; + } + + protected function _getCookieDomain() + { + if (!empty($this->XenConfig['cookie']['domain'])) + { + return $this->XenConfig['cookie']['domain']; + } + else + { + return "." . $this->_clean_url($this->options['boardUrl']); + } + } + + protected function _clean_url($url) + { + if (!$url) + { + return false; + } + + $url = str_replace("http://", "", $url); + if (strtolower(substr($url, 0, 4)) == 'www.') $url = substr($url, 4); + $url = explode('/', $url); + $url = reset($url); + $url = explode(':', $url); + $url = reset($url); + + return $url; + } + + protected function _convert_encoding($text, $revert = false) + { + if (strtoupper($this->DLEConfig['charset']) == strtoupper(F_CHARSET)) { + return $text; + } + + if (is_array($text)) + { + foreach($text as $k => $t) + { + $text[$k] = $this->_convert_encoding($t); + } + } + else + { + if ($revert) { + $text = iconv(F_CHARSET, $this->DLEConfig['charset'], $text); + } + else { + $text = iconv($this->DLEConfig['charset'], F_CHARSET, $text); + } + } + + return $text; + } + + protected function __get($varname) + { + switch ($varname) + { + case 'options': + return $this->_getConfigForum(); + break; + + case 'passwordGenerator': + return $this->_getPasswordGenerator(); + break; + + case 'db': + return $this->_getDb(); + break; + + case 'dleAPI': + return $this->getDLEAPI(); + break; + + default: + throw new Exception('Property "' . $varname . '"not found'); + break; + } + } + + public function __desctruct() + { + + } +} + + +?> \ No newline at end of file diff --git a/DLE_uploads_windows-1251/engine/modules/XenIntegration/last_topic_block.php b/DLE_uploads_windows-1251/engine/modules/XenIntegration/last_topic_block.php new file mode 100644 index 0000000..3aba210 --- /dev/null +++ b/DLE_uploads_windows-1251/engine/modules/XenIntegration/last_topic_block.php @@ -0,0 +1,3 @@ +lastTopics($tpl); diff --git a/DLE_uploads_windows-1251/engine/modules/XenIntegration/xen_default_config.php b/DLE_uploads_windows-1251/engine/modules/XenIntegration/xen_default_config.php new file mode 100644 index 0000000..4e2e7ef --- /dev/null +++ b/DLE_uploads_windows-1251/engine/modules/XenIntegration/xen_default_config.php @@ -0,0 +1,58 @@ + array( + 'adapter' => 'mysqli', + 'host' => 'localhost', + 'port' => '3306', + 'username' => '', + 'password' => '', + 'dbname' => '', + 'adapterNamespace' => 'Zend_Db_Adapter' + ), + 'cache' => array( + 'enabled' => false, + 'cacheSessions' => false, + 'frontend' => 'core', + 'frontendOptions' => array( + 'caching' => true, + 'cache_id_prefix' => 'xf_' + ), + 'backend' => 'file', + 'backendOptions' => array( + 'file_name_prefix' => 'xf_' + ) + ), + 'debug' => false, + 'enableListeners' => true, + 'development' => array( + 'directory' => '', // relative to the configuration directory + 'default_addon' => '' + ), + 'superAdmins' => '1', + 'globalSalt' => 'ae5a99d00f58945a30b1ce054a1e89ef', + 'jsVersion' => '', + 'cookie' => array( + 'prefix' => 'xf_', + 'path' => '/', + 'domain' => '' + ), + 'enableMail' => true, + 'enableMailQueue' => true, + 'internalDataPath' => 'internal_data', + 'externalDataPath' => 'data', + 'externalDataUrl' => 'data', + 'javaScriptUrl' => 'js', + 'checkVersion' => true, + 'enableGzip' => true, + 'enableContentLength' => true, + 'adminLogLength' => 60, // number of days to keep admin log entries + 'chmodWritableValue' => 0, + 'rebuildMaxExecution' => 8, + 'passwordIterations' => 10, + 'enableTemplateModificationCallbacks' => true, + 'enableClickjackingProtection' => true, + 'maxImageResizePixelCount' => 20000000 +); + +?> \ No newline at end of file diff --git a/DLE_uploads_windows-1251/language/Russian/dle_xen.lng b/DLE_uploads_windows-1251/language/Russian/dle_xen.lng new file mode 100644 index 0000000..fe0da21 --- /dev/null +++ b/DLE_uploads_windows-1251/language/Russian/dle_xen.lng @@ -0,0 +1,6 @@ + ' ', + 'yesterday_in' => ' ', +); \ No newline at end of file diff --git a/README.txt b/README.txt new file mode 100644 index 0000000..dae50cc --- /dev/null +++ b/README.txt @@ -0,0 +1,82 @@ +Требования интеграции +PHP 5.2 и выше +Сайт и форум должны быть установлены на одном домене второго уровня (поддомены допускаются) +Если сайт и форум использует разный сервер то сервера должны иметь внешнее подключение к базам данных. + +Изменение файлов нужно проводить с помощью рдактора который не исменяет кодировку исходного файла, например Notepad++ + +Подготовка ДЛЕ: +1. Идем в админку: + Настройки пользователей -> Авторизовать пользователей на домене и всех его поддоменах -> Да + Настройки безопасности скрипта -> Сбрасывать ключ авторизации при каждом входе? -> Нет + +Подготовка форума: +1. Открываем файл library/config.php + Дбавляем следующие строки + $config['globalSalt'] = 'ae5a99d00f58945a30b1ce054a1e89ef'; + $config['cookie']['domain'] = '.sapmle.com'; + +2. В этих строках добавленых в пункте 1, вместо ae5a99d00f58945a30b1ce054a1e89ef поставить свою случайную послежовательность чисел. +Вместо .sapmle.com нужно прописать домен второго уровня с точкой спереди на котором установлен форум, например если форум находиться по адрессу http://forum.sapmle.com или http://www.sapmle.com то нужно указать домен +".sapmle.com" (не забываем про точку спереди), также такое значение будет если сайт и форум используют один домен например http://sapmle.com/dle, http://sapmle.com/forum + +Установка интеграции на форум: + 1. Из папки XenForo_uploads копируем файлы в корень форума. + 2. Файл c cайта /engine/data/dbconfig.php копируем в папку /library/DLEIntegration/config + 3. Открываем файл /library/DLEIntegration/config/dle_config.php там устанавливаем или изменяем если требуются параметры, описание смотрите в коментариях + 4. Заходим в админку форума Home -> Add-on -> Install New Add-on. И загружаем файл addon-DLEIntegration.xml. + +Установка интеграции на ДЛЕ: + 1. Из папки DLE_uploads копируем файлы в корень ДЛЕ, файлы из templates копируем в папку с вашим шаблоном. Исходную папку выбирайте в зависимости от кодировки ДЛЕ (кодировка сайта), настройки интеграции находяться в файле /engine/data/dle_xen_conf.php + 2. Файл с форума /library/config.php копируем в папку /engine/modules/XenIntegration/ + 3. Редактируем файл /engine/init.php + После + require_once ENGINE_DIR . '/modules/gzip.php'; + Вставить + require_once ENGINE_DIR . '/modules/XenIntegration/XenIntegration.php'; + + 4. Редируем файл /engine/modules/sitelogin.php + После + logout(); + + Перед + ?> + Вставить + XenIntegration::getInstance()->login($member_id); + + 5. Редируем файл /engine/modules/register.php + Перед + msgbox( $lang['reg_ok'], $lang['reg_ok_1'] ); + Вставить + XenIntegration::getInstance()->updateMember($row, $land, $info); + + После + $id = $db->insert_id(); + Вставить + XenIntegration::getInstance()->createMember(stripslashes($name), $user_arr[2], $email); + + 6. Редатируем файл /engine/modules/profile.php + Перед + if( strlen( $password1 ) > 0 ) { + + $password1 = md5( md5( $password1 ) ); + + Вставить + XenIntegration::getInstance()->updateProfile($row, $email, $password1, $land, $info); + + 7. Редактируем файл /engine/modules/lostpassword.php + После + $db->query( "UPDATE " . USERPREFIX . "_users set password='" . md5( md5( $new_pass ) ) . "', allowed_ip = '' WHERE user_id='$douser'" ); + $db->query( "DELETE FROM " . USERPREFIX . "_lostdb WHERE lostname='$douser'" ); + Вставить + XenIntegration::getInstance()->lostPassword($row, $new_pass); + + 8. Для вывода блока последних сообщений с форума в шаблон добавьте (настройки в файле /engine/data/dle_xen_conf.php, вид в шаблоне block_forum_posts.tpl) + {include file="engine/modules/XenIntegration/last_topic_block.php"} diff --git a/XenForo_uploads/library/DLEIntegration/ControllerPublic/Logout.php b/XenForo_uploads/library/DLEIntegration/ControllerPublic/Logout.php new file mode 100644 index 0000000..99fe2c4 --- /dev/null +++ b/XenForo_uploads/library/DLEIntegration/ControllerPublic/Logout.php @@ -0,0 +1,19 @@ +logout(); + + return $response; + } + + +} + +?> \ No newline at end of file diff --git a/XenForo_uploads/library/DLEIntegration/ControllerPublic/Register.php b/XenForo_uploads/library/DLEIntegration/ControllerPublic/Register.php new file mode 100644 index 0000000..e9b5804 --- /dev/null +++ b/XenForo_uploads/library/DLEIntegration/ControllerPublic/Register.php @@ -0,0 +1,18 @@ +_input->filterSingle('password', XenForo_Input::STRING); + DLEIntegration_DLE::getInstance()->login($user['username'], $password); + + return $response; + } +} + +?> \ No newline at end of file diff --git a/XenForo_uploads/library/DLEIntegration/DLE.php b/XenForo_uploads/library/DLEIntegration/DLE.php new file mode 100644 index 0000000..3fb37c4 --- /dev/null +++ b/XenForo_uploads/library/DLEIntegration/DLE.php @@ -0,0 +1,345 @@ +"; + echo "За информацией обращайтесь на форум http://forum.kaliostro.net/
"; + echo "You are not using licensed version of the module DLE + XenForo.
"; + echo "For information, visit the forum http://forum.kaliostro.net/"; + exit(); + } + + require_once dirname(__FILE__) . '/config/dbconfig.php'; + require_once dirname(__FILE__) . '/config/dle_config.php'; + + if (!defined('F_CHARSET')) + { + define('F_CHARSET', 'UTF-8'); + } + + if ($this->_clean_url($_SERVER['HTTP_HOST']) == $this->_getCookieDomain() && !session_id()) + { + session_start(); + } + } + + /** + * + * @return self + */ + static public function getInstance() + { + if (!self::$_instance) + { + self::$_instance = new self(); + } + + return self::$_instance; + } + + /** + * + * @staticvar PDO $dbh + * @return \PDO + */ + protected function _getDb() + { + static $dbh = null; + + if (!$dbh) + { + $dbh = new PDO("mysql:host=" . DBHOST . ";dbname=" . DBNAME, DBUSER, DBPASS); + $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT); + $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); + $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + + $dbh->exec('SET SQL_MODE=""'); + $dbh->exec('SET NAMES ' . COLLATE); + } + + return $dbh; + } + + + protected function _getParser() + { + static $parse = null; + + if (!$parse) + { + $parse = new DLEIntegration_ParseFilter(); + } + + return $parse; + } + + /** + * @return XenForo_BbCode_Parser + */ + protected function _getXenParser() + { + static $parse = null; + + if (!$parse) + { + $parse = XenForo_BbCode_Parser::create(XenForo_BbCode_Formatter_Base::create('Base')); + } + + return $parse; + } + + + #region Public function + + public function login($username, $password) + { + if (!DLE_LOGIN) + { + return false; + } + + $user = $this->findDLEUser($username, $password); + + if ($user) + { + $password = $this->_convert_encoding($password); + + $domain = "." . $this->_getCookieDomain(); + setcookie ("dle_password", md5($password), time() + 3600 * 24 * 365, "/", $domain); + setcookie ("dle_user_id", $user->user_id, time() + 3600 * 24 * 365, "/", $domain); + } + + return false; + } + + public function logout() + { + if (!DLE_LOGIN) + { + return false; + } + + $domain = "." . $this->_getCookieDomain(); + setcookie("dle_name", "", time() - 3600, "/", $domain); + setcookie("forum_session_id", "", time() - 3600, "/", $domain); + setcookie("dle_user_id", "", time() - 3600, "/", $domain); + setcookie("dle_user_id", "", time() - 3600, "/"); + setcookie("dle_password", "", time() - 3600, "/", $domain); + setcookie("dle_skin", "", time() - 3600, "/", $domain); + setcookie("dle_newpm", "", time() - 3600, "/", $domain); + setcookie("dle_hash", "", time() - 3600, "/", $domain); + setcookie("PHPSESSID", "", time() - 3600, "/", $domain); + setcookie("PHPSESSID", "", time() - 3600, "/"); + setcookie(session_name(),"",time() - 3600, "/", $domain); + + if (session_id()) + { + $_SESSION['dle_name'] = ""; + $_SESSION['dle_password'] = ""; + @session_destroy(); + @session_unset(); + } + + return false; + } + + public function insert(array $fields) + { + if (!DLE_REGISTER) { + return false; + } + + $fields = array_merge(array( + "reg_date" => time(), + "lastdate" => time(), + "user_group" => USER_GROUP, + "info" => '', + "signature" => '', + "xfields" => '', + "favorites" => '', + "logged_ip" => $_SERVER['REMOTE_ADDR'], + ), $fields); + + $this->prepareValues($fields); + + $sth = $this->_getDb()->prepare('SELECT user_id FROM ' . USERPREFIX . "_users WHERE name=? OR email=?"); + $sth->execute(array($fields['name'], $fields['email'])); + + if ($sth->fetchColumn()) + { + return true; + } + + $this->_getDb()->prepare('INSERT INTO ' . USERPREFIX . '_users (' . implode(", " , array_keys($fields)) . ") VALUES (" . implode(", ", $this->_getDBPrepareKeys($fields)) . ")") + ->execute($fields); + + return false; + } + + public function update($username, array $fields) + { + if (!DLE_PROFILE) { + return false; + } + + $user = $this->findDLEUser($username); + + if (!$user) { + return true; + } + + $update = array(); + foreach ($fields as $field => $value) { + $update[] = "`$field`=:" . $field; + } + + $this->prepareValues($fields); + + $this->_getDb()->prepare('UPDATE ' . USERPREFIX . '_users SET ' . implode(", " , $update) . " WHERE user_id=:user_id") + ->execute(array_merge($fields, array("user_id" => $user->user_id))); + + return false; + } + + public function prepareValues(array &$fields) + { + foreach ($fields as $name => &$value) { + if (in_array($name, array('signature', 'info'))) { + $value = strip_tags($this->_getXenParser()->render($value), "
"); + } + + $value = $this->_convert_encoding($value); + } + } + + public function findDLEUser($login, $password = null) + { + $username = $this->_convert_encoding($login); + $password = $this->_convert_encoding($password); + + if (strpos($username, "@")) { + $sth = $this->_getDb()->prepare("SELECT * FROM " . USERPREFIX . "_users WHERE email=?"); + } + else { + $sth = $this->_getDb()->prepare("SELECT * FROM " . USERPREFIX . "_users WHERE name=?"); + } + $sth->execute(array($username)); + $user = $sth->fetchObject(); + + if ($user && (!$password || md5(md5($password)) == $user->password)) + { + return $user; + } + + return false; + } + + protected function _getDBPrepareKeys(array $array) + { + $return = array(); + foreach (array_keys($array) as $key) + { + $return[] = ":" . $key; + } + + return $return; + } + + protected function _getCookieDomain() + { + return $this->_clean_url(DLE_DOMAIN); + } + + protected function _clean_url($url) + { + if (!$url) + { + return ''; + } + + $url = str_replace("http://", "", $url); + if (strtolower(substr($url, 0, 4)) == 'www.') $url = substr($url, 4); + $url = explode('/', $url); + $url = reset($url); + $url = explode(':', $url); + $url = reset($url); + + return $url; + } + + protected function _convert_encoding($text, $revert = false) + { + if (!$revert) + { + $in_charset = F_CHARSET; + $out_charset = DLE_CHARSET; + } + else + { + $in_charset = DLE_CHARSET; + $out_charset = F_CHARSET; + } + + if (is_array($text)) + { + foreach($text as $k => $t) + { + $text[$k] = $this->_convert_encoding($t); + } + } + else + { + if (strtoupper($in_charset) != strtoupper($out_charset)) + { + $text = iconv($in_charset, $out_charset, $text); + } + } + + return $text; + } + + /** + * @param string $string + * @return array|string + */ + public function convertEncodingFromDLE($string) + { + return $this->_convert_encoding($string, true); + } + + /** + * @param string $string + * @return array|string + */ + public function convertEncodingToDLE($string) + { + return $this->_convert_encoding($string); + } + + public function __get($varname) + { + throw new Exception('unknown property ' . $varname); + } + + public function __desctruct() + { + + } +} diff --git a/XenForo_uploads/library/DLEIntegration/DataWriter/User.php b/XenForo_uploads/library/DLEIntegration/DataWriter/User.php new file mode 100644 index 0000000..323978a --- /dev/null +++ b/XenForo_uploads/library/DLEIntegration/DataWriter/User.php @@ -0,0 +1,66 @@ + 'username', + 'email' => 'email', + 'lastdate' => 'last_activity', + 'reg_date' => 'register_date', + 'signature' => 'signature', + 'info' => 'about', + 'fullname' => 'custom_title', + 'land' => 'location', +// 'logged_ip' => '', + 'banned' => 'is_banned', + ); + + private $password; + + public function setPassword($password, $passwordConfirm = false, XenForo_Authentication_Abstract $auth = null, $requirePassword = false) + { + $this->password = $password; + + parent::setPassword($password, $passwordConfirm, $auth, $requirePassword); + } + + public function setCustomFields(array $fieldValues, array $fieldsShown = null) + { + parent::setCustomFields($fieldValues, $fieldsShown); + } + + protected function _save() + { + parent::_save(); + + $fields = array(); + + foreach ($this->_newData as $data) { + foreach ($data as $column => $value) { + if (in_array($column, $this->fieldsDLE2Xen)) { + $fields[array_search($column, $this->fieldsDLE2Xen)] = $value; + } + } + } + + if ($fields || $this->password) { + + if ($this->password) { + $fields['password'] = md5(md5(DLEIntegration_DLE::getInstance()->convertEncodingToDLE($this->password))); + } + + if ($this->isUpdate()) { + if ($username = $this->getExisting('username')) { + DLEIntegration_DLE::getInstance()->update($username, $fields); + } + } + else { + DLEIntegration_DLE::getInstance()->insert($fields); + } + } + } + + +} \ No newline at end of file diff --git a/XenForo_uploads/library/DLEIntegration/Listener.php b/XenForo_uploads/library/DLEIntegration/Listener.php new file mode 100644 index 0000000..794ee47 --- /dev/null +++ b/XenForo_uploads/library/DLEIntegration/Listener.php @@ -0,0 +1,34 @@ + array('Steam_Helper_Steam', 'convertIdToString') +// ); + } +} diff --git a/XenForo_uploads/library/DLEIntegration/Model/User.php b/XenForo_uploads/library/DLEIntegration/Model/User.php new file mode 100644 index 0000000..281ffac --- /dev/null +++ b/XenForo_uploads/library/DLEIntegration/Model/User.php @@ -0,0 +1,63 @@ +login($nameOrEmail, $password); + return $user_id; + } + + if ($error->getPhraseName() !== 'requested_user_x_not_found') { + return $user_id; + } + + $user = $DLE->findDLEUser($nameOrEmail, $password); + if (!$user) { + return $user_id; + } + + $data = array( + 'username' => $DLE->convertEncodingFromDLE($user->name), + 'email' => $DLE->convertEncodingFromDLE($user->email), + 'last_activity' => $user->lastdate, + 'register_date' => $user->reg_date, + ); + + $options = XenForo_Application::getOptions(); + + $writer = XenForo_DataWriter::create('XenForo_DataWriter_User'); + if ($options->registrationDefaults) + { + $writer->bulkSet($options->registrationDefaults, array('ignoreInvalidFields' => true)); + } + $writer->bulkSet($data); + $writer->setPassword($password, false, null, true); + $writer->set('user_group_id', XenForo_Model_User::$defaultRegisteredGroupId); + $writer->set('language_id', XenForo_Visitor::getInstance()->get('language_id')); + $writer->advanceRegistrationUserState(); + $writer->preSave(); + + $writer->save(); + + $user = $writer->getMergedData(); + + if ($user['user_state'] == 'email_confirm') + { + XenForo_Model::create('XenForo_Model_UserConfirmation')->sendEmailConfirmation($user); + } + + $error = ''; + $DLE->login($nameOrEmail, $password); + + return $user['user_id']; + } +} \ No newline at end of file diff --git a/XenForo_uploads/library/DLEIntegration/Model/UserConfirmation.php b/XenForo_uploads/library/DLEIntegration/Model/UserConfirmation.php new file mode 100644 index 0000000..77ebf6f --- /dev/null +++ b/XenForo_uploads/library/DLEIntegration/Model/UserConfirmation.php @@ -0,0 +1,21 @@ +setExistingData($userId); + $dw->get('username'); + + DLEIntegration_DLE::getInstance()->update($dw->get('username'), array( + 'password' => md5(md5(DLEIntegration_DLE::getInstance()->convertEncodingToDLE($password))) + )); + + return $password; + } +} \ No newline at end of file diff --git a/XenForo_uploads/library/DLEIntegration/ParseFilter.php b/XenForo_uploads/library/DLEIntegration/ParseFilter.php new file mode 100644 index 0000000..260624e --- /dev/null +++ b/XenForo_uploads/library/DLEIntegration/ParseFilter.php @@ -0,0 +1,1215 @@ + '8', 2 => '10', 3 => '12', 4 => '14', 5 => '18', 6 => '24', 7 => '36' ); + + function DLE_ParseFilter($tagsArray = array(), $attrArray = array(), $tagsMethod = 0, $attrMethod = 0, $xssAuto = 1) { + for($i = 0; $i < count( $tagsArray ); $i ++) + $tagsArray[$i] = strtolower( $tagsArray[$i] ); + for($i = 0; $i < count( $attrArray ); $i ++) + $attrArray[$i] = strtolower( $attrArray[$i] ); + $this->tagsArray = ( array ) $tagsArray; + $this->attrArray = ( array ) $attrArray; + $this->tagsMethod = $tagsMethod; + $this->attrMethod = $attrMethod; + $this->xssAuto = $xssAuto; + } + function process($source) { + + if( function_exists( "get_magic_quotes_gpc" ) && get_magic_quotes_gpc() ) $source = stripslashes( $source ); + + $source = $this->remove( $this->decode( $source ) ); + + if( $this->code_count ) { + foreach ( $this->code_text as $key_find => $key_replace ) { + $find[] = $key_find; + $replace[] = $key_replace; + } + + $source = str_replace( $find, $replace, $source ); + } + + $this->code_count = 0; + $this->code_text = array (); + $source = preg_replace( "#\{include#i", "{include", $source ); + + $source = addslashes( $source ); + return $source; + + } + function remove($source) { + $loopCounter = 0; + while ( $source != $this->filterTags( $source ) ) { + $source = $this->filterTags( $source ); + $loopCounter ++; + } + return $source; + } + function filterTags($source) { + $preTag = NULL; + $postTag = $source; + $tagOpen_start = strpos( $source, '<' ); + while ( $tagOpen_start !== FALSE ) { + $preTag .= substr( $postTag, 0, $tagOpen_start ); + $postTag = substr( $postTag, $tagOpen_start ); + $fromTagOpen = substr( $postTag, 1 ); + $tagOpen_end = strpos( $fromTagOpen, '>' ); + if( $tagOpen_end === false ) break; + $tagOpen_nested = strpos( $fromTagOpen, '<' ); + if( ($tagOpen_nested !== false) && ($tagOpen_nested < $tagOpen_end) ) { + $preTag .= substr( $postTag, 0, ($tagOpen_nested + 1) ); + $postTag = substr( $postTag, ($tagOpen_nested + 1) ); + $tagOpen_start = strpos( $postTag, '<' ); + continue; + } + $tagOpen_nested = (strpos( $fromTagOpen, '<' ) + $tagOpen_start + 1); + $currentTag = substr( $fromTagOpen, 0, $tagOpen_end ); + $tagLength = strlen( $currentTag ); + if( ! $tagOpen_end ) { + $preTag .= $postTag; + $tagOpen_start = strpos( $postTag, '<' ); + } + $tagLeft = $currentTag; + $attrSet = array (); + $currentSpace = strpos( $tagLeft, ' ' ); + if( substr( $currentTag, 0, 1 ) == "/" ) { + $isCloseTag = TRUE; + list ( $tagName ) = explode( ' ', $currentTag ); + $tagName = substr( $tagName, 1 ); + } else { + $isCloseTag = FALSE; + list ( $tagName ) = explode( ' ', $currentTag ); + } + if( (! preg_match( "/^[a-z][a-z0-9]*$/i", $tagName )) || (! $tagName) || ((in_array( strtolower( $tagName ), $this->tagBlacklist )) && ($this->xssAuto)) ) { + $postTag = substr( $postTag, ($tagLength + 2) ); + $tagOpen_start = strpos( $postTag, '<' ); + continue; + } + while ( $currentSpace !== FALSE ) { + $fromSpace = substr( $tagLeft, ($currentSpace + 1) ); + $nextSpace = strpos( $fromSpace, ' ' ); + $openQuotes = strpos( $fromSpace, '"' ); + $closeQuotes = strpos( substr( $fromSpace, ($openQuotes + 1) ), '"' ) + $openQuotes + 1; + if( strpos( $fromSpace, '=' ) !== FALSE ) { + if( ($openQuotes !== FALSE) && (strpos( substr( $fromSpace, ($openQuotes + 1) ), '"' ) !== FALSE) ) $attr = substr( $fromSpace, 0, ($closeQuotes + 1) ); + else $attr = substr( $fromSpace, 0, $nextSpace ); + } else + $attr = substr( $fromSpace, 0, $nextSpace ); + if( ! $attr ) $attr = $fromSpace; + $attrSet[] = $attr; + $tagLeft = substr( $fromSpace, strlen( $attr ) ); + $currentSpace = strpos( $tagLeft, ' ' ); + } + $tagFound = in_array( strtolower( $tagName ), $this->tagsArray ); + if( (! $tagFound && $this->tagsMethod) || ($tagFound && ! $this->tagsMethod) ) { + if( ! $isCloseTag ) { + $attrSet = $this->filterAttr( $attrSet, strtolower( $tagName ) ); + $preTag .= '<' . $tagName; + for($i = 0; $i < count( $attrSet ); $i ++) + $preTag .= ' ' . $attrSet[$i]; + if( strpos( $fromTagOpen, "'; + else $preTag .= ' />'; + } else + $preTag .= ''; + } + $postTag = substr( $postTag, ($tagLength + 2) ); + $tagOpen_start = strpos( $postTag, '<' ); + } + $preTag .= $postTag; + return $preTag; + } + + function filterAttr($attrSet, $tagName) { + + global $config; + + $newSet = array (); + for($i = 0; $i < count( $attrSet ); $i ++) { + if( ! $attrSet[$i] ) continue; + + $attrSet[$i] = trim( $attrSet[$i] ); + + $exp = strpos( $attrSet[$i], '=' ); + if( $exp === false ) $attrSubSet = Array ($attrSet[$i] ); + else { + $attrSubSet = Array (); + $attrSubSet[] = substr( $attrSet[$i], 0, $exp ); + $attrSubSet[] = substr( $attrSet[$i], $exp + 1 ); + } + $attrSubSet[1] = stripslashes( $attrSubSet[1] ); + + list ( $attrSubSet[0] ) = explode( ' ', $attrSubSet[0] ); + + $attrSubSet[0] = strtolower( $attrSubSet[0] ); + + if( (! preg_match( "/^[a-z]*$/i", $attrSubSet[0] )) || (($this->xssAuto) && ((in_array( $attrSubSet[0], $this->attrBlacklist )) || (substr( $attrSubSet[0], 0, 2 ) == 'on'))) ) continue; + if( $attrSubSet[1] ) { + $attrSubSet[1] = str_replace( '&#', '', $attrSubSet[1] ); + $attrSubSet[1] = preg_replace( '/\s+/', ' ', $attrSubSet[1] ); + $attrSubSet[1] = str_replace( '"', '', $attrSubSet[1] ); + if( (substr( $attrSubSet[1], 0, 1 ) == "'") && (substr( $attrSubSet[1], (strlen( $attrSubSet[1] ) - 1), 1 ) == "'") ) $attrSubSet[1] = substr( $attrSubSet[1], 1, (strlen( $attrSubSet[1] ) - 2) ); + } + + if( ((strpos( strtolower( $attrSubSet[1] ), 'expression' ) !== false) && ($attrSubSet[0] == 'style')) || (strpos( strtolower( $attrSubSet[1] ), 'javascript:' ) !== false) || (strpos( strtolower( $attrSubSet[1] ), 'behaviour:' ) !== false) || (strpos( strtolower( $attrSubSet[1] ), 'vbscript:' ) !== false) || (strpos( strtolower( $attrSubSet[1] ), 'mocha:' ) !== false) || (strpos( strtolower( $attrSubSet[1] ), 'data:' ) !== false and $attrSubSet[0] == "href") || (strpos( strtolower( $attrSubSet[1] ), 'data:' ) !== false and $attrSubSet[0] == "src") || ($attrSubSet[0] == "href" and strpos( strtolower( $attrSubSet[1] ), $config['admin_path'] ) !== false and preg_match( "/[?&%<\[\]]/", $attrSubSet[1] )) || (strpos( strtolower( $attrSubSet[1] ), 'livescript:' ) !== false) ) continue; + + $attrFound = in_array( $attrSubSet[0], $this->attrArray ); + if( (! $attrFound && $this->attrMethod) || ($attrFound && ! $this->attrMethod) ) { + if( $attrSubSet[1] ) $newSet[] = $attrSubSet[0] . '="' . $attrSubSet[1] . '"'; + elseif( $attrSubSet[1] == "0" ) $newSet[] = $attrSubSet[0] . '="0"'; + else $newSet[] = $attrSubSet[0] . '=""'; + } + } + ; + return $newSet; + } + function decode($source) { + + if( $this->allow_code ) + $source = preg_replace( "#\[code\](.+?)\[/code\]#ies", "\$this->code_tag( '\\1' )", $source ); + + if( $this->safe_mode and ! $this->wysiwyg ) { + + $source = htmlspecialchars( $source, ENT_QUOTES ); + $source = str_replace( '&', '&', $source ); + + } else { + + $source = str_replace( "<>", "<>", str_replace( ">>", ">>", str_replace( "<<", "<<", $source ) ) ); + $source = str_replace( "
", "
{$lang['i_quote']} \\1
", "
", "
" ); + + if( $use_html == false ) { + $find[] = "'\r'"; + $replace[] = ""; + $find[] = "'\n'"; + $replace[] = "
"; + } else { + $source = str_replace( "\r\n\r\n", "\n", $source ); + } + + $smilies_arr = explode( ",", $config['smilies'] ); + foreach ( $smilies_arr as $smile ) { + $smile = trim( $smile ); + $find[] = "':$smile:'"; + $replace[] = "\"$smile\""; + } + + $source = preg_replace( $find, $replace, $source ); + $source = preg_replace( "#allow_php ) { + + $source = str_replace( "", "?>", $source ); + + } + + $source = preg_replace( "#\[code\](.+?)\[/code\]#is", "
\\1
", $source ); + $source = preg_replace( "#\[(left|right|center)\](.+?)\[/\\1\]#is", "
\\2
", $source ); + + $source = preg_replace( "#\[b\](.+?)\[/b\]#is", "\\1", $source ); + $source = preg_replace( "#\[i\](.+?)\[/i\]#is", "\\1", $source ); + $source = preg_replace( "#\[u\](.+?)\[/u\]#is", "\\1", $source ); + $source = preg_replace( "#\[s\](.+?)\[/s\]#is", "\\1", $source ); + + $source = preg_replace( "#\[spoiler\]#ie", "\$this->build_spoiler('')", $source ); + $source = preg_replace( "#\[spoiler=(.+?)\]#ie", "\$this->build_spoiler('\\1')", $source ); + + if( $this->allow_url ) { + + $source = preg_replace( "#\[url\](\S.+?)\[/url\]#ie", "\$this->build_url(array('html' => '\\1', 'show' => '\\1'))", $source ); + $source = preg_replace( "#\[url\s*=\s*\"\;\s*(\S+?)\s*\"\;\s*\](.*?)\[\/url\]#ie", "\$this->build_url(array('html' => '\\1', 'show' => '\\2'))", $source ); + $source = preg_replace( "#\[url\s*=\s*(\S.+?)\s*\](.*?)\[\/url\]#ie", "\$this->build_url(array('html' => '\\1', 'show' => '\\2'))", $source ); + + $source = preg_replace( "#\[leech\](\S.+?)\[/leech\]#ie", "\$this->build_url(array('html' => '\\1', 'show' => '\\1', 'leech' => '1'))", $source ); + $source = preg_replace( "#\[leech\s*=\s*\"\;\s*(\S+?)\s*\"\;\s*\](.*?)\[\/leech\]#ie", "\$this->build_url(array('html' => '\\1', 'show' => '\\2', 'leech' => '1'))", $source ); + $source = preg_replace( "#\[leech\s*=\s*(\S.+?)\s*\](.*?)\[\/leech\]#ie", "\$this->build_url(array('html' => '\\1', 'show' => '\\2', 'leech' => '1'))", $source ); + + } else { + + if( stristr( $source, "[url" ) !== false ) $this->not_allowed_tags = true; + if( stristr( $source, "[leech" ) !== false ) $this->not_allowed_tags = true; + if( stristr( $source, "<a" ) !== false ) $this->not_allowed_tags = true; + + } + + if( $this->allow_image ) { + + $source = preg_replace( "#\[img\](.+?)\[/img\]#ie", "\$this->build_image('\\1')", $source ); + $source = preg_replace( "#\[img=(.+?)\](.+?)\[/img\]#ie", "\$this->build_image('\\2', '\\1')", $source ); + + } else { + + if( stristr( $source, "[img" ) !== false ) $this->not_allowed_tags = true; + if( stristr( $source, "<img" ) !== false ) $this->not_allowed_tags = true; + + } + + $source = preg_replace( "#\[email\s*=\s*\"\;([\.\w\-]+\@[\.\w\-]+\.[\.\w\-]+)\s*\"\;\s*\](.*?)\[\/email\]#ie", "\$this->build_email(array('html' => '\\1', 'show' => '\\2'))", $source ); + $source = preg_replace( "#\[email\s*=\s*([\.\w\-]+\@[\.\w\-]+\.[\w\-]+)\s*\](.*?)\[\/email\]#ie", "\$this->build_email(array('html' => '\\1', 'show' => '\\2'))", $source ); + + if( ! $this->safe_mode ) { + + $source = preg_replace( "'\[thumb\]([^\[]*)([/\\\\])(.*?)\[/thumb\]'ie", "\$this->build_thumb('\$1\$2\$3', '\$1\$2thumbs\$2\$3')", $source ); + $source = preg_replace( "'\[thumb=(.*?)\]([^\[]*)([/\\\\])(.*?)\[/thumb\]'ie", "\$this->build_thumb('\$2\$3\$4', '\$2\$3thumbs\$3\$4', '\$1')", $source ); + $source = preg_replace( "#\[video\s*=\s*(\S.+?)\s*\]#ie", "\$this->build_video('\\1')", $source ); + $source = preg_replace( "#\[audio\s*=\s*(\S.+?)\s*\]#ie", "\$this->build_audio('\\1')", $source ); + $source = preg_replace( "#\[flash=([^\]]+)\](.+?)\[/flash\]#ies", "\$this->build_flash('\\1', '\\2')", $source ); + $source = preg_replace( "#\[youtube=([^\]]+)\]#ies", "\$this->build_youtube('\\1')", $source ); + + while ( preg_match( "#\[size=([^\]]+)\](.+?)\[/size\]#ies", $source ) ) { + $source = preg_replace( "#\[size=([^\]]+)\](.+?)\[/size\]#ies", "\$this->font_change(array('tag'=>'size','1'=>'\\1','2'=>'\\2'))", $source ); + } + + while ( preg_match( "#\[font=\"?([^\"\]]+)\"?\](.+?)\[/font\]#ies", $source ) ) { + $source = preg_replace( "#\[font=\"?([^\"\]]+)\"?\](.+?)\[/font\]#ies", "\$this->font_change(array('tag'=>'font','1'=>'\\1','2'=>'\\2'))", $source ); + + } + + while ( preg_match( "#\[color=\"?([^\"\]]+)\"?\](.+?)\[/color\]#ies", $source ) ) { + $source = preg_replace( "#\[color=\"?([^\"\]]+)\"?\](.+?)\[/color\]#ies", "\$this->font_change(array('tag'=>'color','1'=>'\\1','2'=>'\\2'))", $source ); + } + } + + if( $this->filter_mode ) $source = $this->word_filter( $source ); + + return trim( $source ); + + } + + function decodeBBCodes($txt, $use_html = TRUE, $wysiwig = "no") { + + global $config; + + $find = array (); + $result = array (); + $txt = stripslashes( $txt ); + if( $this->filter_mode ) $txt = $this->word_filter( $txt, false ); + + $txt = preg_replace( "#(.+?)#ie", "\$this->decode_thumb('\\1')", $txt ); + $txt = preg_replace( "#(.+?)#ie", "\$this->decode_newthumb('\\1')", $txt ); + $txt = preg_replace( "#(.+?)#", '[quote]', $txt ); + $txt = preg_replace( "#(.+?)#", "[quote=\\1]", $txt ); + $txt = preg_replace( "#(.+?)#", '[/quote]', $txt ); + $txt = preg_replace( "#(.+?)#", '[code]', $txt ); + $txt = preg_replace( "#(.+?)#", '[/code]', $txt ); + $txt = preg_replace( "#(.+?)#ie", "\$this->decode_leech('\\1\\2', '\\3')", $txt ); + $txt = preg_replace( "#(.+?)src=\"(.+?)\"(.+?)#is", '[video=\\2]', $txt ); + $txt = preg_replace( "#(.+?)#is", '[video=\\1]', $txt ); + $txt = preg_replace( "#(.+?)#is", '[audio=\\1]', $txt ); + $txt = preg_replace( "#(.+?)#ies", "\$this->decode_dle_img('\\1')", $txt ); + $txt = preg_replace( "#(.+?)#is", '[youtube=\\1]', $txt ); + $txt = preg_replace( "#(.+?)#ies", "\$this->decode_flash('\\1')", $txt ); + $txt = preg_replace( "#(.+?)#is", '[spoiler]', $txt ); + $txt = preg_replace( "#(.+?)#is", '[spoiler=\\1]', $txt ); + $txt = str_replace( "", '[/spoiler]', $txt ); + + if( $wysiwig != "yes" ) { + $txt = preg_replace( "#(.+?)#is", "[i]\\1[/i]", $txt ); + $txt = preg_replace( "#(.+?)#is", "[b]\\1[/b]", $txt ); + $txt = preg_replace( "#(.+?)#is", "[s]\\1[/s]", $txt ); + $txt = preg_replace( "#(.+?)#is", "[u]\\1[/u]", $txt ); + $txt = preg_replace( "#
(.+?)
#is", "[center]\\1[/center]", $txt ); + $txt = preg_replace( "##ie", "\$this->decode_img('\\1', '\\2')", $txt ); + + $txt = preg_replace( "#(.+?)#", "[email=\\1]\\2[/email]", $txt ); + $txt = preg_replace( "#(.+?)#ie", "\$this->decode_url('\\1\\2', '\\3')", $txt ); + $txt = preg_replace( "#(.+?)#ie", "\$this->decode_url('\\1\\2', '\\3')", $txt ); + + $txt = preg_replace( "#(.+?)#", "[size=\\1]", $txt ); + $txt = preg_replace( "#(.+?)#", "[color=\\1]", $txt ); + $txt = preg_replace( "#(.+?)#", "[font=\\1]", $txt ); + + $txt = str_replace( "", "[/size]", $txt ); + $txt = str_replace( "", "[/color]", $txt ); + $txt = str_replace( "", "[/font]", $txt ); + + while ( preg_match( "#(.+?)#is", $txt ) ) { + $txt = preg_replace( "#(.+?)#is", "[color=\\1]\\2[/color]", $txt ); + } + + while ( preg_match( "#
(.+?)
#is", $txt ) ) { + $txt = preg_replace( "#
(.+?)
#is", "[left]\\1[/left]", $txt ); + } + while ( preg_match( "#
(.+?)
#is", $txt ) ) { + $txt = preg_replace( "#
(.+?)
#is", "[right]\\1[/right]", $txt ); + } + while ( preg_match( "#
(.+?)
#is", $txt ) ) { + $txt = preg_replace( "#
(.+?)
#is", "[center]\\1[/center]", $txt ); + } + + } else { + + $txt = str_replace( "", "", $txt ); + $txt = str_replace( "", "", $txt ); + $txt = str_replace( "", "", $txt ); + $txt = str_replace( "", "", $txt ); + $txt = str_replace( "", "", $txt ); + $txt = str_replace( "", "", $txt ); + $txt = preg_replace( "##", "", $txt ); + $txt = preg_replace( "##", "", $txt ); + $txt = preg_replace( "##", "", $txt ); + + } + + $txt = preg_replace( "#(.+?)#is", ':\\1:', $txt ); + + $smilies_arr = explode( ",", $config['smilies'] ); + + foreach ( $smilies_arr as $smile ) { + $smile = trim( $smile ); + $replace[] = ":$smile:"; + $find[] = "#['\"]"#is"; + } + + $txt = preg_replace( $find, $replace, $txt ); + + if( ! $use_html ) { + $txt = str_replace( "
", "\n", $txt ); + $txt = str_replace( "
", "\n", $txt ); + $txt = str_replace( "
", "\n", $txt ); + $txt = str_replace( "
", "\n", $txt ); + } + + if (!$this->safe_mode) $txt = htmlspecialchars( $txt, ENT_QUOTES ); + if( $wysiwig != "yes" ) $txt = preg_replace( "#\[code\](.+?)\[/code\]#ies", "\$this->decode_code('\\1', '{$use_html}')", $txt ); + + return trim( $txt ); + + } + + function font_change($tags) { + + if( ! is_array( $tags ) ) { + return; + } + + $style = $tags['1']; + $text = stripslashes( $tags['2'] ); + $type = $tags['tag']; + + $style = str_replace( '"', '', $style ); + $style = preg_replace( "/[&\(\)\.\%\[\]<>\'\"]/", "", preg_replace( "#^(.+?)(?:;|$)#", "\\1", $style ) ); + + if( $type == 'size' ) { + $style = intval( $style ); + + if( $this->font_sizes[$style] ) { + $real = $this->font_sizes[$style]; + } else { + $real = 12; + } + + return "" . $text . ""; + } + + if( $type == 'font' ) { + $style = preg_replace( "/[^\d\w\#\-\_\s]/s", "", $style ); + return "" . $text . ""; + } + + $style = preg_replace( "/[^\d\w\#\s]/s", "", $style ); + return "" . $text . ""; + } + + function build_email($url = array()) { + + $url['html'] = $this->clear_url( $url['html'] ); + $url['show'] = stripslashes( $url['show'] ); + + return "{$url['show']}"; + + } + + function build_flash($size, $url) { + + $size = explode(",", $size); + + $width = trim(intval($size[0])); + $height = trim(intval($size[1])); + + if (!$width OR !$height) return "[flash=".implode(",",$size)."]".$url."[/flash]"; + + $url = $this->clear_url( urldecode( $url ) ); + + if( $url == "" ) return; + + $type = explode( ".", $url ); + $type = strtolower( end( $type ) ); + + if ( strtolower($type) != "swf" ) + { + return "[flash=".implode(",",$size)."]".$url."[/flash]"; + } + + return ""; + + + } + + function decode_flash($url) + { + $url = explode( "||", $url ); + + return '[flash='.$url[0].','.$url[1].']'.$url[2].'[/flash]'; + } + + function build_youtube($url) { + + if (!count($this->video_config)) { + + include (ENGINE_DIR . '/data/videoconfig.php'); + $this->video_config = $video_config; + + } + + $url = $this->clear_url( urldecode( $url ) ); + $url = str_replace("&","&", $url ); + + if( $url == "" ) return; + + $source = @parse_url ( $url ); + + $source['host'] = str_replace( "www.", "", strtolower($source['host']) ); + + if ($source['host'] != "youtube.com" AND $source['host'] != "rutube.ru") return "[youtube=".$url."]"; + + $a = explode('&', $source['query']); + $i = 0; + + while ($i < count($a)) { + $b = explode('=', $a[$i]); + if ($b[0] == "v") $video_link = $b[1]; + $i++; + } + + if ($source['host'] == "youtube.com") + return ''; + else + return ''; + + } + + function build_url($url = array()) { + global $config; + + $skip_it = 0; + + if( preg_match( "/([\.,\?]|!)$/", $url['show'], $match ) ) { + $url['end'] .= $match[1]; + $url['show'] = preg_replace( "/([\.,\?]|!)$/", "", $url['show'] ); + } + + $url['html'] = $this->clear_url( $url['html'] ); + $url['show'] = stripslashes( $url['show'] ); + + if( $this->safe_mode ) { + + $url['show'] = str_replace( " ", " ", $url['show'] ); + + if (strlen(trim($url['show'])) < 3 ) + return "[url=" . $url['html'] . "]" . $url['show'] . "[/url]"; + + } + + if( strpos( $url['html'], $config['http_home_url'] ) !== false AND strpos( $url['html'], $config['admin_path'] ) !== false ) { + + return "[url=" . $url['html'] . "]" . $url['show'] . "[/url]"; + + } + + if( ! preg_match( "#^(http|news|https|ed2k|ftp|aim|mms)://|(magnet:?)#", $url['html'] ) ) { + $url['html'] = 'http://' . $url['html']; + } + + if ($url['html'] == 'http://' ) + return "[url=" . $url['html'] . "]" . $url['show'] . "[/url]"; + + if( preg_match( "/^check_home( $url['html'] ) ) $target = ""; + else $target = "target=\"_blank\""; + + if( $url['leech'] ) { + + $url['html'] = $config['http_home_url'] . "engine/go.php?url=" . rawurlencode( base64_encode( $url['html'] ) ); + + return "" . $show . "" . $url['end']; + + } else { + + if ($this->safe_mode AND !$config['allow_search_link']) + return "" . $show . "" . $url['end']; + else + return "" . $show . "" . $url['end']; + + } + + } + + function code_tag($txt = "") { + if( $txt == "" ) { + return; + } + + $this->code_count ++; + + $txt = str_replace( "&", "&", $txt ); + $txt = str_replace( "<", "<", $txt ); + $txt = str_replace( "'", "'", $txt ); + $txt = str_replace( ">", ">", $txt ); + $txt = str_replace( "<", "<", $txt ); + $txt = str_replace( ">", ">", $txt ); + $txt = str_replace( """, """, $txt ); + $txt = str_replace( "\\\"", """, $txt ); + $txt = str_replace( ":", ":", $txt ); + $txt = str_replace( "[", "[", $txt ); + $txt = str_replace( "]", "]", $txt ); + $txt = str_replace( ")", ")", $txt ); + $txt = str_replace( "(", "(", $txt ); + $txt = str_replace( "\r", "", $txt ); + $txt = str_replace( "\n", "
", $txt ); + + $txt = preg_replace( "#\s{1};#", ";", $txt ); + $txt = preg_replace( "#\t#", "    ", $txt ); + $txt = preg_replace( "#\s{2}#", "  ", $txt ); + + $p = "[code]{" . $this->code_count . "}[/code]"; + + $this->code_text[$p] = "[code]{$txt}[/code]"; + + return $p; + } + + function decode_code($txt = "", $use_html) { + +// $txt = stripslashes( $txt ); + $txt = str_replace( "&", "&", $txt ); + + if( $use_html ) { + $txt = str_replace( "<br />", "\n", $txt ); + } + + return "[code]".$txt."[/code]"; + } + + function build_video($url) { + global $config; + + if (!count($this->video_config)) { + + include (ENGINE_DIR . '/data/videoconfig.php'); + $this->video_config = $video_config; + + } + + $option = explode( "|", trim( $url ) ); + + $url = $this->clear_url( urldecode( $option[0] ) ); + + $type = explode( ".", $url ); + $type = strtolower( end( $type ) ); + + if( preg_match( "/[?&;%<\[\]]/", $url ) ) { + + return "[video=" . $url . "]"; + + } + + if( $option[1] != "" ) { + + $option[1] = htmlspecialchars( strip_tags( stripslashes( $option[1] ) ), ENT_QUOTES ); + $decode_url = $url . "|" . $option[1]; + + } else + $decode_url = $url; + + if( $type == "flv" or $type == "mp4" or $type == "m4v" or $type == "m4a" or $type == "mov" or $type == "3gp" or $type == "f4v") { + + if( $config['flv_watermark'] ) $watermark = "&logo={THEME}/dleimages/flv_watermark.png"; + else $watermark = ""; + + if( $option[1] != "" ) { + + $option[1] = "&image=".urlencode($option[1]); + + } + + $id_player = md5( microtime() ); + + $list = explode( ",", $url ); + $url = urlencode(trim($list[0])); + + $color = array (); + + if ($this->video_config['backgroundBarColor']) $color['backgroundBarColor'] = "&backgroundBarColor=".$this->video_config['backgroundBarColor']; + if ($this->video_config['btnsColor']) $color['btnsColor'] = "&btnsColor=".$this->video_config['btnsColor']; + if ($this->video_config['outputTxtColor']) $color['outputTxtColor'] = "&outputTxtColor=".$this->video_config['outputTxtColor']; + if ($this->video_config['outputBkgColor']) $color['outputBkgColor'] = "&outputBkgColor=".$this->video_config['outputBkgColor']; + if ($this->video_config['loadingBarColor']) $color['loadingBarColor'] = "&loadingBarColor=".$this->video_config['loadingBarColor']; + if ($this->video_config['loadingBackgroundColor']) $color['loadingBackgroundColor'] = "&loadingBackgroundColor=".$this->video_config['loadingBackgroundColor']; + if ($this->video_config['progressBarColor']) $color['progressBarColor'] = "&progressBarColor=".$this->video_config['progressBarColor']; + if ($this->video_config['volumeStatusBarColor']) $color['volumeStatusBarColor'] = "&volumeStatusBarColor=".$this->video_config['volumeStatusBarColor']; + if ($this->video_config['volumeBackgroundColor']) $color['volumeBackgroundColor'] = "&volumeBackgroundColor=".$this->video_config['volumeBackgroundColor']; + + return "video_config['width']}\" height=\"{$this->video_config['height']}\" id=\"Player-{$id_player}\"> + video_config['play']}{$color['backgroundBarColor']}{$color['btnsColor']}&outlineColor=0x666666{$color['outputBkgColor']}{$color['outputTxtColor']}{$color['loadingBarColor']}{$color['loadingBackgroundColor']}{$color['progressBarColor']}{$color['volumeBackgroundColor']}{$color['volumeStatusBarColor']}\" /> + + + + + video_config['play']}{$color['backgroundBarColor']}{$color['btnsColor']}&outlineColor=0x666666{$color['outputBkgColor']}{$color['outputTxtColor']}{$color['loadingBarColor']}{$color['loadingBackgroundColor']}{$color['progressBarColor']}{$color['volumeBackgroundColor']}{$color['volumeStatusBarColor']}\" quality=\"high\" bgcolor=\"#000000\" wmode=\"opaque\" allowFullScreen=\"true\" width=\"{$this->video_config['width']}\" height=\"{$this->video_config['height']}\" align=\"middle\" type=\"application/x-shockwave-flash\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\"> + "; + + + } elseif( $type == "avi" or $type == "divx" ) { + + return "video_config['width']}\" height=\"{$this->video_config['height']}\" codebase=\"http://go.divx.com/plugin/DivXBrowserPlugin.cab\"> + + + video_config['play']}\" /> + + + video_config['width']}\" height=\"{$this->video_config['height']}\" mode=\"zero\" autoPlay=\"{$this->video_config['play']}\" previewImage=\"{$option[1]}\" pluginspage=\"http://go.divx.com/plugin/download/\"> + + "; + + } else { + + return "video_config['width']}\" height=\"{$this->video_config['height']}\" classid=\"CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6\" standby=\"Loading Microsoft Windows Media Player components...\" type=\"application/x-oleobject\"> + + video_config['play']}\" /> + + + + + video_config['width']}\" height=\"{$this->video_config['height']}\" type=\"application/x-mplayer2\" autorewind=\"1\" showstatusbar=\"1\" showcontrols=\"1\" autostart=\"{$this->video_config['play']}\" allowchangedisplaysize=\"1\" volume=\"70\" stretchtofit=\"1\"> + "; + } + + } + function build_audio($url) { + global $config; + + if( $url == "" ) return; + + if( preg_match( "/[?&;%<\[\]]/", $url ) ) { + + return "[audio=" . $url . "]"; + } + + if (!count($this->video_config)) { + + include (ENGINE_DIR . '/data/videoconfig.php'); + $this->video_config = $video_config; + + } + + $url = $this->clear_url( urldecode( $url ) ); + + $list = explode( ",", $url ); + $url = urlencode(trim($list[0])); + + $list = implode( ",", $list ); + $id_player = md5( microtime() ); + $color = array (); + + if ($this->video_config['backgroundBarColor']) $color['backgroundBarColor'] = "&backgroundBarColor=".$this->video_config['backgroundBarColor']; + if ($this->video_config['btnsColor']) $color['btnsColor'] = "&btnsColor=".$this->video_config['btnsColor']; + if ($this->video_config['outputTxtColor']) $color['outputTxtColor'] = "&outputTxtColor=".$this->video_config['outputTxtColor']; + if ($this->video_config['outputBkgColor']) $color['outputBkgColor'] = "&outputBkgColor=".$this->video_config['outputBkgColor']; + if ($this->video_config['loadingBarColor']) $color['loadingBarColor'] = "&loadingBarColor=".$this->video_config['loadingBarColor']; + if ($this->video_config['loadingBackgroundColor']) $color['loadingBackgroundColor'] = "&loadingBackgroundColor=".$this->video_config['loadingBackgroundColor']; + if ($this->video_config['progressBarColor']) $color['progressBarColor'] = "&progressBarColor=".$this->video_config['progressBarColor']; + if ($this->video_config['volumeStatusBarColor']) $color['volumeStatusBarColor'] = "&volumeStatusBarColor=".$this->video_config['volumeStatusBarColor']; + if ($this->video_config['volumeBackgroundColor']) $color['volumeBackgroundColor'] = "&volumeBackgroundColor=".$this->video_config['volumeBackgroundColor']; + + + return "video_config['width']}\" height=\"30\" id=\"Player-{$id_player}\"> + video_config['play']}{$color['backgroundBarColor']}{$color['btnsColor']}&outlineColor=0x666666{$color['outputBkgColor']}{$color['outputTxtColor']}{$color['loadingBarColor']}{$color['loadingBackgroundColor']}{$color['progressBarColor']}{$color['volumeBackgroundColor']}{$color['volumeStatusBarColor']}\" /> + + + + video_config['play']}{$color['backgroundBarColor']}{$color['btnsColor']}&outlineColor=0x666666{$color['outputBkgColor']}{$color['outputTxtColor']}{$color['loadingBarColor']}{$color['loadingBackgroundColor']}{$color['progressBarColor']}{$color['volumeBackgroundColor']}{$color['volumeStatusBarColor']}\" quality=\"high\" wmode=\"transparent\" allowFullScreen=\"false\" width=\"{$this->video_config['width']}\" height=\"30\" align=\"middle\" type=\"application/x-shockwave-flash\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\"> + "; + + } + + function build_image($url = "", $align = "") { + global $config; + + $url = trim( $url ); + $url = urldecode( $url ); + $option = explode( "|", trim( $align ) ); + $align = $option[0]; + + if( $align != "left" and $align != "right" ) $align = ''; + + if( preg_match( "/[?&;%<\[\]]/", $url ) ) { + + if( $align != "" ) return "[img=" . $align . "]" . $url . "[/img]"; + else return "[img]" . $url . "[/img]"; + + } + + $url = $this->clear_url( urldecode( $url ) ); + + $info = $url; + + $info = $info."|".$align; + + if( $url == "" ) return; + + if( $option[1] != "" ) { + + $alt = htmlspecialchars( strip_tags( stripslashes( $option[1] ) ), ENT_QUOTES ); + $info = $info."|".$alt; + $caption = "" . $alt . ""; + $alt = "alt=\"" . $alt . "\" title=\"" . $alt . "\" "; + + } else { + + $alt = htmlspecialchars( strip_tags( stripslashes( $_POST['title'] ) ), ENT_QUOTES ); + $caption = ""; + $alt = "alt=\"" . $alt . "\" title=\"" . $alt . "\" "; + + } + + if( intval( $config['tag_img_width'] ) ) { + + if (clean_url( $config['http_home_url'] ) != clean_url ( $url ) ) { + + $img_info = @getimagesize( $url ); + + if( $img_info[0] > $config['tag_img_width'] ) { + + $out_heigh = ($img_info[1] / 100) * ($config['tag_img_width'] / ($img_info[0] / 100)); + $out_heigh = floor( $out_heigh ); + + if( $align == '' ) return "{$caption}"; + else return "{$caption}"; + + + } + } + } + + + if( $align == '' ) return ""; + else return ""; + + } + + function decode_dle_img($txt) { + + $txt = stripslashes( $txt ); + $txt = explode("|", $txt ); + $url = $txt[0]; + $align = $txt[1]; + $alt = $txt[2]; + $extra = ""; + + if( ! $align and ! $alt ) return "[img]" . $url . "[/img]"; + + if( $align ) $extra = $align; + if( $alt ) { + + $alt = str_replace("'", "'", $alt); + $alt = str_replace(""", '"', $alt); + $alt = str_replace("&", '&', $alt); + $extra .= "|" . $alt; + + } + + return "[img=" . $extra . "]" . $url . "[/img]"; + + } + + function build_thumb($gurl = "", $url = "", $align = "") { + $url = trim( $url ); + $gurl = trim( $gurl ); + $option = explode( "|", trim( $align ) ); + + $align = $option[0]; + + if( $align != "left" and $align != "right" ) $align = ''; + + if( preg_match( "/[?&;%<\[\]]/", $gurl ) ) { + + if( $align != "" ) return "[thumb=" . $align . "]" . $gurl . "[/thumb]"; + else return "[thumb]" . $gurl . "[/thumb]"; + + } + + $url = $this->clear_url( urldecode( $url ) ); + $gurl = $this->clear_url( urldecode( $gurl ) ); + + if( $gurl == "" or $url == "" ) return; + + if( $option[1] != "" ) { + + $alt = htmlspecialchars( strip_tags( stripslashes( $option[1] ) ), ENT_QUOTES ); + $caption = "" . $alt . ""; + $alt = "alt=\"" . $alt . "\" title=\"" . $alt . "\" "; + + } else { + + $alt = htmlspecialchars( strip_tags( stripslashes( $_POST['title'] ) ), ENT_QUOTES ); + $alt = "alt='" . $alt . "' title='" . $alt . "' "; + $caption = ""; + + } + + if( $align == '' ) return "{$caption}"; + else return "{$caption}"; + + } + + function build_spoiler($title = "") { + global $lang; + + $title = trim( $title ); + + $title = stripslashes( $title ); + $title = str_replace( "&amp;", "&", $title ); + $title = preg_replace( "/javascript:/i", "javascript: ", $title ); + + $id_spoiler = md5( microtime() ); + + if( ! $title ) { + + return "
"; + + } else { + + return "
"; + + } + + } + + function clear_url($url) { + + $url = strip_tags( trim( stripslashes( $url ) ) ); + + $url = str_replace( '\"', '"', $url ); + + if( ! $this->safe_mode or $this->wysiwyg ) { + + $url = htmlspecialchars( $url, ENT_QUOTES ); + + } + + $url = str_replace( "document.cookie", "", $url ); + $url = str_replace( " ", "%20", $url ); + $url = str_replace( "'", "", $url ); + $url = str_replace( '"', "", $url ); + $url = str_replace( "<", "<", $url ); + $url = str_replace( ">", ">", $url ); + $url = preg_replace( "/javascript:/i", "", $url ); + $url = preg_replace( "/data:/i", "", $url ); + + return $url; + + } + + function decode_leech($url = "", $show = "") { + + $show = stripslashes( $show ); + + if( $this->leech_mode ) return "[url=" . $url . "]" . $show . "[/url]"; + + $url = explode( "url=", $url ); + $url = end( $url ); + $url = rawurldecode( $url ); + $url = base64_decode( $url ); + $url = str_replace("&","&", $url ); + + return "[leech=" . $url . "]" . $show . "[/leech]"; + } + + function decode_url($url = "", $show = "") { + + $show = stripslashes( $show ); + + $url = str_replace("&","&", $url ); + + return "[url=" . $url . "]" . $show . "[/url]"; + } + + function decode_thumb($txt) { + $align = false; + $alt = false; + $extra = ""; + $txt = stripslashes( $txt ); + + $url = str_replace( "safe_mode ) $allow_find = false; + if ( $word_arr[5] == 2 AND !$this->safe_mode ) $allow_find = false; + + if ( $allow_find ) { + + if( $word_arr[3] ) { + + $find_text = "#(^|\b|\s|\
)" . preg_quote( $word_arr[1], "#" ) . "(\b|!|\?|\.|,|$)#".$register; + + if( $word_arr[2] == "" ) $replace_text = "\\1"; + else $replace_text = "\\1" . $word_arr[2] . ""; + + } else { + + $find_text = "#(" . preg_quote( $word_arr[1], "#" ) . ")#".$register; + + if( $word_arr[2] == "" ) $replace_text = ""; + else $replace_text = "" . $word_arr[2] . ""; + + } + + if ( $word_arr[6] ) { + + if ( preg_match($find_text, $source) ) { + + $this->not_allowed_text = true; + return $source; + + } + + } else { + + $find[] = $find_text; + $replace[] = $replace_text; + } + + } + + } + + if( !count( $find ) ) return $source; + + $source = preg_split( '((>)|(<))', $source, - 1, PREG_SPLIT_DELIM_CAPTURE ); + $count = count( $source ); + + for($i = 0; $i < $count; $i ++) { + if( $source[$i] == "<" or $source[$i] == "[" ) { + $i ++; + continue; + } + + if( $source[$i] != "" ) $source[$i] = preg_replace( $find, $replace, $source[$i] ); + } + + $source = join( "", $source ); + + } else { + + $source = preg_replace( "#(.+?)#", "\\1", $source ); + + } + + return $source; + } + +} +?> \ No newline at end of file diff --git a/XenForo_uploads/library/DLEIntegration/config/dle_config.php b/XenForo_uploads/library/DLEIntegration/config/dle_config.php new file mode 100644 index 0000000..197192b --- /dev/null +++ b/XenForo_uploads/library/DLEIntegration/config/dle_config.php @@ -0,0 +1,18 @@ + \ No newline at end of file diff --git a/addon-DLEIntegration.xml b/addon-DLEIntegration.xml new file mode 100644 index 0000000..0de6e88 --- /dev/null +++ b/addon-DLEIntegration.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/templates_utf-8/block_forum_posts.tpl b/templates_utf-8/block_forum_posts.tpl new file mode 100644 index 0000000..97819cf --- /dev/null +++ b/templates_utf-8/block_forum_posts.tpl @@ -0,0 +1,13 @@ + + + + + + + + + [row] + + + [/row] +
ФорумНазвание темыПользовательПросмотровОтветов
{forum_name}{shot_name_post}{user}{view_count}{reply_count}
\ No newline at end of file diff --git a/templates_windows-1251/block_forum_posts.tpl b/templates_windows-1251/block_forum_posts.tpl new file mode 100644 index 0000000..61172df --- /dev/null +++ b/templates_windows-1251/block_forum_posts.tpl @@ -0,0 +1,13 @@ + + + + + + + + + [row] + + + [/row] +
{forum_name}{shot_name_post}{user}{view_count}{reply_count}
\ No newline at end of file