<?php

/**
 * <pre>
 * Invision Power Services
 * Single file upload field
 * 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		15th Feb 2010
 * @version		$Revision: 67 $
 */

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

class fields_upload
{
	/**#@+
	 * 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		= '';
	
	/**
	 * 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( 'upload', $this->lang->words['field_type__upload'] ),
					);
	}
	
	/**
	 * 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'];
		
		if( $type == 'upload' )
		{
			$_return	= $this->registry->output->formUpload( 'field_' . $id );
			
			if( $default )
			{
				$_return	.= '<br /> ' . $this->registry->output->formCheckbox( 'field_' . $id . '_remove' )  . $this->lang->words['rm_uf__file'];
				$_return	.= "<div class='desctext'>{$this->lang->words['uploadfield__already']}</div>";
			}
			
			return $_return;
		}
		
		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'];
		
		if( $type == 'upload' )
		{
			$_return	= "<input type='file' name='field_{$id}' id='field_{$id}' size='30' />";
			
			if( $default )
			{
				$_return	.= " <input type='checkbox' class='input_check' value='1' name='field_{$id}_remove' />" . $this->lang->words['rm_uf__file'];
				$_return	.= "<div class='desctext'>{$this->lang->words['uploadfield__already']}</div>";
			}
			
			return $_return;
		}
		
		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 )
	{
		$value	= '';
		
		if( $this->request['record'] )
		{
			$_record	= $this->DB->buildAndFetch( array( 'select' => 'field_' . $field['field_id'], 'from' => 'ccs_custom_database_' . $field['field_database_id'], 'where' => 'primary_id_field=' . intval($this->request['record']) ) );
			
			$value		= $_record['field_' . $field['field_id'] ];
		}

		if( $field['field_type'] == 'upload' )
		{
			//-----------------------------------------
			// If we are editing, remove any existing file
			//-----------------------------------------

			if( $this->request['field_' . $field['field_id'] . '_remove'] )
			{
				if( $_record['field_' . $field['field_id'] ] )
				{
					$this->postProcessDelete( $field, $_record );
					
					$value	= '';
				}
			}
				
			//-----------------------------------------
			// Load the library
			//-----------------------------------------
			
			require_once( IPS_KERNEL_PATH . 'classUpload.php' );
			$upload	= new classUpload();

			//-----------------------------------------
			// Set up the variables
			//-----------------------------------------

			$upload->out_file_name		= md5( uniqid( microtime(), true ) );
			$upload->out_file_dir		= $this->settings['upload_dir'];
			$upload->upload_form_field	= 'field_' . $field['field_id'];
			
			if( $field['field_extra'] )
			{
				$upload->allowed_file_ext	= explode( ',', $field['field_extra'] );
			}
			else
			{
				$upload->check_file_ext		= false;
			}

			//-----------------------------------------
			// Upload...
			//-----------------------------------------
			
			$upload->process();
			
			//-----------------------------------------
			// Error?
			//-----------------------------------------
			
			if ( $upload->error_no )
			{
				if( $upload->error_no > 1 OR ( $field['field_required'] AND !$value ) )
				{
					$this->error	= $this->lang->words['field_upload_error__' . $upload->error_no ];
				}

				return $value;
			}
			else
			{
				//-----------------------------------------
				// Successful upload, delete old file
				//-----------------------------------------
				
				if( $this->request['record'] )
				{
					$this->postProcessDelete( $field, $_record );
				}
			}
	
			//-----------------------------------------
			// Still here?
			//-----------------------------------------
			
			return $upload->parsed_file_name;
		}

		return $value;
	}
	
	/**
	 * 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 )
	{
		return false;
	}
	
	/**
	 * Record deletion callback
	 *
	 * @access	public
	 * @param	array 		Field data
	 * @param	array		Record data
	 * @return	bool		Handled successfully or not
	 */
	public function postProcessDelete( $field, $record )
	{
		//-----------------------------------------
		// Delete the file
		//-----------------------------------------
		
		if( $record['field_' . $field['field_id'] ] )
		{
			if( file_exists( $this->settings['upload_dir'] . "/" . $record['field_' . $field['field_id'] ] ) )
			{
				@unlink( $this->settings['upload_dir'] . "/" . $record['field_' . $field['field_id'] ] );
			}
		}
	}
	
	/**
	 * 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 '';
		}
				
		if( $field['field_type'] == 'upload' )
		{
			return $this->settings['upload_url'] . "/" . $fieldValue;
		}

		return '';
	}
	
	/**
	 * 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='' )
	{
		if( !$search )
		{
			return '';
		}

		if( $field['field_type'] == 'upload' )
		{
			if( $search )
			{
				return 'field_' . $field['field_id'] . " LIKE '%{$search}%'";
			}
		}

		return '';
	}
	
	/**
	 * Get a true difference report
	 *
	 * @access	public
	 * @param	string		Current text
	 * @param	string		Previous text
	 * @param	string		HTML to display
	 */
	public function getDifferenceReport( $current, $previous )
	{
		if( !is_object($this->differences) )
		{
			//-----------------------------------------
			// Get Diff library
			//-----------------------------------------
			
			require_once( IPS_KERNEL_PATH . 'classDifference.php' );
			$this->differences         = new classDifference();
			$this->differences->method = 'PHP';
		}
		
		$result	= $this->differences->getDifferences( IPSText::br2nl( $previous ), IPSText::br2nl( $current ) );
		
		if( $this->differences->diff_found )
		{
			$result	= str_replace( "\n", "<br>", $result );
			$result	= str_replace( "&gt;&lt;", "&gt;\n&lt;", $result );
			$result	= preg_replace( "#(?<!(\<del|\<ins)) {1}(?!:style)#i", "&nbsp;", $result );
			$result	= str_replace( "\t", "&nbsp; &nbsp; ", $result );
			//$result	= str_replace( "&lt;br&nbsp;/&gt;", "<br />", $result );
		}
		else
		{
			$result	= $current;
		}
		
		return $result;
	}
	
	/**
	 * 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'] == 'upload' )
		{
			$key	= 'field_' . $field['field_id'];
			return $current == $previous ? $this->getFieldValue( $field, array( $key => $current ) ) : "<ins>" . $this->getFieldValue( $field, array( $key => $current ) ) . "</ins> <del>" . $this->getFieldValue( $field, array( $key => $previous ) ) . "</del>";
		}

		return '';
	}
}