<?php
/**
 * @package BILLETS
 * @link 	http://www.dioscouri.com
 * @license GNU/GPLv2
 */
 
// no direct access
defined('_JEXEC') or die('Restricted access');

// ************************************************************************/
//					
/**					FUNCTIONS
/**
// ************************************************************************/
function billetsGetItemid() {
	global $Itemid;
	$id = $Itemid;
	$database = JFactory::getDBO();
	$link = "index.php?option=com_billets";
	$query = " SELECT * FROM #__menu "
	. " WHERE `link` LIKE '%".$link."%' "
	. " ORDER BY `link` ASC "
	;
	$database->setQuery($query);
	if ( $item = $database->loadObject() ) {
		$id = $item->id;		
	}
	return $id;		
}

/**
* returns TRUE/FALSE after emailing message
* 
// ************************************************************************/
function billetsMail ( $from, $fromname, $recipient, $subject, $body, $actions=NULL, $mode=NULL, $cc=NULL, $bcc=NULL, $attachment=NULL, $replyto=NULL, $replytoname=NULL ) {
	// $actions = array
		// store the message somewhere else?
		// actually send the email?
		// add text to the body of the email?

	$body .= _BILLETS_EMAIL_SIGNATURE;

	return JUTility::sendMail($from, $fromname, $recipient, $subject, $body, $mode, $cc, $bcc, $attachment, $replyto, $replytoname );

} // end billetsMail
// ************************************************************************

/**
* Returns SupportTicketSubjectOptions
*
// ************************************************************************/
function billetsSupportTicketTypeOptions ( ) {
	// should be grabbed from database
	$types[] = "_BILLETS_GENERALSUPPORT";
	$types[] = "_BILLETS_WEBSITEINTEGRATION";
	$types[] = "_BILLETS_FEESBILLING";
	$types[] = "_BILLETS_FEATUREREQUEST";
	$types[] = "_BILLETS_BUGREPORT";
	$types[] = "_BILLETS_OTHER";
	return $types;
}
// ************************************************************************

/**
* billetsSupportTicketStatus
*
// ************************************************************************/
function billetsSupportTicketStatus ( $id ) {
	switch ($id) {
	  case "3": return _BILLETS_REQUIRESUSERFEEDBACK; break;
	  case "2": return _BILLETS_CLOSED; break;
	  case "1": return _BILLETS_RESOLVED; break;
	  case "0": return _BILLETS_PENDINGRESOLUTION; break;
	  default: return _BILLETS_PENDINGRESOLUTION; break;
	} // end switch transactionStatusId
}
// ************************************************************************

/**
* Returns billetsSupportTicketStatus image
*
// ************************************************************************/
function billetsSupportTicketStatusImage ( $id ) {
	global $mainframe;
	
	switch ($id) {
	  case "3": return "<img src='".$mainframe->getCfg('live_site')."/components/com_billets/images/status/requirefeedback.png' alt='"._BILLETS_REQUIRESUSERFEEDBACK."' title='"._BILLETS_REQUIRESUSERFEEDBACK."' name='"._BILLETS_REQUIRESUSERFEEDBACK."'>"; break;
	  case "2": return "<img src='".$mainframe->getCfg('live_site')."/components/com_billets/images/status/completed.gif' alt='"._BILLETS_CLOSED."' title='"._BILLETS_CLOSED."' name='"._BILLETS_CLOSED."'>"; break;
	  case "1": return "<img src='".$mainframe->getCfg('live_site')."/components/com_billets/images/status/completed.gif' alt='"._BILLETS_RESOLVED."' title='"._BILLETS_RESOLVED."' name='"._BILLETS_RESOLVED."'>"; break;
	  case "0": return "<img src='".$mainframe->getCfg('live_site')."/components/com_billets/images/status/pending.png' alt='"._BILLETS_PENDINGRESOLUTION."' title='"._BILLETS_PENDINGRESOLUTION."' name='"._BILLETS_PENDINGRESOLUTION."'>"; break;
	  default: return "<img src='".$mainframe->getCfg('live_site')."/components/com_billets/images/status/pending.png' alt='"._BILLETS_PENDINGRESOLUTION."' title='"._BILLETS_PENDINGRESOLUTION."' name='"._BILLETS_PENDINGRESOLUTION."'>"; break;
	} // end switch transactionStatusId
} // end billetsSupportTicketStatusImage
// ************************************************************************

/**
* billetsFeedbackRating
*
// ************************************************************************/
function billetsFeedbackRating ( $id ) {
	switch ($id) {
	  case "5": return _BILLETS_GREAT; break;
	  case "4": return _BILLETS_GOOD; break;
	  case "3": return _BILLETS_AVERAGE; break;
	  case "2": return _BILLETS_POOR; break;
	  case "1": return _BILLETS_UNSATISFACTORY; break;
	  default: return _BILLETS_UNRATED; break;
	} // end switch

} // end billetsFeedbackRating
// ************************************************************************

/**
* billetsFeedbackRatingImage
*
// ************************************************************************/
function billetsFeedbackRatingImage ( $num ) {
	global $mainframe;
	
	if ($num <= '0') 					 { $id = "0"; }
	elseif ($num > '0' && $num < '0.5') { $id = "0"; }
	elseif ($num >= '0.5' && $num <= '1') { $id = "1"; }
	elseif ($num > '1' && $num < '1.5') { $id = "1.5"; }
	elseif ($num >= '1.5' && $num <= '2') { $id = "2"; }
	elseif ($num > '2' && $num < '2.5') { $id = "2.5"; }
	elseif ($num >= '2.5' && $num <= '3') { $id = "3"; }
	elseif ($num > '3' && $num < '3.5') { $id = "3.5"; }
	elseif ($num >= '3.5' && $num <= '4') { $id = "4"; }
	elseif ($num > '4' && $num < '4.5') { $id = "4.5"; }
	elseif ($num >= '4.5' && $num <= '5') { $id = "5"; }

	
	switch ($id) {
	  case "5": return "<img src='".$mainframe->getCfg('live_site')."/components/com_billets/images/feedback/great.png' alt='"._BILLETS_GREAT."' title='"._BILLETS_GREAT."' name='"._BILLETS_GREAT."' align='center' border='0'>"; break;
	  case "4.5": return "<img src='".$mainframe->getCfg('live_site')."/components/com_billets/images/feedback/great_half.png' alt='"._BILLETS_GREAT."' title='"._BILLETS_GREAT."' name='"._BILLETS_GREAT."' align='center' border='0'>"; break;
	  case "4": return "<img src='".$mainframe->getCfg('live_site')."/components/com_billets/images/feedback/good.png' alt='"._BILLETS_GOOD."' title='"._BILLETS_GOOD."' name='"._BILLETS_GOOD."' align='center' border='0'>"; break;
	  case "3.5": return "<img src='".$mainframe->getCfg('live_site')."/components/com_billets/images/feedback/good_half.png' alt='"._BILLETS_GOOD."' title='"._BILLETS_GOOD."' name='"._BILLETS_GOOD."' align='center' border='0'>"; break;
	  case "3": return "<img src='".$mainframe->getCfg('live_site')."/components/com_billets/images/feedback/average.png' alt='"._BILLETS_AVERAGE."' title='"._BILLETS_AVERAGE."' name='"._BILLETS_AVERAGE."' align='center' border='0'>"; break;
	  case "2.5": return "<img src='".$mainframe->getCfg('live_site')."/components/com_billets/images/feedback/average_half.png' alt='"._BILLETS_AVERAGE."' title='"._BILLETS_AVERAGE."' name='"._BILLETS_AVERAGE."' align='center' border='0'>"; break;
	  case "2": return "<img src='".$mainframe->getCfg('live_site')."/components/com_billets/images/feedback/poor.png' alt='"._BILLETS_POOR."' title='"._BILLETS_POOR."' name='"._BILLETS_POOR."' align='center' border='0'>"; break;
	  case "1.5": return "<img src='".$mainframe->getCfg('live_site')."/components/com_billets/images/feedback/poor_half.png' alt='"._BILLETS_POOR."' title='"._BILLETS_POOR."' name='"._BILLETS_POOR."' align='center' border='0'>"; break;
	  case "1": return "<img src='".$mainframe->getCfg('live_site')."/components/com_billets/images/feedback/unsatisfactory.png' alt='"._BILLETS_UNSATISFACTORY."' title='"._BILLETS_UNSATISFACTORY."' name='"._BILLETS_UNSATISFACTORY."' align='center' border='0'>"; break;
	  default: return "<img src='".$mainframe->getCfg('live_site')."/components/com_billets/images/feedback/unrated.png' alt='"._BILLETS_UNRATED."' title='"._BILLETS_UNRATED."' name='"._BILLETS_UNRATED."' align='center' border='0'>"; break;
	} // end switch

} // end billetsFeedbackRatingImage
// ************************************************************************

// ************************************************************************/
//					
/**					CLASSES
/**
// ************************************************************************/
// needs Joomla installer class
require_once(JPATH_SITE.'/libraries/joomla/installer/installer.php');

// ************************************************************************
class billetsAddonEntry extends JTable {

	var $id					= null;
	var $type	  			= null; // varchar(255)
	var $title  			= null; // varchar(255)
	var $description 		= null; // int(11)
	var $filename	 		= null; // int(11)
	var $published	 		= null; // int(11)
	var $order		 		= null; // int(11)
	var $access 			= null; // datetime
	var $iscore 			= null; // tinyint(1)
	var $checked_out 		= null; // varchar(255)
	var $checked_out_time 	= null; // tinyint(1)
	var $version 			= null; // text 	
	var $created_datetime 	= null; // datetime 			
	var $author_name 		= null; // datetime 	
	var $author_email 		= null; // datetime 	
	var $author_url 		= null; // datetime 	

	function billetsAddonEntry( &$db ) {
		parent::__construct( '#__billets_addons', 'id', $db );
	}
	
	/** overloaded check function */
	function check() {
		/** check for valid name */
		if (trim( $this->title ) == '') {
			$this->_errors[] = _BILLETS_TITLEBLANK;
			return false;
		}

		/** check for existing name */
		$query = "SELECT id"
		. "\n FROM #__billets_addons "
		. "\n WHERE `filename` = " . $this->_db->Quote( $this->filename )
		;
		$this->_db->setQuery( $query );

		$xid = intval( $this->_db->loadResult() );
		if ($xid && $xid != intval( $this->id )) {
			$this->_errors[] = _BILLETS_ADDONEXISTS;
			return false;
		}

		return true;

	}	
} // end class billetsAddonEntry
// ************************************************************************

// ************************************************************************
class billetsAddon extends JInstaller {


	/**
	* getAddonAttribute
	*/
	// ************************************************************************/
	function getAddonAttribute( $filename, $type, $attribute ) {
		
			// change folder
			switch ($type) {
				case "mod":
					$baseDir = JPATH_COMPONENT_ADMINISTRATOR.DS.'modules';
					$dirname = "modules";
				  break;
				case "lang":
					$baseDir = JPATH_COMPONENT_SITE.DS.'languages';
					$dirname = "languages";
				  break;
				default:
					$this->setError( _BILLETS_NOFILETYPESELECTED );				
					return false;
				  break;
			} // end switch type


		if (file_exists( $baseDir . DS . $filename . ".php" )) { 
			// get the contents of the file 
			$contents = file_get_contents( $baseDir . DS . $filename . ".php" );
		} else {
			$this->setError( _BILLETS_NOFILE." - ".$baseDir . DS . $filename . ".php" ); 
			return false; 
		}

		$return = "";
		// define the regular expression
		$regex = "#<".$attribute."(.*?)>(.*?)</".$attribute.">#s";
		
		//Find all instances of plugin and put in $matches
		preg_match_all( $regex, $contents, $matches );
		
		//Number of instances
		$count = count( $matches[0] );
					 
		//if instances 
		if ( $count ) {
			//Get parameters
			unset($thisposition);

			$thisposition[0] = $matches[0][0]; // the full text of the matches {attribute params}contents{/attribute}
			$thisposition[1] = $matches[1][0]; // the params {attribute THIS}contents{/attribute}
			$thisposition[2] = $matches[2][0]; // the contents {attribute}THIS{/attribute}
			$return = $matches[2][0]; // the contents {attribute}THIS{/attribute}
		}
		
		return $return;
	} // end getAddonAttribute
	// ************************************************************************/

	/**
	* install
	*/
	// ************************************************************************	
	function installAddon( $filename, $type ) {
		global $mainframe;
		$database = &JFactory::getDBO();

		if (!$type) {
			$this->setError( _BILLETS_NOFILETYPESELECTED );
			return false;
		}	
		
		// Insert into DB
		$query = "SELECT `id` FROM #__billets_addons "
		. "\n WHERE `type` = " . $database->Quote( $type )
		. " AND `filename` = " . $database->Quote( $filename )
		;
		$database->setQuery( $query );
		if (!$database->query()) {
			$this->setError( 'SQL error: ' . $database->stderr( true ) );
			return false;
		}

		$id = $database->loadResult();
		if ($id) {
			$this->setError( _BILLETS_ADDON.' "' . $filename . '"'._BILLETS_ALREADYEXISTS.'!' );
			return false;
		}
		
		if (!$id) {
			//	  <name>Add-on Name</name>
			//    <author>Dioscouri.com</author>
			//    <authorEmail>info@dioscouri.com</authorEmail>
			//    <authorUrl>http://www.dioscouri.com</authorUrl>
			//    <version>0.1</version>
			//    <creationDate>2008-02-01</creationDate>
			//    <description>This Add-on does this function.</description>
		
			$row = new billetsAddonEntry( $database );
			$row->type			= $type;
			$row->filename		= $filename;
			$row->iscore 		= 0;
			$row->title 		= $this->getAddonAttribute( $filename, $type, "name" );
			$row->description	= $this->getAddonAttribute( $filename, $type, "description" );
			$row->version 		= $this->getAddonAttribute( $filename, $type, "version" );
			$row->created_datetime 	= $this->getAddonAttribute( $filename, $type, "creationDate" );
			$row->author_name 		= $this->getAddonAttribute( $filename, $type, "author" );
			$row->author_email 		= $this->getAddonAttribute( $filename, $type, "authorEmail" );
			$row->author_url 		= $this->getAddonAttribute( $filename, $type, "authorUrl" );
			$row->store();
			return true;
		} 
	} // end installAddon
	// ************************************************************************	
	
	/**
	* uninstall
	*/
	// ************************************************************************	
	function uninstallAddon( $id, $option, $client=0 ) {
		global $database, $mosConfig_absolute_path;

		$id = intval( $id );

		$query = "SELECT module, iscore, client_id"
		. "\n FROM #__modules WHERE id = " . (int) $id
		;
		$database->setQuery( $query );
		$row = null;
		$database->loadObject( $row );

		if ($row->iscore) {
			HTML_installer::showInstallMessage( $row->title .'is a core module, and can not be uninstalled.<br />You need to unpublish it if you don\'t want to use it', 'Uninstall -  error', $this->returnTo( $option, 'module', $row->client_id ? '' : 'admin' ) );
			exit();
		}

		$query = "SELECT id"
		. "\n FROM #__modules"
		. "\n WHERE module = " . $database->Quote( $row->module ) . " AND client_id = " . (int) $row->client_id
		;
		$database->setQuery( $query );
		$modules = $database->loadResultArray();

		if (count( $modules )) {
			mosArrayToInts( $modules );
			$modID = 'moduleid=' . implode( ' OR moduleid=', $modules );

			$query = "DELETE FROM #__modules_menu"
			. "\n WHERE ( $modID )"
			;
			$database->setQuery( $query );
			if (!$database->query()) {
				$msg = $database->stderr;
				die( $msg );
			}


    		$query = "DELETE FROM #__modules"
    		. "\n WHERE module = " . $database->Quote( $row->module ) . " AND client_id = " . (int) $row->client_id
    		;
    		$database->setQuery( $query );
    		if (!$database->query()) {
    			$msg = $database->stderr;
    			die( $msg );
    		}

    		if ( !$row->client_id ) {
    			$basepath = $mosConfig_absolute_path . '/modules/';
    		} else {
    			$basepath = $mosConfig_absolute_path . '/administrator/modules/';
    		}

      		$xmlfile = $basepath . $row->module . '.xml';

    		// see if there is an xml install file, must be same name as element
    		if (file_exists( $xmlfile )) {
    			$this->i_xmldoc = new DOMIT_Lite_Document();
    			$this->i_xmldoc->resolveErrors( true );

    			if ($this->i_xmldoc->loadXML( $xmlfile, false, true )) {
    				$mosinstall =& $this->i_xmldoc->documentElement;
    				// get the files element
    				$files_element =& $mosinstall->getElementsByPath( 'files', 1 );
    				if (!is_null( $files_element )) {
    					$files = $files_element->childNodes;
    					foreach ($files as $file) {
    						// delete the files
    						$filename = $file->getText();
    						if (file_exists( $basepath . $filename )) {
    							$parts = pathinfo( $filename );
    							$subpath = $parts['dirname'];
    							if ($subpath != '' && $subpath != '.' && $subpath != '..') {
    								echo '<br />Deleting: '. $basepath . $subpath;
    								$result = deldir(mosPathName( $basepath . $subpath . '/' ));
    							} else {
    								echo '<br />Deleting: '. $basepath . $filename;
    								$result = unlink( mosPathName ($basepath . $filename, false));
    							}
    							echo intval( $result );
    						}
    					}

    					// remove XML file from front
    					echo "Deleting XML File: $xmlfile";
    					@unlink(  mosPathName ($xmlfile, false ) );
    					return true;
    				}
    			}
    		}
		}

	} // end uninstallAddon
	// ************************************************************************	
		
	/**
	* cleanupInstall
	*/
	// ************************************************************************	
	function cleanupInstallAddon( $userfile_name, $resultdir) {
		global $mosConfig_absolute_path;
	
		if (file_exists( $resultdir )) {
			deldir( $resultdir );
			unlink( mosPathName( $mosConfig_absolute_path . '/media/' . $userfile_name, false ) );
		}
	} // end cleanupInstallAddon
	// ************************************************************************

	/**
	* deldir
	*/
	// ************************************************************************		
	function deldirAddon( $dir ) {
		$current_dir = opendir( $dir );
		$old_umask = umask(0);
		while ($entryname = readdir( $current_dir )) {
			if ($entryname != '.' and $entryname != '..') {
				if (is_dir( $dir . $entryname )) {
					deldir( mosPathName( $dir . $entryname ) );
				} else {
					@chmod($dir . $entryname, 0777);
					unlink( $dir . $entryname );
				}
			}
		}
		umask($old_umask);
		closedir( $current_dir );
		return rmdir( $dir );
	} // end deldirAddon
	// ************************************************************************

	/**
	* uploadAddonFile
	*/
	// ************************************************************************
	function uploadAddonFile( $filename, $userfile_name, $type, &$msg ) {
		jimport('joomla.filesystem.path');

			// change folder
			switch ($type) {
				case "mod":
					$baseDir = JPATH_COMPONENT_ADMINISTRATOR.DS.'modules';
					$dirname = "modules";
				  break;
				case "lang":
					$baseDir = JPATH_COMPONENT_SITE.DS.'languages';
					$dirname = "languages";
				  break;
				default:
					$this->setError( _BILLETS_NOFILETYPESELECTED );				
					return false;
				  break;
			} // end switch type

		if (file_exists( $baseDir . DS . $userfile_name )) { $this->setError( _BILLETS_ADDON.' "' . $filename . '"'._BILLETS_ALREADYEXISTS.'!' ); return false; }
	
		if (file_exists( $baseDir )) {
			if (is_writable( $baseDir )) {
				if (move_uploaded_file( $filename, $baseDir . DS . $userfile_name )) {
					if (JPath::setPermissions( $baseDir . DS . $userfile_name )) {
						return true;
					} else {
						$this->setError( _BILLETS_COULDNOTCHANGEPERMISSIONSOFFILE );
					}
				} else {
					$this->setError( _BILLETS_COULDNOTMOVEFILETO.' <code>/'.$dirname.'</code>' );
				}
			} else {
				$this->setError( '<code>/'.$dirname.'</code> '._BILLETS_NOTWRITEABLE );
			}
		} else {
			$this->setError( '<code>/'.$dirname.'</code> '._BILLETS_DOESNOTEXIST );
		}
		return false;
	} // end uploadAddonFile
	// ************************************************************************
} // end class billetsAddon
// ************************************************************************

// ************************************************************************
class billetsTicket extends JTable {
 	 	 	 	 	 	
	var $id						= null;

	var $sender_email 			= null; // varchar(255)
	var $sender_userid 			= null; // int(11)
	var $sender_read_datetime	= null; // date	
	var $sender_flag_read		= null; // int(1)
	
	var $subject				= null; // varchar(255)
	var $description			= null;
	
	var $type					= null; 
	var $entrytype				= null; 
	var $entryid				= null;
	var $target_datetime		= null;	
	var $manager_userid			= null; 
	var $status					= null; 

	var $feedback_by			= null; 
	var $feedback_datetime		= null; 
	var $feedback_rating		= null; 
	var $closed_by				= null;
	var $closed_datetime		= null;
	
	var $created_by				= null;
	var $created_datetime		= null;
	var $last_modified_by		= null;
	var $last_modified_datetime = null;
	var $published				= null;
	var $followup				= null;
	
	var $firstresponse_by			= null;
	var $firstresponse_datetime		= null;
	
	function billetsTicket( &$db ) {
		parent::__construct( '#__billets_tickets', 'id', $db );
	}
	
	// check -- only one ticket per transaction
	/** overloaded check function */
	function check() {
		return true;
	}
	
} // end class supportTicket
// ************************************************************************

// ************************************************************************
class billetsMessage extends JTable {
 	 	 	 	 	 	
	var $id					= null;
	var $ticketid			= null;
	var $userid_from		= null; // int(11)
	var $username_from		= null; // varchar(255)
	var $subject			= null; // varchar(255)
	var $message			= null; // text
	var $priority			= null; // int(1)
	var $datetime			= null; // date
		
	function billetsMessage( &$db ) {
		parent::__construct( '#__billets_messages', 'id', $db );
	}
} // end class supportMessage
// ************************************************************************/

// ************************************************************************
class billetsModule extends JTable {

	var $id					= null;
	var $type	  			= null; // varchar(255)
	var $title  			= null; // varchar(255)
	var $description 		= null; // int(11)
	var $filename	 		= null; // int(11)
	var $published	 		= null; // int(11)
	var $order		 		= null; // int(11)
	var $access 			= null; // datetime
	var $iscore 			= null; // tinyint(1)
	var $checked_out 		= null; // varchar(255)
	var $checked_out_time 	= null; // tinyint(1)
	var $version 			= null; // text 	
	var $created_datetime 	= null; // datetime 			
	var $author_name 		= null; // datetime 	
	var $author_email 		= null; // datetime 	
	var $author_url 		= null; // datetime 	

	function billetsModule( &$db ) {
		parent::__construct( '#__billets_addons', 'id', $db );
	}
	
	/** overloaded check function */
	function check() {
		/** check for valid name */
		if (trim( $this->title ) == '') {
			$this->_errors[] = _BILLETS_TITLEBLANK;
			return false;
		}

		/** check for existing name */
		$query = "SELECT id"
		. "\n FROM #__billets_addons "
		. "\n WHERE `filename` = " . $this->_db->Quote( $this->filename )
		;
		$this->_db->setQuery( $query );

		$xid = intval( $this->_db->loadResult() );
		if ($xid && $xid != intval( $this->id )) {
			$this->_errors[] = _BILLETS_MODULEEXISTS;
			return false;
		}

		return true;

	}	
} // end class billetsModule
// ************************************************************************
