Просмотр файла engine/includes/start.php

Размер файла: 11.44Kb
  1. <?php
  2. /**
  3. * @author DESURE
  4. * @author Tadochi
  5. */
  6.  
  7.  
  8. /**
  9. * @const START for Generation
  10. * @const H for Inlcudes
  11. */
  12.  
  13. define('START', microtime(1));
  14. define('H', $_SERVER['DOCUMENT_ROOT'].'/');
  15. define('CPU', memory_get_usage());
  16. define('incDir', H.'engine/includes/'); // так я захотел
  17. define('tmpDir', H.'engine/files/tmp/');
  18.  
  19.  
  20. if (file_exists(H.'engine/files/data/settings.ini'))
  21. {
  22. $set = parse_ini_file(H.'engine/files/data/settings.ini');
  23. }
  24. else
  25. exit('<a href="/install/">Установить</a>');
  26.  
  27.  
  28. if (is_file(H . 'engine/files/data/flood_config.swi'))
  29. {
  30. Core::get('floodblocker', 'classes');
  31. $flood = new FloodBlocker;
  32. if (!$flood->CheckFlood())
  33. {
  34. die('Слишком много запросов. Попробуйте позже');
  35. }
  36. unset($flood);
  37. }
  38.  
  39.  
  40. /**
  41. * @var $time время в timestamp. осталось из Dcms 6.6.4
  42. */
  43.  
  44. $time = time();
  45.  
  46.  
  47. /**
  48. * @var $id , $act чтобы 100 раз не проверять
  49. */
  50.  
  51. $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
  52. $act = isset($_GET['act']) ? $_GET['act'] : false;
  53. $cur_page = isset($_GET['page']) ? intval($_GET['page']) : 0;
  54. $sql = include H.'engine/classes/mysqli.class.php';
  55.  
  56. session_name('Secwind');
  57. session_start();
  58.  
  59. //if (is_callable('ini_set')) {
  60. @set_time_limit(6);
  61. @ini_set('html_errors', 1);
  62.  
  63. set_error_handler('error_catch');
  64.  
  65.  
  66. /**
  67. * @class Core эдакий контейнер функций
  68. * @author Tadochi
  69. */
  70.  
  71. Class Core
  72. {
  73. static $user_id = 0;
  74.  
  75. function __construct()
  76. {
  77. self::$user_id = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : 0; // self::$user_id = isset($_SESSION['user_id']);
  78. }
  79.  
  80.  
  81. /**
  82. * Cache юзеров.
  83. * 1000 юзеров = 1000 файлов =)
  84. * @param integer $id id юзера, данные которого нужно получить
  85. * @param boolen $update если указать true, данные обновятся
  86. * @return array
  87. */
  88.  
  89. static function get_user($id, $update = false)
  90. {
  91. if (
  92. $update ||
  93. !file_exists(H.'engine/files/users/cache/'.$id.'.db') ||
  94. filemtime(H.'engine/files/users/cache/'.$id.'.db') > (time() + 3600)
  95. )
  96. {
  97. global $sql;
  98. $user = $sql->query('select * from `user` where `id` = "' . $id . '" limit 1 ')->fetch();
  99. if (!$user)
  100. return
  101. array('id' => 0, 'nick' => 'Гость', 'pol' => 1);
  102. file_put_contents(H.'engine/files/users/cache/'.$id.'.db', serialize($user));
  103. unset($sql, $user);
  104. }
  105. return
  106. unserialize(file_get_contents(H.'engine/files/users/cache/'.$id.'.db'));
  107. }
  108.  
  109.  
  110. /**
  111. * Перенаправление
  112. * @param string $stop
  113. */
  114. static function stop($page = '/')
  115. {
  116. header('location: '.$page);
  117. exit;
  118. }
  119.  
  120.  
  121. /**
  122. * Сохранение настроек
  123. */
  124.  
  125. static function save_settings($set, $file = 'engine/files/data/settings.ini')
  126. {
  127. include_once H.'engine/classes/ini.class.php';
  128. $ini = new ini(H . $file);
  129. foreach($set as $key => $value)
  130. {
  131. $ini->write($key, '"'.$value.'"');
  132. }
  133. return $ini->updateFile();
  134. }
  135. /**
  136. * Вывод даты
  137. * @param integer $time
  138. */
  139. static function time($time)
  140. {
  141. return date('d.m.Y / H:i', $time);
  142. }
  143. /**
  144. * Рекурсивное подключение файлов
  145. * @param mixed $file принимает массив или строку
  146. * @param $path (string) папка файла
  147. */
  148. static function get($file, $path = 'classes')
  149. {
  150. if (is_array($file))
  151. {
  152. foreach($file as $file)
  153. {
  154. self::get($file, $path);
  155. }
  156. }
  157. elseif (file_exists(H.'engine/'.$path.'/'.$file.'.php'))
  158. {
  159. include_once H.'engine/'.$path.'/'.$file.'.php';
  160. }//else die('file engine/'.$path.'/'.$file.'.php not found');
  161. }
  162.  
  163. /**
  164. * Вывод сообщений. Аналог msg() и err()
  165. * @param $msg (mixed) выводимое сообщение. Может быть массивом или строкой
  166. * @param $div (string) класс div'а.
  167. */
  168.  
  169. static function msg_show($msg, $div = 'error')
  170. {
  171. if (is_array($msg))
  172. {
  173. foreach($msg as $msg)
  174. {
  175. echo '<div class="'.$div.'">'.$msg.'</div>';
  176. }
  177. }
  178. else
  179. echo '<div class="'.$div.'">'.$msg.'</div>';
  180. }
  181.  
  182. /**
  183. * Вывод пользователя. Сюда и пихаем код медалек
  184. * @param $user (array) массив юзера
  185. * @param $data (array) $data['post'] текст который выводится снизу. $data['status'] текст который выводится рядом с ником. $data['is_time'] true сли $data['status'] показатель времени
  186. */
  187.  
  188. static function user_show($user, $data = array())
  189. {
  190. return
  191. self::user_icon($user) .
  192. ' <a href="/pages/user.php?id='.$user['id'].'"> ' .
  193. $user['nick'] . ' </a>'.
  194. (isset($data['status']) ? '<span class="status">(' . (isset($data['is_time']) ? Core::time($data['status']) : $data['status']) . ')</span>' : null) .
  195. '<br />'. (!empty($data['post']) ? $data['post'] : null);
  196. }
  197.  
  198. // вывод иконки юзера
  199.  
  200. static function user_icon($user)
  201. {
  202. return '<img src="/style/users/icons/'.$user['pol'].'.png" alt=""/>';
  203. }
  204.  
  205. // вывод аватара юзера
  206.  
  207. static function user_avatar($ava_id = 0, $return = 'image')
  208. {
  209. if (!$ava_id)
  210. $ava_id = Core::$user_id;
  211. $id = file_exists(H . 'style/users/avatar/'.$ava_id.'.jpg') ? $ava_id : 0;
  212. return $return == 'image' ? '<img src="/style/users/avatar/'.$id.'.jpg"/>' : '/style/users/avatar/'.$id.'.jpg';
  213. }
  214.  
  215. // Получение данных о SW
  216.  
  217. static function Secwind($key = false)
  218. {
  219. $inf = unserialize(file_get_contents(H . 'engine/files/data/secwind.db'));
  220. return $key ? $inf[$key] : var_export($inf);
  221. }
  222.  
  223. // Получение фильтрированных данных из $_GET
  224.  
  225. static function Request($key)
  226. {
  227. return
  228. isset($_GET[$key]) ?
  229. is_array($_GET[$key]) ?
  230. $_GET[$key] :
  231. my_esc($_GET[$key], true) :
  232. false;
  233. }
  234.  
  235. static function form($key)
  236. {
  237. return
  238. isset($_POST[$key]) ?
  239. is_array($_POST[$key]) ?
  240. $_POST[$key] :
  241. my_esc($_POST[$key], true) :
  242. false;
  243. }
  244. }
  245.  
  246.  
  247. /**
  248. * Дабы все не заменять)) осталось из Dcms 6.6.4
  249. */
  250. function my_esc($str, $html = false)
  251. {
  252. global $sql;
  253. if ($html)
  254. $str = htmlspecialchars($str);
  255. return mysqli_real_escape_string($sql->db, $str);
  256. }
  257.  
  258. /**
  259. * Перехват ошибок
  260. * строка 27
  261. */
  262.  
  263. function error_catch($errno, $errstr, $errfile, $errline, $desc, $type = 'php')
  264. {
  265. if ( 0 == error_reporting ())
  266. {
  267. return;
  268. }
  269. global $sql, $creator;
  270.  
  271. if ($type == 'php')
  272. $desc = $errstr . ' | Файл ' . $errfile . ' | Линия - ' . $errline;
  273.  
  274. if ($creator && $type == 'php')
  275. echo $desc . '<br />';
  276.  
  277. $sql->query("
  278. INSERT INTO `errors`
  279. (`user` , `time`, `user_agent`, `ip`, `desc`, `type`, `url`) VALUES
  280. ('".Core::$user_id."', '".time()."', '".my_esc($_SERVER['HTTP_USER_AGENT'], true)."', '".my_esc($_SERVER['REMOTE_ADDR'], true)."', '".my_esc($desc)."', '".$type."', '".my_esc($_SERVER['REQUEST_URI'], true)."');");
  281. }
  282.  
  283.  
  284.  
  285. /**
  286. * Авторизация
  287. */
  288. if (isset($_SESSION['user_id']) && $sql->query('SELECT COUNT(*) FROM `user` WHERE `id` = '.$_SESSION['user_id'].' LIMIT 1')->result() == 1)
  289. {
  290. $user = Core::get_user($_SESSION['user_id']);
  291. $user_id = $user['id'];
  292. if (mt_rand(0, 5) == 4)
  293. $sql->query('UPDATE `user` SET `date_last` = '.$time.' WHERE `id` = '.$user['id'].' LIMIT 1');
  294. }
  295. else
  296. $user_id = 0;
  297.  
  298. if (!$user_id &&
  299. isset($_COOKIE['user_id'], $_COOKIE['pass']) &&
  300. $sql->query("SELECT COUNT(*) FROM `user` WHERE `id` = ".intval($_COOKIE['user_id'])." AND `pass` = '".my_esc($_COOKIE['pass'])."' LIMIT 1")->result() == 1)
  301. {
  302. $user = Core::get_user($_COOKIE['user_id']);
  303. $user_id = $_SESSION['user_id'] = $user['id'];
  304. $sql->query('select `file` from `module_services` where `use_in` = "auth"');
  305. $_SESSION['user_authed'] = 'COOKIE';
  306. }
  307.  
  308.  
  309. /**
  310. * @var $user_id (boolen) вернет true если юзер авторизован
  311. * @var $moder (boolen) вернет true для модератора
  312. * @var $admin (boolen) вернет true для админа
  313. * @var $creator (boolen) вернет true для создателя
  314. * @var $author (boolen) вернет true если юзер - автор
  315. */
  316.  
  317. $user_id = isset($_SESSION['user_id']) ? $user['id'] : 0;
  318. $moder = $user_id && $user['group_access'] > 1;
  319. $admin = $user_id && $user['group_access'] > 2;
  320. $creator = $user_id && $user['group_access'] > 9;
  321. //$author = $user_id == $id;
  322.  
  323.  
  324.  
  325. /**
  326. * @author Tadochi
  327. * @package AntiHack =)
  328. *
  329. * По дефолту - отключен
  330. * Рекурсивно фильтрует все.
  331. * Даже массивы в массивах :-D :зар:
  332. * Не тот быдлокод который гуляет по паблу.
  333. * Пабличные только мешают . Своим присутствием
  334. * И вспомните dcms-fiera. "Опросы" ведь выпилены из за антихака =)
  335. *
  336. * Запрещено использовать где-либо, кроме SecWind.
  337. */
  338.  
  339. function helper_awr(&$value, $key)
  340. {
  341. $key = my_esc($value, false);
  342. }
  343.  
  344. function helper_hsc(&$value, $key)
  345. {
  346. $key = htmlspecialchars($value);
  347. }
  348.  
  349. if ($set['filtr_get'])
  350. {
  351. array_walk_recursive($_GET, 'helper_awr');
  352. }
  353.  
  354. if ($set['filtr_post'])
  355. {
  356. array_walk_recursive($_POST, 'helper_awr');
  357. }
  358.  
  359. if ($set['antixss'])
  360. {
  361.  
  362. /*
  363. * Защита/предупреждение XSS-атак
  364. * Author: Yuri 'Bela' Belotitski
  365. */
  366.  
  367. if (isset($_SERVER['HTTP_REFERER']))
  368. {
  369. $ref = parse_url($_SERVER['HTTP_REFERER']);
  370. if (!substr_count($ref['host'], $_SERVER['HTTP_HOST']))
  371. {
  372. if ($_POST) die('<b>Achtung! XSS attack!</b>');
  373. if ($_GET) die('<b>Achtung! XSS attack?></b><br />Подтвердите переход: <a href="'
  374. . htmlspecialchars($_SERVER['REQUEST_URI']) . '">'
  375. . htmlspecialchars($_SERVER['REQUEST_URI']) . '</a>');
  376. }
  377. }
  378.  
  379. // а это уже мое
  380.  
  381. array_walk_recursive($_GET, 'helper_hsc');
  382. array_walk_recursive($_POST, 'helper_hsc');
  383. }
  384.  
  385.  
  386.  
  387. /*
  388. * SecWind?
  389. * Вообще не торгать.
  390. */
  391.  
  392. if (isset($_GET['you_secwind?']))
  393. {
  394. exit(Core::Secwind('version'));
  395. }
  396.  
  397. new Core;
  398. ob_start();