<?php
require_once ('filters.inc.php');

// Copper PDFへの接続を得る
function pripre_get_copper() {
    require_once ('CTI/DriverManager.php');
    $uri = get_option("pripre_copper_uri");
    if (!$uri) {
        $uri = PRIPRE_COPPER_URI_DEFAULT;
    }
    $user = get_option("pripre_copper_user");
    if (!$user) {
        $user = PRIPRE_COPPER_USER_DEFAULT;
    }
    $password = get_option("pripre_copper_password");
    if (!$password) {
        $password = PRIPRE_COPPER_PASSWORD_DEFAULT;
    }
    return cti_get_session($uri, array('user' => $user, 'password' => $password));
}

function pripre_get_base_dir() {
    $dir = dirname(dirname(__FILE__));
    return $dir;
}

function pripre_get_session_id() {
    global $pripre_session_id;
    if (empty($pripre_session_id)) {
        $pripre_session_id = wp_parse_auth_cookie();
        $pripre_session_id = $pripre_session_id['hmac'];
    }
    return $pripre_session_id;
}

function pripre_get_tmp_dir() {
    $dir = pripre_get_base_dir();
    $id = pripre_get_session_id();
    $tmp = "$dir/data/tmp";
    $dir = "$tmp/$id";
    if (!@mkdir($dir, 0777, true)) {
    	touch($dir);
    }
    
    // １日以上前の一時ディレクトリは消す
    if ($dh = opendir($tmp)) {
    	while (($file = readdir($dh)) !== false) {
    		if (substr($file, 0, 1) !== '.' && filemtime("$tmp/$file") < time() - 3600 * 24) {
    			pripre_rmr("$tmp/$file");
    		}
    	}
    	closedir($dh);
    }
    
    return $dir;
}

function pripre_get_templates() {
    $dir = pripre_get_base_dir();
    $dir = "$dir/templates/book";

    $templates = array();
    $dh1 = opendir($dir);
    while (($id1 = readdir($dh1)) !== FALSE) {
        $file = "$dir/$id1/info.xml";
        if (file_exists($file)) {
            $doc = new DOMDocument();
            if ($doc->load($file)) {
                $xpath = new DOMXPath($doc);
                $templates[$id1] = array(
                	'name' => $xpath->evaluate('string(/info/name/text())'),
                    'styles' => array()
                );
            }
            $dh2 = opendir("$dir/$id1");
            while (($id2 = readdir($dh2)) !== FALSE) {
            	if (substr($id2, 0, 1) == '.') {
            		continue;
            	}
            	$template = pripre_get_template("$id1/$id2");
            	if ($template !== FALSE) {
	            	$templates[$id1]['styles'][] = $template;
            	}
            }
            closedir($dh2);
        }
    }
    closedir($dh1);
    return $templates;
}

function pripre_get_etemplates() {
	$dir = pripre_get_base_dir();
	$dir = "$dir/templates/ebook";

	$templates = array();
	$dh = opendir($dir);
	while (($id = readdir($dh)) !== FALSE) {
		$file = "$dir/$id/info.xml";
		if (file_exists($file)) {
			$doc = new DOMDocument();
			if ($doc->load($file)) {
				$xpath = new DOMXPath($doc);
				$templates[$id] = array(
						'name' => $xpath->evaluate('string(/info/name/text())'),
						'id' => $id
				);
			}
		}
	}
	closedir($dh);
	return $templates;
}

function pripre_get_template($id) {
	$dir = pripre_get_base_dir();
	$dir = "$dir/templates/book";
	$file = "$dir/$id/info.xml";
    if (file_exists($file)) {
    	$doc = new DOMDocument();
	    if ($doc->load($file)) {
	        $xpath = new DOMXPath($doc);
	        return array(
	            'id' => $id,
	            'name' => $xpath->evaluate('string(/info/name/text())'),
	            'page-progression' => $xpath->evaluate('string(/info/page-progression/text())'),
	            'width' => (int)$xpath->evaluate('string(/info/width/text())'),
	            'height' => (int)$xpath->evaluate('string(/info/height/text())'),
	            'site' => $xpath->evaluate('string(/info/site/text())'),
	        );
	     }
    }
    return FALSE;
}

function pripre_rmr($dir) {
	if (is_dir($dir)) {
		$objects = scandir($dir);
		foreach ($objects as $object) {
			if ($object != "." && $object != "..") {
				if (filetype($dir."/".$object) == "dir") pripre_rmr($dir."/".$object); else unlink($dir."/".$object);
			}
		}
		reset($objects);
		rmdir($dir);
	}
}

function pripre_set_bookparam($book_id, $name, $value) {
	global $wpdb;
	$wpdb->query($wpdb->prepare(
			"DELETE FROM {$wpdb->prefix}pripre_book_param
			WHERE book_id=%d AND param_name=%s",
		$book_id, $name));
    $wpdb->insert("{$wpdb->prefix}pripre_book_param",
            array('book_id' => $book_id,
            'param_name' => $name,
            'param_value' => $value),
            array('%d', '%s', '%s'));
}

function pripre_get_bookparam($book_id, $name) {
	global $wpdb;
	return $wpdb->get_var($wpdb->prepare(
			"SELECT param_value FROM {$wpdb->prefix}pripre_book_param
			WHERE book_id=%d AND param_name=%s",
		$book_id, $name));
}

function pripre_set_bookpostparam($book_id, $post_id, $name, $value) {
	global $wpdb;
	$wpdb->query($wpdb->prepare(
			"DELETE FROM {$wpdb->prefix}pripre_book_post_param
			WHERE book_id=%d AND post_id=%d AND param_name=%s",
			$book_id, $post_id, $name));
	$wpdb->insert("{$wpdb->prefix}pripre_book_post_param",
	array('book_id' => $book_id,
			'post_id' => $post_id,
			'param_name' => $name,
			'param_value' => $value),
			array('%d', '%d', '%s', '%s'));
}

function pripre_get_bookpostparam($book_id, $post_id, $name) {
	global $wpdb;
	return $wpdb->get_var($wpdb->prepare(
			"SELECT param_value FROM {$wpdb->prefix}pripre_book_post_param
			WHERE book_id=%d AND post_id=%d AND param_name=%s",
			$book_id, $post_id, $name));
}

function pripre_sort_bookposts($book_id, &$posts) {
	$result = array();
	foreach($posts as $k => $v) {
		$i = pripre_get_bookpostparam($book_id, $posts[$k]['id'], 'order');
		$result[$i] = $v;
	}
	if (count($result) == count($posts)) {
		$posts = $result;
		ksort($posts);
	}
	return $posts;
}

?>
