Форум программистов, компьютерный форум, киберфорум
PHP для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.50/4: Рейтинг темы: голосов - 4, средняя оценка - 4.50
2 / 2 / 10
Регистрация: 17.09.2012
Сообщений: 860

Как внедрить этот код?

05.11.2013, 12:59. Показов 919. Ответов 2
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
дорогие программисты подскажите как внедрить этот код

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
<?
/********************************************/
/*Welcome to Anti Mate PHP Class source-code!*/
/*The Anti Mate PHP Class and its functions, contexture are copyrighted by s1ayer [www.spg.arbse.net]*/
/*Current file: anti_mate.php*/
/*Optimized for PHP 4.3.6, Apache 1.3.27*/
/********************************************/
error_reporting(E_ALL ^ E_DEPRECATED);
 
setlocale (LC_ALL, "ru_RU.CP1251");
/*<=====================Describing anti_mate class==============================>*/
class anti_mate {
    //latin equivalents for russian letters
    var $let_matches = array (
    "a" => "а",
    "c" => "с",
    "e" => "е",
    "k" => "к",
    "m" => "м",
    "o" => "о",
    "x" => "х",
    "y" => "у",
    "ё" => "е"
                             );
    //bad words array. Regexp's symbols are readable !
    var $bad_words = array (".*ху(й|и|я|е|л(и|е)).*", ".*пизд.*", "бл(я|т|д).*", "(с|сц)ук(а|о|и).*", "еб.*", ".*уеб.*", ".*пид(о|е)р.*", ".*хер.*");
    //if script will find bad word, it replace word to package of symbols below
    var $rand_sym = array ("#", "@", "&", "*");
 
function rand_replace (){
        for ($i=0; $i<5; $i++)
        @$output .= $this->rand_sym[rand(0,count($this->rand_sym)-1)];
        return $output;
}
function filter ($string){
            $counter = 0;
            $elems = explode (" ", $string); //here we explode string to words
            $count_elems = count($elems);
            for ($i=0; $i<$count_elems; $i++)
            {
            $blocked = 0;
            /*formating word...*/
            $str_rep = eregi_replace ("[^a-zA-Zа-яА-Яё]", "", strtolower($elems[$i]));
                for ($j=0; $j<strlen($str_rep); $j++)
                {
                    foreach ($this->let_matches as $key => $value)
                    {
                        if ($str_rep[$j] == $key)
                        $str_rep[$j] = $value;
 
                    }
                }
            /*done*/
 
            /*here we are trying to find bad word*/
            /*match in the special array*/
                for ($k=0; $k<count($this->bad_words); $k++)
                {
                    if (ereg("\*$", $this->bad_words[$k]))
                    {
                        if (ereg("^".$this->bad_words[$k], $str_rep))
                        {
                        $elems[$i] = $this->rand_replace();
                        $blocked = 1;
                        $counter++;
                        break;
                        }
                    
                    }
                    if ($str_rep == $this->bad_words[$k]){
                    $elems[$i] = $this->rand_replace();
                    $blocked = 1;
                    $counter++;
                    break;
                    }
 
                }
            }
            if ($counter != 0)
            $string = implode (" ", $elems); //here we implode words in the whole string
return $string;
}
}
/*<===================================END=======================================>*/
?>

вот сюда

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
<?
if (event('tooltip')) return;
 
check_access('u');
$admin=$USER->allowed('s');
global $TTPRI,$TTSTATE,$TTSTICO;
include("modules/supp/anti_mate.php");
 
 
if (!isset($_GET['id'])) die(); else $id=intval($_GET['id']);
if (!$t=get_sql_row('sup',"id='$id'")) die();
$tu=new_user($t['user']);
 
$GLOBALS['ticket_other']=$t['other']!=''?unserialize($t['other']):array();
 
if (!$admin and $t['user']!=$USER->id) die();
 
$per=10;
$r=mysql_query("select count(*) from supmsg where sup='$id'") or die('MySQL error 1');
list($num)=mysql_fetch_row($r);
$pgs=floor(($num)/$per); if ($pgs>0) $pgs--;
$page=isset($_GET['page'])?intval($_GET['page']):'last';
if ($page=='last') $page=$pgs; else $page--;
$start=$page*$per;
if ($page==$pgs) $lim=$num%$per+$per; else $lim=$per;
$limit="limit $lim offset $start";
$editor=($page==$pgs);
 
if ($admin and $editor and $t['state']<2 and isset($_GET['files_action'])) {
  files_actions('attach',self_url("id=$id"));
  return;
  }
 
$TITLE="Тикет";
if ($admin and $tu->id) $TITLE.=" '$tu->login'";
$TITLE.=" #$t[id]";
$m_admin=$admin?$t['admin']:$USER->id;
$r=mysql_query("select max(id) from supmsg where sup='$id' and (user='$USER->id' or user='$m_admin')") or die('MySQL error 2');
if (mysql_num_rows($r)<1) $i=0;
else list($i)=mysql_fetch_row($r);
if (!$i) $i=0;
$q="select count(*) from supmsg where sup='$id' and user!='$USER->id' and user!='$m_admin' and id>$i";
$r=mysql_query($q) or die('MySQL error 3');
list($m_new)=mysql_fetch_row($r);
 
function pages($pgs,$page,$id) {
  if ($pgs<1) return;
  for ($i=1; $i<=$pgs+1; $i++) $a[$i]=$i;
?>
<table class="print" cellspacing="0" style="width:100%"><tr><th class="title">
Страницы:
<? foreach ($a as $i=>$s) { $style=($page==$i-1)?'color:yellow':''; ?>
<a href="<?=self_url("id=$id&page=$i")?>" style="<?=$style?>"><?=$s?></a><?=$i<=$pgs?', ':''?>
<? } ?> из <?=$pgs+1?>
</th></tr></table>
<? }
 
function state_msg($t) {
  global $TTSTATE;
  $state=$t['state'];
  $s=$TTSTATE[$state];
  return($s);
  }
 
function out_msg($mid,$m) {
  global $CFG,$t,$id,$USER;
  $admin=$USER->allowed('s');
  $uid=$m['user'];
  $u=new_user($uid);
  $un=ucfirst($u->login);
  if ($admin) $un=link_to(module_url('core','admin/users',"edit=$uid"),$un);
  if ($uid==$t['user']) $style='font-weight:bold';
  else $style='';
  $img="/avatar/$uid".'.png';
  $img=file_exists(files('core').$img)?file_url($img,'core'):file_url('/avatar/nobody.png','core');
  $fio=$u->fio?$u->fio:'Имя неизвестно';
  $add='';
  if ($admin) $add.=a_action_js('Удалить','stop',"delete_msg($mid)");
  $text=page_bb($m['msg']);
  return <<<CODE
<table class="print ticket_message" cellspacing="0" id="t_$mid">
<tr id="h_$mid">
  <td class="p c m ticket_av" rowspan="2">
    <img class="ticket_av_img" src="$img" title="$fio" />
    </td>
  <th class="p ticket_head">
    <a name="msg_$mid"></a>$un ($fio)
    <span class="memo">$m[dt]</span>
    $add
    </th>
  </tr>
<tr id="m_$mid">
  <td class="p m ticket_text" style="$style"><div class="ticket_text">
    $text
    </div></td>
  </tr>
<tr id="b_$mid"><td class="bar" colspan="2">.</td></tr>
</table>
CODE;
  }
 
function xml_msg($mid,$m) {
  xml_start(); xml_head('responce');
  echo out_msg($mid,$m);
  xml_tail('responce');
  }
 
function message($t,$msg) {
  global $USER;
  $admin=$USER->allowed('s');
  $x=array('user'=>$USER->id,'sup'=>$t['id'],'msg'=>$msg);
  if ($msg!='') mysql_query("insert into supmsg set dt=now(),".make_sql_set($x));
  $m=get_sql_row('supmsg',"id=last_insert_id()");
  xml_msg($m['id'],$m);
  $x=array();
  if ($t['state']!='1') {
    if ($admin) { $x['admin']=$USER->id; $x['state']=1; } else $x['state']=0;
    }
  $x['wait']=$admin?'0':'1';
  mysql_query("update sup set dt$t[state]=now(),".make_sql_set($x)." where id='$t[id]'");
  }
 
if (isset($_GET['fromfaq']) and $admin) {
  $n=$_GET['fromfaq'];
  if (!$f=get_sql_row('faq',"id=$n")) return;
  $m="[q][title]Этот ответ взят из FAQ.[/title][center]Оригинал: [url=/m/supp/faq?parent=$n]$f[name][/url][/center][br][/q]";
  $m.=$f['descr'];
  message($t,$m);
  return;
  }
 
if (isset($_GET['faq']) and $admin) {
  $nodes=get_sql_table('faq.id',"parent='$_GET[faq]'",'views desc,name');
  $node=get_sql_row('faq',"id='$_GET[faq]'");
  if (trim($node['descr'])!='') {
    $text=page_bb($node['descr']);
    $a1=a_action_js('Добавить ссылку на раздел','add',"msg_faqlink($node[id])",'Добавить ссылку в сообщение');
    $a2=a_action_js('Отправить текст как сообщение','ok',"send_faq($node[id])",'Отправить как сообщение');
    echo <<<CODE
$a1 $a2
<div id="faqtext_$node[id]" class="chat-faq-text">$text</div>
CODE;
    }
  if (count($nodes)) {
    $img=action_img('link',array('style'=>'vertical-align:top'));
    foreach ($nodes as $id=>$n) {
      echo <<<CODE
$img<a href="javascript:void(0)" onclick="autofaq('faqfeed_$id',$id)">$n[name]</a><br>
<div style="display:none; margin-left:20px" id="faqfeed_$id"></div>
CODE;
      }
    }
  return;
  }
 
if (isset($_GET['fresh']) and isset($_GET['last'])) {
  $last=$_GET['last'];
  xml_start(); xml_head('responce');
  xml_head('commands');
    if ($ml=get_sql_array('supmsg.id.user',"sup='$id' and id>'$last' and user!='$USER->id'",'dt')) {
      foreach ($ml as $mid=>$mu) {
        xml_head('load_msg',array('id'=>$mid,'user'=>$mu),true);
        $last=$mid;
        }
      }
    xml_tail('commands');
  $a=array('name'=>'state','value'=>$t['state']);
  $a['text']=state_msg($t);
  $a['img']=action_img_file($TTSTICO[$t['state']]);
  xml_head('set',$a,true);
  xml_head('set',array('name'=>'last','value'=>$last),true);
  xml_tail('responce');
  return; }
 
if (isset($_GET['msg_get']) and $m=get_sql_row('supmsg',"id='$_GET[msg_get]'")) {
  xml_msg($_GET['msg_get'],$m);
  return; }
 
if (isset($_POST['msg']) and ($admin or $t['user']==$USER->id) and trim($_POST['msg'])!='' and $t['state']!=3) {
  $msg=trim(page_bb($_POST['msg']));
  if (strlen($msg)>65000) $msg="(!ОБРЕЗАНО!)\n".substr($msg,0,65000);
  $msg=explode("\n",$msg);
  foreach ($msg as $i=>$s) if (trim($s)=='') unset($msg[$i]);
  $msg='<p>'.implode("</p>\n<p>",$msg)."</p>\n";
  message($t,$msg);
  return;
  }
 
if (isset($_GET['delete']) and $admin) {
  mysql_query("delete from supmsg where id='$_GET[delete]'");
  return;
  }
?>
 
<center>
 
{SKIN_WIN_START=Тикет #<?=$t['id']?>|width:90%}
 
<? event('head'); ?>
<table class="print ticket_message" cellspacing="0" id="msg_state">
<tr>
  <th class="p ticket_hsubj">Тема:</th>
  <td class="ticket_subj" colspan="4">
    <p><b><?=$t['name']?></b></p>
    </td>
  </tr>
</table>
 
<? pages($pgs,$page,$id); ?>
 
<div id="messages">
<?
$last=get_sql_value('supmsg.id',"sup='$id'",'dt desc');
$mm=get_sql_table('supmsg.id',"sup='$t[id]'",'dt '.$limit);
foreach ($mm as $mid=>$m) {
  echo out_msg($mid,$m);
  }
?>
</div>
 
<table class="print ticket_message" cellspacing="0" id="msg_state">
<tr>
  <th class="p">Тикет #<?=$id?></th>
  <th class="p">
    <?=action_img($TTSTICO[$t['state']],array('id'=>'state_i'))?>
    Статус: <span id="state_s"><?=state_msg($t)?></span>
    </th>
  <th class="p c">
    {FORM_START=}
    {SKIN_TT=Возможность получить оповещение при изменении статуса тикета или получении ответа}
    <input class="checkbox" type="checkbox" name="alert"
           id="msg_alert" title="Показывать сообщение о новом ответе">
    <? $player=file_url('flashplayer.swf').'?file='.file_url('open.mp3'); ?>
    <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
            codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0"
            width="96" height="20" id="flashplayer" style="vertical-align:top; padding:1px">
    <param name="allowScriptAccess" value="sameDomain">
    <param name="movie" value="<?=$player?>" id="flash_movie">
    <param name="quality" value="high">
    <param name="bgcolor" value="#ffffff">
    <embed src="<?=$player?>" id="flash_embed"
          quality="high" bgcolor="#ffffff" width="96" height="20" name="flashplayer"
          allowScriptAccess="sameDomain" type="application/x-shockwave-flash"
          pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>
    </object>
    <input class="checkbox" type="checkbox" name="alert" checked="checked"
           id="msg_sound" title="Проигрывать звуки при смене статуса тикета">
    {FORM_END}
    </th>
  <th class="p c ticket_timer" title="Время до обновления данных">
    [<span id="msg_progress">&nbsp;</span>]
    </th>
  </tr>
</table>
{SKIN_WIN_END}
 
{SKIN_WIN_START=Добавление нового сообщения,margin-top:5px;width:90%}
<? if ($t['state']<2 and $editor) $style=''; else $style='display:none'; ?>
<?=form_start(self_url("id=$id"),'form_msg'); ?>
<table class="print ticket_message" cellspacing="0" style="<?=$style?>" id="editor">
<?
  $img="/avatar/$USER->id".'.png';
  $img=file_exists(files('core').$img)?file_url($img,'core'):file_url('/avatar/nobody.png','core');
  $fio=$USER->fio; if ($fio=='') $fio='Имя неизвестно';
  $un=ucfirst($USER->login);
  if ($admin) $un=link_to(module_url('core','admin/users',"edit=$USER->id"),$un);
?>
<tr>
<tr>
  <td class="p c m ticket_av" rowspan="2">
    <img class="ticket_av_img" src="<?=$img?>" title="<?=$fio?>" />
    </td>
  <th class="p ticket_head">
    <? if ($admin) { ?>
    <div class="p" style="float:right">
    <?=form_button("Авто-ответ","autofaq('autofaqfeed',0)")?></div>
    <? } ?> 
    </th>
  </tr>
<tr id="m_$mid">
  <td class="p c m ticket_text" style="padding:0px">
    <? if ($admin) { ?>
    <div class="chat-autofaq" style="display:none" id="autofaq">
      <div id="autofaqfeed" style="margin:0px 5px 0px 5px">...загружаю...</div>
      <hr>
      </div>
    <? } ?>
  <?=form_richtext('msg',$msg,'100%',3);?>
</td>
  </tr>
<tr><td class="p c" colspan="2">
<?
  echo form_button('Отправить сообщение',"send_msg()");
  if ($t['state']==2) echo form_button('Закрыть тикет',"location.href='".link_url("index?id=$id&state=2")."'");
  echo form_button('Обновить страницу',"location.href='".self_url("id=$id")."'");
?>
  </td></tr>
</table>
<?=form_end(); ?>
 
<table class="print ticket_message" style="display:<?=$t['state']==2?'':'none'?>" cellspacing="0" id="msg_closed">
<tr><th class="p c">
<h1>Тикет закрыт одним из собеседников.</h1>
<h2>При отправке сообщения тикет <?=$admin?'будет снова открыт':'вернётся в очередь'?>.</h2>
</th></tr></table>
 
<table class="print ticket_message" style="display:<?=$t['state']==3?'':'none'?>" cellspacing="0" id="msg_done">
<tr><th class="p c">
<h1>Тикет окончательно закрыт администратором.</h1>
<h2>Вы можете создать новый тикет на странице со списком.</h2>
</th></tr></table>
 
<?=form_start(link_url("index"),'form_actions'); ?>
<table class="print ticket_message" cellspacing="0"><tr>
<th class="p c"><a id="down"></a><?
  if ($t['state']==2) {
    if ($admin) $url=link_url("index?id=$id&state=1"); else $url=link_url("index?id=$id&state=0");
    echo form_button('Добавить сообщение',"show_editor()").' | ';
    }
  echo form_button('Вернуться к списку',"location.href='".link_url("index")."'");
  if ($t['state']<2)
    echo form_button('Закрыть тикет',"location.href='".link_url("index?id=$id&state=2")."'");
  if ($admin and $t['state']==1)
    echo form_button('Вернуть в очередь',"location.href='".link_url("index?id=$id&state=0")."'");
?></th>
<? if ($admin and $t['state']!=3) { ?>
<th class="p c"><?
  echo form_button('Завершить тикет',"if (confirm('Вы уверены? Тикет нельзя будет открыть!')) location.href='".link_url("index?id=$id&state=3")."'");
?></th>
<th class="p c"><? echo a_action_js('Файлы','save',"toggle('files_form')"); ?></th>
<? } ?>
</tr></table>
 
<? if ($admin and $t['state']!=3) { ?>
<div id="files_form" style="display:none">
<table class="print ticket_message" cellspacing="0">
<tr><td class="bar"></td></tr>
<tr><td>
<? files_form($id,'attach',self_url("id=$id"),true); ?>
</td></tr></table>
</div>
<? } ?>
 
<?=form_end(); ?>
 
<? pages($pgs,$page,$id); ?>
 
{SKIN_WIN_END}
 
<script language="JavaScript" type="text/javascript" src="<?="$CFG[PATH]/modules/supp/chat.js"?>"></script>
 
<script language="JavaScript" type="text/javascript">
 
var msgs=new Array();
var last=<?=$last?>;
var state=<?=$t['state']?>;
var chat_timed=3;
var chat_timem=30;
var chat_timec=chat_timed;
var chat_time=chat_timed;
var chatid=<?=$id?>;
var loader_on=<?=$page==$pgs?'true':'false'?>;
var url='<?=self_url("id=$id")?>';
var player='<?=$player?>';
//var u_user=<?=$USER->id?>;
//var u_admin=<?=$t['admin']?>;
var m_new=<?=$m_new?>;
var m_title="<?=$TITLE?>";
 
<? if ($t['state']!=2 and $editor) { ?>
document.getElementById('msg').focus();
<? } ?>
 
<? if (isset($_GET['scroll'])) { ?>
window.scrollBy(0,30000);
<? } ?>
 
maketitle();
request();
 
</script>
 
<noscript>
JavaScript недоступен, автоматическое оповещение невозможно.<br>
<?=self_to("id=$id",'Обновить страницу');?>
</noscript>
 
</center>
Добавлено через 10 часов 33 минуты
помогите пожалуйста
0
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
05.11.2013, 12:59
Ответы с готовыми решениями:

Очередной код с возможным вирусом. Как думаете этот код опасен?
&lt;?php // no direct access defined('_JEXEC') or die('Restricted access'); ?&gt; &lt;ul class=&quot;sections&lt;?php echo...

Как улучшить этот код?
Код хорошего программиста чёткий, понятный, логичный, последовательный. Это видно с первого взгляда. Хорошего качества кода добиваются...

Объясните как работает этот код?
У меня этот код работает, но я не понимаю как!? И что за символы, могли бы вы по полочкам разложить мне. Буду благодарен. RewriteEngine...

2
Эксперт PHP
5755 / 4134 / 1508
Регистрация: 06.01.2011
Сообщений: 11,276
05.11.2013, 14:12
Вот так (я отметил, где я добавил):
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
<?
if (event('tooltip')) return;
 
check_access('u');
$admin=$USER->allowed('s');
global $TTPRI,$TTSTATE,$TTSTICO;
include("modules/supp/anti_mate.php");
 
 
if (!isset($_GET['id'])) die(); else $id=intval($_GET['id']);
if (!$t=get_sql_row('sup',"id='$id'")) die();
$tu=new_user($t['user']);
 
$GLOBALS['ticket_other']=$t['other']!=''?unserialize($t['other']):array();
 
if (!$admin and $t['user']!=$USER->id) die();
 
$per=10;
$r=mysql_query("select count(*) from supmsg where sup='$id'") or die('MySQL error 1');
list($num)=mysql_fetch_row($r);
$pgs=floor(($num)/$per); if ($pgs>0) $pgs--;
$page=isset($_GET['page'])?intval($_GET['page']):'last';
if ($page=='last') $page=$pgs; else $page--;
$start=$page*$per;
if ($page==$pgs) $lim=$num%$per+$per; else $lim=$per;
$limit="limit $lim offset $start";
$editor=($page==$pgs);
 
if ($admin and $editor and $t['state']<2 and isset($_GET['files_action'])) {
  files_actions('attach',self_url("id=$id"));
  return;
  }
 
$TITLE="Тикет";
if ($admin and $tu->id) $TITLE.=" '$tu->login'";
$TITLE.=" #$t[id]";
$m_admin=$admin?$t['admin']:$USER->id;
$r=mysql_query("select max(id) from supmsg where sup='$id' and (user='$USER->id' or user='$m_admin')") or die('MySQL error 2');
if (mysql_num_rows($r)<1) $i=0;
else list($i)=mysql_fetch_row($r);
if (!$i) $i=0;
$q="select count(*) from supmsg where sup='$id' and user!='$USER->id' and user!='$m_admin' and id>$i";
$r=mysql_query($q) or die('MySQL error 3');
list($m_new)=mysql_fetch_row($r);
 
function pages($pgs,$page,$id) {
  if ($pgs<1) return;
  for ($i=1; $i<=$pgs+1; $i++) $a[$i]=$i;
?>
<table class="print" cellspacing="0" style="width:100%"><tr><th class="title">
Страницы:
<? foreach ($a as $i=>$s) { $style=($page==$i-1)?'color:yellow':''; ?>
<a href="<?=self_url("id=$id&page=$i")?>" style="<?=$style?>"><?=$s?></a><?=$i<=$pgs?', ':''?>
<? } ?> из <?=$pgs+1?>
</th></tr></table>
<? }
 
function state_msg($t) {
  global $TTSTATE;
  $state=$t['state'];
  $s=$TTSTATE[$state];
  return($s);
  }
 
function out_msg($mid,$m) {
  global $CFG,$t,$id,$USER;
  $admin=$USER->allowed('s');
  $uid=$m['user'];
  $u=new_user($uid);
  $un=ucfirst($u->login);
  if ($admin) $un=link_to(module_url('core','admin/users',"edit=$uid"),$un);
  if ($uid==$t['user']) $style='font-weight:bold';
  else $style='';
  $img="/avatar/$uid".'.png';
  $img=file_exists(files('core').$img)?file_url($img,'core'):file_url('/avatar/nobody.png','core');
  $fio=$u->fio?$u->fio:'Имя неизвестно';
  $add='';
  if ($admin) $add.=a_action_js('Удалить','stop',"delete_msg($mid)");
  $text=page_bb($m['msg']);
  return <<<CODE
<table class="print ticket_message" cellspacing="0" id="t_$mid">
<tr id="h_$mid">
  <td class="p c m ticket_av" rowspan="2">
    <img class="ticket_av_img" src="$img" title="$fio" />
    </td>
  <th class="p ticket_head">
    <a name="msg_$mid"></a>$un ($fio)
    <span class="memo">$m[dt]</span>
    $add
    </th>
  </tr>
<tr id="m_$mid">
  <td class="p m ticket_text" style="$style"><div class="ticket_text">
    $text
    </div></td>
  </tr>
<tr id="b_$mid"><td class="bar" colspan="2">.</td></tr>
</table>
CODE;
  }
 
function xml_msg($mid,$m) {
  xml_start(); xml_head('responce');
  echo out_msg($mid,$m);
  xml_tail('responce');
  }
 
function message($t,$msg) {
  global $USER;
  $admin=$USER->allowed('s');
  $x=array('user'=>$USER->id,'sup'=>$t['id'],'msg'=>$msg);
  if ($msg!='') mysql_query("insert into supmsg set dt=now(),".make_sql_set($x));
  $m=get_sql_row('supmsg',"id=last_insert_id()");
  xml_msg($m['id'],$m);
  $x=array();
  if ($t['state']!='1') {
    if ($admin) { $x['admin']=$USER->id; $x['state']=1; } else $x['state']=0;
    }
  $x['wait']=$admin?'0':'1';
  mysql_query("update sup set dt$t[state]=now(),".make_sql_set($x)." where id='$t[id]'");
  }
 
if (isset($_GET['fromfaq']) and $admin) {
  $n=$_GET['fromfaq'];
  if (!$f=get_sql_row('faq',"id=$n")) return;
  $m="[q][title]Этот ответ взят из FAQ.[/title][center]Оригинал: [url=/m/supp/faq?parent=$n]$f[name][/url][/center][br][/q]";
  $m.=$f['descr'];
  message($t,$m);
  return;
  }
 
if (isset($_GET['faq']) and $admin) {
  $nodes=get_sql_table('faq.id',"parent='$_GET[faq]'",'views desc,name');
  $node=get_sql_row('faq',"id='$_GET[faq]'");
  if (trim($node['descr'])!='') {
    $text=page_bb($node['descr']);
    $a1=a_action_js('Добавить ссылку на раздел','add',"msg_faqlink($node[id])",'Добавить ссылку в сообщение');
    $a2=a_action_js('Отправить текст как сообщение','ok',"send_faq($node[id])",'Отправить как сообщение');
    echo <<<CODE
$a1 $a2
<div id="faqtext_$node[id]" class="chat-faq-text">$text</div>
CODE;
    }
  if (count($nodes)) {
    $img=action_img('link',array('style'=>'vertical-align:top'));
    foreach ($nodes as $id=>$n) {
      echo <<<CODE
$img<a href="javascript:void(0)" onclick="autofaq('faqfeed_$id',$id)">$n[name]</a><br>
<div style="display:none; margin-left:20px" id="faqfeed_$id"></div>
CODE;
      }
    }
  return;
  }
 
if (isset($_GET['fresh']) and isset($_GET['last'])) {
  $last=$_GET['last'];
  xml_start(); xml_head('responce');
  xml_head('commands');
    if ($ml=get_sql_array('supmsg.id.user',"sup='$id' and id>'$last' and user!='$USER->id'",'dt')) {
      foreach ($ml as $mid=>$mu) {
        xml_head('load_msg',array('id'=>$mid,'user'=>$mu),true);
        $last=$mid;
        }
      }
    xml_tail('commands');
  $a=array('name'=>'state','value'=>$t['state']);
  $a['text']=state_msg($t);
  $a['img']=action_img_file($TTSTICO[$t['state']]);
  xml_head('set',$a,true);
  xml_head('set',array('name'=>'last','value'=>$last),true);
  xml_tail('responce');
  return; }
 
if (isset($_GET['msg_get']) and $m=get_sql_row('supmsg',"id='$_GET[msg_get]'")) {
  xml_msg($_GET['msg_get'],$m);
  return; }
 
if (isset($_POST['msg']) and ($admin or $t['user']==$USER->id) and trim($_POST['msg'])!='' and $t['state']!=3) {
 
    ################################## ТУТ Я ДОБАВИЛ ###############################
    $antimate = new anti_mate;
 
    $msg=trim(page_bb($_POST['msg']));
  
    # Вызываем проверку на мат
    $msg = $antimate->filter( $msg );
  
  if (strlen($msg)>65000) $msg="(!ОБРЕЗАНО!)\n".substr($msg,0,65000);
  $msg=explode("\n",$msg);
  foreach ($msg as $i=>$s) if (trim($s)=='') unset($msg[$i]);
  $msg='<p>'.implode("</p>\n<p>",$msg)."</p>\n";
  message($t,$msg);
  return;
  }
 
if (isset($_GET['delete']) and $admin) {
  mysql_query("delete from supmsg where id='$_GET[delete]'");
  return;
  }
?>
 
<center>
 
{SKIN_WIN_START=Тикет #<?=$t['id']?>|width:90%}
 
<? event('head'); ?>
<table class="print ticket_message" cellspacing="0" id="msg_state">
<tr>
  <th class="p ticket_hsubj">Тема:</th>
  <td class="ticket_subj" colspan="4">
    <p><b><?=$t['name']?></b></p>
    </td>
  </tr>
</table>
 
<? pages($pgs,$page,$id); ?>
 
<div id="messages">
<?
$last=get_sql_value('supmsg.id',"sup='$id'",'dt desc');
$mm=get_sql_table('supmsg.id',"sup='$t[id]'",'dt '.$limit);
foreach ($mm as $mid=>$m) {
  echo out_msg($mid,$m);
  }
?>
</div>
 
<table class="print ticket_message" cellspacing="0" id="msg_state">
<tr>
  <th class="p">Тикет #<?=$id?></th>
  <th class="p">
    <?=action_img($TTSTICO[$t['state']],array('id'=>'state_i'))?>
    Статус: <span id="state_s"><?=state_msg($t)?></span>
    </th>
  <th class="p c">
    {FORM_START=}
    {SKIN_TT=Возможность получить оповещение при изменении статуса тикета или получении ответа}
    <input class="checkbox" type="checkbox" name="alert"
           id="msg_alert" title="Показывать сообщение о новом ответе">
    <? $player=file_url('flashplayer.swf').'?file='.file_url('open.mp3'); ?>
    <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
            codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0"
            width="96" height="20" id="flashplayer" style="vertical-align:top; padding:1px">
    <param name="allowScriptAccess" value="sameDomain">
    <param name="movie" value="<?=$player?>" id="flash_movie">
    <param name="quality" value="high">
    <param name="bgcolor" value="#ffffff">
    <embed src="<?=$player?>" id="flash_embed"
          quality="high" bgcolor="#ffffff" width="96" height="20" name="flashplayer"
          allowScriptAccess="sameDomain" type="application/x-shockwave-flash"
          pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>
    </object>
    <input class="checkbox" type="checkbox" name="alert" checked="checked"
           id="msg_sound" title="Проигрывать звуки при смене статуса тикета">
    {FORM_END}
    </th>
  <th class="p c ticket_timer" title="Время до обновления данных">
    [<span id="msg_progress">&nbsp;</span>]
    </th>
  </tr>
</table>
{SKIN_WIN_END}
 
{SKIN_WIN_START=Добавление нового сообщения,margin-top:5px;width:90%}
<? if ($t['state']<2 and $editor) $style=''; else $style='display:none'; ?>
<?=form_start(self_url("id=$id"),'form_msg'); ?>
<table class="print ticket_message" cellspacing="0" style="<?=$style?>" id="editor">
<?
  $img="/avatar/$USER->id".'.png';
  $img=file_exists(files('core').$img)?file_url($img,'core'):file_url('/avatar/nobody.png','core');
  $fio=$USER->fio; if ($fio=='') $fio='Имя неизвестно';
  $un=ucfirst($USER->login);
  if ($admin) $un=link_to(module_url('core','admin/users',"edit=$USER->id"),$un);
?>
<tr>
<tr>
  <td class="p c m ticket_av" rowspan="2">
    <img class="ticket_av_img" src="<?=$img?>" title="<?=$fio?>" />
    </td>
  <th class="p ticket_head">
    <? if ($admin) { ?>
    <div class="p" style="float:right">
    <?=form_button("Авто-ответ","autofaq('autofaqfeed',0)")?></div>
    <? } ?> 
    </th>
  </tr>
<tr id="m_$mid">
  <td class="p c m ticket_text" style="padding:0px">
    <? if ($admin) { ?>
    <div class="chat-autofaq" style="display:none" id="autofaq">
      <div id="autofaqfeed" style="margin:0px 5px 0px 5px">...загружаю...</div>
      <hr>
      </div>
    <? } ?>
  <?=form_richtext('msg',$msg,'100%',3);?>
</td>
  </tr>
<tr><td class="p c" colspan="2">
<?
  echo form_button('Отправить сообщение',"send_msg()");
  if ($t['state']==2) echo form_button('Закрыть тикет',"location.href='".link_url("index?id=$id&state=2")."'");
  echo form_button('Обновить страницу',"location.href='".self_url("id=$id")."'");
?>
  </td></tr>
</table>
<?=form_end(); ?>
 
<table class="print ticket_message" style="display:<?=$t['state']==2?'':'none'?>" cellspacing="0" id="msg_closed">
<tr><th class="p c">
<h1>Тикет закрыт одним из собеседников.</h1>
<h2>При отправке сообщения тикет <?=$admin?'будет снова открыт':'вернётся в очередь'?>.</h2>
</th></tr></table>
 
<table class="print ticket_message" style="display:<?=$t['state']==3?'':'none'?>" cellspacing="0" id="msg_done">
<tr><th class="p c">
<h1>Тикет окончательно закрыт администратором.</h1>
<h2>Вы можете создать новый тикет на странице со списком.</h2>
</th></tr></table>
 
<?=form_start(link_url("index"),'form_actions'); ?>
<table class="print ticket_message" cellspacing="0"><tr>
<th class="p c"><a id="down"></a><?
  if ($t['state']==2) {
    if ($admin) $url=link_url("index?id=$id&state=1"); else $url=link_url("index?id=$id&state=0");
    echo form_button('Добавить сообщение',"show_editor()").' | ';
    }
  echo form_button('Вернуться к списку',"location.href='".link_url("index")."'");
  if ($t['state']<2)
    echo form_button('Закрыть тикет',"location.href='".link_url("index?id=$id&state=2")."'");
  if ($admin and $t['state']==1)
    echo form_button('Вернуть в очередь',"location.href='".link_url("index?id=$id&state=0")."'");
?></th>
<? if ($admin and $t['state']!=3) { ?>
<th class="p c"><?
  echo form_button('Завершить тикет',"if (confirm('Вы уверены? Тикет нельзя будет открыть!')) location.href='".link_url("index?id=$id&state=3")."'");
?></th>
<th class="p c"><? echo a_action_js('Файлы','save',"toggle('files_form')"); ?></th>
<? } ?>
</tr></table>
 
<? if ($admin and $t['state']!=3) { ?>
<div id="files_form" style="display:none">
<table class="print ticket_message" cellspacing="0">
<tr><td class="bar"></td></tr>
<tr><td>
<? files_form($id,'attach',self_url("id=$id"),true); ?>
</td></tr></table>
</div>
<? } ?>
 
<?=form_end(); ?>
 
<? pages($pgs,$page,$id); ?>
 
{SKIN_WIN_END}
 
<script language="JavaScript" type="text/javascript" src="<?="$CFG[PATH]/modules/supp/chat.js"?>"></script>
 
<script language="JavaScript" type="text/javascript">
 
var msgs=new Array();
var last=<?=$last?>;
var state=<?=$t['state']?>;
var chat_timed=3;
var chat_timem=30;
var chat_timec=chat_timed;
var chat_time=chat_timed;
var chatid=<?=$id?>;
var loader_on=<?=$page==$pgs?'true':'false'?>;
var url='<?=self_url("id=$id")?>';
var player='<?=$player?>';
//var u_user=<?=$USER->id?>;
//var u_admin=<?=$t['admin']?>;
var m_new=<?=$m_new?>;
var m_title="<?=$TITLE?>";
 
<? if ($t['state']!=2 and $editor) { ?>
document.getElementById('msg').focus();
<? } ?>
 
<? if (isset($_GET['scroll'])) { ?>
window.scrollBy(0,30000);
<? } ?>
 
maketitle();
request();
 
</script>
 
<noscript>
JavaScript недоступен, автоматическое оповещение невозможно.<br>
<?=self_to("id=$id",'Обновить страницу');?>
</noscript>
 
</center>

Не по теме:

У вас код антимата написан для старой версии php (4.3.6), если у вас версия php намного новее - будет выдавать ошибки.

1
2 / 2 / 10
Регистрация: 17.09.2012
Сообщений: 860
05.11.2013, 18:20  [ТС]
СПАСИБО ОГРОМНОЕ КОД РАБОТАЕТ
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
05.11.2013, 18:20
Помогаю со студенческими работами здесь

Как можно оптимизировать этот код?
Как можно оптимизировать этот код? $preview = 'preview.'; $preview_url = 'images/' . $folder . '/' . $preview; if ( file_exists(...

Как прочитать этот код? Что он означает?
Всем привет! Только спецы могут понять чего это означает. Предистория: делал фрилансер но не доделал. Разрабатывать начали новый...

Как взять в этот код прошлый день?
Допустим, сегодня 31.03.2017. И есть страница: /scripts/XML_daily.asp?date_req=31.03.2017 И данные из нее подгружаются таким кодом: ...

Как сделать так, чтобы этот код рекурсивно обходил архив?
Здравствуйте! Есть код, который обходит архив и выводит файлы и папки в нём. &lt;?php $archive = new...

Как заставить этот код работать без перезагрузки страницы (ajax)
Здравствуйте. Вопрос такой - есть страница table.html в неё подключается table.php с помощью include. В файле table.php происходит вывод...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
3
Ответ Создать тему
Новые блоги и статьи
Thinkpad X220 Tablet — это лучший бюджетный ноутбук для учёбы, точка.
Programma_Boinc 23.12.2025
Thinkpad X220 Tablet — это лучший бюджетный ноутбук для учёбы, точка. Рецензия / Мнение Это мой обзор планшета X220 с точки зрения школьника. Недавно я решила попытаться уменьшить свой. . .
PhpStorm 2025.3: WSL Terminal всегда стартует в ~
and_y87 14.12.2025
PhpStorm 2025. 3: WSL Terminal всегда стартует в ~ (home), игнорируя директорию проекта Симптом: После обновления до PhpStorm 2025. 3 встроенный терминал WSL открывается в домашней директории. . .
Как объединить две одинаковые БД Access с разными данными
VikBal 11.12.2025
Помогите пожалуйста !! Как объединить 2 одинаковые БД Access с разными данными.
Новый ноутбук
volvo 07.12.2025
Всем привет. По скидке в "черную пятницу" взял себе новый ноутбук Lenovo ThinkBook 16 G7 на Амазоне: Ryzen 5 7533HS 64 Gb DDR5 1Tb NVMe 16" Full HD Display Win11 Pro
Музыка, написанная Искусственным Интеллектом
volvo 04.12.2025
Всем привет. Некоторое время назад меня заинтересовало, что уже умеет ИИ в плане написания музыки для песен, и, собственно, исполнения этих самых песен. Стихов у нас много, уже вышли 4 книги, еще 3. . .
От async/await к виртуальным потокам в Python
IndentationError 23.11.2025
Армин Ронахер поставил под сомнение async/ await. Создатель Flask заявляет: цветные функции - провал, виртуальные потоки - решение. Не threading-динозавры, а новое поколение лёгких потоков. Откат?. . .
Поиск "дружественных имён" СОМ портов
Argus19 22.11.2025
Поиск "дружественных имён" СОМ портов На странице: https:/ / norseev. ru/ 2018/ 01/ 04/ comportlist_windows/ нашёл схожую тему. Там приведён код на С++, который показывает только имена СОМ портов, типа,. . .
Сколько Государство потратило денег на меня, обеспечивая инсулином.
Programma_Boinc 20.11.2025
Сколько Государство потратило денег на меня, обеспечивая инсулином. Вот решила сделать интересный приблизительный подсчет, сколько государство потратило на меня денег на покупку инсулинов. . . .
Ломающие изменения в C#.NStar Alpha
Etyuhibosecyu 20.11.2025
Уже можно не только тестировать, но и пользоваться C#. NStar - писать оконные приложения, содержащие надписи, кнопки, текстовые поля и даже изображения, например, моя игра "Три в ряд" написана на этом. . .
Мысли в слух
kumehtar 18.11.2025
Кстати, совсем недавно имел разговор на тему медитаций с людьми. И обнаружил, что они вообще не понимают что такое медитация и зачем она нужна. Самые базовые вещи. Для них это - когда просто люди. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2025, CyberForum.ru