Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Zeindelf committed Jun 30, 2016
0 parents commit d454c88
Show file tree
Hide file tree
Showing 11 changed files with 976 additions and 0 deletions.
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/vendor/

README.html
composer.lock
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2016 Wellington Barreto

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
72 changes: 72 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
# Badwords

Filtro para censura de palavrões/palavras inapropriadas.

## Instalação

Instale via composer:
```
{
"require": {
"zeindelf/badwords": "1.*"
}
}
```

## Uso

### Verificação simples

```php
$verify = Badwords\Badwords::verify(/* sua palavra a ser verificada */);

if ( $verify ) {
echo 'Badwords!';
}
```

### Adicionando palavras

Você precisa criar um array com o índice `'badwords'` e setar um array com as palavras que deseja acrescentar.

```php
$extra = [
'badwords' => ['rocks'],
];

$verify = Badwords\Badwords::verify('rocks', $extra);

if ( $verify ) {
echo 'Badwords!';
}
```

### Excluindo palavras

Você precisa criar um array com o índice `'ignored'` e setar um array com as palavras que deseja ignorar.

Se a palavra for válida na configuração original, ela deixará de ser considerada, retornando `false` na verificação.

A lista de todas as palavras do filtro encontra-se em: `src/Config/Filter.php`

```php
$extra = [
'ignored' => ['cadela'],
];

$verify = Badwords\Badwords::verify('cadela', $extra);

if ( ! $verify ) {
echo 'Cadela é uma palavra válida';
}
```

### Usando ambos

```php
$extra = [
'badwords' => ['rocks'],
'ignored' => ['cadela'],
];
```
A palavra `'rocks'` será considerada no filtro ao mesmo tempo que a palavra `'cadela'` será ignorada.
28 changes: 28 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
{
"name": "zeindelf/badwords",
"description": "Filtro para censura de palavrões/palavras inapropriadas",
"support": {
"issues": "https://github.com/zeindelf/badwords/issues",
"source": "https://github.com/zeindelf/badwords"
},
"type": "library",
"keywords": ["badwords", "palavrão"],
"require-dev": {
"phpunit/phpunit": "~4.8"
},
"license": "MIT",
"authors": [
{
"name": "Wellington Barreto",
"email": "zeindelf@hotmail.com"
}
],
"require": {
"php": ">5.4"
},
"autoload": {
"psr-4": {
"Badwords\\": "src/"
}
}
}
67 changes: 67 additions & 0 deletions example.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
<?php

require_once __DIR__ . '/vendor/autoload.php';

session_start();

function flash($class, $message) {
$sess = '<div class="message message-' . $class . '"><p>' . $message . '</p></div>';
$_SESSION['flash'] = $sess;
}

$word = filter_input(INPUT_POST, 'word', FILTER_DEFAULT);

if ( !is_null($word) ):
if ( Badwords\Badwords::verify($word) ):
flash('danger', 'Palavra inapropriada');
else:
flash('success', 'Palavra apropriada');
endif;
endif;
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<link href="https://fonts.googleapis.com/css?family=Roboto+Condensed:300,400,700" rel="stylesheet" type="text/css">

<title>Badwords Exemplo</title>

<style>
* { margin: 0; padding: 0; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; }
body { font-family: 'Roboto Condensed'; font-size: 1.2em; font-weight: 300; background: #eee; }
.container { text-align: center; margin-top: 6em; }
.form-container { width: 100%; max-width: 600px; margin: auto; }
.message { width: 100%; padding: 1em; margin: 1em 0; border-radius: 3px; }
.message.message-success { background: #dff0d8; color: #3c763d; border: 1px solid #d0e9c6; }
.message.message-danger { background: #f2dede; color: #a94442; border: 1px solid #ebcccc; }
input { display: block; width: 70%; margin: .5em auto; line-height: 2; font-size: 1em; font-family: 'Roboto Condensed'; border: 1px solid #ccc; border-radius: 3px; outline: none; padding: 0 .5em; }
button { line-height: 2.2; margin-top: 1em; padding: 0 2em; font-size: 1em; border-radius: 3px; outline: none; color: #eee; background: #666; border: 1px solid #777; cursor: pointer; }
button:hover { background: #444; }
h1 { margin: 1em; color: tomato; }
</style>
</head>
<body>
<div class="container">
<h1>Badwords Exemplo</h1>

<div class="form-container">

<?php
if ( isset($_SESSION['flash']) ):
echo $_SESSION['flash'];
unset($_SESSION['flash']);
endif;
?>

<form action="" method="post">
<label for="word">Palavra para filtar:</label>
<input type="text" name="word" id="word">

<button type="submit">Verificar</button>
</form>
</div><!-- /.form-container -->
</div><!-- /.container -->
</body>
</html>
19 changes: 19 additions & 0 deletions phpunit.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit
backupGlobals="false"
backupStaticAtributes="false"
bootstrap="vendor/autoload.php"
colors="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
convertErrorsToExceptions="true"
processIsolation="true"
stopOnFailure="false"
syntaxCheck="false"
>
<testsuites>
<testsuite name="Badwords Test Suite">
<directory suffix=".php">./tests/</directory>
</testsuite>
</testsuites>
</phpunit>
142 changes: 142 additions & 0 deletions src/Badwords.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
<?php

namespace Badwords;

use Badwords\Config\Config;

/**
* Badwords - Filtra palavras indesejadas
*
* @link https://github.com/zeindelf/badwords/ The Badwords GitHub project
* @author Wellington Barreto <zeindelf@hotmail.com>
* @copyright Copyright (c) 2016, Zeindelf
*/
class Badwords
{
//------------------------------------------------------------
// PUBLIC METHODS
//------------------------------------------------------------

/**
* Verifica se a palavra informada existe no filtro
*
* No parâmetro $extra, informe um array com as chaves
* 'badwords' e/ou 'ignored'. Como valor das chaves, informe-os
* em um array, como:
*
* $extra = [
* 'badwords' => ['palavraUm', 'palavraDois', ...],
* 'ignored' => ['palavraTres', 'palavraQuatro', ...],
* ];
*
* 'badwords' são palavras que deseja acrescentar ao filtro
* 'ignored' são palavras que serão ignoradas pelo filtro
*
* @param string $string Palavra a ser verificada
* @param array $extra Array com informações adicionais
* @return boolean
*/
public static function verify($string, array $extra = null)
{
require_once __DIR__ . '/Config/Filter.php';
$string = static::doubleChars($string);

$getFilter = Config::get('filter');

if ( !is_null($extra) ):
if ( array_key_exists('badwords', $extra) ):
$getFilter = array_merge($extra['badwords'], $getFilter);
endif;

if ( array_key_exists('ignored', $extra) ):
for ( $i = 0; $i < count($extra['ignored']); $i++ ):
$extra['ignored'][$i] = static::doubleChars($extra['ignored'][$i]);
endfor;

for ( $i = 0; $i < count($getFilter); $i++ ):
foreach ( $extra['ignored'] as $ignored ):
if ( is_int(strripos($ignored, $getFilter[$i])) ):
$arr[] = $i;
endif;
endforeach;
endfor;

if ( isset($arr) ):
foreach ( $arr as $a ):
unset($getFilter[$a]);
endforeach;
endif;
endif;
endif;

foreach ( $getFilter as $filter ):
if ( is_int(strripos($string, $filter)) ):
return true;
endif;
endforeach;

return false;
}

/**
* Retira ocorrências de caracteres rapetidos na string para verificação
*
* @param string $string String para verificação
* @return string String sem caracteres repetidos
*/
public static function doubleChars($string)
{
$string = static::unreadableString($string);

$letter = range('a', 'z');
$letter[] = '!';
$qntChar = 5;

for ( $i = 0; $i < count($letter); $i++ ):
for ( $j = 0; $j < $qntChar; $j++ ):
$repeat = str_repeat($letter[$i], $j);
$arrString = str_split($repeat);
endfor;

$arr[] = $arrString;
endfor;

for ( $i = 0; $i < count($arr); $i++ ):
for ( $j = 0; $j < count($arr[$i]); $j++ ):
$newRepeat[] = str_repeat($arr[$i][$j], $j + 1);
endfor;
endfor;

$doubleChar = array_chunk($newRepeat, $qntChar - 1);

for ( $i = 0; $i < count($doubleChar); $i++ ):
for ( $j = 1; $j <= 5; $j++ ):
$string = str_replace($doubleChar[$i], $letter[$i], $string);
endfor;
endfor;

return $string;
}

/**
* Converte caracteres especiais e números em letras associadas
*
* @param string $string String para ser convertida
* @param bool $lower Retorna em lowercase caso true
* @return string
*/
public static function unreadableString($string)
{
$arrString['special'] = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜüÝÞß@àáâãäåæç&èéêëìíîïðñòóôõöøùúûýýþÿ$°ºª';
$arrString['number'] = '0123456789';
$unreadable = $arrString['special'] . $arrString['number'];

$arrString['string'] = 'aaaaaaaceeeeiiiidnoooooouuuuuybbaaaaaaaaceeeeeiiiidnoooooouuuyybysooa';
$arrString['letters'] = 'oizeasbtbg';
$readable = $arrString['string'] . $arrString['letters'];

$string = strtr(utf8_decode($string), utf8_decode($unreadable), $readable);

return strtolower(utf8_encode($string));
}
}
Loading

0 comments on commit d454c88

Please sign in to comment.