2012年6月11日月曜日

お名前.com VPS scientific linuxをインストール

お名前.comのVPS(2GB)を借りたので、Scientific Linuxをインストールしてみました。

まずはコントロールパネルから「OS再インストール」を選びます。OSとして、Scientific Linux 6.2 (64bit)を選び、ディスク構成はお好みで。私は1パーティションにします。

確認、実行と進んでいきます。
次にコントロールパネルの「コンソール画面」を選びます。


上に並んでいる「起動」をクリックします。


カーソルを一番上の「Install or upgrade an existing system」に合わせて、リターンキーを押します。


メディアチェックはどちらでも構わないと思いますので、OKかSkip好きな方を選択します。

次のインストール中の言語設定は、日本語は使えないので英語のままでも問題ないのですが、Japaneseを選んでおくと、タイムゾーン設定が少し楽になります。


次のキーボードタイプは、環境にもよりますが、jp106の日本語キーボードを選択します。


次が一番はまりやすいインストールイメージの選択画面です。正解は「URL」ですのでお間違い無く!

ネットワークの設定ですが、私はまだIPv6を使っていないので無効にしますが、どちらでも構わないと思います。


さて、次にイメージを置いてあるサーバーのURLを指定するのですが、公式サイトから最寄りのミラーサイトを見つけます。私は埼玉のKDDIにしました。64bitをインストールするので、入力するアドレスは、http://ftp.ne.jp/Linux/distributions/scientificlinux/6.2/x86_64/os/
となります。

正しく入力すれば次の画面になります。


分かりにくいのですが、右下にスクロールすると、「次⇒」というのが表示されていますので、それをクリックします。


どんどん画面を進めていきます。

タイムゾーンの設定ですが、ここは次のように設定し、デフォルトでついている「システムクロックでUTCを使用」のチェックを外した方がすっきりしていいと思います。



インストールパーティションは次のようにしておきます。


パーティションのレイアウトは、最初このようになっていると思います。


LVMをrootとhomeで分ける必要を感じないので、削除して1つにまとめます。
まず、lv_homeを選択して削除。そして、lv_rootを選択して編集。サイズを最大に変更します。



これで次へ進みます。


Write changes to diskを押して変更を書き込みます。

これで次へ進みます。


このまま次へ進みます。


必要最低限のパッケージだけをインストールしたいので、Minimalを選びます。
インストールが開始されますので、しばらくお待ち下さい。
終わったら、インストールイメージを取り出して、リブートします。

以上で無事にインストールできました。

2012年6月4日月曜日

WordPressのページタイトルをいじりたい

URLパラメータとして ?keyword=hogehoge が指定されたら、ページタイトルにそのパラメータを追加するということをやってみました。 function.phpの中で、wp_titleをhookしてあげればいいようです。
function yk_title_filter($title, $sep, $seplocation) {
    // If it's a item_search page                                                                                  
    if (isset($_GET['keyword'])) {
        if ('right' == $seplocation) {
            $title = $_GET['keyword'] . " $sep " . $title;
 } else {
            $title = $title . " $sep " . $_GET['keyword'];
 }
    }

    return $title;
}
add_filter('wp_title', 'yk_title_filter', 10, 3);

http://r.hatena.ne.jp/rpc could not be pinged. Error message: "transport error - HTTP status code was not 200"

http://r.hatena.ne.jp/rpc could not be pinged. Error message: "transport error - HTTP status code was not 200"
サービス終了のお知らせ

http://hamo-search.com/ping.php could not be pinged. Error message: "transport error - HTTP status code was not 200"

http://hamo-search.com/ping.php could not be pinged. Error message: "transport error - HTTP status code was not 200"
HARMONY SEARCHにつきまして5/6にサービスを終了いたしました。 今までのご利用ありがとうございました。
ということで、サービス終了ですので、エントリーを削除しました。

http://ping.ask.jp/xmlrpc.m could not be pinged. Error message: "transport error - could not open socket"

http://ping.ask.jp/xmlrpc.m could not be pinged. Error message: "transport error - could not open socket"
どうやらpingサーバーは廃止されているようです。 sitemapは受け付けているようなので、そちらで代用することにしました。
http://submissions.ask.com/ping?sitemap=http%3A//www.the URL of your sitemap here.xml

http://blog.goo.ne.jp/XMLRPC could not be pinged. Error message: "transport error - HTTP status code was not 200"

http://blog.goo.ne.jp/XMLRPC could not be pinged. Error message: "transport error - HTTP status code was not 200"
PingのUser-Agentを以下のように変更することで、成功するようになります。 私はWordPress Ping Optimizerを使っているので、以下のファイルを編集します。 cbnet-ping-optimizer.php
$client->useragent .= ' lumiukkoblog/1.0.0';
結果は以下の通り。
http://blog.goo.ne.jp/XMLRPC was successfully pinged
WordPressは嫌われているらしい;;

http://ping.bloggers.jp/rpc/ could not be pinged. Error message: "parse error. not well formed"

http://ping.bloggers.jp/rpc/ could not be pinged. Error message: "parse error. not well formed"
サービス終了のようです。 エントリーを削除。

CLICKYのAPIを使って逆アクセスリンクを作る

CLICKY web analyticsのAPIを使って、逆アクセスリンクを作ってみます。 詳細は、HELP->API->Analytics APIに書いてあります。
<?php
// prereq                                                                                                        
require 'scrape_func.php';
mb_language("Japanese");

// parameters                                                                                                    
$base_url = 'http://api.getclicky.com/api/stats/4';
$params['site_id'] = '99999999';
$params['sitekey'] = 'XXXXXXXXXXXXXXXX';
$params['type'] = 'links';
$params['output'] = 'xml';
$params['limit'] = 5;
$params['date'] = 'last-7-days';

// canonical string                                                                                              
$canonical_string = '';
foreach ($params as $k => $v) {
    $canonical_string .= '&' . $k . '=' . $v;
}
$canonical_string = substr($canonical_string, 1);

// make request                                                                                                  
$request = $base_url . '?' . $canonical_string;
//print_r($request);                                                                                             

// catch the response                                                                                            
$response = file_get_contents($request);
$xml = simplexml_load_string($response);
?>
<ul class="recentcomments">
<?php
for ($rank = 0; $rank < 5; $rank++) :
    $item = $xml->type->date->item[$rank];
//    var_dump($item);                                                                                           
    if (empty($item)) break;
    $url = $item->url;
    $contents = getURL($url);
    $contents = mb_convert_encoding($contents, "UTF-8", "auto");
    $contents = cleanString($contents);
    $title = getElement("title", $contents);
?>
<li class="recentcomments">
      <a href="<?php echo $url; ?>" class="url"><?php echo $rank+1;?>位 <?php echo $title; ?></a>
</li>
<?php
endfor
?>
</ul>
Clickyはスパイなど機能も充実していてお気に入りの分析サービスです。

WordPress: タグ入力の際にエンターキーで入力してしまう

WordPressのタグ入力の際に、エンターキーを押すと変換を確定するのと同時にタグも確定して入力してしまう。 それを回避するには、/wp-admin/js/post.jsの.keyupを.keypressに変換する。

記事に画像を連続して挿入できるようにする

記事に画像を追加する度に、メディア挿入の画面が閉じてしまうので、非常に効率が悪いです。

メディアアップロードを別ウィンドウに

/wp-admin/includes/media.php
        echo '<a href="' . esc_url( get_upload_iframe_src() ) . '" class="thickbox add_media" id="' . esc_attr( $editor_id ) . '-add_media" title="' . esc_attr__( 'Add Media' ) . '" onclick="return false;">' . sprintf( $context, $img ) . '</a>';
        echo "<a href=\"javascript:w=window.open('" . str_replace('TB_iframe=1', 'TB_iframe=0', esc_url(get_upload_iframe_src())) . "','','scrollbars=yes,Width=650,Height=700,top=0,left=0');w.focus();\" id=\"add_image\" title='" . esc_attr__('Add Media') . "' onclick='return true;'><img src='images/media-button-image.gif' alt='' /></a>";
もしくはこっちでもいいかもしれません。
        echo '<a href="' . esc_url( get_upload_iframe_src() ) . '" class="thickbox add_media" id="' . esc_attr( $editor_id ) . '-add_media" title="' . esc_attr__( 'Add Media' ) . '" onclick="return false;">' . sprintf( $context, $img ) . '</a>';
        echo "<a href=\"javascript:w=window.open('" . esc_url(get_upload_iframe_src()) . "','','scrollbars=yes,Width=650,Height=700,top=0,left=0');w.focus();\" id=\"add_image\" title='" . esc_attr__('Add Media') . "' onclick='return true;'><img src='images/media-button-image.gif' alt='' /></a>";

挿入した後に戻る

私は、Custom Field Templateプラグインを使用しているため、media_send_to_editorがフックされています。 そのため、修正するのは/wp-content/plugins/custom-field-template/custom-field-template.phpとなります。
        function media_send_to_custom_field($html) {
                $out =  '<script type="text/javascript">' . "\n" .
                                        '       /* <![CDATA[ */' . "\n" .
                                        '       var win = window.dialogArguments || opener || parent || top;' . "\n" .
                                        '   if ( typeof win.send_to_custom_field == "function" ) ' . "\n" .
                                        '           win.send_to_custom_field("' . addslashes($html) . '");' . "\n" .
                                        '   else ' . "\n" .
                                        '       win.send_to_editor("' . addslashes($html) . '");' . "\n" .
                    '   history.back();' . "\n" .
                                        '/* ]]> */' . "\n" .
                                        '</script>' . "\n";

                echo $out;
                exit();

history.back();を追加するということですね。 Good Luck!

APCインストールと設定

前提モジュールをインストール。
# yum -y install php53u-devel httpd-devel
Loaded plugins: fastestmirror, priorities, security
Loading mirror speeds from cached hostfile
 * epel: ftp.iij.ad.jp
 * ius: mirror.sothatswhy.org.uk
 * sl: ftp.riken.jp
 * sl-security: ftp.riken.jp
99 packages excluded due to repository priority protections
Setting up Install Process
Resolving Dependencies
--> Running transaction check
---> Package httpd-devel.x86_64 0:2.2.15-15.sl6.1 will be installed
--> Processing Dependency: apr-util-devel for package: httpd-devel-2.2.15-15.sl6.1.x86_64
--> Processing Dependency: apr-devel for package: httpd-devel-2.2.15-15.sl6.1.x86_64
---> Package php53u-devel.x86_64 0:5.3.10-1.ius.el6 will be installed
--> Running transaction check
---> Package apr-devel.x86_64 0:1.3.9-3.el6_1.2 will be installed
---> Package apr-util-devel.x86_64 0:1.3.9-3.el6_0.1 will be installed
--> Processing Dependency: openldap-devel for package: apr-util-devel-1.3.9-3.el6_0.1.x86_64
--> Processing Dependency: db4-devel for package: apr-util-devel-1.3.9-3.el6_0.1.x86_64
--> Processing Dependency: expat-devel for package: apr-util-devel-1.3.9-3.el6_0.1.x86_64
--> Running transaction check
---> Package db4-devel.x86_64 0:4.7.25-16.el6 will be installed
--> Processing Dependency: db4-cxx = 4.7.25-16.el6 for package: db4-devel-4.7.25-16.el6.x86_64
--> Processing Dependency: libdb_cxx-4.7.so()(64bit) for package: db4-devel-4.7.25-16.el6.x86_64
---> Package expat-devel.x86_64 0:2.0.1-9.1.el6 will be installed
---> Package openldap-devel.x86_64 0:2.4.23-20.el6 will be installed
--> Processing Dependency: cyrus-sasl-devel >= 2.1 for package: openldap-devel-2.4.23-20.el6.x86_64
--> Running transaction check
---> Package cyrus-sasl-devel.x86_64 0:2.1.23-13.el6 will be installed
---> Package db4-cxx.x86_64 0:4.7.25-16.el6 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

========================================================================================================
 Package                     Arch              Version                     Repository              Size
========================================================================================================
Installing:
 httpd-devel                 x86_64            2.2.15-15.sl6.1             sl-security            146 k
 php53u-devel                x86_64            5.3.10-1.ius.el6            ius                    613 k
Installing for dependencies:
 apr-devel                   x86_64            1.3.9-3.el6_1.2             sl                     175 k
 apr-util-devel              x86_64            1.3.9-3.el6_0.1             sl                      68 k
 cyrus-sasl-devel            x86_64            2.1.23-13.el6               sl                     301 k
 db4-cxx                     x86_64            4.7.25-16.el6               sl                     589 k
 db4-devel                   x86_64            4.7.25-16.el6               sl                     6.6 M
 expat-devel                 x86_64            2.0.1-9.1.el6               sl                     118 k
 openldap-devel              x86_64            2.4.23-20.el6               sl                     1.1 M

Transaction Summary
========================================================================================================
Install       9 Package(s)

Total download size: 9.6 M
Installed size: 37 M
Downloading Packages:
(1/9): apr-devel-1.3.9-3.el6_1.2.x86_64.rpm                                      | 175 kB     00:00     
(2/9): apr-util-devel-1.3.9-3.el6_0.1.x86_64.rpm                                 |  68 kB     00:00     
(3/9): cyrus-sasl-devel-2.1.23-13.el6.x86_64.rpm                                 | 301 kB     00:00     
(4/9): db4-cxx-4.7.25-16.el6.x86_64.rpm                                          | 589 kB     00:00     
(5/9): db4-devel-4.7.25-16.el6.x86_64.rpm                                        | 6.6 MB     00:01     
(6/9): expat-devel-2.0.1-9.1.el6.x86_64.rpm                                      | 118 kB     00:00     
(7/9): httpd-devel-2.2.15-15.sl6.1.x86_64.rpm                                    | 146 kB     00:00     
(8/9): openldap-devel-2.4.23-20.el6.x86_64.rpm                                   | 1.1 MB     00:00     
(9/9): php53u-devel-5.3.10-1.ius.el6.x86_64.rpm                                  | 613 kB     00:02     
--------------------------------------------------------------------------------------------------------
Total                                                                   1.6 MB/s | 9.6 MB     00:05     
Running rpm_check_debug
Running Transaction Test
Transaction Test Succeeded
Running Transaction
  Installing : apr-devel-1.3.9-3.el6_1.2.x86_64                                                     1/9 
  Installing : expat-devel-2.0.1-9.1.el6.x86_64                                                     2/9 
  Installing : db4-cxx-4.7.25-16.el6.x86_64                                                         3/9 
  Installing : db4-devel-4.7.25-16.el6.x86_64                                                       4/9 
  Installing : cyrus-sasl-devel-2.1.23-13.el6.x86_64                                                5/9 
  Installing : openldap-devel-2.4.23-20.el6.x86_64                                                  6/9 
  Installing : apr-util-devel-1.3.9-3.el6_0.1.x86_64                                                7/9 
  Installing : httpd-devel-2.2.15-15.sl6.1.x86_64                                                   8/9 
  Installing : php53u-devel-5.3.10-1.ius.el6.x86_64                                                 9/9 

Installed:
  httpd-devel.x86_64 0:2.2.15-15.sl6.1              php53u-devel.x86_64 0:5.3.10-1.ius.el6             

Dependency Installed:
  apr-devel.x86_64 0:1.3.9-3.el6_1.2                 apr-util-devel.x86_64 0:1.3.9-3.el6_0.1           
  cyrus-sasl-devel.x86_64 0:2.1.23-13.el6            db4-cxx.x86_64 0:4.7.25-16.el6                    
  db4-devel.x86_64 0:4.7.25-16.el6                   expat-devel.x86_64 0:2.0.1-9.1.el6                
  openldap-devel.x86_64 0:2.4.23-20.el6             

Complete!
APCモジュールをインストール。
# pecl install apc
/etc/php.d/にapc.iniファイルを作成。
extension=apc.so
[APC]
apc.enabled = 1
apc.shm_size = 64M
サービスを再読込。
# service php-fpm reslaod

ab: apr_poll: The timeout specified has expired (70007)

ab -c 100 -n 100 あたりで実行していると、以下のメッセージがでて計測できない。
$ ab -c 100 -n 100 http://blog.lumiukko.jp/
This is ApacheBench, Version 2.3 <$Revision: 655654 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking blog.lumiukko.jp (be patient)...apr_poll: The timeout specified has expired (70007)
ab -c 40 -n 100 は問題なし。ab -c 50 -n 100 はエラー。 調査中。

セッションディレクトリのパーミッション

Warning: Unknown: open(/var/lib/php/session/sess_1puk89hmb1sbsp6qi96laldnb7, O_RDWR) failed: Permission denied (13) in Unknown on line 0 Warning: Unknown: Failed to write session data (files). Please verify that the current setting of session.save_path is correct (/var/lib/php/session) in Unknown on line 0 /var/lib/php/sessionのパーミッションを確認。
# ls -l /var/lib/php/
合計 4
drwxrwx--- 2 root apache 4096  2月  3 08:37 2012 session
グループをnginxに変更。
# chgrp nginx session

strtotime()で警告メッセージ

PHP Warning: strtotime(): It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'Asia/Tokyo' for 'JST/9.0/no DST' instead in /var/www/html/blog/wp-content/themes/lumiukko/make_ranking_inboundlink.php on line 16 /etc/php.iniファイルを編集。
[Date]
; Defines the default timezone used by the date functions
; http://www.php.net/manual/en/datetime.configuration.php#ini.date.timezone
date.timezone = "Asia/Tokyo"

emacs定義ファイル

~/.emacs.d/init.elのメモ
;(setq make-backup-files nil)
;(setq auto-save-default nil)

(autoload 'php-mode "php-mode")
(setq auto-mode-alist
      (cons '("\\.php\\'" . php-mode) auto-mode-alist))
(setq php-mode-force-pear t)
(add-hook 'php-mode-user-hook
  '(lambda ()
     (setq php-manual-path "/usr/local/share/php/doc/html")
     (setq php-manual-url "http://www.phppro.jp/phpmanual/")))

PHP Warning: file_get_contents(): http:// wrapper is disabled in the server configuration by allow_url_fopen=0

エラーメッセージ PHP Warning: file_get_contents(): http:// wrapper is disabled in the server configuration by allow_url_fopen=0 in /var/www/html/blog/wp-content/themes/lumiukko/make_newrelease_amazon.php on line 9 /etc/php.iniファイルを編集。
allow_url_fopen = On

php Cache_Liteをインストール

phpでキャッシュを使いたいので、Cache_Liteライブラリをインストール。 その前に、pearがインストールされていない場合には、そちらを先に。
# yum -y install php53u-pear
Loaded plugins: fastestmirror, priorities, security
Loading mirror speeds from cached hostfile
 * epel: ftp.iij.ad.jp
 * ius: mirror.rackspace.com
 * sl: ftp.riken.jp
 * sl-security: ftp.riken.jp
103 packages excluded due to repository priority protections
Setting up Install Process
Resolving Dependencies
--> Running transaction check
---> Package php53u-pear.noarch 1:1.9.4-3.ius.el6 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

==================================================================================================================
 Package                     Arch                   Version                             Repository           Size
==================================================================================================================
Installing:
 php53u-pear                 noarch                 1:1.9.4-3.ius.el6                   ius                 384 k

Transaction Summary
==================================================================================================================
Install       1 Package(s)

Total download size: 384 k
Installed size: 2.2 M
Downloading Packages:
php53u-pear-1.9.4-3.ius.el6.noarch.rpm                                                     | 384 kB     00:01     
Running rpm_check_debug
Running Transaction Test
Transaction Test Succeeded
Running Transaction
  Installing : 1:php53u-pear-1.9.4-3.ius.el6.noarch                                                           1/1 

Installed:
  php53u-pear.noarch 1:1.9.4-3.ius.el6                                                                            

Complete!
続いてCache_Lite
# pear install Cache_Lite
WARNING: channel "pear.php.net" has updated its protocols, use "pear channel-update pear.php.net" to update
downloading Cache_Lite-1.7.12.tgz ...
Starting to download Cache_Lite-1.7.12.tgz (30,469 bytes)
.........done: 30,469 bytes
install ok: channel://pear.php.net/Cache_Lite-1.7.12

WordPressの引越し

引越しの流れは以下の通り。
  1. 引越し先にWordPressをインストール
  2. プラグインをインストール
  3. テーマをインストール
  4. バックアップ
  5. リストア

バックアップ取得

databaseと画像などのアップロードファイルをバックアップ。
$ mysqldump --user=hide --password=yukizou5 --host=localhost --databases blog >wp_db.sql
$ (cd /var/www/html/blog/wp-content/uploads/; tar cf - .) | gzip -c >wp_uploads.tgz
2つのファイルを引っ越先のサーバーのアップロード。
$ sftp -o Port=2022 49.212.129.72
Connecting to 49.212.129.72...
hoge@49.212.129.72's password:

sftp> put wp_db.sql
sftp> put wp_uploads.tgz

リストア

wp_db.sqlとwp_uploads.tgzをリストア。
$ mysql -u hide -p blog <wp_db.sql
Enter password: 
$ cd /var/www/html/blog/wp-content/uploads
$ tar zxf /home/hoge/wp_uploads.tgz

mysqlのインストールと設定

インストール

# yum -y install mysql-server mysql
Loaded plugins: fastestmirror, priorities, security
Loading mirror speeds from cached hostfile
 * epel: ftp.iij.ad.jp
 * ius: archive.linux.duke.edu
 * sl: ftp.riken.jp
 * sl-security: ftp.riken.jp
103 packages excluded due to repository priority protections
Setting up Install Process
Resolving Dependencies
--> Running transaction check
---> Package mysql.x86_64 0:5.1.61-1.el6_2.1 will be installed
---> Package mysql-server.x86_64 0:5.1.61-1.el6_2.1 will be installed
--> Processing Dependency: perl-DBD-MySQL for package: mysql-server-5.1.61-1.el6_2.1.x86_64
--> Processing Dependency: perl(DBI) for package: mysql-server-5.1.61-1.el6_2.1.x86_64
--> Processing Dependency: perl-DBI for package: mysql-server-5.1.61-1.el6_2.1.x86_64
--> Running transaction check
---> Package perl-DBD-MySQL.x86_64 0:4.013-3.el6 will be installed
---> Package perl-DBI.x86_64 0:1.609-4.el6 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

===================================================================================================
 Package                  Arch             Version                     Repository             Size
===================================================================================================
Installing:
 mysql                    x86_64           5.1.61-1.el6_2.1            sl-security           881 k
 mysql-server             x86_64           5.1.61-1.el6_2.1            sl-security           8.1 M
Installing for dependencies:
 perl-DBD-MySQL           x86_64           4.013-3.el6                 sl                    133 k
 perl-DBI                 x86_64           1.609-4.el6                 sl                    704 k

Transaction Summary
===================================================================================================
Install       4 Package(s)

Total download size: 9.8 M
Installed size: 28 M
Downloading Packages:
(1/4): mysql-5.1.61-1.el6_2.1.x86_64.rpm                                    | 881 kB     00:00     
(2/4): mysql-server-5.1.61-1.el6_2.1.x86_64.rpm                             | 8.1 MB     00:02     
(3/4): perl-DBD-MySQL-4.013-3.el6.x86_64.rpm                                | 133 kB     00:00     
(4/4): perl-DBI-1.609-4.el6.x86_64.rpm                                      | 704 kB     00:00     
---------------------------------------------------------------------------------------------------
Total                                                              3.2 MB/s | 9.8 MB     00:03     
Running rpm_check_debug
Running Transaction Test
Transaction Test Succeeded
Running Transaction
  Installing : perl-DBI-1.609-4.el6.x86_64                                                     1/4 
  Installing : perl-DBD-MySQL-4.013-3.el6.x86_64                                               2/4 
  Installing : mysql-5.1.61-1.el6_2.1.x86_64                                                   3/4 
  Installing : mysql-server-5.1.61-1.el6_2.1.x86_64                                            4/4 

Installed:
  mysql.x86_64 0:5.1.61-1.el6_2.1              mysql-server.x86_64 0:5.1.61-1.el6_2.1             

Dependency Installed:
  perl-DBD-MySQL.x86_64 0:4.013-3.el6                 perl-DBI.x86_64 0:1.609-4.el6                

Complete!

起動設定

自動起動の設定。
# chkconfig mysqld on

初期設定

/etc/my.cnfファイルを編集。
[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
user=mysql
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0
character-set-server = utf8
skip-name-resolve
skip-innodb
default-storage-engine=MyISAM

key_buffer = 128M
max_allowed_packet = 16M
join_buffer = 1M
read_buffer_size = 1M
read_rnd_buffer_size = 768K
thread_stack = 192K
thread_cache_size = 512
max_connections = 300
table_cache = 1024
tmp_table_size = 16M
thread_concurrency = 4
query_cache_limit = 4M
query_cache_size = 64M
query_cache_min_res_unit= 4k
query_cache_type = 1

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

[mysql]
default-character-set = utf8

[isamchk]
key_buffer = 64M
sort_buffer = 64M
read_buffer = 16M
write_buffer = 16M

[myisamchk]
key_buffer = 64M
sort_buffer = 64M
read_buffer = 16M
write_buffer = 16M
mysqldを起動。
# service 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 49.212.129.72 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 /usr/mysql-test ; perl mysql-test-run.pl

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

                                                           [  OK  ]
mysqld を起動中:                                           [  OK  ]
mysql_secure_installationを実行し、セキュリティ設定を行う。
# /usr/bin/mysql_secure_installation

NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MySQL
      SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!


In order to log into MySQL to secure it, we'll need the current
password for the root user.  If you've just installed MySQL, and
you haven't set the root password yet, the password will be blank,
so you should just press enter here.

Enter current password for root (enter for none): 
OK, successfully used password, moving on...

Setting the root password ensures that nobody can log into the MySQL
root user without the proper authorisation.

Set root password? [Y/n] 
New password: 
Re-enter new password: 
Password updated successfully!
Reloading privilege tables..
 ... Success!


By default, a MySQL installation has an anonymous user, allowing anyone
to log into MySQL without having to have a user account created for
them.  This is intended only for testing, and to make the installation
go a bit smoother.  You should remove them before moving into a
production environment.

Remove anonymous users? [Y/n] 
 ... Success!

Normally, root should only be allowed to connect from 'localhost'.  This
ensures that someone cannot guess at the root password from the network.

Disallow root login remotely? [Y/n] 
 ... Success!

By default, MySQL comes with a database named 'test' that anyone can
access.  This is also intended only for testing, and should be removed
before moving into a production environment.

Remove test database and access to it? [Y/n] 
 - Dropping test database...
 ... Success!
 - Removing privileges on test database...
 ... Success!

Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.

Reload privilege tables now? [Y/n] 
 ... Success!

Cleaning up...



All done!  If you've completed all of the above steps, your MySQL
installation should now be secure.

Thanks for using MySQL!

php-fpmのインストールと設定

インストール

# yum -y install php53u-common php53u-fpm php53u-mysql php53u-gd php53u-mbstring php53u-xml
Loaded plugins: fastestmirror, priorities, security
Loading mirror speeds from cached hostfile
 * epel: ftp.iij.ad.jp
 * ius: mirror.rackspace.com
 * sl: ftp.riken.jp
 * sl-security: ftp.riken.jp
103 packages excluded due to repository priority protections
Setting up Install Process
Resolving Dependencies
--> Running transaction check
---> Package php53u-common.x86_64 0:5.3.10-1.ius.el6 will be installed
---> Package php53u-fpm.x86_64 0:5.3.10-1.ius.el6 will be installed
--> Processing Dependency: php53u = 5.3.10-1.ius.el6 for package: php53u-fpm-5.3.10-1.ius.el6.x86_64
---> Package php53u-gd.x86_64 0:5.3.10-1.ius.el6 will be installed
--> Processing Dependency: libt1.so.5()(64bit) for package: php53u-gd-5.3.10-1.ius.el6.x86_64
---> Package php53u-mbstring.x86_64 0:5.3.10-1.ius.el6 will be installed
---> Package php53u-mysql.x86_64 0:5.3.10-1.ius.el6 will be installed
--> Processing Dependency: php53u-pdo for package: php53u-mysql-5.3.10-1.ius.el6.x86_64
---> Package php53u-xml.x86_64 0:5.3.10-1.ius.el6 will be installed
--> Running transaction check
---> Package php53u.x86_64 0:5.3.10-1.ius.el6 will be installed
--> Processing Dependency: php53u-cli = 5.3.10-1.ius.el6 for package: php53u-5.3.10-1.ius.el6.x86_64
--> Processing Dependency: httpd-mmn = 20051115 for package: php53u-5.3.10-1.ius.el6.x86_64
--> Processing Dependency: libtool-ltdl for package: php53u-5.3.10-1.ius.el6.x86_64
---> Package php53u-pdo.x86_64 0:5.3.10-1.ius.el6 will be installed
---> Package t1lib.x86_64 0:5.1.2-6.el6_2.1 will be installed
--> Running transaction check
---> Package httpd.x86_64 0:2.2.15-15.sl6.1 will be installed
--> Processing Dependency: httpd-tools = 2.2.15-15.sl6.1 for package: httpd-2.2.15-15.sl6.1.x86_64
--> Processing Dependency: apr-util-ldap for package: httpd-2.2.15-15.sl6.1.x86_64
---> Package libtool-ltdl.x86_64 0:2.2.6-15.5.el6 will be installed
---> Package php53u-cli.x86_64 0:5.3.10-1.ius.el6 will be installed
--> Running transaction check
---> Package apr-util-ldap.x86_64 0:1.3.9-3.el6_0.1 will be installed
---> Package httpd-tools.x86_64 0:2.2.15-15.sl6.1 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

===================================================================================================
 Package                   Arch             Version                    Repository             Size
===================================================================================================
Installing:
 php53u-common             x86_64           5.3.10-1.ius.el6           ius                   525 k
 php53u-fpm                x86_64           5.3.10-1.ius.el6           ius                   1.5 M
 php53u-gd                 x86_64           5.3.10-1.ius.el6           ius                   108 k
 php53u-mbstring           x86_64           5.3.10-1.ius.el6           ius                   457 k
 php53u-mysql              x86_64           5.3.10-1.ius.el6           ius                    80 k
 php53u-xml                x86_64           5.3.10-1.ius.el6           ius                   102 k
Installing for dependencies:
 apr-util-ldap             x86_64           1.3.9-3.el6_0.1            sl                     15 k
 httpd                     x86_64           2.2.15-15.sl6.1            sl-security           812 k
 httpd-tools               x86_64           2.2.15-15.sl6.1            sl-security            69 k
 libtool-ltdl              x86_64           2.2.6-15.5.el6             sl                     43 k
 php53u                    x86_64           5.3.10-1.ius.el6           ius                   1.5 M
 php53u-cli                x86_64           5.3.10-1.ius.el6           ius                   2.9 M
 php53u-pdo                x86_64           5.3.10-1.ius.el6           ius                    63 k
 t1lib                     x86_64           5.1.2-6.el6_2.1            sl-security           159 k

Transaction Summary
===================================================================================================
Install      14 Package(s)

Total download size: 8.2 M
Installed size: 26 M
Downloading Packages:
(1/14): apr-util-ldap-1.3.9-3.el6_0.1.x86_64.rpm                            |  15 kB     00:00     
(2/14): httpd-2.2.15-15.sl6.1.x86_64.rpm                                    | 812 kB     00:00     
(3/14): httpd-tools-2.2.15-15.sl6.1.x86_64.rpm                              |  69 kB     00:00     
(4/14): libtool-ltdl-2.2.6-15.5.el6.x86_64.rpm                              |  43 kB     00:00     
(5/14): php53u-5.3.10-1.ius.el6.x86_64.rpm                                  | 1.5 MB     00:02     
(6/14): php53u-cli-5.3.10-1.ius.el6.x86_64.rpm                              | 2.9 MB     00:03     
(7/14): php53u-common-5.3.10-1.ius.el6.x86_64.rpm                           | 525 kB     00:01     
(8/14): php53u-fpm-5.3.10-1.ius.el6.x86_64.rpm                              | 1.5 MB     00:02     
(9/14): php53u-gd-5.3.10-1.ius.el6.x86_64.rpm                               | 108 kB     00:00     
(10/14): php53u-mbstring-5.3.10-1.ius.el6.x86_64.rpm                        | 457 kB     00:01     
(11/14): php53u-mysql-5.3.10-1.ius.el6.x86_64.rpm                           |  80 kB     00:00     
(12/14): php53u-pdo-5.3.10-1.ius.el6.x86_64.rpm                             |  63 kB     00:00     
(13/14): php53u-xml-5.3.10-1.ius.el6.x86_64.rpm                             | 102 kB     00:00     
(14/14): t1lib-5.1.2-6.el6_2.1.x86_64.rpm                                   | 159 kB     00:00     
---------------------------------------------------------------------------------------------------
Total                                                              389 kB/s | 8.2 MB     00:21     
警告: rpmts_HdrFromFdno: ヘッダ V4 DSA/SHA1 Signature, key ID 9cd4953f: NOKEY
Retrieving key from file:///etc/pki/rpm-gpg/IUS-COMMUNITY-GPG-KEY
Importing GPG key 0x9CD4953F:
 Userid : IUS Community Project 
 Package: ius-release-1.0-10.ius.el6.noarch (installed)
 From   : /etc/pki/rpm-gpg/IUS-COMMUNITY-GPG-KEY
Running rpm_check_debug
Running Transaction Test
Transaction Test Succeeded
Running Transaction
Warning: RPMDB altered outside of yum.
  Installing : php53u-common-5.3.10-1.ius.el6.x86_64                                          1/14 
  Installing : t1lib-5.1.2-6.el6_2.1.x86_64                                                   2/14 
  Installing : php53u-pdo-5.3.10-1.ius.el6.x86_64                                             3/14 
  Installing : php53u-cli-5.3.10-1.ius.el6.x86_64                                             4/14 
  Installing : libtool-ltdl-2.2.6-15.5.el6.x86_64                                             5/14 
  Installing : httpd-tools-2.2.15-15.sl6.1.x86_64                                             6/14 
  Installing : apr-util-ldap-1.3.9-3.el6_0.1.x86_64                                           7/14 
  Installing : httpd-2.2.15-15.sl6.1.x86_64                                                   8/14 
  Installing : php53u-5.3.10-1.ius.el6.x86_64                                                 9/14 
  Installing : php53u-fpm-5.3.10-1.ius.el6.x86_64                                            10/14 
  Installing : php53u-mysql-5.3.10-1.ius.el6.x86_64                                          11/14 
  Installing : php53u-gd-5.3.10-1.ius.el6.x86_64                                             12/14 
  Installing : php53u-mbstring-5.3.10-1.ius.el6.x86_64                                       13/14 
  Installing : php53u-xml-5.3.10-1.ius.el6.x86_64                                            14/14 

Installed:
  php53u-common.x86_64 0:5.3.10-1.ius.el6         php53u-fpm.x86_64 0:5.3.10-1.ius.el6             
  php53u-gd.x86_64 0:5.3.10-1.ius.el6             php53u-mbstring.x86_64 0:5.3.10-1.ius.el6        
  php53u-mysql.x86_64 0:5.3.10-1.ius.el6          php53u-xml.x86_64 0:5.3.10-1.ius.el6             

Dependency Installed:
  apr-util-ldap.x86_64 0:1.3.9-3.el6_0.1            httpd.x86_64 0:2.2.15-15.sl6.1                 
  httpd-tools.x86_64 0:2.2.15-15.sl6.1              libtool-ltdl.x86_64 0:2.2.6-15.5.el6           
  php53u.x86_64 0:5.3.10-1.ius.el6                  php53u-cli.x86_64 0:5.3.10-1.ius.el6           
  php53u-pdo.x86_64 0:5.3.10-1.ius.el6              t1lib.x86_64 0:5.1.2-6.el6_2.1                 

Complete!

設定

/etc/php.iniの基本設定。
post_max_size = 15M
upload_max_filesize = 15M

allow_url_fopen = On

[Date]
; Defines the default timezone used by the date functions
; http://www.php.net/manual/en/datetime.configuration.php#ini.date.timezone
date.timezone = "Asia/Tokyo"
/etc/php-fpm.d/www.confを編集。
listen = /var/run/php-fpm.sock
listen.owner = nobody
listen.group = nobody
listen.mode = 0666
user = nginx
group = nginx

pm = dynamic
pm.max_children = 50
pm.start_servers = 5
pm.min_spare_servers = 5
pm.max_spare_servers = 35
細かなチューニングは後で実施。

起動設定

自動起動に設定し、サービスを起動。
# chkconfig php-fpm on
# service php-fpm start
php-fpm を起動中:                                          [  OK  ]

WordPress install memo

準備

WordPressをインストールするために、必要なパッケージをインストール。

データベース作成

WordPress用にデータベースを作成。
# mysql -u root -p

mysql> create database blog;
Query OK, 1 row affected (0.00 sec)

mysql> grant all privileges on blog.* to "hoge"@"localhost" identified by "password";
Query OK, 0 rows affected (0.00 sec)

mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

ダウンロードと展開

# wget http://ja.wordpress.org/wordpress-3.3.1-ja.tar.gz
# tar -xzvf wordpress-3.3.1-ja.tar.gz
# mv wordpress /var/www/html/blog
# chown -R hoge.hoge /var/www/html/blog

設定

wp-config.phpファイルを作成。
$ mv wp-config-sample.php wp-config.php
$ vi wp-config.php

インストール

ブラウザから、http://blog.lumiukko.jp/wp-admin/install.phpにアクセスしてインストール。

nginxのインストールと設定

インストール

# yum -y install nginx
Loaded plugins: fastestmirror, priorities, security
Loading mirror speeds from cached hostfile
 * epel: ftp.iij.ad.jp
 * sl: ftp.riken.jp
 * sl-security: ftp.riken.jp
102 packages excluded due to repository priority protections
Setting up Install Process
Resolving Dependencies
--> Running transaction check
---> Package nginx.x86_64 0:1.0.14-1.el6 will be installed
--> Processing Dependency: libxslt.so.1(LIBXML2_1.0.18)(64bit) for package: nginx-1.0.14-1.el6.x86_64
--> Processing Dependency: libxslt.so.1(LIBXML2_1.0.11)(64bit) for package: nginx-1.0.14-1.el6.x86_64
--> Processing Dependency: gd for package: nginx-1.0.14-1.el6.x86_64
--> Processing Dependency: GeoIP for package: nginx-1.0.14-1.el6.x86_64
--> Processing Dependency: libxslt.so.1()(64bit) for package: nginx-1.0.14-1.el6.x86_64
--> Processing Dependency: libgd.so.2()(64bit) for package: nginx-1.0.14-1.el6.x86_64
--> Processing Dependency: libexslt.so.0()(64bit) for package: nginx-1.0.14-1.el6.x86_64
--> Processing Dependency: libGeoIP.so.1()(64bit) for package: nginx-1.0.14-1.el6.x86_64
--> Running transaction check
---> Package GeoIP.x86_64 0:1.4.8-1.el6 will be installed
---> Package gd.x86_64 0:2.0.35-10.el6 will be installed
--> Processing Dependency: libXpm.so.4()(64bit) for package: gd-2.0.35-10.el6.x86_64
---> Package libxslt.x86_64 0:1.1.26-2.el6 will be installed
--> Running transaction check
---> Package libXpm.x86_64 0:3.5.8-2.el6 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

==========================================================================================
 Package             Arch               Version                    Repository        Size
==========================================================================================
Installing:
 nginx               x86_64             1.0.14-1.el6               epel             375 k
Installing for dependencies:
 GeoIP               x86_64             1.4.8-1.el6                epel             620 k
 gd                  x86_64             2.0.35-10.el6              sl               141 k
 libXpm              x86_64             3.5.8-2.el6                sl                58 k
 libxslt             x86_64             1.1.26-2.el6               sl               449 k

Transaction Summary
==========================================================================================
Install       5 Package(s)

Total download size: 1.6 M
Installed size: 5.3 M
Downloading Packages:
(1/5): GeoIP-1.4.8-1.el6.x86_64.rpm                                | 620 kB     00:00     
(2/5): gd-2.0.35-10.el6.x86_64.rpm                                 | 141 kB     00:00     
(3/5): libXpm-3.5.8-2.el6.x86_64.rpm                               |  58 kB     00:00     
(4/5): libxslt-1.1.26-2.el6.x86_64.rpm                             | 449 kB     00:00     
(5/5): nginx-1.0.14-1.el6.x86_64.rpm                               | 375 kB     00:00     
------------------------------------------------------------------------------------------
Total                                                     1.7 MB/s | 1.6 MB     00:00     
warning: rpmts_HdrFromFdno: Header V3 RSA/SHA256 Signature, key ID 0608b895: NOKEY
Retrieving key from file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6
Importing GPG key 0x0608B895:
 Userid : EPEL (6) 
 Package: epel-release-6-5.noarch (@sl)
 From   : /etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6
Running rpm_check_debug
Running Transaction Test
Transaction Test Succeeded
Running Transaction
  Installing : GeoIP-1.4.8-1.el6.x86_64                                               1/5 
  Installing : libXpm-3.5.8-2.el6.x86_64                                              2/5 
  Installing : gd-2.0.35-10.el6.x86_64                                                3/5 
  Installing : libxslt-1.1.26-2.el6.x86_64                                            4/5 
  Installing : nginx-1.0.14-1.el6.x86_64                                              5/5 

Installed:
  nginx.x86_64 0:1.0.14-1.el6                                                             

Dependency Installed:
  GeoIP.x86_64 0:1.4.8-1.el6     gd.x86_64 0:2.0.35-10.el6  libXpm.x86_64 0:3.5.8-2.el6 
  libxslt.x86_64 0:1.1.26-2.el6 

Complete!

起動設定と起動

自動起動に設定し、サービスを起動。
# chkconfig nginx on
# service nginx start
nginx を起動中:                                            [  OK  ]
# nginx -v
nginx version: nginx/1.0.14

基本構成

サーバーのCPU数を確認する。
# cat /proc/cpuinfo | grep proc
processor : 0
processor : 1
processor : 2
さくらVPSの2GBプランなので、プロセッサ数は3。 /etc/nginx/nginx.confを編集し、基本的な設定を行う。
user              nginx;
worker_processes  3;

error_log  /var/log/nginx/error.log;

pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
    use epoll;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    server_tokens   off;
    sendfile        on;
    tcp_nodelay     on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    #keepalive_timeout  65;

    fastcgi_read_timeout 300;

    gzip  on;
    gzip_proxied any;
    gzip_comp_level 2;
    gzip_disable "MSIE [1-6].(?!.*SV1)";
    gzip_types text/plain text/css application/x-javascript text/xml application/xml application/xml+rss text/javascript;

    # Upstream to abstract backend connection(s) for PHP
    upstream backend {
        server unix:/var/run/php-fpm.sock;
    }

    # Load config files from the /etc/nginx/conf.d directory
    # The default server is in conf.d/default.conf
    include /etc/nginx/conf.d/*.conf;
}
/etc/nginx/conf.d/virtual.confを編集。
server {
    listen      80;
    server_name blog.lumiukko.jp;
    root        /var/www/html/blog/;

    access_log /var/log/nginx/blog.log main;
    error_log  /var/log/nginx/blog.log;

    client_max_body_size 32M;

    include /etc/nginx/global/restrictions.conf;
    include /etc/nginx/global/wordpress.conf;
}
/etc/nginx/globalディレクトリを作成。
# cd /etc/nginx
# mkdir global
restrictions.confファイルを作成。
# Global restrictions configuration file.
# Designed to be included in any server {} block.

location = /favicon.ico { log_not_found off; access_log off; } location = /robots.txt { allow all; log_not_found off; access_log off; } # Deny all attempts to access hidden files such as .htaccess, .htpasswd, .DS_Store (Mac). location ~ /\. { deny all; access_log off; log_not_found off; } # Deny access to any files with a .php extension in the uploads directory location ~* ^/wp-content/uploads/.*.php$ { deny all; access_log off; log_not_found off; } location ~* ^/wp-content/themes/lumiukko/make.*.php$ { deny all; access_log off; log_not_found off; }
wordpress.confファイルを作成。
# WordPress single blog rules.
# Designed to be included in any server {} block.

# This order might seem weird - this is attempted to match last if rules below fail.
# http://wiki.nginx.org/HttpCoreModule
location / {
        try_files $uri $uri/ /index.php?q=$uri&$args;
}

# Add trailing slash to */wp-admin requests.
rewrite /wp-admin$ $scheme://$host$uri/ permanent;

# Directives to send expires headers and turn off 404 error logging.
location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
        expires 7d;
        log_not_found off;
}

# Uncomment one of the lines below for the appropriate caching plugin (if used).
include global/wordpress-w3-total-cache.conf;

# Pass all .php files onto a php-fpm/php-fcgi server.
location ~ \.php$ {
        # Zero-day exploit defense.
        # http://forum.nginx.org/read.php?2,88845,page=3
        # Won't work properly (404 error) if the file is not stored on this server, which is entirely possible with php-fpm/php-fcgi.
        # Comment the 'try_files' line out if you set up php-fpm/php-fcgi on another machine.  And then cross your fingers that you won't get hacked.
        #try_files $uri =404;

        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        #NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini

        include fastcgi_params;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_pass backend;
}
wordpress-w3-total-cache.confファイルを作成。
# touch wordpress-w3-total-cache.conf
中身は、w3 total cacheプラグインをセットアップする際に編集します。

nginxを再起動

# service nginx restart
nginx を停止中:                                            [  OK  ]
nginx を起動中:                                            [  OK  ]

Scientific Linux 6.2 Install memo

さくらVPSの1Gプランを利用していましたが、乗り換えキャンペーン実施中ということで、2GBプランに移行することにしました。
# cat /etc/redhat-release 
Scientific Linux release 6.2 (Carbon)

ユーザー作成とセキュリティ設定

普段使用するユーザーIDを作成。
# useradd hoge
# passwd hoge
ユーザー hoge のパスワードを変更。
新しいパスワード:
新しいパスワードを再入力してください:
passwd: 全ての認証トークンが正しく更新できました。
# usermod -G wheel hoge
# 
sshでのrootログインを禁止する。 /etc/ssh/sshd_configファイルを編集。
Port 2022
Protocol 2
SyslogFacility AUTHPRIV
PermitRootLogin no
PasswordAuthentication yes
PermitEmptyPasswords no
ChallengeResponseAuthentication no
UsePAM yes
Subsystem       sftp    /usr/libexec/openssh/sftp-server
sshデーモンを再起動して、rootでログインできないことを確認。
# service sshd restart
Stopping sshd:                                             [  OK  ]
Starting sshd:                                             [  OK  ]
# logout
logout
Connection to 49.212.129.72 closed.

client:~ hoge$ ssh -p 2022 root@49.212.129.72
root@49.212.129.72's password: 
Permission denied, please try again.
/etc/pam.d/suを編集し、suできるユーザーをwheelグループに限定。
auth            required        pam_wheel.so use_uid
wheelグループにsudoを許可。
# visudo
%wheel  ALL=(ALL)       NOPASSWD: ALL

ロケール設定

/etc/sysconfig/i18nを編集して、ロケールをUTF-8に設定。
LANG="ja_JP.UTF-8"

ネットワーク設定

IPv6が有効になっている場合には、無効にする。
# ifconfig -a
eth0      Link encap:Ethernet  HWaddr 52:54:06:00:42:98  
          inet addr:49.212.129.72  Bcast:49.212.129.255  Mask:255.255.254.0
          inet6 addr: fe80::5054:6ff:fe00:4298/64 Scope:Link

# echo 'options ipv6 disable=1' >/etc/modprobe.d/disable-ipv6.conf
# chkconfig ip6tables off
# reboot
APIPAが有効になっている場合には、無効にする。
# netstat -nr
Kernel IP routing table
Destination     Gateway         Genmask         Flags   MSS Window  irtt Iface
49.212.128.0    0.0.0.0         255.255.254.0   U         0 0          0 eth0
169.254.0.0     0.0.0.0         255.255.0.0     U         0 0          0 eth0

# sudo echo "NOZEROCONF=yes" >>/etc/sysconfig/network

# service network restart
インターフェース eth0 を終了中:                            [  OK  ]
ループバックインターフェースを終了中                       [  OK  ]
ループバックインターフェイスを呼び込み中                   [  OK  ]
インターフェース eth0 を活性化中:                          [  OK  ]

# netstat -nr
Kernel IP routing table
Destination     Gateway         Genmask         Flags   MSS Window  irtt Iface
49.212.128.0    0.0.0.0         255.255.254.0   U         0 0          0 eth0

yum関連

yumのプラグインを追加。
  • yum-plugin-priorities: 外部リポジトリと混ぜて使用する際に標準リポジトリのバージョンを優先
# yum -y install yum-plugin-priorities
Loaded plugins: fastestmirror, security
Loading mirror speeds from cached hostfile
 * sl: ftp.riken.jp
 * sl-security: ftp.riken.jp
Setting up Install Process
Resolving Dependencies
--> Running transaction check
---> Package yum-plugin-priorities.noarch 0:1.1.30-10.el6 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

================================================================================
 Package                     Arch         Version                Repository
                                                                           Size
================================================================================
Installing:
 yum-plugin-priorities       noarch       1.1.30-10.el6          sl        21 k

Transaction Summary
================================================================================
Install       1 Package(s)

Total download size: 21 k
Installed size: 28 k
Downloading Packages:
yum-plugin-priorities-1.1.30-10.el6.noarch.rpm           |  21 kB     00:00     
警告: rpmts_HdrFromFdno: ヘッダ V4 DSA/SHA1 Signature, key ID 192a7d7d: NOKEY
Retrieving key from file:///etc/pki/rpm-gpg/RPM-GPG-KEY-sl
Importing GPG key 0x192A7D7D:
 Userid : Scientific Linux (RPM signing key for Scientific Linux) 
 Package: sl-release-6.2-1.1.x86_64 (@Scientific Linux/6.1)
 From   : /etc/pki/rpm-gpg/RPM-GPG-KEY-sl
Retrieving key from file:///etc/pki/rpm-gpg/RPM-GPG-KEY-sl6
Importing GPG key 0x9B1FD350:
 Userid : Scientific Linux (RPM signing key for Scientific Linux 6) 
 Package: sl-release-6.2-1.1.x86_64 (@Scientific Linux/6.1)
 From   : /etc/pki/rpm-gpg/RPM-GPG-KEY-sl6
Retrieving key from file:///etc/pki/rpm-gpg/RPM-GPG-KEY-cern
Importing GPG key 0x1D1E034B:
 Userid : CERN Linux Support (RPM signing key for CERN Linux Support) 
 Package: sl-release-6.2-1.1.x86_64 (@Scientific Linux/6.1)
 From   : /etc/pki/rpm-gpg/RPM-GPG-KEY-cern
Running rpm_check_debug
Running Transaction Test
Transaction Test Succeeded
Running Transaction
  Installing : yum-plugin-priorities-1.1.30-10.el6.noarch                   1/1 

Installed:
  yum-plugin-priorities.noarch 0:1.1.30-10.el6                                  

Complete!
/etc/yum.repos.d/に移動し、sl.repoとsl-other.repoのプライオリティを1(優先)に設定。 各セクションの最後にpriority=1を追加。 EPELをリポジトリに追加。
# yum -y install epel-release
Loaded plugins: fastestmirror, priorities, security
Loading mirror speeds from cached hostfile
 * sl: ftp.riken.jp
 * sl-security: ftp.riken.jp
Setting up Install Process
Resolving Dependencies
--> Running transaction check
---> Package epel-release.noarch 0:6-5 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

================================================================================
 Package                 Arch              Version          Repository     Size
================================================================================
Installing:
 epel-release            noarch            6-5              sl             13 k

Transaction Summary
================================================================================
Install       1 Package(s)

Total download size: 13 k
Installed size: 22 k
Downloading Packages:
epel-release-6-5.noarch.rpm                              |  13 kB     00:00     
Running rpm_check_debug
Running Transaction Test
Transaction Test Succeeded
Running Transaction
  Installing : epel-release-6-5.noarch                                      1/1 

Installed:
  epel-release.noarch 0:6-5                                                     

Complete!
IUS Yumリポジトリを追加。
# wget http://dl.iuscommunity.org/pub/ius/stable/Redhat/6/x86_64/ius-release-1.0-10.ius.el6.noarch.rpm
--2012-04-14 16:35:46--  http://dl.iuscommunity.org/pub/ius/stable/Redhat/6/x86_64/ius-release-1.0-10.ius.el6.noarch.rpm
dl.iuscommunity.org をDNSに問いあわせています... 50.57.54.209
dl.iuscommunity.org|50.57.54.209|:80 に接続しています... 接続しました。
HTTP による接続要求を送信しました、応答を待っています... 200 OK
長さ: 7608 (7.4K) [application/x-rpm]
`ius-release-1.0-10.ius.el6.noarch.rpm' に保存中

100%[=========================================================>] 7,608       --.-K/s 時間 0s      

2012-04-14 16:35:48 (442 MB/s) - `ius-release-1.0-10.ius.el6.noarch.rpm' へ保存完了 [7608/7608]

# rpm -Uvh ius-release-1.0-10.ius.el6.noarch.rpm
警告: ius-release-1.0-10.ius.el6.noarch.rpm: ヘッダ V4 DSA/SHA1 Signature, key ID 9cd4953f: NOKEY
準備中...                ########################################### [100%]
   1:ius-release            ########################################### [100%]

IPTABLESの設定

ssh(2022), http(80), smtp(25)を許可するスクリプトを作成。
#!/bin/sh
/sbin/iptables -F
/sbin/iptables -X

/sbin/iptables -P INPUT DROP
/sbin/iptables -P OUTPUT ACCEPT
/sbin/iptables -P FORWARD DROP

/sbin/iptables -A INPUT -i lo -j ACCEPT
/sbin/iptables -A OUTPUT -o lo -j ACCEPT

/sbin/iptables -A INPUT -s 10.0.0.0/8 -j DROP
/sbin/iptables -A INPUT -s 172.16.0.0/12 -j DROP
/sbin/iptables -A INPUT -s 192.168.0.0/16 -j DROP

/sbin/iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT
/sbin/iptables -A INPUT -p tcp --dport 2022 -j ACCEPT
/sbin/iptables -A INPUT -p tcp --dport 25 -j ACCEPT
/sbin/iptables -A INPUT -p tcp --dport 80 -j ACCEPT
/sbin/iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

/sbin/iptables -A INPUT -j LOG --log-prefix "IPTABLES_INPUT_LOG:" --log-level=info

/etc/rc.d/init.d/iptables save

vsftpd

vsftpd用のユーザーを作成。
# groupadd ftpsecure
# useradd -g ftpsecure -d /var/ftpsecure -s /sbin/nologin -d /var/ftpsecure -m -k /dev/null ftpsecure
vsftpdのインストールと設定。
# yum -y install vsftpd
Loaded plugins: fastestmirror, priorities, security
Loading mirror speeds from cached hostfile
 * epel: ftp.iij.ad.jp
 * sl: ftp.riken.jp
 * sl-security: ftp.riken.jp
102 packages excluded due to repository priority protections
Setting up Install Process
Resolving Dependencies
--> Running transaction check
---> Package vsftpd.x86_64 0:2.2.2-6.el6_0.1 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

================================================================================
 Package          Arch             Version                   Repository    Size
================================================================================
Installing:
 vsftpd           x86_64           2.2.2-6.el6_0.1           sl           149 k

Transaction Summary
================================================================================
Install       1 Package(s)

Total download size: 149 k
Installed size: 331 k
Downloading Packages:
vsftpd-2.2.2-6.el6_0.1.x86_64.rpm                        | 149 kB     00:00     
Running rpm_check_debug
Running Transaction Test
Transaction Test Succeeded
Running Transaction
  Installing : vsftpd-2.2.2-6.el6_0.1.x86_64                                1/1 

Installed:
  vsftpd.x86_64 0:2.2.2-6.el6_0.1                                               

Complete!
/etc/vsftpd/vsftpd.confを編集。
anonymous_enable=NO
local_enable=YES
write_enable=YES
local_umask=022
xferlog_enable=YES
xferlog_file=/var/log/vsftpd.log
nopriv_user=ftpsecure
listen=YES
pam_service_name=vsftpd
userlist_enable=NO
tcp_wrappers=YES
自動起動にする。
# chkconfig vsftpd on
# service vsftpd start

logwatch

# yum -y install logwatch
Loaded plugins: fastestmirror, priorities, security
Loading mirror speeds from cached hostfile
 * epel: ftp.iij.ad.jp
 * sl: ftp.riken.jp
 * sl-security: ftp.riken.jp
102 packages excluded due to repository priority protections
Setting up Install Process
Resolving Dependencies
--> Running transaction check
---> Package logwatch.noarch 0:7.3.6-49.el6 will be installed
--> Processing Dependency: perl(Date::Manip) for package: logwatch-7.3.6-49.el6.noarch
--> Running transaction check
---> Package perl-Date-Manip.noarch 0:6.24-1.el6 will be installed
--> Processing Dependency: perl(YAML::Syck) for package: perl-Date-Manip-6.24-1.el6.noarch
--> Running transaction check
---> Package perl-YAML-Syck.x86_64 0:1.07-4.el6 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

=======================================================================================================
 Package                       Arch                 Version                     Repository        Size
=======================================================================================================
Installing:
 logwatch                      noarch               7.3.6-49.el6                sl               297 k
Installing for dependencies:
 perl-Date-Manip               noarch               6.24-1.el6                  sl               1.3 M
 perl-YAML-Syck                x86_64               1.07-4.el6                  sl                74 k

Transaction Summary
=======================================================================================================
Install       3 Package(s)

Total download size: 1.7 M
Installed size: 11 M
Downloading Packages:
(1/3): logwatch-7.3.6-49.el6.noarch.rpm                                         | 297 kB     00:00     
(2/3): perl-Date-Manip-6.24-1.el6.noarch.rpm                                    | 1.3 MB     00:00     
(3/3): perl-YAML-Syck-1.07-4.el6.x86_64.rpm                                     |  74 kB     00:00     
-------------------------------------------------------------------------------------------------------
Total                                                                  2.1 MB/s | 1.7 MB     00:00     
Running rpm_check_debug
Running Transaction Test
Transaction Test Succeeded
Running Transaction
  Installing : perl-YAML-Syck-1.07-4.el6.x86_64                                                    1/3 
  Installing : perl-Date-Manip-6.24-1.el6.noarch                                                   2/3 
  Installing : logwatch-7.3.6-49.el6.noarch                                                        3/3 

Installed:
  logwatch.noarch 0:7.3.6-49.el6                                                                       

Dependency Installed:
  perl-Date-Manip.noarch 0:6.24-1.el6                perl-YAML-Syck.x86_64 0:1.07-4.el6               

Complete!

不要なサービスを停止

停止前のサービス一覧
# chkconfig
acpid           0:off 1:off 2:on 3:on 4:on 5:on 6:off
atd             0:off 1:off 2:off 3:on 4:on 5:on 6:off
auditd          0:off 1:off 2:off 3:off 4:off 5:off 6:off
cpuspeed        0:off 1:on 2:off 3:off 4:off 5:off 6:off
crond           0:off 1:off 2:on 3:on 4:on 5:on 6:off
cups            0:off 1:off 2:off 3:off 4:off 5:off 6:off
haldaemon       0:off 1:off 2:off 3:off 4:off 5:off 6:off
ip6tables       0:off 1:off 2:off 3:off 4:off 5:off 6:off
iptables        0:off 1:off 2:on 3:on 4:on 5:on 6:off
irqbalance      0:off 1:off 2:off 3:on 4:on 5:on 6:off
kdump           0:off 1:off 2:off 3:off 4:off 5:off 6:off
lvm2-monitor    0:off 1:on 2:off 3:off 4:off 5:off 6:off
mdmonitor       0:off 1:off 2:off 3:off 4:off 5:off 6:off
messagebus      0:off 1:off 2:off 3:off 4:off 5:off 6:off
netconsole      0:off 1:off 2:off 3:off 4:off 5:off 6:off
netfs           0:off 1:off 2:off 3:off 4:off 5:off 6:off
network         0:off 1:off 2:on 3:on 4:on 5:on 6:off
ntpd            0:off 1:off 2:on 3:on 4:on 5:on 6:off
ntpdate         0:off 1:off 2:on 3:on 4:on 5:on 6:off
portreserve     0:off 1:off 2:off 3:off 4:off 5:off 6:off
postfix         0:off 1:off 2:on 3:on 4:on 5:on 6:off
psacct          0:off 1:off 2:off 3:off 4:off 5:off 6:off
quota_nld       0:off 1:off 2:off 3:off 4:off 5:off 6:off
rdisc           0:off 1:off 2:off 3:off 4:off 5:off 6:off
restorecond     0:off 1:off 2:off 3:off 4:off 5:off 6:off
rsyslog         0:off 1:off 2:on 3:on 4:on 5:on 6:off
saslauthd       0:off 1:off 2:off 3:off 4:off 5:off 6:off
smartd          0:off 1:off 2:off 3:off 4:off 5:off 6:off
sshd            0:off 1:off 2:on 3:on 4:on 5:on 6:off
sysstat         0:off 1:on 2:on 3:on 4:on 5:on 6:off
udev-post       0:off 1:on 2:off 3:off 4:off 5:off 6:off
vsftpd          0:off 1:off 2:on 3:on 4:on 5:on 6:off
以下のサービスを停止
# chkconfig acpid off
# chkconfig --level=1 cpuspeed off
# chkconfig --level=1 lvm2-monitor off
# chkconfig ntpdate off
# chkconfig --level=1 udev-post off

ntpの設定

デフォルトのままで動作確認。
# ntpq -p
     remote           refid      st t when poll reach   delay   offset  jitter
==============================================================================
*ntp1.sakura.ad. 133.243.238.244  2 u   17   64  377    9.964   -0.070   0.143

表示する抜粋の長さを適宜変えたい

例えば記事の抜粋を検索結果に表示する場合と、ウィジェットに表示する場合とで、表示する文字数を変えたい場合のやり方です。
$excerpt = 40;
$lenght = create_function( '', "return $excerpt;" );
add_filter('excerpt_mblength', $lenght );
remove_filter('excerpt_mblength', $lenght );
このように、マルチバイトパッチで呼び出されている excerpt_mblength()をオーバーライドしてあげます。

prettyphoto用のrelタグを自動で付与する

WordPressで画像に自動的にprettyphoto用のrelタグを付与する方法です。 プラグインを使えば簡単にできると思いますが、使わずにfunctions.phpに以下を追加することで実現しました。
function yk_add_prettyphoto_rel($content) {
    global $post;

    $pattern = "//i";
    $replacement = '';
    $content = preg_replace($pattern, $replacement, $content);
    $content = str_replace("%LIGHTID%", $post->ID, $content);

    return $content;
}
add_filter('the_content', 'yk_add_prettyphoto_rel');

クラスのメソッドを引数に指定する方法

phpのusort()など関数を引数にとる関数に、クラスのメソッドを指定するには以下のようにします。 クラス名との組み合せ
usort($json, array('my_class', 'my_sort'));
オブジェクト名との組み合せ
usort($json, array($this, 'my_sort'));

カスタム投稿の公開をフックする

投稿を公開した際にフックするには、以下のコードを使いますが、これだけではカスタム投稿はフックできません。
add_action('new_to_publish', 'run_when_post_published');
add_action('draft_to_publish', 'run_when_post_published');
add_action('pending_to_publish', 'run_when_post_published');
カスタム投稿もフックするには以下を使います。
// replace {custom_post_type_name} with the name of your post type
add_action('new_to_publish_{custom_post_type_name}', 'run_when_post_published');  
add_action('draft_to_publish_{custom_post_type_name}', 'run_when_post_published');  
add_action('pending_to_publish_{custom_post_type_name}', 'run_when_post_published');

twitterのアバター画像を取得する

WordPressとTwitterの連携を試行錯誤中。
function yk_query_twitter($handle) {
    $url = 'http://api.twitter.com/1/users/show/'. $handle .'.json';
    $data = json_decode(wp_remote_retrieve_body(wp_remote_get($url)));

    return $data;
}

function yk_get_profile_image($twitterID, $comment_id) {
    $image = get_comment_meta($comment_id, 'yk_avatarimage', true);

    if (!$image) {
        $data = yk_query_twitter($twitterID);
        $image = $data->profile_image_url;
        add_comment_meta($comment_id, 'yk_avatarimage', $image, true);
    }
    return $image;
}

function yk_get_avatar($avatar, $data) {
    // not a tweet                                                                             
    if (!isset($data->comment_agent) || strstr($data->comment_author_url, "twitter.com") == fa\
lse) {
        return $avatar;
    }

    // get the url of the avatar                                                               
    $url = yk_get_profile_image(substr($data->comment_author, 1), $data->comment_ID);

    return preg_replace("/http:\/\/([^']*)/", $url, $avatar);
}

add_filter( 'get_avatar', 'yk_get_avatar', 10, 2);

nginx: 特定のファイルへのアクセスを拒否する

location ~* ^/wp-content/uploads/.*.php$ {
        deny all;
        access_log off;
        log_not_found off;
}

WordPress Simple Twitter ConnectでWarning

Warning: session_start(): open(/var/lib/php/session/sess_8e7hutle3p0ajetbkc6avs9sv3, O_RDWR) failed: Permission denied (13) in /var/www/html/blog/wp-content/plugins/simple-twitter-connect/stc.php on line 33
/var/lib/php/sessionのパーミッションを確認し、必要な権限を与える。
$ ls -l
合計 4
drwxrwx--- 2 root apache 4096  2月  3 08:37 2012 session

$ sudo chgrp nginx session
$ ls -l
合計 4
drwxrwx--- 2 root nginx 4096  2月  3 08:37 2012 session

WordPressの画質改善

WordPressで画質を改善するいくつかの修正点をまとめました。 WordPressのバージョンは、3.3.1です。

サムネイル

wp-includes/media.phpの410行目を修正。
function image_resize( $file, $max_w, $max_h, $crop = false, $suffix = null, $dest_path = null, $jpeg_quality = 100 ) {

リサイズ

自分のfunctions.phpに以下を追加。
function yk_jpeg_quality($jpeg_quality) {
    $jpeg_quality = 100;
    return $jpeg_quality;
}
add_filter( 'jpeg_quality', 'yk_jpeg_quality');

WordPressで指定したカテゴリーとタグに一致するメディアを表示する

Attachment Taxonomy Supportなどを使って、メディアにカテゴリーとタグをつけます。 そのあとで、galleryショートコードを拡張して、gallery tag="tag1"やgallery category="cat1"などと指定できるようにします。
            $tax_val = array();
            if ( !empty($tag) ) {
                $tax_val[] = array(
                                   'taxonomy' => 'attachment_tag',
                                   'field' => 'slug',
                                   'terms' => $tag
                                   );
            }
            if ( !empty($category) ) {
                $tax_val[] = array(
                                   'taxonomy' => 'attachment_category',
                                   'field' => 'slug',
                                   'terms' => $category
                                   );
            }
            $_attachments = get_posts( array(
                                            'post_type' => 'attachment',
                                            'post_status' => 'inherit',
                                            'posts_per_page' => -1,
                                            'tax_query' => $tax_val,
                                            'post_parent' => null
                                            ));
            $attachments = array();
            foreach ( $_attachments as $key => $val) {
  $attachments[$val->ID] = $_attachments[$key];
            }

Wordpressのメディアにカテゴリーとタグを付ける

function.phpに以下を追加することで、メディア(attachment)にカテゴリーとタグを付けられます。
function yk_register_taxonomy() {
    // add category                                                                                                
    $labels = array(
                    'name' => _x( 'Attachment Categories', 'taxonomy general name'),
                    'singular_name'     => _x( 'Attachment Category', 'taxonomy singular name' ),
                    'search_items'      =>  __( 'Search Attachment Categories' ),
                    'all_items'         => __( 'All Attachment Categories' ),
                    'parent_item'       => __( 'Parent Attachment Category' ),
                    'parent_item_colon' => __( 'Parent Attachment Category:' ),
                    'edit_item'         => __( 'Edit Attachment Category' ),
                    'update_item'       => __( 'Update Attachment Category' ),
                    'add_new_item'      => __( 'Add New Attachment Category' ),
                    'new_item_name'     => __( 'New Attachment Category Name' ),
                    'menu_name'         => __( 'Attachment Category' ),
                    );
    $args = array(
                  'hierarchical' => true,
                  'labels'       => $labels,
                  'show_ui'      => true,
                  'query_var'    => true,
                  'rewrite'      => true,
                  );
    register_taxonomy('attachment_category', 'attachment', $args);
    // add tag                                                                                                     
    $labels = array(
                    'name'              => _x( 'Attachment Tags', 'taxonomy general name' ),
                    'singular_name'     => _x( 'Attachment Tag', 'taxonomy singular name' ),
                    'search_items'      =>  __( 'Search Attachment Tags' ),
                    'all_items'         => __( 'All Attachment Tags' ),
                    'parent_item'       => __( 'Parent Attachment Tag' ),
                    'parent_item_colon' => __( 'Parent Attachment Tag:' ),
                    'edit_item'         => __( 'Edit Attachment Tag' ),
                    'update_item'       => __( 'Update Attachment Tag' ),
                    'add_new_item'      => __( 'Add New Attachment Tag' ),
                    'new_item_name'     => __( 'New Attachment Tag Name' ),
                    'menu_name'         => __( 'Attachment Tags' ),
                    );
    $args = array(
                  'hierarchical' => false,
                  'labels'       => $labels,
                  'show_ui'      => true,
                  'query_var'    => true,
                  'rewrite'      => true,
                  );
    register_taxonomy('attachment_tag', 'attachment', $args);
}

add_action('init', 'yk_register_taxonomy');
プラグインを使うなら、Attachment Taxonomy Supportがおすすめです。

WordPress パーマリンクを設定すると固定ページが404エラーになる

WordPress 3.3.1 パーマリンクをデフォルト以外にすると、投稿記事は問題なく表示できるが、固定ページが404エラーになってしまうという現象に悩んでいます。 投稿記事には、http://blog.lumiukko.jp/2012/02/hello-world/などで正常に表示できていることから、nginxなどの設定は問題ないのだろうと考えています。

WordPress: RSSが更新されない

RSSが更新されなかったり、表示するブラウザによって内容が異なったりという現象が発生しました。 色々調べたところ、W3 Total Cacheを導入してPage Cacheを有効にしていることが原因でした。
[Plugin: W3 Total Cache] RSS feed caching (3 posts) Bodieko Member Posted 1 year ago # How do I disable / exclude caching of RSS feeds? it's really a problem because od it's delayed publishing. I need them to be refreshed as soon as new post is published. efikim Member Posted 1 year ago # disable 'Cache site, categories, tags, comments and feeds' in the page cache settings Frederick Townes Member Posted 1 year ago # @efikim is right.
W3 Total CacheのPage Cache設定で、RSSのキャッシュを無効にすることで解決しました。

WordPress 特定のページにだけJavascriptを読み込む方法

例えば、itemsearchというスラッグの固定ページにだけ、yk_search.jsというjavascriptのファイルを読み込ませるには、functions.phpに以下を記述する。
function yk_js_enqueue() {
    if (is_page('itemsearch')) {
        wp_register_script('yk_search', get_stylesheet_directory_uri()."/yk_search.js");
        wp_enqueue_script('yk_search');
    }
}
add_action('wp_enqueue_scripts', 'yk_js_enqueue');

phpで文字列が含まれているかを調べる

phpで日本語を含む特定の文字列が含まれているかを調べる場合、mb_strpos/mb_striposとpreg_matchが思い浮かびますが、どっちを使うほうがいいのか速度を測ってみました。
<?php
    $title = 'イッタラ(iittala)/カステへルミ(Kastehelmi) ボウル(サンド)';
    $keywords = array('イッタラ', 'カステヘルミ', 'サンド');

    echo "mb_stripos()\n";
    $stime = microtime(true);
    for ($i = 0; $i < 10000; $i++) {
        foreach ($keywords as $word) {
            mb_stripos($title, $word);
        }
    }
    $etime = microtime(true);
    echo 'finish:' . ($etime - $stime) . "\n";

    echo "preg_match()\n";
    $stime = microtime(true);
    for ($i = 0; $i < 10000; $i++) {
        foreach ($keywords as $word) {
            preg_match('/$word/iu', $title);
        }
    }
    $etime = microtime(true);
    echo 'finish:' . ($etime - $stime) . "\n";
?>
結果は以下の通りで、preg_match()の圧勝です。
$ php -f stripos.php 
mb_stripos()
finish:1.6117179393768
preg_match()
finish:0.041254997253418
$ php -f stripos.php 
mb_stripos()
finish:1.6633319854736
preg_match()
finish:0.047746181488037
$ php -f stripos.php 
mb_stripos()
finish:1.615149974823
preg_match()
finish:0.040589094161987