<?
	//
	// Content Manager code
	// 
	
	require_once("site.phtml");
	
	$cm_use_cache = true;
	
	function _cm_is_() {
		if ( !empty($_GET["cm_from_"]) ||
			 (!empty($_COOKIE["cm_from_"]) &&
			  $_COOKIE["cm_from_"] == "yes") ) {
			return 1;
		} else
			return 0;
	}
	
	if ($cm_use_cache) {
		$cm_block_cache = xall_rows_as_array("
			select *
			  from m_cm_blocks
			 where block_is_active = 1
			   and block_name <> ''", "block_name");
		$cm_text_cache = xall_rows_as_array("
			select *
			  from m_cm_text
			 where block_key <> ''
			   and is_current = 1", "block_key");
	}
	
	function _cm_get_block($block_name) {
		global $PHP_SELF;
		global $cm_text_cache;
		global $cm_use_cache;
		global $cm_block_cache;
		
		if ($cm_use_cache && !empty($cm_block_cache[$block_name])) {
			$block = $cm_block_cache[$block_name];
		} else {
			$block = xone_row("
				select * 
				  from m_cm_blocks b
				 where b.block_is_active = 1
				   and b.block_name = '$block_name'");
			if (!$block) {
				$url = "/cm_block_new.phtml?page=".urlencode($PHP_SELF)."&block=".urlencode($block_name);
				if (_cm_is_()) {
					return "BLOCK RECORD <strong>$block_name</strong> NOT FOUND; <a class=\"cm-edit-link\" target=\"_top\" href=\"$url\"><img src=\"cm.gif\" border=\"0\"></a>";
				} else {
					return "BLOCK RECORD <strong>$block_name</strong> NOT FOUND";
				}
			}
		}
		
		$block_key = $block["block_key"];
		
		if (isset($_GET["cm_block_${block_key}_rev"])) {
			$rev = $_GET["cm_block_${block_key}_rev"];
    		$text = xone_row("
    			select *
    			  from m_cm_text
    			 where block_key = '$block[block_key]'
    			   and revision_key = $rev");
    	} else {
    		if ($cm_use_cache) {
	    		$text = $cm_text_cache[$block["block_key"]];
	    	} else {
		 		$text = xone_row("
    				select *
					 from m_cm_text
    				where block_key = '$block[block_key]'
    			and is_current = 1");
    		}
		}
		
		// XXX Todo: recursive parsing.
		$t = $text["text_value"];
		
		if (_cm_is_()) {
			$url = "/cm_block_edit.phtml?bk=$block[block_key]&page=".urlencode($PHP_SELF)."&block=".urlencode($block_name);
			return "$t <a class=\"cm-edit-link\" target=\"_top\" href=\"$url\"><img src=\"cm.gif\" border=\"0\"></a>";
		} else
			return $t;
	}
	
	function cm_get_block($block_name) {
		return _cm_get_block($block_name);
	}
	
	function cm_show_block($block_name) {
		echo cm_get_block($block_name);
	}
	
	function cm_get_text_preview($text, $len = 80) {
		return substr(strip_tags($text), 0, $len) . "...";
	}
?>
