· 7 years ago · Oct 30, 2018, 08:04 PM
1<?php
2
3function to_link($text) {
4 $text= preg_replace("/(^|[\n ])([\w]*?)((ht|f)tp(s)?:\/\/[\w]+[^ \,\"\n\r\t<]*)/is", "$1$2<a target='_blank' href=\"$3\" ><div style='width: 150px; display: inline-flex;' class='uk-text-truncate'>$3</div>... <i style='font-size: 10px;' class='uk-icon-external-link'></i></a>", $text);
5 $text= preg_replace("/(^|[\n ])([\w]*?)((www|ftp)\.[^ \,\"\t\n\r<]*)/is", "$1$2<a target='_blank' href=\"http://$3\" ><div style='width: 150px; display: inline-flex;' class='uk-text-truncate'>$3</div>... <i style='font-size: 10px;' class='uk-icon-external-link'></i></a>", $text);
6 $text= preg_replace("/(^|[\n ])([a-z0-9&\-_\.]+?)@([\w\-]+\.([\w\-\.]+)+)/i", "$1<a target='_blank' href=\"mailto:$2@$3\"><div style='width: 150px; display: inline-flex;' class='uk-text-truncate'>$2@$3</div>... <i style='font-size: 10px;' class='uk-icon-external-link'></i></a>", $text);
7 return($text);
8}
9
10function getParam($param){
11 if($param){
12 global $sv;
13 $select = $sv->super_query("SELECT value FROM my_system WHERE param='$param'");
14 return $select['value'];
15 $sv->free();
16 }
17}
18
19function setParam($param, $value){
20 if($param){
21 global $sv;
22 $sv->super_query("UPDATE my_system SET value='$value' WHERE param='$param'");
23 $sv->free();
24 }
25}
26
27function getUnixTime($date){
28 $date = str_replace("T", " ", $date);
29 $date = str_replace("-", ".", $date);
30 $untilGet = explode(" ", $date);//Делим на дату и времÑ
31 $dateGet = explode(".", $untilGet[0]); //Разбиваем дату
32 $timeGet = explode(":", $untilGet[1]); //Разбиваем времÑ
33 return mktime($timeGet[0], $timeGet[1], 0, $dateGet[1], $dateGet[2], $dateGet[0]); //Unix Ð²Ñ€ÐµÐ¼Ñ Ð´Ð¾
34}
35
36
37function generate_password($number){
38 $arr = array('a','b','c','d','e','f',
39 'g','h','i','j','k','l',
40 'm','n','o','p','r','s',
41 't','u','v','x','y','z',
42 'A','B','C','D','E','F',
43 'G','H','I','J','K','L',
44 'M','N','O','P','R','S',
45 'T','U','V','X','Y','Z',
46 '1','2','3','4','5','6',
47 '7','8','9','0');
48 $pass = "";
49 for($i = 0; $i < $number; $i++){
50 $index = rand(0, count($arr) - 1);
51 $pass .= $arr[$index];
52 }
53 return $pass;
54}
55
56function SaveLog($username, $action) {
57 global $sv;
58 $action = $sv->safesql($action);
59 $sv->query("INSERT INTO my_donate_log VALUES(null, '$username', '".time()."', '$action')");
60}
61/*
62* запиÑÑŒ информации о Ñчете Ð¿Ð¾Ð»ÑŒÐ·Ð¾Ð²Ð°Ñ‚ÐµÐ»Ñ Ð² дополнительную таблицу
63*/
64function SaveCashLog($account) {
65 global $db;
66 $sql = "SELECT * FROM dle_users WHERE name = '$account' LIMIT 1";
67 $result = $db->query($sql);
68 $userInfo = $result->fetch_object();
69
70 if($userInfo){
71 $logTable = 'lemon_pays';
72 $donate = $userInfo->cash;
73 $sql = "SELECT * FROM ".$logTable." WHERE name = '$account' LIMIT 1";
74 $result = $db->query($sql);
75 if($result->fetch_object()){ // еÑли запиÑÑŒ еÑть - обновлÑем
76 $query = "UPDATE ".$logTable." SET sum = $donate WHERE name = '$account'";
77 }else{// еÑли запиÑи нет - вÑтавлÑем
78 $query = "INSERT INTO ".$logTable." (name, sum) VALUES ('$account','$donate')";
79 }
80
81 return $db->query($query);
82 }else{
83 return false;
84 }
85}
86
87
88/*
89 * Определение IP пользователÑ
90 * */
91function getRealIP(){
92 $headers = array(
93 'HTTP_X_FORWARDED_FOR', 'HTTP_X_CLUSTER_CLIENT_IP',
94 'HTTP_FORWARDED_FOR', 'HTTP_X_FORWARDED',
95 'HTTP_FORWARDED', 'HTTP_VIA', 'HTTP_X_COMING_FROM',
96 'HTTP_X_COMING_FROM', 'HTTP_COMING_FROM',
97 'REMOTE_ADDR'
98 );
99 foreach ($headers as $header) {
100 if (isset($_SERVER[$header])) {
101 $return = $_SERVER[$header];
102 $return2 = preg_replace("/[^.0-9]/", '', $return);
103 if ($return != $return2) {
104
105 $text = "------------------------------\n";
106 $text .= "Дата и времÑ: ".date('Y-m-d H:i:s')." \n";
107 $text .= "Тип запроÑа: SERVER\n";
108 $text .= "Страница: ".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']." \n";
109 $text .= "Лог запроÑа в виде serialize: ".serialize($return)."\n";
110 $text .= "Лог запроÑа в виде json: ".json_encode($return)."\n";
111
112 file_put_contents($_SERVER['DOCUMENT_ROOT'].'/logs/headers_'.date('Y-m-d').'.log', $text, FILE_APPEND|LOCK_EX);
113
114 die( "Hacking attempt!" );
115 }
116 return $return2;
117 }
118 }
119}
120
121
122/*
123* получение информации о Ñчете Ð¿Ð¾Ð»ÑŒÐ·Ð¾Ð²Ð°Ñ‚ÐµÐ»Ñ Ð¸Ð· таблицы
124*/
125function getCashInfo($account) {
126 global $db;
127 $cashTable = 'lemon_pays';
128 $sql = "SELECT * FROM ".$cashTable." WHERE name = '$account' LIMIT 1";
129 $result = $db->query($sql);
130 $result = $result->fetch_object();
131 if(!$result){
132 //еÑли нет запиÑи берем информацию из таблицы пользователей
133 $sql = "SELECT * FROM dle_users WHERE name = '$account' LIMIT 1";
134 $result = $db->query($sql);
135 $userInfo = $result->fetch_object();
136
137 $sum = $userInfo->cash;
138 if (!$sum) {
139 $sum = 0;
140 }
141 // изаводим запиÑÑŒ в таблице "кошельков"
142 $query = "INSERT INTO ".$cashTable." (name, sum) VALUES ('$account','$sum')";
143 $db->query($query);
144 }else{
145
146 $sum = $result->sum;
147 }
148 return $sum;
149}
150
151/*
152* запиÑÑŒ информации о Ñчете Ð¿Ð¾Ð»ÑŒÐ·Ð¾Ð²Ð°Ñ‚ÐµÐ»Ñ Ð² таблицу
153*/
154function setCashInfo($account, $summa = 0) {
155 global $db;
156 setlocale(LC_NUMERIC, "C");
157 $cashTable = 'lemon_pays';
158 $sql = "SELECT * FROM ".$cashTable." WHERE name = '$account' LIMIT 1";
159 $result = $db->query($sql);
160 $result = $result->fetch_object();
161 if($result){ // на момент запиÑи данных о движении ÑредÑтв Ð¸Ð½Ñ„Ð¾Ñ€Ð¼Ð°Ñ†Ð¸Ñ Ð¾ пользователе в таблице кошельков должна уже быть
162 $summa = floatval(str_replace(",", ".", $summa));
163 $result->sum = floatval($result->sum);
164 $sum = $result->sum + $summa;
165 // обновлÑем запиÑÑŒ в таблице "кошельков"
166 $query = "UPDATE ".$cashTable." SET sum = $sum WHERE name = '$account'";
167 return $db->query($query);
168 return true;
169 }else{ // иначе возвращаем ошибку
170 return false;
171 }
172}
173
174
175
176
177
178//начало вÑтавки
179/*
180* платный или беÑплатный Ð¿ÐµÑ€ÐµÐ½Ð¾Ñ Ð¿Ñ€Ð¸Ð²ÐµÐ»ÐµÐ³Ð¸Ð¹
181*/
182function isPayTransfer($username, $buy_date) {
183 global $sm;
184
185 $return = true;
186 if ($buy_date) {
187 $table = 'claim';
188 $d = new DateTime($buy_date);
189 $d->modify("+1 day");
190
191 if ($d->format('Y-m-d H:i:s') >= date('Y-m-d H:i:s')) {
192
193 $sql = "SELECT * FROM " . $table . " WHERE (user = '" . $username . "') AND (buy_date='".$buy_date."')";
194 $result = $sm->super_query( $sql, TRUE );
195 if (!$result) {
196 $return = false;
197 }
198 }
199 }
200
201 return $return;
202}
203
204/*
205* запиÑÑŒ информации о переноÑе привелегий
206*/
207function setTransferInfo($username, $fromServer, $toServer , $group, $cost, $date, $buy_date) {
208 global $sm;
209 $sql = "INSERT INTO claim (user, server_from, server_to, groupName, cost, transfer_date, buy_date) VALUES ('$username', '$fromServer', '$toServer', '$group','$cost', '$date', '$buy_date')";
210 return $sm->super_query($sql, true);
211}
212//конец вÑтавки
213
214
215/*
216* получение полного ÑпиÑка модераторов (Ð´Ð»Ñ Ñтраницы /team.html)
217*/
218function getModersFullList() {
219 global $db;
220 $table = 'm_moderators';
221 $sql = "SELECT * FROM " . $table . " WHERE show_in_team=1 ORDER BY user_group, username";
222 $result = $db->super_query( $sql, TRUE );
223
224 return $result;
225}
226
227/*
228* получение информации о поÑледнем входе пользователÑ
229*/
230function getUserVisit($username) {
231 global $db;
232 $table = 'auth';
233 $sql = "SELECT lasttime, lastserver FROM " . $table . " WHERE login='".$username."' ORDER BY id DESC LIMIT 1";
234 if ($result = $db->super_query( $sql, TRUE )) {
235 $result = $result[0];
236 };
237 return $result;
238}
239
240/*
241* маÑÑив груп модераторов
242*/
243function getModersGroups() {
244 return Array(
245 Array(
246 'name'=>'Admins',
247 'title'=>'ÐдминиÑтратор',
248 'groupTitle'=>'ГЛÐÐ’ÐÐЯ ÐДМИÐИСТРÐЦИЯ',
249 ),
250 Array(
251 'name'=>'GrandModer',
252 'title'=>'Главный Модератор',
253 'groupTitle'=>'Главные Модераторы',
254 ),
255 Array(
256 'name'=>'Moders',
257 'title'=>'Модератор',
258 'groupTitle'=>'Модераторы',
259 ),
260 Array(
261 'name'=>'Helper',
262 'title'=>'Хелпер',
263 'groupTitle'=>'Хелперы',
264 ),
265 Array(
266 'name'=>'Warder',
267 'title'=>'Стажёр',
268 'groupTitle'=>'Стажёры',
269 ),
270 Array(
271 'name'=>'Builder',
272 'title'=>'Строитель',
273 'groupTitle'=>'Билдеры',
274 ),
275 Array(
276 'name'=>'Java',
277 'title'=>'Java программиÑÑ‚',
278 'groupTitle'=>'ТехничеÑÐºÐ°Ñ ÐдминиÑтрациÑ',
279 )
280 );
281}
282//конец вÑтавки
283
284
285/*
286* получение информации о Ñерверах
287*/
288function getServerData() {
289 global $sm;
290 global $servers_permissions;
291 $servers_permissions = Array();
292 $serverTable = 'b_monitor';
293 $sql = "SELECT * FROM ".$serverTable." WHERE published = 1 ORDER BY server";
294 $result = $sm->super_query($sql, true);
295 if (count($result)) {
296 foreach ($result as $server) {
297 if ($server['db_login'] && $server['db_name'] && $server['db_host']) {
298 $db_user = $server['db_login'];
299 $db_password = $server['db_pass'];
300 $db_namedb = $server['db_name'];
301 $db_local = $server['db_host'];
302 $db_error = 1;
303 $serverDb = new db;
304 if ($serverDb->connect($db_user, $db_password, $db_namedb, $db_local, $db_error)) {
305 $serverObject = new stdClass();
306 $serverObject->id = $server['id'];
307 $serverObject->name = $server['server'];
308 $serverObject->name_short = isset($server['server_short']) ? $server['server_short'] : '';
309 $serverObject->name_html = isset($server['server_html']) ? $server['server_html'] : '';
310 $serverObject->link = isset($server['link']) ? $server['link'] : '';
311 $serverObject->active = $server['active'];
312 $serverObject->db = $serverDb;
313
314 $servers_permissions[$server['id']] = $serverObject;
315
316 $sql = "CREATE TABLE IF NOT EXISTS `permissions` (
317 `id` int(11) NOT NULL AUTO_INCREMENT,
318 `name` varchar(50) NOT NULL,
319 `type` tinyint(1) NOT NULL,
320 `permission` varchar(200) NOT NULL,
321 `world` varchar(50) NOT NULL,
322 `value` text NOT NULL,
323 `buy_date` datetime NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT 'Дата покупки привелегии',
324 PRIMARY KEY (`id`),
325 UNIQUE KEY `unique` (`name`,`permission`,`world`,`type`),
326 KEY `user` (`name`,`type`),
327 KEY `world` (`world`,`name`,`type`)
328 ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1";
329 $serverDb->super_query($sql, true);
330
331 $sql = "CREATE TABLE IF NOT EXISTS `permissions_inheritance` (
332 `id` int(11) NOT NULL AUTO_INCREMENT,
333 `child` varchar(50) NOT NULL,
334 `parent` varchar(50) NOT NULL,
335 `type` tinyint(1) NOT NULL,
336 `world` varchar(50) DEFAULT NULL,
337 PRIMARY KEY (`id`),
338 UNIQUE KEY `child` (`child`,`parent`,`type`,`world`),
339 KEY `child_2` (`child`,`type`),
340 KEY `parent` (`parent`,`type`)
341 ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1";
342 $serverDb->super_query($sql, true);
343
344 $sql = "CREATE TABLE IF NOT EXISTS `dle_users` (
345 `user_id` int(11) NOT NULL AUTO_INCREMENT,
346 `name` varchar(40) NOT NULL DEFAULT '',
347 `group_params` varchar(10) NOT NULL,
348 PRIMARY KEY (`user_id`),
349 UNIQUE KEY `name` (`name`)
350 ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;";
351 $serverDb->super_query($sql, true);
352
353 }
354 }
355 }
356 return $servers_permissions;
357 } else {
358 return false;
359 }
360}
361
362
363/*
364*
365*/
366function validateUserInDbs($username, $servers){
367 $return = Array();
368 if($username && count($servers)){
369 foreach ($servers as $server) {
370 if (!$server->db->super_query("SELECT * FROM dle_users WHERE name='$username'")) {
371 $server->db->query("INSERT INTO dle_users (name, group_params) VALUES ('$username', '')");
372 }
373 }
374 }
375 return $return;
376}
377
378
379
380
381
382
383/*
384* Ñ„ÑƒÐ½ÐºÑ†Ð¸Ñ Ð²Ñ‹Ð³Ñ€ÑƒÐ·ÐºÐ¸ файлов на ftp
385*/
386function uploadImageFtp($file, $remote_file, $type, $remote = false) {
387 global $ftp_server,
388 $ftp_user_name,
389 $ftp_user_pass;
390
391 $local_tmp_dir = '/var/www/skins/'; // папка Ð´Ð»Ñ Ð²Ñ€ÐµÐ¼ÐµÐ½Ð½Ð¾Ð³Ð¾ Ñ…Ñ€Ð°Ð½ÐµÐ½Ð¸Ñ Ñ„Ð°Ð¹Ð»Ð¾Ð² (локальнаÑ) (ÐУЖÐО ЗÐПОЛÐИТЬ)
392 switch($type){ // удаленные папки в завиÑимоÑти от типа картинки
393 case 'skin':
394 $remote_dir = '/skins/'; // папка Ð´Ð»Ñ Ñкинов (полный путь отноÑительно точки входа ftp-пользователÑ) (ÐУЖÐО ЗÐПОЛÐИТЬ)
395 break;
396 case 'cloack':
397 $remote_dir = '/cloacks/'; // папка Ð´Ð»Ñ Ð¿Ð»Ð°Ñ‰ÐµÐ¹ (полный путь отноÑительно точки входа ftp-пользователÑ) (ÐУЖÐО ЗÐПОЛÐИТЬ)
398 break;
399 default:
400 $remote_dir = '';
401 break;
402 }
403
404 if($remote){
405 $file = file_get_contents($file);
406 file_put_contents($local_tmp_dir.$remote_file, $file);
407 $file = $local_tmp_dir.$remote_file;
408 }
409 if($remote_dir){
410 // уÑтановка ÑоединениÑ
411 $conn_id = ftp_connect($ftp_server);
412 // проверка имени Ð¿Ð¾Ð»ÑŒÐ·Ð¾Ð²Ð°Ñ‚ÐµÐ»Ñ Ð¸ паролÑ
413 $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
414 // загрузка файла на ftp
415 ftp_pasv($conn_id, true);
416 if (ftp_put($conn_id, $remote_dir.$remote_file, $file, FTP_BINARY)) {
417 $result = true;
418 } else {
419 $result = false;
420 }
421 // закрытие ÑоединениÑ
422 ftp_close($conn_id);
423 if($remote){
424 if (file_exists($file)){
425 unlink ($file);
426 }
427 }
428 } else {
429 $result = false;
430 }
431
432 return $result;
433}
434
435/*
436* Ñ„ÑƒÐ½ÐºÑ†Ð¸Ñ ÑÐºÐ°Ñ‡Ð¸Ð²Ð°Ð½Ð¸Ñ Ñ„Ð°Ð¹Ð»Ð¾Ð² Ñ ftp
437*/
438function getImageFtp($remote_file, $type) {
439 $ftp_server = ''; //ftp host (ÐУЖÐО ЗÐПОЛÐИТЬ)
440 $ftp_user_name = ''; // login (ÐУЖÐО ЗÐПОЛÐИТЬ)
441 $ftp_user_pass = ''; //password (ÐУЖÐО ЗÐПОЛÐИТЬ)
442
443 // картинки заглушки (должны хранитьÑÑ Ð»Ð¾ÐºÐ°Ð»ÑŒÐ½Ð¾)
444 $default_skin = '/var/www/SHOP/upload/skins/default.png'; // Ñкин по умолчанию (хранитÑÑ Ð»Ð¾ÐºÐ°Ð»ÑŒÐ½Ð¾) (ÐУЖÐО ЗÐПОЛÐИТЬ)
445 $default_cloack = '/var/www/SHOP/upload/skins/default.png'; // плащ по умолчанию (хранитÑÑ Ð»Ð¾ÐºÐ°Ð»ÑŒÐ½Ð¾) (ÐУЖÐО ЗÐПОЛÐИТЬ)
446
447 $result = new stdClass();
448 switch($type){ // удаленные папки в завиÑимоÑти от типа картинки
449 case 'skin':
450 $remote_dir = '/skins/'; // папка Ð´Ð»Ñ Ñкинов (удаленнаÑ) (полный путь отноÑительно точки входа ftp-пользователÑ) (ÐУЖÐО ЗÐПОЛÐИТЬ)
451 $local_dir = '/var/www/skins/'; // папка Ð´Ð»Ñ Ñкинов (Ð»Ð¾ÐºÐ°Ð»ÑŒÐ½Ð°Ñ - Ð´Ð»Ñ Ð²Ñ€ÐµÐ¼ÐµÐ½Ð½Ð¾Ð¹ выгрузки Ñ ftp) (ÐУЖÐО ЗÐПОЛÐИТЬ)
452 $default_img = $default_skin;
453 break;
454 case 'cloack':
455 $remote_dir = '/cloacks/'; // папка Ð´Ð»Ñ Ð¿Ð»Ð°Ñ‰ÐµÐ¹ (удаленнаÑ) (полный путь отноÑительно точки входа ftp-пользователÑ) (ÐУЖÐО ЗÐПОЛÐИТЬ)
456 $local_dir = '/var/www/skins/'; // папка Ð´Ð»Ñ Ð¿Ð»Ð°Ñ‰ÐµÐ¹ (Ð»Ð¾ÐºÐ°Ð»ÑŒÐ½Ð°Ñ - Ð´Ð»Ñ Ð²Ñ€ÐµÐ¼ÐµÐ½Ð½Ð¾Ð¹ выгрузки Ñ ftp) (ÐУЖÐО ЗÐПОЛÐИТЬ)
457 $default_img = $default_cloack;
458 break;
459 default:
460 $remote_dir = '';
461 break;
462 }
463
464 if($remote_dir){
465 // уÑтановка ÑоединениÑ
466 $conn_id = ftp_connect($ftp_server);
467
468 // проверка имени Ð¿Ð¾Ð»ÑŒÐ·Ð¾Ð²Ð°Ñ‚ÐµÐ»Ñ Ð¸ паролÑ
469 $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
470 $local_file = $local_dir.$remote_file; // полный путь к локальному файлу
471 $server_file = $remote_dir.$remote_file; // полный путь к удаленному файлу
472
473 // выгрузка файла Ñ ftp
474 ftp_pasv($conn_id, true);
475 if (ftp_get($conn_id, $local_file, $server_file, FTP_BINARY)) {
476 $result->path = $local_file;
477 $result->default = false;
478 } else {
479 $result->path = $default_img;
480 $result->default = true;
481 }
482 // закрытие ÑоединениÑ
483 ftp_close($conn_id);
484 } else {
485 $result->path = $default_img;
486 $result->default = true;
487 }
488
489 return $result;
490}
491
492function getGroup($username, $servarId = 0){
493 global $db;
494 global $servers_permissions;
495 if($username){
496 $sql = "SELECT * FROM permissions_inheritance WHERE child='$username' AND type='1'";
497 if (isset($servers_permissions[$servarId]->db)) {
498 $check = $servers_permissions[$servarId]->db->super_query($sql);
499 } else {
500 $check = $db->super_query($sql);
501 }
502
503 switch($check['parent']){
504 case 'Vips':
505 $checkParent = 'vip';
506 break;
507 case 'Diamond':
508 $checkParent = 'lux';
509 break;
510 default:
511 $checkParent = $check['parent'];
512 break;
513 }
514
515 $sql = "SELECT * FROM permissions WHERE name='$username' AND type='1' AND permission='group-{$checkParent}-until'";
516 if (isset($servers_permissions[$servarId]->db)) {
517 $check2 = $servers_permissions[$servarId]->db->super_query($sql);
518 } else {
519 $check2 = $db->super_query($sql);
520 }
521
522
523 if(strnatcasecmp($check['parent'], 'Moders') == 0) $display = 'Модератор';
524 elseif(strnatcasecmp($check['parent'], 'Diamond') == 0) $display = 'Diamond игрок';
525 elseif(strnatcasecmp($check['parent'], 'premium') == 0) $display = 'Premium игрок';
526 elseif(strnatcasecmp($check['parent'], 'Vips') == 0) $display = 'VIP игрок';
527 elseif(strnatcasecmp($check['parent'], 'Admins') == 0) $display = 'ÐдминиÑтратор';
528 elseif(strnatcasecmp($check['parent'], 'Helper') == 0) $display = 'Хелпер';
529 else $display = 'Обычный игрок';
530
531 $array = array(
532 'group' => $check['parent'],
533 'display' => $display,
534 'until' => $check2['value']
535 );
536 return $array;
537 }
538}
539
540function getServersUserGroup($username, $servers){
541 $return = Array();
542 if($username && count($servers)){
543 foreach ($servers as $server) {
544
545 $sql = "SELECT * FROM permissions_inheritance WHERE child='$username' AND type='1'";
546 $check = $server->db->super_query($sql);
547
548 $parent = isset($check['parent']) ? $check['parent'] : '';
549 switch($parent){
550 case 'Vips':
551 $checkParent = 'vip';
552 break;
553 case 'Diamond':
554 $checkParent = 'lux';
555 break;
556 default:
557 $checkParent = $check['parent'];
558 break;
559 }
560
561 $sql = "SELECT * FROM permissions WHERE name='$username' AND type='1' AND permission='group-{$checkParent}-until'";
562 $check2 = $server->db->super_query($sql);
563
564 if(strnatcasecmp($parent, 'Moders') == 0) $display = 'Модератор';
565 elseif(strnatcasecmp($parent, 'Diamond') == 0) $display = 'Diamond игрок';
566 elseif(strnatcasecmp($parent, 'premium') == 0) $display = 'Premium игрок';
567 elseif(strnatcasecmp($parent, 'Vips') == 0) $display = 'VIP игрок';
568 elseif(strnatcasecmp($parent, 'Admins') == 0) $display = 'ÐдминиÑтратор';
569 elseif(strnatcasecmp($parent, 'Helper') == 0) $display = 'Хелпер';
570 else $display = 'Обычный игрок';
571
572 $return[$server->id] = array(
573 'group' => $parent,
574 'display' => $display,
575 'until' => (isset($check2['value']) ? $check2['value'] : ''),
576 'buy_date' => (($check2['buy_date'] && ($check2['buy_date'] != '0000-00-00 00:00:00')) ? $check2['buy_date'] : '')
577 );
578 }
579 }
580 return $return;
581}
582
583function getUserServerDataForRightPart($serversData, $serverForeverMarks, $userServersGroupData, $isTableRow = false){
584 $html = '';
585 if (!$isTableRow) {
586 $html = '<center><b>Ð˜Ð½Ñ„Ð¾Ñ€Ð¼Ð°Ñ†Ð¸Ñ Ð¾ Ваших группах по Ñерверам:</b></center>';
587 }
588
589 $groupCount = 0;
590 $groupName = '';
591 foreach ($serversData as $sId => $serverData) {
592 if ($userServersGroupData[$sId]['group']) {
593 $groupCount++;
594 if (($userServersGroupData[$sId]['until'] < time()) && ($serverForeverMarks[$sId] != 'forev')) {
595 $until = 'ЧленÑтво <b>ЗÐКОÐЧИЛОСЬ ';
596 $until .= date("d.m.Y H:i", $userServersGroupData[$sId]['until']);
597 $until .= '</b>';
598 } else {
599 $until = 'ЧленÑтво продлитÑÑ <b>';
600 $until .= ($serverForeverMarks[$sId] == 'forev' ? 'навÑегда' : 'до ' . date("d.m.Y H:i", $userServersGroupData[$sId]['until']));
601 $until .= '</b>';
602 }
603 if (!$isTableRow) {
604 $html .= "<hr/>
605 <div class='mini-profile-info'>
606 <div class='panel panel-default'>
607 <div class='panel-heading' role='tab' id='userAccountHeading$sId'>
608 <h4 class='panel-title'>
609 <a role='button' data-toggle='collapse' data-parent='#userAccountsPanel' href='#userAccount$sId' aria-expanded='true' aria-controls='userAccount$sId'>
610 Сервер: <strong>" . $serverData->name . "</strong>
611 </a>
612 </h4>
613 </div>
614 <div id='userAccount$sId' class='panel-collapse collapse' role='tabpanel' aria-labelledby='userAccountHeading$sId'>
615 <div class='panel-body'>
616 Группа: <b>" . $userServersGroupData[$sId]['display'] . "</b><br/>
617 " . (!in_array($userServersGroupData[$sId]['display'], Array('Обычный игрок', "ÐдминиÑтратор", "Модератор", "Ст.Модератор")) ? $until : '') . "
618 </div>
619 </div>
620 </div>
621 </div>";
622 } else {
623 $html .= "<tr>
624 <td>$groupCount</td>
625 <td>".$serverData->name."</td>
626 <td>".$userServersGroupData[$sId]['display']."</td>
627 <td>".(!in_array($userServersGroupData[$sId]['display'], Array('Обычный игрок', "ÐдминиÑтратор", "Модератор", "Ст.Модератор")) ? $until : '')."</td>
628 </tr>";
629 }
630 } else {
631 $groupName = $userServersGroupData[$sId]['display'];
632 }
633 }
634 if (!$groupCount) {
635 if (!$isTableRow) {
636 $html .= "<hr/>Ð’Ñ‹ не ÑоÑтоите ни в одной из груп.<br/>Ðа вÑех Ñерверах Ð’Ñ‹ <strong>$groupName</strong>";
637 } else {
638 $html .= "<tr><td colspan='4'><center>Ð’Ñ‹ не ÑоÑтоите ни в одной из груп.<br/>Ðа вÑех Ñерверах Ð’Ñ‹ <strong>$groupName</strong></center></td></tr>";
639 }
640 }
641 return $html;
642}
643
644
645
646
647function getStoreValue($param) {
648 global $sp;
649 $select = $sp->super_query("SELECT value FROM store_system WHERE param='$param'");
650 return $select['value'];
651}
652
653function getStoreValueUntil($param) {
654 global $sp;
655 $select = $sp->super_query("SELECT until FROM store_system WHERE param='$param'");
656 return $select['until'];
657}
658
659function createNotifer($type, $text, $close = true){
660 if($close) $close = "<a href='' class='uk-alert-close uk-close'>"; else $close = "";
661 if($type == 'error') return "<div class='uk-alert uk-alert-danger' data-uk-alert>$close</a>$text</div>";
662 else if($type == 'good') return "<div class='uk-alert uk-alert-success' data-uk-alert>$close</a>$text</div>";
663 else if($type == 'warn') return "<div class='uk-alert uk-alert-warning' data-uk-alert>$close</a>$text</div>";
664 else if($type == 'norm') return "<div class='uk-alert' data-uk-alert>$close</a>$text</div>";
665}
666
667function isPremium($username, $servarId = 0){
668 if($username){
669 global $db;
670 global $servers_permissions;
671 $sql = "SELECT * FROM permissions_inheritance WHERE child='$username' AND parent='premium' AND type='1'";
672 if (isset($servers_permissions[$servarId]->db)) {
673 $check = $servers_permissions[$servarId]->db->query($sql);
674 } else {
675 $check = $db->query($sql);
676 }
677 if($db->num_rows($check)) return true;
678 }
679 else return false;
680}
681
682function isVip($username, $servarId = 0){
683 if($username){
684 global $db;
685 global $servers_permissions;
686 $sql = "SELECT * FROM permissions_inheritance WHERE child='$username' AND parent='Vips' AND type='1'";
687 if (isset($servers_permissions[$servarId]->db)) {
688 $check = $servers_permissions[$servarId]->db->query($sql);
689 } else {
690 $check = $db->query($sql);
691 }
692 if($db->num_rows($check)) return true;
693 }
694 else return false;
695}
696
697function isLux($username, $servarId = 0){
698 if($username){
699 global $db;
700 global $servers_permissions;
701 $sql = "SELECT * FROM permissions_inheritance WHERE child='$username' AND parent='Diamond' AND type='1'";
702 if (isset($servers_permissions[$servarId]->db)) {
703 $check = $servers_permissions[$servarId]->db->query($sql);
704 } else {
705 $check = $db->query($sql);
706 }
707 if($db->num_rows($check)) return true;
708 }
709 else return false;
710}
711
712function isAdmin($username){
713 if($username){
714 global $db;
715
716 $select = $db->super_query("SELECT * FROM dle_users WHERE name='$username'");
717 $check = $db->query("SELECT * FROM permissions_inheritance WHERE child='$username' AND parent='Admins' AND type='1'");
718 if($db->num_rows($check)) return true;
719 elseif($select['user_group'] == 1) return true;
720 }
721 else return false;
722}
723
724function isModer($username){
725 if($username){
726 global $db;
727
728 $check = $db->query("SELECT * FROM permissions_inheritance WHERE child='$username' AND parent='Moders' AND type='1'");
729 if($db->num_rows($check)) return true;
730 $check = $db->query("SELECT * FROM permissions_inheritance WHERE child='$username' AND parent='St.Moders' AND type='1'");
731 if($db->num_rows($check)) return true;
732 }
733 else return false;
734}
735
736function getUserIp(){
737 $returnIp = '';
738 $serverHeaders = array('HTTP_X_FORWARDED_FOR', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_FORWARDED', 'HTTP_VIA', 'HTTP_X_COMING_FROM', 'HTTP_X_COMING_FROM', 'HTTP_COMING_FROM', 'REMOTE_ADDR');
739 foreach ($serverHeaders as $serverHeader) {
740 if (isset($_SERVER[$serverHeader]) && !$returnIp) {
741 $returnIp = $_SERVER[$serverHeader];
742 }
743 }
744 return $returnIp;
745}
746
747function isAnyServerPermissions($username, $servers, $parent){
748 //варианты Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ Ð¿ÐµÑ€ÐµÐ¼ÐµÐ½Ð½Ð¾Ð¹ $parent
749 //$parent = Vips
750 //$parent = Diamond
751 //$parent = premium
752 //$parent = Moders
753 $return = Array();
754 if($username && count($servers)){
755 foreach ($servers as $server) {
756 $where = "parent='$parent'";
757 if ($parent == 'Moders') {
758 $where = "(parent='$parent' OR parent='St.Moders')";
759 }
760 $sql = "SELECT * FROM permissions_inheritance WHERE child='$username' AND $where AND type='1'";
761 $check = $server->db->query($sql);
762 if ($server->db->num_rows($check)) {
763 $return[$server->id] = $server->id;
764 }
765 }
766 }
767 return $return;
768}
769
770function getServersGroupParams($username, $servers){
771 $return = Array();
772 if($username && count($servers)){
773 foreach ($servers as $server) {
774 $group_params = $server->db->super_query("SELECT group_params FROM dle_users WHERE name='$username'");
775 $return[$server->id] = $group_params['group_params'];
776 }
777 }
778 return $return;
779}
780
781function pr($data){
782 echo '<pre>';
783 print_r($data);
784 echo '</pre>';
785}
786
787
788function getAvatar($username){
789 global $fr;
790 //$select = $fr->super_query("SELECT member_id FROM icubemembers WHERE name='$username'");
791 $memberid = $select['member_id'];
792 if(file_exists("/home/forum/uploads/profile/photo-$memberid.png")) $avatar = "http://forum.icube.su/uploads/profile/photo-$memberid.png";
793 elseif(file_exists("/home/forum/uploads/profile/photo-$memberid.jpg")) $avatar = "http://forum.icube.su/uploads/profile/photo-$memberid.jpg";
794 elseif(file_exists("/home/forum/uploads/profile/photo-$memberid.jpeg")) $avatar = "http://forum.icube.su/uploads/profile/photo-$memberid.jpeg";
795 elseif(file_exists("/home/forum/uploads/profile/photo-$memberid.jpeg")) $avatar = "http://forum.icube.su/uploads/profile/photo-$memberid.jpeg";
796 elseif(file_exists("/home/forum/uploads/profile/photo-$memberid.gif")) $avatar = "http://forum.icube.su/uploads/profile/photo-$memberid.gif";
797 else $avatar = "http://icube.su/templates/Default/dleimages/noavatar.png";
798 return $avatar;
799}
800
801function get_count($count, $form1, $form2, $form3) {
802 $count = abs($count) % 100;
803 $lcount = $count % 10;
804 if ($count >= 11 && $count <= 19) return($form3);
805 if ($lcount >= 2 && $lcount <= 4) return($form2);
806 if ($lcount == 1) return($form1);
807 return $form3;
808 $db->free();
809}
810/*
811=====================================================
812 DataLife Engine - by SoftNews Media Group
813-----------------------------------------------------
814 http://dle-news.ru/
815-----------------------------------------------------
816 Copyright (c) 2004,2015 SoftNews Media Group
817=====================================================
818 Данный код защищен авторÑкими правами
819=====================================================
820 Файл: functions.php
821-----------------------------------------------------
822 Ðазначение: ОÑновные функции
823=====================================================
824*/
825if( ! defined( 'DATALIFEENGINE' ) ) {
826 die( "Hacking attempt!" );
827}
828
829if ( $config['auth_domain'] ) {
830
831 $domain_cookie = explode (".", clean_url( $_SERVER['HTTP_HOST'] ));
832 $domain_cookie_count = count($domain_cookie);
833 $domain_allow_count = -2;
834
835 if ( $domain_cookie_count > 2 ) {
836
837 if ( in_array($domain_cookie[$domain_cookie_count-2], array('com', 'net', 'org') )) $domain_allow_count = -3;
838 if ( $domain_cookie[$domain_cookie_count-1] == 'ua' ) $domain_allow_count = -3;
839 $domain_cookie = array_slice($domain_cookie, $domain_allow_count);
840 }
841
842 $domain_cookie = "." . implode (".", $domain_cookie);
843
844 if( (ip2long($_SERVER['HTTP_HOST']) == -1 OR ip2long($_SERVER['HTTP_HOST']) === FALSE) AND strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN' ) define( 'DOMAIN', $domain_cookie );
845 else define( 'DOMAIN', null );
846
847} else define( 'DOMAIN', null );
848
849$mcache = false;
850
851if ( $config['cache_type'] ) {
852
853 if ( function_exists('memcache_connect') ) {
854
855 $memcache_server = explode(":", $config['memcache_server']);
856
857 if ($memcache_server[0] == 'unix') {
858 $memcache_server = array($config['memcache_server'], 0);
859 }
860
861 $mcache = @memcache_connect( $memcache_server[0], $memcache_server[1] );
862
863 if( $mcache AND function_exists('memcache_set_compress_threshold') )
864 {
865 memcache_set_compress_threshold( $mcache, 20000, 0.2 );
866 }
867
868 }
869
870}
871
872function dle_session( $sid = false ) {
873
874 $params = session_get_cookie_params();
875
876 if ( DOMAIN ) $params['domain'] = DOMAIN;
877
878 if( version_compare(PHP_VERSION, '5.2', '<') ) {
879
880 session_set_cookie_params($params['lifetime'], "/", $params['domain']."; HttpOnly", $params['secure']);
881
882 } else {
883
884 session_set_cookie_params($params['lifetime'], "/", $params['domain'], $params['secure'], true);
885
886 }
887
888 if ( $sid ) @session_id( $sid );
889
890 @session_start();
891
892}
893
894function formatsize($file_size) {
895
896 if( !$file_size OR $file_size < 1) return '0 b';
897
898 $prefix = array("b", "Kb", "Mb", "Gb", "Tb");
899 $exp = floor(log($file_size, 1024)) | 0;
900
901 return round($file_size / (pow(1024, $exp)), 2).' '.$prefix[$exp];
902
903}
904
905class microTimer {
906 var $time;
907
908 function __construct() {
909 $this->time = $this->get_real_time();
910 }
911 function get() {
912 return round( ($this->get_real_time() - $this->time), 5 );
913 }
914
915 function get_real_time() {
916 list ( $seconds, $microSeconds ) = explode( ' ', microtime() );
917 return (( float ) $seconds + ( float ) $microSeconds);
918 }
919}
920
921function flooder($ip, $news_time = false) {
922 global $config, $db;
923
924 if ( $news_time ) {
925
926 $this_time = time() - $news_time;
927 $db->query( "DELETE FROM " . PREFIX . "_flood where id < '$this_time' AND flag='1' " );
928
929 $row = $db->super_query("SELECT COUNT(*) as count FROM " . PREFIX . "_flood WHERE ip = '$ip' AND flag='1'");
930
931 if( $row['count'] ) return TRUE;
932 else return FALSE;
933
934 } else {
935
936 $this_time = time() - $config['flood_time'];
937 $db->query( "DELETE FROM " . PREFIX . "_flood where id < '$this_time' AND flag='0' " );
938
939 $row = $db->super_query("SELECT COUNT(*) as count FROM " . PREFIX . "_flood WHERE ip = '$ip' AND flag='0'");
940
941 if( $row['count'] ) return TRUE;
942 else return FALSE;
943
944 }
945
946}
947
948function totranslit($var, $lower = true, $punkt = true) {
949 global $langtranslit;
950
951 if ( is_array($var) ) return "";
952
953 $var = str_replace(chr(0), '', $var);
954
955 if (!is_array ( $langtranslit ) OR !count( $langtranslit ) ) {
956 $var = trim( strip_tags( $var ) );
957
958 if ( $punkt ) $var = preg_replace( "/[^a-z0-9\_\-.]+/mi", "", $var );
959 else $var = preg_replace( "/[^a-z0-9\_\-]+/mi", "", $var );
960
961 $var = preg_replace( '#[.]+#i', '.', $var );
962 $var = str_ireplace( ".php", ".ppp", $var );
963
964 if ( $lower ) $var = strtolower( $var );
965
966 return $var;
967 }
968
969 $var = trim( strip_tags( $var ) );
970 $var = preg_replace( "/\s+/ms", "-", $var );
971 $var = str_replace( "/", "-", $var );
972
973 $var = strtr($var, $langtranslit);
974
975 if ( $punkt ) $var = preg_replace( "/[^a-z0-9\_\-.]+/mi", "", $var );
976 else $var = preg_replace( "/[^a-z0-9\_\-]+/mi", "", $var );
977
978 $var = preg_replace( '#[\-]+#i', '-', $var );
979 $var = preg_replace( '#[.]+#i', '.', $var );
980
981 if ( $lower ) $var = strtolower( $var );
982
983 $var = str_ireplace( ".php", "", $var );
984 $var = str_ireplace( ".php", ".ppp", $var );
985
986 if( strlen( $var ) > 200 ) {
987
988 $var = substr( $var, 0, 200 );
989
990 if( ($temp_max = strrpos( $var, '-' )) ) $var = substr( $var, 0, $temp_max );
991
992 }
993
994 return $var;
995}
996
997function langdate($format, $stamp, $servertime = false, $custom = false ) {
998 global $langdate, $member_id, $customlangdate;
999
1000 $timezones = array('Pacific/Midway','US/Samoa','US/Hawaii','US/Alaska','US/Pacific','America/Tijuana','US/Arizona','US/Mountain','America/Chihuahua','America/Mazatlan','America/Mexico_City','America/Monterrey','US/Central','US/Eastern','US/East-Indiana','America/Lima','America/Caracas','Canada/Atlantic','America/La_Paz','America/Santiago','Canada/Newfoundland','America/Buenos_Aires','Greenland','Atlantic/Stanley','Atlantic/Azores','Africa/Casablanca','Europe/Dublin','Europe/Lisbon','Europe/London','Europe/Amsterdam','Europe/Belgrade','Europe/Berlin','Europe/Bratislava','Europe/Brussels','Europe/Budapest','Europe/Copenhagen','Europe/Madrid','Europe/Paris','Europe/Prague','Europe/Rome','Europe/Sarajevo','Europe/Stockholm','Europe/Vienna','Europe/Warsaw','Europe/Zagreb','Europe/Athens','Europe/Bucharest','Europe/Helsinki','Europe/Istanbul','Asia/Jerusalem','Europe/Kiev','Europe/Minsk','Europe/Riga','Europe/Sofia','Europe/Tallinn','Europe/Vilnius','Asia/Baghdad','Asia/Kuwait','Africa/Nairobi','Asia/Tehran','Europe/Kaliningrad','Europe/Moscow','Europe/Volgograd','Europe/Samara','Asia/Baku','Asia/Muscat','Asia/Tbilisi','Asia/Yerevan','Asia/Kabul','Asia/Yekaterinburg','Asia/Tashkent','Asia/Kolkata','Asia/Kathmandu','Asia/Almaty','Asia/Novosibirsk','Asia/Jakarta','Asia/Krasnoyarsk','Asia/Hong_Kong','Asia/Kuala_Lumpur','Asia/Singapore','Asia/Taipei','Asia/Ulaanbaatar','Asia/Urumqi','Asia/Irkutsk','Asia/Seoul','Asia/Tokyo','Australia/Adelaide','Australia/Darwin','Asia/Yakutsk','Australia/Brisbane','Pacific/Port_Moresby','Australia/Sydney','Asia/Vladivostok','Asia/Sakhalin','Asia/Magadan','Pacific/Auckland','Pacific/Fiji');
1001
1002 if( is_array($custom) ) $locallangdate = $customlangdate; else $locallangdate = $langdate;
1003
1004 if (!$stamp) { $stamp = time(); }
1005
1006 $local = new DateTime('@'.$stamp);
1007
1008 if (isset($member_id['timezone']) AND $member_id['timezone'] AND !$servertime) {
1009 $localzone = $member_id['timezone'];
1010
1011 } else {
1012
1013 $localzone = date_default_timezone_get();
1014 }
1015
1016 if (!in_array($localzone, $timezones)) $localzone = 'Europe/Moscow';
1017
1018 $local->setTimeZone(new DateTimeZone($localzone));
1019
1020 return strtr( $local->format($format), $locallangdate );
1021
1022}
1023
1024function formdate( $matches=array() ) {
1025 global $news_date, $customlangdate;
1026 return langdate($matches[1], $news_date, false, $customlangdate);
1027
1028}
1029
1030function check_newscount( $matches=array() ) {
1031 global $global_news_count;
1032
1033 $block = $matches[3];
1034
1035 $counts = explode( ',', $matches[2] );
1036
1037 if( $matches[1] == "newscount" ) {
1038
1039 if( !in_array($global_news_count, $counts) ) return "";
1040
1041 } else {
1042
1043 if( in_array($global_news_count, $counts) ) return "";
1044
1045 }
1046
1047 return $block;
1048
1049}
1050
1051function msgbox($title, $text) {
1052 global $tpl;
1053
1054 if (!class_exists('dle_template')) {
1055 return;
1056 }
1057
1058 $tpl_2 = new dle_template( );
1059 $tpl_2->dir = TEMPLATE_DIR;
1060
1061 $tpl_2->load_template( 'info.tpl' );
1062
1063 $tpl_2->set( '{error}', $text );
1064 $tpl_2->set( '{title}', $title );
1065
1066 $tpl_2->compile( 'info' );
1067 $tpl_2->clear();
1068
1069 $tpl->result['info'] .= $tpl_2->result['info'];
1070}
1071
1072function ShowRating($id, $rating, $vote_num, $allow = true) {
1073 global $lang, $config;
1074
1075 if( !$config['rating_type'] ) {
1076
1077 if( $rating AND $vote_num ) $rating = round( ($rating / $vote_num), 0 );
1078 else $rating = 0;
1079
1080 if ($rating < 0 ) $rating = 0;
1081
1082 $rating = $rating * 20;
1083
1084 if( !$allow ) {
1085
1086 $rated = <<<HTML
1087<div class="rating">
1088 <ul class="unit-rating">
1089 <li class="current-rating" style="width:{$rating}%;">{$rating}</li>
1090 </ul>
1091</div>
1092HTML;
1093
1094 return $rated;
1095 }
1096
1097 $rated = <<<HTML
1098<div id='ratig-layer-{$id}'><div class="rating">
1099 <ul class="unit-rating">
1100 <li class="current-rating" style="width:{$rating}%;">{$rating}</li>
1101 <li><a href="#" title="{$lang['useless']}" class="r1-unit" onclick="doRate('1', '{$id}'); return false;">1</a></li>
1102 <li><a href="#" title="{$lang['poor']}" class="r2-unit" onclick="doRate('2', '{$id}'); return false;">2</a></li>
1103 <li><a href="#" title="{$lang['fair']}" class="r3-unit" onclick="doRate('3', '{$id}'); return false;">3</a></li>
1104 <li><a href="#" title="{$lang['good']}" class="r4-unit" onclick="doRate('4', '{$id}'); return false;">4</a></li>
1105 <li><a href="#" title="{$lang['excellent']}" class="r5-unit" onclick="doRate('5', '{$id}'); return false;">5</a></li>
1106 </ul>
1107</div></div>
1108HTML;
1109
1110 return $rated;
1111
1112 } elseif ($config['rating_type'] == "1") {
1113
1114 if( $rating < 0 ) $rating = 0;
1115
1116 if( $allow ) $rated = "<span id=\"ratig-layer-{$id}\" class=\"ignore-select\"><span class=\"ratingtypeplus ignore-select\" >{$rating}</span></span>";
1117 else $rated = "<span class=\"ratingtypeplus ignore-select\" >{$rating}</span>";
1118
1119 return $rated;
1120
1121 } elseif ($config['rating_type'] == "2") {
1122
1123 $extraclass = "ratingzero";
1124
1125 if( $rating < 0 ) {
1126 $extraclass = "ratingminus";
1127 }
1128
1129 if( $rating > 0 ) {
1130 $extraclass = "ratingplus";
1131 $rating = "+".$rating;
1132 }
1133
1134 if( $allow ) $rated = "<span id=\"ratig-layer-{$id}\" class=\"ignore-select\"><span class=\"ratingtypeplusminus ignore-select {$extraclass}\" >{$rating}</span></span>";
1135 else $rated = "<span class=\"ratingtypeplusminus ignore-select {$extraclass}\" >{$rating}</span>";
1136
1137 return $rated;
1138
1139 }
1140
1141}
1142
1143function ShowCommentsRating($id, $rating, $vote_num, $allow = true) {
1144 global $lang, $config;
1145
1146 if( !$config['comments_rating_type'] ) {
1147
1148 if( $rating AND $vote_num ) $rating = round( ($rating / $vote_num), 0 );
1149 else $rating = 0;
1150
1151 if ($rating < 0 ) $rating = 0;
1152
1153 $rating = $rating * 20;
1154
1155 if( !$allow ) {
1156
1157 $rated = <<<HTML
1158<div class="rating">
1159 <ul class="unit-rating">
1160 <li class="current-rating" style="width:{$rating}%;">{$rating}</li>
1161 </ul>
1162</div>
1163HTML;
1164
1165 return $rated;
1166 }
1167
1168 $rated = <<<HTML
1169<div id='comments-ratig-layer-{$id}'><div class="rating">
1170 <ul class="unit-rating">
1171 <li class="current-rating" style="width:{$rating}%;">{$rating}</li>
1172 <li><a href="#" title="{$lang['useless']}" class="r1-unit" onclick="doCommentsRate('1', '{$id}'); return false;">1</a></li>
1173 <li><a href="#" title="{$lang['poor']}" class="r2-unit" onclick="doCommentsRate('2', '{$id}'); return false;">2</a></li>
1174 <li><a href="#" title="{$lang['fair']}" class="r3-unit" onclick="doCommentsRate('3', '{$id}'); return false;">3</a></li>
1175 <li><a href="#" title="{$lang['good']}" class="r4-unit" onclick="doCommentsRate('4', '{$id}'); return false;">4</a></li>
1176 <li><a href="#" title="{$lang['excellent']}" class="r5-unit" onclick="doCommentsRate('5', '{$id}'); return false;">5</a></li>
1177 </ul>
1178</div></div>
1179HTML;
1180
1181 return $rated;
1182
1183 } elseif ($config['comments_rating_type'] == "1") {
1184
1185 if( $rating < 0 ) $rating = 0;
1186
1187 if( $allow ) $rated = "<span id=\"comments-ratig-layer-{$id}\" class=\"ignore-select\"><span class=\"ratingtypeplus ignore-select\" >{$rating}</span></span>";
1188 else $rated = "<span class=\"ratingtypeplus ignore-select\" >{$rating}</span>";
1189
1190 return $rated;
1191
1192 } elseif ($config['comments_rating_type'] == "2") {
1193
1194 $extraclass = "ratingzero";
1195
1196 if( $rating < 0 ) {
1197 $extraclass = "ratingminus";
1198 }
1199
1200 if( $rating > 0 ) {
1201 $extraclass = "ratingplus";
1202 $rating = "+".$rating;
1203 }
1204
1205 if( $allow ) $rated = "<span id=\"comments-ratig-layer-{$id}\" class=\"ignore-select\"><span class=\"ratingtypeplusminus ignore-select {$extraclass}\" >{$rating}</span></span>";
1206 else $rated = "<span class=\"ratingtypeplusminus ignore-select {$extraclass}\" >{$rating}</span>";
1207
1208 return $rated;
1209
1210 }
1211
1212}
1213
1214function userrating($id) {
1215 global $db, $config;
1216
1217 $id = intval($id);
1218
1219 $row = $db->super_query( "SELECT SUM(rating) as rating, SUM(vote_num) as num FROM " . PREFIX . "_post_extras WHERE user_id ='{$id}'" );
1220
1221 if( !$config['rating_type'] ) {
1222
1223 if( $row['num'] ) $rating = round( ($row['rating'] / $row['num']), 0 );
1224 else $rating = 0;
1225
1226 if ($rating < 0 ) $rating = 0;
1227
1228 $rating = $rating * 20;
1229
1230 $rated = <<<HTML
1231<div class="rating" style="display:inline;">
1232 <ul class="unit-rating">
1233 <li class="current-rating" style="width:{$rating}%;">{$rating}</li>
1234 </ul>
1235 </div>
1236HTML;
1237
1238 return $rated;
1239
1240 } elseif ($config['rating_type'] == "1") {
1241
1242 if( $row['num'] ) $rating = $row['rating']; else $rating = 0;
1243
1244 if( $rating < 0 ) $rating = 0;
1245
1246 return "<span class=\"ratingtypeplus\" >{$rating}</span>";
1247
1248 } elseif ($config['rating_type'] == "2") {
1249
1250 if( $row['num'] ) $rating = $row['rating']; else $rating = 0;
1251
1252 $extraclass = "ratingzero";
1253
1254 if( $rating < 0 ) {
1255 $extraclass = "ratingminus";
1256 }
1257
1258 if( $rating > 0 ) {
1259 $extraclass = "ratingplus";
1260 $rating = "+".$rating;
1261 }
1262
1263 return "<span class=\"ratingtypeplusminus {$extraclass}\" >{$rating}</span>";
1264
1265 }
1266}
1267
1268function commentsuserrating($id) {
1269 global $db, $config;
1270
1271 $id = intval($id);
1272 $row = $db->super_query( "SELECT SUM(rating) as rating, SUM(vote_num) as num FROM " . PREFIX . "_comments WHERE user_id ='{$id}'" );
1273
1274 if( !$config['comments_rating_type'] ) {
1275
1276 if( $row['num'] ) $rating = round( ($row['rating'] / $row['num']), 0 );
1277 else $rating = 0;
1278
1279 if ($rating < 0 ) $rating = 0;
1280
1281 $rating = $rating * 20;
1282
1283 $rated = <<<HTML
1284<div class="rating" style="display:inline;">
1285 <ul class="unit-rating">
1286 <li class="current-rating" style="width:{$rating}%;">{$rating}</li>
1287 </ul>
1288 </div>
1289HTML;
1290
1291 return $rated;
1292
1293 } elseif ($config['comments_rating_type'] == "1") {
1294
1295 if( $row['num'] ) $rating = $row['rating']; else $rating = 0;
1296
1297 if( $rating < 0 ) $rating = 0;
1298
1299 return "<span class=\"ratingtypeplus\" >{$rating}</span>";
1300
1301 } elseif ($config['comments_rating_type'] == "2") {
1302
1303 if( $row['num'] ) $rating = $row['rating']; else $rating = 0;
1304
1305 $extraclass = "ratingzero";
1306
1307 if( $rating < 0 ) {
1308 $extraclass = "ratingminus";
1309 }
1310
1311 if( $rating > 0 ) {
1312 $extraclass = "ratingplus";
1313 $rating = "+".$rating;
1314 }
1315
1316 return "<span class=\"ratingtypeplusminus {$extraclass}\" >{$rating}</span>";
1317
1318 }
1319}
1320
1321function CategoryNewsSelection($categoryid = 0, $parentid = 0, $nocat = TRUE, $sublevelmarker = '', $returnstring = '') {
1322 global $cat_info, $user_group, $member_id, $dle_module;
1323
1324 if ($dle_module == 'addnews') $allow_list = explode( ',', $user_group[$member_id['user_group']]['cat_allow_addnews'] );
1325 else $allow_list = explode( ',', $user_group[$member_id['user_group']]['allow_cats'] );
1326
1327 $spec_list = explode( ',', $user_group[$member_id['user_group']]['cat_add'] );
1328
1329 $root_category = array ();
1330
1331 if( $parentid == 0 ) {
1332 if( $nocat ) $returnstring .= '<option value="0"></option>';
1333 } else {
1334 $sublevelmarker .= ' ';
1335 }
1336
1337 if( count( $cat_info ) ) {
1338
1339 foreach ( $cat_info as $cats ) {
1340 if( $cats['parentid'] == $parentid ) $root_category[] = $cats['id'];
1341 }
1342
1343 if( count( $root_category ) ) {
1344 foreach ( $root_category as $id ) {
1345
1346 if( $allow_list[0] == "all" OR in_array( $id, $allow_list ) ) {
1347
1348 if( $spec_list[0] == "all" or in_array( $id, $spec_list ) ) $color = "black";
1349 else $color = "red";
1350
1351 $returnstring .= "<option style=\"color: {$color}\" value=\"" . $id . '" ';
1352
1353 if( is_array( $categoryid ) ) {
1354 foreach ( $categoryid as $element ) {
1355 if( $element == $id ) $returnstring .= 'SELECTED';
1356 }
1357 } elseif( $categoryid == $id ) $returnstring .= 'SELECTED';
1358
1359 $returnstring .= '>' . $sublevelmarker . $cat_info[$id]['name'] . '</option>';
1360 }
1361 $returnstring = CategoryNewsSelection( $categoryid, $id, $nocat, $sublevelmarker, $returnstring );
1362 }
1363 }
1364 }
1365 return $returnstring;
1366}
1367
1368function get_ID($cat_info, $category) {
1369 foreach ( $cat_info as $cats ) {
1370 if( $cats['alt_name'] == $category ) return $cats['id'];
1371 }
1372 return false;
1373}
1374
1375function set_vars($file, $data) {
1376
1377 if ( is_array($data) OR is_int($data) ) {
1378
1379 $file = totranslit($file, true, false);
1380 $fp = fopen( ENGINE_DIR . '/cache/system/' . $file . '.php', 'wb+' );
1381 fwrite( $fp, serialize( $data ) );
1382 fclose( $fp );
1383
1384 @chmod( ENGINE_DIR . '/cache/system/' . $file . '.php', 0666 );
1385
1386 }
1387}
1388
1389function get_vars($file) {
1390 $file = totranslit($file, true, false);
1391
1392 $data = @file_get_contents( ENGINE_DIR . '/cache/system/' . $file . '.php' );
1393
1394 if ( $data !== false ) {
1395
1396 $data = unserialize( $data );
1397 if ( is_array($data) OR is_int($data) ) return $data;
1398
1399 }
1400
1401 return false;
1402}
1403
1404function dle_cache($prefix, $cache_id = false, $member_prefix = false) {
1405 global $config, $is_logged, $member_id, $mcache;
1406
1407 if( !$config['allow_cache'] ) return false;
1408
1409 $config['clear_cache'] = (intval($config['clear_cache']) > 1) ? intval($config['clear_cache']) : 0;
1410
1411 if( $is_logged ) $end_file = $member_id['user_group'];
1412 else $end_file = "0";
1413
1414 if( ! $cache_id ) {
1415
1416 $key = $prefix;
1417
1418 } else {
1419
1420 $cache_id = md5( $cache_id );
1421
1422 if( $member_prefix ) $key = $prefix . "_" . $cache_id . "_" . $end_file;
1423 else $key = $prefix . "_" . $cache_id;
1424
1425 }
1426
1427 if ( $mcache ) {
1428
1429 return memcache_get( $mcache, md5( DBNAME . PREFIX . md5(SECURE_AUTH_KEY) .$key ) );
1430
1431 } else {
1432
1433 $buffer = @file_get_contents( ENGINE_DIR . "/cache/" . $key . ".tmp" );
1434
1435 if ( $buffer !== false AND $config['clear_cache'] ) {
1436
1437 $file_date = @filemtime( ENGINE_DIR . "/cache/" . $key . ".tmp" );
1438 $file_date = time()-$file_date;
1439
1440 if ( $file_date > ( $config['clear_cache'] * 60 ) ) {
1441 $buffer = false;
1442 @unlink( ENGINE_DIR . "/cache/" . $key . ".tmp" );
1443 }
1444
1445 return $buffer;
1446
1447 } else return $buffer;
1448
1449 }
1450}
1451
1452function create_cache($prefix, $cache_text, $cache_id = false, $member_prefix = false) {
1453 global $config, $is_logged, $member_id, $mcache;
1454
1455 if( !$config['allow_cache'] ) return false;
1456
1457 if( $is_logged ) $end_file = $member_id['user_group'];
1458 else $end_file = "0";
1459
1460 if( ! $cache_id ) {
1461 $key = $prefix;
1462 } else {
1463 $cache_id = md5( $cache_id );
1464
1465 if( $member_prefix ) $key = $prefix . "_" . $cache_id . "_" . $end_file;
1466 else $key = $prefix . "_" . $cache_id;
1467
1468 }
1469
1470
1471 if ( $mcache ) {
1472
1473 $config['clear_cache'] = (intval($config['clear_cache']) > 1) ? intval($config['clear_cache']) : 0;
1474
1475 if ( $config['clear_cache'] ) $set_time = $config['clear_cache'] * 60; else $set_time = 86400;
1476
1477 memcache_set( $mcache, md5( DBNAME . PREFIX . md5(SECURE_AUTH_KEY) .$key ), $cache_text, MEMCACHE_COMPRESSED, $set_time );
1478
1479 } else {
1480
1481 file_put_contents (ENGINE_DIR . "/cache/" . $key . ".tmp", $cache_text, LOCK_EX);
1482
1483 @chmod( ENGINE_DIR . "/cache/" . $key . ".tmp", 0666 );
1484 }
1485}
1486
1487function clear_cache($cache_areas = false) {
1488 global $mcache;
1489
1490 if ( $mcache ) {
1491
1492 memcache_flush($mcache);
1493
1494 }
1495
1496 if ( $cache_areas ) {
1497 if(!is_array($cache_areas)) {
1498 $cache_areas = array($cache_areas);
1499 }
1500 }
1501
1502 $fdir = opendir( ENGINE_DIR . '/cache' );
1503
1504 while ( $file = readdir( $fdir ) ) {
1505 if( $file != '.' and $file != '..' and $file != '.htaccess' and $file != 'system' ) {
1506
1507 if( $cache_areas ) {
1508
1509 foreach($cache_areas as $cache_area) if( strpos( $file, $cache_area ) !== false ) @unlink( ENGINE_DIR . '/cache/' . $file );
1510
1511 } else {
1512
1513 @unlink( ENGINE_DIR . '/cache/' . $file );
1514
1515 }
1516 }
1517 }
1518
1519}
1520
1521function ChangeSkin($dir, $skin) {
1522
1523 $templates_list = array ();
1524
1525 $handle = opendir( $dir );
1526
1527 while ( false !== ($file = readdir( $handle )) ) {
1528 if( @is_dir( "./templates/$file" ) and ($file != "." AND $file != ".." AND $file != "smartphone") ) {
1529 $templates_list[] = $file;
1530 }
1531 }
1532
1533 closedir( $handle );
1534 sort($templates_list);
1535
1536 $skin_list = "<form method=\"post\" action=\"\"><select onchange=\"submit()\" name=\"skin_name\">";
1537
1538 foreach ( $templates_list as $single_template ) {
1539 if( $single_template == $skin ) $selected = " selected=\"selected\"";
1540 else $selected = "";
1541 $skin_list .= "<option value=\"$single_template\"" . $selected . ">$single_template</option>";
1542 }
1543
1544 $skin_list .= '</select><input type="hidden" name="action_skin_change" value="yes" /></form>';
1545
1546 return $skin_list;
1547}
1548
1549function get_mass_cats($id) {
1550 global $cat_info;
1551
1552 $id = explode ('-', $id);
1553 $temp_array = array();
1554
1555 foreach ( $cat_info as $cats ) {
1556
1557 if ($cats['id'] >= $id[0] AND $cats['id'] <= $id[1] ) $temp_array[] = intval($cats['id']);
1558
1559 }
1560
1561 if ( count($temp_array) ) { sort($temp_array); return implode(',', $temp_array); }
1562 else return 0;
1563
1564}
1565
1566function custom_print( $matches=array() ) {
1567 global $db, $is_logged, $member_id, $xf_inited, $cat_info, $config, $user_group, $category_id, $_TIME, $lang, $smartphone_detected, $dle_module, $allow_comments_ajax, $PHP_SELF, $news_date, $banners, $banner_in_news, $url_page, $user_query, $custom_news, $global_news_count;
1568
1569 if ( !count($matches) ) return "";
1570 $param_str = trim($matches[1]);
1571
1572 $aviable = array();
1573 $thisdate = date( "Y-m-d H:i:s", $_TIME );
1574 $sql_select = "SELECT p.id, p.autor, p.date, p.short_story, CHAR_LENGTH(p.full_story) as full_story, p.xfields, p.title, p.category, p.alt_name, p.comm_num, p.allow_comm, p.fixed, p.tags, e.news_read, e.allow_rate, e.rating, e.vote_num, e.votes, e.view_edit, e.editdate, e.editor, e.reason FROM " . PREFIX . "_post p LEFT JOIN " . PREFIX . "_post_extras e ON (p.id=e.news_id)";
1575 $where = array();
1576 $allow_cache = $config['allow_cache'];
1577
1578 if( preg_match( "#aviable=['\"](.+?)['\"]#i", $param_str, $match ) ) {
1579 $aviable = explode( '|', $match[1] );
1580 } else $aviable[] = "global";
1581
1582 $do = $dle_module ? $dle_module : "main";
1583
1584 if( ! (in_array( $do, $aviable )) and ($aviable[0] != "global") ) return "";
1585
1586 if( preg_match( "#id=['\"](.+?)['\"]#i", $param_str, $match ) ) {
1587
1588 $temp_array = array();
1589 $where_id = array();
1590 $match[1] = explode (',', trim($match[1]));
1591
1592 foreach ($match[1] as $value) {
1593
1594 if( count(explode('-', $value)) == 2 ) {
1595 $value = explode('-', $value);
1596 $where_id[] = "id >= '" . intval($value[0]) . "' AND id <= '".intval($value[1])."'";
1597
1598 } else $temp_array[] = intval($value);
1599
1600 }
1601
1602 if ( count($temp_array) ) {
1603
1604 $where_id[] = "id IN ('" . implode("','", $temp_array) . "')";
1605 }
1606
1607 if ( count($where_id) ) {
1608 $custom_id = implode(' OR ', $where_id);
1609 $where[] = $custom_id;
1610
1611 }
1612 }
1613
1614 if( preg_match( "#tags=['\"](.+?)['\"]#i", $param_str, $match ) ) {
1615
1616 $temp_array = array();
1617 $tagscache=$match[1];
1618
1619 $match[1] = explode (',', trim($match[1]));
1620
1621 foreach ($match[1] as $value) {
1622 $value = $db->safesql(trim($value));
1623 if( $value ) $temp_array[] = "tag='{$value}'";
1624 }
1625
1626 if ( count($temp_array) ) {
1627
1628 $temp_array = implode(" OR ", $temp_array);
1629
1630 $db->query ( "SELECT news_id FROM " . PREFIX . "_tags WHERE {$temp_array}" );
1631
1632 $temp_array = array ();
1633
1634 while ( $row = $db->get_row () ) {
1635
1636 if (!in_array($row['news_id'], $temp_array)) $temp_array[] = $row['news_id'];
1637
1638 }
1639
1640 if (count ( $temp_array )) {
1641
1642 $where[] = "id IN ('" . implode("','", $temp_array) . "')";
1643
1644 } else $where[] = "id IN ('0')";
1645
1646 }
1647
1648 } else $tagscache="";
1649
1650 if( preg_match( "#idexclude=['\"](.+?)['\"]#i", $param_str, $match ) ) {
1651
1652 $temp_array = array();
1653 $where_id = array();
1654 $match[1] = explode (',', trim($match[1]));
1655
1656 foreach ($match[1] as $value) {
1657
1658 if( count(explode('-', $value)) == 2 ) {
1659 $value = explode('-', $value);
1660 $where_id[] = "(id < '" . intval($value[0]) . "' OR id > '".intval($value[1])."')";
1661
1662 } else $temp_array[] = intval($value);
1663
1664 }
1665
1666 if ( count($temp_array) ) {
1667
1668 $where_id[] = "id NOT IN ('" . implode("','", $temp_array) . "')";
1669 }
1670
1671 if ( count($where_id) ) {
1672 $custom_id = implode(' AND ', $where_id);
1673 $where[] = $custom_id;
1674
1675 }
1676 }
1677
1678 $allow_list = explode( ',', $user_group[$member_id['user_group']]['allow_cats'] );
1679
1680 if( $allow_list[0] != "all" AND !$user_group[$member_id['user_group']]['allow_short'] ) {
1681
1682 if( $config['allow_multi_category'] ) {
1683
1684 $where[] = "category regexp '[[:<:]](" . implode( '|', $allow_list ) . ")[[:>:]]'";
1685
1686 } else {
1687
1688 $where[] = "category IN ('" . implode( "','", $allow_list ) . "')";
1689
1690 }
1691
1692 }
1693
1694 if( preg_match( "#category=['\"](.+?)['\"]#i", $param_str, $match ) ) {
1695
1696 $temp_array = array();
1697
1698 $match[1] = explode (',', $match[1]);
1699
1700 foreach ($match[1] as $value) {
1701
1702 if( count(explode('-', $value)) == 2 ) $temp_array[] = get_mass_cats($value);
1703 else $temp_array[] = intval($value);
1704
1705 }
1706
1707
1708 $temp_array = implode(',', $temp_array);
1709
1710 $custom_category = $db->safesql( trim(str_replace( ',', '|', $temp_array )) );
1711
1712 if( $config['allow_multi_category'] ) {
1713
1714 $where[] = "category regexp '[[:<:]](" . $custom_category . ")[[:>:]]'";
1715
1716 } else {
1717
1718 $custom_category = str_replace( "|", "','", $custom_category );
1719 $where[] = "category IN ('" . $custom_category . "')";
1720
1721 }
1722 }
1723
1724 if( preg_match( "#categoryexclude=['\"](.+?)['\"]#i", $param_str, $match ) ) {
1725
1726 $temp_array = array();
1727
1728 $match[1] = explode (',', $match[1]);
1729
1730 foreach ($match[1] as $value) {
1731
1732 if( count(explode('-', $value)) == 2 ) $temp_array[] = get_mass_cats($value);
1733 else $temp_array[] = intval($value);
1734
1735 }
1736
1737
1738 $temp_array = implode(',', $temp_array);
1739
1740 $custom_category = $db->safesql( trim(str_replace( ',', '|', $temp_array )) );
1741
1742 if( $config['allow_multi_category'] ) {
1743
1744 $where[] = "category NOT REGEXP '[[:<:]](" . $custom_category . ")[[:>:]]'";
1745
1746 } else {
1747
1748 $custom_category = str_replace( "|", "','", $custom_category );
1749 $where[] = "category NOT IN ('" . $custom_category . "')";
1750
1751 }
1752 }
1753
1754 if( preg_match( "#days=['\"](.+?)['\"]#i", $param_str, $match ) ) {
1755 $days = intval(trim($match[1]));
1756 $where[] = "p.date >= '{$thisdate}' - INTERVAL {$days} DAY AND p.date < '{$thisdate}'";
1757 } else $days = 0;
1758
1759 if( preg_match( "#author=['\"](.+?)['\"]#i", $param_str, $match ) ) {
1760 $author = $db->safesql(trim($match[1]));
1761 $where[] = "p.autor like '{$author}'";
1762 } else $author = "";
1763
1764 $where[] = "approve=1";
1765
1766 if( $config['no_date'] AND !$config['news_future'] AND !$days) $where[] = "date < '" . $thisdate . "'";
1767
1768 if( preg_match( "#template=['\"](.+?)['\"]#i", $param_str, $match ) ) {
1769 $custom_template = trim($match[1]);
1770 } else $custom_template = "shortstory";
1771
1772 if( preg_match( "#from=['\"](.+?)['\"]#i", $param_str, $match ) ) {
1773 $custom_from = intval($match[1]);
1774 $custom_all = $custom_from;
1775 } else { $custom_from = 0; $custom_all = 0;}
1776
1777 if( preg_match( "#limit=['\"](.+?)['\"]#i", $param_str, $match ) ) {
1778 $custom_limit = intval($match[1]);
1779 } else $custom_limit = $config['news_number'];
1780
1781 if( preg_match( "#cache=['\"](.+?)['\"]#i", $param_str, $match ) ) {
1782 if( $match[1] == "yes" ) $config['allow_cache'] = 1;
1783 else $config['allow_cache'] = false;
1784 }
1785
1786 if( $config['allow_cache'] ) $short_news_cache = true; else $short_news_cache = false;
1787
1788 if( preg_match( "#fixed=['\"](.+?)['\"]#i", $param_str, $match ) ) {
1789
1790 $fixed = "";
1791 $fixedcache = "fixed yes";
1792
1793 if( $match[1] == "yes" ) $fixed = "fixed DESC, ";
1794 elseif( $match[1] == "only" ) { $where[] = "fixed='1'"; $fixedcache = "fixed only"; }
1795 elseif( $match[1] == "without" ) { $where[] = "fixed='0'"; $fixedcache = "without fixed"; }
1796
1797 } else { $fixed = ""; $fixedcache = ""; }
1798
1799 if( $is_logged and ($user_group[$member_id['user_group']]['allow_edit'] and ! $user_group[$member_id['user_group']]['allow_all_edit']) ) $config['allow_cache'] = false;
1800
1801 if( $cat_info[$custom_category]['news_sort'] != "" ) $news_sort = $cat_info[$custom_category]['news_sort']; else $news_sort = $config['news_sort'];
1802 if( $cat_info[$custom_category]['news_msort'] != "" ) $news_msort = $cat_info[$custom_category]['news_msort']; else $news_msort = $config['news_msort'];
1803
1804 if( preg_match( "#sort=['\"](.+?)['\"]#i", $param_str, $match ) ) {
1805 $allowed_sort = array ('asc' => 'ASC', 'desc' => 'DESC' );
1806
1807 $match[1] = strtolower($match[1]);
1808
1809 if ( $allowed_sort[$match[1]] ) $news_msort = $allowed_sort[$match[1]];
1810
1811 }
1812
1813 if( preg_match( "#order=['\"](.+?)['\"]#i", $param_str, $match ) ) {
1814 $allowed_sort = array ('date' => 'date', 'rating' => 'rating', 'reads' => 'news_read', 'comments' => 'comm_num','title' => 'title', 'rand' => 'RAND()' );
1815
1816 $match[1] = strtolower($match[1]);
1817
1818 if ( $allowed_sort[$match[1]] ) $news_sort = $allowed_sort[$match[1]];
1819
1820 if ($match[1] == "rand" ) { $fixed = ""; $news_msort = ""; }
1821 }
1822
1823 if( preg_match( "#navigation=['\"](.+?)['\"]#i", $param_str, $match ) ) {
1824
1825 if( $match[1] == "yes" AND $url_page !== false ) {
1826
1827 $build_navigation = true;
1828 if (isset ( $_GET['cstart'] )) $cstart = intval ( $_GET['cstart'] ); else $cstart = 0;
1829
1830 if ($cstart > 10) $config['allow_cache'] = false;
1831
1832 if ($cstart) {
1833 $cstart = $cstart - 1;
1834 $cstart = ($cstart * $custom_limit) + $custom_from;
1835 $custom_from = $cstart;
1836 }
1837
1838 } else $build_navigation = false;
1839
1840 } else $build_navigation = false;
1841
1842 $custom_cache_id = $custom_id.$custom_category.$user_group[$member_id['user_group']]['allow_cats'].$custom_from.$custom_limit.$news_sort.$news_msort.$custom_template.$days.$author.$fixedcache.$tagscache;
1843
1844 $content = dle_cache( "news", $custom_cache_id, true );
1845
1846 if( $content !== false ) {
1847
1848 $config['allow_cache'] = $allow_cache;
1849 $custom_news = true;
1850 return $content;
1851
1852 } else {
1853
1854 if ( $build_navigation ) {
1855
1856 $count_all = $db->super_query( "SELECT COUNT(*) as count FROM " . PREFIX . "_post p WHERE ".implode(' AND ', $where) );
1857 $count_all = $count_all['count'] - $custom_all;
1858
1859 }
1860
1861 $tpl = new dle_template();
1862 $tpl->dir = TEMPLATE_DIR;
1863
1864 $tpl->load_template( $custom_template . '.tpl' );
1865
1866 $sql_select .= " WHERE ".implode(' AND ', $where)." ORDER BY " . $fixed . $news_sort . " " . $news_msort . " LIMIT " . $custom_from . "," . $custom_limit;
1867 $sql_result = $db->query( $sql_select );
1868
1869 include (ENGINE_DIR . '/modules/show.custom.php');
1870
1871 if( $config['files_allow'] ) if( strpos( $tpl->result['content'], "[attachment=" ) !== false ) {
1872 $tpl->result['content'] = show_attach( $tpl->result['content'], $attachments );
1873 }
1874
1875 if ( $custom_news ) create_cache( "news", $tpl->result['content'], $custom_cache_id, true );
1876 $config['allow_cache'] = $allow_cache;
1877 return $tpl->result['content'];
1878
1879 }
1880
1881}
1882
1883function check_ip($ips) {
1884
1885 $_IP = get_ip();
1886
1887 $blockip = FALSE;
1888
1889 if( is_array( $ips ) ) {
1890 foreach ( $ips as $ip_line ) {
1891
1892 $ip_arr = rtrim( $ip_line['ip'] );
1893
1894 if( $ip_arr == $_IP ) {
1895 $blockip = $_IP;
1896 break;
1897 }
1898 if( count(explode ('/', $ip_arr)) == 2 ) {
1899
1900 if( maskmatch($_IP, $ip_arr) ) {
1901 $blockip = $ip_line['ip'];
1902 break;
1903 }
1904
1905 } else {
1906
1907 $ip_check_matches = 0;
1908 $db_ip_split = explode( ".", $ip_arr );
1909 $this_ip_split = explode( ".", $_IP );
1910
1911 for($i_i = 0; $i_i < 4; $i_i ++) {
1912 if( $this_ip_split[$i_i] == $db_ip_split[$i_i] or $db_ip_split[$i_i] == '*' ) {
1913 $ip_check_matches += 1;
1914 }
1915
1916 }
1917
1918 if( $ip_check_matches == 4 ) {
1919 $blockip = $ip_line['ip'];
1920 break;
1921 }
1922 }
1923 }
1924 }
1925
1926 return $blockip;
1927}
1928
1929function allowed_ip($ip_array) {
1930
1931 $ip_array = trim( $ip_array );
1932
1933 $_IP = get_ip();
1934
1935 if( $ip_array == "" ) {
1936 return true;
1937 }
1938
1939 $ip_array = explode( "|", $ip_array );
1940
1941 $db_ip_split = explode( ".", $_IP );
1942
1943 foreach ( $ip_array as $ip ) {
1944
1945 $ip = trim( $ip );
1946
1947 if( $ip == $_IP ) {
1948 return true;
1949 }
1950
1951 if( count(explode ('/', $ip)) == 2 ) {
1952
1953 if( maskmatch($_IP, $ip) ) return true;
1954
1955 } else {
1956
1957 $ip_check_matches = 0;
1958 $this_ip_split = explode( ".", $ip );
1959
1960
1961 for($i_i = 0; $i_i < 4; $i_i ++) {
1962 if( $this_ip_split[$i_i] == $db_ip_split[$i_i] or $this_ip_split[$i_i] == '*' ) {
1963 $ip_check_matches += 1;
1964 }
1965
1966 }
1967
1968 if( $ip_check_matches == 4 ) return true;
1969 }
1970
1971 }
1972
1973 return false;
1974}
1975
1976function maskmatch($IP, $CIDR) {
1977 list ($net, $mask) = explode ('/', $CIDR);
1978 return ( ip2long($IP) & ~((1 << (32 - $mask)) - 1) ) == ip2long ($net);
1979}
1980
1981function check_netz($ip1, $ip2) {
1982
1983 $ip1 = explode( ".", $ip1 );
1984 $ip2 = explode( ".", $ip2 );
1985
1986 if( $ip1[0] != $ip2[0] ) return false;
1987 if( $ip1[1] != $ip2[1] ) return false;
1988
1989 return true;
1990
1991}
1992
1993function show_attach($story, $id, $static = false) {
1994 global $db, $config, $lang, $user_group, $member_id, $tpl, $_TIME, $news_date;
1995
1996 $find_1 = array();
1997 $find_2 = array();
1998 $replace_1 = array();
1999 $replace_2 = array();
2000
2001 if( $static ) {
2002
2003 if( is_array( $id ) and count( $id ) ) {
2004 $list = array();
2005
2006 foreach ( $id as $value ) {
2007 $list[] = intval($value);
2008 }
2009
2010 $id = implode( ',', $list );
2011
2012 $where = "static_id IN ({$id})";
2013
2014 } else $where = "static_id = '".intval($id)."'";
2015
2016 $db->query( "SELECT id, date, name, onserver, dcount FROM " . PREFIX . "_static_files WHERE $where" );
2017
2018 $area = "&area=static";
2019
2020 } else {
2021
2022 if( is_array( $id ) and count( $id ) ) {
2023
2024 $list = array();
2025
2026 foreach ( $id as $value ) {
2027 $list[] = intval($value);
2028 }
2029
2030 $id = implode( ',', $list );
2031
2032 $where = "news_id IN ({$id})";
2033
2034 } else $where = "news_id = '".intval($id)."'";
2035
2036 $db->query( "SELECT id, date, name, onserver, dcount FROM " . PREFIX . "_files WHERE $where" );
2037
2038 $area = "";
2039
2040 }
2041
2042 if( !file_exists( $tpl->dir . "/attachment.tpl" ) ) {
2043
2044 $tpl->template = <<<HTML
2045[allow-download]<span class="attachment"><a href="{link}" >{name}</a> [count] [{size}] ({$lang['att_dcount']} {count})[/count]</span>[/allow-download]
2046[not-allow-download]<span class="attachment">{$lang['att_denied']}</span>[/not-allow-download]
2047HTML;
2048
2049 $tpl->copy_template = $tpl->template;
2050
2051 } else {
2052
2053 $tpl->load_template( 'attachment.tpl' );
2054
2055 }
2056
2057 while ( $row = $db->get_row() ) {
2058
2059 $size = formatsize( @filesize( ROOT_DIR . '/uploads/files/' . $row['onserver'] ) );
2060 $md5 = @md5_file( ROOT_DIR . '/uploads/files/' . $row['onserver'] );
2061 $row['name'] = explode( "/", $row['name'] );
2062 $row['name'] = end( $row['name'] );
2063
2064 $find_1[] = '[attachment=' . $row['id'] . ']';
2065 $find_2[] = "#\[attachment={$row['id']}:(.+?)\]#i";
2066
2067 if ( $user_group[$member_id['user_group']]['allow_files'] ) {
2068
2069 $tpl->set( '[allow-download]', "" );
2070 $tpl->set( '[/allow-download]', "" );
2071 $tpl->set_block( "'\\[not-allow-download\\](.*?)\\[/not-allow-download\\]'si", "" );
2072
2073 } else {
2074
2075 $tpl->set( '[not-allow-download]', "" );
2076 $tpl->set( '[/not-allow-download]', "" );
2077 $tpl->set_block( "'\\[allow-download\\](.*?)\\[/allow-download\\]'si", "" );
2078
2079 }
2080
2081 if ( $config['files_count'] ) {
2082 $tpl->set( '{count}', $row['dcount'] );
2083 $tpl->set( '[count]', "" );
2084 $tpl->set( '[/count]', "" );
2085 $tpl->set_block( "'\\[not-allow-count\\](.*?)\\[/not-allow-count\\]'si", "" );
2086
2087 } else {
2088 $tpl->set( '{count}', "" );
2089 $tpl->set( '[not-allow-count]', "" );
2090 $tpl->set( '[/not-allow-count]', "" );
2091 $tpl->set_block( "'\\[count\\](.*?)\\[/count\\]'si", "" );
2092
2093 }
2094
2095 if( date( 'Ymd', $row['date'] ) == date( 'Ymd', $_TIME ) ) {
2096
2097 $tpl->set( '{date}', $lang['time_heute'] . langdate( ", H:i", $row['date'] ) );
2098
2099 } elseif( date( 'Ymd', $row['date'] ) == date( 'Ymd', ($_TIME - 86400) ) ) {
2100
2101 $tpl->set( '{date}', $lang['time_gestern'] . langdate( ", H:i", $row['date'] ) );
2102
2103 } else {
2104
2105 $tpl->set( '{date}', langdate( $config['timestamp_active'], $row['date'] ) );
2106
2107 }
2108
2109 $news_date = $row['date'];
2110 $tpl->copy_template = preg_replace_callback ( "#\{date=(.+?)\}#i", "formdate", $tpl->copy_template );
2111
2112 $tpl->set( '{name}', $row['name'] );
2113 $tpl->set( '{link}', $config['http_home_url']."engine/download.php?id=".$row['id'].$area );
2114 $tpl->set( '{size}', $size );
2115 $tpl->set( '{md5}', $md5 );
2116 $tpl->set( '{id}', $row['id'] );
2117
2118 $tpl->compile( 'attachment' );
2119
2120 $replace_1[] = $tpl->result['attachment'];
2121
2122 $tpl->result['attachment'] = str_replace( $row['name'], "\\1", $tpl->result['attachment'] );
2123
2124 $replace_2[] = $tpl->result['attachment'];
2125
2126 $tpl->result['attachment'] = '';
2127
2128 }
2129
2130 $tpl->clear();
2131 $db->free();
2132
2133 $story = str_replace ( $find_1, $replace_1, $story );
2134 $story = preg_replace( $find_2, $replace_2, $story );
2135
2136 return $story;
2137
2138}
2139
2140function xfieldsload($profile = false) {
2141 global $lang;
2142
2143 if( $profile ) $path = ENGINE_DIR . '/data/xprofile.txt';
2144 else $path = ENGINE_DIR . '/data/xfields.txt';
2145
2146 $filecontents = file( $path );
2147
2148 if( !is_array( $filecontents ) ) msgbox( "System error", "File <b>{$path}</b> not found" );
2149 else {
2150 foreach ( $filecontents as $name => $value ) {
2151 $filecontents[$name] = explode( "|", trim( $value ) );
2152 foreach ( $filecontents[$name] as $name2 => $value2 ) {
2153 $value2 = str_replace( "|", "|", $value2 );
2154 $value2 = str_replace( "__NEWL__", "\r\n", $value2 );
2155 $filecontents[$name][$name2] = $value2;
2156 }
2157 }
2158 }
2159 return $filecontents;
2160}
2161
2162function xfieldsdataload($id) {
2163
2164 if( $id == "" ) return;
2165
2166 $xfieldsdata = explode( "||", $id );
2167 foreach ( $xfieldsdata as $xfielddata ) {
2168 list ( $xfielddataname, $xfielddatavalue ) = explode( "|", $xfielddata );
2169 $xfielddataname = str_replace( "|", "|", $xfielddataname );
2170 $xfielddataname = str_replace( "__NEWL__", "\r\n", $xfielddataname );
2171 $xfielddatavalue = str_replace( "|", "|", $xfielddatavalue );
2172 $xfielddatavalue = str_replace( "__NEWL__", "\r\n", $xfielddatavalue );
2173 $data[$xfielddataname] = $xfielddatavalue;
2174 }
2175 return $data;
2176}
2177
2178function create_keywords($story) {
2179 global $metatags, $config;
2180
2181 $keyword_count = 20;
2182 $newarr = array ();
2183
2184 $quotes = array ("\x22", "\x60", "\t", "\n", "\r", ",", ".", "/", "\\", "¬", "#", ";", ":", "@", "~", "[", "]", "{", "}", "=", "-", "+", ")", "(", "*", "^", "%", "$", "<", ">", "?", "!", '"');
2185 $fastquotes = array ("\x22", "\x60", "\t", "\n", "\r", '"', "\\", '\r', '\n', "/", "{", "}", "[", "]" );
2186
2187 $story = preg_replace( "#\[hide\](.+?)\[/hide\]#is", "", $story );
2188 $story = preg_replace( "'\[attachment=(.*?)\]'si", "", $story );
2189 $story = preg_replace( "'\[page=(.*?)\](.*?)\[/page\]'si", "", $story );
2190 $story = str_replace( "{PAGEBREAK}", "", $story );
2191 $story = str_replace( " ", " ", $story );
2192 $story = str_replace( '<br />', ' ', $story );
2193 $story = strip_tags( $story );
2194 $story = preg_replace( "#&(.+?);#", "", $story );
2195 $story = trim(str_replace( " ,", "", stripslashes( $story )));
2196
2197 $story = str_replace( $fastquotes, '', $story );
2198
2199 $metatags['description'] = dle_substr( $story, 0, 200, $config['charset'] );
2200
2201 if( ($temp_dmax = dle_strrpos( $metatags['description'], ' ', $config['charset'] )) ) $metatags['description'] = dle_substr( $metatags['description'], 0, $temp_dmax, $config['charset'] );
2202
2203 $story = str_replace( $quotes, ' ', $story );
2204
2205 $arr = explode( " ", $story );
2206
2207 foreach ( $arr as $word ) {
2208 if( dle_strlen( $word, $config['charset'] ) > 4 ) $newarr[] = $word;
2209 }
2210
2211 $arr = array_count_values( $newarr );
2212 arsort( $arr );
2213
2214 $arr = array_keys( $arr );
2215
2216 $total = count( $arr );
2217
2218 $offset = 0;
2219
2220 $arr = array_slice( $arr, $offset, $keyword_count );
2221
2222 $metatags['keywords'] = implode( ", ", $arr );
2223}
2224
2225function news_permission($id) {
2226
2227 if( $id == "" ) return;
2228
2229 $data = array ();
2230 $groups = explode( "||", $id );
2231 foreach ( $groups as $group ) {
2232 list ( $groupid, $groupvalue ) = explode( ":", $group );
2233 $data[$groupid] = $groupvalue;
2234 }
2235 return $data;
2236}
2237
2238function bannermass($fest, $massiv) {
2239 return $fest . $massiv[@array_rand( $massiv )]['text'];
2240}
2241
2242function get_sub_cats($id, $subcategory = '') {
2243
2244 global $cat_info;
2245 $subfound = array ();
2246
2247 if( $subcategory == '' ) $subcategory = $id;
2248
2249 foreach ( $cat_info as $cats ) {
2250 if( $cats['parentid'] == $id ) {
2251 $subfound[] = $cats['id'];
2252 }
2253 }
2254
2255 foreach ( $subfound as $parentid ) {
2256 $subcategory .= "|" . $parentid;
2257 $subcategory = get_sub_cats( $parentid, $subcategory );
2258 }
2259
2260 return $subcategory;
2261
2262}
2263
2264function check_xss() {
2265
2266 $url = html_entity_decode( urldecode( $_SERVER['QUERY_STRING'] ), ENT_QUOTES, 'ISO-8859-1' );
2267 $url = str_replace( "\\", "/", $url );
2268
2269 if (isset($_GET['do']) AND $_GET['do'] == "xfsearch") {
2270
2271 $f = html_entity_decode( urldecode( $_GET['xf'] ), ENT_QUOTES, 'ISO-8859-1' );
2272
2273 $count1 = substr_count ($f, "'");
2274 $count2 = substr_count ($url, "'");
2275
2276 if ( $count1 == $count2 AND (strpos( $url, '<' ) === false) AND (strpos( $url, '>' ) === false) AND (strpos( $url, './' ) === false) AND (strpos( $url, '../' ) === false) AND (strpos( $url, '.php' ) === false) ) return;
2277
2278 }
2279
2280 if (isset($_GET['do']) AND $_GET['do'] == "tags") {
2281
2282 $f = html_entity_decode( urldecode( $_GET['tag'] ), ENT_QUOTES, 'ISO-8859-1' );
2283
2284 $count1 = substr_count ($f, "'");
2285 $count2 = substr_count ($url, "'");
2286
2287 if ( $count1 == $count2 AND (strpos( $url, '<' ) === false) AND (strpos( $url, '>' ) === false) AND (strpos( $url, './' ) === false) AND (strpos( $url, '../' ) === false) AND (strpos( $url, '.php' ) === false) ) return;
2288
2289 }
2290
2291 if( $url ) {
2292
2293 if( (strpos( $url, '<' ) !== false) || (strpos( $url, '>' ) !== false) || (strpos( $url, './' ) !== false) || (strpos( $url, '../' ) !== false) || (strpos( $url, '\'' ) !== false) || (strpos( $url, '.php' ) !== false) ) {
2294 if( $_GET['do'] != "search" OR $_GET['subaction'] != "search" ) die( "Hacking attempt!" );
2295 }
2296
2297 }
2298
2299 $url = html_entity_decode( urldecode( $_SERVER['REQUEST_URI'] ), ENT_QUOTES, 'ISO-8859-1' );
2300 $url = str_replace( "\\", "/", $url );
2301
2302 if( $url ) {
2303
2304 if( (strpos( $url, '<' ) !== false) || (strpos( $url, '>' ) !== false) || (strpos( $url, '\'' ) !== false) ) {
2305 if( $_GET['do'] != "search" OR $_GET['subaction'] != "search" ) die( "Hacking attempt!" );
2306
2307 }
2308
2309 }
2310
2311}
2312
2313function check_category( $matches=array() ) {
2314 global $category_id;
2315
2316 $cats = $matches[2];
2317 $block = $matches[3];
2318 $category = $category_id;
2319
2320 if ($matches[1] == "category" OR $matches[1] == "catlist") $action = true; else $action = false;
2321
2322 $cats = str_replace(" ", "", $cats );
2323 $cats = explode( ',', $cats );
2324 $category = explode( ',', $category );
2325 $found = false;
2326
2327 foreach ( $category as $element ) {
2328
2329 if( $action ) {
2330
2331 if( in_array( $element, $cats ) ) {
2332
2333 return $block;
2334 }
2335
2336 } else {
2337
2338 if( in_array( $element, $cats ) ) {
2339 $found = true;
2340 }
2341
2342 }
2343
2344 }
2345
2346 if ( !$action AND !$found ) {
2347
2348 return $block;
2349 }
2350
2351 return "";
2352
2353}
2354
2355function clean_url($url) {
2356
2357 if( $url == '' ) return;
2358
2359 $url = str_replace( "http://", "", strtolower( $url ) );
2360 $url = str_replace( "https://", "", $url );
2361 if( substr( $url, 0, 2 ) == '//' ) $url = str_replace( "//", "", $url );
2362 if( substr( $url, 0, 4 ) == 'www.' ) $url = substr( $url, 4 );
2363 $url = explode( '/', $url );
2364 $url = reset( $url );
2365 $url = explode( ':', $url );
2366 $url = reset( $url );
2367
2368 return $url;
2369}
2370
2371function get_url($id) {
2372
2373 global $cat_info;
2374
2375 if( ! $id ) return;
2376
2377 $parent_id = $cat_info[$id]['parentid'];
2378
2379 $url = $cat_info[$id]['alt_name'];
2380
2381 while ( $parent_id ) {
2382
2383 $url = $cat_info[$parent_id]['alt_name'] . "/" . $url;
2384
2385 $parent_id = $cat_info[$parent_id]['parentid'];
2386
2387 if($parent_id) {
2388 if( $cat_info[$parent_id]['parentid'] == $cat_info[$parent_id]['id'] ) break;
2389 }
2390
2391 }
2392
2393 return $url;
2394}
2395
2396function get_categories($id, $separator=" »") {
2397
2398 global $cat_info, $config, $PHP_SELF;
2399
2400 if( ! $id ) return;
2401
2402 $parent_id = $cat_info[$id]['parentid'];
2403
2404 if( $config['allow_alt_url'] ) $list = "<a href=\"" . $config['http_home_url'] . get_url( $id ) . "/\">{$cat_info[$id]['name']}</a>";
2405 else $list = "<a href=\"$PHP_SELF?do=cat&category={$cat_info[$id]['alt_name']}\">{$cat_info[$id]['name']}</a>";
2406
2407 while ( $parent_id ) {
2408
2409 if( $config['allow_alt_url'] ) $list = "<a href=\"" . $config['http_home_url'] . get_url( $parent_id ) . "/\">{$cat_info[$parent_id]['name']}</a>" . "{$separator} " . $list;
2410 else $list = "<a href=\"$PHP_SELF?do=cat&category={$cat_info[$parent_id]['alt_name']}\">{$cat_info[$parent_id]['name']}</a>" . "{$separator} " . $list;
2411
2412 $parent_id = $cat_info[$parent_id]['parentid'];
2413
2414 if($parent_id) {
2415 if( $cat_info[$parent_id]['parentid'] == $cat_info[$parent_id]['id'] ) break;
2416 }
2417
2418 }
2419
2420 return $list;
2421}
2422
2423function get_breadcrumbcategories($id, $separator="»") {
2424
2425 global $cat_info, $config, $PHP_SELF;
2426
2427 if( ! $id ) return;
2428
2429 $parent_id = $cat_info[$id]['parentid'];
2430
2431 if( $config['allow_alt_url'] ) $list = "<span itemscope itemtype=\"http://data-vocabulary.org/Breadcrumb\"><a href=\"" . $config['http_home_url'] . get_url( $id ) . "/\" itemprop=\"url\"><span itemprop=\"title\">{$cat_info[$id]['name']}</span></a></span>";
2432 else $list = "<span itemscope itemtype=\"http://data-vocabulary.org/Breadcrumb\"><a href=\"$PHP_SELF?do=cat&category={$cat_info[$id]['alt_name']}\" itemprop=\"url\"><span itemprop=\"title\">{$cat_info[$id]['name']}</span></a></span>";
2433
2434 while ( $parent_id ) {
2435
2436 if( $config['allow_alt_url'] ) $list = "<span itemscope itemtype=\"http://data-vocabulary.org/Breadcrumb\"><a href=\"" . $config['http_home_url'] . get_url( $parent_id ) . "/\" itemprop=\"url\"><span itemprop=\"title\">{$cat_info[$parent_id]['name']}</span></a></span>" . " {$separator} " . $list;
2437 else $list = "<span itemscope itemtype=\"http://data-vocabulary.org/Breadcrumb\"><a href=\"$PHP_SELF?do=cat&category={$cat_info[$parent_id]['alt_name']}\" itemprop=\"url\"><span itemprop=\"title\">{$cat_info[$parent_id]['name']}</span></a></span>" . " {$separator} " . $list;
2438
2439 $parent_id = $cat_info[$parent_id]['parentid'];
2440
2441 if($parent_id) {
2442 if( $cat_info[$parent_id]['parentid'] == $cat_info[$parent_id]['id'] ) break;
2443 }
2444 }
2445
2446 return $list;
2447}
2448
2449function set_cookie($name, $value, $expires) {
2450
2451 if( $expires ) {
2452
2453 $expires = time() + ($expires * 86400);
2454
2455 } else {
2456
2457 $expires = FALSE;
2458
2459 }
2460
2461 if( PHP_VERSION < 5.2 ) {
2462
2463 if ( DOMAIN ) setcookie( $name, $value, $expires, "/", "; HttpOnly" );
2464 else setcookie( $name, $value, $expires, "/", DOMAIN . "; HttpOnly" );
2465
2466 } else {
2467
2468 setcookie( $name, $value, $expires, "/", DOMAIN, NULL, TRUE );
2469
2470 }
2471}
2472
2473function news_sort($do) {
2474
2475 global $config, $lang;
2476
2477 if( ! $do ) $do = "main";
2478
2479 $find_sort = "dle_sort_" . $do;
2480 $direction_sort = "dle_direction_" . $do;
2481
2482 $find_sort = str_replace( ".", "", $find_sort );
2483 $direction_sort = str_replace( ".", "", $direction_sort );
2484
2485 $sort = array ();
2486 $allowed_sort = array ('date', 'rating', 'news_read', 'comm_num', 'title' );
2487
2488 $soft_by_array = array (
2489
2490 'date' => array (
2491
2492 'name' => $lang['sort_by_date'], 'value' => "date", 'direction' => "desc", 'image' => "" ),
2493
2494 'rating' => array (
2495
2496 'name' => $lang['sort_by_rating'], 'value' => "rating", 'direction' => "desc", 'image' => "" ),
2497
2498 'news_read' => array (
2499
2500 'name' => $lang['sort_by_read'], 'value' => "news_read", 'direction' => "desc", 'image' => "" ),
2501
2502 'comm_num' => array (
2503
2504 'name' => $lang['sort_by_comm'], 'value' => "comm_num", 'direction' => "desc", 'image' => "" ),
2505
2506 'title' => array (
2507
2508 'name' => $lang['sort_by_title'], 'value' => "title", 'direction' => "desc", 'image' => "" )
2509
2510 );
2511
2512 if( !$config['allow_comments'] ) { unset($allowed_sort[3]); unset($soft_by_array['comm_num']); }
2513
2514 if( isset( $_SESSION[$direction_sort] ) AND ($_SESSION[$direction_sort] == "desc" OR $_SESSION[$direction_sort] == "asc") ) $direction = $_SESSION[$direction_sort];
2515 else $direction = $config['news_msort'];
2516
2517 if( isset( $_SESSION[$find_sort] ) AND $_SESSION[$find_sort] AND in_array( $_SESSION[$find_sort], $allowed_sort ) ) $soft_by = $_SESSION[$find_sort];
2518 else $soft_by = $config['news_sort'];
2519
2520 if( strtolower( $direction ) == "asc" ) {
2521
2522 $soft_by_array[$soft_by]['image'] = "<img src=\"{THEME}/dleimages/asc.gif\" alt=\"\" />";
2523 $soft_by_array[$soft_by]['direction'] = "desc";
2524
2525 } else {
2526
2527 $soft_by_array[$soft_by]['image'] = "<img src=\"{THEME}/dleimages/desc.gif\" alt=\"\" />";
2528 $soft_by_array[$soft_by]['direction'] = "asc";
2529 }
2530
2531 foreach ( $soft_by_array as $value ) {
2532
2533 $sort[] = $value['image'] . "<a href=\"#\" onclick=\"dle_change_sort('{$value['value']}','{$value['direction']}'); return false;\">" . $value['name'] . "</a>";
2534 }
2535
2536 $sort = "<form name=\"news_set_sort\" id=\"news_set_sort\" method=\"post\" action=\"\" >" . $lang['sort_main'] . " " . implode( " | ", $sort );
2537
2538 $sort .= <<<HTML
2539<input type="hidden" name="dlenewssortby" id="dlenewssortby" value="{$config['news_sort']}" />
2540<input type="hidden" name="dledirection" id="dledirection" value="{$config['news_msort']}" />
2541<input type="hidden" name="set_new_sort" id="set_new_sort" value="{$find_sort}" />
2542<input type="hidden" name="set_direction_sort" id="set_direction_sort" value="{$direction_sort}" />
2543<script type="text/javascript">
2544<!-- begin
2545
2546function dle_change_sort(sort, direction){
2547
2548 var frm = document.getElementById('news_set_sort');
2549
2550 frm.dlenewssortby.value=sort;
2551 frm.dledirection.value=direction;
2552
2553 frm.submit();
2554 return false;
2555};
2556
2557// end -->
2558</script></form>
2559HTML;
2560
2561 return $sort;
2562}
2563
2564function compare_tags($a, $b) {
2565
2566 if( $a['tag'] == $b['tag'] ) return 0;
2567
2568 return strcasecmp( $a['tag'], $b['tag'] );
2569
2570}
2571
2572function convert_unicode($t, $to = 'windows-1251') {
2573
2574 $to = strtolower( $to );
2575
2576 if( $to == 'utf-8' ) {
2577
2578 return $t;
2579
2580 } else {
2581
2582 if( function_exists( 'mb_convert_encoding' ) ) {
2583
2584 $t = mb_convert_encoding( $t, $to, "UTF-8" );
2585
2586 } elseif( function_exists( 'iconv' ) ) {
2587
2588 $t = iconv( "UTF-8", $to . "//IGNORE", $t );
2589
2590 } else $t = "The library iconv AND mbstring is not supported by your server";
2591
2592 }
2593
2594 return $t;
2595}
2596
2597function build_js($js, $config) {
2598
2599 $js_array = array();
2600
2601 if ($config['js_min'] AND version_compare(PHP_VERSION, '5.1.0', '>') ) {
2602
2603 $js_array[] = "<script type=\"text/javascript\" src=\"{$config['http_home_url']}engine/classes/min/index.php?charset={$config['charset']}&g=general&16\"></script>";
2604
2605 if ( count($js) ) $js_array[] = "<script type=\"text/javascript\" src=\"{$config['http_home_url']}engine/classes/min/index.php?charset={$config['charset']}&f=".implode(",", $js)."&16\"></script>";
2606
2607 return implode("\n", $js_array);
2608
2609 } else {
2610
2611 $default_array = array (
2612 'engine/classes/js/jquery.js',
2613 'engine/classes/js/jqueryui.js',
2614 'engine/classes/js/dle_js.js',
2615 );
2616
2617 $js = array_merge($default_array, $js);
2618
2619 foreach ($js as $value) {
2620
2621 $js_array[] = "<script type=\"text/javascript\" src=\"{$config['http_home_url']}{$value}\"></script>";
2622
2623 }
2624
2625 return implode("\n", $js_array);
2626 }
2627}
2628
2629function check_static($matches=array()) {
2630 global $dle_module;
2631
2632 $names = $matches[2];
2633 $block = $matches[3];
2634
2635 if ($matches[1] == "static") $action = true; else $action = false;
2636
2637 $names = str_replace(" ", "", $names );
2638 $names = explode( ',', $names );
2639
2640 if ( isset($_GET['page']) ) $page = trim($_GET['page']); else $page = "";
2641
2642 if( $action ) {
2643
2644 if( in_array( $page, $names ) AND $dle_module == "static" ) {
2645
2646 return $block;
2647 }
2648
2649 } else {
2650
2651 if( !in_array( $page, $names ) OR $dle_module != "static") {
2652
2653 return $block;
2654 }
2655
2656 }
2657
2658 return "";
2659}
2660
2661
2662function dle_strlen($value, $charset ) {
2663
2664 if ( strtolower($charset) == "utf-8") {
2665 if( function_exists( 'mb_strlen' ) ) {
2666 return mb_strlen( $value, "utf-8" );
2667
2668 } elseif( function_exists( 'iconv_strlen' ) ) {
2669 return iconv_strlen($value, "utf-8");
2670 }
2671 }
2672
2673 return strlen($value);
2674
2675}
2676
2677function dle_substr($str, $start, $length, $charset ) {
2678
2679 if ( strtolower($charset) == "utf-8") {
2680 if( function_exists( 'mb_substr' ) ) {
2681 return mb_substr( $str, $start, $length, "utf-8" );
2682
2683 } elseif( function_exists( 'iconv_substr' ) ) {
2684 return iconv_substr($str, $start, $length, "utf-8");
2685 }
2686 }
2687
2688 return substr($str, $start, $length);
2689
2690}
2691
2692function dle_strrpos($str, $needle, $charset ) {
2693
2694 if ( strtolower($charset) == "utf-8") {
2695 if( function_exists( 'mb_strrpos' ) ) {
2696 return mb_strrpos( $str, $needle, null, "utf-8" );
2697
2698 } elseif( function_exists( 'iconv_strrpos' ) ) {
2699 return iconv_strrpos($str, $needle, "utf-8");
2700 }
2701 }
2702
2703 return strrpos($str, $needle);
2704
2705}
2706
2707function check_allow_login($ip, $max ) {
2708 global $db, $config;
2709
2710 $config['login_ban_timeout'] = intval($config['login_ban_timeout']);
2711
2712 $block_date = time()-($config['login_ban_timeout'] * 60);
2713
2714 $row = $db->super_query( "SELECT * FROM " . PREFIX . "_login_log WHERE ip='{$ip}'" );
2715
2716 if ( $row['count'] AND $row['date'] < $block_date ) $db->query( "DELETE FROM " . PREFIX . "_login_log WHERE ip = '{$ip}'" );
2717
2718 if ($row['count'] >= $max AND $row['date'] > $block_date ) return false;
2719 else return true;
2720
2721}
2722
2723function detect_encoding($string) {
2724 static $list = array('utf-8', 'windows-1251');
2725
2726 foreach ($list as $item) {
2727
2728 if( function_exists( 'mb_convert_encoding' ) ) {
2729
2730 $sample = mb_convert_encoding( $string, $item, $item );
2731
2732 } elseif( function_exists( 'iconv' ) ) {
2733
2734 $sample = iconv($item, $item, $string);
2735
2736 }
2737
2738 if (md5($sample) == md5($string)) return $item;
2739
2740 }
2741
2742 return null;
2743}
2744
2745function get_ip() {
2746
2747 if ( filter_var( $_SERVER['REMOTE_ADDR'] , FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) ) {
2748 return filter_var( $_SERVER['REMOTE_ADDR'] , FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);
2749 }
2750
2751 if ( filter_var( $_SERVER['REMOTE_ADDR'] , FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) ) {
2752 return filter_var( $_SERVER['REMOTE_ADDR'] , FILTER_VALIDATE_IP, FILTER_FLAG_IPV6);
2753 }
2754
2755 return 'localhost';
2756}
2757
2758function get_votes($all) {
2759
2760 $data = array ();
2761
2762 if( $all != "" ) {
2763 $all = explode( "|", $all );
2764
2765 foreach ( $all as $vote ) {
2766 list ( $answerid, $answervalue ) = explode( ":", $vote );
2767 $data[$answerid] = intval( $answervalue );
2768 }
2769 }
2770
2771 return $data;
2772}
2773
2774function http_get_contents( $file, $post_params = false ) {
2775
2776 $data = false;
2777
2778 if (stripos($file, "http://") !== 0 AND stripos($file, "https://") !== 0) {
2779 return false;
2780 }
2781
2782 if( function_exists( 'curl_init' ) ) {
2783
2784 $ch = curl_init();
2785 curl_setopt( $ch, CURLOPT_URL, $file );
2786
2787 if( is_array($post_params) ) {
2788
2789 curl_setopt($ch, CURLOPT_POST, 1);
2790 curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_params));
2791
2792 }
2793
2794 curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
2795 curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, 5 );
2796 curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false);
2797
2798 $data = curl_exec( $ch );
2799 curl_close( $ch );
2800
2801 if( $data !== false ) return $data;
2802
2803 }
2804
2805 if( preg_match('/1|yes|on|true/i', ini_get('allow_url_fopen')) ) {
2806
2807 if( is_array($post_params) ) {
2808
2809 $file .= '?'.http_build_query($post_params);
2810 }
2811
2812 $data = @file_get_contents( $file );
2813
2814 if( $data !== false ) return $data;
2815
2816 }
2817
2818 return false;
2819}
2820
2821function check_yandex_spam ( $params ) {
2822
2823 $response = http_get_contents('http://cleanweb-api.yandex.ru/1.0/check-spam', $params);
2824
2825 if($response) {
2826 $response = new SimpleXMLElement($response);
2827 if ( $response->text['spam-flag'] == 'yes' ) return true;
2828 }
2829
2830 return false;
2831}
2832
2833function CheckGzip(){
2834
2835 if (headers_sent() || connection_aborted() || !function_exists('ob_gzhandler') || ini_get('zlib.output_compression')) return 0;
2836
2837 if (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'x-gzip') !== false) return "x-gzip";
2838 if (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false) return "gzip";
2839
2840 return 0;
2841}
2842
2843
2844function GzipOut($debug=0){
2845 global $config, $Timer, $db, $tpl, $_DOCUMENT_DATE;
2846
2847 $s = "";
2848
2849 @header("Content-type: text/html; charset=".$config['charset']);
2850
2851 if ($debug) $s = "\n<!-- Ð’Ñ€ÐµÐ¼Ñ Ð²Ñ‹Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ Ñкрипта ".$Timer->get()." Ñекунд -->\n<!-- Ð’Ñ€ÐµÐ¼Ñ Ð·Ð°Ñ‚Ñ€Ð°Ñ‡ÐµÐ½Ð½Ð¾Ðµ на компилÑцию шаблонов ".round($tpl->template_parse_time, 5)." Ñекунд -->\n<!-- Ð’Ñ€ÐµÐ¼Ñ Ð·Ð°Ñ‚Ñ€Ð°Ñ‡ÐµÐ½Ð½Ð¾Ðµ на выполнение MySQL запроÑов: ".round($db->MySQL_time_taken, 5)." Ñекунд -->\n<!-- Общее количеÑтво MySQL запроÑов ".$db->query_num." -->";
2852
2853 if( $debug AND function_exists( "memory_get_peak_usage" ) ) $s .="\n<!-- Затрачено оперативной памÑти ".round(memory_get_peak_usage()/(1024*1024),2)." MB -->";
2854
2855 if($_DOCUMENT_DATE)
2856 {
2857 @header ("Last-Modified: " . date('r', $_DOCUMENT_DATE) ." GMT");
2858
2859 }
2860
2861 if ( !$config['allow_gzip'] ) {if ($debug) echo $s; ob_end_flush(); return;}
2862
2863 $ENCODING = CheckGzip();
2864
2865 if ($ENCODING){
2866 $s .= "\n<!-- Ð”Ð»Ñ Ð²Ñ‹Ð²Ð¾Ð´Ð° иÑпользовалоÑÑŒ Ñжатие $ENCODING -->\n";
2867 $Contents = ob_get_clean();
2868
2869 if ($debug){
2870 $s .= "<!-- Общий размер файла: ".strlen($Contents)." байт ";
2871 $s .= "ПоÑле ÑжатиÑ: ".strlen(gzencode($Contents, 1, FORCE_GZIP))." байт -->";
2872 $Contents .= $s;
2873 }
2874
2875 header("Content-Encoding: $ENCODING");
2876
2877 $Contents = gzencode($Contents, 1, FORCE_GZIP);
2878 echo $Contents;
2879 ob_end_flush();
2880 exit;
2881
2882 }else{
2883
2884 ob_end_flush();
2885 exit;
2886
2887 }
2888}
2889
2890/*
2891 * поиÑк, логирование, замена "плохих" запроÑов
2892 * */
2893function defender_xss($arr, $type){
2894 $clear = array("<!--", "-->");
2895 foreach($arr as $num=>$xss){
2896 $arr[$num] = str_ireplace ($clear, "", $xss);
2897 }
2898
2899 $filter = array("<", ">","=",";","`","\..","/..","UPDATE ", "UNION ALL ", "SELECT ", "CONCAT", "INSERT ", "DELETE ", "ORDER BY ", "WHERE ", "DROP ", "FROM ", "TRUNCATE ","NULL","SLEEP("," AND "," OR ", '.ini', '.zip', '.tar', '.db', "CHAR(", " limit ", "distinct ", "substring ", "information_schema", "table_name ", "Length(", "BENCHMARK(", "WGET", "ROOT", "SYSTEM(", "+dle_", "dle_admin", "md5(", "FLOOR(", "MIN(", '.tables', "waitfor");
2900
2901 $isBad = false;
2902 foreach($arr as $num=>$xss){
2903 foreach ($filter as $f) {
2904 if (mb_stripos($xss, $f) !== false) {
2905 $isBad = true;
2906 }
2907 }
2908 }
2909 if ($isBad) {
2910 $ip = getRealIP();
2911 $text = "------------------------------\n";
2912 $text .= "Дата и времÑ: ".date('Y-m-d H:i:s')." \n";
2913 $text .= "Тип запроÑа: ".$type." \n";
2914 $text .= "IP: ".$ip." \n";
2915 $text .= "Страница: ".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']." \n";
2916 $text .= "Лог запроÑа в виде serialize: ".serialize($arr)."\n";
2917 $text .= "Лог запроÑа в виде json: ".json_encode($arr)."\n";
2918
2919 foreach($arr as $num=>$xss){
2920 $arr[$num] = str_ireplace ($filter, "|", $xss);
2921 }
2922
2923 $text .= "Ð—Ð°Ð¿Ñ€Ð¾Ñ Ð¿Ð¾Ñле Ð¿Ñ€Ð¸Ð¼ÐµÐ½ÐµÐ½Ð¸Ñ Ñ„Ð¸Ð»ÑŒÑ‚Ñ€Ð° в виде serialize: ".serialize($arr)."\n";
2924 $text .= "Ð—Ð°Ð¿Ñ€Ð¾Ñ Ð¿Ð¾Ñле Ð¿Ñ€Ð¸Ð¼ÐµÐ½ÐµÐ½Ð¸Ñ Ñ„Ð¸Ð»ÑŒÑ‚Ñ€Ð° в виде json: ".json_encode($arr)."\n";
2925
2926 file_put_contents($_SERVER['DOCUMENT_ROOT'].'/logs/bad_request_'.date('Y-m-d').'.log', $text, FILE_APPEND|LOCK_EX);
2927 if (!$ip) {
2928 die("Чувак, ÑпаÑибо, что ÑтараешьÑÑ, но Ñ Ñ‚ÐµÐ±Ðµ вÑе равно не заплачу:/");
2929 }
2930 }
2931 return $arr;
2932}
2933
2934//иÑпользуем функцию перед обработкой входÑщих данных:
2935$_POST=defender_xss($_POST, 'POST');
2936$_GET=defender_xss($_GET, 'GET');
2937$_REQUEST=defender_xss($_REQUEST, 'REQUEST');