Конфликтуют между собой несколько кодов
06.06.2014, 13:41. Показов 984. Ответов 2
Здравствуйте, уважаемые обитатели данного форума. Не могу разобраться с проблемой, конфликтуют между собой функции, регистрации/авторизации и система комментариев.
Когда пытаешься отправить комментарий выходит ошибка err5!
Выкладываю коды :
Авторизация/регистрация пользователей:
Кликните здесь для просмотра всего текста
| PHP/HTML | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
| <?php
define('INCLUDE_CHECK',true);
require 'connect.php';
require 'functions.php';
// Данные два файла нужно включать только в случае определения INCLUDE_CHECK
session_name('User');
// Запуск сессии
session_set_cookie_params(2*7*24*60*60);
// Устанавливаем время жизни куки 2 недели
session_start();
if($_SESSION['id'] && !isset($_COOKIE['tzRemember']) && !$_SESSION['rememberMe'])
{
// Если вы вошли в систему, но куки tzRemember (рестарт браузера) отсутствует
// и вы не отметили чекбокс 'Запомнить меня':
$_SESSION = array();
session_destroy();
// Удаляем сессию
}
if(isset($_GET['logoff']))
{
$_SESSION = array();
session_destroy();//уничтожить сессию
header("Location: index.php");//вернуться на главную страницу
exit;
}
if($_POST['submit']=='Войти')
{
// Проверяем, что представлена форма Войти
$err = array();
// Запоминаем ошибки
if(!$_POST['username'] || !$_POST['password'])
$err[] = 'Все поля должны быть заполнены!';
if(!count($err))
{
$_POST['username'] = mysql_real_escape_string($_POST['username']);
$_POST['password'] = mysql_real_escape_string($_POST['password']);
$_POST['rememberMe'] = (int)$_POST['rememberMe'];
// Получаем все введеные данные
$row = mysql_fetch_assoc(mysql_query("SELECT userID,username FROM rche_users WHERE username='{$_POST['username']}' AND password='".md5($_POST['password'])."'"));
if($row['username'])
{
// Если все в порядке - входим в систему
$_SESSION['username']=$row['username'];
$_SESSION['id'] = $row['userID'];
$_SESSION['rememberMe'] = $_POST['rememberMe'];
// Сохраняем некоторые данные сессии
setcookie('tzRemember',$_POST['rememberMe']);
}
else $err[]='Ошибочный пароль или/и имя пользователя!';
}
if($err)
$_SESSION['msg']['login-err'] = implode('<br />',$err);
// Сохраняем сообщение об ошибке сессии
header("Location: index.php");
exit;
}
else if($_POST['submit']=='Зарегистрироваться')
{
// Проверяем, что представлена форма Зарегистрироваться
$err = array();
if(strlen($_POST['username'])<4 || strlen($_POST['username'])>32)
{
$err[]='Имя пользователя должно содержать от 3 до 32 символов!';
}
if(preg_match('/[^a-z0-9\-\_\.]+/i',$_POST['username']))
{
$err[]='Ваше имя пользователя содержит недопустимые символы!';
}
if(!checkEmail($_POST['email']))
{
$err[]='Email не правильный!';
}
if(!count($err))
{
// Если нет ошибок
$pass = substr(md5($_SERVER['REMOTE_ADDR'].microtime().rand(1,100000)),0,6);
// Генерируем случайный пароль
$_POST['email'] = mysql_real_escape_string($_POST['email']);
$_POST['username'] = mysql_real_escape_string($_POST['username']);
// Получаем введеные данные
mysql_query(" INSERT INTO rche_users(username,password,email,regIP,dt)
VALUES(
'".$_POST['username']."',
'".md5($pass)."',
'".$_POST['email']."',
'".$_SERVER['REMOTE_ADDR']."',
NOW()
)");
if(mysql_affected_rows($link)==1)
{
send_mail( 'admin@localhost',
$_POST['email'],
'Регистрация в системе ',
'Ваш пароль: '.$pass);
$_SESSION['msg']['reg-success']='Мы отправили вам письмо с вашим новым паролем!';
}
else $err[]='Данное имя пользователя/e-mail существует в системе!';
}
if(count($err))
{
$_SESSION['msg']['reg-err'] = implode('<br />',$err);
}
header("Location: index.php");
exit;
}
$script = '';
if($_SESSION['msg'])
{
// Скрипт ниже показывает выскальзывающую панель
$script = '
<script type="text/javascript">
$(function(){
$("div#panel").show();
$("#toggle a").toggle();
});
</script>';
}
?>
<!-- Панель -->
<div id="toppanel">
<div id="panel">
<div class="content clearfix">
<div class="left">
<h1>ibook.ru</h1>
<h2>Добро пожаловать на сайт ibook.ru</h2>
Здесь вы можете найти много разных книг на разную тематику, так же есть возможность добавления новых книг, редактирования своих книг.</p>
</div>
<?php
if(!$_SESSION['id']):
?>
<div class="left">
<!-- Форма входа -->
<form class="clearfix" action="" method="post">
<h1>Пожалуйста авторизируйтесь!</h1>
<?php
if($_SESSION['msg']['login-err'])
{
echo '<div class="err">'.$_SESSION['msg']['login-err'].'</div>';
unset($_SESSION['msg']['login-err']);
}
?>
<label class="grey" for="username">Имя пользователя:</label>
<input class="field" type="text" name="username" id="username" value="" size="23" />
<label class="grey" for="password">Пароль который пришел на почту:</label>
<input class="field" type="password" name="password" id="password" size="23" />
<label><input name="rememberMe" id="rememberMe" type="checkbox" checked="checked" value="1" /> Запомнить меня</label>
<div class="clear"></div>
<input type="submit" name="submit" value="Войти" class="bt_login" /><br><a href="recovery_pass.php"> Забыли пароль</a>
<br><br><br><br>
</form>
</div>
<div class="left right">
<!-- Форма регистрации -->
<form action="" method="post">
<h1>Еще не зарегистрировались?</h1>
<?php
if($_SESSION['msg']['reg-err'])
{
echo '<div class="err">'.$_SESSION['msg']['reg-err'].'</div>';
unset($_SESSION['msg']['reg-err']);
}
if($_SESSION['msg']['reg-success'])
{
echo '<div class="success">'.$_SESSION['msg']['reg-success'].'</div>';
unset($_SESSION['msg']['reg-success']);
}
?>
<label class="grey" for="username">Имя пользователя:</label>
<input class="field" type="text" name="username" id="username" value="" size="23" />
<label class="grey" for="email">Email:</label>
<input class="field" type="text" name="email" id="email" size="23" />
<label>Пароль будет отправлен Вам на почту.</label>
<input type="submit" name="submit" value="Зарегистрироваться" class="bt_register" />
</form>
</div>
<?php
else:
?>
<div class="left">
<h1>Для зарегистированных пользователей</h1>
<p>Данные для пользователей</p>
<a href="users/index.php">Мой профиль</a>
<p>- или -</p>
<a href="?logoff">Выйти из системы</a>
</div>
<div class="left right">
</div>
<?php
endif;
?>
</div>
</div>
<!-- Закладка наверху -->
<div class="tab">
<ul class="login">
<li class="left"> </li>
<li>Здравствуйте, <?php echo $_SESSION['username'] ? $_SESSION['username'] : 'Гость';?>!</li>
<li class="sep">|</li>
<li id="toggle">
<a id="open" class="open" href="#"><?php echo $_SESSION['id']?'Открыть панель':'Вход | Регистрация';?></a>
<a id="close" style="display: none;" class="close" href="#">Закрыть панель</a>
</li>
<li class="right"> </li>
</ul>
</div>
</div>
<br><br> |
|
Система комментариев:
Кликните здесь для просмотра всего текста
| PHP/HTML | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
| <?php
define( '_RCHE', 1 );
$AdminPass = '12345';
// Настройки БД
$settings = array(
'dbName' => 'ibook',
'dbUser' => 'admin',
'dbPass' => '123654',
'dbHost' => 'localhost'
);
// Пути
$paths['capcha'] = 'capcha.php'; // вариант: /comments/capcha.php
error_reporting(E_ERROR | E_WARNING | E_PARSE);
require_once('class.registry.php');
require_once('class.dbsql.php');
require_once('class.controller.php');
require_once('class.comments.php');
require_once('functions.php');
require_once('markhtml.php');
session_start();
$DB=new DB_Engine('mysql', $settings['dbHost'], $settings['dbUser'], $settings['dbPass'], $settings['dbName']);
$registry = new Registry;
$registry->set('DB',$DB);
$comments = new Comments($registry);
$comments->admin=@($_GET['pass']==$AdminPass)?true:false;
$comments->login=false; // true - пользователь залогинен, передаем массив с данными пользователя ниже, false - не залогинен
/* массив с данными пользователя
`userID` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(50) NOT NULL DEFAULT '',
`email` varchar(150) NOT NULL DEFAULT '',
`photo` varchar(255) NOT NULL, -- путь к аватарке --
*/
$comments->user=array(); // массив с данными пользователя
$comments->gravatar=true;
$comments->paths=$paths;
$comments->capcha=true;
$comments->index(); |
|
Кликните здесь для просмотра всего текста
| PHP/HTML | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
| <?php
defined('_RCHE') or die('Доступ закрыт');
class Registry implements ArrayAccess{
private $vars = array();
function set($key, $var) {
if (isset($this->vars[$key]) == true) {
throw new Exception('Unable to set var `' . $key . '`. Already set.');
}
$this->vars[$key] = $var;
return true;
}
function get($key) {
if (isset($this->vars[$key]) == false) {
return null;
}
return $this->vars[$key];
}
function remove($var) {
unset($this->vars[$key]);
}
function offsetExists($offset) {
return isset($this->vars[$offset]);
}
function offsetGet($offset) {
return $this->get($offset);
}
function offsetSet($offset, $value) {
$this->set($offset, $value);
}
function offsetUnset($offset) {
unset($this->vars[$offset]);
}
} |
|
Кликните здесь для просмотра всего текста
| PHP | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
| <?php
class DB_Engine {
var $config_params=array();
/**
* Заполняется всеми выполненными запросами в течение генерации страницы.
* <code>
* Формат:
* array (
* [0] => array( [operation] => getRow,
* [file] => /home/user/some.php,
* [line] => 222,
* [query] => SELECT * FROM table,
* [time] => 0.0235,
* [result] => array
* )
* [1] => ...
* )
* </code>
* @access public
* @var array
*/
var $sqls= array ();
var $show_err= TRUE;
/**
* Время выполения последнего запроса.
* @var float
* @access public
*/
var $time_query= 0;
/**
* ID элемента, полученный в результате выполнения последней команды INSERT
* в таблицу с autoincrement'ным полем.
* @var integer
* @access public
*/
var $id= 0;
/**
* Кол-во строк вернувшееся запросом
*
* @var integer
*/
var $num_rows=0;
/**
* Суммарное время выполнения всех запросов, со времени начала генерации страницы.
* @var float
* @access public
*/
var $AllTimeQueries= 0;
/**
* Конструктор класса.
* @param string $type Тип BD (в настоящее время только mysql)
* @param string $server Host сервера (напр., localhost)
* @param string $user Имя пользователя (напр., root)
* @param string $pass Пароль пользователя (может быть пустым)
* @param string $dbname Имя базы данных (напр., invictum )
* @exception Если неизвестный тип BD, то выдает ошибку
* @return void
*/
function DB_Engine($type, $server, $user, $pass, $dbname) {
//$this->assoc = 'ASC';
$this->type= $type; //mysql
switch ($this->type) {
case 'mysql' :
$this->config_params = array('host'=>$server,'user'=>$user,'pass'=>$pass,'dbname'=>$dbname);
$this->connectMySQL($server, $user, $pass, $dbname);
break;
default :
die('Unknow DB: Change type of DB!');
break;
}
/** Файл, с которого вызван текущий запрос */
$this->file= null;
/** Строка, с которой вызван текущий запрос */
$this->line= null;
/** Текущий запрос */
$this->sql= null;
/** Текущая операция */
$this->oprt= null;
/** Выводить ли ошибку, если текущий запрос ошибочен */
$this->showerr= true;
}
/**
* Присоединение к MySQL-серверу.
* @access private
* @param string $server Host сервера (напр., localhost)
* @param string $user Имя пользователя (напр., root)
* @param string $pass Пароль пользователя (может быть пустым)
* @param string $dbname Имя базы данных (напр., invictum )
* @exception При невозможности присоединения выдает ошибку
* @return void
*/
function connectMySQL($server, $user, $pass, $dbname) {
$this->link_id= mysql_connect($server, $user, $pass);
if ($this->link_id === false)
die('Can\'t connect to DB. Server. '.$server.', user: '.$user);
if (!mysql_select_db($dbname, $this->link_id))
die('Can\'t select DB '.$dbname.' ');
mysql_query('SET NAMES utf8', $this->link_id);
}
/**
* Распределяет выполнение запроса на необходимый тип БД
* Заполняет $this->{@link sqls}, $this->{@link time_query},
* $this->{@link AllTimeQueries}, $this->{@link id},
* и, при необходимости, логирует запросы.
* Если затребовано, то при некорректном запросе генерирует критическую ошибку.
* @access private
* @param TYPE $variable Распределяет выполнение запроса на необходимый тип БД
* @return mixed
*/
function operation($log=true) {
if ($this->sql === null)
return;
$this->sql= (string) @ trim($this->sql);
$this->time_query= $this->_mctime();
switch ($this->type) {
case 'mysql' :
$result= $this->MySql($log);
break;
default :
$result= false;
break;
}
if ($result !== false) {
$this->time_query= round($this->_mctime() - $this->time_query, 4);
$this->AllTimeQueries += $this->time_query;
$cur= & $this->sqls[];
$cur['operation']= $this->oprt;
$cur['file']= $this->file;
$cur['line']= $this->line;
$cur['query']= $this->sql;
$cur['time']= $this->time_query;
$cur['result']= sizeof($result);
$this->id= mysql_insert_id();
unset ($cur);
$this->_clear();
return $result;
}
if ($this->showerr and $this->show_err) {
if (preg_match('#^[^\']*? \'(.*?)\' in#',mysql_error(),$filter=null))
$this->sql = str_replace($filter[1], '<b>'.$filter[1].'</b>', $this->sql);
$str= '<B>Ошибка DB:</B> <BR><BR>'.mysql_error().' <BR><BR> '.$this->sql.'';
if (function_exists('critical_error'))
critical_error($str, $this->file, $this->line);
else
die($str);
}
return false;
}
/**
* Выполнение запроса на MySQL сервере.
* @access private
* @return mixed Результат запроса
*/
function MySql($log=true) {
if ($this->sql === null)
return;
$query= mysql_query($this->sql, $this->link_id);
if ($query === false)
return false;
switch ($this->oprt) {
case 'getOne' :
$this->num_rows = mysql_numrows($query);
$result= mysql_fetch_assoc($query);
if ($result === false)
$result= array ();
$result= (sizeof($result) != 0) ? current($result) : '';
break;
case 'getRow' :
$this->num_rows = mysql_numrows($query);
$result= mysql_fetch_assoc($query);
if ($result === false)
$result= array ();
break;
case 'getAll' :
$this->num_rows = mysql_numrows($query);
$result= array ();
while ($row= mysql_fetch_assoc($query))
$result[]= $row;
break;
case 'getCol' :
$this->num_rows = mysql_numrows($query);
$result= array ();
while ($row= mysql_fetch_assoc($query))
$result[]= current($row);
break;
case 'execute' :
/* if ($log)
saveLogAction($this->sql);*/
return true;
}
return $result;
}
/**
* Подготовить переменную к вносу в БД (квотирование и слеширование).
* @access public
* @param string $string Var
* @return string slashedVar
*/
function prepare($string_var) {
$string_var= trim($string_var);
return mysql_real_escape_string($string_var);
}
/**
* Alias функции {@link $DB->prepare()}
* @access public
* @return string slashedVar
*/
function pre($string_var) {
return $this->prepare($string_var);
}
/**
* Возвращает предыдущий выполненный запрос.
* Или указаную инфрмацию по предыдущему запросу.
* @access public
* @param operation|file|line|query|time|result $string Допустимые поля
* @return string
*/
function LastQuery($field= 'query') {
$last= end($this->sqls);
return $last[$field];
}
/**
* Проверяет существует ли таблица.
* @access public
* @param string $table Имя таблицы
* @param boolean $ShowError Генерировать ошибку при неверном запросе
* @return boolean
*/
function TableExists($table, $ShowError= true) {
return (boolean) sizeof((array) $this->operation('getAll', "SHOW TABLE STATUS LIKE '".$this->pre($table)."'", $ShowError));
}
/**
* Выбрать только одно значение.
* <code> getOne("SELECT `a`,`b` FROM `table`") :
* string(5) var_a </code>
* @access public
* @param string $sql SQL-запрос
* @param boolean $ShowError Генерировать ошибку при неверном запросе
* @return mixed
*/
function getOne($sql, $ShowError= true) {
// list ($this->file, $this->line)= LastFileLine(1);
$this->sql= $sql;
$this->oprt= 'getOne';
$this->showerr= (bool) $ShowError;
return $this->operation();
}
/**
* Выбрать строку.
* <code> getRow("SELECT `a`,`b` FROM `table`") :
* array( 'a' => 'var_a', 'b' => 'var_b' ) </code>
* @access public
* @param string $sql SQL-запрос
* @param boolean $ShowError Генерировать ошибку при неверном запросе
* @return mixed
*/
function getRow($sql, $ShowError= true) {
// list ($this->file, $this->line)= LastFileLine(1);
$this->sql= $sql;
$this->oprt= 'getRow';
$this->showerr= (bool) $ShowError;
return $this->operation();
}
/**
* Выбрать столбец.
* <code> getCol("SELECT `a`,`b` FROM `table`") :
* array( 0 => 'var_a1', 1 => 'var_a2' ) </code>
* @access public
* @param string $sql SQL-запрос
* @param boolean $ShowError Генерировать ошибку при неверном запросе
* @return mixed
*/
function getCol($sql, $ShowError= true) {
// list ($this->file, $this->line)= LastFileLine(1);
$this->sql= $sql;
$this->oprt= 'getCol';
$this->showerr= (bool) $ShowError;
return $this->operation();
}
/**
* Выбрать ассоциированный массив.
* <code> getAll("SELECT `a`,`b` FROM `table`") :
* array( 0 => array('a'=>'var_a1', 'b'=>'var_b1'),
* 1 => array('a'=>'var_a2', 'b'=>'var_b2'), ) </code>
* @access public
* @param string $sql SQL-запрос
* @param boolean $ShowError Генерировать ошибку при неверном запросе
* @return mixed
*/
function getAll($sql, $ShowError= true) {
// list ($this->file, $this->line)= LastFileLine(1);
$this->sql= $sql;
$this->oprt= 'getAll';
$this->showerr= (bool) $ShowError;
return $this->operation();
}
/**
* Выполнить запрос.
* <code>execute("DELETE FROM `table` `a`") : true</code>
* @access public
* @param string $sql SQL-запрос
* @param boolean $ShowError Генерировать ошибку при неверном запросе
* @return boolean Результат операции
*/
function execute($sql, $ShowError= true, $log = true) {
// list ($this->file, $this->line)= LastFileLine(1);
$this->sql= $sql;
$this->oprt= 'execute';
$this->showerr= (bool) $ShowError;
return $this->operation($log);
}
/**
* Возвращает следующий номер автоинкрементного id в указанной таблице
* @access public
* @param string $tablename Имя таблицы (напр., ".PRFX."files)
* @return integer
*/
function nextID($tablename) {
// list ($this->file, $this->line)= LastFileLine(1);
$this->sql= "SHOW TABLE STATUS LIKE '".$tablename."'";
$this->oprt= 'getRow';
$this->showerr= true;
$infotable= $this->operation();
return (integer) @ $infotable['Auto_increment'];
}
/**
* Возвращает значение временных переменных в исходное состояние
* @access private
* @return void
*/
function _clear() {
$this->file= null;
$this->line= null;
$this->sql= null;
$this->oprt= null;
$this->showerr= true;
}
/**
* Возвращает текущее число секунд и микросекунд.
* @access private
* @return float
*/
function _mctime() {
list ($sec, $msec)= explode(' ', microtime());
return $sec + $msec;
}
function dump_db($path, $table='', $filename='')
{
$database = $this->config_params['dbname'];
$tables=array();
if ($table=="")
{
$tables = $this->getAll('SHOW TABLES '.($table!="" ? 'FROM `'.$database.'`' : ''));
$filename = $filename=="" ? $database : $filename;
}
else
$tables[0]['Tables_in_'.$database]=$table;
$file_name = $path.$filename.".sql";
if ($table!="")
{
$present=false;
$tmp = $this->getAll('SHOW TABLES');
foreach ($tmp as $num => $tab_tmp)
{
if ($tab_tmp['Tables_in_'.$database]==$table)
{
$present=true;
break;
}
}
if (!$present) return;
}
$data='';
foreach($tables as $num => $tabelle)
{
$tabelle = $tabelle['Tables_in_'.$database];
echo $tabelle;
$def = "";
$def .= "DROP TABLE IF EXISTS `$tabelle`;\n";
$def .= "CREATE TABLE `$tabelle` (";
$result3 = $this->getAll("SHOW FIELDS FROM `".$tabelle."`");
foreach($result3 as $num => $row)
{
$def .= "`$row[Field]` $row[Type]";
if ($row["Default"] != "") $def .= " DEFAULT '$row[Default]'";
if ($row["Null"] != "YES") $def .= " NOT NULL";
if ($row['Extra'] != "") $def .= " $row[Extra]";
$def .= ",";
}
$def = ereg_replace(",$","", $def);
$result3 = $this->getAll("SHOW KEYS FROM `".$tabelle."`");
foreach($result3 as $num => $row)
{
$kname=$row['Key_name'];
if(($kname != "PRIMARY") && ($row['Non_unique'] == 0)) $kname="UNIQUE|$kname";
if(!isset($index[$kname])) $index[$kname] = array();
$index[$kname][] = $row['Column_name'];
}
while(list($xy, $columns) = @each($index))
{
$def .= ",";
if($xy == "PRIMARY") $def .= " PRIMARY KEY (" . implode($columns, ", ") . ")";
else if (substr($xy,0,6) == "UNIQUE") $def .= " UNIQUE ".substr($xy,7)." (" . implode($columns, ", ") . ")";
else $def .= " KEY $xy (" . implode($columns, ", ") . ")";
}
$def .= ");\n";
$fd = fopen($file_name,"a+");
fwrite($fd, $def);
fclose($fd);
$data='';
$ergebnis=array();
if ($tabelle>"")
{
$ergebnis[]=1;
$result=mysql_query("SELECT * FROM `".$tabelle."`", $this->link_id);
$anzahl= mysql_num_rows($result);
$spaltenzahl = mysql_num_fields($result);
for ($i=0;$i<$anzahl;$i++)
{
$zeile=mysql_fetch_array($result);
$data.="INSERT INTO `$tabelle` (";
for ($spalte = 0; $spalte < $spaltenzahl;$spalte++)
{
$feldname = mysql_field_name($result, $spalte);
if($spalte == ($spaltenzahl - 1))
{
$data.= '`'.$feldname.'`';
}
else
{
$data.= '`'.$feldname."`, ";
}
};
$data.=") VALUES (";
for ($k=0;$k < $spaltenzahl;$k++)
{
$data_val = mysql_escape_string($zeile[$k]);
$data_val = str_replace("\r\n", '\r\n',$data_val);
$data_val = str_replace("\r", '\r',$data_val);
$data_val = str_replace("\n", '\n',$data_val);
if($k == ($spaltenzahl - 1))
{
$data.="'".$data_val."'";
}
else
{
$data.="'".$data_val."',";
}
}
$data.= ");\n";
}
$data.= "\n";
}
else
{
$ergebnis[]= $err;
}
$fd = fopen($file_name,"a+");
for ($i3=0;$i3<count($ergebnis);$i3++)
{
fwrite($fd, $data);
fclose($fd);
}
}
}
function importModuleTable($table, $module_name)
{
global $CONFIG;
$dir = $_SERVER['DOCUMENT_ROOT'].'/MODULES/'.$module_name.'/sqls';
$file = $dir.'/'.$table.'.sql';
if (is_file($file))
{
$sqls = file($file);
foreach($sqls as $line)
{
$line=trim($line);
if ($line=="") continue;
$this->execute($line);
}
unset($sqls);
return true;
}
else
return false;
}
} |
|
Кликните здесь для просмотра всего текста
| PHP | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
| <?php
defined('_RCHE') or die('Restricted access');
abstract class Controller_Base {
protected $registry;
final function __construct($registry) {
$this->registry = $registry;
}
function getDate ($arg='d m Y H i') {
$line=explode(' ',$arg);
$date=array();
foreach($line as $l):
$date[$l]=date($l);
endforeach;
return $date;
}
abstract function index();
}
?> |
|
Кликните здесь для просмотра всего текста
| PHP | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
| <?php
class Comments extends Controller_Base {
var $path = ''; // path to page on comments
var $table = 'comments'; // table comments
var $prefix = 'rche_'; // prefix table comments
var $event = '';
var $key = 'e34d9147f42016a32a9bab982492323547e121ce'; // sicret key for ajax
var $login = false; // login user or email and name
var $user = array(); // user info if login
var $admin = false; // admin option
var $gravatar = false; // avatar from gravatar.com
var $capcha = true; // enable Capcha
var $paths = array(); // path's
function index () {
$this->event=@$_POST['eventComments'];
if(@$_GET['eventComments']=='del' and @$_GET['noajax']==1)$this->event=@$_GET['eventComments'];
if($this->event=='save') $status=$this->saveComments();
if($this->event=='del') $status=$this->delComments();
if($this->event=='edit') $status=$this->editComments();
if($this->event=='reply') $status=$this->replyComments();
if($this->event=='')$status=NULL;
return $status;
}
function delComments() {
$id = intval($_POST['id']);
$passport =$_POST['passport'];
if($_GET['noajax']==1)
{
$id = intval($_GET['id']);
$passport =$_GET['passport'];
}
if($passport==md5($this->key.'admin'))
{
$sql="SELECT {$this->prefix}{$this->table}.id, {$this->prefix}{$this->table}.reply FROM {$this->prefix}{$this->table}
WHERE {$this->prefix}{$this->table}.url='".$this->getUrl()."' ORDER BY {$this->prefix}{$this->table}.id ASC";
$allComm=$this->registry['DB']->getAll($sql);
if(count($allComm)>0):
// subcomments
foreach($allComm as $item):
if($item['reply']==0)$sortcomm[$item['id']]=$item;
if($item['reply']>0)
{
if(isset($path[$item['reply']]))
{
$str='$sortcomm';
foreach($path[$item['reply']] as $pitem):
$rep=$item['reply'];
$str.="[$pitem][sub]";
endforeach;
$str.="[{$item['reply']}][sub]";
$str.="[{$item['id']}]";
$str.='=$item;';
eval($str);
foreach($path[$item['reply']] as $pitem):
$path[$item['id']][]=$pitem;
endforeach;
$path[$item['id']][]=$item['reply'];
}
else
{
$sortcomm[$item['reply']]['sub'][$item['id']]=$item;
$path[$item['id']][]=$item['reply'];
}
}
endforeach;
endif;
$this->tree_delComment($sortcomm,$id);
if($_GET['noajax']==1):
$url=explode('?',$_SERVER['REQUEST_URI']);
header('Location: http://'.$_SERVER['HTTP_HOST'].$url[0]);
else: echo 'OK'; endif;
}
if(empty($_GET['noajax']))exit;
}
function tree_delComment(&$a_tree,&$id=0) {
if(count($a_tree)>0)
foreach($a_tree as $sub)
{
if($sub['id']<>$id and isset($sub['sub']))$this->tree_delComment($sub['sub'],$id);
if($sub['id']==$id)
{
$sql="DELETE FROM {$this->prefix}{$this->table} WHERE id = '$id' LIMIT 1";
$this->registry['DB']->execute($sql);
if (isset($sub['sub'])) $this->tree_delComment_process($sub['sub']);
}
}
}
function tree_delComment_process(&$a_tree) {
foreach($a_tree as $sub)
{
$sql="DELETE FROM {$this->prefix}{$this->table} WHERE id = '{$sub['id']}' LIMIT 1";
$this->registry['DB']->execute($sql);
if(isset($sub['sub']))$this->tree_delComment_process($sub['sub']);
}
}
function replyComments() {
$replyid = intval($_POST['replyid']);
$pass_checked=md5($this->user['password'].$this->key);
$post_url = htmlspecialchars(trim($_POST['posturlComment']));
if(strlen($post_url)>50 or strlen($post_url)<10) return;
$url = $post_url;
$urlOpen=$this->getUrl(false, 'open');
if($this->capcha)
{
$capcha ='
<br/>Введите код с картинки: <input type="text" name="capcha" id="Rcapcha" value="" class="inputComment"/><br/>
<img src="'.$this->paths['capcha'].'" alt="картинка" width="120" height="50"/>
<br/>';
}
$form = '
<form action="" method="post" id="RformComment">
Имя: <input name="nameComment" id="nameComment" value="" type="text" class="inputComment">
<input name="nameCommentCap" id="RnameCommentCap" value="" type="text">
Эл. почта: <input name="emailComment" id="emailComment" value="" type="text" class="inputComment">
<input name="replyComment" id="RreplyComment" value="'.$replyid.'" type="hidden">
<input name="loginComment" id="RloginComment" value="'.intval($this->login).'" type="hidden">
<input name="posturlComment" id="RposturlComment" value="'.$url.'" type="hidden">
<input name="personaComment" id="RpersonaComment" value="'.$this->user['userID'].'" type="hidden">
<input name="checkedComment" id="RcheckedComment" value="'.$pass_checked.'" type="hidden">
<input name="posturlOpenComment" id="RposturlOpenComment" value="'.$urlOpen.'" type="hidden">
<input name="eventComments" id="ReventComment" value="save" type="hidden">
<input name="noAjax" value="1" type="hidden">
<textarea name="textComment" id="RtextComment" class="textareaComment tinymce"></textarea>
'.$capcha.'
<input value="Комментировать" name="submit" type="submit" class="submitComment"/>
</form>';
echo $form;
exit;
}
function itemComments($username,$date,$text,$img,$id,$autor=false, $userid='') {
$possport=md5($this->key.'admin');
// if($this->login)
$reply='<a href="javascript://" rel="'.$id.'" class="replyComment" title="Ответить на комментарий: '.$username.'">Ответить</a>';
// if($autor or $this->admin)$edit=' | <a href="javascript://" rel="'.$id.'" class="editComment" title="Редактировать комметарий">Редактировать</a>';
if($this->admin) $del=' | <a href="?id='.$id.'&passport='.$possport.'&noajax=1&eventComments=del" onclick="return false" rel="'.$id.'" passport="'.$possport.'" class="delComment" title="Удалить комментарий">Удалить</a>';
if($userid>0)$uslink="/com/profile/default/$userid/";else $uslink='#itemComment-'.$id;
$out='<div class="itemComment" id="itemComment-'.$id.'">
<div class="avatarComment">
<a href="'.$uslink.'" title="Смотреть профиль пользователя: '.$username.'">
<img src="'.$img.'" width="48" height="48" border="0" alt="Аватар пользователя: '.$username.'"/></a>
</div>
<div class="panelComment">
<a class="userComment" href="'.$uslink.'" title="Смотреть профиль пользователя: '.$username.'">'.$username.'</a>
<span class="dateComment" title="Дата, время комментария">'.$date.'</span>
</div>
<div class="bodyComment">
'.$text.'
</div>
<div class="footerComment">
'.$reply.$edit.$del.'
</div>
';
return $out;
}
function outComments() {
echo '<div id="rcheComments">
<h3 class="titleComment">Комментарии</h3>
<div id="allComment">';
$sql="SELECT {$this->prefix}{$this->table}.*, rche_users.photo, rche_users.username, rche_users.userID FROM {$this->prefix}{$this->table}
LEFT JOIN rche_users ON {$this->prefix}{$this->table}.user =rche_users.userID
WHERE {$this->prefix}{$this->table} .url='".$this->getUrl()."' ORDER BY {$this->prefix}{$this->table}.id ASC";
$allComm=$this->registry['DB']->getAll($sql);
if(count($allComm)>0):
// subcomments
foreach($allComm as $item):
if($item['reply']==0)$sortcomm[$item['id']]=$item;
if($item['reply']>0)
{
if(isset($path[$item['reply']]))
{
$str='$sortcomm';
foreach($path[$item['reply']] as $pitem):
$rep=$item['reply'];
$str.="[$pitem][sub]";
endforeach;
$str.="[{$item['reply']}][sub]";
$str.="[{$item['id']}]";
$str.='=$item;';
eval($str);
foreach($path[$item['reply']] as $pitem):
$path[$item['id']][]=$pitem;
endforeach;
$path[$item['id']][]=$item['reply'];
}
else
{
$sortcomm[$item['reply']]['sub'][$item['id']]=$item;
$path[$item['id']][]=$item['reply'];
}
}
endforeach;
$this->tree_print($sortcomm);
else: echo '<p>Комментариев нет</p>'; endif;
echo '</div>
<div id="messComment"></div>
<div id="ajaxComment"></div>';
echo $this->pageComment();
echo $this->formComment();
}
function tree_print(&$a_tree) {
foreach($a_tree as $sub)
{
$this->outItem($sub);
if(!empty($sub['sub']))$this->tree_print($sub['sub']);
echo "</div>";
}
}
function outItem($item) {
$autor=false;
if(intval($item['user'])==0)
{
if($this->gravatar)
{
$lowercase = strtolower($item['email']);
$image = md5( $lowercase );
$img="http://www.gravatar.com/avatar.php?gravatar_id=$image";
} else $img='images/boy48.gif';
}
else
{
$img=$item['photo'];
$im=explode('/',$img);
$img='/images/'.$item['user'].'/48/48/1/'.$im['4'];
$item['name']=$item['username'];
}
if($item['pass']==$_COOKIE['comment'.$item['id']] and !empty($item['pass']) and ($item['date']+120)>time()) $autor=true;
echo $this->itemComments(
$item['name'],
$this->get_Date($item['date']),
html_entity_decode($item['comment']),
$img,
$item['id'],
$autor,
$item['userID']);
}
function saveComments() {
$name = trim(strip_tags($_POST['nameComment']));
$email = trim($_POST['emailComment']);
$text = PHP_slashes(htmlspecialchars(markhtml(trim(rawurldecode($_POST['textComment'])))));
$post_url = htmlspecialchars(trim($_POST['posturlComment']));
$urlOpen = htmlspecialchars(trim($_POST['posturlOpenComment']));
$error = false;
$login = intval($_POST['loginComment']);
$replyComment = intval($_POST['replyComment']);
$cap=$_POST['nameCommentCap'];
if($this->capcha) {
if($_SESSION['captha_text']!=$_POST['capcha']) {
echo 'ERR5';
exit;
}
}
if($login==1)
{
$persona= intval($_POST['personaComment']);
$checked= htmlspecialchars(trim($_POST['checkedComment']));
if($persona>0 and $checked>'')
{
$sql="SELECT rche_users.* FROM rche_users
WHERE rche_users.userID='$persona' LIMIT 1";
$user=$this->registry['DB']->getAll($sql);
if(md5($user[0]['password'].$this->key)==$checked)
{
$this->login=true;
$this->user=$user[0];
}
}
else
{
echo 'ERR4';
exit;
}
}
if(!$this->login)
{
if(strlen($name)<3) {$error=true;$msg=1;}
if(!$this->emailCheck($email) or strlen($name)>100){$error=true;$msg=2;}
$img='images/boy48.gif';
}
else
{
$img=$this->user['photo'];
$im=explode('/',$img);
$img='/images/'.$this->user['userID'].'/48/48/1/'.$im['4'];
$name=$this->user['username'];
$user=$this->user['userid'];
}
if(strlen($text)==0){$error=true;$msg=3;}
if(strlen($post_url)>50 or strlen($post_url)<10){$error=true;$msg=4;}
if($error)
{
echo 'ERR'.$msg;
exit;
}
$pass=$this->generate_password(8);
$date=$this->get_Date();
$time=time();
if($cap=='') {
$sql="INSERT INTO {$this->prefix}{$this->table} (`reply`,`user`,`name`,`email`,`comment`,`date`,`url`,`pass`,`urlOpen`)
VALUE ('$replyComment','{$this->user['userID']}','$name','$email','$text','$time','$post_url','$pass','$urlOpen')";
$this->registry['DB']->execute($sql);
}
$lastId=$this->registry['DB']->id;
setcookie('comment'.$lastId,$pass,$time+120,'/');
if(intval($_POST['noAjax'])<>1):
echo $this->itemComments(
$name,
$date,
html_entity_decode($text),
$img,
$lastId,
true,
$user);
exit;
endif;
}
function formComment($replyid=0)
{
global $user;
if($this->login)
{
$pass_checked=md5($this->user['password'].$this->key);
}
else
{
$name='
<tr><td class="section-one">Имя</td><td>
<input name="nameComment" id="nameComment" value="" type="text" class="inputComment">
<input name="nameCommentCap" id="nameCommentCap" value="" type="text" class="nameCommentCap">
</td></tr>
<tr><td class="section-one">Эл. почта</td><td><input name="emailComment" id="emailComment" value="" type="text" class="inputComment"></td></tr>';
}
$url=$this->getUrl();
$urlOpen=$this->getUrl(false, 'open');
if($this->capcha)
{
$capcha ='
<tr><td class="section-one">Введите код с картинки:<br/><img src="'.$this->paths['capcha'].'" alt="картинка" width="120" height="50"/></td><td>
<input type="text" name="capcha" id="capcha" value="" class="inputComment"/></td></tr>';
}
$form = '<h3 id="newComment">Оставить свой комментарий </h3>
<form action="" method="post" id="formComment">
<input name="addComment" id="addComment" value="1" type="hidden">
<input name="loginComment" id="loginComment" value="'.intval($this->login).'" type="hidden">
<input name="posturlComment" id="posturlComment" value="'.$url.'" type="hidden">
<input name="posturlOpenComment" id="posturlOpenComment" value="'.$urlOpen.'" type="hidden">
<input name="personaComment" id="personaComment" value="'.@$this->user['userID'].'" type="hidden">
<input name="checkedComment" id="checkedComment" value="'.@$pass_checked.'" type="hidden">
<input name="eventComments" id="eventComment" value="save" type="hidden">
<input name="noAjax" value="1" type="hidden">
<table id="tableComment">
'.$name.'
<tr><td class="section-one">Текст комментария</td><td><textarea name="textComment" id="textComment" class="textareaComment tinymce"></textarea></td></tr>
'.$capcha.'
</table>
<input value="Комментировать" name="submit" type="submit" class="submitComment"/>
</form>';
$form.='</div><p><a href="http://rche.ru" style="font:11px tahoma;color:#999;text-decoration:none">© www.rche.ru</a></p>';
return $form;
}
function pageComment() {
//return $out;
}
function getUrl($explode=false, $open = '') {
$url=$_SERVER["REQUEST_URI"];
if($this->admin==true) {
$u=explode('?',$url);
$e=explode('&',$u[1]);
$i=0;
foreach($e as $item)
{
$i++;
$data=explode('=',$item);
if($data[0]=='pass') continue;
$newQuery.=$item;
if($i<count($e))$newQuery.='&';
$newQuery='?'.$newQuery;
if(substr($newQuery, -1)=='&')$newQuery=substr($newQuery, 0, strlen($newQuery)-1);
}
$url="{$u[0]}{$newQuery}";
}
if($explode)
{
$url=explode('?',$_SERVER['REQUEST_URI']);
$url=$url[0];
}
if($open=='open')return urlencode($url);
return md5($url);
}
function emailCheck($email) {
if (!preg_match("/^(?:[a-z0-9]+(?:[-_.]?[a-z0-9]+)?@[a-z0-9_.-]+(?:\.?[a-z0-9]+)?\.[a-z]{2,5})$/i",trim($email)))
{
return false;
}
else return true;
}
function get_Date($shtamp='') {
if($shtamp=='')$shtamp=time();
$MonthNames=array("Января", "Февраля", "Марта", "Апреля", "Мая", "Июня", "Июля", "Августа", "Сентября", "Октября", "Ноября", "Декабря");
$date = date('d',$shtamp).' '.$MonthNames[date('n',$shtamp)-1].' '.date('Y',$shtamp).'г, '.date('H',$shtamp).'ч '.date('i',$shtamp).'мин';
return $date;
}
function generate_password($number)
{
$arr = array('a','b','c','d','e','f',
'g','h','i','j','k','l',
'm','n','o','p','r','s',
't','u','v','x','y','z',
'A','B','C','D','E','F',
'G','H','I','J','K','L',
'M','N','O','P','R','S',
'T','U','V','X','Y','Z',
'1','2','3','4','5','6',
'7','8','9','0'); /*,'.',',',
'(',')','[',']','!','?',
'&','^','%','@','*','$',
'<','>','/','|','+','-',
'{','}','`','~');*/
$pass = "";
for($i = 0; $i < $number; $i++)
{
$index = rand(0, count($arr) - 1);
$pass .= $arr[$index];
}
return $pass;
}
} |
|
Кликните здесь для просмотра всего текста
| PHP | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
| <?php
/*if(!defined('INCLUDE_CHECK')) die('У вас нет прав запускать файл на выполнение');*/
function checkEmail($str)
{
return preg_match("/^[\.A-z0-9_\-\+]+[@][A-z0-9_\-]+([.][A-z0-9_\-]+)+[A-z]{1,4}$/", $str);
}
function send_mail($from,$to,$subject,$body)
{
$charset = 'utf-8';
mb_language("ru");
$headers = "MIME-Version: 1.0 \n" ;
$headers .= "From: <".$from."> \n";
$headers .= "Reply-To: <".$from."> \n";
$headers .= "Content-Type: text/html; charset=$charset \n";
$body = mb_convert_encoding($body, $charset,"auto");
$subject = mb_convert_encoding($subject, $charset, "auto");
$subject = '=?'.$charset.'?B?'.base64_encode($subject).'?=';
mail($to,$subject,$body,$headers);
}
function add_pr ($str,$count)
{
// $st=preg_replace("/([.,;-])/","\${".$count."}?",$str);
$str=iconv('UTF-8','WINDOWS-1251',$str);
$i = 0;$no_pr = 0;$j = 1;
while ($i < strlen($str))
{
$text[$j] = $text[$j].$str[$i];
if ($str[$i] == ' '){$no_pr = 0;$j = $j+1;}
if ($str[$i] != ' '){$no_pr = $no_pr+1;}
if ($no_pr == $count){$text[$j] = $text[$j].' ';$no_pr = 0;}
$i = $i+1;
}
while ($j != 0){$st = $st.$text[$j];$j = $j-1;}
$st=iconv('WINDOWS-1251','UTF-8',$st);
return $st;
}
function PHP_slashes($string,$type='add')
{
if ($type == 'add')
{
if (get_magic_quotes_gpc())
{
return $string;
}
else
{
if (function_exists('addslashes'))
{
return addslashes($string);
}
else
{
return mysql_real_escape_string($string);
}
}
}
else if ($type == 'strip')
{
return stripslashes($string);
}
else
{
die('error in PHP_slashes (mixed,add | strip)');
}
}
if(!function_exists('utf8_strlen'))
{
function utf8_strlen($s)
{
return preg_match_all('/./u', $s, $tmp);
}
}
if(!function_exists('utf8_substr'))
{
function utf8_substr($s, $offset, $len = 'all')
{
if ($offset<0) $offset = utf8_strlen($s) + $offset;
if ($len!='all')
{
if ($len<0) $len = utf8_strlen2($s) - $offset + $len;
$xlen = utf8_strlen($s) - $offset;
$len = ($len>$xlen) ? $xlen : $len;
preg_match('/^.{' . $offset . '}(.{0,'.$len.'})/us', $s, $tmp);
}
else
{
preg_match('/^.{' . $offset . '}(.*)/us', $s, $tmp);
}
return (isset($tmp[1])) ? $tmp[1] : false;
}
}
if(!function_exists('utf8_strpos'))
{
function utf8_strpos($str, $needle, $offset = null)
{
if (is_null($offset))
{
return mb_strpos($str, $needle);
}
else
{
return mb_strpos($str, $needle, $offset);
}
}
}
function getAllcache($sql, $time=600, $filename='') {
global $DB, $system_query_cache;
if(!$system_query_cache)$time=0;
$crc=md5($sql);
if(!empty($filename))$crc=$filename;
$modif=time()-@filemtime ("cache/".$crc);
if ($modif<$time)
{
$cache=file_get_contents("cache/".$crc);
$cache=unserialize($cache);
}
else
{
$cache = $DB->getAll($sql);
$fp = @fopen ("cache/".$crc, "w");
@fwrite ($fp, serialize($cache));
@fclose ($fp);
}
return $cache;
}
function getOnecache($sql, $time=600,$filename='') {
global $DB, $system_query_cache;
if(!$system_query_cache)$time=0;
$crc=md5($sql);
if(!empty($filename))$crc=$filename;
$modif=time()-@filemtime ("cache/".$crc);
if ($modif<$time)
{
$cache=file_get_contents("cache/".$crc);
$cache=unserialize($cache);
}
else
{
$cache = $DB->getOne($sql);
$fp = @fopen ("cache/".$crc, "w");
@fwrite ($fp, serialize($cache));
@fclose ($fp);
}
return $cache;
}
function email_check($email) {
if (!preg_match("/^(?:[a-z0-9]+(?:[-_.]?[a-z0-9]+)?@[a-z0-9_.-]+(?:\.?[a-z0-9]+)?\.[a-z]{2,5})$/i",trim($email)))
{
return false;
}
else return true;
}
function isIP($ip)
{
return (bool)(ip2long($ip)>0);
};
function getIP() {
if(isset($_SERVER['HTTP_X_REAL_IP'])) return $_SERVER['HTTP_X_REAL_IP'];
return $_SERVER['REMOTE_ADDR'];
} |
|
Кликните здесь для просмотра всего текста
| PHP | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
| <?php
/**
* MarkHtml v1.0
* =============
*
* Чистка HTML кода от зловредного для сайта кода.
* Убирает известный XSS код, запрещает использовать стили, которые могут
* повредить внешнему виду сайта.
*
* Используется внешний Markdown для форматирования текста.
*
* Код основан на [html_filter](http://savvateev.org/blog/36/)
*
* Использование:
* include ('markhtml.php');
* echo markhtml($text);
* echo markhtml($text, true); // XHTML
*
* @license: LGPL
* @date: 2011/04/05
* @author: Vladimir Romanovich <ibnteo@gmail.com>
*/
function markhtml($text, $xhtml = false) {
// MarkHtml
$markhtml = new MarkHtml($text, $xhtml);
$markhtml->markdown();
$markhtml->filter();
return $markhtml->text;
}
include (dirname(__FILE__).'/markdown.php');
class MarkHtml {
public $tags = array();
public $tags_closed = array();
public $tags_attr = array();
public $xhtml = false;
public $text = '';
public function markdown() {
$this->text = Markdown($this->text);
}
public function MarkHtml($text = '', $xhtml = false) {
$this->text = $text;
$this->xhtml = $xhtml;
// Одиночны теги
$this->tags_closed = array('img', 'br', 'hr', 'param', 'input', 'area', 'col', 'isindex');
// Запрещенные теги
$this->tags = array('script', 'meta', 'link', 'style', 'iframe', 'frameset', 'frame', 'layer', 'xml', 'base', 'bgsound', 'basefont', 'body', 'html', 'head', 'title');
// Запрещенные атрибуты
$this->tags_attr = array(
'style' => '\\(|\\\\|position:|margin',
'.*' => 's\s*c\s*r\s*i\s*p\s*t\s*:',
'^on' => '',
'src' => 'm\s*h\s*t\s*m\s*l\s*:',
'type' => 'scriptlet',
'allowscriptaccess' => 'always|samedomain'
);
}
// Фильтрация HTML
public function filter() {
$open_tags_stack = array();
$code = false;
$link = false;
// Разбиваем полученный код на учатки простого текста и теги
$seg = array();
while(preg_match('/<[^<>]+>/siu', $this->text, $matches, PREG_OFFSET_CAPTURE)){
if ($matches[0][1]) $seg[] = array('seg_type'=>'text', 'value'=>substr($this->text, 0, $matches[0][1]));
$seg[] = array('seg_type'=>'tag', 'value'=>$matches[0][0]);
$this->text = substr($this->text, $matches[0][1]+strlen($matches[0][0]));
}
if ($this->text != '') $seg[] = array('seg_type'=>'text', 'value'=>$this->text);
// Обрабатываем полученные участки
for ($i=0; $i<count($seg); $i++) {
//Если участок является простым текстом экранируем в нем спец. символы HTML
if ($seg[$i]['seg_type'] == 'text') {
// Мягко убираем лишние &
$seg[$i]['value'] = preg_replace('/&([a-z#0-9]+;)/ui', '&$1', htmlentities($seg[$i]['value'], ENT_QUOTES, 'UTF-8'));
// Тег
} elseif ($seg[$i]['seg_type'] == 'tag') {
// Тип тега: открывающий/закрывающий, имя тега, строка атрибутов
preg_match('#^<\s*(/)?\s*([a-z]+:)?([a-z0-9]+)(.*?)>$#siu', $seg[$i]['value'], $matches);
if (count($matches)==0) {
$seg[$i]['seg_type']='text';
$i --;
continue;
} elseif ($matches[1]) {
$seg[$i]['tag_type']='close';
} else {
$seg[$i]['tag_type']='open';
}
if ($seg[$i]['tag_type'] != 'text') {
$seg[$i]['tag_ns'] = $matches[2];
$seg[$i]['tag_name'] = $matches[3];
$seg[$i]['tag_name_lc'] = strtolower($matches[3]);
}
if (($seg[$i]['tag_name_lc']=='code') and ($seg[$i]['tag_type']=='close')) {
$code = false;
}
if (($seg[$i]['tag_name_lc']=='a') and ($seg[$i]['tag_type']=='close')) {
$link = false;
}
// Тег внутри <code> превращаем в текст
if ($code) {
$seg[$i]['seg_type'] = 'text';
$i--;
continue;
}
// Открывающий тег
if ($seg[$i]['tag_type'] == 'open') {
// Недопустимый тег показываем как текст
if (array_search($seg[$i]['tag_name_lc'], $this->tags) !== false) {
$seg[$i]['action'] = 'show';
}
// Допустимый тег
else {
if ($seg[$i]['tag_name_lc'] == 'code') $code = true;
if ($seg[$i]['tag_name_lc'] == 'a') $link = true;
// Если тег не одиночный, записываем его в стек открывающих тегов
if (array_search($seg[$i]['tag_name_lc'], $this->tags_closed) === false) {
array_push($open_tags_stack, $seg[$i]['tag_ns'].$seg[$i]['tag_name']);
}
}
// Обработка атрибутов
preg_match_all('#([a-z]+:)?([a-z]+)(\s*=\s*[\"]\s*(.*?)\s*[\"])?(\s*=\s*[\']\s*(.*?)\s*[\'])?(=([^\s>]*))?#siu', $matches[4], $attr_m, PREG_SET_ORDER);
$attr = array();
foreach($attr_m as $arr) {
$attr_ns = $arr[1];
$attr_key = $arr[2];
$attr_val = $arr[count($arr)-1];
$is_attr = true;
if (!(isset($seg[$i]['action']) and $seg[$i]['action'] == 'show')) {
// Поиск неправильных атрибутов
foreach ($this->tags_attr as $key=>$val) {
if (preg_match('/'.$key.'/ui', $attr_key)) {
if ($val == '' or preg_match('/'.$val.'/ui', html_entity_decode($attr_val, ENT_QUOTES, 'UTF-8'))) {
$is_attr = false;
break;
}
}
}
}
if ($is_attr) {
$attr[$attr_ns.$attr_key] = $attr_val;
}
}
$seg[$i]['attr'] = $attr;
}
// Закрывающий тег
else {
// Недопустимый закрывающий тег
if (array_search($seg[$i]['tag_name_lc'], $this->tags) !== false) {
// Удаляем лишний, показываем запрещенный
$seg[$i]['action'] = (array_search($seg[$i]['tag_name_lc'], $this->tags_closed) !== false) ? 'del' : 'show';
}
// Закрывают одиночный тег
elseif (array_search($seg[$i]['tag_name_lc'], $this->tags_closed) !== false) {
$seg[$i]['action'] = 'del';
}
// Допустимый закрывающий тег
else {
if ($seg[$i]['tag_name_lc'] == 'code') $code = false;
if ($seg[$i]['tag_name_lc'] == 'a') $link = false;
// Стек открывающих тегов пуст
if (count($open_tags_stack) == 0) {
$seg[$i]['action'] = 'del';
}
else {
// Закрывающий тег не соответствует открывающему, добавляем закрывающий
$tn = array_pop($open_tags_stack);
if ($seg[$i]['tag_ns'].$seg[$i]['tag_name'] != $tn) {
array_splice($seg, $i, 0, array(array('seg_type'=>'tag', 'tag_type'=>'close', 'tag_name'=>$tn, 'action'=>'add')));
}
}
}
}
}
}
// Закрываем оставшиеся в стеке теги
foreach (array_reverse($open_tags_stack) as $value) {
array_push($seg, array('seg_type'=>'tag', 'tag_type'=>'close', 'tag_name'=>$value, 'action'=>'add'));
}
// Собираем профильтрованный код и возвращаем его
$this->text = '';
foreach ($seg as $segment) {
if ($segment['seg_type'] == 'text') $this->text .= $segment['value'];
elseif (($segment['seg_type'] == 'tag') and !(isset($segment['action']) and $segment['action'] == 'del')) {
// Тег будет показан, или выведен как был
if ((isset($segment['action']) and $segment['action'] == 'show')) {
$st = '<';
$et = '>';
} else {
$st = '<';
$et = '>';
}
// Открывающий тег
if ($segment['tag_type'] == 'open') {
$this->text .= $st.$segment['tag_ns'].$segment['tag_name'];
if (isset($segment['attr']) and is_array($segment['attr'])) {
foreach ($segment['attr'] as $attr_key=>$attr_val) {
// Убираем лишние &
$attr_val = preg_replace('/&([a-z#0-9]+;)/ui', '&$1', htmlentities($attr_val, ENT_QUOTES, 'UTF-8'));
$this->text .= ' '.$attr_key.(($this->xhtml or $attr_key != $attr_val) ? '="'.$attr_val.'"' : '');
}
}
// Закрыть одиночный тег
if ($this->xhtml and array_search($segment['tag_name'], $this->tags_closed) !== false) $this->text .= " /";
$this->text .= $et;
}
// Закрывающий тег
elseif ($segment['tag_type'] == 'close') {
$this->text .= $st.'/'.(isset($segment['tag_ns'])?$segment['tag_ns']:'').$segment['tag_name'].$et;
}
}
}
}
}; |
|
js системы комментариев:
Кликните здесь для просмотра всего текста
| JavaScript | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
| $().ready(function() {
$('textarea.tinymce').tinymce({
// Location of TinyMCE script
script_url : 'js/tinymce/tinymce.js',
relative_urls : false,
// General options
theme : "advanced",language:"ru",
plugins : "autolink,lists,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,advlist",
// Theme options
theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,fontselect,fontsizeselect",
theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,emotions,image",
theme_advanced_buttons3 : "",
theme_advanced_buttons4 : "",
theme_advanced_toolbar_location : "top",
theme_advanced_toolbar_align : "left",
theme_advanced_statusbar_location : "bottom",
theme_advanced_resizing : true,
// Example content CSS (should be your site CSS)
content_css : "css/content.css",
// Drop lists for link/image/media/template dialogs
template_external_list_url : "lists/template_list.js",
external_link_list_url : "lists/link_list.js",
external_image_list_url : "lists/image_list.js",
media_external_list_url : "lists/media_list.js",
// Replace values for the template plugin
template_replace_values : {
username : "Some User",
staffid : "991234"
}
});
});
$(document).ready(function(e){
$(".delComment").live("click", function() {
if (!confirm('Вы подтверждаете удаление?')) return false;
var getvalue = $(this).attr('rel');
var passport = $(this).attr('passport');
var dataString = 'id=' + getvalue + '&passport=' + passport + '&eventComments=del';
$.ajax({
type: "POST",
url: "",
data: dataString,
cache: false,
success: function(html){
if(html=='OK')
{
$("#itemComment-" + getvalue).remove();
}
$("#ajaxComment").html(html);
}
});
e.preventDefault();
});
$(".replyComment").live("click", function() {
var getvalue = $(this).attr('rel');
var post_url = $("#posturlComment").val();
var dataString = 'replyid=' + getvalue + '&eventComments=reply' + '&posturlComment=' + post_url;
$.ajax({
type: "POST",
url: "",
data: dataString,
cache: false,
success: function(html){
$("#RformComment").fadeOut(2000).remove();
$("#itemComment-" + getvalue).append(html);
$('#RformComment textarea.tinymce').tinymce({
// Location of TinyMCE script
script_url : 'js/tinymce/tinymce.js',
relative_urls : false,
// General options
theme : "advanced",language:"ru",
plugins : "autolink,style,save,emotions,paste,xhtmlxtras,template,advlist",
// Theme options
theme_advanced_buttons1 : "cut,copy,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,emotions,image",
theme_advanced_buttons2 : "",
theme_advanced_buttons3 : "",
theme_advanced_buttons4 : "",
theme_advanced_toolbar_location : "top",
theme_advanced_toolbar_align : "left",
theme_advanced_statusbar_location : "bottom",
theme_advanced_resizing : true,
// Example content CSS (should be your site CSS)
content_css : "css/content.css",
// Drop lists for link/image/media/template dialogs
template_external_list_url : "lists/template_list.js",
external_link_list_url : "lists/link_list.js",
external_image_list_url : "lists/image_list.js",
media_external_list_url : "lists/media_list.js",
// Replace values for the template plugin
template_replace_values : {
username : "Some User",
staffid : "991234"
}
});
}
});
return false;//e.preventDefault();
});
$(".submitComment").live("click", function(e) {
var name = $("#nameComment").val();
var email = $("#emailComment").val();
var addComment = $("#addComment").val();
var RreplyComment = $("#RreplyComment").val();
if(typeof name === 'undefined') name='';
if(typeof email === 'undefined') email='';
if(typeof RreplyComment === 'undefined') RreplyComment='';
if(RreplyComment !== "" && RreplyComment !== 0 && RreplyComment !== "0" && RreplyComment !== null &&
RreplyComment !== false && typeof RreplyComment !== 'undefined') {
var loginComment = $("#RloginComment").val();
var comment = $("#RtextComment").val();
var post_url = $("#RposturlComment").val();
var postO_url = $("#RposturlOpenComment").val();
var persona= $("#RpersonaComment").val();
var checked = $("#RcheckedComment").val();
var cap = $("#RnameCommentCap").val();
var capcha = $("#Rcapcha").val();
}
else {
var loginComment = $("#loginComment").val();
var comment = $("#textComment").val();
var post_url = $("#posturlComment").val();
var postO_url = $("#posturlOpenComment").val();
var persona= $("#personaComment").val();
var checked = $("#checkedComment").val();
var cap = $("#nameCommentCap").val();
var capcha = $("#capcha").val();
}
var dataString = 'loginComment=' + loginComment + '&addComment=' + addComment + '&personaComment='
+ persona + '&checkedComment=' + checked + '&eventComments=save&nameComment='+ name
+ '&emailComment=' + email + '&textComment=' + encodeURIComponent(comment) + '&posturlComment='
+ post_url +'&posturlOpenComment=' + postO_url +'&replyComment=' + RreplyComment + '&nameCommentCap=' + cap
+ '&capcha=' + capcha;
if(post_url=='') {alert('Error')};
if((loginComment==0 && (name=='' || email=='')) || comment==='')
{
alert('Пожалуйста заполните все поля');
}
else
{
$("#ajaxComment").show();
$("#ajaxComment").fadeIn(400).html('<img src="img/comment/ajax-bar.gif" align="absmiddle"> <span class="loading"></span>');
$.ajax({
type: "POST",
url: "",
data: dataString,
cache: false,
success: function(html){
if(html!=='ERR1' && html!=='ERR2' && html!=='ERR3' && html!=='ERR4' && html!=='ERR5') {
if(RreplyComment !== "" && RreplyComment !== 0 && RreplyComment !== "0" && RreplyComment !== null &&
RreplyComment !== false && typeof RreplyComment !== 'undefined') {
$("#RformComment").fadeOut(2000).remove();
$("#itemComment-" + RreplyComment).append(html);
$("#ajaxComment").hide();
}
else {
$("#allComment").append(html);
//$("ol#update li:last").fadeIn("slow");
$("#nameComment").val("");
$("#emailComment").val("");
$('#textComment').text("");
$("#nameComment").focus();
$("#ajaxComment").hide();
}
}
else
{
$("#messComment").html('');
$("#messComment").show();
$("#ajaxComment").hide();
if(html=='ERR1')$("#messComment").append("Ошибка: Имя должно состоять более чем из 3 символов<br/>");
if(html=='ERR2')$("#messComment").append("Ошибка: E-Mail указан неверно<br/>");
if(html=='ERR3')$("#messComment").append("Ошибка: Отсутствует текст комментария<br/>");
if(html=='ERR4')$("#messComment").append("Ошибка: Не удается установить тип комментария. Попробуйте позже");
if(html=='ERR5')$("#messComment").append("Ошибка: Не верно указан проверочный код с картинки.");
$("#messComment").fadeOut(3000);
}
}
});
}
e.preventDefault();
});
}); |
|
0
|