<?php
/**
* Joomla Community Builder User Plugin: plug_cbprofilegallery
* @version $Id$
* @package plug_cbprofilegallery
* @subpackage cb.profilegallery.php
* @author Nant, JoomlaJoe and Beat
* @copyright (C) Nant, JoomlaJoe and Beat, www.joomlapolis.com
* @license Limited  http://www.gnu.org/copyleft/gpl.html GNU/GPL
* @final 1.0 RC2
*/

/** ensure this file is being included by a parent file */
defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );

$_PLUGINS->registerFunction( 'onAfterDeleteUser', 'userDeleted','getProfileGalleryTab' );

/**
 * Management Tab still under construction
 *
 */
class getProfileGalleryManagementTab extends cbTabHandler {
	/**
	 * Construnctor
	 */
	function getProfileGalleryManagementTab() {
		$this->cbTabHandler();
	}
	
	/**
	 * Includes the plugin's own language file
	 * @access  private
	 */
	function _getLanguageFile() {
		global $mainframe,$mosConfig_lang;
		$UElanguagePath=$mainframe->getCfg( 'absolute_path' ).'/components/com_comprofiler/plugin/user/plug_cbprofilegallery';
		if (file_exists($UElanguagePath.'/language/'.$mosConfig_lang.'.php')) {
		  include_once($UElanguagePath.'/language/'.$mosConfig_lang.'.php');
		} else include_once($UElanguagePath.'/language/english.php');	
	}
	
	/**
	 * Get all plugin, tab, and CB fields related with this application
	 * @access private
	 * @param object mosUser reflecting the user being displayed
	 */
	function _pgGetTabParameters($user){

		$params = $this->params;
		
		// Plugin Parameters
		$TabParams["pgmanagementtabenabled"] = $params->get('pgManagementTabEnabled', 0);
		$TabParams["pgmoderatornotification"] = $params->get('pgModeratorNotification', 1);
		
		return $TabParams;
	}
	
	/**
	* Generates the HTML to display the user profile tab
	* @param object tab reflecting the tab database entry
	* @param object mosUser reflecting the user being displayed
	* @param int 1 for front-end, 2 for back-end
	* @returns mixed : either string HTML for tab content, or false if ErrorMSG generated
	*/
	function getDisplayTab($tab,$user,$ui) {
		global $my,$mainframe,$mosConfig_lang;
		
		$this->_getLanguageFile();
		$tabparams=$this->_pgGetTabParameters($user);

		$htmltext1 = "";
		if (!$tabparams["pgmanagementtabenabled"]) return $htmltext1;
		// Is user a moderator?
		$isModerator=isModerator($my->id);
		if (!$isModerator) return $htmltext1;
		if($tab->description != null) {
			$htmltext1 .= "\t\t<div class=\"tab_Description\">";
			$htmltext1 .= unHtmlspecialchars(getLangDefinition($tab->description));
			$htmltext1 .= "</div>\n";
			$htmltext1 .= "<br />\n";
			$htmltext1 .= "Feature not available yet\n";
			$htmltext1 .= "<br />\n";
		}
		return $htmltext1;
	}
}

/**
 * Profile Gallery Tab
 *
 */
class getProfileGalleryTab extends cbTabHandler {
	/**
	* Constructor
	*/
	function getProfileGalleryTab() {
		$this->cbTabHandler();
	}
	
	/**
	 * Includes the plugin's own language file
	 * @access  private
	 */
	function _getLanguageFile() {
		global $mainframe,$mosConfig_lang;
		$UElanguagePath=$mainframe->getCfg( 'absolute_path' ).'/components/com_comprofiler/plugin/user/plug_cbprofilegallery';
		if (file_exists($UElanguagePath.'/language/'.$mosConfig_lang.'.php')) {
		  include_once($UElanguagePath.'/language/'.$mosConfig_lang.'.php');
		} else include_once($UElanguagePath.'/language/english.php');	
	}
	
	/**
	 * This function returnd an array of parameter and field settings (values)
	 * used though-out the gallery plugin.
	 * @access private
	 * @param object mosUser reflecting the user being displayed
	 */
	function _pgGetTabParameters($user){

		$params = $this->params;
		
		// Plugin Parameters
		$TabParams["pgmanagementtabenabled"] = $params->get('pgManagementTabEnabled', 1);
		$TabParams["pgmoderatornotification"] = $params->get('pgModeratorNotification', 1);
		
		// Tab Parameters
		$TabParams["pggalleryautoenabled"] = $params->get('pgGalleryAutoEnabled', 1);
		$TabParams["pgpagingenabled"] = $params->get('pgPagingEnabled', 1);
		$TabParams["pgopmode"] = $params->get('pgOpMode','IMAGEMODE');
		$TabParams["pgimagefiletypelist"] = $params->get('pgImageFileTypeList', 'jpg,gif,png');
		$TabParams["pgotherfiletypelist"] = $params->get('pgOtherFileTypeList', 'zip,doc,pdf,txt');
		$TabParams["pgsortoption"] = $params->get('pgSortOption','DATEDESC');
		$TabParams["pgaccessmode"] = $params->get('pgAccessMode','REG');
		$TabParams["pgallowaccessmodeoverride"] = $params->get('pgAllowAccessModeOverride',1);
		$TabParams["pgallowmoderatorfrontenduploads"] = $params->get('pgAllowModeratorFrontEndUploads',1);
		$TabParams["pgdisplayformat"] = $params->get('pgDisplayFormat','DF1');
		$TabParams["pgdisplayformatparameters"] = $params->get('pgDisplayFormatParameters','10,...,100,0,70,10');
		
		if (substr_count($TabParams["pgdisplayformatparameters"],',')==5) {
			$TabParams["cbpgdisplayformatparameters"] = $TabParams["pgdisplayformatparameters"];
		} else {
			$TabParams["cbpgdisplayformatparameters"] = "10,...,100,0,70,10";
		}
		
		$TabParams["pgallowdisplayformatoverride"] = $params->get('pgAllowDisplayFormatOverride', 1);
		$TabParams["pgautopublish"] = $params->get('pgAutoPublish', 1);
		$TabParams["pgallowautopublishoverride"] = $params->get('pgAllowAutoPublishOverride', 0);
		$TabParams["pgautoapprove"] = $params->get('pgAutoApprove', 1);
		$TabParams["pgallowautoapproveoverride"] = $params->get('pgAllowAutoApproveOverride', 1);
		$TabParams["pgbuttonicons"] = $params->get('pgButtonIcons',0);
		$TabParams["pgiconlist"] = $params->get('pgIconList','delete.gif,unpublish.gif,publish.gif,approve.gif,revoke.gif,edit.gif');
		$TabParams["pgentriesperpage"] = $params->get('pgEntriesPerPage','5');
		$TabParams["pgmaxwidth"] = $params->get('pgMaxWidth', '500');
		$TabParams["pgmaxheight"] = $params->get('pgMaxHeight', '500');
		$TabParams["pgmaxsize"] = $params->get('pgMaxSize', '250');
		$TabParams["pgtnmaxwidth"] = $params->get('pgTNMaxWidth', '150');
		$TabParams["pgtnmaxheight"] = $params->get('pgTNMaxHeight', '150');
		$TabParams["pgnumberofgalleryitems"] = (is_numeric($params->get('pgNumberOfGalleryItems', '10'))) ? $params->get('pgNumberOfGalleryItems', '10') : 10;
		$TabParams["pgdefaultquota"] = $params->get('pgDefaultQuota', '1024');
		
		$TabParams["pgGalleryManagementEnabled"] = $params->get('pgGalleryManagementEnabled', 0);
		
		if ($TabParams["pgbuttonicons"]) {
			if (substr_count($TabParams["pgiconlist"],',')==4) {
				$TabParams["cbpgbuttonslist"] = $TabParams["pgiconlist"];
			} else {
				$TabParams["cbpgbuttonslist"] = "delete_f2.png,publish_f2.png,unpublish_f2.png,archive_f2.png,unarchive_f2.png,edit_f2.png";
			}
		} else {
			$TabParams["cbpgbuttonslist"] = "delete_f2.png,publish_f2.png,unpublish_f2.png,archive_f2.png,unarchive_f2.png,edit_f2.png";
		}

		// Get User Level Configuration Options (relevant CB fields)
		
		if ($TabParams["pgallowautopublishoverride"]) {
			if (!is_null($user->cb_pgautopublish)) {
				$TabParams["cbpgautopublish"] = ($user->cb_pgautopublish == '_UE_YES') ? 1 : 0;
			} else {
				$TabParams["cbpgautopublish"] = $TabParams["pgautopublish"];
			}
		} else {
			$TabParams["cbpgautopublish"] = $TabParams["pgautopublish"];
		}
		if ($TabParams["pgallowautoapproveoverride"]) {
			if (!is_null($user->cb_pgautoapprove)) {
				$TabParams["cbpgautoapprove"] = ($user->cb_pgautoapprove == '_UE_YES') ? 1 : 0;
			} else {
				$TabParams["cbpgautoapprove"] = $TabParams["pgautoapprove"];
			}
		} else {
			$TabParams["cbpgautoapprove"] = $TabParams["pgautoapprove"];
		}
		$TabParams["cbpguploadsize"] = (is_numeric($user->cb_pguploadsize)) ? $user->cb_pguploadsize : $TabParams["pgmaxsize"];

		$TabParams["cbpgtotalquotasize"] = (is_numeric($user->cb_pgtotalquotasize)) ? $user->cb_pgtotalquotasize : $TabParams["pgdefaultquota"];
		$TabParams["cbpgtotalitems"] = (is_numeric($user->cb_pgtotalitems)) ? $user->cb_pgtotalitems : 0;
		$TabParams["cbpgtotalsize"] = (is_numeric($user->cb_pgtotalsize)) ? $user->cb_pgtotalsize : 0;
	
		if ($TabParams["pggalleryautoenabled"]) {
			$TabParams["cbpgenable"] = 1;
		} else {
			$TabParams["cbpgenable"] = ($user->cb_pgenable == '_UE_YES') ? 1 : 0;
		}
	
		$TabParams["cbpglastupdate"] = $user->cb_pglastupdate;
		$TabParams["cbpgtotalquotaitems"] = (is_numeric($user->cb_pgtotalquotaitems)) ? $user->cb_pgtotalquotaitems : $TabParams["pgnumberofgalleryitems"];
		$TabParams["cbpgshortgreeting"] = $user->cb_pgshortgreeting;
	
		
		if ($TabParams["pgallowaccessmodeoverride"]) {
			if (!is_null($user->cb_pgaccessmode)) {
				$TabParams["cbpgaccessmode"] = $user->cb_pgaccessmode;
			} else {
				$TabParams["cbpgaccessmode"] = $TabParams["pgaccessmode"];
			}
		} else {
			$TabParams["cbpgaccessmode"] = $TabParams["pgaccessmode"];
		}
		
		if ($TabParams["pgallowdisplayformatoverride"]) {
			if (strlen($user->cb_pgdisplayformat)>0) {
				$TabParams["cbpgdisplayformat"] = $user->cb_pgdisplayformat;
			} else {
				$TabParams["cbpgdisplayformat"] = $TabParams["pgdisplayformat"];
			}
		} else {
			$TabParams["cbpgdisplayformat"] = $TabParams["pgdisplayformat"];
		}

		return $TabParams;
	}
	
	/**
	 * This function is called when a profile owner sumbits a new gallery item
	 * It should perform all validations and upload the file to the correct storage area and
	 * then call the _pgSave() function
	 * $this->_pgProcessNewItem($user->id,$pgautopublish,$pgtotalitems,$pgtotalsize);
	 * 
	 * @access private
	 * @param int $id gallery item id
	 * @param object mosUser reflecting the user being displayed
	 */
	function _pgProcessNewItem($id,&$user){
		global $my,$ueConfig,$mainframe,$mosConfig_lang;
		$this->_getLanguageFile();
		//$PGImagesAbsolutePath=$mainframe->getCfg( 'absolute_path' ).'/components/com_comprofiler/plugin/user/plug_cbprofilegallery/images/';
		$PGItemAbsolutePath=$mainframe->GetCfg( 'absolute_path' ).'/images/comprofiler/plug_profilegallery/';
		$PGItemPath= '/images/comprofiler/plug_profilegallery/';
		$html2return = "";

		$userid = $user->id;
		// Get all relevant tab parameters and user settings
		
		$tabparams = $this->_pgGetTabParameters($user);
		
		
		$pgitemfilename = $this->_getPagingParamName("pgitemfilename");
		$pgitemtitle = $_POST[$this->_getPagingParamName("pgitemtitle")];
		$pgitemdescription = $_POST[$this->_getPagingParamName("pgitemdescription")];
		$pgitemorder = "999"; // default setting for new feature
		
		$upload_pgitem_name = $_FILES[$pgitemfilename]['name'];
		$upload_pgitem_tmpname = $_FILES[$pgitemfilename]["tmp_name"];
		$upload_pgitem_type = $_FILES[$pgitemfilename]["type"];
		$upload_pgitem_size = $_FILES[$pgitemfilename]["size"];
		$upload_pgitem_error = $_FILES[$pgitemfilename]["error"];
		
		$upload_pgitem_nameparts = explode(".",$upload_pgitem_name);
		$upload_pgitem_ext = $upload_pgitem_nameparts[count($upload_pgitem_nameparts)-1];
		$upload_pgitem_baseparts = explode("." . $upload_pgitem_ext,$upload_pgitem_name); 
		$upload_pgitem_base = $upload_pgitem_baseparts[0];
		
		$upload_pgitem_base = str_replace(" ", "_", $upload_pgitem_base);
		
		$pgitemtype = $upload_pgitem_ext = strtolower($upload_pgitem_ext);
		
		// Check for valid upload!
		if (filesize($upload_pgitem_tmpname) == 0){
			$html2return .= "<font color=red>" . _pg_NoFileUploaded . "</font><br />";
			return $html2return;
		}
		

		list($in_width, $in_height, $in_type, $in_attr) = getimagesize($upload_pgitem_tmpname);
		
		// First check size of uploaded item and stop right away if size has exceeded
		// maximum allowable
		if ($upload_pgitem_size > $tabparams["cbpguploadsize"] * 1024) {
			$html2return .= "<font color=red>" . _pg_MaxSizeExceeded . "</font><br />";
			return $html2return;
		}
		
		// Generate random base name for upload
		mt_srand((double)microtime() * 1000000);
		$random_upload_pgitem_base = "pg_" . mt_rand();
		
		// Check file extension type
		$inimagelist = in_array($upload_pgitem_ext,explode(",",$tabparams["pgimagefiletypelist"]));
		$infilelist = in_array($upload_pgitem_ext,explode(",",$tabparams["pgotherfiletypelist"]));
		
		
		$consider_imgToolBox = 0;
		
		switch ($tabparams["pgopmode"]) {
			case 'IMAGEMODE': 
				if ( !$inimagelist) {
					$html2return .= "<font color=red>" . _pg_UnsupportedFileType . "</font><br />";
					return $html2return;
				}
				$consider_imgToolBox = 1;
				break;
			case 'FILEMODE' :
				if ( !$infilelist) {
					$html2return .= "<font color=red>" . _pg_UnsupportedFileType . "</font><br />";
					return $html2return;
				}
				$consider_imgToolBox = 0;
				break;
			case 'MIXEDMODE' :
				if ( !$infilelist && !$inimagelist) {
					$html2return .= "<font color=red>" . _pg_UnsupportedFileType . "</font><br />";
					return $html2return;
				} 
				if (!$infilelist) {
					$consider_imgToolBox = 1;
				}
				break;
			default :
				$consider_imgToolBox = 0;
				break;
		}
		
		
		
		// Categorize uploaded item based on type attribute
		$imgToolBox_needed_typecheck = 0;
		if ($consider_imgToolBox) {
			switch ($in_type) {
				case 1: // GIF
				case 2: // JPG
				case 3: // PNG
					$imgToolBox_needed_typecheck = 1;
					break;
				default: // Other TYPES
					$imgToolBox_needed_typecheck = 0;
					if ($pgitemtype == "gif" || $pgitemtype == "jpg" || $pgitemtype == "png") {
						// trying to upload non image as image extension
						$html2return .= "<font color=red>" . _pg_BadFile . "</font><br />";
						return $html2return;
					}
					break;
			}
		}
		
		// determine if user storage repository has been created (from some previous upload)
		// if not create it now and give it proper permissions!
		
		$PGItemAbsoluteUserPath = $PGItemAbsolutePath . $userid . "/";
		$PGItemUserPath = $PGItemPath . $userid . "/";
		if(!file_exists($PGItemAbsoluteUserPath)){
			if(mkdir($PGItemAbsolutePath . $userid,0755)) {
				IF(copy($PGItemAbsolutePath . "index.html", $PGItemAbsoluteUserPath . "index.html")) {
				// Success action or message would go here
				} ELSE {
					print "<font color=red>" . _pg_IndexCreationFailure . "</font><br />";
				}
				$html2return .= "<font color=green>" . _pg_GalleryAreaCreated . "</font><br />";
			} else {
				$html2return .= "<font color=red>" . _pg_GalleryAreaCreationFailed . "</font><br />";
				return $html2return;
			}
		}

		$final_uploaded_fullfilename = $PGItemAbsoluteUserPath . $random_upload_pgitem_base . "." . $upload_pgitem_ext;
		$final_uploaded_tn_fullfilename = $PGItemAbsoluteUserPath . "tn" . $random_upload_pgitem_base . "." . $upload_pgitem_ext;
		$final_uploaded_filename = $random_upload_pgitem_base . "." . $upload_pgitem_ext;
		
		// Check to see if filename is unique and make it unique if not
		$unique_suffix = 1;
		$new_upload_pgitem_base = $random_upload_pgitem_base;
		
		while (file_exists($final_uploaded_fullfilename)) {
			$new_upload_pgitem_base = $random_upload_pgitem_base . "_" . $unique_suffix++;
			$final_uploaded_fullfilename = $PGItemAbsoluteUserPath . $new_upload_pgitem_base . "." . $upload_pgitem_ext;
			$final_uploaded_tn_fullfilename = $PGItemAbsoluteUserPath . "tn" . $new_upload_pgitem_base . "." . $upload_pgitem_ext;
		}
		$final_uploaded_filename = $new_upload_pgitem_base . "." . $upload_pgitem_ext;
		
		if ($imgToolBox_needed_typecheck) {	
			$imgToolBox = new imgToolBox();
			$imgToolBox->_conversiontype=$ueConfig['conversiontype'];
			$imgToolBox->_IM_path = $ueConfig['im_path'];
			$imgToolBox->_NETPBM_path = $ueConfig['netpbm_path'];
			$imgToolBox->_maxsize = $tabparams["cbpguploadsize"];
			$imgToolBox->_maxwidth = $tabparams["pgmaxwidth"];
			$imgToolBox->_maxheight = $tabparams["pgmaxheight"];
			$imgToolBox->_thumbwidth = $tabparams["pgtnmaxwidth"]; 
			$imgToolBox->_thumbheight = $tabparams["pgtnmaxheight"];
			$imgToolBox->_debug = 0;
			if(!($newFileName=$imgToolBox->processImage($_FILES[$this->_getPagingParamName("pgitemfilename")],$new_upload_pgitem_base,$PGItemAbsoluteUserPath, 0, 0, 1))) {
				$html2return .= "<font color=red>" . _pg_ImageToolBoxFailure . $imgToolBox->_errMSG . "</font><br />";
	    		return $html2return;
	 		} 
		} else {
	 		if (!move_uploaded_file($upload_pgitem_tmpname,$final_uploaded_fullfilename)) {
	 			$html2return .= "<font color=red>" . _pg_FileUploadFailed . "</font><br />";
				return $html2return;
			}
		}
		chmod($final_uploaded_fullfilename, 0755);
	 	$pgitemsize = filesize($final_uploaded_fullfilename);
	 	if ($tabparams["cbpgtotalsize"] + $pgitemsize > $tabparams["cbpgtotalquotasize"] * 1024) {
	 		$html2return .= "<font color=red>" . _pg_QuotaExceeded . "</font><br />";
	 		unlink($final_uploaded_fullfilename);
	 		if (file_exists($final_uploaded_tn_fullfilename)) unlink($final_uploaded_tn_fullfilename);
			return $html2return;
	 	}
	 	$new_cbpgtotalsize = $tabparams["cbpgtotalsize"] + $pgitemsize;
	 	$new_cbpgtotalitems = $tabparams["cbpgtotalitems"] + 1;
	 	
	 	// if we get here it means that we have validated the new entry
	 	// and should finally save it to the database
	 	$this->_pgSave($id,$pgitemorder,$pgitemtype,$final_uploaded_filename,$pgitemsize,$pgitemtitle,$pgitemdescription,$user,$new_cbpgtotalitems,$new_cbpgtotalsize,$tabparams["cbpgautopublish"],$tabparams["cbpgautoapprove"],$tabparams["pgmoderatornotification"]);
	 	$successmessage = "";
	 	if (!$imgToolBox_needed_typecheck) {
	 		$successmessage = "<font color=green>" . sprintf(_pg_FileUploadSucceeded,$final_uploaded_filename) . "</font><br />";
	 	} else {
	 		$successmessage .= "<font color=green>" . sprintf(_pg_FileUploadAndTnSucceeded,$final_uploaded_filename, $successmessage) . "</font><br />";
	 	}
	 	if (!$tabparams["cbpgautoapprove"]) {
	 		$successmessage .= "<br />" . "<font color=green>" . _pg_PendingApproval . "</font><br />";
	 	}
	 	return $successmessage;
	}
	
	function _pgSave($id,$pgitemorder,$pgitemtype,$pgitemfilename,$pgitemsize,$pgitemtitle,$pgitemdescription,&$user,$cbpgtotalitems,$cbpgtotalsize,$pgitempublished,$pgitemapproved,$moderatornotify) {
		global $my, $database,$mosConfig_live_site,$Itemid;

		$html2return = "";
		
		$query = "INSERT INTO #__comprofiler_plug_profilegallery SET "
			. "userid='" . $user->id . "',"
			. "pgitemorder='" . $pgitemorder . "',"
			. "pgitemtype='" . $pgitemtype . "',"
			. "pgitemfilename='" . $pgitemfilename . "',"
			. "pgitemtitle='" . $pgitemtitle . "',"
			. "pgitemdescription='" . $pgitemdescription . "',"
			. "pgitemdate=now(),"
			. "pgitemsize='" . $pgitemsize . "',"
			. "pgitempublished='" . $pgitempublished . "',"
			. "pgitemapproved='" . $pgitemapproved . "'";
			
		$database->setQuery($query);
		$database->query();
		
		// Notification
		$isModerator=isModerator($my->id);
		if($moderatornotify && !$isModerator){
			if (is_numeric($Itemid)) $andItemid = "&Itemid=".$Itemid;
				else $andItemid = "";
			
			$profile_url = $mosConfig_live_site . "/index.php?option=com_comprofiler&task=userProfile&user=".$user->id.$andItemid;
			$notificationmessage = sprintf(_pg_MSGBODY_NEW,$pgitemtype,$pgitemtitle,$pgitemdescription,$user->name,$profile_url);
			eval ("\$notificationmessage = \"$notificationmessage\";");
			
			$cbNotification = new cbNotification();
			$cbNotification->sendToModerators(_pg_MSGSUB_NEW,$notificationmessage);
		}
		
		$html2return .= $this->pgCBUpdate($user,$cbpgtotalitems,$cbpgtotalsize);
		return $html2return;
		
	}
	
	function pgNotify($id,$user,$notification_action) {
		global $my,$mosConfig_live_site,$Itemid;
		
		switch ($notification_action) {
			case 'MODERATOR-APPROVE':
				// Notify end user about approval
				$tabparams = $this->_pgGetTabParameters($user);
				if($tabparams["pgmoderatornotification"] && ($my->id != $user->id)){
					$cbNotification = new cbNotification();
					$messagebody = _pg_MSGBODY_APPROVE;
					eval ("\$messagebody = \"$messagebody\";");
					$res=$cbNotification->sendFromSystem($user->id,_pg_MSGSUB_APPROVE,$messagebody);
				}
				break;
			case 'MODERATOR-DELETE':
				// Notify end-user about deletion
				$tabparams = $this->_pgGetTabParameters($user);
				if($tabparams["pgmoderatornotification"] && ($my->id != $user->id)){
					$cbNotification = new cbNotification();
					$messagebody = _pg_MSGBODY_DELETE;
					eval ("\$messagebody = \"$messagebody\";");
					$res=$cbNotification->sendFromSystem($user->id,_pg_MSGSUB_DELETE,$messagebody);
				}
				break;
			case 'MODERATOR-REVOKE':
				// Notify end-user about item revoke
				$tabparams = $this->_pgGetTabParameters($user);
				if($tabparams["pgmoderatornotification"] && ($my->id != $user->id)){
					$cbNotification = new cbNotification();
					$messagebody = _pg_MSGBODY_REVOKE;
					eval ("\$messagebody = \"$messagebody\";");
					$res=$cbNotification->sendFromSystem($user->id,_pg_MSGSUB_REVOKE,$messagebody);
				}
				break;
			default:
				break;
		}
		return;
	}
	
	
	/**
	 * This function publishes a gallery item that was previously unpublished
	 *
	 * @param unknown_type $id
	 * @return unknown
	 */
	function pgPublish($id) {
		global $database;
		$html2return = "";
		
		$query = "UPDATE #__comprofiler_plug_profilegallery SET  pgitempublished=1, pgitemdate=NOW() WHERE id=" . (int) $id;
		$database->setQuery($query);
		$database->query();
		return $html2return;
		
	}
	
	/**
	 * This function unpublishes a gallery item that was previously published
	 *
	 * @param unknown_type $id
	 * @return unknown
	 */
	function pgUnPublish($id) {
		global $database;
		$html2return = "";
		
		$query = "UPDATE #__comprofiler_plug_profilegallery SET  pgitempublished=0, pgitemdate=NOW() WHERE id=" . (int) $id;
		$database->setQuery($query);
		$database->query();
		//print $database->getQuery();
		return $html2return;
		
	}
	
	/**
	 * This function approves a gallery item that was previously revoked
	 *
	 * @param unknown_type $id
	 * @param unknown_type $user
	 * @return unknown
	 */
	function pgApprove($id,$user) {
		global $database,$my;
		$html2return = "";
		
		$query = "UPDATE #__comprofiler_plug_profilegallery SET  pgitemapproved=1, pgitemdate=NOW() WHERE id=" . (int) $id;
		$database->setQuery($query);
		$database->query();
		
		// Notificy end user about approval
		$this->pgNotify($id,$user,"MODERATOR-APPROVE");
		return $html2return;
		
	}
	
	/**
	 * This function revokes a gallery item that was previously approved
	 *
	 * @param unknown_type $id
	 * @return unknown
	 */
	function pgRevoke($id,$user) {
		global $database;
		$html2return = "";
		
		$query = "UPDATE #__comprofiler_plug_profilegallery SET  pgitemapproved=0, pgitemdate=NOW() WHERE id=" . (int) $id;
		$database->setQuery($query);
		$database->query();
		//print $database->getQuery();
		// Add return code message here
		
		$this->pgNotify($id,$user,"MODERATOR-REVOKE");
		
		return $html2return;
		
	}
	
	/**
	 * This function updates the running total fields stored in the users profile
	 *
	 * @param unknown_type $id
	 */
	function pgCBUpdate(&$user,$cbpgtotalitems,$cbpgtotalsize) {
		global $database;
		$html2return = "";
		
		$query = "UPDATE #__comprofiler SET  cb_pgtotalitems=" . (int) $cbpgtotalitems
			. ", cb_pgtotalsize=" . $cbpgtotalsize 
			. ", cb_pglastupdate=NOW() WHERE id='$user->id'";
		$database->setQuery($query);
		$database->query();
		//print $database->getQuery();
		$user->cb_pgtotalsize = $cbpgtotalsize;
		$user->cb_pgtotalitems = $cbpgtotalitems;
		return $html2return;
		
	}
	
	/**
	* This function updates the title and description of a gallery item 
	*/
	function pgUpdate($id,$updatetitle,$updatedescription) {
		global $database;
		$html2return = "";
		
		$query = "UPDATE #__comprofiler_plug_profilegallery SET  pgitemtitle='".$updatetitle."', pgitemdescription='".$updatedescription. "', pgitemdate='".date('Y-m-d\TH:i:s')."' WHERE id=" . (int) $id;
		$database->setQuery($query);
		$database->query();
		//print $database->getQuery();
		// Add return code message here
		
		return $html2return;
	}

	/**
	 * This function deletes the profile gallery item entry specified by
	 * the id function parameter. Deletion consists of removing the relative row
	 * in the profilegallery table, deleting the actual gallery item file (and any thumbnail)
	 * and adjusting the gallery owners quota figures
	 *
	 * @param unknown_type $id
	 */
	function pgDelete($id,&$user) {
		global $database,$mosConfig_live_site,$my,$ueConfig,$mainframe,$mosConfig_lang;
		$html2return = "";
		
		// Select all entries to be displayed
		$query="SELECT userid, pgitemtype, pgitemfilename, pgitemtitle, pgitemsize"
			. "\n FROM #__comprofiler_plug_profilegallery"
			. "\n WHERE id=". (int) $id;
		$database->setQuery($query);
		$item2delete=$database->loadObjectList();
		
		$PGItemAbsolutePath=$mainframe->GetCfg( 'absolute_path' ).'/images/comprofiler/plug_profilegallery/';
		$PGItemAbsoluteUserPath = $PGItemAbsolutePath . $item2delete[0]->userid . "/";
		$pgitemfilenameuserabsolutepath = $PGItemAbsoluteUserPath . $item2delete[0]->pgitemfilename;
		$pgitemthumbuserabsolutepath = $PGItemAbsoluteUserPath . "tn" . $item2delete[0]->pgitemfilename;
		
		unlink($pgitemfilenameuserabsolutepath);
	 	if (file_exists($pgitemthumbuserabsolutepath)) unlink($pgitemthumbuserabsolutepath);
		
		$database->setQuery("SELECT cb_pgenable, cb_pgautopublish, cb_pgaccessmode, cb_pgdisplayformat, cb_pgtotalquotaitems, cb_pgtotalquotasize, cb_pgshortgreeting, cb_pgtotalitems, cb_pgtotalsize, cb_pglastupdate FROM #__comprofiler WHERE id=".(int) $item2delete[0]->userid);
		$user2update=$database->loadObjectList();
		
		$database->setQuery("DELETE FROM #__comprofiler_plug_profilegallery WHERE id=".$id);
		$database->query();
		
		$query = "UPDATE #__comprofiler SET  cb_pgtotalitems=". (int) $user2update[0]->cb_pgtotalitems . "-1, cb_pgtotalsize=" . $user2update[0]->cb_pgtotalsize . "-" . $item2delete[0]->pgitemsize . ", cb_pglastupdate=NOW() WHERE id=" . (int) $item2delete[0]->userid;
		$database->setQuery($query);
		$database->query();
		$user->cb_pgtotalitems = (int) $user2update[0]->cb_pgtotalitems -1;
		$user->cb_pgtotalsize =  $user2update[0]->cb_pgtotalsize - $item2delete[0]->pgitemsize;
		
		$this->pgNotify($id,$user,"MODERATOR-DELETE");
		
		return $html2return;
	}
	
	/**
	* Generates the HTML to display the user profile tab
	* @param object tab reflecting the tab database entry
	* @param object mosUser reflecting the user being displayed
	* @param int 1 for front-end, 2 for back-end
	* @returns mixed : either string HTML for tab content, or false if Error generated
	*/
	function getDisplayTab($tab,$user,$ui) {
		global $database,$mosConfig_live_site,$my,$ueConfig,$mainframe,$mosConfig_lang;
		
		$this->_getLanguageFile();
				
		// Setup language and image storage paths
		$PGImagesAbsolutePath=$mainframe->getCfg( 'absolute_path' ).'/components/com_comprofiler/plugin/user/plug_cbprofilegallery/images/';
		$PGImagesPath='components/com_comprofiler/plugin/user/plug_cbprofilegallery/images/';
		$PGItemAbsolutePath=$mainframe->GetCfg( 'absolute_path' ).'/images/comprofiler/plug_profilegallery/';
		$PGItemPath= 'images/comprofiler/plug_profilegallery/';
	
		$tabparams = $this->_pgGetTabParameters($user);
		//print_r($tabparams);
		
		// Return if the user doesn't have the ProfileGallery enabled no need to go any further
		// Does not even display the tab
		if(!$tabparams["cbpgenable"]) return "";
		
		$htmltext0 = "";
		$htmltext1 = ""; // first part of html code to display in the tab
		$htmltext2 = ""; // second part of html code to display in the tab
		$pgWHERE = "";
		$pgORDERBY = "";
		
		//Check to see if there are actions that need to be executed
		$action = $this->_getReqParam("PGformaction", null);
		$id = $this->_getReqParam("id",0);
		//$showform = $this->_getReqParam("showform", 0);

		switch ($tabparams["pgsortoption"]) {
			case 'DATEDESC':
				$pgORDERBY = ",pgitemdate desc";
				break;
			case 'DATEASC':
				$pgORDERBY = ",pgitemdate asc";
				break;
			default:
				$pgORDERBY = ",pgitemdate desc";
				break;
		}
		// Is profile owner viewing or not?
		// If not then set additional WHERE clause to only gather published images
		$isModerator=isModerator($my->id);
		
		if(($my->id != $user->id) && !$isModerator) {
			$isME=false;
			$pgWHERE = "\n AND pgitempublished=1";
			$pgWHERE .= "\n AND pgitemapproved=1";
		} else {
			if ($my->id == $user->id) {
				$isME=true;
			} else {
				$isME=false;
			}
			//LOGIC FOR ACTIONS HERE
			//Take necessary profile owner action if there is
			//Check to see if there are actions that need to be executed
			$action = $this->_getReqParam("PGformaction", null);
			$id = $this->_getReqParam("id",0);
					
			switch ($action) {
				CASE 'delete':
					$this->pgDelete($id,$user);
					break;
				CASE 'update':
					$updatetitle = $this->_getReqParam("pguitemtitle",null);
					$updatedescription = $this->_getReqParam("pguitemdescription",null);
					$this->pgUpdate($id,$updatetitle,$updatedescription);
					//print "Updating gallery item id:".$id;
					break;
				CASE 'publish':
					$this->pgPublish($id);
					//print "Publishing gallery item id:".$id;
					break;	
				CASE 'unpublish':
					$this->pgUnPublish($id);
					//print "Unpublishing gallery item id:".$id;
					break;	
				CASE 'approve':
					$this->pgApprove($id,$user);
					//print "Approving gallery item id:".$id;
					break;
				CASE 'revoke':
					$this->pgRevoke($id,$user);
					//print "Revoking gallery item id:".$id;
					break;
				DEFAULT:
					//print "I'm doing nothing:".$id." action:".$action;
					break;
			}
		}
		
		// if moderator viewing display extra info for front-end moderation activities
		if ($isModerator && !$isME) {
			$moderatorviewmessage = sprintf(_pg_ModeratorViewMessage,(int) $user->cb_pgtotalitems,
				$tabparams["cbpgtotalquotaitems"],
				$user->cb_pgtotalsize/1024,
				$tabparams["cbpgtotalquotasize"],
				$tabparams["cbpgaccessmode"],
				$tabparams["cbpgdisplayformat"]);
			$htmltext1 .= $moderatorviewmessage . "<br />";
		}
		
		// First thing to do is to display the correct language tab description if not empty
		if($tab->description != null) {
			$htmltext1 .= "\t\t<div class=\"tab_Description\">";
			$htmltext1 .= unHtmlspecialchars(getLangDefinition($tab->description));
			$htmltext1 .= "</div>\n";
		}
		
		
		// if connections restriction enable
		// and connections enabled on the system
		// and its not me viewing then
		// check if current viewer is connected with
		// profile owner
		
		if($my->id==0) {
			$isAnonymous = true;
		} else {
			$isAnonymous = false;
		}
		$check4connection = 0;

		switch ($tabparams["cbpgaccessmode"]) {
			case 'PUB':
				break;
			case 'REG':
				if ($isAnonymous) {
					
					$htmltext1 .= "<br>" 
						. sprintf(_pg_OnlyRegisteredAllowed, (int) $user->cb_pgtotalitems)
						. "</br>";
					return $htmltext1;
				}
				break;
			case 'REG-S':
				if ($isAnonymous) return "";
				break;
			case 'CON':
				if ($isAnonymous) {
					$htmltext1 .= "<br>" 
						. sprintf(_pg_ConnectionsOnlyMessage, (int) $user->cb_pgtotalitems)
						. "</br>";
					return $htmltext1;
				}
				$check4connection = 1;
				break;
			case 'CON-S':
				if ($isAnonymous) {
					return $htmltext1;
				}
				$check4connection = 1;
				break;
			default:
				break;	
		}
		
		if ($check4connection && !$isAnonymous && !$isModerator && !$isME) {
			if ($ueConfig['allowConnections']) {	
				$query="SELECT count(*)"
					. "\n FROM #__comprofiler_members"
					. "\n WHERE memberid=".$user->id
					. "\n AND referenceid=".$my->id
					. "\n AND accepted=1 AND pending=0";
				$database->setQuery($query);
				$isconnected = $database->loadResult();
				if (!$isconnected) {
					if ($tabparams["cbpgaccessmode"] == 'CON-S') return "";
					$htmltext1 .= "<br>" . sprintf(_pg_ConnectionsOnlyMessage, (int) $user->cb_pgtotalitems) . "</br>";
					return $htmltext1;
				}
			} else {
				if ($tabparams["cbpgaccessmode"] == 'CON-S') return "";
				$htmltext1 .= "<br>" . sprintf(_pg_ConnectionsOnlyMessage, (int) $user->cb_pgtotalitems) . "</br>";
				return $htmltext1;
			}
		} 
		
		//Check to see if a user has submitted a new gallery item entry to be processed
		if (($isME || ($tabparams["pgallowaccessmodeoverride"] && $isModerator)) AND isset($_POST[$this->_getPagingParamName("pgitemtitle")])) {
			$htmltext0 .= $this->_pgProcessNewItem($id,$user);
		}
		
		// Find and show posts
		$pagingParams = $this->_getPaging(array(),array("pgposts_"));
				
		//check to see if the Admin enabled pagination
		if ($tabparams["pgpagingenabled"]) {
			//select a count of all applicable entries for pagination
			$query="SELECT count(*)"
				. "\n FROM #__comprofiler_plug_profilegallery"
				. "\n WHERE userid=".$user->id
				. "\n ".$pgWHERE;
			
			$database->setQuery($query);
			$pgtotal = $database->loadResult();
			
			if (!is_numeric($pgtotal)) $pgtotal = 0;

			if ($pagingParams["pgposts_limitstart"] === null) $pagingParams["pgposts_limitstart"] = "0";
			if ($tabparams["pgentriesperpage"] > $pgtotal) $pagingParams["pgposts_limitstart"] = "0";
		} else {
			$pagingParams["pgposts_limitstart"] = "0";
		}
		
		$PGItemAbsoluteUserPath = $PGItemAbsolutePath . $user->id . "/";
		$PGItemUserPath = $PGItemPath . $user->id . "/";
		// Select all entries to be displayed
		$query="SELECT *"
			. "\n FROM #__comprofiler_plug_profilegallery"
			. "\n WHERE userid=".$user->id
			. "\n ".$pgWHERE
			. "\n ORDER BY pgitemorder"
			. "\n ".$pgORDERBY
			. "\n LIMIT ".($pagingParams["pgposts_limitstart"]?$pagingParams["pgposts_limitstart"]:"0").",".$tabparams["pgentriesperpage"];
		$database->setQuery($query);
		//print $database->getQuery();
		$pgitems=$database->loadObjectList();
		$pgdisplaycount=count($pgitems);
				
		// Display welcome message
		$htmltext2 .= "<br/>";
		$htmltext2 .= $tabparams["cbpgshortgreeting"];
		$htmltext2 .= "<br/>";
		
		// Display submit new item logic
		$base_url = $this->_getAbsURLwithParam(array());
		if (($isME || ($tabparams["pgallowaccessmodeoverride"] && $isModerator))  && ($user->cb_pgtotalitems < $tabparams["cbpgtotalquotaitems"])) {
			$htmltext2 .="\n<script language=\"JavaScript\"  type=\"text/javascript\" src=\"components/com_comprofiler/plugin/user/plug_cbprofilegallery/js/profilegallery.js\"></script>\n";
			$htmltext2 .= "<a href=\"javascript:void(0);\" onclick=\"pg_Expand();\">" . _pg_SubmitEntry . " <img style=\"cursor:pointer;border:0px;\" alt=\"\" id=\"pg_direction\" src=\"components/com_comprofiler/plugin/user/plug_cbprofilegallery/images/none-arrow.gif\" /></a>";
				
			$quota_marks = sprintf(_pg_QuotaMessage,(int) $user->cb_pgtotalitems,
				$tabparams["cbpgtotalquotaitems"],
				$user->cb_pgtotalsize/1024,
				$tabparams["cbpgtotalquotasize"],
				floor($user->cb_pgtotalsize/1024/$tabparams["cbpgtotalquotasize"]*100),
				100-floor($user->cb_pgtotalsize/1024/$tabparams["cbpgtotalquotasize"]*100));
				
			$htmltext2 .= $quota_marks . "<br />";
				
			$htmltext2 .= "<div id=\"pg_divForm\" name=\"pg_divForm\" style=\"display:none;width:100%;\">";
			$htmltext2 .= "<form name=\"pgadminForm\" id=\"pgadminForm\" onsubmit=\"javascript: return PGsubmitForm(this);\" method=\"post\" action=\"".$base_url."\" enctype=\"multipart/form-data\">\n";				
				
			$htmltext2 .= "<b>" ._pg_ItemTitleInput . "</b><br />";
			$htmltext2 .= "<input class=\"inputbox\" type=\"text\" name=\"".$this->_getPagingParamName("pgitemtitle")."\" size=\"30\" maxlength=\255\"><br />";
			$htmltext2 .= "<b>" ._pg_ItemDescriptionInput . "</b><br />";
			$htmltext2 .= "<textarea class=\"inputbox\" cols=\"35\" rows=\"4\" name=\"".$this->_getPagingParamName("pgitemdescription")."\"></textarea><br />";
			$htmltext2 .= "<b>" ._pg_ItemFileNameInput . "</b><br />";
			$htmltext2 .= "<input class=\"inputbox\" type=\"file\" name=\"".$this->_getPagingParamName("pgitemfilename")."\" size=\"30\"><br />";
			$htmltext2 .= "<input class=\"button\" name=\"pgsubmitentry\" id=\"pgsubmitentry\" type=\"submit\" value=\"" . _pg_PostEntry ."\" />"; 
			$htmltext2 .= "</form>"; 
			$htmltext2 .= "</div>";
			$htmltext2 .= "<br />";
			//Add the localized Javascript Paramaters so that error messages are properly translated
			$htmltext2 .="\n\n<script type=\"text/javascript\">\n";
			$htmltext2 .="var _pg_TitleRequired='"._pg_TitleRequired."';\n";
			$htmltext2 .="var _pg_ImageRequired='"._pg_ImageRequired."';\n";
			$htmltext2 .="var _TitleVariable=document.pgadminForm.".$this->_getPagingParamName("pgitemtitle").";\n";
			$htmltext2 .="var _ImageVariable=document.pgadminForm.".$this->_getPagingParamName("pgitemfilename").";\n";
			$htmltext2 .="</script>\n\n";
				
		}
		if ($isME && ($user->cb_pgtotalitems >= $tabparams["cbpgtotalquotaitems"])) {
			$htmltext2 .= "<font color=red>" . _pg_ItemQuotaReached . "</font><br />";
		}
		
		$style = "style=\"padding:5px;\"";	
		if ($pgdisplaycount > 0){	
			// headings go here if needed
			switch ($tabparams["cbpgdisplayformat"]){
				case 'DF1': // thumbnail layout headings and inits
					$icon = explode(",",$tabparams["cbpgbuttonslist"]);
					$dparm = explode(",",$tabparams["cbpgdisplayformatparameters"]);
					//print_r($dparm);
					
					// get extra container box size bazed on icon height
					if ($isME || $isModerator) {
						list($icon_width, $icon_height, $icon_type, $icon_attr) = getimagesize($PGImagesPath . $icon[1]);
						$pg_extrasize = $icon_height;
					} else {
						$pg_extrasize = 0;
					}
					
					$htmltext2 .= "<script language=\"JavaScript\">";
	
					$htmltext2 .= "function pgpopup(pgimagefile,pgimagetitle,pgimagedescription) {\n";
					$htmltext2 .= "var newWindow = window.open(\"\",\"newWindow\",\"height=" . ($tabparams["pgmaxheight"]+$dparm[2]) . ",width=" . ($tabparams["pgmaxwidth"]+$dparm[3]) . ",resizable=yes, scrollbars=yes, toolbar=no " . "\" );\n";
					$htmltext2 .= "var imageurl = \"<img src= \" + pgimagefile + \">\";\n";
					$htmltext2 .= "newWindow.document.open();";
					$htmltext2 .= "newWindow.document.writeln(\"<div align='center' >\");\n";
					$htmltext2 .= "newWindow.document.writeln(\"<title>Profile Gallery Image: \"+ pgimagetitle + \"</title>\");\n";
					$htmltext2 .= "newWindow.document.writeln(imageurl);\n";
					$htmltext2 .= "newWindow.document.writeln(\"<br />\");";
					$htmltext2 .= "newWindow.document.writeln(pgimagedescription);\n";
					$htmltext2 .= "newWindow.document.writeln(\"</div>\");\n";
					$htmltext2 .= "newWindow.document.close();\n";
					$htmltext2 .= "}\n";
					$htmltext2 .= "</script>";
					break;
				case 'DF2': // file list layout headings
					$htmltext2 .= "<table cellpadding=\"2\" cellspacing=\"4\" border=\"0\" width=\"95%\">";
					$htmltext2 .= "<tr class=\"sectiontableheader\">";
					$htmltext2 .= "<td width=25%>"._pg_DateTitle."</td>";
					$htmltext2 .= "<td>"._pg_ItemTitle."</td>";
					$htmltext2 .= "<td width=50%>"._pg_ItemDescription."</td>";
					if ($isME || $isModerator) $htmltext2 .= "<td>"._pg_ItemActions."</td>";
					$htmltext2 .= "</tr>";
					break;
				case 'DF3': // thumbnail layout with lightbox headings and inits
					$icon = explode(",",$tabparams["cbpgbuttonslist"]);
					$dparm = explode(",",$tabparams["cbpgdisplayformatparameters"]);
					//print_r($dparm);
					
					// get extra container box size bazed on icon height
					if ($isME || $isModerator) {
						list($icon_width, $icon_height, $icon_type, $icon_attr) = getimagesize($PGImagesPath . $icon[1]);
						$pg_extrasize = $icon_height;
					} else {
						$pg_extrasize = 0;
					}

					$htmltext2 .= "<link rel=\"stylesheet\" href=\"components/com_comprofiler/plugin/user/plug_cbprofilegallery/css/lightbox.css\" type=\"text/css\" media=\"screen\" />";
					$htmltext2 .= "<script type=\"text/javascript\" src=\"components/com_comprofiler/plugin/user/plug_cbprofilegallery/js/prototype.js\"></script>";
					$htmltext2 .= "<script type=\"text/javascript\" src=\"components/com_comprofiler/plugin/user/plug_cbprofilegallery/js/scriptaculous.js?load=effects\"></script>";
					$htmltext2 .= "<script language=\"JavaScript\">\n";
					$htmltext2 .= "var pg_imagestring = \"" . _pg_LBImageString . "\";\n";
					$htmltext2 .= "var pg_ofstring = \"" . _pg_LBOfString . "\";\n";
					$htmltext2 .= "</script>\n";
					$htmltext2 .= "<script type=\"text/javascript\" src=\"components/com_comprofiler/plugin/user/plug_cbprofilegallery/js/lightbox.js\"></script>";
					break;
				default:
					$htmltext2 .= "<b>column_heading_1 | column_heading2 | column_heading3</b><br />";
			}
			$i=2;
			$k=0;
			foreach ($pgitems as $pgitem) {
				$k++;
				$i= ($i==1) ? 2 : 1;
				$pgitemfilename = $pgitem->pgitemfilename;
				$pgitemtype = $pgitem->pgitemtype;
				$pgitemtitle = $pgitem->pgitemtitle;
				$js_pgitemtitle = str_replace(array('"','<','>',"\\","'","&#039;"), array("&quot;","&lt;","&gt;","\\\\","\\'","\\'"), $pgitemtitle);
				$html_pgitemtitle = htmlspecialchars($pgitemtitle);
				$html_pgitemtitle_formatted = htmlspecialchars(($dparm[0]&&strlen($pgitemtitle)>$dparm[0]) ? substr($pgitemtitle,0,$dparm[0]) . $dparm[1]:$pgitemtitle);
				$pgitemdescription = $pgitem->pgitemdescription;
				$js_pgitemdescription = str_replace(array('"','<','>',"\\","'","&#039;"), array("&quot;","&lt;","&gt;","\\\\","\\'","\\'"), $pgitemdescription);
				$html_pgitemdescription = htmlspecialchars($pgitemdescription);
				$html_pgitemlightbox = _pg_ItemTitle . ": " . $html_pgitemtitle . "<br />" . _pg_ItemDescription . ": " . $html_pgitemdescription;
				$pgitemdate = mosFormatDate($pgitem->pgitemdate);
				$pgitemsize = $pgitem->pgitemsize;
				$pgitempublished = $pgitem->pgitempublished;
				$pgitemapproved = $pgitem->pgitemapproved;
	
			
				switch($pgitemtype) {
					case 'jpg':
					case 'gif':
						$popupname = "pgpopup";
						break;
					default:
						$popupname = "pgpopup";
				}
				
				$pgitemfilenameuserpath = $PGItemUserPath . $pgitemfilename;
				$pgitemthumbuserpath = $PGItemUserPath . "tn" . $pgitemfilename;
				$pgitemfilenameuserabsolutepath = $PGItemAbsoluteUserPath . $pgitemfilename;
				$pgitemthumbuserabsolutepath = $PGItemAbsoluteUserPath . "tn" . $pgitemfilename;
				if (!file_exists($pgitemthumbuserabsolutepath)) {
					$pgitemthumbuserabsolutepath = $PGImagesAbsolutePath . "pgtn_" . $pgitemtype . "item.gif";
					$pgitemthumbuserpath = $PGImagesPath . "pgtn_" . $pgitemtype . "item.gif";
					if (!file_exists($pgitemthumbuserabsolutepath)) {
						$pgitemthumbuserabsolutepath = $PGImagesAbsolutePath . "pgtn_nonimageitem.gif";
						$pgitemthumbuserpath = $PGImagesPath . "pgtn_nonimageitem.gif";
					}
				}
				$pgitemurl = "<a href=\"" . $pgitemfilenameuserpath . "\">" . $pgitemfilename . "</a>";
				$pglivelink = $mosConfig_live_site . "/" . $pgitemfilenameuserpath;
				$pgitemtitle_url = "<a href=\"".sefRelToAbs($pgitemfilenameuserpath)."\" target=\"_blank\"><b>".$html_pgitemtitle_formatted."</b><br />";

				list($pgitemtn_width, $pgitemtn_height, $item_type, $item_attr) = getimagesize($pgitemthumbuserabsolutepath);
					
				if ($pgitemtn_width <= $tabparams["pgtnmaxwidth"]) {
					$needs_new_width = false;
					$resize_width_factor = 1;
				} else {
					$needs_new_width = true;
					$resize_width_factor = $tabparams["pgtnmaxwidth"] / $pgitemtn_width;
				}
				if ($pgitemtn_height <= $tabparams["pgtnmaxheight"]) {
					$needs_new_height = false;
					$resize_height_factor = 1;
				} else {
					$needs_new_height = true;
					$resize_height_factor = $tabparams["pgtnmaxheight"] / $pgitemtn_height;
				}
	
				$resize_factor = min($resize_width_factor,$resize_height_factor);
				$newtn_height = floor($pgitemtn_height * $resize_factor);
				$newtn_width = floor($pgitemtn_width * $resize_factor);

				
				switch ($tabparams["cbpgdisplayformat"]){
					case 'DF1': // image layout headings (none)
						if (!$pgitemapproved || !$pgitempublished) {
							$htmltext2.= "<div class=\"connectionBox\" style=\"text-align:center;border:1px dotted;position:relative;height:".($tabparams["pgtnmaxheight"]+$dparm[4]+$pg_extrasize)."px;width:".($tabparams["pgtnmaxwidth"]+$dparm[5])."px;\">";
						} else {
							$htmltext2.= "<div class=\"connectionBox\" style=\"text-align:center;position:relative;height:".($tabparams["pgtnmaxheight"]+$dparm[4]+$pg_extrasize)."px;width:".($tabparams["pgtnmaxwidth"]+$dparm[5])."px;\">";
						}
						// Check file extension type
						$inimagelist = in_array($pgitemtype,explode(",",$tabparams["pgimagefiletypelist"]));
						if ($tabparams["pgopmode"]!="FILEMODE" && $inimagelist){
							$htmltext2.= "<a href=\"".sefRelToAbs($pgitemfilenameuserpath) . "\" target=\"_blank\"><b>" . $html_pgitemtitle_formatted . "</b></a><br />"
								. "<div style=\"height:".$tabparams["pgtnmaxheight"]."px;\">"
								. "<a href=\"javascript:$popupname('$pglivelink','$js_pgitemtitle','$js_pgitemdescription')\">"
								. "<img src=\"" . $pgitemthumbuserpath . "\" border=\"0\" height=\"$newtn_height\" width=\"$newtn_width\" alt=\"\" title=\"" . $html_pgitemdescription . "\" />"
								. "</a>"
								. "</div>"
								. "<br /><br />";
						} else {
							$htmltext2.= "<a href=\"".sefRelToAbs($pgitemfilenameuserpath)."\"><b>" . $html_pgitemtitle_formatted . "</b></a><br />"
								. "<div style=\"height:".$tabparams["pgtnmaxheight"]."px;\">"
								. "<a href=\"$pgitemfilenameuserpath\" target=\"_blank\">"
								. "<img src=\"" . $pgitemthumbuserpath . "\" border=\"0\" height=\"$newtn_height\" width=\"$newtn_width\" alt=\"\" title=\"" . $html_pgitemdescription . "\" />"
								. "</a>"
								. "</div>"
								. "<br /><br />";							
						}
						$htmltext2 .= "<form name=\"PGactionForm".$k."\" id=\"PGactionForm".$k."\" method=\"post\" action=\"".$base_url."\">";
						$htmltext2 .= "<input type=\"hidden\" name=\"".$this->_getPagingParamName("id")."\" value=\"".$pgitem->id."\" />";
						$htmltext2 .= "<input type=\"submit\" name=\"PGsubmitform\" style=\"display:none;\" />";
						$htmltext2 .= "<input type=\"hidden\" id=\"PGformaction\" name=\"".$this->_getPagingParamName("PGformaction")."\" value=\"default\" /></form>";
						if ($isME || $isModerator) {
							$htmltext2 .= "<a href=\"javascript:if (confirm('" ._pg_DeleteWarning . "')) { document.PGactionForm".$k.".PGformaction.value='delete';document.PGactionForm".$k.".submit(); }\"><img style=\"cursor:pointer;border:0px;\" id=\"pg_c1\" src=\"components/com_comprofiler/plugin/user/plug_cbprofilegallery/images/" . $icon[0] . "\" alt=\"" ._pg_Delete."\" title=\""._pg_Delete."\"></a>";			
							if (!$pgitempublished) {
								$htmltext2 .= "<a href=\"javascript:document.PGactionForm".$k.".PGformaction.value='publish';document.PGactionForm".$k.".submit();\"><img style=\"cursor:pointer;border:0px;\" id=\"pg_c2\" src=\"components/com_comprofiler/plugin/user/plug_cbprofilegallery/images/" . $icon[2] . "\" alt=\"" ._pg_Publish ."\" title=\""._pg_Publish."\"></a>";
							} else {
								$htmltext2 .= "<a href=\"javascript:document.PGactionForm".$k.".PGformaction.value='unpublish';document.PGactionForm".$k.".submit();\"><img style=\"cursor:pointer;border:0px;\" id=\"pg_c3\" src=\"components/com_comprofiler/plugin/user/plug_cbprofilegallery/images/" . $icon[1] . "\" alt=\"" ._pg_Unpublish ."\" title=\""._pg_Unpublish."\"></a>";
							}
						}
						if ($isModerator) {
							if (!$pgitemapproved) {
								$htmltext2 .= "<a href=\"javascript:document.PGactionForm".$k.".PGformaction.value='approve';document.PGactionForm".$k.".submit();\"><img style=\"cursor:pointer;border:0px;\" id=\"pg_c4\" src=\"components/com_comprofiler/plugin/user/plug_cbprofilegallery/images/" . $icon[3] . "\" alt=\"" ._pg_Approve ."\" title=\""._pg_Approve."\"></a>";
							} else {
								$htmltext2 .= "<a href=\"javascript:document.PGactionForm".$k.".PGformaction.value='revoke';document.PGactionForm".$k.".submit();\"><img style=\"cursor:pointer;border:0px;\" id=\"pg_c5\" src=\"components/com_comprofiler/plugin/user/plug_cbprofilegallery/images/" . $icon[4] . "\" alt=\"" ._pg_Revoke ."\" title=\""._pg_Revoke."\"></a>";
							}
						}
						if ($isME || $isModerator) {
							$popform=null;
							$popform .= "<form name=\"PGformaction".$k."\" id=\"PGformaction".$k."\" method=\"post\" action=\"".$base_url."\">";
							$popform .= "<input type=\"hidden\" name=\"".$this->_getPagingParamName("id")."\" value=\"".$pgitem->id."\" />";
							$popform .= "<input type=\"hidden\" name=\"".$this->_getPagingParamName("PGformaction")."\" value=\"update\" />";
							$popform .= "<br /><b>"._pg_ItemTitle.":</b><br /><input class=\"inputbox\" type=\"text\" name=\"".$this->_getPagingParamName("pguitemtitle")."\" size=\"30\" maxlength=\"255\" value=\"".$html_pgitemtitle."\"></input>";
							$popform .= "<br /><b>"._pg_ItemDescription.":</b><br /><textarea class=\"inputbox\" cols=\"35\" rows=\"4\" name=\"".$this->_getPagingParamName("pguitemdescription")."\" style=\"height:75px;width:400px;overflow:auto;\" >".$html_pgitemdescription."</textarea>";
							$popform .= "<br /><input type=\"submit\" value=\""._pg_Update."\" /></form>";					
                            //Add the localized Javascript Paramaters so that error messages are properly translated
							//$popform .="\n\n<script type=\"text/javascript\">\n";
							//$popform .="var _pg_TitleRequired='"._pg_TitleRequired."';\n";
							//$popform .="var _TitleVariable=document.PGformaction.".$this->_getPagingParamName("pguitemtitle").";\n";
							//$popform .="</script>\n\n";

							
							$htmltext2 .= "<a href=\"javascript:void(0);\" name=\"PGeditForm".$k."\" id=\"PGeditForm".$k."\" onclick=\""
								."return overlib('".str_replace(array("&","\\",'"',"<",">","'","\n","\r"), array("&amp;","\\\\","&quot;","&lt;","&gt;","\'","\\n","\\r"),$popform)."', STICKY, CAPTION,'"._pg_EditPopup."', CENTER,CLOSECLICK,CLOSETEXT,'"._UE_CLOSE_OVERLIB."',WIDTH,350, ANCHOR,'PGeditForm".$k."',ANCHORALIGN,'LR','UR');\">"."<img style=\"cursor:pointer;border:0px;\" id=\"pg_c5\" src=\"components/com_comprofiler/plugin/user/plug_cbprofilegallery/images/" . $icon[5] . "\" alt=\"" ._pg_Edit ."\" title=\""._pg_Edit."\""."></a> ";
						}

						$htmltext2 .= "<br /></div>";
						break;	
					case 'DF2': // file list layout
						$htmltext2 .= "<form name=\"PGactionForm".$k."\" id=\"PGactionForm".$k."\" method=\"post\" action=\"".$base_url."\">";
						$htmltext2 .= "<input type=\"hidden\" name=\"".$this->_getPagingParamName("id")."\" value=\"".$pgitem->id."\" />";
						$htmltext2 .= "<input type=\"submit\" name=\"PGsubmitform\" style=\"display:none;\" />";
						$htmltext2 .= "<input type=\"hidden\" id=\"PGformaction\" name=\"".$this->_getPagingParamName("PGformaction")."\" value=\"default\" /></form>";

						$htmltext2 .= "<tr>";
						$htmltext2 .= "<td>".$pgitemdate."</td>";
						$htmltext2 .= "<td>".$pgitemtitle_url."</td>";
						$htmltext2 .= "<td>".unHtmlspecialchars($pgitemdescription)."</td>";
						if ($isME || $isModerator) $htmltext2 .= "<td>";
						if ($isME || $isModerator) {
							$htmltext2 .= "<a href=\"javascript:if (confirm('" ._pg_DeleteWarning . "')) { document.PGactionForm".$k.".PGformaction.value='delete';document.PGactionForm".$k.".submit(); }\">" ._pg_Delete."<br /></a>";			
							if (!$pgitempublished) {
								$htmltext2 .= "<a href=\"javascript:document.PGactionForm".$k.".PGformaction.value='publish';document.PGactionForm".$k.".submit();\">"._pg_Publish."<br /></a>";
							} else {
								$htmltext2 .= "<a href=\"javascript:document.PGactionForm".$k.".PGformaction.value='unpublish';document.PGactionForm".$k.".submit();\">" ._pg_Unpublish."<br /></a>";
							}
						}
						if ($isModerator) {
							if (!$pgitemapproved) {
								$htmltext2 .= "<a href=\"javascript:document.PGactionForm".$k.".PGformaction.value='approve';document.PGactionForm".$k.".submit();\">"._pg_Approve."<br /></a>";
							} else {
								$htmltext2 .= "<a href=\"javascript:document.PGactionForm".$k.".PGformaction.value='revoke';document.PGactionForm".$k.".submit();\">"._pg_Revoke."<br /></a>";
							}
						}
						if ($isME || $isModerator) {
							$popform=null;
							$popform .= "<form name=\"PGformaction".$k."\" id=\"PGformaction".$k."\" method=\"post\" action=\"".$base_url."\">";
							$popform .= "<input type=\"hidden\" name=\"".$this->_getPagingParamName("id")."\" value=\"".$pgitem->id."\" />";
							$popform .= "<input type=\"hidden\" name=\"".$this->_getPagingParamName("PGformaction")."\" value=\"update\" />";
							$popform .= "<br /><b>"._pg_ItemTitle.":</b><br /><input class=\"inputbox\" type=\"text\" name=\"".$this->_getPagingParamName("pguitemtitle")."\" size=\"30\" maxlength=\"255\" value=\"".$html_pgitemtitle."\"></input>";
							$popform .= "<br /><b>"._pg_ItemDescription.":</b><br /><textarea class=\"inputbox\" cols=\"35\" rows=\"4\" name=\"".$this->_getPagingParamName("pguitemdescription")."\" style=\"height:75px;width:400px;overflow:auto;\" >".$html_pgitemdescription."</textarea>";
							$popform .= "<br /><input type=\"submit\" value=\""._pg_Update."\" /></form>";					
                            //Add the localized Javascript Paramaters so that error messages are properly translated
							//$popform .="\n\n<script type=\"text/javascript\">\n";
							//$popform .="var _pg_TitleRequired='"._pg_TitleRequired."';\n";
							//$popform .="var _TitleVariable=document.PGformaction.".$this->_getPagingParamName("pguitemtitle").";\n";
							//$popform .="</script>\n\n";

							
							$htmltext2 .= "<a href=\"javascript:void(0);\" name=\"PGeditForm".$k."\" id=\"PGeditForm".$k."\" onclick=\""
								."return overlib('".str_replace(array("&","\\",'"',"<",">","'","\n","\r"), array("&amp;","\\\\","&quot;","&lt;","&gt;","\'","\\n","\\r"),$popform)."', STICKY, CAPTION,'"._pg_EditPopup."', CENTER,CLOSECLICK,CLOSETEXT,'"._UE_CLOSE_OVERLIB."',WIDTH,350, ANCHOR,'PGeditForm".$k."',ANCHORALIGN,'LR','UR');\">"._pg_Edit ."></a> ";
						}

						if ($isME || $isModerator) $htmltext2 .= "</td>";
						$htmltext2 .= "</tr>";
						break;
					case 'DF3': // image layout headings (none)
						if (!$pgitemapproved || !$pgitempublished) {
							$htmltext2.= "<div class=\"connectionBox\" style=\"border:1px dotted;position:relative;height:".($tabparams["pgtnmaxheight"]+$dparm[4]+$pg_extrasize)."px;width:".($tabparams["pgtnmaxwidth"]+$dparm[5])."px;\">";
						} else {
							$htmltext2.= "<div class=\"connectionBox\" style=\"position:relative;height:".($tabparams["pgtnmaxheight"]+$dparm[4]+$pg_extrasize)."px;width:".($tabparams["pgtnmaxwidth"]+$dparm[5])."px;\">";
						}
						// Check file extension type
						//<a href="images/image-1.jpg" rel="lightbox" title="my caption">image #1</a>
						$inimagelist = in_array($pgitemtype,explode(",",$tabparams["pgimagefiletypelist"]));
						if ($tabparams["pgopmode"]!="FILEMODE" && $inimagelist){
							$htmltext2.= "<a href=\"".sefRelToAbs($pgitemfilenameuserpath) . "\" target=\"_blank\"><b>" . $html_pgitemtitle_formatted . "</b></a><br />"
								. "<div style=\"height:".$tabparams["pgtnmaxheight"]."px;\">"	
								. "<a href=\"$pglivelink\" rel=\"lightbox[group]\" title=\"$html_pgitemlightbox\">"
								. "<img src=\"" . $pgitemthumbuserpath . "\" border=\"0\"  height=\"$newtn_height\" width=\"$newtn_width\" alt=\"\" title=\"" . $html_pgitemdescription . "\" />"
								. "</a>"
								. "</div>"
								. "<br /><br />";
						} else {
							$htmltext2.= "<a href=\"".sefRelToAbs($pgitemfilenameuserpath)."\"><b>" . $html_pgitemtitle_formatted . "</b></a><br />"
								. "<div style=\"height:".$tabparams["pgtnmaxheight"]."px;\">"
								. "<a href=\"$pgitemfilenameuserpath\" target=\"_blank\">"
								. "<img src=\"" . $pgitemthumbuserpath . "\" border=\"0\"  height=\"$newtn_height\" width=\"$newtn_width\" alt=\"\" title=\"" . $html_pgitemdescription . "\" />"
								. "</a>"
								. "</div>"
								. "<br /><br />";							
						}
						$htmltext2 .= "<form name=\"PGactionForm".$k."\" id=\"PGactionForm".$k."\" method=\"post\" action=\"".$base_url."\">";
						$htmltext2 .= "<input type=\"hidden\" name=\"".$this->_getPagingParamName("id")."\" value=\"".$pgitem->id."\" />";
						$htmltext2 .= "<input type=\"submit\" name=\"PGsubmitform\" style=\"display:none;\" />";
						$htmltext2 .= "<input type=\"hidden\" id=\"PGformaction\" name=\"".$this->_getPagingParamName("PGformaction")."\" value=\"default\" /></form>";
						if ($isME || $isModerator) {
							$htmltext2 .= "<a href=\"javascript:if (confirm('" ._pg_DeleteWarning . "')) { document.PGactionForm".$k.".PGformaction.value='delete';document.PGactionForm".$k.".submit(); }\"><img style=\"cursor:pointer;border:0px;\" id=\"pg_c1\" src=\"components/com_comprofiler/plugin/user/plug_cbprofilegallery/images/" . $icon[0] . "\" alt=\"" ._pg_Delete."\" title=\""._pg_Delete."\"></a>";			
							if (!$pgitempublished) {
								$htmltext2 .= "<a href=\"javascript:document.PGactionForm".$k.".PGformaction.value='publish';document.PGactionForm".$k.".submit();\"><img style=\"cursor:pointer;border:0px;\" id=\"pg_c2\" src=\"components/com_comprofiler/plugin/user/plug_cbprofilegallery/images/" . $icon[2] . "\" alt=\"" ._pg_Publish ."\" title=\""._pg_Publish."\"></a>";
							} else {
								$htmltext2 .= "<a href=\"javascript:document.PGactionForm".$k.".PGformaction.value='unpublish';document.PGactionForm".$k.".submit();\"><img style=\"cursor:pointer;border:0px;\" id=\"pg_c3\" src=\"components/com_comprofiler/plugin/user/plug_cbprofilegallery/images/" . $icon[1] . "\" alt=\"" ._pg_Unpublish ."\" title=\""._pg_Unpublish."\"></a>";
							}
						}
						if ($isModerator) {
							if (!$pgitemapproved) {
								$htmltext2 .= "<a href=\"javascript:document.PGactionForm".$k.".PGformaction.value='approve';document.PGactionForm".$k.".submit();\"><img style=\"cursor:pointer;border:0px;\" id=\"pg_c4\" src=\"components/com_comprofiler/plugin/user/plug_cbprofilegallery/images/" . $icon[3] . "\" alt=\"" ._pg_Approve ."\" title=\""._pg_Approve."\"></a>";
							} else {
								$htmltext2 .= "<a href=\"javascript:document.PGactionForm".$k.".PGformaction.value='revoke';document.PGactionForm".$k.".submit();\"><img style=\"cursor:pointer;border:0px;\" id=\"pg_c5\" src=\"components/com_comprofiler/plugin/user/plug_cbprofilegallery/images/" . $icon[4] . "\" alt=\"" ._pg_Revoke ."\" title=\""._pg_Revoke."\"></a>";
							}
						}
						if ($isME || $isModerator) {
							$popform=null;
							$popform .= "<form name=\"PGformaction".$k."\" id=\"PGformaction".$k."\" method=\"post\" action=\"".$base_url."\">";
							$popform .= "<input type=\"hidden\" name=\"".$this->_getPagingParamName("id")."\" value=\"".$pgitem->id."\" />";
							$popform .= "<input type=\"hidden\" name=\"".$this->_getPagingParamName("PGformaction")."\" value=\"update\" />";
							$popform .= "<br /><b>"._pg_ItemTitle.":</b><br /><input class=\"inputbox\" type=\"text\" name=\"".$this->_getPagingParamName("pguitemtitle")."\" size=\"30\" maxlength=\"255\" value=\"".$html_pgitemtitle."\"></input>";
							$popform .= "<br /><b>"._pg_ItemDescription.":</b><br /><textarea class=\"inputbox\" cols=\"35\" rows=\"4\" name=\"".$this->_getPagingParamName("pguitemdescription")."\" style=\"height:75px;width:400px;overflow:auto;\" >".$html_pgitemdescription."</textarea>";
							$popform .= "<br /><input type=\"submit\" value=\""._pg_Update."\" /></form>";					
                            //Add the localized Javascript Paramaters so that error messages are properly translated
							//$popform .="\n\n<script type=\"text/javascript\">\n";
							//$popform .="var _pg_TitleRequired='"._pg_TitleRequired."';\n";
							//$popform .="var _TitleVariable=document.PGformaction.".$this->_getPagingParamName("pguitemtitle").";\n";
							//$popform .="</script>\n\n";

							
							$htmltext2 .= "<a href=\"javascript:void(0);\" name=\"PGeditForm".$k."\" id=\"PGeditForm".$k."\" onclick=\""
								."return overlib('".str_replace(array("&","\\",'"',"<",">","'","\n","\r"), array("&amp;","\\\\","&quot;","&lt;","&gt;","\'","\\n","\\r"),$popform)."', STICKY, CAPTION,'"._pg_EditPopup."', CENTER,CLOSECLICK,CLOSETEXT,'"._UE_CLOSE_OVERLIB."',WIDTH,350, ANCHOR,'PGeditForm".$k."',ANCHORALIGN,'LR','UR');\">"."<img style=\"cursor:pointer;border:0px;\" id=\"pg_c5\" src=\"components/com_comprofiler/plugin/user/plug_cbprofilegallery/images/" . $icon[5] . "\" alt=\"" ._pg_Edit ."\" title=\""._pg_Edit."\""."></a> ";
						}

						$htmltext2 .= "<br /></div>";
						break;
					default:
						$htmltext2 .= $pgitemurl . "|" . $pgitemtype . "|" . $pgitemtitle ."|" . $pgitemdescription ."<br />";
						break;
				}
				
			}
			switch ($tabparams["cbpgdisplayformat"]){
					case 'DF1':
						break;
					case 'DF2':
						$htmltext2 .= "</table>";
						break;
					case 'DF3':
						break;
			}
			// Add paging control at end of list if paging enabled
			if ($tabparams["pgpagingenabled"] && ($tabparams["pgentriesperpage"] < $pgtotal)) {
				$htmltext2 .= "<div style=\"clear:both;\">&nbsp;</div>";
				$htmltext2 .= "<div style='width:95%;text-align:center;'>"
				.$this->_writePaging($pagingParams,"pgposts_",$tabparams["pgentriesperpage"],$pgtotal)
				."</div>";
			}	
		} else {
			$htmltext2 .= "<br/>";
			$htmltext2 .= _pg_NoItems;
			$htmltext2 .= "<br/>";
		}
		$htmltext2 .= "<div style=\"clear:both;\">&nbsp;</div>";
		return $htmltext0 . $htmltext1 . $htmltext2;
	}

	/**
	* Generates the HTML to display the user edit tab
	* @param object tab reflecting the tab database entry
	* @param object mosUser reflecting the user being displayed
	* @param int 1 for front-end, 2 for back-end
	* @returns mixed : either string HTML for tab content, or false if ErrorMSG generated
	*/
	function getEditTab($tab,$user,$ui) {
		global $ueConfig,$acl,$my,$mainframe;
		//fix to hide edit tab from front-end!
		//if ($ui==1) return;
		
		$this->_getLanguageFile();

		// Get all relevant tab parameters - these settings are global and set by the admin
		$tabparams = $this->_pgGetTabParameters($user);
		//print_r($tabparams);

		if ($ui==1 && $tabparams["cbpgenable"]!=1 ) {
			return;
		}
		
		$return="";
		$return .= "<table cellpadding=\"5\" cellspacing=\"0\" border=\"0\" width=\"100%\">\n";
		if($tab->description != null) $return .= "\t\t<div class=\"tab_Description\">".unHtmlspecialchars(getLangDefinition($tab->description))."</div>\n";
		
		// Short Greeting:
		$return .= "<tr>\n";
		$return .= "	<td class=\"titleCell\">"._pg_ShortGreeting.":</td>\n";
		$return .= "	<td class=\"fieldCell\"><input class=\"inputbox\" type=\"text\" name=\"".$this->_getPagingParamName("cb_pgshortgreeting")."\" mosReq=\"0\" mosLabel=\""._pg_ShortGreeting."\" value=\"".unHtmlspecialchars($user->cb_pgshortgreeting)."\" size=\"40\" />";
		$return .= getFieldIcons($ui, false, true, _pg_ShortGreeting_Desc, _pg_ShortGreeting.":");
		$return .= "</td></tr>\n";

		$lists = array();

		// make the select list for the special gallery yes/no fields (normally 1=yes, 0=no)
		$yesno = array();
		$yesno[] = mosHTML::makeOption( '_UE_YES', _CMN_YES );	// 1
		$yesno[] = mosHTML::makeOption( '_UE_NO', _CMN_NO );	// 0

		// Enable Gallery:
		if ($tabparams["pggalleryautoenabled"]=="0" || $ui==2) { 
			$lists['_pg_EnableProfileGallery'] = mosHTML::radioList( $yesno, $this->_getPagingParamName("cb_pgenable"), 'class="inputbox" size="1" mosReq="0" mosLabel="'._pg_EnableProfileGallery.'"', $user->cb_pgenable);
			$return .= "<tr>\n";
			$return .= "  <td class=\"titleCell\">"._pg_EnableProfileGallery.":</td>\n";
			$return .= "  <td class=\"fieldCell\">".$lists['_pg_EnableProfileGallery'];
			$return .= getFieldIcons($ui, false, false, _pg_EnableProfileGallery_Desc,_pg_EnableProfileGallery.":");
			$return .= "</td>\n</tr>\n";
		}

		// Enable Autopublish Items:
		if ($tabparams["pgallowautopublishoverride"]) {
			$lists['_pg_AutoPublish'] = mosHTML::radioList( $yesno, $this->_getPagingParamName("cb_pgautopublish"), 'class="inputbox" size="1" mosReq="0" mosLabel="'._pg_AutoPublish.'"', $user->cb_pgautopublish);
			$return .= "<tr>\n";
			$return .= "  <td class=\"titleCell\">"._pg_AutoPublish.":</td>\n";
			$return .= "  <td class=\"fieldCell\">";
			if ($tabparams["pgautopublish"]) {
				$return .= $lists['_pg_AutoPublish'];
			} else {
				$return .= ($tabparams["cbpgautopublish"] ? _CMN_YES : _CMN_NO);
			}
			$return .= getFieldIcons($ui, false, false, _pg_AutoPublish_Desc, _pg_AutoPublish.":");
			$return .= "</td>\n</tr>\n";
		}

		// Auto-approve Items setting in backend:
		if ($ui == 2 && $tabparams["pgallowautoapproveoverride"]) {
			$lists['_pg_AutoApprove'] = mosHTML::radioList( $yesno, $this->_getPagingParamName("cb_pgautoapprove"), 'class="inputbox" size="1" mosReq="0" mosLabel="'._pg_AutoApprove.'"', $user->cb_pgautoapprove);
			$return .= "<tr>\n";
			$return .= "  <td class=\"titleCell\">"._pg_AutoApprove.":</td>\n";
			$return .= "  <td class=\"fieldCell\">". $lists['_pg_AutoApprove'];
			$return .= getFieldIcons($ui, false, false,_pg_AutoApprove_Desc, _pg_AutoApprove.":");
			$return .= "</td>\n</tr>\n";
		}
		// Storage Quota (setting only in backend):
		if ($user->cb_pgtotalquotasize) {
			$quota = $user->cb_pgtotalquotasize;
		} else {
			$quota = $tabparams["pgdefaultquota"];
		}
		$return .= "<tr>\n";
		$return .= "  <td class=\"titleCell\">"._pg_TotalAllowedQuotaSize.":</td>\n";
		$return .= "  <td class=\"fieldCell\">";
		if ($ui == 2) {
			$return .= "<input class=\"inputbox\" type=\"text\" name=\"".$this->_getPagingParamName("cb_pgtotalquotasize")."\" mosReq=\"0\" mosLabel=\""._pg_TotalAllowedQuotaSize."\" value=\"".$user->cb_pgtotalquotasize."\" size=\"10\" />";
			$return .= " ("._pg_DefaultSetting.": ".$tabparams["pgdefaultquota"].")";

		} else {
			$return .= $quota;
		}
		$return .= getFieldIcons($ui, false, false, _pg_TotalAllowedQuotaSize_Desc, _pg_TotalAllowedQuotaSize.":");
		$return .= "</td>\n</tr>\n";
		
		// Uploaded Items Quota (setting only in backend):
		if ($user->cb_pgtotalquotaitems) {
			$quota = $user->cb_pgtotalquotaitems;
		} else {
			$quota = $tabparams["pgnumberofgalleryitems"];
		}
		$return .= "<tr>\n";
		$return .= "  <td class=\"titleCell\">"._pg_TotalAllowedQuotaItems.":</td>\n";
		$return .= "  <td class=\"fieldCell\">";
		if ($ui == 2) {
			$return .= "<input class=\"inputbox\" type=\"text\" name=\"".$this->_getPagingParamName("cb_pgtotalquotaitems")."\" mosReq=\"0\" mosLabel=\""._pg_TotalAllowedQuotaItems."\" value=\"".$user->cb_pgtotalquotaitems."\" size=\"10\" />";
			$return .= " ("._pg_DefaultSetting.": ".$tabparams["pgnumberofgalleryitems"].")";

		} else {
			$return .= $quota;
		}
		$return .= getFieldIcons($ui, false, false, _pg_TotalAllowedQuotaItems_Desc, _pg_TotalAllowedQuotaItems.":");
		$return .= "</td>\n</tr>\n";
		
		// Single Uploaded Item Maximum Size (setting only in backend):
		if ($user->cb_pguploadsize) {
			$quota = $user->cb_pguploadsize;
		} else {
			$quota = $tabparams["pgmaxsize"];
		}
		$return .= "<tr>\n";
		$return .= "  <td class=\"titleCell\">"._pg_MaxSingleUploadSize.":</td>\n";
		$return .= "  <td class=\"fieldCell\">";
		if ($ui == 2) {
			$return .= "<input class=\"inputbox\" type=\"text\" name=\"".$this->_getPagingParamName("cb_pguploadsize")."\" mosReq=\"0\" mosLabel=\""._pg_MaxSingleUploadSize."\" value=\"".$user->cb_pguploadsize."\" size=\"10\" />";
			$return .= " ("._pg_DefaultSetting.": ".$tabparams["pgmaxsize"].")";

		} else {
			$return .= $quota;
		}
		$return .= getFieldIcons($ui, false, false, _pg_MaxSingleUploadSize_Desc, _pg_MaxSingleUploadSize.":");
		$return .= "</td>\n</tr>\n";
		
		// Current Item Count Usage (information field only):
		if ($user->cb_pgtotalitems) {
			$quota = $user->cb_pgtotalitems;
		} else {
			$quota = "0";
		}
		$return .= "<tr>\n";
		$return .= "  <td class=\"titleCell\">"._pg_CurrentUploadedItemsCount.":</td>\n";
		$return .= "  <td class=\"fieldCell\">";
		
		if ($ui == 2) {
			$return .= "<input class=\"inputbox\" type=\"text\" name=\"".$this->_getPagingParamName("cb_pgtotalitems")."\" mosReq=\"0\" mosLabel=\""._pg_CurrentUploadedItemsCount."\" value=\"".$user->cb_pgtotalitems."\" size=\"10\" />";
		} else {
			$return .= $quota;
		}
		$return .= getFieldIcons($ui, false, false, _pg_CurrentUploadedItemsCount_Desc, _pg_CurrentUploadedItemsCount.":");
		$return .= "</td>\n</tr>\n";
		
		// Current Item Size Usage (information field only):
		if ($user->cb_pgtotalsize) {
			$quota = $user->cb_pgtotalsize;
		} else {
			$quota = "0";
		}
		$return .= "<tr>\n";
		$return .= "  <td class=\"titleCell\">"._pg_CurrentUploadedItemsSize.":</td>\n";
		$return .= "  <td class=\"fieldCell\">";
		if ($ui == 2) {
			$return .= "<input class=\"inputbox\" type=\"text\" name=\"".$this->_getPagingParamName("cb_pgtotalsize")."\" mosReq=\"0\" mosLabel=\""._pg_CurrentUploadedItemsSize."\" value=\"".$user->cb_pgtotalsize."\" size=\"10\" />";
		} else {
			$return .= $quota;
		}
		$return .= getFieldIcons($ui, false, false, _pg_CurrentUploadedItemsSize_Desc, _pg_CurrentUploadedItemsSize.":");
		$return .= "</td>\n</tr>\n";

		// Last Update (information field only):
		if ($user->cb_pglastupdate) {
			$quota = mosFormatDate($user->cb_pglastupdate);
		} else {
			$quota = _UE_NEVER;
		}
		$return .= "<tr>\n";
		$return .= "  <td class=\"titleCell\">"._pg_LastUpdate.":</td>\n";
		$return .= "  <td class=\"fieldCell\">";
		if ($ui == 2) {
			$return .= "<input class=\"inputbox\" type=\"text\" name=\"".$this->_getPagingParamName("cb_pglastupdate")."\" mosReq=\"0\" mosLabel=\""._pg_LastUpdate."\" value=\"".$user->cb_pglastupdate."\" size=\"10\" />";

		} else {
			$return .= $quota;
		}
		$return .= getFieldIcons($ui, false, false, _pg_LastUpdate_Desc, _pg_LastUpdate.":");
		$return .= "</td>\n</tr>\n";
		
		// Display Format:
		if ($tabparams["pgallowdisplayformatoverride"]) {
			$displayFormat = array();
			$displayFormat[] = mosHTML::makeOption( '', ' ' );
			$displayFormat[] = mosHTML::makeOption( 'DF1', _pg_DisplayFormat_DF1 );
			$displayFormat[] = mosHTML::makeOption( 'DF2', _pg_DisplayFormat_DF2 );
			$displayFormat[] = mosHTML::makeOption( 'DF3', _pg_DisplayFormat_DF3 );
			$lists['_pg_DisplayFormat'] = mosHTML::selectList( $displayFormat, $this->_getPagingParamName("cb_pgdisplayformat"), 'class="inputbox" size="1" mosReq="0" mosLabel="'._pg_DisplayFormat.'"', 'value', 'text', $user->cb_pgdisplayformat );
			$return .= "<tr>\n";
			$return .= "  <td class=\"titleCell\">"._pg_DisplayFormat.":</td>\n";
			$return .= "  <td class=\"fieldCell\">". $lists['_pg_DisplayFormat'];
			$return .= getFieldIcons($ui, false, false, _pg_DisplayFormat_Desc, _pg_DisplayFormat.":");
			$return .= "</td>\n</tr>\n";
		}
		
		// Access Mode:
		if ($tabparams["pgallowaccessmodeoverride"]) {
			$accessMode = array();
			$accessMode[] = mosHTML::makeOption( '', ' ' );
			$accessMode[] = mosHTML::makeOption( 'PUB', _pg_AccessMode_PUB );
			$accessMode[] = mosHTML::makeOption( 'REG', _pg_AccessMode_REG );
			$accessMode[] = mosHTML::makeOption( 'CON', _pg_AccessMode_CON );
			$accessMode[] = mosHTML::makeOption( 'REG-S', _pg_AccessMode_REGS );
			$accessMode[] = mosHTML::makeOption( 'CON-S', _pg_AccessMode_CONS );
			
			$lists['_pg_AccessMode'] = mosHTML::selectList( $accessMode, $this->_getPagingParamName("cb_pgaccessmode"), 'class="inputbox" size="1" mosReq="0" mosLabel="'._pg_AccessMode.'"', 'value', 'text', $user->cb_pgaccessmode );
			$return .= "<tr>\n";
			$return .= "  <td class=\"titleCell\">"._pg_AccessMode.":</td>\n";
			$return .= "  <td class=\"fieldCell\">". $lists['_pg_AccessMode'];
			$return .= getFieldIcons($ui, false, false, _pg_AccessMode_Desc, _pg_AccessMode.":");
			$return .= "</td>\n</tr>\n";
		}

		//$return .= "<tr>\n";
		//$return .= "  <td class=\"titleCell\">--- end ---</td>\n";
		//$return .= "  <td class=\"fieldCell\">--- end of programmed fields ! below are the standard cb fields: change fields to 0</td>\n";
		//$return .= "</tr>\n";
		$return .= "</table>\n";

		return $return;
	}

	/**
	* Saves the user edit tab postdata into the tab's permanent storage
	* @param object tab reflecting the tab database entry
	* @param object mosUser reflecting the user being displayed
	* @param int 1 for front-end, 2 for back-end
	* @param array _POST data for saving edited tab content as generated with getEditTab
	* @returns mixed : either string HTML for tab content, or false if ErrorMSG generated
	*/
	function saveEditTab($tab, &$user, $ui, $postdata) {

		// Get all relevant tab parameters - these settings are global and set by the admin
		$tabparams = $this->_pgGetTabParameters($user);

		// Short Greeting:
		$cb_pgshortgreeting = $this->_getReqParam("cb_pgshortgreeting", "");
		$user->cb_pgshortgreeting = cbUnEscapeSQL($cb_pgshortgreeting);
				
		// Enable Gallery:
		if ($tabparams["pggalleryautoenabled"]=="0" || $ui==2) {
			$cb_pgenable = $this->_getReqParam("cb_pgenable", null);
			if ($cb_pgenable) {
				$user->cb_pgenable = $cb_pgenable;
			}
		}
		
		// Enable Autopublish Items:
		if ($tabparams["pgallowautopublishoverride"]) {
			if ($tabparams["pgautopublish"]) {
				$cb_pgautopublish = $this->_getReqParam("cb_pgautopublish", null);
				if ($cb_pgautopublish) {
					$user->cb_pgautopublish = $cb_pgautopublish;
				}
			}
		}

		if ($ui == 2 && $tabparams["pgallowautoapproveoverride"]) {
			// Auto-approve Items setting in backend:			
			$cb_pgautoapprove = $this->_getReqParam("cb_pgautoapprove", null);
			if ($cb_pgautoapprove) {
				$user->cb_pgautoapprove = $cb_pgautoapprove;
			}
		}
		if ($ui == 2) {	
			// Item Quota (setting only in backend):
			$cb_pgtotalquotaitems = $this->_getReqParam("cb_pgtotalquotaitems", null);
			if ($cb_pgtotalquotaitems !== null) {
				$user->cb_pgtotalquotaitems = $cb_pgtotalquotaitems;
			}
		}
		
		if ($ui == 2) {	
			// Storage Quota (setting only in backend):
			$cb_pgtotalquotasize = $this->_getReqParam("cb_pgtotalquotasize", null);
			if ($cb_pgtotalquotasize !== null) {
				$user->cb_pgtotalquotasize = $cb_pgtotalquotasize;
			}
		}
		
		if ($ui == 2) {	
			// Maximum Single Upload Size (setting only in backend):
			$cb_pguploadsize = $this->_getReqParam("cb_pguploadsize", null);
			if ($cb_pguploadsize !== null) {
				$user->cb_pguploadsize = $cb_pguploadsize;
			}
		}
		
		if ($ui == 2) {	
			// Current Item Count Usage (information field only):
			$cb_pgtotalitems = $this->_getReqParam("cb_pgtotalitems", null);
			if ($cb_pgtotalitems !== null) {
				$user->cb_pgtotalitems = $cb_pgtotalitems;
			}
		}
		
		if ($ui == 2) {	
			// Current Item Size Usage (information field only):
			$cb_pgtotalsize = $this->_getReqParam("cb_pgtotalsize", null);
			if ($cb_pgtotalsize !== null) {
				$user->cb_pgtotalsize = $cb_pgtotalsize;
			}
		}

		if ($ui == 2) {	
			// Last Update Date (information field only):
			$cb_pglastupdate = $this->_getReqParam("cb_pglastupdate", null);
			if ($cb_pglastupdate !== null) {
				$user->cb_pglasupdate = $cb_pglastupdate;
			}
		}

		// Access Mode:
		if ($tabparams["pgallowaccessmodeoverride"]) {
			$cb_pgaccessmode = $this->_getReqParam("cb_pgaccessmode", null);
			if ($cb_pgaccessmode) {
				$user->cb_pgaccessmode = $cb_pgaccessmode;
			}
		}
		// Display Format:
		if ($tabparams["pgallowdisplayformatoverride"]) {
			$cb_pgdisplayformat = $this->_getReqParam("cb_pgdisplayformat", null);
			if ($cb_pgdisplayformat) {
				$user->cb_pgdisplayformat = $cb_pgdisplayformat;
			}
		}

	}
	
	function getTabComponent($tab, $user, $ui, $postdata) {
		return "Hello World of Components!";
	}


	/**
	* UserBot Called when a user is deleted from backend (prepare future unregistration)
	* @param object mosUser reflecting the user being deleted
	* @param int 1 for successful deleting
	* @returns true if all is ok, or false if ErrorMSG generated
	* 
	*/
	function userDeleted($user, $success) {
		global $database,$ueConfig,$mainframe;
		
		$PGItemAbsolutePath=$mainframe->GetCfg( 'absolute_path' ).'/images/comprofiler/plug_profilegallery/';
		$PGItemAbsoluteUserPath = $PGItemAbsolutePath . $user->id;
		
		$this->RemoveDirectory($PGItemAbsoluteUserPath);
		print "Deleting user gallery folder ".$user->id;
		$sql="DELETE FROM #__comprofiler_plug_profilegallery WHERE userid=".$user->id;
		$database->SetQuery($sql);
		if (!$database->query()) {
			$this->_setErrorMSG("SQL error cb.profilegallery:userDeleted-1" . $database->stderr(true));
			return false;
		}
		
		//NICK: Here you probably want to delete all user's files and directory using a loop through mosReadDirectory
		
		return true;
	}
	
	/***********************************
		Author : M. Niyazi Yarar
		Created : February, 2006
		Description : Simply clean files 
		and removes the directory

		If any error occurs or for your suggestions,
		please send me e-mail
	***********************************/
	function ClearDirectory($path){
   		if($dir_handle = opendir($path)){    
       		while($file = readdir($dir_handle)){    
          		if($file == "." || $file == ".."){
              		if(!@unlink($path."/".$file)){
                  		continue;
              		}                
          		}else{
              		@unlink($path."/".$file);
           		}
			}
			closedir($dir_handle);
			return true;
			// all files deleted
   			}else{
       			return false;
				// directory doesn?t exist
			}		    
	}
	
	function RemoveDirectory($path){
		if($this->ClearDirectory($path)){
			if(rmdir($path)){
				return true;
				// directory removed
			}else{
				return false;
				// directory couldn?t removed
			}
		}else{
			return false;
			// no empty directory
		}
	}

	
}	// end class getForumTab.
?>