Php/自作ユーティリティclass kz
提供: 初心者エンジニアの簡易メモ
<?php
/**
* phpユーティリティ集+α
* いろんな機能をごちゃ混ぜで結合してます。一番やっちゃいけない暗号的結合なクラスです
* 使いようのものから意味不明なものまで、
* もしかするとほりだしものもあるかも。
* クラスとして使えなくはないですが、使いたいやつをコピーしてもってくのが良いかと思います。
* このスクリプトはsjisで保存
*
* gethtml()はpearのHTTP/Client必須
*/
// php技術メモ、このクラスとはまったく無関係
// set_time_limit(0);処理時間を無限に
// http_build_query // 配列からURLのパラメータを作成 (逆:parse_url)
// parse_ini_file() //iniファイル取得
// ini_set("display_errors", true); // レポート表示
// ini_set("error_reporting", E_ALL); // レポート種類
// ini_set("error_reporting", E_ERROR & ~E_NOTICE & ~E_PARSE); // 関数非推奨エラーを除いたエラー
// ini_set("log_errors", true); // レポートログ
// ini_set("error_log", "./php_error.log"); // レポートログ
// ini_set("memory_limit", "64M"); // メモリサイズ変更
class class_kz
{
// コンストラクタ
function class_kz()
{
}
//--------------------------------------------------
/**
* ウェブ上のhtmlソースを取得
*
* @param string $url URL
* @param string $mobile (softbank,au,docomo
* @return string $rtn コンテンツ
*/
function gethtml($url, $mobile = false)
{
// pear
require_once "HTTP/Client.php";
$client =& new HTTP_Client();
if ($mobile) {
if ($mobile == "softbank") {
$agent = 'SoftBank/1.0/DM002SH/SHJ001[/Serial] Flash/Flash-Lite/2.0';
} elseif ($mobile == "au") {
$agent = 'UP.Browser/6.2.0.5 (GUI) MMP/2.0';
} else {
$agent = 'DoCoMo/2.0 N901iS(c100;TB;W24H12)';
}
} else {
$agent = 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.04506.648)';
}
$client->setDefaultHeader('User-Agent', $agent);
$client->get($url);
$response = $client->currentResponse();
if ($response["code"] == 200) {
return $response['body'];
} else {
die("kz_class false gethtml() " . $response["code"] . " request " . $url);
}
}
// /**
// * ウェブ上のhtmlソースを取得
// *
// * クローラ対策時の偽装方法
// * ini_set("user_agent", "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)");
// * ini_set("user_agent", "DoCoMo/2.0 N901iS(c100;TB;W24H12)");
// * @param string $url URL
// * @return string $rtn コンテンツ
// */
// function gethtml($url, $mode = false)
// {
// $rtn = file_get_contents($url);
// return $rtn;
// }
//--------------------------------------------------
/**
* htmlからtextへ
* phpに同義関数あり
*
* @param string $value html
* @return string htmlspecialchars($value) text
*/
function html_to_text($value)
{
return htmlspecialchars($value);
}
//--------------------------------------------------
/**
* textからhtmlへ
* phpに同義関数あり
*
* @param string $value text
* @return string htmlspecialchars_decode($value) html
*/
function text_to_html($value)
{
return htmlspecialchars_decode($value);
}
//--------------------------------------------------
/**
* テーブル式のデータ取得
*
* @param string $filename ファイル名
* @return object $rtn 読み込みデータ
*/
function get_file_table($filename)
{
$head = array();
$data = array();
$rtn = array();
if (!$handle = fopen($filename, 'r')) {
// exit();
}
if ($handle) {
$i = 0;
while (!feof($handle)) {
$line = fgets($handle, 1024);
if ($line != "") { // 空文字を省く
$data = split("\t", $line);
if ($i == 0) {
foreach ($data as $value) {
$value = preg_replace("/\r\n/", "", $value); // 改行を省く
array_push($head, $value);
}
} else {
foreach ($head as $key => $value) {
$data[$key] = preg_replace("/\r\n/", "", $data[$key]); // 改行を省く
$row[$value] = $data[$key];
}
array_push($rtn, $row);
}
$i++;
}
}
fclose($handle);
}
return $rtn;
}
//--------------------------------------------------
/**
* テーブル式のデータ格納
*
* @param string $filename ファイル名
* @param object $data データ
* @return void
*/
function set_file_table($filename, $data)
{
$out = "";
if ($data) {
$array = array_keys($data[0]);
foreach ($array as $value) {
$out .= $value."\t";
}
}
$out .= "\r\n";
foreach ($data as $key1=> $value1) {
foreach ($value1 as $key2 => $value2) {
$out .= $value2."\t";
}
$out .= "\r\n";
}
// file_put_contents($filename, $out); // php4ノーサポート
// 書き込みモードでファイルを開く
if (!$handle = fopen($filename, 'w')) {
exit;
}
if (fwrite($handle, $out) === FALSE) {
exit;
}
fclose($handle);
}
//--------------------------------------------------
/**
* テーブル式のデータからデータ削除
*
* @param string $filename ファイル名
* @param array $where 条件
* @return void
*/
function del_file_table($filename, $where)
{
$data = $this->get_file_table($filename);
$temp = array();
foreach ($data as $key =>$value) {
$del_flg = 1;
foreach ($where as $keyw => $valuew) {
if ($data[$key][$keyw] != $valuew) {
$del_flg = 0;
}
}
// 削除のとき
if ($del_flg == 1) {
// 削除しないとき
} else {
array_push($temp, $value);
}
}
$this->set_file_table($filename, $temp);
}
//--------------------------------------------------
/**
* テーブル式のデータにデータ追加
*
* @param string $filename ファイル名
* @param array $where 条件
* @return void
*/
function insert_file_table($filename, $data)
{
}
//--------------------------------------------------
/**
* ファイルから単一データ取得
*
* @param string $filename ファイル名
* @return string $rtn 取得データ
*/
function get_file_data($filename)
{
if (!$handle = fopen($filename, 'r')) {
return;
}
$rtn = "";
if ($handle) {
while (!feof($handle)) {
$line = fgets($handle, 1024);
$rtn .= $line;
}
fclose($handle);
}
return $rtn;
}
//--------------------------------------------------
/**
* ファイルへ単一データ書込
*
* @param string $filename ファイル名
* @param string $data 書込データ
* @return void
*/
function set_file_data($filename, $data)
{
//書き込みモードでファイルを開く
if (!$handle = fopen($filename, 'w')) {
return;
}
if (fwrite($handle, $data) === FALSE) {
return;
}
fclose($handle);
}
//--------------------------------------------------
/**
* ファイルから配列データ取得
*
* @param string $filename ファイル名
* @return array $arr 配列データ
*/
function get_file_array($filename)
{
if (file_exists($filename)) {
return file($filename);
}
}
//--------------------------------------------------
/**
* ファイルへ配列データを設定
*
* @param string $filename ファイル名
* @param array $arr 配列データ
* @return void
*/
function set_file_array($filename, $arr)
{
foreach ($arr as $value) {
$buf .= $value;
}
$this->set_file_data($filename, $buf);
}
//--------------------------------------------------
/**
* ファイルからtsvデータ取得
*
* @param string $path ファイル名
* @return array $arr 配列データ
*/
function get_file_tsv($path)
{
$lines = $this->get_file_array($path);
foreach ($lines as $line) {
$line = preg_replace("/\r\n|\r|\n/", "", $line);
$rows = split("\t", $line);
$arr[] = $rows;
}
return $arr;
}
//--------------------------------------------------
/**
* ファイルへtsvデータを設定
*
* @param string $path ファイル名
* @param array $arr 配列データ
* @return void
*/
function set_file_tsv($path, $arr)
{
foreach($arr as $rows) {
unset($line);
foreach ($rows as $key => $value) {
$line .= $value;
if (count($rows) - 1 != $key) {
$line .= "\t";
}
}
$lines[] = $line . "\n";
}
$this->set_file_array($path, $lines);
}
//--------------------------------------------------
/**
* dir内のファイル名一覧を取得
*
* @param string $dirname フィルダ名
* @param int $kakutyousi 拡張子有り(1)無し(0) option
* @return array $rtn フォルダ内のファイル名
*/
function get_dir_file($dirname, $kakutyousi = 1)
{
if (!file_exists($dirname)) return;
$rtn = array();
$handle = openDir($dirname);
while(false !== $name = readDir($handle)) {
if ($name != "." && $name != "..") {
if ($kakutyousi == 0) {
$name = preg_replace("/.[^.]*$/", "", $name); // 拡張子削除
}
array_push($rtn, $name);
}
}
return $rtn;
}
// dir内のファイルを削除
function del_dir_file($dirname)
{
if (!file_exists($dirname)) return;
$files = $this->get_dir_file($dirname, 1);
if ($files) {
// ファイル削除
foreach ($files as $file) {
unlink($dirname . "/" . $file);
}
}
}
//---------------------------------------------------------------------
/**
* ファイルを追加書き込み
*
* @access public
* @param String $filename ファイル名
* @param String $value 書込データ
* @return なし
*/
function add_file_data($filename, $value) {
if ($fp = fopen($filename, "a")) {
flock($fp, LOCK_EX);
fputs($fp, $value);
flock($fp, LOCK_UN);
fclose($fp);
}
}
//--------------------------------------------------
/**
* 画像リサイズ
*
* @param string $img_name = "image.jpg"; //ファイル名(JPEG画像)
* @param string $img_path = "./"; //サムネイルを作る元画像のあるディレクトリ(必ず末尾は"/"で閉じる)
* @param string $thumbnail_path = "thumbnail/"; //サムネイルを保存するディレクトリ
* @param string $thumbnail_w = 80; //サムネイルの横幅
* @param string $thumbnail_h = 60; //サムネイルの縦幅
* @return void
* @GD要 extension=php_gd2.dll
* @参考 http://noongoro.main.jp/note/note0052.html
*/
function create_thumbnail($img_name, $img_path, $thumbnail_path, $thumbnail_w, $thumbnail_h)
{
//元画像のサイズ取得
list($img_w, $img_h) = getimagesize($img_path.$img_name);
//縦比に対しての変更後の横幅を取得
$thumbnail_w_tmp = floor($thumbnail_h/$img_h*$img_w);
//横幅が指定幅より狭いときは縦幅を縮小する
if ($thumbnail_w_tmp < $thumbnail_w) {
$thumbnail_w = $thumbnail_w_tmp;
} else {
$thumbnail_h = floor($thumbnail_w/$img_w*$img_h);
}
$src_img = @imagecreatefromjpeg ( $img_path.$img_name );
if ($src_img) {
$dst_img = imagecreatetruecolor ( $thumbnail_w, $thumbnail_h );
$result = imagecopyresampled ( //$result = imagecopyresized (
$dst_img, //貼り付けするイメージID
$src_img, //コピーする元になるイメージID
0, //int dstX (貼り付けを開始するX座標)
0, //int dstY (貼り付けを開始するY座標)
0, //int srcX (コピーを開始するX座標)
0, //int srcY (コピーを開始するY座標)
$thumbnail_w, //int dstW (貼り付けする幅)
$thumbnail_h, //int dstH (貼り付けする高さ)
$img_w, //int srcW (コピーする幅)
$img_h //int srcH (コピーする高さ)
);
//サムネイルをJPEG形式で保存
imagejpeg ( $dst_img, $thumbnail_path.$img_name );
imagedestroy ( $dst_img ); //サムネイル用イメージIDの破棄
imagedestroy ( $src_img ); //サムネイル元イメージIDの破棄
} else {
exit(); // error
}
}
//--------------------------------------------------
/**
* 画像出力
*
* @param string $addr 画像アドレス
* @return data 画像データ
* @GD要 extension=php_gd2.dll
*/
function imageout($addr)
{
//出力画像形式をgifに指定
header("Content-type:image/gif");
//画像を読み込み
$img = ImageCreateFromGif($addr);
//画像PNG形式で出力
ImageGif($img);
//画像用メモリ開放
ImageDestroy($img);
//プログラム終了(誤動作防止)
exit;
}
//--------------------------------------------------
/**
* ファイルアップロード表示
*
* @access public
* @param string $phpname アップ処理のスクリプトのファイル名指定
* @return void
* @link http://jp.php.net/manual/ja/features.file-upload.php
* @ex print $obj_kz->$file_up_html("fileup.php");
*/
function file_up_html($phpname)
{
$out =<<<EOD
<form enctype="multipart/form-data" action={$phpname} method="POST">
<!-- MAX_FILE_SIZE バイト数指定 -->
<input type="hidden" name="MAX_FILE_SIZE" value="30000000" />
Send this file: <input name="userfile" type="file" />
<input type="submit" value="Send File" />
</form>
EOD;
return $out;
}
//--------------------------------------------------
/**
* ファイルアップロード処理
*
* @access public
* @param string $uploaddir アップロード先のフォルダ指定
* @param string $type ファイルタイプ規制 option 画像のみのときは:"image"
* @return string $rtn 正常:"true"、エラー:"error"、ファイルタイプ不整合:"error_type"、
* ファイルアップロードエラー:"false"、既にUP済み:"already_exists"
* 例)if ($_FILES) {file_up_php("./up/");}
*/
function file_up_php($uploaddir, $type="")
{
// uploaddir = './up/';
if ($_FILES["userfile"]["error"] > 0) {
$rtn = "error";
// echo "Error: " . $_FILES["userfile"]["error"] . "<br/>";
} else {
if ($type != "") {
$match = preg_match("/{$type}/", $_FILES["userfile"]["type"]);
if (!$match) {
$rtn = "error_type";
}
}
if (!$rtn) {
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
if (file_exists($uploadfile)) {
$rtn = "already_exists";
} else {
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
$rtn = "true";
} else {
$rtn = "false";
}
}
}
}
// print nl2br(print_r($_FILES, 1)); // デバッグ用
return $rtn;
}
//--------------------------------------------------
/**
* 改行記号削除
*
* @access public
* @param string $text 元データ
* @return string $rtn 改行記号削除データ
*/
function text_to_del_n($text)
{
$rtn = preg_replace("/(\r|\n|\r\n)/", "", $text);
return $rtn;
}
//--------------------------------------------------
/**
* tab記号削除
*
* @access public
* @param string $text 元データ
* @return string $rtn tab記号削除データ
*/
function text_to_del_t($text)
{
$rtn = preg_replace("/(\t)/", "", $text);
return $rtn;
}
//--------------------------------------------------
/**
* Bタグ削除
*
* @access public
* @param string $text 元データ
* @return string $rtn 削除データ
*/
function text_to_del_b($text)
{
$rtn = preg_replace("/<[\/]?b>/i", "", $text);
return $rtn;
}
//--------------------------------------------------
/**
* タグ削除
*
* @access public
* @param string $text 元データ
* @param mixed option $tag タグ(文字列か、配列か、|区切り文字列か)
* @return string $text 削除データ
* phpに同義関数有り strip_tags
*/
function text_to_del_tag($text, $tag="")
{
// 文字列の時
if (is_string($tag)) {
// 配列形式の文字列のとき
if (preg_match("/\|/", $tag)) {
$arr = array();
$arr = split("\|", $tag);
$text = $this->text_to_del_tag($text, $arr); // 再起
//--------------------------------------------------
// 文字列の時
} else {
$text = preg_replace("/<[\/]?{$tag}[^>]*>/i", "", $text); // タグ削除
}
//--------------------------------------------------
// 配列データのとき
} elseif (is_array($tag)) {
foreach ($tag as $value) {
$text = $this->text_to_del_tag($text, $value); // 再起
}
}
if (!$tag) {
$text = strip_tags($text); // 全タグを取り除く
}
return $text;
}
//--------------------------------------------------
/**
* Aタグ取得
*
* @access public
* @param string $text 取得元データ
* @param string $addr option 取得URLパターン(正規表現)
* @param string $front option タグ内の先頭要素
* @param string $option option nohttp":httpがないURLでも取得]
* @return array $matches [0]:Aタグ、[1]:URL、[2]:title
*/
function text_to_tag_a($text, $addr="", $front = "", $option = "")
{
if ($addr == "") {
$addr = "http:\/\/[-_.!~*'()a-zA-Z0-9;\/\?:@&=+$,%#]+";
}
if ($option == "nohttp") {
$addr = "[-_.!~*'()a-zA-Z0-9;\/\?:@&=+$,%#]+";
}
preg_match_all("/<a$front href=[\"\']?({$addr})[\"\']?[^>]*>([^<]*)<\/a>/i", $text, $matches);
return $matches;
}
//--------------------------------------------------
/**
* imgタグ取得
*
* @access public
* @param string $text 元データ
* @param string $addr option 取得URLパターン(正規表現)
* @param string $front option タグ内の先頭要素
* @param string $option option nohttp":httpがないURLでも取得]
* @return array $matches :imgタグ、[1]:URL
*/
function text_to_tag_img($text, $addr = "", $front = "", $option = "")
{
if ($addr == "") {
$addr = "http:\/\/[-_.!~*'()a-zA-Z0-9;\/\?:@&=+$,%#]+";
}
if ($option == "nohttp") {
$addr = "[-_.!~*'()a-zA-Z0-9;\/\?:@&=+$,%#]+";
}
preg_match_all("/<img$front src=[\"\']?({$addr})[\"\']?[^>]*>/i", $text, $matches);
return $matches;
}
//--------------------------------------------------
/**
* like文から正規表現文を作成
*
* @access public
* @param string $addr
* @return string $rtn
*/
function like_to_reg($addr)
{
$exp = "[-_.!~*'()a-zA-Z0-9;\/\?:@&=+$,%#]+";
$addr = str_replace("/", "\/", $addr);
$rtn = str_replace("%", $exp, $addr);
return $rtn;
}
//--------------------------------------------------
/**
* 'をへ
*
* @param string $str 元文字列
* @return string $rtn
* このメソッドは廃止。mysqlのquoteへ
* phpに同義関数有り addslashes
*/
function quote_to_two_quote($str)
{
$rtn = str_replace("'", "", $str);
return $rtn;
}
//--------------------------------------------------
/**
* date文字列からunixtime
*
* @access public
* @param string $str
* @return int $value
* @例 2007-08-22 01:20:08 →1187713208
* strtotime( "2009-09-26 23:00:00" )でもできる
*/
function date_to_unixtime($str)
{
$value = mktime(substr($str,11,2), substr($str,14,2), substr($str,17,2), substr($str,5,2), substr($str,8,2), substr($str,0,4));
return $value;
}
//--------------------------------------------------
/**
* unixtimeからdate文字列
*
* @access public
* @param int $time
* @return string date("Y-m-d H:i:d", time($str))
* @例 1187713208 → 2007-08-22 01:20:08
*/
function unixtime_to_date($time)
{
return date("Y-m-d H:i:d", $time);
}
//--------------------------------------------------
/**
* ページラベルを表示(廃止の方向で、下を使う)
*
* @access public
* @param int $rowcnt データ数
* @param int $nowpage 現在のページ数
* @param int $viewnum 表示データ数
* @param int $pageviewnum option ページ数上限
* @return array $pagerow ページラベル
*/
function page_label($rowcnt, $nowpage, $viewnum, $pageviewnum = 10)
{
$pagecnt = floor(($rowcnt-1) / $viewnum) + 1;
if (!$nowpage) {
$page = 1;
} else {
$page = $nowpage;
}
$rowstart = ($page-1) * $viewnum; // 表示する最初のデータ番号
$rowlast = $rowstart + $viewnum; // 表示する最後のデータ番号
if ($rowlast > $rowcnt) {$rowlast = $rowcnt;}
$pagerow = array();
$pagef = $page - floor($pageviewnum / 2); // 最初のページ番号
if ($pagef <= 0) {$pagef = 1;}
$pagea = $pagef + $pageviewnum - 1; // 最後のページ番号
if ($pagea > $pagecnt) {
$pagea = $pagecnt;
}
if ($pagea - $pageviewnum < $pagef) {
$pagef = $pagea - $pageviewnum + 1; // 最初のページ番号
$pagea = $pagef + $pageviewnum - 1; // 最後のページ番号
}
if ($pagef <= 0) {$pagef = 1;}
for ($i = $pagef; $i <= $pagea; $i++) {
if ($i > $pagecnt) {
continue;
}
array_push($pagerow, $i);
}
// 1ページのみのときはデータを返さない
if (count($pagerow) == 1) {
$pagerow = "";
} else {
// 次へ(next)をつける
// 戻る(pref)をつける
}
return $pagerow;
}
//--------------------------------------------------
/**
* ページャーを表示
*
* @access public
* @param int $rowcnt データ数
* @param int $nowpage 現在のページ数
* @param int $viewnum 表示データ数
* @param int $pageviewnum option ページ数上限
* @return array $rtn ページラベル 例){page=>array(1,"...",20,21,"...",40),prev=>19,next=>21}
*/
function pager($rowcnt, $nowpage, $viewnum, $pageviewnum = 10)
{
$pagecnt = floor(($rowcnt-1) / $viewnum) + 1;
$nowpage = floor($nowpage);
if ($nowpage <= 0) {
$nowpage = 1;
}
if ($nowpage > $pagecnt) {
$nowpage = $pagecnt;
}
$rowstart = ($nowpage-1) * $viewnum; // 表示する最初のデータ番号
$rowlast = $rowstart + $viewnum; // 表示する最後のデータ番号
if ($rowlast > $rowcnt) {$rowlast = $rowcnt;}
$pagerow = array();
$pagef = $nowpage - floor($pageviewnum / 2); // 最初のページ番号
if ($pagef <= 0) {$pagef = 1;}
$pagea = $pagef + $pageviewnum - 1; // 最後のページ番号
if ($pagea > $pagecnt) {
$pagea = $pagecnt;
}
if ($pagea - $pageviewnum < $pagef) {
$pagef = $pagea - $pageviewnum + 1; // 最初のページ番号
$pagea = $pagef + $pageviewnum - 1; // 最後のページ番号
}
if ($pagef <= 0) {$pagef = 1;}
for ($i = $pagef; $i <= $pagea; $i++) {
if ($i > $pagecnt) {
continue;
}
array_push($pagerow, $i);
}
//--------------------------------------------------
// トップと最後のは必ず表示するときの処理↓
if ($pageviewnum >= 3) { // 表ページ数が3つ以上でないと使えない
if ($pagerow) { // ページ数があるとき
// ページ飛ばし機能
if ($pagerow[0] >= 2) {
array_shift($pagerow); // 最初の配列を取除く
array_unshift($pagerow, "..."); // 最初に配列追加
array_unshift($pagerow, 1); // 最初に配列追加
}
$lastrowpage = count($pagerow) - 1;
if ($pagerow[$lastrowpage] <= $pagecnt - 1) {
array_pop($pagerow); // 最後の配列を取除く
array_push($pagerow, "..."); // 最後の配列追加
array_push($pagerow, $pagecnt); // 最後の配列追加
}
}
}
//--------------------------------------------------
// 1ページのみのときはデータを返さない
if (count($pagerow) == 1) {
$pagerow = "";
} else {
if ($pagecnt > $nowpage) {
$rtn["next"] = $nowpage + 1; // 次へ(next)をつける
}
if ($nowpage >= 2) {
$rtn["prev"] = $nowpage - 1; // 前へ(prev)をつける
}
}
if ($pagerow) {
$rtn['page'] = $pagerow;
}
$rowstart++;
if ($rowstart < 0) {
$rowstart = 0;
}
$rtn['now'] = $nowpage; // 現在のページ
$rtn['last'] = $pagecnt; // 最後のページ
$rtn['data_start'] = $rowstart; // 表示する最初のデータ番号
$rtn['data_last'] = $rowlast; // 表示する最後のデータ番号
return $rtn;
}
//--------------------------------------------------
/**
* フルパスの内ディレクトリパスを返す
*
* @param string $path パス
* @return void
*/
function fullpath_to_dirpath($path)
{
// $pos = strrpos($path, "/") + 1;
// $rtn = substr($path, 0, $pos);
$rtn = dirname($path)."/";
return $rtn;
}
//--------------------------------------------------
/**
* ディレクトリパスとファイル名を結合する(/の数が重ならないように処理)
*
* @param string $dir ディレクトリパス
* @param string $file ファイルパス
* @return string $rtn 結合パス
*/
function dirpath_marge_filename($dir, $file)
{
if (substr($dir, -1, 1) == "/") {
if (substr($file, 0, 1) == "/") {
$file = substr($file, 1);
}
}
$rtn = $dir . $file;
return $rtn;
}
//--------------------------------------------------
/**
* 配列の中に、あるデータが正規表現で一致する場合、配列の中のデータを取得(複数ある場合は最初のデータを取得)
*
* @param string $str 検索文字列
* @param array $arr 対象配列
*/
function array_reg($str, $arr)
{
foreach ($arr as $key => $value) {
if (preg_match("/{$str}/", $value)) {
return $value;
}
}
}
//--------------------------------------------------
/**
* 配列の中に、あるデータが含まれている場合、配列の中のデータを取得(複数ある場合は最初のデータを取得)
*
* @param string $str 検索文字列
* @param array $arr 対象配列
*/
function array_pos($str, $arr)
{
foreach ($arr as $key => $value) {
$pos = strpos($value, $str);
if ($pos !== false) {
return $value;
}
}
}
//--------------------------------------------------
/**
* X文字以上の文字は切り捨て
*
* @param string $str 対象文字
* @param int $len 表示文字数
* @param string $plus option 付加文字
* @return string $str
*/
function strtrim($str, $len, $plus = "")
{
if (strlen($str) > $len) {
$str = substr($str, 0, $len).$plus;
}
return $str;
}
//--------------------------------------------------
/**
* 携帯判別
*
* @return string 端末名
*/
function get_mobile_name()
{
$agent = $_SERVER['HTTP_USER_AGENT'];
// i-mode
if (preg_match("/^DoCoMo/", $agent)) {
return "docomo";
// softbank
} elseif (preg_match("/(^J-PHONE|^SoftBank|^Vodafone|^MOT)/", $agent)) {
return "softbank";
// au
} elseif (preg_match("/(^KDDI|^UP\.Browser|^PDXGW)/", $agent)) {
return "au";
}
}
//--------------------------------------------------
/**
* カレンダーhtml取得
*
* @access public
* @param string $path 元URLパス
* @param array $date 現在の日付["year", "mon", "mday"]
* @param array $link 移動可能な日付(キーに日付を入れる)
* @param string $dkey option キー名(デフォルト:date)
* @return string $out カレンダーHTML
*/
function get_calendar($path, $date = "", $link = "", $dkey = "date")
{
if (!$date['year']) {
$date['year'] = date("Y", time());
$date['mon'] = date("m", time());
$date['mday'] = date("d", time());
}
$date['yearfront'] = $date['year'];
$date['yearafter'] = $date['year'];
$date['monfront'] = $date['mon'] - 1;
if ($date['mon'] == 1) {
$date['monfront'] = 12;
$date['yearfront']--;
}
$date['monafter'] = $date['mon'] + 1;
if ($date['mon'] == 12) {
$date['monafter'] = 1;
$date['yearafter']++;
}
foreach ($date as $key => $value) {
if (preg_match("/(mon|mday)/", $key)) {
if ($date[$key] != 0) {
$date[$key] = substr("0{$value}", -2, 2);
}
}
}
// URLの繋ぎ文字
if (preg_match("/\?/", $path)) {
$con = "&";
} else {
$con = "?";
}
$out .= "<table border='1'><tbody>";
$out .= "<tr>";
$out .= "<td><font size='2'><a href='{$path}{$con}{$dkey}={$date['yearfront']}{$date['monfront']}'>←</a></font></td>";
$out .= "<td colspan='5'>";
$out .= "<font size='2'><center><a href='{$path}{$con}{$dkey}={$date['year']}{$date['mon']}'>{$date['year']}年 ";
$out .= "{$date['mon']}月</a></center></font></td>";
$out .= "<td><font size='2'><a href='{$path}{$con}{$dkey}={$date['yearafter']}{$date['monafter']}'>→</a></font></td>";
$out .= "</tr>";
$out .= "<tr>";
$out .= "<td><font size='2'>日</font></td>";
$out .= "<td><font size='2'>月</font></td>";
$out .= "<td><font size='2'>火</font></td>";
$out .= "<td><font size='2'>水</font></td>";
$out .= "<td><font size='2'>木</font></td>";
$out .= "<td><font size='2'>金</font></td>";
$out .= "<td><font size='2'>土</font></td>";
$out .= "</tr>";
$out .= "<tr>";
$youbim1 = $this->get_calendar_youbi($date);
for ($i = 1; $i <= $youbim1; $i++) {$out .= "<td > </td>";}
$hi = array("", 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
for ($i = 1; $i <= $hi[floor($date['mon'])]; $i++) {
$out .= "<td align='right'";
// 今見ている日付の色を変える。
if ($i == $date['mday']) {$out .= "bgcolor=#cccccc";}
$out .= "><font size='2'>";
if ($link[$i]) {
$i2 = substr("0".$i, -2, 2); // 右から2つ
$out .= "<a href='{$path}{$con}{$dkey}={$date['year']}{$date['mon']}{$i2}'>$i</a>";
} else {
$out .= "$i";
}
$out .= "</font></td>";
if ((($youbim1 + $i ) % 7) == 0) {$out .= "</tr><tr>";}
}
$out .= "</tr>";
$out .= "</td></tr>";
$out .= "</tbody></table>";
return $out;
}
//--------------------------------------------------
/**
* 月の元日の曜日を取得
* 上のカレンダーに依存
*
* @param string $data {year, mon} 年月
* @return int $youbim1 % 7 曜日番号
*/
function get_calendar_youbi($date = "")
{
if (!$date['year']) {
$date['year'] = date("Y", time());
$date['mon'] = date("m", time());
$date['mday'] = date("d", time());
}
$hi = array(0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
$tosi = $date['year'];
$tuki = $date['mon'];
if ($tosi % 4 == 0) {
if ($tosi % 100 == 0) {
if ($tosi % 400 == 0) {$hi[2] = 29;}
}
else {$hi[2] = 29;}
}
$allhi = 0;
if ($tuki >= 2) {
for ($i = 1; $i<= $tuki - 1; $i++) {
$allhi = $allhi + $hi[$i];
}
}
$youbim1 = $tosi + $allhi;
$youbim1 = $youbim1 + floor($tosi / 4);
$youbim1 = $youbim1 - floor($tosi / 100);
$youbim1 = $youbim1 + floor($tosi / 400);
if ($hi[2] == 29) {$youbim1--;}
return $youbim1 % 7;
}
//--------------------------------------------------
/**
* X文字以上の半角文字を削除
*
* @access public
* @param string $str 文字
* @param int $value 番号
* @return string $str 削除後文字
*/
function del_hankaku($str, $value)
{
$str = preg_replace('/([-_.!~*\'()a-zA-Z0-9;\/?:\@&=+\$,%#|?]{'.$value.',})/', , $str);
return $str;
}
//--------------------------------------------------
/**
* X文字以上の半角文字を折り返し
*
* @access public
* @param string $str 文字
* @param int $value 番号
* @return string $str 折り返し入り文字
*/
function br_hankaku($str, $value)
{
$str = preg_replace('/([-_.!~*\'()a-zA-Z0-9;\/:\@&=+\$,%#|]{'.$value.'})/', '$1<br>', $str); // ?は自動改行されるので除く
return $str;
}
//--------------------------------------------------
/**
* urlcheck
*
* @access public
* @param string $url URL
* @return array $rtn [0]:否、[1]:可
* @link http://www.din.or.jp/~ohzaki/perl.htm#URI perlメモ
*/
function url_check($url)
{
// $addr="s?https?://[-_.!~*'()a-zA-Z0-9;/?:@&=+$,%#]+";
$addr = "s?https?:\/\/[-_.!~*'()a-zA-Z0-9;\/\?:@&=+$,%#]+";
$rtn = preg_match("/{$addr}/", $url);
return $rtn;
}
//--------------------------------------------------
/**
* urlcheck_強め
*
* @access public
* @param string $url URL
* @return array $rtn [0]:否、[1]:可
*/
function url_check_hard($url)
{
if ($this->url_check($url)) {
$addr = "s?https?:\/\/[^\.]*[\.][^\.]*"; // URL中に.を含まないものは排除
$rtn = preg_match("/{$addr}/", $url);
}
return $rtn;
}
//--------------------------------------------------
/**
* 正しい書式のメールアドレスの場合は、1 を返す
*
* @access public
* @param string $email メール
* @return int 1 or 0
* @link http://q.hatena.ne.jp/1130649169
*/
function mail_check($email)
{
if (preg_match('/^([a-z0-9_]|\-|\.|\+)+@(([a-z0-9_]|\-)+\.)+[a-z]{2,6}$/i', $email)) {
return 1;
}
return 0;
}
//--------------------------------------------------
/**
* 配列のX番目からX個のみ取り出す
*
* @access public
* @param array $arr 元配列
* @param int $start 取出初め
* @param int $length option 取出個数
* @return array $rtn option 取出配列
*/
function array_substr($arr, $start = 0, $length = "")
{
$i = 0;
$rtn = array();
if ($arr) {
foreach ($arr as $value) {
if ($i >= $start && $i <= $length + $start) {
array_push($rtn, $value);
}
$i++;
}
}
return $rtn;
}
//--------------------------------------------------
/**
* 文字列中のURLをAタグ化する
*
* @access public
* @param string $str 対象文字列
* @param string $target option Aタグ化後のターゲット指定
* @param int $nocomp option 完全でないURLも許可("":完全のみ, 1:不完全を含む)
* @return string $rtn Aタグ化後の文字列
*/
function str_to_atag($str, $target = "", $nocomp = "")
{
if ($target) {
$target_str = "target=$target";
}
if ($nocomp) {
$http = "h?t?tp"; // 不完全パターン
} else {
$http = "http"; // 完全パターン
}
$rtn = preg_replace("/({$http}s?:\/\/)([!#%&*+,\-.\/;=?\@_~0-9A-Za-z]+)\b/", "<a href='http://$2' $target_str>$1$2</a>", $str);
return $rtn;
}
//--------------------------------------------------
/**
* 色コードをランダムで作成
*
* @access public
* @return string $rtn 色文字列
*/
function get_color_rand()
{
for ($k = 1; $k <= 6; $k++) {
$i = floor(rand() % 6) * 3;
if ($i == 10) {$i = 'a';}
if ($i == 11) {$i = 'b';}
if ($i == 12) {$i = 'c';}
if ($i == 13) {$i = 'd';}
if ($i == 14) {$i = 'e';}
if ($i == 15) {$i = 'f';}
$rtn = "{$rtn}{$i}";
}
$rtn = "#{$rtn}";
return $rtn;
}
//--------------------------------------------------
/**
* getパラメータをinputタグへ変更
*
* @access public
* @param string $param get文字列
* @return string $rtn inputタグ
*/
function geturl_to_inputtag($param)
{
$str= preg_replace("/^[\?\&]/", "", $param);
$arr = split("&", $str);
foreach ($arr as $val) {
list($name, $value) = split("=", $val);
$rtn .= "<input type=\"hidden\" name=\"{$name}\" value=\"{$value}\" />";
}
return $rtn;
}
//--------------------------------------------------
/**
* リダイレクト(呼び出され次第リダイレクト)
*
* @access public
* @param string $url
* @return void
*/
function refresh($url)
{
header("HTTP/1.1 301 Moved Permanently");
header("Location: ". $url);
exit;
}
//--------------------------------------------------
/**
* 配列をinputタグへ変更
*
* @access public
* @param array $arr
* @return string $rtn
*/
function array_to_inputtag($arr)
{
foreach ($arr as $name => $value) {
$rtn .= "<input type=\"hidden\" name=\"{$name}\" value=\"{$value}\" />";
}
return $rtn;
}
//--------------------------------------------------------------
/**
* ファイルを追加書き込み
*
* @access public
* @param string $filename ファイル名
* @param string $value 書込データ
* @return void
*/
function set_file_add($filename, $value)
{
//書き込みモードでファイルを開く
if (!$handle = fopen($filename, 'a')) {
return;
}
if (fwrite($handle, $value."\r\n") === FALSE) {
return;
}
fclose($handle);
}
//--------------------------------------------------------------
/**
* kizasiトップワード取得(30ワード取得)
*
* @access public
* @param string $code 変換後の文字コード
* @return array $arr 取得データ {title=>, description=>}
*/
function get_kizasi_word($code = "")
{
if (!$code) {
$code = "shift-jis"; // 取得するデータの文字コード
}
$kizasi_code = "UTF-8"; // kizasiの文字コード
$html = $this->gethtml("http://kizasi.jp/rss.xml");
$xml = new SimpleXMLElement($html);
/* channel/item/ を探します */
$result = $xml->xpath('channel/item');
$arr = array();
foreach ($result as $value) {
if ($kizasi_code != $code) {
$value = $this->mb_convert_encoding_arr($value, $code, $kizasi_code);
}
$value['description'] = $this->text_to_del_tag($value['description'], "a"); // descriptionにAタグが入っているので削除
array_push($arr, $value);
}
return $arr;
}
//--------------------------------------------------------------
/**
* ヤフー急上昇ワード
*
* @access public
* @param string $code 変換後の文字コード
* @return $arr {title=>, description=>}
* @link http://searchranking.yahoo.co.jp/burst_ranking
*/
function get_yahoo_word($code = "")
{
if (!$code) {
$code = "shift-jis"; // 取得するデータの文字コード
}
$front_code = "UTF-8"; // 変換前の文字コード
$html = $this->gethtml("http://searchranking.yahoo.co.jp/rss/burst_ranking-rss.xml");
$xml = new SimpleXMLElement($html);
/* channel/item を探します */
$result = $xml->xpath('channel/item');
$arr = array();
foreach ($result as $value) {
if ($front_code != $code) {
$value = $this->mb_convert_encoding_arr($value, $code, $front_code);
}
array_push($arr, $value);
}
return $arr;
}
//--------------------------------------------------------------
/**
* google急上昇ワード(20ワード取得)
*
* @access public
* @param string $code 変換後の文字コード
* @return $arr {title=>, description=>}
*/
function get_google_word($code = "")
{
if (!$code) {
$code = "shift-jis"; // 取得するデータの文字コード
}
$front_code = "UTF-8"; // 変換前の文字コード
$html = $this->gethtml("http://www.google.com/m/services/trends/get");
$xml = new SimpleXMLElement($html);
/* item を探します */
$result = $xml->xpath('item');
// [query] => ***,[rank] => 4,[prev_rank] => 7,[score] => 106.03,[snippet] => ***,
$arr = array();
foreach ($result as $value) {
if ($front_code != $code) {
$value = $this->mb_convert_encoding_arr($value, $code, $front_code);
}
// 他のワードとの互換のため
$temp['title'] = $value['query'];
$temp['description'] = $value['snippet'];
array_push($arr, $temp);
}
return $arr;
}
//--------------------------------------------------------------
/**
* 配列データの文字コードを一括変換
*
* @access public
* @param $arr 変換前データ
* @param $code 変換後文字コード
* @param $front_code 変換前文字コード
* @return $arr
*/
function mb_convert_encoding_arr($arr, $code, $front_code)
{
$rtn = array();
foreach ($arr as $key => $value) {
$rtn[$key] = mb_convert_encoding($value, $code, $front_code);
}
return $rtn;
}
//--------------------------------------------------------------
/**
* 文字列を省略する
*
* @access public
* @param $str 文字列
* @param $num 省略幅
* @param $code option 文字コード
* @return $rtn
*/
function str_ryaku($str, $num, $code = "")
{
if ($code == "") { $code = "shift-jis"; }
$rtn = mb_strimwidth($str, 0, $num, "...", $code);
return $rtn;
}
//--------------------------------------------------
/**
* データにurlを含むとき1
*
* @access public
* @param string $data データ
* @return int $rtn 0:含まない, 1:含む
*/
function chk_url_data($data)
{
if (preg_match("/tp:\/\//", $data)) {
$rtn = 1;
}
return $rtn;
}
//--------------------------------------------------
/**
* 正規化したURLを取得
*
* @access public
* @param string $url 正規化前URL
* @return string $url 正規化後URL
*/
function get_preg_url($url)
{
$addr = "[-_.!~*'()a-zA-Z0-9;\/\?:@&=+$,%#]+";
preg_match("/({$addr})/", $url, $matches);
$url = $matches[1];
$url = preg_replace("/^(http|ttp|tp|p):\/\//", "", $url);
$url = "http://{$url}";
return $url;
}
//--------------------------------------------------
/**
* ファイルからtab区切りのデータ取得
*
* @access public
* @param string $filename ファイル名
* @return array $rtn 配列データ
*/
function get_file_tab($filename)
{
$data = $this->get_file_data($filename);
$arr = preg_split("/(\t|\r\n|\r|\n)/", $data);
foreach ($arr as $value) {
if ($value) {
preg_match("/^([\w\d]*)=/", $value, $matches);
$key = $matches[1];
$item = str_replace("{$key}=", "", $value);
$rtn[$key] = $item;
}
}
return $rtn;
}
//--------------------------------------------------
/**
* ファイルへtab区切りのデータを設定
*
* @access public
* @param string $filename ファイル名
* @param array $data 配列データ
* @return void
*/
function set_file_tab($filename, $data)
{
$str = "";
if ($data) {
foreach ($data as $key => $value) {
$str .= "{$key}={$value}\t";
}
}
$this->set_file_data($filename, $str);
}
//--------------------------------------------------
/**
* スパムデータ判定
*
* @access public
* @param string $str 判定元データ
* @return int $rtn 0:無し, 1:有り
*/
function chk_spam_data($str)
{
if (preg_match("/^([\w\d\s-_.!~*'();\/\?:@&=+$,%#<>\"]*)$/", $str)) {
$rtn = 1;
}
return $rtn;
}
//--------------------------------------------------
/**
* googleページランク取得(未使用)
*
* @param string $url URL
* @param string $code 変換後の文字コード
* @return int $rtn ページランク
*/
function get_page_rank_bk($url, $code = "")
{
if (!$code) {
$code = "shift-jis"; // 取得するデータの文字コード
}
$front_code = "UTF-8"; // 変換前の文字コード
$url = urlencode($url);
$html = $this->gethtml("http://www.trynt.com/google-pagerank-api/v1/?u={$url}");
$xml = new SimpleXMLElement($html);
/* Pagerank を探します */
$result = $xml->xpath('Pagerank');
$rtn = $result[0];
$rtn = mb_convert_encoding($rtn, $code, $front_code);
return $rtn;
}
//--------------------------------------------------
/**
* googlePageRank配列取得
*
* @access public
* @param array $url URL
* @param string $code 文字コード
* @return array $rtn[]{url, pagerank} ページランクデータ
* @link http://www.gssm.musashi.ac.jp/~ono/grank/index.html
*/
function get_page_rank_arr($url, $code = "")
{
if ($url) {
if (is_array($url)) {
foreach ($url as $value) {
$url_temp .= $value."\n";
}
$url = $url_temp;
}
$url = urlencode($url);
$target = "http://www.gssm.musashi.ac.jp/~ono/grank/cgi-bin/google_pagerank.cgi?url={$url}";
$html = $this->gethtml($target);
$start = strpos($html, "<table");
$len = strpos($html, "</table>") - $start;
$html = substr($html, $start, $len);
$html = preg_replace("/<tr>/", "\n", $html); // 改行追加
$html = $this->text_to_del_tag($html); // タグ削除
$arr = preg_split("/\n/", $html);
$rtn = array();
foreach ($arr as $value) {
list($temp['pagerank'], $temp['url']) = split(" ", $value);
// URLがある
if ($temp['url']) {
// ページランクが空のときは0を入れる
if (!$temp['pagerank']) {$temp['pagerank'] = 0;}
// ページランクが数字のとき
if (is_numeric($temp['pagerank'])) {
array_push($rtn, $temp); // 配列へ格納
}
}
}
}
return $rtn;
}
//--------------------------------------------------
/**
* google検索結果取得
*
* @access public
* @param string $word 取得ワード
* @param int $page option 取得ページ数
* @return array $result[]{url, title} 検索結果
*/
function get_google_search_result($word, $page = "")
{
$word = urlencode($word);
if ($page >= 1) {
$start = ($page-1) * 10;
$plus = "&start={$start}&";
}
$url = "http://www.google.co.jp/search?hl=ja&q={$word}&lr=$plus";
$html = $this->gethtml($url);
$html = substr($html, strpos($html, "<h2 class=hd>検索結果"));
$html = preg_replace("/<[\/]?em>/", "", $html);
$html = preg_replace("/<[\/]?b>/", "", $html);
$html = str_replace("class=l", "", $html);
$html = preg_replace("/onmousedown=\"return clk\(this.href,,,'res','[\d]*',\)\"/", "", $html);
$atag = $this->text_to_tag_a($html);
$result = array();
foreach ($atag[0] as $key => $value) {
$result[$key]['url'] = $atag[1][$key];
$result[$key]['title'] = $atag[2][$key];
}
// ヘッダのイメージ検索リンクを削除
if (preg_match("/^http:\/\/images.google.co.jp\/images?/", $result[0]['url'])) {
array_shift($result); // 前除く
}
// フッターの関連リンクを削除
if (count($result) > 10) {
while(count($result) > 10) {
array_pop($result); // 後除く
}
}
return $result;
}
//--------------------------------------------------
/**
* ある文字列に挟まれた文字列を取得
*
* @access public
* @param string $str 対象文字列
* @param string $start 最初の検索文字列
* @param string $end 最後の検索文字列
* @return string $mid 取得文字列
*/
function get_mid_str($str, $start, $end)
{
$s = strpos($str, $start) + strlen($start);
$str = substr($str, $s);
$e = strpos($str, $end);
$mid = substr($str, 0, $e);
return $mid;
}
//--------------------------------------------------
/**
* ある文字列に挟まれた文字列を削除して返す
*
* @access public
* @param string $str 対象文字列
* @param string $start 最初の検索文字列
* @param string $end 最後の検索文字列
* @return string $rtn 取得文字列
*/
function del_mid_str($str, $start, $end)
{
$s = strpos($str, $start);
$str1 = substr($str, 0, $s);
$s = strpos($str, $start) + strlen($start);
$str2 = substr($str, $s);
$e = strpos($str2, $end) + strlen($end);
$str2 = substr($str2, $e);
$rtn = $str1.$str2;
return $rtn;
}
//--------------------------------------------------
/**
* 指定した文字列の間の文字列を取得
*
* @access public
* @param string $str 対象文字列
* @param string $point 後文字(*)後文字
* @return string $str 取得文字列
*/
function get_mid_str_kakko($str, $point)
{
list($start, $end) = split("\(\*\)", $point);
$str = $this->get_mid_str($str, $start, $end); // ある文字列に挟まれた文字列を取得
return $str;
}
//--------------------------------------------------
/**
* 指定した文字列の間の文字列を排除して取得
*
* @access public
* @param string $str 対象文字列
* @param string $point 後文字(*)後文字
* @return string $str 取得文字列
*/
function del_mid_str_kakko($str, $point)
{
list($start, $end) = split("\(\*\)", $point);
$str = $this->del_mid_str($str, $start, $end); // ある文字列に挟まれた文字列を排除
return $str;
}
//--------------------------------------------------
/**
* URLのパラメータ文字列を配列に変換
*
* @access public
* @param string $URL 文字列
* @return array $hash パラメータのハッシュデータ
*/
function url_to_param_arr($url)
{
$hash = array();
if ($url) {
list($path, $params) = split("\?", $url);
if ($params) {
$arr = split("&", $params);
if ($arr) {
foreach ($arr as $value) {
list($name, $data) = split("=", $value);
$hash[$name] = $data;
}
}
}
}
return $hash;
}
//--------------------------------------------------
/**
* URLからドメイン名を取得する
*
* @access public
* @param string $url URL
* @return string $domain ドメイン名
* @ex http://www.google.com → google.com
*/
function url_to_domain($url)
{
$url = str_replace("http://", "", $url);
$arr = split("\/", $url);
$arr2 = split("\.", $arr[0]);
foreach ($arr2 as $key => $value) {
if ($key != 0) {
$domain .= $value.".";
}
}
$domain = substr($domain, 0, -1); // 最後の.を削除
return $domain;
}
//--------------------------------------------------
/**
* ファイルに記載されているUnixtimeと現在の日時を比較
* ~秒経過してれば、1を返す
*
* @access public
* @param string $file ファイル名
* @param int $sec 経過時間
* @return int $rtn 1:経過, 0:経過せず
*/
function chk_file_time($file, $sec)
{
if (file_exists($file)) {
$filedate = $this->get_file_data($file); // 更新日付取得
}
$rtn = 0;
if (time() >= $filedate +$sec) { // x秒以内に更新が無かった時
$this->set_file_data($file, time()); // 保存
$rtn = 1;
}
return $rtn;
}
//--------------------------------------------------
/**
* ロボットクローラ対策で静的ページを偽装
*
* @access public
* @return void
*/
function set_last_modified()
{
$time = time() - time() % (60 * 60);
header( "Last-Modified: " . gmdate( "D, d M Y H:i:s", $time ) . " GMT" );
}
//--------------------------------------------------
/**
* 検索エンジンから来た時の検索ワードを取得
*
* @param string $encode 変換したい文字コード
* @retrun array $rtn {word=>ワード, engine=>検索エンジン名}
* @link http://edu.nuts-choco.com/blog/archives/d9372c29dfeb509f1bafbbe1521283dffa374bd2.php
*/
function get_engine_word($encode = "SJIS")
{
$url = $_SERVER["HTTP_REFERER"];
/*
$url = "http://search.yahoo.co.jp/search?p=%E3%83%A4%E3%83%95%E3%83%BC&ei=UTF-8&fr=top_ga1&x=wrt"; // ヤフー
$url = "http://www.google.co.jp/search?hl=ja&q=%E3%82%B0%E3%83%BC%E3%82%B0%E3%83%AB&btnG=%E6%A4%9C%E7%B4%A2&lr="; // グーグル
$url = "http://kotochu.fresheye.com/search/?kw=%E3%82%B3%E3%83%88%E3%83%90%E3%82%A6%E3%83%81%E3%83%A5%E3%82%A6&cs=utf8&x=18&y=5"; // fresheye コトバウチュウ
$url = "http://search.goo.ne.jp/web.jsp?SGT=0&from=query&MT=%A5%B0%A1%BC&DC=10"; // goo グー
$url = "http://search.nifty.com/websearch/search?cflg=%E6%A4%9C%E7%B4%A2&select=2&q=%E3%83%8B%E3%83%95%E3%83%86%E3%82%A3&ck=&ss=up"; // nifty ニフティ
$url = "http://search.livedoor.com/search/?c=ld_top_sb_2&q=%A5%E9%A5%A4%A5%D6%A5%C9%A5%A2&lr=lang_ja"; // livedoor ライブドア
$url = "http://www.excite.co.jp/search.gw?search=%83G%83L%83T%83C%83g&target=combined&look=excite_jp&Language="; // excite エキサイト ??
$url = "http://search.www.infoseek.co.jp/Web?col=OW&qt=%E3%82%A4%E3%83%B3%E3%83%95%E3%82%A9&wd=0&svx=101102"; // infoseek インフォ
*/
if ($url) {
if (preg_match("/^http:\/\/(www)?\.?google.*/i", $url)) { // Google
$word = preg_replace("/^.*[\?&]q=([^&]+)&?.*$/i", "$1", $url);
$engine = "google";
} elseif (preg_match("/^http:\/\/search\.yahoo.*/i", $url)) { // Yahoo
$word = preg_replace("/^.*[\?&]p=([^&]+)&?.*$/i", "$1", $url);
$engine = "yahoo";
} elseif (preg_match("/^http:\/\/search\.msn.*/i", $url)) { // MSN
$word = preg_replace("/^.*[\?&]q=([^&]+)&?.*$/i", "$1", $url);
$engine = "msn";
} elseif (preg_match("/^http:\/\/search\.www\.infoseek.*/i", $url)) { // infoseek auto
$word = preg_replace("/^.*[\?&]qt=([^&]+)&?.*$/i", "$1", $url);
$engine = "infoseek";
} elseif (preg_match("/^http:\/\/(www|sleipnir)\.excite.*/i", $url)) { // excite
$word = preg_replace("/^.*[\?&]search=([^&]+)&?.*$/i", "$1", $url);
$engine = "excite";
} elseif (preg_match("/^http:\/\/search\.livedoor.*/i", $url)) { // livedoor euc-jp
$word = preg_replace("/^.*[\?&]q=([^&]+)&?.*$/i", "$1", $url);
$engine = "livedoor";
} elseif (preg_match("/^http:\/\/(search|so-net\.mobile)\.goo.*/i", $url)) { // goo
$word = preg_replace("/^.*[\?&]MT=([^&]+)&?.*$/i", "$1", $url);
$engine = "goo";
} elseif (preg_match("/^http:\/\/search\.nifty.*/i", $url)) { // nifty
$word = preg_replace("/^.*[\?&]q=([^&]+)&?.*$/i", "$1", $url);
$engine = "nifty";
} elseif (preg_match("/^http:\/\/search\.lycos.*/i", $url)) { // Lycos
$word = preg_replace("/^.*[\?&]query=([^&]+)&?.*$/i", "$1", $url);
$engine = "lycos";
} elseif (preg_match("/^http:\/\/(search|kotochu)\.fresheye.*/i", $url)) { // fresheye
$word = preg_replace("/^.*[\?&]kw=([^&]+)&?.*$/i", "$1", $url);
$engine = "fresheye";
} elseif (preg_match("/^http:\/\/(www\.)?alltheweb.*/i", $url)) { // AllTheWeb
$word = preg_replace("/^.*[\?&]q=([^&]+)&?.*$/i", "$1", $url);
$engine = "alltheweb";
}
$word = urldecode($word);
// 検索ワードの元々の文字コード
if (preg_match("/euc/", $url)) {$from = "euc-jp";}
elseif (preg_match("/utf-8/i", $url)) {$from = "utf-8";}
else {$from = "auto";}
$word = mb_convert_encoding($word, $encode, $from);
$rtn['word'] = $word;
$rtn['engine'] = $engine;
}
return $rtn;
}
//--------------------------------------------------
/**
* ロボット判定
*
* @access public
* @return int $rtn 1 or 0
*/
function is_robot()
{
$remote = gethostbyaddr($_SERVER['HTTP_X_FORWARDED_FOR']);
if (!$remote) {
$remote = gethostbyaddr($_SERVER['REMOTE_ADDR']);
}
// $remote = "{$_SERVER['HTTP_VIA']},{$_SERVER['HTTP_FORWARDED']},{$_SERVER['HTTP_X_FORWARDED_FOR']}";
if (preg_match("/.search.msn.com$|.googlebot.com$|.amazon.com$|^125.100.100.105$|.search.ogk.yahoo.co.jp$|.compute-1.amazonaws.com$/", $remote)) {
// ロボット
$rtn = 1;
}
return $rtn;
}
//--------------------------------------------------
/**
* リモートホスト取得
* プロキシごしでもOK
*
* @access public
* @return string $remote ホスト名
*/
function get_remote_host()
{
$remote = gethostbyaddr($_SERVER['HTTP_X_FORWARDED_FOR']);
if (!$remote || !preg_match("/^[\d\.]+$/", $remote)) {
$remote = gethostbyaddr($_SERVER['REMOTE_ADDR']);
}
return $remote;
}
//--------------------------------------------------
/**
* dir内のファイル名一覧を取得(サブフォルダも含む)
* 再起処理
*
* @access public
* @param string $path フィルダ・ファイルパス
* @return array $rtn フォルダ内のファイル名を指定した$pathからのパスで取得
*
*/
function get_dir_file_sub($path)
{
$rtn = array();
if (filetype($path) == "file") {
array_push($rtn, $path);
} elseif (filetype($path) == "dir") {
$handle = openDir($path);
while (false !== $name = readDir($handle)) {
if ($name != "." && $name != "..") {
$rtn = array_merge($rtn, $this->get_dir_file_sub($path."/".$name));
}
}
}
return $rtn;
}
//--------------------------------------------------
/**
* ログセット
* 時間+ログ
*
* @access public
* @param string $filename ファイル名
* @param string $value ログ
* @return void
*/
function set_log($filename, $value)
{
$value = date("Y/m/d H:i:s", time()) ." ". $value;
$this->set_file_add($filename, $value);
}
//--------------------------------------------------
/**
* ディレクトリロック
*
* @access public
* @param string $name ロックdir名
* @return boolean 0, 1
*/
function lock_dir($name = "")
{
if ($name == "") $name = "lock";//"lock/lock.lck"
// 10分以上前のディレクトリなら解除失敗とみなして削除
if ((file_exists($name)) && filemtime($name) < time() - 600) {
rmdir($name);
}
do {
if (mkdir($name, 0777)) {
return 1;
}
sleep(1); // 一秒待って再トライ
$i++;
} while ($i < 5);
return 0;
}
//--------------------------------------------------
/**
* ロック解除
*
* @access public
* @param string $name ロックdir名
*/
function unlock_dir($name = "")
{
if ($name == "") $name = "lock";
rmdir($name);
}
//--------------------------------------------------
// ヤフーカテゴリデータ取得
function get_yahoo_cate_data($target)
{
$text = $this->gethtml($target);
$text = $this->get_mid_str($text, 'sitesorted">', '/.sitesorted');
$text = mb_convert_encoding($text, "sjis", "euc-jp");
$a_arr = $this->text_to_tag_a($text);
$items = array();
foreach ($a_arr[1] as $key => $a) {
if (!preg_match("!http://picks\.dir\.yahoo\.co\.jp!", $a)) {
unset($item);
$item['url'] = $a_arr[1][$key];
$item['title'] = $a_arr[2][$key];
}
array_push($items, $item);
}
return $items;
}
//--------------------------------------------------
/**
* csvファイル読み込み
*
* @param string $file ファイル名
* @return array $rec csvデータ
*/
function get_file_csv($file)
{
//fgetcsvだと適切に区切られない
/*
$handle = fopen($file, "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$rec[] = $data;
}
fclose($handle);
*/
$arr = $this->get_file_array($file);
foreach ($arr as $key => $line) {
$value = explode(",", $line);
$rec[$key] = $value;
}
return $rec;
}
//--------------------------------------------------
// htmlspecialcharsの逆(php4非サポート)
function htmlspecialchars_decode($str)
{
$str = str_replace("&", "&", $str);
$str = str_replace(">", ">", $str);
$str = str_replace("<", "<", $str);
return $str;
}
//--------------------------------------------------
// サイトマップ出力
function set_sitemap_file($file, $urls)
{
$out = "";
foreach ($urls as $url) {
$url = htmlentities($url); // エスケープ
$out .=<<<EOD
<url>
<loc>{$url}</loc>
<changefreq>weekly</changefreq>
<priority>0.5</priority>
</url>
EOD;
}
$out =<<<EOD
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
{$out}</urlset>
EOD;
$this->set_file_data($file, $out);
}
//--------------------------------------------------
/**
* ディレクトリ存在チェック
*
* @param string $path
* @return int 0 or 1
*/
function isDir($path)
{
if (is_dir($path)) {
return 1;
}
return 0;
}
//--------------------------------------------------
/**
* ディレクトリが無ければ作成
*
* @param string $path
*/
function makeDir($path)
{
$tmp = explode("/", $path);
foreach ($tmp as $key => $name) {
$make .= $name;
if (!is_dir($make) && $make && count($tmp) - 2 >= $key) {
mkdir($make);
}
$make .= "/";
}
}
//--------------------------------------------------
}
//--------------------------------------------------
?>
