Перейти до вмісту

Вікіпедія:Обмеження шаблонів

Матеріал з Вікіпедії — вільної енциклопедії.

Програмне забезпечення MediaWiki, яке забезпечує роботу Вікіпедії, має кілька параметрів, що обмежують складність сторінки та кількість даних, які можна включити. Ці обмеження в основному пов'язані з даними, які включаються або підставляються під час розкриття сторінки на противагу даним, які напряму використані в коді самої сторінки. Ця сторінка пояснює як і чому ці обмеження застосовуються і як користовувачі можуть працювати в межах цих обмежень.

Загальний огляд

[ред. код]

Про що це?

[ред. код]

Програмне забезпечення MediaWiki, яке створює HTML сторінки з його вікікоду, використовує парсер, щоб опрацьовувати включені дані. Це робиться, використовуючи «передобробник» (англ. preprocessor), який перетвороює вікітекст у структури даних, відомі як дерево XML, а потім використовує це дерево, щоб створити «розкритий» вікітекст, де дво- та трисклепінні структури замінені на їхній результат.

Під час процесу перетворення, програмне забезпечення використовує кілька лічильників, щоб відстежувати складність сторінки, яка створюється. Коли парсинг сторінки починається, то ці лічильники дорівнюють нулю, але під час процесу парсингу вони інкрементуються, як описано вище. Є верхнє обмеження для цих лічильників, і парсер не дозволяє виходити за ці межі.

Чому є обмеження?

[ред. код]

Дуже довгі або складні сторінки повільно парсуються. Це не лище незручнімть для користувачів, а також може бути використовно для запуску атаки на відмову в обслуговуванні (DoS-атаки) на сервери, при якій сторінка робить запит, що змушує програмне забезпечення MediaWiki парсувати недоречно велику кількість даних. Обмження допомагають запобігти цим видам атак та забезпечують відображення сторінок за доречний час. (Однак, іноді складні сторінки в межах обмежень видають помилку тайм-ауту; це залежить від того, як завантажені сервери.)

Working within the limits

[ред. код]

When a page reaches the template limits, the most common solution is to make the templates shorter, using methods described below. If this isn't possible, it may be necessary to include more data directly in the page source, rather than transcluding it from templates (e.g., formatting references by hand or using <references /> instead of {{Reflist}}). On the other hand, a template can help the server avoid doing duplicate work, see below.

When do problems arise?

[ред. код]
Див. також: Help:Template#Expand limits

The inclusion limits are most commonly reached on pages that use the same template many times, for example using one transclusion per row of a long table. Even though the amount of data that the template adds to the final page may be small, it is counted each time the template is used, and so the limit may be encountered sooner than expected. Pages that only include a few dozen templates are unlikely to exceed the inclusion limits, unless these templates themselves include a lot of data.

How can you find out?

[ред. код]

Once the page body is processed, an HTML comment is added towards the end of the HTML code of the page with the final values of the various counters. For example, the page HIV/AIDS (on January 1, 2024) contains the following comment in its generated HTML source:

<!-- 
NewPP limit report
Parsed by mw‐web.eqiad.main‐d976f4d78‐dn5sb
Cached time: 20251016210947
Cache expiry: 2592000
Reduced expiry: false
Complications: [vary‐revision‐sha1, show‐toc]
CPU time usage: 2.718 seconds
Real time usage: 3.084 seconds
Preprocessor visited node count: 22714/1000000
Revision size: 219436/2097152 bytes
Post‐expand include size: 953824/2097152 bytes
Template argument size: 11844/2097152 bytes
Highest expansion depth: 15/100
Expensive parser function count: 42/500
Unstrip recursion depth: 1/20
Unstrip post‐expand size: 1369326/5000000 bytes
Lua time usage: 1.640/10.000 seconds
Lua memory usage: 22826184/52428800 bytes
Number of Wikibase entities loaded: 1/500
-->
<!--
Transclusion expansion time report (%,ms,calls,template)
100.00% 2560.861      1 -total
 61.06% 1563.754      1 Template:Reflist
 30.06%  769.671    175 Template:Cite_journal
 12.13%  310.653     74 Template:Cite_web
  8.44%  216.167     13 Template:Navbox
  6.91%  177.039     42 Template:Cite_book
  6.26%  160.248      1 Template:Medical_resources
  5.01%  128.211      2 Template:Hlist
  3.76%   96.295      2 Template:Short_description
  3.56%   91.196      1 Template:Subject_bar
-->
<!-- Saved in parser cache with key enwiki:pcache:5069516:|#|:idhash:thumbsize=4 and timestamp 20251016210947 and revision id 1316019162. Rendering was triggered because: page_view
 -->

(Some items may not be present on other wikis, depending on which extensions they have installed; for example, the "Lua" items are added by Extension:Scribunto.)

Because of the way the counters are increased, the preprocessor visited node count, post-expand include size, and template argument size will usually be less than their limits. If any of these items are close to their limit, then it is likely that some of the templates have not been expanded. Each occurrence of an unexpanded template is identified in the page body by an HTML comment containing an error message.

Click "Parser profiling data" at the bottom of a preview to see similar data for the preview without saving it.

Розкриття

[ред. код]

Templates in non-executed branches of conditional parser functions are not expanded, and therefore not counted. For example, in the code {{#if:yes|{{bar}}|{{foo}}}}, the template {{bar}} is expanded, but the template {{foo}} is not expanded. Nevertheless, it is possible for a template argument to contribute to the counts even though it does not appear in the final output. For example, if the code {{#if:{{foo}}|yes|no}} is parsed, the length of the expanded version of template {{foo}} will be added to the post-expand counter, because that template must be expanded to decide which branch of the conditional should be selected.

Preprocessor node count

[ред. код]
Див. також: mw:Manual:$wgMaxPPNodeCount

The preprocessor node count measures the complexity of the page (not the volume of data). As the parser is expanding a page, it creates a data structure known as a tree that corresponds to the HTML structure of the page. Each node of the tree that is visited during expansion is counted towards the preprocessor node count. If this count is exceeded, the parser will abort parsing with the error "Node-count limit exceeded" visible in the generated HTML.

The count starts with 1 for plain text. A pair of nowiki tags counts for 3, a header for 2, etc. A link does not contribute to the count. For the expansion of #switch every checked condition adds 2 to the count. In the case of multiple expansions of the same template the content of a template without arguments counts only once, but that of a template with arguments (even if constant) counts multiple times. In contrast to this, the result of an expansion can be used multiple times while counting only once if it is assigned to a template parameter, and that template has multiple uses of this parameter.

Pages exceeding this limit are automatically categorized into Category:Pages where node count is exceeded (recent additions).

Розмір розкритих включень

[ред. код]

Розмір розкритих включень — це сума довжини розкритого вікітексту, який створено шаблонами, парсерними функціями та змінними. When the parser is instructed by the source code of a page to expand a template etc. (that is, to replace it by transclusion or substitution), the parser adds together the length of the expanded wikitext generated by the template etc. and the current counter value of the page. If this sum is more than the post-expand limit (same as the max article size limit; see $wgMaxArticleSize), the initial template etc. is not replaced and an error message is added as a comment in the output HTML. Otherwise the post-expand counter is increased to the new value, and parsing continues. A template that is expanded more than once in the page contributes more than once to its post-expand include size.

Template invocations with no arguments have an expanded text cache. So if {{foo}} includes the second-level meta-template {{bar}}, then multiple invocations of {{foo}} will only increment the post-expand include size for the fully-expanded {{foo}}; the secondary inclusion {{bar}} is only counted once. But if you included the same template multiple times with {{foo|arg}}, then the secondary templates are counted each time, even if the argument is the same.

Pages exceeding the post-expand include size limit are automatically added to Category:Сторінки з перевищеним розміром включених шаблонів (recent additions). Template:Citations broken from PEIS limit may be manually added to the page when citations or templates are broken as a result of the issue.

Using comments, noinclude and onlyinclude

[ред. код]

Only data that survives the preprocessor expansion stage is counted towards the post-expand counter. The length of HTML comments in the wikitext (which are not reproduced in the HTML source produced) is not included in the post-expand counter. Code which is either inside a <noinclude> section or outside an <onlyinclude> section does not get expanded, so these sections do not contribute to the post-expand size. This also means that category tags only contribute if they are included (to categorize pages calling the template).

Nested transclusions

[ред. код]

Note that the sizes of the wikitexts of all expanded templates and parser functions are added, even in the case of nesting (see phab:T15260), so extra levels increase the count. If page A transcludes B and B does nothing but transclude C, then the size of C will be counted twice towards the post-expand include size on page A, and similarly if a template consists of a parser function call, or a parser function has a template call as parameter, etc. Possible substitutions to reduce nesting include:

  • {{#if:{{{test|}}}|{{template1}}|{{template2}} }} replaced with {{ {{#if:{{{test|}}}|template1|template2}} }}.
  • {{navboxes}} replaced with {{navboxes top}} and {{navboxes bottom}}
  • {{trim}} replaced with {{#ifШаблон:Colon1|...}}
  • {{Episode table|episodes=...}} -> {{episode table|dontclose=y}} ... {{End|html=y|Episode table}}

Non-rendered transclusions

[ред. код]

Non-rendered tranclusions still count towards limit. For example, a page which contains only {{#if:{{:Main Page}}}} would still have a post-expand include size even though it would have no output at all.

The same applies to Scribunto modules. For example, {{#invoke:Test|main}} would still increase post-expand include size even if Module:Test were simply:

mw.getCurrentFrame():preprocess'{{msgnw::Main Page}}' -- remove this line and post-expand include size becomes zero
return { main = function() end } -- p.main() has no return value

Синтаксис #invoke

[ред. код]

Деякі шаблони мають еквівалентні модулі Lua, які можна включати, використавши синтаксис #invoke:назва модуля. Це має менше РРВ ніж використовувати шаблон, який огортає той модуль Lua. Однак, якщо використати напряму у статті, то є погіршення читабельності (та редагування) коду статті, тому це не бажано робити, якщо це не життєво необхідно. До них входять:

Примітки

[ред. код]

Pages may exceed the limit when trying to display references using the {{reflist}} template. Replacing it with <references /> may allow the references to appear, although the list may be truncated if the limit is exceeded by templates such as {{cite web}}. As of 2010, the tag has the same font styling as {{reflist}}, and as of 2017 it allows for responsive columns.

Розділення статей

[ред. код]

Ideally the length of articles would be determined by content-related decisions not technical issues. However, if PEIS issues are unresolvable on an article such as a long list, it may be split into sections which each fit within the limit, following the policy at WP:SPLIT.

Template argument size

[ред. код]

The template argument size counter keeps track of the total length of template arguments that have been substituted. Its limit is the same as the article size limit.

Example:

{{3x|{{2x|abcde}}}} has a template argument size of 40 bytes: the argument Шаблон:2x is counted 3 times, the argument abcde twice.

Arguments in the template call which do not match any parameter tag in the template do not count.

If a template contains a switch, use of template arguments beyond a match do not count. Up to and including the matching case, template arguments used on the left of the equals signs count twice. Those on the right of the equals sign count for the matching case only.

Pages exceeding the template argument size limit are automatically added to Категорія:Сторінки, які містять пропущені аргументи шаблонів (недавні додавання).

Найвища глибина розкриття

[ред. код]

Сторінки, які виходять за ці межі, автоматично додаються до категорії Категорія:Сторінки з перевищеною глибиною розгортання (недавні додавання).

Ресурсомісткі парсерні виклики функцій

[ред. код]

Є обмеження в 500 ресурсомістких парсерних функцій, тобто, число викликів ресурсомісткі парсерних функцій, якими є:

  • #ifexist: умовний вираз, який обирає значення залежно від того, чи вказана сторінка існує, чи ні. Якщо вийти за межі обмеження кількості ресурсомістких парсерних функцій, то кожна додатковий виклик #ifexist буде поводитися так наче вказана сторінка в запиті відсутня.
  • {{PAGESINCATEGORY}} або PAGESINCAT: Кількість сторінок в категорії під назвою назвакатегорії. Кожна підкатегорія рахується як один елемент.
  • PAGESIZE
  • CASCADINGSOURCES
  • REVISIONUSER, коли використано на сторінці, яка відрізняється від поточної сторінки
  • REVISIONTIMESTAMP, коли використано на сторінці, яка відрізняється від поточної сторінки
  • Деякі функції Lua, багато маю еквіваленти до інших елементів у цьому списку:
  • теги <syntaxhighlight>...</syntaxhighlight>

Також можливо вручну збільшувати кількість ресурсомістких парсерних викликів функцій у модулі Lua, використавши mw.incrementExpensiveFunctionCount.

Сторінки, які виходять за ці межі, автоматично додаються до категорії Категорія:Сторінки з дуже великою кількістю викликів ресурсомістких функцій (недавні додавання).

Див. також: mw:Manual:$wgExpensiveParserFunctionLimit

Unstrip post-expand size

[ред. код]

The unstrip post-expand size counter tracks the total bytes added via TemplateStyles (the <templatestyles /> tag itself is counted towards the post-expand include size count).

The total length of the format strings of function #time is limited to 6000 characters [1]. The error message is given by MediaWiki:Pfunc time too long). For each combination of the expanded wikitext of a format string and the expanded wikitext of an expression for the time (e.g. "1 Mar 2008 -1day"), repeated use is not counted, as the results are cached.

Unfortunately, the count is not in the limit report.

Спеціальна:Розгортання шаблонів

[ред. код]

Коли сторінка виходить за обмеження, то одним грубим методом вирішення проблеми є використання Спеціальна:Розгортання шаблонів. На відміну до підстановки, вона рекурсивно розгортає усі рівні одразу, бе потреби особливої підготовки шаблонів з кодом safesubst:<noinclude/> або подібними (див. bug 2777). Це зменшує усі лічильники до нуля, окрім кількості вузлів передобробника, але навіть це зазвичай зменшує до числа, що цілком в межах обмжень.

Історія

[ред. код]

Обмеження включень були введені в дію в англійській Вікіпедії користувачем Tim Starling 14 серпня 2006. Новий передобробник запущено у січні 2008, який вилучив «обмеження передрозкритих включень» та замінив їх на обмеження «кількості вузлів передобробника».

Практика використання сторінок документацій шаблону не є більш обов'язковою з метою уникнення включення тексту документації до обраховання обмежень сторінки при виклику шаблону, хоча досі її корисно використовувати з інших причин.

Примітки

[ред. код]