Расширение:Scribunto

From mediawiki.org
This page is a translated version of the page Extension:Scribunto and the translation is 58% complete.
Это расширение поставляется с MediaWiki 1.34 и выше. Таким образом, вам не нужно загружать его снова. Тем не менее, вы всё равно должны следовать другим инструкциям.
Это расширение работает поверх исполняемых. Вы должны иметь разрешение на запуск исполняемых файлов на хостовой машине, чтобы это расширение работало.
Справка по расширениям MediaWiki
Scribunto
Статус релиза: стабильно
Реализация Расширение парсера
Описание Предоставляет платформу, позволяющую встраивать сценарные языки программирования в страницы MediaWiki
Автор(ы)
  • Victor Vasiliev
  • Tim Starling
и другие
Последняя версия Постоянные обновления
Политика совместимости Snapshots releases along with MediaWiki. Master is not backward compatible.
MediaWiki >= 1.42
PHP 5.5+
Лицензия GPL-2.0-or-later AND MIT
Скачать
Module (ns:828), Talk_Module (ns:829)
  • $wgScribuntoDefaultEngine
  • $wgScribuntoSlowFunctionThreshold
  • $wgScribuntoGatherFunctionStats
  • $wgScribuntoUseGeSHi
  • $wgScribuntoUseCodeEditor
  • $wgScribuntoEngineConf
Ежеквартальные загрузки 547 (Ranked 8th)
Использование общедоступными вики 8,789 (Ranked 30th)
Переведите расширение Scribunto, если оно доступно на translatewiki.net
Роль Vagrant scribunto
Проблемы Открытые задачи · Сообщить об ошибке

Расширение 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:

{{#invoke: Module_name | function_name | arg1 | arg2 | arg3 ... }}

Лицензия

Это расширение содержит код, распространяемый по лицензии GNU General Public License v2.0 или более поздней версии (GPL-2.0+), а также код, распространяемый по лицензии MIT License (MIT).

Требования

Совместимость с версиями PCRE

Рекомендуется версия PCRE 8.33+. PCRE 8.33 была выпущена в мае 2013 года. Вы можете просмотреть используемую PHP версию PCRE на веб-странице phpinfo(), или из командной строки, выполнив следующую команду:

php -r 'echo "pcre: " . ( extension_loaded( "pcre" ) ? PCRE_VERSION : "no" ) . "\n";'

Операционные системы CentOS 6 и RHEL 6 ограничены версией PCRE 7 и должны быть обновлены для работы со Scribunto.

Обновление до версии 8.33 на сервере, использующем более старую версию, может быть проблематично. См. Updating to PCRE 8.33 or Higher для более детальной информации.

Расширение PHP pcntl (LTS)

Версии MediaWiki:
1.25 – 1.28

Версии Scribunto для MediaWiki 1.25 — 1.28 требовали наличия расширения pcntl для PHP, которое доступно только на платформах под управлением ОС Unix/Linux. Это требование действовало только при использовании LuaStandalone (т. е. выполнении Lua в отдельном дочернем процессе). Это расширение сделано необязательным в Scribunto для MediaWiki 1.29.

Вы можете просмотреть, включена ли поддержка pcntl, на веб-странице phpinfo(), или из командной строки, выполнив следующую команду:

php -r 'echo "pcntl: " . ( extension_loaded( "pcntl" ) ? "yes" : "no" ) . "\n";'

PHP-расширение mbstring

В PHP должно быть включено расширение mbstring.

Вы можете проверить, включена ли поддержка mbstring, просмотрев веб-страницу phpinfo() или из командной строки с помощью следующей команды:

php -r 'echo "mbstring: " . ( extension_loaded( "mbstring" ) ? "yes" : "no" ) . "\n";'

Lua binary

Bundled binaries

Scribunto comes bundled with Lua binary distributions for Linux (x86 and x86-64), Mac OS X Lion, and Windows (32- and 64-bit).

Scribunto should work for you out of the box if:

  1. Ваш веб-сервер работает на одной из вышеперечисленных платформ.
  2. Функция PHP proc_open не ограничена.[1]
  3. proc_terminate and shell_exec are not disabled in PHP.
  4. Ваш веб-сервер настроен на выполнение двоичных файлов в дереве MediaWiki.
Заметка Заметка: Возможно, потребуется установить разрешения на выполнение; например, в Linux используйте:
chmod 755 /path/to/extensions/Scribunto/includes/Engines/LuaStandalone/binaries/lua5_1_5_linux_64_generic/lua
If you are using SELinux in "Enforcing" mode on your server, you might need to set a proper context for the binaries. Example for RHEL/CentOS 7:
chcon -t httpd_sys_script_exec_t /path/to/extensions/Scribunto/includes/Engines/LuaStandalone/binaries/lua5_1_5_linux_64_generic/lua

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.

The support was removed due to Spectre and bitrot concerns (phab:T184156).

Установка

  • Скачайте и распакуйте файл(ы) в папку с названием Scribunto в вашей папке extensions/.
    Вместо этого разработчикам и соавторам кода следует установить расширение из Git, используя:cd extensions/
    git clone https://gerrit.wikimedia.org/r/mediawiki/extensions/Scribunto
  • Добавьте следующий код в конце вашего файла LocalSettings.php :
    wfLoadExtension( 'Scribunto' );
    $wgScribuntoDefaultEngine = 'luastandalone';
    
  • Set execute permissions for the Lua binaries bundled with this extension:
chmod a+x /path/to/extensions/Scribunto/includes/Engines/LuaStandalone/binaries/yourOS/lua

[2]

  • Set type to httpd_sys_script_exec_t if SELinux is enforced:
chcon -t httpd_sys_script_exec_t /path/to/extensions/Scribunto/includes/Engines/LuaStandalone/binaries/yourOS/lua

[2]

  • Yes Готово – Перейдите на страницу Special:Version на своей вики, чтобы удостовериться в том, что расширение успешно установлено.


Установка Vagrant:

  • Если вы используете Vagrant , установите с помощью vagrant roles enable scribunto --provision


Optional installation

Интеграция расширений

Для более приятного пользовательского интерфейса с подсветкой синтаксиса и редактором кода с автоотступом установите следующие расширения:

Версия MediaWiki:
1.30

Затем в свой LocalSettings.php после регистрации всех расширений добавьте:

$wgScribuntoUseGeSHi = true;
$wgScribuntoUseCodeEditor = true;

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 используются нижеперечисленные ключи. Обычно их задают примерно таким способом:

$wgScribuntoEngineConf['luastandalone']['key'] = 'value';
luaPath
Указывает путь к интерпретатору Lua.
errorFile
Указывает путь к файлу, к которому учётная запись веб-сервера имеет доступ на запись. В этот файл будут записываться ошибки и отладочный вывод самостоятельного интерпретатора.
По умолчанию не ведётся запись ошибок, выводимых самостоятельным интерпретатором. Вы можете настроить эту запись как в следующей строке:
$wgScribuntoEngineConf['luastandalone']['errorFile'] = '/path/to/file.log';
memoryLimit
Указывает ограничение памяти в байтах, применяемое к процессу самостоятельного интерпретатора на Linux (осуществляется средствами ulimit).
cpuLimit
Указывает ограничение времени ЦП в секундах, применяемое к процессу самостоятельного интерпретатора на Linux (осуществляется средствами ulimit).
allowEnvFuncs
Задайте как true, чтобы разрешить использование в модулях функций setfenv и getfenv.

LuaSandbox

В $wgScribuntoEngineConf для Scribunto_LuaSandboxEngine используются нижеперечисленные ключи. Обычно их задают примерно таким способом:

$wgScribuntoEngineConf['luasandbox']['Ключ'] = 'Значение';
memoryLimit
Указывает лимит памяти в байтайх.
cpuLimit
Указывает лимит процессорного времени в секундах.
profilerPeriod
Указывает время между опросами в секциях для профилировщика Lua.
allowEnvFuncs
Задайте как true, чтобы разрешить использование в модулях функций setfenv и getfenv.

Использование

Скрипты размещаются в новом пространстве имён Модуль. Каждый модуль содержит набор функций, которые могут быть вызваны из вики-текста с помощью синтаксиса:

{{#invoke: Module_name | function_name | arg1 | arg2 | arg3 ... }}

Lua

Изучение Lua

Lua — простой язык программирования, который должен быть доступен для новичков. Для быстрого введения в язык, попробуйте Learn Lua in 15 Minutes.

Лучшим комплексным введением в Lua служит книга Programming in Lua. Её первое издание (для Lua 5.0) доступно в сети и в целом подходит для версии 5.1, используемой Scribunto:

  • Programming in Lua (пролистайте ниже рекламы книг, чтобы найти текст)

Также полезен справочник:

Окружение Lua

Окружением в Lua называется набор глобальных переменных и функций.

Каждый вызов {{#invoke:}} производится в отдельном окружении. Переменные, определённые в одном {{#invoke:}}, не будут доступны из прочих. Это ограничение было необходимо для поддержки гибкости в реализации парсера вики-текста.

Окружение, в котором работают скрипты, не совсем то же, что в стандартном Lua. Их различия описаны на странице Extension:Scribunto/Справочник Lua.

Отладочная консоль

Пример использования отладочной консоли
См. также: Extension:Scribunto/Debug console

При редактировании модуля на 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.

Check your Lua interpreter in:

/path/to/webdir/Scribunto/includes/Engines/LuaStandalone/binaries/lua5_1_5_linux_32_generic

Check the interpreter by using:

file lua 

The result should look like :

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:

$wgScribuntoEngineConf['luastandalone']['luaPath'] = '/usr/bin/lua5.1';

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.

Design documents

Другие страницы

Смотрите также

General
  • Lua Wikibase client - functionality for the Scribunto extension.
  • 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

External links

Примечания

  1. то есть 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.
  2. 2.0 2.1 2.2 The name of the engines folder changed from lowercase to capitalised in 2022.