<?php

	/*
	*	Gekko - Open Source Web Development Framework
	*	------------------------------------------------------------------------
	*	Copyright (C) 2004-2005, J. Carlos Nieto <xiam@users.sourceforge.net>
	*	This program is Free Software.
	*
	*	@package	Gekko
	*	@license	http://www.gnu.org/copyleft/gpl.html GNU/GPL License 2.0
	*	@author		J. Carlos Nieto <xiam@users.sf.net>
	*	@version	CVS: $Id:$
	*	@link		http://gekkoware.sourceforge.net
	*/

	if (!defined("IN-GEKKO")) die("Get a life!");
	function getBlockData($block) {

		if (!isset($_GLOBALS["_cache"]["blockdata.$block"])) {

			$block = explode("/", $block);
			$script = GEKKO_ROOT."modules/{$block[0]}/blocks/{$block[1]}";

			$return = Array();
			if (file_exists($script)) {
				$h = fopen($script, "r");
				$r = fread($h, filesize($script));
				fclose($h);

				preg_match("/<%%>(.*?)<%%>/s", $r, $m);
				$data = trim($m[1]);

				$parser = xml_parser_create();
				if (!xml_parse_into_struct($parser, $data, $xml)) {
					trigger_error("XML: \"".xml_error_string(xml_get_error_code($parser))."\" line: ".xml_get_current_line_number($parser)."", E_USER_ERROR);
				}
				xml_parser_free($parser);

				$info = Array();
				$vars = Array();

				$ib = Array();
				foreach ($xml as $d) {

					//print_r($d);
					switch ($d["level"]) {
						case 1:

						break;
						case 2:
							switch ($d["tag"]) {
								case "INFO":
									switch ($d["type"]) {
										case "open":
											$ib = $d["attributes"]["LANG"];
											$info[$ib] = Array();
										break;
										case "close":
											$ib = null;
										break;
									}
								break;
								case "VARIABLE":
									if ($d["type"] == "complete") {
										$vars[$d["attributes"]["NAME"]] = isset($d["value"]) ? $d["value"] : false;
									}
								break;
							}
						break;
						case 3:
							$info[$ib][strtolower($d["tag"])] = $d["value"];
						break;
					}
				}

				$i = Array();
				while (list($a) = each($info["en"])) {
					// TODO: language
					$i[$a] = isset($info["es"][$a]) ? $info["es"][$a] : $info["en"][$a];
				}

				$return["info"] = $i;
				$return["variables"] = $vars;

				$_GLOBALS["_cache"]["blockdata.$block"] = $return;
			} else {
				trigger_error("Cannot find blockscript!", E_USER_ERROR);
			}
		}

		return $_GLOBALS["_cache"]["blockdata.$block"];
	}
	function deleteBlock($id) {
		slog("blocks: deleted block '$id'", "actions", 1);
		return $GLOBALS["db"]->query ("DELETE FROM ".db_table("block")." WHERE ID='".$id."'", __FILE__, __LINE__, true);
	}
	function blockSetStatus($id, $status) {
		return $GLOBALS["db"]->query ("UPDATE ".db_table("block")." SET Status = '".$status."' WHERE ID='".$id."'", __FILE__, __LINE__, true);
	}
	function bv_serialize($scriptvars) {
		$v = Array();
		if (is_array($scriptvars)) {
			foreach ($scriptvars as $var => $val) {
				$v[$var] = trim($val);
			}
		} else {
			$scriptvars = explode("\n", $scriptvars);
			foreach ($scriptvars as $line) {
				$line = trim($line);
				if (($line) && (preg_match("/^(.*?)\s*?=\s*?(.*?)$/", $line, $m))) {
					$v[$m[1]] = trim($m[2]);
				}
			}
		}
		return serialize($v);
	}
	// checkign script existence
	function blockscript_exists($scriptpath) {
		if (isset($scriptpath) && $scriptpath) {
			$s = explode("/", $scriptpath);
			if (file_exists(GEKKO_ROOT."modules/".$s[0]."/blocks/".$s[1])) {
				return true;
			}
		}
		return false;
	}
	function bv_unserialize($scriptvars) {
		$scriptvars = unserialize($scriptvars);
		$return = "";
		foreach ($scriptvars as $key => $value) {
			$return .= "$key=$value\n";
		}
		return $return;
	}
	function loadBlock($id) {
		$content = "";
		$q = $GLOBALS["db"]->query("SELECT Content,ScriptVars,ScriptPath
		FROM ".db_table("block")." WHERE ID = '$id'", __FILE__, __LINE__, true);
		if ($GLOBALS["db"]->num_rows($q)) {
			$block = $GLOBALS["db"]->fetch_row($q);
			if ($block["ScriptPath"]) {
				$return = loadBlockScript($block);
			}
			if (isset($return)) $content .= $return;
		}
		return $content;
	}
	function loadBlockScript(&$block) {
		$script = $block["ScriptPath"];
		$vars = $block["ScriptVars"];

		$return = "";
		// extracting default variables
		$info = getBlockData($script);
		extract($info["variables"], EXTR_OVERWRITE);
		// extracting (and overwriting) variables from serialized data
		$vars = unserialize($vars);
		if (is_array($vars))
			extract($vars, EXTR_OVERWRITE);
		// loading blockscript
		$script = explode("/", $script);

		// loading block language file (if exists)
		if (file_exists($lang_file = GEKKO_ROOT."modules/{$script[0]}/lang/".$GLOBALS["Lang"]->getLang()."/".substr($script[1], 0, strpos($script[1], ".")).".block.php")) {
			include $lang_file;
		}

		// loading block
		include (GEKKO_ROOT."modules/{$script[0]}/blocks/{$script[1]}");
		// $return variable will be taken as blockscript's output
		return $return;
	}
	function blockCheckAuth($module, $allowed, $auth) {
		$m = "\s*(".(($module != "*") ? $module."|": "")."\*)\s*";
		return (preg_match("/^$m$|^$m,|,$m,|,$m$/", $allowed) && gauth($auth));
	}

	function getBlockPositions() {
		$r = Array();
		$p = explode(",", Conf::getKey("blocks", "block_positions"));
		foreach ($p as $v) {
			$r[$v] = _l("L_POSITION_".$v);
		}
		return $r;
	}
	function getBlockInfo($block, $info = null) {
		return basename($block);
	}
	function getBlockScripts() {
		$modules = ModCore::getModules();
		$scripts = Array("" => _l("L_NO_SCRIPT"));
		foreach ($modules as $module) {
			$blockdir = GEKKO_ROOT."modules/$module/blocks/";
			if (file_exists($blockdir) && is_dir($blockdir)) {
				$dp = opendir($blockdir);
				while (($block = readdir($dp)) !== false) {
					if ($block != "." && $block != "..") {
						$scripts[$module."/".$block] = $module." :: ".getBlockInfo($block, "name");
					}
				}
				closedir($dp);
			}
		}
		return $scripts;
	}
	function createSimpleBlock($title, $content = null, $scriptpath = null, $scriptvars = null, $icon = "blocks.png") {

		if (!blockscript_exists($scriptpath)) $scriptpath = "";

		$scriptvars = $scriptvars ? bv_serialize($scriptvars) : "";

		// appeding to left side
		$GLOBALS["db"]->query ("SELECT OrderID FROM ".db_table("block")."
		WHERE Position = 'L' ORDER BY OrderID DESC LIMIT 1",
		__FILE__, __LINE__);
		$row = $GLOBALS["db"]->fetch_row();
		$orderid = $row["OrderID"]+1;

		// inserting into database
		$GLOBALS["db"]->query ("
		INSERT INTO ".db_table("block")."
			(
				ID,
				Icon,
				Position,
				Status,
				Title,
				Content,
				Modules,
				ScriptPath,
				ScriptVars,
				CreationTime,
				OrderID,
				cssText,
				blockClass,
				auth_Access
			)
				VALUES
			(
				'".($return = $GLOBALS["db"]->free_id("block"))."',
				'$icon',
				'L',
				'1',
				'$title',
				'$content',
				'*',
				'$scriptpath',
				'$scriptvars',
				'".time()."',
				'{$orderid}',
				'',
				'block',
				'*'
			)
		", __FILE__, __LINE__);

		return $return;
	}
?>