<?php
	require_once( $GLOBALS["site_root"] . "/includes/urlgen/Forum.inc.php" );
	require_once( $GLOBALS["site_root"] . "/includes/models/User.inc.php" );
	require_once( $GLOBALS["site_root"] . "/includes/models/MyUser.inc.php" );
	require_once( $GLOBALS["site_root"] . "/includes/models/MyMember.inc.php" );
	require_once( $GLOBALS["site_root"] . "/includes/models/Member.inc.php" );
	require_once( $GLOBALS["site_root"] . "/includes/models/TemplateMail.inc.php" );
	require_once( $GLOBALS["site_root"] . "/includes/models/Constants.inc.php" );

	class ForumModel {

		public static function getPageSize() {
			return 10;
		}

		protected function recreateTopicTreeMetadata() {
			$query = sprintf( "select * from sp_recalculate_tree_metadata('%s','%s','%s','%s','%s','%s','%s')",
				"forum_topics",
				"forum_topic_id",
				"forum_topic_parentid",
				"forum_topic_level",
				"forum_topic_ordering",
				"forum_topic_meta_l",
				"forum_topic_meta_r" );
			FNTH_db_query( $query );
		}

		public function isUsedTopicAlias( $aliasname , $datas ) {
			$forum_topic_parentid = $datas["forum_topic_parentid"];
			$exclude_ids = $datas["exclude_ids"];
			$query = sprintf( "select count(*) as num from forum_topics where forum_topic_parentid%s and forum_topic_aliasname='%s'",
				($forum_topic_parentid) ? sprintf( "=%d" , $forum_topic_parentid ) : sprintf( " is null" ),
				$aliasname );
			if (count( $exclude_ids )) {
				$query.=sprintf( " and forum_topic_id not in (%s)" , implode( "," , $exclude_ids ) );
			}
			$num = FNTH_db_get_field( $query , "num" );
			return ($num>0);
		}

		protected function generateNextTopicAlias( $forum_topic_parentid , $title , $exclude_ids = array() ) {
			$aliasname = fo3_generate_unique_alias( $title , array( $this , "isUsedTopicAlias" ) , array( "forum_topic_parentid" => $forum_topic_parentid , "exclude_ids" => $exclude_ids ) );
			return $aliasname;
		}

		protected function prepareTopic( $params ) {
			$retval = array();
			$forum_topic_parentid=(isset( $params["forum_topic_parentid"] )) ? $params["forum_topic_parentid"] : 0;

			$retval["forum_topic_parentid"]=(isset( $params["forum_topic_parentid"] )) ?
				sprintf( "%d" , $params["forum_topic_parentid"] ) : "null";
			if (isset( $params["owner_user_id"] ) && $params["owner_user_id"] )
				$retval["owner_user_id"]=sprintf( "%d" , $params["owner_user_id"] );
			$retval["forum_topic_level"]=sprintf( "%d" , $params["forum_topic_level"] );
			$retval["forum_topic_ordering"]=sprintf( "%d" , $params["forum_topic_ordering"] );
			$retval["ctstamp"]=(isset( $params["ctstamp"] )) ?	
				sprintf( "'%s'" , FNTH_db_addslashes( $params["ctstamp"] ) ) : "now()";
			$retval["forum_topic_title"]=sprintf( "'%s'" , FNTH_db_addslashes( $params["forum_topic_title"] ) );
			$retval["forum_topic_aliasname"]=sprintf( "'%s'" , FNTH_db_addslashes(
				$this->generateNextTopicAlias( $forum_topic_parentid , $params["forum_topic_title"] ) ) );
			if (isset( $params["is_public"] ))
				$retval["is_public"]=($params["is_public"]) ? "true" : "false";
			if (isset( $params["is_active"] ))
				$retval["is_active"]=($params["is_active"]) ? "true" : "false";
			if (isset( $params["is_admin_acknowledged"] ))
				$retval["is_admin_acknowledged"]=($params["is_admin_acknowledged"]) ? "true" : "false";
			if (isset( $params["oldid"] ))
				$retval["oldid"]=sprintf( "%d" , $params["oldid"] );
			return $retval;
		}

		public function addTopic( $params = array() ) {
			$ins = $this->prepareTopic( $params );
			FNTH_db_free_result( FNTH_db_query( FNTH_db_generate_insert_query( "forum_topics" , $ins ) ) );
			$this->recreateTopicTreeMetadata();
			$query = sprintf( "select currval('forum_topics_forum_topic_id_seq') as num" );
			return FNTH_db_get_field( $query , "num" );
		}

		public function updateTopic( $forum_topic_id = 0 , $params = array() ) {
			$upd = array();
			$upd["forum_topic_title"]=sprintf( "'%s'" , FNTH_db_addslashes( $params["forum_topic_title"] ) );
			$upd["forum_topic_aliasname"]=sprintf( "'%s'" , FNTH_db_addslashes(
				$this->generateNextTopicAlias( $forum_topic_parentid , $params["forum_topic_title"] , array( $forum_topic_id ) ) ) );
			FNTH_db_free_result( FNTH_db_query( FNTH_db_generate_update_query( "forum_topics" , $upd , sprintf( "forum_topic_id=%d" , $forum_topic_id ) ) ) );
		}

		public function deleteTopic( $forum_topic_id = 0 ) {
			$query = sprintf( "delete from forum_posts where forum_topic_id=%d" , $forum_topic_id );
			FNTH_db_free_result( FNTH_db_query( $query ) );
			$query = sprintf( "delete from forum_topics where forum_topic_id=%d" , $forum_topic_id );
			FNTH_db_free_result( FNTH_db_query( $query ) );
		}

		public function getTopicFromId( $forum_topic_id ) {
			$query = sprintf( "select * from forum_topics where forum_topic_id=%d" , $forum_topic_id );
			return FNTH_db_get_row( $query );
		}

		public function getNextTopicOrderingOnParent( $forum_topic_parentid = 0 ) {
			$query = sprintf( "select max(forum_topic_ordering) as num from forum_topics where forum_topic_parentid%s",
				($forum_topic_parentid) ? sprintf( "=%d" , $forum_topic_parentid ) : " is null" );
			$f = FNTH_db_get_field( $query , "num" );
			if (!$f) $f = 0;
			return $f+1;
		}
			
		protected function getTopicNextPostNumber( $forum_topic_id ) {
			$num = FNTH_db_get_field( sprintf( "select count(*) as num from forum_posts where forum_topic_id=%d",
				$forum_topic_id ) , "num" );
			return $num+1;
		}
		protected function getTopicNextOrdering( $forum_topic_id ) {
			$num = FNTH_db_get_field( sprintf( "select max(meta_ordering) as num from forum_posts where forum_topic_id=%d and not is_admin_moderated",
				$forum_topic_id ) , "num" );
			if (!$num) $num=0;
			return $num+1;
		}

		public function addTopicPost( $forum_topic_id , $params = array() ) {
			$um = new UserModel();
			if (isset( $params["owner_user_id"] ) && $params["owner_user_id"] > 0 ) {
				$user = $um->getUserFromUserId( $params["owner_user_id"] );
			} else {
				$user = false;
			}

			$ins = array();
			$ins["forum_topic_id"]=sprintf( "%d" , $forum_topic_id );
			if (isset( $params["forum_post_parentid"] ) && ($params["forum_post_parentid"]>0) )
				$ins["forum_post_parentid"]=sprintf( "%d" , $params["forum_post_parentid"] );
			if (isset( $params["owner_user_id"] ) && ($params["owner_user_id"]>0) )
				$ins["owner_user_id"]=sprintf( "%d" , $params["owner_user_id"] );
			if (!isset( $params["ctstamp"] )) $params["ctstamp"]=fo3_date( "Y-m-d H:i:s" );
			$ins["ctstamp"]=sprintf( "'%s'" , $params["ctstamp"] );

			if ($user) {
				$ins["poster_name"]=sprintf( "'%s'" , FNTH_db_addslashes( $user["user_name"] ) );
				$ins["poster_email"]=sprintf( "'%s'" , FNTH_db_addslashes( $user["email"] ) );
			}

			if (isset( $params["poster_name"] ))
				$ins["poster_name"]=sprintf( "'%s'" , FNTH_db_addslashes( $params["poster_name"] ) );
			if (isset( $params["poster_email"] ))
				$ins["poster_email"]=sprintf( "'%s'" , FNTH_db_addslashes( $params["poster_email"]) );


			if (isset( $params["post"] )) 
				$ins["post"]=sprintf( "'%s'" , FNTH_db_addslashes( $params["post"] ));
			if (isset( $params["ipaddress"] ))
				$ins["ipaddress"]=sprintf( "'%s'" , FNTH_db_addslashes( $params["ipaddress"] ) );
			if (isset( $params["is_admin_acknowledged"] ))
				$ins["is_admin_acknowledged"]=($params["is_admin_acknowledged"]) ? "true" : "false";
			if (!isset( $params["is_admin_moderated"] )) $params["is_admin_moderated"]=false;

			$ins["is_admin_moderated"]=($params["is_admin_moderated"]) ? "true" : "false";
			if (isset( $params["oldid"] ))
				$ins["oldid"]=sprintf( "%d" , $params["oldid"] );

			$next_post = $this->getTopicNextPostNumber( $forum_topic_id );
			$ins["meta_post_number"]=$next_post;
			$ins["meta_ordering"]=($params["is_admin_moderated"]) ? 0 : $this->getTopicNextOrdering( $forum_topic_id );
			$q = FNTH_db_generate_insert_query( "forum_posts" , $ins );
			
			FNTH_db_free_result( FNTH_db_query( $q ) );
			$forum_post_id =  FNTH_db_get_field( "select currval('forum_posts_forum_post_id_seq') as num" , "num" );

			// update topic related
			$upd = array();
			$upd["mtstamp"]="now()";
			$upd["cache_number_of_posts"]=sprintf( "%d" , $next_post );
			$upd["last_poster_user_id"]=$user["user_id"];

			if ($user) {
				$upd["cache_last_poster_name"]=sprintf( "'%s'" , FNTH_db_addslashes( $user["user_name"] ) );
			}
			FNTH_db_free_result( FNTH_db_query(
				FNTH_db_generate_update_query( "forum_topics",
					$upd,sprintf( "forum_topic_id=%d" , $forum_topic_id ) ) ) );

			// send admin email
			$tm = new TemplateMailModel( "sys_forum_post_notification" );
			$cm = new ConstantsModel( $tm );
			$cm->addUserConstantsToTemplate( $user["user_id"] , "user" , $user );
			$mm = new MemberModel();
			$member = $mm->getMemberFromUserId( $user["user_id"] );
			$cm->addMemberConstantsToTemplate( $member["member_id"] , "member" , $member );
			$cm->addForumTopicConstantsToTemplate( $forum_topic_id );
			$cm->addForumPostConstantsToTemplate( $forum_post_id );
			$tm->sendMail( $GLOBALS["fo3_admin_email"] );
			return $forum_post_id;
		}

		public function updateTopicPost( $forum_post_id , $p= array() ) {
			$upd = array();
			if (isset( $p["post"] )) $upd["post"]=sprintf( "'%s'" , FNTH_db_addslashes( $p["post"] ) );
			if (isset( $p["is_admin_acknowledged"] )) $upd["is_admin_acknowledged"]=($p["is_admin_acknowledged"]) ? "true" : "false";
			if (isset( $p["is_admin_moderated"] )) $upd["is_admin_moderated"]=($p["is_admin_moderated"]) ? "true" : "false";
			FNTH_db_free_result( FNTH_db_query(
				FNTH_db_generate_update_query( "forum_posts",
					$upd,sprintf( "forum_post_id=%d",$forum_post_id ) ) ) );
			return $forum_post_id;
		}

		public function deleteTopicPost( $forum_post_id ) {

		}

		public function getForumTopicIdOfPost( $forum_post_id ) {
			return FNTH_db_get_field( sprintf( "select forum_topic_id from forum_posts where forum_post_id=%d" , $forum_post_id ) , "forum_topic_id" );
		}

		public function getForumPostFromId( $forum_post_id ) {
			return FNTH_db_get_row( sprintf( "select * from forum_posts where forum_post_id=%d" , $forum_post_id ) );
		}

		public function moderateTopicPost( $forum_post_id , $moderate = true ) {
			$forum_post = $this->getForumPostFromId( $forum_post_id );
			$moderated = ($forum_post["is_admin_moderated"]=="t");
			if ($moderate==$moderated) return;
			if ($moderate) {
				// elsonek ot lerantjuk
				$upd = array();
				$upd["is_admin_moderated"]="true";
				$upd["meta_ordering"]=0;
				FNTH_db_free_result( FNTH_db_query(
					FNTH_db_generate_update_query( "forum_posts" , $upd,
						sprintf( "forum_post_id=%d" , $forum_post_id )
					)
				) );
				// masodiknak mindenki orderingje eggyel beljebb csuszik
				$upd = array();
				$upd["meta_ordering"]="meta_ordering-1";
				FNTH_db_free_result( FNTH_db_query(
					FNTH_db_generate_update_query( "forum_posts", $upd,
						sprintf( "forum_topic_id=%d and forum_post_id>%d and not is_admin_moderated",
							$forum_post["forum_topic_id"],
							$forum_post_id )
					)
				) );	
			} else {
				// megkeressuk az elotte levo legnagyobb orderinget
				$query = sprintf( "select max(meta_ordering) as num from forum_posts where forum_topic_id=%d and forum_post_id<%d and not is_admin_moderated",
					$forum_post["forum_topic_id"],
					$forum_post_id );
				$num = FNTH_db_get_field( $query , "num" );
				if (!$num) $num = 0;
				$num ++;
				// adunk a mostaninak orderinget
				$upd = array();
				$upd["is_admin_moderated"]="false";
				$upd["meta_ordering"]=$num;
				FNTH_db_free_result( FNTH_db_query(
					FNTH_db_generate_update_query( "forum_posts" , $upd,
						sprintf( "forum_post_id=%d" , $forum_post_id )
					)
				) );
				// a tobbit meg utanarantjuk
				$upd = array();
				$upd["meta_ordering"]="meta_ordering+1";
				FNTH_db_free_result( FNTH_db_query(
					FNTH_db_generate_update_query( "forum_posts", $upd,
						sprintf( "forum_topic_id=%d and forum_post_id>%d and not is_admin_moderated",
							$forum_post["forum_topic_id"],
							$forum_post_id )
					)
				) );	
			}
		}

		public function getForumTopicFromId( $forum_topic_id ) {
			if ($forum_topic_id) {
				$retval = FNTH_db_get_row( sprintf( "select * from forum_topics where forum_topic_id=%d",$forum_topic_id ) );
				$retval["is_topic_post_thread"]=($retval["is_topic_post_thread"]=="t");
				return $retval;
			}
			$retval = array();
			$retval["is_topic_post_thread"]=false;
			return $retval;
		}

		public function getForumTopicBreadcrumbData( $forum_topic_id = 0 ) {
			$retval = array();

			// mainpage
			$row = array();
			$row["url"]=$GLOBALS["site_www"]."/";
			$row["forum_topic_title"]=__("Mainpage");
			$retval[]=$row;
	
			// the forum
			$row = array();
			$row["forum_topic_id"]=0;
			$row["forum_topic_title"]=__("Forum" );
			$row["breadcrumb_last"] = ($forum_topic_id) ? false : true;
			$row["url"]=ForumURL::renderURL( array() );
			$retval[]=$row;

			$query = sprintf( "select forum_topic_meta_l,forum_topic_meta_r from forum_topics where forum_topic_id=%d",
				$forum_topic_id );
			$row = FNTH_db_get_row( $query );
			$ml = $row["forum_topic_meta_l"];
			$mr = $row["forum_topic_meta_r"];
			$query = sprintf( "select * from forum_topics where forum_topic_meta_l<=%d and forum_topic_meta_r>=%d
				order by forum_topic_meta_l",$ml,$mr);
			$ds = FNTH_db_get_resultset( $query );
			$extend = "";
			$p = array();
			foreach ($ds as $row) {
				$extend.=$row["forum_topic_aliasname"]."/";
				$row["url"]=ForumURL::renderURL( $p , $extend );
				$row["breadcrumb_last"]=($row["forum_topic_id"]==$forum_topic_id);
				$retval[]=$row;
			}

			return $retval;
		}

		public function getForumTopicIdFromAlias( $aliasname ) {
			$query = sprintf( "select forum_topic_id from forum_topics where forum_topic_aliasname='%s'",
				FNTH_db_addslashes( $aliasname ) );
			return FNTH_db_get_field( $query , "forum_topic_id" );
		}

		public function getForumTopicIdFromURI( $uri ) {
			if (empty( $uri )) return 0;

			$e = explode( "/" , $uri );
			$forum_topic_level = 1;
			$forum_topic_id=0;
			while (count($e)) {
				$query = sprintf( "select forum_topic_id from forum_topics where forum_topic_level=%d and forum_topic_parentid%s and forum_topic_aliasname='%s'",
					$forum_topic_level,
					($forum_topic_id) ? sprintf( "=%d" , $forum_topic_id ) : " is null",
					FNTH_db_addslashes( $e[0] ) );
				$fti = FNTH_db_get_field( $query , "forum_topic_id" );
				if ($fti) {
					$forum_topic_id = $fti;
					$forum_topic_level++;
				}
				array_shift( $e );
			}
			return $forum_topic_id;
		}

		public function getForumSubtopicOptions( $forum_topic_parentid = 0 , $choose = true ) {
			if ($forum_topic_parentid) {
				$row = FNTH_db_get_row( sprintf( "select * from forum_topics where forum_topic_id=%d" , $forum_topic_parentid ) );
				$forum_topic_level = $row["forum_topic_level"];
				$meta_l = $row["forum_topic_meta_l"];
				$meta_r = $row["forum_topic_meta_r"];
			} else {
				$forum_topic_level = 0;
				$meta_l = 0;
				$meta_r = 999999;
			}
			$query = sprintf( "select * from forum_topics where forum_topic_meta_l>%d and forum_topic_meta_r<%d order by forum_topic_meta_l",
				$meta_l , $meta_r );
			$ds = FNTH_db_get_resultset( $query );
			$retval = array();
			if ($choose) $retval[""]=__("Choose");
			foreach ($ds as $row) {
				$title = str_repeat( "&nbsp;" , ($row["forum_topic_level"]-$forum_topic_level)*3 ).
					$row["forum_topic_title"];
				$retval[$row["forum_topic_id"]]=$title;
			}
			return $retval;
		}

		public function isTopicExistsOnOldid( $oldid ) {
			$query = sprintf( "select count(*) as num from forum_topics where oldid=%d" , $oldid );
			$retval = FNTH_db_get_field( $query , "num" );
			return ($retval>0);
		}

		public function getTopicIdFromOldid( $oldid ) {
			$query = sprintf( "select forum_topic_id from forum_topics where oldid=%d" , $oldid );
			return FNTH_db_get_field( $query , "forum_topic_id" );
		}
	
		public function getForumPostIdFromOldid( $oldid ) {
			$num = (int)FNTH_db_get_field( sprintf( "select forum_post_id from forum_posts where oldid=%d", $oldid ) , "forum_post_id" );
			if (!$num) return false;
			return $num;
		}

		public function getNumberOfSubtopics( $forum_topic_id = 0 ) {
			$query = sprintf( "select count(*) as num from forum_topics where forum_topic_parentid%s",	
				($forum_topic_id) ? sprintf( "=%d" , $forum_topic_id ) : " is null" );
			return FNTH_db_get_field( $query , "num" );
		}

		public static function canViewTopics( $forum_topic_id ) {
			return true;
			/*
			$mym = new MyUserModel();
			if (!$mym->isUserLoggedin()) return false;
			return true;
			*/
		}

		public function getForumTopicLastPosterName( $forum_topic_id  = 0) {
			$query = sprintf( "select poster_name from forum_posts where not is_admin_moderated and forum_topic_id=%d order by forum_post_id desc limit 1" , $forum_topic_id );
			return FNTH_db_get_field( $query , "poster_name" );
		}
		
		public static function canCreateTopic( $forum_topic_id ) {
			$mmm = new MyMemberModel();
			if (!$mmm->isMemberLoggedin()) return false;
			if (!$mmm->isLoggedinMemberActiveSubscriber()) return false;
			$mm = new MemberModel();
			$member = $mm->getMemberFromMemberId( $mmm->getLoggedinMemberId() );
			return ($member["is_forum_poster"]=="t");
		}
		
		public static function canPost( $forum_topic_id ) {
			$mmm = new MyMemberModel();
			if (!$mmm->isMemberLoggedin()) return false;
			if (!$mmm->isLoggedinMemberActiveSubscriber()) return false;
			$mm = new MemberModel();
			$member = $mm->getMemberFromMemberId( $mmm->getLoggedinMemberId() );
			return ($member["is_forum_poster"]=="t");
		}

		public static function canViewPosts( $forum_topic_id ) {
			$mm = new MyMemberModel();
			if (!$mm->isMemberLoggedin()) return false;
			if (!$mm->isLoggedinMemberActiveSubscriber()) return false;
			return true;
		}
	}

?>
