<?php

define('TYPE_NEWS', 2);
define('Archived', 3);

RegisterPrefix("clsNews","article","in-news/news.php");

class clsNews extends clsCatItem
{
    function clsNews($NewsId=NULL)
    {
        global $objSession;

        $this->clsCatItem(TRUE);
        $this->tablename=GetTablePrefix()."News";
        $this->type=TYPE_NEWS;
        $this->Prefix = 'n';
        $this->BasePermission="NEWS";
        $this->id_field = "NewsId";
        $this->TagPrefix="article";
        $this->TitleField = 'Title';
        if(isset($NewsId))
            $this->LoadFromDatabase($NewsId);
        if($objSession->HasSystemPermission("DEBUG.ITEM"))
        {
            $this->SetDebugLevel(1);
        }

        /* keyword highlighting */
        $this->OpenTagVar = "News_Highlight_OpenTag";
        $this->CloseTagVar = "News_Highlight_CloseTag";

    }


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

        $dataValid = true;
        if(!strlen($this->Get("Title")))
        {
            $Errors->AddError("error.fieldIsRequired",'Name',"","",get_class($this),"Validate");
            $dataValid = false;
        }

        if(!(int)($this->Get("CreatedOn")))
        {
            $Errors->AddError("error.fieldIsRequired",'CreatedOn',"","",get_class($this),"Validate");
            $dataValid = false;
        }
        return $dataValid;
    }


    function SetNewItem()
    {
        global $objConfig;

        $value = $this->Get("CreatedOn");

        $cutoff = adodb_date("U") - ($objConfig->Get("News_NewDays") * 86400);
        $this->IsNew = FALSE;
        if($value>$cutoff)
            $this->IsNew = TRUE;
        return $this->IsNew;
    }

    function SetPopItem()
    {
        global $objConfig, $objArticleList;

        $cutoff = $objArticleList->GetPopValue();
        $this->IsPop = FALSE;
        if($cutoff>0)
        {
          if($this->Get('CachedRating') >= $cutoff
          		&& $this->Get('CachedVotesQty') >= $objConfig->Get('News_MinPopVotes'))
          {
            $this->IsPop = TRUE;
          }
        }
        return $this->IsPop;
    }

    function SetHotItem()
    {
        global $objConfig, $objArticleList;

        $this->IsHot = FALSE;
        $cutoff = $objArticleList->GetHotValue();
        if($cutoff>0)
        {
            if($this->Get("Hits")>=$cutoff)
              $this->IsHot = TRUE;
        }
        return $this->IsHot;
    }

	function Approve()
	{
      if($this->Get("Status")==-2)
      {
          $this->SendUserEventMail("ARTICLE.MODIFY.APPROVE",$this->Get("CreatedById"));
          $this->SendAdminEventMail("ARTICLE.MODIFY.APPROVE");
      }
      else
      {
        $this->SendUserEventMail("ARTICLE.APPROVE",$this->Get("CreatedById"));
        $this->SendAdminEventMail("ARTICLE.APPROVE");
      }
	  $this->Set("Status", 1);
	  $this->Update();
	}

    function Deny()
    {
        if($this->Get("Status")==-2)
        {
            $this->SendUserEventMail("ARTICLE.DENY.PENDING",$this->Get("CreatedById"));
            $this->SendAdminEventMail("ARTICLE.DENY.PENDING");
        }
        else
        {
          $this->SendUserEventMail("ARTICLE.DENY",$this->Get("CreatedById"));
          $this->SendAdminEventMail("ARTICLE.DENY");
        }
        $this->Set("Status", 0);
        $this->Update();
    }

    function LoadFromDatabase($Id)
    {
        global $Errors;

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

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

		$data = $result->fields;
		if(is_array($data))
            $this->SetFromArray($data);
        $this->Clean();
    }
    function LoadFromResourceId($Id)
    {
        global $objSession, $Errors;
        if(!isset($Id))
        {
            $Errors->AddError("error.AppError",NULL,'Internal error: LoadFromDatabase id',"",get_class($this),"LoadFromResourceId");
            return false;
        }
        $sql = sprintf("SELECT * FROM ".$this->tablename." WHERE ResourceId = '%s'",$Id);
        $result = $this->adodbConnection->Execute($sql);
        if ($result === false)
        {
            $Errors->AddError("error.DatabaseError",NULL,$adodbConnection->ErrorMsg(),"",get_class($this),"LoadFromResourceId");
            return false;
        }
        $data = $result->fields;
        if(is_array($data))
        {
            $this->SetFromArray($data);
            $this->Clean();
        }
        return TRUE;
    }

	function GetGroupIcon()
	{
	  $ret = "groupicons/".$this->m_GroupId.".gif";
	  return $ret;
	}

    function StatusIcon()
    {
       global $rootURL;

       $ret = $rootURL."/in-news/admin/images/";

       switch($this->Get("Status"))
       {
         case STATUS_DISABLED:
           $ret .= "icon16_article_disabled.gif";
           break;
         case STATUS_PENDING:
           $ret .= "icon16_article_pending.gif";
           break;
         case STATUS_ACTIVE:
           $img = "icon16_article.gif";
           if($this->IsPopItem())
               $img = "icon16_article_pop.gif";
           if($this->IsHotItem())
               $img = "icon16_article_hot.gif";
           if($this->IsNewItem())
               $img = "icon16_article_new.gif";
           if($this->Is("EditorsPick"))
               $img = "icon16_article_pick.gif";
           $ret .= $img;
           break;
       }
       return $ret;
    }

    function ItemURL($Template=NULL,$SetCat=FALSE,$Action=NULL)
    {
		global $var_list_update,$var_list,$n_var_list_update,$m_var_list_update;

		$url_params = Array();
		$var_list_update["t"] = $Template ? $Template : $var_list["t"];

//        if($SetCat)
//        {
           $cat = $this->Get("CategoryId");
           if( !is_numeric($cat) ) $cat = $this->GetPrimaryCategory();
           $m_var_list_update["cat"] = $cat;
//        }

        $n_var_list_update["id"] = $this->Get("NewsId");

        if( isset($Action) && $Action ) $url_params['Action'] = $Action;

        $ret = HREF_Wrapper('', $url_params);
        unset($n_var_list_update["id"], $var_list_update["t"],$m_var_list_update["cat"]);
        return $ret;
    }

    function ParseObject($element)
    {
        global $objConfig, $objCatList, $var_list_update, $var_list, $n_var_list_update, $m_var_list_update, $objSession, $objUsers;

        $extra_attribs = ExtraAttributes($element->attributes);
        if(strtolower($element->name)==$this->TagPrefix)
        {
            $field = strtolower($element->attributes["_field"]);
            switch($field)
            {
            case "excerpt":
               /*
               @field:article.excerpt
               @description Returns the artcle excerpt
               */
               $ret = $this->HighlightField("Excerpt");
               break;
            case "body":
            	/*
            	@field:article.body
            	@description:The main body of the article
            	@attrib:_parsed:bool:If set, HTML and In-Portal tags in the body are preserved, otherwise they are escaped
            	*/
            	$this->Increment("Hits", true);
                $parsed = $element->attributes["_parsed"];
                if($parsed)
                {
                    $body = inp_unescape($this->Get("Body"));
                    $body = $this->HighlightText($body);
                    if($this->Get("TextFormat")!=1)
                    {
                    	$body = nl2br($body);
                    }
                    $ret = $this->ParseTemplateText($body);
                }
                else
                	$ret = inp_unescape($this->Get("Body"));
                $ret = $this->HighlightText($ret);
                break;
            case "title":
            	/*
            	@field:article.title
            	@description: Article Title (headline)
            	*/
                $ret =  $this->HighlightField("Title");
            break;
            case "author":
            	/*
            	@field:article.author
            	@description:text by-line of the article
            	*/
                $ret =  $this->HighlightField("Author");
            break;
            case "createdby":
				/*
				@field:article.createdby
				@description:parse a user field of the user that created the article
  				@attrib:_usertag::User field to return (defaults to login ID)
  				*/
                $field = $element->attributes["_usertag"];
                if(!strlen($field))
                {
                    $field = "user_login";
                }

                $userId = $this->Get("CreatedById");
                if (!empty($userId) && ($userId > 0))
                {
	                $u =& $objUsers->GetItem($userId);
	                if (is_object($u))
	                {
	                	$ret = $u->parsetag($field);
	                }
                }
	            else
	            	$ret = " ";
            break;
            case "date":
            	/*
  				@field:article.date
  				@description:Returns the date/time the article 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");
                $ret = $this->ParseTimeStamp($d,$element->attributes);
            break;
            case "modified":
                /*
 			    @field:article.modified
 			    @description:Returns the date/time the article 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($d<=0)
                  $d = $this->Get("CreatedOn");

                $ret = $this->ParseTimeStamp($d,$element->attributes);
            break;

            case "enddate":
                /*
 			    @field:article.enddate
 			    @description:Returns the date/time the article is to be archived
  			    @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("EndOn");
                $ret = $this->ParseTimeStamp($d,$element->attributes);
            break;
			/*
                @field:article.startdate
 			    @description:Returns the date/time the article is to begin being displayed
  			    @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
			*/
            case "startdate":
                $d = $this->Get("StartDate");
                $ret = $this->ParseTimeStamp($d,$element->attributes);
            break;
            case "add_favorite_link":
                /*
              	@field:article.add_favorite_link
              	@description:Returns a URL to add this article to the user's favorites
  				@attrib:_template:tpl:Template URL should point to
  				*/
      			if($objSession->HasCatPermission("FAVORITES"))
      			{
                	$t = $element->attributes["_template"];
                	if(!strlen($t))
                    	$t = $var_list["t"];
                	$ret = $this->ItemURL($t,FALSE,"n_add_favorite");
      			}
      			else
      			{
      				$t = $element->attributes["_errortemplate"];
      				if(!strlen($t))
      				  $t = "favorite_error.tpl";
      				$ret = $this->ItemURL($t,FALSE,"");
      			}
            break;
            case "del_favorite_link":
                /*
              	@field:article.del_favorite_link
              	@description:Returns a URL to remove this article from the user's favorites
  				@attrib:_template:tpl:Template URL should point to
  				*/
      			if($objSession->HasCatPermission("FAVORITES"))
      			{
                  $t = $element->attributes["_template"];
                  if(!strlen($t))
                    $t = $var_list["t"];
                  $ret = $this->ItemURL($t,FALSE,"n_del_favorite");
      			}
      			else
      			{
      		      	$t = $element->attributes["_errortemplate"];
      				if(!strlen($t))
      				  $t = "favorite_error.tpl";
      				$ret = $this->ItemURL($t,FALSE,"");
      			}
            break;
			/*
				@field:article.favorite_toggle
				@description: Returns a link to set or reset the favorite flag for the current user
				@attrib: _template:tpl:Template to link to if user has the FAVORITES permission (defaults to current template)
				@attrib: _denytemplate:tpl: Template to link to if user does not have favorites permission (ie Guest)  Defaults to current template
				@attrib: _addlabel:lang:Language tag to display if link is to add favorite
				@attrib: _addimage::Image url to include in link if adding favorite
				@attrib: _dellabel:lang:Language tag to display if item is already a favorite
				@attrib: _delimage::Image url to include in link if removing the favorite
			*/
            case "favorite_toggle":
                	$catid = $this->GetPrimaryCategory();
            		$t = $element->attributes["_template"];
                	if(!strlen($t))
                    	$t = $var_list["t"];
      				if($objSession->HasCatPermission('FAVORITES', $catid))
      				{
                		if(!$this->IsFavorite($objSession->Get("PortalUserId"), $this->GetPrimaryCategory()))
                		{
                			$action = "n_add_favorite";
                			$label = $element->attributes["_addlabel"];
                		}
                		else
                		{
                  			$action = "n_del_favorite";
                  			$label = $element->attributes["_dellabel"];
                		}
      				}
      				else
      				{
      				  $action="";
      				  $label = $element->attributes["_addlabel"];
      				  $t = $element->attributes["_errortemplate"];
      				  if(!strlen($t))
      				  	$t = "favorite_error.tpl";
      				}
                 	$ret = "<A ".$extra_attribs." HREF=\"".$this->ItemURL($t,FALSE,$action)."\">".language($label)."</A>";
            break;

            /*
          	@field:article.hits
           	@description:Returns number of hits for item
			*/
            case "hits":
                $ret=round($this->Get("Hits"));
            break;


/*
  				@field:article.link
  				@description:Returns a URL setting the link to the article
  				@attrib:_template:tpl:Template URL should point to
*/
/*
  				@field:article.cat_link
            	@description:Returns a URL setting the article to the current article and the article's category to the current category
  				@attrib:_template:tpl:Template URL should point to
*/
/*
            	@field:article.category
            	@description:Return a category field from the article's category
            	@attrib:_cattag::Category field to parse
*/
/*
				@field:article.reviews
            	@description:Return the number of reviews for the article
				@attrib:_today:bool:Count reviews added today only
*/
/*
				@field:article.new
 				@description:returns text if article's status is "new"
  				@attrib:_label:lang: Text to return if status is new
*/
/*
  				@field:article.pop
 				@description:returns text if article's status is "popular"
  				@attrib:_label:lang: Text to return if status is popular
*/
/*
  				@field:article.hot
 				@description:returns text if article's status is "hot"
  				@attrib:_label:lang: Text to return if status is "hot"
*/
/*
  				@field:article.pick
 				@description:returns text if article's status is "hot"
  				@attrib:_label:lang: Text to return if status is "hot"
*/
/*
            	  @field:article.rating
            	  @description:Displays the article rating
  				  @attrib:_displaymode:: How the rating should be displayed<br>
  				    	<UL>
  				    	  <LI>"Numerical": Show the decimal value
  				    	  <LI>"Text": Show the text version
  				    	  <LI>"Graphical":Show images representing the rating
  				    	</UL>
				  @attrib:_onimage::on image tick shown in graphical display mode
				  @attrib:_offimage::off image tick shown in graphical display mode
				  @attrib:_separator::In graphical display mode, this html is placed between each tick image
*/
/*
                @field:article.custom
                @description:Returns a custom field
  				@attrib:_customfield::field name to return
  				@attrib:_default::default value
*/
/*
             	@field:article.fullpath
            	@description:The full category path of the item
*/
/*
	            @field:article.relevance
	           	@description:Displays the article 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(!isset($ret) || !strlen($ret))
              $ret = parent::ParseObject($element);
        }
        else
        {
            $ret = $this->parsetag($element->name);
        }
        return $ret;
    }


    function parsetag($tag)
    {
        global $n_var_list, $var_list, $n_var_list_update, $var_list_update, $objConfig;

        $tagname = $tag;

        switch($tagname)
        {
	        case "article_category":
                return $this->Get("CategoryId");
                break;
            case "article_id":
                return $this->Get("NewsId");
                break;
	        case "article_title":
                return inp_unescape($this->Get("Title"));
                break;
	        case "article_excerpt":
                return inp_textarea_unescape($this->Get("Excerpt"));
                break;
		    case "article_author":
                return $this->Get("Author");
                break;
		    case "article_body":
                $ret = inp_unescape($this->Get("Body"));
                //$ret = $this->ParseTemplateText($body);
                return $ret;
                break;
		    case "article_footer":
                return inp_textarea_unescape($this->Get("Footer"));
                break;
            case "article_priority":
                return (int)$this->Get("Priority");
                break;
            case "article_date":
		    	if ($this->Get('CreatedOn') <= 0) {
					return '';
		    	}
                return LangDate($this->Get('CreatedOn'), 0, true);
                break;

		    case "article_enddate":
		    	if ($this->Get('EndOn') <= 0) {
					return '';
		    	}
                return LangDate($this->Get('EndOn'), 0, true);
                break;

   	        case "article_startdate":
		    	if ($this->Get('StartDate') <= 0) {
					return '';
		    	}
                return LangDate($this->Get('StartDate'), 0, true);
                break;

		    case "article_hits":
                return $this->Get("Hits");
                break;
			case "article_views":
                return $this->Get("Hits");
                break;
		    case "article_rating":
                return round($this->Get("CachedRating"),1);
                break;
            case "article_rating_img":
                return "inlink/rating/".RatingImage($this->Get("CachedRating")).".gif";
                break;
		    case "article_votes":
                return $this->Get("CachedVotesQty");
                break;
            case "article_pick":
                if ($this->Is("EditorsPick"))
                    return "pick";
                break;

            case "article_new":
                if($this->IsNewItem())
                    return "new";
                break;
            case "article_pop":
                if($this->IsPopItem())
                    return "pop";
                break;
            case "article_hot":
                if($this->IsHotItem())
                    return "new";
                break;

            case "article_admin_icon":
                return $this->StatusIcon();
                break;

		    case "article_email_action":
                $var_list_update["t"] = "window_close";
                $n_var_list_update["id"] = $this->Get("NewsId");
                $ret = HREF_Wrapper();
                unset($var_list_update["t"],$n_var_list_update["id"]);
                return $ret;
                break;
		    case "article_group_icon":
                return $this->GetGroupIcon();
                break;
		    case "article_resourceid":
                return $this->Get("ResourceId");
                break;
			case "article_rating_txt":
				return RatingText($this->Get("CachedRating"));
				break;
            default:
               return "Undefined:$tagname";
           break;
        }
    }

    function Update($UpdatedBy=NULL,$modificationDate = null)
    {
    	DeleteModuleTagCache('innews');
    	return parent::Update($UpdatedBy, $modificationDate);
    }

    function Delete ()
    {
    	DeleteModuleTagCache('innews');
    	return parent::Delete();
    }

    function Create ()
    {
    	DeleteModuleTagCache('innews');
    	return parent::Create();
    }
} /*clsNews*/

class _clsNewsList extends clsCatItemList
{
    function _clsNewsList()
    {
      $this->clsCatItemList();
      $this->Prefix = 'n';
      $this->classname="clsNews";

      $this->SetTable('live', GetTablePrefix().'News');
      $this->AdminSearchFields = array("Title","Excerpt","Body","Author");
      $this->BasePermission="NEWS";

      $this->Page = 1;
      $this->PerPageVar = "Perpage_News";
      $this->PageEnvar = "n_var_list_update";
      $this->PageEnvarIndex = 'p';

	  $this->PerPageVarLong = "Perpage_News";
      $this->PerPageShortVar = "Perpage_News_Short";
      $this->AddSortField("News_SortField","News_SortOrder");
      $this->AddSortField("News_SortField2","News_SortOrder2");
      $this->ItemType = TYPE_NEWS;
    }

    function GetCountSQL($PermName,$CatId=NULL, $GroupId=NULL, $AdditonalWhere="")
    {
    	$sql = parent::GetCountSQL($PermName,$CatId,$GroupId,$AdditonalWhere);

    	if (!IsAdmin())
    	{
    		$sql .= ' AND ('.$this->SourceTable.'.Archived = 0)';
    	}

    	return $sql;
    }

	function SaveNewPage()
    {
		global $n_var_list;
		$n_var_list["p"] = $this->Page;
	}

    function GetCurrentArticle()
    {
      global $objCatList, $n_var_list;

      if(!$this->CurrentItem)
      {
        $id = $n_var_list["id"];
        if($id)
        {
            $this->SetCurrentItem($id);
        }
        else
        {
          $CurrentCat = $objCatList->CurrentCategoryID();
          $sql = "SELECT NewsId FROM ".$this->tablename." WHERE LeadCatStory=1 AND CategoryId=" . $CurrentCat;
          $result = $this->adodbConnection->Execute($sql);
          if ($result && !$result->EOF)
          {
             $this->SetCurrentItem($result->fields["NewsId"]);
          }
        }
      }
      return $this->GetCurrentItem();
    }

    function SetCurrentItem()
    {
        global $n_var_list;
        parent::SetCurrentItem($n_var_list["id"]);
    }

    function CurrentArticleID()
    {
       global $n_var_list;

       return (int)$n_var_list["id"];
    }

    function LoadArticles($whereClause, $orderBy, $JoinCats=TRUE,$SkipCount=FALSE,$fix_method='set_first')
    {
        global $objConfig;

        $this->Clear();

       if(!$SkipCount)
           $this->QueryItemCount=TableCount($this->SourceTable,$whereClause,$JoinCats);

        return $this->Query_List($whereClause, $orderBy,$JoinCats,$fix_method);
    }

    function CountPending()
    {
        return TableCount($this->SourceTable,"Status=".STATUS_PENDING,0);
    }

    function GetAdminPageLinkList($url)
    {
        global $objConfig, $n_var_list_update, $var_list_update, $var_list;

        if(strlen($this->PerPageVar)==0)
            $this->PerPageVar = "Perpage_News";

        $PerPage = $objConfig->Get($this->PerPageVar);
        if($PerPage<1)
            $PerPage=20;

        $NumPages = ceil($this->GetNumPages($PerPage));

        //echo $this->CurrentPage." of ".$NumPages." Pages";

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

        $StartPage = $this->Page - 5;
        if($StartPage<1)
            $StartPage=1;
        $EndPage = $StartPage+9;
        if($EndPage>$NumPages)
        {
            $EndPage = $NumPages;
            $StartPage = $EndPage-9;
            if($StartPage<1)
                $StartPage=1;
        }

        $o = "";

        if($StartPage>1)
        {
          $n_var_list_update["p"] = $this->Page-10;
          $prev_url = $url."?env=".BuildEnv();
           $o .= "<A HREF=\"$prev_url\">&lt;&lt;</A>";
        }


        for($p=$StartPage;$p<=$EndPage;$p++)
        {
            if($p!=$this->Page)
            {
                $n_var_list_update["p"]=$p;
                $href = $url."?env=".BuildEnv();
                $o .= " <A HREF=\"$href\" class=\"NAV_URL\">$p</A> ";
            }
            else
            {
                $o .= "<SPAN class=\"CURRENT_PAGE\">$p</SPAN>";
            }
        }
        if($EndPage<$NumPages)
        {
          $n_var_list_update["p"]=$this->Page+10;
          $next_url = $url."?env=".BuildEnv();
          $o .= "<A HREF=\"$next_url\"> &gt;&gt;</A>";
        }
        unset($n_var_list_update["p"]);
        return $o;
    }

    function &Add_News($CategoryId, $Title, $Excerpt, $Author, $Body, $CreatedOn, $EndOn, $StartDate,
                      $Status, $EditorsPick, $New=2, $Pop=2, $Hot=2, $Rating=0, $Votes=0, $Hits=0, $LeadStory=0,
                      $LeadCatStory=0,$Priority=0,$CreatedBy="",$Format=0, $auto_filename = 1, $filename = '')
    {
        global $objSession;

        if($CreatedBy == '') $CreatedBy = $objSession->Get("PortalUserId");

        $n = new clsNews(NULL);
        $filename = $n->StripDisallowed($filename);

        $n->tablename = $this->SourceTable;
        $n->Set(array("Title", "Excerpt", "Author", "Body", "CreatedOn", "EndOn", "StartDate",
                      "Status", "EditorsPick", "NewItem","PopItem","HotItem","CachedRating","CachedVotesQty","Hits",
                      "LeadStory", "LeadCatStory","Priority","CreatedById","TextFormat", 'AutomaticFilename', 'Filename'),
                array($Title, $Excerpt, $Author, $Body, $CreatedOn, $EndOn, $StartDate,
                      $Status, $EditorsPick, $New, $Pop, $Hot, $Rating, $Votes, $Hits,
                      $LeadStory, $LeadCatStory,$Priority,$CreatedBy,$Format, $auto_filename, $filename) );
        $n->Create();
        $ci_table = $objSession->GetEditTable( GetTablePrefix().'CategoryItems' );
      	$n->AddToCategory($CategoryId, $ci_table, 1);

        $n->SendUserEventMail("ARTICLE.ADD",$CreatedBy);
        $n->SendAdminEventMail("ARTICLE.ADD");
        return $n;
    }

    function &Edit_News($NewsId, $Title, $Excerpt, $Author, $Body, $CreatedOn, $EndOn, $StartDate,
                       $Status, $EditorsPick, $New, $Pop, $Hot, $Rating, $Votes, $Hits,$CreatedBy,$LeadStory=0,
                       $LeadCatStory=0, $Priority=0, $Format=0, $auto_filename = 1, $filename = '')
    {
        global $objSession;

        $n = $this->GetItem($NewsId);
        $filename = $n->StripDisallowed($filename);

        $n->Set(array("Title", "Excerpt", "Author", "Body", "CreatedOn", "EndOn", "StartDate",
                      "Status", "EditorsPick", "NewItem","PopItem","HotItem","CachedRating","CachedVotesQty",
                      "Hits", "LeadStory", "LeadCatStory", "Priority","CreatedById","TextFormat",
                      'AutomaticFilename', 'Filename'),
                array($Title, $Excerpt, $Author, $Body, $CreatedOn, $EndOn, $StartDate,
                      $Status, $EditorsPick, $New, $Pop, $Hot, $Rating, $Votes, $Hits,
                      $LeadStory, $LeadCatStory, $Priority,$CreatedBy,$Format, $auto_filename, $filename) );
        $n->Update();
        $n->SendUserEventMail("ARTICLE.MODIFY",$objSession->Get("PortalUserId"));
        $n->SendAdminEventMail("ARTICLE.MODIFY");
        return $n;
    }

  function GetJoinedSQL($PermName, $CatId=NULL, $AdditionalWhere="", $LoadOnlyPrimary = true)
  {
  	$sql = parent::GetJoinedSQL($PermName,$CatId,$AdditionalWhere, $LoadOnlyPrimary);
  	$today = adodb_date("U");
  	$t = $this->SourceTable;
  	$where ="(($t.StartDate<$today OR $t.StartDate=0) AND ($t.EndOn>$today OR $t.EndOn=0 OR $t.EndOn IS NULL))";
  	$sql .= " AND ".$where;
  	return $sql;

//  	echo $sql;
  }

    function LoadListCategory($attribs=array())
    {
      global $objCatList, $objSession, $objConfig, $content_set;

      $t = $this->SourceTable;
      $ml_formatter =& $this->Application->recallObject('kMultiLanguage');
      $sql = "SELECT ".$this->SourceTable.".*, ".$ml_formatter->LangFieldName('CachedNavbar')." AS CachedNavbar,".GetTablePrefix()."Category.CategoryId as CategoryId FROM ".$this->SourceTable." ";

      $this->Clear();
      $catid=$attribs["_catid"];
      if(!is_numeric($catid))
          $catid = (int)$objCatList->CurrentCategoryID();

        $where = $t.".Status=1 ";
        if(strlen($attribs["_catlead"]))
        {
          switch($attribs["_catlead"])
          {
            case "exclusive":
              $where .= " AND $t.LeadCatStory=1";
              $orderby = " $t.CreatedOn DESC ";
            break;
            case "inclusive":
              $orderby = " $t.CreatedOn DESC ";
            break;
            case "primary":
              $orderby = " $t.LeadCatStory DESC";
            break;
           }
        }
        else
        {
           $orderby = "$t.CreatedOn DESC ";
        }
        if((int)$attribs["_archived"])
        {
            $where .= " AND $t.archived=1";
        }
        else
            $where .= " AND $t.archived=0";

        $sql .= $this->GetJoinedSQL("NEWS.VIEW",$catid,$where, false);
        if(!strlen($orderby))
        {
        	$orderby = $this->QueryOrderByClause(TRUE,TRUE,TRUE);
        	$sql .= " ".$orderby;
        }
        else {
          $tmp_orderby = $this->QueryOrderByClause(TRUE,TRUE,TRUE);
          if (strlen($tmp_orderby)) {
          	$sql .= $tmp_orderby;
          }
          else {
          	$sql .= " ORDER BY ".$orderby;
          }
        }
        //echo $sql."<br><br>";
        $this->QueryItemCount = QueryCount($sql);
        $this->Query_Item($sql);
    }

    function LoadLeadStories($attribs=array())
    {
        global $objItemTypes,$objPermissions, $objSession, $objConfig;

        $acl = $objSession->GetACLClause();
        $this->Clear();
        $ntable = $this->SourceTable;
        $catitems = GetTablePrefix()."CategoryItems";
        $cattable = GetTablePrefix()."Category";
        $ptable = GetTablePrefix()."PermCache";

		$ml_formatter =& $this->Application->recallObject('kMultiLanguage');
        $sql =  "SELECT $ntable.*,$cattable.CategoryId,$cattable.".$ml_formatter->LangFieldName('CachedNavbar')." AS CachedNavbar FROM $ntable ";
        $sql .= $this->GetJoinedSQL("NEWS.VIEW",NULL,"LeadStory=1 AND Archived=0 AND ".$this->SourceTable.".Status=1");
        $sql .= "ORDER BY EditorsPick DESC, Priority DESC";
        if(strlen(trim($objConfig->Get("News_SortField"))))
        {
          $OrderBy =  trim($objConfig->Get("News_SortField")." ".$objConfig->Get("News_SortOrder"));
          $sql .= ", ".$OrderBy;
        }
        if($objSession->HasSystemPermission("DEBUG.LIST"))
              echo htmlentities($sql,ENT_NOQUOTES)."<br>\n";

         if (is_numeric($attribs["_maxcount"]) && (int)$attribs["_maxcount"]>0)
         	$ret = $this->Query_Item($sql, "LIMIT ".$attribs["_maxcount"]);
         else
         	$ret = $this->Query_Item($sql);

        return $ret;
    }

    function GetNewValue($CategoryId=NULL)
	{
    	global $NewValues,$objConfig, $objSystemCache;

    	if(is_numeric($NewValues["news"]))
    	{
      		return $NewValues["news"];
    	}
    	else
    	{
        	$CachedValue = $objSystemCache->GetValue("NewsNewValue","innews","");
        	if(strlen($CachedValue))
        	{
            	$NewValues["news"] = $CachedValue;
            	return $CachedValue;
        	}

      		$ado = &GetADODBConnection();
      		if ($CategoryId)
      		{
          		$days = (int)$objConfig->Get("News_CatNewDays");
          		$cutoffdate = adodb_mktime(0,0,0,adodb_date("m"),adodb_date("d")-$days,adodb_date("Y"));
          		$sql = "SELECT CreatedOn FROM ".GetTablePrefix()."News INNER JOIN ".GetTablePrefix()."CategoryItems AS cat ON (".GetTablePrefix()."News.ResourceId = cat.ItemResourceId) WHERE cat.CategoryId=$CategoryId AND CreatedOn>=$cutoffdate ORDER BY CreatedOn DESC ";
      		}
      		else
      		{
          		$days = (int)$objConfig->Get("News_CatNewDays");
          		$cutoffdate = adodb_mktime(0,0,0,adodb_date("m"),adodb_date("d")-$days,adodb_date("Y"));
          		$sql = "SELECT CreatedOn FROM ".GetTablePrefix()."News WHERE CreatedOn>=$cutoffdate ORDER BY CreatedOn DESC ";
      		}
      		$rs = $ado->Execute($sql);

      		$NewValues["news"] = adodb_mktime(0,0,0,adodb_date("m"),adodb_date("d")-$days,adodb_date("Y"));

      		while($rs && !$rs->EOF)
      		{
		          $NewValues["news"] = $rs->fields["CreatedOn"];
        		  $rs->MoveNext();
      		}
      		return $NewValues["news"];
    	}
	}

	function GetPopValue()
	{
    	global $PopValues, $objConfig, $objSystemCache;

    	if(is_numeric($PopValues['news']))
    	{
        	return $PopValues['news'];
    	}
    	else
    	{
        	$PopValues['news'] = $objConfig->Get('News_MinPopRating');
        	/*$CachedValue = $objSystemCache->GetValue("NewsPopValue","innews","");
        	if(strlen($CachedValue))
        	{
            	$PopValues["news"] = $CachedValue;
            	return $CachedValue;
        	}
        	$ado = &GetADODBConnection();
        	$sql = "SELECT CachedRating FROM ".GetTablePrefix()."News WHERE CachedVotesQty > ".(int)$objConfig->Get("News_MinPopVotes")." ORDER BY CachedRating DESC,CachedVotesQty DESC LIMIT 0,".(int)$objConfig->Get("News_MaxHotNumber");
        	$rs = $ado->Execute($sql);
        	$PopValues["news"] = 0;
        	while($rs && !$rs->EOF)
        	{
            	//echo $rs->fields["CachedRating"]."<br>";
        		$PopValues["news"] = $rs->fields["CachedRating"];
            	$rs->MoveNext();
        	}*/
        	$objSystemCache->EditCacheItem('NewsPopValue',$PopValues['news'],'innews',adodb_mktime()+3600,'');
        	return $PopValues['news'];
 	   	}
	}

	function GetHotValue()
	{
		global $objConfig;

		static $cached_value = null;

		if (!isset($cached_value)) {
			$ado =& GetADODBConnection();
			$sql = 'SELECT Hits
					FROM '.GetTablePrefix().'News
					ORDER BY Hits DESC LIMIT 0,'.$objConfig->Get('News_MaxHotNumber');
			$rs = $ado->Execute($sql);

			$cached_value = 0;
			while ($rs && !$rs->EOF) {
				if ($rs->fields['Hits'] > 0) {
					$cached_value = $rs->fields['Hits'];
				}
				$rs->MoveNext();
			}
		}

		return $cached_value;
	}
}

function News_Custom($ResourceId, $tag)
{
	$adodbConnection = &GetADODBConnection();

    $fieldname= substr($tag, 7);

	$sql = "SELECT Value FROM ".GetTablePrefix()."CustomMetaData LEFT JOIN ".GetTablePrefix()."CustomField USING (CustomFieldId) where ".GetTablePrefix()."CustomMetaData.ResourceId=$ResourceId AND ".GetTablePrefix()."CustomField.FieldName='$fieldname'";

	$result = $adodbConnection->Execute($sql);

	if ($result->EOF)
		return "";
	else
		return $result->fields[0];

}



?>