Difference between pages "Install/ru/Partitioning" and "Package:MediaWiki"

From Funtoo
< Install‎ | ru(Difference between pages)
Jump to navigation Jump to search
 
m (migrate test36 into the page)
 
Line 1: Line 1:
<noinclude>
{{Ebuild
{{InstallPart|процесс разбиения диска и создания файловых систем}}
|Summary=
</noinclude>
|CatPkg=www-apps/mediawiki
=== Подготовка жесткого диска ===
|Maintainer=Drobbins,
|Repository=Funtoo Overlay
}}


В этой части  мы научимся различным способам установки Funtoo Linux -- и загрузки с -- жесткого диска.
{{Fancyimportant|1=
This page documents how to install MediaWiki from source tarball rather than portage, which is the preferred method. It also shows how to use MediaWiki with php-5.4. As of late 1.22 and 1.23, MediaWiki now unofficially works with php-5.5 & php-5.6.}}


==== Введение ====
MediaWiki is a [[Web-server-stack]] web application.  This page documents how to set up MediaWiki on Funtoo Linux, from a bare stage3 install with network connectivity. We will use Nginx, xcache and PHP-FPM, which will result in good performance. We will also properly secure MediaWiki, and also cover some additional tips and tricks, focusing on spam reduction.


В прежние времена существовал лишь один способ загрузить PC-совместимый компьютер. Все наши дектопы и сервера имели стандартный PC BIOS, все наши харды использовали MBR и были разбиты используя схему разбивки MBR.  Вот как это все было и нам это нравилось!
== Portage Settings ==


Затем появились EFI и UEFI,  встроенные программы нового образца наряду со схемой разбивки GPT, поддерживающая диски размером более 2.2TБ. Неожиданно, нам стали доступны различные способы установки и загрузки Линукс систем . То, что было единым методом, стало чем-то более сложным.
Add the following line to <code>/etc/[[make.conf]]</code>:


Воспользуемся моментом и рассмотрим доступные способы конфигурации жесткого диска для загрузки Funtoo Linux. Данное Руководство рекомендует способ "по-старинке" , загрузка BIOS и использование MBR.  Данный способ работает (за исключением редких случаев) и всесторонне поддерживается. И в этом нет ничего плохого. Если Ваш жесткий диск 2TБ или меньшего размера это не является препятствием для использования всего дискового пространства.


Но, бывают ситуации когда метод "по-старинке" не является оптимальным. Если Ваш жесткий диск размером более 2TБ , MBR разбивка не сможет обеспечить доступ ко всему дисковому пространству.  Это одна из причин.  Вторая причина: существуют  "PC" системы, которые более не поддерживают  BIOS загрузку  и  форсируют UEFI загрузку. Из чувства сострадания к тем, кто попал в затруднение перед выбором, это Руководство также описывает установку и загрузку UEFI систем.
<pre>
PHP_TARGETS="php5-4"
</pre>


Мы всё же рекомендуем разбивку "по-старинке". Загрузчик, который мы используем для загрузки Линукс в этом руководстве называется GRUB,  таки образом мы называем метод  как '''BIOS + GRUB (MBR)''' . Это традиционный способ установки на PC-совместимые компьютеры.
Add the following lines to <code>/etc/portage/package.use/php</code>:


Если Вам необходимо использование UEFI для загрузки, мы советуем не использовать MBR вообще, ввиду того, что некоторые системы поддерживают MBR,  а некоторые нет. Вместо, мы советуем использование UEFI  для загрузки GRUB, который, затем в свою очередь загрузит Линукс. Мы называем этот  метод как '''UEFI + GRUB (GPT)'''.
<pre>
dev-lang/php curl exif fpm gd mysql mysqli sockets suhosin threads intl xmlreader xmlwriter
>=dev-php/xcache-2.0.0 php_targets_php5-4
</pre>


И да, есть еще несколько способов, некоторые из них задокументированы в [[Boot Methods]] . Обычно мы рекомендуем  '''BIOS + GRUB (GPT)''' метод, но он ограничивается не столь широкой поддержкой со стороны комплектующих.
== Emerge ==


'''Вопрос --  какой из методов использовать?'''  Вот какой.
Emerge xcache, and we'll also emerge metalog and postfix. This should pull in MySQL as well as php-5.4:


;Принцип 1 - "По-старинке":  Если Вы можете успешно загрузить System Rescue CD и видите синее меню, то Вы используете BIOS,  и скорее всего Вы можете загрузить Funtoo Linux используя BIOS. Итак,  следуйте этому способу и используйте BIOS загрузку,  кроме случаев Вам по-какой либо причине необходим UEFI, например если размер жесткого диска >2.2TБ.  В этом случае следуйте Принцип  2.
<console>
# ##i##emerge --jobs xcache metalog postfix
</console>


;Принцип 2 - "Модерн":  Если Вы можете успешно загрузить System Rescue CD и видите черно-белое меню -- поздравления,  Ваша система поддерживает UEFI загрузку. Это значит, что Вы готовы установить Funtoo Linux к загрузке с помощью UEFI.  Ваша система также может поддерживать загрузку BIOS,  но попрбуйте UEFI для начала. Вы можете "покопаться" в настройках BIOS.
== Start and Configure Services ==


;Какая разница между "По-старинке" и "Модерн"?:  Если Вы следуете  MBR разбивке, Ваш <code>/boot</code> раздел будет отформатирован файловой системой ext2 , и Вы будете использовать <code>fdisk</code> для создания MBR разделов.  Если Вы следуете "модерн", GPT разделам и UEFI загрузке,  Ваш <code>/boot</code> раздел будет отформатирован  в файловую систему vfat,  поскольку это единственная файловая система поддерживаемая UEFI, и Вы будете использовать <code>gdisk</code> для создания GPT разделов.  И Вы установите GRUB несколько иначе.  Вот к чему сводится различие между методами.
Time to configure MySQL with a root password, start it, secure it, and enable it to start at boot. We'll also start metalog and postfix:


;Имейте в виду: Для установки Funtoo Linux используя метод "модерн", Вы должны загрузить System Rescue CD в UEFI режиме -- и увидеть начальное черно-белое меню. В противном случае, UEFI не активно и Вы не сможете продолжить!
<console>
# ##i##emerge --config mysql
# ##i##rc-update add mysql default
# ##i##rc-update add metalog default
# ##i##rc-update add postfix default
# ##i##rc
# ##i##mysql_secure_installation
</console>


{{Note|'''Некоторые материнские платы якобы поддерживают UEFI, но на самом деле нет.''' Исследуйте . К примеру,  Award BIOS в моей Gigabyte GA-990FXA-UD7 rev 1.1 имеет возможность включить UEFI загрузку для CD/DVD. '''Этого не достаточно для обеспечения UEFI загрузки для жестких дисков и установки Funtoo Linux.''' UEFI должно поддерживать и сьемные носители (таким образом Вы сможете загрузить System Rescue CD используя  UEFI) и жесткие диски (Вы можете загрузить Funtoo Linux.) Оказывается, что более поздние ревизии этой платы (rev 3.0) имеют новую версию BIOS который полностью поддерживает UEFI.  Это приводит к третьему принципу -- знайте Ваши комплектующие.}}
== Database Setup ==


==== Метод (BIOS/MBR) "По-старинке" ====
Now, let's create a database named <code>mediawiki</code> for use by MediaWiki, and a <code>mediawiki@localhost</code> user to access this database, using a password of <code>wikifever</code>:


{{Note|Используйте данный метод при загрузке с помощью BIOS, и если System Rescue CD имеет начальное меню загрузки светло-голубое. Если Вы собираетесь использовать "модерн", [[#Метод (UEFI/GPT) "Модерн"|кликните здесь в меню UEFI/GPT.]]}}
<console>
# ##i##mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 7
Server version: 5.1.62-log Gentoo Linux mysql-5.1.62-r1


===== Подготовка =====
Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.


Прежде чем начать , неплохо бы удостовериться, что Вы используете нужный диск для разбивки. Попробуйте эту комманду и проверьте, что <code>/dev/sda</code> тот самый диск, который Вы желаете разбить:
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.


<console>
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
# ##i##fdisk -l /dev/sda


Disk /dev/sda: 640.1 GB, 640135028736 bytes, 1250263728 sectors
mysql> ##i##create database mediawiki;
Units = sectors of 1 * 512 = 512 bytes
Query OK, 1 row affected (0.01 sec)
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk label type: gpt


mysql> ##i##grant index, create, select, insert, update, delete, alter, lock tables on mediawiki.* to 'mediawiki'@'localhost' identified by 'wikifever';
Query OK, 0 rows affected (0.01 sec)


#         Start          End    Size  Type            Name
mysql> ##i##\q
1        2048  1250263694  596.2G  Linux filesyste Linux filesystem
Bye
#
</console>
</console>


Теперь, рекомендуем стереть  существующие таблицы разделов  MBR или GPT,  которые могут помешать BIOS во время загрузки. Мы используем комманду <code>sgdisk</code>:
== Nginx Setup ==
{{fancywarning|Это необратимый процесс, который уничтожит все разделы!  Вы предупреждены! Советуем сохранить критические данние перед этим.}}
 
We will use nginx as our Web server. Let's emerge it:


<console>
<console>
# ##i##sgdisk --zap-all /dev/sda
# ##i##emerge --jobs nginx
</console>


Creating new GPT entries.
== User and Group ==
GPT data structures destroyed! You may now partition the disk using fdisk or
other utilities.
</console>


Не стоит беспокоится об этом сообщении, так как комманда успешно выполнена:
When we run our wiki, we will run it as the <code>docs</code> user, for security. Let's set up a <code>docs</code> user and group:


<console>
<console>
***************************************************************
# ##i##groupadd docs
Found invalid GPT and valid MBR; converting MBR to GPT format
# ##i##useradd -g docs --home /home/docs docs
in memory.
# ##i##install -d /home/docs
***************************************************************
# ##i##chown -R docs:docs /home/docs
</console>
</console>


===== Разбивка диска =====
== Set up PHP ==
 
As our last major configuration step, we will configure the PHP FastCGI Process Manager by creating a <code>/etc/php/fpm-php5.4/php-fpm.conf</code> file with the following contents (existing contents can be deleted):
 
{{file|name=/etc/php/fpm-php5.4/php-fpm.conf|desc= |body=
[global]
error_log = /var/log/php-fpm.log
log_level = notice
 
[docs]
listen = /var/run/docs.php-fpm.socket
listen.allowed_clients = 127.0.0.1
listen.owner = docs
listen.group = nginx
listen.mode = 0660
user = docs
group = docs
pm = dynamic
pm.max_children = 16
pm.start_servers = 2
pm.min_spare_servers = 2
pm.max_spare_servers = 2
pm.max_requests = 500
php_admin_value[open_basedir] = /home/docs/public_html:/tmp
php_admin_value[error_log] = /home/docs/php-errors.log
php_admin_value[disable_functions] = exec, system, shell_exec, passthru, popen, dl, curl_multi_exec, posix_getpwuid,
disk_total_space, disk_free_space, escapeshellcmd, escapeshellarg, eval, get_current_user, getmyuid, getmygid,
posix_getgrgid, parse_ini_file, proc_get-status, proc_nice, proc_terminate, suexec, pclose, virtual, set_time_limit, show_source
}}
This configuration file tells PHP to use the <code>docs</code> user when running MediaWiki. '''Please note that the last line is very long - I have split it into 3 lines for readability on this wiki, but you should combine them into a single line in your configuration file. The line should start with <code>php_admin_value[disable_functions]</code> and end with <code>show_source</code>.
 
== Configure Nginx ==
 
Oh! Now we need to configure nginx to serve pages as the docs user. Assuming your site is named wiki.mysite.com, create a <code>/etc/nginx/sites-available/wiki.mysite.com</code> file with the following contents:
 
<pre>
server {
        listen 80;
        server_name wiki.mysite.com;
 
        access_log /var/log/nginx/wiki.mysite.com.access.log main;
        error_log /var/log/nginx/wiki.mysite.com.error.log error;
       
        root /home/docs/public_html;
        index index.html index.php;
 
        # uncomment this if you want to htpasswd-protect your site while you set it up initially
        # auth_basic "Ninjas allowed only";
        # auth_basic_user_file /etc/nginx/docs.funtoo.org.htpasswd;
 
location ~* ^(.*)(install.php|LocalSettings.php|\.git) { deny all; }
 
location ~* \.php$ {
        #set $https "off";
        #if ($scheme = https) { set $https "on"; }
        #fastcgi_param HTTPS $https;
 
        try_files      $uri    @404;
        fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
        fastcgi_param  SERVER_SOFTWARE    nginx;
        fastcgi_param  QUERY_STRING      $query_string;
        fastcgi_param  REQUEST_METHOD    $request_method;
        fastcgi_param  CONTENT_TYPE      $content_type;
        fastcgi_param  CONTENT_LENGTH    $content_length;
        fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
        fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
        fastcgi_param  REQUEST_URI        $request_uri;
        fastcgi_param  DOCUMENT_URI      $document_uri;
        fastcgi_param  DOCUMENT_ROOT      $document_root;
        fastcgi_param  SERVER_PROTOCOL    $server_protocol;
        fastcgi_param  REMOTE_ADDR        $remote_addr;
        fastcgi_param  REMOTE_PORT        $remote_port;
        fastcgi_param  SERVER_ADDR        $server_addr;
        fastcgi_param  SERVER_PORT        $server_port;
        fastcgi_param  SERVER_NAME        wiki.mysite.com;
 
        fastcgi_pass    unix:/var/run/docs.php-fpm.socket;
        fastcgi_index  index.php;
}
 
# this will secure the MediaWiki uploads against arbitrary PHP injection attacks:
location /images/ {
        location ~.*\.(php)?$ {
                deny all;
        }
}
 
 
location @404 {
        return 404;
        break;
}
 
location / {
        try_files $uri $uri/ @mediawiki;
}
 
location @mediawiki {
        rewrite ^/([^?]*)(?:\?(.*))? /index.php?title=$1&$2 last;
}
 
}
</pre>
 
for localhost/wiki/ short urls in nginx:
{{file|name=/etc/nginx/sites-enabled/localhost|lang=|desc=domain.com/wiki/ short urls|body=
location /wiki {
index index.php;
rewrite "^(wiki)$" $1/ permanent;
rewrite "^/?wiki(/.*)?" /mediawiki/index.php?title=$1&$args last;
}}
 
== Enable Ngnix and PHP-FPM ==


Теперь мы используем <code>fdisk</code> для создания таблицы разделов MBR и самих разделов:
Now, let's enable nginx to serve our site, and also be sure to enable php-fpm:


<console>
<console>
# ##i##fdisk /dev/sda
# ##i##cd /etc/nginx/sites-enabled
# ##i##ln -s ../sites-available/wiki.mysite.com wiki.mysite.com
# ##i##rc-update add nginx default
# ##i##rc-update add php-fpm default
# ##i##rc
* Starting PHP FastCGI Process Manager ...                                                            [ ok ]
* Starting nginx ...                                                                                  [ ok ]
#
</console>
</console>


В консоли <code>fdisk</code>, следуйте следующим шагам:
== MediaWiki from portage ==
There are mediawiki ebuilds in portage, if you like your site breaking upon emerge --sync && emerge -avuND world:
 
<console>###i## emerge mediawiki</console>
 
With out the vhost flag the files will be dropped into /var/www/localhost/htdocs/mediawiki.
 
== Download MediaWiki ==


'''Очистить таблицу разделов''':
We're getting close. Now, head to http://www.mediawiki.org/wiki/Download and copy the link address for the latest version of MediaWiki, currently 1.19.1 at the time this was written. Let's download the archive to <code>/var/tmp</code>:


<console>
<console>
Command (m for help): ##i##o ↵
# ##i##cd /var/tmp
# ##i##wget http://download.wikimedia.org/mediawiki/1.19/mediawiki-1.19.1.tar.gz
</console>
</console>


'''Создать раздел 1''' (boot):
== Extract MediaWiki ==
 
We now have all the Web, database and email infrastructure enabled that we need. Heading to the IP address of your server should result in a 404 - Not Found error in your Web browser. Time to extract and configure MediaWiki itself:


<console>
<console>
Command (m for help): ##i##n ↵
# ##i##su docs
Partition type (default p): ##i##
$ ##i##cd /var/tmp
Partition number (1-4, default 1): ##i##
$ ##i##tar xvf ./mediawiki-1.19.1.tar.gz
First sector: ##i##
$ ##i##mv mediawiki-1.19.1 ~/public_html
Last sector: ##i##+128M ↵
</console>
</console>


'''Создать раздел 2''' (своп):
== MediaWiki from GIT ==
 
Alternatively, we can download the code from the git repository:


<console>
<console>
Command (m for help): ##i##n ↵
# ##i##su docs
Partition type (default p): ##i##
$ ##i##cd ~
Partition number (2-4, default 2): ##i##
$ ##i##git clone https://gerrit.wikimedia.org/r/p/mediawiki/core.git public_html
First sector: ##i##
Last sector: ##i##+2G ↵
Command (m for help): ##i##t ↵
Partition number (1,2, default 2): ##i## ↵
Hex code (type L to list all codes): ##i##82 ↵
</console>
</console>


'''Создать корневой раздел:'''
Specific stable versions of MediaWiki are tracked using 'tags'. These are analogous to the tarball releases. We can see the versions available with:
<console>
$ ##i##cd public_html
$ ##i##git tag -l | sort -V
</console>


To use a specific tag (1.19.1):
<console>
<console>
Command (m for help): ##i##n ↵
$ ##i##git checkout 1.19.1
Partition type (default p): ##i##↵
Partition number (3,4, default 3): ##i##↵
First sector: ##i##↵
Last sector: ##i##↵
</console>
</console>


'''Проверить таблицу разделов:'''
== Initial Web Config ==


<console>
You will now be able to load the URL of your server in your Web browser and configure MediaWiki through the Web user interface. Complete the '''full''' installation process and be sure to specify that you are using XCache for caching. Once you go through this process, the Web installation process will provide you with a <code>LocalSettings.php</code> file, which you should place in <code>/home/docs/public_html</code>. The <code>LocalSettings.php</code> file can also be manually edited and used to enable MediaWiki features and extensions.
Command (m for help): ##i##p


Disk /dev/sda: 298.1 GiB, 320072933376 bytes, 625142448 sectors
== Tips and Tricks ==
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0x82abc9a6


Device    Boot    Start      End    Blocks  Id System
=== Alternate Main Page ===
/dev/sda1          2048    264191    131072  83 Linux
To define your default landing page for mediawiki.
/dev/sda2        264192  4458495  2097152  82 Linux swap / Solaris
edit: localhost/wiki/MediaWiki:Mainpage
/dev/sda3        4458496 625142447 310341976  83 Linux
</console>


'''Записать таблицу разделов на диск:'''
example: http://www.funtoo.org/MediaWiki:Mainpage


<console>
=== Arbitrary Page Titles ===
Command (m for help): ##i##w
To change a page's title from domain.com/Main_Page to "title" insert this magic word in the page:
</console>


Ваша новая таблица разделов будет записана на диск.
*<nowiki>{{DISPLAYTITLE:title}}</nowiki>


{{Note|Вы завершили создание разделов! Теперь, перейдите к  [[#Создание файловых систем|Создание файловых систем]].}}
=== Show Php handler, Database & Plugins Used ===
To show which plugins are installed on a wiki, browse localhost/wiki/Special:Version.


==== Метод (UEFI/GPT) "Модерн" ====
example: http://funtoo.org/Special:Version


{{Note|Используйте данный метод при загрузке с помощью UEFI, и если System Rescue CD имеет начальное меню загрузки черно-белого цвета. Если оно было светло-голубого цвета, этот метод не будет работать.}}
=== Sidebar ===
To define your own sidebar links, edit localhost/wiki/MediaWiki:Sidebar


Комманда <tt>gdisk</tt> используется для создания таблицы разделов GPT . Измените размеры в соответсвии Вашим требованиям, хотя приведенные ниже размеры будут работать для большинства пользователей. Запустите <code>gdisk</code>:
links follow the page|text format.  example:
http://www.funtoo.org/MediaWiki:Sidebar


<console>
=== Rss subscriptions ===
# ##i##gdisk
Rss is handy to track page changes.  all individual pages can be tracked for changes under mediawiki.  For example, if you wish to track your user talk pages via rss, go to your talk page, navigate to history.  add &feed=rss to the end.  &feed=atom is also valid.
</console>


В консоли <tt>gdisk</tt>,  следуйте следующим шагам:
http://www.funtoo.org/index.php?title=User:Drobbins&action=history&feed=rss


'''Создайте новую пустую таблицу разделов''' (Это уничтожит данные при сохранении на диск):


<console>
=== ArticlePath ===
Command: ##i##o ↵
This option deletes all partitions and creates a new protective MBR.
Proceed? (Y/N): ##i##y ↵
</console>


'''Создайте раздел 1''' (загрузочный):
By default, MediaWiki pages will have a URL of <code>wiki.myserver.com/index.php?title=PageName</code>. With a few minor tweaks, you can tell MediaWiki to use <code>wiki.myserver.com/PageName</code> instead. Here's how. Open up <code>LocalSettings.php</code> and search for the <code>$wgScriptPath</code> line. This part of the config will look like this:


<console>
<pre>
Command: ##i##n ↵
$wgScriptPath      = "";
Partition Number: ##i##1 ↵
$wgScriptExtension  = ".php";
First sector: ##i##↵
</pre>
Last sector: ##i##+500M ↵
Hex Code: ##i##↵
</console>


'''Создайте раздел 2''' (своп):
Change this part of the file to look like this:


<console>
<pre>
Command: ##i##n ↵
$wgScriptPath      = "";
Partition Number: ##i##2 ↵
$wgArticlePath      = "/$1";
First sector: ##i##↵
$wgUsePathInfo      = true;
Last sector: ##i##+4G ↵
$wgScriptExtension  = ".php";
Hex Code: ##i##8200 ↵
</pre>
</console>


'''Создайте раздел 3''' (корневой):
The old-style URLs will still work, but the shorter more intuitive URLs will now be used for all wiki links.


<console>
=== $wgSpamRegex ===
Command: ##i##n ↵
Partition Number: ##i##3 ↵
First sector: ##i##↵
Last sector: ##i##↵##!i## (for rest of disk)
Hex Code: ##i##↵
</console>


По пути Вы можете набрать "<tt>p</tt>" и нажать Enter для просмотра текущей таблицы разделов. Если Вы допустили ошибку,  наберите "<tt>d</tt>" для удаления созданного раздела. Если Вы удовлетворены Вашей схемой разделов, наберите "<tt>w</tt>" для записи таблицы на диск:
You may find that your wiki is the target of spammers. The easiest way to combat spam is to set <code>$wgSpamRegex</code> in <code>LocalSettings.php</code>, like so:


'''Записать таблицу разделов на диск''':
<pre>
$wgSpamRegex = "/badword1|badword2|badword3/i"
</pre>


<console>
This will perform a case-insensitive match against the bad words and block anyone from saving edits that contain these words.
Command: ##i##w ↵
Do you want to proceed? (Y/N): ##i##Y ↵
</console>


Таблица разделов будет записана на диск и <tt>gdisk</tt> завершит работу.
=== DNS Blacklist ===


Теперь  GPT/GUID разделы созданы, и будут показаны как ''блочные утройства'' в Linux:
MediaWiki also has the ability to consult a DNS blacklist to prevent known forum and wiki spam sites from performing any edits on your wiki. To enable this capability, add the following to <code>LocalSettings.php</code>:


* <tt>/dev/sda1</tt>, будет использоваться  для <tt>/boot</tt>, загрузочный раздел
<pre>
* <tt>/dev/sda2</tt>, будет использоваться как своп , и
$wgEnableDnsBlacklist = true;
* <tt>/dev/sda3</tt>, корневой раздел.
$wgDnsBlacklistUrls = array( 'xbl.spamhaus.org', 'opm.tornevall.org' );
</pre>


==== Создание файловых систем ====
You may notice a significant decrease in spam posts.


{{Note|Данная часть рассматривает как BIOS ''так и'' UEFI установки. Не пропускайте раздел!}}
=== $wgExternalLinkTarget ===
For external links if you wish for the link to open a new tab or new window for the external link add this to your LocalSettings.php


Прежде чем Ваши только что созданные разделы могут быть использованы, блочные устройства должны быть инициализированы метаданными файловой системы. Данный процесс известен как ''создание файловой системы''.  После этого блочные устройства могут быть смонтированы и использоваться для хранения данных .
{{file|name=/var/www/localhost/htdocs/mediawiki/LocalSettings.php|lang=php|desc=set external links to open in a new tab|body=
...
$wgExternalLinkTarget = '_blank';
}}


Будем проще.  Используете разделы MBR, метод "по-старинке" ? Если да, давайте создадим файловую систему ext2 на /dev/sda1:
=== $wgRawHtml ===


<console>
{{warning|raw html can be dangerous regarding injecting spam/malicious/fishing pages.  use with care!}}
# ##i##mkfs.ext2 /dev/sda1
</console>


Если Вы используете разделы GPT для UEFI, метод "модерн",  Вам нужно создать файловую систему FAT32 на /dev/sda1, поскольку это единственная поддерживамая UEFI фаловая система:
To allow any raw html inserted into your wiki:


<console>
{{file|name=/var/www/localhost/htdocs/mediawiki/LocalSettings.php|lang=php|desc=enabling arbitrary html|body=
# ##i##mkfs.vfat -F 32 /dev/sda1
...
</console>
$wgRawHtml = "true";
}}


Теперь, создадим своп раздел. Он будет использоваться как дисковая виртуальная память для системы Funtoo Linux.
=== $wgServer ===


Вы не будете создавать никакой файловой системы на своп разделе, поскольку он не используется для хранения каких-либо данных. Но необходимо инициализировать своп коммандой <code>mkswap</code>.  Далее мы используем комманду <code>swapon</code> для незамедлительной активации своп-раздела в окружении живого диска live CD, в случае необходимости доступа к своп во время установки:
Here is an important tip -- the <code>$wgServer</code> variable in <code>LocalSettings.php</code> defines the URL of your MediaWiki installation. MediaWiki will encode this within its HTML replies, which means that the Web browser from which you are accessing MediaWiki must be able to reach your server using this address, or pages will not display. This is not a security feature in any way, but a configuration issue. For example, if <code>$wgServer</code> is set to <code>10.0.1.128</code>, then the only systems that will be able to access your MediaWiki installation are those for which <code>10.0.1.128</code> resolves to your MediaWiki installationThe same is true of non-IP <code>$wgServer</code> entries like <code>wiki.mysite.com</code>. If you are setting up a test wiki, you may need a temporary entry in a desktop's <code>/etc/hosts</code> file so that it can interact with the wiki properly before DNS is set up.


<console>
=== $wgLogo ===
# ##i##mkswap /dev/sda2
# ##i##swapon /dev/sda2
</console>


Now, we need to create a root filesystem. This is where Funtoo Linux will live. We generally recommend ext4 or XFS root filesystems. If you're not sure, choose ext4. Here's how to create a root ext4 filesystem:
If you want to change the wiki logo, edit <code>LocalSettings.php</code> and replace $wgLogo with the location of the image you want to use:


<console>
<pre>
# ##i##mkfs.ext4 /dev/sda3
$wgLogo = "image.png"
</console>
</pre>
{{fancynote| The above references the file <code>image.png</code> in the directory <code>/home/docs/public_html</code>}}


...and here's how to create an XFS root filesystem, if you choose to use XFS:
=== MySQL wildcard searches ===
Recent versions of mediawiki have broken search results.


<console>
{{file|name=/var/www/localhost/htdocs/mediawiki/includes/search/SearchMySQL.php|lang=php|desc=line 175 modification to repair mysql searches|body=
# ##i##mkfs.xfs /dev/sda3
if ( trim( $term ) === '' ) {
</console>
return null;
} else {
$term = $term . '*';
}
}}


Your filesystems (and swap) have all now been initialized, so that that can be mounted (attached to your existing directory heirarchy) and used to store files. We are ready to begin installing Funtoo Linux on these brand-new filesystems.
=== License Badges ===
You can have licenses displayed with your pages.


{{fancywarning|1=
{{file|name=/var/www/localhost/htdocs/mediawiki/LocalSettings.php|lang=php|desc=add license badge to articles|body=
When deploying an OpenVZ host, please use ext4 exclusively. The Parallels development team tests extensively with ext4, and modern versions of <code>openvz-rhel6-stable</code> are '''not''' compatible with XFS, and you may experience kernel bugs.
$wgRightsPage = ""; # Set to the title of a wiki page that describes your license/copyright
$wgRightsUrl = "http://creativecommons.org/licenses/by-sa/3.0/"; //external source explaining license
$wgRightsText = "Creative Commons Attribution Share Alike"; //alternate text on the image
$wgRightsIcon = "{$wgStylePath}/common/images/cc-by-sa.png";
}}
}}


==== Mounting filesystems ====
There are 6 possible badge images


Mount the newly-created filesystems as follows, creating <code>/mnt/funtoo</code> as the installation mount point:
* {$wgStylePath}/common/images/cc-0.png
* {$wgStylePath}/common/images/cc-by-nc-sa.png
* {$wgStylePath}/common/images/cc-by-sa.png
* {$wgStylePath}/common/images/cc-by.png
* {$wgStylePath}/common/images/gnu-fdl.png
* {$wgStylePath}/common/images/public-domain.png


<console>
=== Importing Google Fonts & External Css ===
# ##i##mkdir /mnt/funtoo
Googles font api is excellent.  all you have to do is look through https://www.google.com/fonts# and select which font you want.  To the bottom right of the font pane is a little box with an arrow pointing right.  click the arrow, and follow step 1, and 2.  for step 3 you need to select @import.  on your wiki navigate to localhost/MediaWiki:Common.css or a specific skin to add the css to like localhost/MediaWiki:Vector.css and enter this code.
# ##i##mount /dev/sda3 /mnt/funtoo
 
# ##i##mkdir /mnt/funtoo/boot
{{file|name=localhost/MediaWiki:Common.css|lang=css|desc=|body=
# ##i##mount /dev/sda1 /mnt/funtoo/boot
@import url(http://fonts.googleapis.com/css?family=Lobster);
</console>
 
.firstHeading, #mw-head, .body ul li {
font-family: 'Lobster', cursive;
}
}}
 
External css is similar, if you wanted to bootswatch your wiki navigate to http://www.bootstrapcdn.com/#bootswatch_tab select which cdn and insert it into your common css.


Optionally, if you have a separate filesystem for <code>/home</code> or anything else:
{{file|name=localhost/MediaWiki:Common.css|lang=css|desc=yeti for the sasquatch hunter in you|body=
@import url(//maxcdn.bootstrapcdn.com/bootswatch/3.2.0/yeti/bootstrap.min.css);
}}


<console>
== Media ==
# ##i##mkdir /mnt/funtoo/home
{{#widget:YouTube|playlist=PL7ABDor6eEgc2U9PH4Irty4K8mqUgkvDq}}
# ##i##mount /dev/sda4 /mnt/funtoo/home
</console>


If you have <code>/tmp</code> or <code>/var/tmp</code> on a separate filesystem, be sure to change the permissions of the mount point to be globally-writeable after mounting, as follows:
== External Resources ==
* http://www.mediawiki.org/wiki/Manual:System_administration
* http://www.mediawiki.org/wiki/Manual:Performance_tuning
* http://www.mediawiki.org/wiki/Help:Templates
* http://www.mediawiki.org/wiki/Transclusion


<console>
[[Category:Featured]]
# ##i##chmod 1777 /mnt/funtoo/tmp
[[Category:HOWTO]]
</console>
[[Category:Official Documentation]]
[[Category:Ebuilds]]
{{EbuildFooter}}

Revision as of 09:52, January 10, 2015

MediaWiki

   Tip

We welcome improvements to this page. To edit this page, Create a Funtoo account. Then log in and then click here to edit this page. See our editing guidelines to becoming a wiki-editing pro.


   Important

This page documents how to install MediaWiki from source tarball rather than portage, which is the preferred method. It also shows how to use MediaWiki with php-5.4. As of late 1.22 and 1.23, MediaWiki now unofficially works with php-5.5 & php-5.6.

MediaWiki is a Web-server-stack web application. This page documents how to set up MediaWiki on Funtoo Linux, from a bare stage3 install with network connectivity. We will use Nginx, xcache and PHP-FPM, which will result in good performance. We will also properly secure MediaWiki, and also cover some additional tips and tricks, focusing on spam reduction.

Portage Settings

Add the following line to /etc/make.conf:


PHP_TARGETS="php5-4"

Add the following lines to /etc/portage/package.use/php:

dev-lang/php curl exif fpm gd mysql mysqli sockets suhosin threads intl xmlreader xmlwriter
>=dev-php/xcache-2.0.0 php_targets_php5-4

Emerge

Emerge xcache, and we'll also emerge metalog and postfix. This should pull in MySQL as well as php-5.4:

root # emerge --jobs xcache metalog postfix

Start and Configure Services

Time to configure MySQL with a root password, start it, secure it, and enable it to start at boot. We'll also start metalog and postfix:

root # emerge --config mysql
root # rc-update add mysql default
root # rc-update add metalog default
root # rc-update add postfix default
root # rc
root # mysql_secure_installation

Database Setup

Now, let's create a database named mediawiki for use by MediaWiki, and a mediawiki@localhost user to access this database, using a password of wikifever:

root # mysql -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 7
Server version: 5.1.62-log Gentoo Linux mysql-5.1.62-r1

Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> create database mediawiki;
Query OK, 1 row affected (0.01 sec)

mysql> grant index, create, select, insert, update, delete, alter, lock tables on mediawiki.* to 'mediawiki'@'localhost' identified by 'wikifever';
Query OK, 0 rows affected (0.01 sec)

mysql> \q
Bye
root # 

Nginx Setup

We will use nginx as our Web server. Let's emerge it:

root # emerge --jobs nginx

User and Group

When we run our wiki, we will run it as the docs user, for security. Let's set up a docs user and group:

root # groupadd docs
root # useradd -g docs --home /home/docs docs
root # install -d /home/docs
root # chown -R docs:docs /home/docs

Set up PHP

As our last major configuration step, we will configure the PHP FastCGI Process Manager by creating a /etc/php/fpm-php5.4/php-fpm.conf file with the following contents (existing contents can be deleted):

   /etc/php/fpm-php5.4/php-fpm.conf
[global]
error_log = /var/log/php-fpm.log
log_level = notice

[docs]
listen = /var/run/docs.php-fpm.socket
listen.allowed_clients = 127.0.0.1
listen.owner = docs
listen.group = nginx
listen.mode = 0660
user = docs
group = docs
pm = dynamic
pm.max_children = 16
pm.start_servers = 2
pm.min_spare_servers = 2
pm.max_spare_servers = 2
pm.max_requests = 500
php_admin_value[open_basedir] = /home/docs/public_html:/tmp
php_admin_value[error_log] = /home/docs/php-errors.log
php_admin_value[disable_functions] = exec, system, shell_exec, passthru, popen, dl, curl_multi_exec, posix_getpwuid, 
 disk_total_space, disk_free_space, escapeshellcmd, escapeshellarg, eval, get_current_user, getmyuid, getmygid, 
 posix_getgrgid, parse_ini_file, proc_get-status, proc_nice, proc_terminate, suexec, pclose, virtual, set_time_limit, show_source

This configuration file tells PHP to use the docs user when running MediaWiki. Please note that the last line is very long - I have split it into 3 lines for readability on this wiki, but you should combine them into a single line in your configuration file. The line should start with php_admin_value[disable_functions] and end with show_source.

Configure Nginx

Oh! Now we need to configure nginx to serve pages as the docs user. Assuming your site is named wiki.mysite.com, create a /etc/nginx/sites-available/wiki.mysite.com file with the following contents:

server {
        listen 80;
        server_name wiki.mysite.com;

        access_log /var/log/nginx/wiki.mysite.com.access.log main;
        error_log /var/log/nginx/wiki.mysite.com.error.log error;
        
        root /home/docs/public_html;
        index index.html index.php;

        # uncomment this if you want to htpasswd-protect your site while you set it up initially
        # auth_basic "Ninjas allowed only";
        # auth_basic_user_file /etc/nginx/docs.funtoo.org.htpasswd;

location ~* ^(.*)(install.php|LocalSettings.php|\.git) { deny all; }

location ~* \.php$ {
        #set $https "off"; 
        #if ($scheme = https) { set $https "on"; }
        #fastcgi_param HTTPS $https;

        try_files       $uri    @404;
        fastcgi_param   GATEWAY_INTERFACE  CGI/1.1;
        fastcgi_param   SERVER_SOFTWARE    nginx;
        fastcgi_param   QUERY_STRING       $query_string;
        fastcgi_param   REQUEST_METHOD     $request_method;
        fastcgi_param   CONTENT_TYPE       $content_type;
        fastcgi_param   CONTENT_LENGTH     $content_length;
        fastcgi_param   SCRIPT_FILENAME    $document_root$fastcgi_script_name;
        fastcgi_param   SCRIPT_NAME        $fastcgi_script_name;
        fastcgi_param   REQUEST_URI        $request_uri;
        fastcgi_param   DOCUMENT_URI       $document_uri;
        fastcgi_param   DOCUMENT_ROOT      $document_root;
        fastcgi_param   SERVER_PROTOCOL    $server_protocol;
        fastcgi_param   REMOTE_ADDR        $remote_addr;
        fastcgi_param   REMOTE_PORT        $remote_port;
        fastcgi_param   SERVER_ADDR        $server_addr;
        fastcgi_param   SERVER_PORT        $server_port;
        fastcgi_param   SERVER_NAME        wiki.mysite.com;

        fastcgi_pass    unix:/var/run/docs.php-fpm.socket;
        fastcgi_index   index.php;
}

# this will secure the MediaWiki uploads against arbitrary PHP injection attacks:
location /images/ {
        location ~.*\.(php)?$ {
                deny all;
        }
}


location @404 {
        return 404;
        break;
}

location / {
        try_files $uri $uri/ @mediawiki;
}

location @mediawiki {
        rewrite ^/([^?]*)(?:\?(.*))? /index.php?title=$1&$2 last;
}

}

for localhost/wiki/ short urls in nginx:

   /etc/nginx/sites-enabled/localhost - domain.com/wiki/ short urls
location /wiki {
		index index.php;
		rewrite "^(wiki)$" $1/ permanent;
		rewrite "^/?wiki(/.*)?" /mediawiki/index.php?title=$1&$args last;
	}

Enable Ngnix and PHP-FPM

Now, let's enable nginx to serve our site, and also be sure to enable php-fpm:

root # cd /etc/nginx/sites-enabled
root # ln -s ../sites-available/wiki.mysite.com wiki.mysite.com
root # rc-update add nginx default
root # rc-update add php-fpm default
root # rc
 * Starting PHP FastCGI Process Manager ...                                                            [ ok ]
 * Starting nginx ...                                                                                  [ ok ]
root #

MediaWiki from portage

There are mediawiki ebuilds in portage, if you like your site breaking upon emerge --sync && emerge -avuND world:

root # emerge mediawiki

With out the vhost flag the files will be dropped into /var/www/localhost/htdocs/mediawiki.

Download MediaWiki

We're getting close. Now, head to http://www.mediawiki.org/wiki/Download and copy the link address for the latest version of MediaWiki, currently 1.19.1 at the time this was written. Let's download the archive to /var/tmp:

root # cd /var/tmp
root # wget http://download.wikimedia.org/mediawiki/1.19/mediawiki-1.19.1.tar.gz

Extract MediaWiki

We now have all the Web, database and email infrastructure enabled that we need. Heading to the IP address of your server should result in a 404 - Not Found error in your Web browser. Time to extract and configure MediaWiki itself:

root # su docs
user $ cd /var/tmp
user $ tar xvf ./mediawiki-1.19.1.tar.gz
user $ mv mediawiki-1.19.1 ~/public_html

MediaWiki from GIT

Alternatively, we can download the code from the git repository:

root # su docs
user $ cd ~
user $ git clone https://gerrit.wikimedia.org/r/p/mediawiki/core.git public_html

Specific stable versions of MediaWiki are tracked using 'tags'. These are analogous to the tarball releases. We can see the versions available with:

user $ cd public_html
user $ git tag -l | sort -V

To use a specific tag (1.19.1):

user $ git checkout 1.19.1

Initial Web Config

You will now be able to load the URL of your server in your Web browser and configure MediaWiki through the Web user interface. Complete the full installation process and be sure to specify that you are using XCache for caching. Once you go through this process, the Web installation process will provide you with a LocalSettings.php file, which you should place in /home/docs/public_html. The LocalSettings.php file can also be manually edited and used to enable MediaWiki features and extensions.

Tips and Tricks

Alternate Main Page

To define your default landing page for mediawiki. edit: localhost/wiki/MediaWiki:Mainpage

example: http://www.funtoo.org/MediaWiki:Mainpage

Arbitrary Page Titles

To change a page's title from domain.com/Main_Page to "title" insert this magic word in the page:

  • {{DISPLAYTITLE:title}}

Show Php handler, Database & Plugins Used

To show which plugins are installed on a wiki, browse localhost/wiki/Special:Version.

example: http://funtoo.org/Special:Version

Sidebar

To define your own sidebar links, edit localhost/wiki/MediaWiki:Sidebar

links follow the page|text format. example: http://www.funtoo.org/MediaWiki:Sidebar

Rss subscriptions

Rss is handy to track page changes. all individual pages can be tracked for changes under mediawiki. For example, if you wish to track your user talk pages via rss, go to your talk page, navigate to history. add &feed=rss to the end. &feed=atom is also valid.

http://www.funtoo.org/index.php?title=User:Drobbins&action=history&feed=rss


ArticlePath

By default, MediaWiki pages will have a URL of wiki.myserver.com/index.php?title=PageName. With a few minor tweaks, you can tell MediaWiki to use wiki.myserver.com/PageName instead. Here's how. Open up LocalSettings.php and search for the $wgScriptPath line. This part of the config will look like this:

$wgScriptPath       = "";
$wgScriptExtension  = ".php";

Change this part of the file to look like this:

$wgScriptPath       = "";
$wgArticlePath      = "/$1";
$wgUsePathInfo      = true;
$wgScriptExtension  = ".php";

The old-style URLs will still work, but the shorter more intuitive URLs will now be used for all wiki links.

$wgSpamRegex

You may find that your wiki is the target of spammers. The easiest way to combat spam is to set $wgSpamRegex in LocalSettings.php, like so:

$wgSpamRegex = "/badword1|badword2|badword3/i"

This will perform a case-insensitive match against the bad words and block anyone from saving edits that contain these words.

DNS Blacklist

MediaWiki also has the ability to consult a DNS blacklist to prevent known forum and wiki spam sites from performing any edits on your wiki. To enable this capability, add the following to LocalSettings.php:

$wgEnableDnsBlacklist = true;
$wgDnsBlacklistUrls = array( 'xbl.spamhaus.org', 'opm.tornevall.org' );

You may notice a significant decrease in spam posts.

$wgExternalLinkTarget

For external links if you wish for the link to open a new tab or new window for the external link add this to your LocalSettings.php

   /var/www/localhost/htdocs/mediawiki/LocalSettings.php (php source code) - set external links to open in a new tab
...
 $wgExternalLinkTarget = '_blank';

$wgRawHtml

   Warning

raw html can be dangerous regarding injecting spam/malicious/fishing pages. use with care!

To allow any raw html inserted into your wiki:

   /var/www/localhost/htdocs/mediawiki/LocalSettings.php (php source code) - enabling arbitrary html
...
$wgRawHtml = "true";

$wgServer

Here is an important tip -- the $wgServer variable in LocalSettings.php defines the URL of your MediaWiki installation. MediaWiki will encode this within its HTML replies, which means that the Web browser from which you are accessing MediaWiki must be able to reach your server using this address, or pages will not display. This is not a security feature in any way, but a configuration issue. For example, if $wgServer is set to 10.0.1.128, then the only systems that will be able to access your MediaWiki installation are those for which 10.0.1.128 resolves to your MediaWiki installation. The same is true of non-IP $wgServer entries like wiki.mysite.com. If you are setting up a test wiki, you may need a temporary entry in a desktop's /etc/hosts file so that it can interact with the wiki properly before DNS is set up.

If you want to change the wiki logo, edit LocalSettings.php and replace $wgLogo with the location of the image you want to use:

$wgLogo = "image.png"
   Note
The above references the file image.png in the directory /home/docs/public_html

MySQL wildcard searches

Recent versions of mediawiki have broken search results.

   /var/www/localhost/htdocs/mediawiki/includes/search/SearchMySQL.php (php source code) - line 175 modification to repair mysql searches
if ( trim( $term ) === '' ) {
			return null;
		} else {
			$term = $term . '*';
		}

License Badges

You can have licenses displayed with your pages.

   /var/www/localhost/htdocs/mediawiki/LocalSettings.php (php source code) - add license badge to articles
$wgRightsPage = ""; # Set to the title of a wiki page that describes your license/copyright
$wgRightsUrl = "http://creativecommons.org/licenses/by-sa/3.0/"; //external source explaining license
$wgRightsText = "Creative Commons Attribution Share Alike"; //alternate text on the image
$wgRightsIcon = "{$wgStylePath}/common/images/cc-by-sa.png";

There are 6 possible badge images

  • {$wgStylePath}/common/images/cc-0.png
  • {$wgStylePath}/common/images/cc-by-nc-sa.png
  • {$wgStylePath}/common/images/cc-by-sa.png
  • {$wgStylePath}/common/images/cc-by.png
  • {$wgStylePath}/common/images/gnu-fdl.png
  • {$wgStylePath}/common/images/public-domain.png

Importing Google Fonts & External Css

Googles font api is excellent. all you have to do is look through https://www.google.com/fonts# and select which font you want. To the bottom right of the font pane is a little box with an arrow pointing right. click the arrow, and follow step 1, and 2. for step 3 you need to select @import. on your wiki navigate to localhost/MediaWiki:Common.css or a specific skin to add the css to like localhost/MediaWiki:Vector.css and enter this code.

   localhost/MediaWiki:Common.css (css source code)
@import url(http://fonts.googleapis.com/css?family=Lobster);

.firstHeading, #mw-head, .body ul li {
font-family: 'Lobster', cursive;
}

External css is similar, if you wanted to bootswatch your wiki navigate to http://www.bootstrapcdn.com/#bootswatch_tab select which cdn and insert it into your common css.

   localhost/MediaWiki:Common.css (css source code) - yeti for the sasquatch hunter in you
@import url(//maxcdn.bootstrapcdn.com/bootswatch/3.2.0/yeti/bootstrap.min.css);

Media

External Resources