Extension:AbuseFilter/Rules format/ru

Правила представляют собой собственный язык. Они имеют формат, аналогичный условным выражениям в языках, подобных C/Java/Perl.

Литералы

Вы можете указать литерал, поместив его в одинарные или двойные кавычки (для строк) или введя его как есть (для чисел как с плавающей запятой, так и целых). Вы можете использовать разрывы строк с помощью \n, символ табуляции с помощью \t, а также использовать символ кавычки с обратным слешем.

Используйте символ + (плюс) для объединения (конкатенации) двух буквенных строк или значений двух переменных со строковым значением.

Примеры
"Это строка"
'Это также строка'
'Эта строка\' также верная'
"Эта строка\nИмеет перевод строки"
1234
1.234
-123

Пользовательские переменные

Вы можете определить пользовательские переменные для простоты понимания с помощью символа назначения := в строке (закрытой ;) в условии. Такие переменные могут использовать буквы, знаки подчёркивания и цифры (кроме первого символа) и нечувствительны к регистру. Например (для w:Special:AbuseFilter/79):

(
	line1:="(\{\{(r|R)eflist|\{\{(r|R)efs|<references\s?/>|</references\s?>)";
	rcount(line1, removed_lines)
) > (
	rcount(line1, added_lines)
)

Массивы

AbuseFilter поддерживает неассоциативные массивы, которые можно использовать как в следующих примерах.

Осторожно! Предупреждение: Такие выражения, как page_namespace in [14, 15], могут работать не так, как ожидалось. This one will evaluate to true also if page_namespace is 1, 4, or 5. Дополнительные сведения и возможные обходные пути см. T181024.
my_array := [ 5, 6, 7, 10 ];
my_array[0] == 5
length(my_array) == 4
int( my_array ) === 4 // Same as length
float( my_array ) === 4.0 // Считает элементы
string(my_array) == "5\n6\n7\n10\n" // Примечание: последний перенос строки может быть удалён в будущем.
5 in my_array == true
'5' in my_array == true
'5\n6' in my_array == true // Note: this is due to how arrays are cast to string, i.e. by imploding them with linebreaks
1 in my_array == true // Note: this happens because 'in' casts arguments to strings, so the 1 is caught in '10' and returns true.
my_array[] := 57; // Это добавляет элемент в конец массива
my_array === [ 5, 6, 7, 10, 57 ]
my_array[2] := 42; // А это для изменения элемента в массиве
my_array === [ 5, 6, 42, 10, 57 ]

Комментарии

Вы можете добавлять комментарии, используя следующий синтаксис:

/* Это комментарий */

Арифметические действия

Вы можете использовать основные арифметические символы для выполнения арифметических действий с переменными и литералами со следующим синтаксисом:

  • - Вычесть правый операнд из левого операнда.
  • + Сложить правый и левый операнды.
  • * Умножить левый операнд на правый операнд.
  • / Разделить левый операнд на правый операнд.
  • ** Возвести левый операнд в экспоненциальную степень, заданную правым операндом.
  • % Вернуть остаток от деления левого операнда на правый операнд.

Тип возвращаемого результата такой же, как у PHP, для которого можно найти много различных документаций (например). Более исчерпывающие примеры можно найти в этом тесте парсера AF.

Пример Результат
1 + 12
2 * 24
1 / 20.5
9 ** 281
6 % 51

Булевы операции

Вы можете выполнить сопоставление тогда и только тогда, когда из ряда условий все являются истинными либо только одно является истинным, или же когда одно и только одно из всех условий является истинным.

  • x | y OR возвращает true, если одно или несколько условий верны.
  • x & y AND возвращает true, если оба условия верны.
  • x ^ y XOR возвращает true, если одно и только одно из двух условий верно.
  • !x NOT возвращает true, если одно или несколько условий верны.

Примеры

Код Результат
1 | 1 true
1 | 0 true
0 | 0 false
1 & 1 true
1 & 0 false
0 & 0 false
1 ^ 1 false
1 ^ 0 true
0 ^ 0 false
!1 false
!0 true

Простые сравнения

Вы можете сравнить переменные с другими переменными и литералами со следующим синтаксисом:

  • <, > * true возвращает true, если левый операнд меньше/больше правого операнда соответственно. Watch out: operands are cast to strings and, like it happens in PHP, null < any number === true and null > any number === false.
  • <=, >= Return true if the left-hand operand is less than or equal to/greater than or equal to the right-hand operand respectively. Watch out: operands are cast to strings and, like it happens in PHP, null <= any number === true and null >= any number === false.
  • == (or =), != Return true if the left-hand operand is equal to/not equal to the right-hand operand respectively.
  • ===, !== Return true if the left-hand operand is equal to/not equal to the right-hand operand AND the left-hand operand is the same/not the same data type to the right-hand operand respectively.
Пример Результат
1 == 2false
1 <= 2true
1 >= 2false
1 != 2true
1 < 2true
1 > 2false
2 = 2true
'' == falsetrue
'' === falsefalse
1 == truetrue
1 === truefalse
['1','2','3'] == ['1','2','3']true
[1,2,3] === [1,2,3]true
['1','2','3'] == [1,2,3]true
['1','2','3'] === [1,2,3]false
[1,1,''] == [true, true, false]true
[] == false & [] == nulltrue
['1'] == '1'false[1]

Встроенные переменные

Фильтр злоупотреблений передаёт в синтаксический анализатор различные переменные по их именам. Доступ к этим переменным можно получить, введя их имя в том месте, где сработал бы литерал. Вы можете просмотреть переменные, связанные с каждым запросом, в журнале фильтра злоупотреблений.

Переменные AbuseFilter

Переменные, которые доступны всегда

Осторожно! Предупреждение: Переменные, связанные с пользователем, всегда доступны, за исключением одного случая: создание учётной записи, когда создатель не вошел в систему. Затрагиваются все переменные, начинающиеся с user_.
Описание Имя Тип данных Примечания
ДействиеactionстрокаОдно из следующего: edit, move, createaccount, autocreateaccount, delete, upload[2], stashupload[3]
Отметка времени изменения Unixtimestampстрокаint(timestamp) дает вам число, с помощью которого вы можете рассчитать дату, время, день недели и т. д.
Название базы данных вики ($1)wiki_nameстрокаНапример, это «enwiki» в английской Википедии и «itwikiquote» в итальянском Викицитатнике.
Языковой код вики ($1)wiki_languageстрокаНапример, это «en» в английской Википедии и «it» в итальянском Викицитатнике. Многоязычные вики, такие как Commons, Meta и Wikidata, также будут отображаться как «en».
Число правок участника ($1)user_editcountцелый/нулевойNull только для незарегистрированных участников.
Имя учётной записи ($1) (IP in case the user is not registered)user_nameстрока
Для действий "createaccount" и "autocreateaccount" используйте accountname, если вы хотите получить имя создаваемой учётной записи.
Осторожно! Предупреждение: On wikis where temporary accounts are enabled, IPs are not returned for unregistered users. Use user_unnamed_ip instead if the IP is needed. More context is available here .
Тип учётной записи участника ($1)user_typestring The type of the user, which will be one of ip, temp (if the user is using a temporary account), named, external, or unknown.
Время подтверждения адреса эл. почты ($1)user_emailconfirmстрока/нольВ формате: ГГГГММДДЧЧММСС. Null, если электронная почта не была подтверждена.
Возраст учётной записи ($1)user_ageцелое числоВ секундах. 0 для незарегистрированных участников.
Заблокирован ли участник ($1)user_blockedбулево значениеTrue для зарегистрированных участников, которые были заблокированы. Также true для правок, сделанных с заблокированных IP-адресов, даже если редактор является зарегистрированным участником, который не был заблокирован. False в противном случае.
Это не делает различий между частичными и полными блокировками.
Группы (включая неявные) в которых состоит участник ($1)user_groupsмассив строксм. Special:ListGroupRights
Права, которые есть у участника ($1)user_rightsмассив строксм. Special:ListGroupRights
ID страницы ($1)article_articleidцелое число(устарело) Вместо этого используйте page_id.
ID страницы ($1) (можно увидеть по ссылке «Информация о странице» на боковой панели)page_idцелое числоЭто значение равно нулю для новых страниц, но оно ненадёжно при проверке прошлых обращений Если при проверке прошлых обращений вам нужен точный результат, используйте «page_age == 0» для обозначения создания новой страницы. (хотя обратите внимание, что это работает медленнее) This issue has been fixed in 9369d08, merged on September 11th 2023.
Пространство имён страницы ($1)article_namespaceцелое число(устарело) Вместо этого используйте page_namespace.
Пространство имён страницы ($1)page_namespaceцелое числоссылается на индекс пространства имён Check for namespace(s) using expressions like "page_namespace == 2" or "equals_to_any(page_namespace, 1, 3)"
Возраст страницы (в секундах) ($1)page_ageцелое числоколичество секунд с момента первого редактирования (или 0 для новых страниц). Это надёжно, но работает медленнее; рассмотрите возможность использования page_id, если вам не нужна большая точность.
Название страницы (без пространства имён) ($1)article_textстрока(устарело) Вместо этого используйте page_title.
Название страницы (без пространства имён) ($1)page_titleстрока
Полное название страницы ($1)article_prefixedtextстрока(устарело) Вместо этого используйте page_prefixedtitle.
Полное название страницы ($1)page_prefixedtitleстрока
Уровень защиты страницы от правок ($1)article_restrictions_editстрока(устарело) Вместо этого используйте page_restrictions_edit.
Уровень защиты страницы от правок ($1)page_restrictions_editмассив строк
Уровень защиты страницы от переименований ($1)article_restrictions_moveстрока(устарело) Вместо этого используйте page_restrictions_move.
Уровень защиты страницы от переименований ($1)page_restrictions_moveмассив строк
Защита загрузки файла ($1)article_restrictions_uploadстрока(устарело) Вместо этого используйте page_restrictions_upload.
Защита загрузки файла ($1)page_restrictions_uploadмассив строк
Защита от создания страницы ($1)article_restrictions_createстрока(устарело) Вместо этого используйте page_restrictions_create.
Защита от создания страницы ($1)page_restrictions_createмассив строк
Последние десять редакторов страницы ($1)article_recent_contributorsarray of strings(устарело) Вместо этого используйте page_recent_contributors.
Последние десять редакторов страницы ($1)page_recent_contributorsмассив строкОбычно это работает медленно (см. #Performance). Попробуйте перед этим поместить условия, которые с большей вероятностью оцениваются как ложные, чтобы избежать ненужного запуска запроса. Это значение пусто, если пользователь является единственным автором страницы (?) и просматривает только последние 100 правок.
Первый сделавший свой вклад в страницу ($1)article_first_contributorстрока(устарело) Вместо этого используйте page_first_contributor.
Первый сделавший свой вклад в страницу ($1)page_first_contributorстрокаОбычно это работает медленно (см. #Performance).[4] Попробуйте перед этим поместить условия, которые с большей вероятностью оцениваются как ложные, чтобы избежать ненужного запуска запроса.

Переменные, доступные для некоторых действий

Осторожно! Предупреждение: Всегда проверяйте, доступны ли переменные, которые вы хотите использовать, для текущего фильтруемого действия, например, с помощью переменной action. В противном случае (например, с использованием accountname для редактирования или edit_delta для удаления) любой код, использующий рассматриваемую переменную, вернёт false.
Переменные редактирования недоступны при просмотре прошлых загрузок. (T345896)
Описание Имя Тип данных Примечания
Описание правки/причина ($1)summaryстрокаSummaries automatically created by MediaWiki ("New section", "Blanked the page", etc.) are created after the filter checks the edit, so they will never actually catch, even if the debugger shows that they should. The variable contains whatever the user sees in the edit summary window, which may include MediaWiki preloaded section titles.[5]
Была ли правка отмечена как «малое изменение» (больше не используется)minor_editstringDisabled, and set to false for all entries between 2016 and 2018.[6]
Вики-текст старой страницы до правки ($1)old_wikitextstringThis variable can be very large. Consider using removed_lines if possible to improve performance.
Вики-текст новой страницы после правки ($1)new_wikitextstringThis variable can be very large. Consider using added_lines if possible to improve performance.
Унифицированная разница изменений правки ($1)edit_diffstring
Унифицированный diff изменений в процессе редактирования, преобразованных перед сохранением ($1)edit_diff_pststringThis tends to be slow (see #Performance). Checking both added_lines and removed_lines is probably more efficient.[7]
Новый размер страницы ($1)new_sizeinteger
Старый размер страницы ($1)old_sizeinteger
Изменение размера в правке ($1)edit_deltainteger
Добавленные в правке строки ($1)added_linesarray of stringsincludes all lines in the final diff that begin with +
Удалённые в правке строки ($1)removed_linesarray of strings
Строчки, добавленные при редактировании, преобразованные перед сохранением ($1)added_lines_pstarray of stringsUse added_lines if possible, which is more efficient.
External links in the new text ($1)new_linksarray of stringsThis tends to be slow (see #Performance).
External links in the new text ($1)all_linksarray of strings(устарело) Use new_links instead.
Внешние ссылки на странице до правки ($1)old_linksarray of stringsThis tends to be slow (see #Performance).
Внешние ссылки, добавленные в правке ($1)added_linksarray of stringsThis tends to be slow (see #Performance). Consider checking against added_lines first, then check added_links so that fewer edits are slowed down. This follows MediaWiki's rules for external links. Only unique links are added to the array. Changing a link will count as 1 added and 1 removed link.
Внешние ссылки, удалённые в правке ($1)removed_linksarray of stringsThis tends to be slow (see #Performance). Consider checking against removed_lines first, then check removed_links so that fewer edits are slowed down. This follows MediaWiki's rules for external links. Only unique links are added to the array. Changing a link will count as 1 added and 1 removed link.
Вики-текст новой страницы, преобразованный перед сохранением ($1)new_pststringThis variable can be very large.
Разобранный HTML-код новой версии ($1)new_htmlstringThis variable can be very large. Consider using added_lines if possible to improve performance.
Новый текст страницы, очищенный от разметки ($1)new_textstringThis variable can be very large. Consider using added_lines if possible to improve performance.
Вики-текст старой страницы, преобразованный в HTML (больше не используется)old_htmlstringDisabled for performance reasons.
Текст старой страницы, лишённый разметки (больше не используется)old_textstringDisabled for performance reasons.
Время с момента последнего редактирования страницы (в секундах) ($1)page_last_edit_ageinteger or nullnull when the page does not exist
SHA1-хэш содержания файла ($1)file_sha1string[2]
Размер файла в байтах ($1)file_sizeintegerThe file size in bytes[2]
Ширина файла в пикселях ($1)file_widthintegerThe width in pixels[2]
Высота файла в пикселях ($1)file_heightintegerThe height in pixels[2]
Глубина цвета в файле ($1)file_bits_per_channelintegerThe amount of bits per color channel[2]
MIME-тип файла ($1)file_mimestringThe file MIME type.[2]
Медиа-тип файла ($1)file_mediatypestringThe file media type.[8][2]
ID целевой страницы переименования ($1)moved_to_articleidinteger(устарело) Use moved_to_id instead.
ID целевой страницы переименования ($1)moved_to_idinteger
Название целевой страницы переименования ($1)moved_to_textstring(устарело) Use moved_to_title instead.
Название целевой страницы переименования ($1)moved_to_titlestring
Полное название целевой страницы переименования ($1)moved_to_prefixedtextstring(устарело) Use moved_to_prefixedtitle instead.
Полное название целевой страницы переименования ($1)moved_to_prefixedtitlestring
Пространство имён целевой страницы переименования ($1)moved_to_namespaceinteger
Возраст целевой страницы при переименовании (в секундах) ($1)moved_to_ageinteger
Время с момента последнего изменения исходной страницы перемещения (в секундах) ($1)moved_to_last_edit_age integer or nullnull when the target page does not exist
Уровень защиты целевой страницы от редактирования ($1)moved_to_restrictions_editarray of stringSame as page_restrictions_edit, but for the target of the move.
Уровень защиты целевой страницы от переименования ($1)moved_to_restrictions_movearray of stringSame as page_restrictions_move, but for the target of the move.
Защита от загрузки целевой страницы ($1)moved_to_restrictions_uploadarray of stringSame as page_restrictions_upload, but for the target of the move.
Защита от создания целевой страницы при перемещении ($1)moved_to_restrictions_createarray of stringSame as page_restrictions_create, but for the target of the move.
Последние десять участников, редактировавших целевую страницу ($1)moved_to_recent_contributorsarray of stringsSame as page_recent_contributors, but for the target of the move.
Первый участник в целевой странице ($1)moved_to_first_contributorstringSame as page_first_contributor, but for the target of the move.
Пространство имён переименовываемой страницы ($1)moved_from_namespaceinteger
Название переименовываемой страницы ($1)moved_from_textstring(устарело) Use moved_from_title instead.
Название переименовываемой страницы ($1)moved_from_titlestring
Полное название переименовываемой страницы ($1)moved_from_prefixedtextstring(устарело) Use moved_from_prefixedtitle instead.
Полное название переименовываемой страницы ($1)moved_from_prefixedtitlestring
ID переименовываемой страницы ($1)moved_from_articleidinteger(устарело) Use moved_from_id instead.
ID переименовываемой страницы ($1)moved_from_idinteger
Возраст исходной страницы при переименовании в секундах ($1)moved_from_ageinteger
Время с момента последнего изменения исходной страницы перемещения в секундах ($1)moved_from_last_edit_ageinteger
Уровень защиты от редактирования для страницы-источника ($1)moved_from_restrictions_editarray of stringSame as page_restrictions_edit, but for the page being moved.
Уровень защиты от переименования для страницы-источника ($1)moved_from_restrictions_movearray of stringSame as page_restrictions_move, but for the page being moved.
Защита при загрузке файла, который переносится ($1)moved_from_restrictions_uploadarray of stringSame as page_restrictions_upload, but for the page being moved.
Защита от создания исходной страницы при перемещении ($1)moved_from_restrictions_createarray of stringSame as page_restrictions_create, but for the page being moved.
Последние десять участников, редактировавших страницу, которая перемещается ($1)moved_from_recent_contributorsarray of stringsSame as page_recent_contributors, but for the page being moved.
Первый участник в исходной переименованной странице ($1)moved_from_first_contributorstringSame as page_first_contributor, but for the page being moved.
Имя учётной записи (при создании учётной записи) ($1)accountnamestring
Content model of the old revision old_content_model string See Help:ChangeContentModel for information about content model changes
Content model of the new revision new_content_model string See Help:ChangeContentModel for information about content model changes

Protected variables

A variable can be considered protected. For instance, on wikis with temporary accounts enabled, IPs are considered PII and access to them must be restricted. Protected variables and filters that use them (including the logs they create) are only accessible to maintainers with the abusefilter-access-protected-vars right. Using a protected variable flags the filter as protected as well. The filter subsequently cannot be unprotected, even if it no longer actively uses a protected variable, as its historical logs will remain available.

A private log is created when a filter maintainer views the value of a protected variable. This private log is not an abuse filter log. It is a private log only viewable to users with the abusefilter-protected-vars-log right and is stored at Special:Log/abusefilter-protected-vars.

The default protected variables are defined in AbuseFilterProtectedVariables in extension.json.

user_unnamed_ip is null when examining past edits.
Description Name Data type Notes
IP of the user account (for logged-out users and temporary accounts only) ($1)user_unnamed_ip string User IP for anonymous users/temporary accounts
This returns null for registered users.
If the CheckUser extension is installed, then the user must also have access to the IP addresses of temporary accounts.This access is described at Help:Extension:CheckUser#Showing_IPs_for_temporary_accounts.

Variables from other extensions

Most of these variables are always set to false when examinating past edits, and may not reflect their actual value at the time the edit was made. See T102944.
Description Name Data type Values Added by Notes
Глобальные группы участника ($1) global_user_groups array CentralAuth
Global edit count of the user ($1) global_user_editcount integer CentralAuth
Global groups that the user is in on account creation ($1) global_account_groups array Available only when action is createaccount (then it is always empty) or autocreateaccount. CentralAuth
Global edit count of the user on account creation ($1) global_account_editcount integer Available only when action is createaccount (then it is always zero) or autocreateaccount. CentralAuth
OAuth-клиент, использованный для внесения правок ($1) oauth_consumer integer OAuth
Идентификатор страницы доски «Структурированных обсуждений» board_articleid integer (устарело) Use board_id instead. StructuredDiscussions
Идентификатор страницы доски «Структурированных обсуждений» board_id integer StructuredDiscussions
Пространство имён доски «Структурированных обсуждений» board_namespace integer refers to namespace index StructuredDiscussions
Заголовок (без пространства имён) доски «Структурированных обсуждений» board_text string (устарело) Use board_title instead. StructuredDiscussions
Заголовок (без пространства имён) доски «Структурированных обсуждений» board_title string StructuredDiscussions
Полный заголовок доски «Структурированных обсуждений» ($1) board_prefixedtext string (устарело) Use board_prefixedtitle instead. StructuredDiscussions
Полный заголовок доски «Структурированных обсуждений» ($1) board_prefixedtitle string StructuredDiscussions
Исходный текст единицы перевода ($1) translate_source_text string Перевод
Целевой язык для перевода ($1) translate_target_language string This is the language code, like en for English. Перевод
Была ли правка сделана через выходной узел сети Tor ($1) tor_exit_node boolean true if the action comes from a tor exit node. TorBlock
Редактирует ли участник через мобильный интерфейс ($1) user_mobile boolean true for mobile users, false otherwise. MobileFrontend
Редактирует ли пользователь через мобильное приложение ($1) user_app boolean true if the user is editing from the mobile app, false otherwise. MobileApp
Page views article_views integer (устарело) Use page_views instead. HitCounters
Page views page_views integer the amount of page views HitCounters
Source page views moved_from_views integer the amount of page views of the source page HitCounters
Target page views moved_to_views integer the amount of page views of the target page HitCounters
Whether the IP address is blocked using the stopforumspam.com list sfs_blocked boolean Whether the IP address is blocked using the stopforumspam.com list StopForumSpam
Whether the IP being used by the user is known by the IPoid service ($1) ip_reputation_ipoid_known boolean For information about this variable see Extension:IPReputation/AbuseFilter_variables. IPReputation Protected variable
Number of clients associated with IP being used by the user ($1) ip_reputation_client_count integer For information about this variable see Extension:IPReputation/AbuseFilter_variables. IPReputation Protected variable
List of behaviors associated with the IP being used by the user ($1) ip_reputation_client_behaviors array For information about this variable see Extension:IPReputation/AbuseFilter_variables. IPReputation Protected variable
List of proxy services associated with IP being used by the user ($1) ip_reputation_client_proxies array For information about this variable see Extension:IPReputation/AbuseFilter_variables. IPReputation Protected variable
List of risks associated with the IP being used by the user ($1) ip_reputation_risk_types array For information about this variable see Extension:IPReputation/AbuseFilter_variables. IPReputation Protected variable
List of tunnel operators associated with the IP being used by the user ($1) ip_reputation_tunnel_operators array For information about this variable see Extension:IPReputation/AbuseFilter_variables. IPReputation Protected variable

Notes

When action='move', only the summary, action, timestamp and user_* variables are available. The page_* variables are also available, but the prefix is replaced by moved_from_ and moved_to_, that represent the values of the original article name and the destination one, respectively. For example, moved_from_title and moved_to_title instead of page_title.

Since MediaWiki 1.28 (gerrit:295254), action='upload' is only used when publishing an upload, and not for uploads to stash. A new action='stashupload' is introduced, which is used for all uploads, including uploads to stash. This behaves like action='upload' used to, and only provides file metadata variables (file_*). Variables related to the page edit, including summary, new_wikitext and several others, are now available for action='upload'. For every file upload, filters may be called with action='stashupload' (for uploads to stash), and are always called with action='upload'; they are not called with action='edit'.

Filter authors should use action='stashupload' | action='upload' in filter code when a file can be checked based only on the file contents – for example, to reject low-resolution files – and action='upload' only when the wikitext parts of the edit need to be examined too – for example, to reject files with no description. This allows tools that separate uploading the file and publishing the file (e.g. UploadWizard or upload dialog) to inform the user of the failure before they spend the time filling in the upload details.

Performance

As noted in the table above, some of these variables can be very slow. While writing filters, remember that the condition limit is not a good metric of how heavy filters are. For instance, variables like *_recent_contributors or *_links always need a DB query to be computed, while *_pst variables will have to perform parsing of the text, which again is a heavy operation; all these variables should be used very, very carefully. For instance, on Italian Wikipedia it's been observed that, with 135 active filters and an average of 450 used conditions, filters execution time was around 500ms, with peaks reaching 15 seconds. Removing the added_links variable from a single filter, and halving the cases when another filter would use added_lines_pst brought the average execution time to 50ms. More specifically:

  • Use _links variables when you need high accuracy and checking for "http://..." in other variables (for instance, added_lines) could lead to heavy malfunctioning;
  • Use _pst variables when you're really sure that non-PST variables aren't enough.

You may also conditionally decide which one to check: if, for instance, you want to examine a signature, check first if added_lines contains ~~~;

  • In general, when dealing with these variables, it's always much better to consume further conditions but avoid computing heavy stuff.

In order to achieve this, always put heavy variables as last conditions.

Last but not least, note that whenever a variable is computed for a given filter, it'll be saved and any other filter will immediately retrieve it. This means that one single filter computing this variable counts more or less as dozens of filters using it.

Keywords

Where not specifically stated, keywords cast their operands to strings

The following special keywords are included for often-used functionality:

  • like (or matches) returns true if the left-hand operand matches the glob pattern in the right-hand operand.
  • in returns true if the right-hand operand (a string) contains the left-hand operand. Note: empty strings are not contained in, nor contain, any other string (not even the empty string itself).
  • contains works like in, but with the left and right-hand operands switched. Note: empty strings are not contained in, nor contain, any other string (not even the empty string itself).
  • rlike (or regex) and irlike return true if the left-hand operand matches (contains) the regex pattern in the right-hand operand (irlike is case insensitive).
    • The system uses PCRE.
    • The only PCRE option enabled is PCRE_UTF8 (modifier u in PHP); for irlike both PCRE_CASELESS and PCRE_UTF8 are enabled (modifier iu).
  • if ... then ... end
  • if ... then ... else ... end
  • ... ? ... : ...
  • true, false, null

Examples

Code Result Comment
"1234" like "12?4" True
"1234" like "12*" True
"foo" in "foobar" True
"foobar" contains "foo" True
"o" in ["foo", "bar"] True Due to the string cast
"foo" regex "\w+" True
"a\b" regex "a\\\\b" True To look for the escape character backslash using regex you need to use either four backslashes or two \x5C. (Either works fine.)
"a\b" regex "a\x5C\x5Cb" True

Functions

A number of built-in functions are included to ease some common issues. They are executed in the general format functionName( arg1, arg2, arg3 ), and can be used in place of any literal or variable. Its arguments can be given as literals, variables, or even other functions.

namedescription
lcaseReturns the argument converted to lower case.
ucaseReturns the argument converted to upper case.
lengthReturns the length of the string given as the argument. If the argument is an array, returns its number of elements.
stringCasts to string data type. If the argument is an array, implodes it with linebreaks.
intCasts to integer data type.
floatCasts to floating-point data type.
boolCasts to boolean data type.
normEquivalent to rmwhitespace(rmspecials(rmdoubles(ccnorm(arg1)))).
ccnorm Normalises confusable/similar characters in the argument, and returns a canonical form. A list of characters and their replacements can be found on git, e.g. ccnorm( "Eeèéëēĕėęě3ƐƷ" ) === "EEEEEEEEEEEEE".[9] The output of this function is always uppercase. While not expensive, this function isn't cheap either, and could slow a filter down if called many times.
ccnorm_contains_any Normalises confusable/similar characters in all its arguments, and returns true if the first string contains any string from the following arguments (unlimited number of arguments, logic OR mode). A list of characters and their replacements can be found on git. Due to the usage of ccnorm, this function can be slow if passed too many arguments.
ccnorm_contains_all Normalises confusable/similar characters in all its arguments, and returns true if the first string contains every string from the following arguments (unlimited number of arguments, logic AND mode). A list of characters and their replacements can be found on git. Due to the usage of ccnorm, this function can be slow if passed too many arguments.
specialratioReturns the number of non-alphanumeric characters divided by the total number of characters in the argument.
rmspecialsRemoves any special characters in the argument, and returns the result. Does not remove whitespace. (Equivalent to s/[^\p{L}\p{N}\s]//g.)
rmdoublesRemoves repeated characters in the argument, and returns the result.
rmwhitespaceRemoves whitespace (spaces, tabs, newlines).
countReturns the number of times the needle (first string) appears in the haystack (second string). If only one argument is given, splits it by commas and returns the number of segments.
rcount Similar to count but the needle uses a regular expression instead. Can be made case-insensitive by letting the regular expression start with "(?i)". Please note that, for plain strings, this function can be up to 50 times slower than count[10], so use that one when possible.
get_matches MW 1.31+ Looks for matches of the regex needle (first string) in the haystack (second string). Returns an array where the 0 element is the whole match and every [n] element is the match of the n'th capturing group of the needle. Can be made case-insensitive by letting the regular expression start with "(?i)". If a capturing group didn't match, that array position will take value of false.
ip_in_rangeReturns true if user's IP (first string) matches the specified IP range (second string, can be in CIDR notation, explicit notation like "1.1.1.1-2.2.2.2", or a single IP). Only works for anonymous users. Supports both IPv4 and IPv6 addresses.
ip_in_rangesReturns true if user's IP (first string) matches any of the specified IP ranges (following strings in logic OR mode, can be in CIDR notation, explicit notation like "1.1.1.1-2.2.2.2", or a single IP). Only works for anonymous users. Supports both IPv4 and IPv6 addresses.
contains_anyReturns true if the first string contains any string from the following arguments (unlimited number of arguments in logic OR mode). If the first argument is an array, it gets cast to string.
contains_allReturns true if the first string contains every string from the following arguments (unlimited number of arguments in logic AND mode). If the first argument is an array, it gets cast to string.
equals_to_anyReturns true if the first argument is identical (===) to any of the following ones (unlimited number of arguments). Basically, equals_to_any(a, b, c) is the same as a===b | a===c, but more compact and saves conditions.
substrReturns the portion of the first string, by offset from the second argument (starts at 0) and maximum length from the third argument (optional).
strlenSame as length.
strpos Returns the numeric position of the first occurrence of needle (second string) in the haystack (first string), starting from offset from the third argument (optional, default is 0). This function may return 0 when the needle is found at the beginning of the haystack, so it might be misinterpreted as false value by another comparative operator. The better way is to use === or !== for testing whether it is found. Differently from PHP's strpos(), which returns false when the needle is not found, this function returns -1 when the needle is not found.
str_replaceReplaces all occurrences of the search string with the replacement string. The function takes 3 arguments in the following order: text to perform the search on, text to find, replacement text.
str_replace_regexpReplaces all occurrences of the search string with the replacement string using regular expressions. The function takes 3 arguments in the following order: text to perform the search on, regular expression to match, replacement expression.
rescapeReturns the argument with some characters preceded with the escape character "\", so that the string can be used in a regular expression without those characters having a special meaning.
setSets a variable (first string) with a given value (second argument) for further use in the filter. Another syntax: name := value.
set_varSame as set.

Examples

Code Result Comment
length( "Wikipedia" ) 9
lcase( "WikiPedia" ) wikipedia
ccnorm( "w1k1p3d14" ) WIKIPEDIA ccnorm output is always uppercase
ccnorm( "ωɨƙɩᑭƐƉ1α" ) WIKIPEDIA
ccnorm_contains_any( "w1k1p3d14", "wiKiP3D1A", "foo", "bar" ) true
ccnorm_contains_any( "w1k1p3d14", "foo", "bar", "baz" ) false
ccnorm_contains_any( "w1k1p3d14 is 4w3s0me", "bar", "baz", "some" ) true
ccnorm( "ìíîïĩїį!ľ₤ĺľḷĿ" ) IIIIIII!LLLLLL
norm( "!!ω..ɨ..ƙ..ɩ..ᑭᑭ..Ɛ.Ɖ@@1%%α!!" ) WIKIPEDAIA
norm( "F00 B@rr" ) FOBAR norm removes whitespace, special characters and duplicates, then uses ccnorm
rmdoubles( "foobybboo" ) fobybo
specialratio( "Wikipedia!" ) 0.1
count( "foo", "foofooboofoo" ) 3
count( "foo,bar,baz" ) 3
rmspecials( "FOOBAR!!1" ) FOOBAR1
rescape( "abc* (def)" ) abc\* \(def\)
str_replace( "foobarbaz", "bar", "-" ) foo-baz
str_replace_regexp( "foobarbaz", "(.)a(.)", "$2a$1" ) foorabzab
ip_in_range( "127.0.10.0", "127.0.0.0/12" ) true
ip_in_ranges( "127.0.10.0", "10.0.0.0/8", "127.0.0.0/12" ) true
contains_any( "foobar", "x", "y", "f" ) true
get_matches( "(foo?ba+r) is (so+ good)", "fobaaar is soooo good to eat" ) ['fobaaar is soooo good', 'fobaaar', 'soooo good']

Order of operations

Operations are generally done left-to-right, but there is an order to which they are resolved. As soon as the filter fails one of the conditions, it will stop checking the rest of them (due to short-circuit evaluation) and move on to the next filter. The evaluation order is:

  1. Anything surrounded by parentheses (( and )) is evaluated as a single unit.
  2. Turning variables/literals into their respective data. (e.g., page_namespace to 0)
  3. Function calls (norm, lcase, etc.)
  4. Unary + and - (defining positive or negative value, e.g. -1234, +1234)
  5. Keywords (in, rlike, etc.)
  6. Boolean inversion (!x)
  7. Exponentiation (2**3 → 8)
  8. Multiplication-related (multiplication, division, modulo)
  9. Addition and subtraction (3-2 → 1)
  10. Comparisons (<, >, ==)
  11. Boolean operations (&, |, ^)
  12. Ternary operator (... ? ... : ...)
  13. Assignments (:=)

Examples

  • A & B | C is equivalent to (A & B) | C, not to A & (B | C). In particular, both false & true | true and false & false | true evaluates to true.
  • A | B & C is equivalent to (A | B) & C, not to A | (B & C). In particular, both true | true & false and true | false & false evaluates to false.
  • added_lines rlike "foo" + "|bar" is wrong, use added_lines rlike ("foo" + "|bar") instead.

Condition counting

The condition limit is (more or less) tracking the number of comparison operators + number of function calls entered.

Further explanation on how to reduce conditions used can be found at Extension:AbuseFilter/Conditions.

Exclusions

Although the AbuseFilter examine function will identify "rollback" actions as edits, the AbuseFilter will not evaluate rollback actions for matching.[11]

Notes

  1. Сравнение массивов с другими типами всегда будет возвращать false, за исключением примера выше.
  2. 1 2 3 4 5 6 7 8 Единственные переменные, доступные в настоящее время для загрузки файлов (action='upload'), — это user_*, page_*, file_sha1, file_size, file_mime, file_mediatype, file_width, file_height, file_bits_per_channel (последние пять были добавлены только в MediaWiki 1.27 gerrit:281503). Все переменные file_* недоступны для других действий (включая action='edit').
  3. Начиная с MediaWiki 1.28 (gerrit:295254)
  4. Several filters (12) that use this variable have showed up in the AbuseFilterSlow Grafana dashboard (requires logstash access to view). Может помочь перемещение этой переменной ближе к концу фильтра.
  5. See phabricator:T191722
  6. Deprecated with this commit and disabled with this one.
  7. Some filters using this variable have showed up in the AbuseFilterSlow Grafana dashboard (example, requires logstash access). For instance, instead of using "text" in edit_diff_pst (or even edit_diff), consider something like "text" in added_lines & !("text" in removed_lines)
  8. See the source code for a list of types.
  9. Be aware of phab:T27619. You can use Special:AbuseFilter/tools to evaluate ccnorm( "your string" ) to see which characters are transformed.
  10. https://3v4l.org/S6IGP
  11. T24713 - rollback not matched by AF