<?php
// $Id: dlrank.inc.php,v 0.2 2004/04/17 18:43:00 upk Exp $
/*
 * PukiWiki attach ダウンロードランキング プラグイン
 * (C) 2004, Katsumi Saito <katsumi@jo1upk.ymt.prug.or.jp>
 * License: GPL
 * modified by DEX http://dex.qp.land.to/
*/

// upload dir(must set end of /)
define("UPLOAD_DIR","./attach/");

// 該当ページ参照
define('DLRANK_ICON_SEARCH','./image/search.png');
define('DLRANK_ICON_EDIT','./image/edit.png');

// 構成定義ファイル
define('CONFIG_DLRANK','plugin/dlrank/config');

function plugin_dlrank_init() {
	switch (LANG) {
	case 'ja':
		$msg = dlrank_init_ja();
		continue;
	default:
		$msg = dlrank_init_en();
	}
	set_plugin_messages($msg);
}

function dlrank_init_ja() {

	$msg = array(
		'_dlrank_msg' => array(
			'th_page'		=> 'ページ名',
			'th_filename'   => 'ファイル名',
			'th_size'       => 'サイズ',
			'th_lastupdate' => '最終更新日',
			'th_access'     => 'アクセス数',
			'td_count'      => '件',
			'date_fmt'      => 'Y年m月d日 H:i',
			'msg_nodate'    => 'no data.',
		)
	);
	return $msg;
}

function dlrank_init_en() {

	$msg = array(
		'_dlrank_msg' => array(
			'th_page'		=> 'Page',
			'th_filename'   => 'FileName',
			'th_size'       => 'Size',
			'th_lastupdate' => 'LastUpdate',
			'th_access'     => 'AccessCount',
			'td_count'      => '',
			'date_fmt'      => 'Y/m/d H:i:s',
			'msg_nodate'    => 'no data.',
		)
	);
	return $msg;
}

function plugin_dlrank_convert()
{
	global $script;
	global $_dlrank_msg;

	list($pref_page,$sort,$ext) = func_get_args();
	if (is_null($pref_page) || empty($pref_page)) $pref_page = '';
	if (is_null($sort) || empty($sort)) $sort = 0;
	if (is_null($ext) || empty($ext)) $ext = '';

	if (!($dir = @opendir(UPLOAD_DIR))) return $_dlrank_msg['msg_nodate'];

	$bg = dlrank_set_color(); // 色の設定

//	<th class="style_th" style="background-color:{$bg['etc']}">{$_dlrank_msg['th_page']}</th>
	$rc =<<<EOD
<table class="style_table" cellpadding="1" cellspacing="1" summary="Download Ranking List">
<thead>
<tr>
	<th class="style_th" style="background-color:{$bg['etc']}">{$_dlrank_msg['th_filename']}</th>
	<th class="style_th" style="background-color:{$bg['etc']}">{$_dlrank_msg['th_size']}</th>
	<th class="style_th" style="background-color:{$bg['etc']}">{$_dlrank_msg['th_lastupdate']}</th>
	<th class="style_th" style="background-color:{$bg['etc']}">{$_dlrank_msg['th_access']}</th>
</tr>
</thead>
EOD;

	$ctr = 0;
	$data = array();
	while($file = readdir($dir))
	{
		if($file == ".." || $file == "." || strstr($file,".") != false) continue;

		preg_match("/^([^_]+)_([^_]+)$/",$file,$matches);
		$page = decode($matches[1]);
		$attach = decode($matches[2]);

		// 指定ページのみ抽出
		if($pref_page != '' && strpos($page, $pref_page) !== 0 ) continue;

		// 指定拡張子のみ抽出
		if($ext != '' && !preg_match($ext, $attach)) continue;

		$data[$ctr][0] = $attach;		// ファイル名
		$data[$ctr][1] = filesize(UPLOAD_DIR.$file);	// サイズ(ファイルサイズ)
		$data[$ctr][2] = filemtime(UPLOAD_DIR.$file);	// 最終更新日(タイムスタンプ)

		if(file_exists(UPLOAD_DIR.$file.'.log')) {
			$count = file(UPLOAD_DIR.$file.'.log');
			$data[$ctr][3] = chop($count[0]);	// アクセス数(カウンタ)
		} else {
			$data[$ctr][3] = "0";			// アクセス数(カウンタ)
		}
		$data[$ctr][4] = $page;				// ページ名

		$ctr++;
	}
	closedir($dir);

	// FIXME: 暫定対応
	// Sort Key
	// 0:ファイル名 1:サイズ 2:最終更新日 3:ダウンロード 4:ページ名
	// usort($data,create_function('$a,$b','return $b[$sort] - $a[$sort];'));
	switch ($sort)
	{
	case 1:
	case 2:
	case 3:
		$sort_fmt = sprintf('return $b[%d] - $a[%d];',$sort,$sort);
		break;
	case 0:
	case 4:
		$sort_fmt = sprintf('return ($a[%d] == $b[%d]) ? 0 : (($a[%d] > $b[%d]) ? 1 : -1);',$sort,$sort,$sort,$sort);
		break;
	default:
		$sort_fmt = sprintf('return $b[%d] - $a[%d];',$sort,$sort);
	}

	usort($data,create_function('$a,$b',$sort_fmt));

	$rc .= "<tbody>\n";
	foreach($data as $x) {
		$rc .= dlrank_edit_body($x);
	}
	$rc .= "</tbody>\n";

	$rc .= "</table>\n";
	return  $rc;
}

function dlrank_edit_body($data)
{
	global $script;
	global $_dlrank_msg;
	$encFile = rawurlencode($data[0]);	// エンコード済みファイル名
	$encPage = rawurlencode($data[4]);	// エンコード済みページ名

	// 最終更新日を UTIME から指定形式に変換
	$lastmod = date($_dlrank_msg['date_fmt'],$data[2]);
	// 単位変換
	settype($dfile_size,"double");
	$dfile_size = round($data[1]/1000,1);
	$file_size = sprintf("%01.1f",$dfile_size)."KB";

	$doc =  "<a href=\"".$script."?".$encPage."\" ".
		"title=\"".$data[4]."\"><img src=\"";
	// ページの存在チェック
	$doc .= file_exists(get_filename($data[4])) ? DLRANK_ICON_SEARCH : DLRANK_ICON_EDIT;
	$doc .= "\" alt=\"{$data[4]}\" /></a>";

	// $data[] = 0:ファイル名 1:サイズ 2:最終更新日 3:アクセス数 4:ページ名
	$aPage = explode("/", $data[4]);
	$lastPage = array_pop($aPage);
//	<td class="style_td"><a href="{$script}?{$encPage}" title="{$data[4]}">$lastPage</a></td>
	$result =<<<EOD
<tr>
	<td class="style_td">{$doc}
		<a href="{$script}?plugin=attach&amp;openfile={$encFile}&amp;refer={$encPage}" title="{$lastmod} {$file_size}"> {$data[0]}</a>
	</td>
	<td class="style_td" style="text-align:right">{$file_size}</td>
	<td class="style_td">{$lastmod}</td>
	<td class="style_td" style="text-align:right">{$data[3]}{$_dlrank_msg['td_count']}</td>
</tr>
EOD;
	return $result;
}

function dlrank_set_color()
{
	static $color;

	if (!isset($color))
	{
		// デフォルトカラー
		$color = array(
			'cur' => '#88ff88',
			'etc' => '#cccccc'
		);

		$config = new Config(CONFIG_DLRANK);
		$config->read();
		$pconfig_color = $config->get('COLOR');
		unset($config);
		foreach ($pconfig_color as $x)
		{
			// BGCOLOR(#88ff88)
			$color[$x[0]] = htmlspecialchars(
				preg_match('/BGCOLOR\(([^)]+)\)/si',$x[1],$matches) ? $matches[1] : $x[1]
			);
		}
	}
        return $color;
}

?>
