きっかけはWordPressプラグインにしたいわけではなく、はたまた独自ドメインで短縮URLサービスを開きたいわけでもなく、「サイボウズ Office」...これのURLがやたら長くて、メールで送りたいときにOutlookの最大135文字を超える→アクセスできないって言われる→HTMLメールで送ればいいけど...→でもHTMLメールってなんか嫌。

社内に短縮URLシステムあったら便利じゃない?って思って探したのが「YOURLS」です。


OSの準備 とか
 
VMWare ESXiにCentOS 5.7デフォルト環境にインストールしています。
※インストールディスクはCentOS 5.5。yumで5.7にしています。


Apacheインストール
[root@s ~]# yum install httpd -y
入ったのは「2.2.3-53.el5.centos.3」。


Apacheコンフィグ変更

Rewriteが有効でないといけないので、そこだけ修正。
[root@s html]# vim /etc/httpd/conf/httpd.conf
327     #AllowOverride None
328     AllowOverride All

PHPインストール
[root@s ~]# yum install php -y
入ったのは「5.1.6-27.el5_7.5」。


MySQLインストール
[root@s ~]# yum install mysql-server mysql -y
クライアントも一緒にインストール。入ったのは「5.0.95-1.el5_7.1」。


php-mysqlインストール
[root@s ~]# yum install php-mysql
入ったのは「5.1.6-27.el5_7.5」。


MySQLコンフィグ修正

UTF-8に対応させる(よくある設定)。 
[root@s ~]# vim /etc/my.cnf

 [mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
user=mysql
# Default to using old password format for compatibility with mysql 3.x
# clients (those using the mysqlclient10 compatibility package).
old_passwords=1
default-character-set=utf8  //追加
character_set_server=utf8  //追加
skip-character-set-client-handshake  //追加

[mysqld_safe]
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid

[mysql]  //追加
default-character-set=utf8  //追加

Apacheを起動
[root@s ~]# /etc/init.d/httpd start
httpd を起動中:                                            [  OK  ]

MySQL Serverを起動
 
初回起動なので色々言われるが、パスワード設定とか、とりあえずあまり気にしない...。
[root@s ~]# /etc/init.d/mysqld start
MySQL データベースを初期化中:  Installing MySQL system tables...
OK
Filling help tables...
OK

To start mysqld at boot time you have to copy
support-files/mysql.server to the right place for your system

PLEASE REMEMBER TO SET A PASSWORD FOR THE MySQL root USER !
To do so, start the server, then issue the following commands:
/usr/bin/mysqladmin -u root password 'new-password'
/usr/bin/mysqladmin -u root -h s.i2ts.local password 'new-password'

Alternatively you can run:
/usr/bin/mysql_secure_installation

which will also give you the option of removing the test
databases and anonymous user created by default.  This is
strongly recommended for production servers.

See the manual for more instructions.

You can start the MySQL daemon with:
cd /usr ; /usr/bin/mysqld_safe &

You can test the MySQL daemon with mysql-test-run.pl
cd mysql-test ; perl mysql-test-run.pl

Please report any problems with the /usr/bin/mysqlbug script!

The latest information about MySQL is available on the web at
http://www.mysql.com
Support MySQL by buying support/licenses at http://shop.mysql.com
                                                           [  OK  ]
MySQL を起動中:                                            [  OK  ]


YOURLS用のデータベースを作成

MySQLのパスワード設定してないとか、とりあえず気にしない。
[root@s ~]# mysql -u root -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.0.95 Source distribution

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 yourls;
Query OK, 1 row affected (0.00 sec)

mysql> \q
Bye

YOURLSダウンロード
[root@s ~]# wget http://yourls.googlecode.com/files/yourls-1.5.zip

ダウンロードしたファイルの解凍
 
実はunzipコマンドをはじめてつかっているので、なんか手順が変だけれどあまり気にしない。
[root@s ~]# mkdir yourls
[root@s ~]# mv yourls-1.5.zip ./yourls
[root@s ~]# cd yourls/
[root@s yourls]# unzip yourls-1.5.zip

解凍したディレクトリを、Apacheのディレクトリへ移動。
[root@s yourls]# mv ~/yourls/* /var/www/html/

ファイル所有者をApacheに変更。
[root@s html]# chown -R apache /var/www/html

サンプルをコピーして、config.phpにリネームしてコンフィグファイルを作成。 
[root@s html]# cd ./includes/
[root@s includes]# cp -p config-sample.php config.php

コンフィグを編集します。
[root@s includes]# vim config.php
<?php
/* This is a sample config file.
 * Edit this file with your own settings and save it as "config.php"
 * You can leave it in the "includes" directory, or, better, move it to
 * the "user" directory. This way, when a new version of YOURLS is available,
 * simply delete everything but "/user", and upload the new version.
 */


/*
 ** MySQL settings - You can get this info from your web host
 */

/** MySQL database username */
define( 'YOURLS_DB_USER', 'root' ); ←MySQLサーバのログインユーザ

/** MySQL database password */
define( 'YOURLS_DB_PASS', '' );   ←MySQLサーバのログインパスワード

/** The name of the database for YOURLS */
define( 'YOURLS_DB_NAME', 'yourls' ); ←先ほど作ったデータベース名

/** MySQL hostname */
define( 'YOURLS_DB_HOST', 'localhost' );  ←データベースサーバ名。今回はローカルなので「localhost」

/** MySQL tables prefix */
define( 'YOURLS_DB_PREFIX', 'yourls_' );  ←データベースを共有したりするときに、区別するための頭文字。とりあえずデフォルトのままで。

/*
 ** Site options
 */

/** YOURLS installation URL, no trailing slash */
define( 'YOURLS_SITE', 'http://s.url.local' );  ←サイトのURL。ここを正しく設定しないと動作しない。

/** Timezone GMT offset */
define( 'YOURLS_HOURS_OFFSET', 0 );

/** Allow multiple short URLs for a same long URL
 ** Set to true to have only one pair of shortURL/longURL (default YOURLS behavior)
 ** Set to false to allow multiple short URLs pointing to the same long URL (bit.ly behavior) */
define( 'YOURLS_UNIQUE_URLS', true );

/** Private means protected with login/pass as defined below. Set to false for public usage. */
define( 'YOURLS_PRIVATE', true );  ←管理画面にパスワードを付けないなら「false」に変更。

/** A random secret hash used to encrypt cookies. You don't have to remember it, make it long and complicated. Hint: copy from http://yourls.org/cookie **/
define( 'YOURLS_COOKIEKEY', 'qQ4KhL_pu|s@Zm7n#%:b^{A[vhm' );

/**  Username(s) and password(s) allowed to access the site */
$yourls_user_passwords = array(   ←ここでユーザ名とパスワードを設定する。今回はデフォルトで。
        'username' => 'password',
        'username2' => 'password2'      // You can have one or more 'login'=>'password' lines
        );


/*
 ** URL Shortening settings
 */

/** URL shortening method: 36 or 62 */
define( 'YOURLS_URL_CONVERT', 36 );
/*
 * 36: generates case insentitive lowercase keywords (ie: 13jkm)
 * 62: generate case sensitive keywords (ie: 13jKm or 13JKm)
 * Stick to one setting, don't change after you've created links as it will change all your short URLs!
 * Base 36 should be picked. Use 62 only if you understand what it implies.
 */

/**
* Reserved keywords (so that generated URLs won't match them)
* Define here negative, unwanted or potentially misleading keywords.
*/
$yourls_reserved_URL = array(
        'porn', 'faggot', 'sex', 'nigger', 'fuck', 'cunt', 'dick', 'gay',
);

/*
 ** Personal settings would go after here.
 */

サンプルをコピーして、トップページを作成します。
[root@s html]# cp -p sample-public-front-page.php.txt index.php

YOURLSインストールスクリプト実行

http://s.url.local/ にアクセスすると、自動的に http://s.url.local/admin/install.php にリダイレクトされます。


install YOURLSをクリックします。
01

.htaccessとMySQLのテーブルが作成されます。
02

管理画面へログイン

インストール完了画面の[YOURLS Administration Page]をクリックすると、管理画面にいきます。
Username/Passwordはコンフィグで設定したもの。変更していなければは「username/password」です。
03

ログインすると、すでにちょこっと入ってる。
 04


さっそく使ってみよう!!!

http://s.url.local/ にアクセス

「URL:」に適当なURLを入れて、[Shorten]をクリック(Googleの検索結果などが長くてオススメ)。
05

その結果、「http://s.url.local/1」というURLが生成されます
06

これをクリックすると、自動的にリダイレクトされます
07


プラグイン

Twitterとかで使ってるみたいに、ドメインのあとは数字じゃなくて「hJudjK」みたいな感じじゃないと、なんだかカッコよくない。
なので、PluginRandomKeywordsというプラグインを入れます。 


ディレクトリを作成
 [root@s plugins]# mkdir /var/www/html/user/plugins/random-keyword

ディレクトリに移動
[root@s plugins]# cd /var/www/html/user/plugins/random-keyword

「plugin.php」というファイルを作成
[root@s random-keyword]# vim plugin.php

下記を貼り付け
<?php
/*
Plugin Name: Random Keywords
Plugin URI: http://yourls.org/
Description: Assign random keywords to shorturls, like bitly (sho.rt/hJudjK)
Version: 1.1
Author: Ozh
Author URI: http://ozh.org/
*/

/* Release History:
 *
 *  1.0    Initial release
 *  1.1    Added: don't increment sequential keyword counter & save one SQL query
 *         Fixed: plugin now complies to character set defined in config.php
 */

global $ozh_random_keyword;

/*
 * CONFIG: EDIT THIS
 */

/* Length of random keyword */
$ozh_random_keyword['length'] = 5;

/*
 * DO NOT EDIT FARTHER
 */

// Generate a random keyword
yourls_add_filter( 'random_keyword', 'ozh_random_keyword' );
function ozh_random_keyword() {
        global $ozh_random_keyword;
        return yourls_rnd_string( $ozh_random_keyword['length'] );
}

// Don't increment sequential keyword tracker
yourls_add_filter( 'get_next_decimal', 'ozh_random_keyword_next_decimal' );
function ozh_random_keyword_next_decimal( $next ) {
        return ( $next - 1 );
}

YOURS管理画面に戻り、[Plugins]ページに行き、Random Keywordsの[Active]ボタンをクリックします
 08

Activeになります
 09


再度 http://s.url.local/ からURLを入力して、[Shoten]をクリックします
10

Twitterなどで良く見る感じのアドレスになりました。
11

オマケ

Apache, MySQLの自動起動

継続して使うなら、自動起動設定に。
[root@s ~]# chkconfig httpd on
[root@s ~]# chkconfig mysqld on

Quick Shareの文字化け

Quick Shareと、管理ページの「Stats」を開いたときに、titleが文字化けします。
リンク先ページがUTF-8以外の場合に発生するようです。

ちょこっとソース見てみようとも思いましたが、YOURLS Blogにバグと書いてありますので、今のところどうしようもないと思われますので、あきらめました。
But it still sucks :(
 
All things are not perfect yet and there will be a few bugs to axe. In particular, you may experience a few kinks when YOURLS will be fetching the title of a remote page with funky characters.
YOURLS 1.5 Released (YOURLS Blog)

しかし「funky characters」って...。


DBのスキーマ

シンプル。テーブル3つしかない。
mysql> show tables;
++
| Tables_in_yourls |
++
| yourls_log       |
| yourls_options   |
| yourls_url       |
++
3 rows in set (0.00 sec)
各テーブルのカラムも少ない。
mysql> describe yourls_log;
+-----+-----+------+-----++-------+
| Field        | Type         | Null | Key | Default | Extra          |
+-----+-----+------+-----++-------+
| click_id     | int(11)      | NO   | PRI | NULL    | auto_increment |
| click_time   | datetime     | NO   |     | NULL    |                |
| shorturl     | varchar(200) | NO   | MUL | NULL    |                |
| referrer     | varchar(200) | NO   |     | NULL    |                |
| user_agent   | varchar(255) | NO   |     | NULL    |                |
| ip_address   | varchar(41)  | NO   |     | NULL    |                |
| country_code | char(2)      | NO   |     | NULL    |                |
+-----+-----+------+-----++-------+
7 rows in set (0.00 sec)
mysql> describe yourls_options;
+-----+---+------+-----++-------+
| Field        | Type                | Null | Key | Default | Extra          |
+-----+---+------+-----++-------+
| option_id    | bigint(20) unsigned | NO   | PRI | NULL    | auto_increment |
| option_name  | varchar(64)         | NO   | PRI |         |                |
| option_value | longtext            | NO   |     | NULL    |                |
+-----+---+------+-----++-------+
3 rows in set (0.00 sec)
mysql> describe yourls_url;
+--++------+-----+-+-------+
| Field     | Type             | Null | Key | Default           | Extra |
+--++------+-----+-+-------+
| keyword   | varchar(200)     | NO   | PRI | NULL              |       |
| url       | text             | NO   |     | NULL              |       |
| title     | text             | YES  |     | NULL              |       |
| timestamp | timestamp        | NO   | MUL | CURRENT_TIMESTAMP |       |
| ip        | varchar(41)      | NO   | MUL | NULL              |       |
| clicks    | int(10) unsigned | NO   |     | NULL              |       |
+--++------+-----+-+-------+
6 rows in set (0.00 sec)
でも、仕様を考えるとこんなもんか...。


参考