<?php

/**
 * <pre>
 * Invision Power Services
 * Attachments field type abstraction
 * Last Updated: $Date: 2009-08-23 21:54:28 -0400 (Sun, 23 Aug 2009) $
 * </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		2nd Sept 2009
 * @version		$Revision: 67 $
 */

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

class fields_attachments
{
	/**#@+
	 * Registry objects
	 *
	 * @access	protected
	 * @var		object
	 */	
	protected $registry;
	protected $DB;
	protected $settings;
	protected $request;
	protected $lang;
	protected $member;
	protected $memberData;
	protected $caches;
	protected $cache;
	/**#@-*/
	
	/**
	 * Error string stored from last process
	 *
	 * @access	protected
	 * @var		string
	 */
	protected $error		= '';
	
	/**
	 * Attachments class
	 *
	 * @access	protected
	 * @var		object
	 */
	protected $class_attach;

	/**
	 * Constructor
	 *
	 * @access	public
	 * @param	object		Registry
	 * @return	void
	 */
	public function __construct( ipsRegistry $registry )
	{
		/* Make object */
		$this->registry		= $registry;
		$this->DB			= $this->registry->DB();
		$this->settings		=& $this->registry->fetchSettings();
		$this->request		=& $this->registry->fetchRequest();
		$this->lang			= $this->registry->getClass('class_localization');
		$this->member		= $this->registry->member();
		$this->memberData	=& $this->registry->member()->fetchMemberData();
		$this->cache		= $this->registry->cache();
		$this->caches		=& $this->registry->cache()->fetchCaches();
	}
	
	/**
	 * Return default field types
	 *
	 * @access	public
	 * @param	string		Table name
	 * @return	bool
	 */
	public function getTypes()
	{
		return array(
					array( 'attachments', $this->lang->words['field_type__attachments'] ),
					);
	}
	
	/**
	 * Get an ACP field
	 *
	 * @access	public
	 * @param	array		Field data
	 * @param	mixed		Default value
	 * @return	string		HTML field
	 */
	public function getAcpField( $field, $default='' )
	{
		$id			= $field['field_id'];
		$type		= $field['field_type'];
		$options	= $field['field_extra'];
		
		if( $type == 'attachments' )
		{
			if ( ! is_object( $this->class_attach ) )
			{
				//-----------------------------------------
				// Grab render attach class
				//-----------------------------------------

				require_once( IPSLib::getAppDir( 'core' ) . '/sources/classes/attach/class_attach.php' );
				$this->class_attach = new class_attach( $this->registry );
			}
			
			$this->registry->class_localization->loadLanguageFile( array( 'public_post' ), 'forums' );
			$this->class_attach->type		= 'ccs';
			$this->class_attach->init();
			$this->class_attach->getUploadFormSettings();

			return $this->registry->output->getTemplate('ccs_global')->attachments( array( 'post_key' => $this->settings['post_key'], 'stats' => $class_attach->attach_stats ) );

		}
		
		return '';
	}
	
	/**
	 * Get a public field
	 *
	 * @access	public
	 * @param	array		Field data
	 * @param	mixed		Default value
	 * @return	string		HTML field
	 */
	public function getPublicField( $field, $default='' )
	{
		$id			= $field['field_id'];
		$type		= $field['field_type'];
		$options	= $field['field_extra'];
		
		if( $type == 'attachments' )
		{
			if ( ! is_object( $this->class_attach ) )
			{
				require_once( IPSLib::getAppDir( 'core' ) . '/sources/classes/attach/class_attach.php' );
				$this->class_attach = new class_attach( $this->registry );
			}
			
			$this->registry->class_localization->loadLanguageFile( array( 'public_post' ), 'forums' );
			$this->class_attach->type		= 'ccs';
			$this->class_attach->init();
			$this->class_attach->getUploadFormSettings();

			$this->lang->words['upload_title']	= $field['field_name'];
			
			return $this->registry->output->getTemplate('ccs_global')->attachments( array( 'post_key' => $this->settings['post_key'], 'stats' => $class_attach->attach_stats ) );
		}
		
		return '';
	}
	
	/**
	 * Get error, if set
	 *
	 * @access	public
	 * @return	mixed		Error lang key, or false
	 */
	public function getError()
	{
		return $this->error ? $this->error : false;
	}

	/**
	 * Process the input and return normalized value to store
	 *
	 * @access	public
	 * @param	array 		Field data
	 * @return	string		Data to store in DB
	 */
	public function processInput( $field )
	{
		return 0;
	}
	
	/**
	 * Process input after data has been saved to database
	 *
	 * @access	public
	 * @param	array 		Field data
	 * @return	bool		Error or not
	 */
	public function postProcessInput( $field, $record_id=0 )
	{
		if( !$record_id )
		{
			return false;
		}
		
		if( $field['field_type'] == 'attachments' )
		{
			if ( ! is_object( $this->class_attach ) )
			{
				require_once( IPSLib::getAppDir( 'core' ) . '/sources/classes/attach/class_attach.php' );
				$this->class_attach = new class_attach( $this->registry );
			}
			
			$this->class_attach->type				= 'ccs';
			$this->class_attach->attach_post_key	= $this->request['post_key'];
			$this->class_attach->attach_rel_id		= $record_id;
			$this->class_attach->init();
			
			$return = $this->class_attach->postProcessUpload( array( 'field_id' => $field['field_id'], 'database_id' => $field['field_database_id'], 'record_id' => $record_id ) );

			$this->DB->update( 'ccs_custom_database_' . $field['field_database_id'], array( 'field_' . $field['field_id'] => $return['count'] ), 'primary_id_field=' . $record_id );
			
			return true;
		}

		return true;
	}
	
	/**
	 * Record deletion callback
	 *
	 * @access	public
	 * @param	array 		Field data
	 * @param	array		Record data
	 * @return	bool		Handled successfully or not
	 */
	public function postProcessDelete( $field, $record )
	{
		$mapIds	= array();
		
		$this->DB->build( array( 'select' => '*', 'from' => 'ccs_attachments_map', 'where' => "map_database_id={$field['field_database_id']} AND map_field_id={$field['field_id']} AND map_record_id={$record['primary_id_field']}" ) );
		$this->DB->execute();
		
		while( $r = $this->DB->fetch() )
		{
			$mapIds[]	= $r['map_id'];
		}
		
		if( count($mapIds) )
		{
			if ( ! is_object( $this->class_attach ) )
			{
				require_once( IPSLib::getAppDir( 'core' ) . '/sources/classes/attach/class_attach.php' );
				$this->class_attach = new class_attach( $this->registry );
			}
			
			$this->class_attach->type		= 'ccs';
			$this->class_attach->init();
			
			$this->class_attach->bulkRemoveAttachment( $mapIds );
			
			$this->DB->delete( 'ccs_attachments_map', "map_database_id={$field['field_database_id']} AND map_field_id={$field['field_id']} AND map_record_id={$record['primary_id_field']}" );
		}
		
		return true;
	}
	
	/**
	 * Process the field and return a display value
	 *
	 * @access	public
	 * @param	array 		Field data
	 * @param	array		Record data
	 * @param	int			Number of characters to truncate at (0 means no truncating)
	 * @return	string		Data to display
	 */
	public function getFieldValue( $field, $record=array(), $truncate=0 )
	{
		$fieldValue	= $record['field_' . $field['field_id'] ];
		
		if( !$fieldValue )
		{
			return '';
		}

		$returnHTML	= '';
				
		if( $field['field_type'] == 'attachments' )
		{
			if( $truncate )
			{
				return sprintf( $this->lang->words['_attachments_count'], $fieldValue );
			}

			$_id	= $record['primary_id_field'];
			
			$mapIds	= array();
			
			$this->DB->build( array( 'select' => '*', 'from' => 'ccs_attachments_map', 'where' => "map_database_id={$field['field_database_id']} AND map_field_id={$field['field_id']} AND map_record_id={$_id}" ) );
			$this->DB->execute();
			
			while( $r = $this->DB->fetch() )
			{
				$mapIds[]	= $r['map_id'];
				
				$this->caches['ccs_attachments_data'][ $_id ][ $r['map_id'] ]	= array();
			}

			if( count($mapIds) )
			{
				$this->registry->class_localization->loadLanguageFile( array( 'public_topic' ), 'forums' );
				
				if ( ! is_object( $this->class_attach ) )
				{
					require_once( IPSLib::getAppDir( 'core' ) . '/sources/classes/attach/class_attach.php' );
					$this->class_attach = new class_attach( $this->registry );
				}
			
				$this->class_attach->type  = 'ccs';
				$this->class_attach->init();
			
				$attachHTML = $this->class_attach->renderAttachments( '', $mapIds );

				/* Now parse back in the rendered posts */
				foreach( $attachHTML as $id => $data )
				{
					$returnHTML	.= $data['attachmentHtml'];
				}
			}
		}

		return $returnHTML;
	}
	
	/**
	 * Display field in preview
	 *
	 * @access	public
	 * @param	array 		Field data
	 * @param	array		Record data
	 * @param	int			Number of characters to truncate at (0 means no truncating)
	 * @return	string		Data to display
	 */
	public function getFieldValuePreview( $field, $record=array(), $truncate=0 )
	{
		$returnHTML	= '';
				
		if( $field['field_type'] == 'attachments' )
		{
			if( $truncate )
			{
				return sprintf( $this->lang->words['_attachments_count'], $fieldValue );
			}

			$attachIds	= array();
			
			$this->DB->build( array( 'select' => '*', 'from' => 'attachments', 'where' => "attach_rel_module='ccs' AND attach_post_key='{$record['post_key']}'" ) );
			$this->DB->execute();
			
			while( $r = $this->DB->fetch() )
			{
				$attachIds[]	= $r['attach_id'];
			}

			if( count($attachIds) )
			{
				$this->registry->class_localization->loadLanguageFile( array( 'public_topic' ), 'forums' );
				
				if ( ! is_object( $this->class_attach ) )
				{
					require_once( IPSLib::getAppDir( 'core' ) . '/sources/classes/attach/class_attach.php' );
					$this->class_attach = new class_attach( $this->registry );
				}
			
				$this->class_attach->type  = 'ccs';
				$this->class_attach->init();

				//-----------------------------------------
				// Create the 'fake' html for preview
				//-----------------------------------------
				
				$_attachHtml	= '';
				
				foreach( $attachIds as $_attachId )
				{
					$_attachHtml .= "[attachment={$_attachId}:test]<br /><br />";
				}
				
				$attachHTML = $this->class_attach->renderAttachments( $_attachHtml );

				/* Now parse back in the rendered posts */
				foreach( $attachHTML as $id => $data )
				{
					$returnHTML	.= $data['html'] . $data['attachmentHtml'];
				}
			}
		}

		return $returnHTML;
	}
	
	/**
	 * Produce where clause based on search string
	 *
	 * @access	public
	 * @param	array 		Field data
	 * @param	string		Supplid value
	 * @return	string		Data to display
	 */
	public function getSearchWhere( $field, $search='' )
	{
		//-----------------------------------------
		// Cannot search attachments
		//-----------------------------------------
		
		return '';
	}

	/**
	 * Compare two versions of a particular field
	 *
	 * @access	public
	 * @param	array 		Field data
	 * @param	string		Current data in the field
	 * @param	string		Previous data in the field
	 * @return	string		HTML revisions differences
	 */
	public function compareRevision( $field, $current, $previous )
	{
		if( $field['field_type'] == 'attachments' )
		{
			if( $current == $previous )
			{
				return $current;
			}
			else
			{
				return "<ins>" . $current . "</ins> <del>" . $previous . "</del>";
			}
		}

		return '';
	}
}