<?php
/* This is a base class for this module, so load all supporting classes here */
require_once(PHPWS_SOURCE_DIR . 'core/Text.php');
require_once(PHPWS_SOURCE_DIR . 'core/WizardBag.php');
require_once(PHPWS_SOURCE_DIR . 'core/EZform.php');
require_once(PHPWS_SOURCE_DIR . 'core/Pager.php');
require_once(PHPWS_SOURCE_DIR . 'mod/help/class/CLS_help.php');
require_once(PHPWS_SOURCE_DIR . 'mod/fatcat/class/CategoryView.php');

if($GLOBALS['core']->moduleExists('comments')) 
  require_once(PHPWS_SOURCE_DIR . 'mod/comments/class/CommentManager.php');

if (!class_exists('PHPWS_Article'))
  require_once(PHPWS_SOURCE_DIR . 'mod/article/class/Article.php');
/**
* This is the PHPWS_ArticleManager class.  It controls interaction and
* organization with PHPWS_Article objects.
*
* @version $Id: ArticleManager.php,v 1.18 2004/11/14 04:48:48 adarkling Exp $
*
* @author Eloi George <eloi@NOSPAM.bygeorgeware.com>
* @basecode Adam Morton's PageMaster Module
* @module Article Manager
* @param string list_group : Specifies whether to show all stories or just the User's stories.
* @param string list_sort : The field we'll use to sort the listing results.
* @param string list_order : Specifies what to order the search results by. Ascending or Descending.
* @param string group_array : Choices used to build the article listing query.
* @param string sort_array : Choices used to build the article listing query.
* @param string order_array : Choices used to build the article listing query.
* @param string sql_article_table : SQL string fragment specifying what tables will be used.
* @param string sql_predicate : ending SQL string fragment that can filter out all unauthorized records.
* @param array  error   : Holds all Error Flags for the entire module.
* @param array  val     : Configuration Variables from mod_article_config.
* @param array  image_directory : Current Root Image Directory from configuration file.
* @param array  image_path      : Complete path to Root Image Directory from configuration file.
* @param string filter : Letter that a list is being filtered by.
* @param string current_user : Name of the user belonging to the current settings.
*/ 
class PHPWS_ArticleManager
{
	var $list_group;
	var $list_sort;
	var $list_order;
	var $group_array;
	var $sort_array;
	var $order_array;
	var $sql_article_table;
	var $sql_predicate;
	var $error;
	var $val;
	var $image_directory;
	var $image_path;
	var $filter;
	var $date_filter;
	var $news_filter;
  
	/**
	* ArticleManager constructor.
	*
	* @author Eloi George <eloi@NOSPAM.bygeorgeware.com>
	* @module Article Manager
	* @param none
	* @return none
	*/ 
	function PHPWS_ArticleManager ()
	{
		/* Load module default settings */
		include(PHPWS_SOURCE_DIR . 'mod/article/conf/config.php');
    $result = $GLOBALS['core']->quickFetch('SELECT * FROM mod_article_config', true);
    $this->val = $result;
    /* Set up sql code to retrieve pages available to this user */
    /* This method of setting up the sql allows me to add group-based restrictions later */
    $this->sql_article_table = PHPWS_TBL_PREFIX.'mod_article AS A';
    $this->sql_predicate = '';

    /* Set up the list search criteria */ 
    /* Unapproved listings show up under "My Listings" only */ 
		$this->group_array = array('All'=>'All', 'My' =>'My');
    $this->sort_array = array('title'=>'Article Title'
          ,'publication_date'=>'Publication Date'
          ,'expiration_date'=>'Expiration Date'
          ,'created_date'=>'Date Created'
          ,'updated_date'=>'Last Update');
    $this->order_array = array('ASC'=>'Ascending', 'DESC'=>'Descending');

    /* Default search criteria defaults to showing "my" articles only */
    if ($_SESSION['OBJ_user']->username)
      $this->list_group = 'My';
    else 
      $this->list_group = 'All';
    
    $this->list_sort = 'title';
    $this->list_order = "ASC";
	}

	/**
	* Displays the main menu with main functions like "Set as Main", "New Article" and "List Articles"
	*
	* @author Eloi George <eloi@NOSPAM.bygeorgeware.com>
	* @module Article Manager
	* @param none
	* @return none
	*/
	function main_menu ()
	{
		$GLOBALS['CNT_article']['title'] = "Article Manager";

    /* If search criteria are specified, set them */
    if (!empty($_POST['LIST_group']))
		{
	    $this->list_group = $_POST['LIST_group']; 
	    $this->list_sort = $_POST['LIST_sort'];
	    $this->list_order = $_POST['LIST_order'];
		}
    if (!empty($_REQUEST['LIST_group']) && array_key_exists($_REQUEST['LIST_group'], $this->group_array))
	    $this->list_group = $_REQUEST['LIST_group']; 
    if (!empty($_REQUEST['LIST_sort']) && array_key_exists($_REQUEST['LIST_sort'], $this->sort_array))
	    $this->list_sort = $_REQUEST['LIST_sort'];
    if (!empty($_REQUEST['LIST_order']) && array_key_exists($_REQUEST['LIST_order'], $this->order_array))
	    $this->list_order = $_REQUEST['LIST_order'];

    $form = new EZform;
    /* list_group */
    $form->add('LIST_group', 'select', $this->group_array);
    $form->setMatch('LIST_group', $this->list_group, TRUE);
    /* list_sort */
    $form->add('LIST_sort', 'select', $this->sort_array);
    $form->setMatch('LIST_sort', $this->list_sort, TRUE);
    /* list_order */
    $form->add('LIST_order', 'select', $this->order_array);
    $form->setMatch('LIST_order', $this->list_order, TRUE);
    $tags['SEARCHQUERY'] = $_SESSION['translate']->it('Show me [var1] stuff ordered by [var2][var3]'
        , $form->get('LIST_group')
        , $form->get('LIST_sort')
        , $form->get('LIST_order'))
      . '<input name="ARTICLE_vars[disp:main_menu]" value="'.$_SESSION['translate']->it('List Articles').'" type="submit">';

		if ($this->can("create"))
			$tags['BTN_CREATE'] = '<input name="ARTICLE_vars[edit:create]" value="'.$_SESSION['translate']->it('Create New Article').'" type="submit">';

		if ($_SESSION['OBJ_user']->allow_access('article', 'global_article_prefs'))
			$tags['BTN_CONFIG_EDIT'] = '<input name="ARTICLE_vars[config:edit]" value="'.$_SESSION['translate']->it('Edit Configuration').'" type="submit">';

		if ($_SESSION['OBJ_user']->allow_access('article', 'images_in_library'))
			$tags['BTN_IMG_LIB'] = '<input name="IMGLib_op" value="'.$_SESSION['translate']->it('Image Library').'" type="submit">'
          . '<input name="IMGLib_can_select_images" value="0" type="hidden">'
          . '<input name="IMGLib_return_data" value="main_menu" type="hidden">';

    $title = $_SESSION['translate']->it('Main Menu');
    $content = '<form name="ARTICLE_main_menu" action="index.php" method="post" enctype="multipart/form-data">'
        . '<input name="module" value="article" type="hidden">'
        . PHPWS_Template::processTemplate($tags,'article','menu.tpl')
        . '</form>';
		$this->popbox($title, $content);
	}

	/**
	* Lists the articles stored in the database in user-selectable formats
	*
	* @author Eloi George <eloi@NOSPAM.bygeorgeware.com>
	* @module Article Manager
	* @param none
	* @return none
	*/
	function list_articles ()
	{
		include(PHPWS_SOURCE_DIR . 'mod/article/inc/AM_list_articles.php');
	}


	/**
	* Lists the articles stored in the database in a "News Page"
	*
	* @author Eloi George <eloi@NOSPAM.bygeorgeware.com>
	* @module Article Manager
	* @param none
	* @return none
	*/
	function view_news ()
	{
		include(PHPWS_SOURCE_DIR . 'mod/article/inc/AM_view_news.php');
	}


	/**
	* Lists the articles stored in the database within a certain date
	*
	* All parameters are passed via $_REQUEST
	*
	* @author Eloi George <eloi@NOSPAM.bygeorgeware.com>
	* @module Article Manager
	* @param int year
	* @param int month
	* @param int day
	* @param string datetype : Type of date to check & sort on. VALUES: 'publication_date' [default] , 'created_date' or 'updated_date'
	* @return none
	*/
	function view_archives ()
	{
		include(PHPWS_SOURCE_DIR . 'mod/article/inc/AM_view_archives.php');
	}


	/**
	* Sets the main article in the database and in this PHPWS_ArticleManager class.
	*
	* @author Eloi George <eloi@NOSPAM.bygeorgeware.com>
	* @module Article Manager
	* @param none
	* @return none
	*/
	function set_main_article ()
	{
		if($_POST['ARTICLE_id'])
		{
      $GLOBALS['core']->query('UPDATE mod_article SET mainarticle=0 WHERE mainarticle=1', true);
      $GLOBALS['core']->query('UPDATE mod_article SET mainarticle=1 WHERE id='.$_POST['ARTICLE_id'], true);
		}
	}

	/**
	* Simply displays the homepage article.
	*
	* @author Adam Morton <adam@NOSPAM.tux.appstate.edu>
	* @module Article Manager
	* @param none
	* @return none
	*/
	function show_mainarticle ()
	{
		if ($row=$GLOBALS['core']->quickFetch('SELECT id from mod_article WHERE mainarticle = 1',TRUE)) 
		{
			$temp = new PHPWS_Article($row['id']);
    	$temp->view();
    	unset($temp);
		}
	}

	/**
	* Bridge function to the search module to allow articles to be searched
	*
	* This function is optimised to only conduct one query.
	*
	* @author Eloi George <eloi@NOSPAM.bygeorgeware.com>
	* @module Article Manager
	* @param string $where The "where" clause for the SQL statement.
	* @return array List of articles containing the search term.
	*/
	function search($where) 
	{
		$returnArray = array();
		$sql = 'SELECT A.id,A.title,A.summary FROM ' . $this->sql_article_table 
		    . ','.PHPWS_TBL_PREFIX.'mod_article_sections AS S  ' 
		    . $where . ' AND A.id=S.article_id AND '. $this->get_published_sql() 
		    . $this->sql_predicate . ' GROUP BY A.id ORDER BY updated_date DESC';

		$articleResult = $GLOBALS['core']->query($sql); 
		while ($articleResult && $resultRow = $articleResult->fetchrow(DB_FETCHMODE_ASSOC)) 
		{
	    /* Only save/show the first occurence per article */
			if (!isset($returnArray[$resultRow['id']]))
		    $returnArray[$resultRow['id']] = '<b>' . $resultRow['title'] . '</b><br />' . $resultRow['summary'];
		}
		return $returnArray;
	}// END FUNC searchArticles()


	/**
	* Displays summary listings of last n articles on the homepage.
	* 
	* Also displays the "Past n Articles" Block & the "Popular Articles" Block.
	*
	* @author Eloi George <eloi@NOSPAM.bygeorgeware.com>
	* @module Article Manager
	* @param none
	* @return none
	*/
	function view_summaries ()
	{
    $TotalCount = $this->val['summaries_on_homepage'] + $this->val['prev_n_articles'];
    /* Determine how many summaries we're going to show */
    if ($TotalCount<1)
      return;

    /* Load records to display */
    $sql = 'SELECT * FROM '  . $this->sql_article_table 
      . ' WHERE ' . $this->get_published_sql().' AND mainarticle=0'. $this->sql_predicate 
      . ' AND announce ORDER BY updated_date DESC LIMIT ' . $TotalCount;
    $result = $GLOBALS['core']->query($sql);

		/* If there are summaries to display, display 'em */
    if ($this->val['summaries_on_homepage']>0 && $result)
    {
 			$GLOBALS['CNT_article_summaries']['content'] = '';
      for($i=0; $i < $this->val['summaries_on_homepage'] && $summary=$result->fetchrow(DB_FETCHMODE_ASSOC); $i++) 
  		{
      	$temp = new PHPWS_Article($summary['id'], $summary);
      	$temp->view(false);
      	$content = true;
      }
      if(!empty($content))
  			$GLOBALS['CNT_article_summaries']['title'] = $_SESSION['translate']->it('Also on this Site...');
  		if($this->can('create'))
  		  $GLOBALS['CNT_article_summaries']['content'] .= '<div style="text-align:center"><a href="./index.php?module=article&edit=create">'.$_SESSION['translate']->it('Submit a new article').'</a></div>'; 
    }
		/* If there are x articles before these, display the "Prev Articles" Block */
    $content = '';
    if ($this->val['prev_n_articles']>0)
    {
      for($i=0; $i < $this->val['prev_n_articles'] && $summary=$result->fetchrow(DB_FETCHMODE_ASSOC); $i++) 
      {
        if ($i>0)
          $content .= '<br />';
      	$content .= date('F d', strtotime($summary['updated_date']))
      	      . ' <br />' . PHPWS_Text::moduleLink($summary['title'], 'article'
            ,array('view'=>$summary['id'])).'&#013;';
      }
      if (!empty($content))
      {
        $GLOBALS['CNT_article_past']['title'] = 
            $_SESSION['translate']->it('Previous').' '.$this->val['prev_n_articles']
            . ' ' . $_SESSION['translate']->it('Articles');
        $GLOBALS['CNT_article_past']['content'] = &$content;
      }
  	}
  	/* Reset the variable used to hold the class */
  	unset($temp);
	}


	/**
	* Displays a block listing of the n most popular last n articles.
	* 
	* @author Eloi George <eloi@NOSPAM.bygeorgeware.com>
	* @module Article Manager
	* @param none
	* @return none
	*/
	function view_popular ()
	{
    if ($this->val['popular_articles']<1)
      return;

    /* Load records to display */
    $sql = 'SELECT * FROM '  . $this->sql_article_table 
      . ' WHERE ' . $this->get_published_sql().' AND mainarticle=0'. $this->sql_predicate 
      . ' ORDER BY hits DESC LIMIT ' . $this->val['popular_articles'];
    $result = $GLOBALS['core']->query($sql);

		/* If there are summaries to display, display 'em */
		$content = '';
    while($summary=$result->fetchrow(DB_FETCHMODE_ASSOC)) 
    {
    	$content .= '<li>' . PHPWS_Text::moduleLink($summary['title'], 'article'
            ,array('view'=>$summary['id'])).'</li><br />&#013;';
    }
    if (!empty($content))
    {
      $GLOBALS['CNT_article_popular']['title'] = $_SESSION['translate']->it('Popular Articles');
      $GLOBALS['CNT_article_popular']['content'] = '&#013;<ol style="padding-left:1em">&#013;'.$content.'&#013;</ol>&#013;';
    }
	}


	/* Edits the module's default settings.
	*
	* @author Eloi George <eloi@NOSPAM.bygeorgeware.com>
	* @module Article Manager
	* @param none
	* @return none
	*/
	function edit_configuration ()
	{
		include(PHPWS_SOURCE_DIR . 'mod/article/inc/editconfig.php');
	}

	/**
	* Saves the module's default settings to the database.
	*
	* @author Eloi George <eloi@NOSPAM.bygeorgeware.com>
	* @module Article Manager
	* @param none
	* @return none
	*/
	function save_configuration ()
	{
		include(PHPWS_SOURCE_DIR . 'mod/article/inc/saveconfig.php');
  }

	/**
	* Resets the module's default settings.
	*
	* @author Eloi George <eloi@NOSPAM.bygeorgeware.com>
	* @module Article Manager
	* @param none
	* @return none
	*/
	function reset_configuration ()
	{
    $GLOBALS['core']->sqlDelete('mod_article_config');
    $GLOBALS['core']->sqlInsert(array(),'mod_article_config', 0, 0, 0, 0);
	}


	/**
	* Determines whether user is authorized to edit, create, delete articles.
	*
  * @author Eloi George <eloi@NOSPAM.bygeorgeware.com>
	* @module Article Manager
	* @param action to authorize
	* @param username to compare against
	* @return TRUE or FALSE
	* @access public
	*/
	function can($action = NULL, $username = NULL, $is_mainarticle=NULL)
	{
		if ($action == "edit")
  		return (($_SESSION['OBJ_user']->allow_access('article', "edit_articles") 
  			|| ((($this->val['users_can_submit'] && $_SESSION['OBJ_user']->isUser()) 
  			        || $_SESSION['OBJ_user']->allow_access('article', "edit_own_article")) 
  				&& $_SESSION['OBJ_user']->username==$username))
  			&& !($this->val['need_approval'] && $is_mainarticle && !$_SESSION['OBJ_user']->allow_access('approval')));

		elseif ($action == "delete")
  		return ($_SESSION['OBJ_user']->allow_access('article', "delete_articles") 
  			|| ($_SESSION['OBJ_user']->allow_access('article', "delete_own_article") 
  				&& $_SESSION['OBJ_user']->username==$username));

		elseif ($action == "create")
  		return ($_SESSION['OBJ_user']->allow_access('article', "create_articles")
  		        || ($this->val['users_can_submit'] && $_SESSION['OBJ_user']->isUser()));
    	else
  	    return false;
	}


	/**
	* Prints an error message selected by passing the function an error $type
	*
	* @author Eloi George <eloi@NOSPAM.bygeorgeware.com>
	* @module Article Manager
	* @param array type : Type of error that occured. Prints an appropriate error message
	*                      based on the type.
	* @return string     : Error output text
	*/
	function get_error ($type = NULL)
	{
		if (isset($this->error[$type]))
		{
	    $str = '&#013;<span class="errortext">ERROR!<br />&#013;';
	    foreach($this->error[$type] as $msg)
        $str .= $msg . '<br />&#013;';
	    $str .= '</span>&#013;';
	    unset($this->error[$type]);
	    return $str;
    }
	}

	/**
	* Approves an article for publication
	*
	* @author Eloi George <eloi@NOSPAM.bygeorgeware.com>
	* @module Article Manager
	* @param array info_array : Array containing the Article Id
	* @return none
	*/
	function approve ($id)
	{
		$query_data['approved'] = true;
		$GLOBALS['core']->sqlUpdate($query_data, 'mod_article', 'id', $id);
    PHPWS_Fatcat::activate($id, 'article');
	}

	/**
	* Deletes an unpublishable article
	*
	* @author Eloi George <eloi@NOSPAM.bygeorgeware.com>
	* @module Article Manager
	* @param array info_array : Array containing the Article Id
	* @return none
	*/
	function refuse ($id)
	{
		$GLOBALS['core']->sqlDelete('mod_article_sections', 'article_id', $id);
		$GLOBALS['core']->sqlDelete('mod_article', 'id', $id);
    PHPWS_Fatcat::purge($id, 'article');
	}

	/**
	* Creates sql text to retrieve published pages.
	*
	* @author Eloi George <eloi@NOSPAM.bygeorgeware.com>
	* @module Article Manager
	* @param none 
	* @return string : sql text
	*/
	function get_published_sql ()
	{
		$now = date("Y-m-d H:i:s");
    return '(approved OR updated_username="'.$_SESSION['OBJ_user']->username.'") AND publication_date<="'.$now.'" AND (expiration_date IS NULL OR expiration_date>"'.$now.'")';
	}

	/**
	* popbox replacement.
	*
	* @author Eloi George <eloi@NOSPAM.bygeorgeware.com>
	* @module Article Manager
	* @param string title 
	* @param string content 
	* @return none
	*/
	function popbox ($title, $content)
	{
		if(!isset($GLOBALS['CNT_article']['content']))
		  $GLOBALS['CNT_article']['content'] = '';
		$GLOBALS['CNT_article']['content'] .= '<h3>' . $title . '</h3>' . $content;
	}

}
?>