<?php

/**
 * <pre>
 * Invision Power Services
 * IP.CCS pages: displays the pages created in the ACP
 * Last Updated: $Date: 2010-02-10 18:05:14 -0500 (Wed, 10 Feb 2010) $
 * </pre>
 *
 * @author 		$Author: bfarber $
 * @copyright	(c) 2001 - 2009 Invision Power Services, Inc.
 * @license		http://www.invisionpower.com/community/board/license.html
 * @package		IP.Content
 * @link		http://www.invisionpower.com
 * @since		1st March 2009
 * @version		$Revision: 200 $
 */

if ( ! defined( 'IN_ACP' ) )
{
	print "<h1>Incorrect access</h1>You cannot access this file directly.";
	exit();
}

class public_ccs_articles_promote extends ipsCommand
{
	/**
	 * Permissions
	 *
	 * @access	protected
	 * @var		array
	 */
	protected $permissions	= array( 'copy' => false, 'move' => false );

	/**
	 * Main class entry point
	 *
	 * @access	public
	 * @param	object		ipsRegistry reference
	 * @return	void		[Outputs to screen]
	 */
	public function doExecute( ipsRegistry $registry ) 
	{
		//-----------------------------------------
		// Get groups
		//-----------------------------------------
		
		$myGroups	= array( $this->memberData['member_group_id'] );
		$secondary	= IPSText::cleanPermString( $this->memberData['mgroup_others'] );
		$secondary	= $secondary ? explode( ',', $secondary ) : array();
		
		if( count($secondary) )
		{
			$myGroups	= array_merge( $myGroups, $secondary );
		}
				
		//-----------------------------------------
		// Check online/offline first
		//-----------------------------------------

		if( !$this->settings['ccs_online'] )
		{
			$show		= false;
			
			if( $this->settings['ccs_offline_groups'] )
			{
				$groups		= explode( ',', $this->settings['ccs_offline_groups'] );
				
				foreach( $myGroups as $groupId )
				{
					if( in_array( $groupId, $groups ) )
					{
						$show	= true;
						break;
					}
				}
			}
			
			if( !$show )
			{
				IPSText::getTextClass('bbcode')->parse_bbcode		= 1;
				IPSText::getTextClass('bbcode')->parse_html			= 0;
				IPSText::getTextClass('bbcode')->parse_emoticons	= 1;
				IPSText::getTextClass('bbcode')->parse_nl2br		= 1;
				IPSText::getTextClass('bbcode')->parsing_section	= 'global';
		
				$this->registry->output->showError( IPSText::getTextClass('bbcode')->preDisplayParse( $this->settings['ccs_offline_message'] ), '10CCS4' );
			}
		}

		//-----------------------------------------
		// Load Language
		//-----------------------------------------
		
		ipsRegistry::getClass('class_localization')->loadLanguageFile( array( 'public_lang' ) );
		
		//-----------------------------------------
		// Allowing post promotion?
		//-----------------------------------------
		
		if( !$this->settings['ccs_promote'] )
		{
			$this->registry->output->showError( $this->lang->words['promote_disabled'], '10CCS5' );
		}
		
		//-----------------------------------------
		// Are we allowed to copy or move?
		//-----------------------------------------
		
		$_copy	= explode( ',', $this->settings['ccs_promote_g_copy'] );
		$_move	= explode( ',', $this->settings['ccs_promote_g_move'] );
		$_allow	= false;

		foreach( $myGroups as $groupId )
		{
			if( in_array( $groupId, $_copy ) )
			{
				$this->permissions['copy']	= true;
				$_allow	= true;
			}

			if( in_array( $groupId, $_move ) )
			{
				$this->permissions['move']	= true;
				$_allow	= true;
			}
		}
		
		if( !$_allow )
		{
			$this->registry->output->showError( $this->lang->words['noperm_promote'], '10CCS6' );
		}

		//-----------------------------------------
		// What to do?
		//-----------------------------------------
		
		switch( $this->request['do'] )
		{
			case 'doPromote':
				$this->_promote();
			break;
			
			default:
				$this->_intermediary();
			break;
		}
	}
	
	/**
	 * Intermediary screen.  This is where we confirm the details of the article, 
	 * collect any additional data we need, and let user select which method to use 
	 * (if they can use more than one method) to promote the post.
	 *
	 * @access	protected
	 * @return	void
	 */
	protected function _intermediary()
	{
		//-----------------------------------------
		// Get the post
		//-----------------------------------------
		
		$post	= $this->_getPost();
		
		//-----------------------------------------
		// Get forum library
		//-----------------------------------------
		
		$classToLoad = IPSLib::loadLibrary( IPSLib::getAppDir( 'forums' ) . "/sources/classes/forums/class_forums.php", 'class_forums' );
		$this->registry->setClass( 'class_forums', new $classToLoad( $this->registry ) );
		$this->registry->getClass('class_forums')->strip_invisible = 1;
		$this->registry->getClass('class_forums')->forumsInit();
		$this->memberData = IPSMember::setUpModerator( $this->memberData );
		
		//-----------------------------------------
		// Check access
		//-----------------------------------------
		
		if( !$this->registry->getClass('class_forums')->forumsCheckAccess( $post['forum_id'], false, 'topic', $post, true ) )
		{
			$this->registry->output->showError( $this->lang->words['nopost_to_promote'], '10CCS7' );
		}

		//-----------------------------------------
		// Categories
		//-----------------------------------------
		
		$database	= array();
		
		if( count($this->caches['ccs_databases']) AND is_array($this->caches['ccs_databases']) )
		{
			foreach( $this->caches['ccs_databases'] as $dbid => $_database )
			{
				if( $_database['database_is_articles'] )
				{
					$database	= $_database;
				}
			}
		}
		
		if( !$database['database_id'] )
		{
			$this->registry->output->showError( $this->lang->words['promote_no_db_id'], '10CCS8' );
		}
		
		//-----------------------------------------
		// Get possible field types
		//-----------------------------------------
		
		$fieldsClass	= $this->registry->ccsFunctions->getFieldsClass();

		$fields	= array();

		if( is_array($this->caches['ccs_fields'][ $database['database_id'] ]) AND count($this->caches['ccs_fields'][ $database['database_id'] ]) )
		{
			foreach( $this->caches['ccs_fields'][ $database['database_id'] ] as $_field )
			{
				if( !$_field['field_user_editable'] )
				{
					continue;
				}
			
				$fields[ $_field['field_id'] ]	= $_field;
			}
		}

		$categories	= $this->registry->ccsFunctions->getCategoriesClass( $database )->getSelectMenu();
		
		//-----------------------------------------
		// Remap for field handler...
		//-----------------------------------------
		
		foreach( $fields as $_field )
		{
			switch( $_field['field_key'] )
			{
				case 'article_title':
					$post['field_' . $_field['field_id'] ]	= $post['title'];
				break;

				case 'article_body':
					$post['field_' . $_field['field_id'] ]	= $post['post'];
				break;
				
				case 'article_homepage':
					$post['field_' . $_field['field_id'] ]	= ',1,';
				break;
				
				case 'article_date':
					$post['field_' . $_field['field_id'] ]	= $post['post_date'];
				break;
				
				case 'article_expiry':
					$post['field_' . $_field['field_id'] ]	= '';
				break;
				
				case 'article_comments':
					$post['field_' . $_field['field_id'] ]	= '1';
				break;
				
				case 'article_cutoff':
					$post['field_' . $_field['field_id'] ]	= '';
				break;
			}
		}
		
		//-----------------------------------------
		// Good to go?  Output form then
		//-----------------------------------------
		
		$this->registry->output->setTitle( $this->lang->words['promote_post_to_article'] );
		$this->registry->output->addContent( $this->registry->output->getTemplate('ccs_global')->promoteForm( $post, $categories, $fields, $fieldsClass, $this->permissions ) );
		$this->registry->output->sendOutput();
	}
	
	/**
	 * Promote the post to an article
	 *
	 * @access	protected
	 * @return	void
	 */
	protected function _promote()
	{
		//-----------------------------------------
		// Get the post
		//-----------------------------------------
		
		$post	= $this->_getPost();
		
		//-----------------------------------------
		// Method
		//-----------------------------------------
		
		$_method	= '';
		
		if( $this->permissions['copy'] AND !$this->permissions['move'] )
		{
			$_method	= 'copy';
		}
		else if( !$this->permissions['copy'] AND $this->permissions['move'] )
		{
			$_method	= 'move';
		}
		else
		{
			$_method	= in_array( $this->request['promote_method'], array( 'copy', 'move' ) ) ? $this->request['promote_method'] : 'copy';
		}
		
		//-----------------------------------------
		// Get forum library
		//-----------------------------------------
		
		$classToLoad = IPSLib::loadLibrary( IPSLib::getAppDir( 'forums' ) . "/sources/classes/forums/class_forums.php", 'class_forums' );
		$this->registry->setClass( 'class_forums', new $classToLoad( $this->registry ) );
		$this->registry->getClass('class_forums')->strip_invisible = 1;
		$this->registry->getClass('class_forums')->forumsInit();
		$this->memberData = IPSMember::setUpModerator( $this->memberData );
		
		//-----------------------------------------
		// Check access
		//-----------------------------------------
		
		if( !$this->registry->getClass('class_forums')->forumsCheckAccess( $post['forum_id'], false, 'topic', $post, true ) )
		{
			$this->registry->output->showError( $this->lang->words['nopost_to_promote'], '10CCS9' );
		}

		//-----------------------------------------
		// Categories
		//-----------------------------------------
		
		$database	= array();
		
		if( count($this->caches['ccs_databases']) AND is_array($this->caches['ccs_databases']) )
		{
			foreach( $this->caches['ccs_databases'] as $dbid => $_database )
			{
				if( $_database['database_is_articles'] )
				{
					$database	= $_database;
				}
			}
		}
		
		if( !$database['database_id'] )
		{
			$this->registry->output->showError( $this->lang->words['promote_no_db_id'], '10CCS10' );
		}
		
		//-----------------------------------------
		// Get possible field types
		//-----------------------------------------
		
		$fieldsClass	= $this->registry->ccsFunctions->getFieldsClass();

		$fields	= array();

		if( is_array($this->caches['ccs_fields'][ $database['database_id'] ]) AND count($this->caches['ccs_fields'][ $database['database_id'] ]) )
		{
			foreach( $this->caches['ccs_fields'][ $database['database_id'] ] as $_field )
			{
				if( !$_field['field_user_editable'] )
				{
					continue;
				}
				
				$fields[ $_field['field_id'] ]	= $_field;
			}
		}
		
		//-----------------------------------------
		// Category
		//-----------------------------------------
		
		$libCategories	= $this->registry->ccsFunctions->getCategoriesClass( $database );

		if( count($libCategories->categories) AND !$this->request['category_id'] )
		{
			$this->registry->output->showError( $this->lang->words['promote_no_catid'], '10CCS11' );
		}
		
		$_cat	= $libCategories->categories[ $this->request['category_id'] ];
		
		//-----------------------------------------
		// Start save array
		//-----------------------------------------

		$this->settings['post_key']	= $this->request['post_key'];
		
		$_save	= array( 'post_key' => $this->request['post_key'] );
		
		//-----------------------------------------
		// Remove non-user-editable fields
		//-----------------------------------------
		
		foreach( $fields as $_field )
		{
			$_save['field_' . $_field['field_id'] ]	= $fieldsClass->processInput( $_field );
		}

		//-----------------------------------------
		// Any errors?
		//-----------------------------------------
		
		if( $error = $fieldsClass->getError() )
		{
			//-----------------------------------------
			// Cat lib
			//-----------------------------------------
			
			$this->request['category']	= $this->request['category_id'] ? $this->request['category_id'] : 0;

			$categories	= $libCategories->getSelectMenu();

			$this->registry->output->setTitle( $this->lang->words['promote_post_to_article'] );
			$this->registry->output->addContent( $this->registry->output->getTemplate('ccs_global')->promoteForm( array_merge( $post, $_POST ), $categories, $fields, $fieldsClass, $this->permissions, false, $error ) );
			$this->registry->output->sendOutput();
			
			return;
		}
					
		foreach( $fields as $field )
		{
			$this->DB->force_data_type[ 'field_' . $field['field_id'] ]	= 'string';
		}
		
		//-----------------------------------------
		// Some other data for add
		//-----------------------------------------
		
		$_save['member_id']				= $this->memberData['member_id'];
		$_save['record_saved']			= time();
		$_save['record_updated']		= time();
		$_save['category_id']			= $_cat['category_id'];
		$_save['record_dynamic_furl']	= IPSText::makeSeoTitle( $fieldsClass->getFieldValue( $fields[ str_replace( 'field_', '', $database['database_field_title'] ) ], $_save, $fields[ str_replace( 'field_', '', $database['database_field_title'] ) ]['field_truncate'] ) );
		$_save['record_approved']		= 1;

		//-----------------------------------------
		// Previewing?
		//-----------------------------------------

		if( $this->request['preview'] )
		{
			$this->request['category']	= $this->request['category_id'] ? $this->request['category_id'] : 0;

			$categories	= $libCategories->getSelectMenu();
	
			$this->registry->output->setTitle( $this->lang->words['promote_post_to_article'] );
			$this->registry->output->addContent( $this->registry->output->getTemplate('ccs_global')->promoteForm( array_merge( $post, $_POST ), $categories, $fields, $fieldsClass, $this->permissions, true ) );
			$this->registry->output->sendOutput();
			
			return;
		}
		
		//-----------------------------------------
		// Insert and recount
		//-----------------------------------------
		
		$this->DB->insert( $database['database_database'], $_save );
		
		$id	= $this->DB->getInsertId();
		
		$_save['primary_id_field']	= $id;
		
		if( $_save['record_approved'] )
		{
			$this->DB->update( 'ccs_databases', array( 'database_record_count' => ($database['database_record_count'] + 1) ), 'database_id=' . $database['database_id'] );
		}

		//-----------------------------------------
		// Post process
		//-----------------------------------------
		
		foreach( $fields as $field )
		{
			$fieldsClass->postProcessInput( $field, $id );
		}

		//-----------------------------------------
		// Update category
		//-----------------------------------------
		
		$libCategories->recache( $_save['category_id'] );
		
	    //-----------------------------------------
	    // Send out appropriate notifications
	    //-----------------------------------------
	    
	    if( $_save['record_approved'] )
	    {
			//-----------------------------------------
			// Post topic if configured to do so
			//-----------------------------------------
			
			require_once( IPSLib::getAppDir( 'ccs' ) . '/sources/databases/topics.php' );
			$_topics	= new topicsLibrary( $this->registry, $fieldsClass, $libCategories, $fields );
			$_topics->postTopic( $_save, $libCategories->categories[ $_save['category_id'] ], $database );

	    	$_save['poster_name']	= $this->memberData['members_display_name'];
	    	
			require_once( IPSLib::getAppDir( 'ccs' ) . '/sources/databases.php' );
			$databases	= new databaseBuilder( $this->registry );
			$databases->sendRecordNotification( $database, $libCategories->categories[ $_save['category_id'] ], $_save );
	    }
		
	    $url	= $this->registry->ccsFunctions->returnDatabaseUrl( $database['database_id'], 0, $_save );
	    
	    //-----------------------------------------
	    // If we are copying...
	    //-----------------------------------------
	    
	    if( $_method == 'copy' )
	    {
	    	if( $this->settings['ccs_promote_link'] )
	    	{
	    		if( !$this->settings['ccs_promote_nolink'] OR !$this->request['promote_no_link'] )
	    		{
	    			$post['post']	= $post['post'] . $this->registry->output->getTemplate('ccs_global')->promoteLinkAppend( $post, $_save, $url );
	    			
	    			$this->DB->update( "posts", array( 'post' => $post['post'] ), "pid=" . $post['pid'] );
	    			$this->DB->delete( "content_cache_posts", "cache_content_id=" . $post['pid'] );
	    		}
	    	}
	    }
	    
	    //-----------------------------------------
	    // Otherwise, if we are moving...
	    //-----------------------------------------
	    
	    else
	    {
	    	if( $this->settings['ccs_promote_link'] )
	    	{
	    		if( !$this->settings['ccs_promote_nolink'] OR !$this->request['promote_no_link'] )
	    		{
	    			$post['post']	= $this->registry->output->getTemplate('ccs_global')->promoteLinkReplace( $post, $_save, $url );
	    			
	    			$this->DB->update( "posts", array( 'post' => $post['post'] ), "pid=" . $post['pid'] );
	    			$this->DB->delete( "content_cache_posts", "cache_content_id=" . $post['pid'] );
	    		}
	    		else
	    		{
	    			$this->_deletePost( $post );
	    		}
	    	}
	    	else
	    	{
	    		$this->_deletePost( $post );
	    	}
	    }
	    
		//-----------------------------------------
		// Redirect
		//-----------------------------------------

		$this->registry->output->redirectScreen( $this->lang->words['post_promoted_to_article'], $url );
	}
	
	/**
	 * Delete the post ("move" method)
	 *
	 * @access	private
	 * @param	array 		Post data
	 * @return	void
	 */
	private function _deletePost( $post )
	{
		$classToLoad = IPSLib::loadLibrary( IPSLib::getAppDir( 'forums' ) . "/sources/classes/moderate.php", 'moderatorLibrary' );
		$moderatorLib	= new $classToLoad( $this->registry );
		$moderatorLib->init( $this->registry->getClass('class_forums')->forum_by_id[ $post['forum_id'] ], $post );
		
		if( $post['pid'] == $post['topic_firstpost'] )
		{
			$moderatorLib->topicDelete( $post['tid'] );
		}
		else
		{
			$moderatorLib->postDelete( $post['pid'] );
		}
	}
	
	/**
	 * Get the post
	 *
	 * @access	private
	 * @return	array
	 */
	private function _getPost()
	{
		$pid	= intval($this->request['post']);
		$post	= array();
		
		if( $pid )
		{
			$post	= $this->DB->buildAndFetch( array( 
													'select'	=> 'p.*',
													'from'		=> array( 'posts' => 'p' ),
													'where'		=> 'p.pid=' . $pid,
													'add_join'	=> array(
																		array(
																			'select'	=> 't.*',
																			'from'		=> array( 'topics' => 't' ),
																			'where'		=> 't.tid=p.topic_id',
																			'type'		=> 'left',
																			)
																		)
											)		);
		}
		
		if( !$post['pid'] )
		{
			$this->registry->output->showError( $this->lang->words['nopost_to_promote'], '10CCS12' );
		}
		
		return $post;
	}
}
