Extensión: AbuseFilter
AbuseFilter Release status: estable |
|
---|---|
![]() |
|
Implementación | User activity , Special page , API |
Descripción | Permite establecer restricciones específicas basadas en determinadas actividades detectadas en un wiki. |
Autor(es) |
|
Política de compatibilidad | release branches |
MediaWiki | 1.33+ |
PHP | Se recomienda 5.4+ |
Cambios de la base de datos | Sí |
Tablas | abuse_filter abuse_filter_action abuse_filter_history abuse_filter_log |
Licencia | GNU General Public License 2.0 or later |
Descarga | |
|
|
|
|
|
|
Translate the AbuseFilter extension if it is available at translatewiki.net | |
Verificar uso y versión de la matriz. | |
Asuntos | Tareas abiertas · Reportar un bug |
La extensión AbuseFilter permite a los usuarios que dispongan de los permisos correspondientes establecer acciones específicas que deberán llevarse a cabo cuando un usuario realice una acción, por ejemplo, una edición, que coincida con determinados criterios.
Por ejemplo, podría crearse un filtro para evitar que usuarios anónimos añadan enlaces externos, o para bloquear automáticamente a un usuario que borre más de 2000 caracteres de una página.
Instalación
- Descarga y extrae los archivos en el directorio «
AbuseFilter
» dentro del directorioextensions/
existente. - Solo si bajaste esta extensión directamente desde git, ejecuta Composer para instalar las dependencias de PHP usando
composer install --no-dev
en el directorio de la extensión. (ver T173141 para complicaciones potenciales) - Añade el siguiente código a tu LocalSettings.php (preferiblemente al final):
wfLoadExtension( 'AbuseFilter' );
- Ejecuta el script de actualización, que creará automáticamente las tablas que necesita esta extensión en la base de datos.
- Configure as required.
- Hecho – Navega a Special:Version en tu wiki para verificar que la apariencia se haya instalado correctamente.
Para quienes usan MediaWiki 1.26 o versiones anteriores:
Estas instrucciones describen la nueva forma de instalar extensiones usando wfLoadExtension()
. Si necesitas instalar esta extensión en versiones anteriores (MediaWiki 1.26 y anteriores), debes usar lo siguiente en lugar de wfLoadExtension( 'AbuseFilter' );
:
require_once "$IP/extensions/AbuseFilter/AbuseFilter.php";
Configuración
Permisos de usuario
Una vez instalada la extensión, tendrás que configurar los permisos de usuario en "LocalSettings.php".
Permiso | Descripción |
---|---|
abusefilter-modify | Modificar filtros antiabusos |
abusefilter-view | Ver filtros antiabusos |
abusefilter-log | Ver el registro del filtro antiabusos |
abusefilter-log-detail | Ver entradas del registro detalladas del filtro antiabusos |
abusefilter-privatedetails | Ver datos privados en el registro del filtro antiabusos |
abusefilter-modify-restricted | Modificar filtros antiabusos con acciones restringidas |
abusefilter-modify-global | Crear o modificar filtros antiabusos globales. |
abusefilter-revert | Revertir todos los cambios realizados por un determinado filtro antiabusos |
abusefilter-view-private | Ver filtros antiabusos marcados como privados |
abusefilter-log-private | Ver las entradas del registro de filtros antiabusos marcadas como privadas |
abusefilter-hide-log | Ocultar entradas en el registro del filtro antiabusos |
abusefilter-hidden-log | Ver entradas ocultas en el registro del filtro antiabusos |
abusefilter-privatedetails-log | Ver el registro de acceso a datos privados del filtro antiabusos |
Por ejemplo, la siguiente configuración permitiría a los administradores hacer todo lo que quieran con AbuseFilter, y a todo el mundo ver el registro y la configuración de los filtros:
$wgGroupPermissions['sysop']['abusefilter-modify'] = true;
$wgGroupPermissions['*']['abusefilter-log-detail'] = true;
$wgGroupPermissions['*']['abusefilter-view'] = true;
$wgGroupPermissions['*']['abusefilter-log'] = true;
$wgGroupPermissions['sysop']['abusefilter-privatedetails'] = true;
$wgGroupPermissions['sysop']['abusefilter-modify-restricted'] = true;
$wgGroupPermissions['sysop']['abusefilter-revert'] = true;
Parameters
Nombre de variable | Valor predeterminado | Descripción |
---|---|---|
$wgAbuseFilterActions
|
[
'throttle' => true,
'warn' => true,
'disallow' => true,
'blockautopromote' => true,
'block' => true,
'rangeblock' => false,
'degroup' => true,
'tag' => true
]
|
Las posibles acciones que pueden realizar los filtros antiabusos. When adding a new action, check if it is restricted in $wgAbuseFilterRestrictions and, if it is, don't forget to add the abusefilter-modify-restricted right to the appropriate user groups.
|
$wgAbuseFilterConditionLimit
|
1000
|
El número máximo de 'condiciones' que se pueden usar cada vez que los filtros se aplican por haber habido un cambio. Los filtros más complejos necesitan más 'condiciones'. |
$wgAbuseFilterValidGroups
|
[
'default'
]
|
La lista de «grupos» en los que se pueden dividir los filtros. Por defecto, hay un solo grupo. Other extensions may add other groups. |
$wgAbuseFilterEmergencyDisableThreshold
|
[
'default' => 0.05
]
|
Desactivar un filtro si ha coincidido con más de 2 ediciones, constituyendo más del 5% de las acciones que fueron cotejadas con el grupo al que pertenece ese filtro durante el período "observado" (como mucho, un día), salvo que el filtro se haya cambiado en los últimos 86400 segundos (un día). See emergency throttling. |
$wgAbuseFilterEmergencyDisableCount
|
[
'default' => 2
]
| |
$wgAbuseFilterEmergencyDisableAge
|
[
'default' => 86400
]
| |
$wgAbuseFilterParserClass
|
'AbuseFilterParser'
|
Nombre de la clase de analizador de AbuseFilter. |
$wgAbuseFilterRestrictions
|
[
'block' => true,
'degroup' => true,
'blockautopromote' => true,
'rangeblock' => true
]
|
Los usuarios deberán contar con los permisos "abusefilter-modify-restricted" y "abusefilter-modify" para poder crear o modificar los filtros que llevan a cabo estas acciones. |
$wgAbuseFilterNotifications
|
false
|
Permite configurar la extensión para enviar notificaciones de coincidencias a Especial:CambiosRecientes o a UDP. Opciones disponibles: rc, udp, rcandudp |
$wgAbuseFilterNotificationsPrivate
|
false
|
Activar notificaciones para filtros privados. |
$wgAbuseFilterCentralDB
|
null
|
Nombre de una base de datos donde se guardarán los filtros globales antiabuso (esto sólo está soportado en la última versión, en desarrollo). |
$wgAbuseFilterIsCentral
|
false
|
Pon esta variable a TRUE para el wiki donde se guardan los filtros antiabuso globales (esto sólo está soportado en la última versión, en desarrollo). |
$wgAbuseFilterDisallowGlobalLocalBlocks
|
false
|
No permitir que los filtros centralizados realicen accciones que bloqueen, que eliminen usuarios de un grupo, o que revoquen permisos de forma local. |
$wgAbuseFilterBlockDuration
|
'indefinite'
|
Duración de los bloqueos instaurados por AbuseFilter.
Desde la versión 1.31.0-wmf.25, la duración del bloqueo se puede especificar por cada filtro único y sobreescribirá esta variable. This variable is only used when enabling the block in order to preselect a default duration.
|
$wgAbuseFilterAnonBlockDuration
|
null
|
Duración de los bloqueos instaurados por AbuseFilter para usuarios anónimos. Si no se indica un valor, se usará el valor de $wgAbuseFilterBlockDuration.
Desde la versión 1.31.0-wmf.25, la duración del bloqueo se puede especificar por cada filtro único y sobreescribirá esta variable. This variable is only used when enabling the block in order to preselect a default duration.
|
$wgAbuseFilterCustomActionsHandlers
|
[ ]
|
Funciones de llamada de vuelta para acciones personalizadas. |
$wgAbuseFilterDefaultWarningMessage | [
'default' => 'abusefilter-warning'
]
|
Mensajes de aviso predeterminados, por grupo de filtros. |
$wgAbuseFilterLogIPMaxAge
|
3 * 30 * 24 * 3600
|
Tiempo durante el que pueden alargarse los registros antes de eliminar vieja información de registros de IP. De forma predeterminada son 3 meses. El script de mantenimiento purgeOldLogIPData.php usa este valor. |
$wgAbuseFilterProfileActionsCap
|
10000
|
Number of action that determines when to reset profiling stats. |
$wgAbuseFilterLogPrivateDetailsAccess
|
false
|
Whether accessing private information from a filter log entry is logged. |
$wgAbuseFilterPrivateDetailsForceReason
|
false
|
Whether users are forced to provide a reason for accessing private information from a filter log entry. |
- Emergency throttling
AbuseFilter comes with a feature that automatically throttles (disable) filters that have been edited recently and match a certain theresold of the latest actions.
This is done to prevent harmful edits on the filters to block every user that performs an action on the wiki or similar.
The condition to disable the filter depend on those variables:
$wgAbuseFilterEmergencyDisableThreshold
- Percent of matches over the total amount of actions in the observed period.$wgAbuseFilterEmergencyDisableCount
- Count of matches of the filter in the observed period.$wgAbuseFilterEmergencyDisableAge
- Age of the filter to take it into account. If the last edit of the filter is older than this number of seconds, the filter won't be throttled, unless it's already throttled.$wgAbuseFilterProfileActionsCap
- Maximum number of recent actions to count against the threshold. Note that each action increments a counter, and once this counter reaches this configured value, this counter and the number of recent actions that matches all filters are reset to 0.
Throttled filters can be identified in the list of filters (Special:AbuseFilter) with the state Enabled, throttled. Throttling happens silently, and there's no way to see when a filter got throttled.
When a filter gets throttled, it doesn't perform any dangerous action (the ones specified in $wgAbuseFilterRestrictions
), and only "safe" actions are allowed. Throttled filters don't get enabled automatically. To disable the throttling, you need to edit the filter. Note that you need to actually change something from the filter: changing somethin from the filter's notes is sufficient.
Note that editing the filter updates its age, and can cause it to be disabled if it reaches again the conditions to be throttled in a short period since the last edit, leading to a unusable filter if your wiki has more abuse edits than legitimate ones. Filters can also get randomly throttled if the action count reaches $wgAbuseFilterProfileActionsCap
, causing all filter matches count to reset to 0, and then someone repeatedly makes a filter to hit.
Creando y administrando filtros
Una vez instalada la extensión, los filtros pueden ser creados/probados/cambiados/borrados y se puede acceder a los registros desde la página administrativa especial que añade la extensión: Especial:FiltroAntiAbusos.
- Formato de las reglas - Lo básico sobre cómo escribir un filtro
- Acciones
- Reglas globales
- Guía para optimizar el uso límite de la condición
- Para importar filtros de Wikipedia, una vez que hayas instalado la extensión dirígete a Especial:FiltroAntiAbusos, selecciona un filtro (por ejemplo, Especial:FiltroAntiAbusos/6), haz clic en "Exportar este filtro a otro wiki", copia el texto, vé a "Especial:FiltroAntiAbusos/importar" en tu wiki y pega el texto.
API
AbuseFilter añade dos módulos de lista a la API: uno con los detalles de los filtros antiabuso ("abusefilters"), y otro con el registro de abusos, ya que es independiente de otros registros de MediaWiki ("abuselog"). No es posible crear o modificar los filtros antiabusos usando la API.
list = abusefilters
Listar información acerca de los filtros.
- ;Parámetros
abfstartid
: El ID del filtro desde el que empezar a enumerarabfendid
: El ID del filtro con el que concluir la enumeraciónabfdir
: La dirección en la que enumerar (older, newer)abfshow
: Mostrar sólo los filtros que cumplan con estos criterios (enabled|!enabled|deleted|!deleted|private|!private)abflimit
: El número máximo de filtros a listarabfprop
: Propiedades a obtener (id|description|pattern|actions|hits|comments|lasteditor|lastedittime|status|private):abfstartid
- The filter id to start enumerating fromabfendid
- The filter id to stop enumerating atabfdir
- The direction in which to enumerate (older, newer)abfshow
- Show only filters which meet these criteria (enabled|!enabled|deleted|!deleted|private|!private)abflimit
- The maximum number of filters to listabfprop
- Which properties to get (id|description|pattern|actions|hits|comments|lasteditor|lastedittime|status|private)
Cuando los filtros sean privados, algunas de las propiedades especificadas con abfprop
faltarán, a menos que dispongas de los permisos de usuario adecuados.
- ;Ejemplos
Para listar los filtros antiabusos públicos:
list = abuselog
Listar los casos en los que las acciones hicieron saltar un filtro antiabuso.
- ;Parámetros
aflstart
: Fecha y hora desde la que empezar a enumeraraflend
: Fecha y hora en la que detener la enumeraciónafldir
: En qué dirección enumerar (older, newer)afluser
: Mostrar sólo los registros donde la acción fue intentada por un determinado usuario o dirección IPafltitle
: Mostrar sólo los registros donde se veía afectada una página en concretoaflfilter
: Mostrar sólo los registros que hicieron saltar un determinado ID de filtroafllimit
: Número máximo de registros a listaraflprop
: Qué propiedades obtener (ids|user|title|action|result|timestamp|details):aflstart
- The timestamp to start enumerating fromaflend
- The timestamp to stop enumerating atafldir
- The direction in which to enumerate (older, newer)afluser
- Show only entries where the action was attempted by a given user or IP address.afltitle
- Show only entries where the action involved a given page.aflfilter
- Show only entries that triggered a given filter IDafllimit
- The maximum number of entries to listaflprop
- Which properties to get (ids|user|title|action|result|timestamp|details)
- ;Ejemplo
Para listar los casos donde los filtros saltaron en respuesta a las acciones del usuario "SineBot":
Possible errors
- Some users might experience that creating new filters or modifying old filters fail and the user just gets redirected to the original page. If the Wiki is using SSL certificates, this error could possibly be because of the
$wgServer
value, which might be using "http://" instead of "https://". An indication of this error will be, the browser giving https warning for Special:AbuseFilter pages. (Topic:T23dyyih0ofjada5)
Integration with other extensions
You can integrate AbuseFilter with other extension in various ways.
Adding variables for filtering
It is possible to add new variables, to be used in abuse filters. A list of examples is available . To do that, you should:
- Add a handler for the AbuseFilter-builder hook. To add a variable, you should use
$builder['vars']['variable_name'] = 'i18n-key';
, wherevariable_name
is the name of the variable, andi18n-key
is the fragment of an i18n key. The full key will beabusefilter-edit-builder-vars-{$your_key}
. - Add the i18n messages you chose at the previous point.
- Choose a hook handler where the variable will be computed. Depending on your use case, you could:
- Implement the AbuseFilter-generateTitleVars hook; this is specifically thought for page-related variables;
- Implement the AbuseFilter-generateUserVars hook; this is specifically thought for user-related variables;
- Implement the AbuseFilter-generateStaticVars hook; this is specifically thought for "static" variables, i.e. variables whose value shouldn't depend on the context. This is rarely useful;
- Implement the AbuseFilterAlterVariables hook; this is a bit more flexible than the other hooks, but it has a downside: your variable will not be available when examining past RecentChanges entries. If you want to implement that feature (and it's recommended to do so), you should use one of the hooks listed above, and use its third parameter (
$RCRow
).
- Inside the hook handler, there are two ways to add a variable:
- The "direct" way is calling
$vars->setVar( 'var_name', var_value );
. This is ideal only when the value is easy and quick to compute: the value is computed even if no active filter will use it. - The "lazy" way is calling
$vars->setLazyLoadVar( 'var_name', 'method_name', $params );
. Here, 'method_name' is a (unique) identifier that will be used to compute the variable (it's recommended to prefix it with the name of your extension). To register the method, you should add a handler for the AbuseFilter-computeVariable hook; therein, you should check if the $method passed matches your 'method_name', and if so, compute the variable. Lastly, $params is an array of parameters that you'll need to compute the variable; these are passed to the computeVariable hook handler. For an example of this, you can check out CentralAuth'sglobal_user_groups
.
- The "direct" way is calling
Adding rule groups
You can also add extra rule groups, which can be used to group existing abuse filters. Note that, at the moment, each filter can only be in a single group (T116642). Currently, the only known consumer of this feature is Flow. To do that, you should:
- Append the name of the group to
$wgAbuseFilterValidGroups
- Add some code to run the filters with your group. Note that AbuseFilter won't do that on its own. To do that, you should construct an
AbuseFilterRunner
object, passing in the name of your group.
Véase también
- Varios wikis de la WMF donde está activada la extensión (y con qué configuración)
Esta extensión está siendo usada en uno o más proyectos de Wikimedia. Esto significa probablemente que la extensión es estable y funciona lo suficientemente bien como para ser usada en sitios con gran cantidad de visitas. Puedes buscar el nombre de esta extensión en los archivos CommonSettings.php e InitialiseSettings.php de Wikimedia para ver dónde se instala. Encontrarás la lista completa de extensiones instaladas en un wiki en particular en la página Special:Version del wiki. |