Difference between pages "Funtoo:About/pt-br" and "Package:MediaWiki"

From Funtoo
< Funtoo:About(Difference between pages)
Jump to navigation Jump to search
 
m (add external links target)
 
Line 1: Line 1:
= Visão do Projeto =
{{Ebuild
|Summary=
|CatPkg=www-apps/mediawiki
|Maintainer=Drobbins,
|Repository=Funtoo Overlay
}}


Daniel Robbins originalmente escreveu a [[Gentoo_Linux_Philosophy/pt-br|Filosofia Gentoo Linux]], e nisso definiu o conceito de uma ferramenta ideal assim sendo algo que "simplesmente funciona", não fica no caminho do usuário, e responde a vontade do usuário ao invés de forçar o usuário a trabalhar de um jeito particular.
{{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.}}


Funtoo Linux é um projeto de pessoas que concordam filosofia da ferramenta ideal, e que são ''apaixonadas'' pelo nosso desejo de melhorar a tecnologia de ser tão próximo desse ideal quanto possível. O foco de nossos esforços é o melhoramento contínuo da distribuição Gentoo Linux.  
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.


O foco do desenvolvimento do Funtoo Linux é atualmente direcionado ao sistema central (core system), significando qualquer coisa em um stage3, portage, core languages, kernels, aplicações de servidor, e em cima do X11 e gerenciadores de janelas simples, e incluindo ambientes desktop como o GNOME e o KDE.
== Portage Settings ==


== Foco, Foco, Foco ==
Add the following line to <code>/etc/[[make.conf]]</code>:


Os desenvolvedores devem utilizar esses princípios gerais para determinar em quais prioridades focar primeiro. -Essas áreas abaixo estão listadas em ordem de prioridade, então o próximo parágrafo é a mais alta prioridade (top priority), seguido pela próxima prioridade, etc. Só por que algo é prioridade mais baixa não significa que é "menos importante" - somente significa tratar as coisas de prioridades mais altas (higher-priority) primeiro.


=== Constrói? ===
<pre>
PHP_TARGETS="php5-4"
</pre>


* '''Constrói confiavelmente?'''
Add the following lines to <code>/etc/portage/package.use/php</code>:


O primeiro teste - o software constrói a partir do código fonte corretamente? Isso não se trata somente de emergir ebuilds no seu sistema -- OS builds do stage funcionam sem problemas utilizando o Metro? Se não, isso precisa ser corrigido primeiro. O Funtoo Linux continuamente constrói lançamentos do sistema operacional atualizados, e essas devem ser construídas confiavelmente em todos os momentos. O foco aqui é para builds 100% corretos e eficientes utilizando o Metro, e depois emergindo aplicações iniciais em um sistema Funtoo Linux.
<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>


=== Ele executa? ===
== Emerge ==


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


OK, ele constrói. Ele executa corretamente? Ele funciona? Isso é bem vago, então vamos colocar algumas especificações aqui. Quando instalar o Funtoo Linux a partir do stage3, tudo funciona? Quais complicações ou falhas foram  encontradas na instalação inicial? Essas devem ser corrigidas, ou soluções devem ser colocadas no lugar, e correções a longo prazo devem ser trabalhadas para melhorar a experiência do usuário. Lembre-se de que o foco do Funtoo Linux é no sistema central - Essa é a coisa que você toca quando você instala o Funtoo Linux pela primeira vez. Você deve reinstalar o Funtoo Linux regularmente para verificar por quaisquer questões e priorizar as questões de instalação do usuário e a experiência inicial do usuário.
<console>
# ##i##emerge --jobs xcache metalog postfix
</console>


=== Consigo Usá-lo? ===
== Start and Configure Services ==


* '''Facilmente?'''
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:
* '''Para Trabalho de Verdade?'''


OK, ele constrói, e executa. Mas eu posso realizar tarefas de verdade com a ferramenta? Qual é a facilidade ou dificuldade  de realizar essas tarefas? A tecnologia (e documentação) devem ser projetadas para oferecer suporte ao usuário na questão de realizar estas tarefas, ao invés de forçar o usuário a saltar por arcos para obter algo configurado corretamente. As coisas devem ser automatizadas o tanto o quanto possível sem assumir controle distante do usuário. Padrões seguros, razoáveis que são adequados para a cargas produtivas devem ser utilizadas por todas as aplicações. As coisas devem emergir sem bloqueadores ou ausência de recursos que devem ser habilitadas manualmente pelo usuário. E uma implicância - se o emerge parar para dizer ao usuário que ele deve definir uma variável USE para que continue, isso é algo que deve ser corrigido de um jeito ou de outro. Então, quando tudo é dito e feito, ele deve funcionar.
<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>


=== É Documentado? ===
== Database Setup ==


* '''Para projetos de software livre, documentação é a chave.'''
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>:


Se o software, executa e funciona, outros ainda podem ainda não ser capaz de utilizá-lo até que documentação adequada esteja disponível. Documentação montante nem sempre é completa ou fácil de entender, então frequente documentação adicional para usuário é necessária. Se etapas do manual são necessárias, elas devem ser documentadas claramente e corretamente. A opção de escolha da documentação é a Funtoo wiki tão bem quanto as man pages.
<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


Para o código fonte, comentários bem detalhados devem ser utilizados. Você pode estar trabalhando no código agora, mas outra pessoa poderá estar trabalhando nele daqui a seis meses. É esperado que desenvolvedores escrevam comentários claros que sejam suficientemente não-técnicos e forneça o contexto necessário para permitir que desenvolvedores menos experiente entendam partes criticas do código, e idealmente ''''todas'''' as partes do código. Por favor veja [[Coding_Standards/pt-br|Padrões de Código]].
Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.


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


* '''Otimizado?'''
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
* '''Sustentável?'''


Ele constrói e executa, e eu posso utilizá-lo para realizar trabalho de verdade. Mas o sistema é bem projetado? Ele funciona confiavelmente? Todos os patches estão disponíveis e corrige o lugar para assegurar uma experiencia computacional confiável? O Funtoo Linux está fornecendo a melhor tecnologia possível aos usuários? E essa tecnologia é fácil de manter? lembre-se, todas as coisas sendo iguais, menos código é melhor que mais código por que é mais fácil de manter. Há comentários detalhados no código aonde é necessário?
mysql> ##i##create database mediawiki;
Query OK, 1 row affected (0.01 sec)


=== Estamos melhorando? ===
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)


OK, estamos fazendo todas as etapas acima. Aqui está o próximo teste - estamos melhorando? A qualidade, segurança, usabilidade e a manutenção da distribuição está melhorando com o tempo, ou ela está subindo, e depois descendo, e não estamos mesmo tendo nenhum progresso? O objetivo no final do dia é obter progresso avançado no qualidade da distribuição. Isso requer automação melhor, ferramentas melhores, processos melhores, e investimento em pesquisa e desenvolvimento e novos métodos de fazer coisas. Isso também requer a atitude correta. Se estivermos fazendo um monte de trabalho e a qualidade global da distribuição não estiver melhorando, então nossos esforços não estão fazendo diferença a longo prazo, mesmo que eles possam estar tratando bugs e problemas imediatos. Temos que garantir que nossos esforços venham valer a pena, e que eles estão fazendo uma diferença positiva a longo prazo na qualidade da distribuição.
mysql> ##i##\q
Bye
#
</console>


=== Qual o verdadeiro problema? ===
== Nginx Setup ==


Construindo nesse tema - quando um bug é encontrado, qual é o ''verdadeiro'' problema, ou a ''raiz (root cause)''? Pensamento estratégico tão bem quanto uma resolução profunda (in-depth troubleshooting) é necessária para identificar a raiz do problema. Devemos somente corrigir as raízes? Não, isso é impraticável, por que fazer isso leva muito tempo. Ao invés disso, soluções alternativas são com frequência utilizadas para restauras rapidamente a qualidade à níveis aceitáveis. No entanto, somente implementar soluções alternativas é perigoso, por que os bugs tendem a multiplicar-se enquanto a questão subjacente não for solucionada. A solução adequada é implementar soluções alternativas mas não perder o foco no necessário para tratar as questões subjacentes, ou raízes, do problema. De fato, muito do foco do Funtoo Linux está nessa ultima etapa - agressivamente corrigindo um monte de questões imediatas assim nós podemos começar a tratar os problemas mais profundos de uma vez por todas...
We will use nginx as our Web server. Let's emerge it:


=== Arquitetura ===
<console>
# ##i##emerge --jobs nginx
</console>


...e tratar da raiz de problemas com frequência requer uma mudança significativa na arquitetura de software. Funtoo Linux é um projeto que não tem medo de fazer alterações arquitetônicas significantes, e mesmo agressivas, a fim de corrigir problemas. Isso é o que os nossos usuários esperam que façamos, e ''desde que essas alterações sejam propriamente testadas, gerenciadas, planejadas, automatizadas e comunicadas aos usuários'', eles não irão se chatear. Conforme declarado no parágrafo anterior, o projeto Funtoo Linux é zeloso a respeito de tratar esses problemas centrais de arquitetura -- mas nós precisamos controlar os desafios mais fundamentais primeiro. Uma vez soluções alternativas estão no lugar, levaremos uma punhalada em alguma alteração no sistema central que pagarão dividendos bem no futuro.
== User and Group ==


== Exemplos ==
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:


Abaixo, você encontrará exemplos de esforços que tem alinhados a esses objetivos. Essa seção lhe dará uma sensação do quanto projetos reais podem ser iniciados que se alinham com a visão do Funtoo Linux definida acima.
<console>
# ##i##groupadd docs
# ##i##useradd -g docs --home /home/docs docs
# ##i##install -d /home/docs
# ##i##chown -R docs:docs /home/docs
</console>


=== Boot-Update ===
== Set up PHP ==


[[Boot-Update/pt-br|Boot-Update]] foi projetado por Daniel Robbins para prover um jeito mais elegante de configurar o carregador de boot sob o Funtoo Linux. Esse projeto foi priorizado por várias rasões. Uma, esse projeto tinha que fazer com que a experiência da instalação inicial (veja [[#Ele executa?]]) Também, ausência do suporte ao GRUB2, tão bem quanto o suporte ao GPT/GUID, foi definido como um ponto fraco crítica na funcionalidade atual do Gentoo Linux (veja [[#É bem projetado?]]) Por isso, um novo configurador unificado foi escrito que utiliza <tt>/etc/boot.conf</tt> como arquivo de configuração para o carregador de boot global. Isso representa a mudança na arquitetura do carregador de boot (veja [[#Arquitetura]]) sob o  Funtoo Linux, a fim de melhorar a usabilidade e a flexibilidade em soluções existentes, e tentar reduzir ou eliminar uma classe de problemas relacionadas a configuração do carregador de boot, que é especialmente problemático no GRUB2.
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):


=== Metro ===
{{file|name=/etc/php/fpm-php5.4/php-fpm.conf|desc= |body=
[global]
error_log = /var/log/php-fpm.log
log_level = notice


[[Metro]] foi projetado por Daniel Robbins e é utilizado para tratar a questão do "[[#Constrói?]]". A solução existente, catalyst, foi difícil de manter (veja [[#É bem projetado?]]), então Metro foi desenvolvido para prover um novo mecanismo para a construção de lançamentos de sistema operacional (OS releases).
[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>.


=== Forked Ebuilds ===
== Configure Nginx ==


Nem todas as melhoras envolvem grandes esforços no desenvolvimento de software. De fato, a maioria das correções envolvem correções relativamente pequenas para os ebuilds. Essas correções são com frequência feitas para corrigir uma falha no Metro build (veja [[#Constrói?]]) ou tratar de alguma questão de qualidade (veja [[#É bem projetado?]]). O ebuild <tt>www-servers/nginx</tt> foi melhorado para prover melhores configurações padrões para sistemas de produção, com alterações correspondentes feitas ao <tt>sys-libs/pam</tt> para permitir que isso funcione. <tt>dev-lang/python</tt> contem correções para assegurar que o contem correções para assegurar que Metro builds complete corretamente e um symlink <tt>/usr/bin/python</tt> válido sempre exista.
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:


=== OpenVZ ===
<pre>
server {
        listen 80;
        server_name wiki.mysite.com;


Suporte a OpenVZ é uma prioridade específica do Funtoo Linux. Funtoo Linux mantem um patched <tt>sys-cluster/vzctl</tt> com vários patches para corrigir uma variedade de  problemas. Em adição, <tt>openvz-rhel6-stable</tt> e <tt>openvz-rhel5-stable</tt> ebuilds tem sido criados para facilitar a instalação de kernels OpenVZ de qualidade para produção (veja [[#Consigo Usá-lo?]]) em adição, documentação [[OpenVZ]] existe no wiki (veja [[#Consigo Usá-lo?]])
        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;


[[Category:QA]]
        # 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 ==
 
Now, let's enable nginx to serve our site, and also be sure to enable php-fpm:
 
<console>
# ##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>
 
== 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>
# ##i##cd /var/tmp
# ##i##wget http://download.wikimedia.org/mediawiki/1.19/mediawiki-1.19.1.tar.gz
</console>
 
== 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>
# ##i##su docs
$ ##i##cd /var/tmp
$ ##i##tar xvf ./mediawiki-1.19.1.tar.gz
$ ##i##mv mediawiki-1.19.1 ~/public_html
</console>
 
== MediaWiki from GIT ==
 
Alternatively, we can download the code from the git repository:
 
<console>
# ##i##su docs
$ ##i##cd ~
$ ##i##git clone https://gerrit.wikimedia.org/r/p/mediawiki/core.git public_html
</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>
$ ##i##git checkout 1.19.1
</console>
 
== 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 <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.
 
== 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
 
=== 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 <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:
 
<pre>
$wgScriptPath      = "";
$wgScriptExtension  = ".php";
</pre>
 
Change this part of the file to look like this:
 
<pre>
$wgScriptPath      = "";
$wgArticlePath      = "/$1";
$wgUsePathInfo      = true;
$wgScriptExtension  = ".php";
</pre>
 
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 <code>$wgSpamRegex</code> in <code>LocalSettings.php</code>, like so:
 
<pre>
$wgSpamRegex = "/badword1|badword2|badword3/i"
</pre>
 
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 <code>LocalSettings.php</code>:
 
<pre>
$wgEnableDnsBlacklist = true;
$wgDnsBlacklistUrls = array( 'xbl.spamhaus.org', 'opm.tornevall.org' );
</pre>
 
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
 
{{file|name=/var/www/localhost/htdocs/mediawiki/LocalSettings.php|lang=php|desc=set external links to open in a new tab|body=
...
$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:
 
{{file|name=/var/www/localhost/htdocs/mediawiki/LocalSettings.php|lang=php|desc=enabling arbitrary html|body=
...
$wgRawHtml = "true";
}}
 
=== $wgServer ===
 
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 installation.  The 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.
 
=== $wgLogo ===
 
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:
 
<pre>
$wgLogo = "image.png"
</pre>
{{fancynote| The above references the file <code>image.png</code> in the directory <code>/home/docs/public_html</code>}}
 
=== MySQL wildcard searches ===
Recent versions of mediawiki have broken search results.
 
{{file|name=/var/www/localhost/htdocs/mediawiki/includes/search/SearchMySQL.php|lang=php|desc=line 175 modification to repair mysql searches|body=
if ( trim( $term ) === '' ) {
return null;
} else {
$term = $term . '*';
}
}}
 
=== License Badges ===
You can have licenses displayed with your pages.
 
{{file|name=/var/www/localhost/htdocs/mediawiki/LocalSettings.php|lang=php|desc=add license badge to articles|body=
$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.
 
{{file|name=localhost/MediaWiki:Common.css|lang=css|desc=|body=
@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.
 
{{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);
}}
 
== Media ==
{{#widget:YouTube|playlist=PL7ABDor6eEgc2U9PH4Irty4K8mqUgkvDq}}
 
== 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
 
[[Category:Featured]]
[[Category:HOWTO]]
[[Category:Official Documentation]]
[[Category:Ebuilds]]
{{EbuildFooter}}

Revision as of 07:36, 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

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