<?php
// ------------------------------------------------------------------------- //
//                XOOPS - PHP Content Management System                      //
//                       <http://www.xoops.org/>                             //
// ------------------------------------------------------------------------- //
//  This program is free software; you can redistribute it and/or modify     //
//  it under the terms of the GNU General Public License as published by     //
//  the Free Software Foundation; either version 2 of the License, or        //
//  (at your option) any later version.                                      //
//                                                                           //
//  This program is distributed in the hope that it will be useful,          //
//  but WITHOUT ANY WARRANTY; without even the implied warranty of           //
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            //
//  GNU General Public License for more details.                             //
//                                                                           //
//  You should have received a copy of the GNU General Public License        //
//  along with this program; if not, write to the Free Software              //
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA //
// ------------------------------------------------------------------------- //
// Author of File: 							     //
// Kazumi Ono (http://www.mywebaddons.com/ , http://www.myweb.ne.jp/)        //
// ------------------------------------------------------------------------- //
include_once(XOOPS_ROOT_PATH."/class/xoopsobject.php");
include_once(XOOPS_ROOT_PATH."/class/xoopsmodule.php");
include_once(XOOPS_ROOT_PATH."/class/xoopsgroup.php");

class XoopsBlock extends XoopsObject {

	function XoopsBlock($id = NULL) {
		$this->XoopsObject();
		$this->initVar("bid", "int", NULL, false);
		$this->initVar("mid", "int", 0, false);
		$this->initVar("func_num", "int", 0, false);
		$this->initVar("options", "textbox", NULL, false, 255, false);
		$this->initVar("name", "textbox", NULL, true, 150, false);
		$this->initVar("position", "int", 0, false);
		$this->initVar("title", "textbox", NULL, false, 150, false);
		$this->initVar("content", "textarea", NULL, false);
		$this->initVar("side", "int", 0, false);
		$this->initVar("weight", "int", 0, false);
		$this->initVar("visible", "int", 0, false);
		$this->initVar("type", "other", NULL, false);
		$this->initVar("c_type", "other", NULL, false);
		$this->initVar("isactive", "int", NULL, false);
		if ( !empty($id) ) {
			if ( is_array($id) ) {
				$this->set($id);
			} else {
				$this->load(intval($id));
			}
		}
	}

	function load($id) {
		$sql = "SELECT * FROM ".$this->db->prefix("newblocks")." WHERE bid = ".$id."";
		$arr = $this->db->fetchArray($this->db->query($sql));
		$this->set($arr);
	}

	function store() {
		if ( !$this->isCleaned() ) {
			if ( !$this->cleanVars() ) {
				return false;
			}
		}
		foreach ( $this->cleanVars as $k=>$v ) {
			$$k = $v;
		}
		if ( empty($bid) ) {
			$bid = $this->db->genId($this->db->prefix("blocks")."_bid_seq");
			$sql = "INSERT INTO ".$this->db->prefix("newblocks")." (bid, mid, func_num, options, name, position, title, content, side, weight, visible, type, c_type, isactive) VALUES ('$bid', '$mid', '$func_num', '$options', '".$name."', '$position', '".$title."', '".$content."', '".$side."', '".$weight."', '".$visible."', '$type', '".$c_type."', 1)";
		} else {
			$sql = "UPDATE ".$this->db->prefix("newblocks")." SET options='".$options."'";
			// a custom block needs its own name
			if ( $type == "C" ) {
				$sql .= ", name='".$name."'";
			}
			$sql .= ", position='".$position."', title='".$title."', content='".$content."', side='".$side."', weight='".$weight."', visible='".$visible."', c_type='".$c_type."' WHERE bid='".$bid."'";
		}
		//echo $sql;
		if ( !$this->db->query($sql) ) {
			$this->setErrors("Could not save block data into database");
			return false;
		}
		if ( empty($bid) ) {
			$bid = $this->db->getInsertId();
		}
		return $bid;
	}

	function delete() {
		$sql = "DELETE FROM ".$this->db->prefix("newblocks")." WHERE bid=".$this->getVar("bid")."";
		if ( !$this->db->query($sql) ) {
			return false;
		}
		$sql = "DELETE FROM ".$this->db->prefix("groups_blocks_link")." WHERE block_id=".$this->getVar("bid")."";
		$this->db->query($sql);
		return true;
	}

	/**
   	* do stripslashes/htmlspecialchars according to the needed output
	*
	* @param $format      output use: S for Show and E for Edit
	* @param $c_type    type of block content
	* @returns string
	*/
	function getContent($format = "S", $c_type = "T") {
		$myts =& MyTextSanitizer::getInstance();
		switch ( $format ) {
			case "S":
				// check the type of content
				// H : custom HTML block
				// P : custom PHP block
				// S : use text sanitizater (smilies enabled)
				// T : use text sanitizater (smilies disabled)
				if ( $c_type == "H" ) {
					$content = $myts->oopsStripSlashesRT($this->getVar("content", "N"));
					$content = str_replace("{X_SITEURL}", XOOPS_URL."/", $content);
					return $content;
				} elseif ( $c_type == "P" ) {
					ob_start();
					print eval($this->getVar("content", "N"));
    					$content = ob_get_contents();
    					ob_end_clean();
					$content = str_replace("{X_SITEURL}", XOOPS_URL."/", $content);
					return $content;
				} elseif ( $c_type == "S" ) {
					$content = $myts->makeTareaData4Show($this->getVar("content", "N"), 1, 1);
					$content = str_replace("{X_SITEURL}", XOOPS_URL."/", $content);
					return $content;
				} else {
					$content = $myts->makeTareaData4Show($this->getVar("content", "N"));
					$content = str_replace("{X_SITEURL}", XOOPS_URL."/", $content);
					return $content;
				}
			case "E":
				$content = $this->getVar("content", "E");
		}
		return $content;
	}



	function buildBlock() {
		global $xoopsConfig;
		$block = array();
		// M for module block, S for system block C for Custom
		if ( $this->getVar("type") != "C" ) {
			$module = new XoopsModule($this->getVar("mid"));
			// get block display function
			$show_func = $module->blockShowFunc($this->getVar("func_num"));
			if ( !$show_func ) {
				return false;
			}
			// must get lang files b4 execution of the function
			if ( file_exists(XOOPS_ROOT_PATH."/modules/".$module->dirname()."/blocks/".$module->blockFuncFile($this->getVar("func_num"))."") ) {
				if ( file_exists(XOOPS_ROOT_PATH."/modules/".$module->dirname()."/language/".$xoopsConfig['language']."/blocks.php") ) {
					include_once(XOOPS_ROOT_PATH."/modules/".$module->dirname()."/language/".$xoopsConfig['language']."/blocks.php");
				} elseif ( file_exists(XOOPS_ROOT_PATH."/modules/".$module->dirname()."/language/english/blocks.php") ) {
					include_once(XOOPS_ROOT_PATH."/modules/".$module->dirname()."/language/english/blocks.php");
				}
				// get the file where the function is defined
				include_once(XOOPS_ROOT_PATH."/modules/".$module->dirname()."/blocks/".$module->blockFuncFile($this->getVar("func_num"))."");
				$options = explode("|", $this->getVar("options"));
				if ( function_exists($show_func) ) {
					// execute the function
					$block = $show_func($options);
					if ( !$block ) {
						return false;
					}
				} else {
					return false;
				}
				// align content if there is additional content
				// in db
				$block['content'] = $this->buildContent($this->getVar("position"),$block['content'],$this->getContent("S",$this->getVar("c_type")));
				// replace title if there is additional title
				// in db
				$block['title'] = $this->buildTitle($block['title'], $this->getVar("title"));
			} else {
				return false;
			}
		}else{
			// it is a custom block, so just return the contents
			// and title in db
			$block['title'] = $this->getVar("title");
			$block['content'] = $this->getContent("S",$this->getVar("c_type"));
		}
		return $block;
	}

	/*
	* Aligns the content of a block
	* If position is 0, content in DB is positioned
	* before the original content
	* If position is 1, content in DB is positioned
	* after the original content
	*/
	function buildContent($position,$content="",$contentdb="") {
		if ( $position == 0 ) {
			$ret = $contentdb.$content;
		} elseif ( $position == 1 ) {
			$ret = $content.$contentdb;
		}
		return $ret;
	}

	function buildTitle($originaltitle, $newtitle="") {
		if ($newtitle != "") {
			$ret = $newtitle;
		} else {
			$ret = $originaltitle;
		}
		return $ret;
	}

	function isCustom() {
		if ( $this->getVar("type") == "C" ) {
			return true;
		}
		return false;
	}

	/**
   	* gets html form for editting block options
	* 
	*/
	function getOptions() {
		global $xoopsConfig;
		if ( $this->getVar("type") != "C" ) {
			$module = new XoopsModule($this->getVar("mid"));
			$edit_func = $module->blockEditFunc($this->getVar("func_num"));
			if ( !$edit_func ) {
				return false;
			}
			if ( file_exists(XOOPS_ROOT_PATH."/modules/".$module->dirname()."/blocks/".$module->blockFuncFile($this->getVar("func_num"))."") ) {
				if ( file_exists(XOOPS_ROOT_PATH."/modules/".$module->dirname()."/language/".$xoopsConfig['language']."/blocks.php") ) {
					include_once(XOOPS_ROOT_PATH."/modules/".$module->dirname()."/language/".$xoopsConfig['language']."/blocks.php");
				} elseif ( file_exists(XOOPS_ROOT_PATH."/modules/".$module->dirname()."/language/english/blocks.php") ) {
					include_once(XOOPS_ROOT_PATH."/modules/".$module->dirname()."/language/english/blocks.php");
				}
				include_once(XOOPS_ROOT_PATH."/modules/".$module->dirname()."/blocks/".$module->blockFuncFile($this->getVar("func_num"))."");
				$options = explode("|", $this->getVar("options"));
				$edit_form = $edit_func($options);
				if ( !$edit_form ) {
					return false;
				}
				return $edit_form;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}

	/**
   	* get all the blocks that match the supplied parameters
	* @param $side   0: sideblock - left
	*		 1: sideblock - right
	*		 2: sideblock - left and right
	*		 3: centerblock - left
	*		 4: centerblock - right
	*		 5: centerblock - center
	*		 6: centerblock - left, right, center
	* @param $groupid   groupid (can be an array)
	* @param $visible   0: not visible 1: visible
	* @param $orderby   order of the blocks
	* @returns array of block objects
	*/
	function getAllBlocksByGroup($groupid, $asobject=true, $side=NULL, $visible=NULL, $orderby="b.weight,b.bid", $isactive=1){
		$db =& Database::getInstance();
		$ret = array();
		if ( !$asobject ) {
			$sql = "SELECT b.bid ";
		} else {
			$sql = "SELECT b.* ";
		}
		$sql .= "FROM ".$db->prefix("newblocks")." b LEFT JOIN ".$db->prefix("groups_blocks_link")." l ON l.block_id=b.bid";
		if ( is_array($groupid) ) {
			$sql .= " WHERE (l.groupid=".$groupid[0]."";
			$size = sizeof($groupid);
			if ( $size  > 1 ) {
				for ( $i = 1; $i < $size; $i++ ) {
					$sql .= " OR l.groupid=".$groupid[$i]."";
				}
			}
			$sql .= ")";
		} else {
			$sql .= " WHERE l.groupid=".$groupid."";
		} 
		$sql .= " AND b.isactive=".$isactive;
		if ( isset($side) ) {
			// get both sides in sidebox? (some themes need this)
			if ( $side == 2 ) {
				$side = "(b.side=0 OR b.side=1)"; 
			} elseif ( $side == 6 ) {
				$side = "(b.side=3 OR b.side=4 OR b.side=5)";
			} else {
				$side = "b.side=".$side;
			}
			$sql .= " AND ".$side;
		}
		if ( isset($visible) ) {
			$sql .= " AND b.visible=$visible";
		}
		$sql .= " ORDER BY $orderby";
		$result = $db->query($sql);
		$added = array();
		while ( $myrow = $db->fetchArray($result) ) {
			if ( !in_array($myrow['bid'], $added) ) {
				if (!$asobject) {
					$ret[] = $myrow['bid'];							} else {
					$ret[] = new XoopsBlock($myrow);
				}
				array_push($added, $myrow['bid']);
			}
		}
		//echo $sql;
		return $ret;
	}


	function getAllBlocks($rettype="object", $side=NULL, $visible=NULL, $orderby="side,weight,bid", $isactive=1){
		$db =& Database::getInstance();
		$ret = array();
		$where_query = " WHERE isactive=".$isactive;
		if ( isset($side) ) {
			// get both sides in sidebox? (some themes need this)
			if ( $side == 2 ) {
				$side = "(side=0 OR side=1)"; 
			} elseif ( $side == 6 ) {
				$side = "(side=3 OR side=4 OR side=5)";
			} else {
				$side = "side=".$side;
			}
			$where_query .= " AND ".$side;
		}
		if ( isset($visible) ) {
			$where_query .= " AND visible=$visible";
		}
		$where_query .= " ORDER BY $orderby";
		switch($rettype) {
			case "object":
				$sql = "SELECT * FROM ".$db->prefix("newblocks")."".$where_query;
				$result = $db->query($sql);
				while ( $myrow = $db->fetchArray($result) ) {
					$ret[] = new XoopsBlock($myrow);
				}
				break;
			case "list":
				$sql = "SELECT * FROM ".$db->prefix("newblocks")."".$where_query;
				$result = $db->query($sql);
				while ( $myrow = $db->fetchArray($result) ) {
					$block = new XoopsBlock($myrow);
					$name = ($block->getVar("type") != "C") ? $block->getVar("name") : $block->getVar("title");
					$ret[$block->getVar("bid")] = $name;
				}
				break;
			case "id":
				$sql = "SELECT bid FROM ".$db->prefix("newblocks")."".$where_query;
				$result = $db->query($sql);
				while ( $myrow = $db->fetchArray($result) ) {
					$ret[] = $myrow['bid'];
				}
				break;
		}
		//echo $sql;
		return $ret;
	}

	function getByModule($moduleid, $asobject=true){
		$db =& Database::getInstance();
		if ( $asobject == true ) {
			$sql = $sql = "SELECT * FROM ".$db->prefix("newblocks")." WHERE mid=".$moduleid."";
		} else {
			$sql = "SELECT bid FROM ".$db->prefix("newblocks")." WHERE mid=".$moduleid."";
		}
		$result = $db->query($sql);
		$ret = array();
		while( $myrow = $db->fetchArray($result) ) {
			if ( $asobject ) {
				$ret[] = new XoopsBlock($myrow);
			} else {
				$ret[] = $myrow['bid'];
			}
		}
		return $ret;
	}
}

?>