<?php
/*****************************************
画像ランダム表示
Copyright 2007- Akihiro Asai. All rights reserved.

http://aki.adam.ne.jp
aki@ullr.cc
*****************************************/

$path = isset($_GET['path']) ? $_GET["path"] : "./";
$depth = isset($_GET['depth']) ? intval($_GET["depth"]) : 1;
$id = isset($_GET['id']) ? intval($_GET["id"]) : 1;

// ディレクトリへのパス
if(!is_dir($path)) {
    $path = "./";
}
if(dirname($path) != $path) {
    $path = $path."/";
}

// ディレクトリへの深さ
if($depth == 0 || $depth > 10) {
    $depth = 1;
}

// 検索条件
$match = "gif|jpg|png";
$match = ".*?\.({$match})";

$obj_gf = & new getfile();
$ret = $obj_gf->get($path, $depth, $match, $id);

if($ret != "") {
    readfile($ret);
}

exit;

/**
 * ファイルリスト取得用のクラス
 *
 */
class getfile {

    var $dir;
    var $depth;
    var $match;
    var $list;

    /**
     * コンストラクタ(PHP5対応)
     *
     */
    function __construct()
    {
    }

    /*
    * コンストラクタ
    */
    function getfile()
    {
    }

    /**
     * 条件に一致するファイル名を取得する
     *
     * @param string $path フォルダへのパス
     * @param int $depth 深さ
     * @param string $match ファイル形式(正規表現)
     * @return string ファイル名
     */
    function get($path, $depth, $match, $id)
    {
        // メンバ変数に値を設定
        $this->depth = $depth;
        $this->match = $match;

        // ファイルリストを初期化
        $this->list = array();

        // ファイルリストを取得
        $this->getList($path, 1);

        // 出力画像を抽出
        srand($this->make_seed() * $id);
        $key = rand(0, count($this->list) - 1);

        return $this->list[$key];

    }

    /**
     * 指定フォルダ以下の内容を取得する
     *
     * @param string $dir ディレクトリへのパス
     * @param int $depth 深さ
     */
    function getList($dir, $depth) {

        // ディレクトリをオープン
        $df = opendir ($dir);

        while ($filename = readdir($df)) {

            if ($filename !="." && $filename !="..") {

                // 読み取った名前がフォルダかどうかの判断
                if (is_dir($dir.$filename)) {

                    // フォルダかつ読み取り階層以下の場合は、ファイル名に追加
                    if ($depth < $this->depth) {
                        $this->getList($dir.$filename."/", $depth + 1);
                    }

                } else {
                    // ファイル形式をチェック
                    if(@preg_match("/{$this->match}/", $filename)) {
                        array_push($this->list, $dir.$filename);
                    }
                }
            }
        }

        // ディレクトリをクローズ
        closedir ($df);
    }

    /**
     * seed作成関数
     *
     * @return int
     */
    function make_seed()
    {
      list($usec, $sec) = explode(' ', microtime());
      return (float) $sec + ((float) $usec * 100000);
    }
}
?>