リンクに activeとかcurrentとかを簡単につける関数

静的サイトの構築などで地味ですが有ると便利な関数です。

<a <?php print_href('/permalink/');?>>

とすると、/permalink/にアクセスしているときに

<a href="/permalink/" class="current">

となります。地味ですが・・・・・

<?php
$url = $_SERVER["REQUEST_URI"];
$url = str_replace('/index.php', '', $url);

function print_href($href){
	global $url;
	echo 'href="'.$href.'"';

	//home用の処理
	if($href == "/"){
		if($url == $href or !$url ){
			echo ' class="current"';
		}
		return;
	}

	if(strstr($url.'/',$href)){
		echo ' class="current"';
	}
}
?>
リンクに activeとかcurrentとかを簡単につける関数Toro_Unit

Topsyから特定のURLに関するつぶやきをWordPressっぽく取得できるClassを書いてみた。

このサイトのリニューアルこの間リニューアルしたときに作りました。晒そうと思ってすっかり忘れてました。このブログの個別記事の下の方のTwitterタイムラインがそれです。
Topsyで特定のURLに関するつぶやきや、そのユーザーなどを取得します。

functions.phpにでも貼っておくと良いと思います。いちおうPHP5用。PHP4系で使いたい場合は__cunstructをGet_Topsy_Trackbackに変えてあげて下さい。

コード

class Get_Topsy_Trackback {
	private $counter = 0;
	public $response;
	public $trackback;

	function __construct($permalink){
		$topsy = json_decode(file_get_contents("http://otter.topsy.com/trackbacks.json?url=".$permalink));
		$this->response = $topsy->response;
	}

	function get_all_topsy(){
		return count($this->response->list);
	}

	function have_topsy(){
		if(isset($this->response->list[$this->counter])){
			return true;
		}else{
			return false;
		}
	}

	function the_topsy(){
		$this->trackback = $this->response->list[$this->counter];
		$this->counter ++;
	}

	function get_topsy(){
		return $this->trackback;
	}

	function get_the_content(){
		$content = $this->trackback->content;
		return preg_replace('/(https?:\/\/[a-zA-Z0-9\.\/:%,!#~*@&_-]+)/','<a href="\0" title="\0">\0</a>',$content);
	}
	function the_content(){
		echo "<p>".$this->get_the_content()."</p>";
	}

	function get_the_author(){
		return $this->trackback->author;
	}

	function get_the_author_nick(){
		return $this->get_the_author()->nick;
	}
	function the_author_nick(){
		echo $this->get_the_author_nick();
	}

	function get_the_author_link(){
		return $this->get_the_author()->url;
	}
	function the_author_link(){
		echo $this->get_the_author_link();
	}

	function the_author(){
		echo '<a href="'.$this->get_the_author_link().'" class="author">'.$this->get_the_author_nick().'</a>';
	}

	function get_the_author_avator(){
		return $this->get_the_author()->photo_url;
	}
	function the_author_avator( $size = 48 ){
		echo '<img src="'.$this->get_the_author_avator().'" alt="'.$this->get_the_author_nick().'" width="'.$size.'" height="'.$size.'" />';
	}

	function get_the_time( $format = "Y-m-d" ){
		return date($format,$this->trackback->date);
	}
	function the_time( $format = "Y-m-d" ){
		echo $this->get_the_time( $format );
	}

	function get_the_permalink(){
		return $this->trackback->permalink_url;
	}
	function the_permalink(){
		echo $this->get_the_permalink();
	}
}

基本的にgetから始まるメソッドはreturnで返し、theから始まるメソッドはechoします。実にWordPressっぽいですよね?

使い方

こんな感じで使います。

<?php
$topsy = new Get_Topsy_Trackback($URL);
if($topsy->have_topsy()):?>
<p><?php echo $topsy->get_all_topsy();?>回つぶやかれました。</p>
<ul>
<?php while($topsy->have_topsy()):$topsy->the_topsy(); ?>
	<li>
		<a href="<?php $topsy->the_author_link();?>"><?php $topsy->the_author_avator()?></a>
		<div class="content"><?php $topsy->the_author();?><?php $topsy->the_content();?></div>
		<div class="meta">Post:<a href="<?php $topsy->the_permalink();?>"><?php $topsy->the_time("Y-m-d");?></a></div>
	</li>
<?php endwhile; ?>
</ul>
<?php else:?>
<p>まだだれもつぶやいていない様子です。</p>
<?php endif;?>

インスタンス化するときに、URLを引数に入れてあげましょう。WordPressで使うのならばget_permalink(get_the_ID())とかですね。
あとはWordPressっぽいループタグを書いて、WordPressっぽいテンプレートタグを書いてあげればオーケーです。

需要があるかどうか解らないけれど結構便利だと思うので、Topsy使ってみたいけど・・・って人は使ってみて下さい!

Topsyから特定のURLに関するつぶやきをWordPressっぽく取得できるClassを書いてみた。Toro_Unit

hetemlでCakePHPをインストールするときは、PHP5.3で動かすべし。

hetemlでcakePHPを使おうと思って色々一日試行錯誤していたのですが、ちゃんとインストールできていると、

http://example.org/cake_dir/

が、

という画面になるらしいんですが、CSSの効いていない画面で、“Missing Controller”

また、アプリケーション自体にはアクセスできるのですが、アプリケーションのアクションにはアクセスできない。つまり、

http://example.org/cake_dir/appname/にはアクセスできるけど、http://example.org/cake_dir/appname/actionnameや、http://example.org/cake_dir/appname/indexにはアクセスできないといった症状が見られた場合、PHP5.3で動作させるようにすると解決するようです。

PHP5.3で動作させるには、動作させたい、ディレクトリのか、その親の階層の.htaccessに、

AddHandler php5.3-script .php

に記述すれば動作します。

あんまり日本語の情報が無いようですが、頑張っていきたいです。

hetemlでCakePHPをインストールするときは、PHP5.3で動かすべし。Toro_Unit

jQuery.uploadを使った、画像のサムネイルを表示するフォームのデモを作りました。

以前、jQuery.uploadでアップロード画像のサムネイルの作成というエントリーを書いたので、それの実装を作ってみました。アップロードする画像を選択すると、アップロードされ、それのサムネイルが表示されます。

また、ページを離れるときに画像をJavascriptで削除していますが、実際に使うときは使わない場面も多いと思いますので、その部分は適当に削除するなり、なんなりして下さい。

デモ:http://demo.torounit.com/jquery.upload/

script.js(ajaxでのアップロード等々)

jQuery(function($){
	//送信ボタンの非表示
	$('#submit').hide();

	//フォームの内容が変更されたとき
	$('#img').change(function() {
	    var preview = $('#preview');

	    //現在表示されているものを消す。
	    preview.find("img").fadeOut(300);

	    //アップロード
	    $(this).upload(
			'upload.php',
			$("form").serialize(),
			function(html){
			//サムネイルの表示
	        	preview.html(html).animate({"height":preview.find("img").height()+"px"},300,function(){
	            	preview.find("img").hide().fadeIn(300);
	        	});
	    	},'html');
	});

	//離れるときに画像を削除
	$(window).bind("beforeunload",function(){
		var unlinkFile = $("#postPhotoName").val();
		$.ajax({
			async: false,
			cache: false,
			type:	"POST",
			url:	"upload.php",
			data:	"postPhotoName="+unlinkFile

		});

	});

});

upload.php(アップロードしたファイルを加工するスクリプト)

<?php

//前にアップロードされた写真のファイル名
$postPhotoName = $_POST["postPhotoName"];

//古いファイルの削除
if($postPhotoName){

	unlink("./img/".$postPhotoName);
	unlink("./img/thumb-".$postPhotoName);
}

$result = false;

if($_FILES['img']['name'] == "") {
	die("ファイルがないぜよ。");

}else{
	//アップロードされたファイルの情報を取得
	$fileName = basename(date("U")."-".$_FILES['img']['name']);
	$fileType = $_FILES['img']['type'];
	$fileTmpName = $_FILES['img']['tmp_name'];

	if(!preg_match("/jpeg/",$fileType)){

		unlink($fileTmpName);
		die( "jpegじゃないぜよ。");

	}else{
		//ファイルの保存
		if (!move_uploaded_file($fileTmpName, './img/' . $fileName)) {

			die('保存にしっぱいしたぜよ。');

		} else {

			//サムネイル作成
			include('class.image.php');
			list($width, $height, $type, $attr) = getimagesize('img/'.$fileName);

			$thumb = new Image('img/'.$fileName);
			$thumb->name('thumb-'.basename($fileName,".jpg"));

			if($width>$height){
				if($width > 500) $thumb->width(500);
			}else{
				if($height > 500) $thumb->height(500);
			}

			$thumb->save();
			$result = true;
		}

	}

}

if($result == true){
?>

<img src="<?php echo './img/thumb-'.$fileName;?>">
<input type="hidden" value="<?php echo $fileName?>" name="postPhotoName" id="postPhotoName">
<?php
}

HTML

<form method="post" enctype="multipart/form-data" action="upload.php">
<input type="file" value="" id="img" name="img" size="50" />
<input type="submit" id="submit" />
<div id="preview"><div>ここにプレビューが表示されます</div></div>
</form>

このままつかうのはちょっとあれかもですけど、アイデア次第で色々使い道がありそうです。

jQuery.uploadを使った、画像のサムネイルを表示するフォームのデモを作りました。Toro_Unit

PEARのCache_Liteを使ってみた

軽量キャッシュライブラリのCache_Liteの使い方です。


//ライブラリの読み込み
include_once('Cache/Lite.php');

//設定
define("CACHE_DIR","./tmp/");
define("CACHE_TIME",300);//5分

//キャッシュのID
$id = 'hoge';
$options = array(
	'cacheDir' => CACHE_DIR,
	'lifeTime' => CACHE_TIME
);

//インスタンス化
$Cache_Lite = new Cache_Lite($options);

if ($data = $Cache_Lite->get($id)) {
	//キャッシュが有効なときの処理
	//$dataに取得すべきデータが格納されている。

} else {
	//キャッシュが無効、存在しないとき
	$url = "http://search.twitter.com/search.json?q=" . urlencode("ぬこ") . "&rpp=100&lang=ja";
	$ch = curl_init($url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	$search = curl_exec($ch);
	curl_close($ch);

	$Cache_Lite->save($search,$id);//キャッシュを保存
	}
}

キャッシュを手動で消すには、キャッシュの保存されているディレクトリ、(この場合./tmp/)の中身を消すだけで大丈夫です。
TwitterAPIとか回数制限も多いので、使いどころはたくさんあると思います。

PEARのCache_Liteを使ってみたToro_Unit