Руководство:Настройка загрузки файлов
MediaWiki поддерживает загрузку и интеграцию медиа-файлов. Эта страница описывает технические аспекты этой возможности, см. Manual:Image administration/ru и Справка:Изображения для получения общей информации об использовании.
Начиная с версии 1.1, в MediaWiki загрузка изображений, по-умолчанию, отключена. Загрузку можно включить с помощью параметра конфигурации, хотя рекомендуется сначала проверить некоторые необходимые условия.
Требования
Убедитесь, что загрузка активирована в PHP-конфиге
В php.ini должно быть указано следующее:
file_uploads = On
Если этот параметр не активирован - PHP-скрипты не смогут использовать функции загрузки файлов.
Если задана директива open_basedir, она должна содержать как папку загрузки назначения в вашей установленной MediaWiki («{$IP}/images»), так и папку «upload_tmp_dir» (системная папка по умолчанию, если она не установлена). If this is in effect, also check if your hoster has properly configured 'sys_temp_dir', because sometimes they forget about that as well and you cannot write temporary files at all (upload, session or any other tmp file).
Добавление 'upload_tmp_dir' может избежать сообщений типа Не удалось найти файл "/var/tmp/php31aWnF" (где в этом примере 'upload_tmp_dir' есть '/var/tmp'). Подробнее о загрузке файлов в PHP читайте Основы загрузки файлов и, в частности, move_uploaded_file().
Check for Windows and IIS users
Set %SystemRoot%\TEMP
to have permissions for the Internet Guest Account (IUSR
_MachineName, or IUSR
for IIS 7+): Read, write and execute;
Проверьте права доступа
Права доступа на каталог загрузки должны быть настроены так, чтобы обычный пользователь не имел возможности загрузить и выполнить другие скрипты, способные навредить вашему сайту.
Set the /images
folder (or the /uploads
folder in previous versions) to have permission "755":
- User can read, write and execute;
- Group can read and execute;
- World can read and execute.
If using SELinux , make sure to adjust the ACLs accordingly (see there).
Check webserver security
See Manual:Security#Upload security for changes to make to your webserver configuration to prevent uploaded files from executing code or having browsers execute malicious files.
- Restrict directory listing on images folder
If you don't want a public user to list your images folder, an option is to set this up in your apache configuration:
<Directory /var/www/wiki/images>
Options -Indexes
</Directory>
Check .htaccess file
The images
directory in the MediaWiki installation folder contains an .htaccess file with some configurations on it.
The goal of this file is to make the upload folder more secure, and if you place your upload directory somewhere else, it's recommended to also copy the .htaccess file to the new location, or apply that configuration on the server directly.
However, some of those configurations may cause conflicts or errors, depending on how the server is configured.
Some things to take into account:
- If the server doesn't allow to set or override directives in .htaccess files, accessing any file under that folder may result in a generic "HTTP 500 error".
If that's the case, you should comment-out the lines, and apply those directives directly on the server configuration files. The directives that are most likely causing the problems are AddType
—which prevents HTML and PHP files from being served as HTML—, and php_admin_flag
—which would prevent PHP files from being parsed and executed on the server as such.
Включение/отключение загрузки файлов
Версия MediaWiki: | ≥ 1.5 |
В MediaWiki версии 1.5 и более поздних устанавливаемый атрибут находится в LocalSettings.php , где значение параметра $wgEnableUploads
нужно установить следующим образом:
$wgEnableUploads = true; # Разрешить загрузку файлов
Чтобы отключить возможность загрузки файлов, установите значение параметра в false:
$wgEnableUploads = false; # Запретить загрузку файлов
Using a central repository
InstantCommons is a feature, enabled with a configuration change, which gives you immediate access to the millions of free (freely licensed) files in Wikimedia Commons.
Ограничение загрузки файлов
По-умолчанию, все зарегистрированные пользователи могут загружать файлы. Чтобы ограничить это - измените значение параметра $wgGroupPermissions :
- To prevent normal users from uploading files:
$wgGroupPermissions['user']['upload'] = false;
- To create a special group called "uploadaccess", and allow members of that group to upload files:
$wgGroupPermissions['uploadaccess']['upload'] = true;
- To allow "autoconfirmed" (non-newbie) users to upload files:
$wgGroupPermissions['autoconfirmed']['upload'] = true;
Право заменять существующие файлы даётся разрешением - reupload
:
- To prevent normal users from overriding existing files:
$wgGroupPermissions['user']['reupload'] = false;
- To allow "autoconfirmed" (non-newbie) users to replace existing files:
$wgGroupPermissions['autoconfirmed']['reupload'] = true;
If a ForeignFileRepo is set, the right to replace those files locally is handled by an special permission, called reupload-shared
:
- To prevent normal users from overriding filerepo files locally:
$wgGroupPermissions['user']['reupload-shared'] = false;
- To allow "autoconfirmed" (non-newbie) users to replace filerepo files locally:
$wgGroupPermissions['autoconfirmed']['reupload-shared'] = true;
Подробнее о правах пользователей смотрите Руководство:Права пользователя , а для получения информации об ограничении доступа — Руководство:Ограничение доступа .
Настройка типов файлов
Чтобы разрешить загрузку какого-либо типа файлов, добавьте его расширение $wgFileExtensions в LocalSettings.php . К примеру, параметр $wgFileExtensions может выглядеть так
$wgFileExtensions = [ 'png', 'gif', 'jpg', 'jpeg', 'doc',
'xls', 'mpp', 'pdf', 'ppt', 'tiff', 'bmp', 'docx', 'xlsx',
'pptx', 'ps', 'odt', 'ods', 'odp', 'odg'
];
или
$wgFileExtensions = array_merge( $wgFileExtensions, [
'doc', 'xls', 'mpp', 'pdf', 'ppt', 'xlsx', 'jpg',
'tiff', 'odt', 'odg', 'ods', 'odp'
] );
или
# Добавление новых типов файлов к уже существующим в DefaultSettings.php
$wgFileExtensions[] = 'docx';
$wgFileExtensions[] = 'xls';
$wgFileExtensions[] = 'pdf';
$wgFileExtensions[] = 'mpp';
$wgFileExtensions[] = 'odt';
$wgFileExtensions[] = 'ods';
However, certain file extensions are prohibited ($wgProhibitedFileExtensions , formerly $wgFileBlacklist for MediaWiki 1.36 and earlier) and cannot be uploaded even if added to $wgFileExtensions. To upload files with prohibited extensions, you must modify $wgProhibitedFileExtensions . For instance, to allow users to upload Windows executables:
$wgFileExtensions[] = 'exe';
$wgProhibitedFileExtensions = array_diff( $wgProhibitedFileExtensions, [ 'exe' ] );
In addition, $wgMimeTypeExclusions (formerly $wgMimeTypeBlacklist ) prevents certain file types based on MIME type; .zip files, for example, are prohibited based on MIME type (MediaWiki version 1.14 up to 1.17).
Вы также можете установить $wgStrictFileExtensions
$wgStrictFileExtensions = false;
для разрешения загрузки большинства файлов. Ограничение будет продолжать действовать на некоторые запрещённые типы файлов (см. загрузка файлов - не изображений)..
Если вы получаете ошибку "The file is corrupt or has an incorrect extension", убедитесь что определение MIME типов работает корректно.
If you decide to allow any kind of file, make sure your mime detection is working and think about enabling virus scans for uploads .
To enable zip extension (tested in MediaWiki v1.19.23) the following will be necessary in the LocalSettings.php file:
$wgFileExtensions[] = 'zip';
// $wgTrustedMediaFormats[] = 'ARCHIVE';
$wgTrustedMediaFormats[] = 'application/zip';
Миниатюры
Для получения информации об автоматической генерации миниатюр, смотрите Создание миниатюр изображений . For problems with thumbnailing, see Image Thumbnails not working and/or appearing.
Версия MediaWiki: | ≥ 1.11 |
If the file is not visual (like an Image or Video) a fileicon is used instead.
These are generated by the iconThumb()
function in the File class in the FileRepo group.
Icons stored in "$wgStyleDirectory/common/images/icons/
" in a "fileicon-$extension.png
"-format.
Максимальный размер загружаемого файла
Browsers tell the server the size of the file to be uploaded before it actually sends the file.
If the upload is too big, it is rejected by the target (server) and the upload fails providing multiple errors depending at which layer the limit was imposed:
- If it's a server limit (nginx, Apache) on the maximum amount of transmitted data, it may simply fail with a HTTP 500 error or HTTP 413 – Request entity too large.
- If the limit it's at the PHP level, if post_max_size is hit, you may get a generic HTTP 500 error (or simply a blank page) otherwise, MediaWiki should give a more meaningful error message.
По умолчанию настройки php.ini ограничивает размер загружаемых файлов до 2 мегабайт (и максимальный размер операции отправки до 8 мегабайт). Если необходимо загрузить файл большего размера, измените параметр post_max_size в php.ini[1] и upload_max_filesize[2].
- post_max_size, 8 megabytes large by default
- upload_max_filesize, 2 megabytes large by default
Для этого могут потребоваться права администратора - если же ваш сайт находится на стороннем сервере, обратитесь к техподдержке хостинга.
- Locating the php.ini file
The location of the php.ini file varies on the distribution you are using. See Manual:Php.ini for instructions for locating the correct php.ini used by your web server (as opposed to the php.ini used by the command line binary).
- Multiple websites hosted on a server
If you have more than one website hosted on a server and want to change only for MediaWiki, insert into your /etc/apache2/sites-enabled/your_wiki_site.com inside <Virtual Host>:
php_value upload_max_filesize 100M
php_value post_max_size 100M
Both above settings also work in a .htaccess file if your site uses mod_php. If your site uses PHP >= 5.3 and allows it, you can place php.ini directives in .user.ini files instead.
- web server limits
Your web server may impose further limits on the size of files allowed for upload. For Apache, one of the relevant settings is LimitRequestBody. [3] For Nginx, client_max_body_size is the relevant setting.[4] For Lighttpd, server.max-request-size is what may need modification.[5]
Ubuntu 16.04: sudo service apache2 restart
(sudo /etc/init.d/php5-fpm restart in Linux, for example.)
- uploading too large of files warning
MediaWiki покажет предупреждение, если вы попытаетесь загрузить файл, размером превышающем установленный лимит в параметре $wgUploadSizeWarning . Это ограничение не зависит от жёсткого лимита PHP.
- temporary upload limits
Temporary changes to upload limits (when using multiple wikis on a farm, for example) can be altered by adding the lines:
ini_set( 'post_max_size', '50M' );
ini_set( 'upload_max_filesize', '50M' );
to the MediaWiki LocalSettings.php
configuration file for each wiki.
In this example the PHP limit is set at 50 Mb.
Note that these settings will not override the maximum settings set above (since the core php.ini and apache2 php.ini files set the absolute maximum).
This method sets maximums that are less than the absolute maximum.
- IIS7 лимит загруки
<system.webServer>
in the web.config file:<security> <requestFiltering> <requestLimits maxAllowedContentLength="50000000" /> </requestFiltering> </security>
With the above maxAllowedContentLength, users can upload files that are 50,000,000 bytes (50 MB) in size. This setting will work immediately without restarting IIS services. The web.config file is located in the root directory of your web site.
To allow uploading files up to 2G:
add the following lines to LocalSettings.php
:
$wgUploadSizeWarning = 2147483647;
$wgMaxUploadSize = 2147483647;
Also, modify the following lines in php.ini :
memory_limit = 2048M (this line may not be necessary)
post_max_size = 2048M
upload_max_filesize = 2048M
In the IIS web.config file, override the value of maxRequestLength. For example, the following entry in web.config allows files that are less than or equal to 2 gigabytes (GB) to be uploaded:
<httpRuntime maxRequestLength="2097151" executionTimeout="18000"/>
With IIS 7, you also need to configure it to allow large uploads. This is found by clicking “Request Filtering > Edit Feature Settings” in the IIS section in the middle of the window. Set the ”Maximum allowed content length (Bytes)” field to 2147482624. If you don’t see "Request Filtering" in the IIS section, it needs enabled via Internet Information Services > World Wide Web Services > Security in the "Turn Windows features on or off" area in Control Panel.
If the above tip does not enable large uploads, then open a command prompt and execute this command as well:
%windir%\system32\inetsrv\appcmd set config -section:requestFiltering -requestLimits.maxAllowedContentLength: 2147482624
Загрузка файлов напрямую с других сайтов
Если вы хотите разрешить пользователям загружать файлы напрямую с других сайтов, вместо копирования файла на локальный компьютер, установите $wgAllowCopyUploads = true
.
By default, upload by URL are only possible using the API (or extensions such as UploadWizard ).
To make the option usable from Special:Upload, you need to set $wgCopyUploadsFromSpecialUpload to true
as well.
On the upload form, you will then see an additional field for the URL, below the usual filename field.
The URL field is greyed out per default, but can be activated by activating the radiobutton (checkbox) to the left of the field.
In order to use this feature, users must have the user right upload_by_url
.
This right was granted to sysops by default until MediaWiki 1.20 but it now needs to be granted explicitly.
To allow this to normal users, set
$wgGroupPermissions['user']['upload_by_url'] = true;
Keep in mind that allowing uploads directly from an arbitrary location on the web makes it easier to upload random, unwanted material, and it might be misunderstood as an invitation to upload anything that people might come across on the web.
$wgHTTPProxy
needs to be set accordingly. Either you supply it directly or, if your server supplies the environment variable http_proxy
see your phpinfo()
, then you could use the following code in your LocalSettings.php
:/*
* Proxy to use for CURL requests.
*/
if ( isset( $_ENV['http_proxy'] )) $wgHTTPProxy = $_ENV['http_proxy'];
Mass uploading
A number of tools are available for uploading multiple files in one go rather than each file separately:
Расширение | Описание | Статус выпуска | Требования |
---|---|---|---|
Расширение:UploadWizard | Используется на Wikimedia Commons | Стабильный | MediaWiki 1.23+ |
Extension:MsUpload | Позволяет пользователю загружать несколько файлов, включая перемещение и удаление файлов. | Стабильный | 1.32+ |
Extension:SimpleBatchUpload | Basic, no-frills uploading of multiple files to MediaWiki | Стабильный | 1.31+ |
Extension:VisualData/File_upload | Includes a fully-configurable multiple file upload with filename formula and CRUD operations | Stable | 1.35+ |
Commonist (внешняя ссылка на Wikimedia Commons) | Требуется загрузка файла через api.php .
| ||
importImages.php | "Разместите файлы на сервере в удобном для чтения месте и выполните maintenance/importImages.php скрипт из командной строки."[7]
|
Upload directory
Whenever an image is uploaded, several things are created:
- An article in the file namespace with the name of the file, e.g. File:MyPicture.png.
This page is stored and can be edited like any other page.
- The file itself is stored into the folder on the file system, which is configured in
$wgUploadDirectory
or into one if its subfolders (see below).
- If thumbnailing is available, thumbnailed versions of the file will be created when necessary (such as for the usage on the file description page.
These are stored in the thumb directory of the image directory, in a separate directory for each main file.
If $wgHashedUploadDirectory is enabled (by default), MediaWiki creates several subdirectories in the images directory.
If $wgHashedUploadDirectory
is set to true
, uploaded files will be distributed into sub-directories of $wgUploadDirectory based on the first two characters of the md5 hash of the filename. (e.g. $IP/images/a/ab/foo.jpg)
Creation of such subdirectories is handled automatically.
This is used to avoid having too many files in one folder because some filesystems don't perform well with large numbers of files in one folder.
If you only maintain a small wiki with few uploaded images, you could turn this off by setting $wgHashedUploadDirectory = false
, all images are uploaded in $wgUploadDirectory itself. (e.g. $IP/images/foo.jpg)
Multiwiki sites
- Make sure you've changed the site location in
LocalSettings.php
from, e.g./var/lib/mediawiki
to wherever your installation is, and created a writeable images directory (most of the rest can be symlinked).
Not doing so will mysteriously break image uploads.
Configuring the upload form
The upload form message provided with the default MediaWiki installation (which appears when you click "Upload file" link or go to Special:Upload link) may not go very well for you.
For that case you can edit MediaWiki:Uploadtext contents and provide your own text. If your wiki site is multilanguage don't forget to edit localized versions like MediaWiki:Uploadtext/de.
On the MediaWiki:Licenses page you can customize a drop-down list of licenses for uploads of your site. See the documentation of this feature.
Take into account that localized versions like MediaWiki:Licenses/de won't work by default.
To enable them you must configure the $wgForceUIMsgAsContentMsg
variable.
Edit MediaWiki:Upload-default-description to add an initial text to the "Summary" field of your upload form (for example your wiki site has a universal template for upload summaries and you want everyone to use that template).
Известные проблемы на Windows
Запуск MediaWiki на сервере Windows имеет некоторые ограничения в разрешенных именах файлов из-за ошибки PHP. PHP не может корректно обрабатывать имена файлов с не-ascii-символами, а MediaWiki будет отказываться загружать файлы, содержащие такие символы, чтобы предотвратить прерывистую загрузку (задача T3780), с сообщением Эта вики не поддерживает имена файлов с символами, отсутствующими в таблице ASCII..
Since MediaWiki 1.31 MediaWiki can handle filenames with non-ascii characters if it's using PHP 7.1 or later.
Известные проблемы с именами баз данных, которые являются non-alphanumeric символами
If $wgDBname
contains non-alphanumeric characters, uploads may fail with errors like Could not create directory "mwstore://local-backend/local-public/<path>"..
This is caused by an internal check for valid container name for file backend, but it's constructed using $wgDBname
.
Since MediaWiki 1.26, it allows uploads when $wgDBname
contains dots.
См. также
- Manual:Configuration settings#Uploads for a list of all configuration variables related to file uploads
- Категория:Переменные загрузки - similar list as a category (ordered alphabetically)
- You see a blank page when trying to upload a file
Примечания
- ↑ post-max-size, руководство по PHP.
- ↑ upload-max-filesize, руководство по PHP.
- ↑ core - Apache HTTP Server Version 2.4 - LimitRequestBody Directive, Apache manual
- ↑ client_max_body_size, Nginx manual
- ↑ server.max-request-size, Lighthttpd manual
- ↑ IIS7 is a new revision (version 7.0) of the Internet Information Services that is part of Windows Vista and the next Windows Server version.
- ↑ http://xpt.sourceforge.net/techdocs/language/wiki/wikimedia/wkm07-MediaWikiImport/index.html#mass_image_upload_zip_