<?php
// ------------------------------------------------------------------------- //
//                XOOPS - PHP Content Management System                      //
//                       <http://www.xoops.org/>                             //
// ------------------------------------------------------------------------- //
// Based on:								     //
// myPHPNUKE Web Portal System - http://myphpnuke.com/	  		     //
// PHP-NUKE Web Portal System - http://phpnuke.org/	  		     //
// Thatware - http://thatware.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/)                  //
// ------------------------------------------------------------------------- //

include_once(XOOPS_ROOT_PATH."/class/module.errorhandler.php");
include_once(XOOPS_ROOT_PATH."/class/xoopstree.php");

class ForumPosts {
	var $post_id;
	var $topic_id;
	var $forum_id;
	var $post_time;
	var $poster_ip;
	var $order;
	var $subject;
	var $post_text;
	var $pid;
	var $nohtml = 0;
	var $nosmiley = 0;
	var $uid;
	var $icon;
	var $notify;
	var $attachsig;
	var $prefix;
	var $db;
	var $istopic = 0;

	function ForumPosts($id=-1) {
		$this->db =& Database::getInstance();
		if ( is_array($id) ) {
			$this->makePost($id);
		} elseif ( $id != -1 ) {
			$this->getPost($id);
		}
	}

	function setTopicId($value){
		$this->topic_id = $value;
	}

	function setOrder($value){
		$this->order = $value;
	}

	function getTopPosts(){
		$sql = "SELECT p.*, t.post_text FROM ".$this->db->prefix("bb_posts")." p, ".$this->db->prefix("bb_posts_text")." t WHERE p.topic_id=".$this->topic_id." AND p.pid=".$this->pid." AND p.post_id = t.post_id ORDER BY p.".$this->order."";
		$ret = array();
		$result=$this->db->query($sql);
		$numrows = $this->db->getRowsNum($result);
		if ( $numrows == 0 ) {
			return $ret;
		}
		
		while ( $myrow = $this->db->fetchArray($result) ) {
			$ret[] = new ForumPosts($myrow);
		}
		return $ret;
	}

	function getPostTree($pid){
		$mytree = new XoopsTree($this->db->prefix("bb_posts"), "post_id", "pid");
		$parray = array();
		$parray = $mytree->getChildTreeArray($pid, "post_id");
		$ret = array();
		foreach ( $parray as $post ) {
			$ret[] = new ForumPosts($post);
		}
		return $ret;
	}

	function getAllPosts($perpage=0, $start=0){
		$sql = "SELECT p.*, t.post_text FROM ".$this->db->prefix("bb_posts")." p, ".$this->db->prefix("bb_posts_text")." t WHERE p.topic_id=".$this->topic_id." AND p.post_id = t.post_id ORDER BY p.".$this->order."";
		$result=$this->db->query($sql,$perpage,$start);
		$numrows = $this->db->getRowsNum($result);
		$ret = array();
		if ( $numrows == 0 ) {
			return $ret;
		}
		while ( $myrow = $this->db->fetchArray($result) ) {
			$ret[] = new ForumPosts($myrow);
		}
		return $ret;
	}

	function setParent($value){
		$this->pid=$value;
	}

	function setSubject($value){
		$this->subject=$value;
	}

	function setText($value){
		$this->post_text=$value;
	}

	function setUid($value){
		$this->uid=$value;
	}

	function setForum($value){
		$this->forum_id=$value;
	}

	function setIp($value){
		$this->poster_ip=$value;
	}

	function setNohtml($value=0){
		$this->nohtml=$value;
	}

	function setNosmiley($value=0){
		$this->nosmiley=$value;
	}

	function setIcon($value){
		$this->icon=$value;
	}

	function setNotify($value){
		$this->notify=$value;
	}

	function setAttachsig($value){
		$this->attachsig=$value;
	}

	function store() {
		$myts =& MyTextSanitizer::getInstance();
		$subject =$myts->censorString($this->subject);
		$post_text =$myts->censorString($this->post_text);
		$subject = $myts->makeTboxData4Save($subject);
		$post_text = $myts->makeTareaData4Save($post_text);
		if ( empty($this->post_id) ) {
			if ( empty($this->topic_id) ) {
				$this->topic_id = $this->db->genId($this->db->prefix("bb_topics")."_topic_id_seq");
				$datetime = time();
				$sql = "INSERT INTO ".$this->db->prefix("bb_topics")." (topic_id, topic_title, topic_poster, forum_id, topic_time, topic_notify) VALUES (".$this->topic_id.",'$subject', ".$this->uid.", ".$this->forum_id.", $datetime";
				if ( isset($this->notify) && $this->uid != 0 ) {
     					$sql .= ", '1'";
   				} else {
     					$sql .= ", '0'";
				}
   				$sql .= ")";
				//echo $sql;
   				if ( !$result = $this->db->query($sql) ) {
					ErrorHandler::show('0022');
   				}
				if ( $this->topic_id == 0 ) {
					$this->topic_id = $this->db->getInsertId();
				}
			}
			if ( !isset($this->nohtml) || $this->nohtml != 1 ) {
				$this->nohtml = 0;
			}
			if ( !isset($this->nosmiley) || $this->nosmiley != 1 ) {
				$this->nosmiley = 0;
			}
			if ( !isset($this->attachsig) || $this->attachsig != 1 ) {
				$this->attachsig = 0;
			}
			$this->post_id = $this->db->genId($this->db->prefix("bb_posts")."_post_id_seq");
			$datetime = time(); 
			$sql = "INSERT INTO ".$this->db->prefix("bb_posts")." (post_id, pid, topic_id, forum_id, post_time, uid, poster_ip, subject, nohtml, nosmiley, icon, attachsig) VALUES (".$this->post_id.",".$this->pid.",".$this->topic_id.",".$this->forum_id.",$datetime,".$this->uid.",'".$this->poster_ip."','".$subject."',".$this->nohtml.",".$this->nosmiley.",'".$this->icon."',".$this->attachsig.")";
			if ( !$result = $this->db->query($sql) ) {
				ErrorHandler::show('0022');
   			} else {
				if ( $this->post_id == 0 ) {
					$this->post_id = $this->db->getInsertId();
				}
   				$sql = "INSERT INTO ".$this->db->prefix("bb_posts_text")." (post_id, post_text) VALUES (".$this->post_id.", '".$post_text."')";
   				if ( !$result = $this->db->query($sql) ) {
					$this->db->query("DELETE FROM ".$this->db->prefix("bb_posts")." WHERE post_id=".$this->post_id."");
   					ErrorHandler::show('0022');
   				}
				//echo $sql;
   			}

   			if ( $this->uid != 0 ) {
      				XoopsUser::incrementPost($this->uid);
   			}
			if ( $this->pid == 0 ) {
				$sql = "UPDATE ".$this->db->prefix("bb_topics")." SET topic_last_post_id = ".$this->post_id.", topic_time = $datetime WHERE topic_id =".$this->topic_id."";
   				if ( !$result = $this->db->query($sql) ) {
   					//ErrorHandler::show('0022');
   				}
   				$sql = "UPDATE ".$this->db->prefix("bb_forums")." SET forum_posts = forum_posts+1, forum_topics = forum_topics+1, forum_last_post_id = ".$this->post_id." WHERE forum_id = ".$this->forum_id."";
				$result = $this->db->query($sql);
   				if ( !$result ) {
      					//ErrorHandler::show('0022');
   				}
			} else {
				$sql = "UPDATE ".$this->db->prefix("bb_topics")." SET topic_replies=topic_replies+1, topic_last_post_id = ".$this->post_id.", topic_time = $datetime WHERE topic_id =".$this->topic_id."";
   				if ( !$result = $this->db->query($sql) ) {
   					//ErrorHandler::show('0022');
   				}
				$sql = "UPDATE ".$this->db->prefix("bb_forums")." SET forum_posts = forum_posts+1, forum_last_post_id = ".$this->post_id." WHERE forum_id = ".$this->forum_id."";
				$result = $this->db->query($sql);
   				if ( !$result ) {
      					//ErrorHandler::show('0022');
   				}
			}
		}else{
			if ( $this->istopic() && isset($this->notify) && $this->notify != "" ) {
			 	$sql = "UPDATE ".$this->db->prefix("bb_topics")." SET topic_title = '$subject', topic_notify = ".$this->notify." WHERE topic_id = ".$this->topic_id."";
			 	if ( !$result = $this->db->query($sql) ) {
			 		ErrorHandler::show('0022');
			 	}
			}
			if ( !isset($this->nohtml) || $this->nohtml != 1 ) {
				$this->nohtml = 0;
			}
			if ( !isset($this->nosmiley) || $this->nosmiley != 1 ) {
				$this->nosmiley = 0;
			}
			if ( !isset($this->attachsig) || $this->attachsig != 1 ) {
				$this->attachsig = 0;
			}
			$sql = "UPDATE ".$this->db->prefix("bb_posts")." SET subject='".$subject."', nohtml=".$this->nohtml.", nosmiley=".$this->nosmiley.", icon='".$this->icon."', attachsig=".$this->attachsig." WHERE post_id=".$this->post_id."";
			$result = $this->db->query($sql);
			if ( !$result ) {
				//echo $sql;
				ErrorHandler::show('0022');
			} else {
				$sql = "UPDATE ".$this->db->prefix("bb_posts_text")." SET post_text = '".$post_text."' WHERE post_id =".$this->post_id."";
				$result = $this->db->query($sql);
				if ( !$result ) {
					//echo $sql;
					ErrorHandler::show('0022');
				}
			}
		}
		return $this->post_id;
	}

	function getPost($id) {
		$sql = "SELECT p.*, t.post_text FROM ".$this->db->prefix("bb_posts")." p, ".$this->db->prefix("bb_posts_text")." t WHERE p.post_id=$id and p.post_id=t.post_id";
		$array = $this->db->fetchArray($this->db->query($sql));
		$this->post_id = $array['post_id'];
		$this->pid = $array['pid'];
		$this->topic_id = $array['topic_id'];
		$this->forum_id = $array['forum_id'];
		$this->post_time = $array['post_time'];
		$this->uid = $array['uid'];
		$this->poster_ip = $array['poster_ip'];
		$this->subject = $array['subject'];
		$this->nohtml = $array['nohtml'];
		$this->nosmiley = $array['nosmiley'];
		$this->icon = $array['icon'];
		$this->attachsig = $array['attachsig'];
		$this->post_text = $array['post_text'];
		if ( $this->is_topic() ) {
			$sql = "SELECT * FROM ".$this->db->prefix("bb_topics")." where topic_id=".$this->topic_id."";
			$array = $this->db->fetchArray($this->db->query($sql));					
			$this->notify = $array['topic_notify'];
			$this->istopic = 1;
		}
	}

	function makePost($array){
		foreach($array as $key=>$value){
			$this->$key = $value;
		}
	}

	function delete() {
		$sql = "DELETE FROM ".$this->db->prefix("bb_posts")." WHERE post_id=".$this->post_id."";
		if ( !$result = $this->db->query($sql) ) {
			ErrorHandler::show('0022');
		}
		$sql = "DELETE FROM ".$this->db->prefix("bb_posts_text")." WHERE post_id=".$this->post_id."";
		if ( !$result = $this->db->query($sql) ) {
			echo "Could not remove posts text for Post ID:".$this->post_id.".<br />";
		}
		if ( !empty($this->uid) ) {
			$sql = "UPDATE ".$this->db->prefix("users")." SET posts=posts-1 WHERE uid=".$this->uid."";
			if ( !$result = $this->db->query($sql) ) {
			//	echo "Could not update user posts.";
			}
		}
		if ( $this->istopic ) {
			$sql = "DELETE FROM ".$this->db->prefix("bb_topics")." WHERE topic_id =".$this->topic_id."";
			if ( !$result = $this->db->query($sql) ) {
				echo "Could not delete topic.";
			}
		}
		$mytree = new XoopsTree($this->db->prefix("bb_posts"), "post_id", "pid");
		$arr = $mytree->getAllChild($this->post_id);
		$size = sizeof($arr);
		if ( $size > 0 ) {
			for ( $i = 0; $i < $size; $i++ ) {
				$sql = "DELETE FROM ".$this->db->prefix("bb_posts")." WHERE post_id=".$arr[$i]['post_id']."";
				if ( !$result = $this->db->query($sql) ) {
					echo "Could not delete post ".$arr[$i]['post_id']."";
				}
				$sql = "DELETE FROM ".$this->db->prefix("bb_posts_text")." WHERE post_id=".$arr[$i]['post_id']."";
				if ( !$result = $this->db->query($sql) ) {
					echo "Could not delete post text ".$arr[$i]['post_id']."";
				}
				if ( !empty($arr[$i]['uid']) ) {
					$sql = "UPDATE ".$this->db->prefix("users")." SET posts=posts-1 WHERE uid=".$arr[$i]['uid']."";
					if ( !$result = $this->db->query($sql) ) {
					//	echo "Could not update user posts.";
					}
				}
			}
		}
	}

	function subject($format="Show") {
		$myts =& MyTextSanitizer::getInstance();
		$smiley = 1;
		if ( $this->nosmiley() ) {
			$smiley = 0;
		}
		switch ( $format ) {
			case "Show":
				$subject= $myts->makeTboxData4Show($this->subject,$smiley);
				break;
			case "Edit":
				$subject = $myts->makeTboxData4Edit($this->subject);
				break;
			case "Preview":
				$subject = $myts->makeTboxData4Preview($this->subject,$smiley);
				break;
			case "InForm":
				$subject = $myts->makeTboxData4PreviewInForm($this->subject);
				break;
		}
		return $subject;
	}

	function text($format="Show"){
		$myts =& MyTextSanitizer::getInstance();
		$smiley = 1;
		$html = 1;
		$bbcodes = 1;
		if ( $this->nohtml() ) {
			$html = 0;
		}
		if ( $this->nosmiley() ) {
			$smiley = 0;
		}
		switch ( $format ) {
			case "Show":
				$text = $myts->makeTareaData4Show($this->post_text,$html,$smiley,$bbcodes);
				break;
			case "Edit":
				$text = $myts->makeTareaData4Edit($this->post_text);
				break;
			case "Preview":
				$text = $myts->makeTareaData4Preview($this->post_text,$html,$smiley,$bbcodes);
				break;
			case "InForm":
				$text = $myts->makeTareaData4PreviewInForm($this->post_text);
				break;
			case "Quotes":
				$text = $myts->makeTareaData4InsideQuotes($this->post_text);
				break;
		}
		return $text;
	}

	function postid() {
		return $this->post_id;
	}

	function posttime(){
		return $this->post_time;
	}

	function uid(){
		return $this->uid;
	}

	function uname(){
		return XoopsUser::getUnameFromId($this->uid);
	}

	function posterip(){
		return $this->poster_ip;
	}

	function parent(){
		return $this->pid;
	}

	function topic(){
		return $this->topic_id;
	}

	function nohtml(){
		return $this->nohtml;
	}

	function nosmiley(){
		return $this->nosmiley;
	}

	function icon(){
		return $this->icon;
	}

	function forum(){
		return $this->forum_id;
	}

	function notify(){
		return $this->notify;
	}

	function attachsig(){
		return $this->attachsig;
	}

	function prefix(){
		return $this->prefix;
	}

	function istopic() {
		if ( $this->istopic ) {
			return TRUE;
		}
		return FALSE;
	}

	function is_topic() {
		$sql = "SELECT pid FROM ".$this->db->prefix("bb_posts")." WHERE post_id = ".$this->post_id."";
		$r = $this->db->query($sql);
		list($pid)=$this->db->fetchRow($r);
		if ( $pid == 0 ) {
			return true;
		} else {
			return false;
		}
	}

	function showPost($viewmode, $order, $can_post, $topic_status, $allow_sig, $adminview=0, $color_num=1){
		global $xoopsConfig, $xoopsUser;
		$edit_image = "";
		$reply_image = "";
		$delete_image = "";
		$post_date = formatTimestamp($this->posttime(),"m");
		if ( $this->uid != 0 ) {
			$poster = new XoopsUser($this->uid());
			if ( !$poster->isActive() ) {
				$poster = 0;
			}
		} else {
			$poster = 0;
		}	
		if ( isset($this->icon) && $this->icon != "" ) {
			$subject_image = "<a name='".$this->postid()."' id='".$this->postid()."'><img src='".XOOPS_URL."/images/subject/".$this->icon."' alt='' /></a>";
		} else {
			$subject_image =  "<a name='".$this->postid()."' id='".$this->postid()."'><img src='".XOOPS_URL."/images/icons/posticon.gif' alt='' /></a>";
		}
		if ( $adminview ) {
			$ip_image = "<img src='".XOOPS_URL."/images/icons/ip.gif' alt='".$this->posterip()."' />";
		} else {
			$ip_image = "<img src='".XOOPS_URL."/images/icons/ip.gif' alt='' />";
		}
		// if this topic is not locked, show reply/edit link
		if ( $topic_status != 1 ) {
			if ( $adminview || ($xoopsUser && $this->uid() == $xoopsUser->getVar("uid")) ) {
				$edit_image = "<a href='edit.php?forum=".$this->forum()."&amp;post_id=".$this->postid()."&amp;topic_id=".$this->topic()."&amp;viewmode=".$viewmode."&amp;order=".$order."'><img src='".XOOPS_URL."/images/icons/edit.gif' alt='"._MD_EDITTHISPOST."' /></a>";
			}
			if ( $can_post ) {
				$reply_image = "<a href='reply.php?forum=".$this->forum()."&amp;post_id=".$this->postid()."&amp;topic_id=".$this->topic()."&amp;viewmode=".$viewmode."&amp;order=".$order."'><img src='".XOOPS_URL."/images/icons/reply.gif' alt='"._MD_REPLY."' /></a>";
			}
		}
		if ( $adminview ) {
			$delete_image = "<a href='delete.php?forum=".$this->forum()."&amp;topic_id=".$this->topic()."&amp;post_id=".$this->postid()."&amp;viewmode=".$viewmode."&amp;order=".$order."'><img src='".XOOPS_URL."/images/icons/delete.gif' alt='"._MD_DELETEPOST."' /></a>";
		}
		$text = preg_replace("#&lt;small&gt;\[\ "._MD_EDITEDBY."(.*?)\ \]&lt;/small&gt;#si", '<small>[ ' . _MD_EDITEDBY . '\1 ]</small>', $this->text());
		if ( $poster ) {
			if ( $allow_sig == 1 && $this->attachsig() != "" && $poster->attachsig() == 1 ) {
				$text .= "<p><br />_________________<br />". $poster->user_sig()."</p>";
			}
			$reg_date = _JOINED;
			$reg_date .= formatTimestamp($poster->user_regdate(),"s");
			$posts = _POSTS;
			$posts .= $poster->posts();
			$user_from = _FROM;
			$user_from = $poster->user_from();
			$rank = $poster->rank();
			if ( $rank['image'] != "" ) {
				$rank['image'] = "<img src='".XOOPS_URL."/images/ranks/".$rank['image']."' alt='' />";
			}
			$avatar_image = "<img src='".XOOPS_URL."/images/avatar/".$poster->user_avatar()."' alt='' />";
			if ( $poster->isOnline() ) {
				$online_image = "<span style='color:#ee0000;font-weight:bold;'>"._ONLINE."</span>";
			} else {
				$online_image = "";
			}
			$profile_image = "<a href='".XOOPS_URL."/userinfo.php?uid=".$poster->uid()."'><img src='".XOOPS_URL."/images/icons/profile.gif' alt='"._PROFILE."' /></a>";
			if ( $xoopsUser ) {
				$pm_image =  "<a href=\"javascript:openWithSelfMain('".XOOPS_URL."/pmlite.php?send2=1&amp;to_userid=".$poster->uid()."','pmlite',360,300);\"><img src='".XOOPS_URL."/images/icons/pm.gif' alt='".sprintf(_SENDPMTO,$poster->uname())."' /></a>";
			} else {
				$pm_image = "";
			}
   			if ( $poster->user_viewemail() ) {
				$email_image = "<a href='mailto:".$poster->email()."'><img src='".XOOPS_URL."/images/icons/email.gif' alt='".sprintf(_SENDEMAILTO,$poster->uname())."' /></a>";
			} else {
				$email_image = "";
			}
			$posterurl = $poster->url();
   			if ( $poster->url() != "" ) {
				$www_image = "<a href='$posterurl' target='_blank'><img src='".XOOPS_URL."/images/icons/www.gif' alt='"._VISITWEBSITE."' target='_blank' /></a>";
			} else {
				$www_image = "";
			}
   			if ( $poster->user_icq() != "" ) {
				$icq_image = "<a href='http://wwp.icq.com/scripts/search.dll?to=".$poster->user_icq()."'><img src='".XOOPS_URL."/images/icons/icq_add.gif' alt='"._ADDTOLIST."' /></a>";
			} else {
				$icq_image = "";
			}
			if ( $poster->user_aim() != "" ) {
				$aim_image = "<a href='aim:goim?screenname=".$poster->user_aim()."&message=Hi+".$poster->user_aim()."+Are+you+there?'><img src='".XOOPS_URL."/images/icons/aim.gif' alt='aim' /></a>";
			} else {
				$aim_image = "";
			}
   			if ( $poster->user_yim() != "" ) {
				$yim_image = "<a href='http://edit.yahoo.com/config/send_webmesg?.target=".$poster->user_yim()."&.src=pg'><img src='".XOOPS_URL."/images/icons/yim.gif' alt='yim' /></a>";
			} else {
				$yim_image = "";
			}
			if ( $poster->user_msnm() != '' ) {
				$msnm_image = "<a href='".XOOPS_URL."/userinfo.php?uid=".$poster->uid()."'><img src='".XOOPS_URL."/images/icons/msnm.gif' alt='msnm' /></a>";
			} else {
				$msnm_image = "";
			}
			showThread($color_num, $subject_image, $this->subject(), $text, $post_date, $ip_image, $reply_image, $edit_image, $delete_image, $poster->uname(), $rank['title'], $rank['image'], $avatar_image, $reg_date, $posts, $user_from, $online_image, $profile_image, $pm_image, $email_image, $www_image, $icq_image, $aim_image, $yim_image, $msnm_image);
		} else {
			showThread($color_num, $subject_image, $this->subject(), $text, $post_date, $ip_image, $reply_image, $edit_image, $delete_image, $xoopsConfig['anonymous']);
		}
	}

	function showTreeHead($width="100%"){
		echo "<table border='0' cellpadding='0' cellspacing='0' align='center' valign='top' width='$width'><tr><td class='bg2'><table border='0' cellpadding='4' cellspacing='1' width='100%'><tr class='bg3' align='center'><td colspan='3'>". _REPLIES ."</td></tr><tr class='bg3' align='left'><td width='60%' class='fg2'>". _SUBJECT ."</td><td width='20%' class='fg2'>". _POSTER ."</td><td class='fg2'>". _DATE ."</td></tr>";
	}

	function showTreeItem($viewmode, $order, $color_num){
		global $PHP_SELF;
		if ( $color_num == 1 ) {
			$bg = 'bg1';
		} else {
			$bg = 'bg4';
		}
		$prefix = str_replace(".", "&nbsp;&nbsp;&nbsp;&nbsp;", $this->prefix());
		$date = formatTimestamp($this->posttime("m"));
		if ( $this->icon() != "" ) {
			$icon = "subject/".$this->icon();
		} else {
			$icon = "icons/posticon.gif";
		}
		echo "<tr class='$bg' align='left'><td>".$prefix."<img src='".XOOPS_URL."/images/".$icon."'>&nbsp;<a href='".$PHP_SELF."?forum=".$this->forum()."&amp;topic_id=".$this->topic()."&amp;post_id=".$this->postid()."&amp;viewmode=".$viewmode."&amp;order=".$order."#".$this->postid()."'>".$this->subject()."</a></td><td><a href='".XOOPS_URL."/userinfo.php?uid=".$this->uid()."'>".$this->uname()."</a></td><td>".$date."</td></tr>";
	}

	function showTreeFoot(){
		echo "</table></td></tr></table><br />";
	}
}

?>