Это расширение поставляется с MediaWiki 1.34 и выше. Таким образом, вам не нужно загружать его снова. Тем не менее, вы всё равно должны следовать другим инструкциям.
Это расширение работает поверх исполняемых. Вы должны иметь разрешение на запуск исполняемых файлов на хостовой машине, чтобы это расширение работало.
Расширение Scribunto (лат.: «пусть они напишут») позволяет встраивать в страницы MediaWiki модули, написанные на сценарных языках программирования.
На данный момент единственный поддерживаемый язык программирования — Lua.
Скрипты Scribunto размещаются в пространстве имён «Модуль».
Modules are run on normal wiki pages using the #invoke parser function and each module has a collection of functions, which can be called using wikitext syntax such as:
Это расширение содержит код, распространяемый по лицензии GNU General Public License v2.0 или более поздней версии (GPL-2.0+), а также код, распространяемый по лицензии MIT License (MIT).
Требования
Совместимость с версиями PCRE
Рекомендуется версия PCRE 8.33+.
PCRE 8.33 была выпущена в мае 2013 года.
Вы можете просмотреть используемую PHP версию PCRE на веб-странице phpinfo(), или из командной строки, выполнив следующую команду:
Операционные системы CentOS 6 и RHEL 6 ограничены версией PCRE 7 и должны быть обновлены для работы со Scribunto.
Обновление до версии 8.33 на сервере, использующем более старую версию, может быть проблематично.
См. Updating to PCRE 8.33 or Higher для более детальной информации.
Версии Scribunto для MediaWiki 1.25 — 1.28 требовали наличия расширения pcntl для PHP, которое доступно только на платформах под управлением ОС Unix/Linux. Это требование действовало только при использовании LuaStandalone (т. е. выполнении Lua в отдельном дочернем процессе).
Это расширение сделано необязательным в Scribunto для MediaWiki 1.29.
Вы можете просмотреть, включена ли поддержка pcntl, на веб-странице phpinfo(), или из командной строки, выполнив следующую команду:
P.S. Check your version of the extension to see if the name of the engines folder is capitalised or fully lowercase.[2]
Additional binaries
Additional Lua binary distributions, which may be needed for your web server if its operating system is not in the list above, can be obtained from http://luabinaries.sourceforge.net/ or from your Linux distribution.
Only binary files for Lua 5.1.x are supported.
Once you've installed the appropriate binary file on your web server, configure the location of the file with:
# Where Lua is the name of the binary file# e.g. SourceForge LuaBinaries 5.1.5 - Release 2 name the binary file lua5.1$wgScribuntoEngineConf['luastandalone']['luaPath']='/path/to/binaries/lua5.1';
Note that you should not add the above line unless you've confirmed that Scribunto's built-in binaries don't work for you.
LuaJIT, although theoretically compatible, is not supported.
Note: The extension is called "Scribunto" not "Module".
Скачайте и распакуйте файл(ы) в папку с названием Scribunto в вашей папке extensions/. Вместо этого разработчикам и соавторам кода следует установить расширение из Git, используя:cd extensions/ git clone https://gerrit.wikimedia.org/r/mediawiki/extensions/Scribunto
These settings are not necessary in MediaWiki versions after 1.30, where the code editor and syntax hightlighting should be used in the appropriate places automatically once the extensions are loaded. However, other settings may be desired. See the documentation for each extension.
LuaSandbox
Мы разработали написанное на C расширение для PHP под названием LuaSandbox.
Это расширение может быть использовано как альтернатива отдельному исполняемому файлу и обеспечивает более высокую производительность.
См. LuaSandbox для подробностей об этом расширении и инструкции по его установке.
Если вы изначально устанавливали Scribunto для работы с отдельным двоичным файлом Lua, обязательно обновите LocalSettings.php со следующей настройкой конфигурации:
$wgScribuntoDefaultEngine='luasandbox';
Настройка
Доступны следующие переменные конфигурации:
$wgScribuntoDefaultEngine
Выбирает тип движка. Допустимые значения — ключи массива $wgScribuntoEngineConf, по умолчанию это 'luasandbox' и 'luastandalone'.
$wgScribuntoUseGeSHi
Если установлено Расширение:SyntaxHighlight, задайте эту переменную как true, чтобы это расширение использовалось при отображении модулей. (MediaWiki 1.30 или ранее.)
$wgScribuntoUseCodeEditor
Если установлено Расширение:CodeEditor, задайте эту переменную как true, чтобы это расширение использовалось при редактировании модулей. (MediaWiki 1.30 или ранее.)
$wgScribuntoEngineConf
Ассоциативный массив для настройки движков. Ключи — допустимые значения переменной $wgScribuntoDefaultEngine, а значения — ассоциативные массивы с параметрами конфигурации. Каждый массив конфигурации должен содержать ключ 'class', называющий используемый подкласс класса ScribuntoEngineBase.
LuaStandalone
В $wgScribuntoEngineConf для Scribunto_LuaStandaloneEngine используются нижеперечисленные ключи.
Обычно их задают примерно таким способом:
Указывает путь к файлу, к которому учётная запись веб-сервера имеет доступ на запись. В этот файл будут записываться ошибки и отладочный вывод самостоятельного интерпретатора.
По умолчанию не ведётся запись ошибок, выводимых самостоятельным интерпретатором. Вы можете настроить эту запись как в следующей строке:
Указывает время между опросами в секциях для профилировщика Lua.
allowEnvFuncs
Задайте как true, чтобы разрешить использование в модулях функций setfenv и getfenv.
Использование
Скрипты размещаются в новом пространстве имён Модуль.
Каждый модуль содержит набор функций, которые могут быть вызваны из вики-текста с помощью синтаксиса:
Lua — простой язык программирования, который должен быть доступен для новичков.
Для быстрого введения в язык, попробуйте Learn Lua in 15 Minutes.
Лучшим комплексным введением в Lua служит книга Programming in Lua.
Её первое издание (для Lua 5.0) доступно в сети и в целом подходит для версии 5.1, используемой Scribunto:
Окружением в Lua называется набор глобальных переменных и функций.
Каждый вызов {{#invoke:}} производится в отдельном окружении.
Переменные, определённые в одном {{#invoke:}}, не будут доступны из прочих.
Это ограничение было необходимо для поддержки гибкости в реализации парсера вики-текста.
Окружение, в котором работают скрипты, не совсем то же, что в стандартном Lua. Их различия описаны на странице Extension:Scribunto/Справочник Lua.
При редактировании модуля на Lua под окном редактирования располагается так называемая отладочная консоль.
В ней может исполняться код на Lua без необходимости сохранения и даже создания редактируемого модуля.
Поиск и устранение неисправностей
Поиск ошибок с помощью клика по ссылке Ошибка скрипта.
Обратите внимание, что красные сообщения Ошибка скрипта кликабельны и могут предоставить детальную информацию.
Ошибка Lua: Внутренняя ошибка: Интерпретатор завершил работу со статусом 1.
When using the LuaStandalone engine (this is the default), errors along the lines of "Ошибка Lua: Внутренняя ошибка: Интерпретатор завершил работу со статусом 1." may be generated if the standalone Lua interpreter cannot be executed or runs into various runtime errors.
Чтобы получить больше информации, присвойте путь к файлу параметру $wgScribuntoEngineConf['luastandalone']['errorFile'].
Ошибки интерпретатора будут логгироваться в указанный файл, что должно помогать в отслеживании проблемы.
Информация в журнале отладки включает в себя отладочную информацию, поэтому ее так много.
You should be able to ignore any line beginning with "TX" or "RX".
If you're setting up Scribunto and are using IIS/Windows, this appears to be solved by commenting out a particular line.
Ошибка Lua: Внутренняя ошибка: Интерпретатор завершил работу со статусом 2.
When using the LuaStandalone engine (this is the default), status 2 suggests memory allocation errors, probably caused by settings that allocate inadequate memory space for PHP or Lua, or both.Assigning a file path to $wgScribuntoEngineConf['luastandalone']['errorFile'] and examining that output can be valuable in diagnosing memory allocation errors.
Increase PHP allocation in your PHP configuration; add the line memory_limit = 200M.This allocation of 200MB is often sufficient (as of MediaWiki 1.24) but can be increased as required.Set Scribunto's memory allocation in LocalSettings.php as a line:
$wgScribuntoEngineConf['luastandalone']['memoryLimit']=209715200;# в байтах
Finally, depending on the server configuration, some installations may be helped by adding another LocalSettings.php line
$wgMaxShellMemory=204800;# в КБ
Обратите внимание, что лимита памяти задаются в разных единицах.
Lua error: Internal error: 2. on ARM architecture
If you're using an ARM architecture processor like on a RaspberryPi you'll face the error Lua error: Internal error: The interpreter exited with status 2. due to wrong delivered binary format of the Lua interpreter.
lua: ELF 32-bit LSB executable, ARM, EABI5 version 1 (SYSV), dynamically linked, interpreter /lib/ld-linux-armhf.so.3, for GNU/Linux 3.2.0
The installed default Lua interpreter shows:
lua: ELF 32-bit LSB pie executable, Intel 80386, version 1 (SYSV), dynamically linked, interpreter /lib/ld-linux.so.2, for GNU/Linux 2.6.9,
look at the "Intel 80386" part what definitely is not correct.
Check in /usr/bin what version of Lua is installed on your system.If you have lua5.1 installed, you can either copy the interpreter to your lua5_1_5_linux_32_generic directory or set in your LocalSettings.php:
At present don't set wgScribuntoEngineConf to /usr/bin/lua5.3, it'll lead to the "Internal error 1".
Ошибка Lua: Внутренняя ошибка: Интерпретатор завершил работу со статусом 24.
When using the LuaStandalone engine (this is the default), status 24 suggests CPU time limit errors, although those should be generating a "The time allocated for running scripts has expired" message instead.It would be useful to file a task in Фабрикатор and participate in determining why the XCPU signal isn't being caught.
Ошибка Lua: Внутренняя ошибка: Интерпретатор завершил работу со статусом 126.
При использовании движка LuaStandalone (по умолчанию), могут генерироваться ошибки наподобие "Ошибка Lua: Внутренняя ошибка: Интерпретатор завершил работу со статусом 126.", если интерпретатор Lua не может быть запущен.
В большинстве случаев это происходит в двух случаях:
У исполняемого файла lua не задано разрешение на исполнение (x). Установите разрешения как указано в разделе #Установка.
Сервер не позволяет запуск файлов из места установки файла, например, файловая система смонтирована с флагом 'noexec'. Чаще всего это происходит с серверами с общим хостингом. Remedies include adjusting $wgScribuntoEngineConf['luastandalone']['luaPath'] to point to a Lua 5.1 binary installed in an executable location, or adjusting or convincing the shared host to adjust the setting preventing execution.
Ошибки вроде: Fatal exception of type MWException
Check the MediaWiki, PHP, or webserver logs for more details on the exception, or temporarily set $wgShowExceptionDetails to true.
версия 'GLIBC_2.11' не найдена
If the above gives you errors such as "version 'GLIBC_2.11' not found", it means the version of the standard C library on your system is too old for the binaries provided with Scribunto.You should upgrade your C library, or use a version of Lua 5.1 compiled for the C library you do have installed.To upgrade your C library, your best option is usually to follow your distribution's instructions for upgrading packages (or for upgrading to a new release of the distribution, if applicable).
If you copy the lua binaries from Scribunto master (or from gerrit:77905), that should suffice, if you can't or don't want to upgrade your C library.The distributed binaries were recently recompiled against an older version of glibc, so the minimum is now 2.3 rather than 2.11.
Lua errors in Scribunto files
Errors here include:
attempt to index field 'text' (a nil value)
Lua error in mw.html.lua at line 253: Invalid class given:
If you are getting errors such these when attempting to use modules imported from WMF wikis, most likely your version of Scribunto is out of date.
Upgrade if possible; for advanced users, you might also try to identify the needed newer commits and cherry-pick them into your local installation.
preg_replace_callback(): Compilation failed: unknown property name after \P or \p at offset 7
preg_replace_callback(): Compilation failed: unknown property name after \P or \p at offset 7
this usually indicates an incompatible version of PCRE; you'll need to update to >= 8.10
@todo: link to instructions on how to upgrade
Lua error
If you copy templates from Wikipedia and then get big red "Lua error: x" messages where the Scribunto invocation (e.g. the template that uses {{#invoke:}}) should be, that probably means that you didn't import everything you needed.Make sure that you tick the "Include templates" box at w:Special:Export when you export.
When importing pages from another wiki, it is also possible for templates or modules in the imported data to overwrite existing templates or modules with the same title, which may break existing pages, templates, and modules that depend on the overwritten versions.
Blank screen
Make sure your extension version is applicable to your MediaWiki version.
Lua scripting - Wikimedia activity page describing deployment plan to Wikimedia sites.
Расширение:Scribunto/Справочник Lua - The reference about the Lua language, as well as its standard libraries and common Scribunto modules supported on Wikimedia sites.
Commons:Lua - there may be specific notes for using Lua modules on Wikimedia Commons, including additional Lua extensions installed (e.g. for local support of internationalization and for parsing or playing medias).Some general purpose modules may be reused in other wikis in various languages (except specific tunings for policies, namespaces or project/maintenance pages with dedicated names).If possible, modules that could be widely reused across wikis should be tested and internationalized on Wikimedia Commons.
w:Help:Lua - there may be specific notes for using Lua modules on Wikipedia, including additional Lua extensions installed (including for integrating Wikidata and Wikimedia Commons contents, generating complex infoboxes and navigation boxes, or to facilitate the general administration/maintenance of the wiki contents under applicable policies).Some other localized Wikipedia editions (or other projects such Wiktionnary, Wikisource or Wikinews) may also have their own needs and Lua modules.
d:Help:Lua - there may be specific notes for using Lua modules on Wikidata, including additional Lua extensions installed (e.g. for local support of internationalization and for database queries)
Extensions
Capiunto - Provides basic infobox functionality for the Scribunto extension.
↑
то есть Scribunto не будет работать, если proc_open указан в массиве disable_functions в файле "php.ini" вашего сервера. Если это так, вы можете увидеть сообщение об ошибке, например proc_open(): open_basedir restriction in effect. File(/dev/null) is not within the allowed path(s): Если вы используете Plesk и вам предоставлены достаточные разрешения, вы можете установить open_basedir в настройках PHP для своего домена или поддомена. Попробуйте изменить {WEBSPACEROOT}{/}{:}{TMP}{/} на {WEBSPACEROOT}{/}{:}{TMP}{/}{:}/dev/null{:}/bin/bash.
Это расширение используется в одном или нескольких проектах Викимедиа. Вероятно, это означает, что расширение стабильно и работает достаточно хорошо, чтобы использоваться такими сайтами с высоким трафиком. Найдите название этого расширения в файлах конфигурации Викимедиа CommonSettings.php и InitialiseSettings.php, чтобы узнать, где оно установлено. Полный список расширений, установленных на конкретной вики, можно увидеть на странице Special:Version wiki.
Это расширение включено в следующие вики-фермы/хостинги и/или пакеты:
Это не исчерпывающий список. Некоторые вики-фермы/хостинги и/или пакеты могут содержать это расширение, даже если они не перечислены здесь. Всегда сверяйтесь со своими вики-фермами/хостингами или комплектами/бандлами для подтверждения.