<code>php</code><code>
namespace
app\helpers;
use
app\models\other\Censor;
use
app\models\other\CensorLog;
class
CensorHelper
{
public
$id
;
public
$data
;
public
$match_banned
;
public
$match_censor
;
public
function
__construct(
$id
=
'censor'
)
{
$this
->id =
$id
;
$this
->match_banned = [];
$this
->match_censor = [];
$this
->data =
$this
->getData();
}
public
function
getData()
{
$data
= \Yii::
$app
->cache->get(
$this
->id);
if
(
empty
(
$data
)) {
$words
= Censor::find()
->where([
'enable'
=> 1])
->andWhere([
' != '
,
'replacement'
,
''
])
->orderBy([
'replacement'
=> SORT_ASC,
'find'
=> SORT_DESC])
->asArray()
->all();
$censor
= [];
$banned
= [];
$replace
= [];
foreach
(
$words
as
$row
) {
switch
(
$row
[
'replacement'
]) {
case
'{censor}'
:
$censor
[] =
$row
[
'find'
];
break
;
case
'{banned}'
:
$banned
[] =
$row
[
'find'
];
break
;
default
:
$replace
[
'from'
][] =
$row
[
'replacement'
];
$replace
[
'to'
][] =
$row
[
'find'
];
break
;
}
}
if
(
$censor
||
$banned
) {
$data
= [
'censor'
=>
$this
->generateRegularExpression(
$censor
),
'banned'
=>
$this
->generateRegularExpression(
$banned
),
'replace'
=>
$replace
,
];
\Yii::
$app
->cache->set(
$this
->id,
$data
);
}
}
return
$data
;
}
public
function
generateRegularExpression(
array
$words
)
{
$regular
= implode(
'|'
,
array_map
(
'preg_quote'
,
$words
));
return
"/$regular/i"
;
}
public
function
check(
$string
)
{
$this
->banned(
$string
);
$this
->censor(
$string
);
}
public
function
censor(
$string
)
{
if
(!
empty
(
$this
->data[
'censor'
]) && preg_match(
$this
->data[
'censor'
],
$string
,
$matches
)) {
$this
->match_censor =
array_merge
(
$this
->match_censor,
$matches
[0]);
}
}
public
function
banned(
$string
)
{
if
(!
empty
(
$this
->data[
'banned'
]) && preg_match(
$this
->data[
'banned'
],
$string
,
$matches
)) {
$this
->match_banned =
array_merge
(
$this
->match_banned,
$matches
[0]);
}
}
public
function
flush
()
{
\Yii::
$app
->cache->
delete
(
$this
->id);
$this
->getData();
}
public
function
replace(
$string
)
{
return
!
empty
(
$this
->data[
'replace'
]) ?
str_replace
(
$this
->data[
'replace'
][
'from'
],
$this
->data[
'replace'
][
'to'
],
$string
) :
$string
;
}
public
function
getLevel()
{
if
(!
empty
(
$this
->match_banned)) {
return
'banned'
;
}
else
if
(!
empty
(
$this
->match_censor)) {
return
'censor'
;
}
else
{
return
'pass'
;
}
}
public
function
addLog(
$tableId
,
$dataId
)
{
$log
=
new
CensorLog();
$log
->datatb =
$tableId
;
$log
->dataid =
$dataId
;
$log
->matchcensor = implode(
','
,
$this
->match_censor);
$log
->matchbanned = implode(
','
,
$this
->match_banned);
$log
->addtime = time();
if
(!\Yii::
$app
->user->isGuest) {
$log
->uid = \Yii::
$app
->user->getId();
$log
->uname = \Yii::
$app
->user->getUname();
}
$log
->ip = IpHelper::getIP();
$log
->iploc = IpHelper::getLocation(
$log
->ip);
$log
->save();
}
}
</code>