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, "" . $tagName ) ) $preTag .= '>';
+ else $preTag .= ' />';
+ } else
+ $preTag .= '' . $tagName . '>';
+ }
+ $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( "