<?php

RegisterPrefix("clsPosting","posting","in-bulletin/posting.php");

class clsPosting extends clsItem
{
    var $Poster;
    var $Locked;
    var $Children;

    function clsPosting($PostingId=NULL)
    {
        $this->clsItem();
	    $this->adodbConnection = &GetADODBConnection();
        $this->tablename=GetTablePrefix()."Posting";
        $this->type=30;
        $this->BasePermission="TOPIC.REPLY";
        $this->TagPrefix="posting";
        $this->id_field = "PostingId";
        $this->Locked = FALSE;
        if(isset($PostingId))
            $this->LoadFromDatabase($PostingId);
    }

    function Delete()
    {
        $oldparent = $this->Get("PostingId");
        $newparent = $this->Get("ReplyTo");
        $sql="UPDATE ".$this->tablename." SET ReplyTo=$newparent WHERE ReplyTo=$oldparent";
        $this->adodbConnection->Execute($sql);
        parent::Delete();
    }

    function GetUserPosts($UserId)
    {
		global $Errors, $objUsers;
		$sql = "SELECT COUNT(PostingId) as pcount FROM ".$this->tablename." WHERE CreatedById=$UserId";
		$result = $this->adodbConnection->Execute($sql);
		if ($result === false)
		{
			$Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"","clsPosting","GetUserPosts");
			return false;
		}
		$posts = $result->fields["pcount"];

		return $posts;
    }

    function PostOption($name)
    {
		$OptionsMap = Array('show_sig'=>128,'disable_bbcode'=>64,'disable_smileys'=>32);
    	if(!isset($OptionsMap[$name]))return false;
    	$opt = $this->Get("Options");
    	return (($opt & $OptionsMap[$name]) == $OptionsMap[$name]) ? 1 : 0;
    }

    function SetPostOption($name,$value)
    {
    	$OptionsMap = Array('show_sig'=>128,'disable_bbcode'=>64,'disable_smileys'=>32);
    	if(!isset($OptionsMap[$name]))return false;

    	$opt=(int)$this->Get("Options");
    	if($value)
    	{
    		$opt|=$OptionsMap[$name];
    	}
    	else
    	{
    		$opt=$opt&~$OptionsMap[$name];
    	}
        $this->Set("Options",$opt);
    }

    function LoadFromDatabase($Id)
    {
		global $Errors;

        if(!isset($Id))
        {
            $Errors->AddError("error.AppError",NULL,'Internal error: LoadFromDatabase id',"",get_class($this),"GetUserPosts");
            return false;
        }

        $sql = sprintf("SELECT * FROM ".$this->tablename." WHERE PostingId = '%s'",$Id);
        $result = $this->adodbConnection->Execute($sql);
        if ($result === false)
        {
            $Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"LoadFromDatabase");
            return false;
        }
        $this->SetFromArray($result->fields);
        $this->Clean();
        return true;
    }

	function GetTotalPosts()
	{
	 	global $Errors,$objSession;

		$sql = "SELECT count(*) as PostCount FROM ".$this->tablename;
		$result = $this->adodbConnection->Execute($sql);
        if ($result === false || !$result)
        {
            $Errors->AddError("error.DatabaseError",NULL,$objSession->adodbConnection->ErrorMsg(),"","clsPosting","GetTotalPosts");
            return false;
        }
		return $result->fields["PostCount"];
	}

    function RenderText($text,$QouteTemplate)
    {
       global $objSmileys;

       $ret = $this->ReplaceQuote($ret,$QuoteTemplate);

       if(!$this->PostOption("disable_smileys"))
           $ret = $objSmileys->ParseText($ret);
       if(!$this->PostOption("disable_bbcode"))
           $ret = ReplaceBBCode($ret);
       return $ret;
    }

    function ReplaceQuote($text,$QuoteTemplate)
    {
        global $objPostingList;

        //$template = new clsItemTemplate();
        if(strstr($text,"[quote"))
        {
        	$text .= " ";
            $pos = strpos($text,"[quote");
            $endopen = strpos($text,"]",$urlpos);
            $closepos = getLastStr($text,"[/quote]");  // strrpos($text,"[/quote]");

            if($endopen && $closepos)
            {
                $tagText = substr($text,$pos, $closepos + strlen("[/quote]") - $pos);
                $innerText = substr($text,$endopen+1,$closepos - $endopen-1);
                $tagText = substr($text,$pos+1,$endopen - $pos-1);
                $attr = substr($tagText,6);
                $attribs = explode("=",$attr);
//                echo "Tag: $tagText Inner: $innerText<br>\n";
//                echo $attribs[0]."=".$attribs[1];
                if($attribs[0]=="id")
                {
                    $QuoteId = $attribs[1];
                    $p = new clsPosting($QuoteId);// $objPostingList->GetItem($QuoteId);
                    if(is_object($p))
                    {
                          // echo "Parsing $QuoteTemplate..";
                          $p->Set("PostingText",$innerText);
                          $text = substr($text,0,$pos).$p->ParseTemplate($QuoteTemplate).substr($text,$closepos+8)." ";
                         // echo $text;
                    }
                }
            }
        }
        return $text;
    }

    function Link($template="")
    {
        global $var_list_update, $bb_var_list_update,  $var_list;

        if(strlen($template))
        {
            $var_list_update["t"] = $template;
        }
        else
            $var_list_update["t"] = $var_list["t"];

        $bb_var_list_update["top"] = $this->Get("TopicId");
        $bb_var_list_update["post"] = $this->Get("PostingId");
        $ret = HREF_Wrapper();
        unset($bb_var_list_update["top"],$bb_var_list_update["post"], $var_list_update["t"]);
        return $ret;
    }

    function ParseObject($element)
    {
        global $objConfig, $objSmileys, $objSession, $objUsers, $objCatList,
        	   $var_list_update, $var_list, $bb_var_list_update, $objCensorList;

        $extra_attribs = ExtraAttributes($element->attributes);
        if(strtolower($element->name)==$this->TagPrefix)
        {
            $field = strtolower($element->attributes["_field"]);
            switch($field)
            {
            case "id":
            case "postingid":
            	/*
            	@field:posting.postingid
            	@description: Returns the ID field for the post
            	*/
                $ret = $this->Get("PostingId");
            break;
            case "subject":
            	/*
            	@field:posting.subject
            	@description: Returns the post subject, if set
            	*/
                $ret = $objCensorList->CensorText($this->Get("Subject"));
            break;
              	/*
 				@field:posting.image
 				@description:Return an image associated with the topic
  				@attrib:_default:bool:If true, will return the default image if the requested image does not exist
  				@attrib:_name::Return the image with this name
  				@attrib:_thumbnail:bool:If true, return the thumbnail version of the image
  				@attrib:_imagetag:bool:If true, returns a complete image tag. exta html attributes are passed to the image tag
               */
            case "modifiedby":
				/*
				@field:posting.modifiedby
				@description:parse a user field of the user that last modified the topic
  				@attrib:_usertag::User field to return (defaults to login ID)
  				*/
                $field = $element->attributes["_usertag"];
                if(!strlen($field))
                {
                    $field = "user_login";
                }
                $u = $objUsers->GetItem($this->Get("ModifiedById"));
                $ret = $u->parsetag($field);
            break;
            case "depth":
              	/*
              	@field:posting.depth
              	@description: For threaded post lists, this field returns the depth of the post (how many replies deep this post is)
              	@attrib:_multiplier:int:value to multiply the dept by
              	*/
                $ret = (int)$this->Get("Depth");
                if(is_numeric($element->attributes["_multiplier"]))
                    $ret = $ret * $element->attributes["_multiplier"];
            break;
            case "createdby":
				/*
				@field:posting.createdby
				@description:parse a user field of the user that created this post
  				@attrib:_usertag::User field to return (defaults to login ID)
  				*/
                $userfield = $element->attributes["_usertag"];
                if(!strlen($userfield))
                {
                    $userfield = "login";
                }
                if(!is_object($this->Poster))
                {
                    $user_id = $this->Get('CreatedById');
                	if (!$user_id) { // we have registred user, not guest
                		// user_id == 0 - "View Threaded" issued just after deleting reply.
                		global $bb_var_list;
                		$topic_id = $bb_var_list['top'];
                		$sql = 'SELECT PostingId FROM '.GetTablePrefix().'Posting
                				WHERE TopicId = '.$topic_id.'
                				ORDER BY CreatedOn ASC';
                		$db =& GetADODBConnection();
                		$bb_var_list['post'] = $db->GetOne($sql);
                		$this->LoadFromDatabase($bb_var_list['post']);
                	}
                	
                	$this->Poster =& $objUsers->GetItem( $this->Get('CreatedById') );
                }

                $condition = is_object($this->Poster);
                if ($element->attributes['_isactive'])
                {
                	$condition = $condition && ($this->Poster->Get('Status')==1);
                }

                if ($element->attributes["_name"]=='avatar')
                {
                	if (!is_object($objImageList)) $objImageList =& new clsImageList();
                	if ($this->Poster->Get('Status')==1)
                	{
	                	$objAvatar = $objImageList->GetImageByName($this->Poster->Get('ResourceId'), 'avatar', 1);
                	}
	                $condition = $condition && is_object($objAvatar);
                	//$condition = $condition && $this->Poster->;
                }

                if($condition)
                {
                	$e = new clsHtmlTag();
                	$e->name = $this->Poster->TagPrefix;
                	$e->attributes = $element->attributes;
                	$e->attributes["_field"] = $userfield;
                	$ret = $this->Poster->ParseObject($e);
                }
                else
                {
                	$ret = '';
                }
            break;
            case "user_posts":
            	/*
				@field:posting.user_posts
				@description:Number of posts made by the creator of this post
  				*/
                if(!is_object($this->Poster))
                {
                    $this->Poster =& $objUsers->GetItem($this->Get("CreatedById"));
                }
                $ret = $this->Poster->GetPersistantVariable("bb_posts");
                if(!strlen($ret))
                {
                    (int)$ret = $this->GetUserPosts($this->Get("CreatedById"));
                    $this->Poster->SetPersistantVariable("bb_posts",$ret);
                }
                break;

            case "posteralias":
            	/*
            	@field:posting.posteralias
            	@description: Alias used by the poster, or the login name if not set
            	*/
                $ret = $this->Get("PosterAlias");
                if(!strlen($ret))
                {
                    if(!is_object($this->Poster)) {
                        $this->Poster =& $objUsers->GetItem($this->Get("CreatedById"));
                    }

                    $ret = $this->Poster->parsetag("user_login");

                    if ($ret == '') {
                    	$ret = admin_language("lu_Guest");
                    }
                }
            break;
            case "custom":
                /*
                @field:posting.custom
                @description:Returns a custom field
  				@attrib:_customfield::field name to return
  				@attrib:_default::default value
  				*/
                $field =  $element->attributes["_customfield"];
                $default = $element->attributes["_default"];
                $ret = $this->GetCustomFieldValue($field,$default);
            break;
            case "date":
            	/*
  				@field:posting.date
  				@description:Returns the date/time the post was created
  				@attrib:_tz:bool:Convert the date to the user's local time
  				@attrib:_part::Returns part of the date.  The following options are available: month,day,year,time_24hr,time_12hr
            	*/
                $d = $this->Get('CreatedOn');
                if (!$element->GetAttributeByName('_tz')) {
                	$element->SetAttributeByName('_tz', 'auto');
                }
                $ret = $this->ParseTimeStamp($d,$element->attributes);
            break;
            case "modifieddate":
            	/*
  				@field:posting.modifieddate
  				@description:Returns the date/time the topic was last modified
  				@attrib:_tz:bool:Convert the date to the user's local time
  				@attrib:_part::Returns part of the date.  The following options are available: month,day,year,time_24hr,time_12hr
            	*/
                $d = $this->Get('Modified');
                if (!$element->GetAttributeByName('_tz')) {
                	$element->SetAttributeByName('_tz', 'auto');
                }
                $ret = $this->ParseTimeStamp($d,$element->attributes);
            break;

            case "link":
				/*
				@field:posting.link
				@description: Returns a link to the post
				@attrib:_perm::Comma-separated permission list to check, any one permission granted to the user will create the link
				@attrib:_template:tpl:Tempalte to link to if access is granted
              	@attrib:_text:lang:Language tag to display as the link text
              	@attrib:_plaintext:: Plain text to use instead of language tag
              	@attrib:image::Image URL to display in the anchor tag
				*/
                $p = $element->attributes["_perm"];
                if(strlen($p))
                {
                    $hasperm = $objSession->HasCatPermission($p);
                }
                else
                    $hasperm = TRUE;
                if($hasperm)
                {
                  $t = $element->attributes["_template"];
                  $url = $this->Link($t);
                  if($element->attributes["_fulltag"])
                  {
                      $ret = "<A $extra_attribs HREF=\"$url\">";
                      $text = $element->attributes["_text"];
                      if(!strlen($text))
                      {
                        $text = $element->attributes["_plaintext"];
                        if(!strlen($text))
                        {
                            if(strlen($element->attributes["_image"]))
                            {
                                $text = "<IMG SRC=\"".$element->attributes["_image"]."\" BORDER=\"0\">";
                            }
                        }
                        $ret .= $text."</A>";
                      }
                  }
                  else
                      $ret = $url;
                }
                else
                    $ret = "";
            break;
            case "link_edit":
            	/*
              	@field:posting.link_edit
              	@description: Returns a link to edit the post. A complete anchor tag is returned, and the tag class is set to 'topic_reply'
              	@attrib:_template:tpl:Template link should point to
              	@attrib:_text:lang:Language tag to display as the link text
              	@attrib:_plaintext:: Plain text to use instead of language tag
              	@attrib:image::Image URL to display in the anchor tag
            	*/
                //echo $this->Get("CreatedById")." User: ".$objSession->Get("PortalUserId");
                $hasperm = (($this->Get("CreatedById")==$objSession->Get("PortalUserId") &&
                             $objSession->HasCatPermission("TOPIC.REPLY.OWNER.MODIFY")) ||
                           $objSession->HasCatPermission("TOPIC.REPLY.MODIFY"));
                if($hasperm && !$this->Locked)
                {
                  $t = $element->attributes["_template"];
                  $url = $this->Link($t);
                  if($element->attributes["_fulltag"])
                  {
                      $ret = "<A $extra_attribs HREF=\"$url\">";
                      $text = $element->attributes["_text"];
                      if(!strlen($text))
                      {
                        $text = $element->attributes["_plaintext"];
                        if(!strlen($text))
                        {
                            if(strlen($element->attributes["_image"]))
                            {
                                $text = "<IMG SRC=\"".$element->attributes["_image"]."\" BORDER=\"0\">";
                            }
                        }
                        $ret .= $text."</A>";
                      }
                      else
                        $ret .= language($text)."</A>";
                  }
                  else
                      $ret = $url;
                }
                else
                    $ret = "";
            break;
            case "link_delete":
            	/*
              	@field:topic.link_delete
              	@description: Returns a link to delete the post. A complete anchor tag is returned, and the tag class is set to 'topic_reply'
              	@attrib:_template:tpl:Template link should point to
              	@attrib:_text:lang:Language tag to display as the link text
              	@attrib:_plaintext:: Plain text to use instead of language tag
              	@attrib:image::Image URL to display in the anchor tag
            	*/
                $OwnerPerm = ($objSession->HasCatPermission("TOPIC.REPLY.OWNER.DELETE") &&
                              $this->Get("CreatedById")==$objSession->Get("PortalUserId"));
                if(($objSession->HasCatPermission("TOPIC.REPLY.DELETE") || $OwnerPerm)
                   && !$this->Locked)
                {
                    $t = $element->attributes["_template"];
                    if(strlen($t))
                    {
                        $var_list_update["t"] = $t;
                    }
                    else
                        $var_list_update["t"] = $var_list["t"];
                    $text = $element->attributes["_text"];
                    $plaintext = $element->attributes["_plaintext"];
                    $bb_var_list_update["top"] = $this->Get("TopicId");
                    $bb_var_list_update["post"] = $this->Get("PostingId");
                    $ret = "<A $extra_attribs HREF=\"".HREF_Wrapper('', Array('Action' => 'bb_post_delete') ) ."\">";
                    $text = $element->attributes["_text"];
                    if(!strlen($text))
                    {
                        $text = $element->attributes["_plaintext"];
                        if(!strlen($text))
                        {
                            if(strlen($element->attributes["_image"]))
                            {
                                $text = "<IMG SRC=\"".$element->attributes["_image"]."\" BORDER=\"0\">";
                            }
                        }
                        $ret .= $text."</A>";
                    }
                    else
                      $ret .= language($text)."</A>";
                }
                else
                    $ret = "";
                unset($bb_var_list_update["top"]);
            break;
            case "link_quote":
                /*
                @field:posting.link_quote
                @description: Returns a link to reply to the post, with the post quoted in the reply
              	@attrib:_template:tpl:Template link should point to
              	@attrib:_text:lang:Language tag to display as the link text
              	@attrib:_plaintext:: Plain text to use instead of language tag
              	@attrib:image::Image URL to display in the anchor tag
              	@attrib:_fulltag:bool:If set true, returns a complete anchor tag, otherwise returns just the URL
              	*/
                $hasperm = $objSession->HasCatPermission("TOPIC.REPLY.ADD");
                if($hasperm && !$this->Locked)
                {
                  $t = $element->attributes["_template"];

                  $url = $this->Link($t);
                  if($element->attributes["_fulltag"])
                  {
                      $ret = "<A $extra_attribs HREF=\"$url\">";
                      $text = $element->attributes["_text"];
                      if(!strlen($text))
                      {
                        $text = $element->attributes["_plaintext"];
                        if(!strlen($text))
                        {
                            if(strlen($element->attributes["_image"]))
                            {
                                $text = "<IMG SRC=\"".$element->attributes["_image"]."\" BORDER=\"0\">";
                            }
                        }
                        $ret .= $text."</A>";
                      }
                      else
                          $ret .= language($text)."</A>";
                  }
                  else
                      $ret = $url;
                }
                else
                {
                    $ret = "";
                }
               break;
            case "admin_icon":
                if($element->attributes["fulltag"])
                {
                    $ret = "<IMG $extra_attribs SRC=\"".$this->StatusIcon()."\">";
                }
                else
                    $ret = $this->StatusIcon();
            break;
            case "body":
            	/*
            	@field:posting.body
            	@description:Returns the post body
            	@attrib:_parsed:bool:If true, quoted text, smileys, bbcode, and signatures are expanded out
            	*/
                if( $element->GetAttributeByName('_parsed') )
                {
                    $ret = $this->Get('PostingText');

                    $ret = str_replace( Array("[/code]\r\n","[/quote]\r\n"),Array('[/code]','[/quote]'), $ret);
                    $ret = str_replace('&quot;', '"', $ret);
                    $ret = $this->ReplaceQuote($ret,$element->attributes["_quotetemplate"]);
                    $ret = $objCensorList->CensorText($ret);
                    if(!$this->PostOption("disable_smileys"))
                    {
                        $ret = $objSmileys->ParseText($ret);
                    }

                    if(!$this->PostOption("disable_bbcode"))
                    {
                        $ret = ReplaceBBCode($ret);
                    }
                    //$ret = str_replace("\n", '<br />', $ret);
                    $ret = nl2br($ret);
                    while ( strpos($ret, '<br /><br />') !== false )
                    {
                    	$ret = str_replace('<br /><br />', '<br />', $ret);
                    }


                    if( $this->PostOption("show_sig") && $element->GetAttributeByName('_signature') > 0 )
                    {
						if(!is_object($this->Poster))
                        {
                          $this->Poster =& $objUsers->GetUser($this->Get("CreatedById"));
                        }
                        $showsig = $this->PostOption("show_sig"); // show post creator signature in this post
                        $UserSig = (int)$objSession->GetPersistantVariable("bb_signatures"); // viewing user wishes to see other signatures
                        if($showsig == 1 && $UserSig == 1)
                        {
                        	$sig = $this->Poster->GetPersistantVariable("my_signature");
							$sig = htmlspecialchars($sig,ENT_NOQUOTES);
                        	if( !$this->PostOption("disable_smileys") ) $sig = $objSmileys->ParseText($sig);
                        	if( !$this->PostOption("disable_bbcode") ) $sig = ReplaceBBCode($sig);
                        	$ret .= "<br /><br />".nl2br($sig);
                        }
                    }
                }
                else
                {
                  $ret = $this->Get("PostingText");
                }
            break;

//            default:
//              $tag = $this->TagPrefix."_".$field;
//              $ret = $this->parsetag($tag);
//              break;

             /*
            @field:posting.relevance
           	@description:Displays the post relevance in search results
  			@attrib:_displaymode:: How the relevance should be displayed<br>
  				<UL>
  					<LI>"Numerical": Show the decimal value
  				    <LI>"Bar": Show the HTML representing the relevance. Returns two HTML cells &lg;td&lt; with specified background colors
  				    <LI>"Graphical":Show image representing the relevance
  				</UL>
			@attrib:_onimage::Zero relevance image shown in graphical display mode. Also used as prefix to build other images (i.e. prefix+"_"+percentage+".file_extension"
			@attrib:_OffBackGroundColor::Off background color of HTML cell in bar display mode
			@attrib:_OnBackGroundColor::On background color of HTML cell in bar display mode
            */

           }
           if(!strlen($ret))
           {
           	  $ret = parent::ParseObject($element);
           }
        }
        else
        {
            $fcall = $element->Execute();
            if(substr($fcall,0,8)=="{Unknown")
            {
              $ret = $this->parsetag($element->name);
            }
            else
                $ret = $fcall;
        }
        return $ret;
    }

/*
    function parsetag($tag)
    {
        global $objConfig, $objUsers, $m_var_list_update, $bb_var_list_update, $var_list_update, $objSession, $bb_var_list, $bbperm;
        if(is_object($tag))
        {
            $tagname = $tag->name;
        }
        else
            $tagname = $tag;
        switch($tagname)
        {
		    case "posting_id":
                return $this->Get("PostingId");
                break;
            case "posting_resource_id":
                return $this->Get("ResourceId");
                break;
		    case "posting_ip":
                return $this->Get("IPAddress");
                break;
		    case "posting_alias":
                return $this->Get("PosterAlias");
                break;
		    case "posting_text":
                return inp_unescape($this->Get("PostingText"));
                break;
		    case "posting_date":
				if($this->Get("CreatedOn")<=0)
					return "";
				return LangDate($this->Get("CreatedOn"), 0, true);
           		break;
		   	case "posting_modified":
                if($this->Get("ModifiedOn")<=0)
					return "";
				return LangDate($this->Get("ModifiedOn"), 0, true);
          		break;
		    case "posting_topicid":
                return $this->Get("TopicId");
                break;
		    case "posting_reply_quote_link":
                $bb_var_list_update["post"]=$this->Get("PostingId");
                $var_list_update["t"]="inbulletin/bb_post_edit_reply_form";
                $ret = HREF_Wrapper();
                unset($bb_var_list_update["post"],$var_list_update["t"]);
                return $ret;
                break;
		    case "posting_edit_link":
                $bb_var_list_update["post"]=$this->Get("PostingId");
                $var_list_update["t"]="inbulletin/bb_post_edit_reply_form";
                $ret = HREF_Wrapper('', Array('edit' => 'yes') );
                unset($bb_var_list_update["post"],$var_list_update["t"]);
                return $ret;
                break;
		    case "cell_back":
                if ($bb_var_list_update["post_cell"]==$objConfig->Get("Post_Background1"))
                {
                    $bb_var_list_update["post_cell"]=$objConfig->Get("Post_Background2");
                    return $objConfig->Get("Post_Background2");
                }
                else
                {
                    $bb_var_list_update["post_cell"]=$objConfig->Get("Post_Background1");
                    return $objConfig->Get("Post_Background1");
                }
                break;

            default:
                return $tag;
			    break;
        }
    }
*/
}

class _clsPostingList extends clsItemCollection
{
    var $TopicID;
    var $Page;

	function _clsPostingList()
	{
       global $bb_var_list;

       $this->clsItemCollection();
	   $this->TopicID=-1;
       $this->classname = "clsPosting";
       $this->SourceTable = GetTablePrefix()."Posting";
       $this->BasePermission="TOPIC";
       $this->Page = $bb_var_list["pp"];
	}

    function CurrentPostID()
    {
        global $bb_var_list;
        $p = (int)$bb_var_list["post"];
        if($p==0)
        {
            $sql = "SELECT PostingId FROM ".$this->SourceTable." WHERE TopicId=".$this->TopicID;
            $sql .=" AND ReplyTo=0 ORDER BY CreatedOn ASC LIMIT 1";
            $rs = $this->adodbConnection->Execute($sql);
            if($rs && !$rs->EOF)
                $bb_var_list["post"] = $rs->fields["PostingId"];
        }
        return (int)$bb_var_list["post"];
    }

    function &GetCurrentPost()
    {
        $id = $this->CurrentPostID();
        $p = $this->GetItem($id);
        return $p;
    }

    function Query_Posting($whereClause,$orderByClause="", $limit=NULL)
    {
	  global $Errors, $objSession;

      $resultSet = array();

      $sql = "SELECT * FROM ".$this->SourceTable." ";

      if(isset($whereClause))
        $sql = sprintf('%s WHERE %s',$sql,$whereClause);

      if(isset($orderByClause))
        $sql = sprintf('%s ORDER BY %s',$sql,$orderByClause);
      if(strlen(trim($limit))>0)
          $sql .= " ".$limit;

      if($objSession->HasSystemPermission("DEBUG.LIST"))
          echo htmlentities($sql,ENT_NOQUOTES)."<br>\n";

      $this->Query_Item($sql);

      return $this->Items;
    }

    function DeleteTopicPosts($TopicId)
    {
        global $objTopicList;
        $this->Clear();
        $topic = $objTopicList->GetItem($TopicId);
        $sql = "SELECT * FROM ".$this->SourceTable." WHERE TopicId=".$TopicId;
        $this->Query_Item($sql);
        $count = $this->NumItems();

        if( is_object($topic) ) $topic->ClearCacheData();
        DeleteTagCache("m_itemcount","Post%");

        if($this->NumItems()>0)
        {
        	foreach($this->Items as $p)
        	{
        		$p->Delete();
        	}
        }
        $this->Clear();
    }


    function DoGlobalCount($attribs)
    {
  	  global $objCountCache, $objTopicList;

 	  $cc = $objCountCache->GetValue(0,30,$objTopicList->CacheListExtraId("_"),(int)getArrayValue($attribs,'_today'), 3600);
 	  $cc = null;
  	  if(!is_numeric($cc))
  	  {
  	  	$sql = $objTopicList->SqlGlobalCount($attribs);
  	  	$rs = $this->adodbConnection->Execute($sql);
  	  	$ret = ($rs && !$rs->EOF) ? $rs->fields['CachedVal'] : '0';
  	  	$objCountCache->SetValue(0,30,$objTopicList->CacheListExtraId("_"),(int)getArrayValue($attribs,'_today'),$ret);
  	  }
  	  else
  	    $ret = $cc;

  	    //echo "DoGlobalCount Posting: $ret<br>";
  	  return $ret;
    }

    function CategoryCount($attribs)
    {
  	 global $objCatList, $objCountCache;

  	 $cat = $attribs["_catid"];
     if(!is_numeric($cat))
     {
        $cat = $objCatList->CurrentCategoryID();
     }
     if((int)$cat>0)
        $c = $objCatList->GetCategory($cat);

     $cc = $objCountCache->GetValue(1,30,$cat,0,3600);
     //print_pre($attribs);
     if(is_numeric($cc) && $attribs["_forceupdate"] != 1)
     {
     	return $cc;
     }

  	 $CatTable = GetTablePrefix()."CategoryItems";
     //$t = $this->SourceTable;
     $t = GetTablePrefix()."Topic";
     $p = $this->SourceTable;

     $sql = "SELECT (SUM(Posts)-COUNT(TopicId)) as MyCount FROM $t ";
     $sql .=" INNER JOIN $CatTable ON ($CatTable.ItemResourceId=$t.ResourceId) ";
     if($attribs["_subcats"])
     {
     	$ctable = $objCatList->SourceTable;
     	$sql .= "INNER JOIN $ctable ON ($CatTable.CategoryId=$ctable.CategoryId) ";
     	$sql .= "WHERE (ParentPath LIKE '".$c->Get("ParentPath")."%' ";
     	if(!$attribs["_countcurrent"])
     	{
     	  $sql .=" AND $ctable.CategoryId != $cat) ";
     	}
     	else
     	  $sql .=") ";
     }
     else
       $sql .="WHERE ($CatTable.CategoryId=".$cat." AND $t.Status=1) ";

      if($attribs["_today"])
      {
        $today = adodb_mktime(0,0,0,adodb_date("m"),adodb_date("d"),adodb_date("Y"));
        $sql .= "AND ($t.CreatedOn>=$today) ";
      }
	  //echo "Cat:".$sql."<br>\n";
	  $rs = $this->adodbConnection->Execute($sql);
	  $ret = "";
	  if($rs && !$rs->EOF)
	  {
	    $ret = (int)$rs->fields["MyCount"];

	  }
	  if(is_numeric($ret))
	    $objCountCache->SetValue(1,30,$cat,0,$ret);
  	  return $ret;
    }

    function LoadTopicPosts()
    {
      global $objConfig, $objTopicList;

      $o="";  //prepare output

      $this->Clear();
      if($this->Page<1)
          $this->Page=1;
	  if(is_numeric($objConfig->Get("Perpage_Postings")))
	  {
	  	$Start = ($this->Page-1)*$objConfig->Get("Perpage_Postings");
	  	$limit = "LIMIT ".$Start.",".$objConfig->Get("Perpage_Postings");
	  }
	  else
	  	$limit = NULL;

      $where = "TopicId=".$this->TopicID;
      $this->QueryItemCount=TableCount(GetTablePrefix()."Posting",$where,0);
      $this->Query_Posting($where,"CreatedOn ASC",$limit);
      $t = $objTopicList->GetItem($this->TopicID);
      if($t->Get("TopicType")==0)
      {
          for($x=0;$x<$this->NumItems();$x++)
              $this->Items[$x]->Locked=TRUE;
      }
      return $this->Items;
    }    
    
	function GetPageLinkList($dest_template = null, $page = '', $PagesToList = 10, $HideEmpty = true, $extra_attributes = '')
	{
		global $objConfig, $bb_var_list_update, $var_list_update, $bb_var_list, $var_list;
        
        $PerPage = $objConfig->Get("Perpage_Postings");
        if ($PerPage < 1) $PerPage = 20;
          
        $NumPages = ceil( $this->GetNumPages($PerPage) );
		$var_list_update['t'] = isset($dest_template) && $dest_template ? $dest_template : $var_list['t'];

        $o = '';
        if ($this->Page > $NumPages) $this->Page = $NumPages;

        if ($NumPages == 1 && $HideEmpty) return '';

        $StartPage = (int)$this->Page - ($PagesToList / 2);
        if ($StartPage < 1) $StartPage = 1;
        
        $EndPage = $StartPage + ($PagesToList - 1);                
        if ($EndPage > $NumPages)
        {        
            $EndPage = $NumPages;
            $StartPage = $EndPage-($PagesToList-1);
            if ($StartPage < 1) $StartPage = 1;
        }

        $o = '';
        if ($StartPage > 1)
        {
			$bb_var_list_update['pp'] = $this->Page - $PagesToList;
			$bb_var_list_update['top'] = $this->TopicID;
			$prev_url = HREF_Wrapper();
			$o .= '<a '.$extra_attributes.' href="'.$prev_url.'">&lt;&lt;</a>';
        }
        
        for ($p = $StartPage; $p <= $EndPage; $p++)
        {
            if ($p != $this->Page)
            {
                $bb_var_list_update['pp'] = $p;
                $bb_var_list_update['top'] = $this->TopicID;
                $href = HREF_Wrapper();
                $o .= ' <a '.$extra_attributes.' href="'.$href.'">'.$p.'</a> ';
            }
            else
            {
                $o .= $p;
            }
        }
        if ($EndPage < $NumPages && $EndPage > 0)
        {
			$bb_var_list_update['pp'] = $this->Page + $PagesToList;
			$bb_var_list_update['top'] = $this->TopicID;
			$next_url = HREF_Wrapper();
			$o .= '<a '.$extra_attributes.' href="'.$next_url.'"> &gt;&gt;</a>';
        }
                                       
        unset($bb_var_list_update["pp"],$bb_var_list_update["top"],$var_list_update["t"] );
        return $o;
    }

    function ResetCache($CategoryId)
    {
    	global $objCountCache;
    	if( $objCountCache->NumItems() == 0 )
    	{
    		$objCountCache->Query_Item('SELECT * FROM '.$objCountCache->SourceTable);
    	}

    	$db =& GetADODBConnection();
    	$sql = 'SELECT ParentPath FROM '.GetTablePrefix().'Category WHERE CategoryId = '.$CategoryId;
    	$parents = $db->GetOne($sql);
    	$parents = substr($parents,1,strlen($parents)-2);
    	$parents = explode('|',$parents);
    	foreach($parents as $ParentCategoryId)
    	{
    		$objCountCache->DeleteValue(0, 30, $ParentCategoryId, 0);	// total topic count
    		$objCountCache->DeleteValue(0, 30, $ParentCategoryId, 1);	// total
    	}
    }
}/*clsPostingList*/
?>